juice-shop

Форк
0
/
chatbot.component.ts 
119 строк · 3.6 Кб
1
/*
2
 * Copyright (c) 2014-2024 Bjoern Kimminich & the OWASP Juice Shop contributors.
3
 * SPDX-License-Identifier: MIT
4
 */
5

6
import { ChatbotService } from '../Services/chatbot.service'
7
import { UserService } from '../Services/user.service'
8
import { Component, type OnDestroy, type OnInit } from '@angular/core'
9
import { UntypedFormControl } from '@angular/forms'
10
import { library } from '@fortawesome/fontawesome-svg-core'
11
import { faBomb } from '@fortawesome/free-solid-svg-icons'
12
import { FormSubmitService } from '../Services/form-submit.service'
13
import { TranslateService } from '@ngx-translate/core'
14
import { CookieService } from 'ngx-cookie'
15

16
library.add(faBomb)
17

18
enum MessageSources {
19
  user = 'user',
20
  bot = 'bot'
21
}
22

23
interface ChatMessage {
24
  author: MessageSources.user | MessageSources.bot
25
  body: string
26
}
27

28
interface MessageActions {
29
  response: string
30
  namequery: string
31
}
32

33
@Component({
34
  selector: 'app-chatbot',
35
  templateUrl: './chatbot.component.html',
36
  styleUrls: ['./chatbot.component.scss']
37
})
38
export class ChatbotComponent implements OnInit, OnDestroy {
39
  public messageControl: UntypedFormControl = new UntypedFormControl()
40
  public messages: ChatMessage[] = []
41
  public juicyImageSrc: string = 'assets/public/images/ChatbotAvatar.png'
42
  public profileImageSrc: string = 'assets/public/images/uploads/default.svg'
43
  public messageActions: MessageActions = {
44
    response: 'query',
45
    namequery: 'setname'
46
  }
47

48
  public currentAction: string = this.messageActions.response
49

50
  private chatScrollDownTimeoutId: ReturnType<typeof setTimeout> | null = null
51

52
  constructor (private readonly userService: UserService, private readonly chatbotService: ChatbotService, private readonly cookieService: CookieService, private readonly formSubmitService: FormSubmitService, private readonly translate: TranslateService) { }
53

54
  ngOnDestroy (): void {
55
    if (this.chatScrollDownTimeoutId) {
56
      clearTimeout(this.chatScrollDownTimeoutId)
57
    }
58
  }
59

60
  ngOnInit () {
61
    this.chatbotService.getChatbotStatus().subscribe((response) => {
62
      this.messages.push({
63
        author: MessageSources.bot,
64
        body: response.body
65
      })
66
      if (response.action) {
67
        this.currentAction = this.messageActions[response.action]
68
      }
69
    })
70

71
    this.userService.whoAmI().subscribe((user: any) => {
72
      this.profileImageSrc = user.profileImage
73
    }, (err) => {
74
      console.log(err)
75
    })
76
  }
77

78
  handleResponse (response) {
79
    this.messages.push({
80
      author: MessageSources.bot,
81
      body: response.body
82
    })
83
    this.currentAction = this.messageActions[response.action]
84
    if (response.token) {
85
      localStorage.setItem('token', response.token)
86
      const expires = new Date()
87
      expires.setHours(expires.getHours() + 8)
88
      this.cookieService.put('token', response.token, { expires })
89
    }
90
  }
91

92
  sendMessage () {
93
    const messageBody = this.messageControl.value
94
    if (messageBody) {
95
      this.messages.push({
96
        author: MessageSources.user,
97
        body: messageBody
98
      })
99
      this.messageControl.setValue('')
100
      this.chatbotService.getChatbotStatus().subscribe((response) => {
101
        if (!response.status && !response.action) {
102
          this.messages.push({
103
            author: MessageSources.bot,
104
            body: response.body
105
          })
106
        } else {
107
          this.chatbotService.getResponse(this.currentAction, messageBody).subscribe((response) => {
108
            this.handleResponse(response)
109
          })
110
        }
111
        this.chatScrollDownTimeoutId = setTimeout(() => {
112
          const chat = document.getElementById('chat-window')
113
          chat.scrollTop = chat.scrollHeight
114
          this.chatScrollDownTimeoutId = null
115
        }, 250)
116
      })
117
    }
118
  }
119
}
120

Использование cookies

Мы используем файлы cookie в соответствии с Политикой конфиденциальности и Политикой использования cookies.

Нажимая кнопку «Принимаю», Вы даете АО «СберТех» согласие на обработку Ваших персональных данных в целях совершенствования нашего веб-сайта и Сервиса GitVerse, а также повышения удобства их использования.

Запретить использование cookies Вы можете самостоятельно в настройках Вашего браузера.