From b7396f39819b6502fdb4cc36d01c58b8d099f1b8 Mon Sep 17 00:00:00 2001 From: Alex Borisov <79996669747@ya.ru> Date: Fri, 29 Nov 2024 13:33:06 +0300 Subject: [PATCH 1/4] rm junk --- .DS_Store | Bin 8196 -> 0 bytes docker-compose.yaml | 28 ---------------------------- job-manager/.DS_Store | Bin 6148 -> 0 bytes telegram-bot/.DS_Store | Bin 6148 -> 0 bytes 4 files changed, 28 deletions(-) delete mode 100644 .DS_Store delete mode 100644 docker-compose.yaml delete mode 100644 job-manager/.DS_Store delete mode 100644 telegram-bot/.DS_Store diff --git a/.DS_Store b/.DS_Store deleted file mode 100644 index 924bdc10acb007e5887e0ebb215935dd321111c6..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 8196 zcmeHM&rcIU6n-N`wxXsc8aSCnq8uy&QBdNgmUcBU`|w$y|e)R|`H+s=D$-n{S4?sT?9#L~6g7*RhF zS*QXNy=b;5LN4m2vPbnC1v1!EsW6tEZz9 zrKU9u7zX}J2E_BhMirP+*pL`LI?#ki0ALK=VZn7mTmWr_DTNJ*kf1PW3Y4Zy9Wj_R zN58G~QVJUqr8zNm_+ZL2QzsM_ddK*7s7@>;(X@sE!@y<+#MwPYr>HbDzd3R!AV>Er1So4V-S3M>KL(O@ zdWm&z}o$LayX9Fjw`Dv#*BfeedyyP~o9rtE2U!P4Jp5k8M6uo>kG$`isP`Q1p z=;e4l&1+uH4{ftjV8!F{*+k#+^4amEefrG!O443FH!+d4$0sLOR^rx?!IAUVW*19k zk3W{dF!em711h*CJi$c=fwoZ3E`RIHN>57S%kj5EGASMS)6?~PmMw|wYKS;H@b@5F z^-A0;KwB`?OZSju7s)PT33#Xlk#3!Zp24B3(VBYXQ*R2dPcDVaF=AXj+U>RV2z!d} zF^Q=8Rswgr<_A@19HSdp!iWLw2r5TRJ{GZqZ)I9Sq&{x38kYJzdYTL0r#dt$_z269 zww|siPZ2S~b|1!R-Z}x;6*I`|oD%gtkJ8f_J@~VG^_hIIY&oXR=XSa}n?yF;(|$0K zrxI!bQ9Iyg7_;RR{2RA>WOyy9xb*R9J1X>a*e6~Ntjcsmj;*Jp6aAL7Ot(+VhMQNU z(3G8Hpi2(bFV6oLqu>AUoI^8`VZbo3>lk3MOg59ow3@#qH_lL;wQbb9sGR diff --git a/docker-compose.yaml b/docker-compose.yaml deleted file mode 100644 index 0b2fc5a..0000000 --- a/docker-compose.yaml +++ /dev/null @@ -1,28 +0,0 @@ -services: - dragonfly: - image: "docker.dragonflydb.io/dragonflydb/dragonfly" - ulimits: - memlock: -1 - ports: - - "6379:6379" - # For better performance, consider `host` mode instead `port` to avoid docker NAT. - # `host` mode is NOT currently supported in Swarm Mode. - # https://docs.docker.com/compose/compose-file/compose-file-v3/#network_mode - # network_mode: "host" - volumes: - - ./data/dragonflydata:/data -# ! -# own telegram api server -# needed to download / upload large files -# Container link: https://github.com/aiogram/telegram-bot-api -# Info about limitations: https://core.telegram.org/bots/api#using-a-local-bot-api-server -# -# telegram-bot-api: -# image: aiogram/telegram-bot-api:latest -# environment: -# TELEGRAM_API_ID: "" -# TELEGRAM_API_HASH: "" -# volumes: -# - ./data/telegram-bot-api:/var/lib/telegram-bot-api -# ports: -# - "8081:8081" diff --git a/job-manager/.DS_Store b/job-manager/.DS_Store deleted file mode 100644 index e32d6ef73c8ed081ddea266979757454f8e34db8..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 6148 zcmeHKJ5B>J5S@V_S)xfv=_}+0CR$nqibM_hh!lx7O$s{K+=Px(&~YF--h2QVR-%g# znvuqDJRk4wlh*bS5l{Ea3DKB{5>$}I7!Yv}hK@XW1Y})fwYi_n7X5ZNu*~0d$-AG> zg6^PeYTiFxzg@P`ZQphCO+SY>-8@~bULRi0zh^9e$=I#G7)p=NC=Uq+f`MQl7zhRq z$^g!6k#uSpV=xd51OuN8$o`O_g2k~K>ehilTL7S3qg7x_FCjJAu{c&kL?CRXKr3Z$ zG1$uC&z@HttD%(>d-K8mDp23iJ=Z910o{{p|vV3XgL#4H#H z2L2fXJnClM6d&bh>yOWqvo=F-p(2u3#el$WE&-UxK60i(i)XQsR~)OMtRj9b2gXG} L35g*XH~<6hMJO!N diff --git a/telegram-bot/.DS_Store b/telegram-bot/.DS_Store deleted file mode 100644 index d9a7b66c6621423f385b11f80e765dad0b17a070..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 6148 zcmeHKOG*SW5UtV{8r;m%Wjuh3xj`ISJir`4r>8*|J!C)!2HfNtUdV%Z3wORsmC}uk zyAejJAbClBQk@5#q=<+YyKYW2Bcd8jkYz9-qMkIJnDZHsWsUA>-M1i49w^!8B zik@jT{Qhrc|1e*!(`H+CbbI$Q4A`WmY5UYdSHEAqUViM~uE+N7SNryHxVEM!dAxH5 zoB?OR8E^&;#(-VZ_4&av_`=SBGjOa7$oUY^1fyYAEJp{rQUU-gsEc4MwS>e3!)TZl zVS%uQ0yUJa#9$4FKA2xL%!(RLY{ds#=C9&~OLnXuiaT*s^xhe82F47W>U1Xe{|$bb z$s&Io;xlK!8Te-maMdiE1vX`O>yPcpT^rEu(L}^A%K(D$=n;U4oFf;-sP-UZ_(j94 VD65FRgaiE{PzdqP8TbPRJ^>#lFSh^y From 1c8751e96a125992025fdff1892e89b42ed8bbc5 Mon Sep 17 00:00:00 2001 From: Alex Borisov <113920954+soaska@users.noreply.github.com> Date: Fri, 29 Nov 2024 13:35:26 +0300 Subject: [PATCH 2/4] containers (#3) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * Remove junk from repo folder * run with docker * Squashed commit of the following: Making telegram circles Бот в качестве тестовой нагрузки может создавать кружки в телеграме, управляя очередью задач. * /status command, new file structure for telegram bot. * Custom endpoints. I think its ready to use. Next step: create a worker. * Ok, now it can make video notes. * readme * Revert "Squashed commit of the following:" This reverts commit b268dec94c461db60ad49161549d7e543c281b0c. --------- Co-authored-by: AleX --- job-manager/.DS_Store | Bin 0 -> 6148 bytes telegram-bot/.DS_Store | Bin 0 -> 6148 bytes 2 files changed, 0 insertions(+), 0 deletions(-) create mode 100644 job-manager/.DS_Store create mode 100644 telegram-bot/.DS_Store diff --git a/job-manager/.DS_Store b/job-manager/.DS_Store new file mode 100644 index 0000000000000000000000000000000000000000..a43830d236bdefad30dfb4ce5b0c8ba4c0bd555c GIT binary patch literal 6148 zcmeHKJ5B>J5S@V_S)xgasC27-ZL z;GhiP%oa(fhA{>M!9XzZ$$;z+87f#DtD$Zk7_`(q^URa-w^|PiE7sD8XfncCz;Mk^9IsY&5%ZxVpZAr|6 zfneaDF~E~<(arHuezyMjJUMGK^a?5>c~uMu?B)`HiR>e18nk#88+paC8p`$f(l()P!D@p2>28Jfmgr6|L{+IlNqJO z;%$YM8A#q_CNpUsG|3PVFP@q?(Ts>nG(i?+Lc~1jI*4o*8{6CYYSV3d+0ps+Za)mzc2!lkT@73L(Z4>w?B1`&{^nPIe>cc||AtT( zXTTY72AlzB;Lr@%HCk3)Rq3^)V-i~%mHRkgsT>~8(BJ-KTG+6|hB%uAv`ppPB_7|1ztnVsqnqGMh( WOp204>^U6h4}naGch0~cFz^XrH8AV| literal 0 HcmV?d00001 From 9e9e7e15548e497dece05467269ff6140d14de3b Mon Sep 17 00:00:00 2001 From: Alex Borisov <79996669747@ya.ru> Date: Fri, 29 Nov 2024 13:36:50 +0300 Subject: [PATCH 3/4] bruh. --- job-manager/.DS_Store | Bin 6148 -> 0 bytes telegram-bot/.DS_Store | Bin 6148 -> 0 bytes 2 files changed, 0 insertions(+), 0 deletions(-) delete mode 100644 job-manager/.DS_Store delete mode 100644 telegram-bot/.DS_Store diff --git a/job-manager/.DS_Store b/job-manager/.DS_Store deleted file mode 100644 index a43830d236bdefad30dfb4ce5b0c8ba4c0bd555c..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 6148 zcmeHKJ5B>J5S@V_S)xgasC27-ZL z;GhiP%oa(fhA{>M!9XzZ$$;z+87f#DtD$Zk7_`(q^URa-w^|PiE7sD8XfncCz;Mk^9IsY&5%ZxVpZAr|6 zfneaDF~E~<(arHuezyMjJUMGK^a?5>c~uMu?B)`HiR>e18nk#88+paC8p`$f(l()P!D@p2>28Jfmgr6|L{+IlNqJO z;%$YM8A#q_CNpUsG|3PVFP@q?(Ts>nG(i?+Lc~1jI*4o*8{6CYYSV3d+0ps+Za)mzc2!lkT@73L(Z4>w?B1`&{^nPIe>cc||AtT( zXTTY72AlzB;Lr@%HCk3)Rq3^)V-i~%mHRkgsT>~8(BJ-KTG+6|hB%uAv`ppPB_7|1ztnVsqnqGMh( WOp204>^U6h4}naGch0~cFz^XrH8AV| From f748f1a60551e28ebcb0067cdaf49ecbe6191b59 Mon Sep 17 00:00:00 2001 From: Alex Borisov <79996669747@ya.ru> Date: Fri, 29 Nov 2024 17:28:43 +0300 Subject: [PATCH 4/4] Docker compose upd, upd job-manager struct, pocketbase migrations todo: fix big files download... somehow --- README.md | 5 +- compose.yaml | 27 +- example.env | 12 +- job-manager/database-requests.go | 160 ++++++++++ job-manager/main.go | 159 ---------- job-manager/sys.go | 14 +- pocketbase/Dockerfile | 2 +- .../collections/collections-snapshot.js | 291 ++++++++++++++++++ telegram-bot/main.go | 4 +- telegram-bot/sys.go | 27 +- 10 files changed, 499 insertions(+), 202 deletions(-) create mode 100644 pocketbase/collections/collections-snapshot.js diff --git a/README.md b/README.md index e18e147..f4bc625 100644 --- a/README.md +++ b/README.md @@ -21,8 +21,7 @@ cp example.env .env vim .env ``` -Запустим pocketbase, удалим существующую коллекцию users, затем перейдем во вкладку -settings / import collections. Далее в меню load from json выбираем [файл](https://github.com/soaska/faceswaper/blob/main/pocketbase/collections/PB%20Schema.json) +Запустим pocketbase, перейдем по её [url](http://0.0.0.0:8080/_/), создадим пользователя. `pocketbase/collections/PB Schema.json` ```shell podman compose up pocketbase @@ -34,7 +33,7 @@ podman compose up -d --build ``` # Запуск -Запустим pocketbase по [этой](https://pocketbase.io/docs/) инструкции. +Запустим pocketbase по [этой](https://pocketbase.io/docs/) инструкции. Удалим collection `users`. Зайдем во вкладку settings / import collections. Далее в меню load from json выбираем [файл](https://github.com/soaska/faceswaper/blob/main/pocketbase/collections/PB%20Schema.json) pocketbase/collections/PB Schema.json diff --git a/compose.yaml b/compose.yaml index 441c8fc..ad785d6 100644 --- a/compose.yaml +++ b/compose.yaml @@ -1,5 +1,21 @@ services: + # own telegram api server + # needed to download / upload large files + # Container link: https://github.com/aiogram/telegram-bot-api + # Info about limitations: https://core.telegram.org/bots/api#using-a-local-bot-api-server + telegram-bot-api: + image: aiogram/telegram-bot-api:latest + hostname: tgapi + env_file: + - .env + volumes: + - ./data/telegram-bot-api:/var/lib/telegram-bot-api + ports: + - "8081:8081" + - "8082:8082" # statistics + pocketbase: + hostname: pocketbase build: context: ./pocketbase dockerfile: Dockerfile @@ -8,8 +24,13 @@ services: - 8080:8080 volumes: - ./pb_data:/pb/pb_data + healthcheck: + test: ["CMD", "curl", "-f", "http://localhost:8080/api/health"] + interval: 30s + timeout: 10s + retries: 5 - telegram-bot: + job-manager: build: context: ./job-manager dockerfile: Dockerfile @@ -20,8 +41,9 @@ services: restart: unless-stopped depends_on: - pocketbase + - telegram-bot-api - job-manager: + telegram-bot: build: context: ./telegram-bot dockerfile: Dockerfile @@ -32,3 +54,4 @@ services: restart: unless-stopped depends_on: - pocketbase + - telegram-bot-api diff --git a/example.env b/example.env index 257f0bb..0d98f67 100644 --- a/example.env +++ b/example.env @@ -1,9 +1,15 @@ # telegram -TELEGRAM_API = https://api.telegram.org +TELEGRAM_API = "http://tgapi:8081" TELEGRAM_APITOKEN = 1294890:asdasfdewioru3o2ier -BOT_DEBUG = false +BOT_DEBUG = true + +# for own api server +# get from https://my.telegram.org/apps +TELEGRAM_API_ID=3456789 +TELEGRAM_API_HASH=ydgwgyu779cdddw9c9qwd +TELEGRAM_STAT=1 # pocketbase -POCKETBASE_URL = http://0.0.0.0:8080 +POCKETBASE_URL = "http://0.0.0.0:8080" POCKETBASE_LOGIN = admin@supermario.carts POCKETBASE_PASSWORD = MAShsRoOm diff --git a/job-manager/database-requests.go b/job-manager/database-requests.go index a2fe6d8..534221a 100644 --- a/job-manager/database-requests.go +++ b/job-manager/database-requests.go @@ -10,6 +10,8 @@ import ( "net/http" "net/url" "os" + "path/filepath" + "strconv" tgbotapi "github.com/OvyFlash/telegram-bot-api" ) @@ -376,3 +378,161 @@ func getActiveJobs(userID, collection string) ([]map[string]interface{}, error) return nil, nil } + +// Увеличение circle_count на 1 для владельца задачи +func incrementCircleCount(tgUserID int) error { + userInfo, err := getUserInfo(tgUserID) + if err != nil { + return fmt.Errorf("Ошибка получения информации о пользователе с Telegram ID %d: %v", tgUserID, err) + } + currentCircleCount, ok := userInfo["circle_count"].(float64) // JSON numbers в Go парсятся в float64 + if !ok { + currentCircleCount = 0 + } + + newCircleCount := int(currentCircleCount) + 1 + + updateData := map[string]interface{}{ + "circle_count": newCircleCount, + } + + userID, ok := userInfo["id"].(string) + if !ok { + return fmt.Errorf("Не удалось извлечь ID пользователя с Telegram ID %d", tgUserID) + } + + updateURL := fmt.Sprintf("%s/api/collections/users/records/%s", pocketBaseUrl, userID) + + jsonData, err := json.Marshal(updateData) + if err != nil { + return fmt.Errorf("Ошибка сериализации данных для обновления: %v", err) + } + + _, err = sendAuthorizedRequest("PATCH", updateURL, jsonData) + if err != nil { + return fmt.Errorf("Ошибка обновления circle_count для пользователя %s: %v", userID, err) + } + + // log.Printf("circle_count для пользователя с Telegram ID %d успешно обновлен. Новое значение: %d", tgUserID, newCircleCount) + return nil +} + +// Загрузка обработанного файла в output_media +func uploadOutputMedia(taskID, filePath string) error { + url := fmt.Sprintf("%s/api/collections/circle_jobs/records/%s", pocketBaseUrl, taskID) + + file, err := os.Open(filePath) + if err != nil { + return fmt.Errorf("Ошибка открытия файла: %v", err) + } + defer file.Close() + + body := &bytes.Buffer{} + writer := multipart.NewWriter(body) + + // Добавляем файл + filePart, err := writer.CreateFormFile("output_media", filepath.Base(filePath)) + if err != nil { + return fmt.Errorf("Ошибка добавления файла в запрос: %v", err) + } + _, err = io.Copy(filePart, file) + if err != nil { + return fmt.Errorf("Ошибка копирования содержимого файла: %v", err) + } + + // Завершаем формирование multipart + writer.WriteField("status", "completed") + err = writer.Close() + if err != nil { + return fmt.Errorf("Ошибка завершения multipart: %v", err) + } + + request, err := http.NewRequest("PATCH", url, body) + if err != nil { + return fmt.Errorf("Ошибка создания запроса: %v", err) + } + + request.Header.Set("Authorization", fmt.Sprintf("Bearer %s", authToken)) + request.Header.Set("Content-Type", writer.FormDataContentType()) + client := &http.Client{} + + resp, err := client.Do(request) + if err != nil { + return fmt.Errorf("Ошибка отправки запроса: %v", err) + } + defer resp.Body.Close() + + if resp.StatusCode != http.StatusOK { + respBody, _ := io.ReadAll(resp.Body) + return fmt.Errorf("Ошибка загрузки файла: статус %d, ответ: %s", resp.StatusCode, string(respBody)) + } + + return nil +} + +// Получение Telegram ID владельца +func getOwnerTGID(ownerID string) (string, error) { + url := fmt.Sprintf("%s/api/collections/users/records/%s", pocketBaseUrl, ownerID) + body, err := sendAuthorizedRequest("GET", url, nil) + if err != nil { + return "", fmt.Errorf("Ошибка получения данных о владельце: %v", err) + } + + var ownerData struct { + TGID int `json:"tgid"` + } + + err = json.Unmarshal(body, &ownerData) + if err != nil { + return "", fmt.Errorf("Ошибка разбора данных о владельце: %v", err) + } + + if ownerData.TGID == 0 { + return "", fmt.Errorf("Telegram ID владельца %s не найден", ownerID) + } + + return strconv.Itoa(ownerData.TGID), nil +} + +// Получение задачи в статусе "queued" +func fetchQueuedCircleJob(collection string) (*Task, error) { + filter := "status='queued'" + url := fmt.Sprintf("%s/api/collections/%s/records?filter=%s&perPage=1", pocketBaseUrl, collection, filter) + + body, err := sendAuthorizedRequest("GET", url, nil) + if err != nil { + return nil, fmt.Errorf("Ошибка при запросе задач: %v", err) + } + + var response struct { + Items []Task `json:"items"` + } + + err = json.Unmarshal(body, &response) + if err != nil { + return nil, fmt.Errorf("Ошибка разбора JSON: %v", err) + } + + if len(response.Items) > 0 { + return &response.Items[0], nil + } + + return nil, nil // Нет задач в статусе "queued" +} + +// Обновление статуса задачи +func updateTaskStatus(taskID, status string) error { + url := fmt.Sprintf("%s/api/collections/circle_jobs/records/%s", pocketBaseUrl, taskID) + + data := map[string]string{ + "status": status, + } + jsonData, _ := json.Marshal(data) + + _, err := sendAuthorizedRequest("PATCH", url, jsonData) + if err != nil { + return fmt.Errorf("Ошибка обновления статуса задачи: %v", err) + } + + return nil +} diff --git a/job-manager/main.go b/job-manager/main.go index abe187b..f6e0071 100644 --- a/job-manager/main.go +++ b/job-manager/main.go @@ -12,7 +12,6 @@ import ( "strconv" "time" - "encoding/json" "mime/multipart" ) @@ -69,49 +68,6 @@ func processCircleJobs() { } } -// Получение задачи в статусе "queued" -func fetchQueuedCircleJob(collection string) (*Task, error) { - filter := "status='queued'" - url := fmt.Sprintf("%s/api/collections/%s/records?filter=%s&perPage=1", pocketBaseUrl, collection, filter) - - body, err := sendAuthorizedRequest("GET", url, nil) - if err != nil { - return nil, fmt.Errorf("Ошибка при запросе задач: %v", err) - } - - var response struct { - Items []Task `json:"items"` - } - - err = json.Unmarshal(body, &response) - if err != nil { - return nil, fmt.Errorf("Ошибка разбора JSON: %v", err) - } - - if len(response.Items) > 0 { - return &response.Items[0], nil - } - - return nil, nil // Нет задач в статусе "queued" -} - -// Обновление статуса задачи -func updateTaskStatus(taskID, status string) error { - url := fmt.Sprintf("%s/api/collections/circle_jobs/records/%s", pocketBaseUrl, taskID) - - data := map[string]string{ - "status": status, - } - jsonData, _ := json.Marshal(data) - - _, err := sendAuthorizedRequest("PATCH", url, jsonData) - if err != nil { - return fmt.Errorf("Ошибка обновления статуса задачи: %v", err) - } - - return nil -} - // Обработка задачи func processTask(task *Task) error { if task.InputMedia == "" { @@ -190,121 +146,6 @@ func processVideo(inputPath, outputPath string) error { return nil } -// Загрузка обработанного файла в output_media -func uploadOutputMedia(taskID, filePath string) error { - url := fmt.Sprintf("%s/api/collections/circle_jobs/records/%s", pocketBaseUrl, taskID) - - file, err := os.Open(filePath) - if err != nil { - return fmt.Errorf("Ошибка открытия файла: %v", err) - } - defer file.Close() - - body := &bytes.Buffer{} - writer := multipart.NewWriter(body) - - // Добавляем файл - filePart, err := writer.CreateFormFile("output_media", filepath.Base(filePath)) - if err != nil { - return fmt.Errorf("Ошибка добавления файла в запрос: %v", err) - } - _, err = io.Copy(filePart, file) - if err != nil { - return fmt.Errorf("Ошибка копирования содержимого файла: %v", err) - } - - // Завершаем формирование multipart - writer.WriteField("status", "completed") - err = writer.Close() - if err != nil { - return fmt.Errorf("Ошибка завершения multipart: %v", err) - } - - request, err := http.NewRequest("PATCH", url, body) - if err != nil { - return fmt.Errorf("Ошибка создания запроса: %v", err) - } - - request.Header.Set("Authorization", fmt.Sprintf("Bearer %s", authToken)) - request.Header.Set("Content-Type", writer.FormDataContentType()) - client := &http.Client{} - - resp, err := client.Do(request) - if err != nil { - return fmt.Errorf("Ошибка отправки запроса: %v", err) - } - defer resp.Body.Close() - - if resp.StatusCode != http.StatusOK { - respBody, _ := io.ReadAll(resp.Body) - return fmt.Errorf("Ошибка загрузки файла: статус %d, ответ: %s", resp.StatusCode, string(respBody)) - } - - return nil -} - -// Увеличение circle_count на 1 для владельца задачи -func incrementCircleCount(tgUserID int) error { - userInfo, err := getUserInfo(tgUserID) - if err != nil { - return fmt.Errorf("Ошибка получения информации о пользователе с Telegram ID %d: %v", tgUserID, err) - } - currentCircleCount, ok := userInfo["circle_count"].(float64) // JSON numbers в Go парсятся в float64 - if !ok { - currentCircleCount = 0 - } - - newCircleCount := int(currentCircleCount) + 1 - - updateData := map[string]interface{}{ - "circle_count": newCircleCount, - } - - userID, ok := userInfo["id"].(string) - if !ok { - return fmt.Errorf("Не удалось извлечь ID пользователя с Telegram ID %d", tgUserID) - } - - updateURL := fmt.Sprintf("%s/api/collections/users/records/%s", pocketBaseUrl, userID) - - jsonData, err := json.Marshal(updateData) - if err != nil { - return fmt.Errorf("Ошибка сериализации данных для обновления: %v", err) - } - - _, err = sendAuthorizedRequest("PATCH", updateURL, jsonData) - if err != nil { - return fmt.Errorf("Ошибка обновления circle_count для пользователя %s: %v", userID, err) - } - - // log.Printf("circle_count для пользователя с Telegram ID %d успешно обновлен. Новое значение: %d", tgUserID, newCircleCount) - return nil -} - -// Получение Telegram ID владельца -func getOwnerTGID(ownerID string) (string, error) { - url := fmt.Sprintf("%s/api/collections/users/records/%s", pocketBaseUrl, ownerID) - body, err := sendAuthorizedRequest("GET", url, nil) - if err != nil { - return "", fmt.Errorf("Ошибка получения данных о владельце: %v", err) - } - - var ownerData struct { - TGID int `json:"tgid"` - } - - err = json.Unmarshal(body, &ownerData) - if err != nil { - return "", fmt.Errorf("Ошибка разбора данных о владельце: %v", err) - } - - if ownerData.TGID == 0 { - return "", fmt.Errorf("Telegram ID владельца %s не найден", ownerID) - } - - return strconv.Itoa(ownerData.TGID), nil -} - // Отправка готового видеосообщения владельцу через Telegram API func notifyOwner(task *Task) error { if task.Owner == "" { diff --git a/job-manager/sys.go b/job-manager/sys.go index f802309..b3fc38d 100644 --- a/job-manager/sys.go +++ b/job-manager/sys.go @@ -6,7 +6,6 @@ import ( "io" "log" "net/http" - "net/url" "os" tgbotapi "github.com/OvyFlash/telegram-bot-api" @@ -110,25 +109,14 @@ func LoadEnvironment() (string, bool, string) { bot_endpoint := os.Getenv("TELEGRAM_API") if bot_endpoint == `` { bot_endpoint = "https://api.telegram.org" - } else { - // validate db url - _, err := url.ParseRequestURI(bot_endpoint) - if err != nil { - log.Fatal(err) - } } // pocketbase pocketBaseUrl = os.Getenv("POCKETBASE_URL") if pocketBaseUrl == `` { log.Fatal("empty pocketbase url loaded, check POCKETBASE_URL value") - } else { - // validate db url - _, err := url.ParseRequestURI(pocketBaseUrl) - if err != nil { - log.Fatal(err) - } } + email = os.Getenv("POCKETBASE_LOGIN") if email == `` { log.Fatal("empty pocketbase login loaded. env is not correct or configuration is insecure") diff --git a/pocketbase/Dockerfile b/pocketbase/Dockerfile index 96ad8b8..82c620b 100644 --- a/pocketbase/Dockerfile +++ b/pocketbase/Dockerfile @@ -1,6 +1,6 @@ FROM alpine:latest -ARG PB_VERSION=0.23.2 +ARG PB_VERSION=0.22.27 RUN apk add --no-cache \ unzip \ diff --git a/pocketbase/collections/collections-snapshot.js b/pocketbase/collections/collections-snapshot.js new file mode 100644 index 0000000..bc80a7d --- /dev/null +++ b/pocketbase/collections/collections-snapshot.js @@ -0,0 +1,291 @@ +/// +migrate( + (db) => { + const snapshot = [ + { + id: "2dtkk2h5xo817br", + created: "2024-11-29 11:45:22.881Z", + updated: "2024-11-29 11:45:22.881Z", + name: "circle_jobs", + type: "base", + system: false, + schema: [ + { + system: false, + id: "uzfarnhf", + name: "owner", + type: "relation", + required: false, + presentable: false, + unique: false, + options: { + collectionId: "ojssopdqy5r541p", + cascadeDelete: false, + minSelect: null, + maxSelect: 1, + displayFields: null, + }, + }, + { + system: false, + id: "gvtrqemw", + name: "input_media", + type: "file", + required: false, + presentable: false, + unique: false, + options: { + mimeTypes: [], + thumbs: [], + maxSelect: 1, + maxSize: 5242880, + protected: false, + }, + }, + { + system: false, + id: "reycy6gk", + name: "output_media", + type: "file", + required: false, + presentable: false, + unique: false, + options: { + mimeTypes: [], + thumbs: [], + maxSelect: 1, + maxSize: 5242880, + protected: false, + }, + }, + { + system: false, + id: "zi4rfipy", + name: "status", + type: "text", + required: false, + presentable: false, + unique: false, + options: { + min: null, + max: null, + pattern: "", + }, + }, + ], + indexes: [], + listRule: null, + viewRule: null, + createRule: null, + updateRule: null, + deleteRule: null, + options: {}, + }, + { + id: "9r47cxfzaoclhq6", + created: "2024-11-29 11:45:22.882Z", + updated: "2024-11-29 11:45:22.882Z", + name: "face_jobs", + type: "base", + system: false, + schema: [ + { + system: false, + id: "qp8ofgdk", + name: "owner", + type: "relation", + required: false, + presentable: false, + unique: false, + options: { + collectionId: "ojssopdqy5r541p", + cascadeDelete: false, + minSelect: null, + maxSelect: 1, + displayFields: null, + }, + }, + { + system: false, + id: "vzonmr2d", + name: "input_face", + type: "file", + required: false, + presentable: false, + unique: false, + options: { + mimeTypes: [], + thumbs: [], + maxSelect: 1, + maxSize: 5242880, + protected: false, + }, + }, + { + system: false, + id: "zr1yy9v0", + name: "input_media", + type: "file", + required: false, + presentable: false, + unique: false, + options: { + mimeTypes: [], + thumbs: [], + maxSelect: 1, + maxSize: 5242880, + protected: false, + }, + }, + { + system: false, + id: "oavl1xr2", + name: "media_transformed", + type: "file", + required: false, + presentable: false, + unique: false, + options: { + mimeTypes: [], + thumbs: [], + maxSelect: 1, + maxSize: 5242880, + protected: false, + }, + }, + { + system: false, + id: "vjpc4htl", + name: "output_media", + type: "file", + required: false, + presentable: false, + unique: false, + options: { + mimeTypes: [], + thumbs: [], + maxSelect: 1, + maxSize: 5242880, + protected: false, + }, + }, + { + system: false, + id: "db4eyjzd", + name: "status", + type: "text", + required: false, + presentable: false, + unique: false, + options: { + min: null, + max: null, + pattern: "", + }, + }, + ], + indexes: [], + listRule: null, + viewRule: null, + createRule: null, + updateRule: null, + deleteRule: null, + options: {}, + }, + { + id: "ojssopdqy5r541p", + created: "2024-11-29 11:45:22.882Z", + updated: "2024-11-29 11:45:22.882Z", + name: "users", + type: "base", + system: false, + schema: [ + { + system: false, + id: "vqlz3wsv", + name: "tgid", + type: "number", + required: false, + presentable: false, + unique: false, + options: { + min: null, + max: null, + noDecimal: false, + }, + }, + { + system: false, + id: "tekw5iqf", + name: "username", + type: "text", + required: false, + presentable: false, + unique: false, + options: { + min: null, + max: null, + pattern: "", + }, + }, + { + system: false, + id: "yinpouxs", + name: "circle_count", + type: "number", + required: false, + presentable: false, + unique: false, + options: { + min: null, + max: null, + noDecimal: false, + }, + }, + { + system: false, + id: "dths5bgp", + name: "face_replace_count", + type: "number", + required: false, + presentable: false, + unique: false, + options: { + min: null, + max: null, + noDecimal: false, + }, + }, + { + system: false, + id: "bb3yst5x", + name: "coins", + type: "number", + required: false, + presentable: false, + unique: false, + options: { + min: null, + max: null, + noDecimal: false, + }, + }, + ], + indexes: [], + listRule: null, + viewRule: null, + createRule: null, + updateRule: null, + deleteRule: null, + options: {}, + }, + ]; + + const collections = snapshot.map((item) => new Collection(item)); + + return Dao(db).importCollections(collections, true, null); + }, + (db) => { + return null; + }, +); diff --git a/telegram-bot/main.go b/telegram-bot/main.go index 7779d41..44f5912 100644 --- a/telegram-bot/main.go +++ b/telegram-bot/main.go @@ -151,7 +151,7 @@ func main() { // help if update.Message.Text != "" && strings.Contains(strings.ToLower(update.Message.Text), "help") { - helpMessage := "Напиши мне фото для выполнения задачи по замене лица. Пришли видео для создания кружочка." + helpMessage := "Напиши мне фото для создания задачи по замене лица (временно недоступно). Пришли видео для создания кружочка." msg := tgbotapi.NewMessage(update.Message.Chat.ID, helpMessage) bot.Send(msg) continue @@ -188,6 +188,8 @@ func main() { // Обработка получения видео if update.Message.Video != nil { videoFileID := update.Message.Video.FileID + msg := tgbotapi.NewMessage(update.Message.Chat.ID, "Ловлю!") + bot.Send(msg) // Проверяем, есть ли фото в сессии пользователя if session.FaceFileID != "" { diff --git a/telegram-bot/sys.go b/telegram-bot/sys.go index 298056b..b442b53 100644 --- a/telegram-bot/sys.go +++ b/telegram-bot/sys.go @@ -6,7 +6,6 @@ import ( "io" "log" "net/http" - "net/url" "os" tgbotapi "github.com/OvyFlash/telegram-bot-api" @@ -18,6 +17,7 @@ var pocketBaseUrl string var email string var password string var authToken string +var api_endpint string // just for sending search requests to pocketbase func sendAuthorizedRequest(method, url string, payload []byte) ([]byte, error) { @@ -47,13 +47,11 @@ func sendAuthorizedRequest(method, url string, payload []byte) ([]byte, error) { } func downloadTelegramFile(bot *tgbotapi.BotAPI, fileID, destinationPath string) error { - file, err := bot.GetFile(tgbotapi.FileConfig{FileID: fileID}) + fileURL, err := bot.GetFileDirectURL(fileID) if err != nil { return fmt.Errorf("не удалось получить файл по ID: %v", err) } - fileURL := fmt.Sprintf("https://api.telegram.org/file/bot%s/%s", bot.Token, file.FilePath) - // Download request resp, err := http.Get(fileURL) if err != nil { @@ -103,28 +101,17 @@ func LoadEnvironment() (string, bool, string) { bot_debug = false } - bot_endpoint := os.Getenv("TELEGRAM_API") - if bot_endpoint == `` { - bot_endpoint = "https://api.telegram.org" - } else { - // validate db url - _, err := url.ParseRequestURI(bot_endpoint) - if err != nil { - log.Fatal(err) - } + api_endpint = os.Getenv("TELEGRAM_API") + if api_endpint == `` { + api_endpint = "https://api.telegram.org" } // pocketbase pocketBaseUrl = os.Getenv("POCKETBASE_URL") if pocketBaseUrl == `` { log.Fatal("empty pocketbase url loaded, check POCKETBASE_URL value") - } else { - // validate db url - _, err := url.ParseRequestURI(pocketBaseUrl) - if err != nil { - log.Fatal(err) - } } + email = os.Getenv("POCKETBASE_LOGIN") if email == `` { log.Fatal("empty pocketbase login loaded. env is not correct or configuration is insecure") @@ -135,5 +122,5 @@ func LoadEnvironment() (string, bool, string) { log.Fatal("empty pocketbase password loaded. env is not correct or configuration is insecure") } - return bot_token, bot_debug, bot_endpoint + return bot_token, bot_debug, api_endpint }