123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105 |
- Meteor.subscribe("users");
- /**
- * Find the id of a chat between two users.
- *
- * @param {String} myId
- * The current user id.
- * @param {String} otherUserId
- * The id of an other user.
- *
- * @returns {String}
- * The id of a chat between both users.
- */
- const getChatId = function (myId, otherUserId) {
- let id1;
- let id2;
- // Ensure ordering as id1 <= id2. Equality should not happen, but handle it correctly nonetheless.
- if (myId <= otherUserId) {
- id1 = myId;
- id2 = otherUserId;
- }
- else {
- id1 = otherUserId;
- id2 = myId;
- }
- // Since ids are ordered, we do not need a $or.
- const filter = { user1Id: id1, user2Id: id2 };
- const chat = Chats.findOne(filter);
- // Meteor._debug(filter, chat);
- // No chat matching the filter - need to insert a new one.
- let chatId;
- if (!chat) {
- chatId = Chats.insert({
- user1Id: id1,
- user2Id: id2
- });
- console.log("--- No chat found between " + id1 + " and " + id2 + ". Created " + chatId);
- }
- // There is a chat going already - use that.
- else {
- chatId = chat._id;
- console.log("--- Chat " + chatId + " found between " + id1 + " and " + id2 + ".");
- }
- return chatId;
- };
- // set up the main template the the router will use to build pages
- Router.configure({
- layoutTemplate: "ApplicationLayout"
- });
- // specify the top level route, the page users see when they arrive at the site
- Router.route("/", function () {
- console.log("Routing root /");
- this.render("navbar", { to: "header" });
- this.render("lobby_page", { to: "main" });
- });
- // specify a route that allows the current user to chat to another users
- Router.route("/chat/:_id", {
- subscriptions: function () {
- Meteor._debug("Subscriptions");
- return Meteor.subscribe("chats");
- },
- action: function (req, wtf, next) {
- Meteor._debug("Action", req.url);
- if (this.ready()) {
- console.log("- Now ready");
- // The user they want to chat to has id equal to the id sent in after /chat/...
- const otherUserId = this.params._id;
- const myId = Meteor.userId();
- const chatId = getChatId(myId, otherUserId);
- if (chatId) {
- // Looking good, save the id to the session.
- Session.set("chatId", chatId);
- this.render("navbar", { to: "header" });
- this.render("chat_page", {
- to: "main",
- data: function () {
- const other = Meteor.users.findOne({ _id: otherUserId });
- console.log("--- Routing data, other: " + (other ? other.profile.username : "not available"));
- return {
- other: other
- };
- }
- });
- }
- else {
- this.render("navbar", { to: "header" });
- this.render("Error", {
- to: "main",
- data: new Meteor.Error("no-chat", `Could not find a chat between ${myId} and ${otherUserId}.`)
- });
- }
- }
- else {
- console.log("- Not yet ready");
- this.render("Loading");
- }
- }
- });
|