' + util.toStaticHTML(from) + ' says to ' + name + ': ' + '
' + '
' + text + '
' + '
';
88 | messageElement.html(content);
89 | //the log is the stream that we view
90 | $("#chatHistory").append(messageElement);
91 | base += increase;
92 | scrollDown(base);
93 | }
94 |
95 | // show tip
96 | function tip(type, name) {
97 | var tip, title;
98 | switch (type) {
99 | case 'online':
100 | tip = name + ' is online now.';
101 | title = 'Online Notify';
102 | break;
103 | case 'offline':
104 | tip = name + ' is offline now.';
105 | title = 'Offline Notify';
106 | break;
107 | case 'message':
108 | tip = name + ' is saying now.';
109 | title = 'Message Notify';
110 | break;
111 | }
112 | var pop = new Pop(title, tip);
113 | }
114 |
115 | // init user list
116 | function initUserList(data) {
117 | users = data.users;
118 | for (var i = 0; i < users.length; i++) {
119 | var slElement = $(document.createElement("option"));
120 | slElement.attr("value", users[i]);
121 | slElement.text(users[i]);
122 | $("#usersList").append(slElement);
123 | }
124 | }
125 |
126 | // add user in user list
127 | function addUser(user) {
128 | var slElement = $(document.createElement("option"));
129 | slElement.attr("value", user);
130 | slElement.text(user);
131 | $("#usersList").append(slElement);
132 | }
133 |
134 | // remove user from user list
135 | function removeUser(user) {
136 | $("#usersList option").each(
137 | function () {
138 | if ($(this).val() === user) $(this).remove();
139 | });
140 | }
141 |
142 | // set your name
143 | function setName() {
144 | $("#name").text(username);
145 | }
146 |
147 | // show error
148 | function showError(content) {
149 | $("#loginError").text(content);
150 | $("#loginError").show();
151 | }
152 |
153 | // show chat panel
154 | function showChat() {
155 | $("#toolbar").show();
156 | $("entry").focus();
157 | scrollDown(base);
158 | }
159 |
160 |
161 |
162 | $(document).ready(function () {
163 | observer = {
164 | handlePeerMessage: function (msg) {
165 | //console.log("msg sender:", msg.sender, " receiver:", msg.receiver, " content:", msg.content, " timestamp:", msg.timestamp);
166 | addMessage(msg.sender, msg.receiver, msg.content);
167 | $("#chatHistory").show();
168 | //if (msg.sender !== username)
169 | // tip('message', msg.sender);
170 | },
171 | handleMessageACK: function(msg) {
172 | //console.log("message ack local id:", msgLocalID, " receiver:", receiver)
173 | },
174 | handleMessageFailure: function(msg) {
175 | //console.log("message fail local id:", msgLocalID, " receiver:", receiver)
176 | },
177 | onConnectState: function(state) {
178 | if (state == IMService.STATE_CONNECTED) {
179 | console.log("im connected");
180 | } else if (state == IMService.STATE_CONNECTING) {
181 | console.log("im connecting");
182 | } else if (state == IMService.STATE_CONNECTFAIL) {
183 | console.log("im connect fail");
184 | } else if (state == IMService.STATE_UNCONNECTED) {
185 | console.log("im unconnected");
186 | }
187 | }
188 | };
189 |
190 | var im = new IMService();
191 | im.host = host;
192 | im.observer = observer;
193 |
194 | var r = util.getURLParameter('receiver', location.search);
195 | if (r) {
196 | receiver = r;
197 | } else {
198 | receiver = 0;
199 | }
200 | console.log("receiver:" + receiver)
201 |
202 | r = util.getURLParameter('sender', location.search);
203 | if (r) {
204 | sender = r;
205 | } else {
206 | sender = 0;
207 | }
208 | username = sender;
209 | console.log("sender:" + sender)
210 |
211 |
212 | addUser(receiver);
213 | token = util.getCookie("token");
214 | console.log("token:" + token)
215 | im.accessToken = token
216 | im.start();
217 |
218 |
219 | setName();
220 | showChat();
221 | //deal with chat mode.
222 | $("#entry").keypress(function (e) {
223 | var target = $("#usersList").val();
224 | if (e.keyCode != 13 /* Return */) return;
225 | var msg = $("#entry").val().replace("\n", "");
226 | if (!util.isBlank(msg)) {
227 | var now = new Date().getTime() / 1000;
228 | var obj = {"text": msg};
229 | var textMsg = JSON.stringify(obj);
230 | var message = {sender:username, receiver: target, content: textMsg, timestamp:now, msgLocalID:msgLocalID++};
231 | if (im.connectState == IMService.STATE_CONNECTED) {
232 | im.sendPeerMessage(message);
233 | $("#entry").val(""); // clear the entry field.
234 | if (target != '*' && target != username) {
235 | addMessage(username, target, msg);
236 | $("#chatHistory").show();
237 | }
238 | }
239 | }
240 | });
241 | });
242 |
--------------------------------------------------------------------------------
/demo/static/js/client.js:
--------------------------------------------------------------------------------
1 | var username;
2 | var receiver;
3 | var users;
4 | var base = 1000;
5 | var msgLocalID=0;
6 | var increase = 25;
7 |
8 | util = {
9 | urlRE: /https?:\/\/([-\w\.]+)+(:\d+)?(\/([^\s]*(\?\S+)?)?)?/g,
10 | // html sanitizer
11 | toStaticHTML: function (inputHtml) {
12 | inputHtml = inputHtml.toString();
13 | return inputHtml.replace(/&/g, "&").replace(//g, ">");
14 | },
15 | //pads n with zeros on the left,
16 | //digits is minimum length of output
17 | //zeroPad(3, 5); returns "005"
18 | //zeroPad(2, 500); returns "500"
19 | zeroPad: function (digits, n) {
20 | n = n.toString();
21 | while (n.length < digits)
22 | n = '0' + n;
23 | return n;
24 | },
25 | //it is almost 8 o'clock PM here
26 | //timeString(new Date); returns "19:49"
27 | timeString: function (date) {
28 | var minutes = date.getMinutes().toString();
29 | var hours = date.getHours().toString();
30 | return this.zeroPad(2, hours) + ":" + this.zeroPad(2, minutes);
31 | },
32 |
33 | //does the argument only contain whitespace?
34 | isBlank: function (text) {
35 | var blank = /^\s*$/;
36 | return (text.match(blank) !== null);
37 | }
38 | };
39 |
40 | //always view the most recent message when it is added
41 | function scrollDown(base) {
42 | window.scrollTo(0, base);
43 | $("#entry").focus();
44 | }
45 |
46 | // add message on board
47 | function addMessage(from, target, text, time) {
48 | var name = (target == '*' ? 'all' : target);
49 | if (text === null) return;
50 | if (time == null) {
51 | // if the time is null or undefined, use the current time.
52 | time = new Date();
53 | } else if ((time instanceof Date) === false) {
54 | // if it's a timestamp, interpret it
55 | time = new Date(time);
56 | }
57 | //every message you see is actually a table with 3 cols:
58 | // the time,
59 | // the person who caused the event,
60 | // and the content
61 | var messageElement = $(document.createElement("table"));
62 | messageElement.addClass("message");
63 | // sanitize
64 | text = util.toStaticHTML(text);
65 | var content = '
' + '
' + util.timeString(time) + '
' + '
' + util.toStaticHTML(from) + ' says to ' + name + ': ' + '
' + '
' + text + '
' + '
';
66 | messageElement.html(content);
67 | //the log is the stream that we view
68 | $("#chatHistory").append(messageElement);
69 | base += increase;
70 | scrollDown(base);
71 | }
72 |
73 | // show tip
74 | function tip(type, name) {
75 | var tip, title;
76 | switch (type) {
77 | case 'online':
78 | tip = name + ' is online now.';
79 | title = 'Online Notify';
80 | break;
81 | case 'offline':
82 | tip = name + ' is offline now.';
83 | title = 'Offline Notify';
84 | break;
85 | case 'message':
86 | tip = name + ' is saying now.';
87 | title = 'Message Notify';
88 | break;
89 | }
90 | var pop = new Pop(title, tip);
91 | }
92 |
93 | // init user list
94 | function initUserList(data) {
95 | users = data.users;
96 | for (var i = 0; i < users.length; i++) {
97 | var slElement = $(document.createElement("option"));
98 | slElement.attr("value", users[i]);
99 | slElement.text(users[i]);
100 | $("#usersList").append(slElement);
101 | }
102 | }
103 |
104 | // add user in user list
105 | function addUser(user) {
106 | var slElement = $(document.createElement("option"));
107 | slElement.attr("value", user);
108 | slElement.text(user);
109 | $("#usersList").append(slElement);
110 | }
111 |
112 | // remove user from user list
113 | function removeUser(user) {
114 | $("#usersList option").each(
115 | function () {
116 | if ($(this).val() === user) $(this).remove();
117 | });
118 | }
119 |
120 | // set your name
121 | function setName() {
122 | $("#name").text(username);
123 | }
124 |
125 | // show error
126 | function showError(content) {
127 | $("#loginError").text(content);
128 | $("#loginError").show();
129 | }
130 |
131 | // show login panel
132 | function showLogin() {
133 | $("#loginView").show();
134 | $("#chatHistory").hide();
135 | $("#toolbar").hide();
136 | $("#loginError").hide();
137 | $("#loginUser").focus();
138 | }
139 |
140 | // show chat panel
141 | function showChat() {
142 | $("#loginView").hide();
143 | $("#loginError").hide();
144 | $("#toolbar").show();
145 | $("entry").focus();
146 | scrollDown(base);
147 | }
148 |
149 | $(document).ready(function () {
150 | //when first time into chat room.
151 | showLogin();
152 |
153 | observer = {
154 | handlePeerMessage: function (msg) {
155 | //console.log("msg sender:", msg.sender, " receiver:", msg.receiver, " content:", msg.content, " timestamp:", msg.timestamp);
156 | addMessage(msg.sender, msg.receiver, msg.content);
157 | $("#chatHistory").show();
158 | //if (msg.sender !== username)
159 | // tip('message', msg.sender);
160 | },
161 | handleMessageACK: function(msg) {
162 | //console.log("message ack local id:", msgLocalID, " receiver:", receiver)
163 | },
164 | handleMessageFailure: function(msg) {
165 | //console.log("message fail local id:", msgLocalID, " receiver:", receiver)
166 | },
167 |
168 | handleRTMessage: function(msg) {
169 | console.log("rt message sender:", msg.sender, " receiver", msg.receiver, " content:", msg.content);
170 | },
171 |
172 | onConnectState: function(state) {
173 | if (state == IMService.STATE_CONNECTED) {
174 | //console.log("im connected");
175 | // 连接成功
176 | setName();
177 | showChat();
178 | } else if (state == IMService.STATE_CONNECTING) {
179 | //console.log("im connecting");
180 | } else if (state == IMService.STATE_CONNECTFAIL) {
181 | //console.log("im connect fail");
182 | } else if (state == IMService.STATE_UNCONNECTED) {
183 | //console.log("im unconnected");
184 | //showLogin();
185 | }
186 | }
187 | };
188 |
189 | var im = new IMService(observer);
190 | im.host = host
191 | //deal with login button click.
192 | $("#login").click(function () {
193 | username = parseInt($("#loginUser").val());
194 |
195 | $.ajax({
196 | url: "auth/token",
197 | dataType: 'json',
198 | type: 'POST',
199 | contentType: "application/json",
200 | data:JSON.stringify({uid:username}),
201 | success: function(result, status, xhr) {
202 | if (status == "success") {
203 | console.log("login success:", result.token);
204 | receiver = parseInt($("#receiver").val());
205 | addUser(receiver);
206 | im.accessToken = result.token;
207 | im.start();
208 | } else {
209 | console.log("login error status:", status);
210 | alert("login fail");
211 | }
212 | },
213 | error : function(xhr, err) {
214 | console.log("login err:", err, xhr.status);
215 | alert("login fail");
216 | }
217 | });
218 | });
219 |
220 | //deal with chat mode.
221 | $("#entry").keypress(function (e) {
222 | var target = parseInt($("#usersList").val());
223 | if (e.keyCode != 13 /* Return */) return;
224 | var msg = $("#entry").val().replace("\n", "");
225 | if (!util.isBlank(msg)) {
226 |
227 | var message = {sender:username, receiver: target, content: msg, msgLocalID:msgLocalID++};
228 | if (im.connectState == IMService.STATE_CONNECTED) {
229 | im.sendPeerMessage(message);
230 |
231 | $("#entry").val(""); // clear the entry field.
232 | if (target != '*' && target != username) {
233 | addMessage(username, target, msg);
234 | $("#chatHistory").show();
235 | }
236 | }
237 | }
238 | });
239 | });
240 |
--------------------------------------------------------------------------------
/demo/static/js/customer_chat.js:
--------------------------------------------------------------------------------
1 | var username;
2 | var receiver;
3 | var users;
4 | var base = 1000;
5 | var msgLocalID=0;
6 | var increase = 25;
7 |
8 | var appID = 7;
9 | var uid = 0;
10 |
11 | var receiver = 0;
12 |
13 | //客服appid
14 | var receiverAppID = 17;
15 |
16 |
17 | util = {
18 | urlRE: /https?:\/\/([-\w\.]+)+(:\d+)?(\/([^\s]*(\?\S+)?)?)?/g,
19 | // html sanitizer
20 | toStaticHTML: function (inputHtml) {
21 | inputHtml = inputHtml.toString();
22 | return inputHtml.replace(/&/g, "&").replace(//g, ">");
23 | },
24 | //pads n with zeros on the left,
25 | //digits is minimum length of output
26 | //zeroPad(3, 5); returns "005"
27 | //zeroPad(2, 500); returns "500"
28 | zeroPad: function (digits, n) {
29 | n = n.toString();
30 | while (n.length < digits)
31 | n = '0' + n;
32 | return n;
33 | },
34 | //it is almost 8 o'clock PM here
35 | //timeString(new Date); returns "19:49"
36 | timeString: function (date) {
37 | var minutes = date.getMinutes().toString();
38 | var hours = date.getHours().toString();
39 | return this.zeroPad(2, hours) + ":" + this.zeroPad(2, minutes);
40 | },
41 |
42 | //does the argument only contain whitespace?
43 | isBlank: function (text) {
44 | var blank = /^\s*$/;
45 | return (text.match(blank) !== null);
46 | },
47 |
48 |
49 | getURLParameter: function(name, search) {
50 | search = search || location.search
51 | var param = search.match(
52 | RegExp(name + '=' + '(.+?)(&|$)'))
53 | return param ? decodeURIComponent(param[1]) : null
54 | },
55 |
56 | getCookie: function(c_name) {
57 | if (document.cookie.length>0) {
58 | c_start=document.cookie.indexOf(c_name + "=")
59 | if (c_start!=-1) {
60 | c_start=c_start + c_name.length+1
61 | c_end=document.cookie.indexOf(";",c_start)
62 | if (c_end==-1) c_end=document.cookie.length
63 | return unescape(document.cookie.substring(c_start,c_end))
64 | }
65 | }
66 | return ""
67 | },
68 |
69 | };
70 |
71 | //always view the most recent message when it is added
72 | function scrollDown(base) {
73 | window.scrollTo(0, base);
74 | $("#entry").focus();
75 | }
76 |
77 | // add message on board
78 | function addMessage(from, target, text, time) {
79 | var name = (target == '*' ? 'all' : target);
80 | if (text === null) return;
81 | if (time == null) {
82 | // if the time is null or undefined, use the current time.
83 | time = new Date();
84 | } else if ((time instanceof Date) === false) {
85 | // if it's a timestamp, interpret it
86 | time = new Date(time);
87 | }
88 | //every message you see is actually a table with 3 cols:
89 | // the time,
90 | // the person who caused the event,
91 | // and the content
92 | var messageElement = $(document.createElement("table"));
93 | messageElement.addClass("message");
94 | // sanitize
95 | text = util.toStaticHTML(text);
96 | var content = '
' + '
' + util.timeString(time) + '
' + '
' + util.toStaticHTML(from) + ' says to ' + name + ': ' + '
' + '
' + text + '
' + '
';
97 | messageElement.html(content);
98 | //the log is the stream that we view
99 | $("#chatHistory").append(messageElement);
100 | base += increase;
101 | scrollDown(base);
102 | }
103 |
104 | // show tip
105 | function tip(type, name) {
106 | var tip, title;
107 | switch (type) {
108 | case 'online':
109 | tip = name + ' is online now.';
110 | title = 'Online Notify';
111 | break;
112 | case 'offline':
113 | tip = name + ' is offline now.';
114 | title = 'Offline Notify';
115 | break;
116 | case 'message':
117 | tip = name + ' is saying now.';
118 | title = 'Message Notify';
119 | break;
120 | }
121 | var pop = new Pop(title, tip);
122 | }
123 |
124 | // init user list
125 | function initUserList(data) {
126 | users = data.users;
127 | for (var i = 0; i < users.length; i++) {
128 | var slElement = $(document.createElement("option"));
129 | slElement.attr("value", users[i]);
130 | slElement.text(users[i]);
131 | $("#usersList").append(slElement);
132 | }
133 | }
134 |
135 | // add user in user list
136 | function addUser(user) {
137 | var slElement = $(document.createElement("option"));
138 | slElement.attr("value", user);
139 | slElement.text(user);
140 | $("#usersList").append(slElement);
141 | }
142 |
143 | // remove user from user list
144 | function removeUser(user) {
145 | $("#usersList option").each(
146 | function () {
147 | if ($(this).val() === user) $(this).remove();
148 | });
149 | }
150 |
151 | // set your name
152 | function setName() {
153 | $("#name").text(username);
154 | }
155 |
156 | // show error
157 | function showError(content) {
158 | $("#loginError").text(content);
159 | $("#loginError").show();
160 | }
161 |
162 | // show chat panel
163 | function showChat() {
164 | $("#toolbar").show();
165 | $("entry").focus();
166 | scrollDown(base);
167 | }
168 |
169 |
170 |
171 | $(document).ready(function () {
172 | observer = {
173 | handleCustomerMessage: function(msg) {
174 | addMessage(msg.sender, msg.receiver, msg.content);
175 | $("#chatHistory").show();
176 | },
177 | handleCustomerMessageACK: function(msg) {
178 | console.log("handleCustomerMessageACK...");
179 | },
180 | handleCustomerMessageFailure: function(msg) {
181 | console.log("handleCustomerMessageFailure...");
182 | },
183 | onConnectState: function(state) {
184 | if (state == IMService.STATE_CONNECTED) {
185 | console.log("im connected");
186 | } else if (state == IMService.STATE_CONNECTING) {
187 | console.log("im connecting");
188 | } else if (state == IMService.STATE_CONNECTFAIL) {
189 | console.log("im connect fail");
190 | } else if (state == IMService.STATE_UNCONNECTED) {
191 | console.log("im unconnected");
192 | }
193 | }
194 | };
195 |
196 | var im = new IMService();
197 | im.host = host;
198 | im.observer = observer;
199 | im.customerMessageObserver = observer;
200 |
201 | var r = util.getURLParameter('receiver', location.search);
202 | if (r) {
203 | receiver = r;
204 | } else {
205 | receiver = 0;
206 | }
207 | console.log("receiver:" + receiver)
208 |
209 | r = util.getURLParameter('sender', location.search);
210 | if (r) {
211 | sender = r;
212 | } else {
213 | sender = 0;
214 | }
215 | username = sender;
216 | uid = sender;
217 | console.log("sender:" + sender)
218 |
219 |
220 | addUser(receiver);
221 | token = util.getCookie("token");
222 | console.log("token:" + token)
223 | im.accessToken = token
224 | im.start();
225 |
226 |
227 | setName();
228 | showChat();
229 | //deal with chat mode.
230 | $("#entry").keypress(function (e) {
231 | var target = $("#usersList").val();
232 | if (e.keyCode != 13 /* Return */) return;
233 | var msg = $("#entry").val().replace("\n", "");
234 | if (!util.isBlank(msg)) {
235 | var now = new Date().getTime() / 1000;
236 | var obj = {
237 | text:msg,
238 | name:"test",
239 | "app_name":"demo",
240 | "store_id":7,
241 | "store_name":"五湖四海",
242 | };
243 | var textMsg = JSON.stringify(obj);
244 |
245 | var message = {
246 | sender:uid,
247 | senderAppID:appID,
248 | receiver:receiver,
249 | receiverAppID:receiverAppID,
250 | content: textMsg,
251 | contentObj: obj,
252 | msgLocalID:msgLocalID++
253 | };
254 | message.outgoing = true;
255 | message.timestamp = now;
256 |
257 | if (im.connectState == IMService.STATE_CONNECTED) {
258 | im.sendCustomerMessage(message);
259 | $("#entry").val(""); // clear the entry field.
260 | if (target != '*' && target != username) {
261 | addMessage(username, target, msg);
262 | $("#chatHistory").show();
263 | }
264 | }
265 | }
266 | });
267 | });
268 |
--------------------------------------------------------------------------------
/demo/static/js/group_chat.js:
--------------------------------------------------------------------------------
1 | var username;
2 | var uid;
3 | var receiver;
4 | var users;
5 | var base = 1000;
6 | var msgLocalID=0;
7 | var increase = 25;
8 |
9 | util = {
10 | urlRE: /https?:\/\/([-\w\.]+)+(:\d+)?(\/([^\s]*(\?\S+)?)?)?/g,
11 | // html sanitizer
12 | toStaticHTML: function (inputHtml) {
13 | inputHtml = inputHtml.toString();
14 | return inputHtml.replace(/&/g, "&").replace(//g, ">");
15 | },
16 | //pads n with zeros on the left,
17 | //digits is minimum length of output
18 | //zeroPad(3, 5); returns "005"
19 | //zeroPad(2, 500); returns "500"
20 | zeroPad: function (digits, n) {
21 | n = n.toString();
22 | while (n.length < digits)
23 | n = '0' + n;
24 | return n;
25 | },
26 | //it is almost 8 o'clock PM here
27 | //timeString(new Date); returns "19:49"
28 | timeString: function (date) {
29 | var minutes = date.getMinutes().toString();
30 | var hours = date.getHours().toString();
31 | return this.zeroPad(2, hours) + ":" + this.zeroPad(2, minutes);
32 | },
33 |
34 | //does the argument only contain whitespace?
35 | isBlank: function (text) {
36 | var blank = /^\s*$/;
37 | return (text.match(blank) !== null);
38 | },
39 |
40 |
41 | getURLParameter: function(name, search) {
42 | search = search || location.search
43 | var param = search.match(
44 | RegExp(name + '=' + '(.+?)(&|$)'))
45 | return param ? decodeURIComponent(param[1]) : null
46 | },
47 |
48 | getCookie: function(c_name) {
49 | if (document.cookie.length>0) {
50 | c_start=document.cookie.indexOf(c_name + "=")
51 | if (c_start!=-1) {
52 | c_start=c_start + c_name.length+1
53 | c_end=document.cookie.indexOf(";",c_start)
54 | if (c_end==-1) c_end=document.cookie.length
55 | return unescape(document.cookie.substring(c_start,c_end))
56 | }
57 | }
58 | return ""
59 | },
60 |
61 | };
62 |
63 | //always view the most recent message when it is added
64 | function scrollDown(base) {
65 | window.scrollTo(0, base);
66 | $("#entry").focus();
67 | }
68 |
69 | // add message on board
70 | function addMessage(from, target, text, time) {
71 | var name = (target == '*' ? 'all' : target);
72 | if (text === null) return;
73 | if (time == null) {
74 | // if the time is null or undefined, use the current time.
75 | time = new Date();
76 | } else if ((time instanceof Date) === false) {
77 | // if it's a timestamp, interpret it
78 | time = new Date(time);
79 | }
80 | //every message you see is actually a table with 3 cols:
81 | // the time,
82 | // the person who caused the event,
83 | // and the content
84 | var messageElement = $(document.createElement("table"));
85 | messageElement.addClass("message");
86 | // sanitize
87 | text = util.toStaticHTML(text);
88 | var content = '
' + '
' + util.timeString(time) + '
' + '
' + util.toStaticHTML(from) + ' says to ' + name + ': ' + '
' + '
' + text + '
' + '
';
89 | messageElement.html(content);
90 | //the log is the stream that we view
91 | $("#chatHistory").append(messageElement);
92 | base += increase;
93 | scrollDown(base);
94 | }
95 |
96 | // show tip
97 | function tip(type, name) {
98 | var tip, title;
99 | switch (type) {
100 | case 'online':
101 | tip = name + ' is online now.';
102 | title = 'Online Notify';
103 | break;
104 | case 'offline':
105 | tip = name + ' is offline now.';
106 | title = 'Offline Notify';
107 | break;
108 | case 'message':
109 | tip = name + ' is saying now.';
110 | title = 'Message Notify';
111 | break;
112 | }
113 | var pop = new Pop(title, tip);
114 | }
115 |
116 | // init user list
117 | function initUserList(data) {
118 | users = data.users;
119 | for (var i = 0; i < users.length; i++) {
120 | var slElement = $(document.createElement("option"));
121 | slElement.attr("value", users[i]);
122 | slElement.text(users[i]);
123 | $("#usersList").append(slElement);
124 | }
125 | }
126 |
127 | // add user in user list
128 | function addUser(user) {
129 | var slElement = $(document.createElement("option"));
130 | slElement.attr("value", user);
131 | slElement.text(user);
132 | $("#usersList").append(slElement);
133 | }
134 |
135 | // remove user from user list
136 | function removeUser(user) {
137 | $("#usersList option").each(
138 | function () {
139 | if ($(this).val() === user) $(this).remove();
140 | });
141 | }
142 |
143 | // set your name
144 | function setName() {
145 | $("#name").text(username);
146 | }
147 |
148 | // show error
149 | function showError(content) {
150 | $("#loginError").text(content);
151 | $("#loginError").show();
152 | }
153 |
154 | // show chat panel
155 | function showChat() {
156 | $("#toolbar").show();
157 | $("entry").focus();
158 | scrollDown(base);
159 | }
160 |
161 |
162 |
163 | $(document).ready(function () {
164 | observer = {
165 | handleGroupMessage: function (msg) {
166 | console.log("msg sender:", msg.sender, " receiver:", msg.receiver, " content:", msg.content, " timestamp:", msg.timestamp);
167 | addMessage(msg.sender, msg.receiver, msg.content);
168 | $("#chatHistory").show();
169 | },
170 | handleGroupMessageACK: function(msg) {
171 | console.log("message ack local id:", msg.msgLocalID, " receiver:", msg.receiver)
172 | },
173 | handleGroupMessageFailure: function(msgLocalID, receiver) {
174 | console.log("message fail local id:", msg.msgLocalID, " receiver:", msg.receiver)
175 | },
176 |
177 | //创建群,加入群,离开群的通知消息
178 | handleGroupNotification: function(groupNotification) {
179 | console.log("group notification:", groupNotification);
180 | },
181 |
182 | onConnectState: function(state) {
183 | if (state == IMService.STATE_CONNECTED) {
184 | console.log("im connected");
185 | } else if (state == IMService.STATE_CONNECTING) {
186 | console.log("im connecting");
187 | } else if (state == IMService.STATE_CONNECTFAIL) {
188 | console.log("im connect fail");
189 | } else if (state == IMService.STATE_UNCONNECTED) {
190 | console.log("im unconnected");
191 | }
192 | }
193 | };
194 |
195 | var im = new IMService();
196 | im.host = host;
197 | im.observer = observer;
198 |
199 | var r = util.getURLParameter('receiver', location.search);
200 | if (r) {
201 | receiver = parseInt(r);
202 | } else {
203 | receiver = 0;
204 | }
205 | console.log("receiver:" + receiver)
206 |
207 | r = util.getURLParameter('sender', location.search);
208 | if (r) {
209 | sender = parseInt(r);
210 | } else {
211 | sender = 0;
212 | }
213 | username = sender;
214 | uid = sender;
215 | console.log("sender:" + sender)
216 |
217 |
218 | addUser(receiver);
219 | token = util.getCookie("token");
220 | console.log("token:" + token)
221 | im.accessToken = token
222 | im.start();
223 |
224 | setName();
225 | showChat();
226 | //deal with chat mode.
227 | $("#entry").keypress(function (e) {
228 | if (e.keyCode != 13 /* Return */) return;
229 | var msg = $("#entry").val().replace("\n", "");
230 | if (!util.isBlank(msg)) {
231 | var obj = {"text": msg};
232 | var textMsg = JSON.stringify(obj);
233 | var message = {sender:uid, receiver: receiver, content: textMsg, msgLocalID:msgLocalID++};
234 | if (im.connectState == IMService.STATE_CONNECTED) {
235 | im.sendGroupMessage(message);
236 | $("#entry").val(""); // clear the entry field.
237 | addMessage(username, receiver, msg);
238 | $("#chatHistory").show();
239 | }
240 | }
241 | });
242 | });
243 |
--------------------------------------------------------------------------------
/demo/static/js/lib/console.js:
--------------------------------------------------------------------------------
1 | // Avoid `console` errors in browsers that lack a console.
2 | (function() {
3 | var method;
4 | var noop = function () {};
5 | var methods = [
6 | 'assert', 'clear', 'count', 'debug', 'dir', 'dirxml', 'error',
7 | 'exception', 'group', 'groupCollapsed', 'groupEnd', 'info', 'log',
8 | 'markTimeline', 'profile', 'profileEnd', 'table', 'time', 'timeEnd',
9 | 'timeline', 'timelineEnd', 'timeStamp', 'trace', 'warn'
10 | ];
11 | var length = methods.length;
12 | var console = (window.console = window.console || {});
13 |
14 | while (length--) {
15 | method = methods[length];
16 |
17 | // Only stub undefined methods.
18 | if (!console[method]) {
19 | console[method] = noop;
20 | }
21 | }
22 | }());
--------------------------------------------------------------------------------
/demo/static/js/lib/json2.js:
--------------------------------------------------------------------------------
1 | /*
2 | json2.js
3 | 2014-02-04
4 |
5 | Public Domain.
6 |
7 | NO WARRANTY EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK.
8 |
9 | See http://www.JSON.org/js.html
10 |
11 |
12 | This code should be minified before deployment.
13 | See http://javascript.crockford.com/jsmin.html
14 |
15 | USE YOUR OWN COPY. IT IS EXTREMELY UNWISE TO LOAD CODE FROM SERVERS YOU DO
16 | NOT CONTROL.
17 |
18 |
19 | This file creates a global JSON object containing two methods: stringify
20 | and parse.
21 |
22 | JSON.stringify(value, replacer, space)
23 | value any JavaScript value, usually an object or array.
24 |
25 | replacer an optional parameter that determines how object
26 | values are stringified for objects. It can be a
27 | function or an array of strings.
28 |
29 | space an optional parameter that specifies the indentation
30 | of nested structures. If it is omitted, the text will
31 | be packed without extra whitespace. If it is a number,
32 | it will specify the number of spaces to indent at each
33 | level. If it is a string (such as '\t' or ' '),
34 | it contains the characters used to indent at each level.
35 |
36 | This method produces a JSON text from a JavaScript value.
37 |
38 | When an object value is found, if the object contains a toJSON
39 | method, its toJSON method will be called and the result will be
40 | stringified. A toJSON method does not serialize: it returns the
41 | value represented by the name/value pair that should be serialized,
42 | or undefined if nothing should be serialized. The toJSON method
43 | will be passed the key associated with the value, and this will be
44 | bound to the value
45 |
46 | For example, this would serialize Dates as ISO strings.
47 |
48 | Date.prototype.toJSON = function (key) {
49 | function f(n) {
50 | // Format integers to have at least two digits.
51 | return n < 10 ? '0' + n : n;
52 | }
53 |
54 | return this.getUTCFullYear() + '-' +
55 | f(this.getUTCMonth() + 1) + '-' +
56 | f(this.getUTCDate()) + 'T' +
57 | f(this.getUTCHours()) + ':' +
58 | f(this.getUTCMinutes()) + ':' +
59 | f(this.getUTCSeconds()) + 'Z';
60 | };
61 |
62 | You can provide an optional replacer method. It will be passed the
63 | key and value of each member, with this bound to the containing
64 | object. The value that is returned from your method will be
65 | serialized. If your method returns undefined, then the member will
66 | be excluded from the serialization.
67 |
68 | If the replacer parameter is an array of strings, then it will be
69 | used to select the members to be serialized. It filters the results
70 | such that only members with keys listed in the replacer array are
71 | stringified.
72 |
73 | Values that do not have JSON representations, such as undefined or
74 | functions, will not be serialized. Such values in objects will be
75 | dropped; in arrays they will be replaced with null. You can use
76 | a replacer function to replace those with JSON values.
77 | JSON.stringify(undefined) returns undefined.
78 |
79 | The optional space parameter produces a stringification of the
80 | value that is filled with line breaks and indentation to make it
81 | easier to read.
82 |
83 | If the space parameter is a non-empty string, then that string will
84 | be used for indentation. If the space parameter is a number, then
85 | the indentation will be that many spaces.
86 |
87 | Example:
88 |
89 | text = JSON.stringify(['e', {pluribus: 'unum'}]);
90 | // text is '["e",{"pluribus":"unum"}]'
91 |
92 |
93 | text = JSON.stringify(['e', {pluribus: 'unum'}], null, '\t');
94 | // text is '[\n\t"e",\n\t{\n\t\t"pluribus": "unum"\n\t}\n]'
95 |
96 | text = JSON.stringify([new Date()], function (key, value) {
97 | return this[key] instanceof Date ?
98 | 'Date(' + this[key] + ')' : value;
99 | });
100 | // text is '["Date(---current time---)"]'
101 |
102 |
103 | JSON.parse(text, reviver)
104 | This method parses a JSON text to produce an object or array.
105 | It can throw a SyntaxError exception.
106 |
107 | The optional reviver parameter is a function that can filter and
108 | transform the results. It receives each of the keys and values,
109 | and its return value is used instead of the original value.
110 | If it returns what it received, then the structure is not modified.
111 | If it returns undefined then the member is deleted.
112 |
113 | Example:
114 |
115 | // Parse the text. Values that look like ISO date strings will
116 | // be converted to Date objects.
117 |
118 | myData = JSON.parse(text, function (key, value) {
119 | var a;
120 | if (typeof value === 'string') {
121 | a =
122 | /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2}(?:\.\d*)?)Z$/.exec(value);
123 | if (a) {
124 | return new Date(Date.UTC(+a[1], +a[2] - 1, +a[3], +a[4],
125 | +a[5], +a[6]));
126 | }
127 | }
128 | return value;
129 | });
130 |
131 | myData = JSON.parse('["Date(09/09/2001)"]', function (key, value) {
132 | var d;
133 | if (typeof value === 'string' &&
134 | value.slice(0, 5) === 'Date(' &&
135 | value.slice(-1) === ')') {
136 | d = new Date(value.slice(5, -1));
137 | if (d) {
138 | return d;
139 | }
140 | }
141 | return value;
142 | });
143 |
144 |
145 | This is a reference implementation. You are free to copy, modify, or
146 | redistribute.
147 | */
148 |
149 | /*jslint evil: true, regexp: true */
150 |
151 | /*members "", "\b", "\t", "\n", "\f", "\r", "\"", JSON, "\\", apply,
152 | call, charCodeAt, getUTCDate, getUTCFullYear, getUTCHours,
153 | getUTCMinutes, getUTCMonth, getUTCSeconds, hasOwnProperty, join,
154 | lastIndex, length, parse, prototype, push, replace, slice, stringify,
155 | test, toJSON, toString, valueOf
156 | */
157 |
158 |
159 | // Create a JSON object only if one does not already exist. We create the
160 | // methods in a closure to avoid creating global variables.
161 |
162 | if (typeof JSON !== 'object') {
163 | JSON = {};
164 | }
165 |
166 | (function () {
167 | 'use strict';
168 |
169 | function f(n) {
170 | // Format integers to have at least two digits.
171 | return n < 10 ? '0' + n : n;
172 | }
173 |
174 | if (typeof Date.prototype.toJSON !== 'function') {
175 |
176 | Date.prototype.toJSON = function () {
177 |
178 | return isFinite(this.valueOf())
179 | ? this.getUTCFullYear() + '-' +
180 | f(this.getUTCMonth() + 1) + '-' +
181 | f(this.getUTCDate()) + 'T' +
182 | f(this.getUTCHours()) + ':' +
183 | f(this.getUTCMinutes()) + ':' +
184 | f(this.getUTCSeconds()) + 'Z'
185 | : null;
186 | };
187 |
188 | String.prototype.toJSON =
189 | Number.prototype.toJSON =
190 | Boolean.prototype.toJSON = function () {
191 | return this.valueOf();
192 | };
193 | }
194 |
195 | var cx,
196 | escapable,
197 | gap,
198 | indent,
199 | meta,
200 | rep;
201 |
202 |
203 | function quote(string) {
204 |
205 | // If the string contains no control characters, no quote characters, and no
206 | // backslash characters, then we can safely slap some quotes around it.
207 | // Otherwise we must also replace the offending characters with safe escape
208 | // sequences.
209 |
210 | escapable.lastIndex = 0;
211 | return escapable.test(string) ? '"' + string.replace(escapable, function (a) {
212 | var c = meta[a];
213 | return typeof c === 'string'
214 | ? c
215 | : '\\u' + ('0000' + a.charCodeAt(0).toString(16)).slice(-4);
216 | }) + '"' : '"' + string + '"';
217 | }
218 |
219 |
220 | function str(key, holder) {
221 |
222 | // Produce a string from holder[key].
223 |
224 | var i, // The loop counter.
225 | k, // The member key.
226 | v, // The member value.
227 | length,
228 | mind = gap,
229 | partial,
230 | value = holder[key];
231 |
232 | // If the value has a toJSON method, call it to obtain a replacement value.
233 |
234 | if (value && typeof value === 'object' &&
235 | typeof value.toJSON === 'function') {
236 | value = value.toJSON(key);
237 | }
238 |
239 | // If we were called with a replacer function, then call the replacer to
240 | // obtain a replacement value.
241 |
242 | if (typeof rep === 'function') {
243 | value = rep.call(holder, key, value);
244 | }
245 |
246 | // What happens next depends on the value's type.
247 |
248 | switch (typeof value) {
249 | case 'string':
250 | return quote(value);
251 |
252 | case 'number':
253 |
254 | // JSON numbers must be finite. Encode non-finite numbers as null.
255 |
256 | return isFinite(value) ? String(value) : 'null';
257 |
258 | case 'boolean':
259 | case 'null':
260 |
261 | // If the value is a boolean or null, convert it to a string. Note:
262 | // typeof null does not produce 'null'. The case is included here in
263 | // the remote chance that this gets fixed someday.
264 |
265 | return String(value);
266 |
267 | // If the type is 'object', we might be dealing with an object or an array or
268 | // null.
269 |
270 | case 'object':
271 |
272 | // Due to a specification blunder in ECMAScript, typeof null is 'object',
273 | // so watch out for that case.
274 |
275 | if (!value) {
276 | return 'null';
277 | }
278 |
279 | // Make an array to hold the partial results of stringifying this object value.
280 |
281 | gap += indent;
282 | partial = [];
283 |
284 | // Is the value an array?
285 |
286 | if (Object.prototype.toString.apply(value) === '[object Array]') {
287 |
288 | // The value is an array. Stringify every element. Use null as a placeholder
289 | // for non-JSON values.
290 |
291 | length = value.length;
292 | for (i = 0; i < length; i += 1) {
293 | partial[i] = str(i, value) || 'null';
294 | }
295 |
296 | // Join all of the elements together, separated with commas, and wrap them in
297 | // brackets.
298 |
299 | v = partial.length === 0
300 | ? '[]'
301 | : gap
302 | ? '[\n' + gap + partial.join(',\n' + gap) + '\n' + mind + ']'
303 | : '[' + partial.join(',') + ']';
304 | gap = mind;
305 | return v;
306 | }
307 |
308 | // If the replacer is an array, use it to select the members to be stringified.
309 |
310 | if (rep && typeof rep === 'object') {
311 | length = rep.length;
312 | for (i = 0; i < length; i += 1) {
313 | if (typeof rep[i] === 'string') {
314 | k = rep[i];
315 | v = str(k, value);
316 | if (v) {
317 | partial.push(quote(k) + (gap ? ': ' : ':') + v);
318 | }
319 | }
320 | }
321 | } else {
322 |
323 | // Otherwise, iterate through all of the keys in the object.
324 |
325 | for (k in value) {
326 | if (Object.prototype.hasOwnProperty.call(value, k)) {
327 | v = str(k, value);
328 | if (v) {
329 | partial.push(quote(k) + (gap ? ': ' : ':') + v);
330 | }
331 | }
332 | }
333 | }
334 |
335 | // Join all of the member texts together, separated with commas,
336 | // and wrap them in braces.
337 |
338 | v = partial.length === 0
339 | ? '{}'
340 | : gap
341 | ? '{\n' + gap + partial.join(',\n' + gap) + '\n' + mind + '}'
342 | : '{' + partial.join(',') + '}';
343 | gap = mind;
344 | return v;
345 | }
346 | }
347 |
348 | // If the JSON object does not yet have a stringify method, give it one.
349 |
350 | if (typeof JSON.stringify !== 'function') {
351 | escapable = /[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g;
352 | meta = { // table of character substitutions
353 | '\b': '\\b',
354 | '\t': '\\t',
355 | '\n': '\\n',
356 | '\f': '\\f',
357 | '\r': '\\r',
358 | '"' : '\\"',
359 | '\\': '\\\\'
360 | };
361 | JSON.stringify = function (value, replacer, space) {
362 |
363 | // The stringify method takes a value and an optional replacer, and an optional
364 | // space parameter, and returns a JSON text. The replacer can be a function
365 | // that can replace values, or an array of strings that will select the keys.
366 | // A default replacer method can be provided. Use of the space parameter can
367 | // produce text that is more easily readable.
368 |
369 | var i;
370 | gap = '';
371 | indent = '';
372 |
373 | // If the space parameter is a number, make an indent string containing that
374 | // many spaces.
375 |
376 | if (typeof space === 'number') {
377 | for (i = 0; i < space; i += 1) {
378 | indent += ' ';
379 | }
380 |
381 | // If the space parameter is a string, it will be used as the indent string.
382 |
383 | } else if (typeof space === 'string') {
384 | indent = space;
385 | }
386 |
387 | // If there is a replacer, it must be a function or an array.
388 | // Otherwise, throw an error.
389 |
390 | rep = replacer;
391 | if (replacer && typeof replacer !== 'function' &&
392 | (typeof replacer !== 'object' ||
393 | typeof replacer.length !== 'number')) {
394 | throw new Error('JSON.stringify');
395 | }
396 |
397 | // Make a fake root object containing our value under the key of ''.
398 | // Return the result of stringifying the value.
399 |
400 | return str('', {'': value});
401 | };
402 | }
403 |
404 |
405 | // If the JSON object does not yet have a parse method, give it one.
406 |
407 | if (typeof JSON.parse !== 'function') {
408 | cx = /[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g;
409 | JSON.parse = function (text, reviver) {
410 |
411 | // The parse method takes a text and an optional reviver function, and returns
412 | // a JavaScript value if the text is a valid JSON text.
413 |
414 | var j;
415 |
416 | function walk(holder, key) {
417 |
418 | // The walk method is used to recursively walk the resulting structure so
419 | // that modifications can be made.
420 |
421 | var k, v, value = holder[key];
422 | if (value && typeof value === 'object') {
423 | for (k in value) {
424 | if (Object.prototype.hasOwnProperty.call(value, k)) {
425 | v = walk(value, k);
426 | if (v !== undefined) {
427 | value[k] = v;
428 | } else {
429 | delete value[k];
430 | }
431 | }
432 | }
433 | }
434 | return reviver.call(holder, key, value);
435 | }
436 |
437 |
438 | // Parsing happens in four stages. In the first stage, we replace certain
439 | // Unicode characters with escape sequences. JavaScript handles many characters
440 | // incorrectly, either silently deleting them, or treating them as line endings.
441 |
442 | text = String(text);
443 | cx.lastIndex = 0;
444 | if (cx.test(text)) {
445 | text = text.replace(cx, function (a) {
446 | return '\\u' +
447 | ('0000' + a.charCodeAt(0).toString(16)).slice(-4);
448 | });
449 | }
450 |
451 | // In the second stage, we run the text against regular expressions that look
452 | // for non-JSON patterns. We are especially concerned with '()' and 'new'
453 | // because they can cause invocation, and '=' because it can cause mutation.
454 | // But just to be safe, we want to reject all unexpected forms.
455 |
456 | // We split the second stage into 4 regexp operations in order to work around
457 | // crippling inefficiencies in IE's and Safari's regexp engines. First we
458 | // replace the JSON backslash pairs with '@' (a non-JSON character). Second, we
459 | // replace all simple value tokens with ']' characters. Third, we delete all
460 | // open brackets that follow a colon or comma or that begin the text. Finally,
461 | // we look to see that the remaining characters are only whitespace or ']' or
462 | // ',' or ':' or '{' or '}'. If that is so, then the text is safe for eval.
463 |
464 | if (/^[\],:{}\s]*$/
465 | .test(text.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g, '@')
466 | .replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, ']')
467 | .replace(/(?:^|:|,)(?:\s*\[)+/g, ''))) {
468 |
469 | // In the third stage we use the eval function to compile the text into a
470 | // JavaScript structure. The '{' operator is subject to a syntactic ambiguity
471 | // in JavaScript: it can begin a block or an object literal. We wrap the text
472 | // in parens to eliminate the ambiguity.
473 |
474 | j = eval('(' + text + ')');
475 |
476 | // In the optional fourth stage, we recursively walk the new structure, passing
477 | // each name/value pair to a reviver function for possible transformation.
478 |
479 | return typeof reviver === 'function'
480 | ? walk({'': j}, '')
481 | : j;
482 | }
483 |
484 | // If the text is not JSON parseable, then a SyntaxError is thrown.
485 |
486 | throw new SyntaxError('JSON.parse');
487 | };
488 | }
489 | }());
490 |
--------------------------------------------------------------------------------
/demo/static/js/recorder.js:
--------------------------------------------------------------------------------
1 |
2 |
3 | var mediaSource = new MediaSource();
4 | mediaSource.addEventListener('sourceopen', handleSourceOpen, false);
5 | var mediaRecorder;
6 | var recordedBlobs;
7 | var sourceBuffer;
8 |
9 |
10 |
11 | // window.isSecureContext could be used for Chrome
12 | var isSecureOrigin = location.protocol === 'https:' ||
13 | location.hostname === 'localhost';
14 | if (!isSecureOrigin) {
15 | alert('getUserMedia() must be run from a secure origin: HTTPS or localhost.' +
16 | '\n\nChanging protocol to HTTPS');
17 | location.protocol = 'HTTPS';
18 | }
19 |
20 | function download() {
21 | var blob = new Blob(recordedBlobs, {type: 'video/webm'});
22 | var url = window.URL.createObjectURL(blob);
23 | var a = document.createElement('a');
24 | a.style.display = 'none';
25 | a.href = url;
26 | a.download = 'test.webm';
27 | document.body.appendChild(a);
28 | a.click();
29 | setTimeout(function() {
30 | document.body.removeChild(a);
31 | window.URL.revokeObjectURL(url);
32 | }, 100);
33 | }
34 |
35 | function handleSourceOpen(event) {
36 | console.log('MediaSource opened');
37 | sourceBuffer = mediaSource.addSourceBuffer('video/webm; codecs="vp8"');
38 | console.log('Source buffer: ', sourceBuffer);
39 | }
40 |
41 |
42 | function handleDataAvailable(event) {
43 | if (event.data && event.data.size > 0) {
44 | recordedBlobs.push(event.data);
45 | }
46 | }
47 |
48 | function handleStop(event) {
49 | console.log('Recorder stopped: ', event);
50 | }
51 |
52 |
53 | function startRecording() {
54 | recordedBlobs = [];
55 | var options = {mimeType: 'video/webm;codecs=vp9'};
56 | if (!MediaRecorder.isTypeSupported(options.mimeType)) {
57 | console.log(options.mimeType + ' is not Supported');
58 | options = {mimeType: 'video/webm;codecs=vp8'};
59 | if (!MediaRecorder.isTypeSupported(options.mimeType)) {
60 | console.log(options.mimeType + ' is not Supported');
61 | options = {mimeType: 'video/webm'};
62 | if (!MediaRecorder.isTypeSupported(options.mimeType)) {
63 | console.log(options.mimeType + ' is not Supported');
64 | options = {mimeType: ''};
65 | }
66 | }
67 | }
68 | try {
69 | mediaRecorder = new MediaRecorder(window.stream, options);
70 | } catch (e) {
71 | console.error('Exception while creating MediaRecorder: ' + e);
72 | alert('Exception while creating MediaRecorder: '
73 | + e + '. mimeType: ' + options.mimeType);
74 | return;
75 | }
76 | console.log('Created MediaRecorder', mediaRecorder, 'with options', options);
77 | mediaRecorder.onstop = handleStop;
78 | mediaRecorder.ondataavailable = handleDataAvailable;
79 | mediaRecorder.start(10); // collect 10ms of data
80 | console.log('MediaRecorder started', mediaRecorder);
81 | }
82 |
83 | function stopRecording() {
84 | mediaRecorder.stop();
85 | console.log('Recorded Blobs: ', recordedBlobs);
86 | }
87 |
--------------------------------------------------------------------------------
/demo/static/js/room_chat.js:
--------------------------------------------------------------------------------
1 | var username;
2 | var receiver;
3 | var users;
4 | var base = 1000;
5 | var msgLocalID=0;
6 | var increase = 25;
7 |
8 |
9 | util = {
10 | urlRE: /https?:\/\/([-\w\.]+)+(:\d+)?(\/([^\s]*(\?\S+)?)?)?/g,
11 | // html sanitizer
12 | toStaticHTML: function (inputHtml) {
13 | inputHtml = inputHtml.toString();
14 | return inputHtml.replace(/&/g, "&").replace(//g, ">");
15 | },
16 | //pads n with zeros on the left,
17 | //digits is minimum length of output
18 | //zeroPad(3, 5); returns "005"
19 | //zeroPad(2, 500); returns "500"
20 | zeroPad: function (digits, n) {
21 | n = n.toString();
22 | while (n.length < digits)
23 | n = '0' + n;
24 | return n;
25 | },
26 | //it is almost 8 o'clock PM here
27 | //timeString(new Date); returns "19:49"
28 | timeString: function (date) {
29 | var minutes = date.getMinutes().toString();
30 | var hours = date.getHours().toString();
31 | return this.zeroPad(2, hours) + ":" + this.zeroPad(2, minutes);
32 | },
33 |
34 | //does the argument only contain whitespace?
35 | isBlank: function (text) {
36 | var blank = /^\s*$/;
37 | return (text.match(blank) !== null);
38 | },
39 |
40 |
41 | getURLParameter: function(name, search) {
42 | search = search || location.search
43 | var param = search.match(
44 | RegExp(name + '=' + '(.+?)(&|$)'))
45 | return param ? decodeURIComponent(param[1]) : null
46 | },
47 |
48 | getCookie: function(c_name) {
49 | if (document.cookie.length>0) {
50 | c_start=document.cookie.indexOf(c_name + "=")
51 | if (c_start!=-1) {
52 | c_start=c_start + c_name.length+1
53 | c_end=document.cookie.indexOf(";",c_start)
54 | if (c_end==-1) c_end=document.cookie.length
55 | return unescape(document.cookie.substring(c_start,c_end))
56 | }
57 | }
58 | return ""
59 | },
60 |
61 | };
62 |
63 | //always view the most recent message when it is added
64 | function scrollDown(base) {
65 | window.scrollTo(0, base);
66 | $("#entry").focus();
67 | }
68 |
69 | // add message on board
70 | function addMessage(from, target, text, time) {
71 | var name = (target == '*' ? 'all' : target);
72 | if (text === null) return;
73 | if (time == null) {
74 | // if the time is null or undefined, use the current time.
75 | time = new Date();
76 | } else if ((time instanceof Date) === false) {
77 | // if it's a timestamp, interpret it
78 | time = new Date(time);
79 | }
80 | //every message you see is actually a table with 3 cols:
81 | // the time,
82 | // the person who caused the event,
83 | // and the content
84 | var messageElement = $(document.createElement("table"));
85 | messageElement.addClass("message");
86 | // sanitize
87 | text = util.toStaticHTML(text);
88 | var content = '
' + '
' + util.timeString(time) + '
' + '
' + util.toStaticHTML(from) + ' says to ' + name + ': ' + '