2013-03-17 15:28:49 +00:00
|
|
|
/*\
|
|
|
|
title: $:/core/modules/utils/dom/http.js
|
|
|
|
type: application/javascript
|
|
|
|
module-type: utils
|
|
|
|
|
2023-06-13 09:35:55 +00:00
|
|
|
HTTP support
|
2013-03-17 15:28:49 +00:00
|
|
|
|
|
|
|
\*/
|
|
|
|
(function(){
|
|
|
|
|
|
|
|
/*jslint node: true, browser: true */
|
|
|
|
/*global $tw: false */
|
|
|
|
"use strict";
|
|
|
|
|
|
|
|
/*
|
2023-06-13 09:35:55 +00:00
|
|
|
Manage tm-http-request events. Options include:
|
|
|
|
wiki: Reference to the wiki to be used for state tiddler tracking
|
|
|
|
stateTrackerTitle: Title of tiddler to be used for state tiddler tracking
|
|
|
|
*/
|
|
|
|
function HttpClient(options) {
|
|
|
|
options = options || {};
|
|
|
|
this.nextId = 1;
|
|
|
|
this.wiki = options.wiki || $tw.wiki;
|
|
|
|
this.stateTrackerTitle = options.stateTrackerTitle || "$:/state/http-requests";
|
|
|
|
this.requests = []; // Array of {id: string,request: HttpClientRequest}
|
|
|
|
this.updateRequestTracker();
|
|
|
|
}
|
|
|
|
|
|
|
|
/*
|
|
|
|
Return the index into this.requests[] corresponding to a given ID. Returns null if not found
|
|
|
|
*/
|
|
|
|
HttpClient.prototype.getRequestIndex = function(targetId) {
|
|
|
|
var targetIndex = null;
|
|
|
|
$tw.utils.each(this.requests,function(requestInfo,index) {
|
|
|
|
if(requestInfo.id === targetId) {
|
|
|
|
targetIndex = index;
|
|
|
|
}
|
|
|
|
});
|
|
|
|
return targetIndex;
|
|
|
|
};
|
|
|
|
|
|
|
|
/*
|
|
|
|
Update the state tiddler that is tracking the outstanding requests
|
|
|
|
*/
|
|
|
|
HttpClient.prototype.updateRequestTracker = function() {
|
|
|
|
this.wiki.addTiddler({title: this.stateTrackerTitle, text: "" + this.requests.length});
|
|
|
|
};
|
|
|
|
|
|
|
|
HttpClient.prototype.initiateHttpRequest = function(options) {
|
|
|
|
var self = this,
|
|
|
|
id = this.nextId,
|
|
|
|
request = new HttpClientRequest(options);
|
|
|
|
this.nextId += 1;
|
|
|
|
this.requests.push({id: id, request: request});
|
|
|
|
this.updateRequestTracker();
|
|
|
|
request.send(function(err) {
|
|
|
|
var targetIndex = self.getRequestIndex(id);
|
|
|
|
if(targetIndex !== null) {
|
|
|
|
self.requests.splice(targetIndex,1);
|
|
|
|
self.updateRequestTracker();
|
|
|
|
}
|
|
|
|
});
|
|
|
|
return id;
|
|
|
|
};
|
|
|
|
|
|
|
|
HttpClient.prototype.cancelAllHttpRequests = function() {
|
|
|
|
var self = this;
|
|
|
|
if(this.requests.length > 0) {
|
|
|
|
for(var t=this.requests.length - 1; t--; t>=0) {
|
|
|
|
var requestInfo = this.requests[t];
|
|
|
|
requestInfo.request.cancel();
|
|
|
|
}
|
|
|
|
}
|
|
|
|
this.requests = [];
|
|
|
|
this.updateRequestTracker();
|
|
|
|
};
|
|
|
|
|
|
|
|
HttpClient.prototype.cancelHttpRequest = function(targetId) {
|
|
|
|
var targetIndex = this.getRequestIndex(targetId);
|
|
|
|
if(targetIndex !== null) {
|
|
|
|
this.requests[targetIndex].request.cancel();
|
|
|
|
this.requests.splice(targetIndex,1);
|
|
|
|
this.updateRequestTracker();
|
|
|
|
}
|
|
|
|
};
|
|
|
|
|
|
|
|
/*
|
|
|
|
Initiate an HTTP request. Options:
|
|
|
|
wiki: wiki to be used for executing action strings
|
|
|
|
url: URL for request
|
|
|
|
method: method eg GET, POST
|
|
|
|
body: text of request body
|
2023-07-17 11:15:20 +00:00
|
|
|
binary: set to "yes" to force binary processing of response payload
|
2023-06-13 09:35:55 +00:00
|
|
|
oncompletion: action string to be invoked on completion
|
|
|
|
onprogress: action string to be invoked on progress updates
|
|
|
|
bindStatus: optional title of tiddler to which status ("pending", "complete", "error") should be written
|
|
|
|
bindProgress: optional title of tiddler to which the progress of the request (0 to 100) should be bound
|
|
|
|
variables: hashmap of variable name to string value passed to action strings
|
|
|
|
headers: hashmap of header name to header value to be sent with the request
|
|
|
|
passwordHeaders: hashmap of header name to password store name to be sent with the request
|
|
|
|
queryStrings: hashmap of query string parameter name to parameter value to be sent with the request
|
|
|
|
passwordQueryStrings: hashmap of query string parameter name to password store name to be sent with the request
|
|
|
|
*/
|
|
|
|
function HttpClientRequest(options) {
|
|
|
|
var self = this;
|
|
|
|
console.log("Initiating an HTTP request",options)
|
|
|
|
this.wiki = options.wiki;
|
|
|
|
this.completionActions = options.oncompletion;
|
|
|
|
this.progressActions = options.onprogress;
|
2023-07-09 15:50:48 +00:00
|
|
|
this.bindStatus = options["bindStatus"];
|
|
|
|
this.bindProgress = options["bindProgress"];
|
2023-06-13 09:35:55 +00:00
|
|
|
this.method = options.method || "GET";
|
|
|
|
this.body = options.body || "";
|
2023-07-17 11:15:20 +00:00
|
|
|
this.binary = options.binary || "";
|
2023-06-13 09:35:55 +00:00
|
|
|
this.variables = options.variables;
|
|
|
|
var url = options.url;
|
|
|
|
$tw.utils.each(options.queryStrings,function(value,name) {
|
|
|
|
url = $tw.utils.setQueryStringParameter(url,name,value);
|
|
|
|
});
|
|
|
|
$tw.utils.each(options.passwordQueryStrings,function(value,name) {
|
|
|
|
url = $tw.utils.setQueryStringParameter(url,name,$tw.utils.getPassword(value) || "");
|
|
|
|
});
|
|
|
|
this.url = url;
|
|
|
|
this.requestHeaders = {};
|
|
|
|
$tw.utils.each(options.headers,function(value,name) {
|
|
|
|
self.requestHeaders[name] = value;
|
|
|
|
});
|
|
|
|
$tw.utils.each(options.passwordHeaders,function(value,name) {
|
|
|
|
self.requestHeaders[name] = $tw.utils.getPassword(value) || "";
|
|
|
|
});
|
|
|
|
}
|
|
|
|
|
|
|
|
HttpClientRequest.prototype.send = function(callback) {
|
|
|
|
var self = this,
|
|
|
|
setBinding = function(title,text) {
|
|
|
|
if(title) {
|
2023-07-09 15:50:48 +00:00
|
|
|
self.wiki.addTiddler(new $tw.Tiddler({title: title, text: text}));
|
2023-06-13 09:35:55 +00:00
|
|
|
}
|
|
|
|
};
|
|
|
|
if(this.url) {
|
|
|
|
setBinding(this.bindStatus,"pending");
|
|
|
|
setBinding(this.bindProgress,"0");
|
|
|
|
// Set the request tracker tiddler
|
|
|
|
var requestTrackerTitle = this.wiki.generateNewTitle("$:/temp/HttpRequest");
|
|
|
|
this.wiki.addTiddler({
|
|
|
|
title: requestTrackerTitle,
|
|
|
|
tags: "$:/tags/HttpRequest",
|
|
|
|
text: JSON.stringify({
|
|
|
|
url: this.url,
|
|
|
|
type: this.method,
|
|
|
|
status: "inprogress",
|
|
|
|
headers: this.requestHeaders,
|
|
|
|
data: this.body
|
|
|
|
})
|
|
|
|
});
|
|
|
|
this.xhr = $tw.utils.httpRequest({
|
|
|
|
url: this.url,
|
|
|
|
type: this.method,
|
|
|
|
headers: this.requestHeaders,
|
|
|
|
data: this.body,
|
2023-07-17 11:15:20 +00:00
|
|
|
returnProp: this.binary === "" ? "responseText" : "response",
|
|
|
|
responseType: this.binary === "" ? "text" : "arraybuffer",
|
2023-06-13 09:35:55 +00:00
|
|
|
callback: function(err,data,xhr) {
|
|
|
|
var hasSucceeded = xhr.status >= 200 && xhr.status < 300,
|
|
|
|
completionCode = hasSucceeded ? "complete" : "error",
|
|
|
|
headers = {};
|
|
|
|
$tw.utils.each(xhr.getAllResponseHeaders().split("\r\n"),function(line) {
|
|
|
|
var pos = line.indexOf(":");
|
|
|
|
if(pos !== -1) {
|
|
|
|
headers[line.substr(0,pos)] = line.substr(pos + 1).trim();
|
|
|
|
}
|
|
|
|
});
|
|
|
|
setBinding(self.bindStatus,completionCode);
|
|
|
|
setBinding(self.bindProgress,"100");
|
|
|
|
var resultVariables = {
|
|
|
|
status: xhr.status.toString(),
|
|
|
|
statusText: xhr.statusText,
|
|
|
|
error: (err || "").toString(),
|
|
|
|
data: (data || "").toString(),
|
|
|
|
headers: JSON.stringify(headers)
|
|
|
|
};
|
2023-07-17 11:15:20 +00:00
|
|
|
/* Convert data from binary to base64 */
|
|
|
|
if (xhr.responseType === "arraybuffer") {
|
|
|
|
var binary = "",
|
|
|
|
bytes = new Uint8Array(data),
|
|
|
|
len = bytes.byteLength;
|
|
|
|
for (var i=0; i<len; i++) {
|
|
|
|
binary += String.fromCharCode(bytes[i]);
|
|
|
|
}
|
|
|
|
resultVariables.data = window.btoa(binary);
|
|
|
|
}
|
2023-06-13 09:35:55 +00:00
|
|
|
self.wiki.addTiddler(new $tw.Tiddler(self.wiki.getTiddler(requestTrackerTitle),{
|
|
|
|
status: completionCode,
|
|
|
|
}));
|
|
|
|
self.wiki.invokeActionString(self.completionActions,undefined,$tw.utils.extend({},self.variables,resultVariables),{parentWidget: $tw.rootWidget});
|
|
|
|
callback(hasSucceeded ? null : xhr.statusText);
|
|
|
|
// console.log("Back!",err,data,xhr);
|
|
|
|
},
|
|
|
|
progress: function(lengthComputable,loaded,total) {
|
|
|
|
if(lengthComputable) {
|
|
|
|
setBinding(self.bindProgress,"" + Math.floor((loaded/total) * 100))
|
|
|
|
}
|
|
|
|
self.wiki.invokeActionString(self.progressActions,undefined,{
|
|
|
|
lengthComputable: lengthComputable ? "yes" : "no",
|
|
|
|
loaded: loaded,
|
|
|
|
total: total
|
|
|
|
},{parentWidget: $tw.rootWidget});
|
|
|
|
}
|
|
|
|
});
|
|
|
|
}
|
|
|
|
};
|
|
|
|
|
|
|
|
HttpClientRequest.prototype.cancel = function() {
|
|
|
|
if(this.xhr) {
|
|
|
|
this.xhr.abort();
|
|
|
|
}
|
|
|
|
};
|
|
|
|
|
|
|
|
exports.HttpClient = HttpClient;
|
|
|
|
|
|
|
|
/*
|
|
|
|
Make an HTTP request. Options are:
|
2013-03-17 15:28:49 +00:00
|
|
|
url: URL to retrieve
|
2018-08-23 12:13:49 +00:00
|
|
|
headers: hashmap of headers to send
|
2013-03-17 15:28:49 +00:00
|
|
|
type: GET, PUT, POST etc
|
2019-04-15 20:07:23 +00:00
|
|
|
callback: function invoked with (err,data,xhr)
|
2023-06-13 09:35:55 +00:00
|
|
|
progress: optional function invoked with (lengthComputable,loaded,total)
|
2017-03-17 13:41:17 +00:00
|
|
|
returnProp: string name of the property to return as first argument of callback
|
2023-07-17 11:15:20 +00:00
|
|
|
responseType: "text" or "arraybuffer"
|
2013-03-17 15:28:49 +00:00
|
|
|
*/
|
|
|
|
exports.httpRequest = function(options) {
|
|
|
|
var type = options.type || "GET",
|
2020-03-30 14:24:05 +00:00
|
|
|
url = options.url,
|
2013-03-17 15:28:49 +00:00
|
|
|
headers = options.headers || {accept: "application/json"},
|
2020-08-17 17:44:36 +00:00
|
|
|
hasHeader = function(targetHeader) {
|
|
|
|
targetHeader = targetHeader.toLowerCase();
|
|
|
|
var result = false;
|
|
|
|
$tw.utils.each(headers,function(header,headerTitle,object) {
|
|
|
|
if(headerTitle.toLowerCase() === targetHeader) {
|
|
|
|
result = true;
|
|
|
|
}
|
|
|
|
});
|
|
|
|
return result;
|
|
|
|
},
|
2021-08-17 08:56:52 +00:00
|
|
|
getHeader = function(targetHeader) {
|
|
|
|
return headers[targetHeader] || headers[targetHeader.toLowerCase()];
|
|
|
|
},
|
|
|
|
isSimpleRequest = function(type,headers) {
|
|
|
|
if(["GET","HEAD","POST"].indexOf(type) === -1) {
|
|
|
|
return false;
|
|
|
|
}
|
|
|
|
for(var header in headers) {
|
|
|
|
if(["accept","accept-language","content-language","content-type"].indexOf(header.toLowerCase()) === -1) {
|
|
|
|
return false;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
if(hasHeader("Content-Type") && ["application/x-www-form-urlencoded","multipart/form-data","text/plain"].indexOf(getHeader["Content-Type"]) === -1) {
|
|
|
|
return false;
|
|
|
|
}
|
|
|
|
return true;
|
|
|
|
},
|
2017-03-17 13:41:17 +00:00
|
|
|
returnProp = options.returnProp || "responseText",
|
2013-03-17 15:28:49 +00:00
|
|
|
request = new XMLHttpRequest(),
|
|
|
|
data = "",
|
|
|
|
f,results;
|
|
|
|
// Massage the data hashmap into a string
|
|
|
|
if(options.data) {
|
|
|
|
if(typeof options.data === "string") { // Already a string
|
|
|
|
data = options.data;
|
|
|
|
} else { // A hashmap of strings
|
|
|
|
results = [];
|
|
|
|
$tw.utils.each(options.data,function(dataItem,dataItemTitle) {
|
|
|
|
results.push(dataItemTitle + "=" + encodeURIComponent(dataItem));
|
|
|
|
});
|
2020-03-30 14:24:05 +00:00
|
|
|
if(type === "GET" || type === "HEAD") {
|
|
|
|
url += "?" + results.join("&");
|
|
|
|
} else {
|
|
|
|
data = results.join("&");
|
|
|
|
}
|
2013-03-17 15:28:49 +00:00
|
|
|
}
|
|
|
|
}
|
2023-07-17 11:15:20 +00:00
|
|
|
request.responseType = options.responseType || "text";
|
2013-03-17 15:28:49 +00:00
|
|
|
// Set up the state change handler
|
|
|
|
request.onreadystatechange = function() {
|
|
|
|
if(this.readyState === 4) {
|
2014-09-24 14:19:23 +00:00
|
|
|
if(this.status === 200 || this.status === 201 || this.status === 204) {
|
2013-03-17 15:28:49 +00:00
|
|
|
// Success!
|
2017-03-17 13:41:17 +00:00
|
|
|
options.callback(null,this[returnProp],this);
|
2013-03-17 15:28:49 +00:00
|
|
|
return;
|
|
|
|
}
|
|
|
|
// Something went wrong
|
2019-04-15 20:07:23 +00:00
|
|
|
options.callback($tw.language.getString("Error/XMLHttpRequest") + ": " + this.status,null,this);
|
2013-03-17 15:28:49 +00:00
|
|
|
}
|
|
|
|
};
|
2023-06-13 09:35:55 +00:00
|
|
|
// Handle progress
|
|
|
|
if(options.progress) {
|
|
|
|
request.onprogress = function(event) {
|
|
|
|
console.log("Progress event",event)
|
|
|
|
options.progress(event.lengthComputable,event.loaded,event.total);
|
|
|
|
};
|
|
|
|
}
|
2013-03-17 15:28:49 +00:00
|
|
|
// Make the request
|
2020-03-30 14:24:05 +00:00
|
|
|
request.open(type,url,true);
|
2023-06-13 09:35:55 +00:00
|
|
|
// Headers
|
2013-03-17 15:28:49 +00:00
|
|
|
if(headers) {
|
|
|
|
$tw.utils.each(headers,function(header,headerTitle,object) {
|
|
|
|
request.setRequestHeader(headerTitle,header);
|
|
|
|
});
|
|
|
|
}
|
2020-08-17 17:44:36 +00:00
|
|
|
if(data && !hasHeader("Content-Type")) {
|
|
|
|
request.setRequestHeader("Content-Type","application/x-www-form-urlencoded; charset=UTF-8");
|
2013-03-17 15:28:49 +00:00
|
|
|
}
|
2021-08-17 08:56:52 +00:00
|
|
|
if(!hasHeader("X-Requested-With") && !isSimpleRequest(type,headers)) {
|
2018-07-18 15:54:43 +00:00
|
|
|
request.setRequestHeader("X-Requested-With","TiddlyWiki");
|
|
|
|
}
|
2023-06-13 09:35:55 +00:00
|
|
|
// Send data
|
2015-08-29 15:33:04 +00:00
|
|
|
try {
|
|
|
|
request.send(data);
|
|
|
|
} catch(e) {
|
2019-04-15 20:07:23 +00:00
|
|
|
options.callback(e,null,this);
|
2015-08-29 15:33:04 +00:00
|
|
|
}
|
2013-03-17 15:28:49 +00:00
|
|
|
return request;
|
|
|
|
};
|
|
|
|
|
2023-06-13 09:35:55 +00:00
|
|
|
exports.setQueryStringParameter = function(url,paramName,paramValue) {
|
|
|
|
var URL = $tw.browser ? window.URL : require("url").URL,
|
|
|
|
newUrl;
|
|
|
|
try {
|
|
|
|
newUrl = new URL(url);
|
|
|
|
} catch(e) {
|
|
|
|
}
|
|
|
|
if(newUrl && paramName) {
|
|
|
|
newUrl.searchParams.set(paramName,paramValue || "");
|
|
|
|
return newUrl.toString();
|
|
|
|
} else {
|
|
|
|
return url;
|
|
|
|
}
|
|
|
|
};
|
|
|
|
|
2013-03-17 15:28:49 +00:00
|
|
|
})();
|