YZ_Tool_Baidu.ts 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582
  1. import PlatUtils from "./PlatUtils";
  2. import { utils } from "./Utils";
  3. import YZ_Constant, { LevelStatus } from "./YZ_Constant";
  4. import YZ_LocalStorage from "./YZ_LocalStorage";
  5. const { ccclass, property } = cc._decorator;
  6. const ST_ServerUrl: string = "https://apps.youlesp.com/gss?";
  7. const POST_ServerUrl: string = "https://report.youletd.com/gss?";
  8. // 默认配置
  9. let ST_DefaultServerConfig: string = "";
  10. @ccclass
  11. export default class YZ_Tool_Baidu {
  12. _recorder: any = null;
  13. _recommendationButton: any = null;
  14. _videoPath: string = null;
  15. _serverConfig: any = null;
  16. _shareCallback: Function = null;
  17. //@ts-ignore
  18. swan: any = window.swan;
  19. public get ServerConfig() {
  20. return this._serverConfig;
  21. }
  22. _sysInfo: any = {};
  23. public get SysInfo() {
  24. return this._sysInfo;
  25. }
  26. /**
  27. * 当前版本号
  28. */
  29. public gameVersion(): string {
  30. return utils.config.baiduconfig.version;
  31. }
  32. //设备UID
  33. _uid: string = "0";
  34. public get uid() {
  35. // if (this._service_uid != "0") return this._uid;
  36. // this._login();
  37. return "0";
  38. }
  39. //服务器返回UID
  40. _service_uid: string = "0";
  41. /**
  42. * 服务器返回UID
  43. */
  44. public get serviceId() {
  45. if (this._service_uid != "0") return this._service_uid;
  46. this.reportLogin();
  47. return "0";
  48. }
  49. _loginTime: number = 0;
  50. _loginInterval: number = 30;
  51. async _login() {
  52. let curTime: number = new Date().getTime();
  53. let interval: number = (curTime - this._loginTime) / 1000;
  54. if (interval > 0 && interval < 30) {
  55. utils.showLog(`登录请求间隔小于:${this._loginInterval}秒`);
  56. return;
  57. }
  58. this._loginTime = curTime;
  59. let self = this;
  60. utils.showLog("baidu暂时不获取uid,uid全部为0");
  61. this._uid = "0";
  62. // this.reportLogin();
  63. }
  64. _reportLoginTime: number = 0;
  65. _reportLoginInterval: number = 30;
  66. isReport: boolean = false;
  67. /**
  68. * 上报登录接口获取UID
  69. */
  70. reportLogin() {
  71. if (this.isReport) return;
  72. this.isReport = true;
  73. let self = this;
  74. let curTime: number = new Date().getTime();
  75. let interval: number = (curTime - self._reportLoginTime) / 1000;
  76. console.log(curTime, curTime - self._reportLoginTime, interval)
  77. if (interval > 0 && interval < 30) {
  78. utils.showLog(`上报登录获取UID小于:${self._reportLoginInterval}秒`);
  79. return;
  80. }
  81. self._reportLoginTime = curTime;
  82. let method = "m=login";
  83. let url: string = ST_ServerUrl + method + `&device_data=0`;
  84. utils.commomHttpRequest(url, (ret, data) => {
  85. if (ret) {
  86. if (data) {
  87. let result = JSON.parse(data);
  88. utils.showLog("data=" + data);
  89. utils.showLog("result=" + result);
  90. utils.showLog("result.uid=" + result.uid);
  91. if (result.uid) {
  92. self._service_uid = "" + result.uid;
  93. console.log("self._service_uid:" + self._service_uid)
  94. utils.showLog("服务器请求登录成功! _service_uid=" + self._service_uid);
  95. YZ_LocalStorage.setItem(YZ_Constant.ST_SERVICE_UID, self._service_uid);
  96. }
  97. }
  98. } else {
  99. utils.showLog("获取数据失败1");
  100. }
  101. this.isReport = false;
  102. })
  103. }
  104. /**
  105. *
  106. * @param data 配置数据
  107. */
  108. public init(data: string) {
  109. if (PlatUtils.IsBaidu) {
  110. if (data) {
  111. let configObj: any = JSON.parse(data);
  112. if (configObj && configObj.baidu) {
  113. ST_DefaultServerConfig = JSON.stringify(configObj.baidu);
  114. }
  115. }
  116. this._service_uid = YZ_LocalStorage.getItem(YZ_Constant.ST_SERVICE_UID);
  117. this._service_uid = this._service_uid ? this._service_uid : "0";
  118. // 获取系统信息
  119. this._sysInfo = this.swan.getSystemInfoSync();
  120. if (this._sysInfo) {
  121. utils.showLog("百度小游戏平台信息: ", JSON.stringify(this._sysInfo));
  122. } else {
  123. utils.showLog("系统信息获取失败!");
  124. }
  125. this._loadConfig();
  126. if (this.canRecord()) {
  127. this._recorder = this.swan.getVideoRecorderManager();
  128. if (this._recorder) {
  129. this._recorder.onStart((res) => {
  130. utils.showLog("开始录屏回调: ", res);
  131. utils.isRecording = true;
  132. cc.game.emit("YZ_CommonMessage", { type: "YZ_RecordStart" });
  133. });
  134. this._recorder.onStop((res) => {
  135. utils.showLog("结束录屏回调: ", res.videoPath);
  136. utils.isRecording = false;
  137. this._videoPath = res.videoPath;
  138. cc.game.emit("YZ_CommonMessage", { type: "YZ_RecordEnd" });
  139. });
  140. this._recorder.onError((err) => {
  141. utils.isRecording = false;
  142. if (err) {
  143. utils.showLog("录屏出错 : ", err.errCode, err.errMsg);
  144. cc.game.emit("YZ_CommonMessage", { type: "YZ_RecordEnd" });
  145. }
  146. })
  147. }
  148. }
  149. // 显示左上角的分享菜单
  150. this.swan.showShareMenu();
  151. this.swan.onShareAppMessage(() => {
  152. return this._getShareInfo();
  153. });
  154. }
  155. }
  156. _loadConfig() {
  157. if (PlatUtils.IsBaidu) {
  158. let method: string = "m=g";
  159. utils.commomHttpRequest(ST_ServerUrl + method, (ret, data) => {
  160. if (ret) {
  161. utils.showLog("百度服务器配置数据获取成功: data = ", data);
  162. if (data) {
  163. let result = JSON.parse(data);
  164. if (result) {
  165. if (!utils.DebugLoacalConfig) {
  166. this._serverConfig = result;
  167. } else {
  168. cc.warn("开启了本地数据测试,使用本地配置!");
  169. }
  170. } else {
  171. utils.showLog("百度服务器配置数据不是合法的JSON数据, 使用本地配置!");
  172. }
  173. }
  174. } else {
  175. utils.showLog("百度服务器配置数据获取失败, 使用本地配置!");
  176. }
  177. if (!this._serverConfig) {
  178. this._serverConfig = JSON.parse(ST_DefaultServerConfig);
  179. } else {
  180. if (this._serverConfig.is_local_pos_id
  181. && this._serverConfig.is_local_pos_id == "false") {
  182. // 使用服务器下发的广告id
  183. utils.showLog("使用服务器下发的广告id");
  184. utils.config.baiduconfig.bannerId = this._serverConfig.banner_pos_id;
  185. utils.config.baiduconfig.videoId = this._serverConfig.video_pos_id;
  186. } else {
  187. utils.showLog("使用本地配置的广告ID");
  188. }
  189. }
  190. utils.emitServerInitEvent();
  191. });
  192. }
  193. }
  194. /**
  195. * 显示推荐游戏按钮
  196. */
  197. public showRecommendationButton(params: any) {
  198. let styleParams: any = params;
  199. if (PlatUtils.IsBaidu && this.canShowRecommendButton()) {
  200. if (false) {
  201. utils.showLog("按钮存在,直接显示");
  202. this._recommendationButton.show();
  203. this._setRecommendBtnStyle(this._recommendationButton, styleParams);
  204. } else {
  205. utils.showLog("创建并显示");
  206. this._recommendationButton = this.swan.createRecommendationButton({
  207. type: 'list',
  208. style: {
  209. left: -300,
  210. top: -300
  211. }
  212. });
  213. if (this._recommendationButton) {
  214. // 监听按钮资源加载完成
  215. this._recommendationButton.onLoad(() => {
  216. // 显示按钮
  217. this._recommendationButton.show();
  218. this._setRecommendBtnStyle(this._recommendationButton, styleParams);
  219. });
  220. this._recommendationButton.onError((err) => {
  221. if (err) {
  222. utils.showLog("交叉推广按钮出错 : ", err.errCode, err.errMsg);
  223. }
  224. });
  225. // 触发资源加载
  226. this._recommendationButton.load();
  227. }
  228. }
  229. return this._recommendationButton;
  230. } else {
  231. return null;
  232. }
  233. }
  234. _setRecommendBtnStyle(btn: any, params: any) {
  235. if (btn) {
  236. let left: number = 0;
  237. let top: number = 0;
  238. if (params) {
  239. utils.showLog("params:", params);
  240. if (params.left) {
  241. left = params.left / cc.view.getDesignResolutionSize().width * this._sysInfo.screenWidth;
  242. } else if (params.right) {
  243. left = this._sysInfo.screenWidth - params.right / cc.view.getDesignResolutionSize().width * this._sysInfo.screenWidth - btn.style.width;
  244. }
  245. if (params.top) {
  246. top = params.top / cc.view.getDesignResolutionSize().height * this._sysInfo.screenHeight;
  247. } else if (params.bottom) {
  248. top = this._sysInfo.screenHeight - params.bottom / cc.view.getDesignResolutionSize().height * this._sysInfo.screenHeight - btn.style.height;
  249. }
  250. }
  251. utils.showLog(`top:${top}; left:${left}`);
  252. btn.style.top = top;
  253. btn.style.left = left;
  254. }
  255. }
  256. /**
  257. * 隐藏推荐游戏按钮
  258. */
  259. public hideRecommendationButton() {
  260. if (PlatUtils.IsBaidu && this.canShowRecommendButton()) {
  261. if (this._recommendationButton) {
  262. this._recommendationButton.hide();
  263. }
  264. }
  265. }
  266. /**
  267. * 开始录屏
  268. */
  269. public recordStart() {
  270. if (PlatUtils.IsBaidu && this.canRecord()) {
  271. utils.showLog("开始录屏");
  272. if (this._recorder) {
  273. this._recorder.start({
  274. duration: 120
  275. });
  276. }
  277. }
  278. }
  279. /**
  280. * 结束录屏
  281. */
  282. public recordEnd() {
  283. if (PlatUtils.IsBaidu && this.canRecord()) {
  284. utils.showLog("结束录屏");
  285. if (this._recorder) {
  286. this._recorder.stop();
  287. }
  288. }
  289. }
  290. /**
  291. * 分享录屏
  292. */
  293. public shareVideo() {
  294. if (PlatUtils.IsBaidu) {
  295. if (this._videoPath) {
  296. let self = this;
  297. this.swan.shareVideo({
  298. videoPath: this._videoPath,
  299. success() {
  300. utils.showLog('分享成功');
  301. self._videoPath = "";
  302. if (self._shareCallback) {
  303. self._shareCallback(true);
  304. }
  305. },
  306. fail(res) {
  307. self._videoPath = "";
  308. utils.showLog('分享失败');
  309. if (self._shareCallback) {
  310. self._shareCallback(false, "分享失败!");
  311. }
  312. }
  313. });
  314. }
  315. }
  316. }
  317. /**
  318. * 分享图片
  319. */
  320. public shareImage() {
  321. if (PlatUtils.IsBaidu) {
  322. this.swan.shareAppMessage(this._getShareInfo());
  323. }
  324. }
  325. /**
  326. * 分享,有录屏就分享录屏,没有录屏就分享图片
  327. */
  328. public share(callback: Function) {
  329. if (PlatUtils.IsBaidu) {
  330. this._shareCallback = callback;
  331. if (this._videoPath) {
  332. this.shareVideo();
  333. } else {
  334. this.shareImage();
  335. }
  336. }
  337. }
  338. _getShareInfo() {
  339. if (PlatUtils.IsBaidu) {
  340. let shareInfo = utils.getShareInfo();
  341. let self = this;
  342. if (shareInfo) {
  343. return {
  344. title: shareInfo.title,
  345. imageUrl: shareInfo.imageUrl,
  346. success: function (res) {
  347. if (self._shareCallback) {
  348. self._shareCallback(true);
  349. }
  350. utils.showLog("分享成功!");
  351. },
  352. fail: function (err) {
  353. if (self._shareCallback) {
  354. self._shareCallback(false, "分享失败!");
  355. }
  356. utils.showLog("分享失败!");
  357. }
  358. }
  359. }
  360. }
  361. return {};
  362. }
  363. /**
  364. * 是否可以录屏
  365. */
  366. public canRecord() {
  367. if (PlatUtils.IsBaidu) {
  368. if (this._sysInfo) {
  369. return this._compareVersion(this._sysInfo.SDKVersion, "1.4.1") && PlatUtils.IsAndroid;
  370. }
  371. return false;
  372. }
  373. return false;
  374. }
  375. /**
  376. * 是否可以显示交叉推广按钮
  377. */
  378. public canShowRecommendButton() {
  379. if (PlatUtils.IsBaidu) {
  380. if (this._sysInfo) {
  381. return this._compareVersion(this._sysInfo.SDKVersion, "1.5.2") && PlatUtils.IsAndroid;
  382. }
  383. return false;
  384. }
  385. return false;
  386. }
  387. /**
  388. * 是否可以显示添加到我的小程序引导
  389. */
  390. public canShowFavoriteGuide() {
  391. if (PlatUtils.IsBaidu) {
  392. if (this._sysInfo) {
  393. return this._compareVersion(this._sysInfo.SDKVersion, "1.7.2");
  394. }
  395. return false;
  396. }
  397. return false;
  398. }
  399. _compareVersion(first: string, second: string) {
  400. return parseInt(first.split(".").join("")) >= parseInt(second.split(".").join(""));
  401. }
  402. /**
  403. * 跳转到指定的小游戏
  404. * @param pkgName 包名
  405. * @param callback Function(ret) 跳转回调. ret: true | false
  406. */
  407. public navigateToMiniGame(pkgName: string, callback: Function) {
  408. if (PlatUtils.IsBaidu) {
  409. let completeCallback: Function = callback;
  410. if (!pkgName) {
  411. utils.showLog("跳转ID为null");
  412. if (completeCallback) {
  413. completeCallback(false);
  414. }
  415. return;
  416. }
  417. this.swan.navigateToMiniProgram({
  418. appKey: pkgName,
  419. path: "",
  420. extraData: {},
  421. success: (res) => {
  422. utils.showLog("跳转成功!");
  423. if (completeCallback) {
  424. completeCallback(true);
  425. }
  426. },
  427. fail: (error) => {
  428. utils.showLog("跳转失败!");
  429. if (completeCallback) {
  430. completeCallback(false);
  431. }
  432. }
  433. });
  434. }
  435. }
  436. /**
  437. * 上报数据
  438. */
  439. public postData(otherGameAppId: string) {
  440. if (PlatUtils.IsBaidu) {
  441. let appid: string = utils.config.baiduconfig.appID;
  442. let uid: string = "0";
  443. let channel: string = "baidu";
  444. let method = "m=jump";
  445. let url: string = `${POST_ServerUrl} + ${method} + &app_id=${appid}&uid=${uid}&channel=${channel}&jump_app_id=${otherGameAppId}`;
  446. utils.showLog("上报数据, url=", url);
  447. utils.commomHttpRequest(url, (ret, data) => {
  448. if (ret) {
  449. utils.showLog("数据上报成功!");
  450. } else {
  451. utils.showLog("数据上报失败!");
  452. }
  453. });
  454. }
  455. }
  456. /**
  457. * 获取交叉推广数据
  458. */
  459. public getRecommondGameList() {
  460. if (PlatUtils.IsBaidu
  461. && utils.Tool_Baidu
  462. && utils.Tool_Baidu.ServerConfig) {
  463. return utils.Tool_Baidu.ServerConfig.jump_list;
  464. }
  465. return null;
  466. }
  467. /**
  468. * 上报关卡数据
  469. * @param level 当前关卡ID
  470. * @param levelName 关卡名称
  471. * @param status 状态
  472. */
  473. public postLevel(level: string, status: LevelStatus, levelName?: string) {
  474. if (PlatUtils.IsBaidu) {
  475. let method = "m=rlevel";
  476. let url: string = POST_ServerUrl + method + `&level_id=${level}&level_name=${encodeURI(levelName)}&status=${status}`;
  477. utils.commomHttpRequest(url, function (ret, data) {
  478. if (ret) {
  479. utils.showLog("关卡数据上报成功!");
  480. } else {
  481. utils.showLog("关卡数据上报失败!");
  482. }
  483. }.bind(this));
  484. }
  485. }
  486. /**
  487. * 上报自定义事件
  488. * @param level 当前关卡ID
  489. * @param levelName 关卡名称
  490. * @param status 状态
  491. */
  492. public sendEvent(eventName: string) {
  493. if (PlatUtils.IsBaidu) {
  494. let method = "m=revent";
  495. let url: string = POST_ServerUrl + method + `&event=${encodeURI(eventName)}`;
  496. utils.commomHttpRequest(url, function (ret, data) {
  497. if (ret) {
  498. utils.showLog("上报自定义事件成功!");
  499. } else {
  500. utils.showLog("上报自定义事件失败!");
  501. }
  502. }.bind(this));
  503. }
  504. }
  505. /**
  506. * 弹出提示框
  507. * @param msg 消息
  508. */
  509. public showToast(msg: string) {
  510. if (PlatUtils.IsBaidu) {
  511. //@ts-ignore
  512. swan.showToast({
  513. title: msg,
  514. icon: "none",
  515. duration: 2000,
  516. success(res) {
  517. console.log(`${res}`);
  518. },
  519. fail(res) {
  520. console.log(`showToast调用失败`);
  521. }
  522. });
  523. }
  524. }
  525. }