-
-
Notifications
You must be signed in to change notification settings - Fork 547
/
main.go
281 lines (240 loc) · 7 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
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
/*
* @Author: Vincent Yang
* @Date: 2023-07-01 21:45:34
* @LastEditors: Vincent Yang
* @LastEditTime: 2024-11-01 13:04:50
* @FilePath: /DeepLX/main.go
* @Telegram: https://t.me/missuo
* @GitHub: https://github.com/missuo
*
* Copyright © 2024 by Vincent, All Rights Reserved.
*/
package main
import (
"fmt"
"log"
"net/http"
"net/url"
"os"
"strings"
translate "github.com/OwO-Network/DeepLX/translate"
"github.com/gin-contrib/cors"
"github.com/gin-gonic/gin"
)
func authMiddleware(cfg *Config) gin.HandlerFunc {
return func(c *gin.Context) {
if cfg.Token != "" {
providedTokenInQuery := c.Query("token")
providedTokenInHeader := c.GetHeader("Authorization")
// Compatability with the Bearer token format
if providedTokenInHeader != "" {
parts := strings.Split(providedTokenInHeader, " ")
if len(parts) == 2 {
if parts[0] == "Bearer" || parts[0] == "DeepL-Auth-Key" {
providedTokenInHeader = parts[1]
} else {
providedTokenInHeader = ""
}
} else {
providedTokenInHeader = ""
}
}
if providedTokenInHeader != cfg.Token && providedTokenInQuery != cfg.Token {
c.JSON(http.StatusUnauthorized, gin.H{
"code": http.StatusUnauthorized,
"message": "Invalid access token",
})
c.Abort()
return
}
}
c.Next()
}
}
type PayloadFree struct {
TransText string `json:"text"`
SourceLang string `json:"source_lang"`
TargetLang string `json:"target_lang"`
TagHandling string `json:"tag_handling"`
}
type PayloadAPI struct {
Text []string `json:"text"`
TargetLang string `json:"target_lang"`
SourceLang string `json:"source_lang"`
TagHandling string `json:"tag_handling"`
}
func main() {
cfg := initConfig()
fmt.Printf("DeepL X has been successfully launched! Listening on %v:%v\n", cfg.IP, cfg.Port)
fmt.Println("Developed by sjlleo <i@leo.moe> and missuo <me@missuo.me>.")
// Set Proxy
proxyURL := os.Getenv("PROXY")
if proxyURL == "" {
proxyURL = cfg.Proxy
}
if proxyURL != "" {
proxy, err := url.Parse(proxyURL)
if err != nil {
log.Fatalf("Failed to parse proxy URL: %v", err)
}
http.DefaultTransport = &http.Transport{
Proxy: http.ProxyURL(proxy),
}
}
if cfg.Token != "" {
fmt.Println("Access token is set.")
}
// Setting the application to release mode
gin.SetMode(gin.ReleaseMode)
r := gin.Default()
r.Use(cors.Default())
// Defining the root endpoint which returns the project details
r.GET("/", func(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{
"code": http.StatusOK,
"message": "DeepL Free API, Developed by sjlleo and missuo. Go to /translate with POST. http://github.com/OwO-Network/DeepLX",
})
})
// Free API endpoint, No Pro Account required
r.POST("/translate", authMiddleware(cfg), func(c *gin.Context) {
req := PayloadFree{}
c.BindJSON(&req)
sourceLang := req.SourceLang
targetLang := req.TargetLang
translateText := req.TransText
tagHandling := req.TagHandling
proxyURL := cfg.Proxy
if tagHandling != "" && tagHandling != "html" && tagHandling != "xml" {
c.JSON(http.StatusBadRequest, gin.H{
"code": http.StatusBadRequest,
"message": "Invalid tag_handling value. Allowed values are 'html' and 'xml'.",
})
return
}
result, err := translate.TranslateByDeepLX(sourceLang, targetLang, translateText, tagHandling, proxyURL, "")
if err != nil {
log.Fatalf("Translation failed: %s", err)
}
if result.Code == http.StatusOK {
c.JSON(http.StatusOK, gin.H{
"code": http.StatusOK,
"id": result.ID,
"data": result.Data,
"alternatives": result.Alternatives,
"source_lang": result.SourceLang,
"target_lang": result.TargetLang,
"method": result.Method,
})
} else {
c.JSON(result.Code, gin.H{
"code": result.Code,
"message": result.Message,
})
}
})
// Pro API endpoint, Pro Account required
r.POST("/v1/translate", authMiddleware(cfg), func(c *gin.Context) {
req := PayloadFree{}
c.BindJSON(&req)
sourceLang := req.SourceLang
targetLang := req.TargetLang
translateText := req.TransText
tagHandling := req.TagHandling
proxyURL := cfg.Proxy
dlSession := cfg.DlSession
if tagHandling != "" && tagHandling != "html" && tagHandling != "xml" {
c.JSON(http.StatusBadRequest, gin.H{
"code": http.StatusBadRequest,
"message": "Invalid tag_handling value. Allowed values are 'html' and 'xml'.",
})
return
}
cookie := c.GetHeader("Cookie")
if cookie != "" {
dlSession = strings.Replace(cookie, "dl_session=", "", -1)
}
if dlSession == "" {
c.JSON(http.StatusUnauthorized, gin.H{
"code": http.StatusUnauthorized,
"message": "No dl_session Found",
})
return
} else if strings.Contains(dlSession, ".") {
c.JSON(http.StatusUnauthorized, gin.H{
"code": http.StatusUnauthorized,
"message": "Your account is not a Pro account. Please upgrade your account or switch to a different account.",
})
return
}
result, err := translate.TranslateByDeepLX(sourceLang, targetLang, translateText, tagHandling, proxyURL, dlSession)
if err != nil {
log.Fatalf("Translation failed: %s", err)
}
if result.Code == http.StatusOK {
c.JSON(http.StatusOK, gin.H{
"code": http.StatusOK,
"id": result.ID,
"data": result.Data,
"alternatives": result.Alternatives,
"source_lang": result.SourceLang,
"target_lang": result.TargetLang,
"method": result.Method,
})
} else {
c.JSON(result.Code, gin.H{
"code": result.Code,
"message": result.Message,
})
}
})
// Free API endpoint, Consistent with the official API format
r.POST("/v2/translate", authMiddleware(cfg), func(c *gin.Context) {
proxyURL := cfg.Proxy
var translateText string
var targetLang string
translateText = c.PostForm("text")
targetLang = c.PostForm("target_lang")
if translateText == "" || targetLang == "" {
var jsonData struct {
Text []string `json:"text"`
TargetLang string `json:"target_lang"`
}
if err := c.BindJSON(&jsonData); err != nil {
c.JSON(http.StatusBadRequest, gin.H{
"code": http.StatusBadRequest,
"message": "Invalid request payload",
})
return
}
translateText = strings.Join(jsonData.Text, "\n")
targetLang = jsonData.TargetLang
}
result, err := translate.TranslateByDeepLX("", targetLang, translateText, "", proxyURL, "")
if err != nil {
log.Fatalf("Translation failed: %s", err)
}
if result.Code == http.StatusOK {
c.JSON(http.StatusOK, gin.H{
"translations": []map[string]interface{}{
{
"detected_source_language": result.SourceLang,
"text": result.Data,
},
},
})
} else {
c.JSON(result.Code, gin.H{
"code": result.Code,
"message": result.Message,
})
}
})
// Catch-all route to handle undefined paths
r.NoRoute(func(c *gin.Context) {
c.JSON(http.StatusNotFound, gin.H{
"code": http.StatusNotFound,
"message": "Path not found",
})
})
r.Run(fmt.Sprintf("%v:%v", cfg.IP, cfg.Port))
}