File size: 5,979 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
import { Config } from '@aiostreams/types';
import path from 'path';
import { Settings } from './settings';
import { getTextHash } from './crypto';
import { Cache } from './cache';
import { createLogger, maskSensitiveInfo } from './logger';

const logger = createLogger('mediaflow');

const cache = Cache.getInstance<string, string>('publicIp');
const PRIVATE_CIDR = /^(10\.|127\.|172\.(1[6-9]|2[0-9]|3[01])\.|192\.168\.)/;

export async function generateMediaFlowStreams(
  mediaFlowConfig: Config['mediaFlowConfig'],
  streams: {
    url: string;
    filename?: string;
    headers?: {
      request?: Record<string, string>;
      response?: Record<string, string>;
    };
  }[]
): Promise<string[] | null> {
  if (!streams.length) {
    return [];
  }
  if (!mediaFlowConfig) {
    throw new Error('MediaFlow configuration is missing');
  }
  const proxyUrl = new URL(mediaFlowConfig.proxyUrl.replace(/\/$/, ''));
  const generateUrlsEndpoint = '/generate_urls';
  proxyUrl.pathname = `${proxyUrl.pathname === '/' ? '' : proxyUrl.pathname}${generateUrlsEndpoint}`;

  const data = {
    mediaflow_proxy_url: mediaFlowConfig.proxyUrl.replace(/\/$/, ''),
    api_password: Settings.ENCRYPT_MEDIAFLOW_URLS
      ? mediaFlowConfig.apiPassword
      : undefined,
    urls: streams.map((stream) => {
      return {
        endpoint: '/proxy/stream',
        filename: stream.filename || path.basename(stream.url),
        query_params: Settings.ENCRYPT_MEDIAFLOW_URLS
          ? undefined
          : {
              api_password: mediaFlowConfig.apiPassword,
            },
        destination_url: stream.url,
        request_headers: stream.headers?.request,
        response_headers: stream.headers?.response,
      };
    }),
  };

  try {
    if (Settings.LOG_SENSITIVE_INFO) {
      logger.debug(`POST ${proxyUrl.toString()}`);
    } else {
      logger.debug(
        `POST ${proxyUrl.protocol}://${maskSensitiveInfo(proxyUrl.hostname)}${proxyUrl.port ? `:${proxyUrl.port}` : ''}/${generateUrlsEndpoint}`
      );
    }
    const response = await fetch(proxyUrl.toString(), {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify(data),
      signal: AbortSignal.timeout(Settings.MEDIAFLOW_IP_TIMEOUT),
    });
    if (!response.ok) {
      throw new Error(`${response.status}: ${response.statusText}`);
    }

    let responseData: any;
    try {
      responseData = await response.json();
    } catch (error) {
      const text = await response.text();
      logger.debug(`Response body: ${text}`);
      throw new Error('Failed to parse JSON response from MediaFlow');
    }

    if (responseData.error) {
      throw new Error(responseData.error);
    }
    if (responseData.urls) {
      return responseData.urls;
    } else {
      throw new Error('No URLs were returned from MediaFlow');
    }
  } catch (error) {
    logger.error(
      `Failed to generate MediaFlow URLs using request to ${maskSensitiveInfo(proxyUrl.toString())}: ${error}`
    );
    return null;
  }
}

export async function getMediaFlowPublicIp(
  mediaFlowConfig: Config['mediaFlowConfig']
) {
  try {
    if (!mediaFlowConfig) {
      logger.error('mediaFlowConfig is missing');
      throw new Error('MediaFlow configuration is missing');
    }

    if (!mediaFlowConfig?.proxyUrl) {
      logger.error('mediaFlowUrl is missing');
      throw new Error('MediaFlow URL is missing');
    }

    if (mediaFlowConfig.publicIp) {
      return mediaFlowConfig.publicIp;
    }

    const mediaFlowUrl = new URL(mediaFlowConfig.proxyUrl.replace(/\/$/, ''));
    if (PRIVATE_CIDR.test(mediaFlowUrl.hostname)) {
      // MediaFlow proxy URL is a private IP address
      logger.error(
        'MediaFlow proxy URL is a private IP address so returning null'
      );
      return null;
    }

    const cacheKey = getTextHash(
      `mediaFlowPublicIp:${mediaFlowConfig.proxyUrl}:${mediaFlowConfig.apiPassword}`
    );
    const cachedPublicIp = cache ? cache.get(cacheKey) : null;
    if (cachedPublicIp) {
      logger.debug(`Returning cached public IP`);
      return cachedPublicIp;
    }

    const proxyIpUrl = mediaFlowUrl;
    const proxyIpPath = '/proxy/ip';
    proxyIpUrl.pathname = `${proxyIpUrl.pathname === '/' ? '' : proxyIpUrl.pathname}${proxyIpPath}`;
    proxyIpUrl.search = new URLSearchParams({
      api_password: mediaFlowConfig.apiPassword,
    }).toString();

    if (Settings.LOG_SENSITIVE_INFO) {
      logger.debug(`GET ${proxyIpUrl.toString()}`);
    } else {
      logger.debug('GET /proxy/ip?api_password=***');
    }

    const response = await fetch(proxyIpUrl.toString(), {
      method: 'GET',
      headers: {
        'Content-Type': 'application/json',
      },
      signal: AbortSignal.timeout(Settings.MEDIAFLOW_IP_TIMEOUT),
    });

    if (!response.ok) {
      throw new Error(`${response.status}: ${response.statusText}`);
    }

    const data = await response.json();
    const publicIp = data.ip;
    if (publicIp && cache) {
      cache.set(cacheKey, publicIp, Settings.CACHE_MEDIAFLOW_IP_TTL);
    } else {
      logger.error(
        `MediaFlow did not respond with a public IP. Response: ${JSON.stringify(data)}`
      );
    }
    return publicIp;
  } catch (error: any) {
    logger.error(`Failed to get MediaFlow public IP: ${error.message}`);
    return null;
  }
}

export function getMediaFlowConfig(userConfig: Config) {
  const mediaFlowConfig = userConfig.mediaFlowConfig;

  return {
    mediaFlowEnabled:
      mediaFlowConfig?.mediaFlowEnabled ||
      Settings.DEFAULT_MEDIAFLOW_URL !== '',
    proxyUrl: mediaFlowConfig?.proxyUrl || Settings.DEFAULT_MEDIAFLOW_URL,
    apiPassword:
      mediaFlowConfig?.apiPassword || Settings.DEFAULT_MEDIAFLOW_API_PASSWORD,
    publicIp: mediaFlowConfig?.publicIp || Settings.DEFAULT_MEDIAFLOW_PUBLIC_IP,
    proxiedAddons: mediaFlowConfig?.proxiedAddons || null,
    proxiedServices: mediaFlowConfig?.proxiedServices || null,
  };
}