Skip to content

Instantly share code, notes, and snippets.

@jebai0521
Created August 19, 2020 18:06
Show Gist options
  • Save jebai0521/d0df6ce4de2360ff5e329c6a1461051a to your computer and use it in GitHub Desktop.
Save jebai0521/d0df6ce4de2360ff5e329c6a1461051a to your computer and use it in GitHub Desktop.
import { NativeModules } from 'react-native';
import CookieManager from '@react-native-community/cookies';
import SQLite from '@emanon_/react-native-sqlite-storage';
import { DEVICE } from 'common/constants';
import { File } from 'common/files';
const { PerkdHelper } = NativeModules,
DELTA_EPOCH_IN_MICROSECS = 11644473600000000;
// --- Public functions ---
export const Cookies = {
get: (url) => {
if (IOS) return CookieManager.get(url, !DEVICE.IOS_10);
return getAndroidWebViewCookies(url);
},
set: (key) => CookieManager.set(key, !DEVICE.IOS_10),
clearAll: () => CookieManager.clearAll(!DEVICE.IOS_10),
};
// --- Private functions ---
function getHostFromUrl(url) {
const start = url.indexOf('//'),
pos1 = start > -1 ? start + 2 : 0,
end = url.substring(pos1).indexOf('/'),
pos2 = end > -1 ? pos1 + end : undefined;
return url.substring(pos1, pos2);
}
/**
*
* @param {*} url eg. https://xxx.myshopify.com/
*/
function getAndroidWebViewCookies(url) {
const cookieDBs = [ `/data/data/${DEVICE.APP.ID}/app_webview/Cookies`, `/data/data/${DEVICE.APP.ID}/app_webview/Default/Cookies` ],
checks = cookieDBs.map(p => File.exists(p)),
host = getHostFromUrl(url);
return new Promise((resolve) => {
PerkdHelper.flushCookie(); // FIXME: merge the function to cookieManager
Promise.all(checks).then((results) => {
const dbSettings = { options: { readOnly: true } };
results.forEach((item, index) => {
if (item) dbSettings.name = cookieDBs[index];
});
SQLite.enablePromise(true);
SQLite.openDatabase(dbSettings).then(db => {
db.transaction(tx => {
const cookies = {};
//
tx.executeSql(`select name,path,expires_utc,host_key,value from cookies where host_key = '${host}'`, [], (tr, { rows }) => {
for (let j = 0; j < rows.length; j += 1) {
const { expires_utc: expires, host_key: domain, name, value, path } = rows.item(j);
cookies[name] = { expiresDate: expires ? (expires - DELTA_EPOCH_IN_MICROSECS) / 1000 : null, domain, name, value, path };
}
resolve(cookies);
}).then(() => {
db.close();
});
});
}).catch((err) => {
$.watch('getCookies', err);
resolve({});
});
});
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment