Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion cmd/tgbot/internal/bot/bot.go
Original file line number Diff line number Diff line change
Expand Up @@ -508,7 +508,7 @@ func (b *Bot) rename(msg *tgbotapi.Message) {
}

func (b *Bot) download(msg *tgbotapi.Message) {
texts, err := b.service.FullTexts(msg.From.ID)
texts, err := b.service.FullTexts(msg.From.ID, nil)
if err != nil {
b.replyErrorWithI18n(msg, errorOnListMsgId, err)
return
Expand Down
16 changes: 15 additions & 1 deletion cmd/tgbot/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,10 +7,14 @@ import (
"os/signal"
"syscall"

"github.com/go-chi/chi/v5"
"github.com/pechorka/adhd-reader/internal/handler"
"github.com/pechorka/adhd-reader/internal/handler/mw/auth"
"github.com/pechorka/adhd-reader/internal/service"
"github.com/pechorka/adhd-reader/internal/storage"

"github.com/pechorka/adhd-reader/cmd/tgbot/internal/bot"
"github.com/pechorka/adhd-reader/pkg/encryptor"
"github.com/pechorka/adhd-reader/pkg/fileloader"
"github.com/pechorka/adhd-reader/pkg/i18n"
"github.com/pechorka/adhd-reader/pkg/queue"
Expand All @@ -30,6 +34,7 @@ type config struct {
Debug bool `json:"debug"`
DbPath string `json:"db_path"`
Admins []int64 `json:"admins"`
Secret string `json:"secret"`
}

func readCfg(path string) (*config, error) {
Expand Down Expand Up @@ -89,7 +94,8 @@ func run() error {
defer watcher.Close()

scrapper := webscraper.New()
service := service.NewService(store, scrapper, 500)
encryptor := encryptor.NewEncryptor(cfg.Secret)
service := service.NewService(store, 500, scrapper, encryptor)
msgQueue := queue.NewMessageQueue(queue.Config{})
fileLoader := fileloader.NewLoader(fileloader.Config{
MaxFileSize: defaultMaxFileSize,
Expand All @@ -108,6 +114,14 @@ func run() error {
}
go b.Run()

handlers := handler.NewHandlers(service)
mx := chi.NewRouter()
authMW := auth.NewAuthMW(service)
mx.With(authMW.Auth)
mx.Route("/api/v1", func(r chi.Router) {
handlers.Register(r)
})

terminate := make(chan os.Signal, 1)
signal.Notify(terminate, syscall.SIGINT, syscall.SIGTERM)

Expand Down
7 changes: 5 additions & 2 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -5,13 +5,16 @@ go 1.19
require (
github.com/PuerkitoBio/goquery v1.8.1
github.com/fsnotify/fsnotify v1.6.0
github.com/go-chi/chi/v5 v5.0.10
github.com/go-telegram-bot-api/telegram-bot-api/v5 v5.5.1
github.com/google/uuid v1.3.0
github.com/gtank/cryptopasta v0.0.0-20170601214702-1f550f6f2f69
github.com/pkg/errors v0.9.1
github.com/stretchr/testify v1.8.1
github.com/valyala/fasttemplate v1.2.2
go.etcd.io/bbolt v1.3.7
golang.org/x/exp v0.0.0-20230315142452-642cacee5cc0
golang.org/x/net v0.10.0
)

require (
Expand All @@ -20,8 +23,8 @@ require (
github.com/kr/pretty v0.1.0 // indirect
github.com/pmezard/go-difflib v1.0.0 // indirect
github.com/valyala/bytebufferpool v1.0.0 // indirect
golang.org/x/net v0.7.0 // indirect
golang.org/x/sys v0.6.0 // indirect
golang.org/x/crypto v0.11.0 // indirect
golang.org/x/sys v0.10.0 // indirect
gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127 // indirect
gopkg.in/yaml.v3 v3.0.1 // indirect
)
13 changes: 10 additions & 3 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -7,10 +7,14 @@ github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/fsnotify/fsnotify v1.6.0 h1:n+5WquG0fcWoWp6xPWfHdbskMCQaFnG6PfBrh1Ky4HY=
github.com/fsnotify/fsnotify v1.6.0/go.mod h1:sl3t1tCWJFWoRz9R8WJCbQihKKwmorjAbSClcnxKAGw=
github.com/go-chi/chi/v5 v5.0.10 h1:rLz5avzKpjqxrYwXNfmjkrYYXOyLJd37pz53UFHC6vk=
github.com/go-chi/chi/v5 v5.0.10/go.mod h1:DslCQbL2OYiznFReuXYUmQ2hGd1aDpCnlMNITLSKoi8=
github.com/go-telegram-bot-api/telegram-bot-api/v5 v5.5.1 h1:wG8n/XJQ07TmjbITcGiUaOtXxdrINDz1b0J1w0SzqDc=
github.com/go-telegram-bot-api/telegram-bot-api/v5 v5.5.1/go.mod h1:A2S0CWkNylc2phvKXWBBdD3K0iGnDBGbzRpISP2zBl8=
github.com/google/uuid v1.3.0 h1:t6JiXgmwXMjEs8VusXIJk2BXHsn+wx8BZdTaoZ5fu7I=
github.com/google/uuid v1.3.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
github.com/gtank/cryptopasta v0.0.0-20170601214702-1f550f6f2f69 h1:7xsUJsB2NrdcttQPa7JLEaGzvdbk7KvfrjgHZXOQRo0=
github.com/gtank/cryptopasta v0.0.0-20170601214702-1f550f6f2f69/go.mod h1:YLEMZOtU+AZ7dhN9T/IpGhXVGly2bvkJQ+zxj3WeVQo=
github.com/kr/pretty v0.1.0 h1:L/CwN0zerZDmRFUapSPitk6f+Q3+0za1rQkzVuMiMFI=
github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo=
github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ=
Expand All @@ -36,15 +40,18 @@ go.etcd.io/bbolt v1.3.7 h1:j+zJOnnEjF/kyHlDDgGnVL/AIqIJPq8UoB2GSNfkUfQ=
go.etcd.io/bbolt v1.3.7/go.mod h1:N9Mkw9X8x5fupy0IKsmuqVtoGDyxsaDlbk4Rd05IAQw=
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc=
golang.org/x/crypto v0.11.0 h1:6Ewdq3tDic1mg5xRO4milcWCfMVQhI4NkqWWvqejpuA=
golang.org/x/crypto v0.11.0/go.mod h1:xgJhtzW8F9jGdVFWZESrid1U1bjeNy4zgy5cRr/CIio=
golang.org/x/exp v0.0.0-20230315142452-642cacee5cc0 h1:pVgRXcIictcr+lBQIFeiwuwtDIs4eL21OuM9nyAADmo=
golang.org/x/exp v0.0.0-20230315142452-642cacee5cc0/go.mod h1:CxIveKay+FTh1D0yPZemJVgC/95VzuuOLq5Qi4xnoYc=
golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4=
golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg=
golang.org/x/net v0.0.0-20210916014120-12bc252f5db8/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y=
golang.org/x/net v0.0.0-20220722155237-a158d28d115b/go.mod h1:XRhObCWvk6IyKnWLug+ECip1KBveYUHfp+8e9klMJ9c=
golang.org/x/net v0.7.0 h1:rJrUqqhjsgNp7KqAIc25s9pZnjU7TUcSY7HcVZjdn1g=
golang.org/x/net v0.7.0/go.mod h1:2Tu9+aMcznHK/AK1HMvgo6xiTLG5rD5rZLDS+rp2Bjs=
golang.org/x/net v0.10.0 h1:X2//UzNDwYmtCLn7To6G58Wr6f5ahEAQgKNzv9Y951M=
golang.org/x/net v0.10.0/go.mod h1:0qNGK6F8kojg2nk9dLZ2mShWaEBan6FAoqfSigmmuDg=
golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.0.0-20220722155255-886fb9371eb4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
Expand All @@ -55,8 +62,8 @@ golang.org/x/sys v0.0.0-20220520151302-bc2c85ada10a/go.mod h1:oPkhp1MJrh7nUepCBc
golang.org/x/sys v0.0.0-20220722155257-8c9f86f7a55f/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20220908164124-27713097b956/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.5.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.6.0 h1:MVltZSvRTcU2ljQOhs94SXPftV6DCNnZViHeQps87pQ=
golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.10.0 h1:SqMFp9UcQJZa+pmYuAKjd9xq1f0j5rLcDIk0mj4qAsA=
golang.org/x/sys v0.10.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=
golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8=
golang.org/x/term v0.5.0/go.mod h1:jMB1sMXY+tzblOD4FWmEbocvup2/aLOaQEp7JmGp78k=
Expand Down
201 changes: 201 additions & 0 deletions internal/handler/handler.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,201 @@
package handler

import (
"errors"
"net/http"
"time"

"github.com/go-chi/chi/v5"
"github.com/pechorka/adhd-reader/internal/handler/internal/request"
"github.com/pechorka/adhd-reader/internal/handler/internal/respond"
"github.com/pechorka/adhd-reader/internal/handler/mw/auth"
"github.com/pechorka/adhd-reader/internal/service"
"github.com/pechorka/adhd-reader/internal/storage"
)

type Service interface {
FullTexts(userID int64, after *time.Time) ([]storage.FullText, error)
SyncTexts(userID int64, texts []service.SyncText) ([]service.SyncText, error)
NextChunk(userID int64) (storage.Text, string, service.ChunkType, error)
PrevChunk(userID int64) (storage.Text, string, service.ChunkType, error)
}

type Handlers struct {
svc Service
}

func NewHandlers(svc Service) *Handlers {
return &Handlers{svc: svc}
}

func (h *Handlers) Register(mx chi.Router) {
mx.Get("/text", h.GetTexts)
mx.Post("/text/sync", h.SyncTexts)
mx.Post("/text/chunk/next", h.NextChunk)
mx.Post("/text/chunk/prev", h.PrevChunk)
}

type GetTextsResponse struct {
Texts []GetTextsResponseItem `json:"texts"`
}

type GetTextsResponseItem struct {
TextUUID string `json:"id"`
Name string `json:"name"`
CurrentChunk int64 `json:"currentChunk"`
Chunks []string `json:"chunks"`
}

func (h *Handlers) GetTexts(w http.ResponseWriter, r *http.Request) {
userID := auth.GetUserID(r.Context())
var after *time.Time
if afterQ := r.URL.Query().Get("after"); afterQ != "" {
afterT, err := time.Parse(time.RFC3339, afterQ)
if err != nil {
respond.ErrorWithCode(w, http.StatusBadRequest, respond.CODE_INVALID_DATE_FORMAT)
return
}
after = &afterT
}
texts, err := h.svc.FullTexts(userID, after)
if err != nil {
respond.ErrorWithCode(w, http.StatusInternalServerError, respond.CODE_INTERNAL_ERROR)
return
}
resp := GetTextsResponse{Texts: make([]GetTextsResponseItem, 0, len(texts))}
for _, text := range texts {
resp.Texts = append(resp.Texts, GetTextsResponseItem{
TextUUID: text.UUID,
Name: text.Name,
CurrentChunk: text.CurrentChunk,
Chunks: text.Chunks,
})
}
respond.JSON(w, resp)
}

type SyncTextsRequest struct {
Items []SyncItem `json:"items"`
}

type SyncItem struct {
TextUUID string `json:"id"`
ModifiedAt string `json:"modifiedAt"`
CurrentChunk int64 `json:"currentChunk"`
Deleted bool `json:"deleted"`
}

type SyncTextsResponse struct {
Items []SyncItem `json:"items"`
}

func (h *Handlers) SyncTexts(w http.ResponseWriter, r *http.Request) {
userID := auth.GetUserID(r.Context())
var req SyncTextsRequest
err := request.DecodeJSON(r.Body, &req)
if err != nil {
respond.ErrorWithCode(w, http.StatusBadRequest, respond.CODE_INVALID_JSON)
return
}
syncTexts := make([]service.SyncText, 0, len(req.Items))
for _, item := range req.Items {
modifiedAt, err := time.Parse(time.RFC3339, item.ModifiedAt)
if err != nil {
respond.RespondErrorWithText(w, http.StatusBadRequest, respond.CODE_INVALID_DATE_FORMAT, "invalid date format for item: "+item.TextUUID)
return
}
syncTexts = append(syncTexts, service.SyncText{
TextUUID: item.TextUUID,
ModifiedAt: modifiedAt,
CurrentChunk: item.CurrentChunk,
Deleted: item.Deleted,
})
}
syncOnMobile, err := h.svc.SyncTexts(userID, syncTexts)
if err != nil {
respond.ErrorWithCode(w, http.StatusInternalServerError, respond.CODE_INTERNAL_ERROR)
return
}
resp := SyncTextsResponse{Items: make([]SyncItem, 0, len(syncOnMobile))}
for _, item := range syncOnMobile {
resp.Items = append(resp.Items, SyncItem{
TextUUID: item.TextUUID,
ModifiedAt: item.ModifiedAt.Format(time.RFC3339),
CurrentChunk: item.CurrentChunk,
Deleted: item.Deleted,
})
}
respond.JSON(w, resp)
}

type NextChunkRequest struct {
TextUUID string `json:"id"`
}

type NextChunkResponse struct {
TextUUID string `json:"id"`
Chunk string `json:"chunk"`
Type string `json:"type"`
}

func (h *Handlers) NextChunk(w http.ResponseWriter, r *http.Request) {
userID := auth.GetUserID(r.Context())
var req NextChunkRequest
err := request.DecodeJSON(r.Body, &req)
if err != nil {
respond.ErrorWithCode(w, http.StatusBadRequest, respond.CODE_INVALID_JSON)
return
}
text, chunk, chunkType, err := h.svc.NextChunk(userID)
if err != nil {
switch {
case errors.Is(err, service.ErrTextFinished):
respond.ErrorWithCode(w, http.StatusBadRequest, respond.CODE_ALREADY_AT_LAST_CHUNK)
default:
respond.ErrorWithCode(w, http.StatusInternalServerError, respond.CODE_INTERNAL_ERROR)
}
return
}
resp := NextChunkResponse{
TextUUID: text.UUID,
Chunk: chunk,
Type: chunkType.String(),
}
respond.JSON(w, resp)
}

type PrevChunkRequest struct {
TextUUID string `json:"id"`
}

type PrevChunkResponse struct {
TextUUID string `json:"id"`
Chunk string `json:"chunk"`
Type string `json:"type"`
}

func (h *Handlers) PrevChunk(w http.ResponseWriter, r *http.Request) {
userID := auth.GetUserID(r.Context())
var req PrevChunkRequest
err := request.DecodeJSON(r.Body, &req)
if err != nil {
respond.ErrorWithCode(w, http.StatusBadRequest, respond.CODE_INVALID_JSON)
return
}
text, chunk, chunkType, err := h.svc.PrevChunk(userID)
if err != nil {
switch {
case errors.Is(err, service.ErrFirstChunk):
respond.ErrorWithCode(w, http.StatusBadRequest, respond.CODE_ALREADY_AT_FIRST_CHUNK)
default:
respond.ErrorWithCode(w, http.StatusInternalServerError, respond.CODE_INTERNAL_ERROR)
}
return
}
resp := PrevChunkResponse{
TextUUID: text.UUID,
Chunk: chunk,
Type: chunkType.String(),
}
respond.JSON(w, resp)
}
10 changes: 10 additions & 0 deletions internal/handler/internal/request/request.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
package request

import (
"encoding/json"
"io"
)

func DecodeJSON(r io.Reader, v interface{}) error {
return json.NewDecoder(r).Decode(v)
}
11 changes: 11 additions & 0 deletions internal/handler/internal/respond/codes.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
package respond

const (
CODE_AUTH_HEADER_MISSING = 1
CODE_AUTH_TOKEN_INVALID = 2
CODE_INVALID_DATE_FORMAT = 3
CODE_INTERNAL_ERROR = 4
CODE_INVALID_JSON = 5
CODE_ALREADY_AT_FIRST_CHUNK = 6
CODE_ALREADY_AT_LAST_CHUNK = 7
)
30 changes: 30 additions & 0 deletions internal/handler/internal/respond/herror.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
package respond

import (
"encoding/json"
"log"
"net/http"
)

type Error struct {
Code int `json:"code"`
Text string `json:"text,omitempty"`
}

func ErrorWithCode(w http.ResponseWriter, httpCode, appCode int) {
w.WriteHeader(httpCode)
JSON(w, Error{Code: appCode})
}

func RespondErrorWithText(w http.ResponseWriter, httpCode, appCode int, errText string) {
w.WriteHeader(httpCode)
JSON(w, Error{Code: appCode, Text: errText})
}

func JSON(w http.ResponseWriter, v interface{}) {
w.Header().Set("Content-Type", "application/json")
err := json.NewEncoder(w).Encode(v)
if err != nil {
log.Printf("failed to encode response: %v", err)
}
}
Loading