Skip to content

Commit

Permalink
Merge branch 'develop'
Browse files Browse the repository at this point in the history
  • Loading branch information
RoyXiang committed Mar 10, 2022
2 parents f6925be + 2fb175c commit cfbb274
Show file tree
Hide file tree
Showing 10 changed files with 125 additions and 63 deletions.
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -40,4 +40,5 @@ env CGO_ENABLED=0 go install -trimpath -ldflags="-s -w" github.com/RoyXiang/plex
* Or, you can set it to [the official one](https://plaxt.astandke.com/)
- `REDIRECT_WEB_APP` (Optional, default: `true`)
- `DISABLE_TRANSCODE` (Optional, default: `true`)
- `NO_REQUEST_LOGS` (Optional, default: `false`)
2. Run the program
7 changes: 7 additions & 0 deletions common/lock.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ type refCounter struct {

type MultipleLock interface {
TryLock(interface{}, time.Duration) bool
Lock(interface{})
Unlock(interface{})
}

Expand All @@ -31,6 +32,12 @@ func (l *lock) TryLock(key interface{}, timeout time.Duration) bool {
return isLocked
}

func (l *lock) Lock(key interface{}) {
m := l.getLocker(key)
atomic.AddInt64(&m.counter, 1)
m.lock.lock()
}

func (l *lock) Unlock(key interface{}) {
m := l.getLocker(key)
m.lock.unlock()
Expand Down
4 changes: 4 additions & 0 deletions common/mutex.go
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,10 @@ func (m *timedMutex) tryLock(timeout time.Duration) bool {
return false
}

func (m *timedMutex) lock() {
m.c <- struct{}{}
}

func (m *timedMutex) unlock() {
<-m.c
}
2 changes: 1 addition & 1 deletion go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -17,4 +17,4 @@ require (
github.com/google/uuid v1.3.0 // indirect
)

replace github.com/jrudio/go-plex-client v0.0.0-20220106065909-9e1d590b99aa => github.com/RoyXiang/go-plex-client v0.0.0-20220310030059-ef5991e7e4e2
replace github.com/jrudio/go-plex-client v0.0.0-20220106065909-9e1d590b99aa => github.com/RoyXiang/go-plex-client v0.0.0-20220310075632-2e318838193f
4 changes: 2 additions & 2 deletions go.sum
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
cloud.google.com/go v0.26.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMTw=
github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU=
github.com/OneOfOne/xxhash v1.2.2/go.mod h1:HSdplMjZKSmBqAxg5vPj2TmRDmfkzw+cTzAElWljhcU=
github.com/RoyXiang/go-plex-client v0.0.0-20220310030059-ef5991e7e4e2 h1:CV52ZCM7Xjtk3524V31RoX3mRvBHa2PZL6YZDOVb87U=
github.com/RoyXiang/go-plex-client v0.0.0-20220310030059-ef5991e7e4e2/go.mod h1:twidbPLE4eUk3CgDno5uCzpnPRboBTElH+iJrQO7S4w=
github.com/RoyXiang/go-plex-client v0.0.0-20220310075632-2e318838193f h1:vUNGSKhuDTgEqQOmx/mpzR00IPXw7pCbtWha3IlsQyA=
github.com/RoyXiang/go-plex-client v0.0.0-20220310075632-2e318838193f/go.mod h1:twidbPLE4eUk3CgDno5uCzpnPRboBTElH+iJrQO7S4w=
github.com/armon/consul-api v0.0.0-20180202201655-eb2c6b5be1b6/go.mod h1:grANhF5doyWs3UAsr3K4I6qtAmlQcZDesFNEHPZAzj8=
github.com/cespare/xxhash v1.1.0 h1:a6HrQnmkObjyL+Gs60czilIUGqrzKutQD6XZog3p+ko=
github.com/cespare/xxhash v1.1.0/go.mod h1:XrSqR1VqqWfGrhpAt58auRo0WTKS1nRRg3ghfAqPWnc=
Expand Down
4 changes: 4 additions & 0 deletions handler/const.go
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,10 @@ const (
contentTypeAny = "*/*"
contentTypeXml = "xml"

lockKeyFriends = "plex:friends"
lockKeySections = "plex:library:sections"
lockKeySessions = "plex:playback:sessions"

watchedThreshold = 90

webhookEventPlay = "media.play"
Expand Down
12 changes: 5 additions & 7 deletions handler/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@ import (
"os"
"sync"

"github.com/RoyXiang/plexproxy/common"
"github.com/go-chi/chi/v5/middleware"
"github.com/go-redis/redis/v8"
"github.com/gorilla/mux"
Expand All @@ -19,7 +18,6 @@ var (
emptyStruct = struct{}{}

mu sync.RWMutex
ml common.MultipleLock
)

func init() {
Expand All @@ -29,6 +27,7 @@ func init() {
PlaxtUrl: os.Getenv("PLAXT_URL"),
RedirectWebApp: os.Getenv("REDIRECT_WEB_APP"),
DisableTranscode: os.Getenv("DISABLE_TRANSCODE"),
NoRequestLogs: os.Getenv("NO_REQUEST_LOGS"),
})
if plexClient == nil {
log.Fatalln("Please configure PLEX_BASEURL as a valid URL at first")
Expand All @@ -41,16 +40,15 @@ func init() {
redisClient = redis.NewClient(options)
}
}

ml = common.NewMultipleLock()
}

func NewRouter() http.Handler {
r := mux.NewRouter()
r.Use(normalizeMiddleware)
r.Use(middleware.Logger)
r.Use(middleware.Recoverer)
r.Use(trafficMiddleware)
if !plexClient.NoRequestLogs {
r.Use(middleware.Logger)
}
r.Use(wrapMiddleware, middleware.Recoverer, trafficMiddleware)

if redisClient != nil {
// bypass cache
Expand Down
30 changes: 18 additions & 12 deletions handler/middleware.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,12 +12,11 @@ import (
"strconv"
"strings"
"time"

"github.com/go-chi/chi/v5/middleware"
)

var (
cacheInfoCtxKey = &ctxKeyType{"cacheInfo"}
userCtxKey = &ctxKeyType{"user"}
)

func normalizeMiddleware(next http.Handler) http.Handler {
Expand Down Expand Up @@ -74,6 +73,17 @@ func normalizeMiddleware(next http.Handler) http.Handler {
})
}

func wrapMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if token := r.Header.Get(headerToken); token != "" {
if user := plexClient.GetUser(token); user != nil {
r = r.WithContext(context.WithValue(r.Context(), userCtxKey, user))
}
}
next.ServeHTTP(wrapResponseWriter(w, r.ProtoMajor), r)
})
}

func trafficMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
params := r.URL.Query()
Expand All @@ -84,11 +94,11 @@ func trafficMiddleware(next http.Handler) http.Handler {
params.Set(headerRange, rg)
}
lockKey := fmt.Sprintf("%s?%s", r.URL.EscapedPath(), params.Encode())
if !ml.TryLock(lockKey, time.Second) {
if !plexClient.MulLock.TryLock(lockKey, time.Second) {
w.WriteHeader(http.StatusGatewayTimeout)
return
}
defer ml.Unlock(lockKey)
defer plexClient.MulLock.Unlock(lockKey)
next.ServeHTTP(w, r)
})
}
Expand Down Expand Up @@ -148,7 +158,7 @@ func cacheMiddleware(next http.Handler) http.Handler {
resp, _ = http.ReadResponse(reader, r)
}
if resp == nil {
nw := middleware.NewWrapResponseWriter(httptest.NewRecorder(), r.ProtoMajor)
nw := wrapResponseWriter(httptest.NewRecorder(), r.ProtoMajor)
next.ServeHTTP(nw, r)
resp = nw.Unwrap().(*httptest.ResponseRecorder).Result()
defer func() {
Expand Down Expand Up @@ -181,16 +191,12 @@ func cacheMiddleware(next http.Handler) http.Handler {
case cachePrefixStatic:
break
case cachePrefixDynamic, cachePrefixMetadata:
token := r.Header.Get(headerToken)
if token == "" {
return
}
user := plexClient.GetUser(token)
user := r.Context().Value(userCtxKey)
if user != nil {
params.Set(headerUserId, strconv.Itoa(user.Id))
params.Set(headerUserId, strconv.Itoa(user.(*plexUser).Id))
params.Set(headerAccept, getAcceptContentType(r))
} else {
params.Set(headerToken, token)
return
}
default:
// invalid prefix
Expand Down
Loading

0 comments on commit cfbb274

Please sign in to comment.