From a3851d8a93518acff6bb3b97daf2542764ddf3fd Mon Sep 17 00:00:00 2001 From: Chigusa Date: Fri, 1 Aug 2025 21:54:11 +0800 Subject: [PATCH] code clean (#869) * - run go fmt - "github.com/golang/mock" are no longer maintained, use "go.uber.org/mock" * update go version to 1.24 * add golangci-lint * - replace interface{} to any (Go 1.18 feature) - fix non-compliant code --- .github/workflows/release.yaml | 2 +- .github/workflows/tests.yaml | 23 ++++- .golangci.yml | 22 +++++ README.md | 12 --- Videos/.gitignore | 4 - go.mod | 47 +++++++--- go.sum | 37 +++----- src/cmd/bililive/bililive.go | 12 +-- src/cmd/bililive/internal/init.go | 2 - src/configs/config.go | 7 +- src/listeners/listener.go | 2 +- src/listeners/listener_test.go | 2 +- src/listeners/manager.go | 4 +- src/listeners/manager_test.go | 2 +- src/listeners/mock_test.go | 57 +++++++----- src/live/acfun/url.go | 4 +- src/live/douyin/douyin.go | 6 +- src/live/douyu/douyu.go | 10 +- src/live/huomao/huomao.go | 134 --------------------------- src/live/huya/implForXingXiu.go | 2 +- src/live/lives.go | 2 +- src/live/longzhu/longzhu.go | 129 -------------------------- src/live/mock/mock.go | 14 ++- src/live/system/initializing_live.go | 96 +++++++++---------- src/live/twitch/twitch.go | 2 - src/live/weibolive/weibolive.go | 4 +- src/live/xiaohongshu/xiaohongshu.go | 2 +- src/live/yy/yy.go | 3 + src/metrics/metrics.go | 2 +- src/pkg/events/event.go | 4 +- src/pkg/events/mock/mock.go | 56 ++++++----- src/pkg/parser/mock/mock.go | 16 +++- src/pkg/reader/reader.go | 3 +- src/pkg/utils/functions.go | 4 +- src/pkg/utils/strings.go | 2 +- src/pkg/utils/utils.go | 2 +- src/recorders/event.go | 6 +- src/recorders/manager.go | 2 +- src/recorders/manager_test.go | 2 +- src/recorders/mock_test.go | 73 ++++++++------- src/recorders/recorder.go | 6 +- src/servers/handler.go | 35 ++++--- src/servers/middleware.go | 2 +- src/servers/models.go | 6 +- src/servers/utils.go | 4 +- 45 files changed, 338 insertions(+), 530 deletions(-) create mode 100644 .golangci.yml delete mode 100644 Videos/.gitignore delete mode 100644 src/live/huomao/huomao.go delete mode 100644 src/live/longzhu/longzhu.go diff --git a/.github/workflows/release.yaml b/.github/workflows/release.yaml index 953d7fb..22d3973 100644 --- a/.github/workflows/release.yaml +++ b/.github/workflows/release.yaml @@ -11,7 +11,7 @@ jobs: - run: echo "GIT_TAG=`echo $(git describe --tags --abbrev=0)`" >> $GITHUB_ENV - uses: actions/setup-go@v2 with: - go-version: 1.19 + go-version: 1.24 - run: go install github.com/golang/mock/mockgen@v1.6.0 - uses: actions/setup-node@v2.4.0 - name: Build Web Page diff --git a/.github/workflows/tests.yaml b/.github/workflows/tests.yaml index f87c89d..a535b2d 100644 --- a/.github/workflows/tests.yaml +++ b/.github/workflows/tests.yaml @@ -15,7 +15,7 @@ jobs: - name: Set up Go uses: actions/setup-go@v2 with: - go-version: 1.19 + go-version: 1.24 - name: Setup Node.js environment uses: actions/setup-node@v2.4.0 - name: Build @@ -28,10 +28,27 @@ jobs: - name: Set up Go uses: actions/setup-go@v2 with: - go-version: 1.19 + go-version: 1.24 - name: Setup Node.js environment uses: actions/setup-node@v2.4.0 - name: Test run: make build-web test - name: Codecov - uses: codecov/codecov-action@v2 \ No newline at end of file + uses: codecov/codecov-action@v2 + lint: + name: Lint + runs-on: ubuntu-latest + if: github.event_name == 'pull_request' + timeout-minutes: 3 + steps: + - uses: actions/checkout@v4 + with: + fetch-depth: 1 + - name: Setup Go + uses: actions/setup-go@v5 + with: + go-version: 1.24 + - use: golangci/golangci-lint-action@v8 + with: + working-directory: src/ + args: --build-tags=dev \ No newline at end of file diff --git a/.golangci.yml b/.golangci.yml new file mode 100644 index 0000000..6274712 --- /dev/null +++ b/.golangci.yml @@ -0,0 +1,22 @@ +version: "2" +linters: + disable: + - errcheck + exclusions: + generated: lax + presets: + - comments + - common-false-positives + - legacy + - std-error-handling + paths: + - third_party$ + - builtin$ + - examples$ +formatters: + exclusions: + generated: lax + paths: + - third_party$ + - builtin$ + - examples$ diff --git a/README.md b/README.md index 004751c..65311bc 100644 --- a/README.md +++ b/README.md @@ -42,18 +42,6 @@ Bililive-go是一个支持多种直播平台的直播录制工具 滋瓷 - - 火猫直播 - www.huomao.com - 滋瓷 - - - - 龙珠直播 - longzhu.com - 滋瓷 - - 虎牙直播 www.huya.com diff --git a/Videos/.gitignore b/Videos/.gitignore deleted file mode 100644 index 86d0cb2..0000000 --- a/Videos/.gitignore +++ /dev/null @@ -1,4 +0,0 @@ -# Ignore everything in this directory -* -# Except this file -!.gitignore \ No newline at end of file diff --git a/go.mod b/go.mod index 19eacdd..d32dfd7 100644 --- a/go.mod +++ b/go.mod @@ -1,29 +1,52 @@ module github.com/bililive-go/bililive-go -go 1.16 +go 1.23.0 + +toolchain go1.24.4 require ( - github.com/Masterminds/goutils v1.1.0 // indirect - github.com/Masterminds/semver v1.5.0 // indirect github.com/Masterminds/sprig v2.22.0+incompatible github.com/alecthomas/kingpin v2.2.7-0.20180312062423-a39589180ebd+incompatible github.com/bluele/gcache v0.0.0-20190518031135-bc40bd653833 - github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc // indirect - github.com/golang/mock v1.6.0 - github.com/google/uuid v1.1.2 // indirect github.com/gorilla/mux v1.7.4 github.com/hr3lxphr6j/requests v0.0.1 - github.com/huandu/xstrings v1.3.2 // indirect - github.com/imdario/mergo v0.3.11 // indirect github.com/lthibault/jitterbug v2.0.0+incompatible - github.com/mitchellh/copystructure v1.0.0 // indirect - github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 // indirect github.com/prometheus/client_golang v1.11.0 github.com/robertkrimen/otto v0.0.0-20191219234010-c382bd3c16ff github.com/satori/go.uuid v1.2.1-0.20181028125025-b2ce2384e17b github.com/sirupsen/logrus v1.6.0 - github.com/stretchr/testify v1.6.1 + github.com/stretchr/testify v1.9.0 github.com/tidwall/gjson v1.9.3 - gopkg.in/sourcemap.v1 v1.0.5 // indirect + go.uber.org/mock v0.5.2 gopkg.in/yaml.v2 v2.3.0 ) + +require ( + github.com/Masterminds/goutils v1.1.0 // indirect + github.com/Masterminds/semver v1.5.0 // indirect + github.com/alecthomas/template v0.0.0-20190718012654-fb15b899a751 // indirect + github.com/alecthomas/units v0.0.0-20190924025748-f65c72e2690d // indirect + github.com/beorn7/perks v1.0.1 // indirect + github.com/cespare/xxhash/v2 v2.1.1 // indirect + github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc // indirect + github.com/golang/protobuf v1.4.3 // indirect + github.com/google/go-cmp v0.6.0 // indirect + github.com/google/uuid v1.1.2 // indirect + github.com/huandu/xstrings v1.3.2 // indirect + github.com/imdario/mergo v0.3.11 // indirect + github.com/konsorten/go-windows-terminal-sequences v1.0.3 // indirect + github.com/matttproud/golang_protobuf_extensions v1.0.1 // indirect + github.com/mitchellh/copystructure v1.0.0 // indirect + github.com/mitchellh/reflectwalk v1.0.0 // indirect + github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 // indirect + github.com/prometheus/client_model v0.2.0 // indirect + github.com/prometheus/common v0.26.0 // indirect + github.com/prometheus/procfs v0.6.0 // indirect + github.com/tidwall/match v1.1.1 // indirect + github.com/tidwall/pretty v1.2.0 // indirect + golang.org/x/crypto v0.39.0 // indirect + golang.org/x/sys v0.33.0 // indirect + google.golang.org/protobuf v1.26.0-rc.1 // indirect + gopkg.in/sourcemap.v1 v1.0.5 // indirect + gopkg.in/yaml.v3 v3.0.1 // indirect +) diff --git a/go.sum b/go.sum index d1b7189..0a4e3c6 100644 --- a/go.sum +++ b/go.sum @@ -34,8 +34,6 @@ github.com/go-logfmt/logfmt v0.4.0/go.mod h1:3RMwSq7FuexP4Kalkev3ejPJsZTpXXBr9+V github.com/go-logfmt/logfmt v0.5.0/go.mod h1:wCYkCAKZfumFQihp8CzCvQ3paCTfi41vtzG1KdI/P7A= github.com/go-stack/stack v1.8.0/go.mod h1:v0f6uXyyMGvRgIKkXu+yp6POWl0qKG85gN/melR3HDY= github.com/gogo/protobuf v1.1.1/go.mod h1:r8qH/GZQm5c6nD/R0oafs1akxWv10x8SbQlK7atdtwQ= -github.com/golang/mock v1.6.0 h1:ErTB+efbowRARo13NNdxyJji2egdxLGQhRaY+DUumQc= -github.com/golang/mock v1.6.0/go.mod h1:p6yTPP+5HYm5mzsMV8JkE6ZKdX+/wYM6Hr+LicevLPs= github.com/golang/protobuf v1.2.0/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= github.com/golang/protobuf v1.3.1/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= github.com/golang/protobuf v1.3.2/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= @@ -51,8 +49,9 @@ github.com/google/go-cmp v0.3.0/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMyw github.com/google/go-cmp v0.3.1/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU= github.com/google/go-cmp v0.4.0/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= github.com/google/go-cmp v0.5.4/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= -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/go-cmp v0.6.0 h1:ofyhxvXcZhMsU5ulbFiLKl/XBFqE1GSq7atu8tAmTRI= +github.com/google/go-cmp v0.6.0/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY= github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg= github.com/google/uuid v1.1.2 h1:EVhdT+1Kseyi1/pUmXKaFxYsDNy9RQYkMWRH68J/W7Y= github.com/google/uuid v1.1.2/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= @@ -130,36 +129,33 @@ github.com/stretchr/objx v0.1.1/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+ github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs= github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI= github.com/stretchr/testify v1.4.0/go.mod h1:j7eGeouHqKxXV5pUuKE4zz7dFj8WfuZ+81PSLYec5m4= -github.com/stretchr/testify v1.6.1 h1:hDPOHmpOpP40lSULcqw7IrRb/u7w6RpDC9399XyoNd0= github.com/stretchr/testify v1.6.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= +github.com/stretchr/testify v1.9.0 h1:HtqpIVDClZ4nwg75+f6Lvsy/wHu+3BoSGCbBAcpTsTg= +github.com/stretchr/testify v1.9.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY= github.com/tidwall/gjson v1.9.3 h1:hqzS9wAHMO+KVBBkLxYdkEeeFHuqr95GfClRLKlgK0E= github.com/tidwall/gjson v1.9.3/go.mod h1:/wbyibRr2FHMks5tjHJ5F8dMZh3AcwJEMf5vlfC0lxk= github.com/tidwall/match v1.1.1 h1:+Ho715JplO36QYgwN9PGYNhgZvoUSc9X2c80KVTi+GA= github.com/tidwall/match v1.1.1/go.mod h1:eRSPERbgtNPcGhD8UCthc6PmLEQXEWd3PRB5JTxsfmM= github.com/tidwall/pretty v1.2.0 h1:RWIZEg2iJ8/g6fDDYzMpobmaoGh5OLl4AXtGUGPcqCs= github.com/tidwall/pretty v1.2.0/go.mod h1:ITEVvHYasfjBbM0u2Pg8T2nJnzm8xPwvNhhsoaGGjNU= -github.com/yuin/goldmark v1.3.5/go.mod h1:mwnBkeHKe2W/ZEtQ+71ViKU8L12m81fl3OWwC1Zlc8k= +go.uber.org/mock v0.5.2 h1:LbtPTcP8A5k9WPXj54PPPbjcI4Y6lhyOZXn+VS7wNko= +go.uber.org/mock v0.5.2/go.mod h1:wLlUxC2vVTPTaE3UD51E0BGOAElKrILxhVSDYQLld5o= golang.org/x/crypto v0.0.0-20180904163835-0709b304e793/go.mod h1:6SG95UA2DQfeDnfUPMdvaQW0Q7yPrPDi9nlGo2tz2b4= golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= -golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= -golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9 h1:psW17arqaxU48Z5kZ0CQnkZWQJsqcURM6tKiBApRjXI= golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= -golang.org/x/mod v0.4.2/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= +golang.org/x/crypto v0.39.0 h1:SHs+kF4LP+f+p14esP5jAoDpHU8Gu/v9lFRK6IT5imM= +golang.org/x/crypto v0.39.0/go.mod h1:L+Xg3Wf6HoL4Bn4238Z6ft6KfEpN0tJGo53AAPC632U= golang.org/x/net v0.0.0-20180724234803-3673e40ba225/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= golang.org/x/net v0.0.0-20181114220301-adae6a3d119a/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= golang.org/x/net v0.0.0-20190108225652-1e06a53dbb7e/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= golang.org/x/net v0.0.0-20190613194153-d28f0bde5980/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= -golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= golang.org/x/net v0.0.0-20200625001655-4c5254603344/go.mod h1:/O7V0waA8r7cgGh81Ro3o1hOxt32SMVPicZroKQ2sZA= -golang.org/x/net v0.0.0-20210405180319-a5a99cb37ef4/go.mod h1:p54w0d4576C0XHj96bSt6lcn1PtDYWL6XObtHCRCNQM= golang.org/x/oauth2 v0.0.0-20190226205417-e64efc72b421/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw= golang.org/x/sync v0.0.0-20181108010431-42b317875d0f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20181221193216-37e7f081c4d4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= -golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20190911185100-cd5d95a43a6e/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20201207232520-09787c993a3a/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= -golang.org/x/sync v0.0.0-20210220032951-036812b2e83c/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sys v0.0.0-20180905080454-ebe1bf3edb33/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20181116152217-5ac8a444bdc5/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= @@ -169,24 +165,14 @@ golang.org/x/sys v0.0.0-20200106162015-b016eb3dc98e/go.mod h1:h1NjWce9XRLGQEsW7w golang.org/x/sys v0.0.0-20200323222414-85ca7c5b95cd/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20200615200032-f1bc736245b1/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20200625212154-ddb9806d33ae/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20210124154548-22da62e12c0c/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20210330210617-4fbd30eecc44/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20210510120138-977fb7262007/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.0.0-20210603081109-ebe580a85c40 h1:JWgyZ1qgdTaF3N3oxC+MdTV7qvEEgHo3otj+HB5CM7Q= golang.org/x/sys v0.0.0-20210603081109-ebe580a85c40/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= +golang.org/x/sys v0.33.0 h1:q3i8TbbEz+JRD9ywIRlyRAQbM0qF7hu24q3teo2hbuw= +golang.org/x/sys v0.33.0/go.mod h1:BJP2sWEmIv4KK5OTEluFJCKSidICx8ciO85XgH3Ak8k= golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= golang.org/x/text v0.3.2/go.mod h1:bEr9sfX3Q8Zfm5fL9x+3itogRgK3+ptLWKqgva+5dAk= -golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= 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.1/go.mod h1:o0xws9oXOQQZyjljx8fwUC0k7L1pTE6eaCbjGeHmOkk= -golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= -golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= -golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1 h1:go1bK/D/BFZV2I8cIQd1NKEZ+0owSTG1fDTci4IqFcE= -golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= google.golang.org/appengine v1.4.0/go.mod h1:xpcJRLb0r/rnEns0DIKYYv+WjYCduHsrkT7/EB5XEv4= google.golang.org/protobuf v0.0.0-20200109180630-ec00e32a8dfd/go.mod h1:DFci5gLYBciE7Vtevhsrf46CRTquxDuWsQurQQe4oz8= google.golang.org/protobuf v0.0.0-20200221191635-4d8936d0db64/go.mod h1:kwYJMbMJ01Woi6D6+Kah6886xMZcty6N08ah7+eCXa0= @@ -208,5 +194,6 @@ gopkg.in/yaml.v2 v2.2.4/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= gopkg.in/yaml.v2 v2.2.5/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= gopkg.in/yaml.v2 v2.3.0 h1:clyUAQHOM3G0M3f5vQj7LuJrETvjVot3Z5el9nffUtU= gopkg.in/yaml.v2 v2.3.0/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= -gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c h1:dUUwHk2QECo/6vqA44rthZ8ie2QXMNeKRTHCNY2nXvo= 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= diff --git a/src/cmd/bililive/bililive.go b/src/cmd/bililive/bililive.go index b503d8a..3bfb885 100644 --- a/src/cmd/bililive/bililive.go +++ b/src/cmd/bililive/bililive.go @@ -94,10 +94,8 @@ func main() { events.NewDispatcher(ctx) inst.Lives = make(map[types.LiveID]live.Live) - for index, _ := range inst.Config.LiveRooms { - room := &inst.Config.LiveRooms[index] - - l, err := live.New(ctx, room, inst.Cache) + for _, room := range inst.Config.LiveRooms { + l, err := live.New(ctx, &room, inst.Cache) if err != nil { logger.WithField("url", room).Error(err.Error()) continue @@ -131,18 +129,18 @@ func main() { for _, _live := range inst.Lives { room, err := inst.Config.GetLiveRoomByUrl(_live.GetRawUrl()) if err != nil { - logger.WithFields(map[string]interface{}{"room": _live.GetRawUrl()}).Error(err) + logger.WithFields(map[string]any{"room": _live.GetRawUrl()}).Error(err) panic(err) } if room.IsListening { if err := lm.AddListener(ctx, _live); err != nil { - logger.WithFields(map[string]interface{}{"url": _live.GetRawUrl()}).Error(err) + logger.WithFields(map[string]any{"url": _live.GetRawUrl()}).Error(err) } } time.Sleep(time.Second * 5) } - c := make(chan os.Signal) + c := make(chan os.Signal, 1) signal.Notify(c, syscall.SIGHUP, syscall.SIGINT, syscall.SIGTERM) go func() { <-c diff --git a/src/cmd/bililive/internal/init.go b/src/cmd/bililive/internal/init.go index ce66c70..ecf0061 100644 --- a/src/cmd/bililive/internal/init.go +++ b/src/cmd/bililive/internal/init.go @@ -9,11 +9,9 @@ import ( _ "github.com/bililive-go/bililive-go/src/live/douyu" _ "github.com/bililive-go/bililive-go/src/live/hongdoufm" _ "github.com/bililive-go/bililive-go/src/live/huajiao" - _ "github.com/bililive-go/bililive-go/src/live/huomao" _ "github.com/bililive-go/bililive-go/src/live/huya" _ "github.com/bililive-go/bililive-go/src/live/kuaishou" _ "github.com/bililive-go/bililive-go/src/live/lang" - _ "github.com/bililive-go/bililive-go/src/live/longzhu" _ "github.com/bililive-go/bililive-go/src/live/missevan" _ "github.com/bililive-go/bililive-go/src/live/openrec" _ "github.com/bililive-go/bililive-go/src/live/qq" diff --git a/src/configs/config.go b/src/configs/config.go index 4b5366d..cbf5892 100644 --- a/src/configs/config.go +++ b/src/configs/config.go @@ -3,7 +3,6 @@ package configs import ( "errors" "fmt" - "io/ioutil" "net" "os" "time" @@ -93,7 +92,7 @@ type LiveRoom struct { type liveRoomAlias LiveRoom // allow both string and LiveRoom format in config -func (l *LiveRoom) UnmarshalYAML(unmarshal func(interface{}) error) error { +func (l *LiveRoom) UnmarshalYAML(unmarshal func(any) error) error { liveRoomAlias := liveRoomAlias{ IsListening: true, } @@ -228,7 +227,7 @@ func NewConfigWithBytes(b []byte) (*Config, error) { } func NewConfigWithFile(file string) (*Config, error) { - b, err := ioutil.ReadFile(file) + b, err := os.ReadFile(file) if err != nil { return nil, fmt.Errorf("can`t open file: %s", file) } @@ -248,7 +247,7 @@ func (c *Config) Marshal() error { if err != nil { return err } - return ioutil.WriteFile(c.File, b, os.ModeAppend) + return os.WriteFile(c.File, b, os.ModeAppend) } func (c Config) GetFilePath() (string, error) { diff --git a/src/listeners/listener.go b/src/listeners/listener.go index 8aea3ca..24ecae4 100644 --- a/src/listeners/listener.go +++ b/src/listeners/listener.go @@ -87,7 +87,7 @@ func (l *listener) refresh() { latestStatus = status{roomName: info.RoomName, roomStatus: info.Status} evtTyp events.EventType logInfo string - fields = map[string]interface{}{ + fields = map[string]any{ "room": info.RoomName, "host": info.HostName, } diff --git a/src/listeners/listener_test.go b/src/listeners/listener_test.go index ffcd35e..c1306e9 100644 --- a/src/listeners/listener_test.go +++ b/src/listeners/listener_test.go @@ -6,7 +6,6 @@ import ( "testing" "github.com/bluele/gcache" - "github.com/golang/mock/gomock" "github.com/stretchr/testify/assert" "github.com/bililive-go/bililive-go/src/configs" @@ -16,6 +15,7 @@ import ( "github.com/bililive-go/bililive-go/src/log" "github.com/bililive-go/bililive-go/src/pkg/events" evtmock "github.com/bililive-go/bililive-go/src/pkg/events/mock" + gomock "go.uber.org/mock/gomock" ) func TestRefresh(t *testing.T) { diff --git a/src/listeners/manager.go b/src/listeners/manager.go index 2531b91..a4009bf 100644 --- a/src/listeners/manager.go +++ b/src/listeners/manager.go @@ -50,7 +50,7 @@ func (m *manager) registryListener(ctx context.Context, ed events.Dispatcher) { room, err := inst.Config.GetLiveRoomByUrl(live.GetRawUrl()) if err != nil { - logger.WithFields(map[string]interface{}{ + logger.WithFields(map[string]any{ "room": live.GetRawUrl(), }).Error(err) panic(err) @@ -58,7 +58,7 @@ func (m *manager) registryListener(ctx context.Context, ed events.Dispatcher) { room.LiveId = live.GetLiveId() if room.IsListening { if err := m.replaceListener(ctx, initializingLive, live); err != nil { - logger.WithFields(map[string]interface{}{ + logger.WithFields(map[string]any{ "url": live.GetRawUrl(), }).Error(err) } diff --git a/src/listeners/manager_test.go b/src/listeners/manager_test.go index 2f7d2b0..3ac57ad 100644 --- a/src/listeners/manager_test.go +++ b/src/listeners/manager_test.go @@ -5,8 +5,8 @@ import ( "fmt" "testing" - "github.com/golang/mock/gomock" "github.com/stretchr/testify/assert" + gomock "go.uber.org/mock/gomock" "github.com/bililive-go/bililive-go/src/configs" "github.com/bililive-go/bililive-go/src/instance" diff --git a/src/listeners/mock_test.go b/src/listeners/mock_test.go index 348cc51..f5fb795 100644 --- a/src/listeners/mock_test.go +++ b/src/listeners/mock_test.go @@ -1,5 +1,10 @@ // Code generated by MockGen. DO NOT EDIT. // Source: github.com/bililive-go/bililive-go/src/listeners (interfaces: Listener,Manager) +// +// Generated by this command: +// +// mockgen -package listeners -destination mock_test.go github.com/bililive-go/bililive-go/src/listeners Listener,Manager +// // Package listeners is a generated GoMock package. package listeners @@ -8,15 +13,16 @@ import ( context "context" reflect "reflect" - gomock "github.com/golang/mock/gomock" live "github.com/bililive-go/bililive-go/src/live" types "github.com/bililive-go/bililive-go/src/types" + gomock "go.uber.org/mock/gomock" ) // MockListener is a mock of Listener interface. type MockListener struct { ctrl *gomock.Controller recorder *MockListenerMockRecorder + isgomock struct{} } // MockListenerMockRecorder is the mock recorder for MockListener. @@ -66,6 +72,7 @@ func (mr *MockListenerMockRecorder) Start() *gomock.Call { type MockManager struct { ctrl *gomock.Controller recorder *MockManagerMockRecorder + isgomock struct{} } // MockManagerMockRecorder is the mock recorder for MockManager. @@ -86,84 +93,84 @@ func (m *MockManager) EXPECT() *MockManagerMockRecorder { } // AddListener mocks base method. -func (m *MockManager) AddListener(arg0 context.Context, arg1 live.Live) error { +func (m *MockManager) AddListener(ctx context.Context, arg1 live.Live) error { m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "AddListener", arg0, arg1) + ret := m.ctrl.Call(m, "AddListener", ctx, arg1) ret0, _ := ret[0].(error) return ret0 } // AddListener indicates an expected call of AddListener. -func (mr *MockManagerMockRecorder) AddListener(arg0, arg1 interface{}) *gomock.Call { +func (mr *MockManagerMockRecorder) AddListener(ctx, arg1 any) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "AddListener", reflect.TypeOf((*MockManager)(nil).AddListener), arg0, arg1) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "AddListener", reflect.TypeOf((*MockManager)(nil).AddListener), ctx, arg1) } // Close mocks base method. -func (m *MockManager) Close(arg0 context.Context) { +func (m *MockManager) Close(ctx context.Context) { m.ctrl.T.Helper() - m.ctrl.Call(m, "Close", arg0) + m.ctrl.Call(m, "Close", ctx) } // Close indicates an expected call of Close. -func (mr *MockManagerMockRecorder) Close(arg0 interface{}) *gomock.Call { +func (mr *MockManagerMockRecorder) Close(ctx any) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Close", reflect.TypeOf((*MockManager)(nil).Close), arg0) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Close", reflect.TypeOf((*MockManager)(nil).Close), ctx) } // GetListener mocks base method. -func (m *MockManager) GetListener(arg0 context.Context, arg1 types.LiveID) (Listener, error) { +func (m *MockManager) GetListener(ctx context.Context, liveId types.LiveID) (Listener, error) { m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "GetListener", arg0, arg1) + ret := m.ctrl.Call(m, "GetListener", ctx, liveId) ret0, _ := ret[0].(Listener) ret1, _ := ret[1].(error) return ret0, ret1 } // GetListener indicates an expected call of GetListener. -func (mr *MockManagerMockRecorder) GetListener(arg0, arg1 interface{}) *gomock.Call { +func (mr *MockManagerMockRecorder) GetListener(ctx, liveId any) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetListener", reflect.TypeOf((*MockManager)(nil).GetListener), arg0, arg1) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetListener", reflect.TypeOf((*MockManager)(nil).GetListener), ctx, liveId) } // HasListener mocks base method. -func (m *MockManager) HasListener(arg0 context.Context, arg1 types.LiveID) bool { +func (m *MockManager) HasListener(ctx context.Context, liveId types.LiveID) bool { m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "HasListener", arg0, arg1) + ret := m.ctrl.Call(m, "HasListener", ctx, liveId) ret0, _ := ret[0].(bool) return ret0 } // HasListener indicates an expected call of HasListener. -func (mr *MockManagerMockRecorder) HasListener(arg0, arg1 interface{}) *gomock.Call { +func (mr *MockManagerMockRecorder) HasListener(ctx, liveId any) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "HasListener", reflect.TypeOf((*MockManager)(nil).HasListener), arg0, arg1) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "HasListener", reflect.TypeOf((*MockManager)(nil).HasListener), ctx, liveId) } // RemoveListener mocks base method. -func (m *MockManager) RemoveListener(arg0 context.Context, arg1 types.LiveID) error { +func (m *MockManager) RemoveListener(ctx context.Context, liveId types.LiveID) error { m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "RemoveListener", arg0, arg1) + ret := m.ctrl.Call(m, "RemoveListener", ctx, liveId) ret0, _ := ret[0].(error) return ret0 } // RemoveListener indicates an expected call of RemoveListener. -func (mr *MockManagerMockRecorder) RemoveListener(arg0, arg1 interface{}) *gomock.Call { +func (mr *MockManagerMockRecorder) RemoveListener(ctx, liveId any) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "RemoveListener", reflect.TypeOf((*MockManager)(nil).RemoveListener), arg0, arg1) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "RemoveListener", reflect.TypeOf((*MockManager)(nil).RemoveListener), ctx, liveId) } // Start mocks base method. -func (m *MockManager) Start(arg0 context.Context) error { +func (m *MockManager) Start(ctx context.Context) error { m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "Start", arg0) + ret := m.ctrl.Call(m, "Start", ctx) ret0, _ := ret[0].(error) return ret0 } // Start indicates an expected call of Start. -func (mr *MockManagerMockRecorder) Start(arg0 interface{}) *gomock.Call { +func (mr *MockManagerMockRecorder) Start(ctx any) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Start", reflect.TypeOf((*MockManager)(nil).Start), arg0) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Start", reflect.TypeOf((*MockManager)(nil).Start), ctx) } diff --git a/src/live/acfun/url.go b/src/live/acfun/url.go index 1cea9cb..7e8b123 100644 --- a/src/live/acfun/url.go +++ b/src/live/acfun/url.go @@ -25,11 +25,11 @@ func (r representations) Swap(i, j int) { r[i], r[j] = r[j], r[i] } -func (r *representations) Push(x interface{}) { +func (r *representations) Push(x any) { *r = append(*r, x.(representation)) } -func (r *representations) Pop() interface{} { +func (r *representations) Pop() any { old := *r n := len(old) item := old[n-1] diff --git a/src/live/douyin/douyin.go b/src/live/douyin/douyin.go index b11ee28..858be0b 100644 --- a/src/live/douyin/douyin.go +++ b/src/live/douyin/douyin.go @@ -80,7 +80,7 @@ func (l *Live) getLiveRoomWebPageResponse() (body string, err error) { l.Url.String(), live.CommonUserAgent, requests.Cookies(cookieKVs), - requests.Headers(map[string]interface{}{ + requests.Headers(map[string]any{ "Cache-Control": "no-cache", }), ) @@ -256,6 +256,8 @@ func (l *Live) getRoomInfoFromBody(body string) (info *live.Info, streamUrlInfos return streamUrlInfos[i].Vbitrate > streamUrlInfos[j].Vbitrate } }) + // TODO: fix inefficient code + //nolint:ineffassign stepNumberForLog++ return @@ -356,7 +358,7 @@ func (l *Live) legacy_getRoomInfo(body string) (*gjson.Result, error) { roomInfoApi, live.CommonUserAgent, requests.Cookies(cookieKVs), - requests.Headers(map[string]interface{}{ + requests.Headers(map[string]any{ "Cache-Control": "no-cache", })) if err != nil { diff --git a/src/live/douyu/douyu.go b/src/live/douyu/douyu.go index 5f40ebc..48647dd 100644 --- a/src/live/douyu/douyu.go +++ b/src/live/douyu/douyu.go @@ -95,7 +95,7 @@ var ( `)) ) -func render(tmpl *template.Template, data interface{}) (string, error) { +func render(tmpl *template.Template, data any) (string, error) { buf := bytes.NewBuffer(nil) if err := tmpl.Execute(buf, data); err != nil { return "", err @@ -190,7 +190,7 @@ func (l *Live) fetchRoomID() error { func (l *Live) GetInfo() (info *live.Info, err error) { if err := l.fetchRoomID(); err != nil { if err.Error() == "房间未开放" { - return nil, errors.New("room not exists, fetchRoomID failed.") + return nil, errors.New("room not exists, fetchRoomID failed") } else if err.Error() == "房间被关闭" { return &live.Info{ Live: l, @@ -208,7 +208,7 @@ func (l *Live) GetInfo() (info *live.Info, err error) { return nil, err } if resp.StatusCode != http.StatusOK { - return nil, errors.New(fmt.Sprintf("GetInfo() failed, response code: %d", resp.StatusCode)) + return nil, fmt.Errorf("GetInfo() failed, response code: %d", resp.StatusCode) } body, err := resp.Bytes() if err != nil { @@ -230,7 +230,7 @@ func (l *Live) getSignParams() (map[string]string, error) { return nil, err } if resp.StatusCode != http.StatusOK { - return nil, errors.New(fmt.Sprintf("getSignParams() failed, response code: %d", resp.StatusCode)) + return nil, fmt.Errorf("getSignParams() failed, response code: %d", resp.StatusCode) } body, err := resp.Bytes() if err != nil { @@ -333,7 +333,7 @@ func (l *Live) GetStreamUrls() (us []*url.URL, err error) { return nil, err } if errorInt := gjson.GetBytes(body, "error").Int(); errorInt != 0 { - return nil, errors.New(fmt.Sprintf("GetStreamUrls() failed, error: %d", errorInt)) + return nil, fmt.Errorf("GetStreamUrls() failed, error: %d", errorInt) } return utils.GenUrls( fmt.Sprintf("%s/%s", diff --git a/src/live/huomao/huomao.go b/src/live/huomao/huomao.go deleted file mode 100644 index 9aed1d3..0000000 --- a/src/live/huomao/huomao.go +++ /dev/null @@ -1,134 +0,0 @@ -package huomao - -import ( - "fmt" - "net/http" - "net/url" - "time" - - "github.com/hr3lxphr6j/requests" - "github.com/tidwall/gjson" - - "github.com/bililive-go/bililive-go/src/live" - "github.com/bililive-go/bililive-go/src/live/internal" - "github.com/bililive-go/bililive-go/src/pkg/utils" -) - -const ( - domain = "www.huomao.com" - cnName = "火猫" - - liveApiUrl = "http://www.huomao.com/swf/live_data" - salt = "6FE26D855E1AEAE090E243EB1AF73685" -) - -func init() { - live.Register(domain, new(builder)) -} - -type builder struct{} - -func (b *builder) Build(url *url.URL) (live.Live, error) { - return &Live{ - BaseLive: internal.NewBaseLive(url), - }, nil -} - -type Live struct { - internal.BaseLive - isDuanbo bool -} - -func (l *Live) GetInfo() (info *live.Info, err error) { - resp, err := requests.Get(l.Url.String(), live.CommonUserAgent) - if err != nil { - return nil, err - } - if resp.StatusCode != http.StatusOK { - return nil, live.ErrRoomNotExist - } - body, err := resp.Text() - if err != nil { - return nil, err - } - l.isDuanbo = utils.Match1(`face_label\s?=\s?(\d*);`, body) == "1" - var ( - hostNameReg = `"nickname":"([^"]*)",` - roomNameReg = `"channel":"([^"]*)"` - statusReg = `"is_live":"?(\d*)"?,` - ) - if l.isDuanbo { - hostNameReg = `live_yz_h_nickName\s?=\s?"([^"]*)";` - roomNameReg = `live_yz_h_channelName\s?=\s?"([^"]*)";` - statusReg = `is_live\s?=\s?"?(\d*)"?;` - } - var ( - hostName = utils.ParseUnicode(utils.Match1(hostNameReg, body)) - roomName = utils.ParseUnicode(utils.Match1(roomNameReg, body)) - status = utils.Match1(statusReg, body) - ) - if hostName == "" || roomName == "" || status == "" { - return nil, live.ErrInternalError - } - info = &live.Info{ - Live: l, - HostName: hostName, - RoomName: roomName, - Status: status == "1", - } - return info, nil -} - -func (l *Live) GetStreamUrls() ([]*url.URL, error) { - resp, err := requests.Get(l.Url.String(), live.CommonUserAgent) - if err != nil { - return nil, err - } - if resp.StatusCode != http.StatusOK { - return nil, live.ErrRoomNotExist - } - body, err := resp.Text() - if err != nil { - return nil, err - } - streamReg := `getFlash\("\d*","([^"]*)","\d*"\);` - if !l.isDuanbo { - streamReg = `"stream":"([^"]*)"` - } - var ( - from = "huomaoh5room" - t = fmt.Sprintf("%d", time.Now().Unix()) - streamID = utils.Match1(streamReg, body) - token = utils.GetMd5String([]byte(fmt.Sprintf("%s%s%s%s", streamID, from, t, salt))) - ) - resp, err = requests.Post(liveApiUrl, live.CommonUserAgent, requests.Queries(map[string]string{ - "VideoIDS": streamID, - "streamtype": "live", - "cdns": "1", - "from": from, - "time": t, - "token": token, - })) - if err != nil { - return nil, err - } - if resp.StatusCode != http.StatusOK { - return nil, live.ErrRoomNotExist - } - body, err = resp.Text() - if err != nil { - return nil, err - } - urls := make([]string, 0, 0) - gjson.Get(body, "streamList.#.list.#.url").ForEach(func(key, value gjson.Result) bool { - for _, u := range value.Array() { - urls = append(urls, u.String()) - } - return true - }) - return utils.GenUrls(urls...) -} - -func (l *Live) GetPlatformCNName() string { - return cnName -} diff --git a/src/live/huya/implForXingXiu.go b/src/live/huya/implForXingXiu.go index 7f733de..c5ea81a 100644 --- a/src/live/huya/implForXingXiu.go +++ b/src/live/huya/implForXingXiu.go @@ -103,7 +103,7 @@ func getJsonFromBody(htmlBody string) (result *gjson.Result, err error) { params["roomid"] = roomId params["showSecret"] = "1" - headers := make(map[string]interface{}) + headers := make(map[string]any) headers["User-Agent"] = uaForXingXiu headers["xweb_xhr"] = "1" headers["referer"] = "https://servicewechat.com/wx74767bf0b684f7d3/301/page-frame.html" diff --git a/src/live/lives.go b/src/live/lives.go index a21c709..3756aff 100755 --- a/src/live/lives.go +++ b/src/live/lives.go @@ -10,9 +10,9 @@ import ( "strings" "time" - "github.com/bluele/gcache" "github.com/bililive-go/bililive-go/src/configs" "github.com/bililive-go/bililive-go/src/types" + "github.com/bluele/gcache" ) var ( diff --git a/src/live/longzhu/longzhu.go b/src/live/longzhu/longzhu.go deleted file mode 100644 index 71f865f..0000000 --- a/src/live/longzhu/longzhu.go +++ /dev/null @@ -1,129 +0,0 @@ -package longzhu - -import ( - "fmt" - "net/http" - "net/url" - "strings" - - "github.com/hr3lxphr6j/requests" - "github.com/tidwall/gjson" - - "github.com/bililive-go/bililive-go/src/live" - "github.com/bililive-go/bililive-go/src/live/internal" - "github.com/bililive-go/bililive-go/src/pkg/utils" -) - -const ( - domain = "star.longzhu.com" - cnName = "龙珠" - - mobileUrl = "http://m.longzhu.com/" - roomApiUrl = "http://roomapicdn.longzhu.com/room/roomstatus" - liveApiUrl = "https://livestream.longzhu.com/live/getlivePlayurl" -) - -func init() { - live.Register(domain, new(builder)) -} - -type builder struct{} - -func (b *builder) Build(url *url.URL) (live.Live, error) { - return &Live{ - BaseLive: internal.NewBaseLive(url), - }, nil -} - -type Live struct { - internal.BaseLive - realId string -} - -func (l *Live) parseRealId() error { - paths := strings.Split(l.Url.Path, "/") - if len(paths) < 2 { - return live.ErrRoomUrlIncorrect - } - resp, err := requests.Get(fmt.Sprintf("%s%s", mobileUrl, paths[1]), live.CommonUserAgent) - if err != nil { - return err - } - if resp.StatusCode != http.StatusOK { - return live.ErrRoomNotExist - } - body, err := resp.Text() - if err != nil { - return err - } - if l.realId = utils.Match1(`var\s*roomId\s*=\s*(\d+);`, body); l.realId == "" { - return live.ErrRoomNotExist - } - return nil -} - -func (l *Live) GetInfo() (info *live.Info, err error) { - if l.realId == "" { - if err := l.parseRealId(); err != nil { - return nil, err - } - } - resp, err := requests.Get(l.Url.String(), live.CommonUserAgent) - if err != nil { - return nil, err - } - if resp.StatusCode != http.StatusOK { - return nil, live.ErrRoomNotExist - } - dom, err := resp.Text() - if err != nil { - return nil, err - } - hostname := utils.Match1(`"username":"(.*?)"`, dom) - - resp, err = requests.Get(roomApiUrl, requests.Query("roomId", l.realId), live.CommonUserAgent) - if err != nil { - return nil, err - } - if resp.StatusCode != http.StatusOK { - return nil, live.ErrRoomNotExist - } - body, err := resp.Bytes() - if err != nil { - return nil, err - } - info = &live.Info{ - Live: l, - HostName: hostname, - RoomName: gjson.GetBytes(body, "Broadcast.Title").String(), - Status: gjson.GetBytes(body, "Broadcast.LiveType").Int() > 0, - } - return info, nil - -} - -func (l *Live) GetStreamUrls() (us []*url.URL, err error) { - if l.realId == "" { - if err := l.parseRealId(); err != nil { - return nil, err - } - } - resp, err := requests.Get(liveApiUrl, live.CommonUserAgent, requests.Query("roomId", l.realId)) - if err != nil { - return nil, err - } - if resp.StatusCode != http.StatusOK { - return nil, live.ErrRoomNotExist - } - body, err := resp.Bytes() - urls := make([]string, 0, 0) - gjson.GetBytes(body, "playLines.0.urls.#.securityUrl").ForEach(func(key, value gjson.Result) bool { - urls = append(urls, value.String()) - return true - }) - return utils.GenUrls(urls...) -} - -func (l *Live) GetPlatformCNName() string { - return cnName -} diff --git a/src/live/mock/mock.go b/src/live/mock/mock.go index 50ae0a3..4972919 100644 --- a/src/live/mock/mock.go +++ b/src/live/mock/mock.go @@ -1,5 +1,10 @@ // Code generated by MockGen. DO NOT EDIT. // Source: github.com/bililive-go/bililive-go/src/live (interfaces: Live) +// +// Generated by this command: +// +// mockgen -package mock -destination mock/mock.go github.com/bililive-go/bililive-go/src/live Live +// // Package mock is a generated GoMock package. package mock @@ -10,16 +15,17 @@ import ( reflect "reflect" time "time" - gomock "github.com/golang/mock/gomock" configs "github.com/bililive-go/bililive-go/src/configs" live "github.com/bililive-go/bililive-go/src/live" types "github.com/bililive-go/bililive-go/src/types" + gomock "go.uber.org/mock/gomock" ) // MockLive is a mock of Live interface. type MockLive struct { ctrl *gomock.Controller recorder *MockLiveMockRecorder + isgomock struct{} } // MockLiveMockRecorder is the mock recorder for MockLive. @@ -147,7 +153,7 @@ func (m *MockLive) SetLastStartTime(arg0 time.Time) { } // SetLastStartTime indicates an expected call of SetLastStartTime. -func (mr *MockLiveMockRecorder) SetLastStartTime(arg0 interface{}) *gomock.Call { +func (mr *MockLiveMockRecorder) SetLastStartTime(arg0 any) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SetLastStartTime", reflect.TypeOf((*MockLive)(nil).SetLastStartTime), arg0) } @@ -159,7 +165,7 @@ func (m *MockLive) SetLiveIdByString(arg0 string) { } // SetLiveIdByString indicates an expected call of SetLiveIdByString. -func (mr *MockLiveMockRecorder) SetLiveIdByString(arg0 interface{}) *gomock.Call { +func (mr *MockLiveMockRecorder) SetLiveIdByString(arg0 any) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SetLiveIdByString", reflect.TypeOf((*MockLive)(nil).SetLiveIdByString), arg0) } @@ -173,7 +179,7 @@ func (m *MockLive) UpdateLiveOptionsbyConfig(arg0 context.Context, arg1 *configs } // UpdateLiveOptionsbyConfig indicates an expected call of UpdateLiveOptionsbyConfig. -func (mr *MockLiveMockRecorder) UpdateLiveOptionsbyConfig(arg0, arg1 interface{}) *gomock.Call { +func (mr *MockLiveMockRecorder) UpdateLiveOptionsbyConfig(arg0, arg1 any) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "UpdateLiveOptionsbyConfig", reflect.TypeOf((*MockLive)(nil).UpdateLiveOptionsbyConfig), arg0, arg1) } diff --git a/src/live/system/initializing_live.go b/src/live/system/initializing_live.go index 5f2eed5..43e257a 100644 --- a/src/live/system/initializing_live.go +++ b/src/live/system/initializing_live.go @@ -1,48 +1,48 @@ -package system - -import ( - "net/url" - - "github.com/bililive-go/bililive-go/src/live" - "github.com/bililive-go/bililive-go/src/live/internal" -) - -func init() { - live.InitializingLiveBuilderInstance = new(builder) -} - -type builder struct{} - -func (b *builder) Build(live live.Live, url *url.URL) (live.Live, error) { - return &InitializingLive{ - BaseLive: internal.NewBaseLive(url), - OriginalLive: live, - }, nil -} - -type InitializingLive struct { - internal.BaseLive - OriginalLive live.Live -} - -func (l *InitializingLive) GetInfo() (info *live.Info, err error) { - err = nil - info = &live.Info{ - Live: l, - HostName: "", - RoomName: l.GetRawUrl(), - Status: false, - Initializing: true, - } - return -} - -func (l *InitializingLive) GetStreamUrls() (us []*url.URL, err error) { - us = make([]*url.URL, 0) - err = nil - return -} - -func (l *InitializingLive) GetPlatformCNName() string { - return "" -} +package system + +import ( + "net/url" + + "github.com/bililive-go/bililive-go/src/live" + "github.com/bililive-go/bililive-go/src/live/internal" +) + +func init() { + live.InitializingLiveBuilderInstance = new(builder) +} + +type builder struct{} + +func (b *builder) Build(live live.Live, url *url.URL) (live.Live, error) { + return &InitializingLive{ + BaseLive: internal.NewBaseLive(url), + OriginalLive: live, + }, nil +} + +type InitializingLive struct { + internal.BaseLive + OriginalLive live.Live +} + +func (l *InitializingLive) GetInfo() (info *live.Info, err error) { + err = nil + info = &live.Info{ + Live: l, + HostName: "", + RoomName: l.GetRawUrl(), + Status: false, + Initializing: true, + } + return +} + +func (l *InitializingLive) GetStreamUrls() (us []*url.URL, err error) { + us = make([]*url.URL, 0) + err = nil + return +} + +func (l *InitializingLive) GetPlatformCNName() string { + return "" +} diff --git a/src/live/twitch/twitch.go b/src/live/twitch/twitch.go index 9443029..383b644 100644 --- a/src/live/twitch/twitch.go +++ b/src/live/twitch/twitch.go @@ -40,8 +40,6 @@ func (b *builder) Build(url *url.URL) (live.Live, error) { }, nil } -var headers = map[string]string{"client-id": clientId} - type Live struct { internal.BaseLive userId, hostName, roomName string diff --git a/src/live/weibolive/weibolive.go b/src/live/weibolive/weibolive.go index 263c174..93983dd 100644 --- a/src/live/weibolive/weibolive.go +++ b/src/live/weibolive/weibolive.go @@ -49,7 +49,7 @@ func (l *Live) getRoomInfo() ([]byte, error) { resp, err := requests.Get(liveurl+roomid, live.CommonUserAgent, - requests.Headers(map[string]interface{}{ + requests.Headers(map[string]any{ "Referer": l.Url, })) if err != nil { @@ -95,7 +95,7 @@ func (l *Live) GetStreamUrls() (us []*url.URL, err error) { if err == nil && reg.MatchString(streamurl) { streamurl = reg.ReplaceAllString(streamurl, targetQuality) } else { - streamurl = strings.Replace(streamurl, ".flv", targetQuality, -1) + streamurl = strings.ReplaceAll(streamurl, ".flv", targetQuality) } fmt.Println("weibo stream quality fixed: " + streamurl) } diff --git a/src/live/xiaohongshu/xiaohongshu.go b/src/live/xiaohongshu/xiaohongshu.go index bc149bd..cdd38a6 100644 --- a/src/live/xiaohongshu/xiaohongshu.go +++ b/src/live/xiaohongshu/xiaohongshu.go @@ -49,7 +49,7 @@ func (l *Live) GetInfo() (info *live.Info, err error) { pathParts := strings.Split(l.Url.Path, "/") roomId := pathParts[len(pathParts)-1] - headers := map[string]interface{}{ + headers := map[string]any{ "User-Agent": userAgent, "Accept": "application/json, text/plain, */*", "Accept-Language": "zh-CN,zh;q=0.8,zh-TW;q=0.7,zh-HK;q=0.5,en-US;q=0.3,en;q=0.2", diff --git a/src/live/yy/yy.go b/src/live/yy/yy.go index 5e60a47..e31a534 100644 --- a/src/live/yy/yy.go +++ b/src/live/yy/yy.go @@ -141,6 +141,9 @@ func (l *Live) getRoomInfo() ([]byte, bool, error) { return nil, false, live.ErrRoomNotExist } body, err = resp.Bytes() + if err != nil { + return nil, false, err + } return body, false, nil } diff --git a/src/metrics/metrics.go b/src/metrics/metrics.go index a14656e..3c0ae40 100644 --- a/src/metrics/metrics.go +++ b/src/metrics/metrics.go @@ -74,7 +74,7 @@ func (c collector) Collect(ch chan<- prometheus.Metric) { if info.Status && listening { ch <- prometheus.MustNewConstMetric( - liveDurationSeconds, prometheus.CounterValue, time.Now().Sub(l.GetLastStartTime()).Seconds(), + liveDurationSeconds, prometheus.CounterValue, time.Since(l.GetLastStartTime()).Seconds(), string(id), l.GetRawUrl(), info.HostName, info.RoomName, strconv.FormatInt(info.Live.GetLastStartTime().Unix(), 10), ) diff --git a/src/pkg/events/event.go b/src/pkg/events/event.go index d60f99b..961b705 100644 --- a/src/pkg/events/event.go +++ b/src/pkg/events/event.go @@ -6,10 +6,10 @@ type EventHandler func(event *Event) type Event struct { Type EventType - Object interface{} + Object any } -func NewEvent(eventType EventType, object interface{}) *Event { +func NewEvent(eventType EventType, object any) *Event { return &Event{eventType, object} } diff --git a/src/pkg/events/mock/mock.go b/src/pkg/events/mock/mock.go index dc02b9d..0947632 100644 --- a/src/pkg/events/mock/mock.go +++ b/src/pkg/events/mock/mock.go @@ -1,5 +1,10 @@ // Code generated by MockGen. DO NOT EDIT. // Source: github.com/bililive-go/bililive-go/src/pkg/events (interfaces: Dispatcher) +// +// Generated by this command: +// +// mockgen -package mock -destination mock/mock.go github.com/bililive-go/bililive-go/src/pkg/events Dispatcher +// // Package mock is a generated GoMock package. package mock @@ -8,14 +13,15 @@ import ( context "context" reflect "reflect" - gomock "github.com/golang/mock/gomock" events "github.com/bililive-go/bililive-go/src/pkg/events" + gomock "go.uber.org/mock/gomock" ) // MockDispatcher is a mock of Dispatcher interface. type MockDispatcher struct { ctrl *gomock.Controller recorder *MockDispatcherMockRecorder + isgomock struct{} } // MockDispatcherMockRecorder is the mock recorder for MockDispatcher. @@ -36,75 +42,75 @@ func (m *MockDispatcher) EXPECT() *MockDispatcherMockRecorder { } // AddEventListener mocks base method. -func (m *MockDispatcher) AddEventListener(arg0 events.EventType, arg1 *events.EventListener) { +func (m *MockDispatcher) AddEventListener(eventType events.EventType, listener *events.EventListener) { m.ctrl.T.Helper() - m.ctrl.Call(m, "AddEventListener", arg0, arg1) + m.ctrl.Call(m, "AddEventListener", eventType, listener) } // AddEventListener indicates an expected call of AddEventListener. -func (mr *MockDispatcherMockRecorder) AddEventListener(arg0, arg1 interface{}) *gomock.Call { +func (mr *MockDispatcherMockRecorder) AddEventListener(eventType, listener any) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "AddEventListener", reflect.TypeOf((*MockDispatcher)(nil).AddEventListener), arg0, arg1) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "AddEventListener", reflect.TypeOf((*MockDispatcher)(nil).AddEventListener), eventType, listener) } // Close mocks base method. -func (m *MockDispatcher) Close(arg0 context.Context) { +func (m *MockDispatcher) Close(ctx context.Context) { m.ctrl.T.Helper() - m.ctrl.Call(m, "Close", arg0) + m.ctrl.Call(m, "Close", ctx) } // Close indicates an expected call of Close. -func (mr *MockDispatcherMockRecorder) Close(arg0 interface{}) *gomock.Call { +func (mr *MockDispatcherMockRecorder) Close(ctx any) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Close", reflect.TypeOf((*MockDispatcher)(nil).Close), arg0) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Close", reflect.TypeOf((*MockDispatcher)(nil).Close), ctx) } // DispatchEvent mocks base method. -func (m *MockDispatcher) DispatchEvent(arg0 *events.Event) { +func (m *MockDispatcher) DispatchEvent(event *events.Event) { m.ctrl.T.Helper() - m.ctrl.Call(m, "DispatchEvent", arg0) + m.ctrl.Call(m, "DispatchEvent", event) } // DispatchEvent indicates an expected call of DispatchEvent. -func (mr *MockDispatcherMockRecorder) DispatchEvent(arg0 interface{}) *gomock.Call { +func (mr *MockDispatcherMockRecorder) DispatchEvent(event any) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "DispatchEvent", reflect.TypeOf((*MockDispatcher)(nil).DispatchEvent), arg0) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "DispatchEvent", reflect.TypeOf((*MockDispatcher)(nil).DispatchEvent), event) } // RemoveAllEventListener mocks base method. -func (m *MockDispatcher) RemoveAllEventListener(arg0 events.EventType) { +func (m *MockDispatcher) RemoveAllEventListener(eventType events.EventType) { m.ctrl.T.Helper() - m.ctrl.Call(m, "RemoveAllEventListener", arg0) + m.ctrl.Call(m, "RemoveAllEventListener", eventType) } // RemoveAllEventListener indicates an expected call of RemoveAllEventListener. -func (mr *MockDispatcherMockRecorder) RemoveAllEventListener(arg0 interface{}) *gomock.Call { +func (mr *MockDispatcherMockRecorder) RemoveAllEventListener(eventType any) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "RemoveAllEventListener", reflect.TypeOf((*MockDispatcher)(nil).RemoveAllEventListener), arg0) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "RemoveAllEventListener", reflect.TypeOf((*MockDispatcher)(nil).RemoveAllEventListener), eventType) } // RemoveEventListener mocks base method. -func (m *MockDispatcher) RemoveEventListener(arg0 events.EventType, arg1 *events.EventListener) { +func (m *MockDispatcher) RemoveEventListener(eventType events.EventType, listener *events.EventListener) { m.ctrl.T.Helper() - m.ctrl.Call(m, "RemoveEventListener", arg0, arg1) + m.ctrl.Call(m, "RemoveEventListener", eventType, listener) } // RemoveEventListener indicates an expected call of RemoveEventListener. -func (mr *MockDispatcherMockRecorder) RemoveEventListener(arg0, arg1 interface{}) *gomock.Call { +func (mr *MockDispatcherMockRecorder) RemoveEventListener(eventType, listener any) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "RemoveEventListener", reflect.TypeOf((*MockDispatcher)(nil).RemoveEventListener), arg0, arg1) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "RemoveEventListener", reflect.TypeOf((*MockDispatcher)(nil).RemoveEventListener), eventType, listener) } // Start mocks base method. -func (m *MockDispatcher) Start(arg0 context.Context) error { +func (m *MockDispatcher) Start(ctx context.Context) error { m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "Start", arg0) + ret := m.ctrl.Call(m, "Start", ctx) ret0, _ := ret[0].(error) return ret0 } // Start indicates an expected call of Start. -func (mr *MockDispatcherMockRecorder) Start(arg0 interface{}) *gomock.Call { +func (mr *MockDispatcherMockRecorder) Start(ctx any) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Start", reflect.TypeOf((*MockDispatcher)(nil).Start), arg0) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Start", reflect.TypeOf((*MockDispatcher)(nil).Start), ctx) } diff --git a/src/pkg/parser/mock/mock.go b/src/pkg/parser/mock/mock.go index 6c538bc..1636c4c 100644 --- a/src/pkg/parser/mock/mock.go +++ b/src/pkg/parser/mock/mock.go @@ -1,5 +1,10 @@ // Code generated by MockGen. DO NOT EDIT. // Source: github.com/bililive-go/bililive-go/src/pkg/parser (interfaces: Parser) +// +// Generated by this command: +// +// mockgen -package mock -destination mock/mock.go github.com/bililive-go/bililive-go/src/pkg/parser Parser +// // Package mock is a generated GoMock package. package mock @@ -8,14 +13,15 @@ import ( context "context" reflect "reflect" - gomock "github.com/golang/mock/gomock" live "github.com/bililive-go/bililive-go/src/live" + gomock "go.uber.org/mock/gomock" ) // MockParser is a mock of Parser interface. type MockParser struct { ctrl *gomock.Controller recorder *MockParserMockRecorder + isgomock struct{} } // MockParserMockRecorder is the mock recorder for MockParser. @@ -36,17 +42,17 @@ func (m *MockParser) EXPECT() *MockParserMockRecorder { } // ParseLiveStream mocks base method. -func (m *MockParser) ParseLiveStream(arg0 context.Context, arg1 *live.StreamUrlInfo, arg2 live.Live, arg3 string) error { +func (m *MockParser) ParseLiveStream(ctx context.Context, streamUrlInfo *live.StreamUrlInfo, arg2 live.Live, file string) error { m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "ParseLiveStream", arg0, arg1, arg2, arg3) + ret := m.ctrl.Call(m, "ParseLiveStream", ctx, streamUrlInfo, arg2, file) ret0, _ := ret[0].(error) return ret0 } // ParseLiveStream indicates an expected call of ParseLiveStream. -func (mr *MockParserMockRecorder) ParseLiveStream(arg0, arg1, arg2, arg3 interface{}) *gomock.Call { +func (mr *MockParserMockRecorder) ParseLiveStream(ctx, streamUrlInfo, arg2, file any) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ParseLiveStream", reflect.TypeOf((*MockParser)(nil).ParseLiveStream), arg0, arg1, arg2, arg3) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ParseLiveStream", reflect.TypeOf((*MockParser)(nil).ParseLiveStream), ctx, streamUrlInfo, arg2, file) } // Stop mocks base method. diff --git a/src/pkg/reader/reader.go b/src/pkg/reader/reader.go index 9db0357..6e3327c 100644 --- a/src/pkg/reader/reader.go +++ b/src/pkg/reader/reader.go @@ -13,7 +13,7 @@ const ( var ( ErrOutOfBuffer = errors.New("n is bigger than len of buffer") - pool = sync.Pool{New: func() interface{} { return make([]byte, defaultBufferSize) }} + pool = sync.Pool{New: func() any { return make([]byte, defaultBufferSize) }} ) type BufferedReader struct { @@ -76,6 +76,7 @@ func (b *BufferedReader) LastBytes() []byte { func (b *BufferedReader) Free() { b.Reset() + //nolint:staticcheck pool.Put(b.buf) b.buf = nil } diff --git a/src/pkg/utils/functions.go b/src/pkg/utils/functions.go index 2d47fed..67553c2 100644 --- a/src/pkg/utils/functions.go +++ b/src/pkg/utils/functions.go @@ -7,7 +7,7 @@ import ( "github.com/bililive-go/bililive-go/src/configs" ) -func getFunctionList(config *configs.Config) map[string]interface{} { +func getFunctionList(config *configs.Config) map[string]any { filenameFilters := []StringFilter{ UnescapeHTMLEntity, ReplaceIllegalChar, @@ -15,7 +15,7 @@ func getFunctionList(config *configs.Config) map[string]interface{} { if config.Feature.RemoveSymbolOtherCharacter { filenameFilters = append(filenameFilters, RemoveSymbolOtherChar) } - return map[string]interface{}{ + return map[string]any{ "decodeUnicode": ParseUnicode, "replaceIllegalChar": ReplaceIllegalChar, "unescapeHTMLEntity": UnescapeHTMLEntity, diff --git a/src/pkg/utils/strings.go b/src/pkg/utils/strings.go index 39126e6..56cd2c8 100644 --- a/src/pkg/utils/strings.go +++ b/src/pkg/utils/strings.go @@ -45,7 +45,7 @@ var ParseUnicode = StringFilterFunc(func(str string) string { for i := 0; i < len(str); { if chars[i] == 92 && chars[i+1] == 117 { t, _ := strconv.ParseInt(string(chars[i+2:i+6]), 16, 32) - buf.WriteString(fmt.Sprintf("%c", t)) + fmt.Fprintf(buf, "%c", t) i += 6 } else { buf.WriteByte(chars[i]) diff --git a/src/pkg/utils/utils.go b/src/pkg/utils/utils.go index bd19ed7..e433ad3 100644 --- a/src/pkg/utils/utils.go +++ b/src/pkg/utils/utils.go @@ -79,7 +79,7 @@ func Match1(re, str string) string { return "" } match := reg.FindStringSubmatch(str) - if match == nil || len(match) < 2 { + if len(match) < 2 { return "" } return match[1] diff --git a/src/recorders/event.go b/src/recorders/event.go index 34fbd55..346b953 100644 --- a/src/recorders/event.go +++ b/src/recorders/event.go @@ -3,7 +3,7 @@ package recorders import "github.com/bililive-go/bililive-go/src/pkg/events" const ( - RecorderStart events.EventType = "RecorderStart" - RecorderStop events.EventType = "RecorderStop" - RecorderRestart events.EventType = "RecorderRestart" + RecorderStart events.EventType = "RecorderStart" + RecorderStop events.EventType = "RecorderStop" + RecorderRestart events.EventType = "RecorderRestart" ) diff --git a/src/recorders/manager.go b/src/recorders/manager.go index 5a111ba..a083875 100644 --- a/src/recorders/manager.go +++ b/src/recorders/manager.go @@ -118,7 +118,7 @@ func (m *manager) cronRestart(ctx context.Context, live live.Live) { if err != nil { return } - if time.Now().Sub(recorder.StartTime()) < m.cfg.VideoSplitStrategies.MaxDuration { + if time.Since(recorder.StartTime()) < m.cfg.VideoSplitStrategies.MaxDuration { time.AfterFunc(time.Minute/4, func() { m.cronRestart(ctx, live) }) diff --git a/src/recorders/manager_test.go b/src/recorders/manager_test.go index 541f1f6..01cb4c5 100644 --- a/src/recorders/manager_test.go +++ b/src/recorders/manager_test.go @@ -4,8 +4,8 @@ import ( "context" "testing" - "github.com/golang/mock/gomock" "github.com/stretchr/testify/assert" + gomock "go.uber.org/mock/gomock" "github.com/bililive-go/bililive-go/src/configs" "github.com/bililive-go/bililive-go/src/instance" diff --git a/src/recorders/mock_test.go b/src/recorders/mock_test.go index 8551bc4..79e7764 100644 --- a/src/recorders/mock_test.go +++ b/src/recorders/mock_test.go @@ -1,5 +1,10 @@ // Code generated by MockGen. DO NOT EDIT. // Source: github.com/bililive-go/bililive-go/src/recorders (interfaces: Recorder,Manager) +// +// Generated by this command: +// +// mockgen -package recorders -destination mock_test.go github.com/bililive-go/bililive-go/src/recorders Recorder,Manager +// // Package recorders is a generated GoMock package. package recorders @@ -9,15 +14,16 @@ import ( reflect "reflect" time "time" - gomock "github.com/golang/mock/gomock" live "github.com/bililive-go/bililive-go/src/live" types "github.com/bililive-go/bililive-go/src/types" + gomock "go.uber.org/mock/gomock" ) // MockRecorder is a mock of Recorder interface. type MockRecorder struct { ctrl *gomock.Controller recorder *MockRecorderMockRecorder + isgomock struct{} } // MockRecorderMockRecorder is the mock recorder for MockRecorder. @@ -65,17 +71,17 @@ func (mr *MockRecorderMockRecorder) GetStatus() *gomock.Call { } // Start mocks base method. -func (m *MockRecorder) Start(arg0 context.Context) error { +func (m *MockRecorder) Start(ctx context.Context) error { m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "Start", arg0) + ret := m.ctrl.Call(m, "Start", ctx) ret0, _ := ret[0].(error) return ret0 } // Start indicates an expected call of Start. -func (mr *MockRecorderMockRecorder) Start(arg0 interface{}) *gomock.Call { +func (mr *MockRecorderMockRecorder) Start(ctx any) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Start", reflect.TypeOf((*MockRecorder)(nil).Start), arg0) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Start", reflect.TypeOf((*MockRecorder)(nil).Start), ctx) } // StartTime mocks base method. @@ -96,6 +102,7 @@ func (mr *MockRecorderMockRecorder) StartTime() *gomock.Call { type MockManager struct { ctrl *gomock.Controller recorder *MockManagerMockRecorder + isgomock struct{} } // MockManagerMockRecorder is the mock recorder for MockManager. @@ -116,98 +123,98 @@ func (m *MockManager) EXPECT() *MockManagerMockRecorder { } // AddRecorder mocks base method. -func (m *MockManager) AddRecorder(arg0 context.Context, arg1 live.Live) error { +func (m *MockManager) AddRecorder(ctx context.Context, arg1 live.Live) error { m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "AddRecorder", arg0, arg1) + ret := m.ctrl.Call(m, "AddRecorder", ctx, arg1) ret0, _ := ret[0].(error) return ret0 } // AddRecorder indicates an expected call of AddRecorder. -func (mr *MockManagerMockRecorder) AddRecorder(arg0, arg1 interface{}) *gomock.Call { +func (mr *MockManagerMockRecorder) AddRecorder(ctx, arg1 any) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "AddRecorder", reflect.TypeOf((*MockManager)(nil).AddRecorder), arg0, arg1) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "AddRecorder", reflect.TypeOf((*MockManager)(nil).AddRecorder), ctx, arg1) } // Close mocks base method. -func (m *MockManager) Close(arg0 context.Context) { +func (m *MockManager) Close(ctx context.Context) { m.ctrl.T.Helper() - m.ctrl.Call(m, "Close", arg0) + m.ctrl.Call(m, "Close", ctx) } // Close indicates an expected call of Close. -func (mr *MockManagerMockRecorder) Close(arg0 interface{}) *gomock.Call { +func (mr *MockManagerMockRecorder) Close(ctx any) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Close", reflect.TypeOf((*MockManager)(nil).Close), arg0) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Close", reflect.TypeOf((*MockManager)(nil).Close), ctx) } // GetRecorder mocks base method. -func (m *MockManager) GetRecorder(arg0 context.Context, arg1 types.LiveID) (Recorder, error) { +func (m *MockManager) GetRecorder(ctx context.Context, liveId types.LiveID) (Recorder, error) { m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "GetRecorder", arg0, arg1) + ret := m.ctrl.Call(m, "GetRecorder", ctx, liveId) ret0, _ := ret[0].(Recorder) ret1, _ := ret[1].(error) return ret0, ret1 } // GetRecorder indicates an expected call of GetRecorder. -func (mr *MockManagerMockRecorder) GetRecorder(arg0, arg1 interface{}) *gomock.Call { +func (mr *MockManagerMockRecorder) GetRecorder(ctx, liveId any) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetRecorder", reflect.TypeOf((*MockManager)(nil).GetRecorder), arg0, arg1) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetRecorder", reflect.TypeOf((*MockManager)(nil).GetRecorder), ctx, liveId) } // HasRecorder mocks base method. -func (m *MockManager) HasRecorder(arg0 context.Context, arg1 types.LiveID) bool { +func (m *MockManager) HasRecorder(ctx context.Context, liveId types.LiveID) bool { m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "HasRecorder", arg0, arg1) + ret := m.ctrl.Call(m, "HasRecorder", ctx, liveId) ret0, _ := ret[0].(bool) return ret0 } // HasRecorder indicates an expected call of HasRecorder. -func (mr *MockManagerMockRecorder) HasRecorder(arg0, arg1 interface{}) *gomock.Call { +func (mr *MockManagerMockRecorder) HasRecorder(ctx, liveId any) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "HasRecorder", reflect.TypeOf((*MockManager)(nil).HasRecorder), arg0, arg1) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "HasRecorder", reflect.TypeOf((*MockManager)(nil).HasRecorder), ctx, liveId) } // RemoveRecorder mocks base method. -func (m *MockManager) RemoveRecorder(arg0 context.Context, arg1 types.LiveID) error { +func (m *MockManager) RemoveRecorder(ctx context.Context, liveId types.LiveID) error { m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "RemoveRecorder", arg0, arg1) + ret := m.ctrl.Call(m, "RemoveRecorder", ctx, liveId) ret0, _ := ret[0].(error) return ret0 } // RemoveRecorder indicates an expected call of RemoveRecorder. -func (mr *MockManagerMockRecorder) RemoveRecorder(arg0, arg1 interface{}) *gomock.Call { +func (mr *MockManagerMockRecorder) RemoveRecorder(ctx, liveId any) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "RemoveRecorder", reflect.TypeOf((*MockManager)(nil).RemoveRecorder), arg0, arg1) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "RemoveRecorder", reflect.TypeOf((*MockManager)(nil).RemoveRecorder), ctx, liveId) } // RestartRecorder mocks base method. -func (m *MockManager) RestartRecorder(arg0 context.Context, arg1 live.Live) error { +func (m *MockManager) RestartRecorder(ctx context.Context, liveId live.Live) error { m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "RestartRecorder", arg0, arg1) + ret := m.ctrl.Call(m, "RestartRecorder", ctx, liveId) ret0, _ := ret[0].(error) return ret0 } // RestartRecorder indicates an expected call of RestartRecorder. -func (mr *MockManagerMockRecorder) RestartRecorder(arg0, arg1 interface{}) *gomock.Call { +func (mr *MockManagerMockRecorder) RestartRecorder(ctx, liveId any) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "RestartRecorder", reflect.TypeOf((*MockManager)(nil).RestartRecorder), arg0, arg1) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "RestartRecorder", reflect.TypeOf((*MockManager)(nil).RestartRecorder), ctx, liveId) } // Start mocks base method. -func (m *MockManager) Start(arg0 context.Context) error { +func (m *MockManager) Start(ctx context.Context) error { m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "Start", arg0) + ret := m.ctrl.Call(m, "Start", ctx) ret0, _ := ret[0].(error) return ret0 } // Start indicates an expected call of Start. -func (mr *MockManagerMockRecorder) Start(arg0 interface{}) *gomock.Call { +func (mr *MockManagerMockRecorder) Start(ctx any) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Start", reflect.TypeOf((*MockManager)(nil).Start), arg0) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Start", reflect.TypeOf((*MockManager)(nil).Start), ctx) } diff --git a/src/recorders/recorder.go b/src/recorders/recorder.go index e4cb715..5f8acaf 100644 --- a/src/recorders/recorder.go +++ b/src/recorders/recorder.go @@ -108,6 +108,8 @@ func (r *recorder) tryRecord(ctx context.Context) { var err error if streamInfos, err = r.Live.GetStreamInfos(); err == live.ErrNotImplemented { var urls []*url.URL + // TODO: remove deprecated method GetStreamUrls + //nolint:staticcheck if urls, err = r.Live.GetStreamUrls(); err == live.ErrNotImplemented { panic("GetStreamInfos and GetStreamUrls are not implemented for " + r.Live.GetPlatformCNName()) } else if err == nil { @@ -305,13 +307,13 @@ func (r *recorder) getLogger() *logrus.Entry { return r.logger.WithFields(r.getFields()) } -func (r *recorder) getFields() map[string]interface{} { +func (r *recorder) getFields() map[string]any { obj, err := r.cache.Get(r.Live) if err != nil { return nil } info := obj.(*live.Info) - return map[string]interface{}{ + return map[string]any{ "host": info.HostName, "room": info.RoomName, } diff --git a/src/servers/handler.go b/src/servers/handler.go index 4a4b758..eb4654c 100644 --- a/src/servers/handler.go +++ b/src/servers/handler.go @@ -5,9 +5,10 @@ import ( "encoding/json" "errors" "fmt" - "io/ioutil" + "io" "net/http" "net/url" + "os" "path/filepath" "regexp" "sort" @@ -133,9 +134,9 @@ func stopListening(ctx context.Context, liveId types.LiveID) error { ] */ func addLives(writer http.ResponseWriter, r *http.Request) { - b, err := ioutil.ReadAll(r.Body) + b, err := io.ReadAll(r.Body) if err != nil { - writeJSON(writer, map[string]interface{}{ + writeJSON(writer, map[string]any{ "error": err.Error(), }) return @@ -261,7 +262,7 @@ func getRawConfig(writer http.ResponseWriter, r *http.Request) { } func putRawConfig(writer http.ResponseWriter, r *http.Request) { - b, err := ioutil.ReadAll(r.Body) + b, err := io.ReadAll(r.Body) if err != nil { writeJsonWithStatusCode(writer, http.StatusBadRequest, commonResp{ ErrNo: http.StatusBadRequest, @@ -271,7 +272,7 @@ func putRawConfig(writer http.ResponseWriter, r *http.Request) { } ctx := r.Context() inst := instance.GetInstance(ctx) - var jsonBody map[string]interface{} + var jsonBody map[string]any json.Unmarshal(b, &jsonBody) newConfig, err := configs.NewConfigWithBytes([]byte(jsonBody["config"].(string))) if err != nil { @@ -286,7 +287,7 @@ func putRawConfig(writer http.ResponseWriter, r *http.Request) { inst.Config = newConfig newConfig.File = oldConfig.File if err := applyLiveRoomsByConfig(ctx, oldConfig); err != nil { - writeJSON(writer, map[string]interface{}{ + writeJSON(writer, map[string]any{ "error": err.Error(), }) return @@ -313,7 +314,7 @@ func applyLiveRoomsByConfig(ctx context.Context, oldConfig *configs.Config) erro } else { live, ok := inst.Lives[types.LiveID(room.LiveId)] if !ok { - return errors.New(fmt.Sprintf("live id: %s can not find", room.LiveId)) + return fmt.Errorf("live id: %s can not find", room.LiveId) } live.UpdateLiveOptionsbyConfig(ctx, &newRoom) if room.IsListening != newRoom.IsListening { @@ -338,7 +339,7 @@ func applyLiveRoomsByConfig(ctx context.Context, oldConfig *configs.Config) erro // remove live live, ok := inst.Lives[types.LiveID(room.LiveId)] if !ok { - return errors.New(fmt.Sprintf("live id: %s can not find", room.LiveId)) + return fmt.Errorf("live id: %s can not find", room.LiveId) } removeLiveImpl(ctx, live) } @@ -377,7 +378,7 @@ func getFileInfo(writer http.ResponseWriter, r *http.Request) { return } - files, err := ioutil.ReadDir(absPath) + files, err := os.ReadDir(absPath) if err != nil { writeJSON(writer, commonResp{ ErrMsg: "获取目录失败", @@ -394,16 +395,20 @@ func getFileInfo(writer http.ResponseWriter, r *http.Request) { jsonFiles := make([]jsonFile, len(files)) json := struct { Files []jsonFile `json:"files"` - Path string `json:"path` + Path string `json:"path"` }{ Path: path, } for i, file := range files { + info, err := file.Info() + if err != nil { + continue + } jsonFiles[i].IsFolder = file.IsDir() jsonFiles[i].Name = file.Name() - jsonFiles[i].LastModified = file.ModTime().Unix() + jsonFiles[i].LastModified = info.ModTime().Unix() if !file.IsDir() { - jsonFiles[i].Size = file.Size() + jsonFiles[i].Size = info.Size() } } json.Files = jsonFiles @@ -417,12 +422,12 @@ func getLiveHostCookie(writer http.ResponseWriter, r *http.Request) { keys := make([]string, 0) for _, v := range inst.Lives { urltmp, _ := url.Parse(v.GetRawUrl()) - if _, ok := hostCookieMap[urltmp.Host]; ok == true { + if _, ok := hostCookieMap[urltmp.Host]; ok { continue } v1, _ := v.GetInfo() host := urltmp.Host - if cookie, ok := inst.Config.Cookies[host]; ok == true { + if cookie, ok := inst.Config.Cookies[host]; ok { tmp := &live.InfoCookie{Platform_cn_name: v1.Live.GetPlatformCNName(), Host: host, Cookie: cookie} hostCookieMap[host] = tmp } else { @@ -440,7 +445,7 @@ func getLiveHostCookie(writer http.ResponseWriter, r *http.Request) { } func putLiveHostCookie(writer http.ResponseWriter, r *http.Request) { - b, err := ioutil.ReadAll(r.Body) + b, err := io.ReadAll(r.Body) if err != nil { writeJsonWithStatusCode(writer, http.StatusBadRequest, commonResp{ ErrNo: http.StatusBadRequest, diff --git a/src/servers/middleware.go b/src/servers/middleware.go index 1d01fcc..0967d7f 100644 --- a/src/servers/middleware.go +++ b/src/servers/middleware.go @@ -8,7 +8,7 @@ import ( func log(handler http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - instance.GetInstance(r.Context()).Logger.WithFields(map[string]interface{}{ + instance.GetInstance(r.Context()).Logger.WithFields(map[string]any{ "Method": r.Method, "Path": r.RequestURI, "RemoteAddr": r.RemoteAddr, diff --git a/src/servers/models.go b/src/servers/models.go index 6e4ff05..b8a5d3a 100644 --- a/src/servers/models.go +++ b/src/servers/models.go @@ -5,9 +5,9 @@ import ( ) type commonResp struct { - ErrNo int `json:"err_no"` - ErrMsg string `json:"err_msg"` - Data interface{} `json:"data"` + ErrNo int `json:"err_no"` + ErrMsg string `json:"err_msg"` + Data any `json:"data"` } type liveSlice []*live.Info diff --git a/src/servers/utils.go b/src/servers/utils.go index 78eb5ae..ae92ea0 100644 --- a/src/servers/utils.go +++ b/src/servers/utils.go @@ -15,7 +15,7 @@ func writeMsg(w http.ResponseWriter, code int, msg string) { _, _ = w.Write([]byte(msg)) } -func writeJSON(w http.ResponseWriter, obj interface{}) { +func writeJSON(w http.ResponseWriter, obj any) { b, err := json.Marshal(obj) if err != nil { writeMsg(w, http.StatusInternalServerError, err.Error()) @@ -25,7 +25,7 @@ func writeJSON(w http.ResponseWriter, obj interface{}) { _, _ = w.Write(b) } -func writeJsonWithStatusCode(w http.ResponseWriter, code int, obj interface{}) { +func writeJsonWithStatusCode(w http.ResponseWriter, code int, obj any) { b, err := json.Marshal(obj) if err != nil { writeMsg(w, http.StatusInternalServerError, err.Error())