forked from acheong08/ChatGPT-to-API
-
Notifications
You must be signed in to change notification settings - Fork 1
/
main.go
114 lines (104 loc) · 2.45 KB
/
main.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
package main
import (
"bufio"
"freechatgpt/internal/tokens"
"log"
"os"
"strings"
"time"
"github.com/acheong08/OpenAIAuth/auth"
"github.com/acheong08/endless"
"github.com/gin-gonic/gin"
"github.com/joho/godotenv"
)
var HOST string
var PORT string
var ACCESS_TOKENS tokens.AccessToken
var proxies []string
func checkProxy() {
// first check for proxies.txt
proxies = []string{}
if _, err := os.Stat("proxies.txt"); err == nil {
// Each line is a proxy, put in proxies array
file, _ := os.Open("proxies.txt")
defer file.Close()
scanner := bufio.NewScanner(file)
for scanner.Scan() {
// Split line by :
proxy := scanner.Text()
proxy_parts := strings.Split(proxy, ":")
if len(proxy_parts) > 1 {
proxies = append(proxies, proxy)
} else {
continue
}
}
}
// if no proxies, then check env http_proxy
if len(proxies) == 0 {
proxy := os.Getenv("http_proxy")
if proxy != "" {
proxies = append(proxies, proxy)
}
}
}
func init() {
_ = godotenv.Load(".env")
go func() {
for {
if os.Getenv("OPENAI_EMAIL") == "" || os.Getenv("OPENAI_PASSWORD") == "" {
time.Sleep(24 * time.Hour * 7)
continue
}
authenticator := auth.NewAuthenticator(os.Getenv("OPENAI_EMAIL"), os.Getenv("OPENAI_PASSWORD"), os.Getenv("http_proxy"))
err := authenticator.Begin()
if err != nil {
log.Println(err)
break
}
puid, err := authenticator.GetPUID()
if err != nil {
break
}
os.Setenv("PUID", puid)
println(puid)
time.Sleep(24 * time.Hour * 7)
}
}()
HOST = os.Getenv("SERVER_HOST")
PORT = os.Getenv("SERVER_PORT")
if PORT == "" {
PORT = os.Getenv("PORT")
}
if HOST == "" {
HOST = "127.0.0.1"
}
if PORT == "" {
PORT = "8080"
}
checkProxy()
readAccounts()
scheduleToken()
}
func main() {
router := gin.Default()
router.Use(cors)
router.GET("/ping", func(c *gin.Context) {
c.JSON(200, gin.H{
"message": "pong",
})
})
admin_routes := router.Group("/admin")
admin_routes.Use(adminCheck)
/// Admin routes
admin_routes.PATCH("/password", passwordHandler)
admin_routes.PATCH("/tokens", tokensHandler)
admin_routes.PATCH("/puid", puidHandler)
admin_routes.PATCH("/openai", openaiHandler)
/// Public routes
router.OPTIONS("/v1/chat/completions", optionsHandler)
router.POST("/v1/chat/completions", Authorization, nightmare)
router.GET("/v1/engines", Authorization, engines_handler)
router.GET("/v1/models", Authorization, engines_handler)
endless.ListenAndServe(HOST+":"+PORT, router)
}