Skip to content

Commit

Permalink
Add timer again
Browse files Browse the repository at this point in the history
  • Loading branch information
bi1101 committed Mar 16, 2024
1 parent 6733db3 commit 21fa973
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 10 deletions.
3 changes: 2 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -9,4 +9,5 @@ freechatgpt
chatgpttoapi
tools/authenticator/.proxies.txt.swp
.env
*.har
*.har
freechatgpt.exe
33 changes: 24 additions & 9 deletions internal/chatgpt/request.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import (
"freechatgpt/typings"
chatgpt_types "freechatgpt/typings/chatgpt"
"io"
"net"
"os"
"strconv"
"strings"
Expand Down Expand Up @@ -371,7 +372,7 @@ func Handler(c *gin.Context, response *http.Response, token string, puid string,
var isWSS = false
var convId string
var respId string
var wssUrl string
//var wssUrl string
var connInfo *connInfo
var wsSeq int
var isWSInterrupt bool = false
Expand All @@ -386,14 +387,24 @@ func Handler(c *gin.Context, response *http.Response, token string, puid string,
}
var wssResponse chatgpt_types.ChatGPTWSSResponse
json.NewDecoder(response.Body).Decode(&wssResponse)
wssUrl = wssResponse.WssUrl
//wssUrl = wssResponse.WssUrl
respId = wssResponse.ResponseId
convId = wssResponse.ConversationId
}

const readTimeout = 2 * time.Second
for {
var line string
var err error
if isWSS {
//println("Reading message from WebSocket")
if connInfo.conn != nil {
connInfo.conn.SetReadDeadline(time.Now().Add(readTimeout))
} else {
// If the connection is nil, respond with an error immediately
c.JSON(500, gin.H{"error": "WebSocket connection is closed or not initialized"})
return "", nil
}
var messageType int
var message []byte
if isWSInterrupt {
Expand All @@ -411,17 +422,21 @@ func Handler(c *gin.Context, response *http.Response, token string, puid string,
reader:
messageType, message, err = connInfo.conn.ReadMessage()
if err != nil {
connInfo.ticker.Stop()
connInfo.conn.Close()
connInfo.conn = nil
err := createWSConn(wssUrl, connInfo, 0)
if err != nil {
if netErr, ok := err.(net.Error); ok && netErr.Timeout() {
println("Read timeout:", err.Error())
connInfo.ticker.Stop()
connInfo.conn.Close()
connInfo.conn = nil
c.JSON(500, gin.H{"error": "WebSocket read took too long"})
} else {
println(err.Error())
connInfo.ticker.Stop()
connInfo.conn.Close()
connInfo.conn = nil
c.JSON(500, gin.H{"error": err.Error()})
return "", nil
}
isWSInterrupt = true
connInfo.conn.WriteMessage(websocket.TextMessage, []byte("{\"type\":\"sequenceAck\",\"sequenceId\":"+strconv.Itoa(wsSeq)+"}"))
continue
}
if messageType == websocket.TextMessage {
var wssMsgResponse chatgpt_types.WSSMsgResponse
Expand Down

0 comments on commit 21fa973

Please sign in to comment.