author
int64
658
755k
date
stringlengths
19
19
timezone
int64
-46,800
43.2k
hash
stringlengths
40
40
message
stringlengths
5
490
mods
list
language
stringclasses
20 values
license
stringclasses
3 values
repo
stringlengths
5
68
original_message
stringlengths
12
491
532,307
29.08.2020 19:45:47
25,200
f1343c1d77b3e8e135da32b0b99e5995db0c4717
Publish console message on initial startup for disk sizing
[ { "change_type": "MODIFY", "old_path": "server/power.go", "new_path": "server/power.go", "diff": "@@ -141,6 +141,7 @@ func (s *Server) onBeforeStart() error {\n// and process resource limits are correctly applied.\ns.SyncWithEnvironment()\n+ s.PublishConsoleOutputFromDaemon(\"Checking server disk space usage, this could take a few seconds...\")\nif !s.Filesystem.HasSpaceAvailable() {\nreturn errors.New(\"cannot start server, not enough disk space available\")\n}\n" } ]
Go
MIT License
pterodactyl/wings
Publish console message on initial startup for disk sizing
532,307
31.08.2020 20:27:41
25,200
d742acf308058ee601952e0321b2d3fb4d6e38ca
Minimize blocking in Filesystem.getCachedDiskUsage
[ { "change_type": "MODIFY", "old_path": "router/router_server_files.go", "new_path": "router/router_server_files.go", "diff": "@@ -287,7 +287,7 @@ func postServerCompressFiles(c *gin.Context) {\nreturn\n}\n- if !s.Filesystem.HasSpaceAvailable() {\n+ if !s.Filesystem.HasSpaceAvailable(true) {\nc.AbortWithStatusJSON(http.StatusConflict, gin.H{\n\"error\": \"This server does not have enough available disk space to generate a compressed archive.\",\n})\n@@ -361,7 +361,7 @@ func postServerUploadFiles(c *gin.Context) {\nreturn\n}\n- if !s.Filesystem.HasSpaceAvailable() {\n+ if !s.Filesystem.HasSpaceAvailable(true) {\nc.AbortWithStatusJSON(http.StatusConflict, gin.H{\n\"error\": \"This server does not have enough available disk space to accept any file uploads.\",\n})\n" }, { "change_type": "MODIFY", "old_path": "router/websocket/websocket.go", "new_path": "router/websocket/websocket.go", "diff": "@@ -261,7 +261,7 @@ func (h *Handler) HandleInbound(m Message) error {\n// Only send the current disk usage if the server is offline, if docker container is running,\n// Environment#EnableResourcePolling() will send this data to all clients.\nif state == environment.ProcessOfflineState {\n- _ = h.server.Filesystem.HasSpaceAvailable()\n+ _ = h.server.Filesystem.HasSpaceAvailable(false)\nb, _ := json.Marshal(h.server.Proc())\nh.SendJson(&Message{\n" }, { "change_type": "MODIFY", "old_path": "server/filesystem.go", "new_path": "server/filesystem.go", "diff": "@@ -41,9 +41,10 @@ func IsPathResolutionError(err error) bool {\n}\ntype Filesystem struct {\n- mu sync.RWMutex\n+ mu sync.Mutex\nlastLookupTime time.Time\n+ lookupInProgress int32\ndiskUsage int64\nServer *Server\n@@ -211,8 +212,10 @@ func (fs *Filesystem) ParallelSafePath(paths []string) ([]string, error) {\n//\n// Because determining the amount of space being used by a server is a taxing operation we\n// will load it all up into a cache and pull from that as long as the key is not expired.\n-func (fs *Filesystem) HasSpaceAvailable() bool {\n- size, err := fs.getCachedDiskUsage()\n+//\n+// This operation will potentially block unless nonBlocking is true\n+func (fs *Filesystem) HasSpaceAvailable(nonBlocking bool) bool {\n+ size, err := fs.getCachedDiskUsage(nonBlocking)\nif err != nil {\nfs.Server.Log().WithField(\"error\", err).Warn(\"failed to determine root server directory size\")\n}\n@@ -238,20 +241,40 @@ func (fs *Filesystem) HasSpaceAvailable() bool {\n// as needed without overly taxing the system. This will prioritize the value from the cache to avoid\n// excessive IO usage. We will only walk the filesystem and determine the size of the directory if there\n// is no longer a cached value.\n-func (fs *Filesystem) getCachedDiskUsage() (int64, error) {\n+// This will potentially block unless nonBlocking is true.\n+func (fs *Filesystem) getCachedDiskUsage(nonBlocking bool) (int64, error) {\n+\n+ // Check if cache is expired...\n+ if !fs.lastLookupTime.After(time.Now().Add(time.Second * -150)) {\n+ // We're OK with blocking, so go ahead and block\n+ if !nonBlocking {\n+ return fs.updateCachedDiskUsage()\n+ }\n+\n+ // Otherwise, we're fine with not blocking, but still need to update the cache. (If it isn't being done already)\n+ if atomic.LoadInt32(&fs.lookupInProgress) != 1 {\n+ go fs.updateCachedDiskUsage()\n+ }\n+\n+ }\n+\n+ // Go ahead and return the cached value\n+ return atomic.LoadInt64(&fs.diskUsage), nil\n+}\n+\n+func (fs *Filesystem) updateCachedDiskUsage() (int64, error) {\n+\n// Obtain an exclusive lock on this process so that we don't unintentionally run it at the same\n// time as another running process. Once the lock is available it'll read from the cache for the\n// second call rather than hitting the disk in parallel.\n- //\n- // This effectively the same speed as running this call in parallel since this cache will return\n- // instantly on the second call.\nfs.mu.Lock()\ndefer fs.mu.Unlock()\n- // Expire the cache after 2.5 minutes.\n- if fs.lastLookupTime.After(time.Now().Add(time.Second * -150)) {\n- return fs.diskUsage, nil\n- }\n+ // Always clear the in progress flag\n+ defer atomic.StoreInt32(&fs.lookupInProgress, 0)\n+\n+ // Signal that we're currently updating the disk size, to prevent other routines to block on this.\n+ atomic.StoreInt32(&fs.lookupInProgress, 1)\n// If there is no size its either because there is no data (in which case running this function\n// will have effectively no impact), or there is nothing in the cache, in which case we need to\n" }, { "change_type": "MODIFY", "old_path": "server/filesystem_unarchive.go", "new_path": "server/filesystem_unarchive.go", "diff": "@@ -38,7 +38,7 @@ func (fs *Filesystem) SpaceAvailableForDecompression(dir string, file string) (b\nwg.Add(1)\ndefer wg.Done()\n- dirSize, cErr = fs.getCachedDiskUsage()\n+ dirSize, cErr = fs.getCachedDiskUsage(true)\n}()\nvar size int64\n" }, { "change_type": "MODIFY", "old_path": "server/listeners.go", "new_path": "server/listeners.go", "diff": "@@ -46,10 +46,7 @@ func (s *Server) StartEventListeners() {\ns.resources.Stats = *st\ns.resources.mu.Unlock()\n- // TODO: we'll need to handle this better since calling it in rapid succession will\n- // cause it to block until the first call is done calculating disk usage, which will\n- // case stat events to pile up for the server.\n- s.Filesystem.HasSpaceAvailable()\n+ s.Filesystem.HasSpaceAvailable(true)\ns.emitProcUsage()\n}\n" }, { "change_type": "MODIFY", "old_path": "server/loader.go", "new_path": "server/loader.go", "diff": "@@ -128,7 +128,7 @@ func FromConfiguration(data *api.ServerConfigurationResponse) (*Server, error) {\n// If the server's data directory exists, force disk usage calculation.\nif _, err := os.Stat(s.Filesystem.Path()); err == nil {\n- go s.Filesystem.HasSpaceAvailable()\n+ s.Filesystem.HasSpaceAvailable(true)\n}\nreturn s, nil\n" }, { "change_type": "MODIFY", "old_path": "server/power.go", "new_path": "server/power.go", "diff": "@@ -142,7 +142,7 @@ func (s *Server) onBeforeStart() error {\ns.SyncWithEnvironment()\ns.PublishConsoleOutputFromDaemon(\"Checking server disk space usage, this could take a few seconds...\")\n- if !s.Filesystem.HasSpaceAvailable() {\n+ if !s.Filesystem.HasSpaceAvailable(false) {\nreturn errors.New(\"cannot start server, not enough disk space available\")\n}\n" }, { "change_type": "MODIFY", "old_path": "sftp/sftp.go", "new_path": "sftp/sftp.go", "diff": "@@ -63,7 +63,7 @@ func validateDiskSpace(fs FileSystem) bool {\nreturn false\n}\n- return s.Filesystem.HasSpaceAvailable()\n+ return s.Filesystem.HasSpaceAvailable(true)\n}\n// Validates a set of credentials for a SFTP login aganist Pterodactyl Panel and returns\n" } ]
Go
MIT License
pterodactyl/wings
Minimize blocking in Filesystem.getCachedDiskUsage (#53)
532,307
31.08.2020 22:10:57
25,200
1d22e84f21eee9257dfad7c0fe76441f1f589a9d
Allow a stale value on startup for disk size if the disk is unlimited.
[ { "change_type": "MODIFY", "old_path": "server/power.go", "new_path": "server/power.go", "diff": "@@ -141,10 +141,16 @@ func (s *Server) onBeforeStart() error {\n// and process resource limits are correctly applied.\ns.SyncWithEnvironment()\n+ // If a server has unlimited disk space, we don't care enough to block the startup to check remaining.\n+ // However, we should trigger a size anyway, as it'd be good to kick it off for other processes.\n+ if s.DiskSpace() <= 0 {\n+ s.Filesystem.HasSpaceAvailable(true)\n+ } else {\ns.PublishConsoleOutputFromDaemon(\"Checking server disk space usage, this could take a few seconds...\")\nif !s.Filesystem.HasSpaceAvailable(false) {\nreturn errors.New(\"cannot start server, not enough disk space available\")\n}\n+ }\n// Update the configuration files defined for the server before beginning the boot process.\n// This process executes a bunch of parallel updates, so we just block until that process\n" } ]
Go
MIT License
pterodactyl/wings
Allow a stale value on startup for disk size if the disk is unlimited.
532,331
17.09.2020 23:48:09
14,400
033e8e7573f0b7256581021ca3bd9f7ae0eee305
Add GoReportcard badge Adds GoReportcard Badge
[ { "change_type": "MODIFY", "old_path": "README.md", "new_path": "README.md", "diff": "[![Logo Image](https://cdn.pterodactyl.io/logos/new/pterodactyl_logo.png)](https://pterodactyl.io)\n[![Discord](https://img.shields.io/discord/122900397965705216.svg?style=flat-square&label=Discord)](https://pterodactyl.io/discord)\n+[![Go Report Card](https://goreportcard.com/badge/github.com/pterodactyl/wings)](https://goreportcard.com/report/github.com/pterodactyl/wings)\n# Pterodactyl Wings\nWings is Pterodactyl's server control plane, built for the rapidly changing gaming industry and designed to be\n" } ]
Go
MIT License
pterodactyl/wings
Add GoReportcard badge (#57) Adds GoReportcard Badge
532,313
01.10.2020 18:00:26
14,400
b92fab83c8924ad0ccd320aa9c93054add339d55
Removed stray `.` in `./mnt/install`
[ { "change_type": "MODIFY", "old_path": "server/install.go", "new_path": "server/install.go", "diff": "@@ -395,7 +395,7 @@ func (ip *InstallationProcess) Execute() (string, error) {\nAttachStdin: true,\nOpenStdin: true,\nTty: true,\n- Cmd: []string{ip.Script.Entrypoint, \"./mnt/install/install.sh\"},\n+ Cmd: []string{ip.Script.Entrypoint, \"/mnt/install/install.sh\"},\nImage: ip.Script.ContainerImage,\nEnv: ip.Server.GetEnvironmentVariables(),\nLabels: map[string]string{\n" } ]
Go
MIT License
pterodactyl/wings
Removed stray `.` in `./mnt/install`
532,310
07.10.2020 18:39:58
14,400
4c9aaeb769704c37e794e92b98eb80cb47c36330
fix file parsing resolves loads, edits, and re-writes the file instead of inline edits that seem to break. This inefficient but it works in my testing.
[ { "change_type": "MODIFY", "old_path": "parser/parser.go", "new_path": "parser/parser.go", "diff": "@@ -390,38 +390,31 @@ func (f *ConfigurationFile) parseYamlFile(path string) error {\n// scanning a file and performing a replacement. You should attempt to use anything other\n// than this function where possible.\nfunc (f *ConfigurationFile) parseTextFile(path string) error {\n- file, err := os.OpenFile(path, os.O_CREATE|os.O_RDWR, 0644)\n+ // read file\n+ input, err := ioutil.ReadFile(path)\nif err != nil {\nreturn err\n}\n- defer file.Close()\n- scanner := bufio.NewScanner(file)\n- for scanner.Scan() {\n- hasReplaced := false\n- t := scanner.Text()\n+ // split file into lines to parse one by one.\n+ lines := strings.Split(string(input), \"\\n\")\n- // Iterate over the potential replacements for the line and check if there are\n- // any matches.\n+ for i, line := range lines {\nfor _, replace := range f.Replace {\n- if !strings.HasPrefix(t, replace.Match) {\n+ // skip if line doesn't have the prefix\n+ if !strings.HasPrefix(line, replace.Match) {\ncontinue\n}\n- hasReplaced = true\n- t = strings.Replace(t, replace.Match, replace.ReplaceWith.String(), 1)\n- }\n-\n- // If there was a replacement that occurred on this specific line, do a write to the file\n- // immediately to write that modified content to the disk.\n- if hasReplaced {\n- if _, err := file.WriteAt([]byte(t+\"\\n\"), int64(len(scanner.Bytes()))); err != nil {\n- return err\n- }\n+ // replace line if it has the prefix\n+ lines[i] = replace.ReplaceWith.String()\n}\n}\n- if err := scanner.Err(); err != nil {\n+ // join all the file lines with new lines between\n+ output := strings.Join(lines, \"\\n\")\n+ err = ioutil.WriteFile(path, []byte(output), 0644)\n+ if err != nil {\nreturn err\n}\n" } ]
Go
MIT License
pterodactyl/wings
fix file parsing resolves #2393 loads, edits, and re-writes the file instead of inline edits that seem to break. This inefficient but it works in my testing.
532,309
08.11.2020 14:42:55
-28,800
33e584b447c28a8a6d74fd5ab8b16c29ac2d7ee5
Turn off the CGO to make it static linked
[ { "change_type": "MODIFY", "old_path": ".github/workflows/build-test.yml", "new_path": ".github/workflows/build-test.yml", "diff": "@@ -32,6 +32,7 @@ jobs:\nenv:\nGOOS: ${{ matrix.goos }}\nGOARCH: ${{ matrix.goarch }}\n+ CGO_ENABLED: 0\nrun: |\ngo build -v -ldflags=\"-s -w -X github.com/pterodactyl/wings/system.Version=dev-${GIT_COMMIT:0:7}\" -o build/wings_${{ matrix.goos }}_${{ matrix.goarch }} wings.go\n" }, { "change_type": "MODIFY", "old_path": ".github/workflows/release.yml", "new_path": ".github/workflows/release.yml", "diff": "@@ -20,9 +20,9 @@ jobs:\nenv:\nREF: ${{ github.ref }}\nrun: |\n- GOOS=linux GOARCH=amd64 go build -ldflags=\"-s -w -X github.com/pterodactyl/wings/system.Version=${REF:11}\" -o build/wings_linux_amd64 -v wings.go\n- GOOS=linux GOARCH=arm64 go build -ldflags=\"-s -w -X github.com/pterodactyl/wings/system.Version=${REF:11}\" -o build/wings_linux_arm64 -v wings.go\n- GOOS=linux GOARCH=arm go build -ldflags=\"-s -w -X github.com/pterodactyl/wings/system.Version=${REF:11}\" -o build/wings_linux_arm -v wings.go\n+ CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build -ldflags=\"-s -w -X github.com/pterodactyl/wings/system.Version=${REF:11}\" -o build/wings_linux_amd64 -v wings.go\n+ CGO_ENABLED=0 GOOS=linux GOARCH=arm64 go build -ldflags=\"-s -w -X github.com/pterodactyl/wings/system.Version=${REF:11}\" -o build/wings_linux_arm64 -v wings.go\n+ CGO_ENABLED=0 GOOS=linux GOARCH=arm go build -ldflags=\"-s -w -X github.com/pterodactyl/wings/system.Version=${REF:11}\" -o build/wings_linux_arm -v wings.go\n- name: Test\nrun: go test ./...\n" }, { "change_type": "MODIFY", "old_path": "Dockerfile", "new_path": "Dockerfile", "diff": "@@ -6,7 +6,7 @@ FROM golang:1.15-alpine\nCOPY . /go/wings/\nWORKDIR /go/wings/\nRUN apk add --no-cache upx \\\n- && go build -ldflags=\"-s -w\" \\\n+ && CGO_ENABLED=0 go build -ldflags=\"-s -w\" \\\n&& upx --brute wings\nFROM alpine:latest\n" } ]
Go
MIT License
pterodactyl/wings
Turn off the CGO to make it static linked
532,321
01.12.2020 20:43:40
-3,600
4a7510d36f0dc03791e1070bfdd83cf35eac7f52
Allow multiple publishing on multiple interfaces on same port. Fixes the issue where you cannot have multiple ip addresses on the same port for a server.
[ { "change_type": "MODIFY", "old_path": "environment/allocations.go", "new_path": "environment/allocations.go", "diff": "@@ -38,15 +38,26 @@ func (a *Allocations) Bindings() nat.PortMap {\ncontinue\n}\n- binding := []nat.PortBinding{\n- {\n+ binding := nat.PortBinding{\nHostIP: ip,\nHostPort: strconv.Itoa(port),\n- },\n}\n- out[nat.Port(fmt.Sprintf(\"%d/tcp\", port))] = binding\n- out[nat.Port(fmt.Sprintf(\"%d/udp\", port))] = binding\n+ tcpPort, ok := out[nat.Port(fmt.Sprintf(\"%d/tcp\", port))]\n+\n+ if !ok {\n+ out[nat.Port(fmt.Sprintf(\"%d/tcp\", port))] = []nat.PortBinding{binding}\n+ } else {\n+ out[nat.Port(fmt.Sprintf(\"%d/tcp\", port))] = append(tcpPort, binding)\n+ }\n+\n+ udpPort, ok := out[nat.Port(fmt.Sprintf(\"%d/udp\", port))]\n+\n+ if !ok {\n+ out[nat.Port(fmt.Sprintf(\"%d/udp\", port))] = []nat.PortBinding{binding}\n+ } else {\n+ out[nat.Port(fmt.Sprintf(\"%d/udp\", port))] = append(udpPort, binding)\n+ }\n}\n}\n" } ]
Go
MIT License
pterodactyl/wings
Allow multiple publishing on multiple interfaces on same port. Fixes the issue where you cannot have multiple ip addresses on the same port for a server.
532,326
15.12.2020 22:59:18
18,000
8f26c31df640260c27358f25230d74bd16444bde
Support downloading remote files to a server via the API
[ { "change_type": "MODIFY", "old_path": "router/middleware.go", "new_path": "router/middleware.go", "diff": "package router\nimport (\n+ \"errors\"\n\"github.com/gin-gonic/gin\"\n\"github.com/google/uuid\"\n\"github.com/pterodactyl/wings/config\"\n@@ -60,6 +61,9 @@ func AuthorizationMiddleware(c *gin.Context) {\n}\n// Helper function to fetch a server out of the servers collection stored in memory.\n+//\n+// This function should not be used in new controllers, prefer ExtractServer where\n+// possible.\nfunc GetServer(uuid string) *server.Server {\nreturn server.GetServers().Find(func(s *server.Server) bool {\nreturn uuid == s.Id()\n@@ -70,12 +74,24 @@ func GetServer(uuid string) *server.Server {\n// locate it.\nfunc ServerExists(c *gin.Context) {\nu, err := uuid.Parse(c.Param(\"server\"))\n- if err != nil || GetServer(u.String()) == nil {\n+ if err == nil {\n+ if s := GetServer(u.String()); s != nil {\n+ c.Set(\"server\", s)\n+ c.Next()\n+ return\n+ }\n+ }\nc.AbortWithStatusJSON(http.StatusNotFound, gin.H{\n\"error\": \"The resource you requested does not exist.\",\n})\n- return\n}\n- c.Next()\n+// Returns the server instance from the gin context. If there is no server set in the\n+// context (e.g. calling from a controller not protected by ServerExists) this function\n+// will panic.\n+func ExtractServer(c *gin.Context) *server.Server {\n+ if s, ok := c.Get(\"server\"); ok {\n+ return s.(*server.Server)\n+ }\n+ panic(errors.New(\"cannot extract server, missing on gin context\"))\n}\n" }, { "change_type": "MODIFY", "old_path": "router/router.go", "new_path": "router/router.go", "diff": "@@ -83,6 +83,7 @@ func Configure() *gin.Engine {\nfiles.PUT(\"/rename\", putServerRenameFiles)\nfiles.POST(\"/copy\", postServerCopyFile)\nfiles.POST(\"/write\", postServerWriteFile)\n+ files.POST(\"/writeUrl\", postServerDownloadRemoteFile)\nfiles.POST(\"/create-directory\", postServerCreateDirectory)\nfiles.POST(\"/delete\", postServerDeleteFiles)\nfiles.POST(\"/compress\", postServerCompressFiles)\n" }, { "change_type": "MODIFY", "old_path": "router/router_server_files.go", "new_path": "router/router_server_files.go", "diff": "@@ -225,6 +225,51 @@ func postServerWriteFile(c *gin.Context) {\nc.Status(http.StatusNoContent)\n}\n+// Writes the contents of the remote URL to a file on a server.\n+func postServerDownloadRemoteFile(c *gin.Context) {\n+ s := ExtractServer(c)\n+ var data struct {\n+ URL string `binding:\"required\" json:\"url\"`\n+ BasePath string `json:\"path\"`\n+ }\n+ if err := c.BindJSON(&data); err != nil {\n+ return\n+ }\n+\n+ u, err := url.Parse(data.URL)\n+ if err != nil {\n+ if e, ok := err.(*url.Error); ok {\n+ c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{\n+ \"error\": \"An error occurred while parsing that URL: \" + e.Err.Error(),\n+ })\n+ return\n+ }\n+ TrackedServerError(err, s).AbortWithServerError(c)\n+ return\n+ }\n+\n+ resp, err := http.Get(u.String())\n+ if err != nil {\n+ TrackedServerError(err, s).AbortWithServerError(c)\n+ return\n+ }\n+ defer resp.Body.Close()\n+\n+ filename := strings.Split(u.Path, \"/\")\n+ if err := s.Filesystem().Writefile(filepath.Join(data.BasePath, filename[len(filename)-1]), resp.Body); err != nil {\n+ if errors.Is(err, filesystem.ErrIsDirectory) {\n+ c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{\n+ \"error\": \"Cannot write file, name conflicts with an existing directory by the same name.\",\n+ })\n+ return\n+ }\n+ TrackedServerError(err, s).AbortFilesystemError(c)\n+ return\n+ }\n+\n+ c.Status(http.StatusNoContent)\n+}\n+\n// Create a directory on a server.\nfunc postServerCreateDirectory(c *gin.Context) {\ns := GetServer(c.Param(\"server\"))\n" } ]
Go
MIT License
pterodactyl/wings
Support downloading remote files to a server via the API Co-authored-by: Dane Everitt <[email protected]>
532,333
03.01.2021 19:24:28
18,000
a822c7c340d4e5cdbaeba1cfb87cfe7acb5ad74b
typo in docker-compose file minor typo i noticed while messing around
[ { "change_type": "MODIFY", "old_path": "docker-compose.example.yml", "new_path": "docker-compose.example.yml", "diff": "@@ -24,7 +24,7 @@ services:\n- \"/tmp/pterodactyl/:/tmp/pterodactyl/\"\n# you may need /srv/daemon-data if you are upgrading from an old daemon\n#- \"/srv/daemon-data/:/srv/daemon-data/\"\n- # Required for ssl if you user let's encrypt. uncomment to use.\n+ # Required for ssl if you use let's encrypt. uncomment to use.\n#- \"/etc/letsencrypt/:/etc/letsencrypt/\"\nnetworks:\n" } ]
Go
MIT License
pterodactyl/wings
typo in docker-compose file (#82) minor typo i noticed while messing around
532,315
21.02.2021 14:41:50
-28,800
4ed0bf522b487bb3c312abbad6dd46f812fec9ae
Quote and escape Content-Disposition header
[ { "change_type": "MODIFY", "old_path": "router/router_download.go", "new_path": "router/router_download.go", "diff": "@@ -52,7 +52,7 @@ func getDownloadBackup(c *gin.Context) {\ndefer f.Close()\nc.Header(\"Content-Length\", strconv.Itoa(int(st.Size())))\n- c.Header(\"Content-Disposition\", \"attachment; filename=\"+st.Name())\n+ c.Header(\"Content-Disposition\", \"attachment; filename=\"+strconv.Quote(st.Name()))\nc.Header(\"Content-Type\", \"application/octet-stream\")\nbufio.NewReader(f).WriteTo(c.Writer)\n@@ -96,7 +96,7 @@ func getDownloadFile(c *gin.Context) {\n}\nc.Header(\"Content-Length\", strconv.Itoa(int(st.Size())))\n- c.Header(\"Content-Disposition\", \"attachment; filename=\"+st.Name())\n+ c.Header(\"Content-Disposition\", \"attachment; filename=\"+strconv.Quote(st.Name()))\nc.Header(\"Content-Type\", \"application/octet-stream\")\nbufio.NewReader(f).WriteTo(c.Writer)\n" }, { "change_type": "MODIFY", "old_path": "router/router_server_files.go", "new_path": "router/router_server_files.go", "diff": "@@ -39,7 +39,7 @@ func getServerFileContents(c *gin.Context) {\n// If a download parameter is included in the URL go ahead and attach the necessary headers\n// so that the file can be downloaded.\nif c.Query(\"download\") != \"\" {\n- c.Header(\"Content-Disposition\", \"attachment; filename=\"+st.Name())\n+ c.Header(\"Content-Disposition\", \"attachment; filename=\"+strconv.Quote(st.Name()))\nc.Header(\"Content-Type\", \"application/octet-stream\")\n}\ndefer c.Writer.Flush()\n" }, { "change_type": "MODIFY", "old_path": "router/router_transfer.go", "new_path": "router/router_transfer.go", "diff": "@@ -102,7 +102,7 @@ func getServerArchive(c *gin.Context) {\nc.Header(\"X-Checksum\", checksum)\nc.Header(\"X-Mime-Type\", st.Mimetype)\nc.Header(\"Content-Length\", strconv.Itoa(int(st.Size())))\n- c.Header(\"Content-Disposition\", \"attachment; filename=\"+s.Archiver.Name())\n+ c.Header(\"Content-Disposition\", \"attachment; filename=\"+strconv.Quote(s.Archiver.Name()))\nc.Header(\"Content-Type\", \"application/octet-stream\")\nbufio.NewReader(file).WriteTo(c.Writer)\n" } ]
Go
MIT License
pterodactyl/wings
Quote and escape Content-Disposition header
532,323
24.03.2021 10:26:03
-3,600
0c17e240f400b59bda424c653a082850d79dad8a
Added app name
[ { "change_type": "MODIFY", "old_path": "config/config.go", "new_path": "config/config.go", "diff": "@@ -247,6 +247,8 @@ type Configuration struct {\n// if the debug flag is passed through the command line arguments.\nDebug bool\n+ AppName string `json:\"app_name\" yaml:\"app_name\"`\n+\n// A unique identifier for this node in the Panel.\nUuid string\n" }, { "change_type": "MODIFY", "old_path": "server/console.go", "new_path": "server/console.go", "diff": "@@ -127,6 +127,6 @@ func (s *Server) Throttler() *ConsoleThrottler {\nfunc (s *Server) PublishConsoleOutputFromDaemon(data string) {\ns.Events().Publish(\nConsoleOutputEvent,\n- colorstring.Color(fmt.Sprintf(\"[yellow][bold][Pterodactyl Daemon]:[default] %s\", data)),\n+ colorstring.Color(fmt.Sprintf(\"[yellow][bold][%s Daemon]:[default] %s\", config.Get().AppName, data)),\n)\n}\n" } ]
Go
MIT License
pterodactyl/wings
Added app name
532,323
02.04.2021 21:32:30
-7,200
b691b8f06febdbfd9b317df1da4de9c930e8a44d
Fixed /api/servers
[ { "change_type": "MODIFY", "old_path": "router/router_system.go", "new_path": "router/router_system.go", "diff": "@@ -28,7 +28,15 @@ func getSystemInformation(c *gin.Context) {\n// Returns all of the servers that are registered and configured correctly on\n// this wings instance.\nfunc getAllServers(c *gin.Context) {\n- c.JSON(http.StatusOK, middleware.ExtractManager(c).All())\n+ servers := middleware.ExtractManager(c).All()\n+ var procData []serverProcData\n+ for _, v := range servers {\n+ procData = append(procData, serverProcData{\n+ ResourceUsage: v.Proc(),\n+ Suspended: v.IsSuspended(),\n+ })\n+ }\n+ c.JSON(http.StatusOK, procData)\n}\n// Creates a new server on the wings daemon and begins the installation process\n" } ]
Go
MIT License
pterodactyl/wings
Fixed /api/servers
532,322
02.04.2021 22:45:56
14,400
bec6a6112df97c71f5550ab980cc497df06cf017
Fix reading User.Gid from WINGS_GID over WINGS_UID
[ { "change_type": "MODIFY", "old_path": "config/config.go", "new_path": "config/config.go", "diff": "@@ -395,7 +395,7 @@ func EnsurePterodactylUser() error {\nif sysName == \"busybox\" {\n_config.System.Username = system.FirstNotEmpty(os.Getenv(\"WINGS_USERNAME\"), \"pterodactyl\")\n_config.System.User.Uid = system.MustInt(system.FirstNotEmpty(os.Getenv(\"WINGS_UID\"), \"988\"))\n- _config.System.User.Gid = system.MustInt(system.FirstNotEmpty(os.Getenv(\"WINGS_UID\"), \"988\"))\n+ _config.System.User.Gid = system.MustInt(system.FirstNotEmpty(os.Getenv(\"WINGS_GID\"), \"988\"))\nreturn nil\n}\n" } ]
Go
MIT License
pterodactyl/wings
Fix reading User.Gid from WINGS_GID over WINGS_UID
532,310
12.04.2021 19:38:16
14,400
cfa338108fdf93a8e9fd9938aab03bdcadbfb95b
Fixes ghcr build Removes version pins so packages install properly.
[ { "change_type": "MODIFY", "old_path": "Dockerfile", "new_path": "Dockerfile", "diff": "FROM golang:1.15-alpine3.12 AS builder\nARG VERSION\n-RUN apk add --update --no-cache git=2.26.2-r0 make=4.3-r0 upx=3.96-r0\n+RUN apk add --update --no-cache git make upx\nWORKDIR /app/\nCOPY go.mod go.sum /app/\nRUN go mod download\n" } ]
Go
MIT License
pterodactyl/wings
Fixes ghcr build Removes version pins so packages install properly.
532,312
05.07.2021 00:07:46
-7,200
c0a487c47e731576f373f061e03015847ddb4355
Fix environment variables with the same prefix being skipped unintentionally If you have two env variables (for example ONE_VARIABLE and ONE_VARIABLE_NAME) ONE_VARIABLE_NAME has prefix ONE_VARIABLE and will be skipped.
[ { "change_type": "MODIFY", "old_path": "server/server.go", "new_path": "server/server.go", "diff": "@@ -129,7 +129,7 @@ eloop:\nfor k := range s.Config().EnvVars {\n// Don't allow any environment variables that we have already set above.\nfor _, e := range out {\n- if strings.HasPrefix(e, strings.ToUpper(k)) {\n+ if strings.HasPrefix(e, strings.ToUpper(k) + \"=\") {\ncontinue eloop\n}\n}\n" } ]
Go
MIT License
pterodactyl/wings
Fix environment variables with the same prefix being skipped unintentionally (#98) If you have two env variables (for example ONE_VARIABLE and ONE_VARIABLE_NAME) ONE_VARIABLE_NAME has prefix ONE_VARIABLE and will be skipped. Co-authored-by: Jakob <[email protected]>
532,316
04.10.2021 08:22:56
25,200
6f9783f164194afe6cd2fc618e81f8c698eefeed
Update CHS Primary Link to chs.gg Update CHS Primary Link to chs.gg
[ { "change_type": "MODIFY", "old_path": "README.md", "new_path": "README.md", "diff": "@@ -30,7 +30,7 @@ I would like to extend my sincere thanks to the following sponsors for helping f\n| [**Spill Hosting**](https://spillhosting.no/) | Spill Hosting is a Norwegian hosting service, which aims for inexpensive services on quality servers. Premium i9-9900K processors will run your game like a dream. |\n| [**DeinServerHost**](https://deinserverhost.de/) | DeinServerHost offers Dedicated, vps and Gameservers for many popular Games like Minecraft and Rust in Germany since 2013. |\n| [**HostBend**](https://hostbend.com/) | HostBend offers a variety of solutions for developers, students, and others who have a tight budget but don't want to compromise quality and support. |\n-| [**Capitol Hosting Solutions**](https://capitolsolutions.cloud/) | CHS is *the* budget friendly hosting company for Australian and American gamers, offering a variety of plans from Web Hosting to Game Servers; Custom Solutions too! |\n+| [**Capitol Hosting Solutions**](https://chs.gg/) | CHS is *the* budget friendly hosting company for Australian and American gamers, offering a variety of plans from Web Hosting to Game Servers; Custom Solutions too! |\n| [**ByteAnia**](https://byteania.com/?utm_source=pterodactyl) | ByteAnia offers the best performing and most affordable **Ryzen 5000 Series hosting** on the market for *unbeatable prices*! |\n| [**Aussie Server Hosts**](https://aussieserverhosts.com/) | No frills Australian Owned and operated High Performance Server hosting for some of the most demanding games serving Australia and New Zealand. |\n| [**VibeGAMES**](https://vibegames.net/) | VibeGAMES is a game server provider that specializes in DDOS protection for the games we offer. We have multiple locations in the US, Brazil, France, Germany, Singapore, Australia and South Africa.|\n" } ]
Go
MIT License
pterodactyl/wings
Update CHS Primary Link to chs.gg (#107) Update CHS Primary Link to chs.gg
532,331
15.11.2021 12:56:43
18,000
66eb993afa61c4a14f1ea71fb64e2525b2d4f9a9
Update diagnostics command
[ { "change_type": "MODIFY", "old_path": "cmd/diagnostics.go", "new_path": "cmd/diagnostics.go", "diff": "@@ -78,7 +78,7 @@ func diagnosticsCmdRun(cmd *cobra.Command, args []string) {\n{\nName: \"ReviewBeforeUpload\",\nPrompt: &survey.Confirm{\n- Message: \"Do you want to review the collected data before uploading to hastebin.com?\",\n+ Message: \"Do you want to review the collected data before uploading to \" + diagnosticsArgs.HastebinURL + \"?\",\nHelp: \"The data, especially the logs, might contain sensitive information, so you should review it. You will be asked again if you want to upload.\",\nDefault: true,\n},\n@@ -96,7 +96,7 @@ func diagnosticsCmdRun(cmd *cobra.Command, args []string) {\noutput := &strings.Builder{}\nfmt.Fprintln(output, \"Pterodactyl Wings - Diagnostics Report\")\nprintHeader(output, \"Versions\")\n- fmt.Fprintln(output, \" wings:\", system.Version)\n+ fmt.Fprintln(output, \" Wings:\", system.Version)\nif dockerErr == nil {\nfmt.Fprintln(output, \" Docker:\", dockerVersion.Version)\n}\n" } ]
Go
MIT License
pterodactyl/wings
Update diagnostics command (#108) Co-authored-by: Matthew Penner <[email protected]>
532,325
17.01.2022 21:55:13
18,000
cdb86abac1eb48bf57f7e3a041a4d89f85bcb4b6
RPM is now tracking v1.5.3
[ { "change_type": "MODIFY", "old_path": "rpm/ptero-wings.spec", "new_path": "rpm/ptero-wings.spec", "diff": "Name: ptero-wings\n-Version: 1.5.0\n+Version: 1.5.3\nRelease: 1%{?dist}\nSummary: The server control plane for Pterodactyl Panel. Written from the ground-up with security, speed, and stability in mind.\nBuildArch: x86_64\n@@ -91,6 +91,13 @@ rm -rf /var/log/pterodactyl\nwings --version\n%changelog\n+* Wed Oct 27 2021 Capitol Hosting Solutions Systems Engineering <[email protected]> - 1.5.3-1\n+- specfile by Capitol Hosting Solutions, Upstream by Pterodactyl\n+- Rebased for https://github.com/pterodactyl/wings/releases/tag/v1.5.3\n+- Fixes improper event registration and error handling during socket authentication that would cause the incorrect error message to be returned to the client, or no error in some scenarios. Event registration is now delayed until the socket is fully authenticated to ensure needless listeners are not registed.\n+- Fixes dollar signs always being evaluated as environment variables with no way to escape them. They can now be escaped as $$ which will transform into a single dollar sign.\n+- A websocket connection to a server will be closed by Wings if there is a send error encountered and the client will be left to handle reconnections, rather than simply logging the error and continuing to listen for new events.\n+\n* Sun Sep 12 2021 Capitol Hosting Solutions Systems Engineering <[email protected]> - 1.5.0-1\n- specfile by Capitol Hosting Solutions, Upstream by Pterodactyl\n- Rebased for https://github.com/pterodactyl/wings/releases/tag/v1.5.0\n" } ]
Go
MIT License
pterodactyl/wings
RPM is now tracking v1.5.3 (#109)
532,318
17.01.2022 18:55:29
28,800
ed4d903f21ad633d41de896f3656127519fa1700
Redacts redacted info from all
[ { "change_type": "MODIFY", "old_path": "cmd/diagnostics.go", "new_path": "cmd/diagnostics.go", "diff": "@@ -188,6 +188,16 @@ func diagnosticsCmdRun(cmd *cobra.Command, args []string) {\nsurvey.AskOne(&survey.Confirm{Message: \"Upload to \" + diagnosticsArgs.HastebinURL + \"?\", Default: false}, &upload)\n}\nif upload {\n+ if !diagnosticsArgs.IncludeEndpoints {\n+ s := output.String()\n+ output.Reset()\n+ a := strings.ReplaceAll(cfg.PanelLocation, s, \"{redacted}\")\n+ a = strings.ReplaceAll(cfg.Api.Host, a, \"{redacted}\")\n+ a = strings.ReplaceAll(cfg.Api.Ssl.CertificateFile, a, \"{redacted}\")\n+ a = strings.ReplaceAll(cfg.Api.Ssl.KeyFile, a, \"{redacted}\")\n+ a = strings.ReplaceAll(cfg.System.Sftp.Address, a, \"{redacted}\")\n+ output.WriteString(a)\n+ }\nu, err := uploadToHastebin(diagnosticsArgs.HastebinURL, output.String())\nif err == nil {\nfmt.Println(\"Your report is available here: \", u)\n" } ]
Go
MIT License
pterodactyl/wings
Redacts redacted info from all (#112)
532,317
18.01.2022 11:22:13
-28,800
521cc2aef281ca12409cfeae79ee443e11fcf1e6
Don't turn SSL into lowercase
[ { "change_type": "MODIFY", "old_path": "cmd/root.go", "new_path": "cmd/root.go", "diff": "@@ -355,7 +355,7 @@ func rootCmdRun(cmd *cobra.Command, _ []string) {\n// Check if main http server should run with TLS. Otherwise reset the TLS\n// config on the server and then serve it over normal HTTP.\nif api.Ssl.Enabled {\n- if err := s.ListenAndServeTLS(strings.ToLower(api.Ssl.CertificateFile), strings.ToLower(api.Ssl.KeyFile)); err != nil {\n+ if err := s.ListenAndServeTLS(api.Ssl.CertificateFile, api.Ssl.KeyFile); err != nil {\nlog.WithFields(log.Fields{\"auto_tls\": false, \"error\": err}).Fatal(\"failed to configure HTTPS server\")\n}\nreturn\n" }, { "change_type": "MODIFY", "old_path": "router/router_system.go", "new_path": "router/router_system.go", "diff": "@@ -103,15 +103,17 @@ func postUpdateConfiguration(c *gin.Context) {\nif err := c.BindJSON(&cfg); err != nil {\nreturn\n}\n+\n// Keep the SSL certificates the same since the Panel will send through Lets Encrypt\n// default locations. However, if we picked a different location manually we don't\n// want to override that.\n//\n// If you pass through manual locations in the API call this logic will be skipped.\nif strings.HasPrefix(cfg.Api.Ssl.KeyFile, \"/etc/letsencrypt/live/\") {\n- cfg.Api.Ssl.KeyFile = strings.ToLower(config.Get().Api.Ssl.KeyFile)\n- cfg.Api.Ssl.CertificateFile = strings.ToLower(config.Get().Api.Ssl.CertificateFile)\n+ cfg.Api.Ssl.KeyFile = config.Get().Api.Ssl.KeyFile\n+ cfg.Api.Ssl.CertificateFile = config.Get().Api.Ssl.CertificateFile\n}\n+\n// Try to write this new configuration to the disk before updating our global\n// state with it.\nif err := config.WriteToDisk(cfg); err != nil {\n" } ]
Go
MIT License
pterodactyl/wings
Don't turn SSL into lowercase (#114)
532,311
07.05.2022 15:23:56
14,400
6c98a955e3f9220b28e47145a7f3bf9b3d81b9e2
Only set cpu limits if specified; closes pterodactyl/panel#3988
[ { "change_type": "MODIFY", "old_path": "environment/docker/container.go", "new_path": "environment/docker/container.go", "diff": "@@ -480,21 +480,3 @@ func (e *Environment) convertMounts() []mount.Mount {\nreturn out\n}\n-\n-func (e *Environment) resources() container.Resources {\n- l := e.Configuration.Limits()\n- pids := l.ProcessLimit()\n-\n- return container.Resources{\n- Memory: l.BoundedMemoryLimit(),\n- MemoryReservation: l.MemoryLimit * 1_000_000,\n- MemorySwap: l.ConvertedSwap(),\n- CPUQuota: l.ConvertedCpuLimit(),\n- CPUPeriod: 100_000,\n- CPUShares: 1024,\n- BlkioWeight: l.IoWeight,\n- OomKillDisable: &l.OOMDisabled,\n- CpusetCpus: l.Threads,\n- PidsLimit: &pids,\n- }\n-}\n" }, { "change_type": "MODIFY", "old_path": "environment/settings.go", "new_path": "environment/settings.go", "diff": "@@ -99,21 +99,36 @@ func (l Limits) ProcessLimit() int64 {\nreturn config.Get().Docker.ContainerPidLimit\n}\n+// AsContainerResources returns the available resources for a container in a format\n+// that Docker understands.\nfunc (l Limits) AsContainerResources() container.Resources {\npids := l.ProcessLimit()\n-\n- return container.Resources{\n+ resources := container.Resources{\nMemory: l.BoundedMemoryLimit(),\nMemoryReservation: l.MemoryLimit * 1_000_000,\nMemorySwap: l.ConvertedSwap(),\n- CPUQuota: l.ConvertedCpuLimit(),\n- CPUPeriod: 100_000,\n- CPUShares: 1024,\nBlkioWeight: l.IoWeight,\nOomKillDisable: &l.OOMDisabled,\n- CpusetCpus: l.Threads,\nPidsLimit: &pids,\n}\n+\n+ // If the CPU Limit is not set, don't send any of these fields through. Providing\n+ // them seems to break some Java services that try to read the available processors.\n+ //\n+ // @see https://github.com/pterodactyl/panel/issues/3988\n+ if l.CpuLimit > 0 {\n+ resources.CPUQuota = l.CpuLimit * 1_000\n+ resources.CPUPeriod = 100_00\n+ resources.CPUShares = 1024\n+ }\n+\n+ // Similar to above, don't set the specific assigned CPUs if we didn't actually limit\n+ // the server to any of them.\n+ if l.Threads != \"\" {\n+ resources.CpusetCpus = l.Threads\n+ }\n+\n+ return resources\n}\ntype Variables map[string]interface{}\n" } ]
Go
MIT License
pterodactyl/wings
Only set cpu limits if specified; closes pterodactyl/panel#3988
532,311
07.05.2022 15:53:08
14,400
1d197714dfdc759d41128ff17d5d7576a75868c4
Fix faulty handling of named pipes; closes pterodactyl/panel#4059
[ { "change_type": "MODIFY", "old_path": "router/router_server_files.go", "new_path": "router/router_server_files.go", "diff": "@@ -37,6 +37,15 @@ func getServerFileContents(c *gin.Context) {\nreturn\n}\ndefer f.Close()\n+ // Don't allow a named pipe to be opened.\n+ //\n+ // @see https://github.com/pterodactyl/panel/issues/4059\n+ if st.Mode()&os.ModeNamedPipe != 0 {\n+ c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{\n+ \"error\": \"Cannot open files of this type.\",\n+ })\n+ return\n+ }\nc.Header(\"X-Mime-Type\", st.Mimetype)\nc.Header(\"Content-Length\", strconv.Itoa(int(st.Size())))\n" }, { "change_type": "MODIFY", "old_path": "server/filesystem/filesystem_test.go", "new_path": "server/filesystem/filesystem_test.go", "diff": "package filesystem\nimport (\n+ \"bufio\"\n\"bytes\"\n\"errors\"\n\"math/rand\"\n@@ -44,6 +45,14 @@ type rootFs struct {\nroot string\n}\n+func getFileContent(file *os.File) string {\n+ var w bytes.Buffer\n+ if _, err := bufio.NewReader(file).WriteTo(&w); err != nil {\n+ panic(err)\n+ }\n+ return w.String()\n+}\n+\nfunc (rfs *rootFs) CreateServerFile(p string, c []byte) error {\nf, err := os.Create(filepath.Join(rfs.root, \"/server\", p))\n@@ -75,54 +84,6 @@ func (rfs *rootFs) reset() {\n}\n}\n-func TestFilesystem_Readfile(t *testing.T) {\n- g := Goblin(t)\n- fs, rfs := NewFs()\n-\n- g.Describe(\"Readfile\", func() {\n- buf := &bytes.Buffer{}\n-\n- g.It(\"opens a file if it exists on the system\", func() {\n- err := rfs.CreateServerFileFromString(\"test.txt\", \"testing\")\n- g.Assert(err).IsNil()\n-\n- err = fs.Readfile(\"test.txt\", buf)\n- g.Assert(err).IsNil()\n- g.Assert(buf.String()).Equal(\"testing\")\n- })\n-\n- g.It(\"returns an error if the file does not exist\", func() {\n- err := fs.Readfile(\"test.txt\", buf)\n- g.Assert(err).IsNotNil()\n- g.Assert(errors.Is(err, os.ErrNotExist)).IsTrue()\n- })\n-\n- g.It(\"returns an error if the \\\"file\\\" is a directory\", func() {\n- err := os.Mkdir(filepath.Join(rfs.root, \"/server/test.txt\"), 0o755)\n- g.Assert(err).IsNil()\n-\n- err = fs.Readfile(\"test.txt\", buf)\n- g.Assert(err).IsNotNil()\n- g.Assert(IsErrorCode(err, ErrCodeIsDirectory)).IsTrue()\n- })\n-\n- g.It(\"cannot open a file outside the root directory\", func() {\n- err := rfs.CreateServerFileFromString(\"/../test.txt\", \"testing\")\n- g.Assert(err).IsNil()\n-\n- err = fs.Readfile(\"/../test.txt\", buf)\n- g.Assert(err).IsNotNil()\n- g.Assert(IsErrorCode(err, ErrCodePathResolution)).IsTrue()\n- })\n-\n- g.AfterEach(func() {\n- buf.Truncate(0)\n- atomic.StoreInt64(&fs.diskUsed, 0)\n- rfs.reset()\n- })\n- })\n-}\n-\nfunc TestFilesystem_Writefile(t *testing.T) {\ng := Goblin(t)\nfs, rfs := NewFs()\n@@ -140,9 +101,10 @@ func TestFilesystem_Writefile(t *testing.T) {\nerr := fs.Writefile(\"test.txt\", r)\ng.Assert(err).IsNil()\n- err = fs.Readfile(\"test.txt\", buf)\n+ f, _, err := fs.File(\"test.txt\")\ng.Assert(err).IsNil()\n- g.Assert(buf.String()).Equal(\"test file content\")\n+ defer f.Close()\n+ g.Assert(getFileContent(f)).Equal(\"test file content\")\ng.Assert(atomic.LoadInt64(&fs.diskUsed)).Equal(r.Size())\n})\n@@ -152,9 +114,10 @@ func TestFilesystem_Writefile(t *testing.T) {\nerr := fs.Writefile(\"/some/nested/test.txt\", r)\ng.Assert(err).IsNil()\n- err = fs.Readfile(\"/some/nested/test.txt\", buf)\n+ f, _, err := fs.File(\"/some/nested/test.txt\")\ng.Assert(err).IsNil()\n- g.Assert(buf.String()).Equal(\"test file content\")\n+ defer f.Close()\n+ g.Assert(getFileContent(f)).Equal(\"test file content\")\n})\ng.It(\"can create a new file inside a nested directory without a trailing slash\", func() {\n@@ -163,9 +126,10 @@ func TestFilesystem_Writefile(t *testing.T) {\nerr := fs.Writefile(\"some/../foo/bar/test.txt\", r)\ng.Assert(err).IsNil()\n- err = fs.Readfile(\"foo/bar/test.txt\", buf)\n+ f, _, err := fs.File(\"foo/bar/test.txt\")\ng.Assert(err).IsNil()\n- g.Assert(buf.String()).Equal(\"test file content\")\n+ defer f.Close()\n+ g.Assert(getFileContent(f)).Equal(\"test file content\")\n})\ng.It(\"cannot create a file outside the root directory\", func() {\n@@ -190,28 +154,6 @@ func TestFilesystem_Writefile(t *testing.T) {\ng.Assert(IsErrorCode(err, ErrCodeDiskSpace)).IsTrue()\n})\n- /*g.It(\"updates the total space used when a file is appended to\", func() {\n- atomic.StoreInt64(&fs.diskUsed, 100)\n-\n- b := make([]byte, 100)\n- _, _ = rand.Read(b)\n-\n- r := bytes.NewReader(b)\n- err := fs.Writefile(\"test.txt\", r)\n- g.Assert(err).IsNil()\n- g.Assert(atomic.LoadInt64(&fs.diskUsed)).Equal(int64(200))\n-\n- // If we write less data than already exists, we should expect the total\n- // disk used to be decremented.\n- b = make([]byte, 50)\n- _, _ = rand.Read(b)\n-\n- r = bytes.NewReader(b)\n- err = fs.Writefile(\"test.txt\", r)\n- g.Assert(err).IsNil()\n- g.Assert(atomic.LoadInt64(&fs.diskUsed)).Equal(int64(150))\n- })*/\n-\ng.It(\"truncates the file when writing new contents\", func() {\nr := bytes.NewReader([]byte(\"original data\"))\nerr := fs.Writefile(\"test.txt\", r)\n@@ -221,9 +163,10 @@ func TestFilesystem_Writefile(t *testing.T) {\nerr = fs.Writefile(\"test.txt\", r)\ng.Assert(err).IsNil()\n- err = fs.Readfile(\"test.txt\", buf)\n+ f, _, err := fs.File(\"test.txt\")\ng.Assert(err).IsNil()\n- g.Assert(buf.String()).Equal(\"new data\")\n+ defer f.Close()\n+ g.Assert(getFileContent(f)).Equal(\"new data\")\n})\ng.AfterEach(func() {\n" }, { "change_type": "MODIFY", "old_path": "server/filesystem/path_test.go", "new_path": "server/filesystem/path_test.go", "diff": "@@ -119,16 +119,6 @@ func TestFilesystem_Blocks_Symlinks(t *testing.T) {\npanic(err)\n}\n- g.Describe(\"Readfile\", func() {\n- g.It(\"cannot read a file symlinked outside the root\", func() {\n- b := bytes.Buffer{}\n-\n- err := fs.Readfile(\"symlinked.txt\", &b)\n- g.Assert(err).IsNotNil()\n- g.Assert(IsErrorCode(err, ErrCodePathResolution)).IsTrue()\n- })\n- })\n-\ng.Describe(\"Writefile\", func() {\ng.It(\"cannot write to a file symlinked outside the root\", func() {\nr := bytes.NewReader([]byte(\"testing\"))\n" } ]
Go
MIT License
pterodactyl/wings
Fix faulty handling of named pipes; closes pterodactyl/panel#4059
532,311
12.05.2022 18:00:55
14,400
37e4d57cdf4ad7fdd3d42aa8819694183007f225
Don't include files and folders with identical name prefixes when archiving; closes pterodactyl/panel#3946
[ { "change_type": "MODIFY", "old_path": "server/filesystem/archive.go", "new_path": "server/filesystem/archive.go", "diff": "@@ -130,7 +130,7 @@ func (a *Archive) withFilesCallback(tw *tar.Writer) func(path string, de *godirw\nfor _, f := range a.Files {\n// If the given doesn't match, or doesn't have the same prefix continue\n// to the next item in the loop.\n- if p != f && !strings.HasPrefix(p, f) {\n+ if p != f && !strings.HasPrefix(strings.TrimSuffix(p, \"/\")+\"/\", f) {\ncontinue\n}\n" } ]
Go
MIT License
pterodactyl/wings
Don't include files and folders with identical name prefixes when archiving; closes pterodactyl/panel#3946
532,311
15.05.2022 16:01:52
14,400
5bcf4164fb8633b9537debaca7980d5ae85aa93a
Add support for public key based auth
[ { "change_type": "MODIFY", "old_path": "remote/types.go", "new_path": "remote/types.go", "diff": "@@ -11,6 +11,11 @@ import (\n\"github.com/pterodactyl/wings/parser\"\n)\n+const (\n+ SftpAuthPassword = SftpAuthRequestType(\"password\")\n+ SftpAuthPublicKey = SftpAuthRequestType(\"public_key\")\n+)\n+\n// A generic type allowing for easy binding use when making requests to API\n// endpoints that only expect a singular argument or something that would not\n// benefit from being a typed struct.\n@@ -63,9 +68,12 @@ type RawServerData struct {\nProcessConfiguration json.RawMessage `json:\"process_configuration\"`\n}\n+type SftpAuthRequestType string\n+\n// SftpAuthRequest defines the request details that are passed along to the Panel\n// when determining if the credentials provided to Wings are valid.\ntype SftpAuthRequest struct {\n+ Type SftpAuthRequestType `json:\"type\"`\nUser string `json:\"username\"`\nPass string `json:\"password\"`\nIP string `json:\"ip\"`\n@@ -79,7 +87,7 @@ type SftpAuthRequest struct {\n// user for the SFTP subsystem.\ntype SftpAuthResponse struct {\nServer string `json:\"server\"`\n- Token string `json:\"token\"`\n+ PublicKeys []string `json:\"public_keys\"`\nPermissions []string `json:\"permissions\"`\n}\n" }, { "change_type": "MODIFY", "old_path": "sftp/server.go", "new_path": "sftp/server.go", "diff": "@@ -70,7 +70,12 @@ func (c *SFTPServer) Run() error {\nconf := &ssh.ServerConfig{\nNoClientAuth: false,\nMaxAuthTries: 6,\n- PasswordCallback: c.passwordCallback,\n+ PasswordCallback: func(conn ssh.ConnMetadata, password []byte) (*ssh.Permissions, error) {\n+ return c.makeCredentialsRequest(conn, remote.SftpAuthPassword, string(password))\n+ },\n+ PublicKeyCallback: func(conn ssh.ConnMetadata, key ssh.PublicKey) (*ssh.Permissions, error) {\n+ return c.makeCredentialsRequest(conn, remote.SftpAuthPublicKey, string(key.Marshal()))\n+ },\n}\nconf.AddHostKey(private)\n@@ -177,17 +182,17 @@ func (c *SFTPServer) generateED25519PrivateKey() error {\nreturn nil\n}\n-// A function capable of validating user credentials with the Panel API.\n-func (c *SFTPServer) passwordCallback(conn ssh.ConnMetadata, pass []byte) (*ssh.Permissions, error) {\n+func (c *SFTPServer) makeCredentialsRequest(conn ssh.ConnMetadata, t remote.SftpAuthRequestType, p string) (*ssh.Permissions, error) {\nrequest := remote.SftpAuthRequest{\n+ Type: t,\nUser: conn.User(),\n- Pass: string(pass),\n+ Pass: p,\nIP: conn.RemoteAddr().String(),\nSessionID: conn.SessionID(),\nClientVersion: conn.ClientVersion(),\n}\n- logger := log.WithFields(log.Fields{\"subsystem\": \"sftp\", \"username\": conn.User(), \"ip\": conn.RemoteAddr().String()})\n+ logger := log.WithFields(log.Fields{\"subsystem\": \"sftp\", \"method\": request.Type, \"username\": request.User, \"ip\": request.IP})\nlogger.Debug(\"validating credentials for SFTP connection\")\nif !validUsernameRegexp.MatchString(request.User) {\n@@ -206,7 +211,7 @@ func (c *SFTPServer) passwordCallback(conn ssh.ConnMetadata, pass []byte) (*ssh.\n}\nlogger.WithField(\"server\", resp.Server).Debug(\"credentials validated and matched to server instance\")\n- sshPerm := &ssh.Permissions{\n+ permissions := ssh.Permissions{\nExtensions: map[string]string{\n\"uuid\": resp.Server,\n\"user\": conn.User(),\n@@ -214,7 +219,7 @@ func (c *SFTPServer) passwordCallback(conn ssh.ConnMetadata, pass []byte) (*ssh.\n},\n}\n- return sshPerm, nil\n+ return &permissions, nil\n}\n// PrivateKeyPath returns the path the host private key for this server instance.\n" } ]
Go
MIT License
pterodactyl/wings
Add support for public key based auth
532,311
15.05.2022 16:17:06
14,400
1927a59cd0c3f80937564564014f45dd7c2c7bd6
Send key correctly; don't retry 4xx errors
[ { "change_type": "MODIFY", "old_path": "remote/http.go", "new_path": "remote/http.go", "diff": "@@ -142,12 +142,10 @@ func (c *client) request(ctx context.Context, method, path string, body io.Reade\nif r.HasError() {\n// Close the request body after returning the error to free up resources.\ndefer r.Body.Close()\n- // Don't keep spamming the endpoint if we've already made too many requests or\n- // if we're not even authenticated correctly. Retrying generally won't fix either\n- // of these issues.\n- if r.StatusCode == http.StatusForbidden ||\n- r.StatusCode == http.StatusTooManyRequests ||\n- r.StatusCode == http.StatusUnauthorized {\n+ // Don't keep attempting to access this endpoint if the response is a 4XX\n+ // level error which indicates a client mistake. Only retry when the error\n+ // is due to a server issue (5XX error).\n+ if r.StatusCode >= 400 && r.StatusCode < 500 {\nreturn backoff.Permanent(r.Error())\n}\nreturn r.Error()\n" }, { "change_type": "MODIFY", "old_path": "sftp/server.go", "new_path": "sftp/server.go", "diff": "@@ -74,7 +74,7 @@ func (c *SFTPServer) Run() error {\nreturn c.makeCredentialsRequest(conn, remote.SftpAuthPassword, string(password))\n},\nPublicKeyCallback: func(conn ssh.ConnMetadata, key ssh.PublicKey) (*ssh.Permissions, error) {\n- return c.makeCredentialsRequest(conn, remote.SftpAuthPublicKey, string(key.Marshal()))\n+ return c.makeCredentialsRequest(conn, remote.SftpAuthPublicKey, string(ssh.MarshalAuthorizedKey(key)))\n},\n}\nconf.AddHostKey(private)\n" } ]
Go
MIT License
pterodactyl/wings
Send key correctly; don't retry 4xx errors
532,311
15.05.2022 16:41:26
14,400
5df1acd10ea20476f24f917de30697fc8be931ce
We don't return public keys
[ { "change_type": "MODIFY", "old_path": "remote/types.go", "new_path": "remote/types.go", "diff": "@@ -87,7 +87,6 @@ type SftpAuthRequest struct {\n// user for the SFTP subsystem.\ntype SftpAuthResponse struct {\nServer string `json:\"server\"`\n- PublicKeys []string `json:\"public_keys\"`\nPermissions []string `json:\"permissions\"`\n}\n" } ]
Go
MIT License
pterodactyl/wings
We don't return public keys
532,311
21.05.2022 17:01:12
14,400
f390784973fe5124fff216c5daf8bfb916fb829e
Include error in log output if one occurs during move
[ { "change_type": "MODIFY", "old_path": "router/router_server_files.go", "new_path": "router/router_server_files.go", "diff": "@@ -131,6 +131,10 @@ func putServerRenameFiles(c *gin.Context) {\n// Return nil if the error is an is not exists.\n// NOTE: os.IsNotExist() does not work if the error is wrapped.\nif errors.Is(err, os.ErrNotExist) {\n+ s.Log().WithField(\"error\", err).\n+ WithField(\"from_path\", pf).\n+ WithField(\"to_path\", pt).\n+ Warn(\"failed to rename: source or target does not exist\")\nreturn nil\n}\nreturn err\n" }, { "change_type": "MODIFY", "old_path": "server/filesystem/filesystem.go", "new_path": "server/filesystem/filesystem.go", "diff": "@@ -171,16 +171,16 @@ func (fs *Filesystem) CreateDirectory(name string, p string) error {\nreturn os.MkdirAll(cleaned, 0o755)\n}\n-// Moves (or renames) a file or directory.\n+// Rename moves (or renames) a file or directory.\nfunc (fs *Filesystem) Rename(from string, to string) error {\ncleanedFrom, err := fs.SafePath(from)\nif err != nil {\n- return err\n+ return errors.WithStack(err)\n}\ncleanedTo, err := fs.SafePath(to)\nif err != nil {\n- return err\n+ return errors.WithStack(err)\n}\n// If the target file or directory already exists the rename function will fail, so just\n@@ -202,7 +202,10 @@ func (fs *Filesystem) Rename(from string, to string) error {\n}\n}\n- return os.Rename(cleanedFrom, cleanedTo)\n+ if err := os.Rename(cleanedFrom, cleanedTo); err != nil {\n+ return errors.WithStack(err)\n+ }\n+ return nil\n}\n// Recursively iterates over a file or directory and sets the permissions on all of the\n" } ]
Go
MIT License
pterodactyl/wings
Include error in log output if one occurs during move
532,311
29.05.2022 21:48:49
14,400
7fa7cc313fbdce5bbe67cf0ccbf5a2f713d89279
Fix permissions not being checked correctly for admins
[ { "change_type": "MODIFY", "old_path": "CHANGELOG.md", "new_path": "CHANGELOG.md", "diff": "# Changelog\n+## v1.6.3\n+### Fixed\n+* Fixes SFTP authentication failing for administrative users due to a permissions adjustment on the Panel.\n+\n## v1.6.2\n### Fixed\n* Fixes file upload size not being properly enforced.\n" }, { "change_type": "MODIFY", "old_path": "sftp/handler.go", "new_path": "sftp/handler.go", "diff": "@@ -288,14 +288,10 @@ func (h *Handler) can(permission string) bool {\nreturn false\n}\n- // SFTPServer owners and super admins have their permissions returned as '[*]' via the Panel\n- // API, so for the sake of speed do an initial check for that before iterating over the\n- // entire array of permissions.\n- if len(h.permissions) == 1 && h.permissions[0] == \"*\" {\n- return true\n- }\nfor _, p := range h.permissions {\n- if p == permission {\n+ // If we match the permission specifically, or the user has been granted the \"*\"\n+ // permission because they're an admin, let them through.\n+ if p == permission || p == \"*\" {\nreturn true\n}\n}\n" } ]
Go
MIT License
pterodactyl/wings
Fix permissions not being checked correctly for admins
532,311
30.05.2022 17:45:41
14,400
203a2091a071cecef4f070df2a149415012d57d9
Use the correct CPU period when throttling servers; closes pterodactyl/panel#4102
[ { "change_type": "MODIFY", "old_path": "environment/settings.go", "new_path": "environment/settings.go", "diff": "@@ -118,7 +118,7 @@ func (l Limits) AsContainerResources() container.Resources {\n// @see https://github.com/pterodactyl/panel/issues/3988\nif l.CpuLimit > 0 {\nresources.CPUQuota = l.CpuLimit * 1_000\n- resources.CPUPeriod = 100_00\n+ resources.CPUPeriod = 100_000\nresources.CPUShares = 1024\n}\n" } ]
Go
MIT License
pterodactyl/wings
Use the correct CPU period when throttling servers; closes pterodactyl/panel#4102
532,311
30.05.2022 18:42:31
14,400
b1be2081eb0599df432c58329a4446aa28bb4f96
Better archive detection logic; try to use reflection as last ditch effort if unmatched closes pterodactyl/panel#4101
[ { "change_type": "MODIFY", "old_path": "server/filesystem/compress.go", "new_path": "server/filesystem/compress.go", "diff": "@@ -5,9 +5,12 @@ import (\n\"archive/zip\"\n\"compress/gzip\"\n\"fmt\"\n+ gzip2 \"github.com/klauspost/compress/gzip\"\n+ zip2 \"github.com/klauspost/compress/zip\"\n\"os\"\n\"path\"\n\"path/filepath\"\n+ \"reflect\"\n\"strings\"\n\"sync/atomic\"\n\"time\"\n@@ -172,13 +175,26 @@ func ExtractNameFromArchive(f archiver.File) string {\nreturn f.Name()\n}\nswitch s := sys.(type) {\n+ case *zip.FileHeader:\n+ return s.Name\n+ case *zip2.FileHeader:\n+ return s.Name\ncase *tar.Header:\nreturn s.Name\ncase *gzip.Header:\nreturn s.Name\n- case *zip.FileHeader:\n+ case *gzip2.Header:\nreturn s.Name\ndefault:\n+ // At this point we cannot figure out what type of archive this might be so\n+ // just try to find the name field in the struct. If it is found return it.\n+ field := reflect.Indirect(reflect.ValueOf(sys)).FieldByName(\"Name\")\n+ if field.IsValid() {\n+ return field.String()\n+ }\n+ // Fallback to the basename of the file at this point. There is nothing we can really\n+ // do to try and figure out what the underlying directory of the file is supposed to\n+ // be since it didn't implement a name field.\nreturn f.Name()\n}\n}\n" } ]
Go
MIT License
pterodactyl/wings
Better archive detection logic; try to use reflection as last ditch effort if unmatched closes pterodactyl/panel#4101
532,310
03.07.2022 11:09:07
14,400
214baf83fb3b38f6b65b3309ebff0e746a24ec32
Fix/arm64 docker * fix: arm64 docker builds Don't hardcode amd64 platform for the Wings binary. * update docker file don't specify buildplatform remove upx as it causes arm64 failures remove goos as the build is on linux hosts.
[ { "change_type": "MODIFY", "old_path": "Dockerfile", "new_path": "Dockerfile", "diff": "# Stage 1 (Build)\n-FROM --platform=$BUILDPLATFORM golang:1.17-alpine AS builder\n+FROM golang:1.17-alpine AS builder\nARG VERSION\n-RUN apk add --update --no-cache git make upx\n+RUN apk add --update --no-cache git make\nWORKDIR /app/\nCOPY go.mod go.sum /app/\nRUN go mod download\nCOPY . /app/\n-RUN CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build \\\n+RUN CGO_ENABLED=0 go build \\\n-ldflags=\"-s -w -X github.com/pterodactyl/wings/system.Version=$VERSION\" \\\n-v \\\n-trimpath \\\n-o wings \\\nwings.go\n-RUN upx wings\nRUN echo \"ID=\\\"distroless\\\"\" > /etc/os-release\n# Stage 2 (Final)\n" } ]
Go
MIT License
pterodactyl/wings
Fix/arm64 docker (#133) * fix: arm64 docker builds Don't hardcode amd64 platform for the Wings binary. * update docker file don't specify buildplatform remove upx as it causes arm64 failures remove goos as the build is on linux hosts. Co-authored-by: softwarenoob <[email protected]>
532,311
09.07.2022 17:52:59
14,400
dda7d10d37b1abd64cd26bf4ecf5ed267093a8fc
Use the natural panel event names
[ { "change_type": "MODIFY", "old_path": "server/activity.go", "new_path": "server/activity.go", "diff": "@@ -13,10 +13,10 @@ import (\ntype Event string\ntype ActivityMeta map[string]interface{}\n-const ActivityPowerPrefix = \"power_\"\n+const ActivityPowerPrefix = \"server:power.\"\nconst (\n- ActivityConsoleCommand = Event(\"console_command\")\n+ ActivityConsoleCommand = Event(\"server:console.command\")\n)\nvar ipTrimRegex = regexp.MustCompile(`(:\\d*)?$`)\n" } ]
Go
MIT License
pterodactyl/wings
Use the natural panel event names
532,324
10.07.2022 00:08:52
-7,200
204a4375fc5cf0213f628b7cb3c1f2cb520c848c
Make the Docker network MTU configurable
[ { "change_type": "MODIFY", "old_path": "config/config_docker.go", "new_path": "config/config_docker.go", "diff": "@@ -36,6 +36,7 @@ type DockerNetworkConfiguration struct {\nMode string `default:\"pterodactyl_nw\" yaml:\"network_mode\"`\nIsInternal bool `default:\"false\" yaml:\"is_internal\"`\nEnableICC bool `default:\"true\" yaml:\"enable_icc\"`\n+ NetworkMTU int64 `default:\"1500\" yaml:\"network_mtu\"`\nInterfaces dockerNetworkInterfaces `yaml:\"interfaces\"`\n}\n" }, { "change_type": "MODIFY", "old_path": "environment/docker.go", "new_path": "environment/docker.go", "diff": "@@ -92,7 +92,7 @@ func createDockerNetwork(ctx context.Context, cli *client.Client) error {\n\"com.docker.network.bridge.enable_ip_masquerade\": \"true\",\n\"com.docker.network.bridge.host_binding_ipv4\": \"0.0.0.0\",\n\"com.docker.network.bridge.name\": \"pterodactyl0\",\n- \"com.docker.network.driver.mtu\": \"1500\",\n+ \"com.docker.network.driver.mtu\": strconv.FormatInt(nw.NetworkMTU, 10),\n},\n})\nif err != nil {\n" } ]
Go
MIT License
pterodactyl/wings
Make the Docker network MTU configurable (#130)
532,311
09.07.2022 19:37:39
14,400
59fbd2bceaf3c729b19b5880f6b0e2247e17a226
Add initial niaeve implementation of SFTP logging This will end up flooding the activity logs due to the way SFTP works, we'll need to have an intermediate step in Wings that batches events every 10 seconds or so and submits them as a single "event" for activity.
[ { "change_type": "MODIFY", "old_path": "internal/cron/activity_cron.go", "new_path": "internal/cron/activity_cron.go", "diff": "@@ -18,6 +18,7 @@ func processActivityLogs(m *server.Manager, c int64) error {\n// Don't execute this cron if there is currently one running. Once this task is completed\n// go ahead and mark it as no longer running.\nif !processing.SwapIf(true) {\n+ log.WithField(\"subsystem\", \"cron\").Warn(\"cron: process overlap detected, skipping this run\")\nreturn nil\n}\ndefer processing.Store(false)\n" }, { "change_type": "MODIFY", "old_path": "internal/cron/cron.go", "new_path": "internal/cron/cron.go", "diff": "@@ -26,7 +26,7 @@ func Scheduler(m *server.Manager) (*gocron.Scheduler, error) {\n}\ns := gocron.NewScheduler(l)\n- _, _ = s.Tag(\"activity\").Every(config.Get().System.ActivitySendInterval).Seconds().Do(func() {\n+ _, _ = s.Tag(\"activity\").Every(int(config.Get().System.ActivitySendInterval)).Seconds().Do(func() {\nif err := processActivityLogs(m, config.Get().System.ActivitySendCount); err != nil {\nlog.WithField(\"error\", err).Error(\"cron: failed to process activity events\")\n}\n" }, { "change_type": "MODIFY", "old_path": "remote/types.go", "new_path": "remote/types.go", "diff": "@@ -86,6 +86,7 @@ type SftpAuthRequest struct {\n// user for the SFTP subsystem.\ntype SftpAuthResponse struct {\nServer string `json:\"server\"`\n+ User string `json:\"user\"`\nPermissions []string `json:\"permissions\"`\n}\n" }, { "change_type": "MODIFY", "old_path": "server/activity.go", "new_path": "server/activity.go", "diff": "@@ -17,6 +17,11 @@ const ActivityPowerPrefix = \"server:power.\"\nconst (\nActivityConsoleCommand = Event(\"server:console.command\")\n+ ActivityFileDeleted = Event(\"server:file.delete\")\n+ ActivityFileRename = Event(\"server:file.rename\")\n+ ActivityFileCreateDirectory = Event(\"server:file.create-directory\")\n+ ActivityFileWrite = Event(\"server:file.write\")\n+ ActivityFileRead = Event(\"server:file.read\")\n)\nvar ipTrimRegex = regexp.MustCompile(`(:\\d*)?$`)\n" }, { "change_type": "MODIFY", "old_path": "sftp/server.go", "new_path": "sftp/server.go", "diff": "@@ -91,19 +91,21 @@ func (c *SFTPServer) Run() error {\nif conn, _ := listener.Accept(); conn != nil {\ngo func(conn net.Conn) {\ndefer conn.Close()\n- c.AcceptInbound(conn, conf)\n+ if err := c.AcceptInbound(conn, conf); err != nil {\n+ log.WithField(\"error\", err).Error(\"sftp: failed to accept inbound connection\")\n+ }\n}(conn)\n}\n}\n}\n-// Handles an inbound connection to the instance and determines if we should serve the\n-// request or not.\n-func (c *SFTPServer) AcceptInbound(conn net.Conn, config *ssh.ServerConfig) {\n+// AcceptInbound handles an inbound connection to the instance and determines if we should\n+// serve the request or not.\n+func (c *SFTPServer) AcceptInbound(conn net.Conn, config *ssh.ServerConfig) error {\n// Before beginning a handshake must be performed on the incoming net.Conn\nsconn, chans, reqs, err := ssh.NewServerConn(conn, config)\nif err != nil {\n- return\n+ return errors.WithStack(err)\n}\ndefer sconn.Close()\ngo ssh.DiscardRequests(reqs)\n@@ -149,13 +151,19 @@ func (c *SFTPServer) AcceptInbound(conn net.Conn, config *ssh.ServerConfig) {\n// Spin up a SFTP server instance for the authenticated user's server allowing\n// them access to the underlying filesystem.\n- handler := sftp.NewRequestServer(channel, NewHandler(sconn, srv).Handlers())\n- if err := handler.Serve(); err == io.EOF {\n- handler.Close()\n+ handler, err := NewHandler(sconn, srv)\n+ if err != nil {\n+ return errors.WithStackIf(err)\n}\n+ rs := sftp.NewRequestServer(channel, handler.Handlers())\n+ if err := rs.Serve(); err == io.EOF {\n+ _ = rs.Close()\n}\n}\n+ return nil\n+}\n+\n// Generates a new ED25519 private key that is used for host authentication when\n// a user connects to the SFTP server.\nfunc (c *SFTPServer) generateED25519PrivateKey() error {\n@@ -213,8 +221,9 @@ func (c *SFTPServer) makeCredentialsRequest(conn ssh.ConnMetadata, t remote.Sftp\nlogger.WithField(\"server\", resp.Server).Debug(\"credentials validated and matched to server instance\")\npermissions := ssh.Permissions{\nExtensions: map[string]string{\n+ \"ip\": conn.RemoteAddr().String(),\n\"uuid\": resp.Server,\n- \"user\": conn.User(),\n+ \"user\": resp.User,\n\"permissions\": strings.Join(resp.Permissions, \",\"),\n},\n}\n" } ]
Go
MIT License
pterodactyl/wings
Add initial niaeve implementation of SFTP logging This will end up flooding the activity logs due to the way SFTP works, we'll need to have an intermediate step in Wings that batches events every 10 seconds or so and submits them as a single "event" for activity.
532,311
10.07.2022 14:30:32
14,400
f28e06267cb8e872d3f8661b1cc046975ac1a155
Better tracking of SFTP events
[ { "change_type": "MODIFY", "old_path": "internal/cron/activity_cron.go", "new_path": "internal/cron/activity_cron.go", "diff": "@@ -12,16 +12,16 @@ import (\n)\nvar key = []byte(\"events\")\n-var processing system.AtomicBool\n+var activityCron system.AtomicBool\nfunc processActivityLogs(m *server.Manager, c int64) error {\n// Don't execute this cron if there is currently one running. Once this task is completed\n// go ahead and mark it as no longer running.\n- if !processing.SwapIf(true) {\n- log.WithField(\"subsystem\", \"cron\").Warn(\"cron: process overlap detected, skipping this run\")\n+ if !activityCron.SwapIf(true) {\n+ log.WithField(\"subsystem\", \"cron\").WithField(\"cron\", \"activity_logs\").Warn(\"cron: process overlap detected, skipping this run\")\nreturn nil\n}\n- defer processing.Store(false)\n+ defer activityCron.Store(false)\nvar list [][]byte\nerr := database.DB().View(func(tx *nutsdb.Tx) error {\n@@ -30,6 +30,9 @@ func processActivityLogs(m *server.Manager, c int64) error {\n// release the lock on this process.\nend := int(c)\nif s, err := tx.LSize(database.ServerActivityBucket, key); err != nil {\n+ if errors.Is(err, nutsdb.ErrBucket) {\n+ return nil\n+ }\nreturn errors.WithStackIf(err)\n} else if s < end || s == 0 {\nif s == 0 {\n" }, { "change_type": "MODIFY", "old_path": "internal/cron/cron.go", "new_path": "internal/cron/cron.go", "diff": "@@ -10,16 +10,17 @@ import (\n\"time\"\n)\n+const ErrCronRunning = errors.Sentinel(\"cron: job already running\")\n+\nvar o system.AtomicBool\n// Scheduler configures the internal cronjob system for Wings and returns the scheduler\n// instance to the caller. This should only be called once per application lifecycle, additional\n// calls will result in an error being returned.\nfunc Scheduler(m *server.Manager) (*gocron.Scheduler, error) {\n- if o.Load() {\n+ if !o.SwapIf(true) {\nreturn nil, errors.New(\"cron: cannot call scheduler more than once in application lifecycle\")\n}\n- o.Store(true)\nl, err := time.LoadLocation(config.Get().System.Timezone)\nif err != nil {\nreturn nil, errors.Wrap(err, \"cron: failed to parse configured system timezone\")\n@@ -32,5 +33,16 @@ func Scheduler(m *server.Manager) (*gocron.Scheduler, error) {\n}\n})\n+ _, _ = s.Tag(\"sftp\").Every(20).Seconds().Do(func() {\n+ runner := sftpEventProcessor{mu: system.NewAtomicBool(false), manager: m}\n+ if err := runner.Run(); err != nil {\n+ if errors.Is(err, ErrCronRunning) {\n+ log.WithField(\"cron\", \"sftp_events\").Warn(\"cron: job already running, skipping...\")\n+ } else {\n+ log.WithField(\"error\", err).Error(\"cron: failed to process sftp events\")\n+ }\n+ }\n+ })\n+\nreturn s, nil\n}\n" }, { "change_type": "ADD", "old_path": null, "new_path": "internal/cron/sftp_cron.go", "diff": "+package cron\n+\n+import (\n+ \"bytes\"\n+ \"emperror.dev/errors\"\n+ \"encoding/gob\"\n+ \"github.com/pterodactyl/wings/internal/database\"\n+ \"github.com/pterodactyl/wings/server\"\n+ \"github.com/pterodactyl/wings/sftp\"\n+ \"github.com/pterodactyl/wings/system\"\n+ \"github.com/xujiajun/nutsdb\"\n+ \"path/filepath\"\n+)\n+\n+type UserDetail struct {\n+ UUID string\n+ IP string\n+}\n+\n+type Users map[UserDetail][]sftp.EventRecord\n+type Events map[sftp.Event]Users\n+\n+type sftpEventProcessor struct {\n+ mu *system.AtomicBool\n+ manager *server.Manager\n+}\n+\n+// Run executes the cronjob and processes sftp activities into normal activity log entries\n+// by merging together similar records. This helps to reduce the sheer amount of data that\n+// gets passed back to the Panel and provides simpler activity logging.\n+func (sep *sftpEventProcessor) Run() error {\n+ if !sep.mu.SwapIf(true) {\n+ return errors.WithStack(ErrCronRunning)\n+ }\n+ defer sep.mu.Store(false)\n+\n+ set, err := sep.Events()\n+ if err != nil {\n+ return err\n+ }\n+\n+ for s, el := range set {\n+ events := make(Events)\n+ // Take all of the events that we've pulled out of the system for every server and then\n+ // parse them into a more usable format in order to create activity log entries for each\n+ // user, ip, and server instance.\n+ for _, e := range el {\n+ u := UserDetail{UUID: e.User, IP: e.IP}\n+ if _, ok := events[e.Event]; !ok {\n+ events[e.Event] = make(Users)\n+ }\n+ if _, ok := events[e.Event][u]; !ok {\n+ events[e.Event][u] = []sftp.EventRecord{}\n+ }\n+ events[e.Event][u] = append(events[e.Event][u], e)\n+ }\n+\n+ // Now that we have all of the events, go ahead and create a normal activity log entry\n+ // for each instance grouped by user & IP for easier Panel reporting.\n+ for k, v := range events {\n+ for u, records := range v {\n+ files := make([]interface{}, len(records))\n+ for i, r := range records {\n+ if r.Action.Target != \"\" {\n+ files[i] = map[string]string{\n+ \"from\": filepath.Clean(r.Action.Entity),\n+ \"to\": filepath.Clean(r.Action.Target),\n+ }\n+ } else {\n+ files[i] = filepath.Clean(r.Action.Entity)\n+ }\n+ }\n+\n+ entry := server.Activity{\n+ Server: s,\n+ User: u.UUID,\n+ Event: server.Event(\"server:sftp.\" + string(k)),\n+ Metadata: server.ActivityMeta{\"files\": files},\n+ IP: u.IP,\n+ // Just assume that the first record in the set is the oldest and the most relevant\n+ // of the timestamps to use.\n+ Timestamp: records[0].Timestamp,\n+ }\n+\n+ if err := entry.Save(); err != nil {\n+ return errors.Wrap(err, \"cron: failed to save new event for server\")\n+ }\n+\n+ if err := sep.Cleanup([]byte(s)); err != nil {\n+ return errors.Wrap(err, \"cron: failed to cleanup events\")\n+ }\n+ }\n+ }\n+ }\n+\n+ return nil\n+}\n+\n+// Cleanup runs through all of the events we have currently tracked in the bucket and removes\n+// them once we've managed to process them and created the associated server activity events.\n+func (sep *sftpEventProcessor) Cleanup(key []byte) error {\n+ return database.DB().Update(func(tx *nutsdb.Tx) error {\n+ s, err := sep.sizeOf(tx, key)\n+ if err != nil {\n+ return err\n+ }\n+ if s == 0 {\n+ return nil\n+ } else if s < sep.limit() {\n+ for i := 0; i < s; i++ {\n+ if _, err := tx.LPop(database.SftpActivityBucket, key); err != nil {\n+ return errors.WithStack(err)\n+ }\n+ }\n+ } else {\n+ if err := tx.LTrim(database.ServerActivityBucket, key, sep.limit()-1, -1); err != nil {\n+ return errors.WithStack(err)\n+ }\n+ }\n+ return nil\n+ })\n+}\n+\n+// Events pulls all of the events in the SFTP event bucket and parses them into an iterable\n+// set allowing Wings to process the events and send them back to the Panel instance.\n+func (sep *sftpEventProcessor) Events() (map[string][]sftp.EventRecord, error) {\n+ set := make(map[string][]sftp.EventRecord, len(sep.manager.Keys()))\n+ err := database.DB().View(func(tx *nutsdb.Tx) error {\n+ for _, k := range sep.manager.Keys() {\n+ lim := sep.limit()\n+ if s, err := sep.sizeOf(tx, []byte(k)); err != nil {\n+ return err\n+ } else if s == 0 {\n+ continue\n+ } else if s < lim {\n+ lim = -1\n+ }\n+ list, err := tx.LRange(database.SftpActivityBucket, []byte(k), 0, lim)\n+ if err != nil {\n+ return errors.WithStack(err)\n+ }\n+ set[k] = make([]sftp.EventRecord, len(list))\n+ for i, l := range list {\n+ if err := gob.NewDecoder(bytes.NewBuffer(l)).Decode(&set[k][i]); err != nil {\n+ return errors.WithStack(err)\n+ }\n+ }\n+ }\n+ return nil\n+ })\n+\n+ return set, err\n+}\n+\n+// sizeOf is a wrapper around a nutsdb transaction to get the size of a key in the\n+// bucket while also accounting for some expected error conditions and handling those\n+// automatically.\n+func (sep *sftpEventProcessor) sizeOf(tx *nutsdb.Tx, key []byte) (int, error) {\n+ s, err := tx.LSize(database.SftpActivityBucket, key)\n+ if err != nil {\n+ if errors.Is(err, nutsdb.ErrBucket) {\n+ return 0, nil\n+ }\n+ return 0, errors.WithStack(err)\n+ }\n+ return s, nil\n+}\n+\n+// limit returns the number of records that are processed for each server at\n+// once. This will then be translated into a variable number of activity log\n+// events, with the worst case being a single event with \"n\" associated files.\n+func (sep *sftpEventProcessor) limit() int {\n+ return 500\n+}\n" }, { "change_type": "MODIFY", "old_path": "internal/database/database.go", "new_path": "internal/database/database.go", "diff": "@@ -14,6 +14,7 @@ var syncer sync.Once\nconst (\nServerActivityBucket = \"server_activity\"\n+ SftpActivityBucket = \"sftp_activity\"\n)\nfunc initialize() error {\n" }, { "change_type": "MODIFY", "old_path": "server/activity.go", "new_path": "server/activity.go", "diff": "@@ -82,6 +82,10 @@ func (ra RequestActivity) IP() string {\nreturn ra.ip\n}\n+func (ra *RequestActivity) User() string {\n+ return ra.user\n+}\n+\n// SetUser clones the RequestActivity struct and sets a new user value on the copy\n// before returning it.\nfunc (ra RequestActivity) SetUser(u string) RequestActivity {\n" }, { "change_type": "MODIFY", "old_path": "server/manager.go", "new_path": "server/manager.go", "diff": "@@ -52,6 +52,24 @@ func (m *Manager) Client() remote.Client {\nreturn m.client\n}\n+// Len returns the count of servers stored in the manager instance.\n+func (m *Manager) Len() int {\n+ m.mu.RLock()\n+ defer m.mu.RUnlock()\n+ return len(m.servers)\n+}\n+\n+// Keys returns all of the server UUIDs stored in the manager set.\n+func (m *Manager) Keys() []string {\n+ m.mu.RLock()\n+ defer m.mu.RUnlock()\n+ keys := make([]string, len(m.servers))\n+ for i, s := range m.servers {\n+ keys[i] = s.ID()\n+ }\n+ return keys\n+}\n+\n// Put replaces all the current values in the collection with the value that\n// is passed through.\nfunc (m *Manager) Put(s []*Server) {\n" }, { "change_type": "ADD", "old_path": null, "new_path": "sftp/event.go", "diff": "+package sftp\n+\n+import (\n+ \"bytes\"\n+ \"emperror.dev/errors\"\n+ \"encoding/gob\"\n+ \"github.com/apex/log\"\n+ \"github.com/pterodactyl/wings/internal/database\"\n+ \"github.com/xujiajun/nutsdb\"\n+ \"regexp\"\n+ \"time\"\n+)\n+\n+type eventHandler struct {\n+ ip string\n+ user string\n+ server string\n+}\n+\n+type Event string\n+type FileAction struct {\n+ // Entity is the targeted file or directory (depending on the event) that the action\n+ // is being performed _against_, such as \"/foo/test.txt\". This will always be the full\n+ // path to the element.\n+ Entity string\n+ // Target is an optional (often blank) field that only has a value in it when the event\n+ // is specifically modifying the entity, such as a rename or move event. In that case\n+ // the Target field will be the final value, such as \"/bar/new.txt\"\n+ Target string\n+}\n+\n+type EventRecord struct {\n+ Event Event\n+ Action FileAction\n+ IP string\n+ User string\n+ Timestamp time.Time\n+}\n+\n+const (\n+ EventWrite = Event(\"write\")\n+ EventCreate = Event(\"create\")\n+ EventCreateDirectory = Event(\"create-directory\")\n+ EventRename = Event(\"rename\")\n+ EventDelete = Event(\"delete\")\n+)\n+\n+var ipTrimRegex = regexp.MustCompile(`(:\\d*)?$`)\n+\n+// Log logs an event into the Wings bucket for SFTP activity which then allows a seperate\n+// cron to run and parse the events into a more manageable stream of event data to send\n+// back to the Panel instance.\n+func (eh *eventHandler) Log(e Event, fa FileAction) error {\n+ r := EventRecord{\n+ Event: e,\n+ Action: fa,\n+ IP: ipTrimRegex.ReplaceAllString(eh.ip, \"\"),\n+ User: eh.user,\n+ Timestamp: time.Now().UTC(),\n+ }\n+\n+ var buf bytes.Buffer\n+ enc := gob.NewEncoder(&buf)\n+ if err := enc.Encode(r); err != nil {\n+ return errors.Wrap(err, \"sftp: failed to encode event\")\n+ }\n+\n+ return database.DB().Update(func(tx *nutsdb.Tx) error {\n+ if err := tx.RPush(database.SftpActivityBucket, []byte(eh.server), buf.Bytes()); err != nil {\n+ return errors.Wrap(err, \"sftp: failed to push event to stack\")\n+ }\n+ return nil\n+ })\n+}\n+\n+// MustLog is a wrapper around log that will trigger a fatal error and exit the application\n+// if an error is encountered during the logging of the event.\n+func (eh *eventHandler) MustLog(e Event, fa FileAction) {\n+ if err := eh.Log(e, fa); err != nil {\n+ log.WithField(\"error\", err).Fatal(\"sftp: failed to log event\")\n+ }\n+}\n" }, { "change_type": "MODIFY", "old_path": "wings.go", "new_path": "wings.go", "diff": "package main\nimport (\n+ \"encoding/gob\"\n\"github.com/pterodactyl/wings/cmd\"\n+ \"github.com/pterodactyl/wings/sftp\"\n\"math/rand\"\n\"time\"\n)\nfunc main() {\n+ gob.Register(sftp.EventRecord{})\n+\n// Since we make use of the math/rand package in the code, especially for generating\n// non-cryptographically secure random strings we need to seed the RNG. Just make use\n// of the current time for this.\n" } ]
Go
MIT License
pterodactyl/wings
Better tracking of SFTP events
532,311
10.07.2022 14:53:54
14,400
e1e7916790fc21e94b7cdcd8a9ea9bad3d6a0a83
Handle ErrKeyNotFound as a non-error
[ { "change_type": "MODIFY", "old_path": "internal/cron/sftp_cron.go", "new_path": "internal/cron/sftp_cron.go", "diff": "@@ -99,7 +99,7 @@ func (sep *sftpEventProcessor) Run() error {\n// Cleanup runs through all of the events we have currently tracked in the bucket and removes\n// them once we've managed to process them and created the associated server activity events.\nfunc (sep *sftpEventProcessor) Cleanup(key []byte) error {\n- return database.DB().Update(func(tx *nutsdb.Tx) error {\n+ err := database.DB().Update(func(tx *nutsdb.Tx) error {\ns, err := sep.sizeOf(tx, key)\nif err != nil {\nreturn err\n@@ -119,6 +119,15 @@ func (sep *sftpEventProcessor) Cleanup(key []byte) error {\n}\nreturn nil\n})\n+\n+ // Sometimes the key will end up not being found depending on the order of operations for\n+ // different events that are happening on the system. Make sure to account for that here,\n+ // if the key isn't found we can just safely assume it is a non issue and move on with our\n+ // day since there is nothing to clean up.\n+ if err != nil && errors.Is(err, nutsdb.ErrKeyNotFound) {\n+ return nil\n+ }\n+ return err\n}\n// Events pulls all of the events in the SFTP event bucket and parses them into an iterable\n@@ -129,6 +138,11 @@ func (sep *sftpEventProcessor) Events() (map[string][]sftp.EventRecord, error) {\nfor _, k := range sep.manager.Keys() {\nlim := sep.limit()\nif s, err := sep.sizeOf(tx, []byte(k)); err != nil {\n+ // Not every server instance will have events tracked, so don't treat this\n+ // as a true error.\n+ if errors.Is(err, nutsdb.ErrKeyNotFound) {\n+ continue\n+ }\nreturn err\n} else if s == 0 {\ncontinue\n" } ]
Go
MIT License
pterodactyl/wings
Handle ErrKeyNotFound as a non-error
532,311
24.07.2022 10:28:42
14,400
61baccb1a3891bfa25e5b866a61b47cba08145a4
Push draft of sftp reconcilation details
[ { "change_type": "MODIFY", "old_path": "internal/cron/activity_cron.go", "new_path": "internal/cron/activity_cron.go", "diff": "@@ -79,7 +79,7 @@ func (ac *activityCron) Run(ctx context.Context) error {\nif len(logs) == 0 {\nreturn nil\n}\n- if err := ac.manager.Client().SendActivityLogs(context.Background(), logs); err != nil {\n+ if err := ac.manager.Client().SendActivityLogs(ctx, logs); err != nil {\nreturn errors.WrapIf(err, \"cron: failed to send activity events to Panel\")\n}\n" }, { "change_type": "MODIFY", "old_path": "internal/cron/cron.go", "new_path": "internal/cron/cron.go", "diff": "@@ -33,9 +33,14 @@ func Scheduler(ctx context.Context, m *server.Manager) (*gocron.Scheduler, error\nmax: config.Get().System.ActivitySendCount,\n}\n+ sftp := sftpActivityCron{\n+ mu: system.NewAtomicBool(false),\n+ manager: m,\n+ max: config.Get().System.ActivitySendCount,\n+ }\n+\ns := gocron.NewScheduler(l)\n- // int(config.Get().System.ActivitySendInterval)\n- _, _ = s.Tag(\"activity\").Every(5).Seconds().Do(func() {\n+ _, _ = s.Tag(\"activity\").Every(config.Get().System.ActivitySendInterval).Seconds().Do(func() {\nif err := activity.Run(ctx); err != nil {\nif errors.Is(err, ErrCronRunning) {\nlog.WithField(\"cron\", \"activity\").Warn(\"cron: process is already running, skipping...\")\n@@ -45,5 +50,15 @@ func Scheduler(ctx context.Context, m *server.Manager) (*gocron.Scheduler, error\n}\n})\n+ _, _ = s.Tag(\"sftp_activity\").Every(5).Seconds().Do(func() {\n+ if err := sftp.Run(ctx); err != nil {\n+ if errors.Is(err, ErrCronRunning) {\n+ log.WithField(\"cron\", \"sftp\").Warn(\"cron: process is already running, skipping...\")\n+ } else {\n+ log.WithField(\"error\", err).Error(\"cron: failed to process sftp events\")\n+ }\n+ }\n+ })\n+\nreturn s, nil\n}\n" }, { "change_type": "ADD", "old_path": null, "new_path": "internal/cron/sftp_activity_cron.go", "diff": "+package cron\n+\n+import (\n+ \"bytes\"\n+ \"context\"\n+ \"emperror.dev/errors\"\n+ \"encoding/gob\"\n+ \"github.com/pterodactyl/wings/internal/sqlite\"\n+ \"github.com/pterodactyl/wings/server\"\n+ \"github.com/pterodactyl/wings/system\"\n+ \"time\"\n+)\n+\n+const querySftpActivity = `\n+SELECT\n+ event,\n+ user_uuid,\n+ server_uuid,\n+ ip,\n+ GROUP_CONCAT(metadata, '::') AS metadata,\n+ MIN(timestamp) AS first_timestamp\n+FROM activity_logs\n+WHERE event LIKE 'server:sftp.%'\n+GROUP BY event, STRFTIME('%Y-%m-%d %H:%M:00', DATETIME(timestamp, 'unixepoch', 'utc')), user_uuid, server_uuid, ip\n+LIMIT ?\n+`\n+\n+type sftpActivityGroup struct {\n+ Event server.Event\n+ User string\n+ Server string\n+ IP string\n+ Metadata []byte\n+ Timestamp int64\n+}\n+\n+// Activity takes the struct and converts it into a single activity entity to\n+// process and send back over to the Panel.\n+func (g *sftpActivityGroup) Activity() (server.Activity, error) {\n+ m, err := g.processMetadata()\n+ if err != nil {\n+ return server.Activity{}, err\n+ }\n+ t := time.Unix(g.Timestamp, 0)\n+ a := server.Activity{\n+ User: g.User,\n+ Server: g.Server,\n+ Event: g.Event,\n+ Metadata: m,\n+ IP: g.IP,\n+ Timestamp: t.UTC(),\n+ }\n+ return a, nil\n+}\n+\n+// processMetadata takes all of the concatenated metadata returned by the SQL\n+// query and then processes it all into individual entity records before then\n+// merging them into a final, single metadata, object.\n+func (g *sftpActivityGroup) processMetadata() (server.ActivityMeta, error) {\n+ b := bytes.Split(g.Metadata, []byte(\"::\"))\n+ if len(b) == 0 {\n+ return server.ActivityMeta{}, nil\n+ }\n+ entities := make([]server.ActivityMeta, len(b))\n+ for i, v := range b {\n+ if len(v) == 0 {\n+ continue\n+ }\n+ if err := gob.NewDecoder(bytes.NewBuffer(v)).Decode(&entities[i]); err != nil {\n+ return nil, errors.Wrap(err, \"could not decode metadata bytes\")\n+ }\n+ }\n+ var files []interface{}\n+ // Iterate over every entity that we've gotten back from the database's metadata fields\n+ // and merge them all into a single entity by checking what the data type returned is and\n+ // going from there.\n+ //\n+ // We only store a slice of strings, or a string/string map value in the database for SFTP\n+ // actions, hence the case statement.\n+ for _, e := range entities {\n+ if e == nil {\n+ continue\n+ }\n+ if f, ok := e[\"files\"]; ok {\n+ var a []interface{}\n+ switch f.(type) {\n+ case []string:\n+ for _, v := range f.([]string) {\n+ a = append(a, v)\n+ }\n+ case map[string]string:\n+ a = append(a, f)\n+ }\n+ files = append(files, a)\n+ }\n+ }\n+ return server.ActivityMeta{\"files\": files}, nil\n+}\n+\n+type sftpActivityCron struct {\n+ mu *system.AtomicBool\n+ manager *server.Manager\n+ max int64\n+}\n+\n+// Run executes the cronjob and finds all associated SFTP events, bundles them up so\n+// that multiple events in the same timespan are recorded as a single event, and then\n+// cleans up the database.\n+func (sac *sftpActivityCron) Run(ctx context.Context) error {\n+ if !sac.mu.SwapIf(true) {\n+ return errors.WithStack(ErrCronRunning)\n+ }\n+ defer sac.mu.Store(false)\n+\n+ rows, err := sqlite.Instance().QueryContext(ctx, querySftpActivity, sac.max)\n+ if err != nil {\n+ return errors.Wrap(err, \"cron: failed to query sftp activity\")\n+ }\n+ defer rows.Close()\n+\n+ if err := rows.Err(); err != nil {\n+ return errors.WithStack(err)\n+ }\n+\n+ var out []server.Activity\n+ for rows.Next() {\n+ v := sftpActivityGroup{}\n+ if err := rows.Scan(&v.Event, &v.User, &v.Server, &v.IP, &v.Metadata, &v.Timestamp); err != nil {\n+ return errors.Wrap(err, \"failed to scan row\")\n+ }\n+ if a, err := v.Activity(); err != nil {\n+ return errors.Wrap(err, \"could not parse data into activity type\")\n+ } else {\n+ out = append(out, a)\n+ }\n+ }\n+\n+ if len(out) == 0 {\n+ return nil\n+ }\n+ if err := sac.manager.Client().SendActivityLogs(ctx, out); err != nil {\n+ return errors.Wrap(err, \"could not send activity logs to Panel\")\n+ }\n+ return nil\n+}\n" }, { "change_type": "MODIFY", "old_path": "internal/sqlite/database.go", "new_path": "internal/sqlite/database.go", "diff": "@@ -22,7 +22,7 @@ CREATE TABLE IF NOT EXISTS \"activity_logs\" (\n\"server_uuid\" varchar NOT NULL,\n\"metadata\" blob,\n\"ip\" varchar,\n- \"timestamp\" datetime NOT NULL DEFAULT CURRENT_TIMESTAMP,\n+ \"timestamp\" integer NOT NULL,\nPRIMARY KEY (id)\n);\n" }, { "change_type": "MODIFY", "old_path": "server/activity.go", "new_path": "server/activity.go", "diff": "@@ -117,7 +117,7 @@ func (a Activity) Save() error {\nDebug(\"saving activity to database\")\nstmt := `INSERT INTO activity_logs(event, user_uuid, server_uuid, metadata, ip, timestamp) VALUES(?, ?, ?, ?, ?, ?)`\n- if _, err := sqlite.Instance().Exec(stmt, a.Event, a.User, a.Server, buf.Bytes(), a.IP, a.Timestamp); err != nil {\n+ if _, err := sqlite.Instance().Exec(stmt, a.Event, a.User, a.Server, buf.Bytes(), a.IP, a.Timestamp.UTC().Unix()); err != nil {\nreturn errors.WithStack(err)\n}\nreturn nil\n" } ]
Go
MIT License
pterodactyl/wings
Push draft of sftp reconcilation details
532,311
24.07.2022 14:40:06
14,400
4634c931829938ffe7eeb4fca4611fe9c9b151ed
Add cron to handle parsing SFTP events
[ { "change_type": "MODIFY", "old_path": "internal/cron/cron.go", "new_path": "internal/cron/cron.go", "diff": "@@ -33,13 +33,29 @@ func Scheduler(ctx context.Context, m *server.Manager) (*gocron.Scheduler, error\nmax: config.Get().System.ActivitySendCount,\n}\n+ sftp := sftpCron{\n+ mu: system.NewAtomicBool(false),\n+ manager: m,\n+ max: config.Get().System.ActivitySendCount,\n+ }\n+\ns := gocron.NewScheduler(l)\n- _, _ = s.Tag(\"activity\").Every(5).Seconds().Do(func() {\n+ _, _ = s.Tag(\"activity\").Every(config.Get().System.ActivitySendInterval).Seconds().Do(func() {\nif err := activity.Run(ctx); err != nil {\nif errors.Is(err, ErrCronRunning) {\n- log.WithField(\"cron\", \"activity\").Warn(\"cron: process is already running, skipping...\")\n+ log.WithField(\"cron\", \"activity\").Warn(\"activity process is already running, skipping...\")\n+ } else {\n+ log.WithField(\"cron\", \"activity\").WithField(\"error\", err).Error(\"activity process failed to execute\")\n+ }\n+ }\n+ })\n+\n+ _, _ = s.Tag(\"sftp\").Every(config.Get().System.ActivitySendInterval).Seconds().Do(func() {\n+ if err := sftp.Run(ctx); err != nil {\n+ if errors.Is(err, ErrCronRunning) {\n+ log.WithField(\"cron\", \"sftp\").Warn(\"sftp events process already running, skipping...\")\n} else {\n- log.WithField(\"error\", err).Error(\"cron: failed to process activity events\")\n+ log.WithField(\"cron\", \"sftp\").WithField(\"error\", err).Error(\"sftp events process failed to execute\")\n}\n}\n})\n" }, { "change_type": "ADD", "old_path": null, "new_path": "internal/cron/sftp_cron.go", "diff": "+package cron\n+\n+import (\n+ \"context\"\n+ \"emperror.dev/errors\"\n+ \"github.com/pterodactyl/wings/internal/database\"\n+ \"github.com/pterodactyl/wings/internal/models\"\n+ \"github.com/pterodactyl/wings/server\"\n+ \"github.com/pterodactyl/wings/system\"\n+ \"gorm.io/gorm\"\n+ \"reflect\"\n+)\n+\n+type sftpCron struct {\n+ mu *system.AtomicBool\n+ manager *server.Manager\n+ max int64\n+}\n+\n+type mapKey struct {\n+ User string\n+ Server string\n+ IP string\n+ Event models.Event\n+ Timestamp string\n+}\n+\n+type eventMap struct {\n+ max int\n+ ids []int\n+ m map[mapKey]*models.Activity\n+}\n+\n+// Run executes the SFTP reconciliation cron. This job will pull all of the SFTP specific events\n+// and merge them together across user, server, ip, and event. This allows a SFTP event that deletes\n+// tens or hundreds of files to be tracked as a single \"deletion\" event so long as they all occur\n+// within the same one minute period of time (starting at the first timestamp for the group). Without\n+// this we'd end up flooding the Panel event log with excessive data that is of no use to end users.\n+func (sc *sftpCron) Run(ctx context.Context) error {\n+ if !sc.mu.SwapIf(true) {\n+ return errors.WithStack(ErrCronRunning)\n+ }\n+ defer sc.mu.Store(false)\n+\n+ var o int\n+ activity, err := sc.fetchRecords(ctx, o)\n+ if err != nil {\n+ return err\n+ }\n+ o += len(activity)\n+\n+ events := &eventMap{\n+ m: map[mapKey]*models.Activity{},\n+ ids: []int{},\n+ max: int(sc.max),\n+ }\n+\n+ for {\n+ if len(activity) == 0 {\n+ break\n+ }\n+ slen := len(events.ids)\n+ for _, a := range activity {\n+ events.Push(a)\n+ }\n+ if len(events.ids) > slen {\n+ // Execute the query again, we found some events so we want to continue\n+ // with this. Start at the next offset.\n+ activity, err = sc.fetchRecords(ctx, o)\n+ if err != nil {\n+ return errors.WithStack(err)\n+ }\n+ o += len(activity)\n+ } else {\n+ break\n+ }\n+ }\n+\n+ if len(events.m) == 0 {\n+ return nil\n+ }\n+\n+ err = database.Instance().Transaction(func(tx *gorm.DB) error {\n+ tx.Where(\"id IN ?\", events.ids).Delete(&models.Activity{})\n+ if tx.Error != nil {\n+ return tx.Error\n+ }\n+\n+ return sc.manager.Client().SendActivityLogs(ctx, events.Elements())\n+ })\n+\n+ return errors.WithStack(err)\n+}\n+\n+// fetchRecords returns a group of activity events starting at the given offset. This is used\n+// since we might need to make multiple database queries to select enough events to properly\n+// fill up our request to the given maximum. This is due to the fact that this cron merges any\n+// activity that line up across user, server, ip, and event into a single activity record when\n+// sending the data to the Panel.\n+func (sc *sftpCron) fetchRecords(ctx context.Context, offset int) (activity []models.Activity, err error) {\n+ tx := database.Instance().WithContext(ctx).\n+ Where(\"event LIKE ?\", \"server:sftp.%\").\n+ Order(\"event DESC\").\n+ Offset(offset).\n+ Limit(int(sc.max)).\n+ Find(&activity)\n+ if tx.Error != nil {\n+ err = errors.WithStack(tx.Error)\n+ }\n+ return\n+}\n+\n+// Push adds an activity to the event mapping, or de-duplicates it and merges the files metadata\n+// into the existing entity that exists.\n+func (em *eventMap) Push(a models.Activity) {\n+ m := em.forActivity(a)\n+ // If no activity entity is returned we've hit the cap for the number of events to\n+ // send along to the Panel. Just skip over this record and we'll account for it in\n+ // the next iteration.\n+ if m == nil {\n+ return\n+ }\n+ em.ids = append(em.ids, a.ID)\n+ // Always reduce this to the first timestamp that was recorded for the set\n+ // of events, and not\n+ if a.Timestamp.Before(m.Timestamp) {\n+ m.Timestamp = a.Timestamp\n+ }\n+ list := m.Metadata[\"files\"].([]interface{})\n+ if s, ok := a.Metadata[\"files\"]; ok {\n+ v := reflect.ValueOf(s)\n+ if v.Kind() != reflect.Slice || v.IsNil() {\n+ return\n+ }\n+ for i := 0; i < v.Len(); i++ {\n+ list = append(list, v.Index(i).Interface())\n+ }\n+ // You must set it again at the end of the process, otherwise you've only updated the file\n+ // slice in this one loop since it isn't passed by reference. This is just shorter than having\n+ // to explicitly keep casting it to the slice.\n+ m.Metadata[\"files\"] = list\n+ }\n+}\n+\n+// Elements returns the finalized activity models.\n+func (em *eventMap) Elements() (out []models.Activity) {\n+ for _, v := range em.m {\n+ out = append(out, *v)\n+ }\n+ return\n+}\n+\n+// forActivity returns an event entity from our map which allows existing matches to be\n+// updated with additional files.\n+func (em *eventMap) forActivity(a models.Activity) *models.Activity {\n+ key := mapKey{\n+ User: a.User.String,\n+ Server: a.Server,\n+ IP: a.IP,\n+ Event: a.Event,\n+ // We group by the minute, don't care about the seconds for this logic.\n+ Timestamp: a.Timestamp.Format(\"2006-01-02_15:04\"),\n+ }\n+ if v, ok := em.m[key]; ok {\n+ return v\n+ }\n+ // Cap the size of the events map at the defined maximum events to send to the Panel. Just\n+ // return nil and let the caller handle it.\n+ if len(em.m) >= em.max {\n+ return nil\n+ }\n+ // Doesn't exist in our map yet, create a copy of the activity passed into this\n+ // function and then assign it into the map with an empty metadata value.\n+ v := a\n+ v.Metadata = models.ActivityMeta{\n+ \"files\": make([]interface{}, 0),\n+ }\n+ em.m[key] = &v\n+ return &v\n+}\n" } ]
Go
MIT License
pterodactyl/wings
Add cron to handle parsing SFTP events
532,311
24.07.2022 15:59:17
14,400
251f91a08e990a2b6680617301b9416c3ee872e3
Fix crons to actually run correctly using the configuration values
[ { "change_type": "MODIFY", "old_path": "config/config.go", "new_path": "config/config.go", "diff": "@@ -167,10 +167,10 @@ type SystemConfiguration struct {\n// being sent to the Panel. By default this will send activity collected over the last minute. Keep\n// in mind that only a fixed number of activity log entries, defined by ActivitySendCount, will be sent\n// in each run.\n- ActivitySendInterval int64 `default:\"60\" yaml:\"activity_send_interval\"`\n+ ActivitySendInterval int `default:\"60\" yaml:\"activity_send_interval\"`\n// ActivitySendCount is the number of activity events to send per batch.\n- ActivitySendCount int64 `default:\"100\" yaml:\"activity_send_count\"`\n+ ActivitySendCount int `default:\"100\" yaml:\"activity_send_count\"`\n// If set to true, file permissions for a server will be checked when the process is\n// booted. This can cause boot delays if the server has a large amount of files. In most\n" }, { "change_type": "MODIFY", "old_path": "internal/cron/activity_cron.go", "new_path": "internal/cron/activity_cron.go", "diff": "@@ -12,7 +12,7 @@ import (\ntype activityCron struct {\nmu *system.AtomicBool\nmanager *server.Manager\n- max int64\n+ max int\n}\n// Run executes the cronjob and ensures we fetch and send all of the stored activity to the\n@@ -30,7 +30,7 @@ func (ac *activityCron) Run(ctx context.Context) error {\nvar activity []models.Activity\ntx := database.Instance().WithContext(ctx).\nWhere(\"event NOT LIKE ?\", \"server:sftp.%\").\n- Limit(int(ac.max)).\n+ Limit(ac.max).\nFind(&activity)\nif tx.Error != nil {\n" }, { "change_type": "MODIFY", "old_path": "internal/cron/cron.go", "new_path": "internal/cron/cron.go", "diff": "@@ -3,7 +3,7 @@ package cron\nimport (\n\"context\"\n\"emperror.dev/errors\"\n- \"github.com/apex/log\"\n+ log2 \"github.com/apex/log\"\n\"github.com/go-co-op/gocron\"\n\"github.com/pterodactyl/wings/config\"\n\"github.com/pterodactyl/wings/server\"\n@@ -40,7 +40,13 @@ func Scheduler(ctx context.Context, m *server.Manager) (*gocron.Scheduler, error\n}\ns := gocron.NewScheduler(l)\n- _, _ = s.Tag(\"activity\").Every(config.Get().System.ActivitySendInterval).Seconds().Do(func() {\n+ log := log2.WithField(\"subsystem\", \"cron\")\n+\n+ interval := time.Duration(config.Get().System.ActivitySendInterval) * time.Second\n+ log.WithField(\"interval\", interval).Info(\"configuring system crons\")\n+\n+ _, _ = s.Tag(\"activity\").Every(interval).Do(func() {\n+ log.WithField(\"cron\", \"activity\").Debug(\"sending internal activity events to Panel\")\nif err := activity.Run(ctx); err != nil {\nif errors.Is(err, ErrCronRunning) {\nlog.WithField(\"cron\", \"activity\").Warn(\"activity process is already running, skipping...\")\n@@ -50,7 +56,8 @@ func Scheduler(ctx context.Context, m *server.Manager) (*gocron.Scheduler, error\n}\n})\n- _, _ = s.Tag(\"sftp\").Every(config.Get().System.ActivitySendInterval).Seconds().Do(func() {\n+ _, _ = s.Tag(\"sftp\").Every(interval).Do(func() {\n+ log.WithField(\"cron\", \"sftp\").Debug(\"sending sftp events to Panel\")\nif err := sftp.Run(ctx); err != nil {\nif errors.Is(err, ErrCronRunning) {\nlog.WithField(\"cron\", \"sftp\").Warn(\"sftp events process already running, skipping...\")\n" }, { "change_type": "MODIFY", "old_path": "internal/cron/sftp_cron.go", "new_path": "internal/cron/sftp_cron.go", "diff": "@@ -14,7 +14,7 @@ import (\ntype sftpCron struct {\nmu *system.AtomicBool\nmanager *server.Manager\n- max int64\n+ max int\n}\ntype mapKey struct {\n@@ -52,7 +52,7 @@ func (sc *sftpCron) Run(ctx context.Context) error {\nevents := &eventMap{\nm: map[mapKey]*models.Activity{},\nids: []int{},\n- max: int(sc.max),\n+ max: sc.max,\n}\nfor {\n@@ -102,7 +102,7 @@ func (sc *sftpCron) fetchRecords(ctx context.Context, offset int) (activity []mo\nWhere(\"event LIKE ?\", \"server:sftp.%\").\nOrder(\"event DESC\").\nOffset(offset).\n- Limit(int(sc.max)).\n+ Limit(sc.max).\nFind(&activity)\nif tx.Error != nil {\nerr = errors.WithStack(tx.Error)\n" } ]
Go
MIT License
pterodactyl/wings
Fix crons to actually run correctly using the configuration values
532,311
24.07.2022 16:26:52
14,400
21cf66b2b401e90d319ec78a596a22ab94d522a4
Use single connection in pool to avoid simultaneous write lock issues
[ { "change_type": "MODIFY", "old_path": "internal/database/database.go", "new_path": "internal/database/database.go", "diff": "@@ -7,7 +7,9 @@ import (\n\"github.com/pterodactyl/wings/internal/models\"\n\"github.com/pterodactyl/wings/system\"\n\"gorm.io/gorm\"\n+ \"gorm.io/gorm/logger\"\n\"path/filepath\"\n+ \"time\"\n)\nvar o system.AtomicBool\n@@ -20,11 +22,19 @@ func Initialize() error {\npanic(\"database: attempt to initialize more than once during application lifecycle\")\n}\np := filepath.Join(config.Get().System.RootDirectory, \"wings.db\")\n- instance, err := gorm.Open(sqlite.Open(p), &gorm.Config{})\n+ instance, err := gorm.Open(sqlite.Open(p), &gorm.Config{\n+ Logger: logger.Default.LogMode(logger.Silent),\n+ })\nif err != nil {\nreturn errors.Wrap(err, \"database: could not open database file\")\n}\ndb = instance\n+ if sql, err := db.DB(); err != nil {\n+ return errors.WithStack(err)\n+ } else {\n+ sql.SetMaxOpenConns(1)\n+ sql.SetConnMaxLifetime(time.Hour)\n+ }\nif err := db.AutoMigrate(&models.Activity{}); err != nil {\nreturn errors.WithStack(err)\n}\n" } ]
Go
MIT License
pterodactyl/wings
Use single connection in pool to avoid simultaneous write lock issues
532,311
24.07.2022 16:27:05
14,400
f952efd9c72b947d70e63ba69d08214aaeddca30
Don't try to store nil for the metadata
[ { "change_type": "MODIFY", "old_path": "internal/models/activity.go", "new_path": "internal/models/activity.go", "diff": "@@ -60,5 +60,8 @@ func (a *Activity) BeforeCreate(_ *gorm.DB) error {\na.Timestamp = time.Now()\n}\na.Timestamp = a.Timestamp.UTC()\n+ if a.Metadata == nil {\n+ a.Metadata = ActivityMeta{}\n+ }\nreturn nil\n}\n" } ]
Go
MIT License
pterodactyl/wings
Don't try to store nil for the metadata
532,311
24.07.2022 16:27:25
14,400
8cee18a92bd0a062c7f37affc777d5e12368bbea
Save activity in a background routine to speed things along; cap query time at 3 seconds
[ { "change_type": "MODIFY", "old_path": "internal/cron/sftp_cron.go", "new_path": "internal/cron/sftp_cron.go", "diff": "@@ -7,7 +7,6 @@ import (\n\"github.com/pterodactyl/wings/internal/models\"\n\"github.com/pterodactyl/wings/server\"\n\"github.com/pterodactyl/wings/system\"\n- \"gorm.io/gorm\"\n\"reflect\"\n)\n@@ -79,17 +78,13 @@ func (sc *sftpCron) Run(ctx context.Context) error {\nif len(events.m) == 0 {\nreturn nil\n}\n-\n- err = database.Instance().Transaction(func(tx *gorm.DB) error {\n- tx.Where(\"id IN ?\", events.ids).Delete(&models.Activity{})\n- if tx.Error != nil {\n- return tx.Error\n+ if err := sc.manager.Client().SendActivityLogs(ctx, events.Elements()); err != nil {\n+ return errors.Wrap(err, \"failed to send sftp activity logs to Panel\")\n}\n-\n- return sc.manager.Client().SendActivityLogs(ctx, events.Elements())\n- })\n-\n- return errors.WithStack(err)\n+ if tx := database.Instance().Where(\"id IN ?\", events.ids).Delete(&models.Activity{}); tx.Error != nil {\n+ return errors.WithStack(tx.Error)\n+ }\n+ return nil\n}\n// fetchRecords returns a group of activity events starting at the given offset. This is used\n" }, { "change_type": "MODIFY", "old_path": "router/websocket/websocket.go", "new_path": "router/websocket/websocket.go", "diff": "@@ -370,7 +370,7 @@ func (h *Handler) HandleInbound(ctx context.Context, m Message) error {\n}\nif err == nil {\n- _ = h.ra.Save(h.server, models.Event(server.ActivityPowerPrefix+action), nil)\n+ h.server.SaveActivity(h.ra, models.Event(server.ActivityPowerPrefix+action), nil)\n}\nreturn err\n@@ -429,11 +429,13 @@ func (h *Handler) HandleInbound(ctx context.Context, m Message) error {\n}\n}\n- _ = h.ra.Save(h.server, server.ActivityConsoleCommand, models.ActivityMeta{\n+ if err := h.server.Environment.SendCommand(strings.Join(m.Args, \"\")); err != nil {\n+ return err\n+ }\n+ h.server.SaveActivity(h.ra, server.ActivityConsoleCommand, models.ActivityMeta{\n\"command\": strings.Join(m.Args, \"\"),\n})\n-\n- return h.server.Environment.SendCommand(strings.Join(m.Args, \"\"))\n+ return nil\n}\n}\n" }, { "change_type": "MODIFY", "old_path": "server/activity.go", "new_path": "server/activity.go", "diff": "package server\nimport (\n+ \"context\"\n\"emperror.dev/errors\"\n\"github.com/pterodactyl/wings/internal/database\"\n\"github.com/pterodactyl/wings/internal/models\"\n+ \"time\"\n)\nconst ActivityPowerPrefix = \"server:power.\"\n@@ -34,29 +36,6 @@ func (ra RequestActivity) Event(event models.Event, metadata models.ActivityMeta\nreturn a.SetUser(ra.user)\n}\n-// Save creates a new event instance and saves it. If an error is encountered it is automatically\n-// logged to the provided server's error logging output. The error is also returned to the caller\n-// but can be ignored.\n-func (ra RequestActivity) Save(s *Server, event models.Event, metadata models.ActivityMeta) error {\n- if tx := database.Instance().Create(ra.Event(event, metadata)); tx.Error != nil {\n- err := errors.WithStackIf(tx.Error)\n-\n- s.Log().WithField(\"error\", err).WithField(\"event\", event).Error(\"activity: failed to save event\")\n-\n- return err\n- }\n- return nil\n-}\n-\n-// IP returns the IP address associated with this entry.\n-func (ra RequestActivity) IP() string {\n- return ra.ip\n-}\n-\n-func (ra *RequestActivity) User() string {\n- return ra.user\n-}\n-\n// SetUser clones the RequestActivity struct and sets a new user value on the copy\n// before returning it.\nfunc (ra RequestActivity) SetUser(u string) RequestActivity {\n@@ -68,3 +47,17 @@ func (ra RequestActivity) SetUser(u string) RequestActivity {\nfunc (s *Server) NewRequestActivity(user string, ip string) RequestActivity {\nreturn RequestActivity{server: s.ID(), user: user, ip: ip}\n}\n+\n+// SaveActivity saves an activity entry to the database in a background routine. If an error is\n+// encountered it is logged but not returned to the caller.\n+func (s *Server) SaveActivity(a RequestActivity, event models.Event, metadata models.ActivityMeta) {\n+ ctx, cancel := context.WithTimeout(s.Context(), time.Second*3)\n+ go func() {\n+ defer cancel()\n+ if tx := database.Instance().WithContext(ctx).Create(a.Event(event, metadata)); tx.Error != nil {\n+ s.Log().WithField(\"error\", errors.WithStack(tx.Error)).\n+ WithField(\"event\", event).\n+ Error(\"activity: failed to save event\")\n+ }\n+ }()\n+}\n" } ]
Go
MIT License
pterodactyl/wings
Save activity in a background routine to speed things along; cap query time at 3 seconds
532,311
24.07.2022 16:58:03
14,400
c18e84468915bca2925d7c8768ec962f5f4d1339
Support more rapid insertion; ignore issues with i/o
[ { "change_type": "MODIFY", "old_path": "internal/database/database.go", "new_path": "internal/database/database.go", "diff": "@@ -35,6 +35,12 @@ func Initialize() error {\nsql.SetMaxOpenConns(1)\nsql.SetConnMaxLifetime(time.Hour)\n}\n+ if tx := db.Exec(\"PRAGMA synchronous = OFF\"); tx.Error != nil {\n+ return errors.WithStack(tx.Error)\n+ }\n+ if tx := db.Exec(\"PRAGMA journal_mode = MEMORY\"); tx.Error != nil {\n+ return errors.WithStack(tx.Error)\n+ }\nif err := db.AutoMigrate(&models.Activity{}); err != nil {\nreturn errors.WithStack(err)\n}\n" }, { "change_type": "MODIFY", "old_path": "sftp/event.go", "new_path": "sftp/event.go", "diff": "@@ -44,7 +44,7 @@ func (eh *eventHandler) Log(e models.Event, fa FileAction) error {\n}\nif tx := database.Instance().Create(a.SetUser(eh.user)); tx.Error != nil {\n- return errors.Wrap(tx.Error, \"sftp: failed to save event to database\")\n+ return errors.WithStack(tx.Error)\n}\nreturn nil\n}\n@@ -53,6 +53,6 @@ func (eh *eventHandler) Log(e models.Event, fa FileAction) error {\n// if an error is encountered during the logging of the event.\nfunc (eh *eventHandler) MustLog(e models.Event, fa FileAction) {\nif err := eh.Log(e, fa); err != nil {\n- log.WithField(\"error\", err).Fatal(\"sftp: failed to log event\")\n+ log.WithField(\"error\", errors.WithStack(err)).WithField(\"event\", e).Error(\"sftp: failed to log event\")\n}\n}\n" } ]
Go
MIT License
pterodactyl/wings
Support more rapid insertion; ignore issues with i/o
532,311
24.07.2022 17:12:47
14,400
e3ab241d7f34dc71a6b645b3abed3305da795b7f
Track file upload activity
[ { "change_type": "MODIFY", "old_path": "router/router_server_files.go", "new_path": "router/router_server_files.go", "diff": "@@ -3,6 +3,7 @@ package router\nimport (\n\"bufio\"\n\"context\"\n+ \"github.com/pterodactyl/wings/internal/models\"\n\"io\"\n\"mime/multipart\"\n\"net/http\"\n@@ -600,6 +601,11 @@ func postServerUploadFiles(c *gin.Context) {\nif err := handleFileUpload(p, s, header); err != nil {\nNewServerError(err, s).Abort(c)\nreturn\n+ } else {\n+ s.SaveActivity(s.NewRequestActivity(token.UserUuid, c.Request.RemoteAddr), server.ActivityFileUploaded, models.ActivityMeta{\n+ \"file\": header.Filename,\n+ \"directory\": filepath.Clean(directory),\n+ })\n}\n}\n}\n@@ -617,6 +623,5 @@ func handleFileUpload(p string, s *server.Server, header *multipart.FileHeader)\nif err := s.Filesystem().Writefile(p, file); err != nil {\nreturn err\n}\n-\nreturn nil\n}\n" }, { "change_type": "MODIFY", "old_path": "router/tokens/upload.go", "new_path": "router/tokens/upload.go", "diff": "@@ -8,6 +8,7 @@ type UploadPayload struct {\njwt.Payload\nServerUuid string `json:\"server_uuid\"`\n+ UserUuid string `json:\"user_uuid\"`\nUniqueId string `json:\"unique_id\"`\n}\n" }, { "change_type": "MODIFY", "old_path": "server/activity.go", "new_path": "server/activity.go", "diff": "@@ -17,6 +17,7 @@ const (\nActivitySftpCreateDirectory = models.Event(\"server:sftp.create-directory\")\nActivitySftpRename = models.Event(\"server:sftp.rename\")\nActivitySftpDelete = models.Event(\"server:sftp.delete\")\n+ ActivityFileUploaded = models.Event(\"server:file.uploaded\")\n)\n// RequestActivity is a wrapper around a LoggedEvent that is able to track additional request\n" } ]
Go
MIT License
pterodactyl/wings
Track file upload activity
532,311
24.07.2022 17:16:45
14,400
231e24aa3375b3a483b8601d1ccb56f48686d378
Support new metadata from panel for servers
[ { "change_type": "MODIFY", "old_path": "server/configuration.go", "new_path": "server/configuration.go", "diff": "@@ -16,6 +16,11 @@ type EggConfiguration struct {\nFileDenylist []string `json:\"file_denylist\"`\n}\n+type ConfigurationMeta struct {\n+ Name string `json:\"name\"`\n+ Description string `json:\"description\"`\n+}\n+\ntype Configuration struct {\nmu sync.RWMutex\n@@ -24,6 +29,8 @@ type Configuration struct {\n// docker containers as well as in log output.\nUuid string `json:\"uuid\"`\n+ Meta ConfigurationMeta `json:\"meta\"`\n+\n// Whether or not the server is in a suspended state. Suspended servers cannot\n// be started or modified except in certain scenarios by an admin user.\nSuspended bool `json:\"suspended\"`\n" } ]
Go
MIT License
pterodactyl/wings
Support new metadata from panel for servers
532,325
25.09.2022 15:25:53
14,400
9dfc651a911d26ad16ff542959149e3f6d023a6c
rpm: update to 1.7.0
[ { "change_type": "MODIFY", "old_path": "rpm/ptero-wings.spec", "new_path": "rpm/ptero-wings.spec", "diff": "Name: ptero-wings\n-Version: 1.5.3\n+Version: 1.7.0\nRelease: 1%{?dist}\nSummary: The server control plane for Pterodactyl Panel. Written from the ground-up with security, speed, and stability in mind.\nBuildArch: x86_64\n@@ -91,6 +91,9 @@ rm -rf /var/log/pterodactyl\nwings --version\n%changelog\n+* Wed Sep 14 2022 Chance Callahan <[email protected]> - 1.7.0-1\n+- Updating specfile to match stable release.\n+\n* Wed Oct 27 2021 Capitol Hosting Solutions Systems Engineering <[email protected]> - 1.5.3-1\n- specfile by Capitol Hosting Solutions, Upstream by Pterodactyl\n- Rebased for https://github.com/pterodactyl/wings/releases/tag/v1.5.3\n" } ]
Go
MIT License
pterodactyl/wings
rpm: update to 1.7.0 (#140)
532,334
25.09.2022 12:34:28
25,200
c736c24118906e90afe0614146cf6dba70b88177
it's to its
[ { "change_type": "MODIFY", "old_path": "cmd/diagnostics.go", "new_path": "cmd/diagnostics.go", "diff": "@@ -58,7 +58,7 @@ func newDiagnosticsCommand() *cobra.Command {\nreturn command\n}\n-// diagnosticsCmdRun collects diagnostics about wings, it's configuration and the node.\n+// diagnosticsCmdRun collects diagnostics about wings, its configuration and the node.\n// We collect:\n// - wings and docker versions\n// - relevant parts of daemon configuration\n" }, { "change_type": "MODIFY", "old_path": "cmd/root.go", "new_path": "cmd/root.go", "diff": "@@ -81,7 +81,7 @@ func init() {\nrootCommand.Flags().Bool(\"pprof\", false, \"if the pprof profiler should be enabled. The profiler will bind to localhost:6060 by default\")\nrootCommand.Flags().Int(\"pprof-block-rate\", 0, \"enables block profile support, may have performance impacts\")\nrootCommand.Flags().Int(\"pprof-port\", 6060, \"If provided with --pprof, the port it will run on\")\n- rootCommand.Flags().Bool(\"auto-tls\", false, \"pass in order to have wings generate and manage it's own SSL certificates using Let's Encrypt\")\n+ rootCommand.Flags().Bool(\"auto-tls\", false, \"pass in order to have wings generate and manage its own SSL certificates using Let's Encrypt\")\nrootCommand.Flags().String(\"tls-hostname\", \"\", \"required with --auto-tls, the FQDN for the generated SSL certificate\")\nrootCommand.Flags().Bool(\"ignore-certificate-errors\", false, \"ignore certificate verification errors when executing API calls\")\n@@ -162,7 +162,7 @@ func rootCmdRun(cmd *cobra.Command, _ []string) {\nticker := time.NewTicker(time.Minute)\n// Every minute, write the current server states to the disk to allow for a more\n// seamless hard-reboot process in which wings will re-sync server states based\n- // on it's last tracked state.\n+ // on its last tracked state.\ngo func() {\nfor {\nselect {\n" }, { "change_type": "MODIFY", "old_path": "router/router_server.go", "new_path": "router/router_server.go", "diff": "@@ -180,7 +180,7 @@ func postServerReinstall(c *gin.Context) {\nc.Status(http.StatusAccepted)\n}\n-// Deletes a server from the wings daemon and dissociate it's objects.\n+// Deletes a server from the wings daemon and dissociate its objects.\nfunc deleteServer(c *gin.Context) {\ns := middleware.ExtractServer(c)\n" }, { "change_type": "MODIFY", "old_path": "server/filesystem/archive.go", "new_path": "server/filesystem/archive.go", "diff": "@@ -148,7 +148,7 @@ func (a *Archive) withFilesCallback(tw *tar.Writer) func(path string, de *godirw\n// Adds a given file path to the final archive being created.\nfunc (a *Archive) addToArchive(p string, rp string, w *tar.Writer) error {\n// Lstat the file, this will give us the same information as Stat except that it will not\n- // follow a symlink to it's target automatically. This is important to avoid including\n+ // follow a symlink to its target automatically. This is important to avoid including\n// files that exist outside the server root unintentionally in the backup.\ns, err := os.Lstat(p)\nif err != nil {\n" }, { "change_type": "MODIFY", "old_path": "server/filesystem/disk_space.go", "new_path": "server/filesystem/disk_space.go", "diff": "@@ -71,7 +71,7 @@ func (fs *Filesystem) HasSpaceAvailable(allowStaleValue bool) bool {\n// If space is -1 or 0 just return true, means they're allowed unlimited.\n//\n// Technically we could skip disk space calculation because we don't need to check if the\n- // server exceeds it's limit but because this method caches the disk usage it would be best\n+ // server exceeds its limit but because this method caches the disk usage it would be best\n// to calculate the disk usage and always return true.\nif fs.MaxDisk() == 0 {\nreturn true\n" }, { "change_type": "MODIFY", "old_path": "system/sink_pool.go", "new_path": "system/sink_pool.go", "diff": "@@ -23,7 +23,7 @@ type SinkPool struct {\n}\n// NewSinkPool returns a new empty SinkPool. A sink pool generally lives with a\n-// server instance for it's full lifetime.\n+// server instance for its full lifetime.\nfunc NewSinkPool() *SinkPool {\nreturn &SinkPool{}\n}\n" } ]
Go
MIT License
pterodactyl/wings
it's to its (#123)
532,328
26.09.2022 02:47:09
-7,200
c686992e850183a79b7f4619b7979ffcfb1c223a
backups: add an option to change gzip compression level
[ { "change_type": "MODIFY", "old_path": "config/config.go", "new_path": "config/config.go", "diff": "@@ -219,6 +219,15 @@ type Backups struct {\n//\n// Defaults to 0 (unlimited)\nWriteLimit int `default:\"0\" yaml:\"write_limit\"`\n+\n+ // CompressionLevel determines how much backups created by wings should be compressed.\n+ //\n+ // \"none\" -> no compression will be applied\n+ // \"best_speed\" -> uses gzip level 1 for fast speed\n+ // \"best_compression\" -> uses gzip level 9 for minimal disk space useage\n+ //\n+ // Defaults to \"best_speed\" (level 1)\n+ CompressionLevel string `default:\"best_speed\" yaml:\"compression_level\"`\n}\ntype Transfers struct {\n" }, { "change_type": "MODIFY", "old_path": "server/filesystem/archive.go", "new_path": "server/filesystem/archive.go", "diff": "@@ -62,8 +62,21 @@ func (a *Archive) Create(dst string) error {\nwriter = f\n}\n+ // The default compression level is BestSpeed\n+ var cl = pgzip.BestSpeed\n+\n+ // Choose which compression level to use based on the compression_level configuration option\n+ switch config.Get().System.Backups.CompressionLevel {\n+ case \"none\":\n+ cl = pgzip.NoCompression\n+ case \"best_speed\":\n+ cl = pgzip.BestSpeed\n+ case \"best_compression\":\n+ cl = pgzip.BestCompression\n+ }\n+\n// Create a new gzip writer around the file.\n- gw, _ := pgzip.NewWriterLevel(writer, pgzip.BestSpeed)\n+ gw, _ := pgzip.NewWriterLevel(writer, cl)\n_ = gw.SetConcurrency(1<<20, 1)\ndefer gw.Close()\n" } ]
Go
MIT License
pterodactyl/wings
backups: add an option to change gzip compression level (#128)
532,314
25.09.2022 18:49:48
21,600
b6edf3acf96520065198affe1397ebc8983d3d9e
environment(docker): set outgoing ip correctly Closes
[ { "change_type": "MODIFY", "old_path": "environment/allocations.go", "new_path": "environment/allocations.go", "diff": "@@ -12,6 +12,11 @@ import (\n// Defines the allocations available for a given server. When using the Docker environment\n// driver these correspond to mappings for the container that allow external connections.\ntype Allocations struct {\n+ // ForceOutgoingIP causes a dedicated bridge network to be created for the\n+ // server with a special option, causing Docker to SNAT outgoing traffic to\n+ // the DefaultMapping's IP. This is important to servers which rely on external\n+ // services that check the IP of the server (Source Engine servers, for example).\n+ ForceOutgoingIP bool `json:\"force_outgoing_ip\"`\n// Defines the default allocation that should be used for this server. This is\n// what will be used for {SERVER_IP} and {SERVER_PORT} when modifying configuration\n// files or the startup arguments for a server.\n" }, { "change_type": "MODIFY", "old_path": "environment/docker.go", "new_path": "environment/docker.go", "diff": "@@ -41,12 +41,12 @@ func ConfigureDocker(ctx context.Context) error {\nnw := config.Get().Docker.Network\nresource, err := cli.NetworkInspect(ctx, nw.Name, types.NetworkInspectOptions{})\nif err != nil {\n- if client.IsErrNotFound(err) {\n- log.Info(\"creating missing pterodactyl0 interface, this could take a few seconds...\")\n- if err := createDockerNetwork(ctx, cli); err != nil {\n+ if !client.IsErrNotFound(err) {\nreturn err\n}\n- } else {\n+\n+ log.Info(\"creating missing pterodactyl0 interface, this could take a few seconds...\")\n+ if err := createDockerNetwork(ctx, cli); err != nil {\nreturn err\n}\n}\n" }, { "change_type": "MODIFY", "old_path": "environment/docker/container.go", "new_path": "environment/docker/container.go", "diff": "@@ -147,10 +147,12 @@ func (e *Environment) InSituUpdate() error {\n// currently available for it. If the container already exists it will be\n// returned.\nfunc (e *Environment) Create() error {\n+ ctx := context.Background()\n+\n// If the container already exists don't hit the user with an error, just return\n// the current information about it which is what we would do when creating the\n// container anyways.\n- if _, err := e.ContainerInspect(context.Background()); err == nil {\n+ if _, err := e.ContainerInspect(ctx); err == nil {\nreturn nil\n} else if !client.IsErrNotFound(err) {\nreturn errors.Wrap(err, \"environment/docker: failed to inspect container\")\n@@ -190,7 +192,34 @@ func (e *Environment) Create() error {\n},\n}\n- tmpfsSize := strconv.Itoa(int(config.Get().Docker.TmpfsSize))\n+ networkMode := container.NetworkMode(config.Get().Docker.Network.Mode)\n+ if a.ForceOutgoingIP {\n+ e.log().Debug(\"environment/docker: forcing outgoing IP address\")\n+ networkName := strings.ReplaceAll(e.Id, \"-\", \"\")\n+ networkMode = container.NetworkMode(networkName)\n+\n+ if _, err := e.client.NetworkInspect(ctx, networkName, types.NetworkInspectOptions{}); err != nil {\n+ if !client.IsErrNotFound(err) {\n+ return err\n+ }\n+\n+ if _, err := e.client.NetworkCreate(ctx, networkName, types.NetworkCreate{\n+ Driver: \"bridge\",\n+ EnableIPv6: false,\n+ Internal: false,\n+ Attachable: false,\n+ Ingress: false,\n+ ConfigOnly: false,\n+ Options: map[string]string{\n+ \"encryption\": \"false\",\n+ \"com.docker.network.bridge.default_bridge\": \"false\",\n+ \"com.docker.network.host_ipv4\": a.DefaultMapping.Ip,\n+ },\n+ }); err != nil {\n+ return err\n+ }\n+ }\n+ }\nhostConf := &container.HostConfig{\nPortBindings: a.DockerBindings(),\n@@ -202,7 +231,7 @@ func (e *Environment) Create() error {\n// Configure the /tmp folder mapping in containers. This is necessary for some\n// games that need to make use of it for downloads and other installation processes.\nTmpfs: map[string]string{\n- \"/tmp\": \"rw,exec,nosuid,size=\" + tmpfsSize + \"M\",\n+ \"/tmp\": \"rw,exec,nosuid,size=\" + strconv.Itoa(int(config.Get().Docker.TmpfsSize)) + \"M\",\n},\n// Define resource limits for the container based on the data passed through\n@@ -231,10 +260,10 @@ func (e *Environment) Create() error {\n\"setpcap\", \"mknod\", \"audit_write\", \"net_raw\", \"dac_override\",\n\"fowner\", \"fsetid\", \"net_bind_service\", \"sys_chroot\", \"setfcap\",\n},\n- NetworkMode: container.NetworkMode(config.Get().Docker.Network.Mode),\n+ NetworkMode: networkMode,\n}\n- if _, err := e.client.ContainerCreate(context.Background(), conf, hostConf, nil, nil, e.Id); err != nil {\n+ if _, err := e.client.ContainerCreate(ctx, conf, hostConf, nil, nil, e.Id); err != nil {\nreturn errors.Wrap(err, \"environment/docker: failed to create container\")\n}\n" } ]
Go
MIT License
pterodactyl/wings
environment(docker): set outgoing ip correctly (#135) Closes https://github.com/pterodactyl/panel/issues/3841
532,315
05.10.2022 08:11:07
-28,800
e98d249cf7436dca9c9dfa57f286852c7fb32441
Add configuration for trusted proxies
[ { "change_type": "MODIFY", "old_path": "config/config.go", "new_path": "config/config.go", "diff": "@@ -91,6 +91,9 @@ type ApiConfiguration struct {\n// The maximum size for files uploaded through the Panel in MB.\nUploadLimit int64 `default:\"100\" json:\"upload_limit\" yaml:\"upload_limit\"`\n+\n+ // A list of IP address of proxies that may send a X-Forwarded-For header to set the true clients IP\n+ TrustedProxies []string `json:\"trusted_proxies\" yaml:\"trusted_proxies\"`\n}\n// RemoteQueryConfiguration defines the configuration settings for remote requests\n" }, { "change_type": "MODIFY", "old_path": "router/router.go", "new_path": "router/router.go", "diff": "@@ -4,6 +4,7 @@ import (\n\"github.com/apex/log\"\n\"github.com/gin-gonic/gin\"\n+ \"github.com/pterodactyl/wings/config\"\n\"github.com/pterodactyl/wings/remote\"\n\"github.com/pterodactyl/wings/router/middleware\"\nwserver \"github.com/pterodactyl/wings/server\"\n@@ -15,6 +16,7 @@ func Configure(m *wserver.Manager, client remote.Client) *gin.Engine {\nrouter := gin.New()\nrouter.Use(gin.Recovery())\n+ router.SetTrustedProxies(config.Get().Api.TrustedProxies)\nrouter.Use(middleware.AttachRequestID(), middleware.CaptureErrors(), middleware.SetAccessControlHeaders())\nrouter.Use(middleware.AttachServerManager(m), middleware.AttachApiClient(client))\n// @todo log this into a different file so you can setup IP blocking for abusive requests and such.\n" }, { "change_type": "MODIFY", "old_path": "router/router_server_files.go", "new_path": "router/router_server_files.go", "diff": "@@ -602,7 +602,7 @@ func postServerUploadFiles(c *gin.Context) {\nNewServerError(err, s).Abort(c)\nreturn\n} else {\n- s.SaveActivity(s.NewRequestActivity(token.UserUuid, c.Request.RemoteAddr), server.ActivityFileUploaded, models.ActivityMeta{\n+ s.SaveActivity(s.NewRequestActivity(token.UserUuid, c.ClientIP()), server.ActivityFileUploaded, models.ActivityMeta{\n\"file\": header.Filename,\n\"directory\": filepath.Clean(directory),\n})\n" }, { "change_type": "MODIFY", "old_path": "router/router_server_ws.go", "new_path": "router/router_server_ws.go", "diff": "@@ -32,7 +32,7 @@ func getServerWebsocket(c *gin.Context) {\nctx, cancel := context.WithCancel(c.Request.Context())\ndefer cancel()\n- handler, err := websocket.GetHandler(s, c.Writer, c.Request)\n+ handler, err := websocket.GetHandler(s, c.Writer, c.Request, c)\nif err != nil {\nNewServerError(err, s).Abort(c)\nreturn\n" }, { "change_type": "MODIFY", "old_path": "router/websocket/websocket.go", "new_path": "router/websocket/websocket.go", "diff": "@@ -12,6 +12,7 @@ import (\n\"emperror.dev/errors\"\n\"github.com/apex/log\"\n\"github.com/gbrlsnchs/jwt/v3\"\n+ \"github.com/gin-gonic/gin\"\n\"github.com/goccy/go-json\"\n\"github.com/google/uuid\"\n\"github.com/gorilla/websocket\"\n@@ -79,7 +80,7 @@ func NewTokenPayload(token []byte) (*tokens.WebsocketPayload, error) {\n}\n// GetHandler returns a new websocket handler using the context provided.\n-func GetHandler(s *server.Server, w http.ResponseWriter, r *http.Request) (*Handler, error) {\n+func GetHandler(s *server.Server, w http.ResponseWriter, r *http.Request, c *gin.Context) (*Handler, error) {\nupgrader := websocket.Upgrader{\n// Ensure that the websocket request is originating from the Panel itself,\n// and not some other location.\n@@ -111,7 +112,7 @@ func GetHandler(s *server.Server, w http.ResponseWriter, r *http.Request) (*Hand\nConnection: conn,\njwt: nil,\nserver: s,\n- ra: s.NewRequestActivity(\"\", r.RemoteAddr),\n+ ra: s.NewRequestActivity(\"\", c.ClientIP()),\nuuid: u,\n}, nil\n}\n" } ]
Go
MIT License
pterodactyl/wings
Add configuration for trusted proxies (#141)
532,332
05.10.2022 02:12:13
-7,200
0637eebefecd90819e6c98c99b56a0dc33ee6063
docker: add configuration for user namespace remapping
[ { "change_type": "MODIFY", "old_path": "config/config_docker.go", "new_path": "config/config_docker.go", "diff": "@@ -78,6 +78,14 @@ type DockerConfiguration struct {\nOverhead Overhead `json:\"overhead\" yaml:\"overhead\"`\nUsePerformantInspect bool `default:\"true\" json:\"use_performant_inspect\" yaml:\"use_performant_inspect\"`\n+\n+ // Sets the user namespace mode for the container when user namespace remapping option is\n+ // enabled.\n+ //\n+ // If the value is blank, the daemon's user namespace remapping configuration is used,\n+ // if the value is \"host\", then the pterodactyl containers are started with user namespace\n+ // remapping disabled\n+ UsernsMode string `default:\"\" json:\"userns_mode\" yaml:\"userns_mode\"`\n}\n// RegistryConfiguration defines the authentication credentials for a given\n" }, { "change_type": "MODIFY", "old_path": "environment/docker/container.go", "new_path": "environment/docker/container.go", "diff": "@@ -261,6 +261,7 @@ func (e *Environment) Create() error {\n\"fowner\", \"fsetid\", \"net_bind_service\", \"sys_chroot\", \"setfcap\",\n},\nNetworkMode: networkMode,\n+ UsernsMode: container.UsernsMode(config.Get().Docker.UsernsMode),\n}\nif _, err := e.client.ContainerCreate(ctx, conf, hostConf, nil, nil, e.Id); err != nil {\n" }, { "change_type": "MODIFY", "old_path": "server/install.go", "new_path": "server/install.go", "diff": "@@ -449,6 +449,7 @@ func (ip *InstallationProcess) Execute() (string, error) {\n},\nPrivileged: true,\nNetworkMode: container.NetworkMode(config.Get().Docker.Network.Mode),\n+ UsernsMode: container.UsernsMode(config.Get().Docker.UsernsMode),\n}\n// Ensure the root directory for the server exists properly before attempting\n" } ]
Go
MIT License
pterodactyl/wings
docker: add configuration for user namespace remapping (#121)
532,314
04.10.2022 20:35:48
21,600
6fb61261b0f37f87ec87c0ff5faacebe2fa36a70
server(transfers): track progress of archive creation and extraction
[ { "change_type": "MODIFY", "old_path": "router/router_transfer.go", "new_path": "router/router_transfer.go", "diff": "@@ -12,7 +12,6 @@ import (\n\"path/filepath\"\n\"strconv\"\n\"strings\"\n- \"sync/atomic\"\n\"time\"\n\"emperror.dev/errors\"\n@@ -30,19 +29,9 @@ import (\n\"github.com/pterodactyl/wings/router/tokens\"\n\"github.com/pterodactyl/wings/server\"\n\"github.com/pterodactyl/wings/server/filesystem\"\n- \"github.com/pterodactyl/wings/system\"\n)\n-// Number of ticks in the progress bar\n-const ticks = 25\n-\n-// 100% / number of ticks = percentage represented by each tick\n-const tickPercentage = 100 / ticks\n-\n-type downloadProgress struct {\n- size int64\n- progress int64\n-}\n+const progressWidth = 25\n// Data passed over to initiate a server transfer.\ntype serverTransferRequest struct {\n@@ -95,7 +84,7 @@ func getServerArchive(c *gin.Context) {\nreturn\n}\n- // Compute sha1 checksum.\n+ // Compute sha256 checksum.\nh := sha256.New()\nf, err := os.Open(archivePath)\nif err != nil {\n@@ -184,10 +173,34 @@ func postServerArchive(c *gin.Context) {\nreturn\n}\n+ // Get the disk usage of the server (used to calculate the progress of the archive process)\n+ rawSize, err := s.Filesystem().DiskUsage(true)\n+ if err != nil {\n+ sendTransferLog(\"Failed to get disk usage for server, aborting transfer..\")\n+ l.WithField(\"error\", err).Error(\"failed to get disk usage for server\")\n+ return\n+ }\n+\n// Create an archive of the entire server's data directory.\na := &filesystem.Archive{\nBasePath: s.Filesystem().Path(),\n+ Progress: filesystem.NewProgress(rawSize),\n+ }\n+\n+ // Send the archive progress to the websocket every 3 seconds.\n+ ctx, cancel := context.WithCancel(s.Context())\n+ defer cancel()\n+ go func(ctx context.Context, p *filesystem.Progress, t *time.Ticker) {\n+ defer t.Stop()\n+ for {\n+ select {\n+ case <-ctx.Done():\n+ return\n+ case <-t.C:\n+ sendTransferLog(\"Archiving \" + p.Progress(progressWidth))\n+ }\n}\n+ }(ctx, a.Progress, time.NewTicker(5*time.Second))\n// Attempt to get an archive of the server.\nif err := a.Create(getArchivePath(s.ID())); err != nil {\n@@ -196,6 +209,12 @@ func postServerArchive(c *gin.Context) {\nreturn\n}\n+ // Cancel the progress ticker.\n+ cancel()\n+\n+ // Show 100% completion.\n+ sendTransferLog(\"Archiving \" + a.Progress.Progress(progressWidth))\n+\nsendTransferLog(\"Successfully created archive, attempting to notify panel..\")\nl.Info(\"successfully created server transfer archive, notifying panel..\")\n@@ -223,12 +242,6 @@ func postServerArchive(c *gin.Context) {\nc.Status(http.StatusAccepted)\n}\n-func (w *downloadProgress) Write(v []byte) (int, error) {\n- n := len(v)\n- atomic.AddInt64(&w.progress, int64(n))\n- return n, nil\n-}\n-\n// Log helper function to attach all errors and info output to a consistently formatted\n// log string for easier querying.\nfunc (str serverTransferRequest) log() *log.Entry {\n@@ -321,7 +334,7 @@ func postTransfer(c *gin.Context) {\nmanager := middleware.ExtractManager(c)\nu, err := uuid.Parse(data.ServerID)\nif err != nil {\n- WithError(c, err)\n+ _ = WithError(c, err)\nreturn\n}\n// Force the server ID to be a valid UUID string at this point. If it is not an error\n@@ -331,11 +344,12 @@ func postTransfer(c *gin.Context) {\ndata.log().Info(\"handling incoming server transfer request\")\ngo func(data *serverTransferRequest) {\n+ ctx := context.Background()\nhasError := true\n// Create a new server installer. This will only configure the environment and not\n// run the installer scripts.\n- i, err := installer.New(context.Background(), manager, data.Server)\n+ i, err := installer.New(ctx, manager, data.Server)\nif err != nil {\n_ = data.sendTransferStatus(manager.Client(), false)\ndata.log().WithField(\"error\", err).Error(\"failed to validate received server data\")\n@@ -407,25 +421,22 @@ func postTransfer(c *gin.Context) {\nsendTransferLog(\"Writing archive to disk...\")\ndata.log().Info(\"writing transfer archive to disk...\")\n- // Copy the file.\n- progress := &downloadProgress{size: size}\n- ticker := time.NewTicker(3 * time.Second)\n- go func(progress *downloadProgress, t *time.Ticker) {\n- for range ticker.C {\n- // p = 100 (Downloaded)\n- // size = 1000 (Content-Length)\n- // p / size = 0.1\n- // * 100 = 10% (Multiply by 100 to get a percentage of the download)\n- // 10% / tickPercentage = (10% / (100 / 25)) (Divide by tick percentage to get the number of ticks)\n- // 2.5 (Number of ticks as a float64)\n- // 2 (convert to an integer)\n- p := atomic.LoadInt64(&progress.progress)\n- // We have to cast these numbers to float in order to get a float result from the division.\n- width := ((float64(p) / float64(size)) * 100) / tickPercentage\n- bar := strings.Repeat(\"=\", int(width)) + strings.Repeat(\" \", ticks-int(width))\n- sendTransferLog(\"Downloading [\" + bar + \"] \" + system.FormatBytes(p) + \" / \" + system.FormatBytes(progress.size))\n- }\n- }(progress, ticker)\n+ progress := filesystem.NewProgress(size)\n+\n+ // Send the archive progress to the websocket every 3 seconds.\n+ ctx, cancel := context.WithCancel(ctx)\n+ defer cancel()\n+ go func(ctx context.Context, p *filesystem.Progress, t *time.Ticker) {\n+ defer t.Stop()\n+ for {\n+ select {\n+ case <-ctx.Done():\n+ return\n+ case <-t.C:\n+ sendTransferLog(\"Downloading \" + p.Progress(progressWidth))\n+ }\n+ }\n+ }(ctx, progress, time.NewTicker(5*time.Second))\nvar reader io.Reader\ndownloadLimit := float64(config.Get().System.Transfers.DownloadLimit) * 1024 * 1024\n@@ -438,18 +449,16 @@ func postTransfer(c *gin.Context) {\nbuf := make([]byte, 1024*4)\nif _, err := io.CopyBuffer(file, io.TeeReader(reader, progress), buf); err != nil {\n- ticker.Stop()\n_ = file.Close()\nsendTransferLog(\"Failed while writing archive file to disk: \" + err.Error())\ndata.log().WithField(\"error\", err).Error(\"failed to copy archive file to disk\")\nreturn\n}\n- ticker.Stop()\n+ cancel()\n// Show 100% completion.\n- humanSize := system.FormatBytes(progress.size)\n- sendTransferLog(\"Downloading [\" + strings.Repeat(\"=\", ticks) + \"] \" + humanSize + \" / \" + humanSize)\n+ sendTransferLog(\"Downloading \" + progress.Progress(progressWidth))\nif err := file.Close(); err != nil {\ndata.log().WithField(\"error\", err).Error(\"unable to close archive file on local filesystem\")\n" }, { "change_type": "MODIFY", "old_path": "server/filesystem/archive.go", "new_path": "server/filesystem/archive.go", "diff": "@@ -8,6 +8,7 @@ import (\n\"path/filepath\"\n\"strings\"\n\"sync\"\n+ \"sync/atomic\"\n\"emperror.dev/errors\"\n\"github.com/apex/log\"\n@@ -17,6 +18,7 @@ import (\nignore \"github.com/sabhiram/go-gitignore\"\n\"github.com/pterodactyl/wings/config\"\n+ \"github.com/pterodactyl/wings/system\"\n)\nconst memory = 4 * 1024\n@@ -28,6 +30,62 @@ var pool = sync.Pool{\n},\n}\n+// Progress is used to track the progress of any I/O operation that are being\n+// performed.\n+type Progress struct {\n+ // written is the total size of the files that have been written to the writer.\n+ written int64\n+ // Total is the total size of the archive in bytes.\n+ total int64\n+ // w .\n+ w io.Writer\n+}\n+\n+// NewProgress .\n+func NewProgress(total int64) *Progress {\n+ return &Progress{total: total}\n+}\n+\n+// Written returns the total number of bytes written.\n+// This function should be used when the progress is tracking data being written.\n+func (p *Progress) Written() int64 {\n+ return atomic.LoadInt64(&p.written)\n+}\n+\n+// Total returns the total size in bytes.\n+func (p *Progress) Total() int64 {\n+ return atomic.LoadInt64(&p.total)\n+}\n+\n+// Write totals the number of bytes that have been written to the writer.\n+func (p *Progress) Write(v []byte) (int, error) {\n+ n := len(v)\n+ atomic.AddInt64(&p.written, int64(n))\n+ if p.w != nil {\n+ return p.w.Write(v)\n+ }\n+ return n, nil\n+}\n+\n+// Progress returns a formatted progress string for the current progress.\n+func (p *Progress) Progress(width int) string {\n+ current := p.Written()\n+ total := p.Total()\n+\n+ // v = 100 (Progress)\n+ // size = 1000 (Content-Length)\n+ // p / size = 0.1\n+ // * 100 = 10% (Multiply by 100 to get a percentage of the download)\n+ // 10% / tickPercentage = (10% / (100 / 25)) (Divide by tick percentage to get the number of ticks)\n+ // 2.5 (Number of ticks as a float64)\n+ // 2 (convert to an integer)\n+\n+ // We have to cast these numbers to float in order to get a float result from the division.\n+ ticks := ((float64(current) / float64(total)) * 100) / (float64(100) / float64(width))\n+ bar := strings.Repeat(\"=\", int(ticks)) + strings.Repeat(\" \", width-int(ticks))\n+ return \"[\" + bar + \"] \" + system.FormatBytes(current) + \" / \" + system.FormatBytes(total)\n+}\n+\ntype Archive struct {\n// BasePath is the absolute path to create the archive from where Files and Ignore are\n// relative to.\n@@ -40,10 +98,13 @@ type Archive struct {\n// Files specifies the files to archive, this takes priority over the Ignore option, if\n// unspecified, all files in the BasePath will be archived unless Ignore is set.\nFiles []string\n+\n+ // Progress wraps the writer of the archive to pass through the progress tracker.\n+ Progress *Progress\n}\n-// Create creates an archive at dst with all of the files defined in the\n-// included files struct.\n+// Create creates an archive at dst with all the files defined in the\n+// included Files array.\nfunc (a *Archive) Create(dst string) error {\nf, err := os.OpenFile(dst, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0o600)\nif err != nil {\n@@ -62,26 +123,34 @@ func (a *Archive) Create(dst string) error {\nwriter = f\n}\n- // The default compression level is BestSpeed\n- var cl = pgzip.BestSpeed\n-\n// Choose which compression level to use based on the compression_level configuration option\n+ var compressionLevel int\nswitch config.Get().System.Backups.CompressionLevel {\ncase \"none\":\n- cl = pgzip.NoCompression\n- case \"best_speed\":\n- cl = pgzip.BestSpeed\n+ compressionLevel = pgzip.NoCompression\ncase \"best_compression\":\n- cl = pgzip.BestCompression\n+ compressionLevel = pgzip.BestCompression\n+ case \"best_speed\":\n+ fallthrough\n+ default:\n+ compressionLevel = pgzip.BestSpeed\n}\n// Create a new gzip writer around the file.\n- gw, _ := pgzip.NewWriterLevel(writer, cl)\n+ gw, _ := pgzip.NewWriterLevel(writer, compressionLevel)\n_ = gw.SetConcurrency(1<<20, 1)\ndefer gw.Close()\n+ var pw io.Writer\n+ if a.Progress != nil {\n+ a.Progress.w = gw\n+ pw = a.Progress\n+ } else {\n+ pw = gw\n+ }\n+\n// Create a new tar writer around the gzip writer.\n- tw := tar.NewWriter(gw)\n+ tw := tar.NewWriter(pw)\ndefer tw.Close()\n// Configure godirwalk.\n@@ -116,7 +185,7 @@ func (a *Archive) Create(dst string) error {\n// being generated.\nfunc (a *Archive) callback(tw *tar.Writer, opts ...func(path string, relative string) error) func(path string, de *godirwalk.Dirent) error {\nreturn func(path string, de *godirwalk.Dirent) error {\n- // Skip directories because we walking them recursively.\n+ // Skip directories because we are walking them recursively.\nif de.IsDir() {\nreturn nil\n}\n" } ]
Go
MIT License
pterodactyl/wings
server(transfers): track progress of archive creation and extraction (#143)
532,335
17.10.2022 01:17:27
-7,200
5a760a0dcc3327912cf2c98aa5292d46a7b14b90
Add customizable container labels
[ { "change_type": "MODIFY", "old_path": "config/config.go", "new_path": "config/config.go", "diff": "@@ -16,8 +16,8 @@ import (\n\"time\"\n\"emperror.dev/errors\"\n+ \"github.com/acobaugh/osrelease\"\n\"github.com/apex/log\"\n- \"github.com/cobaugh/osrelease\"\n\"github.com/creasty/defaults\"\n\"github.com/gbrlsnchs/jwt/v3\"\n\"gopkg.in/yaml.v2\"\n" }, { "change_type": "MODIFY", "old_path": "environment/config.go", "new_path": "environment/config.go", "diff": "@@ -8,6 +8,7 @@ type Settings struct {\nMounts []Mount\nAllocations Allocations\nLimits Limits\n+ Labels map[string]string\n}\n// Defines the actual configuration struct for the environment with all of the settings\n@@ -68,6 +69,14 @@ func (c *Configuration) Mounts() []Mount {\nreturn c.settings.Mounts\n}\n+// Labels returns the container labels associated with this instance.\n+func (c *Configuration) Labels() map[string]string {\n+ c.mu.RLock()\n+ defer c.mu.RUnlock()\n+\n+ return c.settings.Labels\n+}\n+\n// Returns the environment variables associated with this instance.\nfunc (c *Configuration) EnvironmentVariables() []string {\nc.mu.RLock()\n" }, { "change_type": "MODIFY", "old_path": "environment/docker/container.go", "new_path": "environment/docker/container.go", "diff": "@@ -174,6 +174,16 @@ func (e *Environment) Create() error {\n}\n}\n+ // Merge user-provided labels with system labels\n+ confLabels := e.Configuration.Labels()\n+ labels := make(map[string]string, 2+len(confLabels))\n+\n+ for key := range confLabels {\n+ labels[key] = confLabels[key]\n+ }\n+ labels[\"Service\"] = \"Pterodactyl\"\n+ labels[\"ContainerType\"] = \"server_process\"\n+\nconf := &container.Config{\nHostname: e.Id,\nDomainname: config.Get().Docker.Domainname,\n@@ -186,10 +196,7 @@ func (e *Environment) Create() error {\nExposedPorts: a.Exposed(),\nImage: strings.TrimPrefix(e.meta.Image, \"~\"),\nEnv: e.Configuration.EnvironmentVariables(),\n- Labels: map[string]string{\n- \"Service\": \"Pterodactyl\",\n- \"ContainerType\": \"server_process\",\n- },\n+ Labels: labels,\n}\nnetworkMode := container.NetworkMode(config.Get().Docker.Network.Mode)\n" }, { "change_type": "MODIFY", "old_path": "go.mod", "new_path": "go.mod", "diff": "@@ -7,12 +7,12 @@ require (\ngithub.com/AlecAivazis/survey/v2 v2.3.6\ngithub.com/Jeffail/gabs/v2 v2.6.1\ngithub.com/NYTimes/logrotate v1.0.0\n+ github.com/acobaugh/osrelease v0.1.0\ngithub.com/apex/log v1.9.0\ngithub.com/asaskevich/govalidator v0.0.0-20210307081110-f21760c49a8d\ngithub.com/beevik/etree v1.1.0\ngithub.com/buger/jsonparser v1.1.1\ngithub.com/cenkalti/backoff/v4 v4.1.3\n- github.com/cobaugh/osrelease v0.0.0-20181218015638-a93a0a55a249\ngithub.com/creasty/defaults v1.6.0\ngithub.com/docker/docker v20.10.18+incompatible\ngithub.com/docker/go-connections v0.4.0\n" }, { "change_type": "MODIFY", "old_path": "go.sum", "new_path": "go.sum", "diff": "@@ -87,6 +87,8 @@ github.com/PuerkitoBio/purell v1.1.1/go.mod h1:c11w/QuzBsJSee3cPx9rAFu61PvFxuPbt\ngithub.com/PuerkitoBio/urlesc v0.0.0-20160726150825-5bd2802263f2/go.mod h1:uGdkoq3SwY9Y+13GIhn11/XLaGBb4BfwItxLd5jeuXE=\ngithub.com/PuerkitoBio/urlesc v0.0.0-20170810143723-de5bf2ad4578/go.mod h1:uGdkoq3SwY9Y+13GIhn11/XLaGBb4BfwItxLd5jeuXE=\ngithub.com/Shopify/logrus-bugsnag v0.0.0-20171204204709-577dee27f20d/go.mod h1:HI8ITrYtUY+O+ZhtlqUnD8+KwNPOyugEhfP9fdUIaEQ=\n+github.com/acobaugh/osrelease v0.1.0 h1:Yb59HQDGGNhCj4suHaFQQfBps5wyoKLSSX/J/+UifRE=\n+github.com/acobaugh/osrelease v0.1.0/go.mod h1:4bFEs0MtgHNHBrmHCt67gNisnabCRAlzdVasCEGHTWY=\ngithub.com/alecthomas/template v0.0.0-20160405071501-a0175ee3bccc/go.mod h1:LOuyumcjzFXgccqObfd/Ljyb9UuFJ6TxHnclSeseNhc=\ngithub.com/alecthomas/template v0.0.0-20190718012654-fb15b899a751/go.mod h1:LOuyumcjzFXgccqObfd/Ljyb9UuFJ6TxHnclSeseNhc=\ngithub.com/alecthomas/units v0.0.0-20151022065526-2efee857e7cf/go.mod h1:ybxpYRFXyAe+OPACYpWeL0wqObRcbAqCMya13uyzqw0=\n@@ -151,8 +153,6 @@ github.com/client9/misspell v0.3.4/go.mod h1:qj6jICC3Q7zFZvVWo7KLAzC3yx5G7kyvSDk\ngithub.com/cncf/udpa/go v0.0.0-20191209042840-269d4d468f6f/go.mod h1:M8M6+tZqaGXZJjfX53e64911xZQV5JYwmTeXPW+k8Sc=\ngithub.com/cncf/udpa/go v0.0.0-20201120205902-5459f2c99403/go.mod h1:WmhPx2Nbnhtbo57+VJT5O0JRkEi1Wbu0z5j0R8u5Hbk=\ngithub.com/cncf/xds/go v0.0.0-20210312221358-fbca930ec8ed/go.mod h1:eXthEFrGJvWHgFFCl3hGmgk+/aYT6PnTQLykKQRLhEs=\n-github.com/cobaugh/osrelease v0.0.0-20181218015638-a93a0a55a249 h1:R0IDH8daQ3lODvu8YtxnIqqth5qMGCJyADoUQvmLx4o=\n-github.com/cobaugh/osrelease v0.0.0-20181218015638-a93a0a55a249/go.mod h1:EHKW9yNEYSBpTKzuu7Y9oOrft/UlzH57rMIB03oev6M=\ngithub.com/cockroachdb/datadriven v0.0.0-20190809214429-80d97fb3cbaa/go.mod h1:zn76sxSg3SzpJ0PPJaLDCu+Bu0Lg3sKTORVIj19EIF8=\ngithub.com/containerd/aufs v0.0.0-20200908144142-dab0cbea06f4/go.mod h1:nukgQABAEopAHvB6j7cnP5zJ+/3aVcE7hCYqvIwAHyE=\ngithub.com/containerd/aufs v0.0.0-20201003224125-76a6863f2989/go.mod h1:AkGGQs9NM2vtYHaUen+NljV0/baGCAPELGm2q9ZXpWU=\n" }, { "change_type": "MODIFY", "old_path": "server/configuration.go", "new_path": "server/configuration.go", "diff": "@@ -46,6 +46,9 @@ type Configuration struct {\n// server process.\nEnvVars environment.Variables `json:\"environment\"`\n+ // Labels is a map of container labels that should be applied to the running server process.\n+ Labels map[string]string `json:\"labels\"`\n+\nAllocations environment.Allocations `json:\"allocations\"`\nBuild environment.Limits `json:\"build\"`\nCrashDetectionEnabled bool `json:\"crash_detection_enabled\"`\n" }, { "change_type": "MODIFY", "old_path": "server/manager.go", "new_path": "server/manager.go", "diff": "@@ -205,6 +205,7 @@ func (m *Manager) InitServer(data remote.ServerConfigurationResponse) (*Server,\nMounts: s.Mounts(),\nAllocations: s.cfg.Allocations,\nLimits: s.cfg.Build,\n+ Labels: s.cfg.Labels,\n}\nenvCfg := environment.NewConfiguration(settings, s.GetEnvironmentVariables())\n" } ]
Go
MIT License
pterodactyl/wings
Add customizable container labels (#146)
532,314
06.11.2022 13:33:01
25,200
33373629558700956700d455c533ae6a7d4af8f8
environment(docker): fix podman compatibility
[ { "change_type": "MODIFY", "old_path": ".gitignore", "new_path": ".gitignore", "diff": "# ignore configuration file\n/config.yml\n/config*.yml\n+/config.yaml\n+/config*.yaml\n# Ignore Vagrant stuff\n/.vagrant\n" }, { "change_type": "MODIFY", "old_path": "cmd/diagnostics.go", "new_path": "cmd/diagnostics.go", "diff": "@@ -65,7 +65,7 @@ func newDiagnosticsCommand() *cobra.Command {\n// - the docker debug output\n// - running docker containers\n// - logs\n-func diagnosticsCmdRun(cmd *cobra.Command, args []string) {\n+func diagnosticsCmdRun(*cobra.Command, []string) {\nquestions := []*survey.Question{\n{\nName: \"IncludeEndpoints\",\n" }, { "change_type": "MODIFY", "old_path": "cmd/root.go", "new_path": "cmd/root.go", "diff": "@@ -16,9 +16,6 @@ import (\n\"strings\"\n\"time\"\n- \"github.com/pterodactyl/wings/internal/cron\"\n- \"github.com/pterodactyl/wings/internal/database\"\n-\n\"github.com/NYTimes/logrotate\"\n\"github.com/apex/log\"\n\"github.com/apex/log/handlers/multi\"\n@@ -31,6 +28,8 @@ import (\n\"github.com/pterodactyl/wings/config\"\n\"github.com/pterodactyl/wings/environment\"\n+ \"github.com/pterodactyl/wings/internal/cron\"\n+ \"github.com/pterodactyl/wings/internal/database\"\n\"github.com/pterodactyl/wings/loggers/cli\"\n\"github.com/pterodactyl/wings/remote\"\n\"github.com/pterodactyl/wings/router\"\n@@ -111,7 +110,6 @@ func rootCmdRun(cmd *cobra.Command, _ []string) {\nlog.WithField(\"error\", err).Fatal(\"failed to configure system directories for pterodactyl\")\nreturn\n}\n- log.WithField(\"username\", config.Get().System.User).Info(\"checking for pterodactyl system user\")\nif err := config.EnsurePterodactylUser(); err != nil {\nlog.WithField(\"error\", err).Fatal(\"failed to create pterodactyl system user\")\n}\n@@ -364,7 +362,7 @@ func rootCmdRun(cmd *cobra.Command, _ []string) {\nreturn\n}\n- // Check if main http server should run with TLS. Otherwise reset the TLS\n+ // Check if main http server should run with TLS. Otherwise, reset the TLS\n// config on the server and then serve it over normal HTTP.\nif api.Ssl.Enabled {\nif err := s.ListenAndServeTLS(api.Ssl.CertificateFile, api.Ssl.KeyFile); err != nil {\n" }, { "change_type": "MODIFY", "old_path": "config/config.go", "new_path": "config/config.go", "diff": "@@ -152,9 +152,23 @@ type SystemConfiguration struct {\n// Definitions for the user that gets created to ensure that we can quickly access\n// this information without constantly having to do a system lookup.\nUser struct {\n- Uid int\n- Gid int\n- }\n+ // Rootless controls settings related to rootless container daemons.\n+ Rootless struct {\n+ // Enabled controls whether rootless containers are enabled.\n+ Enabled bool `yaml:\"enabled\" default:\"false\"`\n+ // ContainerUID controls the UID of the user inside the container.\n+ // This should likely be set to 0 so the container runs as the user\n+ // running Wings.\n+ ContainerUID int `yaml:\"container_uid\" default:\"0\"`\n+ // ContainerGID controls the GID of the user inside the container.\n+ // This should likely be set to 0 so the container runs as the user\n+ // running Wings.\n+ ContainerGID int `yaml:\"container_gid\" default:\"0\"`\n+ } `yaml:\"rootless\"`\n+\n+ Uid int `yaml:\"uid\"`\n+ Gid int `yaml:\"gid\"`\n+ } `yaml:\"user\"`\n// The amount of time in seconds that can elapse before a server's disk space calculation is\n// considered stale and a re-check should occur. DANGER: setting this value too low can seriously\n@@ -425,6 +439,19 @@ func EnsurePterodactylUser() error {\nreturn nil\n}\n+ if _config.System.User.Rootless.Enabled {\n+ log.Info(\"rootless mode is enabled, skipping user creation...\")\n+ u, err := user.Current()\n+ if err != nil {\n+ return err\n+ }\n+ _config.System.Username = u.Username\n+ _config.System.User.Uid = system.MustInt(u.Uid)\n+ _config.System.User.Gid = system.MustInt(u.Gid)\n+ return nil\n+ }\n+\n+ log.WithField(\"username\", _config.System.Username).Info(\"checking for pterodactyl system user\")\nu, err := user.Lookup(_config.System.Username)\n// If an error is returned but it isn't the unknown user error just abort\n// the process entirely. If we did find a user, return it immediately.\n" }, { "change_type": "MODIFY", "old_path": "config/config_docker.go", "new_path": "config/config_docker.go", "diff": "@@ -5,6 +5,7 @@ import (\n\"sort\"\n\"github.com/docker/docker/api/types\"\n+ \"github.com/docker/docker/api/types/container\"\n\"github.com/goccy/go-json\"\n)\n@@ -86,6 +87,22 @@ type DockerConfiguration struct {\n// if the value is \"host\", then the pterodactyl containers are started with user namespace\n// remapping disabled\nUsernsMode string `default:\"\" json:\"userns_mode\" yaml:\"userns_mode\"`\n+\n+ LogConfig struct {\n+ Type string `default:\"local\" json:\"type\" yaml:\"type\"`\n+ Config map[string]string `default:\"{\\\"max-size\\\":\\\"5m\\\",\\\"max-file\\\":\\\"1\\\",\\\"compress\\\":\\\"false\\\",\\\"mode\\\":\\\"non-blocking\\\"}\" json:\"config\" yaml:\"config\"`\n+ } `json:\"log_config\" yaml:\"log_config\"`\n+}\n+\n+func (c DockerConfiguration) ContainerLogConfig() container.LogConfig {\n+ if c.LogConfig.Type == \"\" {\n+ return container.LogConfig{}\n+ }\n+\n+ return container.LogConfig{\n+ Type: c.LogConfig.Type,\n+ Config: c.LogConfig.Config,\n+ }\n}\n// RegistryConfiguration defines the authentication credentials for a given\n" }, { "change_type": "MODIFY", "old_path": "environment/docker/container.go", "new_path": "environment/docker/container.go", "diff": "@@ -16,7 +16,6 @@ import (\n\"github.com/docker/docker/api/types/container\"\n\"github.com/docker/docker/api/types/mount\"\n\"github.com/docker/docker/client\"\n- \"github.com/docker/docker/daemon/logger/local\"\n\"github.com/pterodactyl/wings/config\"\n\"github.com/pterodactyl/wings/environment\"\n@@ -43,17 +42,13 @@ func (nw noopWriter) Write(b []byte) (int, error) {\n//\n// Calling this function will poll resources for the container in the background\n// until the container is stopped. The context provided to this function is used\n-// for the purposes of attaching to the container, a seecond context is created\n+// for the purposes of attaching to the container, a second context is created\n// within the function for managing polling.\nfunc (e *Environment) Attach(ctx context.Context) error {\nif e.IsAttached() {\nreturn nil\n}\n- if err := e.followOutput(); err != nil {\n- return err\n- }\n-\nopts := types.ContainerAttachOptions{\nStdin: true,\nStdout: true,\n@@ -90,20 +85,13 @@ func (e *Environment) Attach(ctx context.Context) error {\n}\n}()\n- // Block the completion of this routine until the container is no longer running. This allows\n- // the pollResources function to run until it needs to be stopped. Because the container\n- // can be polled for resource usage, even when stopped, we need to have this logic present\n- // in order to cancel the context and therefore stop the routine that is spawned.\n- //\n- // For now, DO NOT use client#ContainerWait from the Docker package. There is a nasty\n- // bug causing containers to hang on deletion and cause servers to lock up on the system.\n- //\n- // This weird code isn't intuitive, but it keeps the function from ending until the container\n- // is stopped and therefore the stream reader ends up closed.\n- // @see https://github.com/moby/moby/issues/41827\n- c := new(noopWriter)\n- if _, err := io.Copy(c, e.stream.Reader); err != nil {\n- e.log().WithField(\"error\", err).Error(\"could not copy from environment stream to noop writer\")\n+ if err := system.ScanReader(e.stream.Reader, func(v []byte) {\n+ e.logCallbackMx.Lock()\n+ defer e.logCallbackMx.Unlock()\n+ e.logCallback(v)\n+ }); err != nil && err != io.EOF {\n+ log.WithField(\"error\", err).WithField(\"container_id\", e.Id).Warn(\"error processing scanner line in console output\")\n+ return\n}\n}()\n@@ -163,14 +151,14 @@ func (e *Environment) Create() error {\nreturn errors.WithStackIf(err)\n}\n+ cfg := config.Get()\na := e.Configuration.Allocations()\n-\nevs := e.Configuration.EnvironmentVariables()\nfor i, v := range evs {\n// Convert 127.0.0.1 to the pterodactyl0 network interface if the environment is Docker\n// so that the server operates as expected.\nif v == \"SERVER_IP=127.0.0.1\" {\n- evs[i] = \"SERVER_IP=\" + config.Get().Docker.Network.Interface\n+ evs[i] = \"SERVER_IP=\" + cfg.Docker.Network.Interface\n}\n}\n@@ -186,8 +174,7 @@ func (e *Environment) Create() error {\nconf := &container.Config{\nHostname: e.Id,\n- Domainname: config.Get().Docker.Domainname,\n- User: strconv.Itoa(config.Get().System.User.Uid) + \":\" + strconv.Itoa(config.Get().System.User.Gid),\n+ Domainname: cfg.Docker.Domainname,\nAttachStdin: true,\nAttachStdout: true,\nAttachStderr: true,\n@@ -199,7 +186,14 @@ func (e *Environment) Create() error {\nLabels: labels,\n}\n- networkMode := container.NetworkMode(config.Get().Docker.Network.Mode)\n+ // Set the user running the container properly depending on what mode we are operating in.\n+ if cfg.System.User.Rootless.Enabled {\n+ conf.User = fmt.Sprintf(\"%d:%d\", cfg.System.User.Rootless.ContainerUID, cfg.System.User.Rootless.ContainerGID)\n+ } else {\n+ conf.User = strconv.Itoa(cfg.System.User.Uid) + \":\" + strconv.Itoa(cfg.System.User.Gid)\n+ }\n+\n+ networkMode := container.NetworkMode(cfg.Docker.Network.Mode)\nif a.ForceOutgoingIP {\ne.log().Debug(\"environment/docker: forcing outgoing IP address\")\nnetworkName := strings.ReplaceAll(e.Id, \"-\", \"\")\n@@ -238,28 +232,20 @@ func (e *Environment) Create() error {\n// Configure the /tmp folder mapping in containers. This is necessary for some\n// games that need to make use of it for downloads and other installation processes.\nTmpfs: map[string]string{\n- \"/tmp\": \"rw,exec,nosuid,size=\" + strconv.Itoa(int(config.Get().Docker.TmpfsSize)) + \"M\",\n+ \"/tmp\": \"rw,exec,nosuid,size=\" + strconv.Itoa(int(cfg.Docker.TmpfsSize)) + \"M\",\n},\n// Define resource limits for the container based on the data passed through\n// from the Panel.\nResources: e.Configuration.Limits().AsContainerResources(),\n- DNS: config.Get().Docker.Network.Dns,\n+ DNS: cfg.Docker.Network.Dns,\n// Configure logging for the container to make it easier on the Daemon to grab\n// the server output. Ensure that we don't use too much space on the host machine\n// since we only need it for the last few hundred lines of output and don't care\n// about anything else in it.\n- LogConfig: container.LogConfig{\n- Type: local.Name,\n- Config: map[string]string{\n- \"max-size\": \"5m\",\n- \"max-file\": \"1\",\n- \"compress\": \"false\",\n- \"mode\": \"non-blocking\",\n- },\n- },\n+ LogConfig: cfg.Docker.ContainerLogConfig(),\nSecurityOpt: []string{\"no-new-privileges\"},\nReadonlyRootfs: true,\n@@ -268,7 +254,7 @@ func (e *Environment) Create() error {\n\"fowner\", \"fsetid\", \"net_bind_service\", \"sys_chroot\", \"setfcap\",\n},\nNetworkMode: networkMode,\n- UsernsMode: container.UsernsMode(config.Get().Docker.UsernsMode),\n+ UsernsMode: container.UsernsMode(cfg.Docker.UsernsMode),\n}\nif _, err := e.client.ContainerCreate(ctx, conf, hostConf, nil, nil, e.Id); err != nil {\n@@ -349,59 +335,6 @@ func (e *Environment) Readlog(lines int) ([]string, error) {\nreturn out, nil\n}\n-// Attaches to the log for the container. This avoids us missing crucial output\n-// that happens in the split seconds before the code moves from 'Starting' to\n-// 'Attaching' on the process.\n-func (e *Environment) followOutput() error {\n- if exists, err := e.Exists(); !exists {\n- if err != nil {\n- return err\n- }\n- return errors.New(fmt.Sprintf(\"no such container: %s\", e.Id))\n- }\n-\n- opts := types.ContainerLogsOptions{\n- ShowStderr: true,\n- ShowStdout: true,\n- Follow: true,\n- Since: time.Now().Format(time.RFC3339),\n- }\n-\n- reader, err := e.client.ContainerLogs(context.Background(), e.Id, opts)\n- if err != nil {\n- return err\n- }\n-\n- go e.scanOutput(reader)\n-\n- return nil\n-}\n-\n-func (e *Environment) scanOutput(reader io.ReadCloser) {\n- defer reader.Close()\n-\n- if err := system.ScanReader(reader, func(v []byte) {\n- e.logCallbackMx.Lock()\n- defer e.logCallbackMx.Unlock()\n- e.logCallback(v)\n- }); err != nil && err != io.EOF {\n- log.WithField(\"error\", err).WithField(\"container_id\", e.Id).Warn(\"error processing scanner line in console output\")\n- return\n- }\n-\n- // Return here if the server is offline or currently stopping.\n- if e.State() == environment.ProcessStoppingState || e.State() == environment.ProcessOfflineState {\n- return\n- }\n-\n- // Close the current reader before starting a new one, the defer will still run,\n- // but it will do nothing if we already closed the stream.\n- _ = reader.Close()\n-\n- // Start following the output of the server again.\n- go e.followOutput()\n-}\n-\n// Pulls the image from Docker. If there is an error while pulling the image\n// from the source but the image already exists locally, we will report that\n// error to the logger but continue with the process.\n" }, { "change_type": "MODIFY", "old_path": "environment/docker/environment.go", "new_path": "environment/docker/environment.go", "diff": "@@ -96,7 +96,7 @@ func (e *Environment) SetStream(s *types.HijackedResponse) {\ne.mu.Unlock()\n}\n-// IsAttached determine if the this process is currently attached to the\n+// IsAttached determines if this process is currently attached to the\n// container instance by checking if the stream is nil or not.\nfunc (e *Environment) IsAttached() bool {\ne.mu.RLock()\n" }, { "change_type": "MODIFY", "old_path": "environment/docker/power.go", "new_path": "environment/docker/power.go", "diff": "@@ -39,7 +39,7 @@ func (e *Environment) OnBeforeStart(ctx context.Context) error {\n//\n// This won't actually run an installation process however, it is just here to ensure the\n// environment gets created properly if it is missing and the server is started. We're making\n- // an assumption that all of the files will still exist at this point.\n+ // an assumption that all the files will still exist at this point.\nif err := e.Create(); err != nil {\nreturn err\n}\n@@ -107,7 +107,7 @@ func (e *Environment) Start(ctx context.Context) error {\n}\n// If we cannot start & attach to the container in 30 seconds something has gone\n- // quite sideways and we should stop trying to avoid a hanging situation.\n+ // quite sideways, and we should stop trying to avoid a hanging situation.\nactx, cancel := context.WithTimeout(ctx, time.Second*30)\ndefer cancel()\n" }, { "change_type": "MODIFY", "old_path": "environment/docker/stats.go", "new_path": "environment/docker/stats.go", "diff": "@@ -134,7 +134,11 @@ func calculateDockerAbsoluteCpu(pStats types.CPUStats, stats types.CPUStats) flo\npercent := 0.0\nif systemDelta > 0.0 && cpuDelta > 0.0 {\n- percent = (cpuDelta / systemDelta) * cpus * 100.0\n+ percent = (cpuDelta / systemDelta) * 100.0\n+\n+ if cpus > 0 {\n+ percent *= cpus\n+ }\n}\nreturn math.Round(percent*1000) / 1000\n" }, { "change_type": "MODIFY", "old_path": "server/install.go", "new_path": "server/install.go", "diff": "@@ -4,6 +4,7 @@ import (\n\"bufio\"\n\"bytes\"\n\"context\"\n+ \"fmt\"\n\"html/template\"\n\"io\"\n\"os\"\n@@ -419,7 +420,12 @@ func (ip *InstallationProcess) Execute() (string, error) {\n},\n}\n- tmpfsSize := strconv.Itoa(int(config.Get().Docker.TmpfsSize))\n+ cfg := config.Get()\n+ if cfg.System.User.Rootless.Enabled {\n+ conf.User = fmt.Sprintf(\"%d:%d\", cfg.System.User.Rootless.ContainerUID, cfg.System.User.Rootless.ContainerGID)\n+ }\n+\n+ tmpfsSize := strconv.Itoa(int(cfg.Docker.TmpfsSize))\nhostConf := &container.HostConfig{\nMounts: []mount.Mount{\n{\n@@ -439,18 +445,11 @@ func (ip *InstallationProcess) Execute() (string, error) {\nTmpfs: map[string]string{\n\"/tmp\": \"rw,exec,nosuid,size=\" + tmpfsSize + \"M\",\n},\n- DNS: config.Get().Docker.Network.Dns,\n- LogConfig: container.LogConfig{\n- Type: \"local\",\n- Config: map[string]string{\n- \"max-size\": \"5m\",\n- \"max-file\": \"1\",\n- \"compress\": \"false\",\n- },\n- },\n+ DNS: cfg.Docker.Network.Dns,\n+ LogConfig: cfg.Docker.ContainerLogConfig(),\nPrivileged: true,\n- NetworkMode: container.NetworkMode(config.Get().Docker.Network.Mode),\n- UsernsMode: container.UsernsMode(config.Get().Docker.UsernsMode),\n+ NetworkMode: container.NetworkMode(cfg.Docker.Network.Mode),\n+ UsernsMode: container.UsernsMode(cfg.Docker.UsernsMode),\n}\n// Ensure the root directory for the server exists properly before attempting\n" } ]
Go
MIT License
pterodactyl/wings
environment(docker): fix podman compatibility (#151)
532,314
06.11.2022 13:38:30
25,200
eb4df39d14506fea5da1a0cfe08c58e5a47c526a
server(filesystem): fix inaccurate archive progress
[ { "change_type": "MODIFY", "old_path": "go.mod", "new_path": "go.mod", "diff": "@@ -35,7 +35,7 @@ require (\ngithub.com/klauspost/pgzip v1.2.5\ngithub.com/magiconair/properties v1.8.6\ngithub.com/mattn/go-colorable v0.1.13\n- github.com/mholt/archiver/v3 v3.5.1\n+ github.com/mholt/archiver/v4 v4.0.0-alpha.7\ngithub.com/mitchellh/colorstring v0.0.0-20190213212951-d06e56a500db\ngithub.com/patrickmn/go-cache v2.1.0+incompatible\ngithub.com/pkg/sftp v1.13.5\n@@ -88,7 +88,7 @@ require (\ngithub.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect\ngithub.com/modern-go/reflect2 v1.0.2 // indirect\ngithub.com/morikuni/aec v1.0.0 // indirect\n- github.com/nwaples/rardecode v1.1.3 // indirect\n+ github.com/nwaples/rardecode/v2 v2.0.0-beta.2 // indirect\ngithub.com/opencontainers/go-digest v1.0.0 // indirect\ngithub.com/opencontainers/image-spec v1.1.0-rc2 // indirect\ngithub.com/pelletier/go-toml/v2 v2.0.5 // indirect\n@@ -103,9 +103,9 @@ require (\ngithub.com/robfig/cron/v3 v3.0.1 // indirect\ngithub.com/sirupsen/logrus v1.9.0 // indirect\ngithub.com/spf13/pflag v1.0.5 // indirect\n+ github.com/therootcompany/xz v1.0.1 // indirect\ngithub.com/ugorji/go/codec v1.2.7 // indirect\ngithub.com/ulikunitz/xz v0.5.10 // indirect\n- github.com/xi2/xz v0.0.0-20171230120015-48954b6210f8 // indirect\ngo.uber.org/atomic v1.10.0 // indirect\ngo.uber.org/multierr v1.8.0 // indirect\ngolang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4 // indirect\n" }, { "change_type": "MODIFY", "old_path": "go.sum", "new_path": "go.sum", "diff": "@@ -95,7 +95,6 @@ github.com/alecthomas/units v0.0.0-20151022065526-2efee857e7cf/go.mod h1:ybxpYRF\ngithub.com/alecthomas/units v0.0.0-20190717042225-c3de453c63f4/go.mod h1:ybxpYRFXyAe+OPACYpWeL0wqObRcbAqCMya13uyzqw0=\ngithub.com/alecthomas/units v0.0.0-20190924025748-f65c72e2690d/go.mod h1:rBZYJk541a8SKzHPHnH3zbiI+7dagKZ0cgpgrD7Fyho=\ngithub.com/alexflint/go-filemutex v0.0.0-20171022225611-72bdc8eae2ae/go.mod h1:CgnQgUtFrFz9mxFNtED3jI5tLDjKlOM+oUF/sTk6ps0=\n-github.com/andybalholm/brotli v1.0.1/go.mod h1:loMXtMfwqflxFJPmdbJO0a3KNoPuLBgiu3qAvBg8x/Y=\ngithub.com/andybalholm/brotli v1.0.4 h1:V7DdXeJtZscaqfNuAdSRuRFzuiKlHSC/Zh3zl9qY3JY=\ngithub.com/andybalholm/brotli v1.0.4/go.mod h1:fO7iG3H7G2nSZ7m0zPUDn85XEX2GTukHGRSepvi9Eig=\ngithub.com/antihax/optional v1.0.0/go.mod h1:uupD/76wgC+ih3iEmQUL+0Ugr19nfwCT1kdvxnR2qWY=\n@@ -429,7 +428,6 @@ github.com/golang/protobuf v1.4.3/go.mod h1:oDoupMAO8OvCJWAcko0GGGIgR6R6ocIYbsSw\ngithub.com/golang/protobuf v1.5.0/go.mod h1:FsONVRAS9T7sI+LIUmWTfcYkHO4aIWwzhcaSAoJOfIk=\ngithub.com/golang/protobuf v1.5.2 h1:ROPKBNFfQgOUMifHyP+KYbvpjbdoFNs+aK7DXlji0Tw=\ngithub.com/golang/protobuf v1.5.2/go.mod h1:XVQd3VNwM+JqD3oG2Ue2ip4fOMUkwXdXDdiuN0vRsmY=\n-github.com/golang/snappy v0.0.2/go.mod h1:/XxbfmMg8lxefKM7IXC3fBNl/7bRcc72aCRzEWrmP2Q=\ngithub.com/golang/snappy v0.0.4 h1:yAGX7huGHXlcLOEtBnF4w7FQwA26wojNCwOYAEhLjQM=\ngithub.com/golang/snappy v0.0.4/go.mod h1:/XxbfmMg8lxefKM7IXC3fBNl/7bRcc72aCRzEWrmP2Q=\ngithub.com/google/btree v0.0.0-20180813153112-4030bb1f1f0c/go.mod h1:lNA+9X1NB3Zf8V7Ke586lFgjr2dZNuvo3lPJSGZ5JPQ=\n@@ -544,7 +542,6 @@ github.com/kisielk/errcheck v1.5.0/go.mod h1:pFxgyoBC7bSaBwPgfKdkLd5X25qrDl4LWUI\ngithub.com/kisielk/gotool v1.0.0/go.mod h1:XhKaO+MFFWcvkIS/tQcRk01m1F5IRFswLeQ+oQHNcck=\ngithub.com/klauspost/compress v1.4.1/go.mod h1:RyIbtBH6LamlWaDj8nUwkbUhJ87Yi3uG0guNDohfE1A=\ngithub.com/klauspost/compress v1.11.3/go.mod h1:aoV0uJVorq1K+umq18yTdKaF57EivdYsUV+/s2qKfXs=\n-github.com/klauspost/compress v1.11.4/go.mod h1:aoV0uJVorq1K+umq18yTdKaF57EivdYsUV+/s2qKfXs=\ngithub.com/klauspost/compress v1.11.13/go.mod h1:aoV0uJVorq1K+umq18yTdKaF57EivdYsUV+/s2qKfXs=\ngithub.com/klauspost/compress v1.15.11 h1:Lcadnb3RKGin4FYM/orgq0qde+nc15E5Cbqg4B9Sx9c=\ngithub.com/klauspost/compress v1.15.11/go.mod h1:QPwzmACJjUTFsnSHH934V6woptycfrDDJnH7hvFVbGM=\n@@ -606,8 +603,8 @@ github.com/maxbrunsfeld/counterfeiter/v6 v6.2.2/go.mod h1:eD9eIE7cdwcMi9rYluz88J\ngithub.com/mgutz/ansi v0.0.0-20170206155736-9520e82c474b/go.mod h1:01TrycV0kFyexm33Z7vhZRXopbI8J3TDReVlkTgMUxE=\ngithub.com/mgutz/ansi v0.0.0-20200706080929-d51e80ef957d h1:5PJl274Y63IEHC+7izoQE9x6ikvDFZS2mDVS3drnohI=\ngithub.com/mgutz/ansi v0.0.0-20200706080929-d51e80ef957d/go.mod h1:01TrycV0kFyexm33Z7vhZRXopbI8J3TDReVlkTgMUxE=\n-github.com/mholt/archiver/v3 v3.5.1 h1:rDjOBX9JSF5BvoJGvjqK479aL70qh9DIpZCl+k7Clwo=\n-github.com/mholt/archiver/v3 v3.5.1/go.mod h1:e3dqJ7H78uzsRSEACH1joayhuSyhnonssnDhppzS1L4=\n+github.com/mholt/archiver/v4 v4.0.0-alpha.7 h1:xzByj8G8tj0Oq7ZYYU4+ixL/CVb5ruWCm0EZQ1PjOkE=\n+github.com/mholt/archiver/v4 v4.0.0-alpha.7/go.mod h1:Fs8qUkO74HHaidabihzYephJH8qmGD/nCP6tE5xC9BM=\ngithub.com/miekg/pkcs11 v1.0.3/go.mod h1:XsNlhZGX73bx86s2hdc/FuaLm2CPZJemRLMA+WTFxgs=\ngithub.com/mistifyio/go-zfs v2.1.2-0.20190413222219-f784269be439+incompatible/go.mod h1:8AuVvqP/mXw1px98n46wfvcGfQ4ci2FwoAjKYxuo3Z4=\ngithub.com/mitchellh/colorstring v0.0.0-20190213212951-d06e56a500db h1:62I3jR2EmQ4l5rM/4FEfDWcRD+abF5XlKShorW5LRoQ=\n@@ -639,9 +636,8 @@ github.com/mwitkow/go-conntrack v0.0.0-20190716064945-2f068394615f/go.mod h1:qRW\ngithub.com/mxk/go-flowrate v0.0.0-20140419014527-cca7078d478f/go.mod h1:ZdcZmHo+o7JKHSa8/e818NopupXU1YMK5fe1lsApnBw=\ngithub.com/ncw/swift v1.0.47/go.mod h1:23YIA4yWVnGwv2dQlN4bB7egfYX6YLn0Yo/S6zZO/ZM=\ngithub.com/niemeyer/pretty v0.0.0-20200227124842-a10e7caefd8e/go.mod h1:zD1mROLANZcx1PVRCS0qkT7pwLkGfwJo4zjcN/Tysno=\n-github.com/nwaples/rardecode v1.1.0/go.mod h1:5DzqNKiOdpKKBH87u8VlvAnPZMXcGRhxWkRpHbbfGS0=\n-github.com/nwaples/rardecode v1.1.3 h1:cWCaZwfM5H7nAD6PyEdcVnczzV8i/JtotnyW/dD9lEc=\n-github.com/nwaples/rardecode v1.1.3/go.mod h1:5DzqNKiOdpKKBH87u8VlvAnPZMXcGRhxWkRpHbbfGS0=\n+github.com/nwaples/rardecode/v2 v2.0.0-beta.2 h1:e3mzJFJs4k83GXBEiTaQ5HgSc/kOK8q0rDaRO0MPaOk=\n+github.com/nwaples/rardecode/v2 v2.0.0-beta.2/go.mod h1:yntwv/HfMc/Hbvtq9I19D1n58te3h6KsqCf3GxyfBGY=\ngithub.com/nxadm/tail v1.4.4/go.mod h1:kenIhsEOeOJmVchQTgglprH7qJGnHDVpk1VPCcaMI8A=\ngithub.com/oklog/ulid v1.3.1/go.mod h1:CirwcVhetQ6Lv90oh/F+FBtV6XMibvdAFo93nm5qn4U=\ngithub.com/olekukonko/tablewriter v0.0.0-20170122224234-a0225b3f23b5/go.mod h1:vsDQFd/mU46D+Z4whnwzcISnGGzXWMclvtLoiIKAKIo=\n@@ -694,7 +690,6 @@ github.com/pelletier/go-toml v1.8.1/go.mod h1:T2/BmBdy8dvIRq1a/8aqjN41wvWlN4lrap\ngithub.com/pelletier/go-toml/v2 v2.0.5 h1:ipoSadvV8oGUjnUbMub59IDPPwfxF694nG/jwbMiyQg=\ngithub.com/pelletier/go-toml/v2 v2.0.5/go.mod h1:OMHamSCAODeSsVrwwvcJOaoN0LIUIaFVNZzmWyNfXas=\ngithub.com/peterbourgon/diskv v2.0.1+incompatible/go.mod h1:uqqh8zWWbv1HBMNONnaR/tNboyR3/BZd58JJSHlUSCU=\n-github.com/pierrec/lz4/v4 v4.1.2/go.mod h1:gZWDp/Ze/IJXGXf23ltt2EXimqmTUXEy0GFuRQyBid4=\ngithub.com/pierrec/lz4/v4 v4.1.17 h1:kV4Ip+/hUBC+8T6+2EgburRtkE9ef4nbY3f4dFhGjMc=\ngithub.com/pierrec/lz4/v4 v4.1.17/go.mod h1:gZWDp/Ze/IJXGXf23ltt2EXimqmTUXEy0GFuRQyBid4=\ngithub.com/pkg/diff v0.0.0-20210226163009-20ebb0f2a09e/go.mod h1:pJLUxLENpZxwdsKMEsNbx1VGcRFpLqf3715MtcvvzbA=\n@@ -824,6 +819,8 @@ github.com/syndtr/gocapability v0.0.0-20170704070218-db04d3cc01c8/go.mod h1:hkRG\ngithub.com/syndtr/gocapability v0.0.0-20180916011248-d98352740cb2/go.mod h1:hkRG7XYTFWNJGYcbNJQlaLq0fg1yr4J4t/NcTQtrfww=\ngithub.com/syndtr/gocapability v0.0.0-20200815063812-42c35b437635/go.mod h1:hkRG7XYTFWNJGYcbNJQlaLq0fg1yr4J4t/NcTQtrfww=\ngithub.com/tchap/go-patricia v2.2.6+incompatible/go.mod h1:bmLyhP68RS6kStMGxByiQ23RP/odRBOTVjwp2cDyi6I=\n+github.com/therootcompany/xz v1.0.1 h1:CmOtsn1CbtmyYiusbfmhmkpAAETj0wBIH6kCYaX+xzw=\n+github.com/therootcompany/xz v1.0.1/go.mod h1:3K3UH1yCKgBneZYhuQUvJ9HPD19UEXEI0BWbMn8qNMY=\ngithub.com/tj/assert v0.0.0-20171129193455-018094318fb0/go.mod h1:mZ9/Rh9oLWpLLDRpvE+3b7gP/C2YyLFYxNmcLnPTMe0=\ngithub.com/tj/assert v0.0.3 h1:Df/BlaZ20mq6kuai7f5z2TvPFiwC3xaWJSDQNiIS3Rk=\ngithub.com/tj/assert v0.0.3/go.mod h1:Ne6X72Q+TB1AteidzQncjw9PabbMp4PBMZ1k+vd1Pvk=\n@@ -838,7 +835,6 @@ github.com/ugorji/go v1.2.7/go.mod h1:nF9osbDWLy6bDVv/Rtoh6QgnvNDpmCalQV5urGCCS6\ngithub.com/ugorji/go/codec v1.2.7 h1:YPXUKf7fYbp/y8xloBqZOw2qaVggbfwMlI8WM3wZUJ0=\ngithub.com/ugorji/go/codec v1.2.7/go.mod h1:WGN1fab3R1fzQlVQTkfxVtIBhWDRqOviHU95kRgeqEY=\ngithub.com/ulikunitz/xz v0.5.8/go.mod h1:nbz6k7qbPmH4IRqmfOplQw/tblSgqTqBwxkY0oWt/14=\n-github.com/ulikunitz/xz v0.5.9/go.mod h1:nbz6k7qbPmH4IRqmfOplQw/tblSgqTqBwxkY0oWt/14=\ngithub.com/ulikunitz/xz v0.5.10 h1:t92gobL9l3HE202wg3rlk19F6X+JOxl9BBrCCMYEYd8=\ngithub.com/ulikunitz/xz v0.5.10/go.mod h1:nbz6k7qbPmH4IRqmfOplQw/tblSgqTqBwxkY0oWt/14=\ngithub.com/urfave/cli v0.0.0-20171014202726-7bc6a0acffa5/go.mod h1:70zkFmudgCuE/ngEzBv17Jvp/497gISqfk5gWijbERA=\n@@ -856,8 +852,6 @@ github.com/willf/bitset v1.1.11/go.mod h1:83CECat5yLh5zVOf4P1ErAgKA5UDvKtgyUABdr\ngithub.com/xeipuuv/gojsonpointer v0.0.0-20180127040702-4e3ac2762d5f/go.mod h1:N2zxlSyiKSe5eX1tZViRH5QA0qijqEDrYZiPEAiq3wU=\ngithub.com/xeipuuv/gojsonreference v0.0.0-20180127040603-bd5ef7bd5415/go.mod h1:GwrjFmJcFw6At/Gs6z4yjiIwzuJ1/+UwLxMQDVQXShQ=\ngithub.com/xeipuuv/gojsonschema v0.0.0-20180618132009-1d523034197f/go.mod h1:5yf86TLmAcydyeJq5YvxkGPE2fm/u4myDekKRoLuqhs=\n-github.com/xi2/xz v0.0.0-20171230120015-48954b6210f8 h1:nIPpBwaJSVYIxUFsDv3M8ofmx9yWTog9BfvIu0q41lo=\n-github.com/xi2/xz v0.0.0-20171230120015-48954b6210f8/go.mod h1:HUYIGzjTL3rfEspMxjDjgmT5uz5wzYJKVo23qUhYTos=\ngithub.com/xiang90/probing v0.0.0-20190116061207-43a291ad63a2/go.mod h1:UETIi67q53MR2AWcXfiuqkDkRtnGDLqkBTpCHuJHxtU=\ngithub.com/xordataexchange/crypt v0.0.3-0.20170626215501-b2862e3d0a77/go.mod h1:aYKd//L2LvnjZzWKhF00oedf4jCCReLcmhLdhm1A27Q=\ngithub.com/yuin/goldmark v1.1.25/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74=\n" }, { "change_type": "MODIFY", "old_path": "router/router_server_files.go", "new_path": "router/router_server_files.go", "diff": "@@ -13,15 +13,13 @@ import (\n\"strconv\"\n\"strings\"\n- \"github.com/pterodactyl/wings/internal/models\"\n-\n- \"github.com/pterodactyl/wings/config\"\n-\n\"emperror.dev/errors\"\n\"github.com/apex/log\"\n\"github.com/gin-gonic/gin\"\n\"golang.org/x/sync/errgroup\"\n+ \"github.com/pterodactyl/wings/config\"\n+ \"github.com/pterodactyl/wings/internal/models\"\n\"github.com/pterodactyl/wings/router/downloader\"\n\"github.com/pterodactyl/wings/router/middleware\"\n\"github.com/pterodactyl/wings/router/tokens\"\n@@ -442,7 +440,7 @@ func postServerDecompressFiles(c *gin.Context) {\ns := middleware.ExtractServer(c)\nlg := middleware.ExtractLogger(c).WithFields(log.Fields{\"root_path\": data.RootPath, \"file\": data.File})\nlg.Debug(\"checking if space is available for file decompression\")\n- err := s.Filesystem().SpaceAvailableForDecompression(data.RootPath, data.File)\n+ err := s.Filesystem().SpaceAvailableForDecompression(context.Background(), data.RootPath, data.File)\nif err != nil {\nif filesystem.IsErrorCode(err, filesystem.ErrCodeUnknownArchive) {\nlg.WithField(\"error\", err).Warn(\"failed to decompress file: unknown archive format\")\n@@ -454,7 +452,7 @@ func postServerDecompressFiles(c *gin.Context) {\n}\nlg.Info(\"starting file decompression\")\n- if err := s.Filesystem().DecompressFile(data.RootPath, data.File); err != nil {\n+ if err := s.Filesystem().DecompressFile(context.Background(), data.RootPath, data.File); err != nil {\n// If the file is busy for some reason just return a nicer error to the user since there is not\n// much we specifically can do. They'll need to stop the running server process in order to overwrite\n// a file like this.\n" }, { "change_type": "MODIFY", "old_path": "router/router_transfer.go", "new_path": "router/router_transfer.go", "diff": "@@ -19,7 +19,6 @@ import (\n\"github.com/gin-gonic/gin\"\n\"github.com/google/uuid\"\n\"github.com/juju/ratelimit\"\n- \"github.com/mholt/archiver/v3\"\n\"github.com/mitchellh/colorstring\"\n\"github.com/pterodactyl/wings/config\"\n@@ -188,7 +187,7 @@ func postServerArchive(c *gin.Context) {\n}\n// Send the archive progress to the websocket every 3 seconds.\n- ctx, cancel := context.WithCancel(s.Context())\n+ ctx2, cancel := context.WithCancel(s.Context())\ndefer cancel()\ngo func(ctx context.Context, p *filesystem.Progress, t *time.Ticker) {\ndefer t.Stop()\n@@ -200,7 +199,7 @@ func postServerArchive(c *gin.Context) {\nsendTransferLog(\"Archiving \" + p.Progress(progressWidth))\n}\n}\n- }(ctx, a.Progress, time.NewTicker(5*time.Second))\n+ }(ctx2, a.Progress, time.NewTicker(5*time.Second))\n// Attempt to get an archive of the server.\nif err := a.Create(getArchivePath(s.ID())); err != nil {\n@@ -422,9 +421,10 @@ func postTransfer(c *gin.Context) {\ndata.log().Info(\"writing transfer archive to disk...\")\nprogress := filesystem.NewProgress(size)\n+ progress.SetWriter(file)\n// Send the archive progress to the websocket every 3 seconds.\n- ctx, cancel := context.WithCancel(ctx)\n+ ctx2, cancel := context.WithCancel(ctx)\ndefer cancel()\ngo func(ctx context.Context, p *filesystem.Progress, t *time.Ticker) {\ndefer t.Stop()\n@@ -436,7 +436,7 @@ func postTransfer(c *gin.Context) {\nsendTransferLog(\"Downloading \" + p.Progress(progressWidth))\n}\n}\n- }(ctx, progress, time.NewTicker(5*time.Second))\n+ }(ctx2, progress, time.NewTicker(5*time.Second))\nvar reader io.Reader\ndownloadLimit := float64(config.Get().System.Transfers.DownloadLimit) * 1024 * 1024\n@@ -448,7 +448,7 @@ func postTransfer(c *gin.Context) {\n}\nbuf := make([]byte, 1024*4)\n- if _, err := io.CopyBuffer(file, io.TeeReader(reader, progress), buf); err != nil {\n+ if _, err := io.CopyBuffer(progress, reader, buf); err != nil {\n_ = file.Close()\nsendTransferLog(\"Failed while writing archive file to disk: \" + err.Error())\n@@ -495,7 +495,7 @@ func postTransfer(c *gin.Context) {\nsendTransferLog(\"Server environment has been created, extracting transfer archive..\")\ndata.log().Info(\"server environment configured, extracting transfer archive\")\n- if err := archiver.NewTarGz().Unarchive(data.path(), i.Server().Filesystem().Path()); err != nil {\n+ if err := i.Server().Filesystem().DecompressFileUnsafe(ctx, \"/\", data.path()); err != nil {\n// Un-archiving failed, delete the server's data directory.\nif err := os.RemoveAll(i.Server().Filesystem().Path()); err != nil && !os.IsNotExist(err) {\ndata.log().WithField(\"error\", err).Warn(\"failed to delete local server files directory\")\n" }, { "change_type": "MODIFY", "old_path": "server/backup.go", "new_path": "server/backup.go", "diff": "@@ -24,7 +24,6 @@ func (s *Server) notifyPanelOfBackup(uuid string, ad *backup.ArchiveDetails, suc\n\"backup\": uuid,\n\"error\": err,\n}).Error(\"failed to notify panel of backup status due to wings error\")\n-\nreturn err\n}\n@@ -127,7 +126,7 @@ func (s *Server) RestoreBackup(b backup.BackupInterface, reader io.ReadCloser) (\ndefer func() {\ns.Config().SetSuspended(false)\nif reader != nil {\n- reader.Close()\n+ _ = reader.Close()\n}\n}()\n// Send an API call to the Panel as soon as this function is done running so that\n@@ -142,7 +141,7 @@ func (s *Server) RestoreBackup(b backup.BackupInterface, reader io.ReadCloser) (\n// instance, otherwise you'll likely hit all types of write errors due to the\n// server being suspended.\nif s.Environment.State() != environment.ProcessOfflineState {\n- if err = s.Environment.WaitForStop(s.Context(), time.Minute*2, false); err != nil {\n+ if err = s.Environment.WaitForStop(s.Context(), 2*time.Minute, false); err != nil {\nif !client.IsErrNotFound(err) {\nreturn errors.WrapIf(err, \"server/backup: restore: failed to wait for container stop\")\n}\n@@ -152,14 +151,19 @@ func (s *Server) RestoreBackup(b backup.BackupInterface, reader io.ReadCloser) (\n// Attempt to restore the backup to the server by running through each entry\n// in the file one at a time and writing them to the disk.\ns.Log().Debug(\"starting file writing process for backup restoration\")\n- err = b.Restore(s.Context(), reader, func(file string, r io.Reader, mode fs.FileMode, atime, mtime time.Time) error {\n+ err = b.Restore(s.Context(), reader, func(file string, info fs.FileInfo, r io.ReadCloser) error {\n+ defer r.Close()\ns.Events().Publish(DaemonMessageEvent, \"(restoring): \"+file)\n+\nif err := s.Filesystem().Writefile(file, r); err != nil {\nreturn err\n}\n- if err := s.Filesystem().Chmod(file, mode); err != nil {\n+ if err := s.Filesystem().Chmod(file, info.Mode()); err != nil {\nreturn err\n}\n+\n+ atime := info.ModTime()\n+ mtime := atime\nreturn s.Filesystem().Chtimes(file, atime, mtime)\n})\n" }, { "change_type": "MODIFY", "old_path": "server/backup/backup.go", "new_path": "server/backup/backup.go", "diff": "@@ -8,16 +8,21 @@ import (\n\"io/fs\"\n\"os\"\n\"path\"\n- \"time\"\n\"emperror.dev/errors\"\n\"github.com/apex/log\"\n+ \"github.com/mholt/archiver/v4\"\n\"golang.org/x/sync/errgroup\"\n\"github.com/pterodactyl/wings/config\"\n\"github.com/pterodactyl/wings/remote\"\n)\n+var format = archiver.CompressedArchive{\n+ Compression: archiver.Gz{},\n+ Archival: archiver.Tar{},\n+}\n+\ntype AdapterType string\nconst (\n@@ -27,7 +32,7 @@ const (\n// RestoreCallback is a generic restoration callback that exists for both local\n// and remote backups allowing the files to be restored.\n-type RestoreCallback func(file string, r io.Reader, mode fs.FileMode, atime, mtime time.Time) error\n+type RestoreCallback func(file string, info fs.FileInfo, r io.ReadCloser) error\n// noinspection GoNameStartsWithPackageName\ntype BackupInterface interface {\n" }, { "change_type": "MODIFY", "old_path": "server/backup/backup_local.go", "new_path": "server/backup/backup_local.go", "diff": "@@ -6,8 +6,10 @@ import (\n\"os\"\n\"emperror.dev/errors\"\n- \"github.com/mholt/archiver/v3\"\n+ \"github.com/juju/ratelimit\"\n+ \"github.com/mholt/archiver/v4\"\n+ \"github.com/pterodactyl/wings/config\"\n\"github.com/pterodactyl/wings/remote\"\n\"github.com/pterodactyl/wings/server/filesystem\"\n)\n@@ -79,16 +81,27 @@ func (b *LocalBackup) Generate(ctx context.Context, basePath, ignore string) (*A\n// Restore will walk over the archive and call the callback function for each\n// file encountered.\nfunc (b *LocalBackup) Restore(ctx context.Context, _ io.Reader, callback RestoreCallback) error {\n- return archiver.Walk(b.Path(), func(f archiver.File) error {\n- select {\n- case <-ctx.Done():\n- // Stop walking if the context is canceled.\n- return archiver.ErrStopWalk\n- default:\n- if f.IsDir() {\n- return nil\n+ f, err := os.Open(b.Path())\n+ if err != nil {\n+ return err\n+ }\n+\n+ var reader io.Reader = f\n+ // Steal the logic we use for making backups which will be applied when restoring\n+ // this specific backup. This allows us to prevent overloading the disk unintentionally.\n+ if writeLimit := int64(config.Get().System.Backups.WriteLimit * 1024 * 1024); writeLimit > 0 {\n+ reader = ratelimit.Reader(f, ratelimit.NewBucketWithRate(float64(writeLimit), writeLimit))\n}\n- return callback(filesystem.ExtractNameFromArchive(f), f, f.Mode(), f.ModTime(), f.ModTime())\n+ if err := format.Extract(ctx, reader, nil, func(ctx context.Context, f archiver.File) error {\n+ r, err := f.Open()\n+ if err != nil {\n+ return err\n+ }\n+ defer r.Close()\n+\n+ return callback(filesystem.ExtractNameFromArchive(f), f.FileInfo, r)\n+ }); err != nil {\n+ return err\n}\n- })\n+ return nil\n}\n" }, { "change_type": "MODIFY", "old_path": "server/backup/backup_s3.go", "new_path": "server/backup/backup_s3.go", "diff": "package backup\nimport (\n- \"archive/tar\"\n- \"compress/gzip\"\n\"context\"\n\"fmt\"\n\"io\"\n@@ -13,13 +11,12 @@ import (\n\"emperror.dev/errors\"\n\"github.com/cenkalti/backoff/v4\"\n-\n- \"github.com/pterodactyl/wings/server/filesystem\"\n-\n\"github.com/juju/ratelimit\"\n+ \"github.com/mholt/archiver/v4\"\n\"github.com/pterodactyl/wings/config\"\n\"github.com/pterodactyl/wings/remote\"\n+ \"github.com/pterodactyl/wings/server/filesystem\"\n)\ntype S3Backup struct {\n@@ -96,32 +93,17 @@ func (s *S3Backup) Restore(ctx context.Context, r io.Reader, callback RestoreCal\nif writeLimit := int64(config.Get().System.Backups.WriteLimit * 1024 * 1024); writeLimit > 0 {\nreader = ratelimit.Reader(r, ratelimit.NewBucketWithRate(float64(writeLimit), writeLimit))\n}\n- gr, err := gzip.NewReader(reader)\n+ if err := format.Extract(ctx, reader, nil, func(ctx context.Context, f archiver.File) error {\n+ r, err := f.Open()\nif err != nil {\nreturn err\n}\n- defer gr.Close()\n- tr := tar.NewReader(gr)\n- for {\n- select {\n- case <-ctx.Done():\n- return nil\n- default:\n- // Do nothing, fall through to the next block of code in this loop.\n- }\n- header, err := tr.Next()\n- if err != nil {\n- if err == io.EOF {\n- break\n- }\n- return err\n- }\n- if header.Typeflag == tar.TypeReg {\n- if err := callback(header.Name, tr, header.FileInfo().Mode(), header.AccessTime, header.ModTime); err != nil {\n+ defer r.Close()\n+\n+ return callback(filesystem.ExtractNameFromArchive(f), f.FileInfo, r)\n+ }); err != nil {\nreturn err\n}\n- }\n- }\nreturn nil\n}\n" }, { "change_type": "MODIFY", "old_path": "server/filesystem/archive.go", "new_path": "server/filesystem/archive.go", "diff": "@@ -30,6 +30,30 @@ var pool = sync.Pool{\n},\n}\n+// TarProgress .\n+type TarProgress struct {\n+ *tar.Writer\n+ p *Progress\n+}\n+\n+// NewTarProgress .\n+func NewTarProgress(w *tar.Writer, p *Progress) *TarProgress {\n+ if p != nil {\n+ p.w = w\n+ }\n+ return &TarProgress{\n+ Writer: w,\n+ p: p,\n+ }\n+}\n+\n+func (p *TarProgress) Write(v []byte) (int, error) {\n+ if p.p == nil {\n+ return p.Writer.Write(v)\n+ }\n+ return p.p.Write(v)\n+}\n+\n// Progress is used to track the progress of any I/O operation that are being\n// performed.\ntype Progress struct {\n@@ -46,6 +70,12 @@ func NewProgress(total int64) *Progress {\nreturn &Progress{total: total}\n}\n+// SetWriter sets the writer progress will forward writes to.\n+// NOTE: This function is not thread safe.\n+func (p *Progress) SetWriter(w io.Writer) {\n+ p.w = w\n+}\n+\n// Written returns the total number of bytes written.\n// This function should be used when the progress is tracking data being written.\nfunc (p *Progress) Written() int64 {\n@@ -157,23 +187,17 @@ func (a *Archive) Create(dst string) error {\n_ = gw.SetConcurrency(1<<20, 1)\ndefer gw.Close()\n- var pw io.Writer\n- if a.Progress != nil {\n- a.Progress.w = gw\n- pw = a.Progress\n- } else {\n- pw = gw\n- }\n-\n// Create a new tar writer around the gzip writer.\n- tw := tar.NewWriter(pw)\n+ tw := tar.NewWriter(gw)\ndefer tw.Close()\n+ pw := NewTarProgress(tw, a.Progress)\n+\n// Configure godirwalk.\noptions := &godirwalk.Options{\nFollowSymbolicLinks: false,\nUnsorted: true,\n- Callback: a.callback(tw),\n+ Callback: a.callback(pw),\n}\n// If we're specifically looking for only certain files, or have requested\n@@ -182,7 +206,7 @@ func (a *Archive) Create(dst string) error {\nif len(a.Files) == 0 && len(a.Ignore) > 0 {\ni := ignore.CompileIgnoreLines(strings.Split(a.Ignore, \"\\n\")...)\n- options.Callback = a.callback(tw, func(_ string, rp string) error {\n+ options.Callback = a.callback(pw, func(_ string, rp string) error {\nif i.MatchesPath(rp) {\nreturn godirwalk.SkipThis\n}\n@@ -190,7 +214,7 @@ func (a *Archive) Create(dst string) error {\nreturn nil\n})\n} else if len(a.Files) > 0 {\n- options.Callback = a.withFilesCallback(tw)\n+ options.Callback = a.withFilesCallback(pw)\n}\n// Recursively walk the path we are archiving.\n@@ -199,7 +223,7 @@ func (a *Archive) Create(dst string) error {\n// Callback function used to determine if a given file should be included in the archive\n// being generated.\n-func (a *Archive) callback(tw *tar.Writer, opts ...func(path string, relative string) error) func(path string, de *godirwalk.Dirent) error {\n+func (a *Archive) callback(tw *TarProgress, opts ...func(path string, relative string) error) func(path string, de *godirwalk.Dirent) error {\nreturn func(path string, de *godirwalk.Dirent) error {\n// Skip directories because we are walking them recursively.\nif de.IsDir() {\n@@ -223,7 +247,7 @@ func (a *Archive) callback(tw *tar.Writer, opts ...func(path string, relative st\n}\n// Pushes only files defined in the Files key to the final archive.\n-func (a *Archive) withFilesCallback(tw *tar.Writer) func(path string, de *godirwalk.Dirent) error {\n+func (a *Archive) withFilesCallback(tw *TarProgress) func(path string, de *godirwalk.Dirent) error {\nreturn a.callback(tw, func(p string, rp string) error {\nfor _, f := range a.Files {\n// If the given doesn't match, or doesn't have the same prefix continue\n@@ -244,7 +268,7 @@ func (a *Archive) withFilesCallback(tw *tar.Writer) func(path string, de *godirw\n}\n// Adds a given file path to the final archive being created.\n-func (a *Archive) addToArchive(p string, rp string, w *tar.Writer) error {\n+func (a *Archive) addToArchive(p string, rp string, w *TarProgress) error {\n// Lstat the file, this will give us the same information as Stat except that it will not\n// follow a symlink to its target automatically. This is important to avoid including\n// files that exist outside the server root unintentionally in the backup.\n" }, { "change_type": "MODIFY", "old_path": "server/filesystem/compress.go", "new_path": "server/filesystem/compress.go", "diff": "@@ -4,7 +4,9 @@ import (\n\"archive/tar\"\n\"archive/zip\"\n\"compress/gzip\"\n+ \"context\"\n\"fmt\"\n+ iofs \"io/fs\"\n\"os\"\n\"path\"\n\"path/filepath\"\n@@ -13,11 +15,10 @@ import (\n\"sync/atomic\"\n\"time\"\n+ \"emperror.dev/errors\"\ngzip2 \"github.com/klauspost/compress/gzip\"\nzip2 \"github.com/klauspost/compress/zip\"\n-\n- \"emperror.dev/errors\"\n- \"github.com/mholt/archiver/v3\"\n+ \"github.com/mholt/archiver/v4\"\n)\n// CompressFiles compresses all of the files matching the given paths in the\n@@ -73,7 +74,7 @@ func (fs *Filesystem) CompressFiles(dir string, paths []string) (os.FileInfo, er\n// SpaceAvailableForDecompression looks through a given archive and determines\n// if decompressing it would put the server over its allocated disk space limit.\n-func (fs *Filesystem) SpaceAvailableForDecompression(dir string, file string) error {\n+func (fs *Filesystem) SpaceAvailableForDecompression(ctx context.Context, dir string, file string) error {\n// Don't waste time trying to determine this if we know the server will have the space for\n// it since there is no limit.\nif fs.MaxDisk() <= 0 {\n@@ -89,42 +90,76 @@ func (fs *Filesystem) SpaceAvailableForDecompression(dir string, file string) er\n// waiting an unnecessary amount of time on this call.\ndirSize, err := fs.DiskUsage(false)\n- var size int64\n- // Walk over the archive and figure out just how large the final output would be from unarchiving it.\n- err = archiver.Walk(source, func(f archiver.File) error {\n- if atomic.AddInt64(&size, f.Size())+dirSize > fs.MaxDisk() {\n- return newFilesystemError(ErrCodeDiskSpace, nil)\n- }\n- return nil\n- })\n+ fsys, err := archiver.FileSystem(source)\nif err != nil {\n- if IsUnknownArchiveFormatError(err) {\n+ if errors.Is(err, archiver.ErrNoMatch) {\nreturn newFilesystemError(ErrCodeUnknownArchive, err)\n}\nreturn err\n}\n+\n+ var size int64\n+ return iofs.WalkDir(fsys, \".\", func(path string, d iofs.DirEntry, err error) error {\n+ if err != nil {\nreturn err\n}\n+ select {\n+ case <-ctx.Done():\n+ // Stop walking if the context is canceled.\n+ return ctx.Err()\n+ default:\n+ info, err := d.Info()\n+ if err != nil {\n+ return err\n+ }\n+ if atomic.AddInt64(&size, info.Size())+dirSize > fs.MaxDisk() {\n+ return newFilesystemError(ErrCodeDiskSpace, nil)\n+ }\n+ return nil\n+ }\n+ })\n+}\n+\n// DecompressFile will decompress a file in a given directory by using the\n// archiver tool to infer the file type and go from there. This will walk over\n-// all of the files within the given archive and ensure that there is not a\n+// all the files within the given archive and ensure that there is not a\n// zip-slip attack being attempted by validating that the final path is within\n// the server data directory.\n-func (fs *Filesystem) DecompressFile(dir string, file string) error {\n+func (fs *Filesystem) DecompressFile(ctx context.Context, dir string, file string) error {\nsource, err := fs.SafePath(filepath.Join(dir, file))\nif err != nil {\nreturn err\n}\n- // Ensure that the source archive actually exists on the system.\n- if _, err := os.Stat(source); err != nil {\n+ return fs.DecompressFileUnsafe(ctx, dir, source)\n+}\n+\n+// DecompressFileUnsafe will decompress any file on the local disk without checking\n+// if it is owned by the server. The file will be SAFELY decompressed and extracted\n+// into the server's directory.\n+func (fs *Filesystem) DecompressFileUnsafe(ctx context.Context, dir string, file string) error {\n+ // Ensure that the archive actually exists on the system.\n+ if _, err := os.Stat(file); err != nil {\nreturn errors.WithStack(err)\n}\n- // Walk all of the files in the archiver file and write them to the disk. If any\n- // directory is encountered it will be skipped since we handle creating any missing\n- // directories automatically when writing files.\n- err = archiver.Walk(source, func(f archiver.File) error {\n+ f, err := os.Open(file)\n+ if err != nil {\n+ return err\n+ }\n+\n+ // Identify the type of archive we are dealing with.\n+ format, input, err := archiver.Identify(filepath.Base(file), f)\n+ if err != nil {\n+ if errors.Is(err, archiver.ErrNoMatch) {\n+ return newFilesystemError(ErrCodeUnknownArchive, err)\n+ }\n+ return err\n+ }\n+\n+ // Decompress and extract archive\n+ if ex, ok := format.(archiver.Extractor); ok {\n+ return ex.Extract(ctx, input, nil, func(ctx context.Context, f archiver.File) error {\nif f.IsDir() {\nreturn nil\n}\n@@ -133,25 +168,26 @@ func (fs *Filesystem) DecompressFile(dir string, file string) error {\nif err := fs.IsIgnored(p); err != nil {\nreturn nil\n}\n- if err := fs.Writefile(p, f); err != nil {\n- return wrapError(err, source)\n+ r, err := f.Open()\n+ if err != nil {\n+ return err\n+ }\n+ defer r.Close()\n+ if err := fs.Writefile(p, r); err != nil {\n+ return wrapError(err, file)\n}\n// Update the file permissions to the one set in the archive.\nif err := fs.Chmod(p, f.Mode()); err != nil {\n- return wrapError(err, source)\n+ return wrapError(err, file)\n}\n// Update the file modification time to the one set in the archive.\nif err := fs.Chtimes(p, f.ModTime(), f.ModTime()); err != nil {\n- return wrapError(err, source)\n+ return wrapError(err, file)\n}\nreturn nil\n})\n- if err != nil {\n- if IsUnknownArchiveFormatError(err) {\n- return newFilesystemError(ErrCodeUnknownArchive, err)\n- }\n- return err\n}\n+\nreturn nil\n}\n" }, { "change_type": "MODIFY", "old_path": "server/filesystem/compress_test.go", "new_path": "server/filesystem/compress_test.go", "diff": "package filesystem\nimport (\n+ \"context\"\n\"os\"\n\"sync/atomic\"\n\"testing\"\n@@ -28,7 +29,7 @@ func TestFilesystem_DecompressFile(t *testing.T) {\ng.Assert(err).IsNil()\n// decompress\n- err = fs.DecompressFile(\"/\", \"test.\"+ext)\n+ err = fs.DecompressFile(context.Background(), \"/\", \"test.\"+ext)\ng.Assert(err).IsNil()\n// make sure everything is where it is supposed to be\n" }, { "change_type": "MODIFY", "old_path": "server/filesystem/errors.go", "new_path": "server/filesystem/errors.go", "diff": "@@ -4,7 +4,6 @@ import (\n\"fmt\"\n\"os\"\n\"path/filepath\"\n- \"strings\"\n\"emperror.dev/errors\"\n\"github.com/apex/log\"\n@@ -122,15 +121,6 @@ func IsErrorCode(err error, code ErrorCode) bool {\nreturn false\n}\n-// IsUnknownArchiveFormatError checks if the error is due to the archive being\n-// in an unexpected file format.\n-func IsUnknownArchiveFormatError(err error) bool {\n- if err != nil && strings.HasPrefix(err.Error(), \"format \") {\n- return true\n- }\n- return false\n-}\n-\n// NewBadPathResolution returns a new BadPathResolution error.\nfunc NewBadPathResolution(path string, resolved string) error {\nreturn errors.WithStackDepth(&Error{code: ErrCodePathResolution, path: path, resolved: resolved}, 1)\n" } ]
Go
MIT License
pterodactyl/wings
server(filesystem): fix inaccurate archive progress (#145)
532,308
30.01.2023 17:09:36
-3,600
71fbd9271ef129af0e38e3d157a396e62dc5facd
activity: fix ip validity check
[ { "change_type": "MODIFY", "old_path": "internal/cron/activity_cron.go", "new_path": "internal/cron/activity_cron.go", "diff": "@@ -49,7 +49,7 @@ func (ac *activityCron) Run(ctx context.Context) error {\nfor _, v := range activity {\n// Delete any activity that has an invalid IP address. This is a fix for\n// a bug that truncated the last octet of an IPv6 address in the database.\n- if err := net.ParseIP(v.IP); err != nil {\n+ if ip := net.ParseIP(v.IP); ip == nil {\nids = append(ids, v.ID)\ncontinue\n}\n" } ]
Go
MIT License
pterodactyl/wings
activity: fix ip validity check (#159)
105,979
26.01.2017 20:32:53
-3,600
a06f8e46152bf158e13ca3c8109d4bed315c6745
fix(addon): Remove temporary path
[ { "change_type": "MODIFY", "old_path": "addon.py", "new_path": "addon.py", "diff": "@@ -34,8 +34,7 @@ netflix_session = NetflixSession(\n)\nlibrary = Library(\nbase_url=base_url,\n- #root_folder=kodi_helper.base_data_path,\n- root_folder='/Users/asciidisco/Desktop/lib',\n+ root_folder=kodi_helper.base_data_path,\nlibrary_settings=kodi_helper.get_custom_library_settings(),\nlog_fn=kodi_helper.log\n)\n" } ]
Python
MIT License
castagnait/plugin.video.netflix
fix(addon): Remove temporary path
105,992
29.01.2017 15:38:26
-3,600
26c305a4ecab0366fa05d1d4c3bc9ee24d170029
cleanup / msl-includes
[ { "change_type": "MODIFY", "old_path": "resources/lib/MSL.py", "new_path": "resources/lib/MSL.py", "diff": "@@ -18,7 +18,8 @@ from Crypto.Random import get_random_bytes\n# from Crypto.Hash import HMAC, SHA256\nfrom Crypto.Util import Padding\nimport xml.etree.ElementTree as ET\n-from lib import log\n+from common import log\n+from common import ADDONUSERDATA\npp = pprint.PrettyPrinter(indent=4)\n@@ -37,7 +38,8 @@ class MSL:\nhandshake_performed = False # Is a handshake already performed and the keys loaded\nlast_drm_context = ''\nlast_playback_context = ''\n- esn = \"NFCDCH-LX-CQE0NU6PA5714R25VPLXVU2A193T36\"\n+ #esn = \"NFCDCH-LX-CQE0NU6PA5714R25VPLXVU2A193T36\"\n+ esn = \"WWW-BROWSE-D7GW1G4NPXGR1F0X1H3EQGY3V1F5WE\"\ncurrent_message_id = 0\nsession = requests.session()\nrndm = random.SystemRandom()\n@@ -54,6 +56,10 @@ class MSL:\n\"\"\"\nself.email = email\nself.password = password\n+ try:\n+ os.mkdir(ADDONUSERDATA)\n+ except OSError:\n+ pass\nif self.file_exists('msl_data.json'):\nself.__load_msl_data()\n@@ -190,7 +196,7 @@ class MSL:\ndef __tranform_to_dash(self, manifest):\n- self.save_file('/home/johannes/manifest.json', json.dumps(manifest))\n+ self.save_file('manifest.json', json.dumps(manifest))\nmanifest = manifest['result']['viewables'][0]\nself.last_playback_context = manifest['playbackContextId']\n@@ -227,7 +233,8 @@ class MSL:\nrep = ET.SubElement(video_adaption_set, 'Representation',\nwidth=str(downloadable['width']),\nheight=str(downloadable['height']),\n- bitrate=str(downloadable['bitrate']*8*1024),\n+ bandwidth=str(downloadable['bitrate']*8*1024),\n+ codecs='h264',\nmimeType='video/mp4')\n#BaseURL\n@@ -247,7 +254,7 @@ class MSL:\nfor downloadable in audio_track['downloadables']:\nrep = ET.SubElement(audio_adaption_set, 'Representation',\ncodecs='aac',\n- bitrate=str(downloadable['bitrate'] * 8 * 1024),\n+ bandwidth=str(downloadable['bitrate'] * 8 * 1024),\nmimeType='audio/mp4')\n#AudioChannel Config\n@@ -526,7 +533,7 @@ class MSL:\n:param filename: The filename\n:return: True if so\n\"\"\"\n- return os.path.isfile(filename)\n+ return os.path.isfile(ADDONUSERDATA + filename)\n@staticmethod\ndef save_file(filename, content):\n@@ -535,7 +542,7 @@ class MSL:\n:param filename: The filename\n:param content: The content of the file\n\"\"\"\n- with open(filename, 'w') as file_:\n+ with open(ADDONUSERDATA + filename, 'w') as file_:\nfile_.write(content)\nfile_.flush()\n@@ -546,6 +553,6 @@ class MSL:\n:param filename: The file to load\n:return: The content of the file\n\"\"\"\n- with open(filename) as file_:\n+ with open(ADDONUSERDATA + filename) as file_:\nfile_content = file_.read()\nreturn file_content\n" }, { "change_type": "MODIFY", "old_path": "resources/lib/MSLHttpRequestHandler.py", "new_path": "resources/lib/MSLHttpRequestHandler.py", "diff": "@@ -3,7 +3,7 @@ import base64\nfrom urlparse import urlparse, parse_qs\nfrom MSL import MSL\n-from lib import ADDON\n+from common import ADDON\nemail = ADDON.getSetting('email')\npassword = ADDON.getSetting('password')\nmsl = MSL(email, password)\n" }, { "change_type": "MODIFY", "old_path": "resources/lib/common.py", "new_path": "resources/lib/common.py", "diff": "@@ -9,6 +9,7 @@ ADDONVERSION = ADDON.getAddonInfo('version')\nADDONNAME = ADDON.getAddonInfo('name')\nADDONPATH = ADDON.getAddonInfo('path').decode('utf-8')\nADDONPROFILE = xbmc.translatePath( ADDON.getAddonInfo('profile') ).decode('utf-8')\n+ADDONUSERDATA = xbmc.translatePath(\"special://profile/addon_data/service.msl\").decode('utf-8') + \"/\"\nICON = ADDON.getAddonInfo('icon')\ndef log(txt):\n" } ]
Python
MIT License
castagnait/plugin.video.netflix
cleanup / msl-includes
105,992
29.01.2017 18:34:31
-3,600
07c987a9bb20d1766404669fa945b98764b45c97
fix bandwidth calulation
[ { "change_type": "MODIFY", "old_path": "resources/lib/MSL.py", "new_path": "resources/lib/MSL.py", "diff": "@@ -233,7 +233,7 @@ class MSL:\nrep = ET.SubElement(video_adaption_set, 'Representation',\nwidth=str(downloadable['width']),\nheight=str(downloadable['height']),\n- bandwidth=str(downloadable['bitrate']*8*1024),\n+ bandwidth=str(downloadable['bitrate']*1024),\ncodecs='h264',\nmimeType='video/mp4')\n@@ -254,7 +254,7 @@ class MSL:\nfor downloadable in audio_track['downloadables']:\nrep = ET.SubElement(audio_adaption_set, 'Representation',\ncodecs='aac',\n- bandwidth=str(downloadable['bitrate'] * 8 * 1024),\n+ bandwidth=str(downloadable['bitrate']*1024),\nmimeType='audio/mp4')\n#AudioChannel Config\n" } ]
Python
MIT License
castagnait/plugin.video.netflix
fix bandwidth calulation
105,979
04.02.2017 15:38:10
-3,600
c1cb01ec0027c7c5a1c67934df407b4820a5686a
feat(service): Dynamic port allocation
[ { "change_type": "MODIFY", "old_path": "service.py", "new_path": "service.py", "diff": "import threading\nimport SocketServer\nimport xbmc\n+import xbmcaddon\n+import socket\nfrom resources.lib.common import log\nfrom resources.lib.MSLHttpRequestHandler import MSLHttpRequestHandler\n-PORT = 8000\n+def select_unused_port():\n+ s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n+ s.bind(('localhost', 0))\n+ addr, port = s.getsockname()\n+ s.close()\n+ return port\n+\n+addon = xbmcaddon.Addon()\n+PORT = select_unused_port()\n+addon.setSetting('msl_service_port', str(PORT))\n+log(\"Picked Port: \" + str(PORT))\nHandler = MSLHttpRequestHandler\nSocketServer.TCPServer.allow_reuse_address = True\nserver = SocketServer.TCPServer(('127.0.0.1', PORT), Handler)\n" } ]
Python
MIT License
castagnait/plugin.video.netflix
feat(service): Dynamic port allocation
105,979
04.02.2017 16:35:20
-3,600
3305a89c90f475629a06f4ab96fa6fdf9098dd2f
feat(msl): Move functionality from common.py to KodiHelper.py & remove common.py
[ { "change_type": "MODIFY", "old_path": "resources/lib/KodiHelper.py", "new_path": "resources/lib/KodiHelper.py", "diff": "@@ -18,9 +18,6 @@ except:\nclass KodiHelper:\n\"\"\"Consumes all the configuration data from Kodi as well as turns data into lists of folders and videos\"\"\"\n- msl_service_server_url = 'http://localhost:%PORT%'\n- \"\"\"str: MSL service url\"\"\"\n-\ndef __init__ (self, plugin_handle, base_url):\n\"\"\"Fetches all needed info from Kodi & configures the baseline of the plugin\n@@ -42,6 +39,7 @@ class KodiHelper:\nself.cookie_path = self.base_data_path + 'COOKIE'\nself.data_path = self.base_data_path + 'DATA'\nself.config_path = os.path.join(self.base_data_path, 'config')\n+ self.msl_data_path = xbmc.translatePath('special://profile/addon_data/service.msl').decode('utf-8') + '/'\nself.verb_log = self.addon.getSetting('logging') == 'true'\nself.default_fanart = self.addon.getAddonInfo('fanart')\nself.win = xbmcgui.Window(xbmcgui.getCurrentWindowId())\n@@ -647,7 +645,7 @@ class KodiHelper:\nreturn False\n# inputstream addon properties\n- msl_service_url = self.msl_service_server_url.replace('%PORT%', str(self.addon.getSetting('msl_service_port')))\n+ msl_service_url = 'http://localhost:' + str(self.addon.getSetting('msl_service_port'))\nplay_item = xbmcgui.ListItem(path=msl_service_url + '/manifest?id=' + video_id)\nplay_item.setProperty(inputstream_addon + '.license_type', 'com.widevine.alpha')\nplay_item.setProperty(inputstream_addon + '.manifest_type', 'mpd')\n" }, { "change_type": "MODIFY", "old_path": "resources/lib/MSL.py", "new_path": "resources/lib/MSL.py", "diff": "@@ -18,8 +18,14 @@ from Crypto.Random import get_random_bytes\n# from Crypto.Hash import HMAC, SHA256\nfrom Crypto.Util import Padding\nimport xml.etree.ElementTree as ET\n-from common import log\n-from common import ADDONUSERDATA\n+from KodiHelper import KodiHelper\n+\n+plugin_handle = int(sys.argv[1])\n+base_url = sys.argv[0]\n+kodi_helper = KodiHelper(\n+ plugin_handle=plugin_handle,\n+ base_url=base_url\n+)\npp = pprint.PrettyPrinter(indent=4)\n@@ -57,7 +63,7 @@ class MSL:\nself.email = email\nself.password = password\ntry:\n- os.mkdir(ADDONUSERDATA)\n+ os.mkdir(kodi_helper.msl_data_path)\nexcept OSError:\npass\n@@ -65,11 +71,11 @@ class MSL:\nself.__load_msl_data()\nself.handshake_performed = True\nelif self.file_exists('rsa_key.bin'):\n- log('RSA Keys do already exist load old ones')\n+ kodi_helper.log(msg='RSA Keys do already exist load old ones')\nself.__load_rsa_keys()\nself.__perform_key_handshake()\nelse:\n- log('Create new RSA Keys')\n+ kodi_helper.log(msg='Create new RSA Keys')\n# Create new Key Pair and save\nself.rsa_key = RSA.generate(2048)\nself.__save_rsa_keys()\n@@ -113,7 +119,7 @@ class MSL:\ntry:\nresp.json()\n- log('MANIFEST RESPONE JSON: '+resp.text)\n+ kodi_helper.log(msg='MANIFEST RESPONE JSON: '+resp.text)\nexcept ValueError:\n# Maybe we have a CHUNKED response\nresp = self.__parse_chunked_msl_response(resp.text)\n@@ -161,7 +167,7 @@ class MSL:\ntry:\nresp.json()\n- log('LICENSE RESPONE JSON: '+resp.text)\n+ kodi_helper.log(msg='LICENSE RESPONE JSON: '+resp.text)\nexcept ValueError:\n# Maybe we have a CHUNKED response\nresp = self.__parse_chunked_msl_response(resp.text)\n@@ -456,21 +462,21 @@ class MSL:\n'headerdata': base64.standard_b64encode(header),\n'signature': '',\n}\n- log('Key Handshake Request:')\n- log(json.dumps(request))\n+ kodi_helper.log(msg='Key Handshake Request:')\n+ kodi_helper.log(msg=json.dumps(request))\nresp = self.session.post(self.endpoints['manifest'], json.dumps(request, sort_keys=True))\nif resp.status_code == 200:\nresp = resp.json()\nif 'errordata' in resp:\n- log('Key Exchange failed')\n- log(base64.standard_b64decode(resp['errordata']))\n+ kodi_helper.log(msg='Key Exchange failed')\n+ kodi_helper.log(msg=base64.standard_b64decode(resp['errordata']))\nreturn False\nself.__parse_crypto_keys(json.JSONDecoder().decode(base64.standard_b64decode(resp['headerdata'])))\nelse:\n- log('Key Exchange failed')\n- log(resp.text)\n+ kodi_helper.log(msg='Key Exchange failed')\n+ kodi_helper.log(msg=resp.text)\ndef __parse_crypto_keys(self, headerdata):\nself.__set_master_token(headerdata['keyresponsedata']['mastertoken'])\n@@ -521,7 +527,7 @@ class MSL:\nself.rsa_key = RSA.importKey(loaded_key)\ndef __save_rsa_keys(self):\n- log('Save RSA Keys')\n+ kodi_helper.log(msg='Save RSA Keys')\n# Get the DER Base64 of the keys\nencrypted_key = self.rsa_key.exportKey()\nself.save_file('rsa_key.bin', encrypted_key)\n@@ -533,7 +539,7 @@ class MSL:\n:param filename: The filename\n:return: True if so\n\"\"\"\n- return os.path.isfile(ADDONUSERDATA + filename)\n+ return os.path.isfile(kodi_helper.msl_data_path + filename)\n@staticmethod\ndef save_file(filename, content):\n@@ -542,7 +548,7 @@ class MSL:\n:param filename: The filename\n:param content: The content of the file\n\"\"\"\n- with open(ADDONUSERDATA + filename, 'w') as file_:\n+ with open(kodi_helper.msl_data_path + filename, 'w') as file_:\nfile_.write(content)\nfile_.flush()\n@@ -553,6 +559,6 @@ class MSL:\n:param filename: The file to load\n:return: The content of the file\n\"\"\"\n- with open(ADDONUSERDATA + filename) as file_:\n+ with open(kodi_helper.msl_data_path + filename) as file_:\nfile_content = file_.read()\nreturn file_content\n" }, { "change_type": "MODIFY", "old_path": "resources/lib/MSLHttpRequestHandler.py", "new_path": "resources/lib/MSLHttpRequestHandler.py", "diff": "@@ -3,9 +3,18 @@ import base64\nfrom urlparse import urlparse, parse_qs\nfrom MSL import MSL\n-from common import ADDON\n-email = ADDON.getSetting('email')\n-password = ADDON.getSetting('password')\n+from KodiHelper import KodiHelper\n+\n+plugin_handle = int(sys.argv[1])\n+base_url = sys.argv[0]\n+kodi_helper = KodiHelper(\n+ plugin_handle=plugin_handle,\n+ base_url=base_url\n+)\n+\n+account = kodi_helper.addon.get_credentials()\n+email = account['email']\n+password = account['password']\nmsl = MSL(email, password)\nclass MSLHttpRequestHandler(BaseHTTPServer.BaseHTTPRequestHandler):\n" }, { "change_type": "DELETE", "old_path": "resources/lib/common.py", "new_path": null, "diff": "-import os\n-import xbmc\n-import xbmcaddon\n-import xbmcgui\n-import xbmcvfs\n-\n-ADDON = xbmcaddon.Addon()\n-ADDONVERSION = ADDON.getAddonInfo('version')\n-ADDONNAME = ADDON.getAddonInfo('name')\n-ADDONPATH = ADDON.getAddonInfo('path').decode('utf-8')\n-ADDONPROFILE = xbmc.translatePath( ADDON.getAddonInfo('profile') ).decode('utf-8')\n-ADDONUSERDATA = xbmc.translatePath(\"special://profile/addon_data/service.msl\").decode('utf-8') + \"/\"\n-ICON = ADDON.getAddonInfo('icon')\n-\n-def log(txt):\n- if isinstance (txt,str):\n- txt = txt.decode(\"utf-8\")\n- message = u'%s: %s' % (\"service.msl\", txt)\n- xbmc.log(msg=message.encode(\"utf-8\"), level=xbmc.LOGDEBUG)\n" }, { "change_type": "MODIFY", "old_path": "service.py", "new_path": "service.py", "diff": "@@ -3,7 +3,7 @@ import SocketServer\nimport xbmc\nimport xbmcaddon\nimport socket\n-from resources.lib.common import log\n+from resources.lib.KodiHelper import KodiHelper\nfrom resources.lib.MSLHttpRequestHandler import MSLHttpRequestHandler\ndef select_unused_port():\n@@ -13,10 +13,18 @@ def select_unused_port():\ns.close()\nreturn port\n+plugin_handle = int(sys.argv[1])\n+base_url = sys.argv[0]\naddon = xbmcaddon.Addon()\n+\n+kodi_helper = KodiHelper(\n+ plugin_handle=plugin_handle,\n+ base_url=base_url\n+)\n+\nPORT = select_unused_port()\naddon.setSetting('msl_service_port', str(PORT))\n-log(\"Picked Port: \" + str(PORT))\n+kodi_helper.log(msg='Picked Port: ' + str(PORT))\nHandler = MSLHttpRequestHandler\nSocketServer.TCPServer.allow_reuse_address = True\nserver = SocketServer.TCPServer(('127.0.0.1', PORT), Handler)\n@@ -37,4 +45,4 @@ if __name__ == '__main__':\nserver.server_close()\nserver.socket.close()\nserver.shutdown()\n- log(\"Stopped MSL Service\")\n+ kodi_helper.log(msg='Stopped MSL Service')\n" } ]
Python
MIT License
castagnait/plugin.video.netflix
feat(msl): Move functionality from common.py to KodiHelper.py & remove common.py
105,979
06.02.2017 11:54:17
-3,600
8eeebc7e22e95acf7d6cb5ea897450a72c2efe60
fix(msl): Broken imports
[ { "change_type": "MODIFY", "old_path": "resources/lib/MSL.py", "new_path": "resources/lib/MSL.py", "diff": "@@ -18,14 +18,6 @@ from Crypto.Random import get_random_bytes\n# from Crypto.Hash import HMAC, SHA256\nfrom Crypto.Util import Padding\nimport xml.etree.ElementTree as ET\n-from KodiHelper import KodiHelper\n-\n-plugin_handle = int(sys.argv[1])\n-base_url = sys.argv[0]\n-kodi_helper = KodiHelper(\n- plugin_handle=plugin_handle,\n- base_url=base_url\n-)\npp = pprint.PrettyPrinter(indent=4)\n@@ -55,27 +47,28 @@ class MSL:\n'license': 'http://www.netflix.com/api/msl/NFCDCH-LX/cadmium/license'\n}\n- def __init__(self, email, password):\n+ def __init__(self, email, password, kodi_helper):\n\"\"\"\nThe Constructor checks for already existing crypto Keys.\nIf they exist it will load the existing keys\n\"\"\"\nself.email = email\nself.password = password\n+ self.kodi_helper = kodi_helper\ntry:\n- os.mkdir(kodi_helper.msl_data_path)\n+ os.mkdir(self.kodi_helper.msl_data_path)\nexcept OSError:\npass\n- if self.file_exists('msl_data.json'):\n+ if self.file_exists(self.kodi_helper.msl_data_path, 'msl_data.json'):\nself.__load_msl_data()\nself.handshake_performed = True\n- elif self.file_exists('rsa_key.bin'):\n- kodi_helper.log(msg='RSA Keys do already exist load old ones')\n+ elif self.file_exists(self.kodi_helper.msl_data_path, 'rsa_key.bin'):\n+ self.kodi_helper.log(msg='RSA Keys do already exist load old ones')\nself.__load_rsa_keys()\nself.__perform_key_handshake()\nelse:\n- kodi_helper.log(msg='Create new RSA Keys')\n+ self.kodi_helper.log(msg='Create new RSA Keys')\n# Create new Key Pair and save\nself.rsa_key = RSA.generate(2048)\nself.__save_rsa_keys()\n@@ -119,7 +112,7 @@ class MSL:\ntry:\nresp.json()\n- kodi_helper.log(msg='MANIFEST RESPONE JSON: '+resp.text)\n+ self.kodi_helper.log(msg='MANIFEST RESPONE JSON: '+resp.text)\nexcept ValueError:\n# Maybe we have a CHUNKED response\nresp = self.__parse_chunked_msl_response(resp.text)\n@@ -167,7 +160,7 @@ class MSL:\ntry:\nresp.json()\n- kodi_helper.log(msg='LICENSE RESPONE JSON: '+resp.text)\n+ self.kodi_helper.log(msg='LICENSE RESPONE JSON: '+resp.text)\nexcept ValueError:\n# Maybe we have a CHUNKED response\nresp = self.__parse_chunked_msl_response(resp.text)\n@@ -202,7 +195,7 @@ class MSL:\ndef __tranform_to_dash(self, manifest):\n- self.save_file('manifest.json', json.dumps(manifest))\n+ self.save_file(self.kodi_helper.msl_data_path, 'manifest.json', json.dumps(manifest))\nmanifest = manifest['result']['viewables'][0]\nself.last_playback_context = manifest['playbackContextId']\n@@ -462,21 +455,21 @@ class MSL:\n'headerdata': base64.standard_b64encode(header),\n'signature': '',\n}\n- kodi_helper.log(msg='Key Handshake Request:')\n- kodi_helper.log(msg=json.dumps(request))\n+ self.kodi_helper.log(msg='Key Handshake Request:')\n+ self.kodi_helper.log(msg=json.dumps(request))\nresp = self.session.post(self.endpoints['manifest'], json.dumps(request, sort_keys=True))\nif resp.status_code == 200:\nresp = resp.json()\nif 'errordata' in resp:\n- kodi_helper.log(msg='Key Exchange failed')\n- kodi_helper.log(msg=base64.standard_b64decode(resp['errordata']))\n+ self.kodi_helper.log(msg='Key Exchange failed')\n+ self.kodi_helper.log(msg=base64.standard_b64decode(resp['errordata']))\nreturn False\nself.__parse_crypto_keys(json.JSONDecoder().decode(base64.standard_b64decode(resp['headerdata'])))\nelse:\n- kodi_helper.log(msg='Key Exchange failed')\n- kodi_helper.log(msg=resp.text)\n+ self.kodi_helper.log(msg='Key Exchange failed')\n+ self.kodi_helper.log(msg=resp.text)\ndef __parse_crypto_keys(self, headerdata):\nself.__set_master_token(headerdata['keyresponsedata']['mastertoken'])\n@@ -497,7 +490,7 @@ class MSL:\nself.handshake_performed = True\ndef __load_msl_data(self):\n- msl_data = json.JSONDecoder().decode(self.load_file('msl_data.json'))\n+ msl_data = json.JSONDecoder().decode(self.load_file(self.kodi_helper.msl_data_path, 'msl_data.json'))\nself.__set_master_token(msl_data['tokens']['mastertoken'])\nself.encryption_key = base64.standard_b64decode(msl_data['encryption_key'])\nself.sign_key = base64.standard_b64decode(msl_data['sign_key'])\n@@ -515,7 +508,7 @@ class MSL:\n}\n}\nserialized_data = json.JSONEncoder().encode(data)\n- self.save_file('msl_data.json', serialized_data)\n+ self.save_file(self.kodi_helper.msl_data_path, 'msl_data.json', serialized_data)\ndef __set_master_token(self, master_token):\nself.mastertoken = master_token\n@@ -523,42 +516,42 @@ class MSL:\n'sequencenumber']\ndef __load_rsa_keys(self):\n- loaded_key = self.load_file('rsa_key.bin')\n+ loaded_key = self.load_file(self.kodi_helper.msl_data_path, 'rsa_key.bin')\nself.rsa_key = RSA.importKey(loaded_key)\ndef __save_rsa_keys(self):\n- kodi_helper.log(msg='Save RSA Keys')\n+ self.kodi_helper.log(msg='Save RSA Keys')\n# Get the DER Base64 of the keys\nencrypted_key = self.rsa_key.exportKey()\n- self.save_file('rsa_key.bin', encrypted_key)\n+ self.save_file(self.kodi_helper.msl_data_path, 'rsa_key.bin', encrypted_key)\n@staticmethod\n- def file_exists(filename):\n+ def file_exists(msl_data_path, filename):\n\"\"\"\nChecks if a given file exists\n:param filename: The filename\n:return: True if so\n\"\"\"\n- return os.path.isfile(kodi_helper.msl_data_path + filename)\n+ return os.path.isfile(msl_data_path + filename)\n@staticmethod\n- def save_file(filename, content):\n+ def save_file(msl_data_path, filename, content):\n\"\"\"\nSaves the given content under given filename\n:param filename: The filename\n:param content: The content of the file\n\"\"\"\n- with open(kodi_helper.msl_data_path + filename, 'w') as file_:\n+ with open(msl_data_path + filename, 'w') as file_:\nfile_.write(content)\nfile_.flush()\n@staticmethod\n- def load_file(filename):\n+ def load_file(msl_data_path, filename):\n\"\"\"\nLoads the content of a given filename\n:param filename: The file to load\n:return: The content of the file\n\"\"\"\n- with open(kodi_helper.msl_data_path + filename) as file_:\n+ with open(msl_data_path + filename) as file_:\nfile_content = file_.read()\nreturn file_content\n" }, { "change_type": "MODIFY", "old_path": "resources/lib/MSLHttpRequestHandler.py", "new_path": "resources/lib/MSLHttpRequestHandler.py", "diff": "@@ -5,17 +5,12 @@ from urlparse import urlparse, parse_qs\nfrom MSL import MSL\nfrom KodiHelper import KodiHelper\n-plugin_handle = int(sys.argv[1])\n-base_url = sys.argv[0]\nkodi_helper = KodiHelper(\n- plugin_handle=plugin_handle,\n- base_url=base_url\n+ plugin_handle=None,\n+ base_url=None\n)\n-\n-account = kodi_helper.addon.get_credentials()\n-email = account['email']\n-password = account['password']\n-msl = MSL(email, password)\n+account = kodi_helper.get_credentials()\n+msl = MSL(account['email'], account['password'], kodi_helper)\nclass MSLHttpRequestHandler(BaseHTTPServer.BaseHTTPRequestHandler):\n" }, { "change_type": "MODIFY", "old_path": "service.py", "new_path": "service.py", "diff": "@@ -13,13 +13,10 @@ def select_unused_port():\ns.close()\nreturn port\n-plugin_handle = int(sys.argv[1])\n-base_url = sys.argv[0]\naddon = xbmcaddon.Addon()\n-\nkodi_helper = KodiHelper(\n- plugin_handle=plugin_handle,\n- base_url=base_url\n+ plugin_handle=None,\n+ base_url=None\n)\nPORT = select_unused_port()\n" } ]
Python
MIT License
castagnait/plugin.video.netflix
fix(msl): Broken imports
105,979
09.02.2017 12:03:29
-3,600
74733fb1ca2b352a087dd63a60d89a26fa98b27a
feat(search): Adds suggestions to the search results
[ { "change_type": "MODIFY", "old_path": "resources/lib/Navigation.py", "new_path": "resources/lib/Navigation.py", "diff": "@@ -162,6 +162,12 @@ class Navigation:\nfor key in search_results_raw['value']['search'].keys():\nif self.netflix_session._is_size_key(key=key) == False:\nhas_search_results = search_results_raw['value']['search'][key]['titles']['length'] > 0\n+ if has_search_results == False:\n+ for entry in search_results_raw['value']['search'][key]['suggestions']:\n+ if self.netflix_session._is_size_key(key=entry) == False:\n+ if search_results_raw['value']['search'][key]['suggestions'][entry]['relatedvideos']['length'] > 0:\n+ has_search_results = True\n+\n# display that we haven't found a thing\nif has_search_results == False:\n" }, { "change_type": "MODIFY", "old_path": "resources/lib/NetflixSession.py", "new_path": "resources/lib/NetflixSession.py", "diff": "@@ -1495,7 +1495,7 @@ class NetflixSession:\nresponse = self.session.get(url, params=payload, verify=self.verify_ssl);\nreturn self._process_response(response=response, component=url)\n- def fetch_search_results (self, search_str, list_from=0, list_to=48):\n+ def fetch_search_results (self, search_str, list_from=0, list_to=10):\n\"\"\"Fetches the JSON which contains the results for the given search query\nParameters\n@@ -1520,7 +1520,10 @@ class NetflixSession:\npaths = [\n['search', encoded_search_string, 'titles', {'from': list_from, 'to': list_to}, ['summary', 'title']],\n['search', encoded_search_string, 'titles', {'from': list_from, 'to': list_to}, 'boxarts', '_342x192', 'jpg'],\n- ['search', encoded_search_string, 'titles', ['id', 'length', 'name', 'trackIds', 'requestId']]\n+ ['search', encoded_search_string, 'titles', ['id', 'length', 'name', 'trackIds', 'requestId']],\n+ ['search', encoded_search_string, 'suggestions', 0, 'relatedvideos', {'from': list_from, 'to': list_to}, ['summary', 'title']],\n+ ['search', encoded_search_string, 'suggestions', 0, 'relatedvideos', {'from': list_from, 'to': list_to}, 'boxarts', '_342x192', 'jpg'],\n+ ['search', encoded_search_string, 'suggestions', 0, 'relatedvideos', ['id', 'length', 'name', 'trackIds', 'requestId']]\n]\nresponse = self._path_request(paths=paths)\nreturn self._process_response(response=response, component='Search results')\n" } ]
Python
MIT License
castagnait/plugin.video.netflix
feat(search): Adds suggestions to the search results
105,979
26.02.2017 13:20:23
-3,600
1d8369ef0de8ea43ac783282d50f4844f486d01d
fix(profiles): Add default avatar
[ { "change_type": "MODIFY", "old_path": "resources/lib/NetflixSession.py", "new_path": "resources/lib/NetflixSession.py", "diff": "@@ -281,7 +281,9 @@ class NetflixSession:\nprofile = {'id': profile_id}\nfor important_field in important_fields:\nprofile.update({important_field: item['profiles'][profile_id]['summary'][important_field]})\n- profile.update({'avatar': item['avatars']['nf'][item['profiles'][profile_id]['summary']['avatarName']]['images']['byWidth']['320']['value']})\n+ avatar_base = item['avatars']['nf'].get(item['profiles'][profile_id]['summary']['avatarName'], False);\n+ avatar = 'https://secure.netflix.com/ffe/profiles/avatars_v2/320x320/PICON_029.png' if avatar_base == False else avatar_base['images']['byWidth']['320']['value']\n+ profile.update({'avatar': avatar})\nprofiles.update({profile_id: profile})\nreturn profiles\n" } ]
Python
MIT License
castagnait/plugin.video.netflix
fix(profiles): Add default avatar
105,996
27.02.2017 09:56:59
-3,600
0c5653eedae999646dfa3e125cd7126021d927f9
Set MPD::mediaPresentationDuration
[ { "change_type": "MODIFY", "old_path": "resources/lib/MSL.py", "new_path": "resources/lib/MSL.py", "diff": "@@ -207,15 +207,13 @@ class MSL:\nif len(manifest['psshb64']) >= 1:\npssh = manifest['psshb64'][0]\n-\n+ seconds = manifest['runtime']/1000\n+ duration = \"PT\"+str(seconds)+\".00S\"\nroot = ET.Element('MPD')\nroot.attrib['xmlns'] = 'urn:mpeg:dash:schema:mpd:2011'\nroot.attrib['xmlns:cenc'] = 'urn:mpeg:cenc:2013'\n-\n-\n- seconds = manifest['runtime']/1000\n- duration = \"PT\"+str(seconds)+\".00S\"\n+ root.attrib['mediaPresentationDuration'] = duration\nperiod = ET.SubElement(root, 'Period', start='PT0S', duration=duration)\n" } ]
Python
MIT License
castagnait/plugin.video.netflix
Set MPD::mediaPresentationDuration
105,979
27.02.2017 13:53:06
-3,600
559ce4832693d6a8e805ce50c1d6a3283cda6c88
fix(metadata): Bumped version, changed licence to MIT, added providers & removed inputstream.adaptive dependency
[ { "change_type": "MODIFY", "old_path": "addon.xml", "new_path": "addon.xml", "diff": "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>\n-<addon id=\"plugin.video.netflix\" name=\"Netflix\" version=\"0.3.0\" provider-name=\"tba\">\n+<addon id=\"plugin.video.netflix\" name=\"Netflix\" version=\"0.9.0\" provider-name=\"libdev,jojo,asciidisco\">\n<requires>\n<import addon=\"xbmc.python\" version=\"2.24.0\"/>\n<import addon=\"script.module.beautifulsoup4\" version=\"4.3.2\"/>\n<import addon=\"script.module.requests\" version=\"2.12.4\"/>\n<import addon=\"script.module.pycryptodome\" version=\"3.4.3\"/>\n<import addon=\"script.module.simplejson\" version=\"3.3.0\"/>\n- <import addon=\"inputstream.adaptive\" version=\"1.0.7\"/>\n</requires>\n<extension point=\"xbmc.python.pluginsource\" library=\"addon.py\">\n<provides>video</provides>\n<screenshot>resources\\screenshot-03.jpg</screenshot>\n</assets>\n<platform>all</platform>\n- <license>GNU GENERAL PUBLIC LICENSE. Version 2, June 1991</license>\n+ <license>MIT</license>\n<forum>http://www.kodinerds.net/</forum>\n<source>https://github.com/kodinerds/repo</source>\n</extension>\n" } ]
Python
MIT License
castagnait/plugin.video.netflix
fix(metadata): Bumped version, changed licence to MIT, added providers & removed inputstream.adaptive dependency
105,979
27.02.2017 13:54:40
-3,600
e55e9232b3e042fadd2ecaeb2d9f7f7859929915
fix(adult-pin): Fixed named variable for adult pin
[ { "change_type": "MODIFY", "old_path": "resources/lib/Navigation.py", "new_path": "resources/lib/Navigation.py", "diff": "@@ -108,7 +108,7 @@ class Navigation:\nadult_pin = None\nif self.check_for_adult_pin(params=params):\nadult_pin = self.kodi_helper.show_adult_pin_dialog()\n- if self.netflix_session.send_adult_pin(adult_pin=adult_pin) != True:\n+ if self.netflix_session.send_adult_pin(pin=adult_pin) != True:\nreturn self.kodi_helper.show_wrong_adult_pin_notification()\nself.play_video(video_id=params['video_id'], start_offset=params.get('start_offset', -1))\nelif params['action'] == 'user-items' and params['type'] == 'search':\n" } ]
Python
MIT License
castagnait/plugin.video.netflix
fix(adult-pin): Fixed named variable for adult pin
105,979
27.02.2017 13:55:21
-3,600
08d0b0c5ab8ce5424519703268331ee11f1fabe4
fix(core): Added back msl server certificate as long as the kodi settings bug persists
[ { "change_type": "MODIFY", "old_path": "resources/lib/KodiHelper.py", "new_path": "resources/lib/KodiHelper.py", "diff": "@@ -650,7 +650,9 @@ class KodiHelper:\nplay_item.setProperty(inputstream_addon + '.license_type', 'com.widevine.alpha')\nplay_item.setProperty(inputstream_addon + '.manifest_type', 'mpd')\nplay_item.setProperty(inputstream_addon + '.license_key', msl_service_url + '/license?id=' + video_id + '||b{SSM}!b{SID}|')\n- play_item.setProperty(inputstream_addon + '.server_certificate', self.addon.getSetting('msl_service_certificate'))\n+ play_item.setProperty(inputstream_addon + '.server_certificate', 'Cr0CCAMSEOVEukALwQ8307Y2+LVP+0MYh/HPkwUijgIwggEKAoIBAQDm875btoWUbGqQD8eAGuBlGY+Pxo8YF1LQR+Ex0pDONMet8EHslcZRBKNQ/09RZFTP0vrYimyYiBmk9GG+S0wB3CRITgweNE15cD33MQYyS3zpBd4z+sCJam2+jj1ZA4uijE2dxGC+gRBRnw9WoPyw7D8RuhGSJ95OEtzg3Ho+mEsxuE5xg9LM4+Zuro/9msz2bFgJUjQUVHo5j+k4qLWu4ObugFmc9DLIAohL58UR5k0XnvizulOHbMMxdzna9lwTw/4SALadEV/CZXBmswUtBgATDKNqjXwokohncpdsWSauH6vfS6FXwizQoZJ9TdjSGC60rUB2t+aYDm74cIuxAgMBAAE6EHRlc3QubmV0ZmxpeC5jb20SgAOE0y8yWw2Win6M2/bw7+aqVuQPwzS/YG5ySYvwCGQd0Dltr3hpik98WijUODUr6PxMn1ZYXOLo3eED6xYGM7Riza8XskRdCfF8xjj7L7/THPbixyn4mULsttSmWFhexzXnSeKqQHuoKmerqu0nu39iW3pcxDV/K7E6aaSr5ID0SCi7KRcL9BCUCz1g9c43sNj46BhMCWJSm0mx1XFDcoKZWhpj5FAgU4Q4e6f+S8eX39nf6D6SJRb4ap7Znzn7preIvmS93xWjm75I6UBVQGo6pn4qWNCgLYlGGCQCUm5tg566j+/g5jvYZkTJvbiZFwtjMW5njbSRwB3W4CrKoyxw4qsJNSaZRTKAvSjTKdqVDXV/U5HK7SaBA6iJ981/aforXbd2vZlRXO/2S+Maa2mHULzsD+S5l4/YGpSt7PnkCe25F+nAovtl/ogZgjMeEdFyd/9YMYjOS4krYmwp3yJ7m9ZzYCQ6I8RQN4x/yLlHG5RH/+WNLNUs6JAZ0fFdCmw=')\n+ # TODO: Change when Kodi can handle/trnsfer defaults in hidden values in settings\n+ #play_item.setProperty(inputstream_addon + '.server_certificate', self.addon.getSetting('msl_service_certificate'))\nplay_item.setProperty('inputstreamaddon', inputstream_addon)\n# check if we have a bookmark e.g. start offset position\n" } ]
Python
MIT License
castagnait/plugin.video.netflix
fix(core): Added back msl server certificate as long as the kodi settings bug persists
105,979
27.02.2017 14:22:17
-3,600
c69d8a0ec4b7f180c5a7741b64cb86d7e5927bbd
fix(seasons): Make season sorting more robust
[ { "change_type": "MODIFY", "old_path": "resources/lib/KodiHelper.py", "new_path": "resources/lib/KodiHelper.py", "diff": "@@ -557,7 +557,7 @@ class KodiHelper:\nfor index in seasons_sorted:\nfor season_id in season_list:\nseason = season_list[season_id]\n- if int(season['shortName'].split(' ')[1]) == index:\n+ if int(season['id']) == index:\nli = xbmcgui.ListItem(label=season['text'])\n# add some art to the item\nli = self._generate_art_info(entry=season, li=li)\n" } ]
Python
MIT License
castagnait/plugin.video.netflix
fix(seasons): Make season sorting more robust
105,979
02.03.2017 13:48:39
-3,600
cd0b4229bc7472a3e822e8e842e7696b535a22e7
chore(metadata): Version bump
[ { "change_type": "MODIFY", "old_path": "addon.xml", "new_path": "addon.xml", "diff": "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>\n-<addon id=\"plugin.video.netflix\" name=\"Netflix\" version=\"0.9.0\" provider-name=\"libdev,jojo,asciidisco\">\n+<addon id=\"plugin.video.netflix\" name=\"Netflix\" version=\"0.9.1\" provider-name=\"libdev + jojo + asciidisco\">\n<requires>\n<import addon=\"xbmc.python\" version=\"2.24.0\"/>\n<import addon=\"script.module.beautifulsoup4\" version=\"4.3.2\"/>\n" } ]
Python
MIT License
castagnait/plugin.video.netflix
chore(metadata): Version bump
105,979
02.03.2017 14:06:16
-3,600
34e4ea221678c60eb04365005818659f153e42d4
chore(readme): Minor additions
[ { "change_type": "MODIFY", "old_path": "README.md", "new_path": "README.md", "diff": "@@ -31,6 +31,7 @@ please open an issue & we can provide you with some help to get started\n- [ ] Enable possibility to export single episodes or seasons to the Library\n- [ ] Evaluate idea of an auto updating library exporter that keeps track (on Plugin start/on Service start maybe)\n- [ ] If a new user has been created, they need to select their movie/show preferences to actually get started, we could provide the same mechanisms in Kodi\n+- [ ] Enable aggressive fetching of data in background (maybe using Futures), like the Netflix website does, to enhance the speed and the user experience when browsing the frontend\n###Something doesn't work\n-------------------------\n" } ]
Python
MIT License
castagnait/plugin.video.netflix
chore(readme): Minor additions
106,029
02.03.2017 14:12:09
-3,600
3f1982ccdd1e9a0eb46c505996616613e8089ed4
Removes own Loggging Setting
[ { "change_type": "MODIFY", "old_path": "resources/language/English/strings.po", "new_path": "resources/language/English/strings.po", "diff": "@@ -85,14 +85,6 @@ msgctxt \"#30014\"\nmsgid \"Account\"\nmsgstr \"\"\n-msgctxt \"#30015\"\n-msgid \"Logging\"\n-msgstr \"\"\n-\n-msgctxt \"#30016\"\n-msgid \"Verbose logging\"\n-msgstr \"\"\n-\nmsgctxt \"#30017\"\nmsgid \"Logout\"\nmsgstr \"\"\n" }, { "change_type": "MODIFY", "old_path": "resources/language/German/strings.po", "new_path": "resources/language/German/strings.po", "diff": "@@ -85,14 +85,6 @@ msgctxt \"#30014\"\nmsgid \"Account\"\nmsgstr \"Account\"\n-msgctxt \"#30015\"\n-msgid \"Logging\"\n-msgstr \"Logging\"\n-\n-msgctxt \"#30016\"\n-msgid \"Verbose logging\"\n-msgstr \"Verbose logging\"\n-\nmsgctxt \"#30017\"\nmsgid \"Logout\"\nmsgstr \"Logout\"\n" }, { "change_type": "MODIFY", "old_path": "resources/lib/KodiHelper.py", "new_path": "resources/lib/KodiHelper.py", "diff": "@@ -832,7 +832,7 @@ class KodiHelper:\nli.addContextMenuItems(items)\nreturn li\n- def log (self, msg, level=xbmc.LOGNOTICE):\n+ def log (self, msg, level=xbmc.LOGDEBUG):\n\"\"\"Adds a log entry to the Kodi log\nParameters\n@@ -843,9 +843,6 @@ class KodiHelper:\nlevel : :obj:`int`\nKodi log level\n\"\"\"\n- if self.verb_log:\n- if level == xbmc.LOGDEBUG and self.verb_log:\n- level = xbmc.LOGNOTICE\nif isinstance(msg, unicode):\nmsg = msg.encode('utf-8')\nxbmc.log('[%s] %s' % (self.plugin, msg.__str__()), level)\n" }, { "change_type": "MODIFY", "old_path": "resources/settings.xml", "new_path": "resources/settings.xml", "diff": "<setting id=\"msl_service_port\" value=\"8000\" visible=\"false\"/>\n<setting id=\"msl_service_certificate\" visible=\"false\" value=\"Cr0CCAMSEOVEukALwQ8307Y2+LVP+0MYh/HPkwUijgIwggEKAoIBAQDm875btoWUbGqQD8eAGuBlGY+Pxo8YF1LQR+Ex0pDONMet8EHslcZRBKNQ/09RZFTP0vrYimyYiBmk9GG+S0wB3CRITgweNE15cD33MQYyS3zpBd4z+sCJam2+jj1ZA4uijE2dxGC+gRBRnw9WoPyw7D8RuhGSJ95OEtzg3Ho+mEsxuE5xg9LM4+Zuro/9msz2bFgJUjQUVHo5j+k4qLWu4ObugFmc9DLIAohL58UR5k0XnvizulOHbMMxdzna9lwTw/4SALadEV/CZXBmswUtBgATDKNqjXwokohncpdsWSauH6vfS6FXwizQoZJ9TdjSGC60rUB2t+aYDm74cIuxAgMBAAE6EHRlc3QubmV0ZmxpeC5jb20SgAOE0y8yWw2Win6M2/bw7+aqVuQPwzS/YG5ySYvwCGQd0Dltr3hpik98WijUODUr6PxMn1ZYXOLo3eED6xYGM7Riza8XskRdCfF8xjj7L7/THPbixyn4mULsttSmWFhexzXnSeKqQHuoKmerqu0nu39iW3pcxDV/K7E6aaSr5ID0SCi7KRcL9BCUCz1g9c43sNj46BhMCWJSm0mx1XFDcoKZWhpj5FAgU4Q4e6f+S8eX39nf6D6SJRb4ap7Znzn7preIvmS93xWjm75I6UBVQGo6pn4qWNCgLYlGGCQCUm5tg566j+/g5jvYZkTJvbiZFwtjMW5njbSRwB3W4CrKoyxw4qsJNSaZRTKAvSjTKdqVDXV/U5HK7SaBA6iJ981/aforXbd2vZlRXO/2S+Maa2mHULzsD+S5l4/YGpSt7PnkCe25F+nAovtl/ogZgjMeEdFyd/9YMYjOS4krYmwp3yJ7m9ZzYCQ6I8RQN4x/yLlHG5RH/+WNLNUs6JAZ0fFdCmw=\"/>\n</category>\n- <category label=\"30015\">\n- <setting id=\"logging\" type=\"bool\" label=\"30016\" default=\"false\"/>\n- </category>\n</settings>\n" } ]
Python
MIT License
castagnait/plugin.video.netflix
Removes own Loggging Setting
106,029
02.03.2017 14:12:46
-3,600
465712e1d4368f223d522f178934f16e044fbb1a
Changes Crypto to Cryptodome Adds more logging to MSL Service
[ { "change_type": "MODIFY", "old_path": "resources/lib/MSL.py", "new_path": "resources/lib/MSL.py", "diff": "@@ -5,18 +5,16 @@ import os\nimport pprint\nimport random\nfrom StringIO import StringIO\n-from hmac import HMAC\n-import hashlib\nimport requests\nimport zlib\nimport time\n-from Crypto.PublicKey import RSA\n-from Crypto.Cipher import PKCS1_OAEP\n-from Crypto.Cipher import AES\n-from Crypto.Random import get_random_bytes\n-# from Crypto.Hash import HMAC, SHA256\n-from Crypto.Util import Padding\n+from Cryptodome.PublicKey import RSA\n+from Cryptodome.Cipher import PKCS1_OAEP\n+from Cryptodome.Cipher import AES\n+from Cryptodome.Random import get_random_bytes\n+from Crypto.Hash import HMAC, SHA256\n+from Cryptodome.Util import Padding\nimport xml.etree.ElementTree as ET\npp = pprint.PrettyPrinter(indent=4)\n@@ -61,6 +59,7 @@ class MSL:\npass\nif self.file_exists(self.kodi_helper.msl_data_path, 'msl_data.json'):\n+ self.kodi_helper.log(msg='MSL Data exists. Use old Tokens.')\nself.__load_msl_data()\nself.handshake_performed = True\nelif self.file_exists(self.kodi_helper.msl_data_path, 'rsa_key.bin'):\n@@ -75,6 +74,11 @@ class MSL:\nself.__perform_key_handshake()\ndef load_manifest(self, viewable_id):\n+ \"\"\"\n+ Loads the manifets for the given viewable_id and returns a mpd-XML-Manifest\n+ :param viewable_id: The id of of the viewable\n+ :return: MPD XML Manifest or False if no success\n+ \"\"\"\nmanifest_request_data = {\n'method': 'manifest',\n'lookupType': 'PREPARE',\n@@ -106,38 +110,28 @@ class MSL:\n'uiVersion': 'akira'\n}\nrequest_data = self.__generate_msl_request_data(manifest_request_data)\n-\nresp = self.session.post(self.endpoints['manifest'], request_data)\n-\ntry:\n+ # if the json() does not fail we have an error because the manifest response is a chuncked json response\nresp.json()\n- self.kodi_helper.log(msg='MANIFEST RESPONE JSON: '+resp.text)\n+ self.kodi_helper.log(msg='Error getting Manifest: '+resp.text)\n+ return False\nexcept ValueError:\n- # Maybe we have a CHUNKED response\n+ # json() failed so parse the chunked response\n+ self.kodi_helper.log(msg='Got chunked Manifest Response: ' + resp.text)\nresp = self.__parse_chunked_msl_response(resp.text)\n+ self.kodi_helper.log(msg='Parsed chunked Response: ' + json.dumps(resp))\ndata = self.__decrypt_payload_chunk(resp['payloads'][0])\n- # pprint.pprint(data)\nreturn self.__tranform_to_dash(data)\n-\ndef get_license(self, challenge, sid):\n-\n\"\"\"\n- std::time_t t = std::time(0); // t is an integer type\n- licenseRequestData[\"clientTime\"] = (int)t;\n- //licenseRequestData[\"challengeBase64\"] = challengeStr;\n- licenseRequestData[\"licenseType\"] = \"STANDARD\";\n- licenseRequestData[\"playbackContextId\"] = playbackContextId;//\"E1-BQFRAAELEB32o6Se-GFvjwEIbvDydEtfj6zNzEC3qwfweEPAL3gTHHT2V8rS_u1Mc3mw5BWZrUlKYIu4aArdjN8z_Z8t62E5jRjLMdCKMsVhlSJpiQx0MNW4aGqkYz-1lPh85Quo4I_mxVBG5lgd166B5NDizA8.\";\n- licenseRequestData[\"drmContextIds\"] = Json::arrayValue;\n- licenseRequestData[\"drmContextIds\"].append(drmContextId);\n-\n- :param viewable_id:\n- :param challenge:\n- :param kid:\n- :return:\n+ Requests and returns a license for the given challenge and sid\n+ :param challenge: The base64 encoded challenge\n+ :param sid: The sid paired to the challengew\n+ :return: Base64 representation of the license key or False if no success\n\"\"\"\n-\nlicense_request_data = {\n'method': 'license',\n'licenseType': 'STANDARD',\n@@ -159,18 +153,19 @@ class MSL:\nresp = self.session.post(self.endpoints['license'], request_data)\ntry:\n+ # If is valid json the request for the licnese failed\nresp.json()\n- self.kodi_helper.log(msg='LICENSE RESPONE JSON: '+resp.text)\n+ self.kodi_helper.log(msg='Error getting license: '+resp.text)\n+ return False\nexcept ValueError:\n- # Maybe we have a CHUNKED response\n+ # json() failed so we have a chunked json response\nresp = self.__parse_chunked_msl_response(resp.text)\ndata = self.__decrypt_payload_chunk(resp['payloads'][0])\n- # pprint.pprint(data)\nif data['success'] is True:\nreturn data['result']['licenses'][0]['data']\nelse:\n- return ''\n-\n+ self.kodi_helper.log(msg='Error getting license: ' + json.dumps(data))\n+ return False\ndef __decrypt_payload_chunk(self, payloadchunk):\npayloadchunk = json.JSONDecoder().decode(payloadchunk)\n@@ -329,21 +324,7 @@ class MSL:\n'signature': self.__sign(first_payload_encryption_envelope),\n}\n-\n- # Create Second Payload\n- second_payload = {\n- \"messageid\": self.current_message_id,\n- \"data\": \"\",\n- \"endofmsg\": True,\n- \"sequencenumber\": 2\n- }\n- second_payload_encryption_envelope = self.__encrypt(json.dumps(second_payload))\n- second_payload_chunk = {\n- 'payload': base64.standard_b64encode(second_payload_encryption_envelope),\n- 'signature': base64.standard_b64encode(self.__sign(second_payload_encryption_envelope)),\n- }\n-\n- request_data = json.dumps(header) + json.dumps(first_payload_chunk) # + json.dumps(second_payload_chunk)\n+ request_data = json.dumps(header) + json.dumps(first_payload_chunk)\nreturn request_data\n@@ -430,18 +411,18 @@ class MSL:\nencryption_envelope['ciphertext'] = base64.standard_b64encode(ciphertext)\nreturn json.dumps(encryption_envelope)\n- def __sign(self, text):\n- #signature = hmac.new(self.sign_key, text, hashlib.sha256).digest()\n- signature = HMAC(self.sign_key, text, hashlib.sha256).digest()\n-\n- # hmac = HMAC.new(self.sign_key, digestmod=SHA256)\n- # hmac.update(text)\n+ def __sign(self, text):\n+ \"\"\"\n+ Calculates the HMAC signature for the given text with the current sign key and SHA256\n+ :param text:\n+ :return: Base64 encoded signature\n+ \"\"\"\n+ signature = HMAC.new(self.sign_key, text, SHA256).digest()\nreturn base64.standard_b64encode(signature)\ndef __perform_key_handshake(self):\n-\nheader = self.__generate_msl_header(is_key_request=True, is_handshake=True, compressionalgo=\"\", encrypt=False)\nrequest = {\n'entityauthdata': {\n@@ -456,7 +437,6 @@ class MSL:\nself.kodi_helper.log(msg='Key Handshake Request:')\nself.kodi_helper.log(msg=json.dumps(request))\n-\nresp = self.session.post(self.endpoints['manifest'], json.dumps(request, sort_keys=True))\nif resp.status_code == 200:\nresp = resp.json()\n@@ -510,8 +490,7 @@ class MSL:\ndef __set_master_token(self, master_token):\nself.mastertoken = master_token\n- self.sequence_number = json.JSONDecoder().decode(base64.standard_b64decode(master_token['tokendata']))[\n- 'sequencenumber']\n+ self.sequence_number = json.JSONDecoder().decode(base64.standard_b64decode(master_token['tokendata']))['sequencenumber']\ndef __load_rsa_keys(self):\nloaded_key = self.load_file(self.kodi_helper.msl_data_path, 'rsa_key.bin')\n" }, { "change_type": "MODIFY", "old_path": "resources/lib/MSLHttpRequestHandler.py", "new_path": "resources/lib/MSLHttpRequestHandler.py", "diff": "import BaseHTTPServer\nimport base64\nfrom urlparse import urlparse, parse_qs\n-\n+import xbmcaddon\nfrom MSL import MSL\nfrom KodiHelper import KodiHelper\n@@ -9,6 +9,7 @@ kodi_helper = KodiHelper(\nplugin_handle=None,\nbase_url=None\n)\n+\naccount = kodi_helper.get_credentials()\nmsl = MSL(account['email'], account['password'], kodi_helper)\n" }, { "change_type": "MODIFY", "old_path": "service.py", "new_path": "service.py", "diff": "@@ -6,25 +6,27 @@ import socket\nfrom resources.lib.KodiHelper import KodiHelper\nfrom resources.lib.MSLHttpRequestHandler import MSLHttpRequestHandler\n-def select_unused_port():\n- s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n- s.bind(('localhost', 0))\n- addr, port = s.getsockname()\n- s.close()\n- return port\n-\naddon = xbmcaddon.Addon()\nkodi_helper = KodiHelper(\nplugin_handle=None,\nbase_url=None\n)\n-PORT = select_unused_port()\n-addon.setSetting('msl_service_port', str(PORT))\n-kodi_helper.log(msg='Picked Port: ' + str(PORT))\n-Handler = MSLHttpRequestHandler\n+\n+def select_unused_port():\n+ sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n+ sock.bind(('localhost', 0))\n+ addr, port = sock.getsockname()\n+ sock.close()\n+ return port\n+\n+port = select_unused_port()\n+addon.setSetting('msl_service_port', str(port))\n+kodi_helper.log(msg='Picked Port: ' + str(port))\n+\n+#Config the HTTP Server\nSocketServer.TCPServer.allow_reuse_address = True\n-server = SocketServer.TCPServer(('127.0.0.1', PORT), Handler)\n+server = SocketServer.TCPServer(('127.0.0.1', port), MSLHttpRequestHandler)\nserver.server_activate()\nserver.timeout = 1\n" } ]
Python
MIT License
castagnait/plugin.video.netflix
Changes Crypto to Cryptodome Adds more logging to MSL Service
106,029
02.03.2017 15:44:13
-3,600
693e8f1cb855748ca7b496cc6ef2658865cbab1c
Adds profile to manifest request
[ { "change_type": "MODIFY", "old_path": "resources/lib/MSL.py", "new_path": "resources/lib/MSL.py", "diff": "@@ -13,7 +13,7 @@ from Cryptodome.PublicKey import RSA\nfrom Cryptodome.Cipher import PKCS1_OAEP\nfrom Cryptodome.Cipher import AES\nfrom Cryptodome.Random import get_random_bytes\n-from Crypto.Hash import HMAC, SHA256\n+from Cryptodome.Hash import HMAC, SHA256\nfrom Cryptodome.Util import Padding\nimport xml.etree.ElementTree as ET\n@@ -36,6 +36,7 @@ class MSL:\nlast_playback_context = ''\n#esn = \"NFCDCH-LX-CQE0NU6PA5714R25VPLXVU2A193T36\"\nesn = \"WWW-BROWSE-D7GW1G4NPXGR1F0X1H3EQGY3V1F5WE\"\n+ #esn = \"NFCDIE-02-DCH84Q2EK3N6VFVQJ0NLRQ27498N0F\"\ncurrent_message_id = 0\nsession = requests.session()\nrndm = random.SystemRandom()\n@@ -86,6 +87,7 @@ class MSL:\n'profiles': [\n'playready-h264mpl30-dash',\n'playready-h264mpl31-dash',\n+ 'playready-h264mpl40-dash',\n'heaac-2-dash',\n'dfxp-ls-sdh',\n'simplesdh',\n" } ]
Python
MIT License
castagnait/plugin.video.netflix
Adds profile to manifest request
106,029
02.03.2017 20:04:23
-3,600
5567fb19118646a4606df39dcb93dfdacf15f256
Adds more profiles to manifest request
[ { "change_type": "MODIFY", "old_path": "resources/lib/MSL.py", "new_path": "resources/lib/MSL.py", "diff": "@@ -85,10 +85,72 @@ class MSL:\n'lookupType': 'PREPARE',\n'viewableIds': [viewable_id],\n'profiles': [\n- 'playready-h264mpl30-dash',\n- 'playready-h264mpl31-dash',\n- 'playready-h264mpl40-dash',\n+ \"playready-h264bpl30-dash\",\n+ \"playready-h264mpl30-dash\",\n+ \"playready-h264mpl31-dash\",\n+ \"playready-h264mpl40-dash\",\n+ # \"hevc-main-L30-dash-cenc\",\n+ # \"hevc-main-L31-dash-cenc\",\n+ # \"hevc-main-L40-dash-cenc\",\n+ # \"hevc-main-L41-dash-cenc\",\n+ # \"hevc-main-L50-dash-cenc\",\n+ # \"hevc-main-L51-dash-cenc\",\n+ # \"hevc-main10-L30-dash-cenc\",\n+ # \"hevc-main10-L31-dash-cenc\",\n+ # \"hevc-main10-L40-dash-cenc\",\n+ # \"hevc-main10-L41-dash-cenc\",\n+ # \"hevc-main10-L50-dash-cenc\",\n+ # \"hevc-main10-L51-dash-cenc\",\n+ # \"hevc-main10-L30-dash-cenc-prk\",\n+ # \"hevc-main10-L31-dash-cenc-prk\",\n+ # \"hevc-main10-L40-dash-cenc-prk\",\n+ # \"hevc-main10-L41-dash-cenc-prk\",\n+ # \"hevc-main-L30-L31-dash-cenc-tl\",\n+ # \"hevc-main-L31-L40-dash-cenc-tl\",\n+ # \"hevc-main-L40-L41-dash-cenc-tl\",\n+ # \"hevc-main-L50-L51-dash-cenc-tl\",\n+ # \"hevc-main10-L30-L31-dash-cenc-tl\",\n+ # \"hevc-main10-L31-L40-dash-cenc-tl\",\n+ # \"hevc-main10-L40-L41-dash-cenc-tl\",\n+ # \"hevc-main10-L50-L51-dash-cenc-tl\",\n+ # \"hevc-dv-main10-L30-dash-cenc\",\n+ # \"hevc-dv-main10-L31-dash-cenc\",\n+ # \"hevc-dv-main10-L40-dash-cenc\",\n+ # \"hevc-dv-main10-L41-dash-cenc\",\n+ # \"hevc-dv-main10-L50-dash-cenc\",\n+ # \"hevc-dv-main10-L51-dash-cenc\",\n+ # \"hevc-dv5-main10-L30-dash-cenc-prk\",\n+ # \"hevc-dv5-main10-L31-dash-cenc-prk\",\n+ # \"hevc-dv5-main10-L40-dash-cenc-prk\",\n+ # \"hevc-dv5-main10-L41-dash-cenc-prk\",\n+ # \"hevc-dv5-main10-L50-dash-cenc-prk\",\n+ # \"hevc-dv5-main10-L51-dash-cenc-prk\",\n+ # \"hevc-hdr-main10-L30-dash-cenc\",\n+ # \"hevc-hdr-main10-L31-dash-cenc\",\n+ # \"hevc-hdr-main10-L40-dash-cenc\",\n+ # \"hevc-hdr-main10-L41-dash-cenc\",\n+ # \"hevc-hdr-main10-L50-dash-cenc\",\n+ # \"hevc-hdr-main10-L51-dash-cenc\",\n+ # \"hevc-hdr-main10-L30-dash-cenc-prk\",\n+ # \"hevc-hdr-main10-L31-dash-cenc-prk\",\n+ # \"hevc-hdr-main10-L40-dash-cenc-prk\",\n+ # \"hevc-hdr-main10-L41-dash-cenc-prk\",\n+ # \"hevc-hdr-main10-L50-dash-cenc-prk\",\n+ # \"hevc-hdr-main10-L51-dash-cenc-prk\"\n+\n+ # 'playready-h264mpl30-dash',\n+ #'playready-h264mpl31-dash',\n+ #'playready-h264mpl40-dash',\n+ #'hevc-main10-L41-dash-cenc',\n+ #'hevc-main10-L50-dash-cenc',\n+ #'hevc-main10-L51-dash-cenc',\n+\n+\n+\n+ # Audio\n'heaac-2-dash',\n+ 'ddplus-2.0-dash',\n+ 'ddplus-5.1-dash',\n'dfxp-ls-sdh',\n'simplesdh',\n'nflx-cmisc',\n@@ -224,10 +286,18 @@ class MSL:\nET.SubElement(protection, 'cenc:pssh').text = pssh\nfor downloadable in video_track['downloadables']:\n+\n+ hdcp_versions = '0.0'\n+ for hdcp in downloadable['hdcpVersions']:\n+ if hdcp != 'none':\n+ hdcp_versions = hdcp\n+\nrep = ET.SubElement(video_adaption_set, 'Representation',\nwidth=str(downloadable['width']),\nheight=str(downloadable['height']),\nbandwidth=str(downloadable['bitrate']*1024),\n+ hdcp=hdcp_versions,\n+ nflxContentProfile=str(downloadable['contentProfile']),\ncodecs='h264',\nmimeType='video/mp4')\n@@ -246,8 +316,13 @@ class MSL:\ncontentType='audio',\nmimeType='audio/mp4')\nfor downloadable in audio_track['downloadables']:\n+ codec = 'aac'\n+ print downloadable\n+ if downloadable['contentProfile'] == 'ddplus-2.0-dash' or downloadable['contentProfile'] == 'ddplus-5.1-dash':\n+ codec = 'ec-3'\n+ print \"codec is: \" + codec\nrep = ET.SubElement(audio_adaption_set, 'Representation',\n- codecs='aac',\n+ codecs=codec,\nbandwidth=str(downloadable['bitrate']*1024),\nmimeType='audio/mp4')\n@@ -308,7 +383,7 @@ class MSL:\n# Serialize the given Data\nserialized_data = json.dumps(data)\nserialized_data = serialized_data.replace('\"', '\\\\\"')\n- serialized_data = '[{},{\"headers\":{},\"path\":\"/cbp/cadmium-11\",\"payload\":{\"data\":\"' + serialized_data + '\"},\"query\":\"\"}]\\n'\n+ serialized_data = '[{},{\"headers\":{},\"path\":\"/cbp/cadmium-13\",\"payload\":{\"data\":\"' + serialized_data + '\"},\"query\":\"\"}]\\n'\ncompressed_data = self.__compress_data(serialized_data)\n" } ]
Python
MIT License
castagnait/plugin.video.netflix
Adds more profiles to manifest request
105,979
03.03.2017 12:27:06
-3,600
f2d29fb1561ddc4a393555f855a7aa7897106d1b
fix(seasons): Fixes - Seasons are now properly ordered. Remove print debugging statement
[ { "change_type": "MODIFY", "old_path": "resources/lib/KodiHelper.py", "new_path": "resources/lib/KodiHelper.py", "diff": "@@ -532,7 +532,7 @@ class KodiHelper:\nfor index in seasons_sorted:\nfor season_id in season_list:\nseason = season_list[season_id]\n- if int(season['id']) == index:\n+ if int(season['idx']) == index:\nli = xbmcgui.ListItem(label=season['text'])\n# add some art to the item\nli = self._generate_art_info(entry=season, li=li)\n" }, { "change_type": "MODIFY", "old_path": "resources/lib/NetflixSession.py", "new_path": "resources/lib/NetflixSession.py", "diff": "@@ -243,9 +243,6 @@ class NetflixSession:\nif 'memberContext' in dict(item).keys():\nfor important_field in important_fields:\nuser_data.update({important_field: item['memberContext']['data']['userInfo'][important_field]})\n- print '.............'\n- print user_data\n- print '.............'\nreturn user_data\ndef _parse_profile_data (self, netflix_page_data):\n@@ -284,9 +281,6 @@ class NetflixSession:\nfor item in netflix_page_data:\nif 'hasViewedRatingWelcomeModal' in dict(item).keys():\nfor profile_id in item:\n- print '------------'\n- print profile_id\n- print '------------'\nif self._is_size_key(key=profile_id) == False and type(item[profile_id]) == dict and item[profile_id].get('avatar', False) != False:\nprofile = {'id': profile_id}\nfor important_field in important_fields:\n@@ -366,11 +360,6 @@ class NetflixSession:\nself.esn = self._parse_esn_data(netflix_page_data=netflix_page_data)\nself.api_data = self._parse_api_base_data(netflix_page_data=netflix_page_data)\nself.profiles = self._parse_profile_data(netflix_page_data=netflix_page_data)\n- if self.user_data.get('bauthURL', False) == False:\n- print '...............'\n- print page_soup.text.find('authURL');\n- print '...............'\n-\ndef is_logged_in (self, account):\n\"\"\"Determines if a user is already logged in (with a valid cookie),\n@@ -1326,8 +1315,14 @@ class NetflixSession:\nfor key in videos.keys():\nif self._is_size_key(key=key) == False:\nvideo_key = key\n+ # get season index\n+ sorting = {}\n+ for idx in videos[video_key]['seasonList']:\n+ if self._is_size_key(key=idx) == False and idx != 'summary':\n+ sorting[int(videos[video_key]['seasonList'][idx][1])] = int(idx)\nreturn {\nseason['summary']['id']: {\n+ 'idx': sorting[season['summary']['id']],\n'id': season['summary']['id'],\n'text': season['summary']['name'],\n'shortName': season['summary']['shortName'],\n" } ]
Python
MIT License
castagnait/plugin.video.netflix
fix(seasons): Fixes #11 - Seasons are now properly ordered. Remove print debugging statement
105,979
03.03.2017 12:54:37
-3,600
91eacc378fc888732ca71e5bccac4e38c303892f
fix(search): Fixes
[ { "change_type": "MODIFY", "old_path": "resources/lib/Navigation.py", "new_path": "resources/lib/Navigation.py", "diff": "@@ -157,6 +157,7 @@ class Navigation:\nif self.netflix_session._is_size_key(key=key) == False:\nhas_search_results = search_results_raw['value']['search'][key]['titles']['length'] > 0\nif has_search_results == False:\n+ if search_results_raw['value']['search'][key].get('suggestions', False) != False:\nfor entry in search_results_raw['value']['search'][key]['suggestions']:\nif self.netflix_session._is_size_key(key=entry) == False:\nif search_results_raw['value']['search'][key]['suggestions'][entry]['relatedvideos']['length'] > 0:\n" }, { "change_type": "MODIFY", "old_path": "resources/lib/NetflixSession.py", "new_path": "resources/lib/NetflixSession.py", "diff": "@@ -1164,11 +1164,11 @@ class NetflixSession:\n:obj:`str`\nQuality of the video\n\"\"\"\n- quality = '540'\n- if video['videoQuality']['hasHD']:\nquality = '720'\n- if video['videoQuality']['hasUltraHD']:\n+ if video['videoQuality']['hasHD']:\nquality = '1080'\n+ if video['videoQuality']['hasUltraHD']:\n+ quality = '4000'\nreturn quality\ndef parse_runtime_for_video (self, video):\n" } ]
Python
MIT License
castagnait/plugin.video.netflix
fix(search): Fixes #12
105,979
03.03.2017 17:18:13
-3,600
c56befbe404a7931774526ff5d446610e613a2e9
fix(ui): Masks password input, renders empty list if no search or seasons results are found
[ { "change_type": "MODIFY", "old_path": "addon.xml", "new_path": "addon.xml", "diff": "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>\n-<addon id=\"plugin.video.netflix\" name=\"Netflix\" version=\"0.9.2\" provider-name=\"libdev + jojo + asciidisco\">\n+<addon id=\"plugin.video.netflix\" name=\"Netflix\" version=\"0.9.3\" provider-name=\"libdev + jojo + asciidisco\">\n<requires>\n<import addon=\"xbmc.python\" version=\"2.24.0\"/>\n<import addon=\"script.module.beautifulsoup4\" version=\"4.3.2\"/>\n" }, { "change_type": "MODIFY", "old_path": "resources/language/English/strings.po", "new_path": "resources/language/English/strings.po", "diff": "# Kodi Media Center language file\n# Addon Name: Netflix\n# Addon id: plugin.video.netflix\n-# Addon version: 0.2.0\n+# Addon version: 0.9.3\n# Addon Provider: tba.\nmsgid \"\"\nmsgstr \"\"\n" }, { "change_type": "MODIFY", "old_path": "resources/language/German/strings.po", "new_path": "resources/language/German/strings.po", "diff": "# Kodi Media Center language file\n# Addon Name: Netflix\n# Addon id: plugin.video.netflix\n-# Addon version: 0.2.0\n+# Addon version: 0.9.3\n# Addon Provider: tba.\nmsgid \"\"\nmsgstr \"\"\n" }, { "change_type": "MODIFY", "old_path": "resources/lib/KodiHelper.py", "new_path": "resources/lib/KodiHelper.py", "diff": "@@ -100,7 +100,7 @@ class KodiHelper:\nNetflix password\n\"\"\"\ndlg = xbmcgui.Dialog()\n- return dlg.input(self.get_local_string(string_id=30004), type=xbmcgui.INPUT_ALPHANUM)\n+ return dlg.input(self.get_local_string(string_id=30004), type=xbmcgui.INPUT_ALPHANUM, option=xbmcgui.ALPHANUM_HIDE_INPUT)\ndef show_email_dialog (self):\n\"\"\"Asks the user for its Netflix account email\n@@ -137,6 +137,30 @@ class KodiHelper:\ndialog.notification(self.get_local_string(string_id=30028), self.get_local_string(string_id=30029), xbmcgui.NOTIFICATION_ERROR, 5000)\nreturn True\n+ def show_no_search_results_notification (self):\n+ \"\"\"Shows notification that no search results could be found\n+\n+ Returns\n+ -------\n+ bool\n+ Dialog shown\n+ \"\"\"\n+ dialog = xbmcgui.Dialog()\n+ dialog.notification(self.get_local_string(string_id=30011), self.get_local_string(string_id=30013))\n+ return True\n+\n+ def show_no_seasons_notification (self):\n+ \"\"\"Shows notification that no seasons be found\n+\n+ Returns\n+ -------\n+ bool\n+ Dialog shown\n+ \"\"\"\n+ dialog = xbmcgui.Dialog()\n+ dialog.notification(self.get_local_string(string_id=30010), self.get_local_string(string_id=30012))\n+ return True\n+\ndef set_setting (self, key, value):\n\"\"\"Public interface for the addons setSetting method\n@@ -452,8 +476,7 @@ class KodiHelper:\nbool\nList could be build\n\"\"\"\n- li = xbmcgui.ListItem(label=self.get_local_string(30012))\n- xbmcplugin.addDirectoryItem(handle=self.plugin_handle, url='', listitem=li, isFolder=False)\n+ self.show_no_seasons_notification()\nxbmcplugin.endOfDirectory(self.plugin_handle)\nreturn True\n@@ -473,10 +496,8 @@ class KodiHelper:\nbool\nList could be build\n\"\"\"\n- li = xbmcgui.ListItem(label=self.get_local_string(30013))\n- xbmcplugin.addDirectoryItem(handle=self.plugin_handle, url=build_url({'action': action}), listitem=li, isFolder=False)\n- xbmcplugin.endOfDirectory(self.plugin_handle)\n- return True\n+ self.show_no_search_results_notification()\n+ return xbmcplugin.endOfDirectory(self.plugin_handle)\ndef build_user_sub_listing (self, video_list_ids, type, action, build_url):\n\"\"\"Builds the video lists screen for user subfolders (genres & recommendations)\n" } ]
Python
MIT License
castagnait/plugin.video.netflix
fix(ui): Masks password input, renders empty list if no search or seasons results are found
106,029
03.03.2017 23:44:43
-3,600
da6c6467a3bbea8f796851b047df9c8f02399426
Adds init segment length calculation
[ { "change_type": "MODIFY", "old_path": "resources/lib/MSL.py", "new_path": "resources/lib/MSL.py", "diff": "@@ -267,6 +267,7 @@ class MSL:\npssh = manifest['psshb64'][0]\nseconds = manifest['runtime']/1000\n+ init_length = seconds / 2 * 12 + 20*1000\nduration = \"PT\"+str(seconds)+\".00S\"\nroot = ET.Element('MPD')\n@@ -287,6 +288,10 @@ class MSL:\nfor downloadable in video_track['downloadables']:\n+ codec = 'h264'\n+ if 'hevc' in downloadable['contentProfile']:\n+ codec = 'hevc'\n+\nhdcp_versions = '0.0'\nfor hdcp in downloadable['hdcpVersions']:\nif hdcp != 'none':\n@@ -298,14 +303,14 @@ class MSL:\nbandwidth=str(downloadable['bitrate']*1024),\nhdcp=hdcp_versions,\nnflxContentProfile=str(downloadable['contentProfile']),\n- codecs='h264',\n+ codecs=codec,\nmimeType='video/mp4')\n#BaseURL\nET.SubElement(rep, 'BaseURL').text = self.__get_base_url(downloadable['urls'])\n# Init an Segment block\n- segment_base = ET.SubElement(rep, 'SegmentBase', indexRange=\"0-60000\", indexRangeExact=\"true\")\n- ET.SubElement(segment_base, 'Initialization', range='0-60000')\n+ segment_base = ET.SubElement(rep, 'SegmentBase', indexRange=\"0-\"+str(init_length), indexRangeExact=\"true\")\n+ ET.SubElement(segment_base, 'Initialization', range='0-'+str(init_length))\n@@ -334,8 +339,8 @@ class MSL:\n#BaseURL\nET.SubElement(rep, 'BaseURL').text = self.__get_base_url(downloadable['urls'])\n# Index range\n- segment_base = ET.SubElement(rep, 'SegmentBase', indexRange=\"0-60000\", indexRangeExact=\"true\")\n- ET.SubElement(segment_base, 'Initialization', range='0-60000')\n+ segment_base = ET.SubElement(rep, 'SegmentBase', indexRange=\"0-\"+str(init_length), indexRangeExact=\"true\")\n+ ET.SubElement(segment_base, 'Initialization', range='0-'+str(init_length))\nxml = ET.tostring(root, encoding='utf-8', method='xml')\n" } ]
Python
MIT License
castagnait/plugin.video.netflix
Adds init segment length calculation
105,979
04.03.2017 12:50:42
-3,600
a36d534fb70a74aa805e147c4f26d518b1edfdf8
fix(parser): Speeds up HTML parsing
[ { "change_type": "MODIFY", "old_path": "resources/lib/NetflixSession.py", "new_path": "resources/lib/NetflixSession.py", "diff": "@@ -14,7 +14,7 @@ try:\nimport cPickle as pickle\nexcept:\nimport pickle\n-from bs4 import BeautifulSoup\n+from bs4 import BeautifulSoup, SoupStrainer\nfrom pyjsparser import PyJsParser\nfrom utils import noop\n@@ -360,6 +360,7 @@ class NetflixSession:\nself.esn = self._parse_esn_data(netflix_page_data=netflix_page_data)\nself.api_data = self._parse_api_base_data(netflix_page_data=netflix_page_data)\nself.profiles = self._parse_profile_data(netflix_page_data=netflix_page_data)\n+ return netflix_page_data\ndef is_logged_in (self, account):\n\"\"\"Determines if a user is already logged in (with a valid cookie),\n@@ -386,9 +387,9 @@ class NetflixSession:\nresponse = self.session.get(self._get_document_url_for(component='profiles'), verify=self.verify_ssl)\n# parse out the needed inline information\n- page_soup = BeautifulSoup(response.text)\n- page_data = self.extract_inline_netflix_page_data(page_soup=page_soup)\n- self._parse_page_contents(page_soup=page_soup)\n+ only_script_tags = SoupStrainer('script')\n+ page_soup = BeautifulSoup(response.text, 'html.parser', parse_only=only_script_tags)\n+ page_data = self._parse_page_contents(page_soup=page_soup)\n# check if the cookie is still valid\nfor item in page_data:\n@@ -443,7 +444,7 @@ class NetflixSession:\n# perform the login\nlogin_response = self.session.post(self._get_document_url_for(component='login'), data=login_payload, verify=self.verify_ssl)\n- login_soup = BeautifulSoup(login_response.text)\n+ login_soup = BeautifulSoup(login_response.text, 'html.parser')\n# we know that the login was successfull if we find an HTML element with the class of 'profile-name'\nif login_soup.find(attrs={'class' : 'profile-name'}) or login_soup.find(attrs={'class' : 'profile-icon'}):\n@@ -486,7 +487,8 @@ class NetflixSession:\n# fetch the index page again, so that we can fetch the corresponding user data\nbrowse_response = self.session.get(self._get_document_url_for(component='browse'), verify=self.verify_ssl)\n- browse_soup = BeautifulSoup(browse_response.text)\n+ only_script_tags = SoupStrainer('script')\n+ browse_soup = BeautifulSoup(response.text, 'html.parser', parse_only=only_script_tags)\nself._parse_page_contents(page_soup=browse_soup)\naccount_hash = self._generate_account_hash(account=account)\nself._save_data(filename=self.data_path + '_' + account_hash)\n@@ -1476,7 +1478,7 @@ class NetflixSession:\nInstance of an BeautifulSoup document containing the complete page contents\n\"\"\"\nresponse = self.session.get(self._get_document_url_for(component='browse'), verify=self.verify_ssl)\n- return BeautifulSoup(response.text)\n+ return BeautifulSoup(response.text, 'html.parser')\ndef fetch_video_list_ids (self, list_from=0, list_to=50):\n\"\"\"Fetches the JSON with detailed information based on the lists on the landing page (browse page) of Netflix\n@@ -1744,9 +1746,9 @@ class NetflixSession:\n# load the profiles page (to verify the user)\nresponse = self.session.get(self._get_document_url_for(component='profiles'), verify=self.verify_ssl)\n# parse out the needed inline information\n- page_soup = BeautifulSoup(response.text)\n- page_data = self.extract_inline_netflix_page_data(page_soup=page_soup)\n- self._parse_page_contents(page_soup)\n+ only_script_tags = SoupStrainer('script')\n+ page_soup = BeautifulSoup(response.text, 'html.parser', parse_only=only_script_tags)\n+ page_data = self._parse_page_contents(page_soup=page_soup)\naccount_hash = self._generate_account_hash(account=account)\nself._save_data(filename=self.data_path + '_' + account_hash)\n" } ]
Python
MIT License
castagnait/plugin.video.netflix
fix(parser): Speeds up HTML parsing
106,029
04.03.2017 14:54:45
-3,600
d6c102c7e99ca8cb1871ee3ef951c35fcd824b84
fix(mslLogin): Restart for credentials in MSL not longer necessary
[ { "change_type": "MODIFY", "old_path": "resources/lib/MSL.py", "new_path": "resources/lib/MSL.py", "diff": "@@ -46,13 +46,11 @@ class MSL:\n'license': 'http://www.netflix.com/api/msl/NFCDCH-LX/cadmium/license'\n}\n- def __init__(self, email, password, kodi_helper):\n+ def __init__(self, kodi_helper):\n\"\"\"\nThe Constructor checks for already existing crypto Keys.\nIf they exist it will load the existing keys\n\"\"\"\n- self.email = email\n- self.password = password\nself.kodi_helper = kodi_helper\ntry:\nos.mkdir(self.kodi_helper.msl_data_path)\n@@ -459,12 +457,13 @@ class MSL:\nif 'usertoken' in self.tokens:\npass\nelse:\n+ account = self.kodi_helper.get_credentials()\n# Auth via email and password\nheader_data['userauthdata'] = {\n'scheme': 'EMAIL_PASSWORD',\n'authdata': {\n- 'email': self.email,\n- 'password': self.password\n+ 'email': account['email'],\n+ 'password': account['password']\n}\n}\n" }, { "change_type": "MODIFY", "old_path": "resources/lib/MSLHttpRequestHandler.py", "new_path": "resources/lib/MSLHttpRequestHandler.py", "diff": "import BaseHTTPServer\nimport base64\nfrom urlparse import urlparse, parse_qs\n-import xbmcaddon\nfrom MSL import MSL\nfrom KodiHelper import KodiHelper\n@@ -10,8 +9,7 @@ kodi_helper = KodiHelper(\nbase_url=None\n)\n-account = kodi_helper.get_credentials()\n-msl = MSL(account['email'], account['password'], kodi_helper)\n+msl = MSL(kodi_helper)\nclass MSLHttpRequestHandler(BaseHTTPServer.BaseHTTPRequestHandler):\n@@ -51,3 +49,12 @@ class MSLHttpRequestHandler(BaseHTTPServer.BaseHTTPRequestHandler):\nself.send_header('Content-type', 'application/xml')\nself.end_headers()\nself.wfile.write(data)\n+\n+ def log_message(self, format, *args):\n+ \"\"\"\n+ Disable the BaseHTTPServer Log\n+ :param format:\n+ :param args:\n+ :return: None\n+ \"\"\"\n+ return\n" } ]
Python
MIT License
castagnait/plugin.video.netflix
fix(mslLogin): Restart for credentials in MSL not longer necessary
106,029
04.03.2017 15:18:45
-3,600
a190d8141ee4d3a09c7fef3334fd6083ff9c354e
feat(dolbySound): enable/disable dolby sound in addon settings
[ { "change_type": "MODIFY", "old_path": "resources/language/English/strings.po", "new_path": "resources/language/English/strings.po", "diff": "@@ -148,3 +148,8 @@ msgstr \"\"\nmsgctxt \"#30032\"\nmsgid \"Tracking\"\nmsgstr \"\"\n+\n+msgctxt \"#30033\"\n+msgid \"Use Dolby Sound\"\n+msgstr \"\"\n+\n" }, { "change_type": "MODIFY", "old_path": "resources/lib/KodiHelper.py", "new_path": "resources/lib/KodiHelper.py", "diff": "@@ -186,6 +186,13 @@ class KodiHelper:\n'password': self.addon.getSetting('password')\n}\n+ def get_dolby_setting(self):\n+ \"\"\"\n+ Returns if the dolby sound is enabled\n+ :return: True|False\n+ \"\"\"\n+ return self.addon.getSetting('enable_dolby_sound') == 'true'\n+\ndef get_custom_library_settings (self):\n\"\"\"Returns the settings in regards to the custom library folder(s)\n@@ -908,7 +915,7 @@ class KodiHelper:\n:return: None\n\"\"\"\n# Check if tracking is enabled\n- enable_tracking = (self.addon.getSetting('enable_logging') == 'true')\n+ enable_tracking = (self.addon.getSetting('enable_tracking') == 'true')\nif enable_tracking:\n#Get or Create Tracking id\ntracking_id = self.addon.getSetting('tracking_id')\n" }, { "change_type": "MODIFY", "old_path": "resources/lib/MSL.py", "new_path": "resources/lib/MSL.py", "diff": "@@ -147,8 +147,6 @@ class MSL:\n# Audio\n'heaac-2-dash',\n- 'ddplus-2.0-dash',\n- 'ddplus-5.1-dash',\n'dfxp-ls-sdh',\n'simplesdh',\n'nflx-cmisc',\n@@ -171,6 +169,12 @@ class MSL:\n'clientVersion': '4.0004.899.011',\n'uiVersion': 'akira'\n}\n+\n+ # Check if dolby sound is enabled and add to profles\n+ if self.kodi_helper.get_dolby_setting():\n+ manifest_request_data['profiles'].append('ddplus-2.0-dash')\n+ manifest_request_data['profiles'].append('ddplus-5.1-dash')\n+\nrequest_data = self.__generate_msl_request_data(manifest_request_data)\nresp = self.session.post(self.endpoints['manifest'], request_data)\n" }, { "change_type": "MODIFY", "old_path": "resources/settings.xml", "new_path": "resources/settings.xml", "diff": "<setting id=\"customlibraryfolder\" type=\"folder\" label=\"30027\" enable=\"eq(-1,true)\" default=\"special://profile/addon_data/plugin.video.netflix\" source=\"auto\" option=\"writeable\" subsetting=\"true\" />\n</category>\n<category label=\"30023\">\n+ <setting id=\"enable_dolby_sound\" type=\"bool\" label=\"30033\" default=\"true\"/>\n<setting id=\"ssl_verification\" type=\"bool\" label=\"30024\" default=\"true\"/>\n- <setting id=\"enable_logging\" type=\"bool\" label=\"30032\" default=\"true\"/>\n+ <setting id=\"enable_tracking\" type=\"bool\" label=\"30032\" default=\"true\"/>\n<setting id=\"\" value=\"tracking_id\" visible=\"false\"/>\n<setting id=\"msl_service_port\" value=\"8000\" visible=\"false\"/>\n<setting id=\"msl_service_certificate\" visible=\"false\" value=\"Cr0CCAMSEOVEukALwQ8307Y2+LVP+0MYh/HPkwUijgIwggEKAoIBAQDm875btoWUbGqQD8eAGuBlGY+Pxo8YF1LQR+Ex0pDONMet8EHslcZRBKNQ/09RZFTP0vrYimyYiBmk9GG+S0wB3CRITgweNE15cD33MQYyS3zpBd4z+sCJam2+jj1ZA4uijE2dxGC+gRBRnw9WoPyw7D8RuhGSJ95OEtzg3Ho+mEsxuE5xg9LM4+Zuro/9msz2bFgJUjQUVHo5j+k4qLWu4ObugFmc9DLIAohL58UR5k0XnvizulOHbMMxdzna9lwTw/4SALadEV/CZXBmswUtBgATDKNqjXwokohncpdsWSauH6vfS6FXwizQoZJ9TdjSGC60rUB2t+aYDm74cIuxAgMBAAE6EHRlc3QubmV0ZmxpeC5jb20SgAOE0y8yWw2Win6M2/bw7+aqVuQPwzS/YG5ySYvwCGQd0Dltr3hpik98WijUODUr6PxMn1ZYXOLo3eED6xYGM7Riza8XskRdCfF8xjj7L7/THPbixyn4mULsttSmWFhexzXnSeKqQHuoKmerqu0nu39iW3pcxDV/K7E6aaSr5ID0SCi7KRcL9BCUCz1g9c43sNj46BhMCWJSm0mx1XFDcoKZWhpj5FAgU4Q4e6f+S8eX39nf6D6SJRb4ap7Znzn7preIvmS93xWjm75I6UBVQGo6pn4qWNCgLYlGGCQCUm5tg566j+/g5jvYZkTJvbiZFwtjMW5njbSRwB3W4CrKoyxw4qsJNSaZRTKAvSjTKdqVDXV/U5HK7SaBA6iJ981/aforXbd2vZlRXO/2S+Maa2mHULzsD+S5l4/YGpSt7PnkCe25F+nAovtl/ogZgjMeEdFyd/9YMYjOS4krYmwp3yJ7m9ZzYCQ6I8RQN4x/yLlHG5RH/+WNLNUs6JAZ0fFdCmw=\"/>\n" } ]
Python
MIT License
castagnait/plugin.video.netflix
feat(dolbySound): enable/disable dolby sound in addon settings
105,979
04.03.2017 20:26:20
-3,600
9b6a47ca23d1db0a7425edaaa04dae09ae33ec13
fix(parser): Fix copy & paste error
[ { "change_type": "MODIFY", "old_path": "resources/lib/NetflixSession.py", "new_path": "resources/lib/NetflixSession.py", "diff": "@@ -433,7 +433,7 @@ class NetflixSession:\nreturn False;\n# collect all the login fields & their contents and add the user credentials\n- page_soup = BeautifulSoup(response.text)\n+ page_soup = BeautifulSoup(response.text, 'html.parser')\nlogin_form = page_soup.find(attrs={'class' : 'ui-label-text'}).findPrevious('form')\nlogin_payload = self.parse_login_form_fields(form_soup=login_form)\nif 'email' in login_payload:\n@@ -488,7 +488,7 @@ class NetflixSession:\n# fetch the index page again, so that we can fetch the corresponding user data\nbrowse_response = self.session.get(self._get_document_url_for(component='browse'), verify=self.verify_ssl)\nonly_script_tags = SoupStrainer('script')\n- browse_soup = BeautifulSoup(response.text, 'html.parser', parse_only=only_script_tags)\n+ browse_soup = BeautifulSoup(browse_response.text, 'html.parser', parse_only=only_script_tags)\nself._parse_page_contents(page_soup=browse_soup)\naccount_hash = self._generate_account_hash(account=account)\nself._save_data(filename=self.data_path + '_' + account_hash)\n" } ]
Python
MIT License
castagnait/plugin.video.netflix
fix(parser): Fix copy & paste error
105,979
04.03.2017 21:12:19
-3,600
08aa1fe9088e94596cbd40055bf63457a7617db8
fix(user-handling): Fixes user profile switching
[ { "change_type": "MODIFY", "old_path": "addon.xml", "new_path": "addon.xml", "diff": "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>\n-<addon id=\"plugin.video.netflix\" name=\"Netflix\" version=\"0.9.6\" provider-name=\"libdev + jojo + asciidisco\">\n+<addon id=\"plugin.video.netflix\" name=\"Netflix\" version=\"0.9.7\" provider-name=\"libdev + jojo + asciidisco\">\n<requires>\n<import addon=\"xbmc.python\" version=\"2.24.0\"/>\n<import addon=\"script.module.beautifulsoup4\" version=\"4.3.2\"/>\n" }, { "change_type": "MODIFY", "old_path": "resources/language/English/strings.po", "new_path": "resources/language/English/strings.po", "diff": "# Kodi Media Center language file\n# Addon Name: Netflix\n# Addon id: plugin.video.netflix\n-# Addon version: 0.9.6\n-# Addon Provider: tba.\n+# Addon version: 0.9.7\n+# Addon Provider: libdev + jojo + asciidisco\nmsgid \"\"\nmsgstr \"\"\n\"Project-Id-Version: XBMC-Addons\\n\"\n" }, { "change_type": "MODIFY", "old_path": "resources/language/German/strings.po", "new_path": "resources/language/German/strings.po", "diff": "# Kodi Media Center language file\n# Addon Name: Netflix\n# Addon id: plugin.video.netflix\n-# Addon version: 0.9.6\n-# Addon Provider: tba.\n+# Addon version: 0.9.7\n+# Addon Provider: libdev + jojo + asciidisco\nmsgid \"\"\nmsgstr \"\"\n\"Project-Id-Version: XBMC-Addons\\n\"\n" }, { "change_type": "MODIFY", "old_path": "resources/lib/KodiHelper.py", "new_path": "resources/lib/KodiHelper.py", "diff": "@@ -44,12 +44,11 @@ class KodiHelper:\nself.msl_data_path = xbmc.translatePath('special://profile/addon_data/service.msl').decode('utf-8') + '/'\nself.verb_log = self.addon.getSetting('logging') == 'true'\nself.default_fanart = self.addon.getAddonInfo('fanart')\n- self.win = xbmcgui.Window(xbmcgui.getCurrentWindowId())\nself.library = None\nself.setup_memcache()\ndef refresh (self):\n- \"\"\"Refrsh the current list\"\"\"\n+ \"\"\"Refresh the current list\"\"\"\nreturn xbmc.executebuiltin('Container.Refresh')\ndef show_rating_dialog (self):\n@@ -224,7 +223,7 @@ class KodiHelper:\ntype : :obj:`str`\nSelected menu item\n\"\"\"\n- self.win.setProperty('main_menu_selection', type)\n+ xbmcgui.Window(xbmcgui.getCurrentWindowId()).setProperty('main_menu_selection', type)\ndef get_main_menu_selection (self):\n\"\"\"Gets the persisted chosen main menu entry from memory\n@@ -234,18 +233,18 @@ class KodiHelper:\n:obj:`str`\nThe last chosen main menu entry\n\"\"\"\n- return self.win.getProperty('main_menu_selection')\n+ return xbmcgui.Window(xbmcgui.getCurrentWindowId()).getProperty('main_menu_selection')\ndef setup_memcache (self):\n\"\"\"Sets up the memory cache if not existant\"\"\"\n- cached_items = self.win.getProperty('memcache')\n+ cached_items = xbmcgui.Window(xbmcgui.getCurrentWindowId()).getProperty('memcache')\n# no cache setup yet, create one\nif len(cached_items) < 1:\n- self.win.setProperty('memcache', pickle.dumps({}))\n+ xbmcgui.Window(xbmcgui.getCurrentWindowId()).setProperty('memcache', pickle.dumps({}))\ndef invalidate_memcache (self):\n\"\"\"Invalidates the memory cache\"\"\"\n- self.win.setProperty('memcache', pickle.dumps({}))\n+ xbmcgui.Window(xbmcgui.getCurrentWindowId()).setProperty('memcache', pickle.dumps({}))\ndef has_cached_item (self, cache_id):\n\"\"\"Checks if the requested item is in memory cache\n@@ -260,7 +259,7 @@ class KodiHelper:\nbool\nItem is cached\n\"\"\"\n- cached_items = pickle.loads(self.win.getProperty('memcache'))\n+ cached_items = pickle.loads(xbmcgui.Window(xbmcgui.getCurrentWindowId()).getProperty('memcache'))\nreturn cache_id in cached_items.keys()\ndef get_cached_item (self, cache_id):\n@@ -276,7 +275,7 @@ class KodiHelper:\nmixed\nContents of the requested cache item or none\n\"\"\"\n- cached_items = pickle.loads(self.win.getProperty('memcache'))\n+ cached_items = pickle.loads(xbmcgui.Window(xbmcgui.getCurrentWindowId()).getProperty('memcache'))\nif self.has_cached_item(cache_id) != True:\nreturn None\nreturn cached_items[cache_id]\n@@ -292,9 +291,9 @@ class KodiHelper:\ncontents : mixed\nCache entry contents\n\"\"\"\n- cached_items = pickle.loads(self.win.getProperty('memcache'))\n+ cached_items = pickle.loads(xbmcgui.Window(xbmcgui.getCurrentWindowId()).getProperty('memcache'))\ncached_items.update({cache_id: contents})\n- self.win.setProperty('memcache', pickle.dumps(cached_items))\n+ xbmcgui.Window(xbmcgui.getCurrentWindowId()).setProperty('memcache', pickle.dumps(cached_items))\ndef build_profiles_listing (self, profiles, action, build_url):\n\"\"\"Builds the profiles list Kodi screen\n@@ -404,7 +403,7 @@ class KodiHelper:\npreselected_list_item = idx if item else None\npreselected_list_item = idx + 1 if self.get_main_menu_selection() == 'search' else preselected_list_item\nif preselected_list_item != None:\n- xbmc.executebuiltin('ActivateWindowAndFocus(%s, %s)' % (str(self.win.getFocusId()), str(preselected_list_item)))\n+ xbmc.executebuiltin('ActivateWindowAndFocus(%s, %s)' % (str(xbmcgui.Window(xbmcgui.getCurrentWindowId()).getFocusId()), str(preselected_list_item)))\nreturn True\ndef build_video_listing (self, video_list, actions, type, build_url):\n" }, { "change_type": "MODIFY", "old_path": "resources/lib/NetflixSession.py", "new_path": "resources/lib/NetflixSession.py", "diff": "@@ -491,6 +491,7 @@ class NetflixSession:\nbrowse_soup = BeautifulSoup(browse_response.text, 'html.parser', parse_only=only_script_tags)\nself._parse_page_contents(page_soup=browse_soup)\naccount_hash = self._generate_account_hash(account=account)\n+ self.user_data['guid'] = profile_id;\nself._save_data(filename=self.data_path + '_' + account_hash)\nreturn True\n" } ]
Python
MIT License
castagnait/plugin.video.netflix
fix(user-handling): Fixes user profile switching
105,979
06.03.2017 14:08:19
-3,600
d452ed43938b00e420ebe32091597102aad5be22
feat(esn): Adds ESN setting
[ { "change_type": "MODIFY", "old_path": "addon.xml", "new_path": "addon.xml", "diff": "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>\n-<addon id=\"plugin.video.netflix\" name=\"Netflix\" version=\"0.9.8\" provider-name=\"libdev + jojo + asciidisco\">\n+<addon id=\"plugin.video.netflix\" name=\"Netflix\" version=\"0.9.9\" provider-name=\"libdev + jojo + asciidisco\">\n<requires>\n<import addon=\"xbmc.python\" version=\"2.24.0\"/>\n<import addon=\"script.module.beautifulsoup4\" version=\"4.3.2\"/>\n" }, { "change_type": "MODIFY", "old_path": "resources/language/English/strings.po", "new_path": "resources/language/English/strings.po", "diff": "# Kodi Media Center language file\n# Addon Name: Netflix\n# Addon id: plugin.video.netflix\n-# Addon version: 0.9.8\n+# Addon version: 0.9.9\n# Addon Provider: libdev + jojo + asciidisco\nmsgid \"\"\nmsgstr \"\"\n@@ -152,3 +152,7 @@ msgstr \"\"\nmsgctxt \"#30033\"\nmsgid \"Use Dolby Sound\"\nmsgstr \"\"\n+\n+msgctxt \"#30034\"\n+msgid \"ESN (set automatically, can be changed manually)\"\n+msgstr \"\"\n" }, { "change_type": "MODIFY", "old_path": "resources/lib/KodiHelper.py", "new_path": "resources/lib/KodiHelper.py", "diff": "@@ -649,6 +649,11 @@ class KodiHelper:\n# track play event\nself.track_event('playVideo')\n+ # check esn in settings\n+ settings_esn = str(self.addon.getSetting('esn'))\n+ if len(settings_esn) == 0:\n+ self.addon.setSetting('esn', str(esn))\n+\n# inputstream addon properties\nmsl_service_url = 'http://localhost:' + str(self.addon.getSetting('msl_service_port'))\nplay_item = xbmcgui.ListItem(path=msl_service_url + '/manifest?id=' + video_id)\n@@ -656,8 +661,6 @@ class KodiHelper:\nplay_item.setProperty(inputstream_addon + '.manifest_type', 'mpd')\nplay_item.setProperty(inputstream_addon + '.license_key', msl_service_url + '/license?id=' + video_id + '||b{SSM}!b{SID}|')\nplay_item.setProperty(inputstream_addon + '.server_certificate', 'Cr0CCAMSEOVEukALwQ8307Y2+LVP+0MYh/HPkwUijgIwggEKAoIBAQDm875btoWUbGqQD8eAGuBlGY+Pxo8YF1LQR+Ex0pDONMet8EHslcZRBKNQ/09RZFTP0vrYimyYiBmk9GG+S0wB3CRITgweNE15cD33MQYyS3zpBd4z+sCJam2+jj1ZA4uijE2dxGC+gRBRnw9WoPyw7D8RuhGSJ95OEtzg3Ho+mEsxuE5xg9LM4+Zuro/9msz2bFgJUjQUVHo5j+k4qLWu4ObugFmc9DLIAohL58UR5k0XnvizulOHbMMxdzna9lwTw/4SALadEV/CZXBmswUtBgATDKNqjXwokohncpdsWSauH6vfS6FXwizQoZJ9TdjSGC60rUB2t+aYDm74cIuxAgMBAAE6EHRlc3QubmV0ZmxpeC5jb20SgAOE0y8yWw2Win6M2/bw7+aqVuQPwzS/YG5ySYvwCGQd0Dltr3hpik98WijUODUr6PxMn1ZYXOLo3eED6xYGM7Riza8XskRdCfF8xjj7L7/THPbixyn4mULsttSmWFhexzXnSeKqQHuoKmerqu0nu39iW3pcxDV/K7E6aaSr5ID0SCi7KRcL9BCUCz1g9c43sNj46BhMCWJSm0mx1XFDcoKZWhpj5FAgU4Q4e6f+S8eX39nf6D6SJRb4ap7Znzn7preIvmS93xWjm75I6UBVQGo6pn4qWNCgLYlGGCQCUm5tg566j+/g5jvYZkTJvbiZFwtjMW5njbSRwB3W4CrKoyxw4qsJNSaZRTKAvSjTKdqVDXV/U5HK7SaBA6iJ981/aforXbd2vZlRXO/2S+Maa2mHULzsD+S5l4/YGpSt7PnkCe25F+nAovtl/ogZgjMeEdFyd/9YMYjOS4krYmwp3yJ7m9ZzYCQ6I8RQN4x/yLlHG5RH/+WNLNUs6JAZ0fFdCmw=')\n- # TODO: Change when Kodi can handle/trnsfer defaults in hidden values in settings\n- #play_item.setProperty(inputstream_addon + '.server_certificate', self.addon.getSetting('msl_service_certificate'))\nplay_item.setProperty('inputstreamaddon', inputstream_addon)\n# check if we have a bookmark e.g. start offset position\n" }, { "change_type": "MODIFY", "old_path": "resources/settings.xml", "new_path": "resources/settings.xml", "diff": "<setting id=\"enable_dolby_sound\" type=\"bool\" label=\"30033\" default=\"true\"/>\n<setting id=\"ssl_verification\" type=\"bool\" label=\"30024\" default=\"true\"/>\n<setting id=\"enable_tracking\" type=\"bool\" label=\"30032\" default=\"true\"/>\n- <setting id=\"\" value=\"tracking_id\" visible=\"false\"/>\n+ <setting id=\"esn\" type=\"text\" label=\"30034\" value=\"\" default=\"\"/>\n+ <setting id=\"tracking_id\" value=\"\" visible=\"false\"/>\n<setting id=\"msl_service_port\" value=\"8000\" visible=\"false\"/>\n</category>\n</settings>\n" } ]
Python
MIT License
castagnait/plugin.video.netflix
feat(esn): Adds ESN setting
106,029
06.03.2017 16:01:53
-3,600
4ec9b5afd40ef050c550ae2e6c97ca153314b6be
chore(performance): Rearragenes imports to speed up addon start
[ { "change_type": "MODIFY", "old_path": "addon.py", "new_path": "addon.py", "diff": "# Created on: 13.01.2017\n# import local classes\n-if __package__ is None:\n+\nimport sys\n- import os\n- sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))\nfrom resources.lib.NetflixSession import NetflixSession\nfrom resources.lib.KodiHelper import KodiHelper\nfrom resources.lib.Navigation import Navigation\nfrom resources.lib.Library import Library\n-else:\n- from .resources.lib.NetflixSession import NetflixSession\n- from .resources.lib.KodiHelper import KodiHelper\n- from .resources.lib.Navigation import Navigation\n- from .resources.lib.Library import Library\n# Setup plugin\nplugin_handle = int(sys.argv[1])\n" } ]
Python
MIT License
castagnait/plugin.video.netflix
chore(performance): Rearragenes imports to speed up addon start
105,979
06.03.2017 17:13:04
-3,600
86455dfff7e4878e5192dd97991f2e96a3021739
chore(performance): Further speed up of imports
[ { "change_type": "MODIFY", "old_path": "addon.py", "new_path": "addon.py", "diff": "# Module: default\n# Created on: 13.01.2017\n-# import local classes\n-\nimport sys\nfrom resources.lib.NetflixSession import NetflixSession\nfrom resources.lib.KodiHelper import KodiHelper\n" }, { "change_type": "MODIFY", "old_path": "addon.xml", "new_path": "addon.xml", "diff": "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>\n-<addon id=\"plugin.video.netflix\" name=\"Netflix\" version=\"0.9.10\" provider-name=\"libdev + jojo + asciidisco\">\n+<addon id=\"plugin.video.netflix\" name=\"Netflix\" version=\"0.9.11\" provider-name=\"libdev + jojo + asciidisco\">\n<requires>\n<import addon=\"xbmc.python\" version=\"2.24.0\"/>\n<import addon=\"script.module.beautifulsoup4\" version=\"4.3.2\"/>\n<import addon=\"script.module.requests\" version=\"2.12.4\"/>\n<import addon=\"script.module.pycryptodome\" version=\"3.4.3\"/>\n- <import addon=\"script.module.simplejson\" version=\"3.3.0\"/>\n</requires>\n<extension point=\"xbmc.python.pluginsource\" library=\"addon.py\">\n<provides>video</provides>\n" }, { "change_type": "MODIFY", "old_path": "resources/language/English/strings.po", "new_path": "resources/language/English/strings.po", "diff": "# Kodi Media Center language file\n# Addon Name: Netflix\n# Addon id: plugin.video.netflix\n-# Addon version: 0.9.10\n+# Addon version: 0.9.11\n# Addon Provider: libdev + jojo + asciidisco\nmsgid \"\"\nmsgstr \"\"\n" }, { "change_type": "MODIFY", "old_path": "resources/language/German/strings.po", "new_path": "resources/language/German/strings.po", "diff": "# Kodi Media Center language file\n# Addon Name: Netflix\n# Addon id: plugin.video.netflix\n-# Addon version: 0.9.10\n+# Addon version: 0.9.11\n# Addon Provider: libdev + jojo + asciidisco\nmsgid \"\"\nmsgstr \"\"\n" }, { "change_type": "MODIFY", "old_path": "resources/lib/KodiHelper.py", "new_path": "resources/lib/KodiHelper.py", "diff": "# Module: KodiHelper\n# Created on: 13.01.2017\n-import os\n-import urllib\nimport xbmcplugin\nimport xbmcgui\n-import xbmcaddon\nimport xbmc\nimport json\n-import uuid\n+from os.path import join\n+from urllib import urlencode\n+from xbmcaddon import Addon\n+from uuid import uuid4\nfrom UniversalAnalytics import Tracker\ntry:\nimport cPickle as pickle\n@@ -33,14 +33,14 @@ class KodiHelper:\n\"\"\"\nself.plugin_handle = plugin_handle\nself.base_url = base_url\n- self.addon = xbmcaddon.Addon()\n+ self.addon = Addon()\nself.plugin = self.addon.getAddonInfo('name')\nself.base_data_path = xbmc.translatePath(self.addon.getAddonInfo('profile'))\nself.home_path = xbmc.translatePath('special://home')\nself.plugin_path = self.addon.getAddonInfo('path')\nself.cookie_path = self.base_data_path + 'COOKIE'\nself.data_path = self.base_data_path + 'DATA'\n- self.config_path = os.path.join(self.base_data_path, 'config')\n+ self.config_path = join(self.base_data_path, 'config')\nself.msl_data_path = xbmc.translatePath('special://profile/addon_data/service.msl').decode('utf-8') + '/'\nself.verb_log = self.addon.getSetting('logging') == 'true'\nself.default_fanart = self.addon.getAddonInfo('fanart')\n@@ -801,7 +801,7 @@ class KodiHelper:\nentry_keys = entry.keys()\n# action item templates\n- encoded_title = urllib.urlencode({'title': entry['title'].encode('utf-8')}) if 'title' in entry else ''\n+ encoded_title = urlencode({'title': entry['title'].encode('utf-8')}) if 'title' in entry else ''\nurl_tmpl = 'XBMC.RunPlugin(' + self.base_url + '?action=%action%&id=' + str(entry['id']) + '&' + encoded_title + ')'\nactions = [\n['export_to_library', self.get_local_string(30018), 'export'],\n@@ -922,7 +922,7 @@ class KodiHelper:\n#Get or Create Tracking id\ntracking_id = self.addon.getSetting('tracking_id')\nif tracking_id is '':\n- tracking_id = str(uuid.uuid4())\n+ tracking_id = str(uuid4())\nself.addon.setSetting('tracking_id', tracking_id)\n# Send the tracking event\ntracker = Tracker.create('UA-46081640-5', client_id=tracking_id)\n" }, { "change_type": "MODIFY", "old_path": "resources/lib/Library.py", "new_path": "resources/lib/Library.py", "diff": "# Created on: 13.01.2017\nimport os\n-import shutil\n+from shutil import rmtree\n+from utils import noop\ntry:\nimport cPickle as pickle\nexcept:\nimport pickle\n-from utils import noop\nclass Library:\n\"\"\"Exports Netflix shows & movies to a local library folder\"\"\"\n@@ -348,7 +348,7 @@ class Library:\nself._update_local_db(filename=self.db_filepath, db=self.db)\ndirname = os.path.join(self.movie_path, folder)\nif os.path.exists(dirname):\n- shutil.rmtree(dirname)\n+ rmtree(dirname)\nreturn True\nreturn False\n@@ -370,7 +370,7 @@ class Library:\nself._update_local_db(filename=self.db_filepath, db=self.db)\nshow_dir = os.path.join(self.tvshow_path, folder)\nif os.path.exists(show_dir):\n- shutil.rmtree(show_dir)\n+ rmtree(show_dir)\nreturn True\nreturn False\n" }, { "change_type": "MODIFY", "old_path": "resources/lib/Navigation.py", "new_path": "resources/lib/Navigation.py", "diff": "# Module: Navigation\n# Created on: 13.01.2017\n-import urllib\n-import time\n+from urllib import urlencode, unquote\nfrom urlparse import parse_qsl\n-from utils import noop\n-from utils import log\n+from utils import noop, log\nclass Navigation:\n\"\"\"Routes to the correct subfolder, dispatches actions & acts as a controller for the Kodi view & the Netflix model\"\"\"\n@@ -95,7 +93,7 @@ class Navigation:\nreturn self.add_to_list(video_id=params['id'])\nelif params['action'] == 'export':\n# adds a title to the users list on Netflix\n- alt_title = self.kodi_helper.show_add_to_library_title_dialog(original_title=urllib.unquote(params['title']).decode('utf8'))\n+ alt_title = self.kodi_helper.show_add_to_library_title_dialog(original_title=unquote(params['title']).decode('utf8'))\nreturn self.export_to_library(video_id=params['id'], alt_title=alt_title)\nelif params['action'] == 'remove':\n# adds a title to the users list on Netflix\n@@ -543,4 +541,4 @@ class Navigation:\nstr\nUrl + querystring based on the param\n\"\"\"\n- return self.base_url + '?' + urllib.urlencode(query)\n+ return self.base_url + '?' + urlencode(query)\n" }, { "change_type": "MODIFY", "old_path": "resources/lib/NetflixSession.py", "new_path": "resources/lib/NetflixSession.py", "diff": "# Created on: 13.01.2017\nimport os\n-import base64\n-import time\n-import urllib\nimport json\n-import requests\n+from requests import session, cookies\n+from urllib import quote\n+from time import time\n+from base64 import urlsafe_b64encode\n+from bs4 import BeautifulSoup, SoupStrainer\n+from utils import noop\ntry:\nimport cPickle as pickle\nexcept:\nimport pickle\n-from bs4 import BeautifulSoup, SoupStrainer\n-from utils import noop\nclass NetflixSession:\n\"\"\"Helps with login/session management of Netflix users & API data fetching\"\"\"\n@@ -100,7 +100,7 @@ class NetflixSession:\nself.log = log_fn\n# start session, fake chrome on the current platform (so that we get a proper widevine esn) & enable gzip\n- self.session = requests.session()\n+ self.session = session()\nself.session.headers.update({\n'User-Agent': self._get_user_agent_for_current_platform(),\n'Accept-Encoding': 'gzip'\n@@ -272,7 +272,7 @@ class NetflixSession:\n\"\"\"\npayload = {\n'switchProfileGuid': profile_id,\n- '_': int(time.time()),\n+ '_': int(time()),\n'authURL': self.user_data['authURL']\n}\n@@ -1295,7 +1295,7 @@ class NetflixSession:\n'toRow': list_to,\n'opaqueImageExtension': 'jpg',\n'transparentImageExtension': 'png',\n- '_': int(time.time()),\n+ '_': int(time()),\n'authURL': self.user_data['authURL']\n}\nresponse = self._session_get(component='video_list_ids', params=payload, type='api')\n@@ -1321,7 +1321,7 @@ class NetflixSession:\nRaw Netflix API call response or api call error\n\"\"\"\n# properly encode the search string\n- encoded_search_string = urllib.quote(search_str)\n+ encoded_search_string = quote(search_str)\npaths = [\n['search', encoded_search_string, 'titles', {'from': list_from, 'to': list_to}, ['summary', 'title']],\n@@ -1424,7 +1424,7 @@ class NetflixSession:\npayload = {\n'movieid': id,\n'imageformat': 'jpg',\n- '_': int(time.time())\n+ '_': int(time())\n}\nresponse = self._session_get(component='metadata', params=payload, type='api')\nreturn self._process_response(response=response, component=self._get_api_url_for(component='metadata'))\n@@ -1813,10 +1813,10 @@ class NetflixSession:\nreturn False\nwith open(filename) as f:\n- cookies = pickle.load(f)\n- if cookies:\n- jar = requests.cookies.RequestsCookieJar()\n- jar._cookies = cookies\n+ _cookies = pickle.load(f)\n+ if _cookies:\n+ jar = cookies.RequestsCookieJar()\n+ jar._cookies = _cookies\nself.session.cookies = jar\nelse:\nreturn False\n@@ -1849,7 +1849,7 @@ class NetflixSession:\n:obj:`str`\nAccount data hash\n\"\"\"\n- return base64.urlsafe_b64encode(account['email'])\n+ return urlsafe_b64encode(account['email'])\ndef _get_user_agent_for_current_platform (self):\n\"\"\"Determines the user agent string for the current platform (to retrieve a valid ESN)\n@@ -1895,9 +1895,9 @@ class NetflixSession:\nContents of the field to match\n\"\"\"\nurl = self._get_document_url_for(component=component) if type == 'document' else self._get_api_url_for(component=component)\n- start = time.time()\n+ start = time()\nresponse = self.session.post(url=url, data=data, params=params, headers=headers, verify=self.verify_ssl)\n- end = time.time()\n+ end = time()\nself.log('[POST] Request for \"' + url + '\" took ' + str(end - start) + ' seconds')\nreturn response\n@@ -1921,9 +1921,9 @@ class NetflixSession:\nContents of the field to match\n\"\"\"\nurl = self._get_document_url_for(component=component) if type == 'document' else self._get_api_url_for(component=component)\n- start = time.time()\n+ start = time()\nresponse = self.session.get(url=url, verify=self.verify_ssl, params=params)\n- end = time.time()\n+ end = time()\nself.log('[GET] Request for \"' + url + '\" took ' + str(end - start) + ' seconds')\nreturn response\n" }, { "change_type": "MODIFY", "old_path": "service.py", "new_path": "service.py", "diff": "@@ -12,7 +12,6 @@ kodi_helper = KodiHelper(\nbase_url=None\n)\n-\ndef select_unused_port():\nsock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\nsock.bind(('localhost', 0))\n" } ]
Python
MIT License
castagnait/plugin.video.netflix
chore(performance): Further speed up of imports
105,979
07.03.2017 18:40:52
-3,600
69bafa3b4cb738c563f3cc8f7affe7b4fa8e91ea
chore(performance): Removes NetflixSession from the core addon & adds a HTTP proxy service for the Netflix data
[ { "change_type": "MODIFY", "old_path": "addon.py", "new_path": "addon.py", "diff": "# Created on: 13.01.2017\nimport sys\n-from resources.lib.NetflixSession import NetflixSession\nfrom resources.lib.KodiHelper import KodiHelper\nfrom resources.lib.Navigation import Navigation\nfrom resources.lib.Library import Library\n@@ -18,19 +17,12 @@ kodi_helper = KodiHelper(\nplugin_handle=plugin_handle,\nbase_url=base_url\n)\n-netflix_session = NetflixSession(\n- cookie_path=kodi_helper.cookie_path,\n- data_path=kodi_helper.data_path,\n- verify_ssl=kodi_helper.get_ssl_verification_setting(),\n- log_fn=kodi_helper.log\n-)\nlibrary = Library(\nroot_folder=kodi_helper.base_data_path,\nlibrary_settings=kodi_helper.get_custom_library_settings(),\nlog_fn=kodi_helper.log\n)\nnavigation = Navigation(\n- netflix_session=netflix_session,\nkodi_helper=kodi_helper,\nlibrary=library,\nbase_url=base_url,\n" }, { "change_type": "MODIFY", "old_path": "addon.xml", "new_path": "addon.xml", "diff": "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>\n-<addon id=\"plugin.video.netflix\" name=\"Netflix\" version=\"0.9.11\" provider-name=\"libdev + jojo + asciidisco\">\n+<addon id=\"plugin.video.netflix\" name=\"Netflix\" version=\"0.10.1\" provider-name=\"libdev + jojo + asciidisco\">\n<requires>\n<import addon=\"xbmc.python\" version=\"2.24.0\"/>\n<import addon=\"script.module.beautifulsoup4\" version=\"4.3.2\"/>\n" }, { "change_type": "MODIFY", "old_path": "resources/language/English/strings.po", "new_path": "resources/language/English/strings.po", "diff": "# Kodi Media Center language file\n# Addon Name: Netflix\n# Addon id: plugin.video.netflix\n-# Addon version: 0.9.11\n+# Addon version: 0.10.1\n# Addon Provider: libdev + jojo + asciidisco\nmsgid \"\"\nmsgstr \"\"\n" }, { "change_type": "MODIFY", "old_path": "resources/language/German/strings.po", "new_path": "resources/language/German/strings.po", "diff": "# Kodi Media Center language file\n# Addon Name: Netflix\n# Addon id: plugin.video.netflix\n-# Addon version: 0.9.11\n+# Addon version: 0.10.1\n# Addon Provider: libdev + jojo + asciidisco\nmsgid \"\"\nmsgstr \"\"\n" }, { "change_type": "MODIFY", "old_path": "resources/lib/KodiHelper.py", "new_path": "resources/lib/KodiHelper.py", "diff": "@@ -20,7 +20,7 @@ except:\nclass KodiHelper:\n\"\"\"Consumes all the configuration data from Kodi as well as turns data into lists of folders and videos\"\"\"\n- def __init__ (self, plugin_handle, base_url):\n+ def __init__ (self, plugin_handle=None, base_url=None):\n\"\"\"Fetches all needed info from Kodi & configures the baseline of the plugin\nParameters\n" }, { "change_type": "ADD", "old_path": null, "new_path": "resources/lib/NetflixHttpRequestHandler.py", "diff": "+import BaseHTTPServer\n+import json\n+from types import FunctionType\n+from urlparse import urlparse, parse_qs\n+from resources.lib.KodiHelper import KodiHelper\n+from resources.lib.NetflixSession import NetflixSession\n+from resources.lib.NetflixHttpSubRessourceHandler import NetflixHttpSubRessourceHandler\n+\n+kodi_helper = KodiHelper()\n+\n+netflix_session = NetflixSession(\n+ cookie_path=kodi_helper.cookie_path,\n+ data_path=kodi_helper.data_path,\n+ verify_ssl=kodi_helper.get_ssl_verification_setting(),\n+ log_fn=kodi_helper.log\n+)\n+\n+# get list of methods & instance form the sub ressource handler\n+methods = [x for x, y in NetflixHttpSubRessourceHandler.__dict__.items() if type(y) == FunctionType]\n+sub_res_handler = NetflixHttpSubRessourceHandler(kodi_helper=kodi_helper, netflix_session=netflix_session)\n+\n+class NetflixHttpRequestHandler(BaseHTTPServer.BaseHTTPRequestHandler):\n+\n+ def do_GET(self):\n+ url = urlparse(self.path)\n+ params = parse_qs(url.query)\n+ method = params.get('method', [None])[0]\n+\n+ # not method given\n+ if method == None:\n+ self.send_error(500, 'No method declared')\n+ return\n+\n+ # no existing method given\n+ if method not in methods:\n+ self.send_error(404, 'Method \"' + str(method) + '\" not found. Available methods: ' + str(methods))\n+ return\n+\n+ # call method & get the result\n+ result = getattr(sub_res_handler, method)(params)\n+ self.send_response(200)\n+ self.send_header('Content-type', 'application/json')\n+ self.end_headers()\n+ self.wfile.write(json.dumps({'method': method, 'result': result}));\n+ return\n+\n+ def log_message(self, format, *args):\n+ \"\"\"Disable the BaseHTTPServer Log\"\"\"\n+ return\n" }, { "change_type": "ADD", "old_path": null, "new_path": "resources/lib/NetflixHttpSubRessourceHandler.py", "diff": "+class NetflixHttpSubRessourceHandler:\n+\n+ def __init__ (self, kodi_helper, netflix_session):\n+ self.kodi_helper = kodi_helper\n+ self.netflix_session = netflix_session\n+ credentials = self.kodi_helper.get_credentials()\n+\n+ if self.netflix_session.is_logged_in(account=credentials):\n+ self.netflix_session.refresh_session_data(account=credentials)\n+ else:\n+ self.netflix_session.login(account=credentials)\n+ self.profiles = self.netflix_session.profiles\n+\n+ def is_logged_in (self, params):\n+ credentials = self.kodi_helper.get_credentials()\n+ return self.netflix_session.is_logged_in(account=credentials)\n+\n+ def logout (self, params):\n+ return self.netflix_session.logout()\n+\n+ def list_profiles (self, params):\n+ return self.profiles\n+\n+ def get_esn (self, params):\n+ return self.netflix_session.esn\n+\n+ def fetch_video_list_ids (self, params):\n+ video_list_ids_raw = self.netflix_session.fetch_video_list_ids()\n+ if 'error' in video_list_ids_raw:\n+ return video_list_ids_raw\n+ return self.netflix_session.parse_video_list_ids(response_data=video_list_ids_raw)\n+\n+ def fetch_video_list (self, params):\n+ list_id = params.get('list_id', [''])[0]\n+ raw_video_list = self.netflix_session.fetch_video_list(list_id=list_id)\n+ if 'error' in raw_video_list:\n+ return raw_video_list\n+ # parse the video list ids\n+ if 'videos' in raw_video_list.get('value', {}).keys():\n+ return self.netflix_session.parse_video_list(response_data=raw_video_list)\n+ return []\n+\n+ def fetch_episodes_by_season (self, params):\n+ raw_episode_list = self.netflix_session.fetch_episodes_by_season(season_id=params.get('season_id')[0])\n+ if 'error' in raw_episode_list:\n+ return raw_episode_list\n+ return self.netflix_session.parse_episodes_by_season(response_data=raw_episode_list)\n+\n+ def fetch_seasons_for_show (self, params):\n+ show_id = params.get('show_id', [''])[0]\n+ raw_season_list = self.netflix_session.fetch_seasons_for_show(id=show_id)\n+ if 'error' in raw_season_list:\n+ return raw_season_list\n+ # check if we have sesons, announced shows that are not available yet have none\n+ if 'seasons' not in raw_season_list.get('value', {}):\n+ return []\n+ return self.netflix_session.parse_seasons(id=show_id, response_data=raw_season_list)\n+\n+ def rate_video (self, params):\n+ video_id = params.get('video_id', [''])[0]\n+ rating = params.get('rating', [''])[0]\n+ return self.netflix_session.rate_video(video_id=video_id, rating=rating)\n+\n+ def remove_from_list (self, params):\n+ video_id = params.get('video_id', [''])[0]\n+ return self.netflix_session.remove_from_list(video_id=video_id)\n+\n+ def add_to_list (self, params):\n+ video_id = params.get('video_id', [''])[0]\n+ return self.netflix_session.add_to_list(video_id=video_id)\n+\n+ def fetch_metadata (self, params):\n+ video_id = params.get('video_id', [''])[0]\n+ return self.netflix_session.fetch_metadata(id=video_id)\n+\n+ def switch_profile (self, params):\n+ credentials = self.kodi_helper.get_credentials()\n+ profile_id = params.get('profile_id', [''])[0]\n+ return self.netflix_session.switch_profile(profile_id=profile_id, account=credentials)\n+\n+ def get_user_data (self, params):\n+ return self.netflix_session.user_data\n+\n+ def search (self, params):\n+ term = params.get('term', [''])[0]\n+ has_search_results = False\n+ raw_search_results = self.netflix_session.fetch_search_results(search_str=term)\n+ # check for any errors\n+ if 'error' in raw_search_results:\n+ return raw_search_results\n+\n+ # determine if we found something\n+ if 'search' in raw_search_results['value']:\n+ for key in raw_search_results['value']['search'].keys():\n+ if self.netflix_session._is_size_key(key=key) == False:\n+ has_search_results = raw_search_results['value']['search'][key]['titles']['length'] > 0\n+ if has_search_results == False:\n+ if raw_search_results['value']['search'][key].get('suggestions', False) != False:\n+ for entry in raw_search_results['value']['search'][key]['suggestions']:\n+ if self.netflix_session._is_size_key(key=entry) == False:\n+ if raw_search_results['value']['search'][key]['suggestions'][entry]['relatedvideos']['length'] > 0:\n+ has_search_results = True\n+\n+ # display that we haven't found a thing\n+ if has_search_results == False:\n+ return []\n+\n+ # list the search results\n+ search_results = self.netflix_session.parse_search_results(response_data=raw_search_results)\n+ # add more menaingful data to the search results\n+ raw_search_contents = self.netflix_session.fetch_video_list_information(video_ids=search_results.keys())\n+ # check for any errors\n+ if 'error' in raw_search_contents:\n+ return raw_search_contents\n+ return self.netflix_session.parse_video_list(response_data=raw_search_contents)\n" }, { "change_type": "MODIFY", "old_path": "resources/settings.xml", "new_path": "resources/settings.xml", "diff": "<setting id=\"esn\" type=\"text\" label=\"30034\" value=\"\" default=\"\"/>\n<setting id=\"tracking_id\" value=\"\" visible=\"false\"/>\n<setting id=\"msl_service_port\" value=\"8000\" visible=\"false\"/>\n+ <setting id=\"netflix_service_port\" value=\"8001\" visible=\"false\"/>\n</category>\n</settings>\n" }, { "change_type": "MODIFY", "old_path": "service.py", "new_path": "service.py", "diff": "import threading\nimport SocketServer\nimport xbmc\n-import xbmcaddon\nimport socket\n+from xbmcaddon import Addon\nfrom resources.lib.KodiHelper import KodiHelper\nfrom resources.lib.MSLHttpRequestHandler import MSLHttpRequestHandler\n-\n-addon = xbmcaddon.Addon()\n-kodi_helper = KodiHelper(\n- plugin_handle=None,\n- base_url=None\n-)\n+from resources.lib.NetflixHttpRequestHandler import NetflixHttpRequestHandler\ndef select_unused_port():\nsock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n@@ -19,28 +14,49 @@ def select_unused_port():\nsock.close()\nreturn port\n+addon = Addon()\n+kodi_helper = KodiHelper()\n+\nport = select_unused_port()\naddon.setSetting('msl_service_port', str(port))\nkodi_helper.log(msg='Picked Port: ' + str(port))\n-#Config the HTTP Server\n+# server defaults\nSocketServer.TCPServer.allow_reuse_address = True\n-server = SocketServer.TCPServer(('127.0.0.1', port), MSLHttpRequestHandler)\n-server.server_activate()\n-server.timeout = 1\n+\n+# configure the MSL Server\n+msl_server = SocketServer.TCPServer(('127.0.0.1', port), MSLHttpRequestHandler)\n+msl_server.server_activate()\n+msl_server.timeout = 1\n+\n+# configure the Netflix Data Server\n+nd_server = SocketServer.TCPServer(('127.0.0.1', 7005), NetflixHttpRequestHandler)\n+nd_server.server_activate()\n+nd_server.timeout = 1\nif __name__ == '__main__':\nmonitor = xbmc.Monitor()\n- thread = threading.Thread(target=server.serve_forever)\n- thread.daemon = True\n- thread.start()\n+\n+ msl_thread = threading.Thread(target=msl_server.serve_forever)\n+ msl_thread.daemon = True\n+ msl_thread.start()\n+\n+ nd_thread = threading.Thread(target=nd_server.serve_forever)\n+ nd_thread.daemon = True\n+ nd_thread.start()\nwhile not monitor.abortRequested():\nif monitor.waitForAbort(5):\n- server.shutdown()\n+ msl_server.shutdown()\n+ nd_server.shutdown()\nbreak\n- server.server_close()\n- server.socket.close()\n- server.shutdown()\n+ msl_server.server_close()\n+ msl_server.socket.close()\n+ msl_server.shutdown()\nkodi_helper.log(msg='Stopped MSL Service')\n+\n+ nd_server.server_close()\n+ nd_server.socket.close()\n+ nd_server.shutdown()\n+ kodi_helper.log(msg='Stopped HTTP Service')\n" } ]
Python
MIT License
castagnait/plugin.video.netflix
chore(performance): Removes NetflixSession from the core addon & adds a HTTP proxy service for the Netflix data
105,979
07.03.2017 20:02:29
-3,600
ffd4aa3d7edc7f9cab576ae69d3a64d3389d9db9
fix(service): Add dynamic port resolution for netflix service
[ { "change_type": "MODIFY", "old_path": "resources/lib/Navigation.py", "new_path": "resources/lib/Navigation.py", "diff": "@@ -35,7 +35,7 @@ class Navigation:\nself.log = log_fn\ndef get_netflix_service_url (self):\n- return 'http://localhost:7005'\n+ return 'http://localhost:' + str(self.kodi_helper.addon.getSetting('netflix_service_port'))\ndef call_netflix_service (self, params):\nurl_values = urllib.urlencode(params)\n" }, { "change_type": "MODIFY", "old_path": "service.py", "new_path": "service.py", "diff": "@@ -17,20 +17,24 @@ def select_unused_port():\naddon = Addon()\nkodi_helper = KodiHelper()\n-port = select_unused_port()\n-addon.setSetting('msl_service_port', str(port))\n-kodi_helper.log(msg='Picked Port: ' + str(port))\n+msl_port = select_unused_port()\n+addon.setSetting('msl_service_port', str(msl_port))\n+kodi_helper.log(msg='[MSL] Picked Port: ' + str(msl_port))\n+\n+ns_port = select_unused_port()\n+addon.setSetting('netflix_service_port', str(ns_port))\n+kodi_helper.log(msg='[NS] Picked Port: ' + str(ns_port))\n# server defaults\nSocketServer.TCPServer.allow_reuse_address = True\n# configure the MSL Server\n-msl_server = SocketServer.TCPServer(('127.0.0.1', port), MSLHttpRequestHandler)\n+msl_server = SocketServer.TCPServer(('127.0.0.1', msl_port), MSLHttpRequestHandler)\nmsl_server.server_activate()\nmsl_server.timeout = 1\n# configure the Netflix Data Server\n-nd_server = SocketServer.TCPServer(('127.0.0.1', 7005), NetflixHttpRequestHandler)\n+nd_server = SocketServer.TCPServer(('127.0.0.1', ns_port), NetflixHttpRequestHandler)\nnd_server.server_activate()\nnd_server.timeout = 1\n" } ]
Python
MIT License
castagnait/plugin.video.netflix
fix(service): Add dynamic port resolution for netflix service
105,979
07.03.2017 22:12:58
-3,600
e68ef11b3c5f02b0aec3482b81235b9244af4fdb
fix(login): Enables hot login functionality, as well as proper login failed verification
[ { "change_type": "MODIFY", "old_path": "addon.xml", "new_path": "addon.xml", "diff": "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>\n-<addon id=\"plugin.video.netflix\" name=\"Netflix\" version=\"0.10.1\" provider-name=\"libdev + jojo + asciidisco\">\n+<addon id=\"plugin.video.netflix\" name=\"Netflix\" version=\"0.10.2\" provider-name=\"libdev + jojo + asciidisco\">\n<requires>\n<import addon=\"xbmc.python\" version=\"2.24.0\"/>\n<import addon=\"script.module.beautifulsoup4\" version=\"4.3.2\"/>\n" }, { "change_type": "MODIFY", "old_path": "resources/language/English/strings.po", "new_path": "resources/language/English/strings.po", "diff": "# Kodi Media Center language file\n# Addon Name: Netflix\n# Addon id: plugin.video.netflix\n-# Addon version: 0.10.1\n+# Addon version: 0.10.2\n# Addon Provider: libdev + jojo + asciidisco\nmsgid \"\"\nmsgstr \"\"\n" }, { "change_type": "MODIFY", "old_path": "resources/language/German/strings.po", "new_path": "resources/language/German/strings.po", "diff": "# Kodi Media Center language file\n# Addon Name: Netflix\n# Addon id: plugin.video.netflix\n-# Addon version: 0.10.1\n+# Addon version: 0.10.2\n# Addon Provider: libdev + jojo + asciidisco\nmsgid \"\"\nmsgstr \"\"\n" }, { "change_type": "MODIFY", "old_path": "resources/lib/Navigation.py", "new_path": "resources/lib/Navigation.py", "diff": "@@ -34,17 +34,6 @@ class Navigation:\nself.base_url = base_url\nself.log = log_fn\n- def get_netflix_service_url (self):\n- return 'http://localhost:' + str(self.kodi_helper.addon.getSetting('netflix_service_port'))\n-\n- def call_netflix_service (self, params):\n- url_values = urllib.urlencode(params)\n- url = self.get_netflix_service_url()\n- full_url = url + '?' + url_values\n- data = urllib2.urlopen(full_url).read()\n- parsed_json = json.loads(data)\n- return parsed_json.get('result', None)\n-\n@log\ndef router (self, paramstring):\n\"\"\"Route to the requested subfolder & dispatch actions along the way\n@@ -134,7 +123,6 @@ class Navigation:\nstart_offset : :obj:`str`\nOffset to resume playback from (in seconds)\n\"\"\"\n- # widevine esn\nesn = self.call_netflix_service({'method': 'get_esn'})\nreturn self.kodi_helper.play_item(esn=esn, video_id=video_id, start_offset=start_offset)\n@@ -281,6 +269,8 @@ class Navigation:\ndef show_profiles (self):\n\"\"\"List the profiles for the active account\"\"\"\nprofiles = self.call_netflix_service({'method': 'list_profiles'})\n+ if len(profiles) == 0:\n+ return self.kodi_helper.show_login_failed_notification()\nreturn self.kodi_helper.build_profiles_listing(profiles=profiles, action='video_lists', build_url=self.build_url)\n@log\n@@ -384,7 +374,7 @@ class Navigation:\nIf we don't have an active session & the user couldn't be logged in\n\"\"\"\nis_logged_in = self.call_netflix_service({'method': 'is_logged_in'})\n- return True if is_logged_in else self.call_netflix_service({'method': 'login'})\n+ return True if is_logged_in else self.call_netflix_service({'method': 'login', 'email': account['email'], 'password': account['password']})\n@log\ndef before_routing_action (self, params):\n@@ -425,6 +415,7 @@ class Navigation:\nself.call_netflix_service({'method': 'switch_profile', 'profile_id': params['profile_id']})\n# check login, in case of main menu\nif 'action' not in params:\n+ self.kodi_helper.log('ES Called - Zeile 428')\nself.establish_session(account=credentials)\nreturn options\n@@ -495,6 +486,7 @@ class Navigation:\nif 'error' in response:\n# check if we do not have a valid session, in case that happens: (re)login\nif self._is_expired_session(response=response):\n+ self.kodi_helper.log('ES Called - Zeile 499')\nif self.establish_session(account=self.kodi_helper.get_credentials()):\nreturn True\nmessage = response['message'] if 'message' in response else ''\n@@ -517,3 +509,33 @@ class Navigation:\nUrl + querystring based on the param\n\"\"\"\nreturn self.base_url + '?' + urllib.urlencode(query)\n+\n+ def get_netflix_service_url (self):\n+ \"\"\"Returns URL & Port of the internal Netflix HTTP Proxy service\n+\n+ Returns\n+ -------\n+ str\n+ Url + Port\n+ \"\"\"\n+ return 'http://localhost:' + str(self.kodi_helper.addon.getSetting('netflix_service_port'))\n+\n+ def call_netflix_service (self, params):\n+ \"\"\"Makes a GET request to the internal Netflix HTTP proxy and returns the result\n+\n+ Parameters\n+ ----------\n+ params : :obj:`dict` of :obj:`str`\n+ List of paramters to be url encoded\n+\n+ Returns\n+ -------\n+ :obj:`dict`\n+ Netflix Service RPC result\n+ \"\"\"\n+ url_values = urllib.urlencode(params)\n+ url = self.get_netflix_service_url()\n+ full_url = url + '?' + url_values\n+ data = urllib2.urlopen(full_url).read()\n+ parsed_json = json.loads(data)\n+ return parsed_json.get('result', None)\n" }, { "change_type": "MODIFY", "old_path": "resources/lib/NetflixHttpRequestHandler.py", "new_path": "resources/lib/NetflixHttpRequestHandler.py", "diff": "+#!/usr/bin/env python\n+# -*- coding: utf-8 -*-\n+# Module: NetflixHttpRequestHandler\n+# Created on: 07.03.2017\n+\nimport BaseHTTPServer\nimport json\nfrom types import FunctionType\n" }, { "change_type": "MODIFY", "old_path": "resources/lib/NetflixHttpSubRessourceHandler.py", "new_path": "resources/lib/NetflixHttpSubRessourceHandler.py", "diff": "+#!/usr/bin/env python\n+# -*- coding: utf-8 -*-\n+# Module: NetflixHttpSubRessourceHandler\n+# Created on: 07.03.2017\n+\nclass NetflixHttpSubRessourceHandler:\ndef __init__ (self, kodi_helper, netflix_session):\nself.kodi_helper = kodi_helper\nself.netflix_session = netflix_session\n- credentials = self.kodi_helper.get_credentials()\n+ self.credentials = self.kodi_helper.get_credentials()\n- if self.netflix_session.is_logged_in(account=credentials):\n- self.netflix_session.refresh_session_data(account=credentials)\n+ if self.credentials['email'] != '' and self.credentials['password'] != '':\n+ if self.netflix_session.is_logged_in(account=self.credentials):\n+ self.netflix_session.refresh_session_data(account=self.credentials)\nelse:\n- self.netflix_session.login(account=credentials)\n+ self.netflix_session.login(account=self.credentials)\nself.profiles = self.netflix_session.profiles\n+ else:\n+ self.profiles = []\ndef is_logged_in (self, params):\n- credentials = self.kodi_helper.get_credentials()\n- return self.netflix_session.is_logged_in(account=credentials)\n+ if self.credentials['email'] == '' or self.credentials['password'] == '':\n+ return False\n+ return self.netflix_session.is_logged_in(account=self.credentials)\ndef logout (self, params):\n+ self.profiles = []\n+ self.credentials = {'email': '', 'password': ''}\nreturn self.netflix_session.logout()\n+ def login (self, params):\n+ email = params.get('email', [''])[0]\n+ password = params.get('password', [''])[0]\n+ if email != '' and password != '':\n+ self.credentials = {'email': email, 'password': password}\n+ _ret = self.netflix_session.login(account=self.credentials)\n+ self.profiles = self.netflix_session.profiles\n+ return _ret\n+ return None\n+\ndef list_profiles (self, params):\nreturn self.profiles\n@@ -74,9 +95,8 @@ class NetflixHttpSubRessourceHandler:\nreturn self.netflix_session.fetch_metadata(id=video_id)\ndef switch_profile (self, params):\n- credentials = self.kodi_helper.get_credentials()\nprofile_id = params.get('profile_id', [''])[0]\n- return self.netflix_session.switch_profile(profile_id=profile_id, account=credentials)\n+ return self.netflix_session.switch_profile(profile_id=profile_id, account=self.credentials)\ndef get_user_data (self, params):\nreturn self.netflix_session.user_data\n" } ]
Python
MIT License
castagnait/plugin.video.netflix
fix(login): Enables hot login functionality, as well as proper login failed verification
105,979
07.03.2017 22:30:32
-3,600
b6a1c1cd2250104b139115ef16475c539626a9a7
chore(performace): Prefetching of user video lists
[ { "change_type": "MODIFY", "old_path": "addon.xml", "new_path": "addon.xml", "diff": "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>\n-<addon id=\"plugin.video.netflix\" name=\"Netflix\" version=\"0.10.2\" provider-name=\"libdev + jojo + asciidisco\">\n+<addon id=\"plugin.video.netflix\" name=\"Netflix\" version=\"0.10.3\" provider-name=\"libdev + jojo + asciidisco\">\n<requires>\n<import addon=\"xbmc.python\" version=\"2.24.0\"/>\n<import addon=\"script.module.beautifulsoup4\" version=\"4.3.2\"/>\n" }, { "change_type": "MODIFY", "old_path": "resources/language/English/strings.po", "new_path": "resources/language/English/strings.po", "diff": "# Kodi Media Center language file\n# Addon Name: Netflix\n# Addon id: plugin.video.netflix\n-# Addon version: 0.10.2\n+# Addon version: 0.10.3\n# Addon Provider: libdev + jojo + asciidisco\nmsgid \"\"\nmsgstr \"\"\n" }, { "change_type": "MODIFY", "old_path": "resources/language/German/strings.po", "new_path": "resources/language/German/strings.po", "diff": "# Kodi Media Center language file\n# Addon Name: Netflix\n# Addon id: plugin.video.netflix\n-# Addon version: 0.10.2\n+# Addon version: 0.10.3\n# Addon Provider: libdev + jojo + asciidisco\nmsgid \"\"\nmsgstr \"\"\n" }, { "change_type": "MODIFY", "old_path": "resources/lib/Navigation.py", "new_path": "resources/lib/Navigation.py", "diff": "@@ -415,7 +415,6 @@ class Navigation:\nself.call_netflix_service({'method': 'switch_profile', 'profile_id': params['profile_id']})\n# check login, in case of main menu\nif 'action' not in params:\n- self.kodi_helper.log('ES Called - Zeile 428')\nself.establish_session(account=credentials)\nreturn options\n@@ -486,7 +485,6 @@ class Navigation:\nif 'error' in response:\n# check if we do not have a valid session, in case that happens: (re)login\nif self._is_expired_session(response=response):\n- self.kodi_helper.log('ES Called - Zeile 499')\nif self.establish_session(account=self.kodi_helper.get_credentials()):\nreturn True\nmessage = response['message'] if 'message' in response else ''\n" }, { "change_type": "MODIFY", "old_path": "resources/lib/NetflixHttpSubRessourceHandler.py", "new_path": "resources/lib/NetflixHttpSubRessourceHandler.py", "diff": "@@ -9,6 +9,7 @@ class NetflixHttpSubRessourceHandler:\nself.kodi_helper = kodi_helper\nself.netflix_session = netflix_session\nself.credentials = self.kodi_helper.get_credentials()\n+ self.video_list_cache = {}\nif self.credentials['email'] != '' and self.credentials['password'] != '':\nif self.netflix_session.is_logged_in(account=self.credentials):\n@@ -16,9 +17,16 @@ class NetflixHttpSubRessourceHandler:\nelse:\nself.netflix_session.login(account=self.credentials)\nself.profiles = self.netflix_session.profiles\n+ self._prefetch_user_video_lists()\nelse:\nself.profiles = []\n+ def _prefetch_user_video_lists (self):\n+ for profile_id in self.profiles:\n+ self.switch_profile({'profile_id': [profile_id]})\n+ self.video_list_cache[profile_id] = self.fetch_video_list_ids({})\n+ print self.video_list_cache\n+\ndef is_logged_in (self, params):\nif self.credentials['email'] == '' or self.credentials['password'] == '':\nreturn False\n@@ -46,6 +54,10 @@ class NetflixHttpSubRessourceHandler:\nreturn self.netflix_session.esn\ndef fetch_video_list_ids (self, params):\n+ cached_list = self.video_list_cache.get(self.netflix_session.user_data['guid'], None)\n+ if cached_list != None:\n+ self.kodi_helper.log('Serving cached list for user: ' + self.netflix_session.user_data['guid'])\n+ return cached_list\nvideo_list_ids_raw = self.netflix_session.fetch_video_list_ids()\nif 'error' in video_list_ids_raw:\nreturn video_list_ids_raw\n" }, { "change_type": "MODIFY", "old_path": "resources/lib/NetflixSession.py", "new_path": "resources/lib/NetflixSession.py", "diff": "@@ -2296,5 +2296,5 @@ class NetflixSession:\nself.esn = self._parse_esn_data(netflix_page_data=netflix_page_data)\nself.api_data = self._parse_api_base_data(netflix_page_data=netflix_page_data)\nself.profiles = self._parse_profile_data(netflix_page_data=netflix_page_data)\n- self.log('Found ESN \"' + self.esn)\n+ self.log('Found ESN \"' + self.esn + '\"')\nreturn netflix_page_data\n" } ]
Python
MIT License
castagnait/plugin.video.netflix
chore(performace): Prefetching of user video lists
105,979
07.03.2017 22:42:42
-3,600
94f1971e3d59b51d424bc6919b50c7b831eef2a1
chore(performace): Disable prefetching (temporary)
[ { "change_type": "MODIFY", "old_path": "resources/lib/NetflixHttpSubRessourceHandler.py", "new_path": "resources/lib/NetflixHttpSubRessourceHandler.py", "diff": "@@ -17,7 +17,7 @@ class NetflixHttpSubRessourceHandler:\nelse:\nself.netflix_session.login(account=self.credentials)\nself.profiles = self.netflix_session.profiles\n- self._prefetch_user_video_lists()\n+ #self._prefetch_user_video_lists()\nelse:\nself.profiles = []\n@@ -25,7 +25,6 @@ class NetflixHttpSubRessourceHandler:\nfor profile_id in self.profiles:\nself.switch_profile({'profile_id': [profile_id]})\nself.video_list_cache[profile_id] = self.fetch_video_list_ids({})\n- print self.video_list_cache\ndef is_logged_in (self, params):\nif self.credentials['email'] == '' or self.credentials['password'] == '':\n" } ]
Python
MIT License
castagnait/plugin.video.netflix
chore(performace): Disable prefetching (temporary)
105,979
08.03.2017 00:12:20
-3,600
ca74d7fc650a2b74736c9d0e6eaee3aa805d716c
feat(settings): Adds shortcut to inputstream settings
[ { "change_type": "MODIFY", "old_path": "resources/language/English/strings.po", "new_path": "resources/language/English/strings.po", "diff": "@@ -156,3 +156,7 @@ msgstr \"\"\nmsgctxt \"#30034\"\nmsgid \"ESN (set automatically, can be changed manually)\"\nmsgstr \"\"\n+\n+msgctxt \"#30035\"\n+msgid \"Inputstream Addon Settings...\"\n+msgstr \"\"\n" }, { "change_type": "MODIFY", "old_path": "resources/lib/Navigation.py", "new_path": "resources/lib/Navigation.py", "diff": "import urllib\nimport urllib2\nimport json\n+from xbmcaddon import Addon\nfrom urlparse import parse_qsl\nfrom utils import noop, log\n@@ -45,6 +46,10 @@ class Navigation:\n\"\"\"\nparams = self.parse_paramters(paramstring=paramstring)\n+ # open foreign settings dialog\n+ if 'mode' in params.keys() and params['mode'] == 'openSettings':\n+ return self.open_settings(params['url'])\n+\n# log out the user\nif 'action' in params.keys() and params['action'] == 'logout':\nreturn self.call_netflix_service({'method': 'logout'})\n@@ -537,3 +542,9 @@ class Navigation:\ndata = urllib2.urlopen(full_url).read()\nparsed_json = json.loads(data)\nreturn parsed_json.get('result', None)\n+\n+ def open_settings(self, url):\n+ \"\"\"Opens a foreign settings dialog\"\"\"\n+ is_addon = self.kodi_helper.get_inputstream_addon()\n+ url = is_addon if url == 'is' else url\n+ return Addon(url).openSettings()\n" }, { "change_type": "MODIFY", "old_path": "resources/settings.xml", "new_path": "resources/settings.xml", "diff": "<setting id=\"email\" type=\"text\" label=\"30005\" default=\"\"/>\n<setting id=\"password\" type=\"text\" option=\"hidden\" label=\"30004\" default=\"\"/>\n<setting id=\"logout\" type=\"action\" label=\"30017\" action=\"RunPlugin(plugin://plugin.video.netflix/?action=logout)\" option=\"close\"/>\n+ <setting id=\"is_settings\" type=\"action\" label=\"30035\" action=\"RunPlugin(plugin://plugin.video.netflix/?mode=openSettings&url=is)\" option=\"close\"/>\n</category>\n<category label=\"30025\">\n<setting id=\"enablelibraryfolder\" type=\"bool\" label=\"30026\" default=\"false\"/>\n" } ]
Python
MIT License
castagnait/plugin.video.netflix
feat(settings): Adds shortcut to inputstream settings
105,979
08.03.2017 08:41:45
-3,600
6ff6b14efa07a2b0e736cef5fee7296179af9a43
fix(api): Exchanges warmer API endpoint with preflight
[ { "change_type": "MODIFY", "old_path": "addon.xml", "new_path": "addon.xml", "diff": "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>\n-<addon id=\"plugin.video.netflix\" name=\"Netflix\" version=\"0.10.3\" provider-name=\"libdev + jojo + asciidisco\">\n+<addon id=\"plugin.video.netflix\" name=\"Netflix\" version=\"0.10.4\" provider-name=\"libdev + jojo + asciidisco\">\n<requires>\n<import addon=\"xbmc.python\" version=\"2.24.0\"/>\n<import addon=\"script.module.beautifulsoup4\" version=\"4.3.2\"/>\n" }, { "change_type": "MODIFY", "old_path": "resources/language/English/strings.po", "new_path": "resources/language/English/strings.po", "diff": "# Kodi Media Center language file\n# Addon Name: Netflix\n# Addon id: plugin.video.netflix\n-# Addon version: 0.10.3\n+# Addon version: 0.10.4\n# Addon Provider: libdev + jojo + asciidisco\nmsgid \"\"\nmsgstr \"\"\n" }, { "change_type": "MODIFY", "old_path": "resources/language/German/strings.po", "new_path": "resources/language/German/strings.po", "diff": "# Kodi Media Center language file\n# Addon Name: Netflix\n# Addon id: plugin.video.netflix\n-# Addon version: 0.10.3\n+# Addon version: 0.10.4\n# Addon Provider: libdev + jojo + asciidisco\nmsgid \"\"\nmsgstr \"\"\n" }, { "change_type": "MODIFY", "old_path": "resources/lib/NetflixSession.py", "new_path": "resources/lib/NetflixSession.py", "diff": "@@ -25,7 +25,7 @@ class NetflixSession:\nurls = {\n'login': '/login',\n'browse': '/browse',\n- 'video_list_ids': '/warmer',\n+ 'video_list_ids': '/preflight',\n'shakti': '/pathEvaluator',\n'profiles': '/browse',\n'switch_profiles': '/profiles/switch',\n" } ]
Python
MIT License
castagnait/plugin.video.netflix
fix(api): Exchanges warmer API endpoint with preflight
105,979
09.03.2017 10:36:23
-3,600
90f1fed6e5a2422235eb412d202da1f98de16149
chore(perf): Remove an unecessary request when entering a profile
[ { "change_type": "MODIFY", "old_path": "resources/lib/NetflixSession.py", "new_path": "resources/lib/NetflixSession.py", "diff": "@@ -280,14 +280,9 @@ class NetflixSession:\nif response.status_code != 200:\nreturn False\n- # fetch the index page again, so that we can fetch the corresponding user data\n- browse_response = self._session_get(component='browse')\n- only_script_tags = SoupStrainer('script')\n- browse_soup = BeautifulSoup(browse_response.text, 'html.parser', parse_only=only_script_tags)\naccount_hash = self._generate_account_hash(account=account)\nself.user_data['guid'] = profile_id;\n- self._save_data(filename=self.data_path + '_' + account_hash)\n- return True\n+ return self._save_data(filename=self.data_path + '_' + account_hash)\ndef send_adult_pin (self, pin):\n\"\"\"Send the adult pin to Netflix in case an adult rated video requests it\n" } ]
Python
MIT License
castagnait/plugin.video.netflix
chore(perf): Remove an unecessary request when entering a profile
105,979
09.03.2017 11:01:06
-3,600
ed87c5c11a91aedcff4ea843380747f5c7f4df1b
chore(perf): Switch from the browse enpoint to the profiles/manage endpoint when grepping inline JS, as this is twice as fast
[ { "change_type": "MODIFY", "old_path": "resources/lib/NetflixSession.py", "new_path": "resources/lib/NetflixSession.py", "diff": "@@ -24,10 +24,10 @@ class NetflixSession:\nurls = {\n'login': '/login',\n- 'browse': '/browse',\n+ 'browse': '/profiles/manage',\n'video_list_ids': '/preflight',\n'shakti': '/pathEvaluator',\n- 'profiles': '/browse',\n+ 'profiles': '/profiles/manage',\n'switch_profiles': '/profiles/switch',\n'adult_pin': '/pin/service',\n'metadata': '/metadata',\n" } ]
Python
MIT License
castagnait/plugin.video.netflix
chore(perf): Switch from the browse enpoint to the profiles/manage endpoint when grepping inline JS, as this is twice as fast
105,979
09.03.2017 12:47:22
-3,600
f08b44fdcde5403719848fbe80b94efa8417ab57
fix(my-list): Fixes that not all videos have been shown on the list
[ { "change_type": "MODIFY", "old_path": "resources/lib/KodiHelper.py", "new_path": "resources/lib/KodiHelper.py", "diff": "@@ -430,7 +430,6 @@ class KodiHelper:\n\"\"\"\nfor video_list_id in video_list:\nvideo = video_list[video_list_id]\n- if type != 'queue' or (type == 'queue' and video['in_my_list'] == True):\nli = xbmcgui.ListItem(label=video['title'])\n# add some art to the item\nli = self._generate_art_info(entry=video, li=li)\n" }, { "change_type": "MODIFY", "old_path": "resources/lib/NetflixSession.py", "new_path": "resources/lib/NetflixSession.py", "diff": "@@ -1563,8 +1563,6 @@ class NetflixSession:\n})\nparams = {\n- 'withSize': True,\n- 'materialize': True,\n'model': self.user_data['gpsModel']\n}\n@@ -1919,6 +1917,7 @@ class NetflixSession:\nstart = time()\nresponse = self.session.get(url=url, verify=self.verify_ssl, params=params)\nend = time()\n+ print params\nself.log('[GET] Request for \"' + url + '\" took ' + str(end - start) + ' seconds')\nreturn response\n" } ]
Python
MIT License
castagnait/plugin.video.netflix
fix(my-list): Fixes that not all videos have been shown on the list
105,979
09.03.2017 12:48:23
-3,600
c83841672d0834fd26d54d87e5a4430c47a3e15f
chore(debug): Remove debug statements
[ { "change_type": "MODIFY", "old_path": "resources/lib/NetflixSession.py", "new_path": "resources/lib/NetflixSession.py", "diff": "@@ -1917,7 +1917,6 @@ class NetflixSession:\nstart = time()\nresponse = self.session.get(url=url, verify=self.verify_ssl, params=params)\nend = time()\n- print params\nself.log('[GET] Request for \"' + url + '\" took ' + str(end - start) + ' seconds')\nreturn response\n" } ]
Python
MIT License
castagnait/plugin.video.netflix
chore(debug): Remove debug statements
105,979
09.03.2017 14:07:27
-3,600
f2154ed9821a052d1c145f7bdf219f4d9386af81
chore(performance): Does preflight request with lolomoid if given in cookie
[ { "change_type": "MODIFY", "old_path": "resources/lib/MSL.py", "new_path": "resources/lib/MSL.py", "diff": "+#!/usr/bin/env python\n+# -*- coding: utf-8 -*-\n+# Module: MSL\n+# Created on: 26.01.2017\n+\nimport base64\nimport gzip\nimport json\n" }, { "change_type": "MODIFY", "old_path": "resources/lib/MSLHttpRequestHandler.py", "new_path": "resources/lib/MSLHttpRequestHandler.py", "diff": "+#!/usr/bin/env python\n+# -*- coding: utf-8 -*-\n+# Module: MSLHttpRequestHandler\n+# Created on: 26.01.2017\n+\nimport BaseHTTPServer\nimport base64\nfrom urlparse import urlparse, parse_qs\nfrom MSL import MSL\nfrom KodiHelper import KodiHelper\n-kodi_helper = KodiHelper(\n- plugin_handle=None,\n- base_url=None\n-)\n+kodi_helper = KodiHelper()\nmsl = MSL(kodi_helper)\n" }, { "change_type": "MODIFY", "old_path": "resources/lib/NetflixSession.py", "new_path": "resources/lib/NetflixSession.py", "diff": "import os\nimport json\nfrom requests import session, cookies\n-from urllib import quote\n+from urllib import quote, unquote\nfrom time import time\nfrom base64 import urlsafe_b64encode\nfrom bs4 import BeautifulSoup, SoupStrainer\n@@ -1293,6 +1293,13 @@ class NetflixSession:\n'_': int(time()),\n'authURL': self.user_data['authURL']\n}\n+\n+ # check if we have a root lolomo for that user within our cookies\n+ for cookie in self.session.cookies:\n+ if cookie.name == 'lhpuuidh-browse-' + self.user_data['guid']:\n+ value = unquote(cookie.value)\n+ payload['lolomoid'] = value[value.rfind(':')+1:];\n+\nresponse = self._session_get(component='video_list_ids', params=payload, type='api')\nreturn self._process_response(response=response, component=self._get_api_url_for(component='video_list_ids'))\n" }, { "change_type": "MODIFY", "old_path": "service.py", "new_path": "service.py", "diff": "+#!/usr/bin/env python\n+# -*- coding: utf-8 -*-\n+# Module: service\n+# Created on: 26.01.2017\n+\nimport threading\nimport SocketServer\nimport xbmc\n" } ]
Python
MIT License
castagnait/plugin.video.netflix
chore(performance): Does preflight request with lolomoid if given in cookie