sdkUtil.ts 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535
  1. import { _decorator, error, SpriteFrame, sys } from "cc";
  2. import { config } from "./config";
  3. import { uiManager } from "./manager/uiManager";
  4. import { tools } from "./tools";
  5. //管理广告、分享、SDK相关内容的组件
  6. export class SdkUtil {
  7. public static platform: string = 'cocos'; //平台
  8. public static imgAd: SpriteFrame = null!;
  9. public static imgShare: SpriteFrame = null!;
  10. public static isDebugMode: boolean = false;
  11. public static onlineInterval: number = -1;
  12. public static isEnableVibrate: boolean = true;
  13. public static isCheckOffline: boolean = false; //登录后会检查是否展示登录界面,而且只检查一次
  14. public static isWatchVideoAd: boolean = false;//是否正在播放广告
  15. public static isEnableMoving: boolean = false;//是否允许屏幕上下移动
  16. public static isEnableZoom: boolean = false;//是否允许屏幕缩放
  17. public static arrLockDiary = [];//未解锁日记
  18. public static vibrateInterval: number = 100;//两次震动之间的间隔,AppActivity里面的震动间隔也是100
  19. public static vibratePreTime: number = 0;//上次震动时间
  20. public static videoAd:any =null;
  21. public static isLookAd:boolean = false; //是否在看广告
  22. public static tt_systemInfo: any = null; //抖音_系统信息
  23. private static tt_isSupportSidebar:boolean = false; //抖音_是否支持侧边栏
  24. private static tt_isToEnterFromSidebar:boolean = false; //抖音_是否从侧边栏进入
  25. private static tt_gameRecorder:any = null; //抖音游戏录制
  26. private static tt_recordVideoPath:string = ''; //抖音录制视频路径
  27. private static tt_totalRecord:number = 300; //抖音总录制时间
  28. private static tt_isRecording:boolean = false; //抖音是否录制中
  29. //------------------------------ 公共 ------------------------------//
  30. public static init() {
  31. this.ttGetSystemInfo(()=> {
  32. this.ttRegisterInfo()
  33. })
  34. }
  35. // 自定义事件统计
  36. public static customEventStatistics(eventType: string, objParams?: any) {
  37. eventType = eventType.toString();
  38. if (!objParams) { objParams = {}; }
  39. // console.log({'eventType': eventType},{'objParams': objParams});
  40. if (this.platform === 'wx') {
  41. //@ts-ignore
  42. if (window['wx'] && window['wx']['aldSendEvent']) {
  43. //@ts-ignore
  44. window.wx['aldSendEvent'](eventType, objParams);
  45. }
  46. }
  47. //@ts-ignore
  48. if (this.platform === 'cocos' && window.cocosAnalytics && window.cocosAnalytics.isInited()) {
  49. console.log("###统计", eventType, objParams);
  50. //@ts-ignore
  51. window.cocosAnalytics.CACustomEvent.onStarted(eventType, objParams);
  52. }
  53. }
  54. // 登录
  55. public static login(call){
  56. if(sys.platform == sys.Platform.BYTEDANCE_MINI_GAME) {
  57. tt.login({
  58. force: true,
  59. success(res) {
  60. console.log(`login 调用成功${res.code} ${res.anonymousCode}`);
  61. call({"code":res.code,"anonymousCode":res.anonymousCode})
  62. },
  63. fail(res) {
  64. console.log(`login 调用失败`);
  65. call(null)
  66. },
  67. });
  68. }else{
  69. call(null)
  70. }
  71. }
  72. // 获取用户信息
  73. public static getUserInfo(call){
  74. if(sys.platform == sys.Platform.BYTEDANCE_MINI_GAME) {
  75. tt.getUserInfo({
  76. // withCredentials: true,
  77. // withRealNameAuthenticationInfo: true,
  78. success(res) {
  79. console.log(`getUserInfo 调用成功`, res.userInfo);
  80. call(res.userInfo)
  81. },
  82. fail(res) {
  83. console.log(`getUserInfo 调用失败`, res.errMsg);
  84. },
  85. });
  86. }else{
  87. call(null)
  88. }
  89. }
  90. // 震动
  91. public static vibrateShort(){
  92. if(sys.platform == sys.Platform.BYTEDANCE_MINI_GAME) {
  93. tt.vibrateShort({
  94. success(res) {
  95. // console.log(`${res}`);
  96. },
  97. fail(res) {
  98. // console.log(`vibrateShort调用失败`);
  99. },
  100. });
  101. }
  102. }
  103. // 关于loading
  104. public static showLoading(title:string) {
  105. if(title.length<=0) { return }
  106. if(sys.platform == sys.Platform.BYTEDANCE_MINI_GAME) {
  107. tt.showLoading({
  108. title: title,
  109. success(res) { console.log(`${res}`);},
  110. fail(err) { console.log(`showLoading调用失败`,err);},
  111. })
  112. }
  113. }
  114. public static hideLoading() {
  115. if(sys.platform == sys.Platform.BYTEDANCE_MINI_GAME) {
  116. tt.hideLoading({
  117. // success(res) { console.log(`${res}`); },
  118. // fail(err) { console.log(`hideLoading调用失败`,err); },
  119. });
  120. }
  121. }
  122. // 展示toast
  123. public static showToast(title:string,duration=2000,success_cb=null, fail_cb=null) {
  124. if(sys.platform == sys.Platform.BYTEDANCE_MINI_GAME) {
  125. tt.showToast({
  126. title: title,
  127. duration: duration,
  128. success(res) {
  129. console.log(`${res}`);
  130. if(success_cb){ success_cb() }
  131. },
  132. fail(res) {
  133. console.log(`showToast调用失败`);
  134. if(fail_cb) { fail_cb() }
  135. },
  136. });
  137. }
  138. }
  139. // 展示modal
  140. public static showModal(title:string, content:string, suc_cb=null, fail_cb=null, confirmText:string='确定', showCancel:boolean=true, cancelText:string='取消') {
  141. if(sys.platform == sys.Platform.BYTEDANCE_MINI_GAME) {
  142. tt.showModal({
  143. title: title,
  144. content: content,
  145. confirmText: confirmText,
  146. showCancel: showCancel,
  147. cancelText: cancelText,
  148. success(res) {
  149. if(suc_cb) {
  150. suc_cb(res) // 确定:res.confirm 取消:res.cancel
  151. }
  152. },
  153. fail(err) {
  154. if(fail_cb){ fail_cb(err) }
  155. },
  156. });
  157. }
  158. }
  159. // 展示actionSheet
  160. public static showActionSheet(item_list:string[], suc_cb=null, fail_cb=null) {
  161. if(sys.platform == sys.Platform.BYTEDANCE_MINI_GAME) {
  162. tt.showActionSheet({
  163. item_list,
  164. success(res) {
  165. if(suc_cb) {
  166. suc_cb(res) // 点击的索引:`res.tapIndex`
  167. }
  168. },
  169. fail(err) {
  170. if(fail_cb) { fail_cb(err) }
  171. },
  172. });
  173. }
  174. }
  175. // 选择系统相册
  176. public static choosSystemImage(call_back) {
  177. if(sys.platform == sys.Platform.BYTEDANCE_MINI_GAME) {
  178. tt.chooseImage({
  179. sourceType: ["album"],
  180. count:1,
  181. success:(res)=>{
  182. // console.log('chooseImage调用成功=',res)
  183. if(res.tempFilePaths.length>0) {
  184. call_back(res.tempFilePaths[0])
  185. }
  186. },
  187. fail(err) {
  188. console.log(`chooseImage调用失败=`,err);
  189. },
  190. })
  191. } else {
  192. // call_back()
  193. }
  194. }
  195. // 检测显示添加桌面
  196. public static checkIsShowAddDesktop():boolean {
  197. if(sys.platform == sys.Platform.BYTEDANCE_MINI_GAME) {
  198. if(SdkUtil.tt_systemInfo.appName=='Douyin' || SdkUtil.tt_systemInfo.appName=='douyin_lite') {
  199. return true
  200. }
  201. }
  202. return false
  203. }
  204. // 分享游戏
  205. public static shareGame(title: string, call_back) {
  206. if(sys.platform == sys.Platform.BYTEDANCE_MINI_GAME) {
  207. if(title.length<=0) { title = config.TT_CONFIG.SHARE_RELIFE_TITLE }
  208. let desc = tools.sys_config.share_des
  209. if(desc==undefined||desc==null) { desc = ''}
  210. tt.shareAppMessage({
  211. title: title,
  212. desc: desc,
  213. success() {
  214. console.log("分享成功")
  215. // this.showToast('分享成功')
  216. call_back(true)
  217. },
  218. fail(e) {
  219. console.log("分享失败",e)
  220. this.showToast('分享失败')
  221. call_back(false)
  222. },
  223. });
  224. } else if(sys.platform == sys.Platform.WECHAT_GAME) {
  225. if(title.length<=0) { title = config.WX_CONFIG.SHARE_RELIFE_TITLE }
  226. }else{
  227. call_back(true)
  228. }
  229. }
  230. public static shareGameVideo() {
  231. if(sys.platform == sys.Platform.BYTEDANCE_MINI_GAME) {
  232. let videoPath = SdkUtil.ttGetScreenRecordingVideoPath()
  233. uiManager.Instance().showLoading()
  234. this.ttShareScreenRecordVideo(config.gameName,videoPath,()=>{
  235. uiManager.Instance().hideLoading()
  236. }, ()=>{
  237. uiManager.Instance().hideLoading()
  238. })
  239. }
  240. }
  241. // 获取广告id
  242. public static getAdId(ad_type = config.ADS_TYPE.UNKNOWN):string {
  243. let ad_id = ""
  244. if(sys.platform == sys.Platform.BYTEDANCE_MINI_GAME) {
  245. if(ad_type==config.ADS_TYPE.GAME_INFINITE_DEGREE_VIDEO) {
  246. ad_id = config.TT_CONFIG.ADS_ID_INFINITE_DEGREE_VIDEO
  247. } else if(ad_type==config.ADS_TYPE.GAME_RELIFE_VIDEO) {
  248. ad_id = config.TT_CONFIG.ADS_ID_RELIFE_VIDEO
  249. } else if(ad_type==config.ADS_TYPE.GAME_RESTART) {
  250. ad_id = config.TT_CONFIG.ADS_ID_RESTART
  251. }
  252. } else if (sys.platform == sys.Platform.WECHAT_GAME) {
  253. if(ad_type==config.ADS_TYPE.GAME_INFINITE_DEGREE_VIDEO) {
  254. ad_id = config.WX_CONFIG.ADS_ID_INFINITE_DEGREE_VIDEO
  255. } else if(ad_type==config.ADS_TYPE.GAME_RELIFE_VIDEO) {
  256. ad_id = config.WX_CONFIG.ADS_ID_RELIFE_VIDEO
  257. } else if(ad_type==config.ADS_TYPE.GAME_RESTART) {
  258. ad_id = config.WX_CONFIG.ADS_ID_RESTART
  259. }
  260. // if(SdkUtil.KS_GAME) {
  261. // } else {
  262. // }
  263. }
  264. return ad_id
  265. }
  266. // 显示激励视频广告
  267. public static showVideoAd(_adUnitId: string, call_back) {
  268. if(sys.platform==sys.Platform.BYTEDANCE_MINI_GAME) {
  269. uiManager.Instance().showLoading()
  270. SdkUtil.videoAd = tt.createRewardedVideoAd({adUnitId: _adUnitId});
  271. } else {
  272. call_back({"isEnded":true})
  273. return
  274. }
  275. if(SdkUtil.videoAd==null){
  276. uiManager.Instance().hideLoading()
  277. return
  278. }
  279. SdkUtil.videoAd.onLoad(() => {
  280. SdkUtil.isLookAd = true
  281. SdkUtil.videoAd.show();
  282. console.log("广告加载完成");
  283. });
  284. SdkUtil.videoAd.onClose((res) => {
  285. // console.log('广告关闭')
  286. uiManager.Instance().hideLoading()
  287. SdkUtil.isLookAd = false
  288. SdkUtil.videoAd.destroy()
  289. call_back(res)
  290. });
  291. SdkUtil.videoAd.onError((res) => {
  292. // console.log('广告错误')
  293. uiManager.Instance().hideLoading()
  294. SdkUtil.isLookAd = false
  295. SdkUtil.videoAd.destroy()
  296. let errorString = res.errCode + '-' + res.errMsg
  297. call_back({isEnded:false,errorString:errorString})
  298. });
  299. SdkUtil.videoAd.load()
  300. }
  301. //------------------------------ 抖音相关 ------------------------------//
  302. // 抖音获取系统信息
  303. public static ttGetSystemInfo(callback) {
  304. if(sys.platform == sys.Platform.BYTEDANCE_MINI_GAME) {
  305. tt.getSystemInfo({
  306. success:(res) => {
  307. // console.log('tt.getSystemInfo=',res)
  308. // appName: "Douyin" appName: "douyin_lite"
  309. SdkUtil.tt_systemInfo = res
  310. callback()
  311. }
  312. })
  313. }
  314. }
  315. // 抖音添加快捷键(目前仅支持:抖音(Douyin) 和 抖音极速版(douyin_lite))
  316. public static ttAddShortcut(onSuccess:Function = null, onFail:Function = null) {
  317. if(sys.platform == sys.Platform.BYTEDANCE_MINI_GAME) {
  318. if(SdkUtil.tt_systemInfo.appName=='Douyin'||SdkUtil.tt_systemInfo.appName=='douyin_lite') {
  319. if(SdkUtil.tt_systemInfo.brand=='Apple') {
  320. tt.addShortcut({
  321. success() {
  322. console.log("添加桌面成功");
  323. onSuccess && onSuccess(null)
  324. },
  325. fail(err) {
  326. console.log("添加桌面失败", err.errMsg);
  327. onFail && onFail(err)
  328. },
  329. });
  330. } else if(SdkUtil.tt_systemInfo.brand=='Android') {
  331. // 检测只支持安卓
  332. tt.checkShortcut({
  333. success(res) {
  334. console.log("检查快捷方式", res.status);
  335. if(res.status.exist==false||res.status.needUpdate==true) {
  336. tt.addShortcut({
  337. success() {
  338. console.log("添加桌面成功");
  339. onSuccess && onSuccess(null)
  340. },
  341. fail(err) {
  342. console.log("添加桌面失败", err.errMsg);
  343. onFail && onFail(err)
  344. },
  345. });
  346. }
  347. },
  348. fail(err) {
  349. console.log("检查快捷方式失败", err.errMsg);
  350. onFail && onFail(err)
  351. },
  352. });
  353. }
  354. }
  355. }
  356. }
  357. // 抖音注册信息
  358. public static ttRegisterInfo() {
  359. if(sys.platform == sys.Platform.BYTEDANCE_MINI_GAME) {
  360. tt.onShow((res) => {
  361. console.log('tt.onShow =', res)
  362. // console.log('res=',res)
  363. if(res.scene == '021036' || res.scene == '101036') {
  364. SdkUtil.tt_isToEnterFromSidebar = true
  365. }
  366. if(res.scene.launch_from == 'homepage' && res.scene.location == 'sidebar_card') {
  367. SdkUtil.tt_isToEnterFromSidebar = true
  368. }
  369. });
  370. tt.onHide(()=>{
  371. console.log('tt.onHide')
  372. if(SdkUtil.isLookAd==false) {
  373. // statisticsManager.uploadRecordUserLevel(false)
  374. }
  375. })
  376. tt.checkScene({
  377. scene: "sidebar",
  378. success: (res) => {
  379. console.log("check scene success: ", res.isExist);
  380. if(res.isExist != undefined || res.isExist != null) {
  381. SdkUtil.tt_isSupportSidebar = res.isExist
  382. }
  383. },
  384. fail: (res) => {
  385. console.log("check scene fail:", res);
  386. }
  387. });
  388. let options = tt.getLaunchOptionsSync()
  389. console.log('getLaunchOptionsSync=', options)
  390. if(options.scene == '021036' || options.scene == '101036') {
  391. SdkUtil.tt_isToEnterFromSidebar = true
  392. }
  393. }
  394. }
  395. // 抖音检测是否显示奖励
  396. public static ttCheckSceneShowRewards():boolean {
  397. return SdkUtil.tt_isSupportSidebar
  398. }
  399. // 抖音检测是否从侧边栏进入
  400. public static ttCheckToEnterFromSidebar():boolean {
  401. return SdkUtil.tt_isToEnterFromSidebar
  402. }
  403. // 抖音导航到侧边栏场景
  404. public static ttNavToSidebarScene() {
  405. if(sys.platform == sys.Platform.BYTEDANCE_MINI_GAME) {
  406. tt.navigateToScene({
  407. scene: "sidebar",
  408. success: (res) => {
  409. // console.log("navigate to scene success");
  410. },
  411. fail: (res) => {
  412. // console.log("navigate to scene fail: ", res);
  413. },
  414. });
  415. }
  416. }
  417. // 抖音开启屏幕录制
  418. public static ttStartScreenRecording() {
  419. if(sys.platform!=sys.Platform.BYTEDANCE_MINI_GAME) {
  420. return
  421. }
  422. if(this.tt_systemInfo.platform == 'devtools') {
  423. console.log('抖音模拟器')
  424. return
  425. }
  426. if(this.tt_isRecording==true) {
  427. this.ttStopScreenRecording()
  428. }
  429. if(!this.tt_gameRecorder) {
  430. this.tt_gameRecorder = tt.getGameRecorderManager()
  431. }
  432. this.tt_gameRecorder.start({duration: this.tt_totalRecord})
  433. this.tt_gameRecorder.onStart(()=> {
  434. this.tt_isRecording = true
  435. // console.log('GameRecorder onStart onStart onStart')
  436. })
  437. this.tt_gameRecorder.onStop((res)=> {
  438. // console.log('GameRecorder onStop onStop onStop=',res)
  439. this.tt_isRecording = false
  440. this.tt_recordVideoPath = res.videoPath
  441. })
  442. this.tt_gameRecorder.onError((e)=> {
  443. console.log('ttGameRecord error:',e)
  444. })
  445. }
  446. // 抖音关闭屏幕录制
  447. public static ttStopScreenRecording(isClearVideoPath:boolean = false) {
  448. if(sys.platform!=sys.Platform.BYTEDANCE_MINI_GAME) {
  449. return
  450. }
  451. if(this.tt_gameRecorder == null) {
  452. return
  453. }
  454. if(isClearVideoPath) {
  455. this.tt_recordVideoPath = "";
  456. }
  457. this.tt_gameRecorder.stop()
  458. }
  459. // 抖音获取屏幕录制视频文件
  460. public static ttGetScreenRecordingVideoPath():string {
  461. return this.tt_recordVideoPath;
  462. }
  463. // 抖音分享屏幕录制视频
  464. private static ttShareScreenRecordVideo(title: string, videoPath: string, onSuccess: Function = null, onFail: Function = null) {
  465. console.log('tt_录制视频路径=',videoPath)
  466. if(videoPath.length<=0) {
  467. return
  468. }
  469. tt.shareAppMessage({
  470. title: title,
  471. templateId: config.TT_CONFIG.SHARE_RECORD_VIDEO_ID,
  472. channel: "video",
  473. extra: {
  474. videoTopics: [config.gameName],
  475. hashtag_list: ['小游戏','小程序'],
  476. videoPath: videoPath,
  477. withVideoId: true,
  478. },
  479. success: (res) => {
  480. console.log('抖音分享屏幕录制视频,成功=',res)
  481. onSuccess && onSuccess();
  482. },
  483. fail: (e) => {
  484. // 当前今日头条ios无法获得分享成功回调 if(res.platform === 'ios' && res.appName === 'Toutiao')
  485. console.log('抖音分享屏幕录制视频,失败=',e)
  486. onFail && onFail()
  487. }
  488. })
  489. }
  490. }