Skip to content

Instantly share code, notes, and snippets.

@Yukaii
Last active January 2, 2016 13:46
Show Gist options
  • Save Yukaii/c0da2be0087f1c29ffa2 to your computer and use it in GitHub Desktop.
Save Yukaii/c0da2be0087f1c29ffa2 to your computer and use it in GitHub Desktop.
沒有 uglifier 所以就直接複製出來啦
function scrollBottomDistance() {
return $("#contents").height() - ($("#main").scrollTop() + $("#main").height())
}
function scrollToBottomDistance(e) {
return e.children().height() - (e.scrollTop() + e.height())
}
function scrollToBottom(e) {
value = e.children().height() - e.height() - 1, setTimeout(function() {
e.scrollTop(value)
})
}
function scrollToMainBottom(e) {
beLeave ? $("#main").stop(!0, !0) : $("#main").stop(), setTimeout(function() {
scrollTarget = $("#contents").height() - $("#main").height() - 1, e ? $("#main").animate({
scrollTop: scrollTarget
}, e, "easeOutCirc") : $("#main").scrollTop(scrollTarget)
})
}
function wssChecker() {
var e = window.WebSocket || window.MozWebSocket;
return !(!e || 2 !== e.CLOSING)
}
function updateState(e) {
"typing" in e && ($(".typing")[0] || ($("#messages").append("<div class='" + sender_class[2] + " typing'>\u6253\u5b57\u4e2d...</div>"), scrollBottomDistance() < 110 && scrollToMainBottom(200)), clearTimeout(typing_end), typing_end = setTimeout(function() {
$(".typing").slideDown(200, function() {
$(".typing").remove()
})
}, 6e3)), "last_read" in e && e.last_read >= last_send_msg_time && $(".read").last().html("\u5df2\u9001\u9054<br/>").show()
}
function newMessage(e) {
if (!beLeave) {
Array.isArray(e) || (e = [e]);
var t = scrollBottomDistance(),
n = "",
o = [];
if (console.log("#message:", e.length), e.forEach(function(t) {
if (text = t.message, u = new Date(parseInt(t.time)), 0 != t.sender && "image" != t.type && "audio" != t.type) {
if (text = text.replace(/https?:\/\/[-a-zA-Z0-9@:%_\+.~#?&=]{2,256}\.[a-z]{2,63}(\/[/-a-zA-Z0-9@:%_\+.~#?&=;]*)?/gi, "<a target='_blank' href='$&'>$&</a>").trim(), text = text.replace(/ /g, "&nbsp;&nbsp;"), text = text.replace(/&nbsp; /g, "&nbsp;&nbsp;"), lineCount = (text.match(/\n/g) || []).length, 10 > lineCount) text = text.replace(/\n/g, "<br>");
else
for (i = 0; 10 > i; i++) text = text.replace(/\n/, "<br>");
"id" in t && (messageHistory[t.id] = sender_name[t.sender] + ": " + t.message)
} else "chat_otherleave" == t.status && (beLeave = !0, $("#sendButton>input").val("\u56de\u5831"));
if ("image" == t.type && !t.local) {
var r = 1 == e.length ? "scrollToMainBottom(200);" : "";
text = '<a href="' + t.original + '" class="image"><img class="userImage" onload="' + r + '" src="' + t.thumbnail + '" data-src="' + text + '" /></a>'
}
if ("audio" != t.type || t.local || (text = '<div onclick="playVoice(this);" class="voicePlayer" data-src="' + t.original + '"><i class="material-icons">&#xE037;</i></div>'), 1 != t.sender || t.local || my_msg_count++, 1 == t.sender && $("#msg" + t.msg_id)[0]) {
var a = $("#msg" + t.msg_id);
a.removeClass("local"), a.attr("mid", t.id)
} else {
comment_html = "", 0 != t.sender && (comment_html = "<div class='" + sender_class[t.sender] + " comment'>" + (1 == t.sender ? "<span class='read'>\u5df2\u9001\u51fa<br/></span>" : "") + "<span class='hidden_text'> (</span>" + ("device" in t && 2 == t.sender ? "<div class='mobile'>" + sender_device[t.device] + "</div>" : "") + '<time class="timeago" datetime="' + u.toJSON() + "\"></time><span class='hidden_text'>)<br/></span></div>"), n = "<div class='" + sender_class[t.sender] + " text " + (t.local ? "local " : "") + (t.type ? t.type + " " : "") + "' " + ("msg_id" in t ? " id='msg" + t.msg_id.toString() + "'" : "") + ("id" in t ? " mid=" + t.id.toString() : "") + ">" + ("<span class='hidden_text'>" + sender_name[t.sender] + "\uff1a</span>") + text + comment_html + "</div>";
var s = $(n),
l = $(".timeago", s).attr("datetime");
if (l) {
var c, u = new Date(l);
if (o.length > 0) c = new Date($(".timeago", o[o.length - 1]).attr("datetime"));
else {
var d = $("[mid]").last();
c = new Date($(".timeago", d).attr("datetime"))
}
c && c.getDate() != u.getDate() && (o.push($("<div class='" + sender_class[0] + " text timediff'></div>")), console.log("date", u, c))
}
o.push(s)
}
"id" in t && (id = t.id, id > msgMaxID && (msgMaxID = id), msgMinID > id && (msgMinID = id)), last_sender = t.sender, "leave" in t && (is_leave = t.leave), "time" in t && (last_msg_time = t.time), "time" in t && 1 == last_sender && (last_send_msg_time = t.time)
}), is_typing = !!$(".typing")[0], $(".typing").remove(), $(".mobile").hide(), clear_messages && (messages_box.children().remove(), $("#messages").html('\n<div class="loadMoreButton">\n <input type="button" value="\u8f09\u5165\u4e2d..." onclick="loadMore();" />\n</div>\n ')), lastMDOM = o[o.length - 1], lastMid = lastMDOM ? lastMDOM.attr("mid") : null, console.log("lastMid", lastMid, "lastMDOM", lastMDOM, "msgMaxID", msgMaxID, o.length), lastMid && msgMaxID - 1 > lastMid)
for (console.log("prepend"); o.length > 0;) o.pop().prependTo(messages_box);
else {
for (; o.length > maxShowMessage;) o.shift().appendTo(messages_box);
$("#messages").append(o), updateMessagesCount(), $(".text", "blockquote").size() > maxShowMessage + maxShowMessageMargin && setTimeout(function() {
$(".text", "blockquote").slice(0, -maxShowMessage).appendTo(messages_box), updateMessagesCount()
}, 500), updateDateString(), $(".mobile").last().show(), is_typing && 2 != last_sender && $("#messages").append("<div class='" + sender_class[2] + " typing'>\u6253\u5b57\u4e2d...</div>"), (2 != last_sender || 100 > t || clear_messages) && scrollToMainBottom(is_reconnection ? 0 : 200), is_reconnection && 0 != last_sender && (is_reconnection = !1), clear_messages = !1, send_last_read(), windowFocused || (new_msg_count += e.length, updateTitle(), 2 == last_sender && playAudio && 1 == e.length && audio.play()), $("blockquote").magnificPopup({
delegate: "a.image",
type: "image",
closeOnContentClick: !1,
closeBtnInside: !1,
mainClass: "mfp-with-zoom mfp-img-mobile",
image: {
verticalFit: !0
},
gallery: {
enabled: !0
},
zoom: {
enabled: !0,
duration: 300,
opener: function(e) {
return e.find("img")
}
}
})
}
}
}
function updateMessagesCount() {
var e = $("[mid]").first().attr("mid");
e > 0 ? ($(".loadMoreButton > input").prop("value", "\u8f09\u5165\u4e4b\u524d\u8a0a\u606f (" + e + "\u5247)"), $(".loadMoreButton").show()) : $(".loadMoreButton").hide()
}
function loadMore() {
orgHeight = $("blockquote").height(), $(".text", messages_box).slice(-loadMoreMessageCount).insertAfter($("div.loadMoreButton"));
var e = $("[mid]").first();
e.prev().hasClass("timediff") || e.before($("<div class='" + sender_class[0] + " text timediff'></div>")), updateMessagesCount(), updateDateString(), $("#main").scrollTop($("#main").scrollTop() + $("blockquote").height() - orgHeight), minShowID = $("[mid]").first().attr("mid"), msgMinID > 0 && 2 * loadMoreMessageCount > minShowID - msgMinID && (start = msgMinID - loadMoreMessageCount, start = 0 > start ? 0 : start, dispatcher.trigger("get_message", {
start: start,
end: msgMinID - 1
}), console.log("minimum message id:", msgMinID)), ga("send", "event", "chat", "load_more", null, loadMoreCount), loadMoreCount++
}
function displaySystemMessage(e) {
newMessage({
message: e,
sender: 0
})
}
function displayMyMessage(e, t) {
e = jQuery("<div/>").text(e).html(), newMessage({
message: e,
sender: 1,
msg_id: t,
time: Date.now(),
local: !0
})
}
function startChat() {
return msgMaxID = 0, msgMinID = 1e6, last_msg_time = 0, last_read_send = 0, last_send_typing = 0, last_send_msg_time = 1e33, msg_id = 1, msg_count = 0, my_msg_count = 0, messages_box = $("<div>"), maxShowMessage = 30, maxShowMessageMargin = 50, loadMoreMessageCount = 250, loadMoreCount = 1, my_msg_count = 0, $("#main").scrollTop() > 1 ? void $("#main").animate({
scrollTop: 1
}, 500, function() {
console.log("scroll", $("#main").scrollTop()), $("#help").hide(), startChat()
}) : ($("#help").hide(), $("#sendBox,blockquote").attr("style", "display: block !important"), $("#startButton").fadeTo(500, 0), $("#main").css("height", window.innerHeight + "px"), $("#main").animate({
height: window.innerHeight - 50 + 2
}, 400, "easeInQuad", function() {
console.log("clickStartChat5", $("#main").scrollTop()), $("#main").css("height", "calc(100% - 50px)"), createWebSocket(), $(".buttons").hide(), window.mobilecheck() || $("#messageInput").focus()
}), void ga("send", "event", "chat", "start"))
}
function clickStartChat() {
chatStarted || dispatcher || (chatStarted = !0, beLeave = !1, document.getElementById("keyInput").readOnly = !0, key = $("#keyInput").val(), Cookie.set("_key", encodeURIComponent(key)), ga("set", "dimension2", key), startChat(), "" != key && ga("send", "event", "chat", "key", key, 1))
}
function start_help() {
$("#help").show(), $("#main").animate({
scrollTop: $(".bg-image").height()
}, 500), ga("send", "event", "chat", "openhelp")
}
function connect_watchdog() {
!dispatcher || "disconnected" != dispatcher.state || !windowFocused && window.mobilecheck() || (is_reconnection = !0, createWebSocket())
}
function resetTimer() {
clearInterval(watchdog), watchdog = setInterval(function() {
connect_watchdog()
}, 1500), clearInterval(updater), updater = setInterval(function() {
state_updater()
}, 1e3), msgMaxID = 0, msgMinID = 1e6
}
function state_updater() {
windowFocused && !$(".buttons").is(":visible") ? (disconnected = !dispatcher || "connected" != dispatcher.state, disconnected && !$("#connecting").is(":visible") ? ($("#connecting").offset({
top: "-40px"
}), $("#connecting").fadeTo(0, 0), $("#connecting").show().fadeTo(200, 1)) : !disconnected && $("#connecting").is(":visible") && $("#connecting").fadeTo(200, 0, function() {
$("#connecting").hide()
})) : $("#connecting").hide()
}
function send_last_read() {
dispatcher && last_read_send != last_msg_time && (dispatcher.trigger("update_state", {
last_read: last_msg_time
}), last_read_send = last_msg_time)
}
function send_typing() {
dispatcher && Date.now() - last_send_typing > 4e3 && (last_send_typing = Date.now(), dispatcher.trigger("update_state", {
typing: !0
}))
}
function createWebSocket() {
resetTimer(), dispatcher = new WebSocketRails(window.location.host + "/websocket"), dispatcher.on_open = function(e) {
console.log("Connection has been established: ", e), clear_messages = !0, messageHistory = {}, new_msg_count = 0, dispatcher.bind("update_state", updateState), dispatcher.bind("new_message", newMessage)
}, dispatcher._conn.on_close = function(e) {
console.log("Connection has been closed: ", e), dispatcher && (dispatcher.state = "disconnected")
}, dispatcher._conn.on_error = function(e) {
console.log("error: ", e)
}
}
function sendEvents() {
msg_count > 0 && (ga("send", "event", "chat", "send", null, msg_count), msg_count = 0)
}
function sendMessage() {
if (beLeave) $("#messageInput").blur(), setTimeout(function() {
report()
}, 300);
else {
var e = $("#messageInput").val().substring(0, 500);
dispatcher && "connected" == dispatcher.state && !is_leave && 0 != e.length && (dispatcher.trigger("new_message", {
message: e,
msg_id: msg_id
}), $("#messageInput").val(""), $("#messageInput").focus(), last_send_typing = 0, displayMyMessage(e, msg_id), msg_id++, msg_count++)
}
}
function sendImage(e, t, n, i, o) {
beLeave || dispatcher && "connected" == dispatcher.state && !is_leave && dispatcher.trigger("new_message", {
message: t,
width: n,
height: i,
type: "image",
deletehsah: o,
msg_id: e
})
}
function sendAudio(e, t, n) {
beLeave || dispatcher && "connected" == dispatcher.state && !is_leave && dispatcher.trigger("new_message", {
message: t,
type: "audio",
duration: 1e3 * n,
msg_id: e
})
}
function padLeft(e, t) {
return e = "" + e, e.length >= t ? e : new Array(t - e.length + 1).join("0") + e
}
function changePerson() {
beLeave ? leave() : isbluring && window.mobilecheck() ? setTimeout(function() {
popupLeaveDialog()
}, 500) : popupLeaveDialog()
}
function insertToolbar() {
hasToobar = $("#messages").children().last().hasClass("toolbar"), activeToolbar = $(".toolbar.active"), activeToolbar.slideUp(200, function() {
this.remove()
}), hasToobar || ($("#messages").append($(".original").clone().removeClass("original").addClass("active")), scrollToMainBottom(200))
}
function upload_image(e) {
if (e && e.type.match(/image.*/)) {
var t = "img" + Date.now().toString();
msgID = msg_id, msg_id++, msg_count++;
var n = URL.createObjectURL(e),
i = '<div class="progress"></div><img class="userImage" onload="scrollToMainBottom(200);window.URL.revokeObjectURL(this.src);" id="' + t + '" src="' + n + '" />';
newMessage({
message: i,
sender: 1,
msg_id: msgID,
time: Date.now(),
local: !0,
type: "image"
}), document.body.className = "uploading";
var o = new FormData;
o.append("image", e);
var r = new XMLHttpRequest;
r.upload.onprogress = function(e) {
if (e.lengthComputable) {
var n = 100 - e.loaded / e.total * 60;
$("#" + t).prev().css("background", "linear-gradient(0deg, rgba(0,0,0,0.7) " + n + "%, rgba(0,0,0,0.0) " + n + "%)")
}
}, r.onload = function() {
if (response = JSON.parse(r.responseText), 200 == response.status) {
var e = response.data.link,
n = response.data.deletehash,
i = response.data.width,
o = response.data.height;
e = e.replace("http:", "https:"), sendImage(msgID, e, i, o, n), percent = 0
} else percent = 100;
$("#" + t).prev().css("background", "linear-gradient(0deg, rgba(0,0,0,0.7) " + percent + "%, rgba(0,0,0,0.0) " + percent + "%)")
}, r.open("POST", "https://api.imgur.com/3/image.json", !0), r.setRequestHeader("Authorization", "Client-ID f049c4e4f899fd6"), r.send(o)
}
}
function recordAudio() {
return Recorder.recorder ? void stopRecording() : Recorder.isRecordingSupported() ? (recorder = new Recorder({
encoderPath: "/js/oggopusEncoder.js"
}), Recorder.recorder = recorder, duration = 0, recorder.addEventListener("dataAvailable", function(e) {
var t = new FormData;
t.append("audio", e.detail), console.log(e.detail), parseInt(userStatus.uploadTokenExpiration) > Date.now() + 1e4 ? (t.append("token", userStatus.uploadToken), uploadVoice(t, duration)) : updateStatus(function() {
t.append("token", userStatus.uploadToken), uploadVoice(t, duration)
})
}), micIcon = $("#audioButton i"), recorder.addEventListener("duration", function(e) {
console.log("Recorded " + e.detail.toFixed(2) + " seconds"), duration = e.detail, normalizedVolume = recorder.normalizedVolume < .5 ? .5 : recorder.normalizedVolume > 1.5 ? 1.5 : recorder.normalizedVolume, micIcon.css("transform", "scale(" + normalizedVolume + "," + normalizedVolume + ")")
}), recorder.addEventListener("streamError", function(e) {
console.log("Error encountered: " + e.error.name)
}), recorder.addEventListener("start", function() {
console.log("Recorder is started"), $("#audioMessage").text("\u3000\u50b3\u9001\u3000"), $("#audioButton").addClass("recording")
}), recorder.addEventListener("streamReady", function() {
recorder.start(), recordingTimer = setTimeout(function() {
stopRecording()
}, 3e4)
}), void recorder.initStream()) : alert("\u60a8\u7684\u700f\u89bd\u5668\u4e0d\u652f\u63f4\u8a9e\u97f3\u8a0a\u606f")
}
function stopRecording() {
recordingTimer && (clearTimeout(recordingTimer), recordingTimer = null), Recorder.recorder.stop(), $("#audioMessage").text("\u50b3\u9001\u4e2d..."), $("#audioButton").removeClass("recording")
}
function uploadVoice(e, t) {
$.ajax({
type: "POST",
url: "https://www.wootalk.today/sound",
data: e,
processData: !1,
contentType: !1
}).done(function(e) {
console.log(e), msgID = msg_id, msg_id++, msg_count++, sendAudio(msgID, e.data.url, t), $("#audioMessage").text("\u8a9e\u97f3\u8a0a\u606f"), Recorder.recorder = null
})
}
function decodeOgg2(e) {
chunks = [];
var t = new Worker("/js/oggopusDecoder.js");
t.postMessage((new Recorder).config), t.addEventListener("error", function(e) {
console.log(e)
}), t.addEventListener("message", function(e) {
console.log(e.data), chunks += e.data
});
var n = new FileReader;
n.onload = function() {
t.postMessage({
command: "decode",
pages: new Uint8Array(this.result)
})
}, n.readAsArrayBuffer(e), setTimeout(function() {
var e = new(window.AudioContext || window.webkitAudioContext),
t = e.createBufferSource();
console.log(chunks.length), audioBuffer = e.createBuffer(1, chunks.length, e.sampleRate), audioBuffer.getChannelData(0).set(chunks), t.buffer = audioBuffer, t.connect(e.destination), t.start()
}, 5e3)
}
function decodeOgg(e, t) {
var n = new Uint8Array(e),
i = new Worker("/js/oggopusDecoder.js"),
o = new Worker("/js/wavePCM.js");
i.postMessage({
command: "init"
}), o.postMessage({
command: "init"
}), i.onmessage = function(e) {
null === e.data ? o.postMessage({
command: "done"
}) : o.postMessage({
command: "record",
buffers: e.data
}, e.data.map(function(e) {
return e.buffer
}))
}, o.onmessage = function(e) {
audioURL = URL.createObjectURL(new Blob([e.data], {
type: "audio/wav"
})), console.log(audioURL), t(audioURL)
}, i.postMessage({
command: "decode",
pages: n
}, [n.buffer]), i.postMessage({
command: "done"
})
}
function playAudioUrl(e, t) {
if ("voicePlayer" in window) {
if (voicePlayer.src == t) return void(voicePlayer.paused ? voicePlayer.play() : voicePlayer.pause());
voicePlayer.src.indexOf("zero.mp3") >= 0 || (voicePlayer.pause(), voicePlayer.ontimeupdate = null, voicePlayer.onpause = null, voicePlayer.onended = null, lastElement.html('<i class="material-icons">&#xE037;</i>'), lastElement.css("background", "none"))
}
voicePlayer.ontimeupdate = function() {
e.html('<i class="material-icons">&#xE034;</i>'), percent = this.currentTime / this.duration * 100, e.css("background", "linear-gradient(90deg, rgba(0,0,0,0.3) " + percent + "%, rgba(0,0,0,0.0) " + percent + "%)")
}, voicePlayer.onpause = function() {
e.html('<i class="material-icons">&#xE037;</i>')
}, voicePlayer.onended = function() {
e.html('<i class="material-icons">&#xE037;</i>'), e.css("background", "none")
}, voicePlayer.onstalled = function() {
percent = this.currentTime / this.duration * 100, percent > 99 && (this.pause(), e.html('<i class="material-icons">&#xE037;</i>'), e.css("background", "none"), this.load())
}, voicePlayer.onerror = function(e) {
alert(e.currentTarget.error.code), console.log("jQuery error event:", e);
var t = e.originalEvent;
console.log("original event:", t), alert(t.message ? "Error:\n " + t.message + "\nLine:\n " + t.lineno + "\nFile:\n " + t.filename : "Error:\n " + t.type + "\nElement:\n " + (t.srcElement || t.target))
}, voicePlayer.src = t, voicePlayer.load(), voicePlayer.play(), lastElement = e
}
function playVoice(e) {
voicePlayer.src.indexOf("zero.mp3") >= 0 && (voicePlayer.play(), voicePlayer.pause()), el = $(e), src = el.data("src"), el.html('<i class="material-icons spin">&#xE028;</i>'), "voicePlayer" in window || (voicePlayer = new Audio), playAudioUrl(el, src)
}
function getTextHistory() {
var e = "";
for (keys = Object.keys(messageHistory).sort(), i = 0; i < keys.length; i++) e += messageHistory[keys[i]] + "\n";
return e
}
function report() {
$("#talk-content").val(getTextHistory()), $.magnificPopup.open({
items: {
src: "#report-popup",
type: "inline"
},
type: "inline",
midClick: !1,
callbacks: {
open: function() {
$(".report-popup input").not(":button, :submit, :reset").removeAttr("checked").removeAttr("selected").not(":checkbox, :radio, select").val(""), $(".report-popup h5").first().removeClass("red"), ensureLeave = !1, this.content.on("click.mycustomevent", "#popup-yes", function() {
return reasons = [], $(".text", $(".report-popup input[type=checkbox]:checked + label")).each(function() {
reasons.push($(this).text())
}), otherReason = $("#other-reason").val(), "" != otherReason && reasons.push(otherReason), 0 == reasons.length ? void $(".report-popup h5").first().addClass("red") : ($.post("/api/report", {
chatContent: $(".report-popup textarea").val(),
reason: reasons
}, function(e) {
console.log("status:", e)
}), ensureLeave = !0, $.magnificPopup.close(), void ga("send", "event", "chat", "report"))
}), this.content.on("click.mycustomevent2", "#popup-cancel", function() {
$.magnificPopup.close()
})
},
close: function() {
this.content.off("click.mycustomevent"), this.content.off("click.mycustomevent2")
},
afterClose: function() {
ensureLeave && leave()
}
},
showCloseBtn: !1,
removalDelay: 350,
mainClass: "mfp-zoom-in"
})
}
function popupLeaveDialog() {
$.magnificPopup.open($("[mid]").last().attr("mid") > 100 ? {
items: {
type: "inline",
src: $('<div class="white-popup mfp-with-anim"> <h4>\u78ba\u5b9a\u8981\u96e2\u958b\u55ce?</h4> <p>\u56e0\u70ba\u60a8\u804a\u4e86\u5f88\u591a<br> \u82e5\u78ba\u5b9a\u8981\u96e2\u958b<br> \u8acb\u5728\u4e0b\u65b9\u8f38\u5165"leave"</p> <input type="text" id="ensureText" placeholder="\u5728\u6b64\u8f38\u5165 leave" autocomplete="off"/> <button class="right" id="popup-yes">\u96e2\u958b\u5c0d\u8a71</button> <button class="right light" id="popup-cancel">\u53d6\u6d88</button> </div> <i class="report-button material-icons mfp-with-anim" onclick="ensureReport=true;$.magnificPopup.close();">&#xE000;</i>')
},
type: "inline",
midClick: !1,
callbacks: {
open: function() {
ensureLeave = !1, ensureReport = !1, this.content.on("click.mycustomevent", "#popup-cancel", function() {
$.magnificPopup.close()
}), this.content.on("click.mycustomevent2", "#popup-yes", function() {
if ("leave" == $("#ensureText").val().toLowerCase()) ensureLeave = !0, $.magnificPopup.close();
else {
var e = document.getElementById("ensureText"),
t = e.cloneNode(!0);
e.parentNode.replaceChild(t, e), $("#ensureText").addClass("invalid")
}
})
},
close: function() {
this.content.off("click.mycustomevent"), this.content.off("click.mycustomevent2")
},
afterClose: function() {
ensureReport ? report() : ensureLeave && leave()
}
},
showCloseBtn: !1,
removalDelay: 350,
mainClass: "mfp-zoom-in"
} : {
items: {
type: "inline",
src: $('<div class="white-popup mfp-with-anim"> <h4>\u78ba\u5b9a\u8981\u96e2\u958b\u55ce?</h4> <p>\u96e2\u958b\u5c07\u6e05\u9664\u96d9\u65b9\u7684\u5c0d\u8a71\u7d00\u9304\uff01<br> \u4e14\u5c0d\u65b9\u4e0d\u6703\u770b\u5230\u60a8\u7684\u4efb\u4f55\u7559\u8a00\u3002</p> <button class="left light" onclick="ensureReport=true;$.magnificPopup.close();">\u56de\u5831</button> <button class="right" id="popup-yes">\u78ba\u5b9a\u96e2\u958b</button> <button class="right light" id="popup-cancel">\u53d6\u6d88</button> </div>')
},
type: "inline",
midClick: !1,
callbacks: {
open: function() {
ensureLeave = !1, ensureReport = !1, this.content.on("click.mycustomevent", "#popup-cancel", function() {
$.magnificPopup.close()
}), this.content.on("click.mycustomevent2", "#popup-yes", function() {
ensureLeave = !0, $.magnificPopup.close()
})
},
close: function() {
this.content.off("click.mycustomevent"), this.content.off("click.mycustomevent2")
},
afterClose: function() {
ensureReport ? report() : ensureLeave && leave()
}
},
showCloseBtn: !1,
removalDelay: 350,
mainClass: "mfp-zoom-in"
})
}
function leave() {
is_leave = !1, dispatcher.trigger("change_person"), dispatcher.disconnect(), dispatcher = null, $("#sendButton>input").val("\u50b3\u9001"), $(".typing").remove(), $(".buttons").show(), $("#main").animate({
scrollTop: 0,
height: "100%"
}, 500), $("#startButton").fadeTo(500, 1, function() {
$("#sendBox,blockquote").attr("style", "display: none !important"), $("#messages").html(""), chatStarted = !1, document.getElementById("keyInput").readOnly = !1, msg_count > 0 && (ga("send", "event", "chat", "send", null, msg_count), msg_count = 0), base = 2, 1 >= my_msg_count ? label = padLeft(my_msg_count, 4) : (log_count = Math.log(my_msg_count) / Math.log(base), lower_bound = Math.pow(base, Math.floor(log_count)), upper_bound = Math.pow(base, Math.floor(log_count) + 1) - 1, label = padLeft(Math.ceil(lower_bound), 4) + "-" + padLeft(Math.ceil(upper_bound), 4)), ga("send", "event", "chat", "send_histogram", label, my_msg_count), my_msg_count = 0, ga("send", "event", "chat", "changeperson")
})
}
function enterKeyMode(e) {
chatStarted && !e ? showMessageBox("<p>\u8acb\u5148\u96e2\u958b\u76ee\u524d\u5c0d\u8a71<br>\u624d\u80fd\u4f7f\u7528\u5bc6\u8a9e\u5594!</p>", "\u4f7f\u7528\u5bc6\u8a9e") : ($("#main").scrollTop() > 1 && $("#main").animate({
scrollTop: 1
}, 500), $("#keyPanel").css("display", "table"), $("#tip").removeClass("hide"), $("#logoContent").addClass("blurLogo"), $(".keybox").fadeTo(500, 1, "easeInCubic"), document.getElementById("keyInput").readOnly = !1, ga("send", "event", "chat", "enterKeyMode"))
}
function exitKeyMode() {
chatStarted || ($("#tip").addClass("hide"), $("#keyInput").removeClass("onX").val("").change(), $(".keybox").fadeTo(500, 0, "easeOutCubic", function() {
$("#keyPanel").hide()
}), $(".header").removeClass("blurLogo"), document.getElementById("keyInput").readOnly = !0, ga("send", "event", "chat", "exitKeyMode"))
}
function updateTitle() {
document.title = new_msg_count > 0 ? "(" + new_msg_count + ") " + org_title : org_title, ga("set", "title", version)
}
function generateInteval(e) {
var t = 1e3 * (Math.pow(2, e) - 1);
return t > 3e4 && (t = 3e4), Math.random() * t
}
function checkStart() {
console.log("checkStart"), !chatStarted && Date.now() - lastCheckStart > 1e4 && (lastCheckStart = Date.now(), updateStatus(function(e) {
e.alreadyStart && ("keyword" in e && "" != e.keyword ? ($("#keyInput").val(decodeURIComponent(e.keyword)).change(), enterKeyMode(!0)) : exitKeyMode(), clickStartChat())
}))
}
function updateStatus(e) {
$.get("/api/status", function(t) {
userStatus = t, console.log("status:", t, t.uploadToken, userStatus.uploadToken), e && e(t)
})
}
function updateDateString() {
$(".timeago").timeago("refresh"), $("div.timediff").each(function() {
var e = $(this).nextAll("[mid]").first(),
t = $(this).prevAll("[mid]").last(),
n = new Date($(".timeago", e).attr("datetime")),
i = new Date($(".timeago", t).attr("datetime"));
!i || i.getDate() == n.getDate() && i.getMonth() == n.getMonth() && i.getFullYear() == n.getFullYear() ? $(this).hide() : $(this).show().text(generateDataString(n))
})
}
function generateDataString(e) {
var t = "",
n = new Date;
t += n.getFullYear() != e.getFullYear() ? e.getFullYear() + "\u5e74" : e.getMonth() + 1 + "\u6708" + e.getDate() + "\u65e5";
var i = Math.floor((e.getTime() - 6e4 * e.getTimezoneOffset()) / 1e3 / 86400),
o = Math.floor((n.getTime() - 6e4 * e.getTimezoneOffset()) / 1e3 / 86400);
return console.log(i, o, e.getTimezoneOffset()), i == o ? t = "\u4eca\u65e5 (" + t + ")" : i == o - 1 && (t = "\u6628\u65e5 (" + t + ")"), t
}
function showMessageBox(e, t) {
$.magnificPopup.open({
items: {
type: "inline",
src: $('<div class="white-popup mfp-with-anim"> <h4>' + t + "</h4> " + e + ' <button id="popup-yes">\u78ba\u5b9a</button> </div>')
},
type: "inline",
midClick: !1,
callbacks: {
open: function() {
this.content.on("click.mycustomevent", "#popup-yes", function() {
$.magnificPopup.close()
})
},
close: function() {
this.content.off("click.mycustomevent")
}
},
showCloseBtn: !1,
removalDelay: 500,
mainClass: "mfp-zoom-in"
})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment