Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import { observable, action, reaction, computed } from 'mobx';
- import Config from '../Config';
- // import { observer } from 'mobx-react/native';
- import { AsyncStorage } from 'react-native';
- import { persist, create as createPersist } from 'mobx-persist';
- import { Permissions, Notifications } from 'expo';
- import { create } from 'apisauce';
- const serverUrl = `${Config.serverUrl}`;
- const waitstaffUrl = `${Config.waitstaffUrl}`;
- const sauce = create({
- baseURL: serverUrl,
- headers: {
- 'Accept': 'application/json',
- 'Content-Type': 'application/json',
- },
- });
- class UserStore {
- @observable hydrated = false;
- // @persist @observable email = 'phatthaisf@gmail.com';
- // @persist @observable email = 'abhi@joyup.me';
- @persist @observable email = '';
- // @persist @observable password = 'SeatjoyMaster1';
- @persist @observable password = '';
- @observable error = '';
- @persist @observable userName = '';
- @observable budget = null;
- @observable adsMessage = '';
- @observable timerIsAlive = false;
- @observable notificationsPermissions = false;
- @observable sliderData = [];
- @observable categoryPickerData = [];
- @observable chosenProducts = [];
- @observable merchantId = 0;
- @observable locationId = 0;
- @persist @observable expoToken = null;
- @observable response = null;
- @persist @observable token = null;
- @persist @observable tokenSaveTime = 0;
- @persist @observable tokenStoreMS = 2592000000;
- @persist @observable merchantID = null;
- /**
- *
- * @param options {path, token, body, formData, timeout}
- * @returns {Promise.<*>}
- * @description options принимает следующие параметры: [path*, body*,
- * token*, timeout]
- * @constructor
- */
- @action
- async hydrateComplete () {
- this.hydrated = true;
- await this.removeOldExpoToken();
- }
- @action
- setEmail (value) {
- this.email = value;
- }
- @action
- setPassword (value) {
- this.password = value;
- }
- @action
- setToken (value) {
- this.token = value;
- }
- @action
- async login () {
- try {
- const response = await this.APIRequest({
- path: 'login',
- body: {
- email: this.email,
- password: this.password,
- },
- }, 'POST');
- if (response && !response.msg && response.jwt_token) {
- this.token = response.jwt_token;
- this.tokenSaveTime = !this.tokenSaveTime ? new Date().getTime() : this.tokenSaveTime;
- return true;
- } else {
- this.error = 'Invalid email or password';
- return false;
- }
- } catch (e) {
- console.log(e, 'error');
- }
- }
- sleep = (time = 2000) => {
- this.timerIsAlive = true;
- return new Promise(resolve => {
- setTimeout(resolve, time);
- })
- };
- getAllItems = (menu) => {
- let result = []
- menu.map((category, categoryIndex) => {
- category.items.map((item, index) => {
- result.push({item: item, category: category.name ? category.name : ''});
- })
- })
- return result;
- }
- @action
- async getSliderData () {
- this.sliderData = [];
- const url = `https://${waitstaffUrl}menu/square/${this.merchantId}/${this.locationId}`;
- const response = await sauce
- .get(url)
- .then((response) => {return response;})
- .catch((e) => {
- this.sliderData = [];
- });
- const allItems = this.getAllItems(response.data.menu);
- // console.log(response, 'waitstaff response');
- if (response && response.data && response.data.menu && response.data.menu.length && response.data.menu[0] && response.data.menu[0].items && (allItems.length < 13)) {
- let tmpSliderData = [];
- allItems.map((item) => {
- tmpSliderData.push({
- _id: item.item._id.toString(),
- _id_2: item.item.id.toString(),
- image: item.item.image,
- name: item.item.name,
- category: item.category,
- price: item.item.price ? item.item.price : 0
- });
- });
- this.sliderData = tmpSliderData;
- // console.log(response, response.data.menu[0].items.length, 'BIIIIIIIIIG 1')
- } else if (response && response.data && response.data.menu && response.data.menu.length && response.data.menu[0] && response.data.menu[0].items && (allItems.length > 13)) {
- let tmpCategoryPickerData = [];
- allItems.map((item) => {
- tmpCategoryPickerData.push({
- _id: item.item._id.toString(),
- _id_2: item.item.id.toString(),
- name: item.item.name,
- price: item.item.price ? item.item.price : 0,
- image: item.item.image,
- category: item.category
- });
- });
- this.sliderData = tmpCategoryPickerData
- // console.log(response, allItems.length, 'BIIIIIIIIIG 2')
- } else {
- this.sliderData = [];
- }
- }
- @action
- async setupPushNotifications () {
- this.sleep().then(() => {
- this.timerIsAlive = false;
- });
- this.notificationsPermissions = false;
- const { status: existingStatus } = await Permissions.getAsync(Permissions.NOTIFICATIONS);
- let finalStatus = existingStatus;
- if (existingStatus !== 'granted') {
- const { status } = await Permissions.askAsync(Permissions.NOTIFICATIONS);
- finalStatus = status;
- }
- this.notificationsPermissions = true
- if (finalStatus !== 'granted') {
- this.notificationsPermissions = false;
- } else {
- this.notificationsPermissions = true;
- }
- const token = await Notifications.getExpoPushTokenAsync();
- const response = await this.APIRequest({
- path: 'api/registerToken',
- token: this.token,
- body: {
- expoToken: token,
- },
- }, 'POST');
- if (response && response.id === 'success') {
- this.expoToken = token;
- }
- return true;
- }
- @action
- async removeOldExpoToken () {
- if (!!this.expoToken) {
- const response = await this.APIRequest({
- path: 'api/removeToken',
- token: this.token,
- body: {
- expoToken: this.expoToken,
- },
- }, 'POST');
- this.expoToken = null;
- }
- }
- @action
- async forgotPassword () {
- try {
- const response = await this.APIRequest({
- path: '/api/forgot-password/',
- body: { email: this.email },
- }, 'POST');
- if (!response.msg && response.jwt_token) {
- this.token = response.jwt_token;
- return true;
- } else {
- this.error = 'Failed!';
- return false;
- }
- } catch (e) {
- console.log(e, 'error');
- }
- }
- @action
- async APIRequest (options, method = 'GET', ads, budget) {
- const defaultOptions = {
- path: '/',
- body: {},
- token: null,
- credentials: 'include',
- formData: false,
- timeout: 10000,
- method: 'GET',
- };
- const assigned = Object.assign(defaultOptions, options); //{...defaultOptions,...options}
- // //
- if (!!assigned.token) {
- assigned.body.jwt_token = assigned.token;
- delete assigned.token;
- }
- let body = JSON.stringify(assigned.body);
- if (assigned.formData) {
- body = new FormData();
- _.forIn(assigned.body, (value, key) => {
- body.append(key, value);
- });
- }
- try {
- let response;
- body = JSON.parse(body);
- if (!ads) {
- if (this.chosenProducts && this.chosenProducts.length) {
- response = await sauce
- .get(assigned.path+'?items='+this.chosenProducts.join(","))
- .then((response) => {return response;});
- } else {
- response = method === 'POST'
- ? response = await sauce
- .post(assigned.path, body)
- .then((response) => {return response;})
- : response = await sauce
- .get(assigned.path)
- .then((response) => {return response;});
- }
- } else {
- let parseBudget = '';
- if (budget) {
- parseBudget = 'ad_budget=' + budget;
- }
- const newHeaders = {
- 'Content-Type': '*/*',
- 'Accept': '*/*',
- 'mobile': 'DESKTOP_FEED_STANDARD',
- 'Cookie': ';mobile=DESKTOP_FEED_STANDARD;ad_flow=pos;jwt_token=' + this.token + ';' + 'ad_msg=' + encodeURI(ads) + ';' + parseBudget,
- };
- sauce.setHeaders(newHeaders);
- response = await sauce
- .get(assigned.path, { headers: newHeaders })
- .then((response) => {return response;});
- }
- const responseJson = response.data;
- if (response && response.headers && response.headers["set-cookie"]) {
- const headers = response.headers["set-cookie"].split(";");
- let headersParsed = {};
- headers.map((item) => {
- if (item.indexOf("merchantId") !== -1 || item.indexOf("locationId") !== -1) {
- const split1 = item.split(',');
- if (split1.length < 3)
- return;
- const thirdArrayElement = split1[2];
- const split2 = thirdArrayElement.split("=");
- if (split2.length < 1)
- return;
- const keyId = split2[0].replace(/ /g, '');
- const split3 = thirdArrayElement.split("=");
- if (split3.length < 2)
- return;
- headersParsed[keyId] = split3[1].replace(/ /g, '');
- }
- });
- this.merchantId = headersParsed.merchantId;
- this.locationId = headersParsed.locationId;
- }
- this.parseData(responseJson);
- // if (headersParsed && headersParsed.locationId && headersParsed.merchantId && response.config.url === `${serverUrl}thread/334_broadcast_messenger_select-products/`) {
- // console.log('i am here APIRequest');
- // this.getSliderData(headersParsed);
- // }
- return responseJson;
- } catch (error) {
- console.log(error, 'erros');
- return false;
- }
- }
- @action
- async sendRequest (path, method = 'GET', ads_msg, budget) {
- try {
- const response = await this.APIRequest({
- path: path,
- }, method, ads_msg, budget);
- } catch (e) {
- console.log(e, 'error');
- }
- }
- @action
- parseData (data) {
- let tmpBodyAnswer = [];
- let tmpTextAnswer = [];
- let tmpImages = [];
- let tmpAdsText = [];
- let tmpIframePreview = [];
- if (!data) {
- return data;
- }
- if (data.choices && data.choices.length) {
- data.choices.map((item, index) => {
- tmpBodyAnswer.push({
- button: item.text,
- responseApi: item.path,
- });
- });
- }
- if (data.dashboard) {
- for (let keys in data.dashboard.charts) {
- if (data.dashboard.charts[ keys ]) {
- tmpImages.push(data.dashboard.charts[ keys ]);
- }
- }
- }
- if (data.messages && data.messages.length) {
- data.messages.map((item, index) => {
- const parsedHTmlData = this.parseHtmlData(item.text);
- tmpTextAnswer.push(parsedHTmlData);
- if (item.preview) {
- tmpIframePreview.push(item.preview);
- }
- });
- }
- // console.log(data.meta.name)
- if (data.meta && data.meta.name) {
- this.userName = data.meta.name;
- }
- this.response = {
- textAnswer: tmpTextAnswer,
- bodyAnswer: tmpBodyAnswer,
- images: tmpImages,
- iframePreview: tmpIframePreview,
- };
- this.setAnswer(this.response);
- }
- parseHtmlData (text) {
- const htmlExists = /<div|ul|ol|li>/g.test(text);
- const needTagsExists = /<frame|iframe|svg>/g.test(text);
- if (!htmlExists || needTagsExists) {
- return text;
- }
- return text
- .replace(/<\s*div[\s\S]*>\s*([\s\S]*)<\s*\/\s*div\s*>/gi, '$1\n')
- .replace(/<\s*li\s*>\s*([\s\S]+?)(?:<\s*\/\s*li\s*>)+?/gi, '$1\n')
- .replace(/<\/?[\s\S]+?>/gi, '')
- .trim();
- }
- getAnswer () {
- return this.response;
- }
- @action
- setAnswer (answer) {
- this.response = answer;
- }
- @action
- async logout (answer) {
- await this.removeOldExpoToken();
- this.email = '';
- this.password = '';
- this.error = '';
- this.token = null;
- this.tokenSaveTime= 0;
- this.response = null;
- }
- }
- const userStore = new UserStore();
- export default userStore;
- const hydrate = createPersist({ storage: AsyncStorage, jsonify: true });
- hydrate('user', userStore).then(async () => {
- await userStore.hydrateComplete();
- }).catch(error => console.log('hydrate error', error));
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement