File size: 2,730 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
import { BaseProxy, ProxyStream } from './base';
import { createLogger, maskSensitiveInfo, Env } from '../utils';
import path from 'path';

const logger = createLogger('mediaflow');

export class MediaFlowProxy extends BaseProxy {
  protected generateProxyUrl(endpoint: string): URL {
    const proxyUrl = new URL(this.config.url.replace(/\/$/, ''));
    proxyUrl.pathname = `${proxyUrl.pathname === '/' ? '' : proxyUrl.pathname}${endpoint}`;
    if (endpoint === '/proxy/ip') {
      proxyUrl.searchParams.set('api_password', this.config.credentials);
    }
    return proxyUrl;
  }

  protected getPublicIpEndpoint(): string {
    return '/proxy/ip';
  }

  protected getPublicIpFromResponse(data: any): string | null {
    return data.ip || null;
  }

  protected getHeaders(): Record<string, string> {
    return {
      'Content-Type': 'application/json',
    };
  }

  protected async generateStreamUrls(
    streams: ProxyStream[]
  ): Promise<string[] | null> {
    const proxyUrl = this.generateProxyUrl('/generate_urls');

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

    if (Env.LOG_SENSITIVE_INFO) {
      logger.debug(`POST ${proxyUrl.toString()}`);
    } else {
      logger.debug(
        `POST ${proxyUrl.protocol}://${maskSensitiveInfo(proxyUrl.hostname)}${proxyUrl.port ? `:${proxyUrl.port}` : ''}/generate_urls`
      );
    }

    const response = await fetch(proxyUrl.toString(), {
      method: 'POST',
      headers: this.getHeaders(),
      body: JSON.stringify(data),
      signal: AbortSignal.timeout(30000),
    });

    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');
    }
  }
}