Skip to content
This repository was archived by the owner on Mar 16, 2019. It is now read-only.

Commit 6a435da

Browse files
committed
Add cookie related implementation #156
1 parent c2be762 commit 6a435da

File tree

9 files changed

+245
-58
lines changed

9 files changed

+245
-58
lines changed

src/android/src/main/java/com/RNFetchBlob/RNFetchBlob.java

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,13 +3,15 @@
33
import android.content.Intent;
44
import android.net.Uri;
55

6+
import com.RNFetchBlob.Utils.RNFBCookieJar;
67
import com.facebook.react.bridge.Callback;
78
import com.facebook.react.bridge.Promise;
89
import com.facebook.react.bridge.ReactApplicationContext;
910
import com.facebook.react.bridge.ReactContextBaseJavaModule;
1011
import com.facebook.react.bridge.ReactMethod;
1112
import com.facebook.react.bridge.ReadableArray;
1213
import com.facebook.react.bridge.ReadableMap;
14+
import com.facebook.react.bridge.WritableArray;
1315

1416
import java.util.Map;
1517
import java.util.concurrent.LinkedBlockingQueue;
@@ -203,6 +205,20 @@ public void run() {
203205

204206
}
205207

208+
@ReactMethod
209+
/**
210+
* Get cookies belongs specific host.
211+
* @param host String host name.
212+
*/
213+
public void getCookies(String host, Promise promise) {
214+
try {
215+
WritableArray cookies = RNFBCookieJar.getCookies(host);
216+
promise.resolve(cookies);
217+
} catch(Exception err) {
218+
promise.reject("RNFetchBlob.getCookies", err.getMessage());
219+
}
220+
}
221+
206222
@ReactMethod
207223
/**
208224
* @param path Stream file path

src/android/src/main/java/com/RNFetchBlob/RNFetchBlobReq.java

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@
1111

1212
import com.RNFetchBlob.Response.RNFetchBlobDefaultResp;
1313
import com.RNFetchBlob.Response.RNFetchBlobFileResp;
14+
import com.RNFetchBlob.Utils.RNFBCookieJar;
1415
import com.facebook.react.bridge.Arguments;
1516
import com.facebook.react.bridge.Callback;
1617
import com.facebook.react.bridge.ReactApplicationContext;
@@ -25,6 +26,9 @@
2526
import java.io.FileOutputStream;
2627
import java.io.IOException;
2728
import java.io.InputStream;
29+
import java.net.CookieHandler;
30+
import java.net.CookieManager;
31+
import java.net.CookiePolicy;
2832
import java.net.MalformedURLException;
2933
import java.net.SocketException;
3034
import java.net.SocketTimeoutException;
@@ -39,6 +43,7 @@
3943

4044
import okhttp3.Call;
4145
import okhttp3.ConnectionPool;
46+
import okhttp3.CookieJar;
4247
import okhttp3.Headers;
4348
import okhttp3.Interceptor;
4449
import okhttp3.MediaType;
@@ -290,7 +295,11 @@ else if(cType.isEmpty()) {
290295
break;
291296
}
292297

298+
// #156 fix cookie issue
299+
300+
293301
final Request req = builder.build();
302+
clientBuilder.cookieJar(new RNFBCookieJar());
294303
clientBuilder.addNetworkInterceptor(new Interceptor() {
295304
@Override
296305
public Response intercept(Chain chain) throws IOException {
Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
package com.RNFetchBlob.Utils;
2+
3+
import com.facebook.react.bridge.Arguments;
4+
import com.facebook.react.bridge.ReadableMap;
5+
import com.facebook.react.bridge.WritableArray;
6+
import com.facebook.react.bridge.WritableMap;
7+
8+
import java.util.ArrayList;
9+
import java.util.HashMap;
10+
import java.util.List;
11+
12+
import okhttp3.Cookie;
13+
import okhttp3.CookieJar;
14+
import okhttp3.HttpUrl;
15+
16+
/**
17+
* Created by wkh237on 2016/10/14.
18+
*/
19+
20+
21+
22+
public class RNFBCookieJar implements CookieJar {
23+
24+
static final HashMap<String, List<Cookie>> cookieStore = new HashMap<>();
25+
private List<Cookie> cookies;
26+
27+
@Override
28+
public void saveFromResponse(HttpUrl url, List<Cookie> cookies) {
29+
cookieStore.put(url.host(), cookies);
30+
}
31+
32+
@Override
33+
public List<Cookie> loadForRequest(HttpUrl url) {
34+
List<Cookie> cookies = cookieStore.get(url.host());
35+
return cookies != null ? cookies : new ArrayList<Cookie>();
36+
}
37+
38+
public static WritableArray getCookies(String host) {
39+
HttpUrl url = HttpUrl.parse(host);
40+
List<Cookie> cookies = null;
41+
if(url != null) {
42+
cookies = cookieStore.get(url.host());
43+
}
44+
WritableArray cookieList = Arguments.createArray();
45+
if(cookies != null) {
46+
for(Cookie c : cookies){
47+
cookieList.pushString(c.toString());
48+
}
49+
return cookieList;
50+
}
51+
return null;
52+
}
53+
}

src/index.js

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,7 @@ import base64 from 'base-64'
2424
import polyfill from './polyfill'
2525
import android from './android'
2626
import ios from './ios'
27+
import net from './net'
2728
import JSONStream from './json-stream'
2829
const {
2930
RNFetchBlobSession,
@@ -41,10 +42,9 @@ const {
4142
cp
4243
} = fs
4344

44-
4545
const Blob = polyfill.Blob
4646
const emitter = DeviceEventEmitter
47-
const RNFetchBlob:RNFetchBlobNative = NativeModules.RNFetchBlob
47+
const RNFetchBlob= NativeModules.RNFetchBlob
4848

4949
// register message channel event handler.
5050
emitter.addListener("RNFetchBlobMessage", (e) => {
@@ -549,6 +549,7 @@ export default {
549549
session,
550550
fs,
551551
wrap,
552+
net,
552553
polyfill,
553554
JSONStream
554555
}

src/ios/RNFetchBlob/RNFetchBlob.m

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -91,6 +91,7 @@ - (NSDictionary *)constantsToExport
9191

9292
}
9393

94+
9495
// Fetch blob data request
9596
RCT_EXPORT_METHOD(fetchBlob:(NSDictionary *)options
9697
taskId:(NSString *)taskId
@@ -473,8 +474,11 @@ - (UIViewController *) documentInteractionControllerViewControllerForPreview: (U
473474
return window.rootViewController;
474475
}
475476

476-
477-
#pragma mark RNFetchBlob private methods
477+
# pragma mark - getCookies
478+
RCT_EXPORT_METHOD(getCookies:(NSString *)url resolver:(RCTPromiseResolveBlock)resolve rejecter:(RCTPromiseRejectBlock)reject
479+
{
480+
resolve([RNFetchBlobNetwork getCookies:url]);
481+
})
478482

479483

480484
@end

src/ios/RNFetchBlobNetwork.h

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -44,6 +44,7 @@ typedef void(^DataTaskCompletionHander) (NSData * _Nullable resp, NSURLResponse
4444
- (void) sendRequest:(NSDictionary * _Nullable )options contentLength:(long)contentLength bridge:(RCTBridge * _Nullable)bridgeRef taskId:(NSString * _Nullable)taskId withRequest:(NSURLRequest * _Nullable)req callback:(_Nullable RCTResponseSenderBlock) callback;
4545
+ (void) enableProgressReport:(NSString *) taskId config:(RNFetchBlobProgress *)config;
4646
+ (void) enableUploadProgress:(NSString *) taskId config:(RNFetchBlobProgress *)config;
47+
+ (NSArray *) getCookies:(NSString *) url;
4748

4849

4950

src/ios/RNFetchBlobNetwork.m

Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,7 @@
2828

2929
NSMapTable * taskTable;
3030
NSMapTable * expirationTable;
31+
NSMapTable * cookiesTable;
3132
NSMutableDictionary * progressTable;
3233
NSMutableDictionary * uploadProgressTable;
3334

@@ -93,9 +94,55 @@ - (id)init {
9394
{
9495
uploadProgressTable = [[NSMutableDictionary alloc] init];
9596
}
97+
if(cookiesTable == nil)
98+
{
99+
cookiesTable = [[NSMapTable alloc] init];
100+
}
96101
return self;
97102
}
98103

104+
+ (NSArray *) getCookies:(NSString *) url
105+
{
106+
NSString * hostname = [[NSURL URLWithString:url] host];
107+
NSMutableArray * cookies = [NSMutableArray new];
108+
NSArray * list = [cookiesTable objectForKey:hostname];
109+
for(NSHTTPCookie * cookie in list)
110+
{
111+
NSMutableString * cookieStr = [[NSMutableString alloc] init];
112+
[cookieStr appendString:cookie.name];
113+
[cookieStr appendString:@"="];
114+
[cookieStr appendString:cookie.value];
115+
116+
if(cookie.expiresDate == nil) {
117+
[cookieStr appendString:@"; max-age=0"];
118+
}
119+
else {
120+
[cookieStr appendString:@"; expires="];
121+
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
122+
[dateFormatter setDateFormat:@"EEE, dd MM yyyy HH:mm:ss ZZZ"];
123+
NSString *strDate = [dateFormatter stringFromDate:cookie.expiresDate];
124+
[cookieStr appendString:strDate];
125+
}
126+
127+
128+
[cookieStr appendString:@"; domain="];
129+
[cookieStr appendString:hostname];
130+
[cookieStr appendString:@"; path="];
131+
[cookieStr appendString:cookie.path];
132+
133+
134+
if (cookie.isSecure) {
135+
[cookieStr appendString:@"; secure"];
136+
}
137+
138+
if (cookie.isHTTPOnly) {
139+
[cookieStr appendString:@"; httponly"];
140+
}
141+
[cookies addObject:cookieStr];
142+
}
143+
return cookies;
144+
}
145+
99146
+ (void) enableProgressReport:(NSString *) taskId config:(RNFetchBlobProgress *)config
100147
{
101148
[progressTable setValue:config forKey:taskId];
@@ -253,6 +300,8 @@ + (void) emitExpiredTasks
253300

254301
#pragma mark NSURLSession delegate methods
255302

303+
304+
#pragma mark - Received Response
256305
// set expected content length on response received
257306
- (void) URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveResponse:(NSURLResponse *)response completionHandler:(void (^)(NSURLSessionResponseDisposition))completionHandler
258307
{
@@ -332,12 +381,23 @@ - (void) URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dat
332381
@"status": [NSString stringWithFormat:@"%d", statusCode ]
333382
};
334383

384+
#pragma mark - handling cookies
385+
// # 153 get cookies
386+
if(response.URL != nil)
387+
{
388+
NSArray<NSHTTPCookie *> * cookies = [NSHTTPCookie cookiesWithResponseHeaderFields: headers forURL:response.URL];
389+
if(cookies != nil && [cookies count] > 0) {
390+
[cookiesTable setObject:cookies forKey:response.URL.host];
391+
}
392+
}
393+
335394
[self.bridge.eventDispatcher
336395
sendDeviceEventWithName: EVENT_STATE_CHANGE
337396
body:respInfo
338397
];
339398
headers = nil;
340399
respInfo = nil;
400+
341401
}
342402
else
343403
NSLog(@"oops");

src/net.js

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
// Copyright 2016 wkh237@github. All rights reserved.
2+
// Use of this source code is governed by a MIT-style license that can be
3+
// found in the LICENSE file.
4+
// @flow
5+
6+
import {
7+
NativeModules,
8+
DeviceEventEmitter,
9+
Platform,
10+
NativeAppEventEmitter,
11+
} from 'react-native'
12+
13+
const RNFetchBlob = NativeModules.RNFetchBlob
14+
15+
/**
16+
* Get cookie according to the given url.
17+
* @param {string} url HTTP URL string.
18+
* @return {Promise<Array<String>>} Cookies of a specific domain.
19+
*/
20+
function getCookies(url:string):Promise<Array<String>> {
21+
return RNFetchBlob.getCookies(url)
22+
}
23+
24+
export default {
25+
getCookies
26+
}

0 commit comments

Comments
 (0)