Untitled

 avatar
unknown
javascript
a year ago
3.6 kB
6
Indexable
const fetch = require('node-fetch');
const puppeteer = require('puppeteer-core');

const apiUrl = 'http://localhost:3001/v1.0/auth/login-with-token';
const apiToken = 'TOKEN'; // Замените на свой действительный токен

// Функция для аутентификации с использованием токена
const authenticateWithToken = async () => {
  try {
    const response = await fetch(apiUrl, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({
        token: apiToken,
      }),
    });

    if (!response.ok) {
      const errorMessage = await response.text();
      throw new Error(`Failed to authenticate. Status: ${response.status} ${response.statusText}. Error: ${errorMessage}`);
    }

    const data = await response.json();
    console.log('Authentication successful:', data);

    // Возвращаем данные токена или что-то еще, если необходимо
    return data;
  } catch (error) {
    console.error('Authentication error:', error.message);
    throw error; // Прокидываем ошибку для обработки в основной функции
  }
};

// Функция для создания профиля браузера
const createBrowserProfile = async (accessToken) => {
  try {
    const response = await fetch('https://dolphin-anty-api.com/browser_profiles', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${accessToken}`,
      },
      body: JSON.stringify({
        name: 'TestProfile',
        tags: ['test'],
        // Добавьте другие параметры по мере необходимости
      }),
    });

    if (!response.ok) {
      const errorMessage = await response.text();
      throw new Error(`Failed to create browser profile. Status: ${response.status} ${response.statusText}. Error: ${errorMessage}`);
    }

    const data = await response.json();
    console.log('Browser profile created:', data);

    return data.id; // Возвращаем созданный идентификатор профиля
  } catch (error) {
    console.error('Error creating browser profile:', error.message);
    throw error; // Прокидываем ошибку для обработки в основной функции
  }
};

// Остальной код остается неизменным

// Основной скрипт
const main = async () => {
  try {
    // Шаг 1: Аутентификация с использованием токена
    const authenticationResult = await authenticateWithToken();

    // Шаг 2: Создание профиля браузера
    if (authenticationResult) {
      const profileId = await createBrowserProfile(authenticationResult.access_token);

      // Шаг 3: Запуск профиля браузера
      const automationInfo = await startBrowserProfile(profileId);

      // Шаг 4: Подключение к профилю браузера с использованием Puppeteer
      if (automationInfo) {
        await connectToProfile(automationInfo);
      }

      // Шаг 5: Удаление профиля браузера
      await deleteBrowserProfile(profileId);
    }
  } catch (error) {
    console.error('Main script error:', error.message);
  }
};

main(); // Запуск основной функции
Editor is loading...
Leave a Comment