0

Currently trying to implement a live chat feature on my website using Node.js and Heroku, I've done my best to follow these steps to deploy with no avail: http://tutorialzine.com/2014/03/nodejs-private-webchat/

I created the initial chat server by watching these tutorial videos: https://www.youtube.com/playlist?list=PLfdtiltiRHWHZh8C2G0xNRbcf0uyYzzK_

One thing that puzzles me is that I do not have an app.js file, that is described in the walkthrough on the first link I posted. Is this just similar to my server.js?

Here is my code:

HTML (UPDATED): (I have a script a couple lines down the code src="http://127.0.0.1:8080/socket.io/socket.io.js" do I need to delete/edit this? I've already deleted the localhost from var socket = io.connect();)

<!DOCTYPE html>
            <html>
              <head>
                <title>Chat</title>
                <link rel="stylesheet" href="main.css">
              </head>



              <body>
                <div class="all-content">
                <div class="header-bar">
                  <div class="bar">
                      <img src="C:\Users\jlewa\Desktop\assets\affinity_fm_only_letters.png" class="top-logo" style="float: left;">
                      <ul class="standard-nav" style="float: left;">
                        <li>Home</li>
                        <li>Lyrics Hub</li>
                        <li>Affinity LIVE</li>
                        <li>Merchandise</li>
                      </ul>
                  </div>
                  <div class="dropshadow"></div>
                </div>

                <div class="container-middle-third">
                  <div class="youtube-video" style="float: left;">
                    <div class="DJ-text">Affinity FM DJ Room</div>
                    <div class="DJ-underline"></div>
                    <div id="player" style="width: 1280px; height: 720px;"></div>
                  </div>
                  </div>

                  <div class="chat" style="float: left;">
                    <div class="Chat-text">Chat</div>
                    <div class="Chat-underline"></div>
                    <input type="text" class="chat-name" placeholder="Chat">
                        <div class="right-tab">
                            <div class="info-rect">INFO</div>
                        </div>
                    <div class="chat-messages"></div>
                    <textarea placeholder="Join the conversation..."></textarea>
                    <div class="chat-status">Status: <span>Idle</span></div>
                  </div>

                <div class="bottom-bar">

                  <img src="C:\Users\jlewa\Desktop\assets\affinitylogo.png" class="thumbnail" id="thumbnail" style="float: left">

                  <div class="title-bar" style="float: left;">

                    <div class="title" id="title"></div>
                    <div class="dj-playing">Affinity FM is playing</div>

                    <div class="progress-background">
                      <div id="progress-bar" class="progress-bar"></div>
                    </div>

                  </div>
                  <div class="subscribe" style="float: left;">



                    <div class="sub-container">

                        <div class="g-ytsubscribe" data-channel="SAMusicPlaylist" data-layout="full" data-theme="dark" data-count="default"></div> 



                    </div>


                  </div>

                </div>

     <!--do i need to get rid of this script? --> <script src="/socket.io/socket.io.js"></script>

                <script src="https://apis.google.com/js/platform.js"></script>

                <script>
                  (function() {
                    var getNode = function(s) {
                      return document.querySelector(s);
                    },

                        // Get required nodes
                        status = getNode('.chat-status span'),
                        messages = getNode('.chat-messages'), 
                        textarea = getNode('.chat textarea'),
                        chatName = getNode('.chat-name'),

                        statusDefault = status.textContent,    

                        setStatus = function(s){
                          status.textContent = s;

                          if(s !== statusDefault){
                            var delay = setTimeout(function(){
                              setStatus(statusDefault);
                              clearInterval(delay);
                            }, 3000);
                          }
                        };

                    //try connection
                    try{
                      var socket = io.connect(); <!--removed localhost -->
                    } catch(e){
                      //Set status to warn user
                    }

                    if(socket !== undefined){

                      //Listen for output
                      socket.on('output', function(data){
                        if(data.length){
                          //Loop through results
                          for(var x = 0; x < data.length; x = x + 1){
                            var message = document.createElement('div');
                            message.setAttribute('class', 'chat-message');
                            message.textContent = ': ' + data[x].message;
                            var name=document.createElement('span');
                            name.setAttribute('class', 'userName');
                            name.textContent = data[x].name;

                            message.insertBefore(name, message.firstChild);

                            //Append
                            messages.appendChild(message);
                            messages.insertBefore(message, messages.firstChild);
                          }
                        }
                      });

                      //Listen for a status
                      socket.on('status', function(data){
                        setStatus((typeof data === 'object') ? data.message : data);

                        if(data.clear === true){
                          textarea.value = '';
                        }
                      });

                      //Listen for keydown
                      textarea.addEventListener('keydown', function(event){
                        var self = this,
                            name = chatName.value;

                        if(event.which === 13 && event.shiftKey === false){
                          socket.emit('input', {
                            name: name,
                            message: self.value
                          });
                        }
                      });
                    }

                  })();
                </script>
                <script>
                  var time_total;
                  var timeout_setter;
                  var player;
                  var tag = document.createElement("script");//This code loads the IFrame Player API code asynchronously

                  tag.src = "https://www.youtube.com/iframe_api";
                  var firstScriptTag = document.getElementsByTagName("script")[0];
                  firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);

                  //This function creates an <iframe> (and YouTube player) OR uses the iframe if it exists at the "player" element after the API code downloads
                  function onYouTubeIframeAPIReady()
                  {
                    player = new YT.Player("player",
                                           {
                      height: "853",
                      width: "480",
                      /* videoId: "GGmxVDXM5X2UxaP9PvWQ4Z171DXyGcq", */
                      playerVars: {
                        listType:'playlist',
                        list: 'PL_GGmxVDXM5X2UxaP9PvWQ4Z171DXyGcq',
                        controls: '0',
                        html5: '1',
                        cc_load_policy: '0',
                        disablekb: '1',
                        iv_load_policy: '3',
                        modestbranding: '1',
                        showinfo: '0',
                        rel: '0',


                      },
                      events:
                      {
                        "onReady": onPlayerReady,
                        "onStateChange": onPlayerStateChange
                      }

                    });
                  }


                var num = (1 + Math.floor(Math.random() * 10));


                  //The API will call this function when the video player is ready
                  function onPlayerReady(event)
                  {
                    event.target.playVideo();
                    time_total  = convert_to_mins_and_secs(player.getDuration(), 1);
                    loopy();


                    player.addEventListener('onStateChange', 'onPlayerStateChange');


                    player.setShuffle( {
                    'shufflePlaylist': 1
                    } );    
                  }

                  function loopy()
                  {
                    var current_time = convert_to_mins_and_secs(player.getCurrentTime(), 0);
                    document.getElementById("progress-bar").style.width = (player.getCurrentTime()/player.getDuration())*100+"%";
                    console.log( current_time + " / " + time_total);
                    timeout_setter = setTimeout(loopy, 300);
                  }

                  function convert_to_mins_and_secs(seconds, minus1)
                  {
                    var mins    = (seconds>=60) ?Math.round(seconds/60):0;
                    var secs    = (seconds%60!=0) ?Math.round(seconds%60):0;
                    var secs    = (minus1==true) ?(secs-1):secs; //Youtube always displays 1 sec less than its duration time!!! Then we have to set minus1 flag to true for converting player.getDuration()
                    var time    = mins + ":" + ((secs<10)?"0"+secs:secs);
                    return time;
                  }

                  // 5. The API calls this function when the player's state changes
                  function onPlayerStateChange(event)
                  {
                    if (event.data == YT.PlayerState.ENDED)
                    {
                      console.log("END!");
                      clearTimeout(timeout_setter);
                      document.getElementById("progress-bar").style.cssText = "transition: none;";


                    }
                    else if (event.data == YT.PlayerState.PLAYING)
                    {
                      console.log("PLAYING");
                      loopy();
                      document.getElementById("progress-bar").style.cssText = "transition: all 300ms linear 0s;";
                      console.log(player.getPlayerState());
                      if (player.getPlayerState() == 1) {
                      document.getElementById( "title" ).innerText = player.getVideoData().title;
                        }
                    }
                    else if (event.data == YT.PlayerState.PAUSED)
                    {
                        event.target.playVideo();
                        console.log("PLAUSED");
                    }
                    else
                    {
                      console.log(event.data);
                    }
                  }
                </script>

                <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
               <!-- <script>
                    function make_request()
                    {
                        var response        = "";
                        var response1       = "thumbnail";
                        var api_key         = "AIzaSyApWxw8xp1qw09ByArSLD0XABQrE40cKEw";
                        var play_list_id    = "PL_GGmxVDXM5X2UxaP9PvWQ4Z171DXyGcq";
                        var url             = "https://www.googleapis.com/youtube/v3/playlists?part=snippet&id=" + play_list_id + "&key=" + api_key;

                        $.ajax
                        ({
                            url: url,
                            dataType: "json",
                            type: "get",
                            async: false,
                            success: function(data)
                            {
                                response = JSON.stringify(data);
                                response1 = data;
                            }
                        });
                        alert(response1.items[0].snippet.thumbnails.default.url);
                        console.log(response1.items[0].snippet.thumbnails.medium.url);
                        console.log(response);
                    }

                    function init()
                    {
                        gapi.client.setApiKey("AIzaSyApWxw8xp1qw09ByArSLD0XABQrE40cKEw");
                        gapi.client.load('youtube', 'v3').then(make_request);
                    }
                  </script>
                  <script src="https://apis.google.com/js/client.js?onload=init"></script> -->
                    </div>
              </body>

           </html>

Server.js: (I used Mongo for local hosting, do I need to delete some localhost stuff here?)

var mongo = require('mongoDB').MongoClient,
    client = require('socket.io').listen(8080).sockets;

mongo.connect('mongodb://127.0.0.1/chat', function(err, db) {
    if(err) throw err;

    client.on('connection', function(socket){

        var col = db.collection('messages'),
            sendStatus = function(s){
                socket.emit('status', s);   
            };

        //Emit all messages
        col.find().limit(100).sort({_id: 1}).toArray(function(err, res) {
            if(err) throw err;
            socket.emit('output', res);
        });

        //wait for input
        socket.on('input', function(data){
            var name = data.name,
                message = data.message,
                whitespacePattern = /^\s*$/;

            if(whitespacePattern.test(name) || whitespacePattern.test(message)){
                sendStatus('Name and Message is required.');
            } else {
                col.insert({name: name, message: message}, function(){

                    //Emit latest message to ALL clients
                    client.emit('output', [data]);

                  sendStatus({
                      message: "Message sent",
                      clear: true
                  });

                });   
            }

        });

    });

});

package.json (UPDATED):

  {
  "name": "live-chat",
  "version": "1.0.0",
  "engines":{
    "node": "4.4.5"
},
  "description": "a live chat for Affinity LIVE",
  "main": "server.js",
  "dependencies": {
    "mongodb": "^2.1.18",
    "socket.io": "^1.4.6"
  },
  "devDependencies": {},
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "start": "node server.js"
  },
  "keywords": [
    "live",
    "chat"
  ],
  "author": "Jordan Lewallen",
  "license": "ISC"
}

Heroku Log (UPDATED):

2016-06-22T05:42:21.990238+00:00 app[web.1]: npm ERR!     npm owner ls live-chat
2016-06-22T05:42:21.998667+00:00 app[web.1]: npm ERR!     /app/npm-debug.log
2016-06-22T05:42:23.128513+00:00 heroku[web.1]: Process exited with status 1
2016-06-22T05:42:23.147472+00:00 heroku[web.1]: State changed from starting to crashed
2016-06-22T05:42:24.269961+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host=young-wave-94499.herokuapp.com request_id=0a4b2290-a946-49a5-9f67-e216aa71e33e fwd="23.92.9.183" dyno= connect= service= status=503 bytes=

This is the error I get when I type 'heroku open' into cmd prompt:

enter image description here

Jordan Lewallen
  • 1,681
  • 19
  • 54
  • can you show me heroku logs? and please add "start" key in your package.json file – uzaif Jun 22 '16 at 04:58
  • and you forgot define your dependency in package.json – uzaif Jun 22 '16 at 05:04
  • 1
    Hi @uzaif I have updated my post with the log and added a start key to package.json file, I think. Could you explain what I need to do for dependency? Thank you for your help! – Jordan Lewallen Jun 22 '16 at 05:13
  • which modules did you install in this application `npm install` – uzaif Jun 22 '16 at 05:38
  • @uzaif oh gotcha, spent some time working through it and I think I got the package.json running correctly (still errors though). I updated that text and the NEW application error log in my original post – Jordan Lewallen Jun 22 '16 at 05:47
  • on which port your server is running? – uzaif Jun 22 '16 at 05:51

2 Answers2

0

In your package.json file you need to include:

  1. any dependencies you have

  2. a section titled "engines" where you state the version of node you are using.

Be sure to check out this link from heroku: https://devcenter.heroku.com/articles/deploying-nodejs

Clay James
  • 23
  • 4
  • thanks for the info, I looked through and updated dependencies and engines in package.json. I updated the code for that and the NEW error log in my original post – Jordan Lewallen Jun 22 '16 at 05:48
  • @Jordan-Lewallen heroku sets its own port. try having socket.io listen on: (process.env.PORT || 8080) – Clay James Jun 22 '16 at 19:41
  • I changed the index.html line to var socket = io.connect('process.env.PORT || 8080'); with an application error. What can I send that will make debugging this easier for you? – Jordan Lewallen Jun 22 '16 at 19:57
  • I think that the html file was good how it was(you shouldn't specify a port there). What I meant was to change the port in the server.js on line 2. As far as sending anything else, I think the heroku logs are just fine. – Clay James Jun 22 '16 at 20:03
  • Oh I see, my fault. Changed line 2 of server.js to client = require('socket.io').listen(process.env.PORT || 8080).sockets; also on another response it was requested that my mongo.connect line be changed to something that heroku can reach. So I set up mLab and put this in line 4 of server.js: mongo.connect('mongodb://jlewallen18:MYPASSWORD@ds021434.mlab.com:21434/heroku_ccsbtmfd', function(err, db) { if(err) throw err; still get application error by the way – Jordan Lewallen Jun 22 '16 at 20:16
  • edited the comment probably after you opened the reply stating that it still does not work @Clay James – Jordan Lewallen Jun 22 '16 at 20:20
  • Ahh yeah I see that now. Well if that didn't fix it, I'm not sure what else to do. My guess would be that it is a MongoDb problem, but I've never worked with that before so I'm not sure how to fix it. I found one relevant link to point you towards though: http://stackoverflow.com/questions/18076335/cant-connect-to-mongolab-with-node-js-on-heroku best of luck to you. – Clay James Jun 22 '16 at 20:29
  • thanks for sending the link over, I think it is a mongo thing as well...I wasn't able to get it to work. Back to searching. Thanks for your time – Jordan Lewallen Jun 22 '16 at 21:15
0

You will need to adjust the url for your mongoDB to something heroku can reach. You could set that up with a service like mLab

mongo.connect('mongodb://mongodb.example.com/database', function(err, db) { ... });

Right now it is just pointing to the local machine.

For your html you'll need to change the urls, too. Something like this would probably work:

<script src="/socket.io/socket.io.js"></script>

I saw a couple more things pointing to your local machine.

Sebastian
  • 92
  • 1
  • 7
  • Hi @Sebastian, I am trying to set up the mLab database. One of the first few steps states that I need to connect using the mongo shell: mongo ds021434.mlab.com:21434/heroku_ccsbtmfd -u -p , when I type in my user and pass, I get authentification failed. I made sure to use my databaser username and password too (they said this was a common issue) – Jordan Lewallen Jun 22 '16 at 06:52