-
Notifications
You must be signed in to change notification settings - Fork 1
/
script.js
383 lines (316 loc) · 12.8 KB
/
script.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
function scrollToTop() {
const c = document.documentElement.scrollTop || document.body.scrollTop;
if (c > 0) {
window.requestAnimationFrame(scrollToTop);
window.scrollTo(0, c - c / 8);
}
}
const htmlBody = document.querySelector("html, body");
const results = document.querySelector("#results");
const scrollToResults = () => {
const resultsTop = results.offsetTop;
htmlBody.scrollTo({
top: resultsTop,
behavior: "smooth",
});
};
const searchInput = document.getElementById("search-input");
const searchButton = document.getElementById("search-button");
const resultsContainer = document.getElementById("results");
const corsProxy = "https://corsproxy.io/?";
// functions that manipulates the queries of url to get a low resolution image to increase page speed
function optimisedImageUrl(url) {
return url.replace("._V1_.", "._V1_QL75_UX160_.");
}
// Fetch and Show Cards
function fetchAndShow() {
const query = encodeURIComponent(searchInput.value);
const url = `${corsProxy}https://v3.sg.media-imdb.com/suggestion/x/${query}.json`;
Pace.restart();
fetch(url)
.then((response) => response.json())
.then((data) => {
const results = data.d;
resultsContainer.innerHTML = "";
results.forEach((result) => {
if (result.i && (result.qid === "movie" || result.qid === "tvSeries")) {
const resultElem = document.createElement("div");
resultElem.classList.add("result");
resultElem.setAttribute("IMDB", result.id);
let imageAndInfo = "";
if (result.qid === "movie" && result.i) {
imageAndInfo = `<a onClick="setUrl(this); return setVideo(this);" url="imdb=${result.id}&type=movie&title=${result.l.replace(/ /g, "_")}" isWebSeries="false" title="${result.l}" class="links" IMDB="${result.id}" href="https://multiembed.mov/directstream.php?video_id=${result.id}" target="_blank">
<img alt="${result.l}" src="${optimisedImageUrl(result.i.imageUrl)}">
<div class="info">
<h3>${result.l}</h3>
<p>${result.s}</p>
</div>
</a>`;
} else if (result.qid === "tvSeries" && result.i) {
imageAndInfo = `<a onClick="setUrl(this); return setVideo(this);" url="imdb=${result.id}&season=1&episode=1&title=${result.l.replace(/ /g, "_")}" IMDB="${result.id}" title="${result.l}" isWebSeries="true" class="links" href="https://multiembed.mov/directstream.php?video_id=${result.id}&s=1&e=1" target="_blank">
<img alt="${result.l}" src="${optimisedImageUrl(result.i.imageUrl)}">
<div class="info">
<h3>${result.l}</h3>
<p>${result.s}</p>
</div>
</a>`;
}
resultElem.innerHTML = imageAndInfo;
resultsContainer.appendChild(resultElem);
}
});
});
}
// A function which will set the player url and page url by imitating a anchor tag click
function setAll(imdb, title, season, episode, type) {
if (imdb && title && !season && !episode && type) {
let a = document.createElement("a");
a.setAttribute("onClick", "setUrl(this); return setVideo(this);");
a.setAttribute(
"url",
`imdb=${imdb}&type=movie&title=${title.replace(/ /g, "_")}`
);
a.setAttribute("isWebSeries", "false");
a.setAttribute("title", title);
a.setAttribute("class", "links");
a.setAttribute("IMDB", imdb);
a.setAttribute("href", " https://multiembed.mov/directstream.php?video_id=" + imdb);
a.setAttribute("target", "_blank");
a.click();
} else if (imdb && title && episode && !type) {
// let formatedEpisodeNumber = (episode).toLocaleString('en-US', { minimumIntegerDigits: 2, useGrouping: false });
let a = document.createElement("a");
a.setAttribute("onClick", "setUrl(this); return setVideo(this);");
console.log("season setall", season, "episode", episode);
a.setAttribute("url", `imdb=${imdb}&season=${season}&episode=${episode}`);
a.setAttribute("isWebSeries", "true");
a.setAttribute("title", title);
a.setAttribute("class", "links");
a.setAttribute("IMDB", imdb);
a.setAttribute(
"href",
`https://multiembed.mov/directstream.php?video_id=${imdb}&s=${season}&e=${episode}`
);
a.setAttribute("target", "_blank");
a.click();
}
}
// fetch titile of movie/webseries by its imdb id
const fetchTitle = async (imdbID) => {
const url = `${corsProxy}https://v3.sg.media-imdb.com/suggestion/x/${imdbID}.json`;
try {
const response = await fetch(url);
const data = await response.json();
const title = data.d[0].l;
return title;
} catch (error) {
console.error(error);
}
};
// set url of element by getting its custom url attirbute
function setUrl(element) {
let search = element.getAttribute("url");
window.history.replaceState({}, "", `?${search.replace(/%20/g, "+")}`);
}
// insert search query in search box from url and set contents from url
function fillSearchInput() {
let searchParams = new URLSearchParams(window.location.search);
let search = searchParams.get("search");
let season = searchParams.get("season");
let episode = searchParams.get("episode");
let imdb = searchParams.get("imdb");
let type = searchParams.get("type");
// It will set search query in search box from url
if (search && !season && !episode && !imdb) {
search = search.replace(/\+/g, "%20");
const searchInput = document.querySelector("#search-input");
searchInput.value = search;
fetchAndShow();
}
// It will set the contents according to url data
else if (imdb && type && !search && !episode && !season) {
fetchTitle(imdb)
.then((title) => setAll(imdb, title, season, episode, type))
.catch((error) => console.error(error));
// It will set the contents according to url data
} else if (imdb && !search && episode && season) {
console.log("season", season, "episode", episode);
fetchTitle(imdb)
.then((title) => setAll(imdb, title, season, episode, type))
.catch((error) => console.error(error));
console.log("season", season, "episode", episode);
}
}
fillSearchInput();
// update url by search query
function updateURL(input) {
let search = input.value;
if (search) {
window.history.replaceState(
{},
"",
`?search=${encodeURIComponent(search).replace(/%20/g, "+")}`
);
} else {
window.history.replaceState({}, "", window.location.pathname);
}
}
// Highlighting Selected Card
function highlightCards() {
let searchParams = new URLSearchParams(window.location.search);
let imdb_id = searchParams.get("imdb");
try {
document.querySelectorAll(".result").forEach(function (card) {
card.className = "result";
});
document.querySelector(`div[IMDB=${imdb_id}]`).className =
"result hoverClass";
} catch (error) {
// will throw error only if the class is not present
}
}
// Listen for the onpopstate event and update the display of elements with the class "information"
window.onpopstate = function () {
let searchParams = new URLSearchParams(window.location.search);
let search = searchParams.get("search");
let imdb = searchParams.get("imdb");
if (search || imdb) {
let elements = document.getElementsByClassName("information");
for (let i = 0; i < elements.length; i++) {
elements[i].style.display = "none";
}
} else {
let elements = document.getElementsByClassName("information");
for (let i = 0; i < elements.length; i++) {
elements[i].style.display = "block";
}
}
};
// auto search by input which will execute when user stops typing for 500ms
let timer;
searchInput.addEventListener("keyup", function () {
let inputQuery = this;
clearTimeout(timer);
timer = setTimeout(function () {
updateURL(inputQuery);
fetchAndShow();
window.dispatchEvent(new PopStateEvent("popstate"));
scrollToResults();
}, 500); // wait for 500ms before executing the function
});
// button click search
searchButton.addEventListener("click", function () {
fetchAndShow();
scrollToResults();
// hide information
window.dispatchEvent(new PopStateEvent("popstate"));
});
// higlight episodes of webseries
function episodeHighlight(cssidentification = "s1e1") {
document.querySelectorAll(".episodes").forEach(function (episode) {
episode.className = "episodes";
});
document.querySelector(
`.episodes[cssidentification='${cssidentification}']`
).className = "episodes selected";
}
// Do multiple tasks on anchor tag click
function setVideo(element) {
const iframe = document.getElementById("iframe");
const video = document.getElementById("video");
iframe.src = element.getAttribute("href");
video.style.display = "block";
const webSeriesData = document.getElementById("webSeriesData");
const tmdbApiKey = "b6b677eb7d4ec17f700e3d4dfc31d005";
const imdbID = element.getAttribute("IMDB");
Pace.restart();
scrollToTop();
// hide information
window.dispatchEvent(new PopStateEvent("popstate"));
// clearing episodes list box for another series
if (
element.getAttribute("isWebSeries") == "false" &&
element.className == "links"
) {
webSeriesData.innerHTML = "";
}
// setting page title
if (element.getAttribute("title") !== "") {
document.title = element.getAttribute("title");
}
// highlight selected webseries episode
if (element.className.includes("episode")) {
episodeHighlight(element.getAttribute("cssidentification"));
console.log("clicked");
}
// Displaying webseries episode
if (element.getAttribute("isWebSeries") == "true") {
webSeriesData.innerHTML = "";
async function printEpisodes() {
// First, get the show's TMDB id based on its IMDb id
const response = await fetch(
`https://api.themoviedb.org/3/find/${imdbID}?api_key=${tmdbApiKey}&language=en-US&external_source=imdb_id`
);
const data = await response.json();
const showId = data.tv_results[0].id;
// Next, get information about the show's seasons
const seasonsData = await fetch(
`https://api.themoviedb.org/3/tv/${showId}?api_key=${tmdbApiKey}&language=en-US`
);
const seasonsDataJSON = await seasonsData.json();
const numberOfSeasons = seasonsDataJSON.number_of_seasons;
webSeriesData.innerHTML += `<h2>Seasons:</h2>`;
for (
let seasonNumber = 1;
seasonNumber <= numberOfSeasons;
seasonNumber++
) {
webSeriesData.innerHTML += `<h3>Season ${seasonNumber}:</h3><br>`;
let episodeContainer = document.createElement("div");
episodeContainer.classList.add("episode-container");
let episodesData = "";
// Get information about episodes in the season
const episodesDataResponse = await fetch(
`https://api.themoviedb.org/3/tv/${showId}/season/${seasonNumber}?api_key=${tmdbApiKey}&language=en-US`
);
const episodesDataJSON = await episodesDataResponse.json();
for (const episode of episodesDataJSON.episodes) {
const episodeNumber = episode.episode_number;
let formatedEpisodeNumber = episodeNumber.toLocaleString("en-US", {
minimumIntegerDigits: 2,
useGrouping: false,
});
episodesData += `<a class="episodes" title="${seasonsDataJSON.name + ": E" + formatedEpisodeNumber + ". " + episode.name}" cssidentification="s${seasonNumber}e${episodeNumber}" url="imdb=${imdbID}&season=${seasonNumber}&episode=${episodeNumber}&title=${seasonsDataJSON.name.replace(/ /g, "_") + "_E" + formatedEpisodeNumber + "_" + episode.name.replace(/ /g, "_")}" onClick="event.preventDefault();setVideo(this);setUrl(this); " href="https://multiembed.mov/directstream.php?video_id=${imdbID}&s=${seasonNumber}&e=${episodeNumber}">E${formatedEpisodeNumber}. ${episode.name}</a>`;
}
episodeContainer.innerHTML = episodesData;
webSeriesData.appendChild(episodeContainer);
episodeHighlight();
}
// Highlighting Selected Episodes as per url
let searchParams = new URLSearchParams(window.location.search);
let season = searchParams.get("season");
let episode = searchParams.get("episode");
if (season && episode) {
document
.querySelector(`a[cssIdentification="s${season}e${episode}"]`)
.click();
} else if (season && !episode) {
document.querySelector(`a[cssIdentification="s${season}e1"]`).click();
} else {
document.querySelector(`a[cssIdentification="s1e1"]`).click();
}
}
printEpisodes();
} else {
}
// pushing data to analytics by gtag
window.dataLayer = window.dataLayer || [];
function gtag() {
dataLayer.push(arguments);
}
gtag("js", new Date());
gtag("config", "G-THTQ9GZQ0J");
highlightCards();
// returning false so that anchor tag do not work as link
return false;
}