Channel.js 7.25 KB
import React from "react";
import "./Channel.css";
import "@material-ui/icons"
import PersonIcon from "@material-ui/icons/Person";
import PlayArrowIcon from '@material-ui/icons/PlayArrow';
import PauseIcon from '@material-ui/icons/Pause';
import { WatchOutlined } from "@material-ui/icons";
import io from 'socket.io-client'
import tts from './tts';

// audioQueue에서 하나씩 뽑아서 재생한다.
tts.enableAudio()

const socket = io.connect("http://server.oss.jinsu.me")
socket.on("connect", event=>{
    // 테스트용으로 umi0410에게 입장.
    // 다른 거 아무거나 채널이름을 넣으면 되겠지만, 그렇게 하고싶으면 백엔드에서 인자설정을 해줘야함.
    // socket.emit("joinRoom", 'umi0410', '진수봇')
})

// 말해야할 메시지가 왔을 때. 이건 따로 Component와 묶지 않아도 알아서 실행됩니다.
socket.on('chat message', (name, msg)=>{
    console.log(msg)
    console.log("got message")
    //tts를 audio로 변경해 audioQueue에 집어넣는다.
    tts.enqueueTTS(msg)
})

// 해당 채널을 재생하고자할 때 실행시켜주세요.
const listen = (channelName)=>{
    console.log(`listen ${channelName}`);
    socket.emit("joinRoom", channelName, "dummy name") // name이 뭔지 대연이도 잘 모름.
}

// 해당 채널을 재생 안하도록 할 때 실행시켜주세요.
const quit = (channelName)=>{
    console.log(`quit ${channelName}`);
    socket.emit("leaveRoom". channelName, "dummy name") // name이 뭔지 대연이도 잘 모름.
}

export class Channel extends React.Component {
    render(){
        return (
            <div className="channel">
                <a href={this.props.channel.url} className="channel__url">
                    {this.props.channel.logo && <img className="channel__thumbnail" src={this.props.channel.logo} alt=""></img>}
                    {!this.props.channel.logo && <PersonIcon className="channel__icon"/>}
                    <div className="channel__box">
                        <div className="channel__info">
                            <div className="channel__name">{ `${this.props.channel.nickname} (${this.props.channel.id})` }</div>
                            <div className="channel__game">{this.props.channel.category}</div>
                        </div>
                        <div className="channel__view">{this.props.channel.view}</div>
                    </div>
                </a>
                {this.props.channel.isPlay && <PauseIcon className="pause__icon" onClick={this.props.onClick} />}
                {!this.props.channel.isPlay && <PlayArrowIcon className="play__icon" onClick={this.props.onClick} />}
            </div>
        )
    }
}

export class ChannelList extends React.Component {
    constructor(props) {
        super(props);
        
        // data for test
        const test = [
            {"id": "umi0410", "nickname": "진수", "view": 123124124, "category": "game2" , "url": "https://www.twitch.tv/umi0410", "isPlay": false},
            {"id": "name1", "nickname": "nick", "view": 999, "category": "game1" ,"url": "https://www.twitch.tv", "thumbnail": "https://upload.wikimedia.org/wikipedia/commons/2/26/Twitch_logo.svg", "isPlay": false},
            {"id": "name2", "nickname": "nick","view": 123124124, "category": "game2" , "url": "https://www.twitch.tv", "isPlay": false},
        ]

        this.state = {
            channels: [],
            xisPlaying: null,
        }
    }

    changeState(channel, index){
        const channels = this.state.channels;
        // 버튼을 누른 채널이 재생중일때
        if (channel.isPlay === true) {
            channels[index].isPlay = false;
            
            // 기존 채널 재생 중지
            quit(channels[index].id);

            this.setState({
                channels: channels,
                xisPlaying: null,
            });
        }

        // 버튼을 누른 채널이 재생중이 아닐 때
        else {
            // xisPlaying이 null이 아닐 때
            if (this.state.xisPlaying !== null) {
                // 기존에 재생되던 채널의 isPlay를 false로, 클릭 이벤트가 발생한 채널의 isPlay를 true로 변경
                channels[this.state.xisPlaying].isPlay = false;
                channels[index].isPlay = true;

                // 기존 채널 재생을 중지하고 새로운 채널을 listen
                console.log("if")
                quit(channels[this.state.xisPlaying].id);
                listen(channels[index].id);
            }
            
            // xisPlaying이 null일 때
            else {
                channels[index].isPlay = true;
                // 채널 listen
                console.log("else")
                listen(channels[index].id);
            }
            
            this.setState({
                channels: channels,
                xisPlaying: index,
            });
        }
    }


    componentDidMount() {
        console.log('channel cdm');
        fetch('http://server.oss.jinsu.me/channels').then( res => res.json())
            .then(data => {
                var tmpChannels = [];
                data.map((channel, index) => {
                    var tmp = {
                        id: channel.name|| " ",
                        nickname: channel.display_name || " ",
                        category: channel.game || "Not playing",
                        view: channel.views || 0,
                        url: channel.url || "https://www.twitch.tv/",
                        isPlay: false,
                        logo: channel.logo,
                    }
                    tmpChannels.push(tmp);
                })
                return tmpChannels;
            }).then( channels => {
                this.setState({
                    channels: channels,
                    xisPlaying: null,
                })
            })
        }
        /* fetch('http://localhost:3303/list').then( res => res.json())
            .then(data => {
                var tmpChannels = []
                data.channels.map((channel, index) => {
                    var tmp = {
                        id: channel.id,
                        nickname: channel.nickname,
                        category: channel.category,
                        view: channel.view,
                        url: `https://www.twitch.tv/${channel.id}`,
                        isPlay: false,
                    }
                    tmpChannels.push(tmp);
                })

                return tmpChannels;
            }).then( channels => {
                this.setState({
                    channels: channels,
                    xisPlaying: null,
                })
            }) */

        
    

    render() {
        console.log('channel render')
        return (
            <div className="channel__list">
                <div className="channel__list__title">  CHANNEL LIST</div>
                <ul>
                {this.state.channels.map((channel, index) => (
                    <li key={index}>
                        <Channel 
                            channel={channel}
                            onClick={ () => this.changeState(channel, index)}
                        />
                        <hr />
                    </li>
                ))}
                </ul>
            </div>
            
        );
    }
}