File size: 8,196 Bytes
a8ed5f1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2c85231
a8ed5f1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
require("dotenv").config();
const express = require("express");
const app = express();
const { removeDuplicate } = require("./helper");
const UTILS = require("./utils");
const REGEX = {
  season_range:
    /S(?:(eason )|(easons )|(eason )|(easons )|(aisons )|(aison ))?(?<start>\d{1,2})\s*?(?:-|&|à|et)\s*?(?<end>\d{1,2})/, //start and end Sxx-xx|Season(s) xx-xx|Sxx à xx
  ep_range: /((?:e)|(?:ep))?(?: )?(?<start>\d{1,4})\s?(-|~)\s?(?<end>\d{1,4})/, //xxx-xxx
  ep_rangewithS:
    /((?:e)|(?:pisode))\s*(?<start>\d{1,3}(?!\d)|\d\d\d??)(?:-?e?(?<end>\d{1,3}))?(?!\d)/, //Exxx-xxx
};

let caches = {};
let lastCached = 0;

// ----------------------------------------------
app.get("/", (req, res) => {
  return res.status(200).send("okok");
});

app
  .get("/manifest.json", (req, res) => {
    res.setHeader("Access-Control-Allow-Origin", "*");
    res.setHeader("Access-Control-Allow-Headers", "*");
    res.setHeader("Content-Type", "application/json");

    //
    var json = {
      id: "hy.jackettrdos.stream",
      version: "2.0.0",
      name: "IPDay",
      description: "Movie & TV Streams",
      logo: "https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcT2Gs56d_rHcDEY6C6HFqjv113Br2Yc3IpU8A&s",
      resources: [
        {
          name: "stream",
          types: ["movie", "series", "anime"],
          idPrefixes: ["tt", "kitsu"],
        },
      ],
      types: ["movie", "series", "anime", "other"],
      catalogs: [],
    };

    return res.send(json);
  })
  .get("/stream/:type/:id", async (req, res) => {
    res.setHeader("Access-Control-Allow-Origin", "*");
    res.setHeader("Access-Control-Allow-Headers", "*");
    res.setHeader("Content-Type", "application/json");

    //
    media = req.params.type;
    let id = req.params.id;
    id = id.replace(".json", "");

    if (
      id in caches &&
      caches[id]?.length &&
      Date.now() < lastCached + 24 * 60 * 60 * 1000
    ) {
      console.log(`Returning results from cache: ${caches[id]?.length} found`);
      return res.send({ streams: caches[id] });
    }

    let tmp = [];

    if (
      id in caches &&
      caches[id]?.length &&
      Date.now() < lastCached + 24 * 60 * 60 * 1000
    ) {
      console.log(`Returning results from cache: ${caches[id]?.length} found`);
      return res.send({ streams: caches[id] });
    }

    if (id.includes("kitsu")) {
      tmp = await UTILS.getImdbFromKitsu(id);
      if (!tmp) {
        return res.send({ stream: {} });
      }
    } else {
      tmp = id.split(":");
    }

    let [tt, s, e, abs_season, abs_episode, abs] = tmp;

    console.log(tmp);

    let meta = await UTILS.getMeta(tt, media);

    console.log({ meta: id });
    console.log({ name: meta?.name, year: meta?.year });

    let query = "";
    query = meta?.name ?? "";

    let result = [];

    query = query.replace(/['<>:]/g, "");

    if (media == "movie") {
      query += " " + meta?.year;
      result = await UTILS.fetchTorrent2(encodeURIComponent(query), "movie");
    } else if (media == "series") {
      let promises = [
        UTILS.fetchTorrent2(
          encodeURIComponent(
            `${UTILS.simplifiedName(query)} S${(s ?? "1").padStart(2, "0")}`
          )
        ),
        UTILS.fetchTorrent2(
          encodeURIComponent(
            `${UTILS.simplifiedName(query)} Season ${s ?? "1"}`
          )
        ),
        UTILS.fetchTorrent2(
          encodeURIComponent(`${UTILS.simplifiedName(query)} Complet`)
        ),
        UTILS.fetchTorrent2(
          encodeURIComponent(
            `${UTILS.simplifiedName(query)} S${s?.padStart(
              2,
              "0"
            )}E${e?.padStart(2, "0")}`
          )
        ),
      ];

      if (+s == 1) {
        promises.push(
          UTILS.fetchTorrent2(
            encodeURIComponent(
              `${UTILS.simplifiedName(query)} ${e?.padStart(2, "0")}`
            )
          )
        );
      }

      if (abs) {
        promises.push(
          UTILS.fetchTorrent2(
            encodeURIComponent(
              `${UTILS.simplifiedName(query)} ${abs_episode?.padStart(2, "0")}`
            )
          )
        );
        promises.push(
          UTILS.fetchTorrent2(
            encodeURIComponent(
              `${UTILS.simplifiedName(query)} ${abs_episode?.padStart(3, "0")}`
            )
          )
        );
      }

      result = await Promise.all(promises);

      result = result.reduce((resArr, curr) => {
        if (curr) {
          resArr = [...resArr, ...curr];
        }
        return resArr;
      }, []);
    }

    result = removeDuplicate(result, "Title");

    // ------------------------------- FOR RANGE THINGS ---------------------------------------------

    let matches = [];

    for (const key in result) {
      const element = result[key];

      let r = new RegExp(REGEX.season_range, "gmi");
      let match = r.exec(element["Title"]);
      if (match && match["groups"] != null) {
        if (
          ![match["groups"]["start"], match["groups"]["end"]].includes(
            meta?.year
          )
        ) {
          if (s >= +match["groups"]["start"] && s <= +match["groups"]["end"]) {
            matches.push(result[key]);
            result.splice(key, 1);
            continue;
          }
        }
      }

      r = new RegExp(REGEX.ep_range, "gmi");
      match = r.exec(element["Title"]);

      if (match && match["groups"] != null) {
        if (
          ![match["groups"]["start"], match["groups"]["end"]].includes(
            meta?.year
          )
        ) {
          if (
            abs_episode >= +match["groups"]["start"] &&
            abs_episode <= +match["groups"]["end"]
          ) {
            matches.push(result[key]);
            result.splice(key, 1);
          }
        }
      }
    }

    console.log({ matches: matches.map((el) => el["Title"]) });

    result = [...matches, ...result];
    result.sort((a, b) => {
      return -(+a["Peers"] - +b["Peers"]) ?? 0;
    });

    console.log({ "Retenus for filtering": result.length });

    const MAX_RES = process.env.MAX_RES ?? 20;
    result = result?.length >= MAX_RES ? result.splice(0, MAX_RES) : result;

    // ----------------------------------------------------------------------------

    result = (result ?? []).filter(
      (torrent) =>
        (torrent["MagnetUri"] != "" || torrent["Link"] != "") &&
        torrent["Peers"] >= 0
    );

    console.log({ "Result after removing low peers items": result.length });

    let torrentParsed = await Promise.all(
      result.map((torrent) =>
        UTILS.getParsedFromMagnetorTorrentFile(
          torrent,
          torrent["MagnetUri"] || torrent["Link"]
        )
      )
    );
    console.log({
      "After parsing (non parsed included)": torrentParsed.length,
    });

    // engine ? engine.destroy() : null;

    torrentParsed = torrentParsed.filter(
      (torrent) =>
        torrent &&
        torrent?.parsedTor != null &&
        torrent?.parsedTor?.files?.length > 0
    );

    console.log({ "Parsed torrents": torrentParsed.length });

    let stream_results = await Promise.all(
      torrentParsed.map((torrent) =>
        UTILS.toStream(
          torrent,
          media,
          s,
          e,
          abs_season,
          abs_episode,
          abs,
          torrentParsed.length
        )
      )
    );

    stream_results = Array.from(new Set(stream_results)).filter((e) => !!e);

    stream_results = [
      ...UTILS.filterBasedOnQuality(stream_results, UTILS.qualities["4k"]),
      ...UTILS.filterBasedOnQuality(stream_results, UTILS.qualities.fhd),
      ...UTILS.filterBasedOnQuality(stream_results, UTILS.qualities.hd),
      ...UTILS.filterBasedOnQuality(stream_results, UTILS.qualities.sd),
      ...UTILS.filterBasedOnQuality(stream_results, UTILS.qualities.unknown),
    ];

    if (stream_results.length) {
      caches[id] = stream_results;
      lastCached = Date.now();
    }
    nbreAdded = 0;
    console.log({ Final: stream_results.length });

    return res.send({ streams: stream_results });
  })
  .listen(process.env.PORT || 3000, () => {
    console.log("The server is working on " + process.env.PORT || 3000);
  });