PubNub Live Chat Beta Testing


 
Thread Tools Search this Thread
The Lounge What is on Your Mind? PubNub Live Chat Beta Testing
# 22  
Old 05-05-2019
UserCP Screeching Frog 0.7593
  • Found an issue with too many keepalives generating unnecessary traffic from client to pubnub network, so I changed the keepalives, and tweaked other heartbeat params:

Please clear your cache (and restart most browsers), to save our pubnub transactions quota. Thanks!
# 23  
Old 05-06-2019
Update:

There is still an issue with PubNub Javascript SDK generating too much network traffic with heartbeats and presence ping every few seconds.

This issue does not effect the live chat page, per se, but it does generate too many transactions and I am planning to work with PubNub to (hopefully) correct this.

I am seeing 1000s of truncations where there should be a handful and this is not scalable or efficient. I hope the issue is because I am doing something incorrect in the configuration.
# 24  
Old 05-06-2019
UserCP Screeching Frog 0.7594
  • Added "snap scroll bar code to top or bottom of chat window on (1) incoming message or (2) enter key for send message.

Code:
adjustScroll() {
      var scroll = document.querySelector(".vue-steam-chat__wrapper--scroll");
      if (!this.reverseorder) scroll.scrollTop = 0;
      else scroll.scrollTop = scroll.scrollHeight;
    },

Seems to work fine in Chome but not so great in Safari.

UserCP Screeching Frog 0.7596
  • Minor scrollbar snap tweaks on init.
  • Disable pubnub presence in subscribe() for testing to see if network load will decrease and all work as it should.


UserCP Screeching Frog 0.7598
  • Disabled unused service workers.
  • Disable presense in pubnub listeners (testing ways to reduce network XHR calls).

UserCP Screeching Frog 0.7599
  • Force scroll to top or bottom of browser window on reload, new message, or toogle.
This User Gave Thanks to Neo For This Post:
# 25  
Old 05-06-2019
Here is the my current Vue.js UserCP (v0.7691) Live Chat code (not yet optimized, so please forgive my mess) using PubNub:

Code:
<template>
  <div class="bottomfill">
    <div class="d-flex justify-content-start flex-wrap room nomargin togglearea">
      <div class="checkbox leftmargin">
        <label>
          <input class="ckbox" type="checkbox" v-model="reverseorder">
          <span v-bind:class="{reverseon: this.reverseorder}" class="toggler">Toggle Message Order</span>
          <span v-if="this.reverseorder">
            <i v-bind:class="{reverseon: this.reverseorder}" class="tim-icons icon-minimal-down"></i>
          </span>
          <span v-else>
            <i class="tim-icons icon-minimal-up"></i>
          </span>
        </label>
      </div>
    </div>

    <div class="d-flex justify-content-around flex-wrap room">
      <div class="col-md-12 box">
        <div
          class="neo-chat-title"
          v-if="this.psoccupancy"
        >Live Chat Participants: {{ this.psoccupancy}}</div>

        <div class="neo-chat-title">{{ this.userlist}}</div>
        <VueSteamChat :messages="this.msglist" @vue-steam-chat-on-message="onNewMessage"/>
      </div>
    </div>

    <div class="d-flex justify-content-around flex-wrap room channelbar">
      <div>Channels</div>
      <div class="checkbox">
        <label>
          <input class="ckbox" type="checkbox" v-model="livebox">
          <span v-bind:class="{liveon: this.livebox}">Live</span>
        </label>
      </div>
      <div class="checkbox">
        <label>
          <input class="ckbox" type="checkbox" v-model="postsbox">
          <span v-bind:class="{liveon: this.postsbox}">Posts</span>
        </label>
      </div>
      <div class="checkbox disabled">
        <label>
          <input class="ckbox" type="checkbox" v-model="statusbox">
          <span v-bind:class="{liveon: this.statusbox}">Status</span>
        </label>
      </div>
    </div>
  </div>
</template>

<script>
    function init() {
        sessionStorage.setItem("loaded", true);
    }
    window.onload = init;
    // import Vuex from "vuex";
    // Vue.use(Vuex);

    import Vue from "vue";
    import VueSteamChat from "vue-steam-chat";
    import {
        setTimeout,
        setInterval,
        clearInterval
    } from "timers";
    var PubNub = require("pubnub");
    require("vue-steam-chat/dist/index.css");
    var interval = null;
    var vbchat = "";

    if (window.vbname == "Unregistered") {
        const d = Math.floor(Math.random() * 100);
        if (localStorage.getItem("randomuser")) {
            vbchat = "Guest " + localStorage.getItem("randomuser");
        } else {
            const d = Math.floor(Math.random() * 100);
            localStorage.setItem("randomuser", d);
            vbchat = "Guest " + localStorage.getItem("randomuser");
        }
    } else {
        vbchat = window.vbname;
    }

    var pubnub = new PubNub({
        subscribeKey: "demo",
        publishKey: "demo",
        ssl: true,
        keepAlive: true,
        // heartbeatInterval: 10,
        presenceTimeout: 300,
        restore: true,
        uuid: vbchat
    });
    var debounce = require("debounce");
    export default {
        name: "vue-steam-chat",
        components: {
            VueSteamChat
        },
        computed: {
            msglist() {
                var listarray = [];
                //console.log("this.text ", this.text);
                var that = this;
                this.text.forEach(function(element) {
                    if (
                        element.text.match(/Forum Replied To/g) ||
                        element.text.match(/Forum Started Post/g)
                    ) {
                        if (that.postsbox == true) {
                            listarray.push(element);
                        }
                    } else if (element.text.match(/Forum Status/g)) {
                        if (that.statusbox == true) {
                            listarray.push(element);
                        }
                    } else if (that.livebox == true) {
                        listarray.push(element);
                    }
                });
                if (this.reverseorder == true) {
                    return listarray.reverse();
                } else {
                    return listarray;
                }
                //this.adjustScroll();
            },
            uuid() {
                return pubnub.getUUID();
            }
        },
        data() {
            return {
                blockpublish: false,
                livebox: true,
                reverseorder: true,
                postsbox: true,
                statusbox: true,
                historydone: false,
                userlist: "",
                userarray: [],
                uuida: window.vbuserId,
                uuname: window.vbusername,
                ch1: null,
                time: Date.now() / 1000,
                chathist: [],
                laststatuschange: [{}],
                occupancy: 0,
                psoccupancy: 0,
                initdone: 0,
                status: 0,
                text: [{
                        time: 1506117496,
                        username: "Gaben",
                        text: "Chat initialized ..."
                    },
                    {
                        time: 1506117500,
                        username: "Solo",
                        text: "So, say something !!"
                    },
                    {
                        time: 1506117530,
                        username: "Neo",
                        text: "Hmmm ..."
                    }
                ]
            };
        },
        methods: {
            adjustScroll() {
                var scroll = document.querySelector(".vue-steam-chat__wrapper--scroll");
                var view = document.querySelector(".bottomfill");
                var toggle = document.querySelector(".togglearea");
                var channels = document.querySelector(".channelbar");

                if (!this.reverseorder) {
                    scroll.scrollTop = 0;
                    //$("html,body").animate({ scrollTop: 0 }, "slow");
                    // view.scrollIntoView(true);
                    view.scrollIntoView({
                        behavior: "smooth",
                        block: "start",
                        inline: "nearest"
                    });
                } else {
                    scroll.scrollTop = scroll.scrollHeight;
                    // channels.scrollIntoView(false);
                    channels.scrollIntoView({
                        behavior: "smooth",
                        block: "end",
                        inline: "nearest"
                    });
                    //$("html,body").animate({ scrollTop: scroll.scrollHeight }, "slow");
                }
            },
            initScroll() {
                var view = document.querySelector(".bottomfill");
                var channels = document.querySelector(".channelbar");
                var scroll = document.querySelector(".vue-steam-chat__wrapper--scroll");
                //$("html,body").animate({ scrollTop: scroll.scrollHeight }, "slow");
                //channels.animate({ scrollIntoView: false }, "slow");
                view.scrollIntoView({
                    behavior: "smooth",
                    block: "end",
                    inline: "nearest"
                });
            },
            getHereNow() {
                var that = this;
                pubnub.hereNow({
                        channels: ["ch1"],
                        // channelGroups : ["cg1"],
                        includeUUIDs: true,
                        includeState: true
                    },
                    function(status, response) {
                        that.psoccupancy = response.totalOccupancy;
                        // console.log("herenow: ", response);
                        var allusers = "";
                        var index = 0;

                        response.channels.ch1.occupants.forEach(function(user) {
                            if (response.channels.ch1.occupants) {
                                that.userarray.push(user);
                                if (index == 0) allusers = user.uuid;
                                else allusers = allusers + ", " + user.uuid;
                            }
                            index++;
                            that.userlist = allusers;
                        });
                    }
                );
            },
            gmCallback(status, response) {
                console.log("gm callback", status, response);
            },
            history() {
                var that = this;
                if (pubnub) {
                    pubnub.history({
                            reverse: false,
                            channel: "ch1",
                            count: 100, // how many items to fetch
                            stringifiedTimeToken: true // false is the default
                        },
                        function(status, response) {
                            if (status.error == false) {
                                response.messages.forEach(function(element) {
                                    if (element.entry.username && element.entry.text != undefined) {
                                        if (
                                            element.entry.text.match(/Forum Replied To/g) ||
                                            element.entry.text.match(/Forum Started Post/g)
                                        ) {
                                            if (that.postsbox == true) {
                                                that.text.push(element.entry);
                                            }
                                        } else if (element.entry.text.match(/Forum Status/g)) {
                                            if (that.statusbox == true) {
                                                that.text.push(element.entry);
                                            }
                                        } else if (that.livebox == true) {
                                            that.text.push(element.entry);
                                        }
                                    }
                                });
                                that.historydone = true;
                            } else {
                                console.log("error ", status);
                            }
                        }
                    );
                }
                that.initScroll();
            },
            controlMessage(message) {
                var that = this;
                if (message.length < 2) {
                    return false;
                }
                let m = {
                    time: Date.now() / 1000,
                    username: this.uuid,
                    text: message
                };
                var publishConfig = {
                    sendByPost: true,
                    channel: "controlreply",
                    message: m
                };

                pubnub.publish(publishConfig, function(status, response) {
                    if (status.error) {
                        console.log(status);
                    } else {
                        // console.log("control message Published w/ timetoken", JSON.stringify(publishConfig));
                    }
                });
            },

            onNewMessage(message) {
                var that = this;
                if (message.length < 2) {
                    return false;
                }
                let m = {
                    time: Date.now() / 1000,
                    username: this.uuid,
                    text: message
                };
                var publishConfig = {
                    sendByPost: true,
                    channel: "ch1",
                    message: m
                };

                if (that.blockpublish != true) {
                    pubnub.publish(publishConfig, function(status, response) {
                        if (status.error) {
                            console.log(status);
                        } else {
                            // console.log("message Published w/ timetoken", response.timetoken);
                        }
                    });
                    that.getHereNow();
                    // that.adjustScroll();
                }
            }
        },
        created() {
            $.LoadingOverlay("show");
            pubnub.subscribe({
                channels: ["ch1", "control"],
                withPresence: false
            });
        },
        updated() {
            debounce(this.getHereNow, 300, false);
            this.adjustScroll();
        },
        beforeDestroy() {
            pubnub.unsubscribeAll();
            // pubnub.unsubscribe({
            //   channels: ["ch1", "control"]
            // });
            var existingListener = {
                message: function() {}
            };

            if (existingListener) pubnub.removeListener(existingListener);
            if (interval) {
                clearInterval(interval);
            }
        },
        async mounted() {
            if (localStorage.blc) {
                if (localStorage.getItem("blc") == "true") {
                    this.blockpublish = true;
                }
            }
            if (localStorage.status_msgs) {
                if (localStorage.getItem("status_msgs") == "yes") {
                    this.statusbox = true;
                }
            }
            var that = this;
            that.history();

            pubnub.addListener({
                // status: function(statusEvent) {
                //   if (statusEvent.category === "PNConnectedCategory") {
                //     var newState = {
                //       name: this.uuid,
                //       timestamp: Date.now()
                //     };
                //     pubsub.setState({
                //       channels: ["ch1"],
                //       state: newState
                //     });
                //   }
                // },
                message: function(m) {
                    // console.log("livechat msg channel received: ", JSON.stringify(m));
                    that.adjustScroll();
                    if (m.channel == "ch1") {
                        if (
                            m.message.text.match(/Forum Replied To/g) ||
                            m.message.text.match(/Forum Started Post/g)
                        ) {
                            if (that.postsbox == true) {
                                that.text.push(m.message);
                            }
                        } else if (m.message.text.match(/Forum Status/g)) {
                            if (that.statusbox == true) {
                                that.text.push(element.entry);
                            }
                        } else if (that.livebox == true) {
                            that.text.push(m.message);
                        }
                    } 

                     // 
                    // Removed lines for internal use only
                    //
   
                        that.getHereNow();
                    }
                    //that.text.push(m.message);
                    //console.log("newmsg: ", m.message);
                }
                // presence: function(presenceEvent) {
                //   that.psoccupancy = presenceEvent.occupancy;
                //   const i = Date.now();
                //   that.getHereNow();
                // }
            });
            this.getHereNow();
            var mythis = this;
            $(function() {
                var input = document.querySelector(".vue-steam-chat__textarea");
                var button = document.querySelector(".vue-steam-chat__button");
                var scroll = document.querySelector(".vue-steam-chat__wrapper--scroll");
                input.addEventListener("keyup", function(event) {
                    if (event.keyCode === 13) {
                        event.preventDefault();
                        button.click();
                    }
                });
                $.LoadingOverlay("hide");
            });
        }
    };
</script>
<style scoped>
    .box {
        margin: 0px !important;
        height: 500px;
        margin: 20px;
    }

    .neo-chat-title {
        color: slategray;
        font-size: 1.2em;
        text-align: center;
        margin: 10px;
    }

    .room {
        margin-bottom: 20px;
    }

    .ckbox {
        margin-right: 7px;
        background-color: cornflowerblue;
    }

    .reverseon {
        color: cornflowerblue;
    }

    .liveon {
        color: cornflowerblue;
    }

    .ckbox {
        color: cornflowerblue;
    }

    .nomargin {
        margin: 0px 0px 0px 0px;
    }

    .leftmargin {
        margin-left: 30px;
    }

    .toggler {
        margin: 10px 10px 0px 0px;
    }

    .channelbar {
        margin: 100px 10px 10px 10px;
        padding-bottom: 10px;
    }

    .bottomfill {
        margin-bottom: 0px;
        padding-top: 20px;
    }
</style>

# 26  
Old 05-07-2019
version 0.7062... minor changes

Code:
<template>
  <div class="bottomfill">
    <div class="d-flex justify-content-start flex-wrap room nomargin togglearea">
      <div class="checkbox leftmargin">
        <label>
          <input class="ckbox" type="checkbox" v-model="reverseorder">
          <span v-bind:class="{reverseon: this.reverseorder}" class="toggler">Toggle Message Order</span>
          <span v-if="this.reverseorder">
            <i v-bind:class="{reverseon: this.reverseorder}" class="tim-icons icon-minimal-down"></i>
          </span>
          <span v-else>
            <i class="tim-icons icon-minimal-up"></i>
          </span>
        </label>
      </div>
    </div>

    <div class="d-flex justify-content-around flex-wrap room">
      <div class="col-md-12 box">
        <div
          class="neo-chat-title"
          v-if="this.psoccupancy"
        >Live Chat Participants: {{ this.psoccupancy}}</div>

        <div class="neo-chat-title">{{ this.userlist}}</div>
        <VueSteamChat :messages="this.msglist" @vue-steam-chat-on-message="onNewMessage"/>
      </div>
    </div>

    <div class="d-flex justify-content-around flex-wrap room channelbar">
      <div>Channels</div>
      <div class="checkbox">
        <label>
          <input class="ckbox" type="checkbox" v-model="livebox">
          <span v-bind:class="{liveon: this.livebox}">Live</span>
        </label>
      </div>
      <div class="checkbox">
        <label>
          <input class="ckbox" type="checkbox" v-model="postsbox">
          <span v-bind:class="{liveon: this.postsbox}">Posts</span>
        </label>
      </div>
      <div class="checkbox disabled">
        <label>
          <input class="ckbox" type="checkbox" v-model="statusbox">
          <span v-bind:class="{liveon: this.statusbox}">Status</span>
        </label>
      </div>
    </div>
  </div>
</template>

<script>
function init() {
  sessionStorage.setItem("loaded", true);
}
window.onload = init;
// import Vuex from "vuex";
// Vue.use(Vuex);

import Vue from "vue";
import VueSteamChat from "vue-steam-chat";
import { setTimeout, setInterval, clearInterval } from "timers";
var PubNub = require("pubnub");
require("vue-steam-chat/dist/index.css");
var interval = null;
var vbchat = "";

if (window.vbname == "Unregistered") {
  const d = Math.floor(Math.random() * 100);
  if (localStorage.getItem("randomuser")) {
    vbchat = "Guest " + localStorage.getItem("randomuser");
  } else {
    const d = Math.floor(Math.random() * 100);
    localStorage.setItem("randomuser", d);
    vbchat = "Guest " + localStorage.getItem("randomuser");
  }
} else {
  vbchat = window.vbname;
}

var pubnub = new PubNub({
  subscribeKey: "demo",
  publishKey: "demo",
  ssl: true,
  keepAlive: true,
  // heartbeatInterval: 10,
  presenceTimeout: 300,
  restore: true,
  uuid: vbchat
});
var debounce = require("debounce");
export default {
  name: "vue-steam-chat",
  components: {
    VueSteamChat
  },
  computed: {
    msglist() {
      var listarray = [];
      //console.log("this.text ", this.text);
      var that = this;
      this.text.forEach(function(element) {
        if (
          element.text.match(/Forum Replied To/g) ||
          element.text.match(/Forum Started Post/g)
        ) {
          if (that.postsbox == true) {
            listarray.push(element);
          }
        } else if (element.text.match(/Forum Status/g)) {
          if (that.statusbox == true) {
            listarray.push(element);
          }
        } else if (that.livebox == true) {
          listarray.push(element);
        }
      });
      if (this.reverseorder == true) {
        return listarray.reverse();
      } else {
        return listarray;
      }
      //this.adjustScroll();
    },
    uuid() {
      return pubnub.getUUID();
    }
  },
  data() {
    return {
      blockpublish: false,
      livebox: true,
      reverseorder: true,
      postsbox: true,
      statusbox: true,
      historydone: false,
      userlist: "",
      userarray: [],
      uuida: window.vbuserId,
      uuname: window.vbusername,
      ch1: null,
      time: Date.now() / 1000,
      chathist: [],
      laststatuschange: [{}],
      occupancy: 0,
      psoccupancy: 0,
      initdone: 0,
      status: 0,
      text: [
        {
          time: 1506117496,
          username: "Gaben",
          text: "Chat initialized ..."
        },
        {
          time: 1506117500,
          username: "Solo",
          text: "So, say something !!"
        },
        {
          time: 1506117530,
          username: "Neo",
          text: "Hmmm ..."
        }
      ]
    };
  },
  methods: {
    adjustScroll() {
      var scroll = document.querySelector(".vue-steam-chat__wrapper--scroll");
      var view = document.querySelector(".bottomfill");
      var toggle = document.querySelector(".togglearea");
      var channels = document.querySelector(".channelbar");

      if (!this.reverseorder) {
        scroll.scrollTop = 0;
        //$("html,body").animate({ scrollTop: 0 }, "slow");
        // view.scrollIntoView(true);
        view.scrollIntoView({
          behavior: "smooth",
          block: "start",
          inline: "nearest"
        });
      } else {
        scroll.scrollTop = scroll.scrollHeight;
        // channels.scrollIntoView(false);
        channels.scrollIntoView({
          behavior: "smooth",
          block: "end",
          inline: "nearest"
        });
        //$("html,body").animate({ scrollTop: scroll.scrollHeight }, "slow");
      }
    },
    initScroll() {
      var view = document.querySelector(".bottomfill");
      var channels = document.querySelector(".channelbar");
      var scroll = document.querySelector(".vue-steam-chat__wrapper--scroll");
      //$("html,body").animate({ scrollTop: scroll.scrollHeight }, "slow");
      //channels.animate({ scrollIntoView: false }, "slow");
      view.scrollIntoView({
        behavior: "smooth",
        block: "end",
        inline: "nearest"
      });
    },
    getHereNow() {
      var that = this;
      pubnub.hereNow(
        {
          channels: ["ch1"],
          // channelGroups : ["cg1"],
          includeUUIDs: true,
          includeState: true
        },
        function(status, response) {
          that.psoccupancy = response.totalOccupancy;
          // console.log("herenow: ", response);
          var allusers = "";
          var index = 0;

          response.channels.ch1.occupants.forEach(function(user) {
            if (response.channels.ch1.occupants) {
              that.userarray.push(user);
              if (index == 0) allusers = user.uuid;
              else allusers = allusers + ", " + user.uuid;
            }
            index++;
            that.userlist = allusers;
          });
        }
      );
    },
    gmCallback(status, response) {
      console.log("gm callback", status, response);
    },
    history() {
      var that = this;
      if (pubnub) {
        pubnub.history(
          {
            reverse: false,
            channel: "ch1",
            count: 100, // how many items to fetch
            stringifiedTimeToken: true // false is the default
          },
          function(status, response) {
            if (status.error == false) {
              response.messages.forEach(function(element) {
                if (element.entry.username && element.entry.text != undefined) {
                  if (
                    element.entry.text.match(/Forum Replied To/g) ||
                    element.entry.text.match(/Forum Started Post/g)
                  ) {
                    if (that.postsbox == true) {
                      that.text.push(element.entry);
                    }
                  } else if (element.entry.text.match(/Forum Status/g)) {
                    if (that.statusbox == true) {
                      that.text.push(element.entry);
                    }
                  } else if (that.livebox == true) {
                    that.text.push(element.entry);
                  }
                }
              });
              that.historydone = true;
            } else {
              console.log("error ", status);
            }
          }
        );
      }
      that.initScroll();
    },
    controlMessage(message) {
      var that = this;
      if (message.length < 2) {
        return false;
      }
      let m = {
        time: Date.now() / 1000,
        username: this.uuid,
        text: message
      };
      var publishConfig = {
        sendByPost: true,
        channel: "controlreply",
        message: m
      };

      pubnub.publish(publishConfig, function(status, response) {
        if (status.error) {
          console.log(status);
        } else {
          // console.log("control message Published w/ timetoken", JSON.stringify(publishConfig));
        }
      });
    },

    onNewMessage(message) {
      var that = this;
      if (message.length < 2) {
        return false;
      }
      let m = {
        time: Date.now() / 1000,
        username: this.uuid,
        text: message
      };
      var publishConfig = {
        sendByPost: true,
        channel: "ch1",
        message: m
      };

      if (that.blockpublish != true) {
        pubnub.publish(publishConfig, function(status, response) {
          if (status.error) {
            console.log(status);
          } else {
            // console.log("message Published w/ timetoken", response.timetoken);
          }
        });
        that.getHereNow();
        // that.adjustScroll();
      }
    }
  },
  created() {
    $.LoadingOverlay("show");
    pubnub.subscribe({
      channels: ["ch1", "control"],
      withPresence: false
    });
  },
  updated() {
    debounce(this.getHereNow, 300, true);

    this.adjustScroll();
  },
  beforeDestroy() {
    //pubnub.unsubscribeAll();
    pubnub.unsubscribe({
      channels: ["ch1", "control"]
    });
    var existingListener = {
      message: function() {}
    };

    if (existingListener) pubnub.removeListener(existingListener);
    if (interval) {
      clearInterval(interval);
    }
  },
  async mounted() {
    if (localStorage.blc) {
      if (localStorage.getItem("blc") == "true") {
        this.blockpublish = true;
      }
    }
    if (localStorage.status_msgs) {
      if (localStorage.getItem("status_msgs") == "yes") {
        this.statusbox = true;
      }
    }
    var that = this;
    that.history();

    pubnub.addListener({
      // status: function(statusEvent) {
      //   if (statusEvent.category === "PNConnectedCategory") {
      //     var newState = {
      //       name: this.uuid,
      //       timestamp: Date.now()
      //     };
      //     pubsub.setState({
      //       channels: ["ch1"],
      //       state: newState
      //     });
      //   }
      // },
      message: function(m) {
        // console.log("livechat msg channel received: ", JSON.stringify(m));
        that.adjustScroll();
        if (m.channel == "ch1") {
          if (
            m.message.text.match(/Forum Replied To/g) ||
            m.message.text.match(/Forum Started Post/g)
          ) {
            if (that.postsbox == true) {
              that.text.push(m.message);
            }
          } else if (m.message.text.match(/Forum Status/g)) {
            if (that.statusbox == true) {
              that.text.push(element.entry);
            }
          } else if (that.livebox == true) {
            that.text.push(m.message);
          }
        } else if (m.channel == "control") {
          if (m.message.text.match(/ping/gi)) {
            that.controlMessage(
              "IAMHERE V" +
                that.$store.state.version.toFixed(4) +
                " Blocked: " +
                that.blockpublish
            );
          }
          //   console.log("live chat control", m.channel, m.message);
         ///
         /// deleted internal stuff
      ///
        }
        that.getHereNow();
        //that.text.push(m.message);
        //console.log("newmsg: ", m.message);
      },
      presence: function(presenceEvent) {
        that.psoccupancy = presenceEvent.occupancy;
        //const i = Date.now();
        console.log("listen presence", presenceEvent);
        that.getHereNow();
      }
    });
    this.getHereNow();
    var mythis = this;
    $(function() {
      var input = document.querySelector(".vue-steam-chat__textarea");
      var button = document.querySelector(".vue-steam-chat__button");
      var scroll = document.querySelector(".vue-steam-chat__wrapper--scroll");
      input.addEventListener("keyup", function(event) {
        if (event.keyCode === 13) {
          event.preventDefault();
          button.click();
        }
      });
      $.LoadingOverlay("hide");
    });
  }
};
</script>
<style scoped>
.box {
  margin: 0px !important;
  height: 500px;
  margin: 20px;
}

.neo-chat-title {
  color: slategray;
  font-size: 1.2em;
  text-align: center;
  margin: 10px;
}

.room {
  margin-bottom: 20px;
}

.ckbox {
  margin-right: 7px;
  background-color: cornflowerblue;
}

.reverseon {
  color: cornflowerblue;
}

.liveon {
  color: cornflowerblue;
}

.ckbox {
  color: cornflowerblue;
}

.nomargin {
  margin: 0px 0px 0px 0px;
}

.leftmargin {
  margin-left: 30px;
}

.toggler {
  margin: 10px 10px 0px 0px;
}

.channelbar {
  margin: 100px 10px 10px 10px;
  padding-bottom: 10px;
}

.bottomfill {
  margin-bottom: 0px;
  padding-top: 20px;
}
</style>

# 27  
Old 05-07-2019
Feedback on PubNub issues/code

Neo -

If you are actually using the demo keys, you have two things that are different than the key sets you get in your own PubNub Account:
  1. demo keys have a tight publish throttling setting
  2. demo keys have a 30s long poll setting instead of the default 280s
Code:
var pubnub = new PubNub({
        subscribeKey: "demo",
        publishKey: "demo",
        ssl: true,
        keepAlive: true,
        // heartbeatInterval: 10,
        presenceTimeout: 300,
        restore: true,
        uuid: vbchat
    });

Minor feedback
  • keepAlive likely as no effect on browser connections so this only makes sense in Node apps and IIRC, it is default enabled.
  • presenceTimeout : 300 is default so that can be removed
  • heartbeatInterval : 10 will cause a presence heartbeat API to happen every 10s, so keep that commented out

Inquiries
debounce(this.getHereNow, 300, false);
  1. How often is debounce called and what does it do?
  2. What does the "300" and the "false" paremeters mean?

Would like to see the app running to investigate further.

Cheers
Craig
This User Gave Thanks to pubnubcraig For This Post:
# 28  
Old 05-07-2019
Hi Craig,

Thanks for your reply here at unix.com.

Regarding debounce(), this is from the npm debounce package (currently showing over 500K weekly downloads - a shout out to that achievement) here:

Code:
https://www.npmjs.com/package/debounce

where:

Code:
debounce(fn, wait, [ immediate || false ])

Quote:
Creates and returns a new debounced version of the passed function that will postpone its execution until after wait milliseconds have elapsed since the last time it was invoked.

Pass true for the immediate parameter to cause debounce to trigger the function on the leading edge instead of the trailing edge of the wait interval. Useful in circumstances like preventing accidental double-clicks on a "submit" button from firing a second time.

The debounced function returned has a property 'clear' that is a function that will clear any scheduled future executions of your function.

The debounced function returned has a property 'flush' that is a function that will immediately execute the function if and only if execution is scheduled, and reset the execution timer for subsequent invocations of the debounced function.
But in the case of our beta Vue.js live chat component we are working with; in the Vue.js updated() lifecycle hook:

Code:
 updated() {
    debounce(this.getHereNow, 300, false);
  },

When false, the
Code:
this.getHereNow()

function is not executed (according to Chrome DevTools and console.log()) because the updated() lifecycle hook is faster than 300 ms and false sets the function to fire at the trailing edge of the 300ms.

Hence, this line of code, as written does not fire (I assume you noticed that and hence that is why you were asking) because at 300 ms, the function instance does not exist anymore due to the speed of the Vue lifecycle (it's like a gaming loop, if you are familiar with game programming, which I assume you are)..

I was mainly experimenting with it (debouncing in the updated lifecycle hook) and how changes and updates in the Vue lifecycle might be used to effect pubnub HereNow updates. I will remove this line of code soon because, I guess.

Regarding your remark, "Would like to see the app running to investigate further," this is running live here:

Code:
https://community.unix.com/

The current version is 0.7602 (bottom right in the page) and if you see an earlier version, best to clear your JS files from the cache and insure you have the latest version; but I am sure you know that being a JS person!

This app needs more tweaking, as I still not running the API as efficiently as it should be, and the presence (hereNow) is not working (in the Vue.js app) as well as I would like. Basically, I want the list of folks viewing live chat to remain current without a page reload and without excess API polling; so I have tried to update this during changes in the app, for example (1) when a message is received, the occupancy and names will update; and I was experimenting with the Vue.js lifecycle to update occupancy and the uuid list when someone interacts with app, but that is not working as well as I would like (the update() - debounce() ) idea.

Ideally, it seems to be that PubNub should add a configuration parameter to the subscribe() API as follows;

Code:
pubnub.subscribe({
      channels: ["ch1", "control"],
      withPresence: true,
     presenceInterval:   10000 // milliseconds
    });

I notice PubNub often (mostly) uses seconds in API configuration parameters in the SDK. I think it would be better and more consistent to change it to milliseconds (in all PubNub API configuration params) like Javascript interval timers, but then again, I am not a great Javascript developer, or even a good one, so I need to be careful what I am recommending.

I am just a "wannabe" great Javascript developer and "wannabe" expert on PubNub Javascript SDK so I can use PubNub in more sophisticated cybersecurity applications. This live chat app is just getting my feet wet and is not the end goal. It is just a humble beginning.
Login or Register to Ask a Question

Previous Thread | Next Thread

4 More Discussions You Might Find Interesting

1. What is on Your Mind?

Update: UserCP Screeching Frog 0.7641 - Changed Live Chat to Live Updates

Update: UserCP Screeching Frog 0.7641 - Changed Live Chat to Live Updates In this version of the UserCP, I have changed "Live Chat" to "Live Updates" by disabling the ability to post in the "live chat" area and changed the name to "Live Updates" The reason for this change is that experienced... (6 Replies)
Discussion started by: Neo
6 Replies

2. What is on Your Mind?

Live Chat (Alpha) in UserCP SF 0.7517

Interesting.... I am still working on the kinks for Live Chat here at unix.com using a publish-subscribe API from PubNub. Two days ago while working on it, a new user joined the live chat and asked about how to post a new thread in the forum. Then today, one of the members of the PubNub team... (23 Replies)
Discussion started by: Neo
23 Replies

3. What is on Your Mind?

A Quick Video Overview of PubNub Live Chat @UNIX.com (version 0.7614)

A number of people have asked me to make some videos, so I just got my first condenser microphone and so I can make some amateurish screen casts. I will try to do better in the future. A quick overview of PubNub Live Chat @unix.com The video is best is you set the Quality to HD 1080. The... (0 Replies)
Discussion started by: Neo
0 Replies

4. Solaris

Live Chat For Solaris?

Does anyone know of any online live chat discussion groups for Solaris? If so, please let me know... Thanks! Rob Sandifer (3 Replies)
Discussion started by: RobSand
3 Replies
Login or Register to Ask a Question