Skip to content

Commit

Permalink
添加获取ghu服务
Browse files Browse the repository at this point in the history
  • Loading branch information
ljnchn committed Jan 27, 2024
1 parent d6ac6a8 commit 8451197
Show file tree
Hide file tree
Showing 9 changed files with 151 additions and 214 deletions.
4 changes: 2 additions & 2 deletions Dockerfile
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,8 @@ FROM alpine:latest

WORKDIR /app

COPY ./dist/copilot2gpt-linux-386-v0.5.tar.gz .
COPY ./dist/copilot2gpt-linux-386-v0.6.tar.gz .

RUN tar -xf copilot2gpt-linux-386-v0.5.tar.gz
RUN tar -xf copilot2gpt-linux-386-v0.6.tar.gz

CMD ["./copilot2gpt"]
10 changes: 10 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,14 +10,24 @@

## ghu token 获取

### 通过 cocoilot 获取

点击链接:[cocopilot](https://cocopilot.org/copilot/token),根据提示拿到 ghu_xxxx 格式的 token。务必保存好,不要泄露给其他人。

### 自己部署应用获取

`/auth`

## docker 部署

``` shell

docker run -d -p 8081:8081 ersichub/copilot2gpt

- 部署授权服务

docker run -d -p 8081:8081 -e CLIENT_ID="Iv1.b507a08c87ecfe98" ersichub/copilot2gpt

```

## 下载程序
Expand Down
28 changes: 28 additions & 0 deletions assets.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
package main

import (
"time"

"github.com/jessevdk/go-assets"
)

var _Assetsf86c9bbb3d0fc4401249716089ed36f50263323a = "<!doctype html>\n<html>\n<h1>\n {{ .title }}\n</h1>\n打开链接 <a href=\"https://github.com/login/device\" target=\"__blank\">https://github.com/login/device</a>\n<!-- <button onclick=\"copyToClipboard()\">复制</button> -->\n<p>输入:<input type=\"text\" value=\"{{ .userCode }}\" disabled=\"disabled\" id=\"code\" size=\"10\"></p>\n<p>获取有延迟,填写完毕请勿刷新页面</p>\n<p>ghu: <input type=\"text\" value=\"获取中\" id=\"ghu\" size=\"50\"></p>\n<script>\n var deviceCode = \"{{ .deviceCode }}\"\n\n let intervalId = null;\n let count = 0;\n\n // 每5秒执行一次的函数\n function polling() {\n count++;\n console.log('Polling: ' + count);\n var xhr = new XMLHttpRequest();\n xhr.open(\"POST\", \"/auth/check\", true);\n var formData = new FormData();\n formData.append(\"deviceCode\", deviceCode);\n\n xhr.onreadystatechange = function () {\n console.log(xhr.responseText);\n if (xhr.status >= 200 && xhr.status < 300) {\n if (xhr.responseText.length > 0) { \n try {\n var data = JSON.parse(xhr.responseText);\n // 现在你可以使用解析后的数据了\n console.log(data);\n if (data.code == \"0\") {\n stopPolling();\n var inputElement = document.getElementById('ghu');\n inputElement.value = data.data; // 将值更改为你想要的任何字符串\n }\n } catch (e) {\n console.error(\"解析JSON数据时出错: \", e);\n }\n }\n } else {\n console.error(\"请求失败,HTTP状态码: \", xhr.status);\n }\n };\n xhr.send(formData);\n }\n\n // 15分钟后停止轮询的函数\n function stopPolling() {\n clearInterval(intervalId);\n console.log('Polling stopped');\n }\n\n // 开始轮询\n intervalId = setInterval(polling, 6 * 1000); // 5秒\n\n // 15分钟后停止轮询\n setTimeout(stopPolling, 15 * 60 * 1000); // 15分钟\n\n function copyToClipboard() {\n let text = document.getElementById('code').innerHTML;\n const copyContent = async () => {\n try {\n await navigator.clipboard.writeText(text);\n console.log('Content copied to clipboard');\n } catch (err) {\n console.error('Failed to copy: ', err);\n }\n }\n }\n\n</script>\n\n</html>"

// Assets returns go-assets FileSystem
var Assets = assets.NewFileSystem(map[string][]string{"/": []string{"html"}, "/html": []string{"auth.tmpl"}}, map[string]*assets.File{
"/": &assets.File{
Path: "/",
FileMode: 0x800001ed,
Mtime: time.Unix(1706329587, 1706329587321956499),
Data: nil,
}, "/html": &assets.File{
Path: "/html",
FileMode: 0x800001ed,
Mtime: time.Unix(1706329545, 1706329545851955289),
Data: nil,
}, "/html/auth.tmpl": &assets.File{
Path: "/html/auth.tmpl",
FileMode: 0x1a4,
Mtime: time.Unix(1706331887, 1706331887582267463),
Data: []byte(_Assetsf86c9bbb3d0fc4401249716089ed36f50263323a),
}}, "")
1 change: 1 addition & 0 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ require (
github.com/go-playground/validator/v10 v10.16.0 // indirect
github.com/goccy/go-json v0.10.2 // indirect
github.com/google/uuid v1.5.0 // indirect
github.com/jessevdk/go-assets v0.0.0-20160921144138-4f4301a06e15 // indirect
github.com/joho/godotenv v1.5.1 // indirect
github.com/json-iterator/go v1.1.12 // indirect
github.com/klauspost/cpuid/v2 v2.2.6 // indirect
Expand Down
2 changes: 2 additions & 0 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,8 @@ github.com/google/go-cmp v0.5.5/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/
github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg=
github.com/google/uuid v1.5.0 h1:1p67kYwdtXjb0gL0BPiP1Av9wiZPo5A8z2cWkTZ+eyU=
github.com/google/uuid v1.5.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
github.com/jessevdk/go-assets v0.0.0-20160921144138-4f4301a06e15 h1:cW/amwGEJK5MSKntPXRjX4dxs/nGxGT8gXKIsKFmHGc=
github.com/jessevdk/go-assets v0.0.0-20160921144138-4f4301a06e15/go.mod h1:Fdm/oWRW+CH8PRbLntksCNtmcCBximKPkVQYvmMl80k=
github.com/joho/godotenv v1.5.1 h1:7eLL/+HRGLY0ldzfGMeQkb7vMd0as4CfYvUVzLqw0N0=
github.com/joho/godotenv v1.5.1/go.mod h1:f4LDr5Voq0i2e/R5DDNOoa2zzDfwtkZa6DnEwAbqwq4=
github.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnrnM=
Expand Down
76 changes: 76 additions & 0 deletions html/auth.tmpl
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
<!doctype html>
<html>
<h1>
{{ .title }}
</h1>
打开链接 <a href="https://github.com/login/device" target="__blank">https://github.com/login/device</a>
<!-- <button onclick="copyToClipboard()">复制</button> -->
<p>输入:<input type="text" value="{{ .userCode }}" disabled="disabled" id="code" size="10"></p>
<p>获取有延迟,填写完毕请勿刷新页面</p>
<p>ghu: <input type="text" value="获取中" id="ghu" size="50"></p>
<script>
var deviceCode = "{{ .deviceCode }}"

let intervalId = null;
let count = 0;

// 每5秒执行一次的函数
function polling() {
count++;
console.log('Polling: ' + count);
var xhr = new XMLHttpRequest();
xhr.open("POST", "/auth/check", true);
var formData = new FormData();
formData.append("deviceCode", deviceCode);

xhr.onreadystatechange = function () {
console.log(xhr.responseText);
if (xhr.status >= 200 && xhr.status < 300) {
if (xhr.responseText.length > 0) {
try {
var data = JSON.parse(xhr.responseText);
// 现在你可以使用解析后的数据了
console.log(data);
if (data.code == "0") {
stopPolling();
var inputElement = document.getElementById('ghu');
inputElement.value = data.data; // 将值更改为你想要的任何字符串
}
} catch (e) {
console.error("解析JSON数据时出错: ", e);
}
}
} else {
console.error("请求失败,HTTP状态码: ", xhr.status);
}
};
xhr.send(formData);
}

// 15分钟后停止轮询的函数
function stopPolling() {
clearInterval(intervalId);
console.log('Polling stopped');
}

// 开始轮询
intervalId = setInterval(polling, 6 * 1000); // 5秒

// 15分钟后停止轮询
setTimeout(stopPolling, 15 * 60 * 1000); // 15分钟

function copyToClipboard() {
let text = document.getElementById('code').innerHTML;
const copyContent = async () => {
try {
await navigator.clipboard.writeText(text);
console.log('Content copied to clipboard');
} catch (err) {
console.error('Failed to copy: ', err);
}
}
}

</script>

</html>
41 changes: 32 additions & 9 deletions main.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import (
"encoding/hex"
"encoding/json"
"fmt"
"html/template"
"io"
"log"
"net/http"
Expand Down Expand Up @@ -43,7 +44,7 @@ type ModelList struct {
Data []Model `json:"data"`
}

var version = "v0.5"
var version = "v0.6"
var port = "8081"
var client_id = ""

Expand All @@ -58,6 +59,10 @@ func main() {
}

log.Printf("Server is running on port %s, version: %s\n", port, version)
client_id = os.Getenv("CLIENT_ID")
if client_id != "" {
log.Printf("client_id: %s\n", client_id)
}

gin.SetMode(gin.ReleaseMode)

Expand Down Expand Up @@ -110,9 +115,13 @@ func main() {
})

// 获取ghu
client_id = os.Getenv("CLIENT_ID")

r.LoadHTMLGlob("templates/**/*")
t, err := loadTemplate()
if err != nil {
panic(err)
}
r.SetHTMLTemplate(t)

r.GET("/auth", func(c *gin.Context) {
if client_id == "" {
c.String(http.StatusOK, `clent id null`)
Expand All @@ -129,8 +138,8 @@ func main() {
fmt.Println("Device Code: ", deviceCode)
fmt.Println("User Code: ", userCode)

c.HTML(http.StatusOK, "auth/index.tmpl", gin.H{
"title": "auth index",
c.HTML(http.StatusOK, "/html/auth.tmpl", gin.H{
"title": "Get Copilot Token",
"deviceCode": deviceCode,
"userCode": userCode,
})
Expand Down Expand Up @@ -487,9 +496,6 @@ func checkUserCode(deviceCode string) (string, error) {
body.Set("device_code", deviceCode)
body.Set("grant_type", "urn:ietf:params:oauth:grant-type:device_code")
res, err := handleRequest("POST", body, requestUrl, headers)
fmt.Print(body)
fmt.Printf("")
fmt.Printf(res)
if err != nil {
return "", err
}
Expand All @@ -498,7 +504,6 @@ func checkUserCode(deviceCode string) (string, error) {
}

func handleRequest(method string, body url.Values, requestUrl string, headers map[string]string) (string, error) {
fmt.Print(body, requestUrl)
client := &http.Client{}

req, err := http.NewRequest(method, requestUrl, bytes.NewBuffer([]byte(body.Encode())))
Expand All @@ -521,3 +526,21 @@ func handleRequest(method string, body url.Values, requestUrl string, headers ma

return string(respBody), nil
}

func loadTemplate() (*template.Template, error) {
t := template.New("")
for name, file := range Assets.Files {
if file.IsDir() || !strings.HasSuffix(name, ".tmpl") {
continue
}
h, err := io.ReadAll(file)
if err != nil {
return nil, err
}
t, err = t.New(name).Parse(string(h))
if err != nil {
return nil, err
}
}
return t, nil
}
30 changes: 0 additions & 30 deletions templates/auth/index.tmpl

This file was deleted.

Loading

0 comments on commit 8451197

Please sign in to comment.