aboutsummaryrefslogtreecommitdiff
path: root/vnext/server/sape.js
blob: ad374f2bb1e4be266dd28895e6fc7ce0caf4c0e9 (plain) (blame)
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
import { parseStringPromise } from 'xml2js';
import axios from 'axios';
import { setupCache } from 'axios-cache-interceptor';
import config from 'config';

const token = config.get('service.sape.token') || process.env.SAPE_TOKEN;

/** @external Promise */

/**
 * @param { string } uri
 * @param { string } sapeCookie
 * @returns { Promise<string[]>} links
 */
export const getLinks = async (uri, sapeCookie) => {
    if (!token) {
        console.warn('Sape is not configured');
        return [];
    }
    const response = await sape.get(`http://dispencer-01.sape.ru/code.php?user=${token}&host=juick.com&charset=UTF-8&as_xml=true`);
    const data = await parseStringPromise(response.data);
    const showCode = token === sapeCookie;
    const requestURI = showCode ? '*' : uri;
    const page = data.sape.page.filter(page => {
        const uri = page['$']['uri'];
        return uri === requestURI;
    });
    return page.length > 0 ? showCode ? [page[0]._] : page[0].link : [];
};

/** @type { import('axios-cache-interceptor').AxiosCacheInstance } */
let sape = setupCache(
    axios.create({
        headers: {
            'User-Agent': 'SAPE_Client PHP 1.0.3'
        }
    }),
    { ttl: 3600 * 1000 }
);