Source: app/util/messageParser/detectYoutubeVideo.js

import { SEGMENT_URL, SEGMENT_YOUTUBE_VIDEO } from '../../data/enum/SegmentType';
import VideoType from '../../data/enum/VideoType';
import { YOUTUBE_REGEX } from '../../data/regexPatterns';

/**
 * Detects YouTube video urls in each SEGMENT_URL message segment provided to `input`. If a youtube
 * url is detected, will convert it to a SEGMENT_YOUTUBE_VIDEO and attach a video object.
 * @param input {Array<Object>} An array of message segments
 * @returns {Array<Object>} The processed array of message segments
 */
const detectYoutubeVideo = () => input =>
  input.map(segment => {
    const { type, data } = segment;

    switch (type) {
      case SEGMENT_URL: {
        const match = data.url.match(YOUTUBE_REGEX);

        if (match) {
          return {
            type: SEGMENT_YOUTUBE_VIDEO,
            data: {
              text: data.text,
              url: data.url,
              video: {
                _type: VideoType.YOUTUBE,
                videoId: match[1],
                autoplay: 1,
              },
            },
          };
        }

        return segment;
      }
      default:
        return segment;
    }
  });

export default detectYoutubeVideo;