main.js 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333
  1. class Home {
  2. static start() {
  3. this.cache = {
  4. items: undefined,
  5. item: new Map(),
  6. };
  7. this.config = new Config();
  8. this.itemQuery = this.config.itemQuery;
  9. this.coverOptions = { type: "Backdrop", maxWidth: 3000 };
  10. this.logoOptions = { type: "Logo", maxWidth: 3000 };
  11. // this.initStart = false;
  12. let isStatic = 2;
  13. let isLoad = true;
  14. this.HomeInterval = setInterval(() => {
  15. if (window.ApiClient != undefined) { //获取ApiClientuserView
  16. if (ApiClient._userViewsPromise != null) {
  17. ApiClient._userViewsPromise.then(vlaue => {
  18. let itemId = new Array();
  19. vlaue.Items.forEach(item => { itemId.push(item.Id) });
  20. this.config.parentIds = this.config.parentIds.filter(value => itemId.includes(value));
  21. //this.initStart = false;
  22. isStatic = isStatic & 1;
  23. if (this.config.parentIds.length !== 0) {
  24. isStatic = isStatic | 1;
  25. } else {
  26. clearInterval(this.HomeInterval);
  27. isLoad = false;
  28. $(".misty-loading").fadeOut(5, () => $(".misty-loading").remove());
  29. }
  30. });
  31. }
  32. }
  33. if (window.location.href.indexOf("!/home") != -1) {
  34. if ($(".view:not(.hide) .misty-banner").length == 0 && $(".misty-loading").length == 0) {
  35. //this.initStart = false; //0
  36. isStatic = isStatic & 1;
  37. if (isLoad) { this.initLoading(); }
  38. }
  39. if (window.ApiClient == undefined) {
  40. //this.initStart = true; //1
  41. isStatic = isStatic | 2;
  42. }
  43. if (isStatic & 1 == 1 && $(".hide .misty-banner").length != 0) { //1
  44. $(".hide .misty-banner").remove();
  45. }
  46. if (isStatic == 1 && $(".section0 .card").length != 0 && $(".view:not(.hide) .misty-banner").length == 0) {
  47. //this.initStart = true; //1 1
  48. isStatic = isStatic | 2;
  49. this.init();
  50. }
  51. } else {
  52. if ($(".misty-loading").length == 1) {
  53. $(".misty-loading").fadeOut(5, () => $(".misty-loading").remove());
  54. }
  55. }
  56. }, 233);
  57. }
  58. static async init() {
  59. // Beta
  60. $(".view:not(.hide)").attr("data-type", "home");
  61. // Loading
  62. const serverName = await this.injectCall("serverName", "");
  63. $(".misty-loading h1").text(serverName).addClass("active");
  64. // Banner
  65. await this.initBanner();
  66. this.initEvent();
  67. }
  68. /* 插入Loading */
  69. static initLoading() {
  70. const load = `
  71. <div class="misty-loading">
  72. <h1></h1>
  73. <div class="mdl-spinner"><div class="mdl-spinner__layer mdl-spinner__layer-1"><div class="mdl-spinner__circle-clipper mdl-spinner__left"><div class="mdl-spinner__circle mdl-spinner__circleLeft"></div></div><div class="mdl-spinner__circle-clipper mdl-spinner__right"><div class="mdl-spinner__circle mdl-spinner__circleRight"></div></div></div></div>
  74. </div>
  75. `;
  76. $("body").append(load);
  77. }
  78. static injectCode(code) {
  79. let hash = md5(code + Math.random().toString());
  80. return new Promise((resolve, reject) => {
  81. if ("BroadcastChannel" in window) {
  82. const channel = new BroadcastChannel(hash);
  83. channel.addEventListener("message", (event) => resolve(event.data));
  84. } else if ("postMessage" in window) {
  85. window.addEventListener("message", (event) => {
  86. if (event.data.channel === hash) {
  87. resolve(event.data.message);
  88. }
  89. });
  90. }
  91. const script = `
  92. <script class="I${hash}">
  93. setTimeout(async ()=> {
  94. async function R${hash}(){${code}};
  95. if ("BroadcastChannel" in window) {
  96. const channel = new BroadcastChannel("${hash}");
  97. channel.postMessage(await R${hash}());
  98. } else if ('postMessage' in window) {
  99. window.parent.postMessage({channel:"${hash}",message:await R${hash}()}, "*");
  100. }
  101. document.querySelector("script.I${hash}").remove()
  102. }, 16)
  103. </script>
  104. `;
  105. $(document.head || document.documentElement).append(script);
  106. });
  107. }
  108. static injectCall(func, arg) {
  109. const script = `
  110. // const client = (await window.require(["ApiClient"]))[0];
  111. const client = await new Promise((resolve, reject) => {
  112. setInterval(() => {
  113. if (window.ApiClient != undefined) resolve(window.ApiClient);
  114. }, 16);
  115. });
  116. return await client.${func}(${arg})
  117. `;
  118. return this.injectCode(script);
  119. }
  120. static getItems(query) {
  121. //由于要合并多个媒体库所以放弃做临时缓存
  122. //if (this.cache.items == undefined) {
  123. // this.cache.items = this.injectCall("getItems", "client.getCurrentUserId(), " + JSON.stringify(query));
  124. //}
  125. //return this.cache.items;
  126. return this.injectCall("getItems", "client.getCurrentUserId(), " + JSON.stringify(query));
  127. }
  128. static itemsRandom(array) {
  129. let res = [], random;
  130. while (array.length > 0) {
  131. random = Math.floor(Math.random() * array.length);
  132. res.push(array[random]);
  133. array.splice(random, 1);
  134. }
  135. return res;
  136. }
  137. static async getItem(itemId) {
  138. // 双缓存 优先使用 WebStorage
  139. if (typeof Storage !== "undefined" && !localStorage.getItem("CACHE|" + itemId) && !this.cache.item.has(itemId)) {
  140. const data = JSON.stringify(await this.injectCall("getItem", `client.getCurrentUserId(), "${itemId}"`));
  141. if (typeof Storage !== "undefined") localStorage.setItem("CACHE|" + itemId, data);
  142. else this.cache.item.set(itemId, data);
  143. }
  144. return JSON.parse(typeof Storage !== "undefined" ? localStorage.getItem("CACHE|" + itemId) : this.cache.item.get(itemId));
  145. }
  146. static getImageUrl(itemId, options) {
  147. return this.injectCall("getImageUrl", itemId + ", " + JSON.stringify(options));
  148. }
  149. static async appendItem(i) {
  150. const detail = await this.getItem(this.data.Items[i].Id),
  151. itemHtml = `
  152. <div class="misty-banner-item" id="${detail.Id}">
  153. <img draggable="false" loading="eager" decoding="async" class="misty-banner-cover" src="${await this.getImageUrl(detail.Id, this.coverOptions)}" alt="Backdrop" style="">
  154. <div class="misty-banner-info padded-left padded-right">
  155. <h1>${detail.Name}</h1>
  156. <div><p>${detail.Overview}</p></div>
  157. <div><button onclick="appRouter.showItem('${detail.Id}')">MORE</button></div>
  158. </div>
  159. </div>
  160. `,
  161. logoHtml = `
  162. <img id="${detail.Id}" draggable="false" loading="auto" decoding="lazy" class="misty-banner-logo" data-banner="img-title" alt="Logo" src="${await this.getImageUrl(detail.Id, this.logoOptions)}">
  163. `;
  164. if (detail.ImageTags && detail.ImageTags.Logo) {
  165. $(".misty-banner-logos").append(logoHtml);
  166. }
  167. $(".misty-banner-body").append(itemHtml);
  168. console.log(this.data.Items[i].Id, detail);
  169. }
  170. static async bannerRoll() {
  171. if (!window.location.href.endsWith("home")) {
  172. return;
  173. }
  174. // 背景切换
  175. this.index += this.index + 1 == $(".misty-banner-item").length ? -this.index : 1;
  176. //已经切换到最后且总数大于10
  177. if (this.index == 0 && this.data.Items.length >= 10) {
  178. clearInterval(this.bannerInterval);
  179. let l = $(".misty-banner-item").length;
  180. //剩余小于10张直接舍弃,从头开始
  181. if (this.count + 1 == this.data.Items.length || this.data.Items.length - this.count - 1 < 10)
  182. this.count = -1;
  183. //向后添加,剩余10张以上添加10张
  184. for (let i = this.count + 1; i < this.count + 1 + (this.data.Items.length - this.count - 1 < 10 ? this.data.Items.length - this.count - 1 : 10); i++) {
  185. await this.appendItem(i)
  186. }
  187. //切换到第一张
  188. $(".misty-banner-body").css("left", "0%");
  189. $(".misty-banner-item.active").removeClass("active");
  190. let id = $(".misty-banner-item").eq(l).addClass("active").attr("id");
  191. $(".misty-banner-logo.active").removeClass("active");
  192. $(`.misty-banner-logo[id=${id}]`).addClass("active");
  193. //从dom中移除上一轮次的横幅
  194. for (let i = 0; i < l; i++) {
  195. $(".misty-banner-item").eq(0).remove();
  196. }
  197. this.bannerInterval = setInterval(this.bannerRoll.bind(this), this.config.interval);
  198. } else {
  199. $(".misty-banner-body").css("left", -(this.index * 100).toString() + "%");
  200. // 信息切换
  201. $(".misty-banner-item.active").removeClass("active");
  202. let id = $(".misty-banner-item").eq(this.index).addClass("active").attr("id");
  203. // LOGO切换
  204. $(".misty-banner-logo.active").removeClass("active");
  205. $(`.misty-banner-logo[id=${id}]`).addClass("active");
  206. }
  207. this.count++;
  208. }
  209. /* 插入Banner */
  210. static async initBanner() {
  211. const banner = `
  212. <div class="misty-banner">
  213. <div class="misty-banner-body">
  214. </div>
  215. <div class="misty-banner-library">
  216. <div class="misty-banner-logos"></div>
  217. </div>
  218. </div>
  219. `;
  220. $(".view:not(.hide) .homeSectionsContainer").prepend(banner);
  221. // $(".view:not(.hide) .section0").detach().appendTo(".view:not(.hide) .misty-banner-library");
  222. // 插入数据
  223. this.data = { Items: [] }
  224. //配置的媒体库不为空
  225. if (this.config.parentIds[0] != "") {
  226. console.log(this.config.parentIds);
  227. //合并所有配置的媒体库的结果
  228. for (let parentId of this.config.parentIds) {
  229. this.itemQuery.ParentId = parentId;
  230. let res = await this.getItems(this.itemQuery);
  231. this.data.Items = this.data.Items.concat(res.Items);
  232. }
  233. } else {
  234. //查询所有媒体库
  235. this.itemQuery = { ImageTypes: "Backdrop", EnableImageTypes: "Logo,Backdrop", IncludeItemTypes: "Movie,Series", SortBy: "ProductionYear, PremiereDate, SortName", Recursive: true, ImageTypeLimit: 1, Limit: 10, Fields: "ProductionYear", SortOrder: "Descending", EnableUserData: false, EnableTotalRecordCount: false };
  236. this.data = await this.getItems(this.itemQuery);
  237. }
  238. console.log(this.data);
  239. if (this.config.random == true) {
  240. this.data.Items = this.itemsRandom(this.data.Items);
  241. }
  242. //大于10时添加10张
  243. for (let i = 0; i < (this.data.Items.length < 10 ? this.data.Items.length : 10); i++) {
  244. await this.appendItem(i)
  245. }
  246. // 只判断第一张海报加载完毕, 优化加载速度
  247. await new Promise((resolve, reject) => {
  248. let waitLoading = setInterval(() => {
  249. if (document.querySelector(".misty-banner-cover")?.complete) {
  250. clearInterval(waitLoading);
  251. resolve();
  252. }
  253. }, 16);
  254. });
  255. // 判断section0加载完毕
  256. await new Promise((resolve, reject) => {
  257. let waitsection0 = setInterval(() => {
  258. if ($(".view:not(.hide) .section0 .emby-scrollbuttons").length > 0 && $(".view:not(.hide) .section0.hide").length == 0) {
  259. clearInterval(waitsection0);
  260. resolve();
  261. }
  262. }, 16);
  263. });
  264. $(".view:not(.hide) .section0 .emby-scrollbuttons").remove();
  265. const items = $(".view:not(.hide) .section0 .emby-scroller .itemsContainer")[0].items;
  266. if (CommonUtils.checkType() === 'pc') {
  267. $(".view:not(.hide) .section0").detach().appendTo(".view:not(.hide) .misty-banner-library");
  268. }
  269. $(".misty-loading").fadeOut(500, () => $(".misty-loading").remove());
  270. await CommonUtils.sleep(150);
  271. $(".view:not(.hide) .section0 .emby-scroller .itemsContainer")[0].items = items;
  272. // 置入场动画
  273. let delay = 80; // 动媒体库画间隔
  274. let id = $(".misty-banner-item").eq(0).addClass("active").attr("id"); // 初次信息动画
  275. $(`.misty-banner-logo[id=${id}]`).addClass("active");
  276. await CommonUtils.sleep(200); // 间隔动画
  277. $(".section0 > div").addClass("misty-banner-library-overflow"); // 关闭overflow 防止媒体库动画溢出
  278. $(".misty-banner .card").each((i, dom) => setTimeout(() => $(dom).addClass("misty-banner-library-show"), i * delay)); // 媒体库动画
  279. await CommonUtils.sleep(delay * 8 + 1000); // 等待媒体库动画完毕
  280. $(".section0 > div").removeClass("misty-banner-library-overflow"); // 开启overflow 防止无法滚动
  281. // 滚屏逻辑
  282. this.index = 0; this.count = 0;
  283. clearInterval(this.bannerInterval);
  284. this.bannerInterval = setInterval(this.bannerRoll.bind(this), this.config.interval);
  285. }
  286. /* 初始事件 */
  287. static initEvent() {
  288. // 通过注入方式, 方可调用appRouter函数, 以解决Content-Script window对象不同步问题
  289. const script = `
  290. // 挂载appRouter
  291. if (!window.appRouter) window.appRouter = (await window.require(["appRouter"]))[0];
  292. /* // 修复library事件参数
  293. const serverId = ApiClient._serverInfo.Id,
  294. librarys = document.querySelectorAll(".view:not(.hide) .section0 .card");
  295. librarys.forEach(library => {
  296. library.setAttribute("data-serverid", serverId);
  297. library.setAttribute("data-type", "CollectionFolder");
  298. }); */
  299. `;
  300. this.injectCode(script);
  301. }
  302. }
  303. // 运行
  304. if ("BroadcastChannel" in window || "postMessage" in window) {
  305. if ($("meta[name=application-name]").attr("content") == "Emby" || $(".accent-emby") != undefined) {
  306. Home.start();
  307. }
  308. }