{"size": 714, "ext": "js", "max_stars_repo_path": "api/utils/video.js", "max_stars_repo_name": "AudioVisuaali/Eligere-backend", "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "api/utils/video.js", "max_issues_repo_name": "AudioVisuaali/Eligere-backend", "max_issues_repo_issues_event_min_datetime": "2021-05-10T21:32:55.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-10T21:32:55.000Z", "max_forks_repo_path": "api/utils/video.js", "max_forks_repo_name": "AudioVisuaali/Eligere-backend", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null}
{"max_stars_count": null, "max_issues_count": 1, "max_forks_count": null, "avg_line_length": 19.8333333333, "max_line_length": 133, "alphanum_fraction": 0.5882352941}
const axios = require('axios');

const youtubeAddr = url =>
  `https://www.youtube.com/oembed?url=${url}&format=json`;

async function getPlatform(url) {
  const MATCH_URL = /(?:youtu\.be\/|youtube\.com\/(?:embed\/|v\/|watch\?v=|watch\?.+&v=))((\w|-){11})|youtube\.com\/playlist\?list=/;

  if (!url) {
    return;
  }

  const canPlay = MATCH_URL.test(url);
  if (!canPlay) {
    return;
  }

  const slug = url.match(MATCH_URL)[1];
  try {
    const video = await axios.get(youtubeAddr(url));
    return {
      platform: 'youtube',
      url,
      slug,
      thumbnailURL: video.data.thumbnail_url,
      title: video.data.title,
    };
  } catch (e) {
    return;
  }
}

module.exports = {
  getPlatform,
};
