-
-
Notifications
You must be signed in to change notification settings - Fork 112
/
Copy pathindex.ios.ts
410 lines (336 loc) · 14.3 KB
/
index.ios.ts
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
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
import { Observable, knownFolders } from "@nativescript/core";
import { ProgressEventData, ErrorEventData, ResultEventData, Session as ISession, Task as ITask, Request as IRequest, CompleteEventData } from ".";
const main_queue = dispatch_get_current_queue();
let zonedOnProgress = null;
let zonedOnError = null;
function onProgress(nsSession, nsTask, sent, expectedTotal) {
const task = Task.getTask(nsSession, nsTask);
task.notifyPropertyChange("upload", task.upload);
task.notifyPropertyChange("totalUpload", task.totalUpload);
task.notify(<ProgressEventData>{
eventName: "progress",
object: task,
currentBytes: sent,
totalBytes: expectedTotal
});
}
function onError(session, nsTask, error) {
const task = Task.getTask(session, nsTask);
if (task._fileToCleanup) {
NSFileManager.defaultManager.removeItemAtPathError(task._fileToCleanup);
}
const response = nsTask && <NSHTTPURLResponse>nsTask.performSelector("response");
if (error) {
task.notifyPropertyChange("status", task.status);
task.notify(<ErrorEventData>{
eventName: "error",
object: task,
error,
responseCode: response ? response.statusCode : -1,
response
});
} else {
task.notifyPropertyChange("upload", task.upload);
task.notifyPropertyChange("totalUpload", task.totalUpload);
task.notify(<ProgressEventData>{
eventName: "progress",
object: task,
currentBytes: nsTask.countOfBytesSent,
totalBytes: nsTask.countOfBytesExpectedToSend
});
task.notify(<CompleteEventData>{
eventName: "complete",
object: task,
responseCode: response ? response.statusCode : -1,
response
});
Task._tasks.delete(nsTask);
}
}
@NativeClass()
class BackgroundUploadDelegate extends NSObject implements NSURLSessionDelegate, NSURLSessionTaskDelegate, NSURLSessionDataDelegate, NSURLSessionDownloadDelegate {
static ObjCProtocols = [NSURLSessionDelegate, NSURLSessionTaskDelegate, NSURLSessionDataDelegate, NSURLSessionDownloadDelegate];
// NSURLSessionDelegate
URLSessionDidBecomeInvalidWithError(session, error) {
}
URLSessionDidReceiveChallengeCompletionHandler(session, challenge, comlpetionHandler) {
const disposition = null;
const credential = null;
comlpetionHandler(disposition, credential);
}
URLSessionDidFinishEventsForBackgroundURLSession(session) {
}
// NSURLSessionTaskDelegate
URLSessionTaskDidCompleteWithError(session: NSURLSession, nsTask: NSURLSessionTask, error: NSError) {
dispatch_async(main_queue, () => {
zonedOnError(session, nsTask, error);
});
}
URLSessionTaskDidReceiveChallengeCompletionHandler(session, task, challenge, completionHandler) {
const disposition = null;
const credential = null;
completionHandler(disposition, credential);
}
URLSessionTaskDidSendBodyDataTotalBytesSentTotalBytesExpectedToSend(nsSession: NSURLSession, nsTask: NSURLSessionTask, data, sent: number, expectedTotal: number) {
dispatch_async(main_queue, () => {
zonedOnProgress(nsSession, nsTask, sent, expectedTotal);
});
}
URLSessionTaskNeedNewBodyStream(session, task, need) {
}
URLSessionTaskWillPerformHTTPRedirectionNewRequestCompletionHandler(session, task, redirect, request, completionHandler) {
completionHandler(request);
}
// NSURLSessionDataDelegate
URLSessionDataTaskDidReceiveResponseCompletionHandler(session, dataTask, response, completionHandler) {
const disposition = null;
completionHandler(disposition);
}
URLSessionDataTaskDidBecomeDownloadTask(session, dataTask, downloadTask) {
}
URLSessionDataTaskDidReceiveData(session: NSURLSession, dataTask: NSURLSessionDataTask, data: NSData) {
dispatch_async(main_queue, () => {
// we have a response in the data...
const jsTask = Task.getTask(session, dataTask);
const jsonString = NSString.alloc().initWithDataEncoding(data, NSUTF8StringEncoding);
jsTask.notify(<ResultEventData>{
eventName: "responded",
object: jsTask,
data: jsonString.toString(),
responseCode: dataTask && dataTask.response ? (<NSHTTPURLResponse>dataTask.response).statusCode : -1
});
});
}
URLSessionDataTaskWillCacheResponseCompletionHandler() {
}
// NSURLSessionDownloadDelegate
URLSessionDownloadTaskDidResumeAtOffsetExpectedTotalBytes(session, task, offset, expects) {
}
URLSessionDownloadTaskDidWriteDataTotalBytesWrittenTotalBytesExpectedToWrite(session, task, data, written, expected) {
}
URLSessionDownloadTaskDidFinishDownloadingToURL(session, task, url) {
}
}
class Session implements Session {
// TODO: Create a mechanism to clean sessions from the cache that have all their tasks completed, canceled or errored out.
private static _sessions: { [id: string]: Session } = {};
private _session: NSURLSession;
constructor(id: string) {
const delegate = BackgroundUploadDelegate.alloc().init();
const configuration = NSURLSessionConfiguration.backgroundSessionConfigurationWithIdentifier(id);
this._session = NSURLSession.sessionWithConfigurationDelegateDelegateQueue(configuration, delegate, null);
zonedOnProgress = global.zonedCallback(onProgress);
zonedOnError = global.zonedCallback(onError);
}
get ios(): any {
return this._session;
}
public uploadFile(fileUri: string, options: IRequest): Task {
if (!fileUri) {
throw new Error("File must be provided.");
}
const url = NSURL.URLWithString(options.url);
const request = NSMutableURLRequest.requestWithURL(url);
const headers = options.headers;
if (headers) {
for (let header in headers) {
const value = headers[header];
if (value !== null && value !== void 0) {
request.setValueForHTTPHeaderField(value.toString(), header);
}
}
}
if (options.method) {
request.HTTPMethod = options.method;
}
let fileURL: NSURL;
if (fileUri.substr(0, 7) === "file://") {
// File URI in string format
fileURL = NSURL.URLWithString(fileUri);
} else if (fileUri.charAt(0) === "/") {
// Absolute path with leading slash
fileURL = NSURL.fileURLWithPath(fileUri);
}
const newTask = this._session.uploadTaskWithRequestFromFile(request, fileURL);
newTask.taskDescription = options.description;
newTask.resume();
const retTask: Task = <any>Task.getTask(this._session, newTask);
return retTask;
}
public multipartUpload(params: any[], options: any): Task {
const MPF = new MultiMultiPartForm();
for (let i = 0; i < params.length; i++) {
const curParam = params[i];
if (typeof curParam.name === 'undefined') {
throw new Error("You must have a `name` value");
}
if (curParam.filename) {
const destFileName = curParam.destFilename || curParam.filename.substring(curParam.filename.lastIndexOf('/') + 1, curParam.filename.length);
MPF.appendParam(curParam.name, null, curParam.filename, curParam.mimeType, destFileName);
} else {
MPF.appendParam(curParam.name, curParam.value);
}
}
const header = MPF.getHeader();
const uploadFile = MPF.generateFile();
if (!options.headers) {
options.headers = {};
}
options.headers['Content-Type'] = header['Content-Type'];
const task = this.uploadFile(uploadFile, options);
// Tag the file to be deleted and cleanup after upload
(<any>task)._fileToCleanup = uploadFile;
return task;
}
static getSession(id: string): Session {
let jsSession = Session._sessions[id];
if (jsSession) {
return jsSession;
}
jsSession = new Session(id);
Session._sessions[id] = jsSession;
return jsSession;
}
}
class NativePropertyReader {
private _invocationCache = new Map<string, NSInvocation>();
private getInvocationObject(object: NSObject, selector: string): NSInvocation {
let invocation = this._invocationCache.get(selector);
if (!invocation) {
const sig = object.methodSignatureForSelector(selector);
invocation = NSInvocation.invocationWithMethodSignature(sig);
invocation.selector = selector;
this._invocationCache[selector] = invocation;
}
return invocation;
}
public readProp<T>(object: NSObject, prop: string, type: interop.Type<T>): T {
const invocation = this.getInvocationObject(object, prop);
invocation.invokeWithTarget(object);
const ret = new interop.Reference<T>(type, new interop.Pointer());
invocation.getReturnValue(ret);
return ret.value;
}
}
class Task extends Observable {
public static _tasks = new Map<NSURLSessionTask, Task>();
public static tasksReader = new NativePropertyReader();
private static is64BitArchitecture = interop.sizeof(interop.types.id) === 8;
public static NSIntegerType = Task.is64BitArchitecture ? interop.types.int64 : interop.types.int32;
public _fileToCleanup: string;
private _task: NSURLSessionTask;
private _session: NSURLSession;
constructor(nsSession: NSURLSession, nsTask: NSURLSessionTask) {
super();
this._task = nsTask;
this._session = nsSession;
}
get ios(): any {
return this._task;
}
get description(): string {
return this._task.taskDescription;
}
get upload(): number {
return Task.tasksReader.readProp(this._task, "countOfBytesSent", interop.types.int64);
}
get totalUpload(): number {
return Task.tasksReader.readProp(this._task, "countOfBytesExpectedToSend", interop.types.int64);
}
get status(): string {
if (Task.tasksReader.readProp(this._task, "error", Task.NSIntegerType)) {
return "error";
}
// NSURLSessionTaskState : NSInteger, so we should pass number format here
switch (Task.tasksReader.readProp(this._task, "state", Task.NSIntegerType) as NSURLSessionTaskState) {
case NSURLSessionTaskState.Running: return "uploading";
case NSURLSessionTaskState.Completed: return "complete";
case NSURLSessionTaskState.Canceling: return "error";
case NSURLSessionTaskState.Suspended: return "pending";
}
}
public static getTask(nsSession: NSURLSession, nsTask: NSURLSessionTask): Task {
let task = Task._tasks.get(nsTask);
if (task) {
return task;
}
task = new Task(nsSession, nsTask);
Task._tasks.set(nsTask, task);
return task;
}
public cancel(): void {
this._task.cancel();
}
}
export function session(id: string): Session {
return Session.getSession(id);
}
class MultiMultiPartForm {
private boundary: string;
private header: any;
private fileCount: number;
private fields: Array<any>;
constructor() {
this.clear();
}
public clear(): void {
this.boundary = "--------------formboundary" + Math.floor(Math.random() * 100000000000);
this.header = { "Content-Type": 'multipart/form-data; boundary=' + this.boundary };
this.fileCount = 0;
this.fields = [];
}
public appendParam(name: string, value: string, filename?: string, mimeType?: string, destFileName?: string): void {
// If all we are doing is passing a field, we just add it to the fields list
if (filename == null) {
this.fields.push({ name: name, value: value });
return;
}
// Load file
mimeType = mimeType || "application/data";
if (filename.startsWith("~/")) {
filename = filename.replace("~/", knownFolders.currentApp().path + "/");
}
const finalName = destFileName || filename.substr(filename.lastIndexOf('/') + 1, filename.length);
this.fields.push({ name: name, filename: filename, destFilename: finalName, mimeType: mimeType });
}
public generateFile(): string {
const CRLF = "\r\n";
const fileName = knownFolders.documents().path + "/temp-MPF-" + Math.floor(Math.random() * 100000000000) + ".tmp";
const combinedData = NSMutableData.alloc().init();
let results: string = "";
let tempString: NSString;
let newData: any;
for (let i = 0; i < this.fields.length; i++) {
results += "--" + this.boundary + CRLF;
results += 'Content-Disposition: form-data; name="' + this.fields[i].name + '"';
if (!this.fields[i].filename) {
results += CRLF + CRLF + this.fields[i].value + CRLF;
} else {
results += '; filename="' + this.fields[i].destFilename + '"';
if (this.fields[i].mimeType) {
results += CRLF + "Content-Type: " + this.fields[i].mimeType;
}
results += CRLF + CRLF;
}
tempString = NSString.stringWithString(results);
results = "";
newData = tempString.dataUsingEncoding(NSUTF8StringEncoding);
combinedData.appendData(newData);
if (this.fields[i].filename) {
const fileData = NSData.alloc().initWithContentsOfFile(this.fields[i].filename);
combinedData.appendData(fileData);
results = CRLF;
}
}
// Add final part of it...
results += "--" + this.boundary + "--" + CRLF;
tempString = NSString.stringWithString(results);
newData = tempString.dataUsingEncoding(NSUTF8StringEncoding);
combinedData.appendData(newData);
NSFileManager.defaultManager.createFileAtPathContentsAttributes(fileName, combinedData, null);
return fileName;
}
public getHeader(): string {
return this.header;
}
}