Skip to content

Commit 2c15f7f

Browse files
committed
feat(): get file support
1 parent 7623606 commit 2c15f7f

File tree

6 files changed

+929
-554
lines changed

6 files changed

+929
-554
lines changed

src/http/http-request-common.ts

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -84,6 +84,16 @@ export interface HttpRequestOptions {
8484
onLoading?: () => void;
8585
}
8686

87+
export interface HttpDownloadRequestOptions {
88+
url: string;
89+
headers?: Headers;
90+
filePath?: any;
91+
timeout?: number;
92+
onProgress?: (event: any) => void;
93+
onHeaders?: (...args) => void;
94+
onLoading?: () => void;
95+
}
96+
8797
export enum HttpResponseEncoding {
8898
UTF8,
8999
GBK
@@ -96,3 +106,10 @@ export interface HttpResponse {
96106
url: string;
97107
}
98108

109+
export interface HttpDownloadResponse {
110+
statusCode: number;
111+
filePath: string;
112+
headers: Headers;
113+
url: string;
114+
}
115+

src/http/http.android.ts

Lines changed: 198 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,16 +1,18 @@
11
import {
22
fileNameFromPath,
33
Headers,
4+
HttpDownloadRequestOptions,
45
HttpError,
56
HttpRequestOptions,
67
isImageUrl,
78
SaveImageStorageKey,
89
TNSHttpSettings
910
} from './http-request-common';
1011
import * as types from 'tns-core-modules/utils/types';
12+
import { isString } from 'tns-core-modules/utils/types';
1113
import { NetworkAgent } from 'tns-core-modules/debugger';
1214
import { getString, setString } from 'tns-core-modules/application-settings';
13-
import { File, knownFolders, path } from 'tns-core-modules/file-system';
15+
import { File, Folder, knownFolders, path } from 'tns-core-modules/file-system';
1416
import { FileManager } from '..';
1517

1618
export type CancellablePromise = Promise<any> & { cancel: () => void };
@@ -102,7 +104,7 @@ export class Http {
102104
constructor() {
103105
}
104106

105-
buildJavaOptions(options: HttpRequestOptions) {
107+
private static buildJavaOptions(options: HttpRequestOptions) {
106108
if (!types.isString(options.url)) {
107109
throw new Error('Http request must provide a valid url.');
108110
}
@@ -148,6 +150,45 @@ export class Http {
148150
return javaOptions;
149151
}
150152

153+
private static buildJavaDownloadOptions(options: HttpDownloadRequestOptions) {
154+
if (!types.isString(options.url)) {
155+
throw new Error('Http request must provide a valid url.');
156+
}
157+
158+
const javaOptions = new com.github.triniwiz.async.Async.Http.DownloadRequestOptions();
159+
javaOptions.url = options.url;
160+
161+
if (typeof options.timeout === 'number') {
162+
javaOptions.timeout = options.timeout;
163+
}
164+
165+
if (typeof options.filePath === 'string') {
166+
javaOptions.filePath = options.filePath;
167+
} else {
168+
// creates directory
169+
Folder.fromPath(path.join(knownFolders.temp().path, 'async_http'));
170+
javaOptions.filePath = path.join(knownFolders.temp().path, 'async_http', java.util.UUID.randomUUID().toString());
171+
}
172+
173+
if (options.headers) {
174+
const arrayList = new java.util.ArrayList<any>();
175+
const pair = com.github.triniwiz.async.Async.Http.KeyValuePair;
176+
177+
if (options.headers instanceof Map) {
178+
options.headers.forEach((value, key) => {
179+
arrayList.add(new pair(key, value + ''));
180+
});
181+
} else {
182+
for (let key in options.headers) {
183+
arrayList.add(new pair(key, options.headers[key] + ''));
184+
}
185+
}
186+
187+
javaOptions.headers = arrayList;
188+
}
189+
return javaOptions;
190+
}
191+
151192
request(options: HttpRequestOptions): CancellablePromise {
152193
const headers: Headers = {};
153194
let statusCode = 0;
@@ -157,7 +198,7 @@ export class Http {
157198
try {
158199

159200
// initialize the options
160-
const javaOptions = this.buildJavaOptions(options);
201+
const javaOptions = Http.buildJavaOptions(options);
161202

162203
if (TNSHttpSettings.debug) {
163204
// @ts-ignore
@@ -396,6 +437,160 @@ export class Http {
396437
return request;
397438
}
398439

440+
public static getFile(options: HttpDownloadRequestOptions): CancellablePromise {
441+
const headers: Headers = {};
442+
let statusCode = 0;
443+
let id;
444+
const counter = requestIdCounter;
445+
const request = <CancellablePromise>new Promise<any>((resolve, reject) => {
446+
try {
447+
448+
// initialize the options
449+
const javaOptions = Http.buildJavaDownloadOptions(options);
450+
451+
if (TNSHttpSettings.debug) {
452+
// @ts-ignore
453+
if (global.__inspector && global.__inspector.isConnected) {
454+
NetworkAgent.requestWillBeSent(requestIdCounter, options);
455+
}
456+
}
457+
458+
const makeRemoteRequest = () => {
459+
const callback = new com.github.triniwiz.async.Async.Http.Callback({
460+
onCancel(param: any): void {
461+
reject({
462+
type: HttpError.Cancelled,
463+
result: param
464+
});
465+
requestCallbacks.delete(id);
466+
},
467+
onComplete(result: any): void {
468+
if (result && result.headers) {
469+
const length = result.headers.size();
470+
let pair;
471+
for (let i = 0; i < length; i++) {
472+
pair = result.headers.get(i);
473+
addHeader(headers, pair.key, pair.value);
474+
}
475+
}
476+
// send response data (for requestId) to network debugger
477+
478+
479+
let contentType = headers['Content-Type'];
480+
if (types.isNullOrUndefined(contentType)) {
481+
contentType = headers['content-type'];
482+
}
483+
let acceptHeader;
484+
485+
if (types.isNullOrUndefined(contentType)) {
486+
acceptHeader = headers['Accept'];
487+
if (types.isNullOrUndefined(acceptHeader)) {
488+
acceptHeader = headers['accept'];
489+
}
490+
} else {
491+
acceptHeader = contentType;
492+
}
493+
494+
let returnType = 'text/plain';
495+
if (!types.isNullOrUndefined(acceptHeader) && types.isString(acceptHeader)) {
496+
let acceptValues = acceptHeader.split(',');
497+
let quality = [];
498+
let defaultQuality = [];
499+
let customQuality = [];
500+
for (let value of acceptValues) {
501+
if (value.indexOf(';q=') > -1) {
502+
customQuality.push(value);
503+
} else {
504+
defaultQuality.push(value);
505+
}
506+
}
507+
customQuality = customQuality.sort((a, b) => {
508+
const a_quality = parseFloat(a.substring(a.indexOf(';q=')).replace(';q=', ''));
509+
const b_quality = parseFloat(b.substring(b.indexOf(';q=')).replace(';q=', ''));
510+
return (b_quality - a_quality);
511+
});
512+
quality.push(...defaultQuality);
513+
quality.push(...customQuality);
514+
returnType = quality[0];
515+
}
516+
517+
result['statusCode'] = statusCode;
518+
519+
if (TNSHttpSettings.debug) {
520+
// send response data (for requestId) to network debugger
521+
// @ts-ignore
522+
if (global.__inspector && global.__inspector.isConnected) {
523+
NetworkAgent.responseReceived(counter, {
524+
url: result.url,
525+
statusCode,
526+
headers,
527+
responseAsString: isString ? (result.contentText ? result.contentText : result.content.toString()) : null,
528+
responseAsImage: null // TODO needs base64 Image
529+
}, headers);
530+
}
531+
532+
}
533+
534+
535+
resolve(result.filePath);
536+
requestCallbacks.delete(id);
537+
},
538+
onError(param0: string, param1: java.lang.Exception): void {
539+
reject({
540+
type: HttpError.Error,
541+
message: param0
542+
});
543+
requestCallbacks.delete(id);
544+
},
545+
onHeaders(jHeaders: any, status: number): void {
546+
statusCode = status;
547+
const length = jHeaders.size();
548+
let pair;
549+
for (let i = 0; i < length; i++) {
550+
pair = jHeaders.get(i);
551+
addHeader(headers, pair.key, pair.value);
552+
}
553+
if (options.onHeaders) {
554+
options.onHeaders(headers, statusCode);
555+
}
556+
requestCallbacks.delete(id);
557+
}, onLoading(): void {
558+
options.onLoading();
559+
requestCallbacks.delete(id);
560+
}, onProgress(lengthComputable: boolean, loaded: number, total: number): void {
561+
if (options.onProgress) {
562+
options.onProgress({
563+
lengthComputable,
564+
loaded,
565+
total
566+
});
567+
}
568+
requestCallbacks.delete(id);
569+
},
570+
onTimeout(): void {
571+
reject({
572+
type: HttpError.Timeout
573+
});
574+
requestCallbacks.delete(id);
575+
}
576+
});
577+
id = com.github.triniwiz.async.Async.Http.getFileRequest(javaOptions, callback);
578+
requestCallbacks.set(id, callback);
579+
};
580+
makeRemoteRequest();
581+
requestIdCounter++;
582+
} catch (ex) {
583+
reject({
584+
type: HttpError.Error,
585+
message: ex.message
586+
});
587+
}
588+
});
589+
request['cancel'] = function () {
590+
com.github.triniwiz.async.Async.Http.cancelRequest(id);
591+
};
592+
return request;
593+
}
399594
}
400595

401596
function serialize(data: any): any {

src/http/http.d.ts

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import { Headers, HttpRequestOptions } from './http-request-common';
1+
import { Headers, HttpDownloadRequestOptions, HttpRequestOptions } from './http-request-common';
22

33
export enum HttpResponseEncoding {
44
UTF8,
@@ -14,5 +14,7 @@ export class Http {
1414

1515
request(options: HttpRequestOptions): CancellablePromise;
1616

17+
public static getFile(options: HttpDownloadRequestOptions): CancellablePromise;
18+
1719
cancel();
1820
}

0 commit comments

Comments
 (0)