This commit is contained in:
huangkun 2024-11-19 16:58:21 +08:00
parent 927d1af3e0
commit a056e3bb5f
101 changed files with 5738 additions and 89 deletions

View File

Before

Width:  |  Height:  |  Size: 1.4 KiB

After

Width:  |  Height:  |  Size: 1.4 KiB

View File

Before

Width:  |  Height:  |  Size: 2.8 KiB

After

Width:  |  Height:  |  Size: 2.8 KiB

View File

Before

Width:  |  Height:  |  Size: 982 B

After

Width:  |  Height:  |  Size: 982 B

View File

Before

Width:  |  Height:  |  Size: 1.7 KiB

After

Width:  |  Height:  |  Size: 1.7 KiB

View File

Before

Width:  |  Height:  |  Size: 1.9 KiB

After

Width:  |  Height:  |  Size: 1.9 KiB

View File

Before

Width:  |  Height:  |  Size: 3.8 KiB

After

Width:  |  Height:  |  Size: 3.8 KiB

View File

Before

Width:  |  Height:  |  Size: 2.8 KiB

After

Width:  |  Height:  |  Size: 2.8 KiB

View File

Before

Width:  |  Height:  |  Size: 5.8 KiB

After

Width:  |  Height:  |  Size: 5.8 KiB

View File

Before

Width:  |  Height:  |  Size: 3.8 KiB

After

Width:  |  Height:  |  Size: 3.8 KiB

View File

Before

Width:  |  Height:  |  Size: 7.6 KiB

After

Width:  |  Height:  |  Size: 7.6 KiB

View File

View File

@ -1,89 +1,89 @@
@rem @rem
@rem Copyright 2015 the original author or authors. @rem Copyright 2015 the original author or authors.
@rem @rem
@rem Licensed under the Apache License, Version 2.0 (the "License"); @rem Licensed under the Apache License, Version 2.0 (the "License");
@rem you may not use this file except in compliance with the License. @rem you may not use this file except in compliance with the License.
@rem You may obtain a copy of the License at @rem You may obtain a copy of the License at
@rem @rem
@rem https://www.apache.org/licenses/LICENSE-2.0 @rem https://www.apache.org/licenses/LICENSE-2.0
@rem @rem
@rem Unless required by applicable law or agreed to in writing, software @rem Unless required by applicable law or agreed to in writing, software
@rem distributed under the License is distributed on an "AS IS" BASIS, @rem distributed under the License is distributed on an "AS IS" BASIS,
@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@rem See the License for the specific language governing permissions and @rem See the License for the specific language governing permissions and
@rem limitations under the License. @rem limitations under the License.
@rem @rem
@if "%DEBUG%" == "" @echo off @if "%DEBUG%" == "" @echo off
@rem ########################################################################## @rem ##########################################################################
@rem @rem
@rem Gradle startup script for Windows @rem Gradle startup script for Windows
@rem @rem
@rem ########################################################################## @rem ##########################################################################
@rem Set local scope for the variables with windows NT shell @rem Set local scope for the variables with windows NT shell
if "%OS%"=="Windows_NT" setlocal if "%OS%"=="Windows_NT" setlocal
set DIRNAME=%~dp0 set DIRNAME=%~dp0
if "%DIRNAME%" == "" set DIRNAME=. if "%DIRNAME%" == "" set DIRNAME=.
set APP_BASE_NAME=%~n0 set APP_BASE_NAME=%~n0
set APP_HOME=%DIRNAME% set APP_HOME=%DIRNAME%
@rem Resolve any "." and ".." in APP_HOME to make it shorter. @rem Resolve any "." and ".." in APP_HOME to make it shorter.
for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi
@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m"
@rem Find java.exe @rem Find java.exe
if defined JAVA_HOME goto findJavaFromJavaHome if defined JAVA_HOME goto findJavaFromJavaHome
set JAVA_EXE=java.exe set JAVA_EXE=java.exe
%JAVA_EXE% -version >NUL 2>&1 %JAVA_EXE% -version >NUL 2>&1
if "%ERRORLEVEL%" == "0" goto execute if "%ERRORLEVEL%" == "0" goto execute
echo. echo.
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
echo. echo.
echo Please set the JAVA_HOME variable in your environment to match the echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation. echo location of your Java installation.
goto fail goto fail
:findJavaFromJavaHome :findJavaFromJavaHome
set JAVA_HOME=%JAVA_HOME:"=% set JAVA_HOME=%JAVA_HOME:"=%
set JAVA_EXE=%JAVA_HOME%/bin/java.exe set JAVA_EXE=%JAVA_HOME%/bin/java.exe
if exist "%JAVA_EXE%" goto execute if exist "%JAVA_EXE%" goto execute
echo. echo.
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
echo. echo.
echo Please set the JAVA_HOME variable in your environment to match the echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation. echo location of your Java installation.
goto fail goto fail
:execute :execute
@rem Setup the command line @rem Setup the command line
set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
@rem Execute Gradle @rem Execute Gradle
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %*
:end :end
@rem End local scope for the variables with windows NT shell @rem End local scope for the variables with windows NT shell
if "%ERRORLEVEL%"=="0" goto mainEnd if "%ERRORLEVEL%"=="0" goto mainEnd
:fail :fail
rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
rem the _cmd.exe /c_ return code! rem the _cmd.exe /c_ return code!
if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
exit /b 1 exit /b 1
:mainEnd :mainEnd
if "%OS%"=="Windows_NT" endlocal if "%OS%"=="Windows_NT" endlocal
:omega :omega

18
backend/.gitignore vendored Normal file
View File

@ -0,0 +1,18 @@
# ---> Go
# Binaries for programs and plugins
*.exe
*.exe~
*.dll
*.so
*.dylib
# Test binary, built with `go test -c`
*.test
# Output of the go coverage tool, specifically when used with LiteIDE
*.out
# Dependency directories (remove the comment below to include it)
# vendor/
travebing

2
backend/README.md Normal file
View File

@ -0,0 +1,2 @@
# travebing_backend

View File

@ -0,0 +1,13 @@
package v1
/*
*/
type TravelPlan struct {
ID int `json:"id" gorm:"autoIncrement;primaryKey"`
Name string `json:"name" gorm:"type:varchar(32)"`
LeaveFrom string `json:"leave" gorm:"type:varchar(64)"`
ArriveTo string `json:"arrive" gorm:"type:varchar(64)"`
CreatedAt int64 `json:"created_at"`
UpdatedAt int64 `json:"updated_at"`
}

View File

@ -0,0 +1,32 @@
package v1
import (
"encoding/json"
"path"
"strconv"
)
type TravelWay struct {
ID int `json:"id" gorm:"autoIncrement;primaryKey"`
Plan int `json:"plan"`
Image string `json:"image" gorm:"type:char(8)"`
Lat float32 `json:"lat"`
Lon float32 `json:"lon"`
Address string `json:"address" gorm:"type:varchar(64)"`
CreatedAt int64 `json:"createdAt"`
}
func (w *TravelWay) ImagePath(dir string) string {
return path.Join(dir, strconv.Itoa(w.Plan), strconv.Itoa(w.ID) + w.Image)
}
func (w *TravelWay) ImageSrc() string {
if w.Image == "" {
return ""
}
return "/" + path.Join("img", strconv.Itoa(w.Plan), strconv.Itoa(w.ID) + w.Image)
}
func (w *TravelWay)Bytes()([]byte, error){
return json.Marshal(w)
}

15
backend/config.yaml Normal file
View File

@ -0,0 +1,15 @@
database:
addr: 192.168.0.200
auth: root:hOnelUCXoJlsXScg
name: travebing
showLog: true
maxLifeTime: 600
maxIdleTime: 600
maxOpenConnections: 100
maxIdleConnections: 100
image:
dir: /tmp/travebing
geo:
key: d0483514405ba2d851eb2040ddfba02e
url: https://restapi.amap.com/v3/geocode/regeo
listen: 0.0.0.0:3000

60
backend/config/config.go Normal file
View File

@ -0,0 +1,60 @@
package config
import (
"os"
"gopkg.in/yaml.v2"
)
type DB struct {
Address string `yaml:"addr"`
Auth string `yaml:"auth"`
Name string `yaml:"name"`
ShowLog bool `yaml:"showLog"`
MaxLifeTime int `yaml:"maxLifeTime"`
MaxIdleTime int `yaml:"maxIdleTime"`
MaxOpenConnections int `yaml:"maxOpenConnections"`
MaxIdleConnections int `yaml:"maxIdleConnections"`
}
type Image struct {
Dir string `yaml:"dir"`
}
type Geo struct {
Key string `yaml:"key"`
Secret string `yaml:"secret"`
URL string `yaml:"url"`
}
type Config struct {
Database DB `yaml:"database"`
Image Image `yaml:"image"`
Geo Geo `yaml:"geo"`
Listen string `yaml:"listen"`
}
func (c *Config) Save(f string) error {
data, err := yaml.Marshal(c)
if err != nil {
return err
}
err = os.WriteFile(f, data, os.ModePerm)
return err
}
func NewConfig(file string) (*Config, error) {
data, err := os.ReadFile(file)
if err != nil {
return nil, err
}
conf := &Config{}
err = yaml.Unmarshal(data, conf)
return conf, err
}
func NewStrConfig(confStr string) (*Config, error) {
cfg := &Config{}
err := yaml.Unmarshal([]byte(confStr), cfg)
return cfg, err
}

View File

@ -0,0 +1,59 @@
package controller
import (
"fmt"
"time"
"gorm.io/driver/mysql"
"gorm.io/gorm"
"gorm.io/gorm/logger"
"pkg.bing89.com/travebing/config"
"pkg.bing89.com/travebing/controller/geo"
"pkg.bing89.com/travebing/controller/plan"
"pkg.bing89.com/travebing/controller/way"
)
type Controller interface {
Ways(plan int) way.Controller
Plans() plan.Controller
}
type controller struct {
db *gorm.DB
cfg *config.Config
}
func New(cfg *config.Config) (Controller, error) {
c := &controller{
cfg: cfg,
}
dsn := fmt.Sprintf("%s@tcp(%s)/%s?charset=utf8mb4&parseTime=True&loc=Local", cfg.Database.Auth, cfg.Database.Address, cfg.Database.Name)
opt := &gorm.Config{}
if cfg.Database.ShowLog {
opt.Logger = logger.Default.LogMode(logger.Info)
}
conn, err := gorm.Open(mysql.Open(dsn), opt)
if err != nil {
return nil, err
}
sqlDB, err := conn.DB()
if err != nil {
return nil, err
}
conn.Set("gorm:table_options", "ENGINE=InnoDB CHARACTER SET=utf8mb4 COLLATE=utf8mb4_unicode_ci")
sqlDB.SetConnMaxIdleTime(time.Duration(cfg.Database.MaxIdleTime) * time.Second)
sqlDB.SetConnMaxLifetime(time.Duration(cfg.Database.MaxLifeTime) * time.Second)
sqlDB.SetMaxIdleConns(cfg.Database.MaxIdleConnections)
sqlDB.SetMaxOpenConns(cfg.Database.MaxOpenConnections)
c.db = conn
return c, nil
}
func (c *controller) Ways(plan int) way.Controller {
return way.New(plan, c.db, &c.cfg.Image, geo.New(&c.cfg.Geo))
}
func (c *controller) Plans() plan.Controller {
return plan.New(c.db)
}

View File

@ -0,0 +1,43 @@
package geo
import (
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"pkg.bing89.com/travebing/config"
)
type ctrl struct {
cfg *config.Geo
}
func New(cfg *config.Geo)Controller{
return &ctrl{
cfg: cfg,
}
}
func (c *ctrl)Address(lon, lat float32)(string, error){
url := fmt.Sprintf("%s?key=%s&location=%6f,%6f", c.cfg.URL, c.cfg.Key, lon, lat)
resp, err := http.Get(url)
if err != nil {
return "", err
}
defer resp.Body.Close()
data, err := io.ReadAll(resp.Body)
if err != nil {
return "", err
}
ret := &geoResponse{}
err = json.Unmarshal(data, ret)
if err != nil {
return "", err
}
if ret.Status != "1" {
return "", errors.New(ret.Info)
}
return ret.RegeoCode.Address, nil
}

View File

@ -0,0 +1,16 @@
package geo
type Controller interface {
Address(float32, float32) (string, error)
}
type RegeoCode struct {
Address string `json:"formatted_address"`
}
type geoResponse struct {
Status string `json:"status"`
Info string `json:"info"`
InfoCode string `json:"infocode"`
RegeoCode RegeoCode `json:"regeocode"`
}

View File

@ -0,0 +1,63 @@
package plan
import (
"errors"
"time"
"gorm.io/gorm"
v1 "pkg.bing89.com/travebing/api/v1"
"pkg.bing89.com/travebing/tberror"
)
type Controller interface {
List() ([]v1.TravelPlan, int, error)
Get(id int)(*v1.TravelPlan, int, error)
Create(opt CreateOption) (*v1.TravelPlan, int, error)
}
type plan struct {
db *gorm.DB
}
func New(db *gorm.DB) Controller {
p := &plan{
db: db,
}
return p
}
func (c *plan) List() ([]v1.TravelPlan, int, error) {
ret := []v1.TravelPlan{}
err := c.db.Find(&ret).Error
if err != nil {
return ret, tberror.CodeDatabase, err
}
return ret, 0, nil
}
func (c *plan) Create(opt CreateOption) (*v1.TravelPlan, int, error) {
if opt.Validate() {
return nil, tberror.CodeInvalidArgs, errors.New("invalid args")
}
ret := &v1.TravelPlan{
Name: opt.Name,
ArriveTo: opt.Arrive,
LeaveFrom: opt.Leave,
CreatedAt: time.Now().Unix(),
}
err := c.db.Create(ret).Error
if err != nil {
return nil, tberror.CodeDatabase, err
}
return ret, 0, nil
}
func (c *plan)Get(id int)(*v1.TravelPlan, int, error) {
ret := &v1.TravelPlan{}
err := c.db.Where("id = ?", id).First(ret).Error
if err != nil {
return ret, tberror.CodeDatabase, err
}
return ret, 0, nil
}

View File

@ -0,0 +1,11 @@
package plan
type CreateOption struct {
Name string `json:"name"`
Leave string `json:"leave"`
Arrive string `json:"arrive"`
}
func (o CreateOption)Validate()bool {
return o.Name != "" && o.Leave != ""
}

View File

@ -0,0 +1,10 @@
package way
import "mime/multipart"
type CreateOption struct {
File *multipart.FileHeader `json:"-" `
Lat float32 `json:"lat" form:"lat"`
Lon float32 `json:"lon" form:"lon"`
Plan int `json:"-"`
}

View File

@ -0,0 +1,115 @@
package way
import (
"io"
"log"
"mime/multipart"
"os"
"path"
"strings"
"time"
"gorm.io/gorm"
v1 "pkg.bing89.com/travebing/api/v1"
"pkg.bing89.com/travebing/config"
"pkg.bing89.com/travebing/controller/geo"
"pkg.bing89.com/travebing/tberror"
)
type Controller interface {
List() ([]v1.TravelWay, int, error)
Create(opt CreateOption) (*v1.TravelWay, int, error)
}
type way struct {
db *gorm.DB
cfg *config.Image
plan int
geoCtrl geo.Controller
}
func New(plan int, db *gorm.DB, cfg *config.Image, geoCtrl geo.Controller) Controller {
c := &way{
db: db,
cfg: cfg,
plan: plan,
geoCtrl: geoCtrl,
}
return c
}
func (c *way) List() ([]v1.TravelWay, int, error) {
ret := []v1.TravelWay{}
err := c.db.Where("plan = ?", c.plan).Find(&ret).Error
if err != nil {
return ret, tberror.CodeDatabase, err
}
ways := []v1.TravelWay{}
for _, w := range ret {
w.Image = w.ImageSrc()
ways = append(ways, w)
}
return ways, 0, nil
}
func (c *way) checkDir(file string) error {
dir := path.Dir(file)
_, err := os.ReadDir(dir)
if os.IsNotExist(err) {
return os.MkdirAll(dir, os.ModeDir|os.ModePerm)
}
return err
}
func (c *way) saveFile(file *multipart.FileHeader, dst string) error {
if file == nil {
return nil
}
if err := c.checkDir(dst); err != nil {
return err
}
src, err := file.Open()
if err != nil {
return err
}
defer src.Close()
out, err := os.Create(dst)
if err != nil {
return err
}
defer out.Close()
_, err = io.Copy(out, src)
if err != nil {
return err
}
return nil
}
func (c *way) Create(opt CreateOption) (*v1.TravelWay, int, error) {
ret := &v1.TravelWay{
Plan: c.plan,
Lat: opt.Lat,
Lon: opt.Lon,
CreatedAt: time.Now().Unix(),
}
addr, err := c.geoCtrl.Address(opt.Lon, opt.Lat)
if err != nil {
log.Println("===>>>> get address failed:", err)
}
ret.Address = addr
if opt.File != nil {
fileExt := strings.ToLower(path.Ext(opt.File.Filename))
ret.Image = fileExt
}
err = c.db.Create(ret).Error
if err != nil {
return nil, tberror.CodeDatabase, err
}
err = c.saveFile(opt.File, ret.ImagePath(c.cfg.Dir))
if err != nil {
return ret, tberror.CodeFileSave, err
}
ret.Image = ret.ImageSrc()
return ret, 0, nil
}

View File

@ -0,0 +1,20 @@
create database if not exists travebing default character set utf8mb4;
create table if not exists travel_plans (
id INT AUTO_INCREMENT PRIMARY KEY,
`name` VARCHAR(32) NOT NULL,
`leave_from` VARCHAR(64) NOT NULL,
arrive_to VARCHAR(64) DEFAULT '',
created_at BIGINT DEFAULT 0,
updated_at BIGINT DEFAULT 0
);
create table if not exists travel_ways (
id INT AUTO_INCREMENT PRIMARY KEY,
plan int not null,
image char(8) default '.jpeg',
lat double default 0,
lon double default 0,
address varchar(64) default '',
created_at BIGINT DEFAULT 0
)

43
backend/go.mod Normal file
View File

@ -0,0 +1,43 @@
module pkg.bing89.com/travebing
go 1.21.4
require (
github.com/docker/distribution v2.8.3+incompatible
github.com/gin-gonic/gin v1.9.1
github.com/google/uuid v1.6.0
github.com/gorilla/websocket v1.5.1
gopkg.in/yaml.v2 v2.4.0
gorm.io/driver/mysql v1.5.2
gorm.io/gorm v1.25.6
)
require (
github.com/bytedance/sonic v1.9.1 // indirect
github.com/chenzhuoyu/base64x v0.0.0-20221115062448-fe3a3abad311 // indirect
github.com/gabriel-vasile/mimetype v1.4.2 // indirect
github.com/gin-contrib/sse v0.1.0 // indirect
github.com/go-playground/locales v0.14.1 // indirect
github.com/go-playground/universal-translator v0.18.1 // indirect
github.com/go-playground/validator/v10 v10.14.0 // indirect
github.com/go-sql-driver/mysql v1.7.0 // indirect
github.com/goccy/go-json v0.10.2 // indirect
github.com/jinzhu/inflection v1.0.0 // indirect
github.com/jinzhu/now v1.1.5 // indirect
github.com/json-iterator/go v1.1.12 // indirect
github.com/klauspost/cpuid/v2 v2.2.4 // indirect
github.com/leodido/go-urn v1.2.4 // indirect
github.com/mattn/go-isatty v0.0.19 // indirect
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect
github.com/modern-go/reflect2 v1.0.2 // indirect
github.com/pelletier/go-toml/v2 v2.0.8 // indirect
github.com/twitchyliquid64/golang-asm v0.15.1 // indirect
github.com/ugorji/go/codec v1.2.11 // indirect
golang.org/x/arch v0.3.0 // indirect
golang.org/x/crypto v0.14.0 // indirect
golang.org/x/net v0.17.0 // indirect
golang.org/x/sys v0.13.0 // indirect
golang.org/x/text v0.13.0 // indirect
google.golang.org/protobuf v1.30.0 // indirect
gopkg.in/yaml.v3 v3.0.1 // indirect
)

105
backend/go.sum Normal file
View File

@ -0,0 +1,105 @@
github.com/bytedance/sonic v1.5.0/go.mod h1:ED5hyg4y6t3/9Ku1R6dU/4KyJ48DZ4jPhfY1O2AihPM=
github.com/bytedance/sonic v1.9.1 h1:6iJ6NqdoxCDr6mbY8h18oSO+cShGSMRGCEo7F2h0x8s=
github.com/bytedance/sonic v1.9.1/go.mod h1:i736AoUSYt75HyZLoJW9ERYxcy6eaN6h4BZXU064P/U=
github.com/chenzhuoyu/base64x v0.0.0-20211019084208-fb5309c8db06/go.mod h1:DH46F32mSOjUmXrMHnKwZdA8wcEefY7UVqBKYGjpdQY=
github.com/chenzhuoyu/base64x v0.0.0-20221115062448-fe3a3abad311 h1:qSGYFH7+jGhDF8vLC+iwCD4WpbV1EBDSzWkJODFLams=
github.com/chenzhuoyu/base64x v0.0.0-20221115062448-fe3a3abad311/go.mod h1:b583jCggY9gE99b6G5LEC39OIiVsWj+R97kbl5odCEk=
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
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/docker/distribution v2.8.3+incompatible h1:AtKxIZ36LoNK51+Z6RpzLpddBirtxJnzDrHLEKxTAYk=
github.com/docker/distribution v2.8.3+incompatible/go.mod h1:J2gT2udsDAN96Uj4KfcMRqY0/ypR+oyYUYmja8H+y+w=
github.com/gabriel-vasile/mimetype v1.4.2 h1:w5qFW6JKBz9Y393Y4q372O9A7cUSequkh1Q7OhCmWKU=
github.com/gabriel-vasile/mimetype v1.4.2/go.mod h1:zApsH/mKG4w07erKIaJPFiX0Tsq9BFQgN3qGY5GnNgA=
github.com/gin-contrib/sse v0.1.0 h1:Y/yl/+YNO8GZSjAhjMsSuLt29uWRFHdHYUb5lYOV9qE=
github.com/gin-contrib/sse v0.1.0/go.mod h1:RHrZQHXnP2xjPF+u1gW/2HnVO7nvIa9PG3Gm+fLHvGI=
github.com/gin-gonic/gin v1.9.1 h1:4idEAncQnU5cB7BeOkPtxjfCSye0AAm1R0RVIqJ+Jmg=
github.com/gin-gonic/gin v1.9.1/go.mod h1:hPrL7YrpYKXt5YId3A/Tnip5kqbEAP+KLuI3SUcPTeU=
github.com/go-playground/assert/v2 v2.2.0 h1:JvknZsQTYeFEAhQwI4qEt9cyV5ONwRHC+lYKSsYSR8s=
github.com/go-playground/assert/v2 v2.2.0/go.mod h1:VDjEfimB/XKnb+ZQfWdccd7VUvScMdVu0Titje2rxJ4=
github.com/go-playground/locales v0.14.1 h1:EWaQ/wswjilfKLTECiXz7Rh+3BjFhfDFKv/oXslEjJA=
github.com/go-playground/locales v0.14.1/go.mod h1:hxrqLVvrK65+Rwrd5Fc6F2O76J/NuW9t0sjnWqG1slY=
github.com/go-playground/universal-translator v0.18.1 h1:Bcnm0ZwsGyWbCzImXv+pAJnYK9S473LQFuzCbDbfSFY=
github.com/go-playground/universal-translator v0.18.1/go.mod h1:xekY+UJKNuX9WP91TpwSH2VMlDf28Uj24BCp08ZFTUY=
github.com/go-playground/validator/v10 v10.14.0 h1:vgvQWe3XCz3gIeFDm/HnTIbj6UGmg/+t63MyGU2n5js=
github.com/go-playground/validator/v10 v10.14.0/go.mod h1:9iXMNT7sEkjXb0I+enO7QXmzG6QCsPWY4zveKFVRSyU=
github.com/go-sql-driver/mysql v1.7.0 h1:ueSltNNllEqE3qcWBTD0iQd3IpL/6U+mJxLkazJ7YPc=
github.com/go-sql-driver/mysql v1.7.0/go.mod h1:OXbVy3sEdcQ2Doequ6Z5BW6fXNQTmx+9S1MCJN5yJMI=
github.com/goccy/go-json v0.10.2 h1:CrxCmQqYDkv1z7lO7Wbh2HN93uovUHgrECaO5ZrCXAU=
github.com/goccy/go-json v0.10.2/go.mod h1:6MelG93GURQebXPDq3khkgXZkazVtN9CRI+MGFi0w8I=
github.com/golang/protobuf v1.5.0/go.mod h1:FsONVRAS9T7sI+LIUmWTfcYkHO4aIWwzhcaSAoJOfIk=
github.com/google/go-cmp v0.5.5 h1:Khx7svrCpmxxtHBq5j2mp/xVjsi8hQMfNLvJFAlrGgU=
github.com/google/go-cmp v0.5.5/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=
github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg=
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/gorilla/websocket v1.5.1 h1:gmztn0JnHVt9JZquRuzLw3g4wouNVzKL15iLr/zn/QY=
github.com/gorilla/websocket v1.5.1/go.mod h1:x3kM2JMyaluk02fnUJpQuwD2dCS5NDG2ZHL0uE0tcaY=
github.com/jinzhu/inflection v1.0.0 h1:K317FqzuhWc8YvSVlFMCCUb36O/S9MCKRDI7QkRKD/E=
github.com/jinzhu/inflection v1.0.0/go.mod h1:h+uFLlag+Qp1Va5pdKtLDYj+kHp5pxUVkryuEj+Srlc=
github.com/jinzhu/now v1.1.5 h1:/o9tlHleP7gOFmsnYNz3RGnqzefHA47wQpKrrdTIwXQ=
github.com/jinzhu/now v1.1.5/go.mod h1:d3SSVoowX0Lcu0IBviAWJpolVfI5UJVZZ7cO71lE/z8=
github.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnrnM=
github.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo=
github.com/klauspost/cpuid/v2 v2.0.9/go.mod h1:FInQzS24/EEf25PyTYn52gqo7WaD8xa0213Md/qVLRg=
github.com/klauspost/cpuid/v2 v2.2.4 h1:acbojRNwl3o09bUq+yDCtZFc1aiwaAAxtcn8YkZXnvk=
github.com/klauspost/cpuid/v2 v2.2.4/go.mod h1:RVVoqg1df56z8g3pUjL/3lE5UfnlrJX8tyFgg4nqhuY=
github.com/leodido/go-urn v1.2.4 h1:XlAE/cm/ms7TE/VMVoduSpNBoyc2dOxHs5MZSwAN63Q=
github.com/leodido/go-urn v1.2.4/go.mod h1:7ZrI8mTSeBSHl/UaRyKQW1qZeMgak41ANeCNaVckg+4=
github.com/mattn/go-isatty v0.0.19 h1:JITubQf0MOLdlGRuRq+jtsDlekdYPia9ZFsB8h/APPA=
github.com/mattn/go-isatty v0.0.19/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=
github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd h1:TRLaZ9cD/w8PVh93nsPXa1VrQ6jlwL5oN8l14QlcNfg=
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=
github.com/modern-go/reflect2 v1.0.2 h1:xBagoLtFs94CBntxluKeaWgTMpvLxC4ur3nMaC9Gz0M=
github.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk=
github.com/pelletier/go-toml/v2 v2.0.8 h1:0ctb6s9mE31h0/lhu+J6OPmVeDxJn+kYnJc2jZR9tGQ=
github.com/pelletier/go-toml/v2 v2.0.8/go.mod h1:vuYfssBdrU2XDZ9bYydBu6t+6a6PYNcZljzZR9VXg+4=
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/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw=
github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo=
github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU=
github.com/stretchr/testify v1.8.1/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4=
github.com/stretchr/testify v1.8.2/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4=
github.com/stretchr/testify v1.8.3 h1:RP3t2pwF7cMEbC1dqtB6poj3niw/9gnV4Cjg5oW5gtY=
github.com/stretchr/testify v1.8.3/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo=
github.com/twitchyliquid64/golang-asm v0.15.1 h1:SU5vSMR7hnwNxj24w34ZyCi/FmDZTkS4MhqMhdFk5YI=
github.com/twitchyliquid64/golang-asm v0.15.1/go.mod h1:a1lVb/DtPvCB8fslRZhAngC2+aY1QWCk3Cedj/Gdt08=
github.com/ugorji/go/codec v1.2.11 h1:BMaWp1Bb6fHwEtbplGBGJ498wD+LKlNSl25MjdZY4dU=
github.com/ugorji/go/codec v1.2.11/go.mod h1:UNopzCgEMSXjBc6AOMqYvWC1ktqTAfzJZUZgYf6w6lg=
golang.org/x/arch v0.0.0-20210923205945-b76863e36670/go.mod h1:5om86z9Hs0C8fWVUuoMHwpExlXzs5Tkyp9hOrfG7pp8=
golang.org/x/arch v0.3.0 h1:02VY4/ZcO/gBOH6PUaoiptASxtXU10jazRCP865E97k=
golang.org/x/arch v0.3.0/go.mod h1:5om86z9Hs0C8fWVUuoMHwpExlXzs5Tkyp9hOrfG7pp8=
golang.org/x/crypto v0.14.0 h1:wBqGXzWJW6m1XrIKlAH0Hs1JJ7+9KBwnIO8v66Q9cHc=
golang.org/x/crypto v0.14.0/go.mod h1:MVFd36DqK4CsrnJYDkBA3VC4m2GkXAM0PvzMCn4JQf4=
golang.org/x/net v0.17.0 h1:pVaXccu2ozPjCXewfr1S7xza/zcXTity9cCdXQYSjIM=
golang.org/x/net v0.17.0/go.mod h1:NxSsAGuq816PNPmqtQdLE42eU2Fs7NoRIZrHJAlaCOE=
golang.org/x/sys v0.0.0-20220704084225-05e143d24a9e/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.13.0 h1:Af8nKPmuFypiUBjVoU9V20FiaFXOcuZI21p0ycVYYGE=
golang.org/x/sys v0.13.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/text v0.13.0 h1:ablQoSUd0tRdKxZewP80B+BaqeKJuVhuRxj/dkrun3k=
golang.org/x/text v0.13.0/go.mod h1:TvPlkZtksWOMsz7fbANvkp4WM8x/WCo/om8BMLbz+aE=
golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543 h1:E7g+9GITq07hpfrRu66IVDexMakfv52eLZ2CXBWiKr4=
golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
google.golang.org/protobuf v1.26.0-rc.1/go.mod h1:jlhhOSvTdKEhbULTjvd4ARK9grFBp09yW+WbY/TyQbw=
google.golang.org/protobuf v1.30.0 h1:kPPoIgf3TsEvrm0PFe15JQ+570QVxYzEvvHqChK+cng=
google.golang.org/protobuf v1.30.0/go.mod h1:HV8QOd/L58Z+nl8r43ehVNZIU/HEI6OcFqwMG9pJV4I=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/yaml.v2 v2.4.0 h1:D8xgwECY7CYvx+Y2n4sBz93Jn9JRvxdiyyo8CTfuKaY=
gopkg.in/yaml.v2 v2.4.0/go.mod h1:RDklbk79AGWmwhnvt/jBztapEOGDOx6ZbXqjP6csGnQ=
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
gorm.io/driver/mysql v1.5.2 h1:QC2HRskSE75wBuOxe0+iCkyJZ+RqpudsQtqkp+IMuXs=
gorm.io/driver/mysql v1.5.2/go.mod h1:pQLhh1Ut/WUAySdTHwBpBv6+JKcj+ua4ZFx1QQTBzb8=
gorm.io/gorm v1.25.2-0.20230530020048-26663ab9bf55/go.mod h1:L4uxeKpfBml98NYqVqwAdmV1a2nBtAec/cf3fpucW/k=
gorm.io/gorm v1.25.6 h1:V92+vVda1wEISSOMtodHVRcUIOPYa2tgQtyF+DfFx+A=
gorm.io/gorm v1.25.6/go.mod h1:hbnx/Oo0ChWMn1BIhpy1oYozzpM15i4YPuHDmfYtwg8=
rsc.io/pdf v0.1.1/go.mod h1:n8OzWcQ6Sp37PL01nO98y4iUCRdTGarVfzxY20ICaU4=

65
backend/http/http.go Normal file
View File

@ -0,0 +1,65 @@
package http
import (
"log"
"github.com/gin-gonic/gin"
)
type ResponseData struct {
Code int `json:"code"`
Message string `json:"msg"`
Data interface{} `json:"data"`
}
func Success(c *gin.Context, data interface{}) {
c.JSON(200, ResponseData{Code: 0, Message: "success", Data: data})
}
func ErrorWithData(c *gin.Context, code int, err error, data interface{}) {
if code == 0 {
Success(c, err)
return
}
if err == nil {
c.AbortWithStatusJSON(200, ResponseData{Code: code, Message: "failed", Data: data})
return
}
c.AbortWithStatusJSON(200, ResponseData{Code: code, Message: err.Error(), Data: data})
}
func Error(c *gin.Context, code int, err error) {
if code == 0 {
Success(c, err)
return
}
if err == nil {
c.AbortWithStatusJSON(200, ResponseData{Code: code, Message: "failed"})
return
}
log.Println(err)
c.AbortWithStatusJSON(200, ResponseData{Code: code, Message: err.Error()})
}
func Response(c *gin.Context, res bool) {
if res {
Success(c, res)
return
}
Error(c, 400, nil)
}
// OutRedirect 重定向
func Redirect(c *gin.Context, code int, loc string) {
if code < 301 || code > 308 || code == 304 {
code = 303
}
c.Redirect(code, loc)
// c.Abort()
}
func ResponseBytes(c *gin.Context, data []byte) {
// c.Abort()
c.Writer.Write(data)
}

26
backend/main.go Normal file
View File

@ -0,0 +1,26 @@
package main
import (
"flag"
"pkg.bing89.com/travebing/config"
"pkg.bing89.com/travebing/server"
)
func main(){
conf := ""
flag.StringVar(&conf, "config", "/etc/travebing/config.yaml", "config file")
flag.Parse()
cfg, err := config.NewConfig(conf)
if err != nil {
panic(err)
}
svr, err := server.New(cfg)
if err != nil {
panic(err)
}
err = svr.Run()
if err != nil {
panic(err)
}
}

104
backend/notifier/client.go Normal file
View File

@ -0,0 +1,104 @@
package notifier
import (
"errors"
"sync"
)
type Clients struct {
m sync.Map
}
func NewClients() *Clients {
c := &Clients{
m: sync.Map{},
}
return c
}
func (c *Clients) Get(id string) (*Sessions, error) {
v, ok := c.m.Load(id)
if !ok {
return nil, errors.New("not found")
}
if ret, ok := v.(*Sessions); ok {
return ret, nil
}
return nil, errors.New("value not a comsumer")
}
func (c *Clients) SetSession(user string, s *Session) {
ss, err := c.Get(user)
if err != nil {
ss = NewSessions()
}
ss.Set(s.ID(), s)
c.m.Store(user, ss)
}
func (c *Clients) Set(id string, sessions *Sessions) *Sessions {
ss, ok := c.m.Swap(id, sessions)
if !ok {
return nil
}
old, ok := ss.(*Sessions)
if ok {
return old
}
return nil
}
func (c *Clients) Range(f func(string,* Sessions) bool) {
c.m.Range(func(k, v any) bool {
i, ok := k.(string)
if !ok {
return false
}
ss, ok := v.(*Sessions)
if !ok {
return false
}
return f(i, ss)
})
}
func (c *Clients) List() []*Sessions {
ret := []*Sessions{}
c.m.Range(func(key, value any) bool {
ss, ok := value.(*Sessions)
if !ok {
return false
}
ret = append(ret, ss)
return true
})
return ret
}
func (c *Clients) Map() map[string]*Sessions {
ret := make(map[string]*Sessions)
c.m.Range(func(key, value any) bool {
id, ok := key.(string)
if !ok {
return false
}
ss, ok := key.(*Sessions)
if !ok {
return false
}
ret[id] = ss
return true
})
return ret
}
func (c *Clients) Delete(user string) {
c.m.Delete(user)
}
func (c *Clients) DeleteSession(user, id string) {
ss, err := c.Get(user)
if err != nil {
return
}
ss.Delete(id)
}

View File

@ -0,0 +1,99 @@
package notifier
import (
"encoding/json"
"errors"
"strconv"
)
type MessageType int
const (
MessageTypeOpened MessageType = iota
MessageTypeSystem
)
type Message struct {
Type MessageType `json:"type"`
To string `json:"to"`
Data interface{} `json:"data"`
ID string `json:"id"`
}
func NewMessage(data []byte)(Message, error){
m := Message{}
err := json.Unmarshal(data, &m)
return m, err
}
func NewMessageFromMap(m map[string]interface{})(Message, error){
msg := Message{}
to := m["to"]
typ := m["type"]
data := m["data"]
if t, ok := to.(string); ok {
msg.To = t
}else{
return msg, errors.New("field to type error")
}
if ty, ok := typ.(string); ok {
i, _ := strconv.Atoi(ty)
msg.Type = MessageType(i)
}else{
return msg, errors.New("field type type error")
}
msg.Data = data
return msg, nil
}
func (m Message) IDString() string {
return strconv.Itoa(int(m.Type))
}
func (m Message) SSEIDBytes() []byte {
return []byte("id: " + m.TypeString() + "\n")
}
func (m Message) TypeString() string {
return strconv.Itoa(int(m.Type))
}
func (m Message) SSETypeBytes() []byte {
return []byte("event: " + m.TypeString() + "\n")
}
func (m Message) Bytes() ([]byte, error) {
return json.Marshal(&m)
}
func (m Message) SSEBytes() ([]byte, error) {
data, err := m.Bytes()
if err != nil {
return []byte("data: "), err
}
return []byte("data: " + string(data) + "\n\n"), nil
}
func (m Message) DataBytes() ([]byte, error) {
return json.Marshal(m.Data)
}
func (m Message) SSEDataBytes() ([]byte, error) {
data, err := m.DataBytes()
if err != nil {
return []byte("data: "), err
}
return []byte("data: " + string(data) + "\n\n"), nil
}
func (m Message)Map()map[string]interface{}{
ret := make(map[string]interface{}, 0)
ret["type"] = int(m.Type)
ret["id"] = m.ID
ret["to"] = m.To
ret["data"] = m.Data
return ret
}

View File

@ -0,0 +1,118 @@
package notifier
import (
"context"
"fmt"
"log"
"sync"
)
const (
DefaultLengthMessageQueue = 5
DefaultLengthSessionQueue = 5
)
type Notifier struct {
clients *Clients
lock sync.RWMutex
sessionChan chan *Session
messageChan chan Message
ctx context.Context
cancel context.CancelFunc
}
func New() *Notifier {
ctx, cancel := context.WithCancel(context.TODO())
c := Notifier{
clients: NewClients(),
lock: sync.RWMutex{},
sessionChan: make(chan *Session, DefaultLengthSessionQueue),
messageChan: make(chan Message, DefaultLengthMessageQueue),
ctx: ctx,
cancel: cancel,
}
return &c
}
func (c *Notifier) recieveSession(ctx context.Context) {
for {
select {
case <-c.ctx.Done():
return
case <-ctx.Done():
return
case session := <-c.sessionChan:
log.Println("recieve a session of user", session.User(), session.ID())
c.clients.SetSession(session.User(), session)
err := session.Write(Message{Type: MessageTypeOpened, Data: fmt.Sprintf(`{"session": "%s"}`, session.ID()), To: session.ID()})
if err != nil {
log.Println("send session info", err)
return
}
}
}
}
func (c *Notifier) recieveMessage(ctx context.Context) {
for {
select {
case <-c.ctx.Done():
return
case <-ctx.Done():
return
case msg := <-c.messageChan:
// log.Println("oxnotifier recieve a message:", msg)
c.notify(msg)
}
}
}
func (c *Notifier) writeMessage(s *Session, msg Message) {
err := s.Write(msg)
if err != nil {
log.Println("write msg to ", s.ID(), "failed:", err, " close it")
s.Close()
c.DeleteSession(s.User(), s.ID())
}
}
func (c *Notifier) notify(msg Message) error {
sessions, err := c.clients.Get(msg.To)
if err != nil {
return err
}
for _, s := range sessions.List() {
go c.writeMessage(s, msg)
}
return nil
}
func (c *Notifier) Run(ctx context.Context) error {
log.Println("starting notifier")
go c.recieveSession(ctx)
c.recieveMessage(ctx)
return nil
}
func (c *Notifier)Send(data interface{}, to string){
c.SendMessage(c.ctx, Message{Data: data, To: to , Type: MessageTypeSystem})
}
func (c *Notifier) SendMessage(ctx context.Context, msg Message) (string, error) {
go func() { c.messageChan <- msg }()
return "", nil
}
func (c *Notifier) AddSession(session *Session) {
go func() { c.sessionChan <- session }()
session.Run(c.ctx)
}
func (c *Notifier) DeleteSession(user, id string) {
log.Println("delete session of user", user, id)
c.clients.DeleteSession(user, id)
}

140
backend/notifier/session.go Normal file
View File

@ -0,0 +1,140 @@
package notifier
import (
// "compress/gzip"
"context"
"errors"
"io"
"log"
"net/http"
"strings"
"github.com/gin-gonic/gin"
"github.com/google/uuid"
)
type Session struct {
user string
id string
w gin.ResponseWriter
blockChan chan int
ctx context.Context
cancel context.CancelFunc
flusher http.Flusher
writer io.Writer
}
func NewSession(c *gin.Context) (*Session, error) {
user := c.Param("plan")
clientID := uuid.New().String()
ctx, cancel := context.WithCancel(context.Background())
session := Session{
user: user,
id: clientID,
blockChan: make(chan int),
ctx: ctx,
cancel: cancel,
}
useGzip := false
if strings.Contains(c.GetHeader("Accept-Encoding"), "gzip") {
useGzip = true
}
err := session.init(useGzip, c.Writer)
return &session, err
}
func (s *Session) WriteString(str string) error {
_, err := s.writer.Write([]byte(str))
if err == nil {
s.flusher.Flush()
}
return err
}
func (s *Session) Write(msg Message) error {
if s.writer == nil {
return errors.New("conn is nil")
}
data, err := msg.SSEBytes()
if err != nil {
return err
}
n, err := s.writer.Write(msg.SSEIDBytes())
if err != nil {
log.Println("msg type write failed ", s.id, n, err)
return err
}
n, err = s.writer.Write(data)
if err != nil {
log.Println("msg data write failed ", s.id, n, err)
return err
}
s.flusher.Flush()
return err
}
func (s *Session) init(gz bool, writer gin.ResponseWriter) error {
// header := writer.Header()
// header.Set("Content-Type", "text/event-stream")
// header.Set("Cache-Control", "no-cache")
// header.Set("Connection", "keep-alive")
// header.Set("Access-Control-Allow-Origin", "*")
// header.Set("Session-ID", s.id)
// if gz {
// header.Set("Content-Encoding", "gzip")
// }
// writer.WriteHeader(http.StatusOK)
// writer.Flush()
s.w = writer
flusher, ok := writer.(http.Flusher)
if !ok {
return errors.New("flusher not support")
}
s.flusher = flusher
w, ok := writer.(io.Writer)
if !ok {
return errors.New("writer not support")
}
s.writer = w
// if gz {
// s.writer = gzip.NewWriter(s.writer)
// }
// err := s.Write(Message{Type: MessageTypeOpened, Data: s.id, To: s.id})
return nil
}
func (s *Session) ID() string {
return s.id
}
func (s *Session) User() string {
return s.user
}
func (s *Session) Run(ctx context.Context) {
for {
select {
case <-ctx.Done():
return
case <-s.ctx.Done():
return
}
}
}
func (s *Session) Flush() {
if s.flusher != nil {
s.flusher.Flush()
}
}
func (s *Session) Close() {
defer s.cancel()
}
func (s *Session) Messages() <-chan Message {
return nil
}

View File

@ -0,0 +1,88 @@
package notifier
import (
"errors"
"sync"
)
type Sessions struct {
m sync.Map
}
func NewSessions() *Sessions {
cs := Sessions{
m: sync.Map{},
}
return &cs
}
func (c *Sessions) Get(id string) (*Session, error) {
v, ok := c.m.Load(id)
if !ok {
return nil, errors.New("not found")
}
if ret, ok := v.(*Session); ok {
return ret, nil
}
return nil, errors.New("value not a comsumer")
}
func (c *Sessions) Set(id string, session *Session) *Session {
v, ok := c.m.Swap(id, session)
if !ok {
return nil
}
if ret, ok := v.(*Session); ok {
return ret
}
return nil
}
func (c *Sessions) Range(f func(string, *Session) bool) {
c.m.Range(func(k, v any) bool {
id, ok := k.(string)
if !ok {
return false
}
consumer, ok := v.(*Session)
if !ok {
return false
}
return f(id, consumer)
})
}
func (c *Sessions) List() []*Session {
ret := []*Session{}
c.m.Range(func(key, value any) bool {
consumer, ok := value.(*Session)
if !ok {
return false
}
ret = append(ret, consumer)
return true
})
return ret
}
func (c *Sessions) Map() map[string]*Session {
ret := make(map[string]*Session)
c.m.Range(func(key, value any) bool {
id, ok := key.(string)
if !ok {
return false
}
consumer, ok := value.(*Session)
if !ok {
return false
}
ret[id] = consumer
return true
})
return ret
}
func (c *Sessions) Delete(id string) {
c.m.Delete(id)
}

91
backend/server/client.go Normal file
View File

@ -0,0 +1,91 @@
package server
import (
"github.com/google/uuid"
"github.com/gorilla/websocket"
v1 "pkg.bing89.com/travebing/api/v1"
"sync"
)
type Client struct {
plan string
id string
conn *websocket.Conn
}
func NewClient(plan string, conn *websocket.Conn) *Client {
return &Client{
id: uuid.NewString(),
plan: plan,
conn: conn,
}
}
func (c *Client) Send(way v1.TravelWay) error {
data, err := way.Bytes()
if err != nil {
return err
}
err = c.conn.WriteMessage(websocket.BinaryMessage, data)
return err
}
func (c *Client) SendMessage(data []byte) error {
err := c.conn.WriteMessage(websocket.BinaryMessage, data)
return err
}
type Clients struct {
m map[string]*Client
lock sync.RWMutex
}
func NewClients() *Clients {
return &Clients{
m: make(map[string]*Client),
lock: sync.RWMutex{},
}
}
func (c *Clients) Get(plan string) (*Client, bool) {
c.lock.Lock()
defer c.lock.Unlock()
cs, ok := c.m[plan]
return cs, ok
}
func (c *Clients) Notify(way v1.TravelWay) error {
data, err := way.Bytes()
if err != nil {
return err
}
c.lock.Lock()
defer c.lock.Unlock()
failed := []string{}
for id, clt := range c.m {
err := clt.SendMessage(data)
if err != nil {
failed = append(failed, id)
}
}
//清理报错的
for _, f := range failed {
delete(c.m, f)
}
return nil
}
func (c *Clients) Set(clt *Client) {
if clt.id == "" {
return
}
c.lock.Lock()
defer c.lock.Unlock()
c.m[clt.id] = clt
}
func (c *Clients) Delete(id string) {
c.lock.Lock()
defer c.lock.Unlock()
delete(c.m, id)
}

View File

@ -0,0 +1,47 @@
package server
import (
"strconv"
"github.com/gin-gonic/gin"
"pkg.bing89.com/travebing/controller/plan"
"pkg.bing89.com/travebing/http"
"pkg.bing89.com/travebing/tberror"
)
func (s *Server)HandlePlanList(c *gin.Context){
ret, code, err := s.ctrl.Plans().List()
if err != nil {
http.Error(c, code, err)
return
}
http.Success(c, ret)
}
func (s *Server)HandlePlanCreate(c *gin.Context){
opt := plan.CreateOption{}
if err := c.ShouldBind(&opt); err != nil {
http.Error(c, tberror.CodeBadRequest, err)
return
}
ret, code, err := s.ctrl.Plans().Create(opt)
if err != nil {
http.Error(c, code, err)
return
}
http.Success(c, ret)
}
func (s *Server)HandlePlanGet(c *gin.Context){
plan, err := strconv.Atoi(c.Param("plan"))
if err != nil {
http.Error(c, tberror.CodeBadRequest, err)
return
}
ret, code, err := s.ctrl.Plans().Get(plan)
if err != nil {
http.Error(c, code, err)
return
}
http.Success(c, ret)
}

View File

@ -0,0 +1,70 @@
package server
import (
"log"
"strconv"
"github.com/gin-gonic/gin"
"pkg.bing89.com/travebing/controller/way"
"pkg.bing89.com/travebing/http"
"pkg.bing89.com/travebing/notifier"
"pkg.bing89.com/travebing/tberror"
)
func (s *Server)HandleWayList(c *gin.Context){
plan, err := strconv.Atoi(c.Param("plan"))
if err != nil {
http.Error(c, tberror.CodeBadRequest, err)
return
}
ret, code, err := s.ctrl.Ways(plan).List()
if err != nil {
http.Error(c, code, err)
return
}
http.Success(c, ret)
}
func (s *Server)HandleWayCreate(c *gin.Context){
plan := c.Param("plan")
planID, err := strconv.Atoi(plan)
if err != nil {
http.Error(c, tberror.CodeBadRequest, err)
return
}
opt := way.CreateOption{}
if err := c.ShouldBind(&opt); err != nil {
http.Error(c, tberror.CodeBadRequest, err)
return
}
file, err := c.FormFile("file")
if err == nil {
opt.File = file
}else{
opt.File = nil
}
ret, code, err := s.ctrl.Ways(planID).Create(opt)
if err != nil {
http.Error(c, code, err)
return
}
s.notifier.Send(ret, plan)
http.Success(c, ret)
}
func (s *Server)HandleWaySync(c *gin.Context){
c.Header("Content-Type", "text/event-stream")
c.Header("Cache-Control", "no-cache")
c.Header("Connection", "keep-alive")
c.Header("Access-Control-Allow-Origin", "*")
session, err := notifier.NewSession(c)
if err != nil {
log.Println("new session failed:", err)
http.Error(c, tberror.CodeSystem, err)
return
}
s.notifier.AddSession(session)
log.Println(session.ID(), "returned")
defer s.notifier.DeleteSession(session.User(), session.ID())
}

77
backend/server/server.go Normal file
View File

@ -0,0 +1,77 @@
package server
import (
"context"
"sync"
"github.com/gin-gonic/gin"
"github.com/gorilla/websocket"
v1 "pkg.bing89.com/travebing/api/v1"
"pkg.bing89.com/travebing/config"
"pkg.bing89.com/travebing/controller"
"pkg.bing89.com/travebing/notifier"
)
type Server struct {
ctrl controller.Controller
cfg *config.Config
ClientMap map[string]*Clients
cmLock sync.RWMutex
notifier *notifier.Notifier
}
func New(cfg *config.Config) (*Server, error) {
s := &Server{
cfg: cfg,
ClientMap: make(map[string]*Clients),
cmLock: sync.RWMutex{},
notifier: notifier.New(),
}
ctrl, err := controller.New(cfg)
if err != nil {
return nil, err
}
s.ctrl = ctrl
return s, nil
}
func (s *Server) AddClient(plan string, conn *websocket.Conn) {
s.cmLock.Lock()
defer s.cmLock.Unlock()
clts, ok := s.ClientMap[plan]
if !ok {
clts = NewClients()
}
clts.Set(NewClient(plan, conn))
s.ClientMap[plan] = clts
}
func (s *Server) Notify(plan string, way v1.TravelWay) error {
s.cmLock.Lock()
defer s.cmLock.Unlock()
clts, ok := s.ClientMap[plan]
if !ok {
return nil
}
return clts.Notify(way)
}
func (s *Server) Run() error {
engine := gin.Default()
apiGroup := engine.Group("/api/v1")
apiGroup.GET("/plans", s.HandlePlanList)
apiGroup.POST("/plans", s.HandlePlanCreate)
apiGroup.GET("/plans/:plan", s.HandlePlanGet)
apiGroup.GET("/plans/:plan/ways", s.HandleWayList)
apiGroup.POST("/plans/:plan/ways", s.HandleWayCreate)
apiGroup.GET("/plans/:plan/sync", s.HandleWaySync)
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
go func() {
err := s.notifier.Run(ctx)
if err != nil {
panic(err)
}
}()
return engine.Run(s.cfg.Listen)
}

11
backend/tberror/code.go Normal file
View File

@ -0,0 +1,11 @@
package tberror
const (
CodeSystem = 500000 + iota
CodeDatabase
CodeBadRequest
CodeInvalidArgs
CodeFileSave
)

120
frontend/.gitignore vendored Normal file
View File

@ -0,0 +1,120 @@
# ---> Node
# Logs
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
lerna-debug.log*
.pnpm-debug.log*
# Diagnostic reports (https://nodejs.org/api/report.html)
report.[0-9]*.[0-9]*.[0-9]*.[0-9]*.json
# Runtime data
pids
*.pid
*.seed
*.pid.lock
# Directory for instrumented libs generated by jscoverage/JSCover
lib-cov
# Coverage directory used by tools like istanbul
coverage
*.lcov
# nyc test coverage
.nyc_output
# Grunt intermediate storage (https://gruntjs.com/creating-plugins#storing-task-files)
.grunt
# Bower dependency directory (https://bower.io/)
bower_components
# node-waf configuration
.lock-wscript
# Compiled binary addons (https://nodejs.org/api/addons.html)
build/Release
# Dependency directories
node_modules/
jspm_packages/
# Snowpack dependency directory (https://snowpack.dev/)
web_modules/
# TypeScript cache
*.tsbuildinfo
# Optional npm cache directory
.npm
# Optional eslint cache
.eslintcache
# Microbundle cache
.rpt2_cache/
.rts2_cache_cjs/
.rts2_cache_es/
.rts2_cache_umd/
# Optional REPL history
.node_repl_history
# Output of 'npm pack'
*.tgz
# Yarn Integrity file
.yarn-integrity
# dotenv environment variables file
.env
.env.test
.env.production
# parcel-bundler cache (https://parceljs.org/)
.cache
.parcel-cache
# Next.js build output
.next
out
# Nuxt.js build / generate output
.nuxt
dist
# Gatsby files
.cache/
# Comment in the public line in if your project uses Gatsby and not Next.js
# https://nextjs.org/blog/next-9-1#public-directory-support
# public
# vuepress build output
.vuepress/dist
# Serverless directories
.serverless/
# FuseBox cache
.fusebox/
# DynamoDB Local files
.dynamodb/
# TernJS port file
.tern-port
# Stores VSCode versions used for testing VSCode extensions
.vscode-test
# yarn v2
.yarn/cache
.yarn/unplugged
.yarn/build-state.yml
.yarn/install-state.gz
.pnp.*

40
frontend/README.md Normal file
View File

@ -0,0 +1,40 @@
# frontend
This template should help get you started developing with Vue 3 in Vite.
## Recommended IDE Setup
[VSCode](https://code.visualstudio.com/) + [Volar](https://marketplace.visualstudio.com/items?itemName=Vue.volar) (and disable Vetur) + [TypeScript Vue Plugin (Volar)](https://marketplace.visualstudio.com/items?itemName=Vue.vscode-typescript-vue-plugin).
## Type Support for `.vue` Imports in TS
TypeScript cannot handle type information for `.vue` imports by default, so we replace the `tsc` CLI with `vue-tsc` for type checking. In editors, we need [TypeScript Vue Plugin (Volar)](https://marketplace.visualstudio.com/items?itemName=Vue.vscode-typescript-vue-plugin) to make the TypeScript language service aware of `.vue` types.
If the standalone TypeScript plugin doesn't feel fast enough to you, Volar has also implemented a [Take Over Mode](https://github.com/johnsoncodehk/volar/discussions/471#discussioncomment-1361669) that is more performant. You can enable it by the following steps:
1. Disable the built-in TypeScript Extension
1) Run `Extensions: Show Built-in Extensions` from VSCode's command palette
2) Find `TypeScript and JavaScript Language Features`, right click and select `Disable (Workspace)`
2. Reload the VSCode window by running `Developer: Reload Window` from the command palette.
## Customize configuration
See [Vite Configuration Reference](https://vitejs.dev/config/).
## Project Setup
```sh
npm install
```
### Compile and Hot-Reload for Development
```sh
npm run dev
```
### Type-Check, Compile and Minify for Production
```sh
npm run build
```

1
frontend/env.d.ts vendored Normal file
View File

@ -0,0 +1 @@
/// <reference types="vite/client" />

13
frontend/index.html Normal file
View File

@ -0,0 +1,13 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<link rel="icon" href="/favicon.ico">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>travebing-旅途愉快</title>
</head>
<body>
<div id="app"></div>
<script type="module" src="/src/main.ts"></script>
</body>
</html>

3132
frontend/package-lock.json generated Normal file

File diff suppressed because it is too large Load Diff

34
frontend/package.json Normal file
View File

@ -0,0 +1,34 @@
{
"name": "frontend",
"version": "0.0.0",
"private": true,
"type": "module",
"scripts": {
"dev": "vite",
"build": "run-p type-check \"build-only {@}\" --",
"preview": "vite preview",
"build-only": "vite build",
"type-check": "vue-tsc --build --force"
},
"dependencies": {
"@amap/amap-jsapi-loader": "^1.0.1",
"@vuemap/vue-amap": "^2.0.24",
"axios": "^1.6.7",
"element-plus": "^2.5.3",
"pinia": "^2.1.7",
"vue": "^3.4.15",
"vue-router": "^4.2.5",
"ws": "^8.16.0"
},
"devDependencies": {
"@tsconfig/node20": "^20.1.2",
"@types/node": "^20.11.10",
"@types/ws": "^8.5.10",
"@vitejs/plugin-vue": "^5.0.3",
"@vue/tsconfig": "^0.5.1",
"npm-run-all2": "^6.1.1",
"typescript": "~5.3.0",
"vite": "^5.0.11",
"vue-tsc": "^1.8.27"
}
}

BIN
frontend/public/favicon.ico Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.2 KiB

31
frontend/src/App.vue Normal file
View File

@ -0,0 +1,31 @@
<script setup lang="ts">
import { RouterLink, RouterView } from 'vue-router'
import { useRouter } from 'vue-router';
const router = useRouter()
const handleSelect = (key: string, keyPath: string[]) => {
switch (key) {
case "0":
router.push("/")
break
}
}
</script>
<template>
<div class="common-layout">
<el-container>
<el-header><el-menu :default-active="'1'" class="el-menu-demo" mode="horizontal" :ellipsis="false"
@select="handleSelect">
<el-menu-item index="0">
TraveBing
</el-menu-item>
<div class="flex-grow" />
</el-menu></el-header>
<el-main>
<RouterView />
</el-main>
</el-container>
</div>
</template>
<style scoped></style>

57
frontend/src/api/event.ts Normal file
View File

@ -0,0 +1,57 @@
import type { IWay } from "@/model/way"
import { apiPrefix } from "."
export const addEventListen = (plan:string, f:(data:IWay)=>void) => {
if (!window.EventSource) {
return null
}
console.info("addEventListen")
let eventSource = new EventSource(`${apiPrefix}/plans/${plan}/sync`, {
// // 设置重连时间
// heartbeatTimeout: 60 * 60 * 1000,
// // 添加token
// headers: {
// 'Token': `${state.token}`,
// }
})
// 监听message事件
eventSource.onmessage = (event: MessageEvent) => {
var message = JSON.parse(event.data);
console.info("recieve an event ", event.type, message)
switch (event.lastEventId) {
case "0":
console.info("this is an open message", message)
break;
case "1":
console.info("this is a system message", message)
let obj = message.data as IWay
f(obj)
break
}
}
// 监听open事件
eventSource.onopen = (event: Event) => {
// 连接成功后发送认证请求
console.info("connected", event)
}
// 监听error事件
eventSource.onerror = (event: Event) => {
if (eventSource.readyState == EventSource.CLOSED) {
console.log("SSE连接关闭");
} else if (eventSource.readyState == EventSource.CONNECTING) {
console.log("SSE正在重连");
//重新设置token
// state.eventSource.headers = {
// 'Token': `${state.token}`,
// };
} else {
console.log('error', event);
}
}
console.info(eventSource)
return eventSource
}

58
frontend/src/api/index.ts Normal file
View File

@ -0,0 +1,58 @@
import axios from 'axios'
import type { AxiosRequestConfig } from 'axios'
export const apiPrefix = `/api/v1`
const token = localStorage.getItem("token") || ""
const service = axios.create({
baseURL: '',
timeout: 1800000,
headers: { 'Content-Type': 'application/json', "Token":token }
})
export const setRequest = function(token:string) {
if(token) {
service.interceptors.request.use(config => {
config.headers = config.headers || {}
config.headers['Token'] = token
let type: 'params' | 'data' = config.method == 'post' ? 'data' : 'params'
return config
}, (error) => {
console.log("service.request:", error)
return Promise.reject(error)
})
}
}
service.interceptors.response.use((response) => {
return response.data
}, (error) => {
// if(error.response && error.response.status == 401) {
// window.location.href = "/login"
// return
// }
// console.info("service.response:", error)
return Promise.reject(error)
})
interface ResponseData<T> {
code: number,
message: string,
data: T
}
const post = <T = any>(url: string, data?: any, config?: any): Promise<ResponseData<T>> => {
return service.post(url, data, { ...config })
}
const get = <T = any>(url: string, data?: any, config?: AxiosRequestConfig): Promise<ResponseData<T>> => {
return service.get(url, { params: data, ...config })
}
const put = <T = any>(url: string, data?: any, config?: AxiosRequestConfig): Promise<ResponseData<T>> => {
return service.put(url, data, {...config} )
}
const del = <T = any>(url: string, data?: any, config?: AxiosRequestConfig): Promise<ResponseData<T>> => {
return service.delete(url, {params:data, ...config })
}
export {post, get, put, del, service as request}

8
frontend/src/api/plan.ts Normal file
View File

@ -0,0 +1,8 @@
import type { IPlan } from '@/model/plan'
import {get, post, del, put, apiPrefix} from '.'
export const PlanAPI = {
List: ()=> get<Array<IPlan>>(`${apiPrefix}/plans`),
Get:(id:string)=>get<IPlan>(`${apiPrefix}/plans/${id}`)
}

6
frontend/src/api/way.ts Normal file
View File

@ -0,0 +1,6 @@
import type { IWay } from '@/model/way';
import { get, apiPrefix } from '.';
export const WayAPI = {
List: (plan: string) => get<Array<IWay>>(`${apiPrefix}/plans/${plan}/ways`),
};

View File

@ -0,0 +1 @@
/* color palette from <https://github.com/vuejs/theme> */

View File

@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 261.76 226.69"><path d="M161.096.001l-30.225 52.351L100.647.001H-.005l130.877 226.688L261.749.001z" fill="#41b883"/><path d="M161.096.001l-30.225 52.351L100.647.001H52.346l78.526 136.01L209.398.001z" fill="#34495e"/></svg>

After

Width:  |  Height:  |  Size: 276 B

View File

@ -0,0 +1 @@
@import './base.css';

View File

@ -0,0 +1,41 @@
<script setup lang="ts">
defineProps<{
msg: string
}>()
</script>
<template>
<div class="greetings">
<h1 class="green">{{ msg }}</h1>
<h3>
Youve successfully created a project with
<a href="https://vitejs.dev/" target="_blank" rel="noopener">Vite</a> +
<a href="https://vuejs.org/" target="_blank" rel="noopener">Vue 3</a>. What's next?
</h3>
</div>
</template>
<style scoped>
h1 {
font-weight: 500;
font-size: 2.6rem;
position: relative;
top: -10px;
}
h3 {
font-size: 1.2rem;
}
.greetings h1,
.greetings h3 {
text-align: center;
}
@media (min-width: 1024px) {
.greetings h1,
.greetings h3 {
text-align: left;
}
}
</style>

View File

@ -0,0 +1,88 @@
<script setup lang="ts">
import WelcomeItem from './WelcomeItem.vue'
import DocumentationIcon from './icons/IconDocumentation.vue'
import ToolingIcon from './icons/IconTooling.vue'
import EcosystemIcon from './icons/IconEcosystem.vue'
import CommunityIcon from './icons/IconCommunity.vue'
import SupportIcon from './icons/IconSupport.vue'
</script>
<template>
<WelcomeItem>
<template #icon>
<DocumentationIcon />
</template>
<template #heading>Documentation</template>
Vues
<a href="https://vuejs.org/" target="_blank" rel="noopener">official documentation</a>
provides you with all information you need to get started.
</WelcomeItem>
<WelcomeItem>
<template #icon>
<ToolingIcon />
</template>
<template #heading>Tooling</template>
This project is served and bundled with
<a href="https://vitejs.dev/guide/features.html" target="_blank" rel="noopener">Vite</a>. The
recommended IDE setup is
<a href="https://code.visualstudio.com/" target="_blank" rel="noopener">VSCode</a> +
<a href="https://github.com/johnsoncodehk/volar" target="_blank" rel="noopener">Volar</a>. If
you need to test your components and web pages, check out
<a href="https://www.cypress.io/" target="_blank" rel="noopener">Cypress</a> and
<a href="https://on.cypress.io/component" target="_blank" rel="noopener"
>Cypress Component Testing</a
>.
<br />
More instructions are available in <code>README.md</code>.
</WelcomeItem>
<WelcomeItem>
<template #icon>
<EcosystemIcon />
</template>
<template #heading>Ecosystem</template>
Get official tools and libraries for your project:
<a href="https://pinia.vuejs.org/" target="_blank" rel="noopener">Pinia</a>,
<a href="https://router.vuejs.org/" target="_blank" rel="noopener">Vue Router</a>,
<a href="https://test-utils.vuejs.org/" target="_blank" rel="noopener">Vue Test Utils</a>, and
<a href="https://github.com/vuejs/devtools" target="_blank" rel="noopener">Vue Dev Tools</a>. If
you need more resources, we suggest paying
<a href="https://github.com/vuejs/awesome-vue" target="_blank" rel="noopener">Awesome Vue</a>
a visit.
</WelcomeItem>
<WelcomeItem>
<template #icon>
<CommunityIcon />
</template>
<template #heading>Community</template>
Got stuck? Ask your question on
<a href="https://chat.vuejs.org" target="_blank" rel="noopener">Vue Land</a>, our official
Discord server, or
<a href="https://stackoverflow.com/questions/tagged/vue.js" target="_blank" rel="noopener"
>StackOverflow</a
>. You should also subscribe to
<a href="https://news.vuejs.org" target="_blank" rel="noopener">our mailing list</a> and follow
the official
<a href="https://twitter.com/vuejs" target="_blank" rel="noopener">@vuejs</a>
twitter account for latest news in the Vue world.
</WelcomeItem>
<WelcomeItem>
<template #icon>
<SupportIcon />
</template>
<template #heading>Support Vue</template>
As an independent project, Vue relies on community backing for its sustainability. You can help
us by
<a href="https://vuejs.org/sponsor/" target="_blank" rel="noopener">becoming a sponsor</a>.
</WelcomeItem>
</template>

View File

@ -0,0 +1,87 @@
<template>
<div class="item">
<i>
<slot name="icon"></slot>
</i>
<div class="details">
<h3>
<slot name="heading"></slot>
</h3>
<slot></slot>
</div>
</div>
</template>
<style scoped>
.item {
margin-top: 2rem;
display: flex;
position: relative;
}
.details {
flex: 1;
margin-left: 1rem;
}
i {
display: flex;
place-items: center;
place-content: center;
width: 32px;
height: 32px;
color: var(--color-text);
}
h3 {
font-size: 1.2rem;
font-weight: 500;
margin-bottom: 0.4rem;
color: var(--color-heading);
}
@media (min-width: 1024px) {
.item {
margin-top: 0;
padding: 0.4rem 0 1rem calc(var(--section-gap) / 2);
}
i {
top: calc(50% - 25px);
left: -26px;
position: absolute;
border: 1px solid var(--color-border);
background: var(--color-background);
border-radius: 8px;
width: 50px;
height: 50px;
}
.item:before {
content: ' ';
border-left: 1px solid var(--color-border);
position: absolute;
left: 0;
bottom: calc(50% + 25px);
height: calc(50% - 25px);
}
.item:after {
content: ' ';
border-left: 1px solid var(--color-border);
position: absolute;
left: 0;
top: calc(50% + 25px);
height: calc(50% - 25px);
}
.item:first-of-type:before {
display: none;
}
.item:last-of-type:after {
display: none;
}
}
</style>

View File

@ -0,0 +1,7 @@
<template>
<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" fill="currentColor">
<path
d="M15 4a1 1 0 1 0 0 2V4zm0 11v-1a1 1 0 0 0-1 1h1zm0 4l-.707.707A1 1 0 0 0 16 19h-1zm-4-4l.707-.707A1 1 0 0 0 11 14v1zm-4.707-1.293a1 1 0 0 0-1.414 1.414l1.414-1.414zm-.707.707l-.707-.707.707.707zM9 11v-1a1 1 0 0 0-.707.293L9 11zm-4 0h1a1 1 0 0 0-1-1v1zm0 4H4a1 1 0 0 0 1.707.707L5 15zm10-9h2V4h-2v2zm2 0a1 1 0 0 1 1 1h2a3 3 0 0 0-3-3v2zm1 1v6h2V7h-2zm0 6a1 1 0 0 1-1 1v2a3 3 0 0 0 3-3h-2zm-1 1h-2v2h2v-2zm-3 1v4h2v-4h-2zm1.707 3.293l-4-4-1.414 1.414 4 4 1.414-1.414zM11 14H7v2h4v-2zm-4 0c-.276 0-.525-.111-.707-.293l-1.414 1.414C5.42 15.663 6.172 16 7 16v-2zm-.707 1.121l3.414-3.414-1.414-1.414-3.414 3.414 1.414 1.414zM9 12h4v-2H9v2zm4 0a3 3 0 0 0 3-3h-2a1 1 0 0 1-1 1v2zm3-3V3h-2v6h2zm0-6a3 3 0 0 0-3-3v2a1 1 0 0 1 1 1h2zm-3-3H3v2h10V0zM3 0a3 3 0 0 0-3 3h2a1 1 0 0 1 1-1V0zM0 3v6h2V3H0zm0 6a3 3 0 0 0 3 3v-2a1 1 0 0 1-1-1H0zm3 3h2v-2H3v2zm1-1v4h2v-4H4zm1.707 4.707l.586-.586-1.414-1.414-.586.586 1.414 1.414z"
/>
</svg>
</template>

View File

@ -0,0 +1,7 @@
<template>
<svg xmlns="http://www.w3.org/2000/svg" width="20" height="17" fill="currentColor">
<path
d="M11 2.253a1 1 0 1 0-2 0h2zm-2 13a1 1 0 1 0 2 0H9zm.447-12.167a1 1 0 1 0 1.107-1.666L9.447 3.086zM1 2.253L.447 1.42A1 1 0 0 0 0 2.253h1zm0 13H0a1 1 0 0 0 1.553.833L1 15.253zm8.447.833a1 1 0 1 0 1.107-1.666l-1.107 1.666zm0-14.666a1 1 0 1 0 1.107 1.666L9.447 1.42zM19 2.253h1a1 1 0 0 0-.447-.833L19 2.253zm0 13l-.553.833A1 1 0 0 0 20 15.253h-1zm-9.553-.833a1 1 0 1 0 1.107 1.666L9.447 14.42zM9 2.253v13h2v-13H9zm1.553-.833C9.203.523 7.42 0 5.5 0v2c1.572 0 2.961.431 3.947 1.086l1.107-1.666zM5.5 0C3.58 0 1.797.523.447 1.42l1.107 1.666C2.539 2.431 3.928 2 5.5 2V0zM0 2.253v13h2v-13H0zm1.553 13.833C2.539 15.431 3.928 15 5.5 15v-2c-1.92 0-3.703.523-5.053 1.42l1.107 1.666zM5.5 15c1.572 0 2.961.431 3.947 1.086l1.107-1.666C9.203 13.523 7.42 13 5.5 13v2zm5.053-11.914C11.539 2.431 12.928 2 14.5 2V0c-1.92 0-3.703.523-5.053 1.42l1.107 1.666zM14.5 2c1.573 0 2.961.431 3.947 1.086l1.107-1.666C18.203.523 16.421 0 14.5 0v2zm3.5.253v13h2v-13h-2zm1.553 12.167C18.203 13.523 16.421 13 14.5 13v2c1.573 0 2.961.431 3.947 1.086l1.107-1.666zM14.5 13c-1.92 0-3.703.523-5.053 1.42l1.107 1.666C11.539 15.431 12.928 15 14.5 15v-2z"
/>
</svg>
</template>

View File

@ -0,0 +1,7 @@
<template>
<svg xmlns="http://www.w3.org/2000/svg" width="18" height="20" fill="currentColor">
<path
d="M11.447 8.894a1 1 0 1 0-.894-1.789l.894 1.789zm-2.894-.789a1 1 0 1 0 .894 1.789l-.894-1.789zm0 1.789a1 1 0 1 0 .894-1.789l-.894 1.789zM7.447 7.106a1 1 0 1 0-.894 1.789l.894-1.789zM10 9a1 1 0 1 0-2 0h2zm-2 2.5a1 1 0 1 0 2 0H8zm9.447-5.606a1 1 0 1 0-.894-1.789l.894 1.789zm-2.894-.789a1 1 0 1 0 .894 1.789l-.894-1.789zm2 .789a1 1 0 1 0 .894-1.789l-.894 1.789zm-1.106-2.789a1 1 0 1 0-.894 1.789l.894-1.789zM18 5a1 1 0 1 0-2 0h2zm-2 2.5a1 1 0 1 0 2 0h-2zm-5.447-4.606a1 1 0 1 0 .894-1.789l-.894 1.789zM9 1l.447-.894a1 1 0 0 0-.894 0L9 1zm-2.447.106a1 1 0 1 0 .894 1.789l-.894-1.789zm-6 3a1 1 0 1 0 .894 1.789L.553 4.106zm2.894.789a1 1 0 1 0-.894-1.789l.894 1.789zm-2-.789a1 1 0 1 0-.894 1.789l.894-1.789zm1.106 2.789a1 1 0 1 0 .894-1.789l-.894 1.789zM2 5a1 1 0 1 0-2 0h2zM0 7.5a1 1 0 1 0 2 0H0zm8.553 12.394a1 1 0 1 0 .894-1.789l-.894 1.789zm-1.106-2.789a1 1 0 1 0-.894 1.789l.894-1.789zm1.106 1a1 1 0 1 0 .894 1.789l-.894-1.789zm2.894.789a1 1 0 1 0-.894-1.789l.894 1.789zM8 19a1 1 0 1 0 2 0H8zm2-2.5a1 1 0 1 0-2 0h2zm-7.447.394a1 1 0 1 0 .894-1.789l-.894 1.789zM1 15H0a1 1 0 0 0 .553.894L1 15zm1-2.5a1 1 0 1 0-2 0h2zm12.553 2.606a1 1 0 1 0 .894 1.789l-.894-1.789zM17 15l.447.894A1 1 0 0 0 18 15h-1zm1-2.5a1 1 0 1 0-2 0h2zm-7.447-5.394l-2 1 .894 1.789 2-1-.894-1.789zm-1.106 1l-2-1-.894 1.789 2 1 .894-1.789zM8 9v2.5h2V9H8zm8.553-4.894l-2 1 .894 1.789 2-1-.894-1.789zm.894 0l-2-1-.894 1.789 2 1 .894-1.789zM16 5v2.5h2V5h-2zm-4.553-3.894l-2-1-.894 1.789 2 1 .894-1.789zm-2.894-1l-2 1 .894 1.789 2-1L8.553.106zM1.447 5.894l2-1-.894-1.789-2 1 .894 1.789zm-.894 0l2 1 .894-1.789-2-1-.894 1.789zM0 5v2.5h2V5H0zm9.447 13.106l-2-1-.894 1.789 2 1 .894-1.789zm0 1.789l2-1-.894-1.789-2 1 .894 1.789zM10 19v-2.5H8V19h2zm-6.553-3.894l-2-1-.894 1.789 2 1 .894-1.789zM2 15v-2.5H0V15h2zm13.447 1.894l2-1-.894-1.789-2 1 .894 1.789zM18 15v-2.5h-2V15h2z"
/>
</svg>
</template>

View File

@ -0,0 +1,7 @@
<template>
<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" fill="currentColor">
<path
d="M10 3.22l-.61-.6a5.5 5.5 0 0 0-7.666.105 5.5 5.5 0 0 0-.114 7.665L10 18.78l8.39-8.4a5.5 5.5 0 0 0-.114-7.665 5.5 5.5 0 0 0-7.666-.105l-.61.61z"
/>
</svg>
</template>

View File

@ -0,0 +1,19 @@
<!-- This icon is from <https://github.com/Templarian/MaterialDesign>, distributed under Apache 2.0 (https://www.apache.org/licenses/LICENSE-2.0) license-->
<template>
<svg
xmlns="http://www.w3.org/2000/svg"
xmlns:xlink="http://www.w3.org/1999/xlink"
aria-hidden="true"
role="img"
class="iconify iconify--mdi"
width="24"
height="24"
preserveAspectRatio="xMidYMid meet"
viewBox="0 0 24 24"
>
<path
d="M20 18v-4h-3v1h-2v-1H9v1H7v-1H4v4h16M6.33 8l-1.74 4H7v-1h2v1h6v-1h2v1h2.41l-1.74-4H6.33M9 5v1h6V5H9m12.84 7.61c.1.22.16.48.16.8V18c0 .53-.21 1-.6 1.41c-.4.4-.85.59-1.4.59H4c-.55 0-1-.19-1.4-.59C2.21 19 2 18.53 2 18v-4.59c0-.32.06-.58.16-.8L4.5 7.22C4.84 6.41 5.45 6 6.33 6H7V5c0-.55.18-1 .57-1.41C7.96 3.2 8.44 3 9 3h6c.56 0 1.04.2 1.43.59c.39.41.57.86.57 1.41v1h.67c.88 0 1.49.41 1.83 1.22l2.34 5.39z"
fill="currentColor"
></path>
</svg>
</template>

28
frontend/src/main.ts Normal file
View File

@ -0,0 +1,28 @@
import './assets/main.css'
import { createApp } from 'vue'
import { createPinia } from 'pinia'
import App from './App.vue'
import router from './router'
import ElementPlus from 'element-plus'
import 'element-plus/dist/index.css'
import VueAMap, {initAMapApiLoader} from '@vuemap/vue-amap';
// import VueAMapLoca from '@vuemap/vue-amap-loca';
// import VueAMapExtra from '@vuemap/vue-amap-extra';
import '@vuemap/vue-amap/dist/style.css'
initAMapApiLoader({
key: '53454ecb24e9f607e4fa4db781efb61f',
securityJsCode: '8ac1d35497e01f86dd868b5b79e32f78', // 新版key需要配合安全密钥使用
//Loca:{
// version: '2.0.0'
//} // 如果需要使用loca组件库需要加载Loca
})
const app = createApp(App)
app.use(VueAMap)
app.use(createPinia())
app.use(router)
app.use(ElementPlus)
app.mount('#app')

View File

@ -0,0 +1,7 @@
export interface IPlan {
id: number
name:string
leave:string
arrive:string
createdAt: number
}

10
frontend/src/model/way.ts Normal file
View File

@ -0,0 +1,10 @@
export interface IWay {
id: number
plan: number
image: string
lat: number
lon: number
address: string
createdAt: number
time?:string
}

View File

@ -0,0 +1,23 @@
import { createRouter, createWebHistory } from 'vue-router'
import HomeView from '../views/HomeView.vue'
const router = createRouter({
history: createWebHistory(import.meta.env.BASE_URL),
routes: [
{
path: '/',
name: 'home',
component: HomeView
},
{
path: '/plans/:id',
name: 'plan',
// route level code-splitting
// this generates a separate chunk (About.[hash].js) for this route
// which is lazy-loaded when the route is visited.
component: () => import('../views/PlanView.vue')
}
]
})
export default router

View File

@ -0,0 +1,12 @@
import { ref, computed } from 'vue'
import { defineStore } from 'pinia'
export const useCounterStore = defineStore('counter', () => {
const count = ref(0)
const doubleCount = computed(() => count.value * 2)
function increment() {
count.value++
}
return { count, doubleCount, increment }
})

View File

@ -0,0 +1,42 @@
<template>
<div>
<el-row v-for="p in state.plans" :key="p.id" class="plan-row" @click ="()=>{openPlan(p)}">
<h3>{{ p.name }}({{ p.leave }}@{{ formatDate(p.createdAt) }} --- {{ p.arrive }})</h3>
</el-row>
</div>
</template>
<script setup lang="ts">
import { onBeforeMount, reactive } from 'vue';
import {PlanAPI} from '@/api/plan'
import {type IPlan} from '@/model/plan'
import { useRouter } from 'vue-router';
const state = reactive({
plans: [] as unknown as Array<IPlan>
})
const listPlan = ()=>{
PlanAPI.List().then(res=>{
state.plans = []
res.data.map(p=>state.plans.push(p))
})
}
onBeforeMount(async () => {
listPlan()
})
const formatDate = (t: number) => {
let date = new Date(t * 1000);
let formattedDate = date.getFullYear() + '年' + (date.getMonth() + 1).toString().padStart(2, '0') + '月' + date.getDate().toString().padStart(2, '0') + '日 ' + date.getHours().toString().padStart(2, '0') + '时' + date.getMinutes().toString().padStart(2, '0') + '分' + date.getSeconds().toString().padStart(2, '0') + '秒';
console.log(t, formattedDate);
return formattedDate
}
const router = useRouter()
const openPlan = (p:IPlan)=>{
router.push(`/plans/${p.id}`)
}
</script>
<style scoped>
.plan-row {
margin-bottom: 10px;
}
</style>

View File

@ -0,0 +1,129 @@
<template>
<div>
<el-row>
<h3>{{ state.plan.name }}</h3>
</el-row>
<el-row>
<h4>{{ state.current.time }}: {{ state.current.address }}({{ state.current.lon }}, {{
state.current.lat }})</h4>
</el-row>
<el-row>
<div class="amap">
<el-amap :show-label="true" :center="state.center" :zoom="11" @click="clickMap" @init="initMap">
<el-amap-polyline :editable="polyline.editable" :visible="polyline.visible" :draggable="polyline.draggable"
:path="polyline.path" @click="click" />
</el-amap>
</div>
</el-row>
<el-row>
<el-image class="amap" :src="state.latestImg" :fit="'contain'" />
</el-row>
</div>
</template>
<script setup lang="ts">
import { onBeforeMount, onMounted, onUnmounted, reactive, ref } from 'vue';
import { PlanAPI } from '@/api/plan'
import { WayAPI } from '@/api/way'
import { type IPlan } from '@/model/plan'
import { type IWay } from '@/model/way'
import { useRoute } from 'vue-router'
import { addEventListen } from '@/api/event';
const route = useRoute()
const zoom = ref(12);
const state = reactive({
plan: {} as unknown as IPlan,
ways: [] as unknown as Array<IWay>,
center: [113.5271, 22.232183],
eventListened: false,
eventSource: null as unknown as EventSource,
current: {} as unknown as IWay,
latestImg: ""
})
const polyline = reactive({
path: [[113.5271, 22.232183]],
editable: false,
visible: true,
draggable: false
});
const setCenter = (w: IWay) => {
state.center = [w.lon, w.lat]
if(w.image != "") {
state.latestImg = w.image + `?resize_w=800`
}
console.info(w.createdAt)
w.time = formatDate(w.createdAt)
state.current = w
}
const listWay = () => {
let p = route.params["id"] as string
WayAPI.List(p).then(res => {
console.info(res)
polyline.path = []
res.data.map(w => { state.ways.push(w); polyline.path.push([w.lon, w.lat]); setCenter(w); })
console.info('====>', polyline.path)
})
}
const getPlan = () => {
let p = route.params["id"] as string
PlanAPI.Get(p).then(res => {
if (res.code == 0) {
state.plan = res.data
}
})
}
const wayCallback = (w: IWay) => {
if (w.lon == 0 || w.lat == 0) {
return
}
setCenter(w)
polyline.path.push([w.lon, w.lat])
}
const syncWay = () => {
let p = route.params["id"] as string
if (!state.eventListened) {
addEventListen(p, wayCallback)
state.eventListened = true
}
}
const formatDate = (t: number) => {
let date = new Date(t * 1000);
let formattedDate = date.getFullYear() + '年' + (date.getMonth() + 1).toString().padStart(2, '0') + '月' + date.getDate().toString().padStart(2, '0') + '日 ' + date.getHours().toString().padStart(2, '0') + '时' + date.getMinutes().toString().padStart(2, '0') + '分' + date.getSeconds().toString().padStart(2, '0') + '秒';
console.log(t, formattedDate);
return formattedDate
}
const clickMap = (e: any) => {
console.log('click map: ', e);
}
const initMap = (map: any) => {
console.log('init map: ', map);
}
const click = (e: any) => {
}
onBeforeMount(async () => {
getPlan()
await listWay()
syncWay()
});
onUnmounted(() => {
});
</script>
<style scoped>
.amap {
height: 45vh;
width: 90vw;
}
</style>

View File

@ -0,0 +1,14 @@
{
"extends": "@vue/tsconfig/tsconfig.dom.json",
"include": ["env.d.ts", "src/**/*", "src/**/*.vue", "src/**/*.ts"],
"exclude": ["src/**/__tests__/*"],
"compilerOptions": {
"composite": true,
"tsBuildInfoFile": "./node_modules/.tmp/tsconfig.app.tsbuildinfo",
"baseUrl": ".",
"paths": {
"@/*": ["src/*"]
}
}
}

11
frontend/tsconfig.json Normal file
View File

@ -0,0 +1,11 @@
{
"files": [],
"references": [
{
"path": "./tsconfig.node.json"
},
{
"path": "./tsconfig.app.json"
}
]
}

View File

@ -0,0 +1,19 @@
{
"extends": "@tsconfig/node20/tsconfig.json",
"include": [
"vite.config.*",
"vitest.config.*",
"cypress.config.*",
"nightwatch.conf.*",
"playwright.config.*"
],
"compilerOptions": {
"composite": true,
"noEmit": true,
"tsBuildInfoFile": "./node_modules/.tmp/tsconfig.node.tsbuildinfo",
"module": "ESNext",
"moduleResolution": "Bundler",
"types": ["node"]
}
}

Some files were not shown because too many files have changed in this diff Show More