sdkUtil.ts 18 KB

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