sdkUtil.ts 18 KB

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