简体   繁体   中英

How do I create chat rooms in Firechat?

I am using Firechat and I am able to successfully initiate the chat window. I am using Firebase custom authentication and I can login without any problem. However, I now try to create a new chat room and then enter it. Based on the Firechat documentation I did the following:

<!doctype html>
<html>
<head>
<title>Test</title>
<meta charset="UTF-8" />
<script src='https://cdn.firebase.com/js/client/2.0.2/firebase.js'></script>
<link rel='stylesheet' href='https://cdn.firebase.com/libs/firechat/2.0.1/firechat.min.css' />
<script src='https://cdn.firebase.com/libs/firechat/2.0.1/firechat.min.js'></script>
</head>
<body>

    <script type='text/javascript'>
    var fireBase = new Firebase("https://XXXXXXXXX.firebaseio.com/");

    function initChat(authData) {
      var Firechat = new FirechatUI(fireBase, document.getElementById('firechat'));
      Firechat.setUser(authData.uid, "Username");
      Firechat.createRoom("Test chat room", "public");
    }

    fireBase.authWithCustomToken("UNIQUE_TOKEN", function(error, authData) {
      if (error) {
        console.log("Login Failed!", error);
      } else {
        console.log("Login successful", authData);
        initChat(authData);
      }
    });
    </script>
    <div id='firechat'>
    </div>

</body>
</html>

In the javascript console I can see that login is successful:

Login successful Object { auth: Object, expires: XXXXXXXXX, token: "XXXXXXXX…", uid: "XXXXXX", provider: "custom" } 

But the createRoom function is not found:

TypeError: Firechat.createRoom is not a function

Any idea what is going wrong here?

From the docs: Firechat.createRoom(roomName, roomType, callback(roomId))

Creates a new room with the given name (string) and type (string - public or private) and invokes the callback with the room ID on completion.


It would seem that you do not have a callback.


 Firechat.prototype.createRoom = function(roomName, roomType, callback) {
    var self = this,
        newRoomRef = this._roomRef.push();

    var newRoom = {
      id: newRoomRef.name(),
      name: roomName,
      type: roomType || 'public',
      createdByUserId: this._userId,
      createdAt: Firebase.ServerValue.TIMESTAMP
    };

    if (roomType === 'private') {
      newRoom.authorizedUsers = {};
      newRoom.authorizedUsers[this._userId] = true;
    }

    newRoomRef.set(newRoom, function(error) {
      if (!error) {
        self.enterRoom(newRoomRef.name());
      }
      if (callback) {
        callback(newRoomRef.name());
      }
    });
  };

Source: https://firechat.firebaseapp.com/docs/firechat.html

So it turns out that there are two classes (is that the right word) used in the Firechat javascript plugin:

var chat = new FirechatUI
var chat = new Firechat

Because they seem so similar I did not notice the difference. Nowhere in the documentation have I been able to find details of the FirechatUI instance (even though this code is recommended on the github readme ).

So anyway, the thing is that new FirechatUI loads the actual UI for the chat. new Firechat loads the API that allows you to talk to the chat plugin (but NOT to the UI). This is an important difference. The documentation found here only relates to the API so if you initiate a new Firechat instance. However, the trick is to get the UI up and running and then interact with it directly (doing things like creating new rooms or entering rooms). I have honestly not found out how to do this the official/recommended way. The only thing I've been able to come up with is a hack. It's ugly, but it works. The code below includes functionality to create a new chat room (using Firechat ) and to open a particular chatroom in the UI (that bit is hacked as I couldn't find a way to interact with the UI directly).

<!doctype html>
<html>
<head>
<meta charset="UTF-8" />
<title>Title</title>

<!-- jQuery -->
<script src='https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.1/jquery.min.js'></script>

<!-- Firebase -->
<script src='https://cdn.firebase.com/js/client/2.1.0/firebase.js'></script>

<!-- Firechat -->
<link rel='stylesheet' href='https://cdn.firebase.com/libs/firechat/2.0.1/firechat.min.css' />
<script src='https://cdn.firebase.com/libs/firechat/2.0.1/firechat.min.js'></script>

<!-- This plugin here: https://gist.github.com/buu700/4200601 -->
<script type="text/javascript" src="js/arrive.js"></script>

<style type="text/css">
#firechat{width:400px}
</style>

</head>

<body>

<h1>Test</h1>

    <script type='text/javascript'>
    var fireBase = new Firebase("https://XXXXXX.firebaseio.com/");

    function roomChatSetup(authData) {
        var chat = new Firechat(fireBase);
        chat.setUser(authData.uid, "My User Name", function(user) {
          console.log("Creating chatroom...");
          chat.createRoom("New Chatroom Name", "public", function(roomId) {
            console.log("Created room "+roomId);
          });
        $("#firechat").html("<div class='alert alert-success'>Your chatroom has been set up. Refresh to view</div>");
       });
    }

    function initChat(authData) {
        var chatUI = new FirechatUI(fireBase, document.getElementById('firechat'));
        chatUI.setUser(authData.uid, "My User Name");
        console.log("Simulating clicks...");
        $("#firechat-tab-content div.tab-pane").waitUntilExists(function(){
          console.log("Close all other tabs by simulating clicking the X button");
          $("#firechat-tab-content div.tab-pane:not(#XXXXXXXXX) a.close").click(); // XXXXX should have the chatroom name of the one you want to open
        });
        $("#firechat-btn-rooms").waitUntilExists(function(){
          $("#firechat-btn-rooms").click();
          console.log("Open submenu to load all possible rooms");
        });
        $("li[data-room-id='XXXXXXXXXXXXX']").waitUntilExists(function(){
          $("li[data-room-id='XXXXXXXXXX'] a").click();
          console.log("Simulating clicking on chatroom XXXXXXXXXXXXXX");
        });
    }

    fireBase.authWithCustomToken("XXXXXXXXXXXXXXXXXXXXXXXXXXXXXX", function(error, authData) {
      if (error) {
        console.log("Login Failed!", error);
      } else {
        console.log("Login successful", authData);

            // Here you can use a programming language to decide. If you already have a
            // chatroom, run initChat. If you don't, run createRoom. I haven't been 
            // able to run them both at the same time. 

            initChat(authData);
            // or:
            roomChatSetup(authData);

         }
    });
    </script>

    <div id="firechat"></div>

</body>
</html>

The FirechatUI object is separate from the Firechat object. FirechatUI does not have the same methods that Firechat does.

In order to get the associated Firechat object from a FirechatUI object you can do the following:

let chatUI = new FirechatUI(chatRef, document.getElementById("firechat-wrapper"));
let chat = chatUI._chat;

You can then do any normal Firechat operations without any issues.

chat.setUser(user.uid, firstName, function(user) {
    chat.resumeSession();
});

Please keep in mind that the _chat element is not really supposed to be used (as you can tell from the naming convention), but since FirechatUI does not properly expose enough functionality this is probably the cleanest way to do it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM