Light12306/RwTicketAssistantV2/app/contentscripts/kyfw/12306.js
iFish addcafcdf8 + 集成扩展的源码
+ 增加相关TypedScript的导入
2014-08-08 14:33:43 +08:00

1468 lines
43 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

/// <reference path="/app/libs/jquery.js"/>
/// <reference path="/app/libs/underscore/underscore.js"/>
/// <reference path="../framework.js"/>
var queryStatics = null, currentProfile = null;
var tagOtnMap = {
9: "SWZ",
"P": "TZ",
"M": "ZY",
"O": "ZE",
"6": "GR",
"4": "RW",
"3": "YW",
"2": "RZ",
"1": "YZ",
"0": "WZ",
"*": "QT"
};
var tagRevMap = _.invert(tagOtnMap);
var seatNameMap = { "商务座": "SWZ", "特等座": "TZ", "一等座": "ZY", "二等座": "ZE", "高级软卧": "GR", "软卧": "RW", "硬卧": "YW", "软座": "RZ", "硬座": "YZ", "无座": "WZ" };
var seatNameInvMap = _.invert(seatNameMap);
var $doc = $(document);
var ISLOGINED = $.trim($("#regist_out").text()) != "注册";
var currentUser;
//#region 切换声音
unsafeInvoke(function changeAudio() {
var audio = new Audio("http://static.liebao.cn/resources/audio/music2.ogg");
audio.loop = true;
window.jPlayer = function (cmd) {
if (cmd === "play") audio.play();
else if (cmd === "stop") audio.pause();
};
});
//#endregion
//#region 拦截事件
unsafeInvoke(function () {
var w = window, q = jQuery;
var dataExchange,
dispatchEventBody = function (action, detail) {
document.body.dispatchEvent(new CustomEvent("$_$", { detail: { action: action, detail: detail } }));
},
addEventListener = function (action, callback) {
document.addEventListener("$_$", function (e) {
if (e && e.detail && e.detail.action && e.detail.action === action)
callback.call(e.detail.detail || {});
});
};
addEventListener("dr", function () { dataExchange = this; });
addEventListener("eval", function () {
dispatchEventBody("dr", eval(this.code));
});
var dataFilter = function (data) {
dataExchange = null;
dispatchEventBody("dd", data);
data = dataExchange || data;
return data;
};
w.dhtmlx.modalbox.hide = (function (o) {
return function () {
o.apply(this, arguments);
dispatchEventBody("qf");
};
})(w.dhtmlx.modalbox.hide);
q(document).ajaxComplete(function (e, xhr, d) {
if (d.url.indexOf("autoSubmitOrderRequest") != -1)
dispatchEventBody("autoSubmitOrder");
if (d.url.indexOf("leftTicket/query") !== -1)
dispatchEventBody("qr", { opt: { url: d.url, data: d.data, type: d.type }, text: xhr.responseText, headers: xhr.getAllResponseHeaders() });
}).ajaxSend(function (e, xhr, d) {
if (d.url.indexOf("leftTicket/query") !== -1)
dispatchEventBody("qs", { opt: { url: d.url, data: d.data, type: d.type } });
}).ajaxError(function (e, xhr, d) {
if (d.url.indexOf("leftTicket/query") !== -1) {
var status = xhr.statusText;
if ("timeout" == status || "No Transport" == status || "abort" == status)
return;
dispatchEventBody("qe", { opt: { url: d.url, data: d.data, type: d.type }, text: xhr.responseText, headers: xhr.getAllResponseHeaders() });
}
});
q.ajaxSetup({
accepts: { json: "text/json, application/json" },
contents: { json: /json/ },
converters: {
"text json": function () {
return dataFilter(jQuery.parseJSON.apply(this, jQuery.makeArray(arguments)));
}
}
});
w.refreshImg = (function (o) {
return function (dlg, type, id) {
o.apply(this, $.makeArray(arguments));
if (id === 'img_rand_code2')
dispatchEventBody("autoSubmit");
else
if (dlg === "login")
dispatchEventBody("login");
//检测验证码
id = id || "img_rand_code";
var ele = document.getElementById(id);
var fun = function () {
dispatchEventBody("randCodeLoaded", id);
};
if (ele) {
if (ele.naturalHeight > 0) {
fun();
} else {
$(ele).load(function () {
fun();
});
}
}
};
})(w.refreshImg);
q(document).on("click", "#relogin_close", function () {
dispatchEventBody("loginCancelled");
});
w.loginAsyn = (function (o) {
return function (name) {
o.apply(this, $.makeArray(arguments));
dispatchEventBody("loginSuccess", { name: name });
};
})(w.loginAsyn);
q.fn.val = (function (o) {
return function () {
var data = $.makeArray(arguments);
var result = o.apply(this, data);
if ($.inArray(this.attr("id"), ['train_date', 'fromStation', 'toStation']) !== -1 && data.length > 0 && data[0]) {
var e = document.createEvent("UIEvents");
e.initUIEvent("change", true, true);
this.each(function () { this.dispatchEvent(e); });
}
return result;
};
})(q.fn.val);
if (w.myJpopup)
w.myJpopup.startOrHiden = (function (o) {
return function () {
if (!w.myJpopup.isShow())
dispatchEventBody("prompt");
else dispatchEventBody("promptDismiss");
o.apply(this, $.makeArray(arguments));
};
})(w.myJpopup.startOrHiden);
if (w.renderCheckTickInfo) {
w.renderCheckTickInfo = (function (o) {
return function (data) {
o.apply(this, $.makeArray(arguments));
dispatchEventBody("renderCheckTickInfo");
};
})(w.renderCheckTickInfo);
}
});
$(document).on("routePage", function () {
if (sysConfig.blockVcVerify) {
unsafeInvoke(function () {
$.ajaxTransport("+*", function (o, oo, xhr) {
if (o.url.indexOf("checkRandCodeAnsyn") != -1) {
return {
send: function (header, callback) { callback(200, 'ok', { json: { "validateMessagesShowId": "_validatorMessage", "status": true, "httpstatus": 200, "data": "Y", "messages": [], "validateMessages": {} } }, {}); },
abort: function () { }
};
}
});
});
}
//if (sysConfig.blockQueueCount) {
// unsafeInvoke(function () {
// $.ajaxTransport("+json", function (o, oo, xhr) {
// if (o.url.indexOf("getQueueCount") != -1) {
// return {
// send: function (header, callback) {
// callback(200, 'ok', {
// json: {
// "validateMessagesShowId": "_validatorMessage",
// "status": true,
// "httpstatus": 200,
// "data": { "count": "25", "ticket": oo.data.leftTicket, "op_2": "false", "countT": "0", "op_1": "true" },
// "messages": [],
// "validateMessages": {}
// }
// }, {});
// },
// abort: function () { }
// };
// }
// });
// });
//}
});
(function () {
document.body.addEventListener(evtTag, function (e) {
var detail = e.detail;
if (!detail) return;
$doc.trigger(detail.action, [detail.detail]);
});
$(document).on("dispatch", function() {
document.dispatchEvent(new CustomEvent(evtTag, { detail: { action: arguments[1], detail: arguments[2] || null } }));
}).on("autoSubmitOrder", function() {
msg.sendAction("autoSubmitOrder");
});
})();
//#endregion
//#region 保持在线
(function () {
(function () {
var timer = null;
$doc.on("sysConfigUpdated", function () {
if (!sysConfig) return;
//保持在线
if (!sysConfig.keepOnline) {
if (timer) {
clearInterval(timer);
timer = null;
}
return;
} else {
log.print("init keep-online timer.");
timer = setInterval(function () {
$.post("/otn/login/checkUser");
}, 10 * 60 * 1000);
}
}).trigger("sysConfigUpdated");
})();
})();
//#endregion
//#region 登录页面
$(document).bind(EVT_ONLOGINPAGE, function () {
//登录页面,自动填充用户名和密码
msg.on("fillUserInfo", function () {
if (this.name)
$("#username").val(this.name);
if (this.pwd) {
$("#password").val(this.pwd);
document.getElementById("randCode").focus();
} else {
$("#password")[0].focus();
}
});
chrome.runtime.sendMessage({ action: "getLastUser" }, function (m) {
if (m.name)
$("#username").val(m.name);
if (m.pwd) {
$("#password").val(m.pwd);
$("#randCode")[0].focus();
} else {
$("#password")[0].focus();
}
});
$("#randCode").keyup(function () {
if (sysConfig.autoLoginAfterVerifyCode && this.value.length >= 4) {
var links = $("#loginSub, #loginSubAsyn");
if (links.length) {
msg.sendAction("notify", {
title: "提示",
message: "已自动登录等待12306回应。如卡太久请重试一次。",
iconUrl: "/icons/icon_128.png"
});
links.nativeClick(10);
}
}
});
$("#loginSub, #loginSubAsyn").on("click", function () {
var data = { tempUser: $("#username").val(), tempPwd: $("#password").val() };
if (!data.tempUser || !data.tempPwd)
return;
chrome.runtime.sendMessage({ action: "logTempUser", detail: data });
});
$(document).bind("login", function () {
chrome.runtime.sendMessage({
action: "pageInitCall",
detail: {
page: "onLoginPage"
}
});
}).bind("loginCancelled", function () {
chrome.runtime.sendMessage({
action: "pageInitCall",
detail: {
page: "onQueryPage",
logined: false
}
});
}).bind("loginSuccess", function (e, data) {
var name = data.name;
log.print(data);
chrome.runtime.sendMessage({
action: "logTempUserSuccess",
detail: {
name: name
}
});
chrome.runtime.sendMessage({
action: "pageInitCall",
detail: {
page: "onQueryPage",
logined: true
}
});
ISLOGINED = true;
$(document).trigger("userLogined");
$(document).trigger(EVT_ONMAINPAGE);
});
});
//#endregion
//#region 查询
$(document).bind(EVT_ONQUERYPAGE, function () {
var suspendStationUpdate = false;
var firstRun = true;
var isResign = false;
var newProfile = null;
//检测改签
(function () {
var data = evalCode.eval("[tour_flag, ClickWho]");
isResign = data[0] == 'gc';
if (!isResign) return;
newProfile = {};
newProfile.fromText = $("#fromStationText").val();
newProfile.fromCode = $("#fromStation").val();
newProfile.toText = $("#toStationText").val();
newProfile.toCode = $("#toStation").val();
newProfile.depDate = $("#train_date").val();
newProfile.studentTicket = data[1] == '0X00';
})();
//用户
(function () {
$(document).on("applyUser", function () {
if (currentUser.rawPassenger && currentUser.rawPassenger.length) {
evalCode.eval("window.passengerAll=" + JSON.stringify(currentUser.rawPassenger) + ",$.renderPassenger();");
} else {
evalCode.eval("$.reloadPassenger(), $('#sel-buyer').hide();");
}
if (currentUser.options.showMore) {
if ($("#show_more").not(".up")) {
document.getElementById("show_more").click();
}
} else {
if ($("#show_more").is(".up")) {
document.getElementById("show_more").click();
}
}
});
})();
//配置文件
(function () {
var processProfile = function () {
currentProfile.selectedTrain = _.map(currentProfile.selectedTrain, function (e, k) {
return tagMap[e] || e;
});
};
$(document).on("applyProfile", function () {
suspendStationUpdate = true;
processProfile();
if (currentProfile.fromText)
$("#fromStationText").val(currentProfile.fromText);
if (currentProfile.fromCode)
$("#fromStation").val(currentProfile.fromCode);
if (currentProfile.toText)
$("#toStationText").val(currentProfile.toText);
if (currentProfile.toCode)
$("#toStation").val(currentProfile.toCode);
if (new Date() < new Date(currentProfile.depDate))
$("#train_date").val(currentProfile.depDate);
//其它的东西初始化
//已选择车次
if (firstRun)
$(document).trigger("restoreTrain", [currentProfile.selectedTrain]);
//已选择席别
if (firstRun)
$doc.trigger("restoreSeat", [currentProfile.selectedSeatType]);
//已选择联系人
if (firstRun)
$doc.trigger("restorePassenger", [currentProfile.passengers]);
//已选择备选日期
if (firstRun)
$doc.trigger("restoreDateLoop", [currentProfile.dateloop]);
//其它选项-预选模式,自动提交
if (firstRun)
$doc.trigger("restoreMisc");
suspendStationUpdate = false;
});
//注册响应消息
msg.on("getStationInfo", function (response) {
response({ detail: getCurrentStationInfo() });
});
//如果是首页进入的,那就保存当前状态
if (evalCode.eval("window.page_show_flag") == 'index') {
chrome.runtime.sendMessage({ action: "stationInfoUpdate", detail: getCurrentStationInfo() });
}
//当配置发生变化时发送消息通知。
$doc.on("change", "#fromStationText, #fromStation, #toStationText, #toStation, #train_date", function () {
if (suspendStationUpdate)
return;
chrome.runtime.sendMessage({ action: "stationInfoUpdate", detail: getCurrentStationInfo() });
});
//回填状态
chrome.runtime.sendMessage({ action: "getCurrentUser" }, function (message) {
currentUser = message.detail;
currentProfile = _.extend(currentUser.currentProfile, _.omit(newProfile, "depDate"));
$(document).trigger("applyUser");
$(document).trigger("applyProfile");
firstRun = false;
//继续初始化
msg.on("profileChanged", function () {
currentProfile = _.extend(this, _.omit(newProfile, "depDate"));
currentProfile = this;
processProfile();
$(document).trigger("applyProfile");
$(document).trigger("profileChanged");
});
msg.on("profileReload", function () {
$("#clearAll")[0].click();
firstRun = true;
currentProfile = this;
processProfile();
$(document).trigger("applyProfile");
$(document).trigger("profileChanged");
});
});
})();
//备选日期
(function () {
$(document).on("restoreDateLoop", function (e, dateloop) {
suspendStationUpdate = true;
//var html = [];
$.each(dateloop, function () {
//html.push("<span class='sel-box w80' name='{{DATE}}'>{{DATE}}<a class='close' href='javascript:' onclick='$.removeSel(this,\"{{DATE}}\",3)'></a></span>".replace(/{{DATE}}/g, this));
var check = $("#date-list input[value='" + this + "']:not(:checked)");
check.length && check[0].click();
});
//$("#prior_date").find("span:gt(0)").remove().end().append(html.join("")).find("span a").click(removeHandle);
$("#prior_date").find("span:gt(0) a").click(removeHandle);
//evalCode.eval("window.rqChecked=[" + _.map(dateloop, function(d) {
// return "'" + d + "'";
//}).join(", ") + "]");
suspendStationUpdate = false;
});
//当用户选择日期时,发送消息到后台
$("#sel-date :checkbox").click(function () {
if (suspendStationUpdate) return;
suspendStationUpdate = true;
var v = this.value;
if (this.checked) {
msg.sendAction("addDateLoop", v);
$("#prior_date span[name=" + v + "] a").click(removeHandle);
} else {
msg.sendAction("removeDateLoop", v);
}
suspendStationUpdate = false;
});
var removeHandle = function () {
var span = $(this).closest("span");
var dt = span.attr("name");
msg.sendAction("removeDateLoop", dt);
};
msg.on("removeDateLoop", function () {
$("#prior_date span[name=" + this + "] a")[0].click();
});
msg.on("addDateLoop", function () {
var check = $("#date-list input[value='" + this + "']:not(:checked)");
check.length && check[0].click();
});
})();
//候选席别
(function () {
$(document).on("restoreSeat", function (e, seats) {
suspendStationUpdate = true;
if (seats.length > 5) {
msg.sendAction("pageNotification", { id: "seatNumOutTip", title: "提示", message: "由于12306的自动刷票不支持针对5个以上的席别进行检测因此超出的部分席别将会失效。请使用订票助手的自动刷票。" });
}
$.each(seats.slice(0, 5), function () {
var check = $("#sel-seat input[value='" + tagOtnMap[this] + "']:not(:checked)");
check.length && check[0].click();
});
$("#prior_seat").find("span:gt(0) a").click(removeHandle);
suspendStationUpdate = false;
});
//当用户选择席别时,发送消息到后台
$("#sel-seat :checkbox").click(function () {
var v = this.value;
var code = tagRevMap[v];
if (this.checked) {
if (!suspendStationUpdate)
msg.sendAction("addSeat", code);
$("#prior_seat span[name='" + seatNameInvMap[v] + "'] a").click(removeHandle);
} else {
if (!suspendStationUpdate)
msg.sendAction("removeSeat", code);
}
});
var removeHandle = function () {
var span = $(this).closest("span");
var name = span.attr("name");
var code = tagRevMap[seatNameMap[name]];
if (!suspendStationUpdate)
msg.sendAction("removeSeat", code);
};
msg.on("removeSeat", function () {
suspendStationUpdate = true;
$("#prior_seat span[name='" + seatNameInvMap[tagOtnMap[this]] + "'] a")[0].click();
suspendStationUpdate = false;
});
msg.on("addSeat", function () {
if ($("#prior_seat span").length >= 6) {
msg.sendAction("pageNotification", { id: "seatNumOutTip", title: "提示", message: "由于12306的自动刷票不支持针对5个以上的席别进行检测因此超出的部分席别无法应用到12306自带刷票中。请使用订票助手的自动刷票。" });
return;
}
suspendStationUpdate = true;
var check = $("#sel-seat input[value='" + tagOtnMap[this] + "']:not(:checked)");
check.length && check[0].click();
suspendStationUpdate = false;
});
msg.on("seatReset", function () {
suspendStationUpdate = true;
$("#prior_seat span:gt(0) a").click();
$(document).trigger("restoreSeat", [this]);
suspendStationUpdate = false;
});
})();
//联系人
(function () {
var addFailedTip = function () {
msg.sendAction("pageNotification", { id: "addFailedTip", title: "提示", message: "添加联系人失败,请先将联系人保存到常用联系人中。" });
};
var findSpanForPassenger = function (p) {
var lic = $("#buyer-list li");
var data = p.name + "(" + p.typename + ")(" + p.id + ")";
return $(_.find($.makeArray(lic), function (e) {
return $.trim($(e).text()) === data;
}));
};
$(document).on("restorePassenger", function (e, passengers) {
suspendStationUpdate = true;
$.each(passengers, function () {
var check = findSpanForPassenger(this).find(":checkbox");
if (check.length) {
if (!check.is(":checked"))
check[0].click();
} else {
//没有找到?可能是新增的。。
var rawP = toRawPassenger(this);
evalCode.eval("(function(){window.passengerAll.push(" + JSON.stringify(rawP) + "); $.renderPassenger();})()");
check = findSpanForPassenger(this).find(":checkbox");
if (check.length) {
if (!check.is(":checked"))
check[0].click();
} else {
addFailedTip();
}
}
});
$("#setion_postion").find("span:gt(0) a").click(removeHandle);
suspendStationUpdate = false;
});
//当用户选择时,发送消息到后台
$(document).on("click", "#buyer-list :checkbox", function () {
if (suspendStationUpdate) return;
suspendStationUpdate = true;
var li = $(this).closest("li");
var info = li.getTrimedText();
var data = /^(.*?)\(([^\)]+)\)\(([^\)]+)\)$/.exec(info);
if (this.checked) {
msg.sendAction("addPassenger", { name: data[1], typename: data[2], id: data[3] });
$("#setion_postion span:gt(0):last a").click(removeHandle);
} else {
msg.sendAction("removePassenger", { name: data[1], typename: data[2], id: data[3] });
}
suspendStationUpdate = false;
});
var removeHandle = function () {
var span = $(this).closest("span");
var name = span.attr("name");
var data = /^(.*?)\(([^\)]+)\)\(([^\)]+)\)$/.exec(name);
msg.sendAction("removePassenger", { name: data[1], typename: data[2], id: data[3] });
};
msg.on("removePassenger", function () {
var data = this.name + "(" + this.typename + ")(" + this.id + ")";
$("#setion_postion span[name='" + data + "'] a")[0].click();
});
msg.on("addPassenger", function () {
var data = this.name + "(" + this.typename + ")(" + this.id + ")";
var check = findSpanForPassenger(this).find(":checkbox");
if (check.length) {
if (!check.is(":checked"))
check[0].click();
} else {
//没有找到?可能是新增的。。
var rawP = toRawPassenger(this);
evalCode.eval("window.passengerAll.push(" + JSON.stringify(rawP) + "); $.renderPassenger();");
check = findSpanForPassenger(this).find(":checkbox");
if (check.length) {
if (!check.is(":checked"))
check[0].click();
} else {
addFailedTip();
}
}
});
})();
//优选车次
(function () {
var notSupportNotify = function () {
//msg.sendAction("pageNotification", { id: "noRegSupport", title: "提示", message: "由于12306的自动刷票不支持高级过滤规则因此部分车次无法添加到列表中。但是订票助手会自动帮你处理兼容性因此刷票不会受到影响。" });
};
$(document).on("restoreTrain", function (e, trains) {
suspendStationUpdate = true;
var html = [];
var foundExtra = false, trainFiltered = [];
$.each(trains, function () {
var tcode = (this + '').toUpperCase();
if (!tcode)
return;
if (!/^[A-Z]?\d+$/i.test(tcode)) {
foundExtra = true;
return;
}
trainFiltered.push(tcode);
html.push("<span class='sel-box w80'>{{TRAIN}}<a class='close' href='javascript:' onclick='$.removeSel(this,\"{{TRAIN}}\",4)'></a></span>".replace(/{{TRAIN}}/g, tcode));
});
$("#prior_train").find("span:gt(0)").remove().end().append(html.join("")).find("span a").click(removeHandle);
evalCode.eval("window.ccSelected=[" + _.map(trainFiltered, function (d) {
return "'" + d + "'";
}).join(", ") + "]");
suspendStationUpdate = false;
if (foundExtra) {
notSupportNotify();
}
});
//当用户选择席别时,发送消息到后台
$("#add-train").click(function () {
if (suspendStationUpdate) return;
suspendStationUpdate = true;
var box = $("#prior_train span:gt(0):last");
if (!box)
return;
msg.sendAction("addTrain", $.trim(box.text()));
suspendStationUpdate = false;
});
var removeHandle = function () {
var span = $(this).closest("span");
msg.sendAction("removeTrain", $.trim(span.text()));
};
var findTrainSpan = function (id) {
var boxes = $.makeArray($("#prior_train span:gt(0)"));
return _.find(boxes, function (b) {
return $.trim($(b).text()) == id;
});
};
msg.on("removeTrain", function () {
var box = findTrainSpan(this);
if (!box) return;
$(box).find("a")[0].click();
});
msg.on("addTrain", function () {
var tcode = (this + '').toUpperCase();
var box = findTrainSpan(tcode);
if (box) return;
if (!/^[A-Z]?\d+$/i.test(tcode)) {
notSupportNotify();
return;
}
$("#prior_train").append("<span class='sel-box w80'>{{TRAIN}}<a class='close' href='javascript:' onclick='$.removeSel(this,\"{{TRAIN}}\",4)'></a></span>".replace(/{{TRAIN}}/g, tcode))
.find("span:last a").click(removeHandle);
evalCode.eval("window.ccSelected.push(\"" + this + "\")");
});
})();
//其它杂项
(function () {
suspendStationUpdate = true;
$doc.on("restoreMisc", function () {
$("#_prior").val(currentProfile.selectSeatFirst ? "1" : "2");
$("#autoSubmit:enabled").prop("checked", currentProfile.autoSubmitEnabled);
$("#partSubmit:enabled").prop("checked", currentProfile.partialSubmitEnabled);
if (!currentProfile.studentTicket) {
document.getElementById("sf1").click();
} else {
document.getElementById("sf2").click();
}
suspendStationUpdate = false;
});
var handler = function () {
suspendStationUpdate = true;
var id = $(this).attr("id");
if (id === 'sf1' || id === 'sf2') {
msg.sendAction("miscChanged", { key: "studentTicket", value: document.getElementById("sf2").checked });
} else if (id === '_prior') {
msg.sendAction("miscChanged", { key: "selectSeatFirst", value: $(this).val() === '1' });
} else {
var key = id === 'autoSubmit' ? "autoSubmitEnabled" : "partialSubmitEnabled";
var value = this.checked;
msg.sendAction("miscChanged", { key: key, value: value });
}
suspendStationUpdate = false;
};
msg.on("miscChanged", function () {
if (suspendStationUpdate)
return;
var id = this.key;
var value = this.value;
if (id === 'studentTicket') {
if (value === document.getElementById("sf2").checked)
return;
document.getElementById("sf" + (value ? "2" : "1")).click();
} else if (id === 'selectSeatFirst') {
value = value ? "1" : "2";
if ($("#_prior").val() === value)
return;
$("#_prior").val(value);
} else if (id === 'partialSubmitEnabled' || id === 'autoSubmitEnabled') {
var key = id === 'autoSubmitEnabled' ? "autoSubmit" : "partSubmit";
if (document.getElementById(key).checked === value)
return;
$("#" + key).prop("checked", value).change();
}
});
$("#_prior, #autoSubmit, #partSubmit").change(handler);
$("#sf1, #sf2").click(handler);
})();
//选项展开状态
(function () {
//show_more
$("#show_more").click(function () {
var a = $(this);
msg.sendAction("userOptionChanged", { showMore: a.hasClass("up") });
});
})();
//查询
(function () {
var sendStopQueryInfo = function () {
msg.sendAction("queryStop", getCurrentStationInfo());
};
msg.on("startQuery", function (r) {
log.print("query");
//如果使用系统自己的刷票功能,那就提示
if ($("#query_ticket.btn-disabled").length) {
alert("亲,查询按钮还是灰色,咱不着急,稍安勿躁 :-)");
r({ canquery: false });
return;
}
log.print("正在尝试查票,时间:" + new Date());
if ($("#auto_query:not(:checked)").length && document.getElementById("autoSubmit").disabled == false && currentProfile.autoSubmitEnabled) {
$("#auto_query")[0].click();
}
if (!document.getElementById("autoSubmit").disabled && currentProfile.autoSubmitEnabled && !document.getElementById("autoSubmit").checked)
document.getElementById("autoSubmit").checked = true;
suspendStationUpdate = true;
if (this.date) {
$("#train_date").val(this.date);
}
if (!this.byAuto) {
//这里不需要更新信息了
}
currentProfile.byAuto = this.byAuto;
var ql = $("#query_ticket");
ql[0].click();
log.print("正在尝试查票,已点击,时间:" + new Date());
var result = ql.hasClass('btn-disabled') || ql.text().indexOf("停止") != -1;
r({ canquery: result, sysAuto: ql.text().indexOf("停止") != -1 });
suspendStationUpdate = false;
});
msg.on("stopQuery", function () {
var ql = $("#query_ticket");
if (ql.text().indexOf("停止") != -1)
ql[0].click();
});
$(document).on("prompt", function () {
sendStopQueryInfo();
//聚焦
var info = $("#filterRes").text();
msg.sendAction("notify", { iconUrl: "/icons/icon_128.png", title: "灰来约票!", message: "主淫,快来把票推倒啊!" + info });
msg.sendAction("attention");
}).on("autoSubmit", function () {
sendStopQueryInfo();
//聚焦
msg.sendAction("notify", { iconUrl: "/icons/icon_128.png", title: "灰来约票!", message: "主淫,快来输入验证码把票推倒啊!" });
msg.sendAction("attention");
setTimeout(function () {
document.getElementById("img_rand_code2").focus();
}, 100);
});
$("#query_ticket").click(function () {
if (suspendStationUpdate) return;
var ele = $(this);
if (ele.data("suspend")) {
ele.removeData("suspend");
return;
}
$("#train_date").change();
setTimeout(function () {
if (ele.text().indexOf("停止") == -1 || ele.hasClass("btn-disabled"))
sendStopQueryInfo();
}, 10);
});
})();
msg.sendAction("setResignMode", { profile: newProfile });
});
function getCurrentStationInfo() {
if (!document.getElementById("fromStationText")) return null;
var data = {
fromText: $("#fromStationText").val(),
fromCode: $("#fromStation").val(),
toText: $("#toStationText").val(),
toCode: $("#toStation").val(),
depDate: $("#train_date").val()
};
return data;
}
//车次预过滤等处理
(function () {
var trainData;
$doc.on("getTrainFilterData", function (e) {
e.result = trainData;
});
$doc.on("dd", function (e, d) {
var result = d;
if (!Array.isArray(result.data) || !result.data.length || !result.data[0].queryLeftNewDTO) return;
trainData = { raw: result, rawTrainMap: {}, trainMap: {}, auto: null, nextTime: null };
_.each(result.data, function (t) {
var train = {
id: t.queryLeftNewDTO.train_no,
code: t.queryLeftNewDTO.station_train_code,
available: t.queryLeftNewDTO.canWebBuy === 'Y' ? 1 : 0,
start: {
code: t.queryLeftNewDTO.start_station_telecode,
name: t.queryLeftNewDTO.start_station_name,
},
from: {
code: t.queryLeftNewDTO.from_station_telecode,
fromStationNo: t.queryLeftNewDTO.from_station_no,
name: t.queryLeftNewDTO.from_station_name,
endpoint: t.queryLeftNewDTO.from_station_telecode == t.queryLeftNewDTO.start_station_telecode,
time: t.queryLeftNewDTO.start_time
},
to: {
code: t.queryLeftNewDTO.to_station_telecode,
toStationNo: t.queryLeftNewDTO.to_station_no,
name: t.queryLeftNewDTO.to_station_name,
endpoint: t.queryLeftNewDTO.end_station_telecode == t.queryLeftNewDTO.to_station_telecode,
time: t.queryLeftNewDTO.arrive_time
},
elapsedTime: {
days: t.queryLeftNewDTO.day_difference,
total: t.queryLeftNewDTO.lishi
},
end: {
code: t.queryLeftNewDTO.end_station_telecode,
name: t.queryLeftNewDTO.end_station_name,
},
ypinfo: t.queryLeftNewDTO.yp_info,
ypinfo_ex: t.queryLeftNewDTO.yp_ex,
locationCode: t.queryLeftNewDTO.location_code,
controlDay: t.queryLeftNewDTO.control_day,
supportCard: t.queryLeftNewDTO.is_support_card,
saleTime: t.queryLeftNewDTO.sale_time,
secureStr: t.secretStr,
selltime: null
};
var kp = _.pairs(getTicketInfo(t.queryLeftNewDTO.yp_info));
train.price = _.object(_.filter(kp, function (p) { return p[0][0] === '_'; }));
train.tickets = _.object(_.filter(kp, function (p) { return p[0][0] !== '_'; }));
//起售时间
var selltimem = /(0*(\d+)月0*(\d+)日)?(\d+)\s*点\s*((\d+)分)?\s*起售/i.exec(t.buttonTextInfo.replace(/<.*?>/g, ''));
if (selltimem) {
train.available = -1;
train.selltime = new Date();
train.selltime.setHours(parseInt(selltimem[4]));
train.selltime.setMinutes(parseInt(selltimem[6] || "0", 10));
train.selltime.setSeconds(0);
if (selltimem[1]) {
//带日期
train.selltime.setMonth(parseInt(selltimem[2]) - 1);
train.selltime.setDate(parseInt(selltimem[3]));
if (train.selltime.getMonth() < new Date().getMonth()) {
train.selltime.setFullYear(train.selltime.getFullYear() + 1);
}
}
}
trainData.rawTrainMap[train.id] = t;
trainData.trainMap[train.id] = train;
});
trainData.original = _.values(trainData.trainMap);
trainData.available = trainData.original;
trainData.trainCodes = _.pluck(trainData.original, "code");
trainData.filtered = [];
trainData.include = trainData.available;
//执行车次预过滤。过滤内容:出发地,目标地,时间
$(document).trigger("filterTrains", trainData);
//处理车次
$(document).trigger("processTrains", trainData);
//过滤数据
if (trainData.filtered && trainData.filtered.length) {
//从原始数据中删除
var orgMap = _.toMap(result.data, function (e) {
return e.queryLeftNewDTO.train_no;
});
var filtered = _.map(trainData.filtered, function (t) {
return orgMap[t.id];
});
trainData.rawDataFiltered = _.without.apply(null, [result.data].concat(filtered));
result.data = trainData.rawDataFiltered;
$doc.trigger("dispatch", ["dr", result]);
}
//记录可能存在的车次,并按照预定列表过滤后,自动填入候选车次列表中。
if (currentProfile.selectedTrain.length) {
var trains = _.pluck(trainData.include, "code");
$doc.trigger("restoreTrain", [trains]);
}
});
})();
(function () {
$(document).bind("qr", function (e, ex) {
$doc.trigger("prepareResult");
$doc.trigger("trainListComplete");
});
})();
(function () {
var auto;
$(document).bind("performAutoSubmit", function (e, ex) {
auto = ex;
if (!auto)return;
evalCode.eval("submitOrderRequest(\"" + auto.data.secureStr + "\", \"" + auto.data.from.time + "\");");
});
})();
//#endregion
//#region 显示实际票数
(function () {
var queryData;
$(document).on("prepareResult", function (e) {
if (typeof sysConfig === 'undefined') {
$(document).bind("sysConfigUpdated", function () {
document.dispatchEvent(new CustomEvent("qr"));
});
return;
}
//如果之前的处理失败了,那么才开始处理
//执行车次预过滤。过滤内容:出发地,目标地,时间
var je = new $.Event("getTrainFilterData");
$doc.trigger(je);
if (je.result) {
queryData = je.result;
} else {
var rows = $("#queryLeftTable tr");
queryData = { raw: null, rawTrainMap: {}, trainMap: {}, auto: null, nextTime: null };
rows.each(function () {
var tr = $(this);
//基本信息分解
var infodiv = tr.find("td:eq(0)>div>div");
var idinfo = infodiv.eq(0).find("a");
if (!idinfo.length) return;
var idargs = idinfo.attr("id").split('_');
var tinfo = {
id: idargs[0],
from: { code: idargs[1] },
to: { code: idargs[2] }
};
//额外信息
var exinfo = infodiv.eq(0).find(">span").attr("id").split('_');
tinfo = _.extend(tinfo, {
fromStationNo: exinfo[1],
toStationNo: exinfo[2],
ypinfo: exinfo[3],
seatTypes: exinfo[4].split("")
});
//余票信息?
tinfo.tickets = getTicketInfo(tinfo.ypinfo);
var kp = _.pairs(getTicketInfo(tinfo.ypinfo));
tinfo.price = _.object(_.filter(kp, function (p) { return p[0][0] === '_'; }));
tinfo.tickets = _.object(_.filter(kp, function (p) { return p[0][0] !== '_'; }));
//发到站信息
var sinfo = infodiv.eq(1).find("strong");
tinfo.from.name = $.trim(sinfo.eq(0).text());
tinfo.from.endpoint = sinfo.eq(0).hasClass("start-s");
tinfo.to.name = $.trim(sinfo.eq(1).text());
tinfo.to.endpoint = sinfo.eq(1).hasClass("end-s");
//时间信息
var tminfo = infodiv.eq(2).find("strong");
tinfo.from.time = $.trim(tminfo.eq(0).text());
tinfo.to.time = $.trim(tminfo.eq(1).text());
//是否有效?
var cb = tr.find("td:last a");
if (!cb.length) {
tinfo.available = 0;
var txt = $.trim(tr.find("td:last"));
//起售时间
var selltimem = /(0*(\d+)月0*(\d+)日)?(\d+)\s*点\s*((\d+)分)?\s*起售/i.exec(t.buttonTextInfo.replace(/<.*?>/g, ''));
if (selltimem) {
tinfo.available = -1;
tinfo.selltime = new Date();
tinfo.selltime.setHours(parseInt(selltimem[4]));
train.selltime.setMinutes(parseInt(selltimem[6] || "0", 10));
tinfo.selltime.setSeconds(0);
if (selltimem[1]) {
//带日期
tinfo.selltime.setMonth(parseInt(selltimem[2]) - 1);
tinfo.selltime.setDate(parseInt(selltimem[3]));
if (tinfo.selltime.getMonth() < new Date().getMonth()) {
tinfo.selltime.setFullYear(tinfo.selltime.getFullYear() + 1);
}
}
}
} else {
tinfo.available = 1;
tinfo.secureStr = /\(['"](.*?)['"]\)/.exec(cb.attr("onclick"))[1];
}
tr.data("ticket", tinfo);
queryData.trainMap[tinfo.id] = tinfo;
});
queryData.original = _.values(queryData.trainMap);
queryData.available = queryData.original;
queryData.trainCodes = _.pluck(queryData.original, "code");
queryData.filtered = [];
queryData.include = queryData.available;
$(document).trigger("filterTrains", queryData);
//处理车次
$(document).trigger("processTrains", queryData);
if (queryData.filtered && queryData.filtered.length) {
//从原始数据中删除
_.each(queryData.filtered, function () {
var tr = $("#ticket_" + this.id);
tr.remove();
});
}
}
if (sysConfig.showRealSeatCount) {
_.each(queryData.original, function (train) {
$.each(train.tickets, function (key, value) {
if (key[0] === "_") return;
var price = train.price["_" + key];
var td = $("#" + tagOtnMap[key] + "_" + train.id);
var text = value == 0 ? "无" : value;
if (value) {
td.addClass("t-num");
}
if (price && sysConfig.showTicketPrice)
text += "<br /><span style='font-size:11px; color:blue;font-weight:normal; font-family: Arial;'>" + (sysConfig.appendPriceUnit ? "¥" : "") + (price / 10) + "</span>";
td.html(text);
});
});
}
});
})();
$doc.bind(EVT_ONQUERYPAGE, function () {
//randCode2
$(document).on("keyup", "#randCode2", function () {
if (!this.value || this.value.length < 4 || sysConfig.otnAutoConfirmOrderDelay < 0) {
return;
}
if ($("#qr_submit.btn92s").nativeClick(sysConfig.otnAutoConfirmOrderDelay).length) {
msg.sendAction("notify", {
title: "提示",
message: "已自动提交等待12306回应。如卡太久请重试一次。",
iconUrl: "/icons/icon_128.png"
});
}
}).bind("autoSubmit", function () {
setTimeout(function () {
$("#randCode2").nativeFocus();
}, 500);
});
});
//#endregion
//#region 提交页面
$doc.on("renderCheckTickInfo", function () {
if (sysConfig.otnAutoConfirmOrderDelay >= 0) {
setTimeout(function () {
if ($("#qr_submit_id.btn92s").nativeClick().length) {
msg.sendAction("notify", {
title: "提示",
message: "已自动提交等待12306回应。如卡太久请重试一次。",
iconUrl: "/icons/icon_128.png"
});
}
else {
msg.sendAction("notify", {
title: "提示",
message: "未能帮你自动提交,请尽快手动提交。",
iconUrl: "/icons/icon_128.png"
});
}
}, sysConfig.otnAutoConfirmOrderDelay);
}
});
$(document).bind(EVT_ONSUBMITPAGE, function () {
var stat = null;
var enableSubmitOrder = false;
var info = evalCode.eval("window.ticketInfoForPassengerForm");
unsafeInvoke(function up() {
// $.fn.query_passenger = (function (o) {
// return function () {
// o.apply(this, $.makeArray(arguments));
// document.dispatchEvent(new CustomEvent("query_passenger"));
// return this;
// };
// })($.fn.query_passenger);
//document.addEventListener("sf", function () {
// $("div.tj_btn button:last")[0].click();
// });
$(document).ajaxComplete(function (e, xhr, s) {
var x = new CustomEvent("ajax", {
detail: {
url: s.url,
status: xhr.status,
resp: xhr.responseText,
data: s.data,
type: s.type
}
});
document.dispatchEvent(x);
});
});
//是否有学生票?
var pas, hasStudent, canStudent;
var initPassengerSelect = function () {
pas = (stat && stat.auto && stat.auto.passengers) || (currentProfile && currentProfile.passengers);
if (!pas) return;
hasStudent = _.findWhere(pas, { type: "3" });
canStudent = _.findWhere(info.limitBuySeatTicketDTO.ticket_type_codes, { id: "3" });
_.each(pas, function (e) {
e.key = e.name + "_" + e.idtype + "_" + e.id;
});
if (!canStudent) {
_.each(pas, function (e) {
e.type = "1";
});
hasStudent = false;
}
selectPassenger();
};
var selectPassenger = function () {
if ((info.purpose_codes == "0X00" || (hasStudent && canStudent)) && !$("#normal_passenger_id li").length) {
//还没有添加成功
var x = setInterval(function () {
if ($("#normal_passenger_id li").length) {
clearInterval(x);
selectPassenger();
}
}, 300);
} else {
//选择
if (info.tour_flag != 'gc') {
if (info.purpose_codes === "0X00" || hasStudent) {
$("#show_more_passenger_id")[0].click();
$.each(pas, function() {
$("input:checkbox[id^='normalPassenger_" + this.key + "']")[0].click();
});
} else {
var needAdd = false;
$.each(pas, function() {
//if (this.save) {
//手动加的
if (needAdd)
$("div.add-per > span")[0].click();
else {
needAdd = true;
}
var tr = $("#ticketInfo_id tr:not(.tips):last");
tr.find("td:eq(2) select").val(this.type);
tr.find("td:eq(3) input").val(this.name);
tr.find("td:eq(4) select").val(this.idtype);
tr.find("td:eq(5) input").val(this.id);
tr.find("td:last :checkbox").prop("checked", this.save);
//} else {
// var ck = $("#" + this.name + this.idtype + this.id + " :checkbox");
// if (!ck.length) return;
// ck.click();
//}
});
}
}
//选择席别
if (stat && stat.auto)
$("select[id^=seatType_]").val(stat.auto.seat === '0' ? '1' : stat.auto.seat);
if (pas && pas.length) {
setTimeout(function () {
document.getElementById("randCode").focus();
}, 500);
}
}
};
//自动提交?
msg.on("enableSubmitOrder", function () {
enableSubmitOrder = true;
$("#randCode").keyup();
});
$("#randCode").keyup(function () {
if (!enableSubmitOrder) return;
if (sysConfig.autoSubmitAfterVerifyCode && this.value.length >= 4) {
if ($("#submitOrder_id").nativeClick(1).length) {
msg.sendAction("notify", {
title: "提示",
message: "已自动提交等待12306回应。如卡太久请重试一次。",
iconUrl: "/icons/icon_128.png"
});
}
}
});
$("#submitOrder_id").click(function () {
sysConfig.autoSubmitAfterVerifyCode && $("#qr_submit_id:visible").nativeClick(1);
});
document.addEventListener("ajax", function (e) {
var i = e.detail;
if (i.url.indexOf("method=getQueueCount") === -1) return;
setTimeout(function () {
var btns = parent.$("#queue_note").closest(".ui-dialog").find("button");
for (var j = 0; j < btns.length; j++) {
if ($.trim(btns.eq(j).text()).replace(/\s/g, "") === "确定") {
btns[j].click();
}
}
}, 1000);
});
//报告车次参数
(function () {
var data = {
date: new Date(info.orderRequestDTO.train_date.time).format("yyyy-MM-dd"),
from: info.orderRequestDTO.from_station_telecode,
to: info.orderRequestDTO.to_station_telecode,
td: info.orderRequestDTO.train_no,
code: info.purpose_codes,
tcode: info.station_train_code
};
chrome.runtime.sendMessage({ action: "reportSubmitInfo", detail: data });
})();
var getLastAuto = function () {
chrome.runtime.sendMessage({ action: "getLastAutoData" }, function (m) {
stat = m;
initPassengerSelect();
});
};
var getCurrentUser = function () {
chrome.runtime.sendMessage({ action: "getCurrentUser" }, function (message) {
currentProfile = message.detail.currentProfile;
getLastAuto();
});
};
getCurrentUser();
});
//#endregion
//#region 路由函数
$doc.bind("routePage", function () {
var path = location.pathname.slice(5);
var search = location.search.slice(1);
var onValidPage = false;
var dispatchEvent = function (evt) {
onValidPage = true;
var username = ISLOGINED ? $.trim($("#login_user").text()) : "";
chrome.runtime.sendMessage({
action: "pageInitCall",
detail: {
page: evt,
logined: ISLOGINED,
username: username
}
});
$(document).trigger(evt);
};
if (path === "login/init") {
dispatchEvent(EVT_ONLOGINPAGE, true);
}
if (path === '' || path === 'index/init') {
if (ISLOGINED) {
var name = $("#login_user").getTrimedText();
chrome.runtime.sendMessage({
action: "logTempUserSuccess",
detail: {
name: name
}
});
}
//dispatchEvent(EVT_ONMAINPAGE);
}
if (path === 'leftTicket/init') {
if (!ISLOGINED)
$(document).trigger(EVT_ONLOGINPAGE);
dispatchEvent(EVT_ONQUERYPAGE);
}
if (path === "confirmPassenger/initDc" || path === "confirmPassenger/initGc" || path === "confirmPassenger/initWc") {
//订单页
dispatchEvent(EVT_ONSUBMITPAGE);
}
//没有操作?
if (!onValidPage) {
chrome.runtime.sendMessage({ action: "onUnvalidPage" });
}
});
//#endregion
//#region BUG
(function () {
var executed = false;
$(function () {
executed = true;
});
if (document.readyState === "complete") {
if (!executed)
$.ready();
} else {
var callback = function () {
if (document.readyState !== "complete")
return;
clearInterval(timer);
if (!executed)
$.ready();
};
var timer = setInterval(callback, 100);
}
})();
//#endregion