1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
|
"use strict";
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
Object.defineProperty(exports, "__esModule", {
value: true
});
var _exportNames = {
MatrixHttpApi: true
};
exports.MatrixHttpApi = void 0;
var _defineProperty2 = _interopRequireDefault(require("@babel/runtime/helpers/defineProperty"));
var _fetch = require("./fetch");
var _prefix = require("./prefix");
Object.keys(_prefix).forEach(function (key) {
if (key === "default" || key === "__esModule") return;
if (Object.prototype.hasOwnProperty.call(_exportNames, key)) return;
if (key in exports && exports[key] === _prefix[key]) return;
Object.defineProperty(exports, key, {
enumerable: true,
get: function () {
return _prefix[key];
}
});
});
var utils = _interopRequireWildcard(require("../utils"));
var callbacks = _interopRequireWildcard(require("../realtime-callbacks"));
var _method = require("./method");
Object.keys(_method).forEach(function (key) {
if (key === "default" || key === "__esModule") return;
if (Object.prototype.hasOwnProperty.call(_exportNames, key)) return;
if (key in exports && exports[key] === _method[key]) return;
Object.defineProperty(exports, key, {
enumerable: true,
get: function () {
return _method[key];
}
});
});
var _errors = require("./errors");
Object.keys(_errors).forEach(function (key) {
if (key === "default" || key === "__esModule") return;
if (Object.prototype.hasOwnProperty.call(_exportNames, key)) return;
if (key in exports && exports[key] === _errors[key]) return;
Object.defineProperty(exports, key, {
enumerable: true,
get: function () {
return _errors[key];
}
});
});
var _utils2 = require("./utils");
Object.keys(_utils2).forEach(function (key) {
if (key === "default" || key === "__esModule") return;
if (Object.prototype.hasOwnProperty.call(_exportNames, key)) return;
if (key in exports && exports[key] === _utils2[key]) return;
Object.defineProperty(exports, key, {
enumerable: true,
get: function () {
return _utils2[key];
}
});
});
var _interface = require("./interface");
Object.keys(_interface).forEach(function (key) {
if (key === "default" || key === "__esModule") return;
if (Object.prototype.hasOwnProperty.call(_exportNames, key)) return;
if (key in exports && exports[key] === _interface[key]) return;
Object.defineProperty(exports, key, {
enumerable: true,
get: function () {
return _interface[key];
}
});
});
function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function (nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); }
function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; }
/*
Copyright 2022 The Matrix.org Foundation C.I.C.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
class MatrixHttpApi extends _fetch.FetchHttpApi {
constructor(...args) {
super(...args);
(0, _defineProperty2.default)(this, "uploads", []);
}
/**
* Upload content to the homeserver
*
* @param file - The object to upload. On a browser, something that
* can be sent to XMLHttpRequest.send (typically a File). Under node.js,
* a Buffer, String or ReadStream.
*
* @param opts - options object
*
* @returns Promise which resolves to response object, as
* determined by this.opts.onlyData, opts.rawResponse, and
* opts.onlyContentUri. Rejects with an error (usually a MatrixError).
*/
uploadContent(file, opts = {}) {
var _opts$includeFilename, _opts$abortController, _ref, _opts$type, _opts$name;
const includeFilename = (_opts$includeFilename = opts.includeFilename) !== null && _opts$includeFilename !== void 0 ? _opts$includeFilename : true;
const abortController = (_opts$abortController = opts.abortController) !== null && _opts$abortController !== void 0 ? _opts$abortController : new AbortController();
// If the file doesn't have a mime type, use a default since the HS errors if we don't supply one.
const contentType = (_ref = (_opts$type = opts.type) !== null && _opts$type !== void 0 ? _opts$type : file.type) !== null && _ref !== void 0 ? _ref : "application/octet-stream";
const fileName = (_opts$name = opts.name) !== null && _opts$name !== void 0 ? _opts$name : file.name;
const upload = {
loaded: 0,
total: 0,
abortController
};
const defer = utils.defer();
if (global.XMLHttpRequest) {
const xhr = new global.XMLHttpRequest();
const timeoutFn = function () {
xhr.abort();
defer.reject(new Error("Timeout"));
};
// set an initial timeout of 30s; we'll advance it each time we get a progress notification
let timeoutTimer = callbacks.setTimeout(timeoutFn, 30000);
xhr.onreadystatechange = function () {
switch (xhr.readyState) {
case global.XMLHttpRequest.DONE:
callbacks.clearTimeout(timeoutTimer);
try {
if (xhr.status === 0) {
throw new DOMException(xhr.statusText, "AbortError"); // mimic fetch API
}
if (!xhr.responseText) {
throw new Error("No response body.");
}
if (xhr.status >= 400) {
defer.reject((0, _utils2.parseErrorResponse)(xhr, xhr.responseText));
} else {
defer.resolve(JSON.parse(xhr.responseText));
}
} catch (err) {
if (err.name === "AbortError") {
defer.reject(err);
return;
}
defer.reject(new _errors.ConnectionError("request failed", err));
}
break;
}
};
xhr.upload.onprogress = ev => {
var _opts$progressHandler;
callbacks.clearTimeout(timeoutTimer);
upload.loaded = ev.loaded;
upload.total = ev.total;
timeoutTimer = callbacks.setTimeout(timeoutFn, 30000);
(_opts$progressHandler = opts.progressHandler) === null || _opts$progressHandler === void 0 ? void 0 : _opts$progressHandler.call(opts, {
loaded: ev.loaded,
total: ev.total
});
};
const url = this.getUrl("/upload", undefined, _prefix.MediaPrefix.R0);
if (includeFilename && fileName) {
url.searchParams.set("filename", encodeURIComponent(fileName));
}
if (!this.opts.useAuthorizationHeader && this.opts.accessToken) {
url.searchParams.set("access_token", encodeURIComponent(this.opts.accessToken));
}
xhr.open(_method.Method.Post, url.href);
if (this.opts.useAuthorizationHeader && this.opts.accessToken) {
xhr.setRequestHeader("Authorization", "Bearer " + this.opts.accessToken);
}
xhr.setRequestHeader("Content-Type", contentType);
xhr.send(file);
abortController.signal.addEventListener("abort", () => {
xhr.abort();
});
} else {
const queryParams = {};
if (includeFilename && fileName) {
queryParams.filename = fileName;
}
const headers = {
"Content-Type": contentType
};
this.authedRequest(_method.Method.Post, "/upload", queryParams, file, {
prefix: _prefix.MediaPrefix.R0,
headers,
abortSignal: abortController.signal
}).then(response => {
return this.opts.onlyData ? response : response.json();
}).then(defer.resolve, defer.reject);
}
// remove the upload from the list on completion
upload.promise = defer.promise.finally(() => {
utils.removeElement(this.uploads, elem => elem === upload);
});
abortController.signal.addEventListener("abort", () => {
utils.removeElement(this.uploads, elem => elem === upload);
defer.reject(new DOMException("Aborted", "AbortError"));
});
this.uploads.push(upload);
return upload.promise;
}
cancelUpload(promise) {
const upload = this.uploads.find(u => u.promise === promise);
if (upload) {
upload.abortController.abort();
return true;
}
return false;
}
getCurrentUploads() {
return this.uploads;
}
/**
* Get the content repository url with query parameters.
* @returns An object with a 'base', 'path' and 'params' for base URL,
* path and query parameters respectively.
*/
getContentUri() {
return {
base: this.opts.baseUrl,
path: _prefix.MediaPrefix.R0 + "/upload",
params: {
access_token: this.opts.accessToken
}
};
}
}
exports.MatrixHttpApi = MatrixHttpApi;
//# sourceMappingURL=index.js.map
|