aboutsummaryrefslogtreecommitdiff
path: root/cli/onionshare_cli/resources/static/js/chat.js
blob: b4ef30dfa0b90dc20d9271c59abc4d188feefd9b (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
$(function () {
  $(document).ready(function () {
    $('.chat-container').removeClass('no-js');
    var socket = io.connect(
      'http://' + document.domain + ':' + location.port + '/chat',
      {
        transports: ['websocket']
      }
    );

    // Store current username received from app context
    var current_username = $('#username').val();

    // On browser connect, emit a socket event to be added to
    // room and assigned random username
    socket.on('connect', function () {
      socket.emit('joined', {});
    });

    // Triggered on any status change by any user, such as some
    // user joined, or changed username, or left, etc.
    socket.on('status', function (data) {
      addMessageToRoom(data, current_username, 'status');
      console.log(data, current_username);
    });

    // Triggered when message is received from a user. Even when sent
    // by self, it get triggered after the server sends back the emit.
    socket.on('message', function (data) {
      addMessageToRoom(data, current_username, 'chat');
      console.log(data, current_username);
    });

    // Triggered when disconnected either by server stop or timeout
    socket.on('disconnect', function (data) {
      addMessageToRoom({ 'msg': 'The chat server is disconnected.' }, current_username, 'status');
    })
    socket.on('connect_error', function (error) {
      console.log("error");
    })

    // Trigger new message on enter or click of send message button.
    $('#new-message').on('keypress', function (e) {
      var code = e.keyCode || e.which;
      if (code == 13) {
        emitMessage(socket);
      }
    });

    // Keep buttons disabled unless changed or not empty
    $('#username').on('keyup', function (event) {
      if ($('#username').val() !== '' && $('#username').val() !== current_username) {
        if (event.keyCode == 13 || event.which == 13) {
          this.blur();
          current_username = updateUsername(socket) || current_username;
        }
      }
    });

    // Show warning of losing data
    $(window).on('beforeunload', function (e) {
      e.preventDefault();
      e.returnValue = '';
      return '';
    });
  });
});

var addMessageToRoom = function (data, current_username, messageType) {
  var scrollDiff = getScrollDiffBefore();
  if (messageType === 'status') {
    addStatusMessage(data.msg);
    if (data.connected_users) {
      addUserList(data.connected_users, current_username);
    }
  } else if (messageType === 'chat') {
    addChatMessage(data.username, data.msg)
  }
  scrollBottomMaybe(scrollDiff);
}

var emitMessage = function (socket) {
  var text = $('#new-message').val();
  $('#new-message').val('');
  $('#chat').scrollTop($('#chat')[0].scrollHeight);
  socket.emit('text', { msg: text });
}

var updateUsername = function (socket) {
  var username = $('#username').val();
  if (!checkUsernameExists(username) && !checkUsernameTooLong(username)) {
    $.ajax({
      method: 'POST',
      url: `http://${document.domain}:${location.port}/update-session-username`,
      contentType: 'application/json',
      dataType: 'json',
      data: JSON.stringify({ 'username': username })
    }).done(function (response) {
      console.log(response);
      if (response.success && response.username == username) {
        socket.emit('update_username', { username: username });
      }
    });
    return username;
  }
  return false;
}

/************************************/
/********* Util Functions ***********/
/************************************/

var createUserListHTML = function (connected_users, current_user) {
  var userListHTML = '';
  connected_users.sort();
  connected_users.forEach(function (username) {
    if (username !== current_user) {
      userListHTML += `<li>${sanitizeHTML(username)}</li>`;
    }
  });
  return userListHTML;
}

var checkUsernameExists = function (username) {
  $('#username-error').text('');
  var userMatches = $('#user-list li').filter(function () {
    return $(this).text() === username;
  });
  if (userMatches.length) {
    $('#username-error').text('User with that username exists!');
    return true;
  }
  return false;
}

var checkUsernameTooLong = function (username) {
  $('#username-error').text('');
  if (username.length > 128) {
    $('#username-error').text('Please choose a shorter username.');
    return true;
  }
  return false;
}

var getScrollDiffBefore = function () {
  return $('#chat').scrollTop() - ($('#chat')[0].scrollHeight - $('#chat')[0].offsetHeight);
}

var scrollBottomMaybe = function (scrollDiff) {
  // Scrolls to bottom if the user is scrolled at bottom
  // if the user has scrolled up, it won't scroll at bottom.
  // Note: when a user themselves send a message, it will still
  // scroll to the bottom even if they had scrolled up before.
  if (scrollDiff > 0) {
    $('#chat').scrollTop($('#chat')[0].scrollHeight);
  }
}

var addStatusMessage = function (message) {
  $('#chat').append(
    `<p class="status">${sanitizeHTML(message)}</p>`
  );
}

var addChatMessage = function (username, message) {
  $('#chat').append(`<p><span class="username">${sanitizeHTML(username)}</span><span class="message">${sanitizeHTML(message)}</span></p>`);
}

var addUserList = function (connected_users, current_username) {
  $('#user-list').html(
    createUserListHTML(
      connected_users,
      current_username
    )
  );
}

var sanitizeHTML = function (str) {
  var temp = document.createElement('span');
  temp.textContent = str;
  return temp.innerHTML;
};