Advertisement
Guest User

Untitled

a guest
Apr 19th, 2019
110
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 5.06 KB | None | 0 0
  1. import { Component, OnInit, OnDestroy, ViewEncapsulation } from '@angular/core';
  2. import { Subscription } from 'rxjs';
  3. import { WebsocketService } from './websocket.service';
  4. import { Accommodation } from './accommodation/accommodation';
  5.  
  6.  
  7. const WS_URL: string = 'wss://api.night2stay.com/api/v2/websocket';
  8.  
  9. const AUTHENTICATION_KEY: string = '4bd97223-9ad0-4261-821d-3e9ffc356e32';
  10. const ACCOMMODATION_KEY: string = '2ee1edbf-d90f-4785-b9db-5b07ce70a928';
  11.  
  12.  
  13. @Component({
  14. selector: 'app-root',
  15. templateUrl: './app.component.html',
  16. styleUrls: ['./app.component.css'],
  17. providers: [WebsocketService],
  18. encapsulation: ViewEncapsulation.None
  19. })
  20. export class AppComponent implements OnDestroy, OnInit {
  21.  
  22. private wsSubscription: Subscription;
  23. private searchHash: string = null;
  24. private lastid: number = 0;
  25.  
  26. isSearchLocked: boolean = false;
  27.  
  28. accommodations: Accommodation[] = [];
  29.  
  30. constructor(private wsService: WebsocketService) {
  31.  
  32. }
  33.  
  34. subscribe() {
  35.  
  36. this.wsSubscription = this.wsService.createObservableSocket(WS_URL)
  37. .subscribe(
  38. data => {
  39. let dataObject = JSON.parse(data);
  40. let accommodation: Accommodation = null;
  41.  
  42. // 3. Чтобы отличить на какой запрос пришёл ответ, надо сверять «key» отправленного запроса
  43. // и полученного ответа. Они должны совпадать.
  44.  
  45. if (dataObject.key === AUTHENTICATION_KEY)
  46. {
  47. // 1. Поиск запускать, только при успешной авторизации. Т.е. когда придёт ответ со статусом 200(status=”200”).
  48.  
  49. if (dataObject.status === 200){
  50. this.getAccommodations();
  51. } else {
  52. alert("Authentication failed");
  53. }
  54. }
  55. else if (dataObject.key === ACCOMMODATION_KEY && dataObject.status === 200)
  56. {
  57. // 2. Повторять поисковый запрос чаще чем раз в 2 секунды не нужно.
  58.  
  59. setTimeout(() => { this.isSearchLocked = false; }, 2000);
  60.  
  61. // 4. Если поле “hash” в ответе при поиске такой же, как был до этого, то перестраивать список отелей не нужно.
  62.  
  63. if (this.searchHash === dataObject.data.hash)
  64. {
  65. return;
  66. }
  67. else
  68. {
  69. this.accommodations.length = 0;
  70. }
  71.  
  72. this.searchHash = dataObject.data.hash;
  73.  
  74.  
  75. dataObject.data.search.forEach((item: { info: any; items: any; }) => {
  76.  
  77. let info = item.info;
  78. let items = item.items;
  79.  
  80. accommodation = new Accommodation({
  81. id : info.id,
  82. name : info.name,
  83. addr : info.addr,
  84. img : info.img,
  85. stars: info.cat ? null : info.cat + 3,
  86.  
  87. currency: items[0][0].commerce.currency,
  88. originalPrice: items[0][0].commerce.payment,
  89. discount: items[0][0].commerce.discount,
  90. discountPrice: items[0][0].commerce.tpayment
  91. });
  92.  
  93. console.log(accommodation);
  94.  
  95. if (this.lastid > dataObject.data.found)
  96. this.lastid = dataObject.data.found;
  97.  
  98. this.accommodations.push(accommodation);
  99. });
  100.  
  101. }
  102.  
  103. },
  104. err => {console.log( err);},
  105. () => {
  106. console.log('The observable stream is complete');
  107. this.isSearchLocked = false;
  108. }
  109. );
  110.  
  111. }
  112.  
  113. authenticate () {
  114. this.isSearchLocked = true;
  115.  
  116. let authMessage = `
  117. {
  118. "action":"login",
  119. "data": {
  120. "key":"123123 ",
  121. "wlcompany": "CMPN00000053"
  122. },
  123. "key":"${AUTHENTICATION_KEY}",
  124. "type":"account"
  125. }`
  126.  
  127. if(!this.wsService.ws || !this.wsService.sendMessage(authMessage))
  128. {
  129. this.resubscribe();
  130. }
  131. }
  132.  
  133. getAccommodations() {
  134. this.isSearchLocked = true;
  135.  
  136. let query = `
  137. {
  138. "action": "accommodation",
  139. "data": {
  140. "place": {"in": "CI266088ZZ"},
  141. "date": {"in": 1551042000000,"out": 1551301200000},
  142. "families": [{"adults": 2}],
  143. "lastid": "${this.lastid}",
  144. "num": 5
  145. },
  146. "key": "${ACCOMMODATION_KEY}",
  147. "type": "service"
  148. }`
  149.  
  150. if(!this.wsService.ws || !this.wsService.sendMessage(query))
  151. {
  152. this.resubscribe()
  153. }
  154. }
  155.  
  156. resubscribe() {
  157. if (this.wsSubscription)
  158. this.wsSubscription.unsubscribe();
  159.  
  160. this.subscribe();
  161. this.wsService.ws.onopen = () => {
  162. this.authenticate();
  163. };
  164. }
  165.  
  166. getPrev5() {
  167. this.lastid = (this.lastid < 5) ? 0 : (this.lastid - 5);
  168. this.getAccommodations();
  169. }
  170.  
  171. getNext5() {
  172.  
  173. if (this.accommodations.length == 0)
  174. this.lastid = 0;
  175. else
  176. this.lastid = this.lastid + 5;
  177.  
  178. this.getAccommodations();
  179. }
  180.  
  181. ngOnInit() {
  182. this.getNext5();
  183. }
  184.  
  185. ngOnDestroy() {
  186. this.wsSubscription.unsubscribe();
  187. }
  188.  
  189. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement