File size: 6,589 Bytes
0bfe2e3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import { AddonDetail, ParseResult, StreamRequest } from '@aiostreams/types';
import { ParsedStream, Config } from '@aiostreams/types';
import { BaseWrapper } from './base';
import { addonDetails, createLogger } from '@aiostreams/utils';
import { Settings } from '@aiostreams/utils';

const logger = createLogger('wrappers');

// name, title, url
export class Jackettio extends BaseWrapper {
  constructor(
    configString: string | null,
    overrideUrl: string | null,
    addonName: string = 'Jackettio',
    addonId: string,
    userConfig: Config,
    indexerTimeout?: number
  ) {
    let url = overrideUrl
      ? overrideUrl
      : Settings.JACKETTIO_URL + (configString ? configString + '/' : '');

    super(
      addonName,
      url,
      addonId,
      userConfig,
      indexerTimeout || Settings.DEFAULT_JACKETTIO_TIMEOUT,
      Settings.DEFAULT_JACKETTIO_USER_AGENT
        ? { 'User-Agent': Settings.DEFAULT_JACKETTIO_USER_AGENT }
        : undefined
    );
  }

  protected parseStream(stream: { [key: string]: any }): ParseResult {
    const parsedStream = super.parseStream(stream);
    if (stream.url && parsedStream.type === 'stream') {
      if (
        Settings.FORCE_JACKETTIO_HOSTNAME !== undefined ||
        Settings.FORCE_JACKETTIO_PORT !== undefined ||
        Settings.FORCE_JACKETTIO_PROTOCOL !== undefined
      ) {
        // modify the URL according to settings, needed when using a local URL for requests but a public stream URL is needed.
        const url = new URL(stream.url);

        if (Settings.FORCE_JACKETTIO_PROTOCOL !== undefined) {
          url.protocol = Settings.FORCE_JACKETTIO_PROTOCOL;
        }
        if (Settings.FORCE_JACKETTIO_PORT !== undefined) {
          url.port = Settings.FORCE_JACKETTIO_PORT.toString();
        }
        if (Settings.FORCE_JACKETTIO_HOSTNAME !== undefined) {
          url.hostname = Settings.FORCE_JACKETTIO_HOSTNAME;
        }
        parsedStream.result.url = url.toString();
      }
    }
    return parsedStream;
  }
}

const getJackettioConfigString = (
  debridService: string,
  debridApiKey: string
) => {
  return Buffer.from(
    JSON.stringify({
      maxTorrents: 30,
      priotizePackTorrents: 2,
      excludeKeywords: [],
      debridId: debridService,
      debridApiKey: debridApiKey,
      hideUncached: false,
      sortCached: [
        ['quality', true],
        ['size', true],
      ],
      sortUncached: [['seeders', true]],
      forceCacheNextEpisode: false,
      priotizeLanguages: [],
      indexerTimeoutSec: 60,
      metaLanguage: '',
      enableMediaFlow: false,
      mediaflowProxyUrl: '',
      mediaflowApiPassword: '',
      mediaflowPublicIp: '',
      useStremThru: true,
      stremthruUrl: Settings.DEFAULT_JACKETTIO_STREMTHRU_URL,
      qualities: [0, 360, 480, 720, 1080, 2160],
      indexers: Settings.DEFAULT_JACKETTIO_INDEXERS,
    })
  ).toString('base64');
};

export async function getJackettioStreams(
  config: Config,
  jackettioOptions: {
    prioritiseDebrid?: string;
    overrideUrl?: string;
    indexerTimeout?: string;
    overrideName?: string;
  },
  streamRequest: StreamRequest,
  addonId: string
): Promise<{
  addonStreams: ParsedStream[];
  addonErrors: string[];
}> {
  const supportedServices: string[] =
    addonDetails.find((addon: AddonDetail) => addon.id === 'jackettio')
      ?.supportedServices || [];
  const addonStreams: ParsedStream[] = [];

  const indexerTimeout = jackettioOptions.indexerTimeout
    ? parseInt(jackettioOptions.indexerTimeout)
    : undefined;

  // If overrideUrl is provided, use it to get streams and skip all other steps
  if (jackettioOptions.overrideUrl) {
    const jackettio = new Jackettio(
      null,
      jackettioOptions.overrideUrl as string,
      jackettioOptions.overrideName,
      addonId,
      config,
      indexerTimeout
    );
    return jackettio.getParsedStreams(streamRequest);
  }

  // find all usable and enabled services
  const usableServices = config.services.filter(
    (service) => supportedServices.includes(service.id) && service.enabled
  );

  // if no usable services found, throw an error
  if (usableServices.length < 1) {
    throw new Error('No supported service(s) enabled');
  }

  // otherwise, depending on the configuration, create multiple instances of jackettio or use a single instance with the prioritised service

  if (
    jackettioOptions.prioritiseDebrid &&
    !supportedServices.includes(jackettioOptions.prioritiseDebrid)
  ) {
    throw new Error('Invalid debrid service');
  }

  if (jackettioOptions.prioritiseDebrid) {
    const debridService = usableServices.find(
      (service) => service.id === jackettioOptions.prioritiseDebrid
    );
    if (!debridService) {
      throw new Error(
        'Debrid service not found for ' + jackettioOptions.prioritiseDebrid
      );
    }
    if (!debridService.credentials.apiKey) {
      throw new Error(
        'Debrid service API key not found for ' +
          jackettioOptions.prioritiseDebrid
      );
    }

    // get the jackettio config and b64 encode it

    const configString = getJackettioConfigString(
      debridService.id,
      debridService.credentials.apiKey
    );
    const jackettio = new Jackettio(
      configString,
      null,
      jackettioOptions.overrideName,
      addonId,
      config,
      indexerTimeout
    );

    return jackettio.getParsedStreams(streamRequest);
  }

  // if no prioritised service is provided, create a jackettio instance for each service
  const addonErrors: string[] = [];
  const servicesToUse = usableServices.filter((service) => service.enabled);
  if (servicesToUse.length < 1) {
    throw new Error('No supported service(s) enabled');
  }

  const streamPromises = servicesToUse.map(async (service) => {
    logger.info(`Getting Jackettio streams for ${service.name}`, {
      func: 'jackettio',
    });
    const configString = getJackettioConfigString(
      service.id,
      service.credentials.apiKey
    );
    const jackettio = new Jackettio(
      configString,
      null,
      jackettioOptions.overrideName,
      addonId,
      config,
      indexerTimeout
    );
    return jackettio.getParsedStreams(streamRequest);
  });

  const streamsArray = await Promise.allSettled(streamPromises);
  streamsArray.forEach((result) => {
    if (result.status === 'fulfilled') {
      addonStreams.push(...result.value.addonStreams);
      addonErrors.push(...result.value.addonErrors);
    } else {
      addonErrors.push(result.reason.message);
    }
  });

  return {
    addonStreams,
    addonErrors,
  };
}