├── .gitignore ├── .pre-commit-config.yaml ├── .github ├── dependabot.yml └── workflows │ ├── release.yaml │ ├── verify.yaml │ └── stale.yaml ├── go.sum ├── go.mod ├── README.md ├── examples └── list_devices.go ├── jdownloader ├── crypto_test.go ├── utils.go ├── types.go ├── crypto.go ├── client_mock.go ├── device.go ├── settings.go ├── client.go ├── downloader.go └── linkgrabber.go └── LICENSE.txt /.gitignore: -------------------------------------------------------------------------------- 1 | .idea 2 | -------------------------------------------------------------------------------- /.pre-commit-config.yaml: -------------------------------------------------------------------------------- 1 | --- 2 | repos: 3 | - repo: https://github.com/pre-commit/pre-commit-hooks 4 | rev: v6.0.0 5 | hooks: 6 | - id: trailing-whitespace 7 | - id: check-yaml 8 | - id: check-merge-conflict 9 | - repo: https://github.com/golangci/golangci-lint 10 | rev: v2.7.2 11 | hooks: 12 | - id: golangci-lint 13 | - repo: https://github.com/dnephin/pre-commit-golang 14 | rev: v0.5.1 15 | hooks: 16 | - id: go-mod-tidy 17 | - id: go-fmt 18 | -------------------------------------------------------------------------------- /.github/dependabot.yml: -------------------------------------------------------------------------------- 1 | # Copyright 2024 Richard Kosegi 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | --- 15 | version: 2 16 | updates: 17 | - package-ecosystem: gomod 18 | directory: / 19 | schedule: 20 | interval: daily 21 | - package-ecosystem: github-actions 22 | directory: / 23 | schedule: 24 | interval: daily 25 | -------------------------------------------------------------------------------- /go.sum: -------------------------------------------------------------------------------- 1 | github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= 2 | github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= 3 | github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= 4 | github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= 5 | github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U= 6 | github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U= 7 | gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM= 8 | gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= 9 | gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= 10 | gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= 11 | -------------------------------------------------------------------------------- /go.mod: -------------------------------------------------------------------------------- 1 | // Copyright 2022 Richard Kosegi 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | module github.com/rkosegi/jdownloader-go 16 | 17 | go 1.25 18 | 19 | require github.com/stretchr/testify v1.11.1 20 | 21 | require ( 22 | github.com/davecgh/go-spew v1.1.1 // indirect 23 | github.com/pmezard/go-difflib v1.0.0 // indirect 24 | gopkg.in/yaml.v3 v3.0.1 // indirect 25 | ) 26 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # JDownloader client in Go 2 | 3 | This repository hosts code for [JDownloader](https://jdownloader.org/) client written in Go 4 | 5 | ### Example usage 6 | 7 | #### Add link and start download 8 | 9 | ```go 10 | package main 11 | 12 | import ( 13 | "github.com/rkosegi/jdownloader-go/jdownloader" 14 | "log/slog" 15 | ) 16 | 17 | func main() { 18 | c := jdownloader.NewClient("test@acme.tld", "passw0rd", slog.Default()) 19 | err := c.Connect() 20 | if err != nil { 21 | panic(err) 22 | } 23 | dev, err := c.Device("my-device-name") 24 | if err != nil { 25 | panic(err) 26 | } 27 | _, err = dev.LinkGrabber().Add([]string{"http://myremoteservice/somefile.zip"}, 28 | jdownloader.AddLinksOptionPackage("Package-Name"), 29 | jdownloader.AddLinksOptionAutostart(true), 30 | jdownloader.AddLinksOptionDestinationDir("/mnt/download"), 31 | ) 32 | if err != nil { 33 | panic(err) 34 | } 35 | _ = c.Disconnect() 36 | } 37 | ``` 38 | 39 | -------------------------------------------------------------------------------- /.github/workflows/release.yaml: -------------------------------------------------------------------------------- 1 | # Copyright 2024 Richard Kosegi 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | --- 15 | name: tag release 16 | on: 17 | push: 18 | tags: 19 | - v* 20 | 21 | permissions: 22 | packages: write 23 | contents: write 24 | 25 | jobs: 26 | release: 27 | runs-on: ubuntu-latest 28 | steps: 29 | - uses: actions/checkout@v6 30 | - uses: softprops/action-gh-release@v2 31 | with: 32 | generate_release_notes: true 33 | -------------------------------------------------------------------------------- /examples/list_devices.go: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright 2022 Richard Kosegi 3 | 4 | Licensed under the Apache License, Version 2.0 (the "License"); 5 | you may not use this file except in compliance with the License. 6 | You may obtain a copy of the License at 7 | 8 | http://www.apache.org/licenses/LICENSE-2.0 9 | 10 | Unless required by applicable law or agreed to in writing, software 11 | distributed under the License is distributed on an "AS IS" BASIS, 12 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | See the License for the specific language governing permissions and 14 | limitations under the License. 15 | */ 16 | 17 | package main 18 | 19 | import ( 20 | "fmt" 21 | "log/slog" 22 | 23 | "github.com/rkosegi/jdownloader-go/jdownloader" 24 | ) 25 | 26 | const ( 27 | mail = "name@acme.tld" 28 | password = "abcdefghijklmnopqrstuvwxyz" 29 | ) 30 | 31 | func main() { 32 | c := jdownloader.NewClient(mail, password, slog.Default()) 33 | devs, err := c.ListDevices() 34 | if err != nil { 35 | panic(err) 36 | } 37 | for _, dev := range *devs { 38 | fmt.Printf("Device: %s\n", dev.Name) 39 | } 40 | _ = c.Disconnect() 41 | } 42 | -------------------------------------------------------------------------------- /.github/workflows/verify.yaml: -------------------------------------------------------------------------------- 1 | # Copyright 2024 Richard Kosegi 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | --- 15 | name: CI 16 | 17 | on: 18 | push: 19 | branches: 20 | - main 21 | pull_request: 22 | branches: 23 | - main 24 | workflow_dispatch: 25 | permissions: 26 | contents: read 27 | 28 | jobs: 29 | build: 30 | runs-on: ubuntu-latest 31 | steps: 32 | - name: Checkout code 33 | uses: actions/checkout@v6 34 | 35 | - name: Set up Go 36 | uses: actions/setup-go@v6 37 | with: 38 | go-version: '1.25' 39 | 40 | - uses: actions/setup-python@v6 41 | with: 42 | python-version: '3.x' 43 | - uses: pre-commit/action@v3.0.1 44 | 45 | - name: Build 46 | run: go build -v ./... 47 | 48 | - name: Test 49 | run: go test -v ./... 50 | -------------------------------------------------------------------------------- /.github/workflows/stale.yaml: -------------------------------------------------------------------------------- 1 | # Copyright 2024 Richard Kosegi 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | --- 15 | name: Close inactive issues 16 | on: 17 | schedule: 18 | - cron: 37 2 * * 1 19 | workflow_dispatch: 20 | jobs: 21 | close-issues: 22 | runs-on: ubuntu-latest 23 | permissions: 24 | issues: write 25 | pull-requests: write 26 | steps: 27 | - uses: actions/stale@v10 28 | with: 29 | days-before-stale: 60 30 | days-before-close: 7 31 | stale-issue-label: stale 32 | stale-pr-label: stale 33 | stale-issue-message: This issue has been marked 'stale' due to lack of activity. The issue will be closed in another 30 days. 34 | close-issue-message: This issue has been closed due to inactivity. If you feel this is in error, please reopen the issue or file a new issue with the relevant details. 35 | stale-pr-message: This pr has been marked 'stale' due to lack of recent activity.The issue will be closed in another 30 days. 36 | close-pr-message: This pr has been closed due to inactivity. If you feel this is in error, please reopen the issue or file a new issue with the relevant details. 37 | repo-token: ${{ secrets.GITHUB_TOKEN }} 38 | -------------------------------------------------------------------------------- /jdownloader/crypto_test.go: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright 2022 Richard Kosegi 3 | 4 | Licensed under the Apache License, Version 2.0 (the "License"); 5 | you may not use this file except in compliance with the License. 6 | You may obtain a copy of the License at 7 | 8 | http://www.apache.org/licenses/LICENSE-2.0 9 | 10 | Unless required by applicable law or agreed to in writing, software 11 | distributed under the License is distributed on an "AS IS" BASIS, 12 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | See the License for the specific language governing permissions and 14 | limitations under the License. 15 | */ 16 | 17 | package jdownloader 18 | 19 | import ( 20 | "math/rand" 21 | "testing" 22 | "time" 23 | 24 | "github.com/stretchr/testify/assert" 25 | ) 26 | 27 | func TestCreateSecret(t *testing.T) { 28 | assert.Equal(t, [32]byte{ 29 | 0xee, 0x06, 0xc8, 0x31, 0x92, 0xf3, 0xc0, 0x33, 0x27, 0xfd, 0x93, 0x0, 0x10, 30 | 0xe8, 0x8f, 0x21, 0x3c, 0x21, 0x10, 0x51, 0x44, 0xe8, 0x6a, 0x64, 0x15, 0xfc, 31 | 0x3c, 0xff, 0x2d, 0xf0, 0x1e, 0x57, 32 | }, createSecret("test@acme.tld", "123456", "something")) 33 | } 34 | 35 | func TestEncryptDecryptLong(t *testing.T) { 36 | r := rand.New(rand.NewSource(time.Now().UnixNano())) 37 | key := createSecret("test@acme.tld", "123456", "something") 38 | size := 500 39 | data := make([]byte, size) 40 | _, err := r.Read(data) 41 | assert.Nil(t, err) 42 | encrypted, _ := encrypt(data, key) 43 | // t.Log(base64.StdEncoding.EncodeToString(encrypted)) 44 | decrypted, _ := decrypt(encrypted, key) 45 | assert.Equal(t, decrypted, data) 46 | } 47 | 48 | func TestEncryptDecryptShort(t *testing.T) { 49 | key := createSecret("test@acme.tld", "123456", "something") 50 | ciphertext, _ := encrypt([]byte("test"), key) 51 | plaintext, _ := decrypt(ciphertext, key) 52 | assert.Equal(t, []byte("test"), plaintext) 53 | } 54 | -------------------------------------------------------------------------------- /jdownloader/utils.go: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright 2022 Richard Kosegi 3 | 4 | Licensed under the Apache License, Version 2.0 (the "License"); 5 | you may not use this file except in compliance with the License. 6 | You may obtain a copy of the License at 7 | 8 | http://www.apache.org/licenses/LICENSE-2.0 9 | 10 | Unless required by applicable law or agreed to in writing, software 11 | distributed under the License is distributed on an "AS IS" BASIS, 12 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | See the License for the specific language governing permissions and 14 | limitations under the License. 15 | */ 16 | 17 | package jdownloader 18 | 19 | import ( 20 | "encoding/json" 21 | "fmt" 22 | "io" 23 | "log/slog" 24 | "net/url" 25 | ) 26 | 27 | func toObj(response *DataResponse, dst interface{}) error { 28 | if response == nil || response.Data == nil || dst == nil { 29 | return nil 30 | } 31 | data, err := json.Marshal(response.Data) 32 | if err != nil { 33 | return err 34 | } 35 | return json.Unmarshal(data, dst) 36 | } 37 | 38 | func parseError(data []byte, key [32]byte, log *slog.Logger) map[string]interface{} { 39 | // 1, try simple json unmarshal 40 | var v map[string]interface{} 41 | err := json.Unmarshal(data, &v) 42 | // 2, if that doesn't work, it must be encrypted 43 | if err != nil { 44 | decoded, err := decode(data, key) 45 | if err != nil { 46 | log.Warn("unable to decrypt error response", "error", err) 47 | } else { 48 | // 3, now try to unmarshal error 49 | err = json.Unmarshal(decoded, &v) 50 | if err != nil { 51 | log.Warn("error response is not a json", "error", err) 52 | return nil 53 | } else { 54 | return v 55 | } 56 | } 57 | } else { 58 | return v 59 | } 60 | return nil 61 | } 62 | 63 | // qp Creates escaped query parameter 64 | func qp(key string, value string) string { 65 | return fmt.Sprintf("%s=%s", key, url.QueryEscape(value)) 66 | } 67 | 68 | func bodycloser(b io.ReadCloser, log *slog.Logger) { 69 | err := b.Close() 70 | if err != nil { 71 | log.Warn("error while closing reader", "error", err) 72 | } 73 | } 74 | -------------------------------------------------------------------------------- /jdownloader/types.go: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright 2022 Richard Kosegi 3 | 4 | Licensed under the Apache License, Version 2.0 (the "License"); 5 | you may not use this file except in compliance with the License. 6 | You may obtain a copy of the License at 7 | 8 | http://www.apache.org/licenses/LICENSE-2.0 9 | 10 | Unless required by applicable law or agreed to in writing, software 11 | distributed under the License is distributed on an "AS IS" BASIS, 12 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | See the License for the specific language governing permissions and 14 | limitations under the License. 15 | */ 16 | 17 | package jdownloader 18 | 19 | import ( 20 | "log/slog" 21 | "net/http" 22 | "time" 23 | ) 24 | 25 | type DeviceInfo struct { 26 | Id string `json:"id"` 27 | Type string `json:"type"` 28 | Name string `json:"name"` 29 | Status string `json:"status"` 30 | } 31 | 32 | type ResponseIdentifier struct { 33 | ResponseID int64 `json:"rid,omitempty"` 34 | } 35 | 36 | type DeviceList struct { 37 | ResponseIdentifier 38 | List []DeviceInfo `json:"list"` 39 | } 40 | 41 | type actionRequest struct { 42 | Url string `json:"url"` 43 | Params []interface{} `json:"params,omitempty"` 44 | RequestId int64 `json:"rid"` 45 | ApiVersion int `json:"apiVer"` 46 | } 47 | 48 | type DataResponse struct { 49 | Data interface{} `json:"data,omitempty"` 50 | Source string `json:"src,omitempty"` 51 | Type string `json:"type,omitempty"` 52 | ResponseIdentifier 53 | } 54 | 55 | type JdClient interface { 56 | // Connect connects to device and obtains session key 57 | Connect() error 58 | // IsConnected returns true if client is connected to API server 59 | IsConnected() bool 60 | // Reconnect reconnects client to API server 61 | Reconnect() error 62 | // Disconnect disconnects client from API server 63 | Disconnect() error 64 | // ListDevices lists all devices associated with account used to connect to API server 65 | ListDevices() (*[]DeviceInfo, error) 66 | // Device gets specific device instance based on device name 67 | Device(string) (Device, error) 68 | // ConfigHash return hash code of configuration. 69 | // This method can be used to determine if there was configuration change 70 | ConfigHash() string 71 | } 72 | 73 | func NewClient(email string, password string, logger *slog.Logger, opts ...ClientOption) JdClient { 74 | c := &jDownloaderClient{ 75 | connected: false, 76 | email: email, 77 | appKey: appName, 78 | client: http.Client{ 79 | Timeout: 15 * time.Second, 80 | }, 81 | loginSecret: createSecret(email, password, "server"), 82 | deviceSecret: createSecret(email, password, "device"), 83 | log: logger, 84 | configHash: hashConfigKeys(email, password), 85 | lastCall: time.Now(), 86 | endpoint: apiEndpoint, 87 | } 88 | for _, opt := range opts { 89 | opt(c) 90 | } 91 | return c 92 | } 93 | -------------------------------------------------------------------------------- /jdownloader/crypto.go: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright 2022 Richard Kosegi 3 | 4 | Licensed under the Apache License, Version 2.0 (the "License"); 5 | you may not use this file except in compliance with the License. 6 | You may obtain a copy of the License at 7 | 8 | http://www.apache.org/licenses/LICENSE-2.0 9 | 10 | Unless required by applicable law or agreed to in writing, software 11 | distributed under the License is distributed on an "AS IS" BASIS, 12 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | See the License for the specific language governing permissions and 14 | limitations under the License. 15 | */ 16 | 17 | package jdownloader 18 | 19 | import ( 20 | "bytes" 21 | "crypto/aes" 22 | "crypto/cipher" 23 | "crypto/hmac" 24 | "crypto/sha256" 25 | "encoding/base64" 26 | "fmt" 27 | "strings" 28 | ) 29 | 30 | func decode(body []byte, key [32]byte) ([]byte, error) { 31 | decoded, err := base64.StdEncoding.DecodeString(string(body)) 32 | if err != nil { 33 | return nil, fmt.Errorf("can't decode base64 string: %v", err) 34 | } 35 | return decrypt(decoded, key) 36 | } 37 | 38 | func decrypt(ciphertext []byte, key [32]byte) ([]byte, error) { 39 | block, err := aes.NewCipher(key[16:]) 40 | if err != nil { 41 | return nil, err 42 | } 43 | decrypter := cipher.NewCBCDecrypter(block, key[:16]) 44 | plaintext := make([]byte, len(ciphertext)) 45 | decrypter.CryptBlocks(plaintext, ciphertext) 46 | plaintext = trimPKCS5(plaintext) 47 | return plaintext, nil 48 | } 49 | 50 | // encrypt Encrypts plaintext using AES-128 with provided key 51 | // first half of key is IV and second half is actual key 52 | func encrypt(plaintext []byte, key [32]byte) ([]byte, error) { 53 | block, err := aes.NewCipher(key[16:]) 54 | if err != nil { 55 | return nil, err 56 | } 57 | encrypter := cipher.NewCBCEncrypter(block, key[:16]) 58 | paddedPlainText := padPKCS7(plaintext, encrypter.BlockSize()) 59 | ciphertext := make([]byte, len(paddedPlainText)) 60 | encrypter.CryptBlocks(ciphertext, paddedPlainText) 61 | return ciphertext, nil 62 | } 63 | 64 | // sign Signs uri with key using Sha256HMAC 65 | func sign(uri string, key []byte) string { 66 | h := hmac.New(sha256.New, key) 67 | h.Write([]byte(uri)) 68 | return fmt.Sprintf("%x", h.Sum(nil)) 69 | } 70 | 71 | func createSecret(email string, password string, domain string) [32]byte { 72 | return sha256.Sum256([]byte(fmt.Sprintf("%s%s%s", strings.ToLower(email), password, domain))) 73 | } 74 | 75 | func hashConfigKeys(email string, password string) string { 76 | h := sha256.New() 77 | h.Write([]byte(email)) 78 | h.Write([]byte(password)) 79 | return base64.StdEncoding.EncodeToString(h.Sum(nil)) 80 | } 81 | 82 | func updateToken(newToken []byte, existing [32]byte) [32]byte { 83 | var buff bytes.Buffer 84 | buff.Write(existing[:]) 85 | buff.Write(newToken) 86 | return sha256.Sum256(buff.Bytes()) 87 | } 88 | 89 | func padPKCS7(topad []byte, blockSize int) []byte { 90 | padding := blockSize - len(topad)%blockSize 91 | padded := bytes.Repeat([]byte{byte(padding)}, padding) 92 | return append(topad, padded...) 93 | } 94 | 95 | func trimPKCS5(text []byte) []byte { 96 | padding := text[len(text)-1] 97 | return text[:len(text)-int(padding)] 98 | } 99 | -------------------------------------------------------------------------------- /jdownloader/client_mock.go: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright 2022 Richard Kosegi 3 | 4 | Licensed under the Apache License, Version 2.0 (the "License"); 5 | you may not use this file except in compliance with the License. 6 | You may obtain a copy of the License at 7 | 8 | http://www.apache.org/licenses/LICENSE-2.0 9 | 10 | Unless required by applicable law or agreed to in writing, software 11 | distributed under the License is distributed on an "AS IS" BASIS, 12 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | See the License for the specific language governing permissions and 14 | limitations under the License. 15 | */ 16 | 17 | package jdownloader 18 | 19 | import ( 20 | "fmt" 21 | ) 22 | 23 | type MockClient struct { 24 | devs *[]DeviceInfo 25 | connected bool 26 | } 27 | 28 | func (m *MockClient) SetDevices(devs *[]DeviceInfo) { 29 | m.devs = devs 30 | } 31 | 32 | func (m *MockClient) Connect() error { 33 | m.connected = true 34 | return nil 35 | } 36 | 37 | func (m *MockClient) IsConnected() bool { 38 | return m.connected 39 | } 40 | 41 | func (m *MockClient) Reconnect() error { 42 | return nil 43 | } 44 | 45 | func (m *MockClient) Disconnect() error { 46 | m.connected = false 47 | return nil 48 | } 49 | 50 | func (m *MockClient) ListDevices() (*[]DeviceInfo, error) { 51 | return m.devs, nil 52 | } 53 | 54 | func (m *MockClient) Device(name string) (Device, error) { 55 | for _, d := range *m.devs { 56 | if d.Name == name { 57 | return &MockDevice{ 58 | id: name, 59 | }, nil 60 | } 61 | } 62 | return nil, fmt.Errorf("no such device: %s", name) 63 | } 64 | 65 | func (m *MockClient) ConfigHash() string { 66 | return "123" 67 | } 68 | 69 | func NewMockClient() *MockClient { 70 | return &MockClient{ 71 | devs: &[]DeviceInfo{}, 72 | } 73 | } 74 | 75 | type MockDevice struct { 76 | Device 77 | links []DownloadLink 78 | id string 79 | } 80 | 81 | func (d *MockDevice) LinkGrabber() LinkGrabber { 82 | // TODO implement me 83 | panic("implement me") 84 | } 85 | 86 | func (d *MockDevice) Downloader() Downloader { 87 | return &MockDownloader{ 88 | dev: *d, 89 | } 90 | } 91 | 92 | func (d *MockDevice) Name() string { 93 | // TODO implement me 94 | panic("implement me") 95 | } 96 | 97 | func (d *MockDevice) Id() string { 98 | return d.id 99 | } 100 | 101 | func (d *MockDevice) Status() string { 102 | return "UNKNOWN" 103 | } 104 | 105 | func (d *MockDevice) ConnectionInfo() (*DirectConnectionInfo, error) { 106 | return &DirectConnectionInfo{}, nil 107 | } 108 | 109 | func (d *MockDevice) Packages(...LinkGrabberQueryPackagesOptions) (*[]DownloadPackage, error) { 110 | // TODO implement me 111 | panic("implement me") 112 | } 113 | 114 | func (d *MockDevice) Links(...DownloadQueryLinksOptions) (*[]DownloadLink, error) { 115 | // TODO implement me 116 | panic("implement me") 117 | } 118 | 119 | func (d *MockDevice) SetLinks(links *[]DownloadLink) { 120 | d.links = *links 121 | } 122 | 123 | type MockDownloader struct { 124 | dev MockDevice 125 | } 126 | 127 | func (dw *MockDownloader) Remove([]int64, []int64) error { 128 | return nil 129 | } 130 | 131 | func (dw *MockDownloader) Packages(...LinkGrabberQueryPackagesOptions) (*[]DownloadPackage, error) { 132 | // TODO implement me 133 | panic("implement me") 134 | } 135 | 136 | func (dw *MockDownloader) Links(...DownloadQueryLinksOptions) (*[]DownloadLink, error) { 137 | return &dw.dev.links, nil 138 | } 139 | 140 | func (dw *MockDownloader) Start() (bool, error) { 141 | // TODO implement me 142 | panic("implement me") 143 | } 144 | 145 | func (dw *MockDownloader) Stop() (bool, error) { 146 | // TODO implement me 147 | panic("implement me") 148 | } 149 | 150 | func (dw *MockDownloader) Pause() (bool, error) { 151 | return false, nil 152 | } 153 | 154 | func (dw *MockDownloader) Speed() (*DownloadSpeedInfo, error) { 155 | return nil, nil 156 | } 157 | 158 | func (dw *MockDownloader) Force([]int64, []int64) error { 159 | return nil 160 | } 161 | 162 | func (dw *MockDownloader) State() (*DownloadState, error) { 163 | return nil, nil 164 | } 165 | -------------------------------------------------------------------------------- /jdownloader/device.go: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright 2022 Richard Kosegi 3 | 4 | Licensed under the Apache License, Version 2.0 (the "License"); 5 | you may not use this file except in compliance with the License. 6 | You may obtain a copy of the License at 7 | 8 | http://www.apache.org/licenses/LICENSE-2.0 9 | 10 | Unless required by applicable law or agreed to in writing, software 11 | distributed under the License is distributed on an "AS IS" BASIS, 12 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | See the License for the specific language governing permissions and 14 | limitations under the License. 15 | */ 16 | 17 | package jdownloader 18 | 19 | import ( 20 | "encoding/base64" 21 | "encoding/json" 22 | "fmt" 23 | "log/slog" 24 | "net/http" 25 | "net/url" 26 | ) 27 | 28 | type DirectConnectionPort struct { 29 | Ip *string `json:"ip"` 30 | Port *int `json:"port"` 31 | } 32 | 33 | type DirectConnectionInfo struct { 34 | Mode *string `json:"mode"` 35 | Ports *[]DirectConnectionPort `json:"infos"` 36 | RebindProtectionDetected *bool `json:"rebindProtectionDetected"` 37 | } 38 | 39 | type Device interface { 40 | // LinkGrabber gets reference to LinkGrabber interface 41 | LinkGrabber() LinkGrabber 42 | // Downloader gets reference to Downloader interface 43 | Downloader() Downloader 44 | // Name gets this device's name 45 | Name() string 46 | // Id gets this device's ID 47 | Id() string 48 | // Status get this device's status 49 | Status() string 50 | // ConnectionInfo gets direct connection info 51 | ConnectionInfo() (*DirectConnectionInfo, error) 52 | } 53 | 54 | type jDevice struct { 55 | id string 56 | name string 57 | status string 58 | log *slog.Logger 59 | impl *jDownloaderClient 60 | } 61 | 62 | func (d *jDevice) LinkGrabber() LinkGrabber { 63 | return newLinkGrabber(d.log, d) 64 | } 65 | 66 | func (d *jDevice) Downloader() Downloader { 67 | return newDownloadController(d.log, d) 68 | } 69 | 70 | func (d *jDevice) Name() string { 71 | return d.name 72 | } 73 | 74 | func (d *jDevice) Status() string { 75 | return d.status 76 | } 77 | 78 | func (d *jDevice) Id() string { 79 | return d.id 80 | } 81 | 82 | func (d *jDevice) ConnectionInfo() (*DirectConnectionInfo, error) { 83 | data, err := d.doDevice("/device/getDirectConnectionInfos", false) 84 | if err != nil { 85 | return nil, err 86 | } 87 | info := &DirectConnectionInfo{} 88 | err = toObj(data, info) 89 | if err != nil { 90 | return nil, err 91 | } 92 | return info, nil 93 | } 94 | 95 | func serializeParams(marshal bool, params ...interface{}) ([]interface{}, error) { 96 | if len(params) == 1 && params[0] == nil { 97 | return nil, nil 98 | } 99 | ps := make([]interface{}, 0) 100 | for _, p := range params { 101 | if marshal { 102 | s, err := json.Marshal(p) 103 | if err != nil { 104 | return nil, fmt.Errorf("unable to marshal parameter into json string: %v:\n%v", err, p) 105 | } 106 | ps = append(ps, string(s)) 107 | } else { 108 | ps = append(ps, p) 109 | } 110 | } 111 | return ps, nil 112 | } 113 | 114 | func (d *jDevice) doDevice(action string, marshal bool, params ...interface{}) (_ *DataResponse, err error) { 115 | // Ensure impl is not nil 116 | if d.impl == nil { 117 | return nil, fmt.Errorf("device implementation is not initialized") 118 | } 119 | 120 | err = d.impl.reconnectIfNecessary() 121 | if err != nil { 122 | return nil, err 123 | } 124 | qs := fmt.Sprintf("t_%s_%s%s", url.QueryEscape(d.impl.sessionToken), url.QueryEscape(d.id), action) 125 | p, err := serializeParams(marshal, params...) 126 | if err != nil { 127 | return nil, err 128 | } 129 | data := &actionRequest{ 130 | Url: action, 131 | Params: p, 132 | RequestId: d.impl.nextRid(), 133 | ApiVersion: 1, 134 | } 135 | plaintext, err := json.Marshal(data) 136 | if err != nil { 137 | return nil, err 138 | } 139 | ciphertext, err := encrypt(plaintext, d.impl.deviceEncryptionToken) 140 | if err != nil { 141 | return nil, err 142 | } 143 | payload := base64.StdEncoding.EncodeToString(ciphertext) 144 | body, err := d.impl.do(fmt.Sprintf("/%s", qs), http.MethodPost, []byte(payload), d.impl.deviceEncryptionToken) 145 | if err != nil { 146 | return nil, err 147 | } 148 | result := &DataResponse{} 149 | err = json.Unmarshal(body, result) 150 | if err != nil { 151 | return nil, err 152 | } 153 | return result, nil 154 | } 155 | 156 | var _ Device = &jDevice{} 157 | -------------------------------------------------------------------------------- /jdownloader/settings.go: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright 2022 Richard Kosegi 3 | 4 | Licensed under the Apache License, Version 2.0 (the "License"); 5 | you may not use this file except in compliance with the License. 6 | You may obtain a copy of the License at 7 | 8 | http://www.apache.org/licenses/LICENSE-2.0 9 | 10 | Unless required by applicable law or agreed to in writing, software 11 | distributed under the License is distributed on an "AS IS" BASIS, 12 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | See the License for the specific language governing permissions and 14 | limitations under the License. 15 | */ 16 | 17 | package jdownloader 18 | 19 | const ( 20 | GeneralSettingsFile = "org.jdownloader.settings.GeneralSettings.json" 21 | MyJdownloaderSettingsfile = "org.jdownloader.api.myjdownloader.MyJDownloaderSettings.json" 22 | LinkGrabberSettingsFile = "org.jdownloader.gui.views.linkgrabber.addlinksdialog.LinkgrabberSettings.json" 23 | CustomProxyListFile = "org.jdownloader.settings.InternetConnectionSettings.customproxylist.json" 24 | ) 25 | 26 | type GeneralSettings struct { 27 | MaxSimultaneDownloadsPerHost int `json:"maxsimultanedownloadsperhost"` 28 | DefaultDownloadFolder string `json:"defaultdownloadfolder"` 29 | OnSkipDueToAlreadyExistsAction string `json:"onskipduetoalreadyexistsaction"` 30 | } 31 | 32 | type LinkGrabberSettings struct { 33 | AutoExtractionEnabled bool `json:"autoextractionenabled"` 34 | LinkGrabberAutoStartEnabled bool `json:"linkgrabberautostartenabled"` 35 | VariousPackageEnabled bool `json:"variouspackageenabled"` 36 | LatestDownloadDestinationFolder string `json:"latestdownloaddestinationfolder"` 37 | LinkGrabberAddAtTop bool `json:"linkgrabberaddattop"` 38 | LinkGrabberAutoConfirmEnabled bool `json:"linkgrabberautoconfirmenabled"` 39 | } 40 | 41 | type MyJdownloaderSettings struct { 42 | UniqueDeviceIdSaltV2 string `json:"uniquedeviceidsaltv2"` 43 | AutoConnectEnabledV2 bool `json:"autoconnectenabledv2"` 44 | Password string `json:"password"` 45 | DebugEnabled bool `json:"debugenabled"` 46 | UniqueDeviceId *string `json:"uniquedeviceid"` 47 | ServerHost string `json:"serverhost"` 48 | DirectConnectMode string `json:"directconnectmode"` 49 | UniqueDeviceIdV2 string `json:"uniquedeviceidv2"` 50 | Email string `json:"email"` 51 | LastError string `json:"lasterror"` 52 | DeviceName string `json:"devicename"` 53 | LastLocalPort int `json:"lastlocalport"` 54 | } 55 | 56 | func DefaultGeneralSettings() *GeneralSettings { 57 | return &GeneralSettings{ 58 | MaxSimultaneDownloadsPerHost: 1, 59 | DefaultDownloadFolder: "download", 60 | OnSkipDueToAlreadyExistsAction: "SKIP_FILE", 61 | } 62 | } 63 | 64 | func DefaultMyJdownloaderSettings() *MyJdownloaderSettings { 65 | return &MyJdownloaderSettings{ 66 | AutoConnectEnabledV2: true, 67 | DebugEnabled: false, 68 | LastError: "NONE", 69 | ServerHost: "api.jdownloader.org", 70 | DirectConnectMode: "LAN", 71 | } 72 | } 73 | 74 | func DefaultLinkGrabberSettings() *LinkGrabberSettings { 75 | return &LinkGrabberSettings{ 76 | AutoExtractionEnabled: true, 77 | LinkGrabberAutoStartEnabled: true, 78 | VariousPackageEnabled: true, 79 | LatestDownloadDestinationFolder: "download", 80 | LinkGrabberAddAtTop: false, 81 | LinkGrabberAutoConfirmEnabled: false, 82 | } 83 | } 84 | 85 | type ProxyServer struct { 86 | Type string `json:"type"` 87 | Address *string `json:"address"` 88 | Port int `json:"port"` 89 | PreferNativeImplementation bool `json:"preferNativeImplementation"` 90 | ResolveHostName bool `json:"resolveHostName"` 91 | Username *string `json:"username"` 92 | ConnectMethodPrefered bool `json:"connectMethodPrefered"` 93 | Password *string `json:"password"` 94 | } 95 | 96 | type ProxyFilter struct { 97 | Type string `json:"type"` 98 | Entries *[]string `json:"entries"` 99 | } 100 | 101 | type ProxyServerEntry struct { 102 | Filter *ProxyFilter `json:"filter"` 103 | Enabled bool `json:"enabled"` 104 | Pac bool `json:"pac"` 105 | ReconnectSupported bool `json:"reconnectSupported"` 106 | RangeRequestsSupported bool `json:"rangeRequestsSupported"` 107 | Proxy *ProxyServer `json:"proxy"` 108 | } 109 | 110 | func DefaultProxyServerEntry() *ProxyServerEntry { 111 | return &ProxyServerEntry{ 112 | Enabled: false, 113 | Pac: false, 114 | ReconnectSupported: false, 115 | RangeRequestsSupported: false, 116 | Proxy: &ProxyServer{ 117 | Type: "NONE", 118 | Address: nil, 119 | Port: 80, 120 | PreferNativeImplementation: false, 121 | ResolveHostName: false, 122 | Username: nil, 123 | ConnectMethodPrefered: false, 124 | Password: nil, 125 | }, 126 | } 127 | } 128 | 129 | func DefaultProxyList() []*ProxyServerEntry { 130 | return []*ProxyServerEntry{ 131 | DefaultProxyServerEntry(), 132 | } 133 | } 134 | -------------------------------------------------------------------------------- /jdownloader/client.go: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright 2022 Richard Kosegi 3 | 4 | Licensed under the Apache License, Version 2.0 (the "License"); 5 | you may not use this file except in compliance with the License. 6 | You may obtain a copy of the License at 7 | 8 | http://www.apache.org/licenses/LICENSE-2.0 9 | 10 | Unless required by applicable law or agreed to in writing, software 11 | distributed under the License is distributed on an "AS IS" BASIS, 12 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | See the License for the specific language governing permissions and 14 | limitations under the License. 15 | */ 16 | 17 | package jdownloader 18 | 19 | import ( 20 | "bytes" 21 | "encoding/hex" 22 | "encoding/json" 23 | "fmt" 24 | "io" 25 | "log/slog" 26 | "net/http" 27 | "strconv" 28 | "strings" 29 | "sync" 30 | "sync/atomic" 31 | "time" 32 | ) 33 | 34 | const ( 35 | apiEndpoint = "https://api.jdownloader.org" 36 | mediaType = "application/aesjson-jd; charset=utf-8" 37 | appName = "jdownloader-clientgo" 38 | paramSessionToken = "sessiontoken" 39 | ) 40 | 41 | var ( 42 | yes = true 43 | ) 44 | 45 | type sessionInfo struct { 46 | SessionToken string `json:"sessiontoken"` 47 | RegainToken string `json:"regaintoken"` 48 | ResponseIdentifier 49 | } 50 | 51 | type jDownloaderClient struct { 52 | connected bool 53 | email string 54 | counter int64 55 | appKey string 56 | loginSecret [32]byte 57 | deviceSecret [32]byte 58 | serverEncryptionToken [32]byte 59 | deviceEncryptionToken [32]byte 60 | client http.Client 61 | sessionToken string 62 | regainToken string 63 | lock sync.Mutex 64 | log *slog.Logger 65 | configHash string 66 | lastCall time.Time 67 | lastCallLock sync.Mutex 68 | endpoint string 69 | afterCallFn func(error, time.Duration) 70 | } 71 | 72 | type ClientOption func(c *jDownloaderClient) 73 | 74 | func ClientOptionApiEndpoint(url string) ClientOption { 75 | return func(c *jDownloaderClient) { 76 | c.endpoint = url 77 | } 78 | } 79 | 80 | func ClientOptionApiCallbacks(afterCallFn func(error, time.Duration)) ClientOption { 81 | return func(c *jDownloaderClient) { 82 | c.afterCallFn = afterCallFn 83 | } 84 | } 85 | 86 | func ClientOptionTimeout(timeout time.Duration) ClientOption { 87 | return func(c *jDownloaderClient) { 88 | c.client.Timeout = timeout 89 | } 90 | } 91 | 92 | func ClientOptionAppKey(app string) ClientOption { 93 | return func(c *jDownloaderClient) { 94 | c.appKey = app 95 | } 96 | } 97 | 98 | func (j *jDownloaderClient) ConfigHash() string { 99 | return j.configHash 100 | } 101 | 102 | func (j *jDownloaderClient) IsConnected() bool { 103 | return j.connected 104 | } 105 | 106 | func (j *jDownloaderClient) Device(name string) (_ Device, err error) { 107 | dl, err := j.ListDevices() 108 | if err != nil { 109 | return nil, err 110 | } 111 | var dev *DeviceInfo 112 | for _, d := range *dl { 113 | if d.Name == name { 114 | dev = &d 115 | break 116 | } 117 | } 118 | if dev == nil { 119 | return nil, fmt.Errorf("no such device: %s", name) 120 | } 121 | return &jDevice{ 122 | id: dev.Id, 123 | name: dev.Name, 124 | log: j.log.With("device", dev.Name), 125 | impl: j, 126 | status: dev.Status, 127 | }, nil 128 | } 129 | 130 | func (j *jDownloaderClient) Connect() (err error) { 131 | j.serverEncryptionToken = j.loginSecret 132 | j.deviceEncryptionToken = j.deviceSecret 133 | j.connected = false 134 | 135 | data, err := j.doServer("/my/connect", http.MethodPost, []string{ 136 | qp("email", strings.ToLower(j.email)), 137 | qp("appkey", strings.ToLower(j.appKey)), 138 | }, nil, j.loginSecret) 139 | if err != nil { 140 | return fmt.Errorf("API doServer failed: %v", err) 141 | } 142 | session := &sessionInfo{} 143 | err = json.Unmarshal(data, session) 144 | if err != nil { 145 | return fmt.Errorf("invalid payload received from server: %v", err) 146 | } 147 | if j.currentRid() != session.ResponseID { 148 | return fmt.Errorf("mismatched RID, expected: %d, actual: %d", j.currentRid(), session.ResponseID) 149 | } 150 | newToken, err := hex.DecodeString(session.SessionToken) 151 | if err != nil { 152 | return fmt.Errorf("unable to decode session token from response: %v", err) 153 | } 154 | j.sessionToken = session.SessionToken 155 | j.regainToken = session.RegainToken 156 | j.updateTokens(newToken) 157 | j.connected = true 158 | return nil 159 | } 160 | 161 | func (j *jDownloaderClient) ListDevices() (_ *[]DeviceInfo, err error) { 162 | err = j.reconnectIfNecessary() 163 | if err != nil { 164 | return nil, err 165 | } 166 | data, err := j.doServer("/my/listdevices", http.MethodGet, []string{ 167 | qp(paramSessionToken, j.sessionToken), 168 | }, nil, j.serverEncryptionToken) 169 | if err != nil { 170 | return nil, err 171 | } 172 | dl := &DeviceList{} 173 | err = json.Unmarshal(data, dl) 174 | if err != nil { 175 | return nil, err 176 | } 177 | return &dl.List, nil 178 | } 179 | 180 | func (j *jDownloaderClient) Reconnect() (err error) { 181 | data, err := j.doServer("/my/reconnect", http.MethodGet, []string{ 182 | qp(paramSessionToken, j.sessionToken), 183 | qp("regaintoken", j.regainToken), 184 | }, nil, j.serverEncryptionToken) 185 | if err != nil { 186 | return err 187 | } 188 | session := &sessionInfo{} 189 | err = json.Unmarshal(data, session) 190 | if err != nil { 191 | return fmt.Errorf("invalid payload received from server: %v", err) 192 | } 193 | if j.currentRid() != session.ResponseID { 194 | return fmt.Errorf("mismatched RID, expected: %d, actual: %d", j.currentRid(), session.ResponseID) 195 | } 196 | newToken, err := hex.DecodeString(session.SessionToken) 197 | if err != nil { 198 | return fmt.Errorf("unable to decode session token from response: %v", err) 199 | } 200 | j.sessionToken = session.SessionToken 201 | j.regainToken = session.RegainToken 202 | j.updateTokens(newToken) 203 | j.connected = true 204 | return nil 205 | } 206 | 207 | func (j *jDownloaderClient) Disconnect() error { 208 | _, err := j.doServer("/my/disconnect", http.MethodPost, []string{ 209 | qp(paramSessionToken, j.sessionToken), 210 | }, nil, j.serverEncryptionToken) 211 | return err 212 | } 213 | 214 | func (j *jDownloaderClient) updateTokens(newToken []byte) { 215 | j.serverEncryptionToken = updateToken(newToken, j.serverEncryptionToken) 216 | j.deviceEncryptionToken = updateToken(newToken, j.deviceEncryptionToken) 217 | } 218 | 219 | func (j *jDownloaderClient) reconnectIfNecessary() error { 220 | j.lastCallLock.Lock() 221 | defer j.lastCallLock.Unlock() 222 | if !j.connected || time.Since(j.lastCall).Seconds() > 30 { 223 | j.lastCall = time.Now() 224 | return j.Connect() 225 | } 226 | return nil 227 | } 228 | 229 | func (j *jDownloaderClient) do(path string, method string, data []byte, key [32]byte) (_ []byte, err error) { 230 | defer j.onApiDone(err, time.Now()) 231 | j.lock.Lock() 232 | defer j.lock.Unlock() 233 | uri := fmt.Sprintf("%s%s", j.endpoint, path) 234 | var resp *http.Response 235 | j.log.Debug("Request", "method", method, "uri", uri, "rid", j.currentRid()) 236 | if http.MethodGet == method { 237 | resp, err = j.client.Get(uri) 238 | } else { 239 | if data != nil { 240 | resp, err = j.client.Post(uri, mediaType, bytes.NewBuffer(data)) 241 | } else { 242 | resp, err = j.client.Post(uri, mediaType, nil) 243 | } 244 | } 245 | if err != nil { 246 | return nil, err 247 | } 248 | j.log.Debug("Response", "status", resp.StatusCode, "rid", j.currentRid()) 249 | defer bodycloser(resp.Body, j.log) 250 | body, err := io.ReadAll(resp.Body) 251 | if err != nil { 252 | return nil, fmt.Errorf("unable to fully consume response body: %v", err) 253 | } 254 | if resp.StatusCode != http.StatusOK { 255 | e := parseError(body, key, j.log) 256 | return nil, fmt.Errorf("API doServer failed: %v", e) 257 | } else { 258 | return decode(body, key) 259 | } 260 | } 261 | 262 | func (j *jDownloaderClient) doServer(path string, method string, args []string, data []byte, key [32]byte) (_ []byte, err error) { 263 | if args == nil { 264 | args = make([]string, 0) 265 | } 266 | args = append(args, qp("rid", strconv.FormatInt(j.nextRid(), 10))) 267 | uri := strings.Join(args, "&") 268 | uri = fmt.Sprintf("%s?%s", path, uri) 269 | uri = fmt.Sprintf("%s&signature=%s", uri, sign(uri, key[:])) 270 | return j.do(uri, method, data, key) 271 | } 272 | 273 | func (j *jDownloaderClient) nextRid() int64 { 274 | return atomic.AddInt64(&j.counter, 1) 275 | } 276 | 277 | func (j *jDownloaderClient) currentRid() int64 { 278 | return j.counter 279 | } 280 | 281 | func (j *jDownloaderClient) onApiDone(err error, start time.Time) { 282 | if j.afterCallFn != nil { 283 | j.afterCallFn(err, time.Since(start)) 284 | } 285 | } 286 | 287 | var _ JdClient = &jDownloaderClient{} 288 | -------------------------------------------------------------------------------- /jdownloader/downloader.go: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright 2022 Richard Kosegi 3 | 4 | Licensed under the Apache License, Version 2.0 (the "License"); 5 | you may not use this file except in compliance with the License. 6 | You may obtain a copy of the License at 7 | 8 | http://www.apache.org/licenses/LICENSE-2.0 9 | 10 | Unless required by applicable law or agreed to in writing, software 11 | distributed under the License is distributed on an "AS IS" BASIS, 12 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | See the License for the specific language governing permissions and 14 | limitations under the License. 15 | */ 16 | 17 | package jdownloader 18 | 19 | import ( 20 | "errors" 21 | "log/slog" 22 | ) 23 | 24 | type DownloadState struct { 25 | State *string `json:"state,omitempty"` 26 | } 27 | 28 | type DownloadSpeedInfo struct { 29 | Speed *float64 `json:"speed,omitempty"` 30 | } 31 | 32 | type DownloadQueryLinksParams struct { 33 | BytesTotal *bool `json:"bytesTotal,omitempty"` 34 | Comment *bool `json:"comment,omitempty"` 35 | Status *bool `json:"status,omitempty"` 36 | Enabled *bool `json:"enabled,omitempty"` 37 | MaxResults *int `json:"maxResults,omitempty"` 38 | StartAt *int `json:"startAt,omitempty"` 39 | Host *bool `json:"host,omitempty"` 40 | BytesLoaded *bool `json:"bytesLoaded,omitempty"` 41 | Speed *bool `json:"speed,omitempty"` 42 | Eta *bool `json:"eta,omitempty"` 43 | Finished *bool `json:"finished,omitempty"` 44 | FinishedDate *bool `json:"finishedDate,omitempty"` 45 | Running *bool `json:"running,omitempty"` 46 | Skipped *bool `json:"skipped,omitempty"` 47 | ExtractionStatus *bool `json:"extractionStatus,omitempty"` 48 | PackageUUIDs *[]int64 `json:"packageUUIDs"` 49 | Url *bool `json:"url"` 50 | Priority *bool `json:"priority"` 51 | } 52 | 53 | type DownloadQueryLinksOptions func(params *DownloadQueryLinksParams) 54 | 55 | func DefaultDownloadQueryLinksOptions() DownloadQueryLinksOptions { 56 | return func(params *DownloadQueryLinksParams) { 57 | params.BytesLoaded = &yes 58 | params.BytesTotal = &yes 59 | params.Comment = &yes 60 | params.Status = &yes 61 | params.Enabled = &yes 62 | params.Host = &yes 63 | params.Speed = &yes 64 | params.Eta = &yes 65 | params.Finished = &yes 66 | params.FinishedDate = &yes 67 | params.Running = &yes 68 | params.Skipped = &yes 69 | params.ExtractionStatus = &yes 70 | params.Url = &yes 71 | params.Priority = &yes 72 | } 73 | } 74 | 75 | type DownloadLink struct { 76 | AddedDate *int64 `json:"addedDate,omitempty"` 77 | BytesTotal *int64 `json:"bytesTotal,omitempty"` 78 | BytesLoaded *int64 `json:"bytesLoaded,omitempty"` 79 | Comment *string `json:"comment,omitempty"` 80 | DownloadPassword *string `json:"downloadPassword"` 81 | Enabled *bool `json:"enabled,omitempty"` 82 | Eta *int64 `json:"eta,omitempty"` 83 | ExtractionStatus *string `json:"extractionStatus"` 84 | Finished *bool `json:"finished,omitempty"` 85 | FinishedDate *int64 `json:"finishedDate,omitempty"` 86 | Host *string `json:"host,omitempty"` 87 | Name *string `json:"name,omitempty"` 88 | PackageUuid *int64 `json:"packageUUID,omitempty"` 89 | Priority *string `json:"priority"` 90 | Skipped *bool `json:"skipped,omitempty"` 91 | Speed *float64 `json:"speed,omitempty"` 92 | Status *string `json:"status,omitempty"` 93 | StatusIconKey *string `json:"statusIconKey,omitempty"` 94 | Url *string `json:"url,omitempty"` 95 | Uuid *int64 `json:"uuid,omitempty"` 96 | } 97 | 98 | type DownloadPackage struct { 99 | ActiveTask *string `json:"activeTask"` 100 | BytesLoaded *int64 `json:"bytesLoaded,omitempty"` 101 | BytesTotal *int64 `json:"bytesTotal,omitempty"` 102 | ChildCount *int `json:"childCount,omitempty"` 103 | Comment *string `json:"comment"` 104 | DownloadPassword *string `json:"downloadPassword"` 105 | Enabled *bool `json:"enabled,omitempty"` 106 | Eta *int64 `json:"eta,omitempty"` 107 | Finished *bool `json:"finished,omitempty"` 108 | Hosts *[]string `json:"hosts,omitempty"` 109 | Name *string `json:"name"` 110 | Priority *string `json:"priority"` 111 | Running *bool `json:"running"` 112 | SaveTo *string `json:"saveTo,omitempty"` 113 | Speed *float64 `json:"speed,omitempty"` 114 | Status *string `json:"status"` 115 | StatusIconKey *string `json:"statusIconKey"` 116 | Uuid *int64 `json:"uuid,omitempty"` 117 | } 118 | 119 | type Downloader interface { 120 | // Packages queries information about existing packages 121 | Packages(...LinkGrabberQueryPackagesOptions) (*[]DownloadPackage, error) 122 | // Links queries information about existing links 123 | Links(...DownloadQueryLinksOptions) (*[]DownloadLink, error) 124 | // Remove removes given links and/or packages 125 | Remove([]int64, []int64) error 126 | // Start starts download process 127 | Start() (bool, error) 128 | // Stop stops download process 129 | Stop() (bool, error) 130 | // Pause pauses download process 131 | Pause() (bool, error) 132 | // Speed get current download speed 133 | Speed() (*DownloadSpeedInfo, error) 134 | // Force forces download of given links/packages 135 | Force([]int64, []int64) error 136 | // State gets current state of download process 137 | State() (*DownloadState, error) 138 | } 139 | 140 | type downloadController struct { 141 | l *slog.Logger 142 | d *jDevice 143 | } 144 | 145 | func newDownloadController(log *slog.Logger, d *jDevice) Downloader { 146 | return &downloadController{ 147 | d: d, 148 | l: log.With("component", "download"), 149 | } 150 | } 151 | 152 | func (dc *downloadController) Links(options ...DownloadQueryLinksOptions) (*[]DownloadLink, error) { 153 | params := &DownloadQueryLinksParams{} 154 | if len(options) == 0 { 155 | defaults := DefaultDownloadQueryLinksOptions() 156 | options = append(options, defaults) 157 | } 158 | for _, opt := range options { 159 | opt(params) 160 | } 161 | data, err := dc.d.doDevice("/downloadsV2/queryLinks", true, params) 162 | if err != nil { 163 | return nil, err 164 | } 165 | items := make([]DownloadLink, 0) 166 | err = toObj(data, &items) 167 | if err != nil { 168 | return nil, err 169 | } 170 | return &items, nil 171 | } 172 | 173 | func (dc *downloadController) Packages(options ...LinkGrabberQueryPackagesOptions) (*[]DownloadPackage, error) { 174 | params := &QueryPackagesParams{} 175 | if len(options) == 0 { 176 | options = append(options, QueryPackagesOptionDefault()) 177 | } 178 | for _, opt := range options { 179 | opt(params) 180 | } 181 | data, err := dc.d.doDevice("/downloadsV2/queryPackages", true, params) 182 | if err != nil { 183 | return nil, err 184 | } 185 | items := make([]DownloadPackage, 0) 186 | err = toObj(data, &items) 187 | if err != nil { 188 | return nil, err 189 | } 190 | return &items, nil 191 | } 192 | 193 | func (dc *downloadController) Start() (bool, error) { 194 | data, err := dc.d.doDevice("/downloadcontroller/start", false) 195 | if err != nil { 196 | return false, err 197 | } 198 | return data.Data.(bool), err 199 | } 200 | 201 | func (dc *downloadController) Stop() (bool, error) { 202 | data, err := dc.d.doDevice("/downloadcontroller/stop", false) 203 | if err != nil { 204 | return false, err 205 | } 206 | return data.Data.(bool), err 207 | } 208 | 209 | func (dc *downloadController) Pause() (bool, error) { 210 | data, err := dc.d.doDevice("/downloadcontroller/pause", false) 211 | if err != nil { 212 | return false, err 213 | } 214 | return data.Data.(bool), err 215 | } 216 | 217 | func (dc *downloadController) Speed() (*DownloadSpeedInfo, error) { 218 | data, err := dc.d.doDevice("/downloadcontroller/getSpeedInBps", false) 219 | if err != nil { 220 | return nil, err 221 | } 222 | speed := data.Data.(float64) 223 | return &DownloadSpeedInfo{Speed: &speed}, nil 224 | } 225 | 226 | func (dc *downloadController) Force(linkIds []int64, packageIds []int64) error { 227 | if len(linkIds) == 0 && len(packageIds) == 0 { 228 | return errors.New("one of linkIds or packageIds must not be empty") 229 | } 230 | _, err := dc.d.doDevice("/downloadcontroller/forceDownload", false, linkIds, packageIds) 231 | return err 232 | } 233 | 234 | func (dc *downloadController) Remove(linkIds []int64, packageIds []int64) error { 235 | if len(linkIds) == 0 && len(packageIds) == 0 { 236 | return errors.New("one of linkIds or packageIds must not be empty") 237 | } 238 | _, err := dc.d.doDevice("/downloadsV2/removeLinks", false, linkIds, packageIds) 239 | return err 240 | } 241 | 242 | func (dc *downloadController) State() (*DownloadState, error) { 243 | data, err := dc.d.doDevice("/downloadcontroller/getCurrentState", false) 244 | if err != nil { 245 | return nil, err 246 | } 247 | state := data.Data.(string) 248 | return &DownloadState{State: &state}, nil 249 | } 250 | 251 | var _ Downloader = &downloadController{} 252 | -------------------------------------------------------------------------------- /jdownloader/linkgrabber.go: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright 2022 Richard Kosegi 3 | 4 | Licensed under the Apache License, Version 2.0 (the "License"); 5 | you may not use this file except in compliance with the License. 6 | You may obtain a copy of the License at 7 | 8 | http://www.apache.org/licenses/LICENSE-2.0 9 | 10 | Unless required by applicable law or agreed to in writing, software 11 | distributed under the License is distributed on an "AS IS" BASIS, 12 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | See the License for the specific language governing permissions and 14 | limitations under the License. 15 | */ 16 | 17 | package jdownloader 18 | 19 | import ( 20 | "errors" 21 | "fmt" 22 | "log/slog" 23 | "strings" 24 | ) 25 | 26 | type AddLinksParams struct { 27 | Links string `json:"links"` 28 | Autostart *bool `json:"autostart,omitempty"` 29 | PackageName *string `json:"packageName,omitempty"` 30 | DestinationFolder *string `json:"destinationFolder,omitempty"` 31 | DownloadPassword *string `json:"downloadPassword"` 32 | ExtractPassword *string `json:"extractPassword"` 33 | } 34 | 35 | type AddLinksOptions func(params *AddLinksParams) 36 | 37 | func AddLinksOptionAutostart(autostart bool) AddLinksOptions { 38 | return func(params *AddLinksParams) { 39 | params.Autostart = &autostart 40 | } 41 | } 42 | 43 | func AddLinksOptionPackage(name string) AddLinksOptions { 44 | return func(params *AddLinksParams) { 45 | params.PackageName = &name 46 | } 47 | } 48 | 49 | func AddLinksOptionDestinationDir(name string) AddLinksOptions { 50 | return func(params *AddLinksParams) { 51 | params.DestinationFolder = &name 52 | } 53 | } 54 | 55 | func AddLinksOptionDownloadPassword(pass string) AddLinksOptions { 56 | return func(params *AddLinksParams) { 57 | params.DownloadPassword = &pass 58 | } 59 | } 60 | 61 | func AddLinksOptionExtractPassword(pass string) AddLinksOptions { 62 | return func(params *AddLinksParams) { 63 | params.ExtractPassword = &pass 64 | } 65 | } 66 | 67 | type QueryPackagesParams struct { 68 | AvailableOfflineCount *bool `json:"availableOfflineCount,omitempty"` 69 | AvailableOnlineCount *bool `json:"availableOnlineCount,omitempty"` 70 | AvailableTempUnknownCount *bool `json:"availableTempUnknownCount,omitempty"` 71 | AvailableUnknownCount *bool `json:"availableUnknownCount,omitempty"` 72 | BytesTotal *bool `json:"bytesTotal,omitempty"` 73 | ChildCount *bool `json:"childCount,omitempty"` 74 | Comment *bool `json:"comment,omitempty"` 75 | Enabled *bool `json:"enabled,omitempty"` 76 | Hosts *bool `json:"hosts,omitempty"` 77 | MaxResults *int `json:"maxResults,omitempty"` 78 | PackageUUIDs *[]string `json:"packageUUIDs,omitempty"` 79 | Priority *bool `json:"priority,omitempty"` 80 | SaveTo *bool `json:"saveTo,omitempty"` 81 | StartAt *int `json:"startAt,omitempty"` 82 | Status *bool `json:"status,omitempty"` 83 | } 84 | 85 | type LinkGrabberQueryPackagesOptions func(params *QueryPackagesParams) 86 | 87 | func LinkGrabberQueryPackagesOptionPackageUUIDs(uuids []string) LinkGrabberQueryPackagesOptions { 88 | return func(params *QueryPackagesParams) { 89 | params.PackageUUIDs = &uuids 90 | } 91 | } 92 | 93 | func QueryPackagesOptionDefault() LinkGrabberQueryPackagesOptions { 94 | return func(params *QueryPackagesParams) { 95 | params.AvailableOfflineCount = &yes 96 | params.AvailableOnlineCount = &yes 97 | params.AvailableTempUnknownCount = &yes 98 | params.AvailableUnknownCount = &yes 99 | params.BytesTotal = &yes 100 | params.ChildCount = &yes 101 | params.Comment = &yes 102 | params.Enabled = &yes 103 | params.Hosts = &yes 104 | params.Priority = &yes 105 | params.SaveTo = &yes 106 | params.Status = &yes 107 | } 108 | } 109 | 110 | type CrawledPackage struct { 111 | OnlineCount *int `json:"onlineCount,omitempty"` 112 | OfflineCount *int `json:"offlineCount,omitempty"` 113 | SaveTo *string `json:"saveTo,omitempty"` 114 | UnknownCount *int `json:"unknownCount,omitempty"` 115 | TempUnknownCount *int `json:"tempUnknownCount,omitempty"` 116 | Uuid *int64 `json:"uuid,omitempty"` 117 | BytesTotal *uint64 `json:"bytesTotal,omitempty"` 118 | ChildCount *int `json:"childCount,omitempty"` 119 | Enabled *bool `json:"enabled,omitempty"` 120 | Hosts *[]string `json:"hosts,omitempty"` 121 | Name *string `json:"name"` 122 | } 123 | 124 | type LinkGrabberQueryLinksParams struct { 125 | BytesTotal *bool `json:"bytesTotal,omitempty"` 126 | Comment *bool `json:"comment,omitempty"` 127 | Status *bool `json:"status,omitempty"` 128 | Enabled *bool `json:"enabled,omitempty"` 129 | MaxResults *int `json:"maxResults,omitempty"` 130 | StartAt *int `json:"startAt,omitempty"` 131 | Hosts *bool `json:"hosts,omitempty"` 132 | Url *bool `json:"url,omitempty"` 133 | Availability *bool `json:"availability,omitempty"` 134 | VariantIcon *bool `json:"variantIcon,omitempty"` 135 | VariantName *bool `json:"variantName,omitempty"` 136 | VariantID *bool `json:"variantID,omitempty"` 137 | Variants *bool `json:"variants,omitempty"` 138 | Priority *bool `json:"priority,omitempty"` 139 | } 140 | 141 | type LinkGrabberQueryLinksOptions func(params *LinkGrabberQueryLinksParams) 142 | 143 | func DefaultLinkGrabberQueryLinksOptions() LinkGrabberQueryLinksOptions { 144 | return func(params *LinkGrabberQueryLinksParams) { 145 | params.BytesTotal = &yes 146 | params.Comment = &yes 147 | params.Status = &yes 148 | params.Enabled = &yes 149 | params.Hosts = &yes 150 | params.Url = &yes 151 | params.Availability = &yes 152 | params.VariantIcon = &yes 153 | params.VariantID = &yes 154 | params.Variants = &yes 155 | params.Priority = &yes 156 | } 157 | } 158 | 159 | type CrawledLink struct { 160 | Availability *string `json:"availability,omitempty"` 161 | BytesTotal *uint64 `json:"bytesTotal,omitempty"` 162 | Comment *string `json:"comment,omitempty"` 163 | DownloadPassword *string `json:"downloadPassword,omitempty"` 164 | Enabled *bool `json:"enabled,omitempty"` 165 | Host *string `json:"host,omitempty"` 166 | Name *string `json:"name,omitempty"` 167 | PackageUuid *int64 `json:"packageUUID,omitempty"` 168 | Priority *string `json:"priority,omitempty"` 169 | Url *string `json:"url,omitempty"` 170 | Uuid *int64 `json:"uuid,omitempty"` 171 | Status *string `json:"status,omitempty"` 172 | Variants *bool `json:"variants,omitempty"` 173 | } 174 | 175 | type LinkGrabber interface { 176 | // Clear clears list of links 177 | Clear() error 178 | // Packages gets list of packages 179 | Packages(options ...LinkGrabberQueryPackagesOptions) (*[]CrawledPackage, error) 180 | // Links queries links currently being present 181 | Links(...LinkGrabberQueryLinksOptions) (*[]CrawledLink, error) 182 | // Add adds one or more links into download queue 183 | Add([]string, ...AddLinksOptions) (*DataResponse, error) 184 | // IsCollecting checks if link grabber is collecting links 185 | IsCollecting() (bool, error) 186 | // Remove removes given linksIds and/or packageIds 187 | Remove([]int64, []int64) error 188 | // RenameLink renames link 189 | RenameLink(int64, string) error 190 | } 191 | 192 | type linkGrabber struct { 193 | log *slog.Logger 194 | d *jDevice 195 | } 196 | 197 | func newLinkGrabber(log *slog.Logger, device *jDevice) LinkGrabber { 198 | return &linkGrabber{ 199 | log: log.With("component", "links"), 200 | d: device, 201 | } 202 | } 203 | 204 | func (l *linkGrabber) Links(options ...LinkGrabberQueryLinksOptions) (*[]CrawledLink, error) { 205 | params := &LinkGrabberQueryLinksParams{} 206 | if len(options) == 0 { 207 | defaults := DefaultLinkGrabberQueryLinksOptions() 208 | options = append(options, defaults) 209 | } 210 | for _, opt := range options { 211 | opt(params) 212 | } 213 | data, err := l.d.doDevice("/linkgrabberv2/queryLinks", true, params) 214 | if err != nil { 215 | return nil, err 216 | } 217 | items := make([]CrawledLink, 0) 218 | err = toObj(data, &items) 219 | if err != nil { 220 | return nil, err 221 | } 222 | return &items, nil 223 | } 224 | 225 | func (l *linkGrabber) Packages(options ...LinkGrabberQueryPackagesOptions) (*[]CrawledPackage, error) { 226 | return queryPackages("linkgrabberv2", l.d, options...) 227 | } 228 | 229 | func (l *linkGrabber) Add(links []string, options ...AddLinksOptions) (*DataResponse, error) { 230 | params := &AddLinksParams{ 231 | Links: strings.Join(links, ","), 232 | } 233 | for _, opt := range options { 234 | opt(params) 235 | } 236 | data, err := l.d.doDevice("/linkgrabberv2/addLinks", true, params) 237 | if err != nil { 238 | return nil, err 239 | } 240 | resp := &DataResponse{} 241 | err = toObj(data, resp) 242 | if err != nil { 243 | return nil, err 244 | } 245 | return resp, nil 246 | } 247 | 248 | func (l *linkGrabber) IsCollecting() (bool, error) { 249 | data, err := l.d.doDevice("/linkgrabberv2/isCollecting", false, nil) 250 | if err != nil { 251 | return false, err 252 | } 253 | var res bool 254 | err = toObj(data, &res) 255 | return res, err 256 | } 257 | 258 | func (l *linkGrabber) Remove(linkIds []int64, packageIds []int64) error { 259 | if len(linkIds) == 0 && len(packageIds) == 0 { 260 | return errors.New("One of linkIds or packageIds must not be empty") 261 | } 262 | _, err := l.d.doDevice("/linkgrabberv2/removeLinks", false, linkIds, packageIds) 263 | return err 264 | } 265 | 266 | func (l *linkGrabber) Clear() error { 267 | _, err := l.d.doDevice("/linkgrabberv2/clearList", false) 268 | return err 269 | } 270 | 271 | func (l *linkGrabber) RenameLink(id int64, name string) error { 272 | _, err := l.d.doDevice("/linkgrabberv2/renameLink", false, id, name) 273 | return err 274 | } 275 | 276 | func queryPackages(prefix string, d *jDevice, options ...LinkGrabberQueryPackagesOptions) (*[]CrawledPackage, error) { 277 | params := &QueryPackagesParams{} 278 | if len(options) == 0 { 279 | options = append(options, QueryPackagesOptionDefault()) 280 | } 281 | for _, opt := range options { 282 | opt(params) 283 | } 284 | data, err := d.doDevice(fmt.Sprintf("/%s/queryPackages", prefix), true, params) 285 | if err != nil { 286 | return nil, err 287 | } 288 | items := make([]CrawledPackage, 0) 289 | err = toObj(data, &items) 290 | if err != nil { 291 | return nil, err 292 | } 293 | return &items, nil 294 | } 295 | 296 | var _ LinkGrabber = &linkGrabber{} 297 | -------------------------------------------------------------------------------- /LICENSE.txt: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | --------------------------------------------------------------------------------