FCLT#60561 MS-Graph koppeling savepoint nu met Webhook mogelijkheid
svn path=/Website/trunk/; revision=49932
This commit is contained in:
159
UTILS/Exchange/create_webhooks.wsf
Normal file
159
UTILS/Exchange/create_webhooks.wsf
Normal file
@@ -0,0 +1,159 @@
|
||||
<![CDATA[
|
||||
/*
|
||||
$Id$
|
||||
|
||||
File: create_webhooks.wsf
|
||||
|
||||
Calling: cscript ..\..\..\utils\exchange\create_webhooks.wsf
|
||||
Parameters: Optioneel nrgokurl zoals bijvoorbeeld https://b01f8e4ffe12.ngrok.io/trunk
|
||||
Context: Scheduled task
|
||||
Description: Maakt voor alle res_ruimte's een webhook waar we notificaties op gaan krijgen
|
||||
Note: De code veronderstelt (nog) dat de current folder een cust/xxxx/exchange folder is
|
||||
Concreter: ../Oracle.udl wordt gebruikt
|
||||
*/
|
||||
]]>
|
||||
|
||||
<job id="exchange_webhooks">
|
||||
<script language="JScript" src="../wsf_shared.js"/>
|
||||
<script language="JScript" src="../json2.js"/>
|
||||
<script language="JScript" src="ms_graph.js"/>
|
||||
|
||||
<script language="JScript">
|
||||
var config = loadconfig("test.config");
|
||||
|
||||
if (WScript.Arguments.length > 0)
|
||||
{
|
||||
var hookurl = WScript.Arguments(0);
|
||||
}
|
||||
else
|
||||
{ // Autodetect ngrok started with: ngrok http sggr.facws001.sg.nl:80
|
||||
var ngrokurl = null;
|
||||
try
|
||||
{ // Probeer of ngrrok is opgestart
|
||||
var result = doHTTP('GET',
|
||||
'http://127.0.0.1:4040/api/tunnels/command_line',
|
||||
null,
|
||||
{"Content-Type": "application/json"});
|
||||
var json = JSON.parse(result.responseText);
|
||||
//WScript.Echo(JSON.stringify(json, null, 2))
|
||||
ngrokurl = json.public_url; // https://09f8481827d5.ngrok.io
|
||||
WScript.Echo("Ngrok detected: " + ngrokurl);
|
||||
WScript.Echo(" tip: view traffic at http://127.0.0.1:4040");
|
||||
hookurl = ngrokurl + "/trunk/";
|
||||
}
|
||||
catch(e)
|
||||
{
|
||||
__Log("Usage: CScript create_webhooks.wsf <<hookurl>>");
|
||||
__Log(" hookurl: https://xxxx.facilitor.nl");
|
||||
__Log("For local testing start ngrok.exe en omit hookurl");
|
||||
WScript.Quit(1);
|
||||
}
|
||||
}
|
||||
WScript.Echo("Using hookurl : " + hookurl);
|
||||
|
||||
var apiname = 'MSGRAPHNOTIFICATION'; // must point to appl/api/api_msgraphnotification.asp
|
||||
|
||||
var token = requestToken(config);
|
||||
|
||||
var oCrypto = new ActiveXObject("SLNKDWF.Crypto");
|
||||
|
||||
var Oracle = new ActiveXObject("ADODB.Connection");
|
||||
Oracle.Open('File Name=../Oracle.udl');
|
||||
|
||||
var sql = "BEGIN DBMS_APPLICATION_INFO.SET_MODULE ('create_webhooks.wsf', NULL); END;";
|
||||
Oracle.Execute(sql);
|
||||
|
||||
var sql = "SELECT fac_version_cust FROM fac_version";
|
||||
var oRs = Oracle.Execute(sql);
|
||||
var customerId = oRs(0).Value;
|
||||
oRs.Close();
|
||||
|
||||
//var sql = "SELECT prs_perslid_apikey FROM prs_perslid WHERE prs_perslid_login = '_MSGRAPHNOTIFICATION'";
|
||||
//var oRs = Oracle.Execute(sql);
|
||||
//var APIKEY = oRs(0).Value;
|
||||
//oRs.Close();
|
||||
var apikey = 'APIJOSGL';
|
||||
|
||||
var future = new Date();
|
||||
if (ngrokurl)
|
||||
{
|
||||
future.setMinutes(future.getMinutes() + 120); // ngrok is toch na 2 uur expired
|
||||
}
|
||||
else
|
||||
{
|
||||
future.setDate(future.getDate() + 2); // 2 dagen (max is 3)
|
||||
}
|
||||
|
||||
var webhookurl = hookurl + "?API={0}&APIKEY={1}&fac_id={2}".format(apiname, apikey, customerId); // fac_id is vooral voor ngrok nodig
|
||||
|
||||
// Test zelf ook even de hookurl direct op dezelfde manier als MS-Graph dat doen.
|
||||
// Zelf kunnen we betere foutmeldingen geven
|
||||
var validationToken = "Validation: testing create_webhooks.wsf connection " + new Date().toISOString();
|
||||
WScript.Echo("\nPre-testing webhook url (like MS Graph will do soon): ");
|
||||
WScript.Echo("get "+ webhookurl + "&validationToken=" + encodeURIComponent(validationToken));
|
||||
try
|
||||
{
|
||||
var result = doHTTP('GET',
|
||||
webhookurl + "&validationToken=" + encodeURIComponent(validationToken),
|
||||
null,
|
||||
{"Accept": "application/json"}); // application/json maakt dat een AiAi leesbaarder terugkomt
|
||||
if (!result || result.responseText != validationToken)
|
||||
{
|
||||
WScript.Echo("FAILED");
|
||||
WScript.Echo("Expected: " + validationToken);
|
||||
if (result)
|
||||
WScript.Echo(" Got: " + result.responseText);
|
||||
WScript.Quit(1);
|
||||
}
|
||||
}
|
||||
catch(e)
|
||||
{
|
||||
WScript.Echo("FAILED");
|
||||
WScript.Echo(e.description);
|
||||
WScript.Quit(1);
|
||||
}
|
||||
WScript.Echo("SUCCESS\n");
|
||||
|
||||
var sql = "SELECT res_ruimte_key,"
|
||||
+ " res_ruimte_extern_id,"
|
||||
+ " res_ruimte_graphhooksecret"
|
||||
+ " FROM res_ruimte"
|
||||
+ " WHERE res_ruimte_verwijder IS NULL"
|
||||
+ " AND res_ruimte_extern_id IS NOT NULL";
|
||||
var oRs = Oracle.Execute(sql);
|
||||
while (!oRs.Eof)
|
||||
{
|
||||
var email = oRs("res_ruimte_extern_id").Value;
|
||||
WScript.Echo("Creating hook for " + email);
|
||||
var user = getGraphUser(email);
|
||||
var user_id = user.id;
|
||||
//WScript.Echo(" Id " + user_id);
|
||||
|
||||
// Todo: oude subscription verwijderen?
|
||||
var clientState = oCrypto.hex_random(20);
|
||||
var sql = "UPDATE res_ruimte"
|
||||
+ " SET res_ruimte_graphhooksecret = " + safe.quoted_sql(clientState)
|
||||
+ " WHERE res_ruimte_key = " + oRs("res_ruimte_key").Value;
|
||||
Oracle.Execute(sql);
|
||||
|
||||
|
||||
var reqBody = JSON.stringify({
|
||||
"changeType": "updated",
|
||||
"notificationUrl": webhookurl + "&res_ruimte=" + oRs("res_ruimte_key").Value,
|
||||
"resource": "/users/" + user_id + "/events",
|
||||
"clientState": clientState,
|
||||
"expirationDateTime": future.toJSON()
|
||||
});
|
||||
var result = doHTTP('POST',
|
||||
'https://graph.microsoft.com/v1.0/subscriptions',
|
||||
reqBody,
|
||||
{"Content-Type": "application/json", "Authorization": "Bearer " + token});
|
||||
|
||||
WScript.Echo(JSON.stringify(JSON.parse(result.responseText), null, 2))
|
||||
oRs.MoveNext();
|
||||
}
|
||||
oRs.Close();
|
||||
|
||||
Oracle.Close();
|
||||
</script>
|
||||
</job>
|
||||
@@ -24,52 +24,9 @@
|
||||
// V todo-5: schrijven van een CSV bestand obv de xhr-response ipv CSV obv .xsl bestand
|
||||
|
||||
var fso = new ActiveXObject("Scripting.FileSystemObject");
|
||||
var zaalemail = WScript.Arguments(0); //todo-1:
|
||||
var import_app_key = WScript.Arguments(1); // Gebruik EXCHFULL voor alles in bepaalde periode
|
||||
|
||||
var inifile = ".\\exchange.config";
|
||||
var f = fso.OpenTextFile(inifile, 1); // ForReading
|
||||
var config = eval('(' + f.ReadAll() + ')')
|
||||
f.Close();
|
||||
|
||||
config.loglevel = config.loglevel || 0;
|
||||
|
||||
/// FROM HERE THE ADDED CODE STARTS
|
||||
var msgraphUserOfZaalEmail = '';
|
||||
|
||||
// get bearer token based on client_secret, client_id, tenant
|
||||
function requestToken(client_secret, client_id, tenant) {
|
||||
var token = null;
|
||||
var client_secret = client_secret || config.client_secret || '--1v5muB.yB2Z~2V7~dhtZ5.Dmd_FJcWUf'; //Development secret fallback (temporary)
|
||||
var client_id = client_id || config.client_id || '41706888-968f-469a-b7ce-5ebc9b8432d4'; //Development client fallback (temporary)
|
||||
var tenant = tenant || config.tenant || 'bab7c51b-2329-47f1-b6ff-1a5270efc193'; //Development tenant fallback (temporary)
|
||||
var parms = 'grant_type=' + 'client_credentials'
|
||||
+ '&client_secret=' + client_secret
|
||||
+ '&scope=' + 'https://graph.microsoft.com/.default'
|
||||
+ '&client_id=' + client_id;
|
||||
var xhr = doHTTP("POST", "https://login.microsoftonline.com/" + tenant + "/oauth2/v2.0/token", parms, { "Content-Type": "application/x-www-form-urlencoded" }); //- removed from content type
|
||||
if (xhr != null) {
|
||||
var token = JSON.parse(xhr.responseText).access_token;
|
||||
}
|
||||
return token;
|
||||
}
|
||||
|
||||
// get de MS-graph user by e-mailaddress
|
||||
function getGraphUser(email) {
|
||||
var user = null;
|
||||
var xhr = doHTTP("GET", "https://graph.microsoft.com/v1.0/users", null, { "Accept": "application/json", "Authorization": "Bearer " + token });
|
||||
if (xhr != null) {
|
||||
var users = JSON.parse(xhr.responseText).value;
|
||||
var index;
|
||||
for (index = 0; index < users.length; index++) {
|
||||
if (users[index].mail && users[index].mail.toLowerCase() === email.toLowerCase()) {
|
||||
user = users[index];
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
return user;
|
||||
}
|
||||
|
||||
// get user calendar items based on token and userid
|
||||
function getGraphUserCalendarItems(user_id, skiptoken, deltatoken) {
|
||||
@@ -88,13 +45,13 @@ function getGraphUserCalendarItems(user_id, skiptoken, deltatoken) {
|
||||
dateFrom.setDate(dateFrom.getDate() - config.fullpast);
|
||||
var dateTo = new Date(dateFrom);
|
||||
dateTo.setDate(dateTo.getDate() + config.fullfuture);
|
||||
WScript.Echo("Full syncing from " + dateFrom.toISOString() + " to " + dateTo.toISOString() + " (" + (config.fullfuture + config.fullpast) + " days)");
|
||||
__Log("Full syncing from " + dateFrom.toISOString() + " to " + dateTo.toISOString() + " (" + (config.fullfuture + config.fullpast) + " days)");
|
||||
parms = 'startDateTime=' + dateFrom.toISOString() + '&endDateTime=' + dateTo.toISOString();
|
||||
}
|
||||
|
||||
var xhr = doHTTP("GET", 'https://graph.microsoft.com/v1.0/users/' + user_id + '/calendarView/delta?' + parms, null, { "Accept": "application/json", "Authorization": "Bearer " + token });
|
||||
if (xhr != null) {
|
||||
var response = JSON.parse(xhr.responseText);
|
||||
var response = JSON.parse(xhr.responseText, internal_parsedate);
|
||||
if (response["@odata.deltaLink"] && response["@odata.deltaLink"].indexOf("$deltatoken=") != -1) {
|
||||
response.deltatoken = response["@odata.deltaLink"].split("$deltatoken=")[1];
|
||||
} else if (response["@odata.nextLink"] && response["@odata.nextLink"].indexOf("$skiptoken=") != -1) {
|
||||
@@ -105,104 +62,99 @@ function getGraphUserCalendarItems(user_id, skiptoken, deltatoken) {
|
||||
}
|
||||
///
|
||||
|
||||
WScript.Echo("Connecting to " + config.endpointurl)
|
||||
// ---
|
||||
// kunnen we niets mee doExchange(config.endpointurl, "<m:GetRoomLists />", "roomlist.xml");
|
||||
|
||||
if (!Date.prototype.toISOString) {
|
||||
Date.prototype.toISOString = function () {
|
||||
function pad(n) { return n < 10 ? '0' + n : n }
|
||||
return this.getUTCFullYear() + '-'
|
||||
+ pad(this.getUTCMonth() + 1) + '-'
|
||||
+ pad(this.getUTCDate()) + 'T'
|
||||
+ pad(this.getUTCHours()) + ':'
|
||||
+ pad(this.getUTCMinutes()) + ':'
|
||||
+ pad(this.getUTCSeconds()) + 'Z';
|
||||
};
|
||||
}
|
||||
|
||||
var room_id = safefilename(zaalemail);
|
||||
var deltatoken;
|
||||
var skiptoken;
|
||||
var oRs;
|
||||
|
||||
if (import_app_key != "EXCHFULL") {
|
||||
// vanaf hier alleen wijzigingen ophalen
|
||||
var udl = "../Oracle.udl";
|
||||
var Oracle = new ActiveXObject("ADODB.Connection");
|
||||
Oracle.Open('File Name=' + udl);
|
||||
|
||||
var sql = "BEGIN DBMS_APPLICATION_INFO.SET_MODULE ('Exchange_Graph.js', NULL); END;";
|
||||
Oracle.Execute(sql);
|
||||
|
||||
var sql = "SELECT s.res_ruimte_syncstate" // is deltatoken
|
||||
+ " FROM res_ruimte r"
|
||||
+ " , res_ruimte_sync s"
|
||||
+ " WHERE r.res_ruimte_key = s.res_ruimte_key(+)"
|
||||
+ " AND r.res_ruimte_verwijder IS NULL"
|
||||
+ " AND res_ruimte_extern_id = '" + zaalemail + "'";
|
||||
|
||||
oRs = Oracle.Execute(sql);
|
||||
deltatoken = oRs("res_ruimte_syncstate").Value || "";
|
||||
oRs.Close();
|
||||
WScript.Echo("\n\n==== Room: " + zaalemail + "\nDelta token: " + deltatoken);
|
||||
}
|
||||
else {
|
||||
// no skiptoken and no deltatoken means retrieve all events
|
||||
}
|
||||
|
||||
// Verwijderen : het verwijderen van sync_*.csv
|
||||
try
|
||||
function csv_for_room(zaalemail, import_app_key, as_stream)
|
||||
{
|
||||
fso.DeleteFile(config.xmlfolder + "sync_*.csv");
|
||||
// Als hierboven geen files gevonden zijn komen we in de exception
|
||||
// en niet in onderstaande echo.
|
||||
WScript.Echo("Oude syncfile is verwijderd.");
|
||||
}
|
||||
catch(e)
|
||||
{
|
||||
// Neem aan dat gelukkig geen files zijn gevonden
|
||||
}
|
||||
__Log("Connecting to " + config.endpointurl)
|
||||
// ---
|
||||
// kunnen we niets mee doExchange(config.endpointurl, "<m:GetRoomLists />", "roomlist.xml");
|
||||
|
||||
var skiptoken;
|
||||
var deltatoken;
|
||||
var token = requestToken();
|
||||
var user = getGraphUser(zaalemail);
|
||||
var user_id = user ? user.id : null;
|
||||
if (user_id)
|
||||
{
|
||||
var response = getGraphUserCalendarItems(user_id, skiptoken, deltatoken);
|
||||
var results = response.value;
|
||||
var index;
|
||||
while (response.skiptoken) {
|
||||
response = getGraphUserCalendarItems(user_id, response.skiptoken, null);
|
||||
for (index = 0; index < response.value.length; index++) {
|
||||
results.push(response.value[index]);
|
||||
}
|
||||
|
||||
var room_id = safefilename(zaalemail);
|
||||
var deltatoken;
|
||||
var skiptoken;
|
||||
var oRs;
|
||||
|
||||
if (import_app_key != "EXCHFULL") {
|
||||
// vanaf hier alleen wijzigingen ophalen
|
||||
var sql = "SELECT s.res_ruimte_syncstate" // is deltatoken
|
||||
+ " FROM res_ruimte r"
|
||||
+ " , res_ruimte_sync s"
|
||||
+ " WHERE r.res_ruimte_key = s.res_ruimte_key(+)"
|
||||
+ " AND r.res_ruimte_verwijder IS NULL"
|
||||
+ " AND res_ruimte_extern_id = '" + zaalemail + "'";
|
||||
|
||||
oRs = Oracle.Execute(sql);
|
||||
deltatoken = oRs("res_ruimte_syncstate").Value || "";
|
||||
oRs.Close();
|
||||
__Log("\n\n==== Room: " + zaalemail + "\nDelta token: " + deltatoken);
|
||||
}
|
||||
else {
|
||||
// no skiptoken and no deltatoken means retrieve all events
|
||||
}
|
||||
deltatoken = response.deltatoken;
|
||||
|
||||
// save the CSV file to disc here
|
||||
var outputFileHandle = fso.OpenTextFile(config.xmlfolder + "sync_" + room_id + ".csv", 2); // ForWriting == 2
|
||||
outputFileHandle.write(makeCSV(results));
|
||||
outputFileHandle.close();
|
||||
// Verwijderen : het verwijderen van sync_*.csv
|
||||
try
|
||||
{
|
||||
fso.DeleteFile(config.xmlfolder + "sync_*.csv");
|
||||
// Als hierboven geen files gevonden zijn komen we in de exception
|
||||
// en niet in onderstaande echo.
|
||||
__Log("Oude syncfile is verwijderd.");
|
||||
}
|
||||
catch(e)
|
||||
{
|
||||
// Neem aan dat gelukkig geen files zijn gevonden
|
||||
}
|
||||
|
||||
// deltatoken needs to be saved to retrieve changes during a future run
|
||||
var sql = "UPDATE res_ruimte r, res_ruimte_sync s"
|
||||
+ " SET s.res_ruimte_syncstate = '" + deltatoken + "'"
|
||||
+ " WHERE r.res_ruimte_key = s.res_ruimte_key(+)"
|
||||
+ " AND r.res_ruimte_verwijder IS NULL"
|
||||
+ " AND res_ruimte_extern_id = '" + zaalemail + "'";
|
||||
oRs = Oracle.Execute(sql);
|
||||
oRs.Close();
|
||||
var skiptoken;
|
||||
var deltatoken;
|
||||
var user = getGraphUser(zaalemail);
|
||||
var user_id = user ? user.id : null;
|
||||
if (user_id)
|
||||
{
|
||||
var response = getGraphUserCalendarItems(user_id, skiptoken, deltatoken);
|
||||
var results = response.value;
|
||||
var index;
|
||||
while (response.skiptoken) {
|
||||
response = getGraphUserCalendarItems(user_id, response.skiptoken, null);
|
||||
for (index = 0; index < response.value.length; index++) {
|
||||
results.push(response.value[index]);
|
||||
}
|
||||
}
|
||||
deltatoken = response.deltatoken;
|
||||
// save the CSV file to disc here
|
||||
fileStream = new ActiveXObject("ADODB.Stream");
|
||||
fileStream.Type = 2; // adTypeBinary eerst nog
|
||||
fileStream.Open();
|
||||
fileStream.CharSet = "utf-8";
|
||||
fileStream.WriteText(makeCSV(results));
|
||||
if (as_stream)
|
||||
{
|
||||
// Leveren we die zo op en gaat die rechtstreeks impReadStream in
|
||||
}
|
||||
else
|
||||
{
|
||||
var csvname = config.xmlfolder + "sync_" + room_id + ".csv";
|
||||
fileStream.SaveToFile(csvname, 2); // overwrite
|
||||
}
|
||||
|
||||
// Als we hier komen is alles goed
|
||||
WScript.Quit(10);
|
||||
}
|
||||
else
|
||||
{
|
||||
WScript.Echo("User for email address " + zaalemail + " not found");
|
||||
WScript.Quit(1);
|
||||
// deltatoken needs to be saved to retrieve changes during a future run
|
||||
var sql = "UPDATE res_ruimte r, res_ruimte_sync s"
|
||||
+ " SET s.res_ruimte_syncstate = '" + deltatoken + "'"
|
||||
+ " WHERE r.res_ruimte_key = s.res_ruimte_key(+)"
|
||||
+ " AND r.res_ruimte_verwijder IS NULL"
|
||||
+ " AND res_ruimte_extern_id = '" + zaalemail + "'";
|
||||
__Log(sql);
|
||||
//oRs = Oracle.Execute(sql);
|
||||
|
||||
// Als we hier komen is alles goed
|
||||
return fileStream;
|
||||
}
|
||||
else
|
||||
{
|
||||
__Log("User for email address " + zaalemail + " not found");
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
function quotedVal(val) {
|
||||
@@ -219,7 +171,7 @@ function getMasterEvent(data, id) {
|
||||
}
|
||||
return result;
|
||||
}
|
||||
function makeCsv(data)
|
||||
function makeCSV(data)
|
||||
{
|
||||
var trs = [];
|
||||
var tds = [];
|
||||
@@ -280,7 +232,7 @@ function makeCsv(data)
|
||||
quotedVal(new Date(data[index].start.dateTime).toISOString()),
|
||||
quotedVal(++seqNbr)
|
||||
];
|
||||
} else if (["singleInstance","seriesMaster","exception"].indexOf(data[index].type) != -1) { // singleInstance / seriesMaster / exception
|
||||
} else if (inArray(data[index].type, ["singleInstance","seriesMaster","exception"])) { // singleInstance / seriesMaster / exception
|
||||
tds = [
|
||||
quotedVal(data[index].subject),
|
||||
quotedVal(new Date(data[index].start.dateTime).toISOString()),
|
||||
@@ -290,7 +242,7 @@ function makeCsv(data)
|
||||
quotedVal(data[index].organizer.emailAddress.name),
|
||||
quotedVal("C"), // only changed here
|
||||
quotedVal(data[index].id),
|
||||
quotedVal(["seriesMaster","exception"].indexOf(data[index].type) != -1 ? new Date(data[index].start.dateTime).toISOString() : ""),
|
||||
quotedVal(inArray(data[index].type, ["seriesMaster","exception"]) ? new Date(data[index].start.dateTime).toISOString() : ""),
|
||||
quotedVal(++seqNbr)
|
||||
];
|
||||
}
|
||||
@@ -299,62 +251,3 @@ function makeCsv(data)
|
||||
}
|
||||
return trs.join("\r\n");
|
||||
}
|
||||
|
||||
function doHTTP(method, url, body, headers) {
|
||||
//var SXH_PROXY_SET_PROXY = 2;
|
||||
var SXH_OPTION_IGNORE_SERVER_SSL_CERT_ERROR_FLAGS = 2;
|
||||
var SXH_SERVER_CERT_IGNORE_ALL_SERVER_ERRORS = 0x3300;
|
||||
|
||||
var objXMLHTTP = new ActiveXObject("MSXML2.ServerXMLHTTP.6.0");
|
||||
// objXMLHTTP.setProxy(SXH_PROXY_SET_PROXY, "127.0.0.1:8888");
|
||||
|
||||
objXMLHTTP.open(method, url, false);
|
||||
if (headers) {
|
||||
var header;
|
||||
for (header in headers) {
|
||||
objXMLHTTP.setRequestHeader(header, headers[header]);
|
||||
}
|
||||
}
|
||||
|
||||
objXMLHTTP.setOption(SXH_OPTION_IGNORE_SERVER_SSL_CERT_ERROR_FLAGS, SXH_SERVER_CERT_IGNORE_ALL_SERVER_ERRORS);
|
||||
|
||||
if (config.loglevel > 0)
|
||||
__Log2File("request.xml", body);
|
||||
objXMLHTTP.send(body);
|
||||
|
||||
if (objXMLHTTP.status >= 200 && objXMLHTTP.status <= 299) {
|
||||
return objXMLHTTP;
|
||||
}
|
||||
// else: er is iets fout
|
||||
__Log2File("response.xml", objXMLHTTP.responseText);
|
||||
WScript.Echo(objXMLHTTP.status);
|
||||
WScript.Echo(objXMLHTTP.statusText);
|
||||
WScript.Echo(objXMLHTTP.responseText);
|
||||
return null;
|
||||
}
|
||||
|
||||
function safefilename(naam) // geen 'lage' karakters en geen (back)slashes, *,%,<,>, '"', ':', ';' '?' and '|' of '+'
|
||||
{
|
||||
return naam.replace(/[\x00-\x1F|\/|\\|\*|\%\<\>\"\:\;\?\|\+]+/g, "_"); // " syntax highlight correctie
|
||||
}
|
||||
function __Log2File(log_file, data) {
|
||||
var utf8Stream = new ActiveXObject("ADODB.Stream");
|
||||
utf8Stream.Open();
|
||||
utf8Stream.Type = 2;
|
||||
utf8Stream.CharSet = "utf-8";
|
||||
utf8Stream.WriteText(data);
|
||||
utf8Stream.SaveToFile(config.xmlfolder + safefilename(log_file), 2);
|
||||
utf8Stream.Close();
|
||||
}
|
||||
|
||||
// From MyJSON in shared.inc
|
||||
function internal_parsedate(key, value) {
|
||||
var a;
|
||||
if (typeof value === 'string') {
|
||||
a = /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2}(?:\.\d*)?)Z$/.exec(value);
|
||||
if (a) {
|
||||
return new Date(Date.UTC(+a[1], +a[2] - 1, +a[3], +a[4], +a[5], +a[6]));
|
||||
}
|
||||
}
|
||||
return value;
|
||||
}
|
||||
36
UTILS/Exchange/exchange_graph.wsf
Normal file
36
UTILS/Exchange/exchange_graph.wsf
Normal file
@@ -0,0 +1,36 @@
|
||||
<![CDATA[
|
||||
/*
|
||||
$Id$
|
||||
|
||||
Calling: cscript ..\..\..\utils\exchange\exchange_graph.js
|
||||
Parameters:
|
||||
Context:
|
||||
Description: exchange_all.js genereert een batchfile met aanroepen naar dit bestand per ruimte_extern_id
|
||||
Note:
|
||||
*/
|
||||
]]>
|
||||
|
||||
<job id="exchange_webhooks">
|
||||
<script language="JScript" src="../wsf_shared.js"/>
|
||||
<script language="JScript" src="../json2.js"/>
|
||||
<script language="JScript" src="ms_graph.js"/>
|
||||
<script language="JScript" src="exchange_graph.js"/>
|
||||
|
||||
<script language="JScript">
|
||||
/* global */ var custabspath = fso.GetAbsolutePathName("../");
|
||||
var Oracle = Connect2Oracle('exchange_graph.js');
|
||||
|
||||
var config = loadconfig("test.config");
|
||||
var token = requestToken(config);
|
||||
|
||||
var zaalemail = WScript.Arguments(0);
|
||||
var import_app_key = WScript.Arguments(1); // Gebruik EXCHFULL voor alles in bepaalde periode
|
||||
|
||||
var res = csv_for_room(zaalemail, import_app_key);
|
||||
if (res)
|
||||
WScript.Quit(10); // alles goed
|
||||
else
|
||||
WScript.Quit(1); // Fout
|
||||
|
||||
</script>
|
||||
</job>
|
||||
31
UTILS/Exchange/list_webhooks.wsf
Normal file
31
UTILS/Exchange/list_webhooks.wsf
Normal file
@@ -0,0 +1,31 @@
|
||||
<![CDATA[
|
||||
/*
|
||||
$Id$
|
||||
|
||||
File: list_webhooks.wsf
|
||||
|
||||
Calling: cscript ..\..\..\utils\exchange\list_webhooks.wsf
|
||||
Parameters:
|
||||
Context: Test only vanuit cust/Exchange folder
|
||||
Description: Toon de lopende webhook subscriptions
|
||||
Note:
|
||||
*/
|
||||
]]>
|
||||
|
||||
<job id="exchange_webhooks">
|
||||
<script language="JScript" src="../wsf_shared.js"/>
|
||||
<script language="JScript" src="../json2.js"/>
|
||||
<script language="JScript" src="ms_graph.js"/>
|
||||
|
||||
<script language="JScript">
|
||||
|
||||
var config = loadconfig("exchange.config");
|
||||
var token = requestToken(config);
|
||||
|
||||
var xhr = doHTTP("GET", "https://graph.microsoft.com/v1.0/subscriptions",
|
||||
null,
|
||||
{ "Accept": "application/json", "Authorization": "Bearer " + token });
|
||||
WScript.Echo(JSON.stringify(JSON.parse(xhr.responseText), null, 2));
|
||||
|
||||
</script>
|
||||
</job>
|
||||
141
UTILS/Exchange/ms_graph.js
Normal file
141
UTILS/Exchange/ms_graph.js
Normal file
@@ -0,0 +1,141 @@
|
||||
/*
|
||||
$Revision$
|
||||
$Id$
|
||||
|
||||
File: ms_Graph.js
|
||||
|
||||
Description: MS Graph koppeling hulpfuncties
|
||||
*/
|
||||
|
||||
// V todo-1: graph-user-id bepalen obv zaalemail.
|
||||
// V todo-2: XML vervangen door REST aanroep MS-graph
|
||||
// V todo-3: nog niet opgehaalde items bepalen van een user (=ruimte)
|
||||
// V todo-4: synchroniseren van items van een user van de komende 90 dagen
|
||||
// V todo-5: schrijven van een CSV bestand obv de xhr-response ipv CSV obv .xsl bestand
|
||||
|
||||
var fso = new ActiveXObject("Scripting.FileSystemObject");
|
||||
|
||||
function loadconfig(configpath)
|
||||
{
|
||||
var f = fso.OpenTextFile(configpath, 1); // ForReading
|
||||
var config = eval("(" + f.ReadAll() + ")");
|
||||
config.loglevel = config.loglevel || 0;
|
||||
f.Close();
|
||||
return config;
|
||||
}
|
||||
|
||||
// get bearer token based on client_secret, client_id, tenant
|
||||
function requestToken(config)
|
||||
{
|
||||
var token = null;
|
||||
var parms = 'grant_type=client_credentials'
|
||||
+ '&client_secret=' + config.client_secret
|
||||
+ '&scope=https://graph.microsoft.com/.default'
|
||||
+ '&client_id=' + config.client_id;
|
||||
var xhr = doHTTP("POST", "https://login.microsoftonline.com/" + config.tenant + "/oauth2/v2.0/token", parms, { "Content-Type": "application/x-www-form-urlencoded" });
|
||||
if (xhr != null) {
|
||||
var token = JSON.parse(xhr.responseText).access_token;
|
||||
}
|
||||
return token;
|
||||
}
|
||||
|
||||
// get de MS-graph user by e-mailaddress
|
||||
function getGraphUser(email)
|
||||
{
|
||||
var user = null;
|
||||
var xhr = doHTTP("GET", "https://graph.microsoft.com/v1.0/users", null, { "Accept": "application/json", "Authorization": "Bearer " + token });
|
||||
if (xhr != null)
|
||||
{
|
||||
var users = JSON.parse(xhr.responseText).value;
|
||||
var index;
|
||||
for (index = 0; index < users.length; index++)
|
||||
{
|
||||
if (users[index].mail && users[index].mail.toLowerCase() === email.toLowerCase())
|
||||
{
|
||||
user = users[index];
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
return user;
|
||||
}
|
||||
|
||||
if (!Date.prototype.toISOString) {
|
||||
Date.prototype.toISOString = function () {
|
||||
function pad(n) { return n < 10 ? '0' + n : n }
|
||||
return this.getUTCFullYear() + '-'
|
||||
+ pad(this.getUTCMonth() + 1) + '-'
|
||||
+ pad(this.getUTCDate()) + 'T'
|
||||
+ pad(this.getUTCHours()) + ':'
|
||||
+ pad(this.getUTCMinutes()) + ':'
|
||||
+ pad(this.getUTCSeconds()) + 'Z';
|
||||
};
|
||||
}
|
||||
|
||||
function doHTTP(method, url, body, headers) {
|
||||
//var SXH_PROXY_SET_PROXY = 2;
|
||||
var SXH_OPTION_IGNORE_SERVER_SSL_CERT_ERROR_FLAGS = 2;
|
||||
var SXH_SERVER_CERT_IGNORE_ALL_SERVER_ERRORS = 0x3300;
|
||||
|
||||
var objXMLHTTP = new ActiveXObject("MSXML2.ServerXMLHTTP.6.0");
|
||||
// objXMLHTTP.setProxy(SXH_PROXY_SET_PROXY, "127.0.0.1:8888");
|
||||
|
||||
objXMLHTTP.open(method, url, false);
|
||||
if (headers) {
|
||||
var header;
|
||||
for (header in headers) {
|
||||
objXMLHTTP.setRequestHeader(header, headers[header]);
|
||||
}
|
||||
}
|
||||
|
||||
objXMLHTTP.setOption(SXH_OPTION_IGNORE_SERVER_SSL_CERT_ERROR_FLAGS, SXH_SERVER_CERT_IGNORE_ALL_SERVER_ERRORS);
|
||||
|
||||
if (config.loglevel > 0)
|
||||
__Log2File("request.xml", body);
|
||||
objXMLHTTP.send(body);
|
||||
|
||||
if (objXMLHTTP.status >= 200 && objXMLHTTP.status <= 299) {
|
||||
return objXMLHTTP;
|
||||
}
|
||||
// else: er is iets fout
|
||||
__Log2File("response.xml", objXMLHTTP.responseText);
|
||||
__Log(objXMLHTTP.status);
|
||||
__Log(objXMLHTTP.statusText);
|
||||
__Log(objXMLHTTP.responseText);
|
||||
return null;
|
||||
}
|
||||
|
||||
function safefilename(naam) // geen 'lage' karakters en geen (back)slashes, *,%,<,>, '"', ':', ';' '?' and '|' of '+'
|
||||
{
|
||||
return naam.replace(/[\x00-\x1F|\/|\\|\*|\%\<\>\"\:\;\?\|\+]+/g, "_"); // " syntax highlight correctie
|
||||
}
|
||||
|
||||
function __Log2File(log_file, data) {
|
||||
var utf8Stream = new ActiveXObject("ADODB.Stream");
|
||||
utf8Stream.Open();
|
||||
utf8Stream.Type = 2;
|
||||
utf8Stream.CharSet = "utf-8";
|
||||
utf8Stream.WriteText(data);
|
||||
utf8Stream.SaveToFile(config.xmlfolder + safefilename(log_file), 2);
|
||||
utf8Stream.Close();
|
||||
}
|
||||
|
||||
// From MyJSON in shared.inc
|
||||
// Maar subtiel anders: msgraph stuurt de Z niet achteraan
|
||||
function internal_parsedate(key, value) {
|
||||
var a;
|
||||
if (typeof value === 'string') {
|
||||
a = /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2}(?:\.\d*)?)$/.exec(value);
|
||||
if (a) {
|
||||
return new Date(Date.UTC(+a[1], +a[2] - 1, +a[3], +a[4], +a[5], +a[6]));
|
||||
}
|
||||
}
|
||||
return value;
|
||||
}
|
||||
function inArray(needle, haystack) {
|
||||
var length = haystack.length;
|
||||
for(var i = 0; i < length; i++) {
|
||||
if(haystack[i] == needle) return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
112
UTILS/Exchange/process_webhook.wsc
Normal file
112
UTILS/Exchange/process_webhook.wsc
Normal file
@@ -0,0 +1,112 @@
|
||||
<?xml version="1.0" encoding="windows-1252"?>
|
||||
<![CDATA[
|
||||
/*
|
||||
$Id$
|
||||
|
||||
File: process_webhook.wsc
|
||||
Context: Vanuit APPL\API\api_msgraphnotification.asp
|
||||
Note: Verwerk <20><>n notificatie
|
||||
|
||||
*/
|
||||
]]>
|
||||
<component>
|
||||
<?component error="true" debug="true"?>
|
||||
<registration
|
||||
description="process_webhook"
|
||||
progid="process_webhook.wsc"
|
||||
version="1.00"
|
||||
classid="{6D817B6F-9D08-4636-AAD9-8BD7C5EFF56A}"
|
||||
>
|
||||
</registration>
|
||||
|
||||
<public>
|
||||
|
||||
<!-- properties -->
|
||||
|
||||
<!-- methods -->
|
||||
<method name="initialize">
|
||||
<PARAMETER name="params"/>
|
||||
</method>
|
||||
<method name="process_webhook">
|
||||
<PARAMETER name="res_ruimte_key"/>
|
||||
<PARAMETER name="zaalemail"/>
|
||||
<PARAMETER name="notidata"/>
|
||||
</method>
|
||||
</public>
|
||||
|
||||
<script language="JScript" src="../wsf_shared.js"/>
|
||||
<script language="JScript" src="../json2.js"/>
|
||||
<script language="JScript" src="ms_graph.js"/>
|
||||
<script language="JScript" src="exchange_graph.js"/>
|
||||
<script language="JScript" src="../../appl/imp/imp_shared.js"/>
|
||||
|
||||
<script language="javascript">
|
||||
<![CDATA[
|
||||
|
||||
/* properties */
|
||||
|
||||
|
||||
/* methods */
|
||||
/*
|
||||
|
||||
/* Globals */
|
||||
var DEZE; // context voor alle globale functies vanuit ASP
|
||||
var Oracle;
|
||||
var custabspath;
|
||||
|
||||
var config;
|
||||
var token;
|
||||
function initialize(params)
|
||||
{
|
||||
DEZE = params.DEZE;
|
||||
custabspath = params.custabspath;
|
||||
Oracle = DEZE.Oracle;
|
||||
}
|
||||
|
||||
// notidata zoals de webhook hem van Graph binnenkreeg
|
||||
function process_webhook(res_ruimte_key, zaalemail, notidata)
|
||||
{
|
||||
__Log = DEZE.__Log; // overrule degene uit wsf_shared.js
|
||||
__DoLog = DEZE.__DoLog;
|
||||
__Log("Now in process_webhook.wsc for " + zaalemail);
|
||||
//__Log(notidata);
|
||||
|
||||
/*global*/ config = loadconfig(custabspath + "\\Exchange\\exchange.config");
|
||||
/*global*/ token = requestToken(config);
|
||||
|
||||
var import_app = "EXCHSYNC";
|
||||
var sql = "SELECT i.fac_import_app_key "
|
||||
+ " FROM fac_import_app i"
|
||||
+ " WHERE i.fac_import_app_code = " + DEZE.safe.quoted_sql(import_app)
|
||||
+ " AND fac_import_app_prefix IS NULL";
|
||||
var oRs = Oracle.Execute(sql);
|
||||
if (oRs.EOF)
|
||||
{
|
||||
__DoLog("FATAL: Import EXCHSYNC not found");
|
||||
return false;
|
||||
}
|
||||
var import_app_key = oRs("fac_import_app_key").Value;
|
||||
oRs.Close();
|
||||
|
||||
var fileStream = csv_for_room(zaalemail, import_app, true); // as Stream
|
||||
if (!fileStream)
|
||||
{
|
||||
__DoLog("CSV creating failed?");
|
||||
return false;
|
||||
}
|
||||
|
||||
var res = impReadStream(fileStream,
|
||||
import_app_key,
|
||||
{ fac_home: custabspath + "../../",
|
||||
filepathname: "EXCHANGE " + zaalemail,
|
||||
customerId: DEZE.customerId,
|
||||
ref_key: res_ruimte_key,
|
||||
keep_old: 300, // Parallelle import 300 seconden ondersteunen (nodig voor deze import?)
|
||||
user_key: DEZE.user_key,
|
||||
keep_backup: false // mits fac_import_app_folder gezet
|
||||
});
|
||||
return true;
|
||||
}
|
||||
]]>
|
||||
</script>
|
||||
</component>
|
||||
506
UTILS/json2.js
Normal file
506
UTILS/json2.js
Normal file
@@ -0,0 +1,506 @@
|
||||
// json2.js
|
||||
// 2016-05-01
|
||||
// Public Domain.
|
||||
// NO WARRANTY EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK.
|
||||
// See http://www.JSON.org/js.html
|
||||
// This code should be minified before deployment.
|
||||
// See http://javascript.crockford.com/jsmin.html
|
||||
|
||||
// USE YOUR OWN COPY. IT IS EXTREMELY UNWISE TO LOAD CODE FROM SERVERS YOU DO
|
||||
// NOT CONTROL.
|
||||
|
||||
// This file creates a global JSON object containing two methods: stringify
|
||||
// and parse. This file is provides the ES5 JSON capability to ES3 systems.
|
||||
// If a project might run on IE8 or earlier, then this file should be included.
|
||||
// This file does nothing on ES5 systems.
|
||||
|
||||
// JSON.stringify(value, replacer, space)
|
||||
// value any JavaScript value, usually an object or array.
|
||||
// replacer an optional parameter that determines how object
|
||||
// values are stringified for objects. It can be a
|
||||
// function or an array of strings.
|
||||
// space an optional parameter that specifies the indentation
|
||||
// of nested structures. If it is omitted, the text will
|
||||
// be packed without extra whitespace. If it is a number,
|
||||
// it will specify the number of spaces to indent at each
|
||||
// level. If it is a string (such as "\t" or " "),
|
||||
// it contains the characters used to indent at each level.
|
||||
// This method produces a JSON text from a JavaScript value.
|
||||
// When an object value is found, if the object contains a toJSON
|
||||
// method, its toJSON method will be called and the result will be
|
||||
// stringified. A toJSON method does not serialize: it returns the
|
||||
// value represented by the name/value pair that should be serialized,
|
||||
// or undefined if nothing should be serialized. The toJSON method
|
||||
// will be passed the key associated with the value, and this will be
|
||||
// bound to the value.
|
||||
|
||||
// For example, this would serialize Dates as ISO strings.
|
||||
|
||||
// Date.prototype.toJSON = function (key) {
|
||||
// function f(n) {
|
||||
// // Format integers to have at least two digits.
|
||||
// return (n < 10)
|
||||
// ? "0" + n
|
||||
// : n;
|
||||
// }
|
||||
// return this.getUTCFullYear() + "-" +
|
||||
// f(this.getUTCMonth() + 1) + "-" +
|
||||
// f(this.getUTCDate()) + "T" +
|
||||
// f(this.getUTCHours()) + ":" +
|
||||
// f(this.getUTCMinutes()) + ":" +
|
||||
// f(this.getUTCSeconds()) + "Z";
|
||||
// };
|
||||
|
||||
// You can provide an optional replacer method. It will be passed the
|
||||
// key and value of each member, with this bound to the containing
|
||||
// object. The value that is returned from your method will be
|
||||
// serialized. If your method returns undefined, then the member will
|
||||
// be excluded from the serialization.
|
||||
|
||||
// If the replacer parameter is an array of strings, then it will be
|
||||
// used to select the members to be serialized. It filters the results
|
||||
// such that only members with keys listed in the replacer array are
|
||||
// stringified.
|
||||
|
||||
// Values that do not have JSON representations, such as undefined or
|
||||
// functions, will not be serialized. Such values in objects will be
|
||||
// dropped; in arrays they will be replaced with null. You can use
|
||||
// a replacer function to replace those with JSON values.
|
||||
|
||||
// JSON.stringify(undefined) returns undefined.
|
||||
|
||||
// The optional space parameter produces a stringification of the
|
||||
// value that is filled with line breaks and indentation to make it
|
||||
// easier to read.
|
||||
|
||||
// If the space parameter is a non-empty string, then that string will
|
||||
// be used for indentation. If the space parameter is a number, then
|
||||
// the indentation will be that many spaces.
|
||||
|
||||
// Example:
|
||||
|
||||
// text = JSON.stringify(["e", {pluribus: "unum"}]);
|
||||
// // text is '["e",{"pluribus":"unum"}]'
|
||||
|
||||
// text = JSON.stringify(["e", {pluribus: "unum"}], null, "\t");
|
||||
// // text is '[\n\t"e",\n\t{\n\t\t"pluribus": "unum"\n\t}\n]'
|
||||
|
||||
// text = JSON.stringify([new Date()], function (key, value) {
|
||||
// return this[key] instanceof Date
|
||||
// ? "Date(" + this[key] + ")"
|
||||
// : value;
|
||||
// });
|
||||
// // text is '["Date(---current time---)"]'
|
||||
|
||||
// JSON.parse(text, reviver)
|
||||
// This method parses a JSON text to produce an object or array.
|
||||
// It can throw a SyntaxError exception.
|
||||
|
||||
// The optional reviver parameter is a function that can filter and
|
||||
// transform the results. It receives each of the keys and values,
|
||||
// and its return value is used instead of the original value.
|
||||
// If it returns what it received, then the structure is not modified.
|
||||
// If it returns undefined then the member is deleted.
|
||||
|
||||
// Example:
|
||||
|
||||
// // Parse the text. Values that look like ISO date strings will
|
||||
// // be converted to Date objects.
|
||||
|
||||
// myData = JSON.parse(text, function (key, value) {
|
||||
// var a;
|
||||
// if (typeof value === "string") {
|
||||
// a =
|
||||
// /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2}(?:\.\d*)?)Z$/.exec(value);
|
||||
// if (a) {
|
||||
// return new Date(Date.UTC(+a[1], +a[2] - 1, +a[3], +a[4],
|
||||
// +a[5], +a[6]));
|
||||
// }
|
||||
// }
|
||||
// return value;
|
||||
// });
|
||||
|
||||
// myData = JSON.parse('["Date(09/09/2001)"]', function (key, value) {
|
||||
// var d;
|
||||
// if (typeof value === "string" &&
|
||||
// value.slice(0, 5) === "Date(" &&
|
||||
// value.slice(-1) === ")") {
|
||||
// d = new Date(value.slice(5, -1));
|
||||
// if (d) {
|
||||
// return d;
|
||||
// }
|
||||
// }
|
||||
// return value;
|
||||
// });
|
||||
|
||||
// This is a reference implementation. You are free to copy, modify, or
|
||||
// redistribute.
|
||||
|
||||
/*jslint
|
||||
eval, for, this
|
||||
*/
|
||||
|
||||
/*property
|
||||
JSON, apply, call, charCodeAt, getUTCDate, getUTCFullYear, getUTCHours,
|
||||
getUTCMinutes, getUTCMonth, getUTCSeconds, hasOwnProperty, join,
|
||||
lastIndex, length, parse, prototype, push, replace, slice, stringify,
|
||||
test, toJSON, toString, valueOf
|
||||
*/
|
||||
|
||||
|
||||
// Create a JSON object only if one does not already exist. We create the
|
||||
// methods in a closure to avoid creating global variables.
|
||||
|
||||
if (typeof JSON !== "object") {
|
||||
JSON = {};
|
||||
}
|
||||
|
||||
(function () {
|
||||
"use strict";
|
||||
|
||||
var rx_one = /^[\],:{}\s]*$/;
|
||||
var rx_two = /\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g;
|
||||
var rx_three = /"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g;
|
||||
var rx_four = /(?:^|:|,)(?:\s*\[)+/g;
|
||||
var rx_escapable = /[\\\"\u0000-\u001f\u007f-\u009f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g;
|
||||
var rx_dangerous = /[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g;
|
||||
|
||||
function f(n) {
|
||||
// Format integers to have at least two digits.
|
||||
return n < 10
|
||||
? "0" + n
|
||||
: n;
|
||||
}
|
||||
|
||||
function this_value() {
|
||||
return this.valueOf();
|
||||
}
|
||||
|
||||
if (typeof Date.prototype.toJSON !== "function") {
|
||||
|
||||
Date.prototype.toJSON = function () {
|
||||
|
||||
return isFinite(this.valueOf())
|
||||
? this.getUTCFullYear() + "-" +
|
||||
f(this.getUTCMonth() + 1) + "-" +
|
||||
f(this.getUTCDate()) + "T" +
|
||||
f(this.getUTCHours()) + ":" +
|
||||
f(this.getUTCMinutes()) + ":" +
|
||||
f(this.getUTCSeconds()) + "Z"
|
||||
: null;
|
||||
};
|
||||
|
||||
Boolean.prototype.toJSON = this_value;
|
||||
Number.prototype.toJSON = this_value;
|
||||
String.prototype.toJSON = this_value;
|
||||
}
|
||||
|
||||
var gap;
|
||||
var indent;
|
||||
var meta;
|
||||
var rep;
|
||||
|
||||
|
||||
function quote(string) {
|
||||
|
||||
// If the string contains no control characters, no quote characters, and no
|
||||
// backslash characters, then we can safely slap some quotes around it.
|
||||
// Otherwise we must also replace the offending characters with safe escape
|
||||
// sequences.
|
||||
|
||||
rx_escapable.lastIndex = 0;
|
||||
return rx_escapable.test(string)
|
||||
? "\"" + string.replace(rx_escapable, function (a) {
|
||||
var c = meta[a];
|
||||
return typeof c === "string"
|
||||
? c
|
||||
: "\\u" + ("0000" + a.charCodeAt(0).toString(16)).slice(-4);
|
||||
}) + "\""
|
||||
: "\"" + string + "\"";
|
||||
}
|
||||
|
||||
|
||||
function str(key, holder) {
|
||||
|
||||
// Produce a string from holder[key].
|
||||
|
||||
var i; // The loop counter.
|
||||
var k; // The member key.
|
||||
var v; // The member value.
|
||||
var length;
|
||||
var mind = gap;
|
||||
var partial;
|
||||
var value = holder[key];
|
||||
|
||||
// If the value has a toJSON method, call it to obtain a replacement value.
|
||||
|
||||
if (value && typeof value === "object" &&
|
||||
typeof value.toJSON === "function") {
|
||||
value = value.toJSON(key);
|
||||
}
|
||||
|
||||
// If we were called with a replacer function, then call the replacer to
|
||||
// obtain a replacement value.
|
||||
|
||||
if (typeof rep === "function") {
|
||||
value = rep.call(holder, key, value);
|
||||
}
|
||||
|
||||
// What happens next depends on the value's type.
|
||||
|
||||
switch (typeof value) {
|
||||
case "string":
|
||||
return quote(value);
|
||||
|
||||
case "number":
|
||||
|
||||
// JSON numbers must be finite. Encode non-finite numbers as null.
|
||||
|
||||
return isFinite(value)
|
||||
? String(value)
|
||||
: "null";
|
||||
|
||||
case "boolean":
|
||||
case "null":
|
||||
|
||||
// If the value is a boolean or null, convert it to a string. Note:
|
||||
// typeof null does not produce "null". The case is included here in
|
||||
// the remote chance that this gets fixed someday.
|
||||
|
||||
return String(value);
|
||||
|
||||
// If the type is "object", we might be dealing with an object or an array or
|
||||
// null.
|
||||
|
||||
case "object":
|
||||
|
||||
// Due to a specification blunder in ECMAScript, typeof null is "object",
|
||||
// so watch out for that case.
|
||||
|
||||
if (!value) {
|
||||
return "null";
|
||||
}
|
||||
|
||||
// Make an array to hold the partial results of stringifying this object value.
|
||||
|
||||
gap += indent;
|
||||
partial = [];
|
||||
|
||||
// Is the value an array?
|
||||
|
||||
if (Object.prototype.toString.apply(value) === "[object Array]") {
|
||||
|
||||
// The value is an array. Stringify every element. Use null as a placeholder
|
||||
// for non-JSON values.
|
||||
|
||||
length = value.length;
|
||||
for (i = 0; i < length; i += 1) {
|
||||
partial[i] = str(i, value) || "null";
|
||||
}
|
||||
|
||||
// Join all of the elements together, separated with commas, and wrap them in
|
||||
// brackets.
|
||||
|
||||
v = partial.length === 0
|
||||
? "[]"
|
||||
: gap
|
||||
? "[\n" + gap + partial.join(",\n" + gap) + "\n" + mind + "]"
|
||||
: "[" + partial.join(",") + "]";
|
||||
gap = mind;
|
||||
return v;
|
||||
}
|
||||
|
||||
// If the replacer is an array, use it to select the members to be stringified.
|
||||
|
||||
if (rep && typeof rep === "object") {
|
||||
length = rep.length;
|
||||
for (i = 0; i < length; i += 1) {
|
||||
if (typeof rep[i] === "string") {
|
||||
k = rep[i];
|
||||
v = str(k, value);
|
||||
if (v) {
|
||||
partial.push(quote(k) + (
|
||||
gap
|
||||
? ": "
|
||||
: ":"
|
||||
) + v);
|
||||
}
|
||||
}
|
||||
}
|
||||
} else {
|
||||
|
||||
// Otherwise, iterate through all of the keys in the object.
|
||||
|
||||
for (k in value) {
|
||||
if (Object.prototype.hasOwnProperty.call(value, k)) {
|
||||
v = str(k, value);
|
||||
if (v) {
|
||||
partial.push(quote(k) + (
|
||||
gap
|
||||
? ": "
|
||||
: ":"
|
||||
) + v);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Join all of the member texts together, separated with commas,
|
||||
// and wrap them in braces.
|
||||
|
||||
v = partial.length === 0
|
||||
? "{}"
|
||||
: gap
|
||||
? "{\n" + gap + partial.join(",\n" + gap) + "\n" + mind + "}"
|
||||
: "{" + partial.join(",") + "}";
|
||||
gap = mind;
|
||||
return v;
|
||||
}
|
||||
}
|
||||
|
||||
// If the JSON object does not yet have a stringify method, give it one.
|
||||
|
||||
if (typeof JSON.stringify !== "function") {
|
||||
meta = { // table of character substitutions
|
||||
"\b": "\\b",
|
||||
"\t": "\\t",
|
||||
"\n": "\\n",
|
||||
"\f": "\\f",
|
||||
"\r": "\\r",
|
||||
"\"": "\\\"",
|
||||
"\\": "\\\\"
|
||||
};
|
||||
JSON.stringify = function (value, replacer, space) {
|
||||
|
||||
// The stringify method takes a value and an optional replacer, and an optional
|
||||
// space parameter, and returns a JSON text. The replacer can be a function
|
||||
// that can replace values, or an array of strings that will select the keys.
|
||||
// A default replacer method can be provided. Use of the space parameter can
|
||||
// produce text that is more easily readable.
|
||||
|
||||
var i;
|
||||
gap = "";
|
||||
indent = "";
|
||||
|
||||
// If the space parameter is a number, make an indent string containing that
|
||||
// many spaces.
|
||||
|
||||
if (typeof space === "number") {
|
||||
for (i = 0; i < space; i += 1) {
|
||||
indent += " ";
|
||||
}
|
||||
|
||||
// If the space parameter is a string, it will be used as the indent string.
|
||||
|
||||
} else if (typeof space === "string") {
|
||||
indent = space;
|
||||
}
|
||||
|
||||
// If there is a replacer, it must be a function or an array.
|
||||
// Otherwise, throw an error.
|
||||
|
||||
rep = replacer;
|
||||
if (replacer && typeof replacer !== "function" &&
|
||||
(typeof replacer !== "object" ||
|
||||
typeof replacer.length !== "number")) {
|
||||
throw new Error("JSON.stringify");
|
||||
}
|
||||
|
||||
// Make a fake root object containing our value under the key of "".
|
||||
// Return the result of stringifying the value.
|
||||
|
||||
return str("", {"": value});
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
// If the JSON object does not yet have a parse method, give it one.
|
||||
|
||||
if (typeof JSON.parse !== "function") {
|
||||
JSON.parse = function (text, reviver) {
|
||||
|
||||
// The parse method takes a text and an optional reviver function, and returns
|
||||
// a JavaScript value if the text is a valid JSON text.
|
||||
|
||||
var j;
|
||||
|
||||
function walk(holder, key) {
|
||||
|
||||
// The walk method is used to recursively walk the resulting structure so
|
||||
// that modifications can be made.
|
||||
|
||||
var k;
|
||||
var v;
|
||||
var value = holder[key];
|
||||
if (value && typeof value === "object") {
|
||||
for (k in value) {
|
||||
if (Object.prototype.hasOwnProperty.call(value, k)) {
|
||||
v = walk(value, k);
|
||||
if (v !== undefined) {
|
||||
value[k] = v;
|
||||
} else {
|
||||
delete value[k];
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return reviver.call(holder, key, value);
|
||||
}
|
||||
|
||||
|
||||
// Parsing happens in four stages. In the first stage, we replace certain
|
||||
// Unicode characters with escape sequences. JavaScript handles many characters
|
||||
// incorrectly, either silently deleting them, or treating them as line endings.
|
||||
|
||||
text = String(text);
|
||||
rx_dangerous.lastIndex = 0;
|
||||
if (rx_dangerous.test(text)) {
|
||||
text = text.replace(rx_dangerous, function (a) {
|
||||
return "\\u" +
|
||||
("0000" + a.charCodeAt(0).toString(16)).slice(-4);
|
||||
});
|
||||
}
|
||||
|
||||
// In the second stage, we run the text against regular expressions that look
|
||||
// for non-JSON patterns. We are especially concerned with "()" and "new"
|
||||
// because they can cause invocation, and "=" because it can cause mutation.
|
||||
// But just to be safe, we want to reject all unexpected forms.
|
||||
|
||||
// We split the second stage into 4 regexp operations in order to work around
|
||||
// crippling inefficiencies in IE's and Safari's regexp engines. First we
|
||||
// replace the JSON backslash pairs with "@" (a non-JSON character). Second, we
|
||||
// replace all simple value tokens with "]" characters. Third, we delete all
|
||||
// open brackets that follow a colon or comma or that begin the text. Finally,
|
||||
// we look to see that the remaining characters are only whitespace or "]" or
|
||||
// "," or ":" or "{" or "}". If that is so, then the text is safe for eval.
|
||||
|
||||
if (
|
||||
rx_one.test(
|
||||
text
|
||||
.replace(rx_two, "@")
|
||||
.replace(rx_three, "]")
|
||||
.replace(rx_four, "")
|
||||
)
|
||||
) {
|
||||
|
||||
// In the third stage we use the eval function to compile the text into a
|
||||
// JavaScript structure. The "{" operator is subject to a syntactic ambiguity
|
||||
// in JavaScript: it can begin a block or an object literal. We wrap the text
|
||||
// in parens to eliminate the ambiguity.
|
||||
|
||||
j = eval("(" + text + ")");
|
||||
|
||||
// In the optional fourth stage, we recursively walk the new structure, passing
|
||||
// each name/value pair to a reviver function for possible transformation.
|
||||
|
||||
return (typeof reviver === "function")
|
||||
? walk({"": j}, "")
|
||||
: j;
|
||||
}
|
||||
|
||||
// If the text is not JSON parseable, then a SyntaxError is thrown.
|
||||
|
||||
throw new SyntaxError("JSON.parse");
|
||||
};
|
||||
}
|
||||
}());
|
||||
Reference in New Issue
Block a user