import { _decorator, error, Mask, SpriteFrame, sys, utils } from "cc"; import { gameManager } from "./run/gameManager"; import { config } from "./config"; import { statisticsManager } from "./statisticsManager"; import { tools } from "./tools"; //管理广告、分享、SDK相关内容的组件 export class SdkUtil { public static platform: string = 'cocos'; //平台 public static imgAd: SpriteFrame = null!; public static imgShare: SpriteFrame = null!; public static isDebugMode: boolean = false; public static onlineInterval: number = -1; public static isEnableVibrate: boolean = true; public static isCheckOffline: boolean = false; //登录后会检查是否展示登录界面,而且只检查一次 public static isWatchVideoAd: boolean = false;//是否正在播放广告 public static isEnableMoving: boolean = false;//是否允许屏幕上下移动 public static isEnableZoom: boolean = false;//是否允许屏幕缩放 public static arrLockDiary = [];//未解锁日记 public static vibrateInterval: number = 100;//两次震动之间的间隔,AppActivity里面的震动间隔也是100 public static vibratePreTime: number = 0;//上次震动时间 public static videoAd:any =null; public static isLookAd:boolean = false; //是否在看广告 public static gridGamePanel = null; //互推游戏组件 public static tt_systemInfo: any = null; //抖音_系统信息 public static wx_systemInfo:any = null; //微信_系统信息 public static ks_systemInfo:any = null; //ks_系统信息 private static tt_isSupportSidebar:boolean = false; //抖音_是否支持侧边栏 private static tt_isToEnterFromSidebar:boolean = false; //抖音_是否从侧边栏进入 private static tt_gameRecorder:any = null; //抖音游戏录制 private static tt_recordVideoPath:string = ''; //抖音录制视频路径 private static tt_totalRecord:number = 300; //抖音总录制时间 private static tt_isRecording:boolean = false; //抖音是否录制中 //------------------------------ 公共 ------------------------------// // 初始化(设置当前运行平台) public static init() { if(sys.platform==sys.Platform.BYTEDANCE_MINI_GAME) { tools.platform = config.Platform.TT } else if(sys.platform==sys.Platform.WECHAT_GAME) { let isKSGame = typeof KSGameGlobal != 'undefined' // console.log('isKSGame=',isKSGame) if(isKSGame) { tools.platform = config.Platform.KS } else { tools.platform = config.Platform.WX // 微信初始化设置显示分享弹窗,右上角'···'才可以转发给朋友,复制链接 wx.showShareMenu({ withShareTicket: true, menus: ['shareAppMessage', 'shareTimeline'] }) } } this.getSystemInfo(()=> { this.ttRegisterInfo() this.registerGridGamePanel() }) } // 获取平台标识 public static getPlatformIdentify():string { let identify = config.PLATFORM_IDENTIFY.BROWSER switch (tools.platform) { case config.Platform.TT: identify = config.PLATFORM_IDENTIFY.TT break; case config.Platform.WX: identify = config.PLATFORM_IDENTIFY.WX break; case config.Platform.KS: identify = config.PLATFORM_IDENTIFY.KS break; default: break; } return identify } // 获取系统信息 public static getSystemInfo(callback) { switch (tools.platform) { case config.Platform.TT: tt.getSystemInfo({ success:(res) => { console.log('tt.getSystemInfo=',res) // appName: "Douyin" appName: "douyin_lite" SdkUtil.tt_systemInfo = res callback && callback() } }) break; case config.Platform.WX: wx.getSystemInfo({ success:(res) => { console.log('wx.getSystemInfo=',res) SdkUtil.wx_systemInfo = res callback && callback() } }) break; case config.Platform.KS: ks.getSystemInfo({ success:(res) => { console.log('ks.getSystemInfo=',res) SdkUtil.ks_systemInfo = res callback && callback() } }) break; default: break; } } // 是否苹果平台 public static is_iphone_platform():boolean { if(SdkUtil.tt_systemInfo&&SdkUtil.tt_systemInfo.platform=='ios') { return true } if(SdkUtil.wx_systemInfo&&SdkUtil.wx_systemInfo.platform=='ios') { return true } if(SdkUtil.ks_systemInfo&&SdkUtil.ks_systemInfo.platform=='ios') { return true } return false } // 是否平台开发工具 public static is_devtools_platform():boolean { if(SdkUtil.tt_systemInfo&&SdkUtil.tt_systemInfo.platform=='devtools') { return true } if(SdkUtil.wx_systemInfo&&SdkUtil.wx_systemInfo.platform=='devtools') { return true } if(SdkUtil.ks_systemInfo&&SdkUtil.ks_systemInfo.platform=='devtools') { return true } return false } // 苹果手机是否有灵动岛 public static iPhoneIsLingdongdao():boolean { if(sys.platform==sys.Platform.BYTEDANCE_MINI_GAME) { if(SdkUtil.tt_systemInfo !=null) { if(SdkUtil.is_iphone_platform()||SdkUtil.tt_systemInfo.platform=='devtools') { if(SdkUtil.tt_systemInfo.model=='iPhone 14'|| SdkUtil.tt_systemInfo.model=='iPhone 14 Pro'|| SdkUtil.tt_systemInfo.model=='iPhone 14 Pro Max'|| SdkUtil.tt_systemInfo.model=='iPhone 15'|| SdkUtil.tt_systemInfo.model=='iPhone 15 Pro'|| SdkUtil.tt_systemInfo.model=='iPhone 15 Pro Max') { return true } } } } return false } // 自定义事件统计 public static customEventStatistics(eventType: string, objParams?: any) { eventType = eventType.toString(); if (!objParams) { objParams = {}; } // console.log({'eventType': eventType},{'objParams': objParams}); if (this.platform === 'wx') { //@ts-ignore if (window['wx'] && window['wx']['aldSendEvent']) { //@ts-ignore window.wx['aldSendEvent'](eventType, objParams); } } //@ts-ignore if (this.platform === 'cocos' && window.cocosAnalytics && window.cocosAnalytics.isInited()) { console.log("###统计", eventType, objParams); //@ts-ignore window.cocosAnalytics.CACustomEvent.onStarted(eventType, objParams); } } // 登录 public static login(call){ switch (tools.platform) { case config.Platform.TT: tt.login({ force: true, success(res) { console.log(`tt_login 调用成功:${res.code} ${res.anonymousCode}`); call({"code":res.code,"anonymousCode":res.anonymousCode}) }, fail(err) { console.log(`tt_login 调用失败:${err}`); // call(null) }, }); break; case config.Platform.WX: wx.login({ success(res) { console.log(`wx_login 调用成功:${res.code}`); call({"code":res.code}) }, fali(err) { console.log(`wx_login 调用失败:${err}`); // call(null) } }) break; case config.Platform.KS: ks.login({ success(res) { console.log(`ks_login 调用成功:${res.code}`); call({"code":res.code}) }, fali(err) { console.log(`ks_login 调用失败:${err}`); // call(null) } }) break; default: call(null) break; } } // 展示loading public static showLoading(title='加载中...',mask=false) { switch (tools.platform) { case config.Platform.TT: tt.showLoading({ title: title, mask:mask }) break; case config.Platform.WX: wx.showLoading({ title: title, mask:mask }) break; case config.Platform.KS: ks.showLoading({ title: title, mask:mask }) break; default: break; } } // 隐藏loading public static hideLoading() { switch (tools.platform) { case config.Platform.TT: tt.hideLoading() break; case config.Platform.WX: wx.hideLoading() break; case config.Platform.KS: ks.hideLoading() break; default: break; } } // 检测显示添加桌面 public static checkIsShowAddDesktop():boolean { if(sys.platform == sys.Platform.BYTEDANCE_MINI_GAME) { if(SdkUtil.tt_systemInfo.appName=='Douyin' || SdkUtil.tt_systemInfo.appName=='douyin_lite') { return true } } return false } // 分享游戏 public static shareGame(title: string, imageUrl: string, videoPath: string) { switch (tools.platform) { case config.Platform.TT: if(videoPath!="") { this.ttShareScreenRecordVideo(config.gameName,videoPath) } break; case config.Platform.WX: title = title + '好刺激、好好玩' this.wxShare(title, imageUrl) break; case config.Platform.KS: title = title + '好刺激、好好玩' this.ksShare(title, imageUrl) break; default: break; } } // 获取广告id public static getAdId(ad_type = config.AD_TYPE.UNKNOWN):string { let ad_id = "" switch (tools.platform) { case config.Platform.TT: if(ad_type == config.AD_TYPE.RE_LIFE) { ad_id = config.TT_REWARD.RE_LIFE } else if (ad_type == config.AD_TYPE.ANSWER) { ad_id = config.TT_REWARD.ANSWER } else if (ad_type == config.AD_TYPE.LOOK_TIPS) { ad_id = config.TT_REWARD.LOOK_TIPS } else if (ad_type == config.AD_TYPE.UN_LOCK_24) { ad_id = config.TT_REWARD.UN_LOCK_24 } else if (ad_type == config.AD_TYPE.UN_LOCK) { ad_id = config.TT_REWARD.UN_LOCK } else if (ad_type == config.AD_TYPE.ADD_TIME) { ad_id = config.TT_REWARD.ADD_TIME } break; case config.Platform.WX: if(ad_type == config.AD_TYPE.RE_LIFE) { ad_id = config.WX_REWARD.RE_LIFE } else if (ad_type == config.AD_TYPE.ANSWER) { ad_id = config.WX_REWARD.ANSWER } else if (ad_type == config.AD_TYPE.LOOK_TIPS) { ad_id = config.WX_REWARD.LOOK_TIPS } else if (ad_type == config.AD_TYPE.UN_LOCK_24) { ad_id = config.WX_REWARD.UN_LOCK_24 } else if (ad_type == config.AD_TYPE.UN_LOCK) { ad_id = config.WX_REWARD.UN_LOCK } else if (ad_type == config.AD_TYPE.ADD_TIME) { ad_id = config.WX_REWARD.ADD_TIME } break; case config.Platform.KS: if(ad_type == config.AD_TYPE.RE_LIFE) { ad_id = config.KS_REWARD.RE_LIFE } else if (ad_type == config.AD_TYPE.ANSWER) { ad_id = config.KS_REWARD.ANSWER } else if (ad_type == config.AD_TYPE.LOOK_TIPS) { ad_id = config.KS_REWARD.LOOK_TIPS } else if (ad_type == config.AD_TYPE.UN_LOCK_24) { ad_id = config.KS_REWARD.UN_LOCK_24 } else if (ad_type == config.AD_TYPE.UN_LOCK) { ad_id = config.KS_REWARD.UN_LOCK } else if (ad_type == config.AD_TYPE.ADD_TIME) { ad_id = config.KS_REWARD.ADD_TIME } break; default: break; } return ad_id } // 显示激励视频广告 public static showVideoAd(_adUnitId: string, call_back) { if(gameManager.isFreeAds()) { call_back && call_back({"isEnded":true}) return } switch (tools.platform) { case config.Platform.TT: gameManager.Singleton.showLoadingLevel() SdkUtil.videoAd = tt.createRewardedVideoAd({adUnitId: _adUnitId}) break; case config.Platform.WX: gameManager.Singleton.showLoadingLevel() SdkUtil.videoAd = wx.createRewardedVideoAd({adUnitId: _adUnitId}); break; case config.Platform.KS: gameManager.Singleton.showLoadingLevel() SdkUtil.videoAd = ks.createRewardedVideoAd({adUnitId: _adUnitId}) break; default: break; } if(SdkUtil.videoAd==null){ gameManager.Singleton.hideLoadingLevel() return } if(tools.platform == config.Platform.WX) { // 取消关闭,取消错误,提示重复回调,造成奖励重复发送的问题或错误重复发送的问题 SdkUtil.videoAd.offClose() SdkUtil.videoAd.offError() SdkUtil.videoAd.load().then(()=>{ console.log("wx 广告加载完成"); SdkUtil.isLookAd = true SdkUtil.videoAd.show() }).catch(err=>{ console.error('wx 视频广告加载或展示失败:', err); let errorString = err.errCode + '-' + err.errMsg call_back && call_back({isEnded:false,errorString:errorString}) SdkUtil.isLookAd = false gameManager.Singleton.hideLoadingLevel() }) } if(tools.platform == config.Platform.KS) { SdkUtil.videoAd.show().then(()=>{ console.log("ks 广告加载完成"); SdkUtil.isLookAd = true }) } if(tools.platform == config.Platform.TT) { SdkUtil.videoAd.onLoad(() => { console.log("tt 广告加载完成"); SdkUtil.isLookAd = true SdkUtil.videoAd.show(); }); } SdkUtil.videoAd.onClose((res) => { console.log('广告关闭=',res) call_back && call_back(res) SdkUtil.isLookAd = false if(tools.platform!=config.Platform.WX) { SdkUtil.videoAd.destroy() // 微信销毁后,再次获取广告,不会显示 } gameManager.Singleton.hideLoadingLevel() }); SdkUtil.videoAd.onError((res) => { console.log('广告加载失败=',res) let errorString = res.errCode + '-' + res.errMsg call_back && call_back({isEnded:false,errorString:errorString}) SdkUtil.isLookAd = false if(tools.platform!=config.Platform.WX) { SdkUtil.videoAd.destroy() // 微信销毁后,再次获取广告,不会显示 } gameManager.Singleton.hideLoadingLevel() }); if(tools.platform == config.Platform.TT) { SdkUtil.videoAd.load() } } // 注册游戏互推组件 public static registerGridGamePanel() { if(SdkUtil.is_devtools_platform()==true) { return } switch (tools.platform) { case config.Platform.TT: try{ let height = SdkUtil.tt_systemInfo.safeArea.bottom let gridGamePanel_top = 660 if(height) { gridGamePanel_top = height - 150 } // 单宫格gridCount: "one",可设置大小和位置 size:"large",position:{top:700,left:20}, // 四宫格gridCount: "four",可设置大小,设置位置无实际作用 size:"large" // 九宫格gridCount: "nine",设置大小和位置无实际作用 const gridGamePanel = tt.createGridGamePanel({ gridCount: "one", size:"large", position:{top:gridGamePanel_top,left:20}, query: { 'tt3e9d4820a1ac27d902': "", //开局自行车 // 'tt0e4878f5917a358002': "", //找茬 }, }); SdkUtil.gridGamePanel = gridGamePanel } catch(error) { console.log('error=',error) } break; case config.Platform.WX: break; case config.Platform.KS: break; default: break; } } // 显示游戏互推组件 public static showGridGamePanel() { if(SdkUtil.is_devtools_platform()==true) { return } if(!SdkUtil.gridGamePanel) {return} switch (tools.platform) { case config.Platform.TT: SdkUtil.gridGamePanel.show().then(() => { console.log("tt 展示游戏推荐组件成功"); }).catch((err) => { console.error("展示游戏推荐组件失败", err); }); break; case config.Platform.WX: break; case config.Platform.KS: break; default: break; } } // 隐藏互推游戏组件 public static hideGridGamePanel() { if(SdkUtil.is_devtools_platform()==true) { return } if(!SdkUtil.gridGamePanel) {return} switch (tools.platform) { case config.Platform.TT: SdkUtil.gridGamePanel.hide() break; case config.Platform.WX: break; case config.Platform.KS: break; default: break; } } //------------------------------ 微信相关 ------------------------------// // 微信分享 public static wxShare(title: string, imageUrl: string) { // console.log('wx分享=',title, 'imageUrl=',imageUrl) wx.showShareMenu({ withShareTicket: true, // shareAppMessage(可以删除):显示分享给好友选项,shareTimeline(可以删除):显示分享至朋友圈选项 // 可以只开启前者。如果要开启后者,则两者必须都开启才能生效。 // menus: ['shareAppMessage', 'shareTimeline'], menus: ['shareAppMessage'], complete: () => {} }); // 主动分享 wx.shareAppMessage({ title: title, imageUrl: imageUrl }); } //------------------------------ 快手相关 ------------------------------// // 快手加载分包 public static ksLoadSubpackage(name:string,cb) { ks.loadSubpackage({ name: name, success: function(res) { // console.log(`success->${name}=${res}`) cb && cb() }, fail: function(err) { // console.log(`err->${name}=${err}`) } }); } // 快手分享 public static ksShare(title: string, imageUrl: string) { // console.log('ks分享=',title, 'imageUrl=',imageUrl) ks.shareAppMessage({ success:(res)=>{ console.log('ks success=',res) }, fail:(err)=>{ console.log('ks fail=',err) } }); } //------------------------------ 抖音相关 ------------------------------// // 抖音添加快捷键(目前仅支持:抖音(Douyin) 和 抖音极速版(douyin_lite)) public static ttAddShortcut(onSuccess:Function = null, onFail:Function = null) { if(sys.platform == sys.Platform.BYTEDANCE_MINI_GAME) { if(SdkUtil.tt_systemInfo.appName=='Douyin'||SdkUtil.tt_systemInfo.appName=='douyin_lite') { if(SdkUtil.tt_systemInfo.brand=='Apple') { tt.addShortcut({ success() { console.log("添加桌面成功"); onSuccess && onSuccess(null) }, fail(err) { console.log("添加桌面失败", err.errMsg); onFail && onFail(err) }, }); } else if(SdkUtil.tt_systemInfo.brand=='Android') { // 检测只支持安卓 tt.checkShortcut({ success(res) { console.log("检查快捷方式", res.status); if(res.status.exist==false||res.status.needUpdate==true) { tt.addShortcut({ success() { console.log("添加桌面成功"); onSuccess && onSuccess(null) }, fail(err) { console.log("添加桌面失败", err.errMsg); onFail && onFail(err) }, }); } }, fail(err) { console.log("检查快捷方式失败", err.errMsg); onFail && onFail(err) }, }); } } } } // 抖音注册信息 public static ttRegisterInfo() { if(sys.platform == sys.Platform.BYTEDANCE_MINI_GAME) { tt.onShow((res) => { console.log('tt.onShow =', res) // console.log('res=',res) if(res.scene == '021036' || res.scene == '101036') { SdkUtil.tt_isToEnterFromSidebar = true } if(res.scene.launch_from == 'homepage' && res.scene.location == 'sidebar_card') { SdkUtil.tt_isToEnterFromSidebar = true } }); tt.onHide(()=>{ console.log('tt.onHide') if(SdkUtil.isLookAd==false) { statisticsManager.uploadRecordUserLevel(false) } }) tt.checkScene({ scene: "sidebar", success: (res) => { console.log("check scene success: ", res.isExist); if(res.isExist != undefined || res.isExist != null) { SdkUtil.tt_isSupportSidebar = res.isExist } }, fail: (res) => { console.log("check scene fail:", res); } }); let options = tt.getLaunchOptionsSync() console.log('getLaunchOptionsSync=', options) if(options.scene == '021036' || options.scene == '101036') { SdkUtil.tt_isToEnterFromSidebar = true } } } // 抖音检测是否显示奖励 public static ttCheckSceneShowRewards():boolean { return SdkUtil.tt_isSupportSidebar } // 抖音检测是否从侧边栏进入 public static ttCheckToEnterFromSidebar():boolean { return SdkUtil.tt_isToEnterFromSidebar } // 抖音导航到侧边栏场景 public static ttNavToSidebarScene() { if(sys.platform == sys.Platform.BYTEDANCE_MINI_GAME) { tt.navigateToScene({ scene: "sidebar", success: (res) => { // console.log("navigate to scene success"); }, fail: (res) => { // console.log("navigate to scene fail: ", res); }, }); } } // 抖音开启屏幕录制 public static ttStartScreenRecording() { if(sys.platform!=sys.Platform.BYTEDANCE_MINI_GAME) { return } if(this.tt_systemInfo.platform == 'devtools') { console.log('抖音模拟器') return } if(this.tt_isRecording==true) { this.ttStopScreenRecording() } if(!this.tt_gameRecorder) { this.tt_gameRecorder = tt.getGameRecorderManager() } this.tt_gameRecorder.start({duration: this.tt_totalRecord}) this.tt_gameRecorder.onStart(()=> { this.tt_isRecording = true // console.log('GameRecorder onStart onStart onStart') }) this.tt_gameRecorder.onStop((res)=> { // console.log('GameRecorder onStop onStop onStop=',res) this.tt_isRecording = false this.tt_recordVideoPath = res.videoPath }) this.tt_gameRecorder.onError((e)=> { console.log('ttGameRecord error:',e) }) } // 抖音关闭屏幕录制 public static ttStopScreenRecording(isClearVideoPath:boolean = false) { if(sys.platform!=sys.Platform.BYTEDANCE_MINI_GAME) { return } if(this.tt_gameRecorder == null) { return } if(isClearVideoPath) { this.tt_recordVideoPath = ""; } this.tt_gameRecorder.stop() } // 抖音获取屏幕录制视频文件 public static ttGetScreenRecordingVideoPath():string { return this.tt_recordVideoPath; } // 抖音分享屏幕录制视频 private static ttShareScreenRecordVideo(title: string, videoPath: string, onSuccess: Function = null, onFail: Function = null) { // console.log('tt_录制视频路径=',videoPath) if(videoPath.length<=0) { return } tt.shareAppMessage({ title: title, templateId: config.TT_SHARE_TEMPLATEID, channel: "video", extra: { videoTopics: [config.gameName], hashtag_list: ['小游戏','小程序'], videoPath: videoPath, withVideoId: true, }, success: (res) => { console.log('抖音分享屏幕录制视频,成功=',res) onSuccess && onSuccess(); }, fail: (e) => { // 当前今日头条ios无法获得分享成功回调 if(res.platform === 'ios' && res.appName === 'Toutiao') console.log('抖音分享屏幕录制视频,失败=',e) onFail && onFail() } }) } }