Merge pull request 'dev' (#1) from dev into main
Reviewed-on: blahaj-fuckers/scrap#1
This commit was merged in pull request #1.
This commit is contained in:
2
.gitignore
vendored
Normal file
2
.gitignore
vendored
Normal file
@@ -0,0 +1,2 @@
|
|||||||
|
*.db
|
||||||
|
tiles/
|
||||||
78
api/article/handler.go
Normal file
78
api/article/handler.go
Normal file
@@ -0,0 +1,78 @@
|
|||||||
|
package article
|
||||||
|
|
||||||
|
import (
|
||||||
|
"net/http"
|
||||||
|
"scrap/api/httpio"
|
||||||
|
"scrap/internal/article"
|
||||||
|
"scrap/internal/db"
|
||||||
|
)
|
||||||
|
|
||||||
|
func ArticleDownloadHandler(w http.ResponseWriter, r *http.Request) {
|
||||||
|
dbInstance := db.GetInstance()
|
||||||
|
txRepo := db.NewTxRepository(dbInstance)
|
||||||
|
articleRepo := article.NewArticleRepository()
|
||||||
|
|
||||||
|
service := article.NewArticleService(txRepo, articleRepo)
|
||||||
|
if err := service.DownloadArticles(); err != nil {
|
||||||
|
switch err {
|
||||||
|
default:
|
||||||
|
httpio.RaiseOnlyStatusCode(w, http.StatusInternalServerError)
|
||||||
|
}
|
||||||
|
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func ArticleQueryHandler(w http.ResponseWriter, r *http.Request) {
|
||||||
|
body, err := httpio.ParseURLQuery[ArticleQueryRequest](
|
||||||
|
r,
|
||||||
|
httpio.URLQueryKey[string]("title"),
|
||||||
|
)
|
||||||
|
if err != nil {
|
||||||
|
httpio.RaiseOnlyStatusCode(w, http.StatusInternalServerError)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
if httpErr := body.Validate(); httpErr != nil {
|
||||||
|
httpErr.Raise(w)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
dbInstance := db.GetInstance()
|
||||||
|
txRepo := db.NewTxRepository(dbInstance)
|
||||||
|
articleRepo := article.NewArticleRepository()
|
||||||
|
|
||||||
|
service := article.NewArticleService(txRepo, articleRepo)
|
||||||
|
|
||||||
|
articleQueryData := article.ArticleQueryDTO{
|
||||||
|
Title: body.Title,
|
||||||
|
}
|
||||||
|
|
||||||
|
articles, err := service.QueryArticles(articleQueryData)
|
||||||
|
if err != nil {
|
||||||
|
switch err {
|
||||||
|
case article.ErrArticleTitleInvalidLength:
|
||||||
|
ErrHttpArticleTitleInvalidLength.Raise(w)
|
||||||
|
default:
|
||||||
|
httpio.RaiseOnlyStatusCode(w, http.StatusInternalServerError)
|
||||||
|
}
|
||||||
|
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
articlesOut := make([]ArticleResponse, 0, len(articles))
|
||||||
|
for _, a := range articles {
|
||||||
|
ar := ArticleResponse{
|
||||||
|
Uuid: a.Uuid,
|
||||||
|
Title: a.Title,
|
||||||
|
Content: a.Content,
|
||||||
|
}
|
||||||
|
|
||||||
|
articlesOut = append(articlesOut, ar)
|
||||||
|
}
|
||||||
|
|
||||||
|
if err = ArticleQueryResponse(articlesOut).Return(w, http.StatusOK); err != nil {
|
||||||
|
httpio.RaiseOnlyStatusCode(w, http.StatusInternalServerError)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
14
api/article/httperror.go
Normal file
14
api/article/httperror.go
Normal file
@@ -0,0 +1,14 @@
|
|||||||
|
package article
|
||||||
|
|
||||||
|
import (
|
||||||
|
"net/http"
|
||||||
|
"scrap/api/httpio"
|
||||||
|
)
|
||||||
|
|
||||||
|
var (
|
||||||
|
ErrHttpArticleTitleInvalidLength = httpio.HTTPError{
|
||||||
|
StatusCode: http.StatusBadRequest,
|
||||||
|
ErrorCode: "ARTICLE_TITLE_LENGTH",
|
||||||
|
Message: "Invalid title length.",
|
||||||
|
}
|
||||||
|
)
|
||||||
16
api/article/request.go
Normal file
16
api/article/request.go
Normal file
@@ -0,0 +1,16 @@
|
|||||||
|
package article
|
||||||
|
|
||||||
|
import "scrap/api/httpio"
|
||||||
|
|
||||||
|
type ArticleQueryRequest struct {
|
||||||
|
Title string `json:"title"`
|
||||||
|
}
|
||||||
|
|
||||||
|
func (a ArticleQueryRequest) Validate() *httpio.HTTPError {
|
||||||
|
titleLength := len(a.Title)
|
||||||
|
if titleLength < 1 || titleLength > 255 {
|
||||||
|
return &ErrHttpArticleTitleInvalidLength
|
||||||
|
}
|
||||||
|
|
||||||
|
return nil
|
||||||
|
}
|
||||||
15
api/article/response.go
Normal file
15
api/article/response.go
Normal file
@@ -0,0 +1,15 @@
|
|||||||
|
package article
|
||||||
|
|
||||||
|
import "scrap/api/httpio"
|
||||||
|
|
||||||
|
type ArticleResponse struct {
|
||||||
|
Uuid string `json:"uuid"`
|
||||||
|
Title string `json:"title"`
|
||||||
|
Content string `json:"content"`
|
||||||
|
}
|
||||||
|
|
||||||
|
func ArticleQueryResponse(articles []ArticleResponse) httpio.ResponseIO {
|
||||||
|
return httpio.ResponseIO{
|
||||||
|
"articles": articles,
|
||||||
|
}
|
||||||
|
}
|
||||||
24
api/httpio/httperror.go
Normal file
24
api/httpio/httperror.go
Normal file
@@ -0,0 +1,24 @@
|
|||||||
|
package httpio
|
||||||
|
|
||||||
|
import (
|
||||||
|
"encoding/json"
|
||||||
|
"net/http"
|
||||||
|
)
|
||||||
|
|
||||||
|
type HTTPError struct {
|
||||||
|
StatusCode int `json:"-"`
|
||||||
|
ErrorCode string `json:"error-code"`
|
||||||
|
Message string `json:"message"`
|
||||||
|
}
|
||||||
|
|
||||||
|
func (h HTTPError) Raise(w http.ResponseWriter) {
|
||||||
|
jsonBytes, _ := json.Marshal(h)
|
||||||
|
|
||||||
|
w.Header().Set("Content-Type", "application/json")
|
||||||
|
w.WriteHeader(h.StatusCode)
|
||||||
|
w.Write(jsonBytes)
|
||||||
|
}
|
||||||
|
|
||||||
|
func RaiseOnlyStatusCode(w http.ResponseWriter, code int) {
|
||||||
|
http.Error(w, "", code)
|
||||||
|
}
|
||||||
38
api/httpio/request.go
Normal file
38
api/httpio/request.go
Normal file
@@ -0,0 +1,38 @@
|
|||||||
|
package httpio
|
||||||
|
|
||||||
|
import (
|
||||||
|
"encoding/json"
|
||||||
|
"errors"
|
||||||
|
"io"
|
||||||
|
"log"
|
||||||
|
"net/http"
|
||||||
|
)
|
||||||
|
|
||||||
|
type IRequestIO interface {
|
||||||
|
// Validates the received request.
|
||||||
|
Validate() *HTTPError
|
||||||
|
}
|
||||||
|
|
||||||
|
// Parses request body into the provided struct.
|
||||||
|
// Throws an error if the body could not be parsed.
|
||||||
|
func ParseRequestBody[T IRequestIO](r *http.Request) (*T, error) {
|
||||||
|
requestBytes, err := io.ReadAll(r.Body)
|
||||||
|
if err != nil {
|
||||||
|
log.Println(err.Error())
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
if !json.Valid(requestBytes) {
|
||||||
|
return nil, errors.New("invalid JSON format")
|
||||||
|
}
|
||||||
|
|
||||||
|
var req T
|
||||||
|
err = json.Unmarshal(requestBytes, &req)
|
||||||
|
if err != nil {
|
||||||
|
log.Println(err.Error())
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
return &req, nil
|
||||||
|
|
||||||
|
}
|
||||||
21
api/httpio/response.go
Normal file
21
api/httpio/response.go
Normal file
@@ -0,0 +1,21 @@
|
|||||||
|
package httpio
|
||||||
|
|
||||||
|
import (
|
||||||
|
"encoding/json"
|
||||||
|
"net/http"
|
||||||
|
)
|
||||||
|
|
||||||
|
type ResponseIO map[string]any
|
||||||
|
|
||||||
|
func (r ResponseIO) Return(w http.ResponseWriter, statusCode int) error {
|
||||||
|
jsonBytes, err := json.Marshal(r)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
w.Header().Set("Content-Type", "application/json")
|
||||||
|
w.WriteHeader(statusCode)
|
||||||
|
w.Write(jsonBytes)
|
||||||
|
|
||||||
|
return nil
|
||||||
|
}
|
||||||
86
api/httpio/urlquery.go
Normal file
86
api/httpio/urlquery.go
Normal file
@@ -0,0 +1,86 @@
|
|||||||
|
package httpio
|
||||||
|
|
||||||
|
import (
|
||||||
|
"encoding/json"
|
||||||
|
"errors"
|
||||||
|
"net/http"
|
||||||
|
"strconv"
|
||||||
|
)
|
||||||
|
|
||||||
|
type URLQueryValueType interface {
|
||||||
|
string | int | float32 | float64 | bool
|
||||||
|
}
|
||||||
|
|
||||||
|
type iURLQueryKeyType interface {
|
||||||
|
GetKey() string
|
||||||
|
}
|
||||||
|
|
||||||
|
type URLQueryKeyType[T URLQueryValueType] struct {
|
||||||
|
Key string
|
||||||
|
_ T
|
||||||
|
}
|
||||||
|
|
||||||
|
func (u URLQueryKeyType[T]) GetKey() string { return u.Key }
|
||||||
|
|
||||||
|
func URLQueryKey[T URLQueryValueType](key string) iURLQueryKeyType {
|
||||||
|
return URLQueryKeyType[T]{
|
||||||
|
Key: key,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func ParseURLQuery[T IRequestIO](r *http.Request, keys ...iURLQueryKeyType) (*T, error) {
|
||||||
|
query := make(map[string]any, len(keys))
|
||||||
|
|
||||||
|
for _, key := range keys {
|
||||||
|
queryValue := r.URL.Query().Get(key.GetKey())
|
||||||
|
|
||||||
|
if queryValue == "" {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
|
switch key.(type) {
|
||||||
|
case URLQueryKeyType[string]:
|
||||||
|
query[key.GetKey()] = queryValue
|
||||||
|
case URLQueryKeyType[int]:
|
||||||
|
x, err := strconv.Atoi(queryValue)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
query[key.GetKey()] = x
|
||||||
|
case URLQueryKeyType[float32]:
|
||||||
|
x, err := strconv.ParseFloat(queryValue, 32)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
query[key.GetKey()] = x
|
||||||
|
case URLQueryKeyType[float64]:
|
||||||
|
x, err := strconv.ParseFloat(queryValue, 64)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
query[key.GetKey()] = x
|
||||||
|
case URLQueryKeyType[bool]:
|
||||||
|
x, err := strconv.ParseBool(queryValue)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
query[key.GetKey()] = x
|
||||||
|
default:
|
||||||
|
return nil, errors.New("unsupported URL query key type")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
queryBytes, _ := json.Marshal(query)
|
||||||
|
|
||||||
|
var req T
|
||||||
|
err := json.Unmarshal(queryBytes, &req)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
return &req, nil
|
||||||
|
}
|
||||||
18
api/setup.go
Normal file
18
api/setup.go
Normal file
@@ -0,0 +1,18 @@
|
|||||||
|
package api
|
||||||
|
|
||||||
|
import (
|
||||||
|
"net/http"
|
||||||
|
"scrap/api/article"
|
||||||
|
|
||||||
|
"github.com/go-chi/chi"
|
||||||
|
)
|
||||||
|
|
||||||
|
func Setup() {
|
||||||
|
r := chi.NewRouter()
|
||||||
|
|
||||||
|
r.Get("/articles", article.ArticleQueryHandler)
|
||||||
|
r.Get("/articles-download", article.ArticleDownloadHandler)
|
||||||
|
r.Handle("/tiles/", http.StripPrefix("/tiles/", http.FileServer(http.Dir("tiles"))))
|
||||||
|
|
||||||
|
http.ListenAndServe(":8080", r)
|
||||||
|
}
|
||||||
@@ -1,5 +1,22 @@
|
|||||||
package serve
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"log"
|
||||||
|
"scrap/api"
|
||||||
|
"scrap/internal/config"
|
||||||
|
"scrap/internal/db"
|
||||||
|
"scrap/internal/osm"
|
||||||
|
)
|
||||||
|
|
||||||
func main() {
|
func main() {
|
||||||
|
config.Setup()
|
||||||
|
|
||||||
|
db.Setup()
|
||||||
|
defer db.Close()
|
||||||
|
|
||||||
|
log.SetFlags(log.Lshortfile)
|
||||||
|
|
||||||
|
osm.OSM()
|
||||||
|
|
||||||
|
api.Setup()
|
||||||
}
|
}
|
||||||
|
|||||||
4
config.json
Normal file
4
config.json
Normal file
@@ -0,0 +1,4 @@
|
|||||||
|
{
|
||||||
|
"sql-tables-dir": "./sqltable/",
|
||||||
|
"sql-database-name": "scrap.db"
|
||||||
|
}
|
||||||
25
go.mod
25
go.mod
@@ -1,3 +1,28 @@
|
|||||||
module scrap
|
module scrap
|
||||||
|
|
||||||
go 1.24.4
|
go 1.24.4
|
||||||
|
|
||||||
|
require (
|
||||||
|
github.com/go-chi/chi v1.5.5
|
||||||
|
github.com/gocolly/colly v1.2.0
|
||||||
|
github.com/mattn/go-sqlite3 v1.14.32
|
||||||
|
)
|
||||||
|
|
||||||
|
require (
|
||||||
|
github.com/PuerkitoBio/goquery v1.10.3 // indirect
|
||||||
|
github.com/andybalholm/cascadia v1.3.3 // indirect
|
||||||
|
github.com/antchfx/htmlquery v1.3.4 // indirect
|
||||||
|
github.com/antchfx/xmlquery v1.4.4 // indirect
|
||||||
|
github.com/antchfx/xpath v1.3.5 // indirect
|
||||||
|
github.com/gobwas/glob v0.2.3 // indirect
|
||||||
|
github.com/golang/groupcache v0.0.0-20241129210726-2c02b8208cf8 // indirect
|
||||||
|
github.com/golang/protobuf v1.5.4 // indirect
|
||||||
|
github.com/google/uuid v1.6.0
|
||||||
|
github.com/kennygrant/sanitize v1.2.4 // indirect
|
||||||
|
github.com/saintfish/chardet v0.0.0-20230101081208-5e3ef4b5456d // indirect
|
||||||
|
github.com/temoto/robotstxt v1.1.2 // indirect
|
||||||
|
golang.org/x/net v0.44.0 // indirect
|
||||||
|
golang.org/x/text v0.29.0 // indirect
|
||||||
|
google.golang.org/appengine v1.6.8 // indirect
|
||||||
|
google.golang.org/protobuf v1.36.10 // indirect
|
||||||
|
)
|
||||||
|
|||||||
121
go.sum
Normal file
121
go.sum
Normal file
@@ -0,0 +1,121 @@
|
|||||||
|
github.com/PuerkitoBio/goquery v1.10.3 h1:pFYcNSqHxBD06Fpj/KsbStFRsgRATgnf3LeXiUkhzPo=
|
||||||
|
github.com/PuerkitoBio/goquery v1.10.3/go.mod h1:tMUX0zDMHXYlAQk6p35XxQMqMweEKB7iK7iLNd4RH4Y=
|
||||||
|
github.com/andybalholm/cascadia v1.3.3 h1:AG2YHrzJIm4BZ19iwJ/DAua6Btl3IwJX+VI4kktS1LM=
|
||||||
|
github.com/andybalholm/cascadia v1.3.3/go.mod h1:xNd9bqTn98Ln4DwST8/nG+H0yuB8Hmgu1YHNnWw0GeA=
|
||||||
|
github.com/antchfx/htmlquery v1.3.4 h1:Isd0srPkni2iNTWCwVj/72t7uCphFeor5Q8nCzj1jdQ=
|
||||||
|
github.com/antchfx/htmlquery v1.3.4/go.mod h1:K9os0BwIEmLAvTqaNSua8tXLWRWZpocZIH73OzWQbwM=
|
||||||
|
github.com/antchfx/xmlquery v1.4.4 h1:mxMEkdYP3pjKSftxss4nUHfjBhnMk4imGoR96FRY2dg=
|
||||||
|
github.com/antchfx/xmlquery v1.4.4/go.mod h1:AEPEEPYE9GnA2mj5Ur2L5Q5/2PycJ0N9Fusrx9b12fc=
|
||||||
|
github.com/antchfx/xpath v1.3.3/go.mod h1:i54GszH55fYfBmoZXapTHN8T8tkcHfRgLyVwwqzXNcs=
|
||||||
|
github.com/antchfx/xpath v1.3.5 h1:PqbXLC3TkfeZyakF5eeh3NTWEbYl4VHNVeufANzDbKQ=
|
||||||
|
github.com/antchfx/xpath v1.3.5/go.mod h1:i54GszH55fYfBmoZXapTHN8T8tkcHfRgLyVwwqzXNcs=
|
||||||
|
github.com/davecgh/go-spew v1.1.0 h1:ZDRjVQ15GmhC3fiQ8ni8+OwkZQO4DARzQgrnXU1Liz8=
|
||||||
|
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||||
|
github.com/go-chi/chi v1.5.5 h1:vOB/HbEMt9QqBqErz07QehcOKHaWFtuj87tTDVz2qXE=
|
||||||
|
github.com/go-chi/chi v1.5.5/go.mod h1:C9JqLr3tIYjDOZpzn+BCuxY8z8vmca43EeMgyZt7irw=
|
||||||
|
github.com/gobwas/glob v0.2.3 h1:A4xDbljILXROh+kObIiy5kIaPYD8e96x1tgBhUI5J+Y=
|
||||||
|
github.com/gobwas/glob v0.2.3/go.mod h1:d3Ez4x06l9bZtSvzIay5+Yzi0fmZzPgnTbPcKjJAkT8=
|
||||||
|
github.com/gocolly/colly v1.2.0 h1:qRz9YAn8FIH0qzgNUw+HT9UN7wm1oF9OBAilwEWpyrI=
|
||||||
|
github.com/gocolly/colly v1.2.0/go.mod h1:Hof5T3ZswNVsOHYmba1u03W65HDWgpV5HifSuueE0EA=
|
||||||
|
github.com/golang/groupcache v0.0.0-20210331224755-41bb18bfe9da/go.mod h1:cIg4eruTrX1D+g88fzRXU5OdNfaM+9IcxsU14FzY7Hc=
|
||||||
|
github.com/golang/groupcache v0.0.0-20241129210726-2c02b8208cf8 h1:f+oWsMOmNPc8JmEHVZIycC7hBoQxHH9pNKQORJNozsQ=
|
||||||
|
github.com/golang/groupcache v0.0.0-20241129210726-2c02b8208cf8/go.mod h1:wcDNUvekVysuuOpQKo3191zZyTpiI6se1N1ULghS0sw=
|
||||||
|
github.com/golang/protobuf v1.5.0/go.mod h1:FsONVRAS9T7sI+LIUmWTfcYkHO4aIWwzhcaSAoJOfIk=
|
||||||
|
github.com/golang/protobuf v1.5.2/go.mod h1:XVQd3VNwM+JqD3oG2Ue2ip4fOMUkwXdXDdiuN0vRsmY=
|
||||||
|
github.com/golang/protobuf v1.5.4 h1:i7eJL8qZTpSEXOPTxNKhASYpMn+8e5Q6AdndVa1dWek=
|
||||||
|
github.com/golang/protobuf v1.5.4/go.mod h1:lnTiLA8Wa4RWRcIUkrtSVa5nRhsEGBg48fD6rSs7xps=
|
||||||
|
github.com/google/go-cmp v0.5.5/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=
|
||||||
|
github.com/google/go-cmp v0.6.0/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY=
|
||||||
|
github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8=
|
||||||
|
github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU=
|
||||||
|
github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
|
||||||
|
github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
|
||||||
|
github.com/kennygrant/sanitize v1.2.4 h1:gN25/otpP5vAsO2djbMhF/LQX6R7+O1TB4yv8NzpJ3o=
|
||||||
|
github.com/kennygrant/sanitize v1.2.4/go.mod h1:LGsjYYtgxbetdg5owWB2mpgUL6e2nfw2eObZ0u0qvak=
|
||||||
|
github.com/mattn/go-sqlite3 v1.14.32 h1:JD12Ag3oLy1zQA+BNn74xRgaBbdhbNIDYvQUEuuErjs=
|
||||||
|
github.com/mattn/go-sqlite3 v1.14.32/go.mod h1:Uh1q+B4BYcTPb+yiD3kU8Ct7aC0hY9fxUwlHK0RXw+Y=
|
||||||
|
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
|
||||||
|
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
|
||||||
|
github.com/saintfish/chardet v0.0.0-20230101081208-5e3ef4b5456d h1:hrujxIzL1woJ7AwssoOcM/tq5JjjG2yYOc8odClEiXA=
|
||||||
|
github.com/saintfish/chardet v0.0.0-20230101081208-5e3ef4b5456d/go.mod h1:uugorj2VCxiV1x+LzaIdVa9b4S4qGAcH6cbhh4qVxOU=
|
||||||
|
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
|
||||||
|
github.com/stretchr/testify v1.3.0 h1:TivCn/peBQ7UY8ooIcPgZFpTNSz0Q2U6UrFlUfqbe0Q=
|
||||||
|
github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
|
||||||
|
github.com/temoto/robotstxt v1.1.2 h1:W2pOjSJ6SWvldyEuiFXNxz3xZ8aiWX5LbfDiOFd7Fxg=
|
||||||
|
github.com/temoto/robotstxt v1.1.2/go.mod h1:+1AmkuG3IYkh1kv0d2qEB9Le88ehNO0zwOr3ujewlOo=
|
||||||
|
github.com/yuin/goldmark v1.4.13/go.mod h1:6yULJ656Px+3vBD8DxQVa3kxgyrAnzto9xy5taEt/CY=
|
||||||
|
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.13.0/go.mod h1:y6Z2r+Rw4iayiXXAIxJIDAJ1zMW4yaTpebo8fPOliYc=
|
||||||
|
golang.org/x/crypto v0.19.0/go.mod h1:Iy9bg/ha4yyC70EfRS8jz+B6ybOBKMaSxLj6P6oBDfU=
|
||||||
|
golang.org/x/crypto v0.23.0/go.mod h1:CKFgDieR+mRhux2Lsu27y0fO304Db0wZe70UKqHu0v8=
|
||||||
|
golang.org/x/crypto v0.31.0/go.mod h1:kDsLvtWBEx7MV9tJOj9bnXsPbxwJQ6csT/x4KIN4Ssk=
|
||||||
|
golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4=
|
||||||
|
golang.org/x/mod v0.8.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs=
|
||||||
|
golang.org/x/mod v0.12.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs=
|
||||||
|
golang.org/x/mod v0.15.0/go.mod h1:hTbmBsO62+eylJbnUtE2MGJUyE7QWk4xUqPFrRgJ+7c=
|
||||||
|
golang.org/x/mod v0.17.0/go.mod h1:hTbmBsO62+eylJbnUtE2MGJUyE7QWk4xUqPFrRgJ+7c=
|
||||||
|
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-20220722155237-a158d28d115b/go.mod h1:XRhObCWvk6IyKnWLug+ECip1KBveYUHfp+8e9klMJ9c=
|
||||||
|
golang.org/x/net v0.6.0/go.mod h1:2Tu9+aMcznHK/AK1HMvgo6xiTLG5rD5rZLDS+rp2Bjs=
|
||||||
|
golang.org/x/net v0.10.0/go.mod h1:0qNGK6F8kojg2nk9dLZ2mShWaEBan6FAoqfSigmmuDg=
|
||||||
|
golang.org/x/net v0.15.0/go.mod h1:idbUs1IY1+zTqbi8yxTbhexhEEk5ur9LInksu6HrEpk=
|
||||||
|
golang.org/x/net v0.21.0/go.mod h1:bIjVDfnllIU7BJ2DNgfnXvpSvtn8VRwhlsaeUTyUS44=
|
||||||
|
golang.org/x/net v0.25.0/go.mod h1:JkAGAh7GEvH74S6FOH42FLoXpXbE/aqXSrIQjXgsiwM=
|
||||||
|
golang.org/x/net v0.33.0/go.mod h1:HXLR5J+9DxmrqMwG9qjGCxZ+zKXxBru04zlTvWlWuN4=
|
||||||
|
golang.org/x/net v0.44.0 h1:evd8IRDyfNBMBTTY5XRF1vaZlD+EmWx6x8PkhR04H/I=
|
||||||
|
golang.org/x/net v0.44.0/go.mod h1:ECOoLqd5U3Lhyeyo/QDCEVQ4sNgYsqvCZ722XogGieY=
|
||||||
|
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/sync v0.1.0/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
||||||
|
golang.org/x/sync v0.3.0/go.mod h1:FU7BRWz2tNW+3quACPkgCx/L+uEAv1htQ0V83Z9Rj+Y=
|
||||||
|
golang.org/x/sync v0.6.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk=
|
||||||
|
golang.org/x/sync v0.7.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk=
|
||||||
|
golang.org/x/sync v0.10.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk=
|
||||||
|
golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
|
||||||
|
golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||||
|
golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||||
|
golang.org/x/sys v0.0.0-20220520151302-bc2c85ada10a/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||||
|
golang.org/x/sys v0.0.0-20220722155257-8c9f86f7a55f/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||||
|
golang.org/x/sys v0.5.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||||
|
golang.org/x/sys v0.8.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||||
|
golang.org/x/sys v0.12.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||||
|
golang.org/x/sys v0.17.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
|
||||||
|
golang.org/x/sys v0.20.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
|
||||||
|
golang.org/x/sys v0.28.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
|
||||||
|
golang.org/x/telemetry v0.0.0-20240228155512-f48c80bd79b2/go.mod h1:TeRTkGYfJXctD9OcfyVLyj2J3IxLnKwHJR8f4D8a3YE=
|
||||||
|
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=
|
||||||
|
golang.org/x/term v0.8.0/go.mod h1:xPskH00ivmX89bAKVGSKKtLOWNx2+17Eiy94tnKShWo=
|
||||||
|
golang.org/x/term v0.12.0/go.mod h1:owVbMEjm3cBLCHdkQu9b1opXd4ETQWc3BhuQGKgXgvU=
|
||||||
|
golang.org/x/term v0.17.0/go.mod h1:lLRBjIVuehSbZlaOtGMbcMncT+aqLLLmKrsjNrUguwk=
|
||||||
|
golang.org/x/term v0.20.0/go.mod h1:8UkIAJTvZgivsXaD6/pH6U9ecQzZ45awqEOzuCvwpFY=
|
||||||
|
golang.org/x/term v0.27.0/go.mod h1:iMsnZpn0cago0GOrHO2+Y7u7JPn5AylBrcoWkElMTSM=
|
||||||
|
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
|
||||||
|
golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
|
||||||
|
golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ=
|
||||||
|
golang.org/x/text v0.3.8/go.mod h1:E6s5w1FMmriuDzIBO73fBruAKo1PCIq6d2Q6DHfQ8WQ=
|
||||||
|
golang.org/x/text v0.7.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8=
|
||||||
|
golang.org/x/text v0.9.0/go.mod h1:e1OnstbJyHTd6l/uOt8jFFHp6TRDWZR/bV3emEE/zU8=
|
||||||
|
golang.org/x/text v0.13.0/go.mod h1:TvPlkZtksWOMsz7fbANvkp4WM8x/WCo/om8BMLbz+aE=
|
||||||
|
golang.org/x/text v0.14.0/go.mod h1:18ZOQIKpY8NJVqYksKHtTdi31H5itFRjB5/qKTNYzSU=
|
||||||
|
golang.org/x/text v0.15.0/go.mod h1:18ZOQIKpY8NJVqYksKHtTdi31H5itFRjB5/qKTNYzSU=
|
||||||
|
golang.org/x/text v0.21.0/go.mod h1:4IBbMaMmOPCJ8SecivzSH54+73PCFmPWxNTLm+vZkEQ=
|
||||||
|
golang.org/x/text v0.29.0 h1:1neNs90w9YzJ9BocxfsQNHKuAT4pkghyXc4nhZ6sJvk=
|
||||||
|
golang.org/x/text v0.29.0/go.mod h1:7MhJOA9CD2qZyOKYazxdYMF85OwPdEr9jTtBpO7ydH4=
|
||||||
|
golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
|
||||||
|
golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo=
|
||||||
|
golang.org/x/tools v0.1.12/go.mod h1:hNGJHUnrk76NpqgfD5Aqm5Crs+Hm0VOH/i9J2+nxYbc=
|
||||||
|
golang.org/x/tools v0.6.0/go.mod h1:Xwgl3UAJ/d3gWutnCtw505GrjyAbvKui8lOU390QaIU=
|
||||||
|
golang.org/x/tools v0.13.0/go.mod h1:HvlwmtVNQAhOuCjW7xxvovg8wbNq7LwfXh/k7wXUl58=
|
||||||
|
golang.org/x/tools v0.21.1-0.20240508182429-e35e4ccd0d2d/go.mod h1:aiJjzUbINMkxbQROHiO6hDPo2LHcIPhhQsa9DLh0yGk=
|
||||||
|
golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
|
||||||
|
golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
|
||||||
|
google.golang.org/appengine v1.6.8 h1:IhEN5q69dyKagZPYMSdIjS2HqprW324FRQZJcGqPAsM=
|
||||||
|
google.golang.org/appengine v1.6.8/go.mod h1:1jJ3jBArFh5pcgW8gCtRJnepW8FzD1V44FJffLiz/Ds=
|
||||||
|
google.golang.org/protobuf v1.26.0-rc.1/go.mod h1:jlhhOSvTdKEhbULTjvd4ARK9grFBp09yW+WbY/TyQbw=
|
||||||
|
google.golang.org/protobuf v1.26.0/go.mod h1:9q0QmTI4eRPtz6boOQmLYwt+qCgq0jsYwAQnmE0givc=
|
||||||
|
google.golang.org/protobuf v1.36.10 h1:AYd7cD/uASjIL6Q9LiTjz8JLcrh/88q5UObnmY3aOOE=
|
||||||
|
google.golang.org/protobuf v1.36.10/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco=
|
||||||
11
internal/article/dto.go
Normal file
11
internal/article/dto.go
Normal file
@@ -0,0 +1,11 @@
|
|||||||
|
package article
|
||||||
|
|
||||||
|
type ArticleDTO struct {
|
||||||
|
Uuid string
|
||||||
|
Title string
|
||||||
|
Content string
|
||||||
|
}
|
||||||
|
|
||||||
|
type ArticleQueryDTO struct {
|
||||||
|
Title string
|
||||||
|
}
|
||||||
12
internal/article/error.go
Normal file
12
internal/article/error.go
Normal file
@@ -0,0 +1,12 @@
|
|||||||
|
package article
|
||||||
|
|
||||||
|
import "errors"
|
||||||
|
|
||||||
|
var (
|
||||||
|
ErrArticleDownloadFailed = errors.New("article: download failed")
|
||||||
|
ErrArticleQueryFailed = errors.New("article: article query failed")
|
||||||
|
ErrArticleCreateFailed = errors.New("article: create failed")
|
||||||
|
ErrArticleDeleteAllFailed = errors.New("article: failed to delete all articles")
|
||||||
|
|
||||||
|
ErrArticleTitleInvalidLength = errors.New("article: invalid article length")
|
||||||
|
)
|
||||||
9
internal/article/irepository.go
Normal file
9
internal/article/irepository.go
Normal file
@@ -0,0 +1,9 @@
|
|||||||
|
package article
|
||||||
|
|
||||||
|
import "database/sql"
|
||||||
|
|
||||||
|
type IArticleRepository interface {
|
||||||
|
CreateArticle(tx *sql.Tx, data ArticleCreateModel) error
|
||||||
|
GetArticlesByTitle(tx *sql.Tx, title string) ([]ArticleModel, error)
|
||||||
|
DeleteAllArticles(tx *sql.Tx) error
|
||||||
|
}
|
||||||
6
internal/article/iservice.go
Normal file
6
internal/article/iservice.go
Normal file
@@ -0,0 +1,6 @@
|
|||||||
|
package article
|
||||||
|
|
||||||
|
type IArticleService interface {
|
||||||
|
DownloadArticles() error
|
||||||
|
QueryArticles(ArticleQueryDTO) ([]ArticleDTO, error)
|
||||||
|
}
|
||||||
13
internal/article/model.go
Normal file
13
internal/article/model.go
Normal file
@@ -0,0 +1,13 @@
|
|||||||
|
package article
|
||||||
|
|
||||||
|
type ArticleModel struct {
|
||||||
|
Uuid string
|
||||||
|
Title string
|
||||||
|
Content string
|
||||||
|
}
|
||||||
|
|
||||||
|
type ArticleCreateModel struct {
|
||||||
|
Uuid string
|
||||||
|
Title string
|
||||||
|
Content string
|
||||||
|
}
|
||||||
60
internal/article/repository.go
Normal file
60
internal/article/repository.go
Normal file
@@ -0,0 +1,60 @@
|
|||||||
|
package article
|
||||||
|
|
||||||
|
import (
|
||||||
|
"database/sql"
|
||||||
|
"fmt"
|
||||||
|
)
|
||||||
|
|
||||||
|
type ArticleRepository struct{}
|
||||||
|
|
||||||
|
func NewArticleRepository() IArticleRepository {
|
||||||
|
return &ArticleRepository{}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (ArticleRepository) CreateArticle(tx *sql.Tx, data ArticleCreateModel) error {
|
||||||
|
query := `
|
||||||
|
INSERT INTO articles(uuid, title, content)
|
||||||
|
VALUES ($1, $2, $3);
|
||||||
|
`
|
||||||
|
|
||||||
|
_, err := tx.Exec(query, data.Uuid, data.Title, data.Content)
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
func (ArticleRepository) GetArticlesByTitle(tx *sql.Tx, title string) ([]ArticleModel, error) {
|
||||||
|
fmt.Println(title, " ------------------")
|
||||||
|
query := `
|
||||||
|
SELECT uuid, title, content
|
||||||
|
FROM articles
|
||||||
|
WHERE title LIKE $1 || '%'
|
||||||
|
LIMIT 10;
|
||||||
|
`
|
||||||
|
|
||||||
|
rows, err := tx.Query(query, title)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
articles := []ArticleModel{}
|
||||||
|
for rows.Next() {
|
||||||
|
var a ArticleModel
|
||||||
|
|
||||||
|
err = rows.Scan(&a.Uuid, &a.Title, &a.Content)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
articles = append(articles, a)
|
||||||
|
}
|
||||||
|
|
||||||
|
fmt.Println(articles)
|
||||||
|
|
||||||
|
return articles, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (ArticleRepository) DeleteAllArticles(tx *sql.Tx) error {
|
||||||
|
query := `DELETE FROM articles;`
|
||||||
|
|
||||||
|
_, err := tx.Exec(query)
|
||||||
|
return err
|
||||||
|
}
|
||||||
107
internal/article/service.go
Normal file
107
internal/article/service.go
Normal file
@@ -0,0 +1,107 @@
|
|||||||
|
package article
|
||||||
|
|
||||||
|
import (
|
||||||
|
"log"
|
||||||
|
"scrap/internal/db"
|
||||||
|
"scrap/internal/wikipediadl"
|
||||||
|
|
||||||
|
"github.com/google/uuid"
|
||||||
|
)
|
||||||
|
|
||||||
|
type ArticleService struct {
|
||||||
|
txRepo db.ITxRepository
|
||||||
|
articleRepo IArticleRepository
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewArticleService(
|
||||||
|
txRepo db.ITxRepository,
|
||||||
|
articleRepo IArticleRepository,
|
||||||
|
) IArticleService {
|
||||||
|
return &ArticleService{
|
||||||
|
txRepo: txRepo,
|
||||||
|
articleRepo: articleRepo,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (a ArticleService) QueryArticles(data ArticleQueryDTO) ([]ArticleDTO, error) {
|
||||||
|
tx, err := a.txRepo.Begin()
|
||||||
|
if err != nil {
|
||||||
|
log.Println(err.Error())
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
defer a.txRepo.RollbackOnError(tx, &err)
|
||||||
|
|
||||||
|
articleTitleLength := len(data.Title)
|
||||||
|
if articleTitleLength < 1 || articleTitleLength > 255 {
|
||||||
|
return nil, ErrArticleTitleInvalidLength
|
||||||
|
}
|
||||||
|
|
||||||
|
articles, err := a.articleRepo.GetArticlesByTitle(tx, data.Title)
|
||||||
|
if err != nil {
|
||||||
|
log.Println(err.Error())
|
||||||
|
return nil, ErrArticleQueryFailed
|
||||||
|
}
|
||||||
|
|
||||||
|
articlesOut := make([]ArticleDTO, 0, len(articles))
|
||||||
|
for _, am := range articles {
|
||||||
|
a := ArticleDTO{
|
||||||
|
Uuid: am.Uuid,
|
||||||
|
Title: am.Title,
|
||||||
|
Content: am.Content,
|
||||||
|
}
|
||||||
|
|
||||||
|
articlesOut = append(articlesOut, a)
|
||||||
|
}
|
||||||
|
|
||||||
|
return articlesOut, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (a ArticleService) DownloadArticles() error {
|
||||||
|
tx, err := a.txRepo.Begin()
|
||||||
|
if err != nil {
|
||||||
|
log.Println(err.Error())
|
||||||
|
return db.ErrTxBeginFailed
|
||||||
|
}
|
||||||
|
|
||||||
|
defer a.txRepo.RollbackOnError(tx, &err)
|
||||||
|
|
||||||
|
if err = a.articleRepo.DeleteAllArticles(tx); err != nil {
|
||||||
|
log.Println(err.Error())
|
||||||
|
return ErrArticleDeleteAllFailed
|
||||||
|
}
|
||||||
|
|
||||||
|
articleBundles, err := wikipediadl.FetchArticleBundles()
|
||||||
|
if err != nil {
|
||||||
|
log.Println(err.Error())
|
||||||
|
return ErrArticleDownloadFailed
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, ab := range articleBundles {
|
||||||
|
articles, err := wikipediadl.ExtractArticles(ab)
|
||||||
|
if err != nil {
|
||||||
|
log.Println(err.Error())
|
||||||
|
return ErrArticleDownloadFailed
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, article := range articles {
|
||||||
|
articleData := ArticleCreateModel{
|
||||||
|
Uuid: uuid.NewString(),
|
||||||
|
Title: article.Title,
|
||||||
|
Content: article.Revision.Text,
|
||||||
|
}
|
||||||
|
|
||||||
|
if err = a.articleRepo.CreateArticle(tx, articleData); err != nil {
|
||||||
|
log.Println(err.Error(), "tutaj ---------")
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if err = a.txRepo.Commit(tx); err != nil {
|
||||||
|
log.Println(err.Error())
|
||||||
|
return db.ErrTxCommitFailed
|
||||||
|
}
|
||||||
|
|
||||||
|
return nil
|
||||||
|
}
|
||||||
26
internal/config/setup.go
Normal file
26
internal/config/setup.go
Normal file
@@ -0,0 +1,26 @@
|
|||||||
|
package config
|
||||||
|
|
||||||
|
import (
|
||||||
|
"encoding/json"
|
||||||
|
"os"
|
||||||
|
)
|
||||||
|
|
||||||
|
type AppConfig struct {
|
||||||
|
SqlTablesDir string `json:"sql-tables-dir"`
|
||||||
|
SqlDatabaseName string `json:"sql-database-name"`
|
||||||
|
}
|
||||||
|
|
||||||
|
var appConfigInstance *AppConfig
|
||||||
|
|
||||||
|
func Setup() {
|
||||||
|
file, err := os.ReadFile("config.json")
|
||||||
|
if err != nil {
|
||||||
|
panic(err)
|
||||||
|
}
|
||||||
|
|
||||||
|
if err = json.Unmarshal(file, &appConfigInstance); err != nil {
|
||||||
|
panic(err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func GetAppConfig() *AppConfig { return appConfigInstance }
|
||||||
8
internal/db/error.go
Normal file
8
internal/db/error.go
Normal file
@@ -0,0 +1,8 @@
|
|||||||
|
package db
|
||||||
|
|
||||||
|
import "errors"
|
||||||
|
|
||||||
|
var (
|
||||||
|
ErrTxBeginFailed = errors.New("tx: could not begin a Tx")
|
||||||
|
ErrTxCommitFailed = errors.New("tx: could not commit the Tx")
|
||||||
|
)
|
||||||
14
internal/db/irepository.go
Normal file
14
internal/db/irepository.go
Normal file
@@ -0,0 +1,14 @@
|
|||||||
|
package db
|
||||||
|
|
||||||
|
import "database/sql"
|
||||||
|
|
||||||
|
type ITxRepository interface {
|
||||||
|
// Creates a new tx.
|
||||||
|
Begin() (*sql.Tx, error)
|
||||||
|
|
||||||
|
// Rollbacks tx's data or returns an error to the given error's pointer address.
|
||||||
|
RollbackOnError(*sql.Tx, *error)
|
||||||
|
|
||||||
|
// Applies changes to the database.
|
||||||
|
Commit(*sql.Tx) error
|
||||||
|
}
|
||||||
34
internal/db/repository.go
Normal file
34
internal/db/repository.go
Normal file
@@ -0,0 +1,34 @@
|
|||||||
|
package db
|
||||||
|
|
||||||
|
import (
|
||||||
|
"database/sql"
|
||||||
|
)
|
||||||
|
|
||||||
|
type TxRepository struct {
|
||||||
|
db *sql.DB
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewTxRepository(instance *sql.DB) ITxRepository {
|
||||||
|
return &TxRepository{
|
||||||
|
db: instance,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (t TxRepository) Begin() (*sql.Tx, error) {
|
||||||
|
tx, err := t.db.Begin()
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
return tx, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (TxRepository) RollbackOnError(tx *sql.Tx, errObserve *error) {
|
||||||
|
if *errObserve != nil {
|
||||||
|
tx.Rollback()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (TxRepository) Commit(tx *sql.Tx) error {
|
||||||
|
return tx.Commit()
|
||||||
|
}
|
||||||
67
internal/db/setup.go
Normal file
67
internal/db/setup.go
Normal file
@@ -0,0 +1,67 @@
|
|||||||
|
package db
|
||||||
|
|
||||||
|
import (
|
||||||
|
"database/sql"
|
||||||
|
"os"
|
||||||
|
"scrap/internal/config"
|
||||||
|
"strings"
|
||||||
|
|
||||||
|
_ "github.com/mattn/go-sqlite3"
|
||||||
|
)
|
||||||
|
|
||||||
|
var dbInstance *sql.DB
|
||||||
|
|
||||||
|
func Setup() {
|
||||||
|
cfg := config.GetAppConfig()
|
||||||
|
|
||||||
|
db, err := sql.Open("sqlite3", cfg.SqlDatabaseName)
|
||||||
|
if err != nil {
|
||||||
|
panic(err)
|
||||||
|
}
|
||||||
|
|
||||||
|
dbInstance = db
|
||||||
|
|
||||||
|
tableFilenames := getTableFilenames()
|
||||||
|
createTablesFromSQLFiles(tableFilenames)
|
||||||
|
}
|
||||||
|
|
||||||
|
func GetInstance() *sql.DB { return dbInstance }
|
||||||
|
|
||||||
|
func Close() { dbInstance.Close() }
|
||||||
|
|
||||||
|
func getTableFilenames() []string {
|
||||||
|
appConfig := config.GetAppConfig()
|
||||||
|
|
||||||
|
files, err := os.ReadDir(appConfig.SqlTablesDir)
|
||||||
|
if err != nil {
|
||||||
|
panic(err)
|
||||||
|
}
|
||||||
|
|
||||||
|
filenames := []string{}
|
||||||
|
for _, f := range files {
|
||||||
|
fName := f.Name()
|
||||||
|
if !strings.HasSuffix(fName, ".sql") {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
|
filenames = append(filenames, fName)
|
||||||
|
}
|
||||||
|
|
||||||
|
return filenames
|
||||||
|
}
|
||||||
|
|
||||||
|
func createTablesFromSQLFiles(filenames []string) {
|
||||||
|
appConfig := config.GetAppConfig()
|
||||||
|
|
||||||
|
for _, fName := range filenames {
|
||||||
|
tableBytes, err := os.ReadFile(appConfig.SqlTablesDir + fName)
|
||||||
|
if err != nil {
|
||||||
|
panic(err)
|
||||||
|
}
|
||||||
|
|
||||||
|
tableQuery := string(tableBytes)
|
||||||
|
if _, err = dbInstance.Exec(tableQuery); err != nil {
|
||||||
|
panic(err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
152
internal/osm/osm.go
Normal file
152
internal/osm/osm.go
Normal file
@@ -0,0 +1,152 @@
|
|||||||
|
package osm
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"fmt"
|
||||||
|
"io"
|
||||||
|
"log"
|
||||||
|
"math"
|
||||||
|
"net/http"
|
||||||
|
"os"
|
||||||
|
"path/filepath"
|
||||||
|
"runtime"
|
||||||
|
"strconv"
|
||||||
|
"sync"
|
||||||
|
"time"
|
||||||
|
)
|
||||||
|
|
||||||
|
var (
|
||||||
|
userLat = 50.06465
|
||||||
|
userLon = 19.94598
|
||||||
|
radiusM = 2000.0
|
||||||
|
maxZoom = 17
|
||||||
|
userAgent = "krakow-tiles-downloader/1.0 (+your_email@example.com)"
|
||||||
|
osmTileURL = "https://tile.openstreetmap.org/%d/%d/%d.png"
|
||||||
|
tilesDir = "tiles"
|
||||||
|
)
|
||||||
|
|
||||||
|
const earthRadius = 6378137.0
|
||||||
|
|
||||||
|
func offsetLatLon(lat, lon, distance, bearingRad float64) (float64, float64) {
|
||||||
|
r := earthRadius
|
||||||
|
latRad := lat * math.Pi / 180.0
|
||||||
|
lonRad := lon * math.Pi / 180.0
|
||||||
|
angDist := distance / r
|
||||||
|
newLatRad := math.Asin(math.Sin(latRad)*math.Cos(angDist) + math.Cos(latRad)*math.Sin(angDist)*math.Cos(bearingRad))
|
||||||
|
newLonRad := lonRad + math.Atan2(math.Sin(bearingRad)*math.Sin(angDist)*math.Cos(latRad),
|
||||||
|
math.Cos(angDist)-math.Sin(latRad)*math.Sin(newLatRad))
|
||||||
|
return newLatRad * 180.0 / math.Pi, newLonRad * 180.0 / math.Pi
|
||||||
|
}
|
||||||
|
|
||||||
|
func boundingBoxForCircle(lat, lon, radius float64) (minLat, maxLat, minLon, maxLon float64) {
|
||||||
|
maxLat, _ = offsetLatLon(lat, lon, radius, 0)
|
||||||
|
minLat, _ = offsetLatLon(lat, lon, radius, math.Pi)
|
||||||
|
_, maxLon = offsetLatLon(lat, lon, radius, math.Pi/2)
|
||||||
|
_, minLon = offsetLatLon(lat, lon, radius, 3*math.Pi/2)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
func latLonToTile(lat, lon float64, z int) (x, y int) {
|
||||||
|
latRad := lat * math.Pi / 180.0
|
||||||
|
n := math.Pow(2.0, float64(z))
|
||||||
|
xFloat := (lon + 180.0) / 360.0 * n
|
||||||
|
yFloat := (1.0 - math.Log(math.Tan(latRad)+1.0/math.Cos(latRad))/math.Pi) / 2.0 * n
|
||||||
|
return int(math.Floor(xFloat)), int(math.Floor(yFloat))
|
||||||
|
}
|
||||||
|
|
||||||
|
func tileXYBounds(minLat, maxLat, minLon, maxLon float64, z int) (minX, maxX, minY, maxY int) {
|
||||||
|
x1, y1 := latLonToTile(maxLat, minLon, z)
|
||||||
|
x2, y2 := latLonToTile(minLat, maxLon, z)
|
||||||
|
if x1 > x2 {
|
||||||
|
minX, maxX = x2, x1
|
||||||
|
} else {
|
||||||
|
minX, maxX = x1, x2
|
||||||
|
}
|
||||||
|
if y1 > y2 {
|
||||||
|
minY, maxY = y2, y1
|
||||||
|
} else {
|
||||||
|
minY, maxY = y1, y2
|
||||||
|
}
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
func downloadTile(ctx context.Context, z, x, y int) error {
|
||||||
|
url := fmt.Sprintf(osmTileURL, z, x, y)
|
||||||
|
req, _ := http.NewRequestWithContext(ctx, "GET", url, nil)
|
||||||
|
req.Header.Set("User-Agent", userAgent)
|
||||||
|
resp, err := http.DefaultClient.Do(req)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
defer resp.Body.Close()
|
||||||
|
|
||||||
|
if resp.StatusCode == 429 || resp.StatusCode == 403 {
|
||||||
|
time.Sleep(5 * time.Second)
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
if resp.StatusCode != 200 {
|
||||||
|
return fmt.Errorf("HTTP %d for %s", resp.StatusCode, url)
|
||||||
|
}
|
||||||
|
|
||||||
|
tileCount := 1 << uint(z)
|
||||||
|
yFlipped := tileCount - 1 - y
|
||||||
|
path := filepath.Join(tilesDir, strconv.Itoa(z), strconv.Itoa(x))
|
||||||
|
if err := os.MkdirAll(path, 0o755); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
filePath := filepath.Join(path, fmt.Sprintf("%d.png", yFlipped))
|
||||||
|
f, err := os.Create(filePath)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
defer f.Close()
|
||||||
|
_, err = io.Copy(f, resp.Body)
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
func downloadRange(ctx context.Context, z, minX, maxX, minY, maxY int) {
|
||||||
|
log.Printf("Downloading tiles zoom %d: x %d..%d, y %d..%d", z, minX, maxX, minY, maxY)
|
||||||
|
sem := make(chan struct{}, runtime.NumCPU())
|
||||||
|
var wg sync.WaitGroup
|
||||||
|
rate := time.NewTicker(1 * time.Second)
|
||||||
|
defer rate.Stop()
|
||||||
|
|
||||||
|
for x := minX; x <= maxX; x++ {
|
||||||
|
for y := minY; y <= maxY; y++ {
|
||||||
|
wg.Add(1)
|
||||||
|
sem <- struct{}{}
|
||||||
|
<-rate.C
|
||||||
|
go func(x, y int) {
|
||||||
|
defer wg.Done()
|
||||||
|
defer func() { <-sem }()
|
||||||
|
filePath := filepath.Join(tilesDir, strconv.Itoa(z), strconv.Itoa(x), fmt.Sprintf("%d.png", (1<<uint(z))-1-y))
|
||||||
|
if _, err := os.Stat(filePath); err == nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if err := downloadTile(ctx, z, x, y); err != nil {
|
||||||
|
log.Printf("Failed %d/%d/%d: %v", z, x, y, err)
|
||||||
|
}
|
||||||
|
}(x, y)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
wg.Wait()
|
||||||
|
}
|
||||||
|
|
||||||
|
func runDownloader(ctx context.Context) error {
|
||||||
|
minLat, maxLat, minLon, maxLon := boundingBoxForCircle(userLat, userLon, radiusM)
|
||||||
|
minX, maxX, minY, maxY := tileXYBounds(minLat, maxLat, minLon, maxLon, maxZoom)
|
||||||
|
downloadRange(ctx, maxZoom, minX, maxX, minY, maxY)
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func OSM(){
|
||||||
|
if err := os.MkdirAll(tilesDir, 0o755); err != nil {
|
||||||
|
log.Fatalf("failed to create tiles dir: %v", err)
|
||||||
|
}
|
||||||
|
ctx := context.Background()
|
||||||
|
go func() {
|
||||||
|
if err := runDownloader(ctx); err != nil {
|
||||||
|
log.Printf("Downloader finished with error: %v", err)
|
||||||
|
}
|
||||||
|
}()
|
||||||
|
}
|
||||||
6
internal/wikipediadl/const.go
Normal file
6
internal/wikipediadl/const.go
Normal file
@@ -0,0 +1,6 @@
|
|||||||
|
package wikipediadl
|
||||||
|
|
||||||
|
const (
|
||||||
|
WikipediaDumpDomain = "dumps.wikimedia.org"
|
||||||
|
WikipediaDumpUrl = "https://" + WikipediaDumpDomain + "/plwiki/latest/"
|
||||||
|
)
|
||||||
8
internal/wikipediadl/error.go
Normal file
8
internal/wikipediadl/error.go
Normal file
@@ -0,0 +1,8 @@
|
|||||||
|
package wikipediadl
|
||||||
|
|
||||||
|
import "errors"
|
||||||
|
|
||||||
|
var (
|
||||||
|
ErrArticleBundleFetchFailed = errors.New("wikipediadl: failed to fetch article bundles")
|
||||||
|
ErrArticleDownloadFailed = errors.New("wikipediadl: failed to extract articles")
|
||||||
|
)
|
||||||
75
internal/wikipediadl/extractarticles.go
Normal file
75
internal/wikipediadl/extractarticles.go
Normal file
@@ -0,0 +1,75 @@
|
|||||||
|
package wikipediadl
|
||||||
|
|
||||||
|
import (
|
||||||
|
"compress/bzip2"
|
||||||
|
"encoding/xml"
|
||||||
|
"errors"
|
||||||
|
"io"
|
||||||
|
"log"
|
||||||
|
"net/http"
|
||||||
|
)
|
||||||
|
|
||||||
|
type WikiArticle struct {
|
||||||
|
Title string `xml:"title"`
|
||||||
|
Revision Revision `xml:"revision"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type Revision struct {
|
||||||
|
Text string `xml:"text"`
|
||||||
|
}
|
||||||
|
|
||||||
|
func ExtractArticles(bundle string) ([]WikiArticle, error) {
|
||||||
|
url := WikipediaDumpUrl + bundle
|
||||||
|
|
||||||
|
resp, err := http.Get(url)
|
||||||
|
if err != nil {
|
||||||
|
log.Println(err.Error())
|
||||||
|
return nil, errors.New("wikipediadl: failed load articles")
|
||||||
|
}
|
||||||
|
|
||||||
|
defer resp.Body.Close()
|
||||||
|
|
||||||
|
if resp.StatusCode != 200 {
|
||||||
|
return nil, errors.New("wikipediadl: bad response status")
|
||||||
|
}
|
||||||
|
|
||||||
|
bz2Reader := bzip2.NewReader(resp.Body)
|
||||||
|
xmlDec := xml.NewDecoder(bz2Reader)
|
||||||
|
|
||||||
|
count := 0
|
||||||
|
|
||||||
|
articles := []WikiArticle{}
|
||||||
|
Loop:
|
||||||
|
for {
|
||||||
|
tok, err := xmlDec.Token()
|
||||||
|
if err != nil {
|
||||||
|
if err == io.EOF {
|
||||||
|
break
|
||||||
|
}
|
||||||
|
|
||||||
|
return nil, errors.New("XML token error")
|
||||||
|
}
|
||||||
|
|
||||||
|
switch se := tok.(type) {
|
||||||
|
case xml.StartElement:
|
||||||
|
if count == 2 { // XXX: remove later
|
||||||
|
break Loop
|
||||||
|
}
|
||||||
|
|
||||||
|
if se.Name.Local != "page" {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
|
var p WikiArticle
|
||||||
|
if err := xmlDec.DecodeElement(&p, &se); err != nil {
|
||||||
|
log.Println(err.Error())
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
|
articles = append(articles, p)
|
||||||
|
count++ // XXX: remove later
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return articles, nil
|
||||||
|
}
|
||||||
64
internal/wikipediadl/fetcharticles.go
Normal file
64
internal/wikipediadl/fetcharticles.go
Normal file
@@ -0,0 +1,64 @@
|
|||||||
|
package wikipediadl
|
||||||
|
|
||||||
|
import (
|
||||||
|
"log"
|
||||||
|
"strings"
|
||||||
|
|
||||||
|
"github.com/gocolly/colly"
|
||||||
|
)
|
||||||
|
|
||||||
|
const (
|
||||||
|
DumpDomain = "dumps.wikimedia.org"
|
||||||
|
DumpUrl = "https://dumps.wikimedia.org/plwiki/latest/"
|
||||||
|
)
|
||||||
|
|
||||||
|
func FetchArticleBundles() ([]string, error) {
|
||||||
|
scraper := getScraper()
|
||||||
|
|
||||||
|
articles := getAllArticles(scraper)
|
||||||
|
return articles, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func getScraper() *colly.Collector {
|
||||||
|
return colly.NewCollector(
|
||||||
|
colly.AllowedDomains(DumpDomain),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
func getAllArticles(s *colly.Collector) []string {
|
||||||
|
articles := []string{}
|
||||||
|
|
||||||
|
s.OnHTML("a", func(h *colly.HTMLElement) {
|
||||||
|
article := h.Attr("href")
|
||||||
|
if !isValidArticle(article) {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
articles = append(articles, h.Attr("href"))
|
||||||
|
|
||||||
|
})
|
||||||
|
|
||||||
|
s.OnError(func(r *colly.Response, err error) {
|
||||||
|
log.Println(r.Request.URL)
|
||||||
|
})
|
||||||
|
|
||||||
|
s.Visit(DumpUrl)
|
||||||
|
|
||||||
|
return articles
|
||||||
|
}
|
||||||
|
|
||||||
|
func isValidArticle(a string) bool {
|
||||||
|
const (
|
||||||
|
validPrefix = "plwiki-latest-pages-articles"
|
||||||
|
validSuffix = ".bz2"
|
||||||
|
)
|
||||||
|
|
||||||
|
if !strings.HasPrefix(a, validPrefix) || !strings.HasSuffix(a, validSuffix) {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
|
article, _ := strings.CutPrefix(a, validPrefix)
|
||||||
|
|
||||||
|
articleIndex := article[0]
|
||||||
|
return articleIndex >= 48 && articleIndex <= 57
|
||||||
|
}
|
||||||
5
sqltable/1_articles.sql
Normal file
5
sqltable/1_articles.sql
Normal file
@@ -0,0 +1,5 @@
|
|||||||
|
CREATE TABLE IF NOT EXISTS articles(
|
||||||
|
uuid CHAR(36) PRIMARY KEY,
|
||||||
|
title VARCHAR(255) NOT NULL,
|
||||||
|
content TEXT NOT NULL
|
||||||
|
)
|
||||||
Reference in New Issue
Block a user