Advertisement
Guest User

Untitled

a guest
Jun 29th, 2018
276
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 14.56 KB | None | 0 0
  1. import { observable, action, reaction, computed } from 'mobx';
  2. import Config from '../Config';
  3. // import { observer } from 'mobx-react/native';
  4. import { AsyncStorage } from 'react-native';
  5. import { persist, create as createPersist } from 'mobx-persist';
  6.  
  7. import { Permissions, Notifications } from 'expo';
  8. import { create } from 'apisauce';
  9.  
  10.  
  11. const serverUrl = `${Config.serverUrl}`;
  12. const waitstaffUrl = `${Config.waitstaffUrl}`;
  13.  
  14. const sauce = create({
  15. baseURL: serverUrl,
  16. headers: {
  17. 'Accept': 'application/json',
  18. 'Content-Type': 'application/json',
  19. },
  20. });
  21.  
  22. class UserStore {
  23. @observable hydrated = false;
  24. // @persist @observable email = 'phatthaisf@gmail.com';
  25. // @persist @observable email = 'abhi@joyup.me';
  26. @persist @observable email = '';
  27. // @persist @observable password = 'SeatjoyMaster1';
  28. @persist @observable password = '';
  29. @observable error = '';
  30. @persist @observable userName = '';
  31.  
  32. @observable budget = null;
  33. @observable adsMessage = '';
  34. @observable timerIsAlive = false;
  35. @observable notificationsPermissions = false;
  36. @observable sliderData = [];
  37. @observable categoryPickerData = [];
  38. @observable chosenProducts = [];
  39. @observable merchantId = 0;
  40. @observable locationId = 0;
  41.  
  42. @persist @observable expoToken = null;
  43.  
  44. @observable response = null;
  45. @persist @observable token = null;
  46. @persist @observable tokenSaveTime = 0;
  47. @persist @observable tokenStoreMS = 2592000000;
  48.  
  49. @persist @observable merchantID = null;
  50.  
  51. /**
  52. *
  53. * @param options {path, token, body, formData, timeout}
  54. * @returns {Promise.<*>}
  55. * @description options принимает следующие параметры: [path*, body*,
  56. * token*, timeout]
  57. * @constructor
  58. */
  59.  
  60. @action
  61. async hydrateComplete () {
  62. this.hydrated = true;
  63.  
  64. await this.removeOldExpoToken();
  65. }
  66.  
  67. @action
  68. setEmail (value) {
  69. this.email = value;
  70. }
  71.  
  72. @action
  73. setPassword (value) {
  74. this.password = value;
  75. }
  76.  
  77. @action
  78. setToken (value) {
  79. this.token = value;
  80. }
  81.  
  82. @action
  83. async login () {
  84. try {
  85. const response = await this.APIRequest({
  86. path: 'login',
  87. body: {
  88. email: this.email,
  89. password: this.password,
  90. },
  91. }, 'POST');
  92. if (response && !response.msg && response.jwt_token) {
  93. this.token = response.jwt_token;
  94. this.tokenSaveTime = !this.tokenSaveTime ? new Date().getTime() : this.tokenSaveTime;
  95. return true;
  96. } else {
  97. this.error = 'Invalid email or password';
  98. return false;
  99. }
  100. } catch (e) {
  101. console.log(e, 'error');
  102. }
  103. }
  104.  
  105. sleep = (time = 2000) => {
  106. this.timerIsAlive = true;
  107. return new Promise(resolve => {
  108. setTimeout(resolve, time);
  109. })
  110. };
  111.  
  112. getAllItems = (menu) => {
  113. let result = []
  114. menu.map((category, categoryIndex) => {
  115. category.items.map((item, index) => {
  116. result.push({item: item, category: category.name ? category.name : ''});
  117. })
  118. })
  119. return result;
  120. }
  121.  
  122. @action
  123. async getSliderData () {
  124. this.sliderData = [];
  125. const url = `https://${waitstaffUrl}menu/square/${this.merchantId}/${this.locationId}`;
  126. const response = await sauce
  127. .get(url)
  128. .then((response) => {return response;})
  129. .catch((e) => {
  130. this.sliderData = [];
  131. });
  132. const allItems = this.getAllItems(response.data.menu);
  133. // console.log(response, 'waitstaff response');
  134. if (response && response.data && response.data.menu && response.data.menu.length && response.data.menu[0] && response.data.menu[0].items && (allItems.length < 13)) {
  135. let tmpSliderData = [];
  136. allItems.map((item) => {
  137. tmpSliderData.push({
  138. _id: item.item._id.toString(),
  139. _id_2: item.item.id.toString(),
  140. image: item.item.image,
  141. name: item.item.name,
  142. category: item.category,
  143. price: item.item.price ? item.item.price : 0
  144. });
  145. });
  146. this.sliderData = tmpSliderData;
  147. // console.log(response, response.data.menu[0].items.length, 'BIIIIIIIIIG 1')
  148. } else if (response && response.data && response.data.menu && response.data.menu.length && response.data.menu[0] && response.data.menu[0].items && (allItems.length > 13)) {
  149. let tmpCategoryPickerData = [];
  150. allItems.map((item) => {
  151. tmpCategoryPickerData.push({
  152. _id: item.item._id.toString(),
  153. _id_2: item.item.id.toString(),
  154. name: item.item.name,
  155. price: item.item.price ? item.item.price : 0,
  156. image: item.item.image,
  157. category: item.category
  158. });
  159. });
  160. this.sliderData = tmpCategoryPickerData
  161. // console.log(response, allItems.length, 'BIIIIIIIIIG 2')
  162. } else {
  163. this.sliderData = [];
  164. }
  165. }
  166.  
  167. @action
  168. async setupPushNotifications () {
  169. this.sleep().then(() => {
  170. this.timerIsAlive = false;
  171. });
  172. this.notificationsPermissions = false;
  173. const { status: existingStatus } = await Permissions.getAsync(Permissions.NOTIFICATIONS);
  174. let finalStatus = existingStatus;
  175.  
  176. if (existingStatus !== 'granted') {
  177. const { status } = await Permissions.askAsync(Permissions.NOTIFICATIONS);
  178. finalStatus = status;
  179. }
  180. this.notificationsPermissions = true
  181. if (finalStatus !== 'granted') {
  182. this.notificationsPermissions = false;
  183. } else {
  184. this.notificationsPermissions = true;
  185. }
  186.  
  187. const token = await Notifications.getExpoPushTokenAsync();
  188. const response = await this.APIRequest({
  189. path: 'api/registerToken',
  190. token: this.token,
  191. body: {
  192. expoToken: token,
  193. },
  194. }, 'POST');
  195.  
  196. if (response && response.id === 'success') {
  197. this.expoToken = token;
  198. }
  199.  
  200. return true;
  201. }
  202.  
  203. @action
  204. async removeOldExpoToken () {
  205. if (!!this.expoToken) {
  206. const response = await this.APIRequest({
  207. path: 'api/removeToken',
  208. token: this.token,
  209. body: {
  210. expoToken: this.expoToken,
  211. },
  212. }, 'POST');
  213.  
  214. this.expoToken = null;
  215. }
  216. }
  217.  
  218. @action
  219. async forgotPassword () {
  220. try {
  221. const response = await this.APIRequest({
  222. path: '/api/forgot-password/',
  223. body: { email: this.email },
  224. }, 'POST');
  225. if (!response.msg && response.jwt_token) {
  226. this.token = response.jwt_token;
  227. return true;
  228. } else {
  229. this.error = 'Failed!';
  230. return false;
  231. }
  232. } catch (e) {
  233. console.log(e, 'error');
  234. }
  235. }
  236.  
  237. @action
  238. async APIRequest (options, method = 'GET', ads, budget) {
  239. const defaultOptions = {
  240. path: '/',
  241. body: {},
  242. token: null,
  243. credentials: 'include',
  244. formData: false,
  245. timeout: 10000,
  246. method: 'GET',
  247. };
  248.  
  249. const assigned = Object.assign(defaultOptions, options); //{...defaultOptions,...options}
  250. // //
  251.  
  252. if (!!assigned.token) {
  253. assigned.body.jwt_token = assigned.token;
  254. delete assigned.token;
  255. }
  256.  
  257.  
  258. let body = JSON.stringify(assigned.body);
  259.  
  260.  
  261. if (assigned.formData) {
  262.  
  263. body = new FormData();
  264.  
  265. _.forIn(assigned.body, (value, key) => {
  266. body.append(key, value);
  267. });
  268. }
  269. try {
  270. let response;
  271. body = JSON.parse(body);
  272.  
  273. if (!ads) {
  274. if (this.chosenProducts && this.chosenProducts.length) {
  275. response = await sauce
  276. .get(assigned.path+'?items='+this.chosenProducts.join(","))
  277. .then((response) => {return response;});
  278. } else {
  279. response = method === 'POST'
  280. ? response = await sauce
  281. .post(assigned.path, body)
  282. .then((response) => {return response;})
  283. : response = await sauce
  284. .get(assigned.path)
  285. .then((response) => {return response;});
  286. }
  287. } else {
  288. let parseBudget = '';
  289. if (budget) {
  290. parseBudget = 'ad_budget=' + budget;
  291. }
  292. const newHeaders = {
  293. 'Content-Type': '*/*',
  294. 'Accept': '*/*',
  295. 'mobile': 'DESKTOP_FEED_STANDARD',
  296. 'Cookie': ';mobile=DESKTOP_FEED_STANDARD;ad_flow=pos;jwt_token=' + this.token + ';' + 'ad_msg=' + encodeURI(ads) + ';' + parseBudget,
  297. };
  298.  
  299. sauce.setHeaders(newHeaders);
  300. response = await sauce
  301. .get(assigned.path, { headers: newHeaders })
  302. .then((response) => {return response;});
  303. }
  304. const responseJson = response.data;
  305. if (response && response.headers && response.headers["set-cookie"]) {
  306. const headers = response.headers["set-cookie"].split(";");
  307. let headersParsed = {};
  308. headers.map((item) => {
  309. if (item.indexOf("merchantId") !== -1 || item.indexOf("locationId") !== -1) {
  310. const split1 = item.split(',');
  311. if (split1.length < 3)
  312. return;
  313.  
  314. const thirdArrayElement = split1[2];
  315.  
  316. const split2 = thirdArrayElement.split("=");
  317.  
  318. if (split2.length < 1)
  319. return;
  320.  
  321. const keyId = split2[0].replace(/ /g, '');
  322.  
  323. const split3 = thirdArrayElement.split("=");
  324.  
  325. if (split3.length < 2)
  326. return;
  327.  
  328. headersParsed[keyId] = split3[1].replace(/ /g, '');
  329. }
  330. });
  331. this.merchantId = headersParsed.merchantId;
  332. this.locationId = headersParsed.locationId;
  333. }
  334. this.parseData(responseJson);
  335.  
  336. // if (headersParsed && headersParsed.locationId && headersParsed.merchantId && response.config.url === `${serverUrl}thread/334_broadcast_messenger_select-products/`) {
  337. // console.log('i am here APIRequest');
  338. // this.getSliderData(headersParsed);
  339. // }
  340. return responseJson;
  341. } catch (error) {
  342. console.log(error, 'erros');
  343. return false;
  344. }
  345. }
  346.  
  347. @action
  348. async sendRequest (path, method = 'GET', ads_msg, budget) {
  349. try {
  350. const response = await this.APIRequest({
  351. path: path,
  352. }, method, ads_msg, budget);
  353. } catch (e) {
  354. console.log(e, 'error');
  355. }
  356. }
  357.  
  358. @action
  359. parseData (data) {
  360. let tmpBodyAnswer = [];
  361. let tmpTextAnswer = [];
  362. let tmpImages = [];
  363. let tmpAdsText = [];
  364. let tmpIframePreview = [];
  365.  
  366. if (!data) {
  367. return data;
  368. }
  369.  
  370. if (data.choices && data.choices.length) {
  371. data.choices.map((item, index) => {
  372. tmpBodyAnswer.push({
  373. button: item.text,
  374. responseApi: item.path,
  375. });
  376. });
  377. }
  378.  
  379. if (data.dashboard) {
  380. for (let keys in data.dashboard.charts) {
  381. if (data.dashboard.charts[ keys ]) {
  382. tmpImages.push(data.dashboard.charts[ keys ]);
  383. }
  384. }
  385. }
  386.  
  387. if (data.messages && data.messages.length) {
  388. data.messages.map((item, index) => {
  389. const parsedHTmlData = this.parseHtmlData(item.text);
  390. tmpTextAnswer.push(parsedHTmlData);
  391. if (item.preview) {
  392. tmpIframePreview.push(item.preview);
  393. }
  394. });
  395. }
  396.  
  397. // console.log(data.meta.name)
  398.  
  399. if (data.meta && data.meta.name) {
  400. this.userName = data.meta.name;
  401. }
  402.  
  403. this.response = {
  404. textAnswer: tmpTextAnswer,
  405. bodyAnswer: tmpBodyAnswer,
  406. images: tmpImages,
  407. iframePreview: tmpIframePreview,
  408. };
  409.  
  410. this.setAnswer(this.response);
  411. }
  412.  
  413. parseHtmlData (text) {
  414. const htmlExists = /<div|ul|ol|li>/g.test(text);
  415. const needTagsExists = /<frame|iframe|svg>/g.test(text);
  416.  
  417. if (!htmlExists || needTagsExists) {
  418. return text;
  419. }
  420.  
  421. return text
  422. .replace(/<\s*div[\s\S]*>\s*([\s\S]*)<\s*\/\s*div\s*>/gi, '$1\n')
  423. .replace(/<\s*li\s*>\s*([\s\S]+?)(?:<\s*\/\s*li\s*>)+?/gi, '$1\n')
  424. .replace(/<\/?[\s\S]+?>/gi, '')
  425. .trim();
  426. }
  427.  
  428. getAnswer () {
  429. return this.response;
  430. }
  431.  
  432. @action
  433. setAnswer (answer) {
  434. this.response = answer;
  435. }
  436.  
  437. @action
  438. async logout (answer) {
  439. await this.removeOldExpoToken();
  440.  
  441. this.email = '';
  442. this.password = '';
  443. this.error = '';
  444. this.token = null;
  445. this.tokenSaveTime= 0;
  446. this.response = null;
  447. }
  448. }
  449.  
  450. const userStore = new UserStore();
  451. export default userStore;
  452.  
  453. const hydrate = createPersist({ storage: AsyncStorage, jsonify: true });
  454. hydrate('user', userStore).then(async () => {
  455. await userStore.hydrateComplete();
  456. }).catch(error => console.log('hydrate error', error));
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement