sdkUtil.ts 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539
  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) {
  110. // console.log(`${res}`)
  111. },
  112. fail(err) {
  113. // console.log(`showLoading调用失败`,err)
  114. },
  115. })
  116. }
  117. }
  118. public static hideLoading() {
  119. if(sys.platform == sys.Platform.BYTEDANCE_MINI_GAME) {
  120. tt.hideLoading({
  121. // success(res) { console.log(`${res}`); },
  122. // fail(err) { console.log(`hideLoading调用失败`,err); },
  123. });
  124. }
  125. }
  126. // 展示toast
  127. public static showToast(title:string,duration=2000,success_cb=null, fail_cb=null) {
  128. if(sys.platform == sys.Platform.BYTEDANCE_MINI_GAME) {
  129. tt.showToast({
  130. title: title,
  131. duration: duration,
  132. success(res) {
  133. console.log(`${res}`);
  134. if(success_cb){ success_cb() }
  135. },
  136. fail(res) {
  137. console.log(`showToast调用失败`);
  138. if(fail_cb) { fail_cb() }
  139. },
  140. });
  141. }
  142. }
  143. // 展示modal
  144. public static showModal(title:string, content:string, suc_cb=null, fail_cb=null, confirmText:string='确定', showCancel:boolean=true, cancelText:string='取消') {
  145. if(sys.platform == sys.Platform.BYTEDANCE_MINI_GAME) {
  146. tt.showModal({
  147. title: title,
  148. content: content,
  149. confirmText: confirmText,
  150. showCancel: showCancel,
  151. cancelText: cancelText,
  152. success(res) {
  153. if(suc_cb) {
  154. suc_cb(res) // 确定:res.confirm 取消:res.cancel
  155. }
  156. },
  157. fail(err) {
  158. if(fail_cb){ fail_cb(err) }
  159. },
  160. });
  161. }
  162. }
  163. // 展示actionSheet
  164. public static showActionSheet(item_list:string[], suc_cb=null, fail_cb=null) {
  165. if(sys.platform == sys.Platform.BYTEDANCE_MINI_GAME) {
  166. tt.showActionSheet({
  167. item_list,
  168. success(res) {
  169. if(suc_cb) {
  170. suc_cb(res) // 点击的索引:`res.tapIndex`
  171. }
  172. },
  173. fail(err) {
  174. if(fail_cb) { fail_cb(err) }
  175. },
  176. });
  177. }
  178. }
  179. // 选择系统相册
  180. public static choosSystemImage(call_back) {
  181. if(sys.platform == sys.Platform.BYTEDANCE_MINI_GAME) {
  182. tt.chooseImage({
  183. sourceType: ["album"],
  184. count:1,
  185. success:(res)=>{
  186. // console.log('chooseImage调用成功=',res)
  187. if(res.tempFilePaths.length>0) {
  188. call_back(res.tempFilePaths[0])
  189. }
  190. },
  191. fail(err) {
  192. console.log(`chooseImage调用失败=`,err);
  193. },
  194. })
  195. } else {
  196. // call_back()
  197. }
  198. }
  199. // 检测显示添加桌面
  200. public static checkIsShowAddDesktop():boolean {
  201. if(sys.platform == sys.Platform.BYTEDANCE_MINI_GAME) {
  202. if(SdkUtil.tt_systemInfo.appName=='Douyin' || SdkUtil.tt_systemInfo.appName=='douyin_lite') {
  203. return true
  204. }
  205. }
  206. return false
  207. }
  208. // 分享游戏
  209. public static shareGame(title: string, call_back) {
  210. if(sys.platform == sys.Platform.BYTEDANCE_MINI_GAME) {
  211. if(title.length<=0) { title = config.TT_CONFIG.SHARE_RELIFE_TITLE }
  212. let desc = tools.sys_config.share_des
  213. if(desc==undefined||desc==null) { desc = ''}
  214. tt.shareAppMessage({
  215. title: title,
  216. desc: desc,
  217. success() {
  218. console.log("分享成功")
  219. // this.showToast('分享成功')
  220. call_back(true)
  221. },
  222. fail(e) {
  223. console.log("分享失败",e)
  224. this.showToast('分享失败')
  225. call_back(false)
  226. },
  227. });
  228. } else if(sys.platform == sys.Platform.WECHAT_GAME) {
  229. if(title.length<=0) { title = config.WX_CONFIG.SHARE_RELIFE_TITLE }
  230. }else{
  231. call_back(true)
  232. }
  233. }
  234. public static shareGameVideo() {
  235. if(sys.platform == sys.Platform.BYTEDANCE_MINI_GAME) {
  236. let videoPath = SdkUtil.ttGetScreenRecordingVideoPath()
  237. uiManager.Instance().showLoading()
  238. this.ttShareScreenRecordVideo(config.gameName,videoPath,()=>{
  239. uiManager.Instance().hideLoading()
  240. }, ()=>{
  241. uiManager.Instance().hideLoading()
  242. })
  243. }
  244. }
  245. // 获取广告id
  246. public static getAdId(ad_type = config.ADS_TYPE.UNKNOWN):string {
  247. let ad_id = ""
  248. if(sys.platform == sys.Platform.BYTEDANCE_MINI_GAME) {
  249. if(ad_type==config.ADS_TYPE.GAME_INFINITE_DEGREE_VIDEO) {
  250. ad_id = config.TT_CONFIG.ADS_ID_INFINITE_DEGREE_VIDEO
  251. } else if(ad_type==config.ADS_TYPE.GAME_RELIFE_VIDEO) {
  252. ad_id = config.TT_CONFIG.ADS_ID_RELIFE_VIDEO
  253. } else if(ad_type==config.ADS_TYPE.GAME_RESTART) {
  254. ad_id = config.TT_CONFIG.ADS_ID_RESTART
  255. }
  256. } else if (sys.platform == sys.Platform.WECHAT_GAME) {
  257. if(ad_type==config.ADS_TYPE.GAME_INFINITE_DEGREE_VIDEO) {
  258. ad_id = config.WX_CONFIG.ADS_ID_INFINITE_DEGREE_VIDEO
  259. } else if(ad_type==config.ADS_TYPE.GAME_RELIFE_VIDEO) {
  260. ad_id = config.WX_CONFIG.ADS_ID_RELIFE_VIDEO
  261. } else if(ad_type==config.ADS_TYPE.GAME_RESTART) {
  262. ad_id = config.WX_CONFIG.ADS_ID_RESTART
  263. }
  264. // if(SdkUtil.KS_GAME) {
  265. // } else {
  266. // }
  267. }
  268. return ad_id
  269. }
  270. // 显示激励视频广告
  271. public static showVideoAd(_adUnitId: string, call_back) {
  272. if(sys.platform==sys.Platform.BYTEDANCE_MINI_GAME) {
  273. uiManager.Instance().showLoading()
  274. SdkUtil.videoAd = tt.createRewardedVideoAd({adUnitId: _adUnitId});
  275. } else {
  276. call_back({"isEnded":true})
  277. return
  278. }
  279. if(SdkUtil.videoAd==null){
  280. uiManager.Instance().hideLoading()
  281. return
  282. }
  283. SdkUtil.videoAd.onLoad(() => {
  284. SdkUtil.isLookAd = true
  285. SdkUtil.videoAd.show();
  286. console.log("广告加载完成");
  287. });
  288. SdkUtil.videoAd.onClose((res) => {
  289. // console.log('广告关闭')
  290. uiManager.Instance().hideLoading()
  291. SdkUtil.isLookAd = false
  292. SdkUtil.videoAd.destroy()
  293. call_back(res)
  294. });
  295. SdkUtil.videoAd.onError((res) => {
  296. // console.log('广告错误')
  297. uiManager.Instance().hideLoading()
  298. SdkUtil.isLookAd = false
  299. SdkUtil.videoAd.destroy()
  300. let errorString = res.errCode + '-' + res.errMsg
  301. call_back({isEnded:false,errorString:errorString})
  302. });
  303. SdkUtil.videoAd.load()
  304. }
  305. //------------------------------ 抖音相关 ------------------------------//
  306. // 抖音获取系统信息
  307. public static ttGetSystemInfo(callback) {
  308. if(sys.platform == sys.Platform.BYTEDANCE_MINI_GAME) {
  309. tt.getSystemInfo({
  310. success:(res) => {
  311. // console.log('tt.getSystemInfo=',res)
  312. // appName: "Douyin" appName: "douyin_lite"
  313. SdkUtil.tt_systemInfo = res
  314. callback()
  315. }
  316. })
  317. }
  318. }
  319. // 抖音添加快捷键(目前仅支持:抖音(Douyin) 和 抖音极速版(douyin_lite))
  320. public static ttAddShortcut(onSuccess:Function = null, onFail:Function = null) {
  321. if(sys.platform == sys.Platform.BYTEDANCE_MINI_GAME) {
  322. if(SdkUtil.tt_systemInfo.appName=='Douyin'||SdkUtil.tt_systemInfo.appName=='douyin_lite') {
  323. if(SdkUtil.tt_systemInfo.brand=='Apple') {
  324. tt.addShortcut({
  325. success() {
  326. console.log("添加桌面成功");
  327. onSuccess && onSuccess(null)
  328. },
  329. fail(err) {
  330. console.log("添加桌面失败", err.errMsg);
  331. onFail && onFail(err)
  332. },
  333. });
  334. } else if(SdkUtil.tt_systemInfo.brand=='Android') {
  335. // 检测只支持安卓
  336. tt.checkShortcut({
  337. success(res) {
  338. console.log("检查快捷方式", res.status);
  339. if(res.status.exist==false||res.status.needUpdate==true) {
  340. tt.addShortcut({
  341. success() {
  342. console.log("添加桌面成功");
  343. onSuccess && onSuccess(null)
  344. },
  345. fail(err) {
  346. console.log("添加桌面失败", err.errMsg);
  347. onFail && onFail(err)
  348. },
  349. });
  350. }
  351. },
  352. fail(err) {
  353. console.log("检查快捷方式失败", err.errMsg);
  354. onFail && onFail(err)
  355. },
  356. });
  357. }
  358. }
  359. }
  360. }
  361. // 抖音注册信息
  362. public static ttRegisterInfo() {
  363. if(sys.platform == sys.Platform.BYTEDANCE_MINI_GAME) {
  364. tt.onShow((res) => {
  365. console.log('tt.onShow =', res)
  366. // console.log('res=',res)
  367. if(res.scene == '021036' || res.scene == '101036') {
  368. SdkUtil.tt_isToEnterFromSidebar = true
  369. }
  370. if(res.scene.launch_from == 'homepage' && res.scene.location == 'sidebar_card') {
  371. SdkUtil.tt_isToEnterFromSidebar = true
  372. }
  373. });
  374. tt.onHide(()=>{
  375. console.log('tt.onHide')
  376. if(SdkUtil.isLookAd==false) {
  377. // statisticsManager.uploadRecordUserLevel(false)
  378. }
  379. })
  380. tt.checkScene({
  381. scene: "sidebar",
  382. success: (res) => {
  383. console.log("check scene success: ", res.isExist);
  384. if(res.isExist != undefined || res.isExist != null) {
  385. SdkUtil.tt_isSupportSidebar = res.isExist
  386. }
  387. },
  388. fail: (res) => {
  389. console.log("check scene fail:", res);
  390. }
  391. });
  392. let options = tt.getLaunchOptionsSync()
  393. console.log('getLaunchOptionsSync=', options)
  394. if(options.scene == '021036' || options.scene == '101036') {
  395. SdkUtil.tt_isToEnterFromSidebar = true
  396. }
  397. }
  398. }
  399. // 抖音检测是否显示奖励
  400. public static ttCheckSceneShowRewards():boolean {
  401. return SdkUtil.tt_isSupportSidebar
  402. }
  403. // 抖音检测是否从侧边栏进入
  404. public static ttCheckToEnterFromSidebar():boolean {
  405. return SdkUtil.tt_isToEnterFromSidebar
  406. }
  407. // 抖音导航到侧边栏场景
  408. public static ttNavToSidebarScene() {
  409. if(sys.platform == sys.Platform.BYTEDANCE_MINI_GAME) {
  410. tt.navigateToScene({
  411. scene: "sidebar",
  412. success: (res) => {
  413. // console.log("navigate to scene success");
  414. },
  415. fail: (res) => {
  416. // console.log("navigate to scene fail: ", res);
  417. },
  418. });
  419. }
  420. }
  421. // 抖音开启屏幕录制
  422. public static ttStartScreenRecording() {
  423. if(sys.platform!=sys.Platform.BYTEDANCE_MINI_GAME) {
  424. return
  425. }
  426. if(this.tt_systemInfo.platform == 'devtools') {
  427. console.log('抖音模拟器')
  428. return
  429. }
  430. if(this.tt_isRecording==true) {
  431. this.ttStopScreenRecording()
  432. }
  433. if(!this.tt_gameRecorder) {
  434. this.tt_gameRecorder = tt.getGameRecorderManager()
  435. }
  436. this.tt_gameRecorder.start({duration: this.tt_totalRecord})
  437. this.tt_gameRecorder.onStart(()=> {
  438. this.tt_isRecording = true
  439. // console.log('GameRecorder onStart onStart onStart')
  440. })
  441. this.tt_gameRecorder.onStop((res)=> {
  442. // console.log('GameRecorder onStop onStop onStop=',res)
  443. this.tt_isRecording = false
  444. this.tt_recordVideoPath = res.videoPath
  445. })
  446. this.tt_gameRecorder.onError((e)=> {
  447. console.log('ttGameRecord error:',e)
  448. })
  449. }
  450. // 抖音关闭屏幕录制
  451. public static ttStopScreenRecording(isClearVideoPath:boolean = false) {
  452. if(sys.platform!=sys.Platform.BYTEDANCE_MINI_GAME) {
  453. return
  454. }
  455. if(this.tt_gameRecorder == null) {
  456. return
  457. }
  458. if(isClearVideoPath) {
  459. this.tt_recordVideoPath = "";
  460. }
  461. this.tt_gameRecorder.stop()
  462. }
  463. // 抖音获取屏幕录制视频文件
  464. public static ttGetScreenRecordingVideoPath():string {
  465. return this.tt_recordVideoPath;
  466. }
  467. // 抖音分享屏幕录制视频
  468. private static ttShareScreenRecordVideo(title: string, videoPath: string, onSuccess: Function = null, onFail: Function = null) {
  469. console.log('tt_录制视频路径=',videoPath)
  470. if(videoPath.length<=0) {
  471. return
  472. }
  473. tt.shareAppMessage({
  474. title: title,
  475. templateId: config.TT_CONFIG.SHARE_RECORD_VIDEO_ID,
  476. channel: "video",
  477. extra: {
  478. videoTopics: [config.gameName],
  479. hashtag_list: ['小游戏','小程序'],
  480. videoPath: videoPath,
  481. withVideoId: true,
  482. },
  483. success: (res) => {
  484. console.log('抖音分享屏幕录制视频,成功=',res)
  485. onSuccess && onSuccess();
  486. },
  487. fail: (e) => {
  488. // 当前今日头条ios无法获得分享成功回调 if(res.platform === 'ios' && res.appName === 'Toutiao')
  489. console.log('抖音分享屏幕录制视频,失败=',e)
  490. onFail && onFail()
  491. }
  492. })
  493. }
  494. }