This commit is contained in:
yulixing 2019-11-29 10:05:54 +08:00
parent 4725567f23
commit 98c23e8e38
36 changed files with 5583 additions and 153 deletions

View File

@ -1,18 +1,23 @@
{
"presets": [
["env", {
"modules": false,
"targets": {
"browsers": ["> 1%", "last 2 versions", "not ie <= 8"]
}
}],
"stage-2"
["env", {
"modules": false,
"targets": {
"browsers": ["> 1%", "last 2 versions", "not ie <= 8"]
}
}],
"stage-2"
],
"plugins": [
["transform-runtime", {
"polyfill": true,
"regenerator": true
}]
],
"plugins": ["transform-runtime"],
"env": {
"test": {
"presets": ["env", "stage-2"],
"plugins": ["istanbul"]
}
"test": {
"presets": ["env", "stage-2"],
"plugins": ["istanbul"]
}
}
}

View File

@ -20,7 +20,7 @@
},
"miniprogramRoot": "dist/wx/",
"compileType": "miniprogram",
"appid": "wx4d305a3b655ad75f",
"appid": "wx7764bfbd023a1c67",
"projectname": "maker",
"simulatorType": "wechat",
"simulatorPluginLibVersion": {},
@ -49,24 +49,24 @@
"current": -1,
"list": [
{
"id": -1,
"id": 0,
"name": "首页",
"pathName": "pages/index/main",
"query": "",
"scene": null
"scene": 1011
},
{
"id": 1,
"name": "结果",
"pathName": "pages/result/main",
"query": "_id=5ddd07973d804967211a10fc&users=猫大王",
"query": "_id=5ddce89b944bbb720aa771ea&users=猫大王",
"scene": null
},
{
"id": 2,
"name": "详情页",
"pathName": "pages/details/main",
"query": "_id=5ddd07973d804967211a10fc",
"query": "_id=5ddce89b944bbb720aa771ea",
"scene": null
},
{

File diff suppressed because one or more lines are too long

View File

@ -10,6 +10,37 @@
"backgroundTextStyle": "light",
"navigationBarBackgroundColor": "#FFDC34",
"navigationBarTextStyle": "white"
},
"tabBar": {
"color": "#999",
"backgroundColor": "#fff",
"selectedColor": "#333",
"borderStyle": "white",
"list": [{
"text": "首页",
"pagePath": "pages/index/main",
"iconPath": "static/tabs/home.png",
"selectedIconPath": "static/tabs/home-active.png"
}, {
"text": "列表",
"pagePath": "pages/list/main",
"iconPath": "static/tabs/list.png",
"selectedIconPath": "static/tabs/list-active.png"
}],
"items": [{
"name": "首页",
"pagePath": "pages/index/main",
"icon": "static/tabs/home.png",
"activeIcon": "static/tabs/home-active.png"
}, {
"name": "列表",
"pagePath": "pages/list/main",
"icon": "static/tabs/list.png",
"activeIcon": "static/tabs/list-active.png"
}],
"position": "bottom"
}
}

View File

@ -14,6 +14,8 @@
<script>
import tag from '@/components/tag'
import requestUtil from '@/utils/request'
import sdkManage from '@/utils/jcfw/SDKManage'
export default {
props: ['data'],
components: {
@ -24,6 +26,9 @@ export default {
tags: []
}
},
async onLoad(options) {
sdkManage.init(options)
},
watch: {
data: {
handler: function(val) {
@ -33,10 +38,19 @@ export default {
deep: true
}
},
methods: {
goDetails(id) {
setTimeout(() => {
sdkManage.uploadLog('click_test', {
id: id,
title: this.data.title,
tags: this.data.tags
})
}, 0)
this.$emit('clickItem', { _id: id })
requestUtil.postData('/view', { _id: id })
wx.navigateTo({
wx.reLaunch({
url: `/pages/details/main?_id=${id}`
})
}
@ -59,6 +73,7 @@ export default {
white-space: nowrap;
overflow: hidden;
font-weight: 700;
font-size: 32rpx;
}
.num {
font-size: 24rpx;

View File

@ -8,8 +8,8 @@
/>
<input
@input="changeText"
@confirm="search"
@input="changeText"
class="ipt"
confirm-type="search"
placeholder="搜索你感兴趣的内容"
@ -22,6 +22,8 @@
<script>
import requestUtil from '@/utils/request'
import sdkManage from '@/utils/jcfw/SDKManage'
export default {
props: ['text'],
data() {
@ -29,13 +31,15 @@ export default {
keyWord: ''
}
},
async onLoad(options) {
sdkManage.init(options)
},
mounted() {},
watch: {
text: {
handler: function(val) {
this.keyWord = this.text || ''
if(this.keyWord) this.search()
if (this.keyWord) this.search()
},
immediate: true,
deep: true
@ -50,6 +54,9 @@ export default {
records = new Set(records)
records = [...records]
wx.setStorageSync('search-record', records)
setTimeout(() => {
sdkManage.uploadLog('search_kw', { kw: this.keyWord })
}, 0)
this.$emit('search', data)
} catch (err) {
console.log(err)

View File

@ -8,7 +8,7 @@ export default {
props: ['text'],
methods: {
goSearch(key) {
wx.navigateTo({
wx.redirectTo({
url: `/pages/search/main?key=tag:${key}`
})
}

View File

@ -13,8 +13,7 @@
<div class="card-bd">
<div class="card-cont">{{maker.desc}}</div>
<div class="card-ipt-wrap">
<input class="card-ipt" placeholder="输入想要测试的名字" type="text" v-model="users" />
<div class="card-ipt-tip">可输入任何文字</div>
<input class="card-ipt" placeholder="输入你的名字" type="text" v-model="users" />
</div>
<div @click="getResult" class="card-btn">GO</div>
</div>
@ -84,14 +83,14 @@ export default {
}
},
goList() {
wx.navigateTo({
wx.switchTab({
url: `/pages/list/main`
})
},
getResult() {
if (!this.users) {
wx.showToast({
title: '请填写名', //,
title: '请填写名', //,
icon: 'none',
duration: 2000, //,
mask: true, //穿,
@ -150,6 +149,7 @@ export default {
.card-cont {
margin-bottom: 32rpx;
text-indent: 2em;
font-size: 48rpx;
}
}
.card-ipt-wrap {
@ -157,9 +157,12 @@ export default {
margin: 24rpx auto;
.card-ipt {
margin-bottom: 10rpx;
height: 48rpx;
height: 60rpx;
color: #333;
border-bottom: 1px solid #333;
border-bottom: 1px solid #ffdc34;
font-size: 60rpx;
line-height: 60rpx;
}
.card-ipt-tip {
@ -171,13 +174,13 @@ export default {
position: absolute;
transform: translateX(-50%);
left: 50%;
bottom: 32rpx;
width: 120rpx;
height: 120rpx;
bottom: 36rpx;
width: 140rpx;
height: 140rpx;
color: #fff;
font-size: 48rpx;
font-weight: 700;
line-height: 120rpx;
line-height: 140rpx;
text-align: center;
background: linear-gradient(
0deg,

View File

@ -2,7 +2,7 @@
<div class="page p-home">
<!-- Header -->
<div class="header">
<div class="title">奇妙生成器</div>
<div class="title">奇妙测试机</div>
</div>
<div :class="fixed? 'fixed' : ''" @click="goSearch" class="search-box" id="search-box">
<search></search>
@ -29,7 +29,7 @@
<div class="card">
<div class="card-hd">{{recommandList[curRecommandIdx].title}}</div>
<div class="card-bd">{{recommandList[curRecommandIdx].desc}}</div>
<div @click="goDetails(recommandList[curRecommandIdx]._id)" class="card-btn">GO</div>
<div @click="goDetails(recommandList[curRecommandIdx]._id, true)" class="card-btn">GO</div>
</div>
</div>
</div>
@ -55,12 +55,18 @@
>最新</div>
</div>
<div class="list-bd">
<list-item :data="item" :key="index" v-for="(item, index) in listData"></list-item>
<list-item
:data="item"
:from="curActive"
:key="index"
@clickItem="clickItem"
v-for="(item, index) in listData"
></list-item>
</div>
</div>
</div>
<!-- 查看更多 -->
<button class="btn-more" @click="goList">查看更多</button>
<!-- 查看全部 -->
<button @click="goList" class="btn-more">查看全部</button>
</div>
</div>
</template>
@ -70,6 +76,7 @@ import card from '@/components/card'
import search from '@/components/search'
import listItem from '@/components/list-item'
import requestUtil from '@/utils/request'
import sdkManage from '@/utils/jcfw/SDKManage'
export default {
data() {
@ -96,7 +103,8 @@ export default {
this.listData = this.hotList
this.getNew()
},
onLoad() {
async onLoad(options) {
sdkManage.init(options)
let self = this
//tab
const query = wx.createSelectorQuery()
@ -152,21 +160,31 @@ export default {
this.curActive = type
this.listData = type === 'hot' ? this.hotList : this.newList
},
goDetails(id) {
goDetails(id, isRecommand) {
if (isRecommand) {
setTimeout(() => {
sdkManage.uploadLog('click_recommand', { id: id })
}, 0)
}
requestUtil.postData('/view', { _id: id })
wx.navigateTo({
url: `/pages/details/main?_id=${id}`
})
},
goList() {
wx.navigateTo({
wx.switchTab({
url: `/pages/list/main`
})
},
goSearch() {
wx.navigateTo({
wx.redirectTo({
url: `/pages/search/main`
})
},
clickItem(data) {
setTimeout(() => {
sdkManage.uploadLog(`click_${this.curActive}`, data)
}, 0)
}
}
}
@ -323,7 +341,6 @@ export default {
border-radius: 0;
width: 100%;
letter-spacing: 4rpx;
}
}
</style>

View File

@ -93,6 +93,13 @@ export default {
}
},
loadMore() {
wx.showToast({
title: '加载中', //,
icon: 'loading', //,
duration: 1000, //,
mask: true, //穿,
success: res => {}
})
this.getData()
},
toggleTags() {
@ -101,7 +108,7 @@ export default {
this.tagText = this.showAllTags ? '收起' : '展开'
},
goSearch() {
wx.navigateTo({
wx.redirectTo({
url: `/pages/search/main`
})
}
@ -123,8 +130,7 @@ export default {
}
}
.main {
margin-top: 108rpx;
padding: 60rpx 32rpx 60rpx;
padding: 168rpx 32rpx 80rpx;
}
.sec-1 {

View File

@ -1,3 +1,3 @@
{
"navigationBarTitleText": "生成器列表"
"navigationBarTitleText": "测试列表"
}

View File

@ -25,12 +25,13 @@
</button>
<button class="card-btn" data-id="shareBtn" open-type="share">
<image
@click="share"
class="icon icon-share"
lazy-load="false"
mode="scaleToFill"
src="/static/images/icon-share.png"
style="width:16px;height:16px;"
/>
/>
</button>
<button @click="replay" class="card-btn">
<image
@ -74,6 +75,7 @@ import search from '@/components/search'
import listItem from '@/components/list-item'
import tag from '@/components/tag'
import requestUtil from '@/utils/request'
import sdkManage from '@/utils/jcfw/SDKManage'
export default {
data() {
@ -83,7 +85,8 @@ export default {
title: '',
template: {},
imgPath: '',
paint: false
paint: false,
_id: ''
}
},
@ -92,13 +95,94 @@ export default {
listItem,
tag
},
onLoad(options) {
async onLoad(options) {
this.users = options.users
this._id = options._id
sdkManage.init(options)
},
async mounted() {
await this.getResult()
await this.getHot()
const palette = {
background: '#eee',
width: '750rpx',
height: '850rpx',
views: [
{
type: 'image',
url: '/static/images/bg-result.png',
css: {
top: '0rpx',
left: '0rpx',
width: '750rpx',
height: '850rpx'
}
},
{
type: 'text',
text: this.title,
css: {
top: '64rpx',
left: '100rpx',
width: '550rpx',
color: '#000000',
textAlign: 'center',
fontSize: '48rpx',
fontWeight: 'bold',
lineHeight: '58rpx'
}
},
{
type: 'text',
text: this.result.join(''),
css: {
top: '220rpx',
left: '100rpx',
width: '550rpx',
color: '#000000',
lineHeight: '48rpx',
fontSize: '48rpx'
}
},
{
type: 'image',
url: '/static/images/qr-code.jpg',
css: {
bottom: '128rpx',
right: '60rpx',
width: '120rpx',
height: '120rpx'
}
},
{
type: 'text',
text: '小程序',
css: {
bottom: '64rpx',
right: '64rpx',
height: '120rpx',
color: '#999999',
lineHeight: '48rpx',
fontSize: '28rpx'
}
},
{
type: 'text',
text: '奇妙测试机',
css: {
bottom: '32rpx',
right: '64rpx',
height: '120rpx',
color: '#999999',
lineHeight: '48rpx',
fontSize: '28rpx'
}
}
]
}
this.template = palette
this.paint = true
},
onShareAppMessage(res) {
// if (res.from === 'button') {
@ -131,95 +215,31 @@ export default {
}
},
replay() {
wx.navigateTo({
url: `/pages/details/main?_id=${this._id}`
wx.navigateBack({
delta: 1 // delta ,
})
},
share() {
setTimeout(() => {
sdkManage.uploadLog('click_share', { id: this._id, title: this.title })
}, 0)
},
paint() {},
onImgOk(e) {
this.imgPath = e.mp.detail.path
console.log(this.imgPath)
},
saveResult() {
const palette = {
background: '#eee',
width: '750rpx',
height: '850rpx',
views: [
{
type: 'image',
url: '/static/images/bg-result.png',
css: {
top: '0rpx',
left: '0rpx',
width: '750rpx',
height: '850rpx'
}
},
{
type: 'text',
text: this.title,
css: {
top: '64rpx',
left: '100rpx',
width: '550rpx',
color: '#000000',
textAlign: 'center',
fontSize: '48rpx',
fontWeight: 'bold',
lineHeight: '58rpx'
}
},
{
type: 'text',
text: this.result.join(''),
css: {
top: '220rpx',
left: '100rpx',
width: '550rpx',
color: '#000000',
lineHeight: '48rpx',
fontSize: '36rpx'
}
},
{
type: 'image',
url: '/static/images/qr-code.png',
css: {
bottom: '128rpx',
right: '60rpx',
width: '120rpx',
height: '120rpx'
}
},
{
type: 'text',
text: '小程序',
css: {
bottom: '64rpx',
right: '64rpx',
height: '120rpx',
color: '#999999',
lineHeight: '48rpx',
fontSize: '28rpx'
}
},
{
type: 'text',
text: '奇妙生成器',
css: {
bottom: '32rpx',
right: '64rpx',
height: '120rpx',
color: '#999999',
lineHeight: '48rpx',
fontSize: '28rpx'
}
}
]
}
setTimeout(() => {
sdkManage.uploadLog('click_save', { id: this._id, title: this.title })
}, 0)
this.template = palette
this.paint = true
wx.showToast({
title: '正在保存', //,
icon: 'loading', //,
duration: 2000, //,
mask: true //穿,
})
const self = this
setTimeout(() => {
wx.saveImageToPhotosAlbum({
@ -233,13 +253,19 @@ export default {
})
},
fail: function(err) {
wx.showToast({
title: '保存失败!请重试!', //,
icon: 'none', //,
duration: 2000, //,
mask: true //穿,
})
console.log(err)
}
})
}, 1000)
},
goList() {
wx.navigateTo({
wx.switchTab({
url: `/pages/list/main`
})
}
@ -285,8 +311,9 @@ export default {
font-size: 32rpx;
.card-cont {
margin: 60rpx 0;
margin: 48rpx 0;
text-indent: 2em;
font-size: 48rpx;
}
.card-btn {

View File

@ -22,7 +22,7 @@
</div>
</div>
<!-- 搜索记录 -->
<div class="sec-1" v-if="listData.length === 0 ">
<div class="sec-1" v-if="listData.length === 0 && records.length > 0">
<div class="hd">
<div class="title">搜索记录</div>
<div @click="clearRecord" class="del">
@ -35,7 +35,7 @@
</div>
</div>
<div class="bd">
<span
<span
:key="index"
@click="searchRecord(item)"
class="record-item"
@ -49,8 +49,8 @@
<tag :key="index" :text="item" v-for="(item, index) in tags"></tag>
</div>
<!-- 查看更多 -->
<button @click="goList" class="btn-more">查看更多</button>
<!-- 查看全部 -->
<button @click="goList" class="btn-more">查看全部</button>
</div>
</div>
</template>
@ -115,7 +115,7 @@ export default {
this.getRecord()
},
goList() {
wx.navigateTo({
wx.switchTab({
url: `/pages/list/main`
})
}

View File

@ -1,27 +1,35 @@
.color-yellow {
color: #FFDC34;
color: #ffdc34;
}
.color-white {
color: #fff;
color: #fff;
}
.bg-yellow {
background-color: #FFDC34;
background-color: #ffdc34;
}
.color-black {
color: #333;
color: #333;
}
.font-bold {
font-weight: 700;
font-weight: 700;
}
page {
color: #333;
color: #333;
}
button::after {
border: none;
}
.page {
min-height: 100vh;
background-color: #fff;
background-size: 100vh;
background-image: url(https://resource.kingsome.cn/share-images/5ddf3913094847e6b4f0d8eb.png);
}

View File

@ -0,0 +1,15 @@
const env = 'product'; //product, test
export default {
env: env,
dataType: 'game', //game, movie, book
// apiBase: env === 'test'? 'http://192.168.100.232' : 'https://ghost.kingsome.cn',
apiBase: env === 'test'? 'https://ghost-test.kingsome.cn' : 'https://ghost.kingsome.cn',
loginPage: env === 'test'? 'https://wechat-test.kingsome.cn/weapp/index.html?scope=snsapi_base' : 'https://wechat.kingsome.cn/weapp/index.html?scope=snsapi_base',
cdnBase: 'https://h5games-al.kingsome.cn/emulator-static/',
version: '1.0.0',
gameTypes: ['射击','格斗', '角色扮演','动作角色扮演',
'赛车', '动作游戏','策略战棋', '其他',
'益智游戏', '体育游戏', '冒险游戏', '模拟战略',
'桌面游戏', '音乐游戏', '第一人称射击'
]
}

File diff suppressed because one or more lines are too long

View File

@ -0,0 +1,38 @@
let events = {};
export default {
on (name, self, cb) {
let cbArr = events[name];
if (Array.isArray(cbArr)) {
cbArr.push({self, cb})
} else {
events[name] = [{self, cb}]
}
},
remove (name, self) {
let cbArr = events[name];
if (Array.isArray(cbArr)) {
events[name] = cbArr.filter(({target, cb}) => {
return target !== self
})
}
},
emit (name, data) {
let cbArr = events[name];
if (Array.isArray(cbArr)) {
cbArr.map(({target, cb}) => {
cb.call(target, data)
})
}
},
events: {
BUY_GAME_SUCCESS: 'buy-game-success',
UPDATE_RECENT_GAMES: 'update-recent-games',
UPDATE_GAME_STATUS: 'update-game-status',
NEED_UPDATE_SCORE: 'need-update-score',
NEED_UPDATE_CFG: 'need-update-cfg',
NEED_UPDATE_UINFO: 'need-update-uinfo',
BUY_ITEM_RESULT: 'buy-item-result',
BUY_VIP_RESULT: 'buy-vip-result',
NEED_SHOW_LOGIN_PAGE: 'need_show_login_page',
}
}

193
src/utils/jcfw/SDKManage.js Normal file
View File

@ -0,0 +1,193 @@
import jcfw from './jcfw'
import g from '../common/global'
let jcshare = jcfw.share;
let SDKManage = function () {
this.isoffical = g.env === 'product';
this.gameId = 8005;
this.hasLogin = false;
this.vision = '1.0.0';
this.ChannelId = 6001;
this.mpCode = '';
this.init = function (launchObj) {
this.launchObj = launchObj;
jcfw.init(this.ChannelId, this.gameId, this.isoffical, launchObj);
};
this.updateMpCode = function (mpCode) {
this.mpCode = mpCode;
};
this.login = async function (cb) {
await this.gameLogin();
await this.checkShareData();
// redis 配置
await this.getGameConfig();
// 获取分享配置
await this.getShareConfig();
};
this.gameLogin = () => {
let self = this;
let loginCount = 0;
return new Promise((resolve, reject) => {
let login = () => {
let token = wx.getStorageSync('token');
if (!token) {
token = jcfw.makeUUID();
try {
wx.setStorageSync('token', token);
} catch (e) {
}
}
jcfw.loginUser((res) => {
self.hasLogin = true;
console.log('login success', res);
wx.setStorageSync('account', res);
self.account_id = res.account_id;
resolve();
},
(neterr, logicerr, errmsg) => {
if (loginCount++ < 10) {
login();
} else {
reject();
}
},
self.mpCode
);
};
login();
});
};
this.checkShareData = function () {
return new Promise((resolve, reject) => {
let ldata;
if (this.launchObj) {
ldata = this.launchObj.query;
} else {
ldata = wx.getLaunchOptionsSync().query;
}
if (ldata.inviter_id) {
jcshare.acceptAchievementInvite(ldata.inviter_id, '100', JSON.stringify([['100', 100]]));
}
resolve();
});
};
this.getGameConfig = function () {
let tryCount = 0;
return new Promise((resolve, reject) => {
let cb = function (res) {
console.log('getGameConfig', res);
wx.setStorageSync('cfg', res);
resolve();
};
let cbf = function (res) {
console.log('getGameConfig fail');
if (tryCount++ < 10) {
request();
} else {
reject();
}
};
let request = () => {
jcfw.cloud.initConfig(cb, cbf);
};
request();
});
};
this.setStorage = function (v, successcb, failcb) {
if (this.hasLogin) {
jcfw.cloud.setStorages(v, successcb, failcb);
}
};
this.getStorage = function (keys, successcb, failcb) {
if (this.hasLogin) {
jcfw.cloud.getStorages(keys, successcb, failcb);
}
};
this.getShareConfig = function () {
let tryCount = 0;
return new Promise((resolve, reject) => {
let cbs = function (res) {
if (res.length > 0) {
let shareArr = [];
for (let obj of res) {
shareArr.push({
image: obj.image,
str: obj.str
});
}
wx.setStorageSync('share_cfg', shareArr);
}
console.log('getShareConfig success', res);
resolve();
};
let cbf = function () {
console.log('getShareConfig fail');
if (tryCount++ < 10) {
request();
} else {
reject();
}
};
let request = () => {
jcfw.cloud.getShareData(this.sex, this.province, this.city, cbs, cbf);
};
request();
});
};
this.getAchievInviteeNum = function () {
return new Promise((resolve, reject) => {
const callback = function (res) {
console.log('playerData.invitee_nums');
console.log(res);
let invitee_nums = 0;
for (let i = 0; i < res.length; i++) {
if (res[i].achievement_id === 100) {
invitee_nums = res[i].invitee_num;//邀请玩家数
break;
}
}
resolve(invitee_nums);
};
jcshare.getAchievInviteeNum(callback, (err) => {
reject(err);
});
});
};
this.queryAchievementShareDetail = function () {
return new Promise((resolve, reject) => {
const callback = function (res) {
const result = res[100] || [];
resolve(result);
};
jcshare.queryAchievementShareDetail([100], callback, function () {
reject();
});
});
};
this.updateUser = function (allInfo) {
return new Promise((resolve, reject) => {
jcfw.updateUser(allInfo, (obj) => {
resolve(obj);
}, (err) => {
reject(err);
});
});
};
this.uploadLog = function (eventName, param) {
jcfw.gamelog.logButtonClick(eventName, param);
};
};
let instance = new SDKManage();
export default instance;

View File

@ -0,0 +1,203 @@
var httpcli = function(){
// LIFE-CYCLE CALLBACKS:
// onLoad () {},
// start () {},
// update (dt) {},
this.init=function(){
this.cachemsg = [];
this._needretry = false;
this._retrycount = 3;
this._retryms = 3000;
this._runningcount = 0;
this._maxrunning = 10;
// this._retry_tid = setInterval(this._retry.bind(this), this._retryms);
};
this.httpGet=function(url, cbRes, cbErr){
// var realurl = url;
// if(urldata){
// if(realurl.indexOf("?") == -1){
// realurl += "?";
// }else{
// realurl += "&";
// }
// realurl += encodeURIComponent(urldata);
// }
return this.httpsend(url, null, cbRes, cbErr, 'GET');
};
this.httpPost=function(url, postdata, cbRes, cbErr){
return this.httpsend(url, postdata, cbRes, cbErr, 'POST');
};
this.httpsend=function(url, urldata, cbRes, cbErr, smethod, isretry){
if(this._runningcount < this._maxrunning){
return this._httpsend(url, urldata, cbRes, cbErr, smethod, isretry);
}else if(!isretry){
let obj = {
u: url,
v: urldata,
successcb: cbRes,
errcb: cbErr
};
this.cachemsg.push(obj);
return null;
}
};
this._httpsend=function(url, urldata, cbRes, cbErr, smethod, isretry){
this._runningcount++;
let self = this;
if(typeof(XMLHttpRequest) != 'undefined'){
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function () {
if (xhr.readyState == 4){
self._runningcount--;
if(xhr.status >= 200 && xhr.status < 400) {
var response = xhr.responseText;
cbRes && cbRes(response);
}else{
if(!isretry && self._needretry){
let obj = {
u: url,
v: urldata,
successcb: cbRes,
errcb: cbErr
};
self.cachemsg.push(obj);
}else{
cbErr && cbErr(xhr.status, xhr.statusText);
}
}
}
};
// xhr.onabort = function(){
// self._runningcount--;
// };
xhr.onerror = function(){
self._runningcount--;
};
xhr.open(smethod, url, true);
xhr.send(urldata);
return xhr;
}else if(typeof(wx) != 'undefined'){
var jsobj = urldata? JSON.parse(urldata): null;
var xhr = wx.request({
url: url,
data: jsobj,
method: smethod,
success: function(res){
console.log("[wx]request success!" + res.statusCode);
if(res.statusCode >= 200 && res.statusCode < 400) {
var restext = JSON.stringify(res.data);
cbRes && cbRes(restext);
}else{
cbErr && cbErr(res.statusCode, res.msg);
}
},
fail: function(res){
console.log("[wx]request fail!"+ JSON.stringify(res));
if(!isretry && self._needretry){
let obj = {
u: url,
v: urldata,
successcb: cbRes,
errcb: cbErr
};
self.cachemsg.push(obj);
}else{
cbErr && cbErr(-1, res.msg);
}
// cbErr && cbErr(-1, res.msg);
},
complete: function(){
self._runningcount--;
console.log("[wx]request complete!");
}
});
return xhr;
}
return null;
};
this._retry=function(){
if(this.cachemsg.length > 0){
this.cachemsg.forEach(element => {
let obj = element;
if(obj.retrying){
return;
}
let bneedretry = false;
if(!obj.retry_count){
obj.retry_count = 1;
obj.passtime = 0;
}
obj.passtime += this._retryms;
bneedretry = (obj.passtime >= obj.retry_count * this._retryms);
if(bneedretry && !obj.retrying){
obj.retrying = true;
let method = obj.v? 'POST': 'GET';
this.httpsend(obj.u, obj.v, (restext) => {
obj.successcb && obj.successcb(restext);
let idx = this.cachemsg.findIndex((element) => {
return element == obj;
});
if(idx != -1){
this.cachemsg.splice(idx, 1);
}
}, (errcode, errmsg) => {
obj.retrying = false;
obj.passtime = 0;
obj.retry_count++;
if(obj.retry_count >= this._retrycount){
obj.errcb && obj.errcb(errcode, errmsg);
let idx = this.cachemsg.findIndex((element) => {
return element == obj;
});
if(idx != -1){
this.cachemsg.splice(idx, 1);
}
}
}, method, true);
}
});
}
};
this.setRetryCount=function(count){
this.retrycount = count;
};
this.setRetryInterval=function(millsec){
if(millsec != this._retryms){
this._retryms = millsec;
if(this._retry_tid){
clearInterval(this._retry_tid);
this._retry_tid = 0;
}
}
if(!this._retry_tid){
this._retry_tid = setInterval(this._retry.bind(this), this._retryms);
}
};
this.setNeedRetry=function(needretry){
this._needretry = needretry;
// if(!this._needretry && this._retry_tid){
// clearInterval(this._retry_tid);
// this._retry_tid = 0;
// }else if(this._needretry && !this._retry_tid){
// this._retry_tid = setInterval(this._retry.bind(this), this._retryms);
// }
}
};
export default httpcli;

View File

@ -0,0 +1,52 @@
import httpcli from './httpcli'
export default {
// LIFE-CYCLE CALLBACKS:
// onLoad () {},
// start () {},
// update (dt) {},
getInstance(){
if(!this._instance){
this._instance = new httpcli();
this._instance.init();
this._instance.setRetryInterval(3000);
this._instance.setNeedRetry(true);
}
return this._instance;
},
httpGet(url, cbRes, cbErr){
// var realurl = url;
// if(urldata){
// if(realurl.indexOf("?") == -1){
// realurl += "?";
// }else{
// realurl += "&";
// }
// realurl += encodeURIComponent(urldata);
// }
return this.httpsend(url, null, cbRes, cbErr, 'GET');
},
httpPost(url, postdata, cbRes, cbErr){
return this.httpsend(url, postdata, cbRes, cbErr, 'POST');
},
httpsend(url, urldata, cbRes, cbErr, smethod){
return this.getInstance().httpsend(url, urldata, cbRes, cbErr, smethod);
},
JSON_parse(text){
try{
return JSON.parse(text);
}catch(err){
console.log(err);
return null;
}
}
};

View File

@ -0,0 +1,129 @@
/**
* Created by y.x on 16/11/8.
*/
// var signals = require("./signals");
var notification = {
_signals: [],
_cachebinds: {},
_findSignal: function(eEvent) {
// var i, signal;
// for(i = this._signals.length; i--;) {
// signal = this._signals[i];
// if(signal.event === eEvent) {
// return signal;
// }
// }
return null;
},
/**
* 创建一个信号与监听函数的绑定
* @param {Number} [eEvent] 事件id也可使用字符串
* @param {Function} [fnListener] 信号处理函数.
* @param {Object} [oTarget] 信号处理函数的对象
* @return {Object} 返回一个描述信号与处理函数的绑定对象作为移除绑定的句柄使用
*/
createBinding: function(eEvent, fnListener, oTarget) {
// find signal
var signal = this._findSignal(eEvent);
// find unused signal
if(signal === null) {
signal = this._findSignal(null);
}
// create new signal
// if(signal === null) {
// signal = new signals.Signal();
// this._signals.push(signal);
// }
// bind listener
if(signal) {
signal.event = eEvent;
return signal.add(fnListener, oTarget);
}
},
/**
* 移除信号的绑定函数
* @param {Object|Array} [oBinding] createSignalBinding返回的对象
*/
removeBinding: function(oBinding) {
var bindings = oBinding instanceof Array ? oBinding : [oBinding];
for(var i = bindings.length; i--;) {
var one = bindings[i],
signal = one.getSignal();
one.detach();
if(signal && signal.getNumListeners() == 0) {
signal.event = null;
}
}
},
/**
* 监听事件
* 与createBinding功能一致(增加了缓存方便删除)
*/
on(eEvent, fnListener, oTarget){
let obj = this._cachebinds[eEvent];
if(!obj){
obj = [];
this._cachebinds[eEvent] = obj;
}
let ob = obj.find((element) => {
return element.listener == fnListener && element.target == oTarget;
});
if(ob){
return ob.binding;
}
let bd = this.createBinding(eEvent, fnListener, oTarget);
ob = {
listener: fnListener,
target: oTarget,
binding: bd
};
obj.push(ob);
return bd;
},
/**
* 取消监听事件参数必须与监听事件保持一致
*/
off(eEvent, fnListener, oTarget){
let obj = this._cachebinds[eEvent];
if(!obj){
return;
}
let idx = obj.findIndex((element) => {
return element.listener == fnListener && element.target == oTarget;
});
if(idx < 0){
return;
}
let ob = obj[idx];
this.removeBinding(ob.binding);
obj.splice(idx, 1);
},
/**
* 发送信号
* @param {Number} [eEvent] 事件id
*/
emit: function(eEvent) {
var signal = this._findSignal(eEvent);
if(signal) {
signal.dispatch.apply(this, arguments);
}
}
};
export default notification;

View File

@ -0,0 +1,445 @@
/*jslint onevar:true, undef:true, newcap:true, regexp:true, bitwise:true, maxerr:50, indent:4, white:false, nomen:false, plusplus:false */
/*global define:false, require:false, exports:false, module:false, signals:false */
/** @license
* JS Signals <http://millermedeiros.github.com/js-signals/>
* Released under the MIT license
* Author: Miller Medeiros
* Version: 1.0.0 - Build: 268 (2012/11/29 05:48 PM)
*/
(function(global){
// SignalBinding -------------------------------------------------
//================================================================
/**
* Object that represents a binding between a Signal and a listener function.
* <br />- <strong>This is an internal constructor and shouldn't be called by regular users.</strong>
* <br />- inspired by Joa Ebert AS3 SignalBinding and Robert Penner's Slot classes.
* @author Miller Medeiros
* @constructor
* @internal
* @name SignalBinding
* @param {Signal} signal Reference to Signal object that listener is currently bound to.
* @param {Function} listener Handler function bound to the signal.
* @param {boolean} isOnce If binding should be executed just once.
* @param {Object} [listenerContext] Context on which listener will be executed (object that should represent the `this` variable inside listener function).
* @param {Number} [priority] The priority level of the event listener. (default = 0).
*/
function SignalBinding(signal, listener, isOnce, listenerContext, priority) {
/**
* Handler function bound to the signal.
* @type Function
* @private
*/
this._listener = listener;
/**
* If binding should be executed just once.
* @type boolean
* @private
*/
this._isOnce = isOnce;
/**
* Context on which listener will be executed (object that should represent the `this` variable inside listener function).
* @memberOf SignalBinding.prototype
* @name context
* @type Object|undefined|null
*/
this.context = listenerContext;
/**
* Reference to Signal object that listener is currently bound to.
* @type Signal
* @private
*/
this._signal = signal;
/**
* Listener priority
* @type Number
* @private
*/
this._priority = priority || 0;
}
SignalBinding.prototype = {
/**
* If binding is active and should be executed.
* @type boolean
*/
active : true,
/**
* Default parameters passed to listener during `Signal.dispatch` and `SignalBinding.execute`. (curried parameters)
* @type Array|null
*/
params : null,
/**
* Call listener passing arbitrary parameters.
* <p>If binding was added using `Signal.addOnce()` it will be automatically removed from signal dispatch queue, this method is used internally for the signal dispatch.</p>
* @param {Array} [paramsArr] Array of parameters that should be passed to the listener
* @return {*} Value returned by the listener.
*/
execute : function (paramsArr) {
var handlerReturn, params;
if (this.active && !!this._listener) {
params = this.params? this.params.concat(paramsArr) : paramsArr;
handlerReturn = this._listener.apply(this.context, params);
if (this._isOnce) {
this.detach();
}
}
return handlerReturn;
},
/**
* Detach binding from signal.
* - alias to: mySignal.remove(myBinding.getListener());
* @return {Function|null} Handler function bound to the signal or `null` if binding was previously detached.
*/
detach : function () {
return this.isBound()? this._signal.remove(this._listener, this.context) : null;
},
/**
* @return {Boolean} `true` if binding is still bound to the signal and have a listener.
*/
isBound : function () {
return (!!this._signal && !!this._listener);
},
/**
* @return {boolean} If SignalBinding will only be executed once.
*/
isOnce : function () {
return this._isOnce;
},
/**
* @return {Function} Handler function bound to the signal.
*/
getListener : function () {
return this._listener;
},
/**
* @return {Signal} Signal that listener is currently bound to.
*/
getSignal : function () {
return this._signal;
},
/**
* Delete instance properties
* @private
*/
_destroy : function () {
delete this._signal;
delete this._listener;
delete this.context;
},
/**
* @return {string} String representation of the object.
*/
toString : function () {
return '[SignalBinding isOnce:' + this._isOnce +', isBound:'+ this.isBound() +', active:' + this.active + ']';
}
};
/*global SignalBinding:false*/
// Signal --------------------------------------------------------
//================================================================
function validateListener(listener, fnName) {
if (typeof listener !== 'function') {
throw new Error( 'listener is a required param of {fn}() and should be a Function.'.replace('{fn}', fnName) );
}
}
/**
* Custom event broadcaster
* <br />- inspired by Robert Penner's AS3 Signals.
* @name Signal
* @author Miller Medeiros
* @constructor
*/
function Signal() {
/**
* @type Array.<SignalBinding>
* @private
*/
this._bindings = [];
this._prevParams = null;
// enforce dispatch to aways work on same context (#47)
var self = this;
this.dispatch = function(){
Signal.prototype.dispatch.apply(self, arguments);
};
}
Signal.prototype = {
/**
* Signals Version Number
* @type String
* @const
*/
VERSION : '1.0.0',
/**
* If Signal should keep record of previously dispatched parameters and
* automatically execute listener during `add()`/`addOnce()` if Signal was
* already dispatched before.
* @type boolean
*/
memorize : false,
/**
* @type boolean
* @private
*/
_shouldPropagate : true,
/**
* If Signal is active and should broadcast events.
* <p><strong>IMPORTANT:</strong> Setting this property during a dispatch will only affect the next dispatch, if you want to stop the propagation of a signal use `halt()` instead.</p>
* @type boolean
*/
active : true,
/**
* @param {Function} listener
* @param {boolean} isOnce
* @param {Object} [listenerContext]
* @param {Number} [priority]
* @return {SignalBinding}
* @private
*/
_registerListener : function (listener, isOnce, listenerContext, priority) {
var prevIndex = this._indexOfListener(listener, listenerContext),
binding;
if (prevIndex !== -1) {
binding = this._bindings[prevIndex];
if (binding.isOnce() !== isOnce) {
throw new Error('You cannot add'+ (isOnce? '' : 'Once') +'() then add'+ (!isOnce? '' : 'Once') +'() the same listener without removing the relationship first.');
}
} else {
binding = new SignalBinding(this, listener, isOnce, listenerContext, priority);
this._addBinding(binding);
}
if(this.memorize && this._prevParams){
binding.execute(this._prevParams);
}
return binding;
},
/**
* @param {SignalBinding} binding
* @private
*/
_addBinding : function (binding) {
//simplified insertion sort
var n = this._bindings.length;
do { --n; } while (this._bindings[n] && binding._priority <= this._bindings[n]._priority);
this._bindings.splice(n + 1, 0, binding);
},
/**
* @param {Function} listener
* @return {number}
* @private
*/
_indexOfListener : function (listener, context) {
var n = this._bindings.length,
cur;
while (n--) {
cur = this._bindings[n];
if (cur._listener === listener && cur.context === context) {
return n;
}
}
return -1;
},
/**
* Check if listener was attached to Signal.
* @param {Function} listener
* @param {Object} [context]
* @return {boolean} if Signal has the specified listener.
*/
has : function (listener, context) {
return this._indexOfListener(listener, context) !== -1;
},
/**
* Add a listener to the signal.
* @param {Function} listener Signal handler function.
* @param {Object} [listenerContext] Context on which listener will be executed (object that should represent the `this` variable inside listener function).
* @param {Number} [priority] The priority level of the event listener. Listeners with higher priority will be executed before listeners with lower priority. Listeners with same priority level will be executed at the same order as they were added. (default = 0)
* @return {SignalBinding} An Object representing the binding between the Signal and listener.
*/
add : function (listener, listenerContext, priority) {
validateListener(listener, 'add');
return this._registerListener(listener, false, listenerContext, priority);
},
/**
* Add listener to the signal that should be removed after first execution (will be executed only once).
* @param {Function} listener Signal handler function.
* @param {Object} [listenerContext] Context on which listener will be executed (object that should represent the `this` variable inside listener function).
* @param {Number} [priority] The priority level of the event listener. Listeners with higher priority will be executed before listeners with lower priority. Listeners with same priority level will be executed at the same order as they were added. (default = 0)
* @return {SignalBinding} An Object representing the binding between the Signal and listener.
*/
addOnce : function (listener, listenerContext, priority) {
validateListener(listener, 'addOnce');
return this._registerListener(listener, true, listenerContext, priority);
},
/**
* Remove a single listener from the dispatch queue.
* @param {Function} listener Handler function that should be removed.
* @param {Object} [context] Execution context (since you can add the same handler multiple times if executing in a different context).
* @return {Function} Listener handler function.
*/
remove : function (listener, context) {
validateListener(listener, 'remove');
var i = this._indexOfListener(listener, context);
if (i !== -1) {
this._bindings[i]._destroy(); //no reason to a SignalBinding exist if it isn't attached to a signal
this._bindings.splice(i, 1);
}
return listener;
},
/**
* Remove all listeners from the Signal.
*/
removeAll : function () {
var n = this._bindings.length;
while (n--) {
this._bindings[n]._destroy();
}
this._bindings.length = 0;
},
/**
* @return {number} Number of listeners attached to the Signal.
*/
getNumListeners : function () {
return this._bindings.length;
},
/**
* Stop propagation of the event, blocking the dispatch to next listeners on the queue.
* <p><strong>IMPORTANT:</strong> should be called only during signal dispatch, calling it before/after dispatch won't affect signal broadcast.</p>
* @see Signal.prototype.disable
*/
halt : function () {
this._shouldPropagate = false;
},
/**
* Dispatch/Broadcast Signal to all listeners added to the queue.
* @param {...*} [params] Parameters that should be passed to each handler.
*/
dispatch : function (params) {
if (! this.active) {
return;
}
var paramsArr = Array.prototype.slice.call(arguments),
n = this._bindings.length,
bindings;
if (this.memorize) {
this._prevParams = paramsArr;
}
if (! n) {
//should come after memorize
return;
}
bindings = this._bindings.slice(); //clone array in case add/remove items during dispatch
this._shouldPropagate = true; //in case `halt` was called before dispatch or during the previous dispatch.
//execute all callbacks until end of the list or until a callback returns `false` or stops propagation
//reverse loop since listeners with higher priority will be added at the end of the list
do { n--; } while (bindings[n] && this._shouldPropagate && bindings[n].execute(paramsArr) !== false);
},
/**
* Forget memorized arguments.
* @see Signal.memorize
*/
forget : function(){
this._prevParams = null;
},
/**
* Remove all bindings from signal and destroy any reference to external objects (destroy Signal object).
* <p><strong>IMPORTANT:</strong> calling any method on the signal instance after calling dispose will throw errors.</p>
*/
dispose : function () {
this.removeAll();
delete this._bindings;
delete this._prevParams;
},
/**
* @return {string} String representation of the object.
*/
toString : function () {
return '[Signal active:'+ this.active +' numListeners:'+ this.getNumListeners() +']';
}
};
// Namespace -----------------------------------------------------
//================================================================
/**
* Signals namespace
* @namespace
* @name signals
*/
var signals = Signal;
/**
* Custom event broadcaster
* @see Signal
*/
// alias for backwards compatibility (see #gh-44)
signals.Signal = Signal;
//exports to multiple environments
if(typeof define === 'function' && define.amd){ //AMD
define(function () { return signals; });
} else if (typeof module !== 'undefined' && module.exports){ //node
module.exports = signals;
} else { //browser
//use string because of Google closure compiler ADVANCED_MODE
/*jslint sub:true */
global['signals'] = signals;
}
}(this));

View File

@ -0,0 +1,112 @@
/**
* Created by y.x on 18/09/06.
*/
export default {
set: function(key, value){
try{
wx.setStorageSync(key,value);
return true;
}catch(err){
console.log(err);
}
return false;
},
get: function(key){
return wx.getStorageSync(key);
},
setjson: function(key, value){
this.set(key,JSON.stringify(value));
},
getjson:function(key){
let str = this.get(key);
if(str){
try{
return JSON.parse(str);
}catch(err){
}
}
return null;
},
remove: function(key){
wx.removeStorageSync(key);
},
hasItem: function(key){
var result = wx.getStorageSync(key);
if(result == '' && typeof(result) != 'number'){
return false;
}
return true;
},
setData: function(key,value){
var data = {};
data[key] = value;
console.log("storage====set== " + JSON.stringify(data));
return this.set(key, JSON.stringify(data));
},
getStringData: function(key){
console.log("storage====get== start" + key);
var result = wx.getStorageSync(key);
if (!result)
{
return "0";
}
var data = null;
try{
data = JSON.parse(result);
}catch(err){
console.log(err);
}
console.log("storage====get== " + data);
if(!data){
return "0";
}
console.log("storage====get== " + data[key]);
return data[key];
},
setStorage: function(skey, svalue, successcb, failcb, timeorign_type, time_value){
var bok = this.set(skey, svalue);
if(bok){
successcb && successcb();
}else{
failcb && failcb(-1, 0, 'storage kev/value failed!k/v:'+skey+'/'+svalue);
}
},
setStorages: function(kvlist, successcb, failcb){
let bok = true;
kvlist.forEach(element => {
if(!this.set(element.key, element.value)){
bok = false;
}
});
if(bok){
successcb && successcb();
}else{
failcb && failcb(-1, 0, 'storage kvlist failed!'+JSON.stringify(kvlist));
}
},
getStorage: function(key, successcb, failcb){
let value = this.get(key);
successcb && successcb(value);
},
getStorages: function(keylist, successcb, failcb){
let lst = [];
keylist.forEach(element => {
let v = this.get(element);
lst.push({
key: element,
value: v,
});
});
successcb && successcb(lst);
},
};

View File

@ -0,0 +1,35 @@
export default function(url){
this.orginurl = url;
this.baseurl = url;
this.checked = false;
this.addKV=function(key, value){
if(typeof(value) == 'undefined'){
return this;
}
this._checkurl();
var str = encodeURIComponent(key) + '=' + encodeURIComponent(value);
this.baseurl += str;
return this;
};
this.clear=function(){
this.baseurl = this.orginurl;
this.checked = false;
};
this._checkurl=function(){
if(!this.checked){
if(this.baseurl.indexOf("?") == -1){
this.baseurl += "?";
}else{
this.baseurl += "&";
}
this.checked = true;
}else{
this.baseurl += "&";
}
};
};

647
src/utils/jcfw/jcfw.js Normal file
View File

@ -0,0 +1,647 @@
import jccloud from './service/jccloud'
import jcgamelog from './service/jcgamelog'
import jclogin from './service/jclogin'
import jcshare from './service/jcshare'
import jcAD from './service/jcAD'
import jcStat from './service/jcstat'
import jcNotify from './service/jcnotify'
import storage from './common/storage'
import notification from './common/notification'
const _GAME_LOCALUUID = 'jc_game_localuuid';
const _GAME_INFO_HANDLER_BINDING = 'jc_gameinfo_handler_binding';
const _GAME_INFO_HANDLER_UNBINDING = 'jc_gameinfo_handler_unbinding';
const JC_CLOUD_URL = 'cloud';
const JC_GAMELOG_URL = 'gamelog';
const JC_LOGIN_URL = 'login';
const JC_NOTIFY_URL = 'notify';
const JC_SVC_URL = 'service';
const JC_STAT_URL = 'stat';
const JC_GAMELIST_URL = 'service';
var JCFW = {
cloud: jccloud,
gamelog: jcgamelog,
login: jclogin,
share: jcshare,
ad: jcAD,
stat: jcStat,
notify: jcNotify,
localUUID: '',
systemInfo: null,
lauchInfo: null,
shareInfo: {},
_handlers: [],
_inited: false,
__getUrl(isoffical, key) {
let pre = key;
if (!isoffical) {
pre += '-test';
}
let str = 'https://' + pre + '.kingsome.cn/webapp/index.php';
// let str = 'https://www.xmjl123.cn/' + pre + '/webapp/index.php';
return str;
},
// 初始化
/**
*
* @param {number} channelid 频道ID
* @param {number} gameid 游戏ID
* @param {boolean} isoffical 上线版本还是测试版本
* @param {object} response 回调对象可不填如果填的话可实现以下一个或多个函数
* .onLogin(logininfo)
* .onLoginFail(net_err, logic_err, errmsg)
* .onUpdateUser(userinfo)
* .onUpdateUserFail(net_err, logic_err, errmsg)
* .onShare(***)
* .onShareFail(***)
*/
init(channelid, gameid, isoffical, launchObj, response, env) {
if (this._inited) {
if (this.rsp != response) {
this.rsp = response;
}
return;
}
this.rsp = response;
this.channelID = parseInt(channelid);
this.gameID = parseInt(gameid);
this.isOffical = isoffical;
this._fixChannelID();
this._checkListener();
this.gamelog.init(this.channelID, this.gameID, isoffical, this, this.__getUrl(isoffical, JC_GAMELOG_URL));
this.cloud.init(this.channelID, this.gameID, isoffical, this, this.__getUrl(isoffical, JC_CLOUD_URL));
this.login.init(this.channelID, this.gameID, isoffical, this, env, this.__getUrl(isoffical, JC_LOGIN_URL));
this.share.init(this.channelID, this.gameID, isoffical, this, this.__getUrl(isoffical, JC_SVC_URL));
this.ad.init(this.channelID, this.gameID, isoffical, this);
this.stat.init(this.channelID, this.gameID, isoffical, this, this.__getUrl(isoffical, JC_STAT_URL));
this.notify.init(this.channelID, this.gameID, isoffical, this, this.__getUrl(isoffical, JC_NOTIFY_URL));
this._loadLocalID();
this._loadLaunchInfo(launchObj);
this._loadSystemInfo();
//this._loadConfig();
this._handleInit(this.channelID, this.gameID, isoffical);
this._inited = true;
},
/**
* 登陆函数
* @param {object} successcb 成功回调初始化时设置了回调对象的话此处可不填
* @param {object} failcb 失败回调初始化时设置了回调对象的话此处可不填
* @param {string} ex_param 额外参数预留字段某些平台可能会使用此字段
*/
loginUser(successcb, failcb, ex_param) {
//console.log('loginUser');
if (this._logining) {
return 1;
}
this.logining = true;
this.login.loginPT((res) => {
this._logining = false;
this.logined = true;
this.setAccountID(res.account_id, res.session_id, res);
this.setNickName(res.nickname);
this.setServerTime(res.server_time);
this.gamelog.logLoginSuccess(res, this.login.login_costtime);
this.gamelog.logShareInvite(this.shareInfo.inviter, this.shareInfo.type, this.shareInfo.id, this.shareInfo.param);
this.gamelog.logSystemInfo(this.systemInfo);
if (this.shareInfo && this.shareInfo.id && this.shareInfo.id != '') {
this.share.acceptDailyInvite(this.shareInfo.param, this.shareInfo.id, () => {
}, () => {
});
}
this.rsp && this.rsp.onLogin && this.rsp.onLogin(res);
successcb && successcb(res);
if (this.cacheuser) {
this.updateUser(this.cacheuser.info, this.cacheuser.success, this.cacheuser.fail);
}
}, (neterr, logicerr, errmsg) => {
this._logining = false;
this.gamelog.logLoginFailed(neterr, logicerr, errmsg);
this.rsp && this.rsp.onLoginFail && this.rsp.onLoginFail(neterr, logicerr, errmsg);
failcb && failcb(neterr, logicerr, errmsg);
}, ex_param);
return 0;
},
loginUserByToken(token, successcb, failcb) {
//console.log('loginUserByToken:' + token);
return this.loginUser(successcb, failcb, token);
},
// 激活
/**
*
* @param {object} allinfo 包含用户信息的对象: 注意allinfo.userInfo为用户实际信息
* @param {object} successcb 成功回调初始化时设置了回调对象的话此处可不填
* @param {object} failcb 失败回调初始化时设置了回调对象的话此处可不填
*/
updateUser(allinfo, successcb, failcb) {
//console.log('updateUser');
if (!this.logined) {
if (!this.cacheuser) {
this.cacheuser = {};
}
this.cacheuser.info = allinfo;
this.cacheuser.success = successcb;
this.cacheuser.fail = failcb;
return;
} else {
this.cacheuser = null;
}
let userinfo = allinfo && allinfo.userInfo;
if (!userinfo) {
this.gamelog.logAuthFail();
this.setUserInfo(null);
} else {
this.gamelog.logAuthSuccess(userinfo);
this.setUserInfo(userinfo);
}
if (!allinfo || !userinfo) {
this.rsp && this.rsp.onUpdateUserFail && this.rsp.onUpdateUserFail(0, -10000, 'info is NULL');
failcb && failcb(0, -10000, 'info is NULL');
return 0;
}
if (this._userupdating) {
return 1;
}
this._userupdating = true;
this.login.updatePTInfo(userinfo, allinfo, (obj) => {
this._userupdating = false;
this.rsp && this.rsp.onUpdateUser && this.rsp.onUpdateUser(obj);
successcb && successcb(obj);
}, (neterr, logicerr, errmsg) => {
this._userupdating = false;
this.rsp && this.rsp.onUpdateUserFail && this.rsp.onUpdateUserFail(neterr, logicerr, errmsg);
failcb && failcb(neterr, logicerr, errmsg);
});
return 0;
},
initGlobalConfig(successcb, failcb) {
this.cloud.getServerConfig((cfg) => {
this.rsp && this.rsp.onServerConfig && this.rsp.onServerConfig(cfg);
successcb && successcb(cfg);
}, (neterr, logicerr, errmsg) => {
this.rsp && this.rsp.onServerConfigFail && this.rsp.onServerConfigFail(neterr, logicerr, errmsg);
failcb && failcb(neterr, logicerr, errmsg);
});
},
// 普通分享
shareNormal(content, imgurl, sharetype, shareparam, extrainfo) {
this.share.shareNormal(content, imgurl, sharetype, shareparam, extrainfo, () => {
this.rsp && this.rsp.onShare && this.rsp.onShare(content, imgurl, sharetype, shareparam, extrainfo);
}, () => {
this.rsp && this.rsp.onShareFail && this.rsp.onShareFail(content, imgurl, sharetype, shareparam, extrainfo);
});
},
// 截图分享
shareCapture(content, capture_rect, sharetype, shareparam, extrainfo) {
this.share.shareCapture(content, capture_rect, sharetype, shareparam, extrainfo, () => {
this.rsp && this.rsp.onShare && this.rsp.onShare(content, capture_rect, sharetype, shareparam, extrainfo);
}, () => {
this.rsp && this.rsp.onShareFail && this.rsp.onShareFail(content, capture_rect, sharetype, shareparam, extrainfo);
});
},
// 生成唯一ID【无需关注此函数】
makeUUID() {
return this.gamelog.generateUUID();
},
// 根据OpenID生成账号ID【通常情况不使用此函数】
makeAccountID(openid) {
return this.login.AccountID(openid);
},
// 添加监听处理器
// handler是回调对象按实际需要可实现以下一个或多个回调
// .onJCInit(channelid, gameid, isoffical){}
// .onJCAccountID(accountid, sessionid){}
// .onJCLocalUUID(localuuid){}
// .onJCUserInfo(userinfo){}
// .onJCLaunchInfo(lauchscene, lauchfromid, launchparam){}
// .onJCGameStart(startmode, extparam){}
// .onJCGameOver(score, bsuccess, extparam){}
addHandler(handler) {
this._checkListener();
if (!handler) {
return false;
}
let obj = this._handlers.find(element => {
return element == handler;
});
if (!obj) {
this._handlers.push(handler);
this._initHandler(handler);
}
return true;
},
// 删除监听处理器
delHandler(handler) {
if (!handler || !this._handlers) {
return false;
}
let idx = this._handlers.findIndex((item) => {
return item == handler;
});
if (idx < 0) {
return true;
}
this._handlers.splice(idx, 1);
return true;
},
// 重置本地ID【通常情况不使用此函数】
resetLocalID() {
this._cleanLocalID();
this._loadLocalID();
},
// 设置sdk回调
setResponse(rsp) {
this.rsp = rsp;
},
// 获取服务器当前时间【登陆完成后才能调用】
getServerNowTime() {
let tm = new Date().getTime();
return this.loginSrvTime + (tm - this.loginLocalTime) / 1000;
},
//游戏相关-------------------------------------------------------
// 游戏开始
// startmode: 0:正常开始游戏 1:重新开始 2:再来一次
gameStart(startmode, extparam) {
switch (startmode) {
case 0:
this.gamelog.logStartGame(extparam);
break;
case 1:
this.gamelog.logRestartGame(extparam);
break;
case 2:
this.gamelog.logTryAgain(extparam);
break;
}
this._handleGameStart(startmode, extparam);
},
// 游戏结束
gameOver(score, bsuccess, extparam) {
this.gamelog.logGameover(extparam, score, bsuccess ? 1 : 0);
this._handleGameOver(score, bsuccess, extparam);
},
// 游戏显示
gameShow(showinfo) {
this.gamelog.logShow();
this._handleGameShow(showinfo);
},
// 游戏隐藏
gameHide() {
this.gamelog.logHide();
this._handGameHide();
},
// 使用道具
gameUseItem(itemid, itemcount, reson, extparam) {
this.gamelog.logUseItem(itemid, itemcount, reson, extparam);
},
// 获得道具
gameGetItem(itemid, itemcount, reson, extparam) {
this.gamelog.logProductItem(itemid, itemcount, reson, extparam);
},
//-----------------------------------------------------------------
// 以下函数无需手动调用
setAccountID(accountid, sessionid, exobj) {
this.accountID = accountid;
this.sessionID = sessionid;
this.accountobj = exobj;
if (exobj && exobj.wid) {
this.weakID = exobj.wid;
}
if (exobj && exobj.sid) {
this.strongID = exobj.sid;
}
if (exobj && exobj.ptid) {
this.ptID = exobj.ptID;
}
this.share.setAccountID(accountid, sessionid, exobj);
this.gamelog.setAccountID(accountid, sessionid, exobj);
this.login.setAccountID(accountid, sessionid, exobj);
this.cloud.setAccountID(accountid, sessionid, exobj);
this.ad.setAccountID(accountid, sessionid, exobj);
this.stat.setAccountID(accountid, sessionid, exobj);
this.notify.setAccountID(accountid, sessionid, exobj);
this._handleAccountID(accountid, sessionid, exobj);
// this.logined = this.accountID && this.accountID != '';
},
setLocalUUID(uuid) {
this.localUUID = uuid;
this.gamelog.setLocalUUID(uuid);
this.cloud.setLocalUUID(uuid);
this.login.setLocalUUID(uuid);
this.share.setLocalUUID(uuid);
this.ad.setLocalUUID(uuid);
this.stat.setLocalUUID(uuid);
this.notify.setLocalUUID(uuid);
this._handleLocalID(uuid);
},
setNickName(nickname) {
if (nickname && nickname != '' && this.nickName != nickname) {
this.nickName = nickname;
this.gamelog.setNickName(nickname);
this.cloud.setNickName(nickname);
this.login.setNickName(nickname);
this.share.setNickName(nickname);
this.ad.setNickName(nickname);
this.stat.setNickName(nickname);
this.notify.setNickName(nickname);
this._handleNickName(nickname);
}
},
setFromAppID(appid, scene, paramobj) {
this.scene = scene;
if (appid) {
this.fromID = appid;
this.gamelog.setFromAppID(appid);
this.cloud.setFromAppID(appid);
this.login.setFromAppID(appid);
this.share.setFromAppID(appid);
this.ad.setFromAppID(appid);
this.stat.setFromAppID(appid);
this.notify.setFromAppID(appid);
}
if (paramobj) {
this.lauchparam = paramobj;
}
this._handleLauchInfo(scene, appid, paramobj);
},
setSystemInfo(info) {
this.systemInfo = info;
this.gamelog.setSystemInfo(info);
this.cloud.setSystemInfo(info);
this.login.setSystemInfo(info);
this.share.setSystemInfo(info);
this.ad.setSystemInfo(info);
this.stat.setSystemInfo(info);
this.notify.setSystemInfo(info);
},
setUserInfo(info) {
if (!this._userInfo) {
this._userinfo = {};
}
this.login.appendUserInfo(this._userinfo, info);
// this.userInfo = info;
if (this._userinfo.nickName) {
this.setNickName(this._userinfo.nickName);
}
this.share.setUserInfo(this._userinfo);
this._handleUserInfo(this._userinfo);
},
setServerTime(srvtime) {
if (!srvtime) {
return;
}
this.loginSrvTime = srvtime;
this.loginLocalTime = new Date().getTime();
this.notify.setServerTime(srvtime, this.loginLocalTime);
this._handleServerTime(srvtime, this.loginLocalTime);
},
_loadLocalID() {
let id = storage.get(_GAME_LOCALUUID);
let bneedsave = false;
if (!id) {
id = this.makeUUID();
bneedsave = true;
}
this.setLocalUUID(id);
if (bneedsave) {
this._saveLocalID();
}
},
_saveLocalID() {
if (!storage.set(_GAME_LOCALUUID, this.localUUID)) {
setTimeout(this._saveLocalID.bind(this), 5000);
}
},
_cleanLocalID() {
storage.remove(_GAME_LOCALUUID);
},
_loadLaunchInfo(res) {
let info = null;
if (wx && wx.getLaunchOptionsSync) {
info = wx.getLaunchOptionsSync();
}
this.lauchInfo = res ? res : info;
if (!this.lauchInfo) {
return;
}
this.gamelog.handlelaunch(this.lauchInfo, (sharetype, shareparam, shareid, inviterid,
fromid, fromscene, launchobj) => {
this.shareInfo.type = sharetype;
this.shareInfo.param = shareparam;
this.shareInfo.id = shareid;
this.shareInfo.inviter = inviterid;
this.setFromAppID(fromid, fromscene, launchobj);
});
},
_loadSystemInfo() {
let info = wx.getSystemInfoSync();
this.gamelog.logLaunchSystemInfo(info);
this.setSystemInfo(info);
},
_loadConfig() {
this.initGlobalConfig();
},
_initHandler(obj) {
if (this.gameID && obj.onJCInit) {
obj.onJCInit(this.channelID, this.gameID, this.isOffical);
}
if (this.accountID && this.sessionID && obj.onJCAccountID) {
obj.onJCAccountID(this.accountID, this.sessionID, this.accountobj);
}
if (this.localUUID && obj.onJCLocalUUID) {
obj.onJCLocalUUID(this.localUUID);
}
if (this.nickName && obj.onJCNickName) {
obj.onJCNickName(this.nickName);
}
if (this._userinfo && obj.onJCUserInfo) {
obj.onJCUserInfo(this._userinfo);
}
if (this.fromID && obj.onJCLaunchInfo) {
obj.onJCLaunchInfo(this.scene, this.fromID, this.lauchparam);
}
},
_handleInit(channelid, gameid, isoffical) {
this._handlers.forEach(element => {
if (element.onJCInit) {
element.onJCInit(channelid, gameid, isoffical);
}
});
},
_handleAccountID(accountid, sessionid, exobj) {
this._handlers.forEach(element => {
if (element.onJCAccountID) {
element.onJCAccountID(accountid, sessionid, exobj);
}
});
},
_handleLocalID(localuuid) {
this._handlers.forEach(element => {
if (element.onJCLocalUUID) {
element.onJCLocalUUID(localuuid);
}
});
},
_handleNickName(nickname) {
this._handlers.forEach(element => {
if (element.onJCNickName) {
element.onJCNickName(nickname);
}
});
},
_handleUserInfo(userinfo) {
this._handlers.forEach(element => {
if (element.onJCUserInfo) {
element.onJCUserInfo(userinfo);
}
});
},
_handleLauchInfo(lauchscene, lauchfromid, launchparam) {
this._handlers.forEach(element => {
if (element.onJCLaunchInfo) {
element.onJCLaunchInfo(lauchscene, lauchfromid, launchparam);
}
});
},
_handleServerTime(servertime, localtime) {
this._handlers.forEach(element => {
if (element.onJCServerTime) {
element.onJCServerTime(servertime, localtime);
}
});
},
_handleGameStart(startmode, extparam) {
this._handlers.forEach(element => {
if (element.onJCGameStart) {
element.onJCGameStart(startmode, extparam);
}
});
},
_handleGameOver(score, bsuccess, extparam) {
this._handlers.forEach(element => {
if (element.onJCGameOver) {
element.onJCGameOver(score, bsuccess, extparam);
}
});
},
_handleGameShow(showinfo) {
this._handlers.forEach(element => {
if (element.onJCGameShow) {
element.onJCGameShow(showinfo);
}
});
},
_handGameHide(hideinfo) {
this._handlers.forEach(element => {
if (element.onJCGameHide) {
element.onJCGameHide(hideinfo);
}
});
},
_handleNotifyMsgs(lst, notifyobj) {
this._handlers.forEach(element => {
if (element.onJCNotifyMsg) {
element.onJCNotifyMsg(lst, notifyobj);
}
});
},
_checkListener() {
if (!this._listenerID) {
this._listenerID = notification.on(_GAME_INFO_HANDLER_BINDING, (msgid, handler) => {
this.addHandler(handler);
}, this);
}
if (!this._unlistenerID) {
this._unlistenerID = notification.on(_GAME_INFO_HANDLER_UNBINDING, (msgid, handler) => {
this.delHandler(handler);
}, this);
}
},
_fixChannelID() {
}
};
export default JCFW;

View File

@ -0,0 +1,414 @@
export default {
properties: {
},
// LIFE-CYCLE CALLBACKS:
// onLoad () {},
__createAD: function(adtype, adunitid, bannerY, canvasH, owner){
let obj = owner;
if(!owner){
obj = {
adType: adtype,
adUnitId: adunitid,
state: 0
};
}
switch(this.channelid){
case 6001:
{
if(adtype == 0){
let realy = this.winH / 2 - bannerY / canvasH * this.winH - 80 / 2;
if(!obj.style){
obj.style = {
left: 0,
top: realy,
width: this.winW,
height: 80,
//realWidth: nc.width,
//realHeight: nc.height
};
}
let data = {
adUnitId: adunitid,
style: obj.style
};
if(wx && wx.createBannerAd){
let ad = wx.createBannerAd(data);
obj.ad = ad;
}
/*
ad.onResize(res => {
console.log("[bannerad]onResize:" + res.width + "," + res.height);
console.log("[bannerad]style:" + JSON.stringify(ad));
});
*/
}else if(adtype == 1){
let data = {
adUnitId: adunitid
};
if(wx && wx.createRewardedVideoAd){
let ad = wx.createRewardedVideoAd(data);
obj.ad = ad;
}
}
}break;
case 6002:
{
if(adtype == 0){
let realy = this.winH / 2 - bannerY / canvasH * this.winH - 80 / 2;
if(!obj.style){
obj.style = {
x: 0,
y: realy
//realWidth: nc.width,
//realHeight: nc.height
};
}
let data = {
viewId: adunitid,
style: obj.style
};
if(BK && BK.Advertisement && BK.Advertisement.createBannerAd){
let ad = BK.Advertisement.createBannerAd(data);
obj.ad = ad;
}
}else if(adtype == 1){
if(BK && BK.Advertisement && BK.Advertisement.createVideoAd){
let ad = BK.Advertisement.createVideoAd();
obj.ad = ad;
}
}
}break;
case 6003:{
if(typeof(qg)!='undefined'){
if(adtype == 0){
let ad = qg.createBannerAd({
posId: adunitid
});
obj.ad = ad;
}else if(adtype == 1){
let ad = qg.createRewardedVideoAd({
posId: adunitid
});
obj.ad = ad;
}else if(adtype == 2){
let ad = qg.createInsertAd({
posId: adunitid
});
obj.ad = ad;
}
}
}break;
}
return obj;
},
init(channelid, gameid, isoffical, owner){
this.owner = owner;
this.gameid = gameid;
this.channelid = channelid;
this.BannerAds = [];
this.VideoAds = [];
this.cleanBannerAD();
this.cleanVideoAD();
},
initAdEnv(param){
switch(this.channelid){
case 6003:
{
if(typeof(qg)!='undefined'){
qg.initAdService({
appId: param,
isDebug: false,
});
}
}break;
}
},
setAccountID(accountid, sessionid){
this.accountid = accountid;
this.sessionid = sessionid;
},
setNickName(nickname){
this.nickname = nickname;
},
setFromAppID(appid){
this.fromid = appid;
},
setLocalUUID(uuid){
this.localid = uuid;
},
setSystemInfo(info){
this.winW = info.windowWidth;
this.winH = info.windowHeight;
},
// 添加banner广告
addBannerAD(advid, identifier, bannerY, canvasH, rspCb){
var adobj = this.__createAD(0, advid, bannerY, canvasH);
if(adobj){
adobj.param = identifier;
adobj.rspCb = rspCb;
this.initAD(adobj);
this.BannerAds.push(adobj);
}
return ad;
},
// 添加激励广告(视频广告)
addVideoAD(advid, identifier, rspCb){
var adobj = this.__createAD(1, advid);
if(adobj){
adobj.param = identifier;
adobj.rspCb = rspCb;
this.initAD(adobj);
this.VideoAds.push(adobj);
}
},
// update (dt) {},
reLoadBannerAD(identifier){
let obj = this.BannerAds.find((element) => {
return element.param == identifier;
})
if(obj && obj.ad){
let id = obj.adUnitId;
this.destoryAD(obj.ad);
this.__createAD(0, id, 0, 0, obj);
}
return obj;
},
hasBannerAD(identifier){
let obj = this.findBannerAD(identifier);
if(obj && obj.ad){
return true;
}
return false;
},
hasVideoAD(identifier){
let obj = this.findVideoAD(identifier);
if(obj && obj.ad){
return true;
}
return false;
},
findBannerAD(identifier){
let obj = this.BannerAds.find((element) => {
return element.param == identifier;
})
return obj;
},
findVideoAD(identifier){
let obj = this.VideoAds.find((element) => {
return element.param == identifier;
})
return obj;
},
hideAllAD(){
this.BannerAds.forEach(element => {
this.hideAD(element);
});
},
// 显示/隐藏banner广告
switchBannerAD (identifier, bShow){
this.hideAllAD();
if(bShow){
let obj = reLoadBannerAD(identifier);
obj.needshow = true;
this.showAD(obj);
}
},
// 显示激励广告(视频广告)
showRewardAD (identifier, successcb, failcb){
let obj = this.findVideoAD(identifier);
if(!obj || !obj.ad){
failcb && failcb(identifier);
return;
}
obj.successcb = successcb;
obj.failcb = failcb;
obj.needshow = true;
this.loadAD(obj);
},
onLoadAD(obj){
console.log("[ad]onload");
obj.rspCb && obj.rspCb(100, obj);
if(obj.needshow){
this.showAD(obj);
}
},
onErrAD(errtype, err, obj){
console.log('[AD]err:' + errtype);
console.log(err);
obj.rspCb && obj.rspCb(errtype, obj, err);
if(obj.needshow && obj.failcb){
obj.failcb(obj.param, err);
}
obj.needshow = false;
},
onFinishAD(bReward, obj, res){
if(bReward){
obj.rspCb && obj.rspCb(10, obj, res, true);
if(obj.needshow && obj.successcb){
obj.successcb(obj.param, res);
obj.needshow = false;
}
}else{
obj.rspCb && obj.rspCb(11, obj, res, false);
if(obj.needshow && obj.failcb){
obj.failcb(obj.param, res);
obj.needshow = false;
}
}
},
destoryAD(ad){
if(!ad){
return;
}
ad.state = 30;
ad.destroy && ad.destroy();
},
showAD(obj){
let ad = obj.ad;
if(!ad){
return;
}
ad.state = 10;
ad.show && ad.show();
},
hideAD(obj){
let ad = obj.ad;
if(!ad){
return;
}
ad.state = 20;
ad.hide && ad.hide();
},
// 激励广告调用
loadAD(obj){
let ad = obj.ad;
if(!ad){
return;
}
ad.state = 100;
switch(this.channelid){
case 6001:
{
ad.load && ad.load();
}break;
case 6002:{
this.onLoadAD(obj);
}break;
case 6003:{
ad.load && ad.load();
}break;
}
},
initAD(obj){
let ad = obj.ad;
if(!ad){
return;
}
ad.onLoad && ad.onLoad(() => {
console.log("[ad]onload");
this.onLoadAD(obj);
});
ad.onError && ad.onError(res => {
console.log("[ad]onerror:"+JSON.stringify(res));
this.onErrAD(-obj.state, res, obj);
});
let self = this;
switch(this.channelid){
case 6001:{
let closeCb = function(res){
console.log("[ad]onClose:"+JSON.stringify(res));
// 用户点击了【关闭广告】按钮
// 小于 2.1.0 的基础库版本res 是一个 undefined
if (res && res.isEnded || res === undefined) {
// 正常播放结束,可以下发游戏奖励
self.onFinishAD(res.isEnded, obj, res);
} else {
// 播放中途退出,不下发游戏奖励
self.onFinishAD(false, obj, res);
}
// ad.offClose && ad.offClose(closeCb);
};
ad.onClose && ad.onClose(closeCb);
}break;
case 6002:{
let closeCb = function(res){
console.log("[ad]onClose:"+JSON.stringify(res));
self.onFinishAD(false, obj, res);
// ad.offClose && ad.offClose(closeCb);
};
// ad.onPlayStart && ad.onPlayStart(function () {
// //开始播放
// });
ad.onPlayFinish && ad.onPlayFinish(function () {
//播放结束
self.onFinishAD(true, obj, null);
});
ad.onClose && ad.onClose(closeCb);
}break;
case 6003:{
let closeCb = function(){
console.log("[ad]onRewarded");
self.onFinishAD(true, obj, null);
// ad.offClose && ad.offClose(closeCb);
};
ad.onRewarded && ad.onRewarded(closeCb);
}break;
}
},
cleanBannerAD(){
if(this.BannerAds.length > 0){
this.BannerAds.forEach(element => {
this.destoryAD(element.ad);
});
this.BannerAds.length = 0;
}
},
cleanVideoAD(){
if(this.VideoAds.length > 0){
this.VideoAds.length = 0;
}
}
};

View File

@ -0,0 +1,479 @@
import httpclient from '../common/httpclient'
import urlbuilder from '../common/urlbuilder'
export default {
// LIFE-CYCLE CALLBACKS:
// onLoad () {},
// start () {},
// update (dt) {},
__getConfig(accountid, sessionid, channelid, gameid, actionname, successcb, failcb) {
channelid = 6001;
this.urlbd.clear();
this.urlbd.addKV('c', 'Config')
.addKV('a', actionname)
.addKV('account_id', accountid)
.addKV('session_id', sessionid)
.addKV('gameid', gameid)
.addKV('channel', channelid)
;
httpclient.httpGet(this.urlbd.baseurl, function (restext) {
var obj = httpclient.JSON_parse(restext);
if (obj.errcode == 0) {
//console.log('[__getConfig]success!'+JSON.stringify(obj));
var kvobj = httpclient.JSON_parse(obj.KVList);
if (kvobj) {
successcb && successcb(kvobj);
} else {
failcb && failcb(0, -1, "kvlist is not obj");
}
} else {
//console.log('[__getConfig]failed!'+obj.errcode+":"+obj.errmsg);
failcb && failcb(0, obj.errcode, obj.errmsg);
}
}, function (errcode, errmsg) {
//console.log('[__getConfig]failed!'+errcode+":"+errmsg);
failcb && failcb(errcode, 0, errmsg);
});
},
__getStorage(accountid, sessionid, token, skey, successcb, failcb) {
this.urlbd.clear();
this.urlbd.addKV('c', 'CloudStorage')
.addKV('a', 'getStorage')
.addKV('account_id', accountid)
.addKV('session_id', sessionid)
.addKV('access_token', token)
.addKV('keys', skey);
httpclient.httpGet(this.urlbd.baseurl, function (restext) {
var obj = httpclient.JSON_parse(restext);
if (obj.errcode == 0) {
//console.log('[__getStorage]success!'+JSON.stringify(obj));
//var kvobj = httpclient.JSON_parse(obj.KVList);
var kvobj = obj.KVList;
if (kvobj) {
successcb && successcb(kvobj);
} else {
failcb && failcb(0, -1, "kvlist is not obj");
}
} else {
//console.log('[__getStorage]failed!'+obj.errcode+":"+obj.errmsg);
failcb && failcb(0, obj.errcode, obj.errmsg);
}
}, function (errcode, errmsg) {
//console.log('[__getStorage]failed!'+errcode+":"+errmsg);
failcb && failcb(errcode, 0, errmsg);
});
},
__getExpireTime(accountid, sessionid, token, skey, successcb, failcb) {
this.urlbd.clear();
this.urlbd.addKV('c', 'CloudStorage')
.addKV('a', 'ttl')
.addKV('account_id', accountid)
.addKV('session_id', sessionid)
.addKV('access_token', token)
.addKV('keys', skey);
httpclient.httpGet(this.urlbd.baseurl, function (restext) {
var obj = httpclient.JSON_parse(restext);
if (obj.errcode == 0) {
//console.log('[__getExpireTime]success!'+JSON.stringify(obj));
var ktobj = httpclient.JSON_parse(obj.KTList);
if (ktobj) {
successcb && successcb(ktobj);
} else {
failcb && failcb(0, -1, "kvlist is not obj");
}
} else {
//console.log('[__getExpireTime]failed!'+obj.errcode+":"+obj.errmsg);
failcb && failcb(0, obj.errcode, obj.errmsg);
}
}, function (errcode, errmsg) {
//console.log('[__getExpireTime]failed!'+errcode+":"+errmsg);
failcb && failcb(errcode, 0, errmsg);
});
},
__setStorage(accountid, sessionid, token, kvlist, successcb, failcb) {
this.urlbd.clear();
this.urlbd.addKV('c', 'CloudStorage')
.addKV('a', 'setStorage')
.addKV('account_id', accountid)
.addKV('session_id', sessionid)
.addKV('access_token', token);
let value = JSON.stringify(kvlist);
httpclient.httpPost(this.urlbd.baseurl, value, function (restext) {
let obj = httpclient.JSON_parse(restext);
if (obj.errcode == 0) {
//console.log('[__setStorage]success!'+JSON.stringify(obj));
successcb && successcb();
} else {
//console.log('[__setStorage]failed!'+obj.errcode+":"+obj.errmsg);
failcb && failcb(0, obj.errcode, obj.errmsg);
}
}, function (errcode, errmsg) {
//console.log('[__setStorage]failed!'+errcode+":"+errmsg);
failcb && failcb(errcode, 0, errmsg);
});
},
__setExpireTime(accountid, sessionid, token, skey, origntype, timevalue, successcb, failcb) {
this.urlbd.clear();
this.urlbd.addKV('c', 'CloudStorage')
.addKV('a', 'expire')
.addKV('account_id', accountid)
.addKV('session_id', sessionid)
.addKV('access_token', token)
.addKV('keys', skey)
.addKV('time_origin', origntype)
.addKV('time_val', timevalue);
httpclient.httpGet(this.urlbd.baseurl, function (restext) {
let obj = httpclient.JSON_parse(restext);
if (obj.errcode == 0) {
//console.log('[__delStorage]success!'+JSON.stringify(obj));
successcb && successcb();
} else {
//console.log('[__delStorage]failed!'+obj.errcode+":"+obj.errmsg);
failcb && failcb(0, obj.errcode, obj.errmsg);
}
}, function (errcode, errmsg) {
//console.log('[__delStorage]failed!'+errcode+":"+errmsg);
failcb && failcb(errcode, 0, errmsg);
});
},
__clearStorage(accountid, sessionid, token, successcb, failcb) {
this.urlbd.clear();
this.urlbd.addKV('c', 'CloudStorage')
.addKV('a', 'clearStorage')
.addKV('account_id', accountid)
.addKV('session_id', sessionid)
.addKV('access_token', token);
httpclient.httpGet(this.urlbd.baseurl, function (restext) {
let obj = httpclient.JSON_parse(restext);
if (obj.errcode == 0) {
//console.log('[__clearStorage]success!'+JSON.stringify(obj));
successcb && successcb();
} else {
//console.log('[__clearStorage]failed!'+obj.errcode+":"+obj.errmsg);
failcb && failcb(0, obj.errcode, obj.errmsg);
}
}, function (errcode, errmsg) {
//console.log('[__clearStorage]failed!'+errcode+":"+errmsg);
failcb && failcb(errcode, 0, errmsg);
});
},
__delStorage(accountid, sessionid, token, skey, successcb, failcb) {
this.urlbd.clear();
this.urlbd.addKV('c', 'CloudStorage')
.addKV('a', 'delKeys')
.addKV('account_id', accountid)
.addKV('session_id', sessionid)
.addKV('access_token', token)
.addKV('keys', skey);
httpclient.httpGet(this.urlbd.baseurl, function (restext) {
let obj = httpclient.JSON_parse(restext);
if (obj.errcode == 0) {
//console.log('[__delStorage]success!'+JSON.stringify(obj));
successcb && successcb();
} else {
//console.log('[__delStorage]failed!'+obj.errcode+":"+obj.errmsg);
failcb && failcb(0, obj.errcode, obj.errmsg);
}
}, function (errcode, errmsg) {
//console.log('[__delStorage]failed!'+errcode+":"+errmsg);
failcb && failcb(errcode, 0, errmsg);
});
},
__getShareConfig(accountid, sessionid, gameid, sex, province, city, successcb, failcb) {
this.urlbd.clear();
this.urlbd.addKV('c', 'Config')
.addKV('a', 'share')
.addKV('account_id', accountid)
.addKV('session_id', sessionid)
.addKV('gameid', gameid)
.addKV('sex', sex)
.addKV('province', province)
.addKV('city', city)
;
httpclient.httpGet(this.urlbd.baseurl, function (restext) {
let obj = httpclient.JSON_parse(restext);
if (obj.errcode == 0) {
//console.log('[__getShareConfig]success!'+JSON.stringify(obj));
successcb && successcb(obj.share_info);
} else {
//console.log('[__getShareConfig]failed!'+obj.errcode+":"+obj.errmsg);
failcb && failcb(0, obj.errcode, obj.errmsg);
}
}, function (errcode, errmsg) {
//console.log('[__getShareConfig]failed!'+errcode+":"+errmsg);
failcb && failcb(errcode, 0, errmsg);
});
},
init(channelid, gameid, isoffical, owner, url) {
this.gameid = gameid;
this.channelid = channelid;
this.token = '';
this.urlbd = new urlbuilder(url);
this.cfg = {
_reborntype: -1,
_getrewardtype: -1,
_exchange_rewardtype: -1,
_navigateflag: -1,
_serverversion: -1,
_gglFlag: -1
};
this.cfginited = false;
//console.log("[jccloud]init:"+gameid + "|" + channelid + "|" + isoffical);
},
setAccountID(accountid, sessionid) {
this.accountid = accountid;
this.sessionid = sessionid;
},
setNickName(nickname) {
this.nickname = nickname;
},
setFromAppID(appid) {
this.fromid = appid;
},
setLocalUUID(uuid) {
this.localid = uuid;
},
setSystemInfo(info) {
},
setUserInfo(info) {
this.userinfo = info;
},
getConfig(successcb, failcb) {
if (this._configgetting) {
return 1;
}
this._configgetting = true;
this.__getConfig(this.accountid, this.sessionid, this.channelid, this.gameid, 'read', (kvlist) => {
this._configgetting = false;
successcb && successcb(kvlist);
}, (neterr, logicerr, errmsg) => {
this._configgetting = false;
failcb && failcb(neterr, logicerr, errmsg);
});
return 0;
},
initConfig(successcb, failcb) {
if (this.cfginited) {
successcb && successcb(this.cfg);
return 0;
}
this.cfginited = false;
return this.getConfig((res) => {
//console.log(JSON.stringify(res));
if (res instanceof Array) {
res.forEach(element => {
if (element.key == 'reborn') {
this.cfg._reborntype = element.value;
} else if (element.key == 'share_reward') {
this.cfg._getrewardtype = element.value;
} else if (element.key == 'exchange_reward') {
this.cfg._exchange_rewardtype = element.value;
} else if (element.key == 'navigate') {
this.cfg._navigateflag = element.value;
} else if (element.key == 'version') {
this.cfg._serverversion = element.value;
} else if (element.key == 'ggl') {
this.cfg._gglFlag = element.value;
} else if (element.key == 'festival') {
this.cfg._festivalFlag = element.value;
} else {
this.cfg[element.key] = element.value;
}
});
this.cfginited = true;
successcb && successcb(this.cfg);
} else {
failcb && failcb(0, -1, '');
}
}, (neterr, logicerr, errmsg) => {
failcb && failcb(neterr, logicerr, errmsg);
});
},
getPrivateConfig(successcb, failcb) {
if (this._pvconfiggetting) {
return 1;
}
this._pvconfiggetting = true;
this.__getConfig(this.accountid, this.sessionid, this.channelid, this.gameid, 'readPrivate', (kvlist) => {
this._pvconfiggetting = false;
successcb && successcb(kvlist);
}, (neterr, logicerr, errmsg) => {
this._pvconfiggetting = false;
failcb && failcb(neterr, logicerr, errmsg);
});
return 0;
},
initPrivateConfig(successcb, failcb) {
if (this.pvcfginited) {
successcb && successcb(this.pvcfg);
return 0;
}
this.pvcfginited = false;
return this.getPrivateConfig((res) => {
//console.log(JSON.stringify(res));
if (res instanceof Array) {
res.forEach(element => {
this.pvcfg[element.key] = element.value;
});
this.pvcfginited = true;
successcb && successcb(this.pvcfg);
} else {
failcb && failcb(0, -1, '');
}
}, (neterr, logicerr, errmsg) => {
failcb && failcb(neterr, logicerr, errmsg);
});
},
// 获取服务器配置
getServerConfig(successcb, failcb, bForce) {
if (bForce) {
this.cfginited = false;
}
return this.initConfig(successcb, failcb);
},
getPrivateConfig(successcb, failcb) {
if (bForce) {
this.pvcfginited = false;
}
return this.initPrivateConfig(successcb, failcb);
},
getShareConfig(successcb, failcb) {
if (this.userinfo) {
this.__getShareConfig(this.accountid, this.sessionid, this.gameid,
this.userinfo.sex, this.userinfo.province, this.userinfo.city, successcb, failcb);
} else {
this.__getShareConfig(this.accountid, this.sessionid, this.gameid,
0, '', '', successcb, failcb);
}
},
setStorage: function (skey, svalue, successcb, failcb, timeorign_type, time_value) {
let obj = {
key: skey,
value: svalue
};
if (timeorign_type && time_value) {
obj.time_origin = timeorign_type;
obj.time_val = time_value;
}
let lst = [obj];
this.__setStorage(this.accountid, this.sessionid, this.token, lst, successcb, failcb);
},
setStorages: function (kvlist, successcb, failcb) {
this.__setStorage(this.accountid, this.sessionid, this.token, kvlist, successcb, failcb);
},
getStorage: function (key, successcb, failcb) {
this.__getStorage(this.accountid, this.sessionid, this.token, key, (kvlist) => {
if (kvlist.length > 0) {
let obj = kvlist[0];
successcb && successcb(obj.value, obj.ttl_seconds, obj.key);
} else {
successcb && successcb(null, -1, key);
}
}, failcb);
},
getStorages: function (keylist, successcb, failcb) {
let skey = keylist.join();
this.__getStorage(this.accountid, this.sessionid, this.token, skey, successcb, failcb);
},
delStorage: function (key, successcb, failcb) {
this.__delStorage(this.accountid, this.sessionid, this.token, key, successcb, failcb);
},
delStorages: function (keylist, successcb, failcb) {
let skey = keylist.join();
this.__delStorage(this.accountid, this.sessionid, this.token, skey, successcb, failcb);
},
clearStorage: function (successcb, failcb) {
this.__clearStorage(this.accountid, this.sessionid, this.token, successcb, failcb);
},
setExpireTime: function (key, timeorign_type, time_value, successcb, failcb) {
this.__setExpireTime(this.accountid, this.sessionid, this.token, key, timeorign_type, time_value, successcb, failcb);
},
setExpireTimes: function (keylist, timeorign_type, time_value, successcb, failcb) {
let skey = keylist.join();
this.__setExpireTime(this.accountid, this.sessionid, this.token, skey, timeorign_type, time_value, successcb, failcb);
},
getExpireTime: function (key, successcb, failcb) {
this.__getStorage(this.accountid, this.sessionid, this.token, key, (ktlist) => {
if (ktlist.length > 0) {
let obj = ktlist[0];
successcb && successcb(obj.ttl_seconds, obj.key);
} else {
successcb && successcb(-1, key);
}
}, failcb);
},
getExpireTimes: function (key, successcb, failcb) {
this.__getStorage(this.accountid, this.sessionid, this.token, key, successcb, failcb);
},
getShareData(psex, pprovince, pcity, successcb, failcb) {
this.urlbd.clear();
this.urlbd.addKV('c', 'Config')
.addKV('a', 'share')
.addKV('gameid', this.gameid)
.addKV('sex', psex)
.addKV('province', pprovince)
.addKV('city', pcity)
.addKV('account_id', this.accountid)
.addKV('session_id', this.sessionid)
.addKV('access_token', this.token);
httpclient.httpGet(this.urlbd.baseurl, function (restext) {
let obj = httpclient.JSON_parse(restext);
if (obj.errcode == 0) {
successcb && successcb(obj.share_info);
} else {
//console.log('[__delStorage]failed!'+obj.errcode+":"+obj.errmsg);
failcb && failcb();
}
}, function (errcode, errmsg) {
//console.log('[__delStorage]failed!'+errcode+":"+errmsg);
failcb && failcb();
});
},
};

View File

@ -0,0 +1,951 @@
import httpclient from '../common/httpclient'
import urlbuilder from '../common/urlbuilder'
import storage from '../common/storage'
const JC_LOG_T = {
lauch: {
key: 1,
subkey: 1,
},
entermain: {
key: 1,
subkey: 2,
},
show: {
key: 1,
subkey: 3
},
hide: {
key: 1,
subkey: 3
},
jumpapp: {
key: 1,
subkey: 4
},
loginFailed: {
key: 1,
subkey: 5
},
launchsysteminfo: {
key: 1,
subkey: 6
},
logined: {
key: 11,
subkey: 1
},
authed: {
key: 11,
subkey: 2
},
authfail: {
key: 11,
subkey: 3
},
startgame: {
key: 11,
subkey: 4
},
restartgame: {
key: 11,
subkey: 4
},
gameover: {
key: 11,
subkey: 6
},
againgame: {
key: 11,
subkey: 4
},
productitem: {
key: 11,
subkey: 8
},
useitem: {
key: 11,
subkey: 9
},
share: {
key: 11,
subkey: 10
},
inviter: {
key: 11,
subkey: 11
},
systeminfo: {
key: 11,
subkey: 20
},
advinfo: {
key: 11,
subkey: 21
},
vslogin: {
key: 11,
subkey: 24
},
vsreconnect: {
key: 11,
subkey: 25
},
vsroomcreate: {
key: 11,
subkey: 26
},
vsroomjoin: {
key: 11,
subkey: 27
},
vsroomleave: {
key: 11,
subkey: 28
},
vsroomsetstate: {
key: 11,
subkey: 29
},
business: {
key: 11,
subkey: 30
},
buttonclick: {
key: 11,
subkey: 31
},
msgevent: {
key: 11,
subkey: 32
}
};
const _SHOW_FLAG = 2;
const _HIDE_FLAG = 1;
const _ONLINE_KEY = 'jc_online_flags';
// 说明:带下划线的函数是内部函数,无需关心
export default {
// LIFE-CYCLE CALLBACKS:
// onLoad () {},
// start () {},
// update (dt) {},
__uuid(len, radix) {
var chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.split('');
var uuid = [], i;
radix = radix || chars.length;
if (len) {
// Compact form
for (i = 0; i < len; i++) uuid[i] = chars[0 | Math.random() * radix];
} else {
// rfc4122, version 4 form
var r;
// rfc4122 requires these characters
uuid[8] = uuid[13] = uuid[18] = uuid[23] = '-';
uuid[14] = '4';
// Fill in random data. At i==19 set the high bits of clock sequence as
// per rfc4122, sec. 4.1.5
for (i = 0; i < 36; i++) {
if (!uuid[i]) {
r = 0 | Math.random() * 16;
uuid[i] = chars[(i == 19) ? (r & 0x3) | 0x8 : r];
}
}
}
return uuid.join('');
},
_buildReportUrl(typeobj) {
this.urlbd.clear();
this.urlbd.addKV('c', 'GameLog')
.addKV('a', 'reportLog')
.addKV('gameid', this.gameid)
.addKV('channel', this.channelid)
.addKV('account_id', this.accountid)
.addKV('session_id', this.sessionid)
.addKV('access_token', this.token)
.addKV('wid', this.wid)
.addKV('sid', this.sid)
.addKV('ptid', this.ptid)
.addKV('logclass1', typeobj.key)
.addKV('logclass2', typeobj.subkey)
.addKV('localuuid', this.localid)
.addKV('from_appid', this.fromid)
;
//console.log("[gamelog]");
//console.log(JSON.stringify(typeobj));
return this.urlbd.baseurl;
},
_buildReportUserUrl() {
this.urlbd.clear();
this.urlbd.addKV('c', 'GameLog')
.addKV('a', 'reportUser')
.addKV('gameid', this.gameid)
.addKV('channel', this.channelid)
.addKV('account_id', this.accountid)
.addKV('session_id', this.sessionid)
.addKV('access_token', this.token)
;
return this.urlbd.baseurl;
},
_buildShowHideMsg(showflag) {
let data = {
str1: this.localid,
str2: this.fromid,
str3: this.accountid,
str4: this.nickName,
num1: showflag,
num2: -1
};
let msg = {
u: this._buildReportUrl(showflag == _SHOW_FLAG ? JC_LOG_T.show : JC_LOG_T.hide),
v: JSON.stringify(data),
ext: showflag
};
return msg;
},
_report(typeobj, valueobj, successcb, failcb) {
let url = this._buildReportUrl(typeobj);
let value = JSON.stringify(valueobj);
var self = this;
httpclient.httpPost(url, value, function (restext) {
let obj = httpclient.JSON_parse(restext);
if (obj.errcode == 0) {
//console.log('[_report]success!'+JSON.stringify(obj));
successcb && successcb();
} else {
//console.log('[_report]'+url);
//console.log('[_report]failed!'+obj.errcode+":"+obj.errmsg);
failcb && failcb(0, obj.errcode, obj.errmsg);
}
}, function (errcode, errmsg) {
//console.log('[_report]'+url);
//console.log('[_report]failed!'+errcode+":"+errmsg);
failcb && failcb(errcode, 0, errmsg);
let nflag = -1;
if (typeobj.key == JC_LOG_T.show.key && typeobj.subkey == JC_LOG_T.show.subkey) {
nflag = valueobj.num1;
}
let msg = {
u: url,
v: value,
ext: nflag
}
self.cachemsg.push(msg);
});
},
_reportUser(valueobj, successcb, failcb) {
let url = this._buildReportUserUrl();
let value = JSON.stringify(valueobj);
var self = this;
httpclient.httpPost(url, value, function (restext) {
let obj = httpclient.JSON_parse(restext);
if (obj.errcode == 0) {
//console.log('[_reportUser]success!'+JSON.stringify(obj));
successcb && successcb();
} else {
//console.log('[_reportUser]failed!'+obj.errcode+":"+obj.errmsg);
failcb && failcb(0, obj.errcode, obj.errmsg);
}
}, function (errcode, errmsg) {
//console.log('[_reportUser]failed!'+errcode+":"+errmsg);
failcb && failcb(errcode, 0, errmsg);
let nflag = -1;
let msg = {
u: url,
v: value,
ext: nflag
}
self.cachemsg.push(msg);
});
},
_retry() {
if (this.cachemsg.length > 0) {
let obj = this.cachemsg[0];
var self = this;
httpclient.httpPost(obj.u, obj.v, function (restext) {
if (obj.ext >= 0) {
self.showflag = obj.ext;
self._saveflag(self.showflag);
}
self.cachemsg.shift();
}, function (errcode, errmsg) {
//console.log('[_retry_report]failed!'+errcode+":"+errmsg);
});
}
},
_saveflag(showflag) {
storage.set(_ONLINE_KEY, showflag);
},
_loadflag() {
return storage.get(_ONLINE_KEY);
},
_handlelaunch(res) {
if (res) {
if (res.query && res.query.weixinadinfo) {
let wxaddr = res.query.weixinadinfo.split('.');
let ad = wxaddr[0];
if (ad && ad != '') {
this.fromadvid = ad;
}
}
this.launchparam = res.query;
if (res.referrerInfo && res.referrerInfo.appId) {
this.setFromAppID(res.referrerInfo.appId);
this.launchparam = res.referrerInfo.extraData;
} else if (res.query && res.query.scene) {
this.setFromAppID(res.query.scene);
}
this.scene = res.scene ? res.scene : 0;
}
},
_handleLoginInfo(res) {
if (res.account_id && res.session_id) {
this.setAccountID(res.account_id, res.session_id);
}
if (res && res.nickname && res.nickname != '') {
this.setNickName(res.nickname);
}
},
_handleAuthInfo(res) {
if (res && res.nickname && res.nickname != '') {
this.setNickName(res.nickname);
}
},
//【通用函数】生成本地匿名ID
generateUUID() {
return this.__uuid(32, 62);
},
// 初始化上报前必须调用此函数【使用jcfw.init的话此函数无需手动调用】
init(channelid, gameid, isoffical, owner, url) {
this.gameid = gameid;
this.channelid = channelid;
this.accountid = this.accountid ? this.accountid : '';
this.sessionid = this.sessionid ? this.sessionid : '';
this.token = this.token ? this.token : '';
this.localid = this.localid ? this.localid : '';
this.nickname = this.nickname ? this.nickname : '';
this.fromid = this.fromid ? this.fromid : '';
this.fromadvid = this.fromadvid ? this.fromadvid : '';
this.scene = this.scene ? this.scene : 0;
this._tempuuid = '';
this._starttime = 0;
this._launchtime = 0;
this.needsubmit = false;
this.urlbd = new urlbuilder(url);
this.showflag = this._loadflag();
this.cachemsg = [];
if (this.showflag == _SHOW_FLAG) {
this.cachemsg.push(this._buildShowHideMsg(this.showflag));
}
this.showflag = null;
setInterval(this._retry.bind(this), 5000);
//console.log("[jcgamelog]init:"+gameid + "|" + channelid + "|" + isoffical);
},
// 【暂未使用】
setSubmitFlag(bsubmit) {
this.needsubmit = bsubmit;
},
// 登陆成功后调用传入accountid和sessionid【使用jcfw.login的话此函数无需手动调用】
setAccountID(accountid, sessionid, exobj) {
if (!this.accountid || this.accountid != accountid) {
this.accountid = accountid;
}
if (!this.sessionid || this.sessionid != sessionid) {
this.sessionid = sessionid;
}
if (exobj) {
this.wid = exobj.wid;
this.sid = exobj.sid;
this.ptid = exobj.ptid;
}
},
// 设置昵称【无需手动调用】
setNickName(nickname) {
if (!this.nickname || this.nickname != nickname) {
this.nickname = nickname;
}
},
// 设置本app从哪个appid跳转过来的【使用jcfw.init的话此函数无需手动调用】
setFromAppID(appid) {
if (!this.fromid || this.fromid != appid) {
this.fromid = appid;
}
},
// 设置本地匿名ID本地生成匿名id后调用【使用jcfw.init的话此函数无需手动调用】
setLocalUUID(uuid) {
if (!this.localid || this.localid != uuid) {
this.localid = uuid;
}
},
setSystemInfo(info) {
},
// 【暂未使用】
setToken(token) {
this.token = token;
},
handlelaunch(res, cb) {
this._launchtime = new Date().getTime();
var param = 0;
var uid = '';
var stype = 0;
var invid = '';
if (res) {
this._handlelaunch(res);
param = res.query.activity_param ? res.query.activity_param : 0;
uid = res.query.localuuid ? res.query.localuuid : '';
stype = res.query.sharetype ? res.query.sharetype : 0;
invid = res.query.inviter_id ? res.query.inviter_id : '';
}
this.logLauchDefault(res);
cb && cb(stype, param, uid, invid, this.fromid, this.scene, this.launchparam);
},
//////////////////统计函数////////////////////
// 启动游戏--------游戏启动后上报【使用jcfw.init的话此函数无需手动调用】
logLaunch(launch_option) {
this._launchtime = new Date().getTime();
this._handlelaunch(launch_option);
this.logLauchDefault(launch_option);
},
//启动游戏(内部调用)
logLauchDefault(launch_option) {
let data = {
str1: this.localid,
str2: this.fromid,
ext: launch_option ? JSON.stringify(launch_option) : null,
str3: this.fromadvid,
num1: this.scene
}
this._report(JC_LOG_T.lauch, data);
},
// 登陆成功--------游戏登陆成功后上报【使用jcfw.login的话此函数无需手动调用】
logLoginSuccess(res, costtime) {
let nowtime = new Date().getTime();
let dttime = nowtime - this._launchtime;
this._handleLoginInfo(res);
let data = {
str1: res.nickname,
str2: res.unionid,
str3: res.country,
str4: res.province,
str5: res.city,
str6: this.localid,
num1: costtime ? costtime : 0,
num2: dttime,
str7: this.fromadvid
}
//console.log('[launchcost]'+dttime);
this._report(JC_LOG_T.logined, data);
},
// 登陆失败---------游戏登陆失败后上报【使用jcfw.login的话此函数无需手动调用】
logLoginFailed(neterr, logicerr, errmsg) {
let data = {
error_code_net: neterr,
error_code_logic: logicerr,
error_msg: errmsg
};
this._report(JC_LOG_T.loginFailed, data);
},
// 授权成功--------微信获取userinfo后上报【使用jcfw.login的话此函数无需手动调用】
logAuthSuccess(res) {
this._handleAuthInfo(res);
let data = {
str1: res.nickName,
num1: res.gender,
str3: res.country,
str4: res.province,
str5: res.city,
str6: this.localid,
str7: res.avatarUrl ? res.avatarUrl : '',
str8: res.language
}
this._report(JC_LOG_T.authed, data);
},
// 授权失败--------微信获取userinfo时用户拒绝授权后上报【使用jcfw.login的话此函数无需手动调用】
logAuthFail() {
let data = {
str1: this.nickName,
str2: this.localid
}
this._report(JC_LOG_T.authfail, data);
},
// 分享---------------用户分享时上报【使用jcfw.shareNormal/shareCapture的话此函数无需手动调用】
logShare(businessid, sharetokenid, param) {
let data = {
str1: this.nickname,
str2: sharetokenid ? sharetokenid : '',
num1: businessid,
str3: param ? param : ''
}
this._report(JC_LOG_T.share, data);
},
// 分享点击-------------当用户点击别人分享的卡片进入游戏时上报【使用jcfw.login的话此函数无需手动调用】
logShareInvite(inviterid, businessid, sharetokenid, param) {
let data = {
str1: this.nickName,
str2: inviterid,
num1: businessid,
str3: sharetokenid ? sharetokenid : sharetokenid,
str4: param ? param : ''
}
this._report(JC_LOG_T.inviter, data);
},
// 系统信息-------------获取用户系统信息后上报【使用jcfw.init的话此函数无需手动调用】
logSysInfo(res, typeobj) {
let data = {
str1: res.brand,
str2: res.model,
str3: res.language,
str4: res.version,
str5: res.platform,
str6: res.SDKVersion,
str7: res.system,
num1: res.pixelRatio,
num2: res.screenWidth,
num3: res.screenHeight,
num4: res.windowWidth,
num5: res.windowHeight,
num6: res.benchmarkLevel
// ext: JSON.stringify(res)
};
this._report(typeobj, data);
},
logSystemInfo(res) {
if (!res) {
return;
}
this.logSysInfo(res, JC_LOG_T.systeminfo);
},
logLaunchSystemInfo(res) {
if (!res) {
return;
}
this.logSysInfo(res, JC_LOG_T.launchsysteminfo);
},
// 开始游戏---------开始一局游戏时上报【使用jcfw.gameStart的话此函数无需手动调用】
logStartGame(param, startmode) {
this._tempuuid = this.generateUUID();
this._starttime = new Date().getTime();
let data = {
str1: this.fromid,
str2: this._tempuuid,
str3: param ? param : '',
str4: this.nickname,
str5: this.localid,
num1: startmode ? startmode : 0
}
this._report(JC_LOG_T.startgame, data);
},
// 重新开始游戏---------重新开始一局游戏时上报【使用jcfw.gameStart的话此函数无需手动调用】
logRestartGame(param) {
this._tempuuid = this.generateUUID();
this._starttime = new Date().getTime();
let data = {
str1: this.fromid,
str2: this._tempuuid,
str3: param ? param : '',
str4: this.nickname,
str5: this.localid,
num1: 1
}
this._report(JC_LOG_T.restartgame, data);
},
// 游戏结束---------本局游戏结束时上报【使用jcfw.gameOver的话此函数无需手动调用】
logGameover(param, score, endflag) {
let nowtime = new Date().getTime();
let data = {
str1: this.fromid,
str2: this._tempuuid,
str3: param ? param : '',
num1: score,
str4: this.nickname,
str5: this.localid,
num2: nowtime - this._starttime,
num3: endflag ? endflag : 0
}
this._report(JC_LOG_T.gameover, data);
},
// 再来一次----------再来一次时上报【使用jcfw.gameStart的话此函数无需手动调用】
logTryAgain(param) {
this._tempuuid = this.generateUUID();
let data = {
str1: this.fromid,
str2: this._tempuuid,
str3: param ? param : '',
str4: this.nickname,
str5: this.localid,
num1: 2
}
this._report(JC_LOG_T.againgame, data);
},
// 显示-----------------------app显示时上报eg:wx.onShow【使用jcfw.gameShow的话此函数无需手动调用】
logShow(bIgnoreFlag) {
if (!bIgnoreFlag) {
let bok = !this.showflag || this.showflag == _HIDE_FLAG;
if (!bok) {
return;
}
this.showflag = _SHOW_FLAG;
}
let nowtime = new Date().getTime();
let data = {
str1: this.localid,
str2: this.fromid,
str3: this.accountid,
str4: this.nickName,
num1: _SHOW_FLAG,
num2: nowtime - this._launchtime
};
this._report(JC_LOG_T.show, data, () => {
if (!bIgnoreFlag) {
this._saveflag(this.showflag);
}
}, () => {
});
},
// 隐藏-----------------------app隐藏时上报eg:wx.onHide【使用jcfw.gameHide的话此函数无需手动调用】
logHide(bIgnoreFlag) {
if (!bIgnoreFlag) {
let bok = this.showflag && this.showflag == _SHOW_FLAG;
if (!bok) {
return;
}
this.showflag = _HIDE_FLAG;
}
let nowtime = new Date().getTime();
let data = {
str1: this.localid,
str2: this.fromid,
str3: this.accountid,
str4: this.nickName,
num1: _HIDE_FLAG,
num2: nowtime - this._launchtime
};
this._report(JC_LOG_T.hide, data, () => {
if (!bIgnoreFlag) {
this._saveflag(this.showflag);
}
}, () => {
});
},
// 产出道具----------道具产出时上报【使用jcfw.gameGetItem的话此函数无需手动调用】
logProductItem(itemid, itemcount, reson, resonparam) {
let data = {
str1: this.nickname,
num1: itemid,
num2: itemcount,
num3: reson,
num4: resonparam
}
this._report(JC_LOG_T.productitem, data);
},
// 使用道具----------使用道具时上报【使用jcfw.gameUseItem的话此函数无需手动调用】
logUseItem(itemid, itemcount, reson, resonparam) {
let data = {
str1: this.nickname,
num1: itemid,
num2: itemcount,
num3: reson,
num4: resonparam
}
this._report(JC_LOG_T.useitem, data);
},
// 运营活动上报---------------开始运营活动时上报
logBusiness(businessid, actionid) {
let data = {
str1: this.nickName,
str2: this.localid,
num1: businessid,
num2: actionid
};
this._report(JC_LOG_T.business, data);
},
// 进入游戏主界面-------------主界面显示时上报
logEnterMainScene(dt) {
let data = {
str1: this.localid,
str2: this.fromid,
num1: dt ? dt : 0
};
this._report(JC_LOG_T.entermain, data);
},
// 跳转到其他app--------------跳转到其他app时上报eg: wx.navigateMiniProgram)
logJumpApp(appid, appparam, jumpres) {
let data = {
str1: this.localid,
str2: this.fromid,
str3: this.accountid,
str4: this.nickName,
str5: appid,
str6: appparam,
num1: jumpres ? jumpres : 0
};
this._report(JC_LOG_T.jumpapp, data);
},
// 广告相关-----------------处理广告时上报eg: 激励广告出现时)
logAdvInfo(advid, actiontype, actionparam) {
let data = {
str1: this.nickname,
str2: advid,
num1: actiontype,
str3: actionparam
};
this._report(JC_LOG_T.advinfo, data);
},
// 【对战开房间】登陆【无需主动调用】
logVS_login() {
let data = {
str1: this.nickName
};
this._report(JC_LOG_T.vslogin, data);
},
// 【对战开房间】重连【无需主动调用】
logVS_reconnect(roomid) {
let data = {
str1: this.nickName,
str2: roomid
};
this._report(JC_LOG_T.vsreconnect, data);
},
// 【对战开房间】创建房间【无需主动调用】
logVS_createRoom(roomname, maxplayer) {
let data = {
str1: this.nickname,
str2: roomname,
num1: maxplayer
};
this._report(JC_LOG_T.vsroomcreate, data);
},
// 【对战开房间】加入房间【无需主动调用】
logVS_joinRoom(roomid, customdata, israndom) {
let data = {
str1: this.nickname,
str2: roomid ? roomid : '',
num1: israndom ? 1 : 0,
str3: customdata
};
this._report(JC_LOG_T.vsroomjoin, data);
},
// 【对战开房间】离开房间【无需主动调用】
logVS_leaveRoom(roomid, customdata) {
let data = {
str1: this.nickname,
str2: roomid,
str3: customdata
};
this._report(JC_LOG_T.vsroomleave, data);
},
// 【对战开房间】游戏准备【无需主动调用】
logVS_gameReady(roomid, customdata, isready) {
let data = {
str1: this.nickname,
str2: roomid,
num1: isready ? 1 : 0,
str3: customdata
};
this._report(JC_LOG_T.vsroomsetstate, data);
},
// 【对战开房间】游戏开始【无需主动调用】
logVS_gameStart(roomid, customdata) {
let data = {
str1: this.nickname,
str2: roomid,
num1: 2,
str3: customdata
};
this._report(JC_LOG_T.vsroomsetstate, data);
},
// 按钮事件----------------点击按钮时上报
logButtonClick(buttonname, param, buttonsubname) {
let data = {
nickname: this.nickname,
button_name: buttonname,
button_param: param ? param : ''
};
if (buttonsubname) {
data.button_subname = buttonsubname;
}
this._report(JC_LOG_T.buttonclick, data);
},
logMsg(msgid, msgname, errcode, reqcontent, rspcontent, passtime) {
let data = {
msg_id: msgid,
msg_name: msgname,
msg_error: errcode,
req_content: reqcontent,
rsp_content: rspcontent,
msg_cosumetime: passtime
};
this._report(JC_LOG_T.msgevent, data);
},
// 设置角色属性
/*
run(){
let obj = {
level: 1,
money: 10000,
...
};
jcfw.gamelog.userSet(obj);
}
*/
userSet(kvobj) {
let data = {
set: kvobj
};
this._reportUser(data);
},
// 设置角色属性(仅允许设置一次)
/*
run(){
let obj = {
nickname: "abc"
};
jcfw.gamelog.userSet(obj);
}
*/
userSetOnce(kvobj) {
let data = {
set_once: kvobj
};
this._reportUser(data);
},
// 增加/减少角色数值属性
/*
run(){
let obj = {
level: 1
};
jcfw.gamelog.userAdd(obj);
}
*/
userAdd(kvobj) {
let data = {
add: kvobj
};
this._reportUser(data);
},
/*可以一次调用set/setonce/add */
userReport(setobj, setonceobj, addobj) {
let data = {
set: setobj,
set_once: setonceobj,
add: addobj
};
this._reportUser(data);
},
/**
*
* @param {number} externalID 外部调用的ID
* @param {object} logFunc 外部调用的方法
* @param {string} p1 参数1
* @param {string} p2 参数2
* @param {string} p3 参数3
* @param {string} p4 参数4
*/
externalLog(externalID, logFunc, p1, p2, p3, p4) {
let tmpid = this.gameid;
this.gameid = externalID;
logFunc && logFunc.call(this, p1, p2, p3, p4);
this.gameid = tmpid;
}
};

View File

@ -0,0 +1,740 @@
import httpclient from '../common/httpclient'
import urlbuilder from '../common/urlbuilder'
export default {
// LIFE-CYCLE CALLBACKS:
// onLoad () {},
//start () {},
// update (dt) {},
__login(channelid, gameid, tokencode, isoffical, successcb, failcb, openid) {
this.urlbd.clear();
this.urlbd.addKV('c', 'Login')
.addKV('a', 'auth')
.addKV('gameid', gameid)
.addKV('channel', channelid)
.addKV('token', tokencode);
if (openid && openid != '') {
this.urlbd.addKV('openid', openid);
}
if (this.env) {
this.urlbd.addKV('env', this.env);
}
httpclient.httpGet(this.urlbd.baseurl, function (restext) {
var obj = httpclient.JSON_parse(restext);
if (obj && obj.errcode == 0) {
//console.log('[__login]success!'+JSON.stringify(obj));
successcb && successcb(obj);
} else {
//console.log('[__login]failed!'+restext);
failcb && failcb(0, obj ? obj.errcode : -1, obj ? obj.errmsg : restext);
}
}, function (errcode, errmsg) {
//console.log('[__login]failed!'+errcode+":"+errmsg);
failcb && failcb(errcode, 0, errmsg);
});
},
__activeWX(gameid, accountid, sessionid, raw, sign, encyptdata, iv, successcb, failcb) {
this.urlbd.clear();
this.urlbd.addKV('c', 'Login')
.addKV('a', 'activateWeiXinUser')
.addKV('gameid', gameid)
.addKV('account_id', accountid)
.addKV('session_id', sessionid)
.addKV('rawdata', raw)
.addKV('signature', sign)
.addKV('encrypted_data', encyptdata)
.addKV('iv', iv)
;
httpclient.httpGet(this.urlbd.baseurl, function (restext) {
if (restext == '') {
failcb && failcb(0, -1, "restext is nullstring!");
return;
}
var obj = httpclient.JSON_parse(restext);
if (obj && obj.errcode == 0) {
//console.log('[__activeWX]success!'+JSON.stringify(obj));
successcb && successcb(obj);
} else {
//console.log('[__activeWX]failed!'+obj.errcode+":"+obj.errmsg);
failcb && failcb(0, obj.errcode, obj.errmsg);
}
}, function (errcode, errmsg) {
//console.log('[__activeWX]failed!'+errcode+":"+errmsg);
failcb && failcb(errcode, 0, errmsg);
});
},
__updateInfo(accountid, sessionid, usrinfo, successcb, failcb) {
this.urlbd.clear();
this.urlbd.addKV('c', 'Login')
.addKV('a', 'updateUserInfo')
.addKV('account_id', accountid)
.addKV('session_id', sessionid)
.addKV('nickname', usrinfo.nickname)
.addKV('city', usrinfo.city)
.addKV('province', usrinfo.province)
.addKV('avatar_url', usrinfo.avatar_url)
.addKV('country', usrinfo.country)
.addKV('sex', usrinfo.sex)
.addKV('birthday', usrinfo.birthday)
.addKV('phone', usrinfo.phone)
.addKV('location', usrinfo.location)
;
// if(!this.isoffical){
// //console.log(this.urlbd.baseurl);
// }
httpclient.httpGet(this.urlbd.baseurl, function (restext) {
var obj = httpclient.JSON_parse(restext);
if (obj.errcode == 0) {
//console.log('[__updateInfo]success!'+JSON.stringify(obj));
successcb && successcb(obj);
} else {
//console.log('[__updateInfo]failed!'+obj.errcode+":"+obj.errmsg);
failcb && failcb(0, obj.errcode, obj.errmsg);
}
}, function (errcode, errmsg) {
//console.log('[__updateInfo]failed!'+errcode+":"+errmsg);
failcb && failcb(errcode, 0, errmsg);
});
},
__generalSignature(accountid, sessionid, signdata, successcb, failcb) {
this.urlbd.clear();
this.urlbd.addKV('c', 'Login')
.addKV('a', 'signature')
.addKV('account_id', accountid)
.addKV('session_id', sessionid)
.addKV('params', signdata)
;
httpclient.httpGet(this.urlbd.baseurl, function (restext) {
var obj = httpclient.JSON_parse(restext);
if (obj.errcode == 0) {
//console.log('[__generalSignature]success!'+JSON.stringify(obj));
successcb && successcb(obj);
} else {
//console.log('[__generalSignature]failed!'+obj.errcode+":"+obj.errmsg);
failcb && failcb(0, obj.errcode, obj.errmsg);
}
}, function (errcode, errmsg) {
//console.log('[__generalSignature]failed!'+errcode+":"+errmsg);
failcb && failcb(errcode, 0, errmsg);
});
},
__generalToken(accountid, sessionid, sceneid, successcb, failcb) {
this.urlbd.clear();
this.urlbd.addKV('c', 'Login')
.addKV('a', 'getAccessToken')
.addKV('account_id', accountid)
.addKV('session_id', sessionid)
.addKV('scene', sceneid)
;
httpclient.httpGet(this.urlbd.baseurl, function (restext) {
var obj = httpclient.JSON_parse(restext);
if (obj.errcode == 0) {
//console.log('[__generalToken]success!'+JSON.stringify(obj));
successcb && successcb(obj);
} else {
//console.log('[__generalToken]failed!'+obj.errcode+":"+obj.errmsg);
failcb && failcb(0, obj.errcode, obj.errmsg);
}
}, function (errcode, errmsg) {
//console.log('[__generalToken]failed!'+errcode+":"+errmsg);
failcb && failcb(errcode, 0, errmsg);
});
},
__getAnnouncement(channelid, gameid, successcb, failcb) {
this.urlbd.clear();
this.urlbd.addKV('c', 'Annc')
.addKV('a', 'getAnnouncement')
.addKV('gameid', gameid)
.addKV('channel', channelid)
;
httpclient.httpGet(this.urlbd.baseurl, function (restext) {
var obj = httpclient.JSON_parse(restext);
if (obj.errcode == 0) {
//console.log('[__getAnnouncement]success!'+JSON.stringify(obj));
successcb && successcb(obj);
} else {
//console.log('[__getAnnouncement]failed!'+obj.errcode+":"+obj.errmsg);
failcb && failcb(0, obj.errcode, obj.errmsg);
}
}, function (errcode, errmsg) {
//console.log('[__getAnnouncement]failed!'+errcode+":"+errmsg);
failcb && failcb(errcode, 0, errmsg);
});
},
__getServerList(channelid, gameid, successcb, failcb) {
this.urlbd.clear();
this.urlbd.addKV('c', 'SrvList')
.addKV('a', 'getSrvList')
.addKV('gameid', gameid)
.addKV('channel', channelid);
if (this.env) {
this.urlbd.addKV('env', this.env);
}
httpclient.httpGet(this.urlbd.baseurl, function (restext) {
var obj = httpclient.JSON_parse(restext);
if (obj.errcode == 0) {
//console.log('[__getServerList]success!'+JSON.stringify(obj));
successcb && successcb(obj.server_list);
} else {
//console.log('[__getServerList]failed!'+obj.errcode+":"+obj.errmsg);
failcb && failcb(0, obj.errcode, obj.errmsg);
}
}, function (errcode, errmsg) {
//console.log('[__getServerList]failed!'+errcode+":"+errmsg);
failcb && failcb(errcode, 0, errmsg);
});
},
__loginYoume(accountid, sessionid, nickname, successcb, failcb) {
this.urlbd.clear();
this.urlbd.addKV('c', 'YouMe')
.addKV('a', 'login')
.addKV('account_id', accountid)
.addKV('session_id', sessionid)
.addKV('nickname', nickname);
httpclient.httpGet(this.urlbd.baseurl, function (restext) {
var obj = httpclient.JSON_parse(restext);
if (obj.errcode == 0) {
//console.log('[__loginYoume]success!'+JSON.stringify(obj));
successcb && successcb(obj.token);
} else {
//console.log('[__loginYoume]failed!'+obj.errcode+":"+obj.errmsg);
failcb && failcb(0, obj.errcode, obj.errmsg);
}
}, function (errcode, errmsg) {
//console.log('[__loginYoume]failed!'+errcode+":"+errmsg);
failcb && failcb(errcode, 0, errmsg);
});
},
__registerJCAccount(account, pwd, phone, smscode, successcb, failcb) {
this.urlbd.clear();
this.urlbd.addKV('c', 'SelfSdk')
.addKV('a', 'registerAccount')
.addKV('account', account)
.addKV('passwd', pwd)
.addKV('phone', phone)
.addKV('sms_auth_code', smscode)
;
httpclient.httpGet(this.urlbd.baseurl, function (restext) {
var obj = httpclient.JSON_parse(restext);
if (obj.errcode == 0) {
//console.log('[__registerAccount]success!'+JSON.stringify(obj));
successcb && successcb(obj.token);
} else {
//console.log('[__registerAccount]failed!'+obj.errcode+":"+obj.errmsg);
failcb && failcb(0, obj.errcode, obj.errmsg);
}
}, function (errcode, errmsg) {
//console.log('[__registerAccount]failed!'+errcode+":"+errmsg);
failcb && failcb(errcode, 0, errmsg);
});
},
__loginJCByID(account, pwd, successcb, failcb) {
this.urlbd.clear();
this.urlbd.addKV('c', 'SelfSdk')
.addKV('a', 'login')
.addKV('account', account)
.addKV('passwd', pwd)
;
httpclient.httpGet(this.urlbd.baseurl, function (restext) {
var obj = httpclient.JSON_parse(restext);
if (obj.errcode == 0) {
//console.log('[__loginJC]success!'+JSON.stringify(obj));
successcb && successcb(obj.token);
} else {
//console.log('[__loginJC]failed!'+obj.errcode+":"+obj.errmsg);
failcb && failcb(0, obj.errcode, obj.errmsg);
}
}, function (errcode, errmsg) {
//console.log('[__loginJC]failed!'+errcode+":"+errmsg);
failcb && failcb(errcode, 0, errmsg);
});
},
__loginJCBySMS(phone, smscode, successcb, failcb) {
this.urlbd.clear();
this.urlbd.addKV('c', 'SelfSdk')
.addKV('a', 'smsLogin')
.addKV('phone', phone)
.addKV('sms_auth_code', smscode)
;
httpclient.httpGet(this.urlbd.baseurl, function (restext) {
var obj = httpclient.JSON_parse(restext);
if (obj.errcode == 0) {
//console.log('[__loginSMS]success!'+JSON.stringify(obj));
successcb && successcb(obj.token);
} else {
//console.log('[__loginSMS]failed!'+obj.errcode+":"+obj.errmsg);
failcb && failcb(0, obj.errcode, obj.errmsg);
}
}, function (errcode, errmsg) {
//console.log('[__loginSMS]failed!'+errcode+":"+errmsg);
failcb && failcb(errcode, 0, errmsg);
});
},
__sendSMSCode(phone, code_type, successcb, failcb) {
this.urlbd.clear();
this.urlbd.addKV('c', 'SelfSdk')
.addKV('a', 'sendSmsCode')
.addKV('phone', phone)
.addKV('code_type', code_type)
;
httpclient.httpGet(this.urlbd.baseurl, function (restext) {
var obj = httpclient.JSON_parse(restext);
if (obj.errcode == 0) {
//console.log('[__sendSMSCode]success!'+JSON.stringify(obj));
successcb && successcb();
} else {
//console.log('[__sendSMSCode]failed!'+obj.errcode+":"+obj.errmsg);
failcb && failcb(0, obj.errcode, obj.errmsg);
}
}, function (errcode, errmsg) {
//console.log('[__sendSMSCode]failed!'+errcode+":"+errmsg);
failcb && failcb(errcode, 0, errmsg);
});
},
_checkUserInfo() {
if (this._localinfoloaded && this._svinfoloaded) {
if (this.channelid == 6001) {
if (!this.actived) {
this.activewx(this.userinfo, this._activesuccess, this._activefail);
} else {
if (this._combineInfo(this.svuserinfo, this.userinfo)) {
this.updateinfo(this.svuserinfo, this._activesuccess, this._activefail);
} else {
this._activesuccess && this._activesuccess(this.userinfo);
}
// this._activefail && this._activefail(0, -1, 'is not weixin platform!');
}
} else {
if (this._combineInfo(this.svuserinfo, this.userinfo)) {
this.updateinfo(this.svuserinfo, this._activesuccess, this._activefail);
} else {
this._activesuccess && this._activesuccess(this.userinfo);
}
}
}
},
_checkNickName() {
if (this.userinfo.nickname) {
this.owner && this.owner.setNickName(this.userinfo.nickname);
}
},
_loadLocalInfo(info) {
if (!this.userinfo) {
this.userinfo = {};
}
switch (this.channelid) {
case 6001:
case 7101:
{
this.userinfo.nickname = info.nickName;
this.userinfo.country = info.country;
this.userinfo.province = info.province;
this.userinfo.city = info.city;
this.userinfo.avatar_url = info.avatarUrl;
this.userinfo.sex = info.gender;
} break;
case 6002: {
} break;
case 6003: {
this.userinfo.nickname = info.nickName;
this.userinfo.avatar_url = info.avatar;
this.userinfo.sex = info.sex;
this.userinfo.birthday = info.birthday;
this.userinfo.phone = info.phoneNum;
this.userinfo.location = info.location;
} break;
case 6004: {
this.userinfo.nickname = info.nickname;
this.userinfo.avatar_url = info.avatar;
this.userinfo.unionid = info.unionid;
//todo:
} break;
case 6501: {
this.userinfo.nickname = info.nick;
this.userinfo.avatar_url = info.avatar;
//todo:
} break;
default: {
this.userinfo.nickname = info.nickname;
} break;
}
//console.log('[_loadLocalInfo]finish');
this._localinfoloaded = true;
},
_loadTokenInfo(tokeninfo) {
if (!this.userinfo) {
this.userinfo = {};
}
if (tokeninfo && tokeninfo.rawData) {
this.userinfo.rawData = tokeninfo.rawData;
this.userinfo.signature = tokeninfo.signature;
this.userinfo.encryptedData = tokeninfo.encryptedData;
this.userinfo.iv = tokeninfo.iv;
}
this._localtokenloaded = true;
},
_loadServerInfo(info) {
if (!this.svuserinfo) {
this.svuserinfo = {};
}
this.svuserinfo.nickname = info.nickname;
this.svuserinfo.country = info.country;
this.svuserinfo.province = info.province;
this.svuserinfo.city = info.city;
this.svuserinfo.avatar_url = info.avatar_url;
this.svuserinfo.sex = info.sex;
this.svuserinfo.birthday = info.birthday;
this.svuserinfo.phone = info.phone;
this.svuserinfo.location = info.location;
//console.log('[_loadServerInfo]finish');
this._svinfoloaded = true;
},
_combineInfo(svinfo, lcinfo) {
let bupdated = false;
if (lcinfo.nickname && svinfo.nickname != lcinfo.nickname) {
//console.log('[nickname]'+svinfo.nickName+"|"+lcinfo.nickname);
svinfo.nickname = lcinfo.nickname;
bupdated = true;
}
if (lcinfo.city && (svinfo.city != lcinfo.city)) {
//console.log('[city]'+svinfo.city+"|"+lcinfo.city);
svinfo.city = lcinfo.city;
bupdated = true;
}
if (lcinfo.province && (svinfo.province != lcinfo.province)) {
//console.log('[province]'+svinfo.province+"|"+lcinfo.province);
svinfo.province = lcinfo.province;
bupdated = true;
}
if (lcinfo.country && (svinfo.country != lcinfo.country)) {
//console.log('[country]'+svinfo.country+"|"+lcinfo.country);
svinfo.country = lcinfo.country;
bupdated = true;
}
if (lcinfo.avatar_url && (svinfo.avatar_url != lcinfo.avatar_url)) {
//console.log('[avatar_url]'+svinfo.avatar_url+"|"+lcinfo.avatar_url);
svinfo.avatar_url = lcinfo.avatar_url;
bupdated = true;
}
if (lcinfo.sex && (svinfo.sex != lcinfo.sex)) {
//console.log('[sex]'+svinfo.sex+"|"+lcinfo.sex);
svinfo.sex = lcinfo.sex;
bupdated = true;
}
if (lcinfo.birthday && (svinfo.birthday != lcinfo.birthday)) {
//console.log('[birthday]'+svinfo.birthday+"|"+lcinfo.birthday);
svinfo.birthday = lcinfo.birthday;
bupdated = true;
}
if (lcinfo.phone && (svinfo.phone != lcinfo.phone)) {
//console.log('[phone]'+svinfo.phone+"|"+lcinfo.phone);
svinfo.phone = lcinfo.phone;
bupdated = true;
}
if (lcinfo.location && (svinfo.location != lcinfo.location)) {
//console.log('[location]'+svinfo.location+"|"+lcinfo.location);
svinfo.location = lcinfo.location;
bupdated = true;
}
return bupdated;
},
init(channelid, gameid, isoffical, owner, env, url) {
this.owner = owner;
this.channelid = channelid;
this.gameid = gameid;
this.sessionid = this.sessionid ? this.sessionid : '';
this.accountid = this.accountid ? this.accountid : '';
this.openid = this.openid ? this.openid : '';
this.env = env;
this.isoffical = isoffical;
this.logined = this.logined ? this.logined : false;
this.urlbd = new urlbuilder(url);
console.log("[jclogin]init:" + gameid + "|" + channelid + "|" + isoffical);
},
login(token, successcb, failcb, openid) {
var self = this;
this.__login(this.channelid, this.gameid, token, this.isoffical, function (obj) {
let nowtime = new Date().getTime();
self.sessionid = obj.session_id;
self.accountid = obj.account_id;
self.openid = obj.openid;
self.actived = !!obj.activated;
self.logined = true;
self.login_costtime = nowtime - self._loginstarttime;
self._loadServerInfo(obj);
self._checkUserInfo();
successcb && successcb(obj);
}, failcb, openid);
},
// 登陆平台
loginPT(successcb, failcb, exparam) {
this._loginstarttime = new Date().getTime();
switch (this.channelid) {
case 6000: {
this.login(this.localid, successcb, failcb);
} break;
case 6001: {
this.loginwx(successcb, failcb);
} break;
case 6002: {
//
let self = this;
let openId = BK.getSystemInfoSync().openId;
//console.log("loginQQ openid:"+openId);
// BK.Script.loadlib("GameRes://qqPlayCore.js") //预加载bricks js层接口
BK.QQ.fetchOpenKey(function (errCode, cmd, data) {
if (errCode == 0) {
let openKey = data.openKey;
//console.log("loginQQ openKey:"+openKey);
self.login(openKey, successcb, failcb, openId);
}
});
} break;
case 6003: {
//console.log('[qg.login]BEGIN:' + exparam);
if (typeof (qg) != 'undefined') {
qg.login({
pkgName: exparam,
success: (res) => {
//console.log('[qg.login]success');
//console.log(JSON.stringify(res));
this.login(res.token, successcb, failcb, res.uid);
this.updateuserinfo(res);
},
fail: (res) => {
//console.log('[qg.login]fail');
//console.log(JSON.stringify(res));
failcb && failcb();
}
});
}
} break;
case 6004: {
var self = this;
var vivoGetUserInfo = function (vivotoken) {
qg.getProfile({
token: vivotoken,
success: function (data) {
//console.log('[vivo.login]success');
self.login(vivotoken, successcb, failcb, data.openid);
self.updateuserinfo(data);
},
fail: function (data, code) {
//console.log('[vivo.login]fail');
failcb && failcb();
}
})
};
qg.authorize({
type: "token",
success: function (data) {
//console.log("vivoAuthorize success");
vivoGetUserInfo(data.accessToken);
},
fail: function (data, code) {
//console.log("vivoAuthorize fail");
failcb && failcb();
}
});
} break;
case 6501: {
var self = this;
FBInstant.player.getSignedPlayerInfoAsync('my_metadata')
.then(function (result) {
self.login(result.getSignature(), successcb, failcb, result.getPlayerID());
});
var userinfo = {
nick: FBInstant.player.getName(),
avatar: FBInstant.player.getPhoto(),
}
this.updateuserinfo(userinfo);
} break;
case 7001:
case 7002:
case 7101: {
this.login(exparam, successcb, failcb);
} break;
}
},
// 更新用户信息
updatePTInfo(userinfo, tokeninfo, successcb, failcb) {
this.updateuserinfo(userinfo, tokeninfo, successcb, failcb);
},
// 登陆微信
loginwx(successcb, failcb) {
// let wx = wx || {};
if (wx.login) {
var self = this;
wx.login({
success: function (res) {
//console.log("[wx]login success!" + res.code);
self.login(res.code, successcb, failcb);
},
fail: function (res) {
//console.log("[wx]login fail!");
failcb && failcb(0, res.errcode, res.errmsg);
},
});
} else {
failcb && failcb(-1, 0, "not weixin platform!");
}
},
// 登陆游密
loginYoume(successcb, failcb) {
this.__loginYoume(this.accountid, this.sessionid, this.nickname, successcb, failcb);
},
// 登陆金蚕
loginJC(id, pwd, type, successcb, failcb) {
if (type == 0) {
this.__loginJCByID(id, pwd, successcb, failcb);
} else {
this.__loginJCBySMS(id, pwd, successcb, failcb);
}
},
// 注册金蚕
registerJC(phone, smscode, pwd, successcb, failcb) {
this.__registerJCAccount(phone, pwd, phone, smscode, successcb, failcb);
},
// 获取用户信息后调用此方法激活账号info为空说明授权失败
updateuserinfo(userinfo, tokeninfo, successcb, failcb) {
this._loadLocalInfo(userinfo);
this._loadTokenInfo(tokeninfo);
this._activesuccess = successcb;
this._activefail = failcb;
this._checkUserInfo();
this._checkNickName();
},
activewx(res, successcb, failcb) {
var self = this;
this.__activeWX(this.gameid, this.accountid, this.sessionid, res.rawData, res.signature, res.encryptedData, res.iv, function (obj) {
self.actived = true;
successcb && successcb(obj);
}, failcb);
},
updateinfo(usrinfo, successcb, failcb) {
this.__updateInfo(this.accountid, this.sessionid, usrinfo, successcb, failcb);
},
getToken(sceneid, successcb, failcb) {
this.__generalToken(this.accountid, this.sessionid, sceneid, successcb, failcb);
},
getSignature(signdata, successcb, failcb) {
this.__generalSignature(this.accountid, this.sessionid, signdata, successcb, failcb);
},
getAnnouncement(successcb, failcb) {
this.__getAnnouncement(this.channelid, this.gameid, successcb, failcb);
},
getServerList(successcb, failcb) {
this.__getServerList(this.channelid, this.gameid, successcb, failcb);
},
isActived() {
return this.actived;
},
AccountID(openid) {
if (this.accountid && this.accountid != '') {
return this.accountid;
}
return this.channelid + "_" + this.gameid + "_" + openid;
},
setAccountID(accountid, sessionid) {
this.accountid = accountid;
this.sessionid = sessionid;
},
setNickName(nickname) {
this.nickname = nickname;
},
setFromAppID(appid) {
this.fromid = appid;
},
setLocalUUID(uuid) {
this.localid = uuid;
},
setSystemInfo(info) {
},
appendUserInfo(dstinfo, srcinfo) {
if (!dstinfo) {
return false;
}
if (!srcinfo) {
dstinfo.nickname = '';
dstinfo.country = '';
dstinfo.province = '';
dstinfo.city = '';
dstinfo.avatar_url = '';
dstinfo.sex = 0;
dstinfo.birthday = '';
dstinfo.phone = '';
dstinfo.location = '';
} else {
for (var attr in srcinfo) {
dstinfo[attr] = srcinfo[attr];
}
}
},
};

View File

@ -0,0 +1,226 @@
import httpclient from '../common/httpclient'
import urlbuilder from '../common/urlbuilder'
import storage from '../common/storage'
const JC_NOTIFY_MSG_KEY = 'jc_notify_msg';
export default {
// LIFE-CYCLE CALLBACKS:
// onLoad () {},
// start () {},
// update (dt) {},
__getMsglist(successcb, failcb){
return;
this.urlbd.clear();
this.urlbd.addKV('c', 'MsgQueue')
.addKV('a', 'getMsgList')
.addKV('session_id', this.sessionid)
.addKV('account_id', this.accountid)
.addKV('sid', this.sid)
.addKV('wid', this.wid)
.addKV('ptid', this.ptid)
;
httpclient.httpGet(this.urlbd.baseurl, (restext) => {
//console.log('[__getMsglist]result:');
////console.log(restext);
var obj = httpclient.JSON_parse(restext);
if(obj.errcode == 0){
//console.log('[__getMsglist]success!'+JSON.stringify(obj));
//var msglst = httpclient.JSON_parse(obj.msglist);
var msglst = obj.msglist;
if(msglst){
successcb && successcb(msglst);
}else{
failcb && failcb(0, -1, "msglst is not obj");
}
}else{
//console.log('[__getMsglist]failed!'+obj.errcode+":"+obj.errmsg);
failcb && failcb(0, obj.errcode, obj.errmsg);
}
}, (errcode, errmsg) => {
//console.log('[__getMsglist]failed!'+errcode+":"+errmsg);
failcb && failcb(errcode, 0, errmsg);
});
},
__markMsgs(msgidlst){
let smsgs = (msgidlst instanceof Array)? msgidlst.join(): msgidlst;
this.urlbd.clear();
this.urlbd.addKV('c', 'MsgQueue')
.addKV('a', 'markMsg')
.addKV('session_id', this.sessionid)
.addKV('account_id', this.accountid)
.addKV('sid', this.sid)
.addKV('wid', this.wid)
.addKV('ptid', this.ptid)
.addKV('msg_ids', smsgs);
httpclient.httpGet(this.urlbd.baseurl, (res) => {
if(!this.isoffical){
//console.log('[__markMsgs]'+res);
}
}, (err, errmsg) => {
if(!this.isoffical){
//console.log('[__markMsgs]Err:'+err+'|'+errmsg);
}
});
},
init(channelid, gameid, isoffical, owner, url){
this.owner = owner;
this.gameid = gameid;
this.channelid = channelid;
this.isoffical = isoffical;
this.urlbd = new urlbuilder(url);
this.initMsglist();
//console.log("[jcnotify]init:"+gameid + "|" + channelid + "|" + isoffical);
},
setAccountID(accountid, sessionid, exobj){
this.accountid = accountid;
this.sessionid = sessionid;
if(exobj){
this.wid = exobj.wid;
this.sid = exobj.sid;
this.ptid = exobj.ptid;
}
this.getMsglist();
},
setNickName(nickname){
this.nickname = nickname;
},
setFromAppID(appid){
this.fromid = appid;
},
setLocalUUID(uuid){
this.localid = uuid;
},
setSystemInfo(info){
},
setServerTime(servertime, localtime){
this.loginSrvTime = servertime;
this.loginLocalTime = localtime;
},
getMsglist(){
this.__getMsglist((res) => {
let idlst = [];
res.forEach(element => {
let obj = this.msglist.find((item) => {
return item.id == element.msg_id;
});
if(!obj){
obj = {
id: element.msg_id,
type: element.msg_type,
content: element.content,
name: element.msg_name,
sendtime: element.sendtime,
expiretime: element.expiretime? element.expiretime: element.sendtime+24*3600000
};
this.msglist.push(obj);
}else{
obj.type = element.msg_type;
obj.content = element.content;
obj.name = element.msg_name;
obj.sendtime = element.sendtime;
obj.expiretime = element.expiretime? element.expiretime: element.sendtime+24*3600000;
}
idlst.push(element.msg_id);
});
if(idlst.length > 0){
//this.__markMsgs(idlst);
this._checkMsglist();
}
this._reqMsglist(false);
}, () => {
this._reqMsglist(true);
});
},
initMsglist(){
if(!this.msglist){
this.msglist = [];
}else{
this.msglist.length = 0;
}
let obj = storage.getjson(JC_NOTIFY_MSG_KEY);
if(obj){
this.msglist = this.msglist.concat(obj);
}
this._lastidx = this.msglist.length > 0? 0: -1;
},
resetMsglist(){
storage.remove(JC_NOTIFY_MSG_KEY);
this.msglist.length = 0;
this.getMsglist();
},
_reqMsglist(breload){
let dt = breload? 10000: 600000;
setTimeout(() => {
this.getMsglist();
}, dt);
},
_checkMsglist(){
let tm = this._getServerNowTime();
let i = this.msglist.length;
while(i--){
let obj = this.msglist[i];
if(this._isExpire(obj, tm)){
this.msglist.splice(i, 1);
}
}
this.msglist.sort((a, b) => {
return a.sendtime > b.sendtime;
});
this._handleMsglist(this.msglist, this);
storage.setjson(JC_NOTIFY_MSG_KEY, this.msglist);
},
_getServerNowTime(){
if(this.owner){
return this.owner.getServerNowTime();
}else{
let tm = new Date().getTime();
return this.loginSrvTime + (tm - this.loginLocalTime) / 1000;
}
},
_isExpire(msg, nowtime){
return msg.expiretime < nowtime;
},
getOneMsg(){
if(!this.msglist){
return '';
}
if(this._lastidx >= this.msglist.length){
this._lastidx = this.msglist.length > 0? 0: -1;
}
if(this._lastidx < this.msglist.length && this._lastidx >= 0){
let obj = this.msglist[this._lastidx];
this._lastidx++;
return obj.content;
}
return '';
},
_handleMsglist(lst, owner){
this.owner && this.owner._handleNotifyMsgs && this.owner._handleNotifyMsgs(lst, owner);
}
};

View File

@ -0,0 +1,547 @@
import httpclient from '../common/httpclient'
import urlbuilder from '../common/urlbuilder'
export default {
// LIFE-CYCLE CALLBACKS:
// onLoad () {},
// start () {},
// update (dt) {},
init(channelid, gameid, isoffical, owner, url) {
this.owner = owner;
this.gameid = gameid;
this.channelid = channelid;
this.urlbd = new urlbuilder(url);
//console.log("[jcshare]init:"+gameid + "|" + channelid + "|" + isoffical);
},
setAccountID(accountid, sessionid) {
this.accountid = accountid;
this.sessionid = sessionid;
},
setNickName(nickname) {
this.nickname = nickname;
},
setFromAppID(appid) {
this.fromid = appid;
},
setLocalUUID(uuid) {
this.localid = uuid;
},
setSystemInfo(info) {
},
setUserInfo(info) {
this.sex = info.sex;
this.avatar_url = info.avatar_url;
},
/**
* 接受邀请分级时用大部分时候不用此接口
* @param {string} actionid 业务号
* @param {string} inviterid 邀请方账号id
* @param {object} successcb 成功回调以下该名称都是此功能
* @param {object} failcb 失败回调以下该名称都是此功能
*/
acceptInvite(actionid, inviterid, successcb, failcb) {
if (!actionid) {
return;
}
let sid = inviterid ? inviterid : '';
this.urlbd.clear();
this.urlbd.addKV('c', 'Fission')
.addKV('a', 'accept')
.addKV('session_id', this.sessionid)
.addKV('account_id', this.accountid)
.addKV('business_no', actionid)
.addKV('inviter_id', sid)
.addKV('nickname', this.nickname)
.addKV('sex', this.sex)
.addKV('avatar_url', this.avatar_url)
;
httpclient.httpGet(this.urlbd.baseurl, function (restext) {
var obj = JSON.parse(restext);
if (obj.errcode == 0 || obj.errcode == 1 || obj.errcode == 2) {
//console.log('[acceptInvite]success!'+JSON.stringify(obj));
successcb && successcb();
} else {
//console.log('[acceptInvite]failed!'+obj.errcode+":"+obj.errmsg);
failcb && failcb(0, obj.errcode, obj.errmsg);
}
}, function (errcode, errmsg) {
//console.log('[acceptInvite]failed!'+errcode+":"+errmsg);
failcb && failcb(errcode, 0, errmsg);
});
},
/**
* 查询子节点数据分级时用大部分时候不用此接口
* @param {string} actionid 业务号
* @param {object} successcb
* @param {object} failcb
*/
queryShareStat(actionid, successcb, failcb) {
this.urlbd.clear();
this.urlbd.addKV('c', 'Fission')
.addKV('a', 'getChild')
.addKV('session_id', this.sessionid)
.addKV('account_id', this.accountid)
.addKV('business_no', actionid);
httpclient.httpGet(this.urlbd.baseurl, function (restext) {
var obj = JSON.parse(restext);
if (obj.errcode == 0) {
//console.log('[queryShareStat]success!'+JSON.stringify(obj));
successcb && successcb(obj.nodes);
} else {
//console.log('[queryShareStat]failed!'+obj.errcode+":"+obj.errmsg);
failcb && failcb(0, obj.errcode, obj.errmsg);
}
}, function (errcode, errmsg) {
//console.log('[queryShareStat]failed!'+errcode+":"+errmsg);
failcb && failcb(errcode, 0, errmsg);
});
},
/**
* 查询接受邀请人的详细信息分级时用大部分时候不用此接口
* @param {string} actionid 业务号
* @param {object} successcb
* @param {object} failcb
*/
queryShareDetail(actionid, successcb, failcb) {
this.urlbd.clear();
this.urlbd.addKV('c', 'Fission')
.addKV('a', 'getFriendsDetail')
.addKV('session_id', this.sessionid)
.addKV('account_id', this.accountid)
.addKV('business_no', actionid);
httpclient.httpGet(this.urlbd.baseurl, function (restext) {
var obj = JSON.parse(restext);
if (obj.errcode == 0) {
//console.log('[queryShareDetail]success!'+JSON.stringify(obj));
successcb && successcb(obj.nodes);
} else {
//console.log('[queryShareDetail]failed!'+obj.errcode+":"+obj.errmsg);
failcb && failcb(0, obj.errcode, obj.errmsg);
}
}, function (errcode, errmsg) {
//console.log('[queryShareDetail]failed!'+errcode+":"+errmsg);
failcb && failcb(errcode, 0, errmsg);
});
},
/**
* 每日任务的接受邀请使用jcfw的话无需主动调用
* @param {string} actionid 任务id
* @param {string} inviterid 邀请方账号id
* @param {object} successcb
* @param {object} failcb
*/
acceptDailyInvite(actionid, inviterid, successcb, failcb) {
let sid = inviterid ? inviterid : '';
this.urlbd.clear();
this.urlbd.addKV('c', 'DailyMission')
.addKV('a', 'acceptInvite')
.addKV('session_id', this.sessionid)
.addKV('account_id', this.accountid)
.addKV('inviter_id', sid)
.addKV('activity_param', actionid)
.addKV('nickname', this.nickname)
.addKV('sex', this.sex)
.addKV('avatar_url', this.avatar_url)
;
httpclient.httpGet(this.urlbd.baseurl, function (restext) {
var obj = JSON.parse(restext);
if (obj.errcode == 0 || obj.errcode == 1) {
//console.log('[acceptDailyInvite]success!'+JSON.stringify(obj));
successcb && successcb();
} else {
//console.log('[acceptDailyInvite]failed!'+obj.errcode+":"+obj.errmsg);
failcb && failcb(0, obj.errcode, obj.errmsg);
}
}, function (errcode, errmsg) {
//console.log('[acceptDailyInvite]failed!'+errcode+":"+errmsg);
failcb && failcb(errcode, 0, errmsg);
});
},
/**
* 每日任务的查询接受邀请的人数
* @param {string} actionid 业务号
* @param {object} successcb
* @param {object} failcb
*/
queryDailyShareStat(actionid, successcb, failcb) {
this.urlbd.clear();
this.urlbd.addKV('c', 'DailyMission')
.addKV('a', 'getInviteeNum')
.addKV('session_id', this.sessionid)
.addKV('account_id', this.accountid)
.addKV('activity_param', actionid);
httpclient.httpGet(this.urlbd.baseurl, function (restext) {
var obj = JSON.parse(restext);
if (obj.errcode == 0) {
//console.log('[queryDailyShareStat]success!'+JSON.stringify(obj));
successcb && successcb(obj);
} else {
//console.log('[queryDailyShareStat]failed!'+obj.errcode+":"+obj.errmsg);
failcb && failcb(0, obj.errcode, obj.errmsg);
}
}, function (errcode, errmsg) {
//console.log('[queryDailyShareStat]failed!'+errcode+":"+errmsg);
failcb && failcb(errcode, 0, errmsg);
});
},
/**
* 每日任务的查询接受邀请人的详细信息
* @param {string} actionid 业务号
* @param {object} successcb
* @param {object} failcb
*/
queryDailyShareDetail(actionid, successcb, failcb) {
this.urlbd.clear();
this.urlbd.addKV('c', 'DailyMission')
.addKV('a', 'getInviteeList')
.addKV('session_id', this.sessionid)
.addKV('account_id', this.accountid)
.addKV('activity_param', actionid);
httpclient.httpGet(this.urlbd.baseurl, function (restext) {
var obj = JSON.parse(restext);
if (obj.errcode == 0) {
//console.log('[queryDailyShareDetail]success!'+JSON.stringify(obj));
successcb && successcb(obj.invitee_list);
} else {
//console.log('[queryDailyShareDetail]failed!'+obj.errcode+":"+obj.errmsg);
failcb && failcb(0, obj.errcode, obj.errmsg);
}
}, function (errcode, errmsg) {
//console.log('[queryDailyShareDetail]failed!'+errcode+":"+errmsg);
failcb && failcb(errcode, 0, errmsg);
});
},
/**
* 上报游戏分数获取兑换码
* @param {string} score 分数
* @param {object} successcb
* @param {object} failcb
*/
queryActionCode(score, successcb, failcb) {
this.urlbd.clear();
this.urlbd.addKV('c', 'Exchange')
.addKV('a', 'reportScore')
.addKV('session_id', this.sessionid)
.addKV('account_id', this.accountid)
.addKV('score', score);
httpclient.httpGet(this.urlbd.baseurl, function (restext) {
var obj = JSON.parse(restext);
if (obj.errcode == 0) {
//console.log('[queryActionCode]success!'+JSON.stringify(obj));
successcb && successcb(obj.exchange_code);
} else {
//console.log('[queryActionCode]failed!'+obj.errcode+":"+obj.errmsg);
failcb && failcb(0, obj.errcode, obj.errmsg);
}
}, function (errcode, errmsg) {
//console.log('[queryActionCode]failed!'+errcode+":"+errmsg);
failcb && failcb(errcode, 0, errmsg);
});
},
/**
* 接力活动的接受邀请
* @param {string} actionid 任务id
* @param {string} inviterid 邀请方账号id
* @param {object} successcb
* @param {object} failcb
*/
acceptRelayInvite(actionid, inviterid, successcb, failcb) {
let sid = inviterid ? inviterid : '';
this.urlbd.clear();
this.urlbd.addKV('c', 'Relay')
.addKV('a', 'acceptInvite')
.addKV('session_id', this.sessionid)
.addKV('account_id', this.accountid)
.addKV('inviter_id', sid)
.addKV('activity_param', actionid)
.addKV('nickname', this.nickname)
.addKV('sex', this.sex)
.addKV('avatar_url', this.avatar_url)
;
httpclient.httpGet(this.urlbd.baseurl, function (restext) {
var obj = JSON.parse(restext);
if (obj.errcode == 0 || obj.errcode == 1) {
//console.log('[acceptRelayInvite]success!'+JSON.stringify(obj));
successcb && successcb();
} else {
//console.log('[acceptRelayInvite]failed!'+obj.errcode+":"+obj.errmsg);
failcb && failcb(0, obj.errcode, obj.errmsg);
}
}, function (errcode, errmsg) {
//console.log('[acceptRelayInvite]failed!'+errcode+":"+errmsg);
failcb && failcb(errcode, 0, errmsg);
});
},
/**
* 接力活动的查询接受邀请的人数
* @param {string} actionid 业务号
* @param {object} successcb
* @param {object} failcb
*/
queryRelayShareStat(actionid, successcb, failcb) {
this.urlbd.clear();
this.urlbd.addKV('c', 'Relay')
.addKV('a', 'getInviteeNum')
.addKV('session_id', this.sessionid)
.addKV('account_id', this.accountid)
.addKV('activity_param', actionid);
httpclient.httpGet(this.urlbd.baseurl, function (restext) {
var obj = JSON.parse(restext);
if (obj.errcode == 0) {
//console.log('[queryRelayShareStat]success!'+JSON.stringify(obj));
successcb && successcb(obj);
} else {
//console.log('[queryRelayShareStat]failed!'+obj.errcode+":"+obj.errmsg);
failcb && failcb(0, obj.errcode, obj.errmsg);
}
}, function (errcode, errmsg) {
//console.log('[queryRelayShareStat]failed!'+errcode+":"+errmsg);
failcb && failcb(errcode, 0, errmsg);
});
},
/**
* 成就的接受邀请
* @param {Array} relationidlst 有关联的成就id列表格式如下[[1001,3], [1002,3], [1003,3]]
* @param {string} inviterid 邀请方账号id
* @param {object} successcb
* @param {object} failcb
*/
acceptAchivementInvite(relationidlst, inviterid, successcb, failcb) {
let sid = inviterid ? inviterid : '';
this.urlbd.clear();
this.urlbd.addKV('c', 'AchievementShare')
.addKV('a', 'acceptInvite')
.addKV('session_id', this.sessionid)
.addKV('account_id', this.accountid)
.addKV('inviter_id', sid)
.addKV('relate_achivements', JSON.stringify(relationidlst))
.addKV('nickname', this.nickname)
.addKV('sex', this.sex)
.addKV('avatar_url', this.avatar_url)
;
httpclient.httpGet(this.urlbd.baseurl, function (restext) {
var obj = JSON.parse(restext);
if (obj.errcode == 0 || obj.errcode == 1) {
//console.log('[acceptAchivementInvite]success!'+JSON.stringify(obj));
successcb && successcb();
} else {
//console.log('[acceptAchivementInvite]failed!'+obj.errcode+":"+obj.errmsg);
failcb && failcb(0, obj.errcode, obj.errmsg);
}
}, function (errcode, errmsg) {
//console.log('[acceptAchivementInvite]failed!'+errcode+":"+errmsg);
failcb && failcb(errcode, 0, errmsg);
});
},
/**
* 成就的查询接受邀请的人数
* @param {Array} actionidlst 成就id列表格式如下[1001,1002,1003]
* @param {object} successcb
* @param {object} failcb
*/
queryAchievementShareStat(actionidlst, successcb, failcb) {
this.urlbd.clear();
this.urlbd.addKV('c', 'AchievementShare')
.addKV('a', 'getInviteeNum')
.addKV('session_id', this.sessionid)
.addKV('account_id', this.accountid)
.addKV('achievement_ids', actionidlst.join());
httpclient.httpGet(this.urlbd.baseurl, function (restext) {
var obj = JSON.parse(restext);
if (obj.errcode == 0) {
//console.log('[queryAchievementShareStat]success!'+JSON.stringify(obj));
successcb && successcb(obj);
} else {
//console.log('[queryAchievementShareStat]failed!'+obj.errcode+":"+obj.errmsg);
failcb && failcb(0, obj.errcode, obj.errmsg);
}
}, function (errcode, errmsg) {
//console.log('[queryAchievementShareStat]failed!'+errcode+":"+errmsg);
failcb && failcb(errcode, 0, errmsg);
});
},
/**
* 成就的查询接受邀请的详细信息
* @param {Array} actionidlst 成就id列表格式如下[1001,1002,1003]
* @param {object} successcb
* @param {object} failcb
*/
queryAchievementShareDetail(actionidlst, successcb, failcb) {
this.urlbd.clear();
this.urlbd.addKV('c', 'AchievementShare')
.addKV('a', 'getInviteeList')
.addKV('session_id', this.sessionid)
.addKV('account_id', this.accountid)
.addKV('achievement_ids', actionidlst.join());
httpclient.httpGet(this.urlbd.baseurl, function (restext) {
var obj = JSON.parse(restext);
if (obj && obj.errcode == 0) {
//console.log('[queryAchievementShareDetail]success!'+JSON.stringify(obj));
successcb && successcb(obj.invitee_list);
} else {
//console.log('[queryAchievementShareDetail]failed!'+obj.errcode+":"+obj.errmsg);
failcb && failcb(0, obj.errcode, obj.errmsg);
}
}, function (errcode, errmsg) {
//console.log('[queryAchievementShareDetail]failed!'+errcode+":"+errmsg);
failcb && failcb(errcode, 0, errmsg);
});
},
/**
* 普通分享
* @param {string} content 分享显示的标题
* @param {string} imgurl 分享显示的图片
* @param {int} sharetype 分享类型每日活动/成就/接力
* @param {string} shareparam 分享类型相关参数活动id/成就id等
* @param {string} extrainfo 分享额外参数key/value格式的字符串eg: 'inviter_name=***&inviter_sex=***'
* @param {object} successcb
* @param {object} failcb
*/
shareNormal(content, imgurl, sharetype, shareparam, extrainfo, successcb, failcb) {
let uuid = this.owner ? this.owner.makeUUID() : '';
let qstr = 'inviter_id=' + this.accountid + '&activity_param='
+ shareparam + '&localuuid=' + uuid + '&sharetype=' + sharetype;
if (extrainfo) {
qstr += '&';
qstr += extrainfo;
}
switch (this.channelid) {
case 6001: {
wx.shareAppMessage({
title: content,
imageUrl: imgurl,
query: qstr
});
this.owner && this.owner.gamelog.logShare(sharetype, uuid, shareparam);
successcb && successcb();
}
break;
case 6002: {
}
break;
}
}
,
shareCapture(content, rc, sharetype, shareparam, extrainfo, successcb, failcb) {
let uuid = this.owner ? this.owner.makeUUID() : '';
let qstr = 'inviter_id=' + this.accountid + '&activity_param='
+ shareparam + '&localuuid=' + uuid + '&sharetype=' + sharetype;
if (extrainfo) {
qstr += '&';
qstr += extrainfo;
}
switch (this.channelid) {
case 6001: {
let surl = canvas.toTempFilePathSync({
x: rc.x,
y: rc.y,
width: rc.width,
height: rc.height,
destWidth: 500,
destHeight: 400
});
wx.shareAppMessage({
title: content,
imageUrl: surl,
query: qstr
});
this.owner && this.owner.gamelog.logShare(sharetype, uuid, shareparam);
successcb && successcb();
}
break;
case 6002: {
}
break;
}
},
acceptAchievementInvite(inviter_id, achievement_id, relate_achivements) {
this.urlbd.clear();
this.urlbd.addKV('c', 'AchievementShare')
.addKV('a', 'acceptInvite')
.addKV('account_id', this.accountid)
.addKV('session_id', this.sessionid)
.addKV('inviter_id', inviter_id);
if (relate_achivements) {
this.urlbd.addKV('relate_achivements', relate_achivements);
} else {
this.urlbd.addKV('achievement_id', Number(achievement_id));
}
//console.log(this.urlbd.baseurl);
httpclient.httpGet(this.urlbd.baseurl, function (restext) {
var obj = JSON.parse(restext);
if (obj.errcode == 0) {
//console.log('[acceptAchievementInvite]success!'+JSON.stringify(obj));
} else {
//console.log('[acceptAchievementInvite]failed!'+obj.errcode+":"+obj.errmsg);
}
}, function (errcode, errmsg) {
//console.log('[acceptAchievementInvite]failed!'+errcode+":"+errmsg);
});
},
getAchievInviteeNum(successcb, failcb) {
this.urlbd.clear();
this.urlbd.addKV('c', 'AchievementShare')
.addKV('a', 'getInviteeNum')
.addKV('account_id', this.accountid)
.addKV('session_id', this.sessionid);
// .addKV('achievement_ids', achievement_ids)
httpclient.httpGet(this.urlbd.baseurl, function (restext) {
var obj = JSON.parse(restext);
if (obj.errcode == 0) {
//console.log('[getAchievInviteeNum]success!'+JSON.stringify(obj));
successcb && successcb(obj.invitee_nums);
} else {
//console.log('[getAchievInviteeNum]failed!'+obj.errcode+":"+obj.errmsg);
failcb && failcb(0, obj.errcode, obj.errmsg);
}
}, function (errcode, errmsg) {
//console.log('[getAchievInviteeNum]failed!'+errcode+":"+errmsg);
failcb && failcb(errcode, 0, errmsg);
});
}
}

View File

@ -0,0 +1,63 @@
import httpclient from '../common/httpclient'
import urlbuilder from '../common/urlbuilder'
export default {
// LIFE-CYCLE CALLBACKS:
// onLoad () {},
// start () {},
// update (dt) {},
_heart() {
this.urlbd.clear();
this.urlbd.addKV('c', 'Stat')
.addKV('a', 'updateSession')
.addKV('session_id', this.sessionid)
.addKV('account_id', this.accountid);
httpclient.httpGet(this.urlbd.baseurl, (res) => {
if (!this.isoffical) {
//console.log('[stat.heart]'+res);
}
}, (err, errmsg) => {
if (!this.isoffical) {
//console.log('[stat.heart]Err:'+err+'|'+errmsg);
}
});
},
init(channelid, gameid, isoffical, owner, url) {
this.owner = owner;
this.gameid = gameid;
this.channelid = channelid;
this.isoffical = isoffical;
this.urlbd = new urlbuilder(url);
//console.log("[jcstat]init:"+gameid + "|" + channelid + "|" + isoffical);
},
setAccountID(accountid, sessionid) {
this.accountid = accountid;
this.sessionid = sessionid;
this._heart();
setInterval(() => {
this._heart();
}, 300000);
},
setNickName(nickname) {
this.nickname = nickname;
},
setFromAppID(appid) {
this.fromid = appid;
},
setLocalUUID(uuid) {
this.localid = uuid;
},
setSystemInfo(info) {
},
};

BIN
static/images/qr-code.jpg Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 46 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 5.7 KiB

View File

Before

Width:  |  Height:  |  Size: 141 B

After

Width:  |  Height:  |  Size: 141 B

View File

Before

Width:  |  Height:  |  Size: 133 B

After

Width:  |  Height:  |  Size: 133 B