Программируемый чат Twilio - getChannelByUniqueName, кажется, возвращает ноль, независимо от того, что - PullRequest
0 голосов
/ 10 апреля 2020

Я добавляю чат в существующее приложение для видео-интервью. В чате используется программируемый чат Twilio. Видеоролик был в производстве некоторое время и использует программируемое видео Twilio.

В настоящее время я заблокирован проблемой с чатом. Я могу успешно присоединиться к чату, если имя комнаты, которую я ввожу при первоначальном присоединении, является совершенно новым и уникальным. Если я использую имя комнаты, которое я использовал ранее, я получаю сообщение об ошибке, что я пытаюсь создать канал с именем, которое уже существует.

Это должен быть простой обходной путь, однако моя попытка / catch с использованием getChannelByUniqueName возвращает один и тот же ответ независимо от того, какое имя я использую (существующее или новое).

Вы можете увидеть его вживую, перейдя к любому имени и имени комнаты и введя его. У меня включена отладка чата twilio, чтобы вы могли видеть подробные ошибки в консоли. Просто нажмите на значок чата на правой панели, и вы увидите подробный вывод в консоли.

Вот код, с которого я запускаю клиент чата, проверьте, существует ли имя комнаты, и затем попробуйте либо присоединиться к нему, либо создать его, а затем присоединиться к нему. Все работает, если мне нужно создать новое имя комнаты. Однако выгода для getChannelByUniqueName и / или просто попытка объединить имя комнаты с помощью жесткого кодирования, которое, как я уже знаю, существует, выдает ошибку.

class App extends Component {
  constructor(props) {
    super(props);
    this.state = {
      messages: [],
      username: null,
      joinedChannel: null,
    };
  }

  componentDidMount = () => {
    this.getToken()
      .then(this.createChatClient)
      .then(this.fetchRoomChannel)
      //.then(this.joinGeneralChannel)
      .then(this.configureChannelEvents)
      .catch(error => {
        console.log(`Chat onmount token error`);
        this.addMessage({ body: `Error: ${error.message}` });
      });
  };


//verified that this works
  getToken = () => {
    return new Promise((resolve, reject) => {
      const cookieMgr = new Cookies();
      var identity = cookieMgr.get('identity');
      var room = cookieMgr.get('room');

      this.addMessage({ body: 'Connecting...' });

      var thetoken = cookieMgr.get('token');

      this.setState({ username: identity });
      console.log(`Chat getToken identity value as ${identity}`);

      this.setState({ channel: room });
      console.log(`Chat getToken room value as ${room}`);

      console.log(`Chat getToken token value as ${thetoken}`);
      resolve(thetoken);
    });
  };


//verified that this works
  createChatClient = token => {
    return new Promise((resolve, reject) => {
     this.addMessage({ body: 'Creating chat client...' });

      const cookieMgr = new Cookies();
      var thetoken = cookieMgr.get('token');
      var identity = cookieMgr.get('identity');
      var room = cookieMgr.get('room');

      const token = new AccessToken(twilioAccountSid, twilioApiKeySID, twilioApiKeySecret);

      const chatGrant = new ChatGrant({
        serviceSid: twilioChatSService,
      });
      token.addGrant(chatGrant);
      token.identity = identity;

      console.log('New token: ' + token.toJwt());

      var thetoken = cookieMgr.get('token');

      console.log(`Chat createChatclient token value as ${thetoken}`);
      //resolve(new TwilioChat(token.toJwt()));

        //enabling twilio chat debug mode.  this gives a lot more detail in the console.
        let clientOptions = { logLevel: 'debug' };

        resolve(new TwilioChat(thetoken, clientOptions));
        this.addMessage({ body: 'Token resolved...' });
    });
  };

  fetchRoomChannel = chatClient => {
    return new Promise((resolve, reject) => {
      const cookieMgr = new Cookies();
      var room = cookieMgr.get('room');
        var identity = cookieMgr.get('identity');

        this.addMessage({ body: `Checking to see if ${room} channel exists...` });


      //This is where the problem exists.  Even when a room exists we get a response that it doesn't.
      chatClient.getChannelByUniqueName(room).then(() => this.addMessage({ body: `${room} does exist, this is where we fail...` }));

      //This works so long as the channel doesn't actually exist already.
      chatClient.getChannelByUniqueName(room).catch(() => this.createGeneralChannel(chatClient));
    });
  };

    //this is breaking for room names we didn't just create
  joinGeneralChannel = channel => {
    return new Promise((resolve, reject) => {
      const cookieMgr = new Cookies();
      var room = cookieMgr.get('room');
      var identity = cookieMgr.get('identity');

      this.addMessage({ body: `Joining ${room} channel...` });

      channel
        .join()
        .then(() => {
          this.addMessage({ body: `Joined channel as ${identity}` });
          this.setState({ joinedChannel: channel });
          window.addEventListener('beforeunload', () => channel.leave());
        })
        .catch(() => reject(Error('Could not join channel.')));

      this.configureChannelEvents(channel);
      resolve(channel);
    });
  };

  createGeneralChannel = (chatClient, channel) => {
    const cookieMgr = new Cookies();
    var room = cookieMgr.get('room');

      this.addMessage({ body: `${room} channel doesn't already exist so we're creating it` });

    return new Promise((resolve, reject) => {
      this.addMessage({ body: `Creating ${room} channel...` });
      chatClient
          .createChannel({ uniqueName: room, friendlyName: room })
          .then(this.addMessage({ body: `${room} created...` }))
          .then(this.addMessage({ body: `now going to try and join it...` }))
          .then((channel = function (_channel) { }) => this.joinGeneralChannel(channel))
        .catch(() => reject(Error(`Could not create ${room} channel.`)));
    });
  };

Когда я ввел имя комнаты / канала, я знаю, что он новый и уникальный, он работает: enter image description here

Когда я ввожу имя комнаты / канала, которое, я знаю, уже существует, оно не работает: enter image description here enter image description here

Даже подробное сообщение об ошибке, которое я получаю из режима отладки twilio в консоли, просто говорит мне, что я не могу создать канал, потому что он уже существует. Однако, когда я сделал попытку / поймать, чтобы проверить, существует ли имя комнаты выше в моем коде, он возвращает false, так что это вполне уловка-22 ..

1 Ответ

0 голосов
/ 10 апреля 2020

Хорошо, мы решили это. Вот окончательный рабочий код на случай, если у кого-нибудь еще возникнет эта проблема:

class App extends Component {
  constructor(props) {
    super(props);
    this.state = {
      messages: [],
      username: null,
      joinedChannel: null,
    };
  }

  componentDidMount = () => {
    this.getToken()
      .then(this.createChatClient)
      .then(this.fetchRoomChannel)
      //.then(this.joinGeneralChannel)
      .then(this.configureChannelEvents)
      .catch(error => {
        console.log(`Chat onmount token error`);
        this.addMessage({ body: `Error: ${error.message}` });
      });
  };


  getToken = () => {
    return new Promise((resolve, reject) => {
      const cookieMgr = new Cookies();
      var identity = cookieMgr.get('identity');
      var room = cookieMgr.get('room');

      this.addMessage({ body: 'Connecting...' });

      var thetoken = cookieMgr.get('token');

      this.setState({ username: identity });
      console.log(`Chat getToken identity value as ${identity}`);

      this.setState({ channel: room });
      console.log(`Chat getToken room value as ${room}`);

      console.log(`Chat getToken token value as ${thetoken}`);
      resolve(thetoken);
    });
  };


  createChatClient = token => {
    return new Promise((resolve, reject) => {
     this.addMessage({ body: 'Creating chat client...' });

      const cookieMgr = new Cookies();
      var thetoken = cookieMgr.get('token');
      var identity = cookieMgr.get('identity');
      var room = cookieMgr.get('room');

      const token = new AccessToken(twilioAccountSid, twilioApiKeySID, twilioApiKeySecret);

      const chatGrant = new ChatGrant({
        serviceSid: twilioChatSService,
      });
      token.addGrant(chatGrant);
      token.identity = identity;

      console.log('New token: ' + token.toJwt());

      var thetoken = cookieMgr.get('token');

      console.log(`Chat createChatclient token value as ${thetoken}`);
      //resolve(new TwilioChat(token.toJwt()));

        //enabling twilio chat debug mode.  this gives a lot more detail in the console.
        let clientOptions = { logLevel: 'debug' };

        resolve(new TwilioChat(thetoken, clientOptions));
        this.addMessage({ body: 'Token resolved...' });
    });
  };

  fetchRoomChannel = chatClient => {
    return new Promise((resolve, reject) => {
      const cookieMgr = new Cookies();
      var room = cookieMgr.get('room');
      var identity = cookieMgr.get('identity');

      this.addMessage({ body: `Checking to see if ${room} channel exists...` });

        chatClient.username = identity;

        this.addMessage({ body: `identity set as ${chatClient.username}...` });

      chatClient.getChannelByUniqueName(room).then(() => this.addMessage({ body: `${room} does exist, this is where we fail...` }));

      chatClient.getChannelByUniqueName(room).catch(() => this.createGeneralChannel(chatClient));
    });
  };

  joinGeneralChannel = channel => {
    return new Promise((resolve, reject) => {
      const cookieMgr = new Cookies();
      var room = cookieMgr.get('room');
      var identity = cookieMgr.get('identity');

      this.addMessage({ body: `Joining ${room} channel...` });

      channel
        .join()
        .then(() => {
          this.addMessage({ body: `Joined channel as ${identity}` });
          this.setState({ joinedChannel: channel });
          window.addEventListener('beforeunload', () => channel.leave());
        })
        .catch(() => reject(Error('Could not join channel.')));

      this.configureChannelEvents(channel);
      resolve(channel);
    });
  };

  createGeneralChannel = (chatClient, channel) => {
    const cookieMgr = new Cookies();
    var room = cookieMgr.get('room');
      var identity = cookieMgr.get('identity');

      this.addMessage({ body: `${room} channel doesn't already exist so we're creating it` });

    return new Promise((resolve, reject) => {
        this.addMessage({ body: `Creating ${room} channel...` });
      chatClient
          .createChannel({ uniqueName: room, friendlyName: room, type: 'public' })
          .then(this.addMessage({ body: `${room} created...` }))
          .then(this.addMessage({ body: `now going to try and join it...` }))
          .then((channel = function (_channel) { }) => this.joinGeneralChannel(channel))
        .catch(() => reject(Error(`Could not create ${room} channel.`)));
    });
  };

  addMessage = message => {
    const messageData = { ...message, me: message.author === this.state.username };
    this.setState({
      messages: [...this.state.messages, messageData],
    });
  };

  handleNewMessage = text => {
    if (this.state.joinedChannel) {
      this.state.joinedChannel.sendMessage(text);
    }
  };

  configureChannelEvents = channel => {
    channel.on('messageAdded', ({ author, body }) => {
      this.addMessage({ author, body });
    });

    channel.on('memberJoined', member => {
      this.addMessage({ body: `${member.identity} has joined the channel.` });
    });

    channel.on('memberLeft', member => {
      this.addMessage({ body: `${member.identity} has left the channel.` });
    });
  };

  render() {
    return (
      <div className="EditingArea ChatContainer">
        <MessageList messages={this.state.messages} />
        <MessageForm onMessageSend={this.handleNewMessage} />
      </div>
    );
  }
}

export default App;
...