├── .github ├── linters │ ├── .golangci.yml │ ├── .dockerfilelintrc │ ├── .hadolint.yaml │ └── .markdown-lint.yml ├── workflows │ ├── snapcraft.yml │ ├── stale.yml │ ├── testing.yml │ ├── builder.yml │ ├── release.yml │ ├── linter.yml │ └── codeql-analysis.yml ├── dependabot.yml └── ISSUE_TEMPLATE │ ├── Bug_report.md │ └── Feature_request.md ├── pkg ├── ipfs-cluster │ ├── doc.go │ └── cluster.go ├── temporal │ ├── temporal.go │ └── doc.go ├── fission │ ├── fission_test.go │ ├── doc.go │ └── fission.go ├── infura │ ├── doc.go │ ├── infura.go │ └── infura_test.go ├── pinata │ ├── doc.go │ ├── pinata.go │ └── pinata_test.go ├── nftstorage │ ├── doc.go │ ├── nftstorage.go │ └── nftstorage_test.go └── web3storage │ ├── doc.go │ ├── web3storage.go │ └── web3storage_test.go ├── http ├── doc.go └── client.go ├── file ├── doc.go ├── multifile_test.go ├── mime.go ├── serialfile.go └── multifile.go ├── .gitignore ├── go.mod ├── snapcraft.yaml ├── .golangci.yml ├── cmd └── ipfs-pinner │ └── main.go ├── pinner.go ├── go.sum ├── Makefile ├── README.md ├── pinner_test.go └── LICENSE /.github/linters/.golangci.yml: -------------------------------------------------------------------------------- 1 | ../../.golangci.yml -------------------------------------------------------------------------------- /.github/linters/.dockerfilelintrc: -------------------------------------------------------------------------------- 1 | rules: 2 | missing_tag: off 3 | -------------------------------------------------------------------------------- /pkg/ipfs-cluster/doc.go: -------------------------------------------------------------------------------- 1 | // https://cluster.ipfs.io/documentation/guides/pinning/ 2 | package ipfsCluster 3 | -------------------------------------------------------------------------------- /pkg/temporal/temporal.go: -------------------------------------------------------------------------------- 1 | package temporal 2 | 3 | // 4 | // func PinFile() {} 5 | // 6 | // func PinHash() {} 7 | -------------------------------------------------------------------------------- /pkg/ipfs-cluster/cluster.go: -------------------------------------------------------------------------------- 1 | package ipfsCluster 2 | 3 | // 4 | // func PinFile() {} 5 | // 6 | // func PinHash() {} 7 | -------------------------------------------------------------------------------- /.github/linters/.hadolint.yaml: -------------------------------------------------------------------------------- 1 | --- 2 | ########################## 3 | ## Hadolint config file ## 4 | ########################## 5 | ignored: 6 | -------------------------------------------------------------------------------- /pkg/fission/fission_test.go: -------------------------------------------------------------------------------- 1 | package fission 2 | 3 | import ( 4 | "testing" 5 | ) 6 | 7 | func TestPinFile(t *testing.T) { 8 | } 9 | 10 | func TestPinHash(t *testing.T) { 11 | } 12 | -------------------------------------------------------------------------------- /pkg/infura/doc.go: -------------------------------------------------------------------------------- 1 | // Infura is a freemium pinning service that doesn't require any additional setup. 2 | // Please bear in mind that Infura is a free service, so there is probably a rate-limiting. 3 | // Docs: https://infura.io/docs 4 | package infura 5 | -------------------------------------------------------------------------------- /pkg/fission/doc.go: -------------------------------------------------------------------------------- 1 | // Fission is a backend-as-a-service that uses IPFS and supports pinning. 2 | // This service requires [signup](https://guide.fission.codes/hosting/fission-accounts). 3 | // https://guide.fission.codes/developers/web-api 4 | package fission 5 | -------------------------------------------------------------------------------- /pkg/pinata/doc.go: -------------------------------------------------------------------------------- 1 | // Pinata is another freemium pinning service. 2 | // It gives you more control over what's uploaded. 3 | // You can delete, label and add custom metadata. This service requires signup. 4 | // https://www.pinata.cloud/documentation 5 | package pinata 6 | -------------------------------------------------------------------------------- /pkg/temporal/doc.go: -------------------------------------------------------------------------------- 1 | // Temporal is an enterprise-grade storage solution featuring an easy to use API that 2 | // can be integrated into any existing application stack. 3 | // https://gateway.temporal.cloud/ipns/docs.api.temporal.cloud/ipfs.html#post-upload-file 4 | package temporal 5 | -------------------------------------------------------------------------------- /http/doc.go: -------------------------------------------------------------------------------- 1 | // Copyright 2021 Wayback Archiver. All rights reserved. 2 | // Use of this source code is governed by the GNU GPL v3 3 | // license that can be found in the LICENSE file. 4 | 5 | /* 6 | Package http implements an HTTP client with retries. 7 | */ 8 | package http // import "github.com/wabarc/ipfs-pinner/http" 9 | -------------------------------------------------------------------------------- /file/doc.go: -------------------------------------------------------------------------------- 1 | // Copyright 2022 Wayback Archiver. All rights reserved. 2 | // Use of this source code is governed by the GNU GPL v3 3 | // license that can be found in the LICENSE file. 4 | 5 | /* 6 | Package file provides a series of file creation functions. 7 | */ 8 | package file // import "github.com/wabarc/ipfs-pinner/file" 9 | -------------------------------------------------------------------------------- /pkg/nftstorage/doc.go: -------------------------------------------------------------------------------- 1 | // NFT.Storage is a long-term storage service designed for off-chain NFT data 2 | // (like metadata, images, and other assets) for up to 31GiB in size. Data is 3 | // content addressed using IPFS, meaning the URL pointing to a piece of data 4 | // (“ipfs://…”) is completely unique to that data. 5 | // 6 | // Docs: https://nft.storage/api-docs/ 7 | package nftstorage 8 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Binaries for programs and plugins 2 | *.exe 3 | *.exe~ 4 | *.dll 5 | *.so 6 | *.dylib 7 | 8 | # Test binary, built with `go test -c` 9 | *.test 10 | 11 | # Output of the go coverage tool, specifically when used with LiteIDE 12 | *.out 13 | 14 | # Dependency directories (remove the comment below to include it) 15 | # vendor/ 16 | 17 | /bin 18 | /build/binary/* 19 | /build/package/* 20 | !/build/package/.gitkeep 21 | -------------------------------------------------------------------------------- /pkg/web3storage/doc.go: -------------------------------------------------------------------------------- 1 | // Web3.Storage is a service to make building on top of Filecoin as simple as 2 | // possible - giving the developers the power of open, distributed networks via 3 | // a friendly JS client library. Behind the scenes, Web3.Storage is backed by 4 | // Filecoin and makes content available via IPFS leveraging the unique 5 | // properties of each network. 6 | // 7 | // Docs: https://docs.web3.storage/ 8 | package web3storage 9 | -------------------------------------------------------------------------------- /pkg/fission/fission.go: -------------------------------------------------------------------------------- 1 | package fission 2 | 3 | import ( 4 | "net/http" 5 | ) 6 | 7 | const FISSION_URI = "https://runfission.com/ipfs" 8 | 9 | type Fission struct { 10 | *http.Client 11 | 12 | Username string 13 | Password string 14 | } 15 | 16 | func (p *Fission) PinFile(filepath string) (string, error) { 17 | return "", nil 18 | } 19 | 20 | func (p *Fission) PinHash(hash string) (bool, error) { 21 | return true, nil 22 | } 23 | -------------------------------------------------------------------------------- /.github/workflows/snapcraft.yml: -------------------------------------------------------------------------------- 1 | name: Snapcraft 2 | 3 | on: 4 | push: 5 | tags: 6 | - 'v*' # Push events to matching v*, i.e. v1.0, v20.15.10 7 | workflow_dispatch: 8 | 9 | permissions: 10 | contents: read 11 | 12 | jobs: 13 | snapcraft: 14 | name: Build Snap 15 | uses: wabarc/.github/.github/workflows/reusable-builder-snap.yml@main 16 | with: 17 | product: ipfs-pinner 18 | channel: stable 19 | publish: true 20 | release: true 21 | secrets: 22 | snapcraft-token: ${{ secrets.SNAPCRAFT_TOKEN }} 23 | -------------------------------------------------------------------------------- /.github/dependabot.yml: -------------------------------------------------------------------------------- 1 | # To get started with Dependabot version updates, you'll need to specify which 2 | # package ecosystems to update and where the package manifests are located. 3 | # Please see the documentation for all configuration options: 4 | # https://help.github.com/github/administering-a-repository/configuration-options-for-dependency-updates 5 | 6 | version: 2 7 | updates: 8 | - package-ecosystem: "gomod" 9 | directory: "/" 10 | schedule: 11 | interval: "daily" 12 | open-pull-requests-limit: 10 13 | 14 | - package-ecosystem: "github-actions" 15 | directory: "/" 16 | schedule: 17 | interval: "daily" 18 | 19 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/Bug_report.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: 🐛 Bug Report 3 | about: If something isn't working as expected 🤔. 4 | --- 5 | 6 | ## Bug Report 7 | 8 | **Current Behavior** 9 | A clear and concise description of the behavior. 10 | 11 | ```shell 12 | // Your error message 13 | ``` 14 | 15 | **Expected behavior/code** 16 | A clear and concise description of what you expected to happen (or code). 17 | 18 | **Environment** 19 | 20 | - Wayback version(s): [e.g. v0.8.0] 21 | - Golang version: [e.g. Go 1.16] 22 | - OS: [e.g. OSX 10.13.4, Windows 10] 23 | 24 | **Possible Solution** 25 | 26 | 27 | 28 | **Additional context/Screenshots** 29 | Add any other context about the problem here. If applicable, add screenshots to help explain. 30 | 31 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/Feature_request.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: 🚀 Feature Request 3 | about: I have a suggestion (and may want to implement it 🙂)! 4 | --- 5 | 6 | ## Feature Request 7 | 8 | **Is your feature request related to a problem? Please describe.** 9 | A clear and concise description of what the problem is. Ex. I have an issue when [...] 10 | 11 | **Describe the solution you'd like** 12 | A clear and concise description of what you want to happen. Add any considered drawbacks. 13 | 14 | **Describe alternatives you've considered** 15 | A clear and concise description of any alternative solutions or features you've considered. 16 | 17 | **Teachability, Documentation, Adoption, Migration Strategy** 18 | If you can, explain how users will be able to use this and possibly write out a version the docs. 19 | Maybe a screenshot or design? 20 | -------------------------------------------------------------------------------- /.github/workflows/stale.yml: -------------------------------------------------------------------------------- 1 | name: Stale 2 | 3 | on: 4 | schedule: 5 | - cron: "0 3 * * 6" 6 | 7 | permissions: 8 | issues: write 9 | pull-requests: write 10 | jobs: 11 | stale: 12 | name: Stale 13 | runs-on: ubuntu-latest 14 | steps: 15 | - name: Mark stale issues and pull requests 16 | uses: actions/stale@v4 17 | with: 18 | repo-token: ${{ github.token }} 19 | exempt-issue-labels: "enhancement,question,help wanted,bug" 20 | exempt-pr-labels: "need-help,WIP" 21 | stale-issue-message: "This issue is stale because it has been open 120 days with no activity. Remove stale label or comment or this will be closed in 5 days" 22 | stale-pr-message: 'It has been open 120 days with no activity. Remove stale label or comment or this will be closed in 5 days' 23 | days-before-stale: 120 24 | days-before-close: 5 25 | -------------------------------------------------------------------------------- /http/client.go: -------------------------------------------------------------------------------- 1 | // Copyright 2021 Wayback Archiver. All rights reserved. 2 | // Use of this source code is governed by the GNU GPL v3 3 | // license that can be found in the LICENSE file. 4 | 5 | package http // import "github.com/wabarc/ipfs-pinner/http" 6 | 7 | import ( 8 | "net/http" 9 | "time" 10 | 11 | "github.com/ybbus/httpretry" 12 | ) 13 | 14 | func NewClient(client *http.Client) *http.Client { 15 | if client == nil { 16 | client = http.DefaultClient 17 | } 18 | return httpretry.NewCustomClient( 19 | client, 20 | // retry 5 times 21 | httpretry.WithMaxRetryCount(5), 22 | // retry on status == 429, if status >= 500, if err != nil, or if response was nil (status == 0) 23 | httpretry.WithRetryPolicy(func(statusCode int, err error) bool { 24 | return err != nil || statusCode == http.StatusTooManyRequests || statusCode >= http.StatusInternalServerError || statusCode == 0 25 | }), 26 | // every retry should wait one more 10 second 27 | // backoff will be: 5, 10, 20, 40, 80, ... 28 | httpretry.WithBackoffPolicy(httpretry.ExponentialBackoff(5*time.Second, time.Minute, time.Second)), 29 | ) 30 | } 31 | -------------------------------------------------------------------------------- /file/multifile_test.go: -------------------------------------------------------------------------------- 1 | package file 2 | 3 | import ( 4 | "io/ioutil" 5 | "os" 6 | "testing" 7 | 8 | "github.com/wabarc/helper" 9 | ) 10 | 11 | func TestCreateMultiForm(t *testing.T) { 12 | dir, err := ioutil.TempDir("", "ipfs-pinner-dir-") 13 | if err != nil { 14 | t.Fatalf("Unexpected create directory: %v", err) 15 | } 16 | defer os.RemoveAll(dir) 17 | 18 | // Create files 19 | for i := 1; i <= 2; i++ { 20 | f, err := ioutil.TempFile(dir, "file-") 21 | if err != nil { 22 | t.Fatal("Unexpected create file") 23 | } 24 | content := []byte(helper.RandString(6, "lower")) 25 | if _, err := f.Write(content); err != nil { 26 | t.Fatal("Unexpected write content to file") 27 | } 28 | } 29 | 30 | node, err := NewSerialFile(dir) 31 | if err != nil { 32 | t.Fatalf("Unexpected new a serial file: %v", err) 33 | } 34 | node.MapDirectory("a-dir-name-show-in-pinning-service") 35 | 36 | body, err := CreateMultiForm(node, true) 37 | if err != nil { 38 | t.Fatalf("Unexpected creates multipart form data: %v", err) 39 | } 40 | 41 | boundary := body.Boundary() 42 | if boundary == "" { 43 | t.Fatal("Unexpected multipart boundary") 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /.github/linters/.markdown-lint.yml: -------------------------------------------------------------------------------- 1 | --- 2 | ########################### 3 | ########################### 4 | ## Markdown Linter rules ## 5 | ########################### 6 | ########################### 7 | 8 | # Linter rules doc: 9 | # - https://github.com/DavidAnson/markdownlint 10 | # 11 | # Note: 12 | # To comment out a single error: 13 | # 14 | # any violations you want 15 | # 16 | # 17 | 18 | ############### 19 | # Rules by id # 20 | ############### 21 | MD004: false # Unordered list style 22 | MD007: 23 | indent: 2 # Unordered list indentation 24 | MD013: 25 | line_length: 400 # Line length 80 is far to short 26 | MD024: false # Multiple headings with the same content 27 | MD026: 28 | punctuation: ".,;:!。,;:" # List of not allowed 29 | MD029: false # Ordered list item prefix 30 | MD033: false # Allow inline HTML 31 | MD034: false # Allow Bare URL 32 | MD036: false # Emphasis used instead of a heading 33 | MD041: false # Allow top-level heading first line 34 | 35 | ################# 36 | # Rules by tags # 37 | ################# 38 | blank_lines: false # Error on blank lines 39 | -------------------------------------------------------------------------------- /go.mod: -------------------------------------------------------------------------------- 1 | module github.com/wabarc/ipfs-pinner 2 | 3 | go 1.19 4 | 5 | require ( 6 | github.com/ipfs/boxo v0.8.1 7 | github.com/ipfs/go-cid v0.4.0 8 | github.com/wabarc/helper v0.0.0-20230418130954-be7440352bcb 9 | github.com/ybbus/httpretry v1.0.2 10 | ) 11 | 12 | require ( 13 | github.com/crackcomm/go-gitignore v0.0.0-20170627025303-887ab5e44cc3 // indirect 14 | github.com/fortytw2/leaktest v1.3.0 // indirect 15 | github.com/kennygrant/sanitize v1.2.4 // indirect 16 | github.com/klauspost/cpuid/v2 v2.2.3 // indirect 17 | github.com/mattn/go-isatty v0.0.18 // indirect 18 | github.com/minio/sha256-simd v1.0.0 // indirect 19 | github.com/mr-tron/base58 v1.2.0 // indirect 20 | github.com/multiformats/go-base32 v0.1.0 // indirect 21 | github.com/multiformats/go-base36 v0.2.0 // indirect 22 | github.com/multiformats/go-multibase v0.1.1 // indirect 23 | github.com/multiformats/go-multihash v0.2.1 // indirect 24 | github.com/multiformats/go-varint v0.0.7 // indirect 25 | github.com/spaolacci/murmur3 v1.1.0 // indirect 26 | golang.org/x/crypto v0.6.0 // indirect 27 | golang.org/x/net v0.9.0 // indirect 28 | golang.org/x/sys v0.7.0 // indirect 29 | golang.org/x/text v0.9.0 // indirect 30 | lukechampine.com/blake3 v1.1.7 // indirect 31 | mvdan.cc/xurls/v2 v2.5.0 // indirect 32 | ) 33 | -------------------------------------------------------------------------------- /file/mime.go: -------------------------------------------------------------------------------- 1 | package file 2 | 3 | import ( 4 | "bufio" 5 | "io" 6 | "net/http" 7 | "os" 8 | // "github.com/gabriel-vasile/mimetype" 9 | ) 10 | 11 | // MediaType returns the file's mime type. If the mime type cannot be 12 | // determined, it returns "application/octet-stream". 13 | // 14 | // The i should be a *os.File, io.Reader, or byte slice. 15 | func MediaType(i interface{}) string { 16 | defaultType := "application/octet-stream" 17 | 18 | // var err error 19 | // var mtype *mimetype.MIME 20 | // switch v := i.(type) { 21 | // case *os.File: 22 | // mtype, err = mimetype.DetectFile(v.Name()) 23 | // case io.Reader: 24 | // mtype, err = mimetype.DetectReader(v) 25 | // case []byte: 26 | // mtype = mimetype.Detect(v) 27 | // default: 28 | // return defaultType 29 | // } 30 | 31 | // if err != nil { 32 | // return defaultType 33 | // } 34 | // return mtype.String() 35 | 36 | switch v := i.(type) { 37 | case *os.File: 38 | scanner := bufio.NewScanner(v) 39 | return http.DetectContentType(scanner.Bytes()) 40 | case io.Reader: 41 | rd := bufio.NewReader(v) 42 | buf, err := rd.Peek(8192) 43 | if err != nil { 44 | return defaultType 45 | } 46 | return http.DetectContentType(buf) 47 | case []byte: 48 | return http.DetectContentType(v) 49 | } 50 | 51 | return defaultType 52 | } 53 | -------------------------------------------------------------------------------- /.github/workflows/testing.yml: -------------------------------------------------------------------------------- 1 | name: Testing 2 | 3 | on: 4 | push: 5 | branches: 6 | - "*" 7 | paths: 8 | - "**/*.go" 9 | - "go.mod" 10 | - "go.sum" 11 | - ".github/workflows/testing.yml" 12 | - "Makefile" 13 | pull_request: 14 | branches: [ main ] 15 | types: [ opened, synchronize, reopened ] 16 | paths: 17 | - "**/*.go" 18 | - "go.mod" 19 | - "go.sum" 20 | - ".github/workflows/testing.yml" 21 | - "Makefile" 22 | workflow_dispatch: 23 | 24 | permissions: write-all 25 | jobs: 26 | test: 27 | name: Testing 28 | runs-on: ${{ matrix.os }} 29 | strategy: 30 | fail-fast: false 31 | matrix: 32 | os: [ ubuntu-latest, macos-latest, windows-latest ] 33 | go: [ "1.19", "1.20" ] 34 | 35 | steps: 36 | - name: Set up Go 1.x 37 | uses: actions/setup-go@v2 38 | with: 39 | go-version: ${{ matrix.go }} 40 | 41 | - name: Set up IPFS 42 | uses: ibnesayeed/setup-ipfs@master 43 | with: 44 | run_daemon: true 45 | 46 | - name: Check out code into the Go module directory 47 | uses: actions/checkout@v3 48 | with: 49 | fetch-depth: 0 50 | 51 | - name: Cache go module 52 | uses: actions/cache@v3 53 | with: 54 | path: | 55 | ~/.cache/go-build 56 | ~/Library/Caches/go-build 57 | %LocalAppData%\go-build 58 | ~/go/pkg/mod 59 | key: ${{ runner.os }}-go-${{ hashFiles('**/go.sum') }} 60 | restore-keys: ${{ runner.os }}-go- 61 | 62 | - name: Get dependencies 63 | run: | 64 | go get -v -t -d ./... 65 | 66 | - name: Test 67 | run: | 68 | make test 69 | -------------------------------------------------------------------------------- /snapcraft.yaml: -------------------------------------------------------------------------------- 1 | name: ipfs-pinner 2 | 3 | version: 'git' 4 | 5 | summary: A toolkit to upload files or directory to IPFS pinning services. 6 | 7 | description: | 8 | ipfs-pinner is a toolkit to help upload files or specific content id to IPFS pinning services. 9 | Website https://github.com/wabarc/ipfs-pinner 10 | 11 | Supported Pinning Services: 12 | 13 | 1.Infura 14 | Infura is a freemium pinning service that doesn't require any additional setup. It's the default one used. 15 | Please bear in mind that Infura is a free service, so there is probably a rate-limiting. https://infura.io 16 | Usage:ipfs-pinner file-to-path 17 | 18 | 2.Pinata 19 | Pinata is a freemium pinning service. It gives you more control over what's uploaded. 20 | You can delete, label and add custom metadata. This service requires signup. https://pinata.cloud/ 21 | Usage:ipfs-pinner -p pinata file-to-path 22 | 23 | 3.NFT.Storage 24 | NFT.Storage is a long-term storage service designed for off-chain NFT data 25 | (like metadata, images, and other assets) for up to 31GiB in size. Data is 26 | content addressed using IPFS, meaning the URL pointing to a piece of data 27 | (“ipfs://…”) is completely unique to that data. 28 | 29 | 4.Web3.Storage 30 | Web3.Storage is a service to make building on top of Filecoin as simple as 31 | possible - giving the developers the power of open, distributed networks via 32 | a friendly JS client library. Behind the scenes, Web3.Storage is backed by 33 | Filecoin and makes content available via IPFS leveraging the unique 34 | properties of each network. 35 | 36 | grade: stable 37 | 38 | confinement: strict 39 | 40 | base: core18 41 | 42 | parts: 43 | ipfs-pinner: 44 | plugin: go 45 | source: https://github.com/wabarc/ipfs-pinner.git 46 | go-importpath: github.com/wabarc/ipfs-pinner/cmd/ipfs-pinner 47 | build-packages: 48 | - build-essential 49 | 50 | apps: 51 | ipfs-pinner: 52 | command: ipfs-pinner 53 | plugs: 54 | - home 55 | - network 56 | -------------------------------------------------------------------------------- /file/serialfile.go: -------------------------------------------------------------------------------- 1 | package file 2 | 3 | import ( 4 | "fmt" 5 | "os" 6 | "path/filepath" 7 | "strings" 8 | ) 9 | 10 | // Node represents a serial files. 11 | type Node struct { 12 | base string 13 | root string 14 | files []os.FileInfo 15 | paths []string // relative path 16 | stat os.FileInfo 17 | } 18 | 19 | // NewSerialFile adopts serial files and returns a Node represents a file, 20 | // directory, or special file. 21 | func NewSerialFile(root string) (node *Node, err error) { 22 | node = new(Node) 23 | node.root = root 24 | stat, err := os.Stat(root) 25 | if err != nil { 26 | return node, fmt.Errorf("lookup path failed: %v", err) 27 | } 28 | node.stat = stat 29 | switch mode := stat.Mode(); { 30 | case mode.IsRegular(): 31 | node.files = append(node.files, stat) 32 | node.paths = append(node.paths, root) 33 | case mode.IsDir(): 34 | err := filepath.Walk(root, func(path string, fi os.FileInfo, err error) error { 35 | if !fi.IsDir() { 36 | path = strings.TrimPrefix(path, root) 37 | path = strings.TrimPrefix(path, "/") 38 | node.paths = append(node.paths, path) 39 | node.files = append(node.files, fi) 40 | } 41 | return nil 42 | }) 43 | if err != nil { 44 | return node, fmt.Errorf("read directory failed: %v", err) 45 | } 46 | default: 47 | return node, fmt.Errorf("unrecognized file type for %s: %s", root, mode.String()) 48 | } 49 | return 50 | } 51 | 52 | // MapDirectory sets up a new target directory by given path name. 53 | func (n *Node) MapDirectory(name string) { 54 | if n.stat.IsDir() { 55 | n.base = name 56 | } 57 | } 58 | 59 | // Mode returns a os.FileMode of Node 60 | func (n *Node) Mode() os.FileMode { 61 | return n.stat.Mode() 62 | } 63 | 64 | // Size returns the file size of the Node. 65 | func (n *Node) Size() (du int64, err error) { 66 | if len(n.files) == 0 { 67 | return 0, fmt.Errorf("node is empty") 68 | } 69 | 70 | for _, fi := range n.files { 71 | if fi.Mode().IsRegular() { 72 | du += fi.Size() 73 | } 74 | if fi.Mode().IsDir() { 75 | err = filepath.Walk(fi.Name(), func(p string, fi os.FileInfo, err error) error { 76 | if err != nil || fi == nil { 77 | return err 78 | } 79 | 80 | if fi.Mode().IsRegular() { 81 | du += fi.Size() 82 | } 83 | 84 | return nil 85 | }) 86 | if err != nil { 87 | return 0, fmt.Errorf("walk directory failed: %v", err) 88 | } 89 | } 90 | } 91 | 92 | return du, err 93 | } 94 | -------------------------------------------------------------------------------- /.golangci.yml: -------------------------------------------------------------------------------- 1 | --- 2 | ######################### 3 | ######################### 4 | ## Golang Linter rules ## 5 | ######################### 6 | ######################### 7 | 8 | # configure golangci-lint 9 | # see https://github.com/golangci/golangci-lint/blob/master/.golangci.example.yml 10 | run: 11 | # default concurrency is a available CPU number. 12 | # concurrency: 4 # explicitly omit this value to fully utilize available resources. 13 | deadline: 5m 14 | issues-exit-code: 1 15 | tests: false 16 | 17 | issues: 18 | exclude-rules: 19 | - path: _test\.go 20 | linters: 21 | - dupl 22 | - gosec 23 | - goconst 24 | linters: 25 | disable-all: true 26 | enable: 27 | - gosec 28 | - unconvert 29 | - gocyclo 30 | - goconst 31 | - goimports 32 | - gocritic 33 | - bodyclose 34 | - misspell 35 | - rowserrcheck 36 | - structcheck 37 | - stylecheck 38 | - typecheck 39 | - varcheck 40 | - unconvert 41 | - unparam 42 | - whitespace 43 | linters-settings: 44 | errcheck: 45 | # report about assignment of errors to blank identifier: `num, _ := strconv.Atoi(numStr)`; 46 | # default is false: such cases aren't reported by default. 47 | check-blank: true 48 | govet: 49 | # report about shadowed variables 50 | check-shadowing: true 51 | gocyclo: 52 | # minimal code complexity to report, 30 by default 53 | min-complexity: 15 54 | gosec: 55 | # To specify a set of rules to explicitly exclude. 56 | # Available rules: https://github.com/securego/gosec#available-rules 57 | excludes: 58 | - G108 59 | # To specify the configuration of rules. 60 | # The configuration of rules is not fully documented by gosec: 61 | # https://github.com/securego/gosec#configuration 62 | # https://github.com/securego/gosec/blob/569328eade2ccbad4ce2d0f21ee158ab5356a5cf/rules/rulelist.go#L60-L102 63 | config: 64 | misspell: 65 | # Correct spellings using locale preferences for US or UK. 66 | # Default is to use a neutral variety of English. 67 | # Setting locale to US will correct the British spelling of 'colour' to 'color'. 68 | locale: US 69 | ignore-words: 70 | - someword 71 | stylecheck: 72 | go: "1.16" 73 | # https://staticcheck.io/docs/options#checks 74 | checks: [ "all", "-ST1003", "-ST1008", "-ST1016" ] 75 | # https://staticcheck.io/docs/options#initialisms 76 | initialisms: [ "ACL", "API", "ASCII", "CPU", "CSS", "DNS", "EOF", "GUID", "HTML", "HTTP", "HTTPS", "ID", "IP", "JSON", "QPS", "RAM", "RPC", "SLA", "SMTP", "SQL", "SSH", "TCP", "TLS", "TTL", "UDP", "UI", "GID", "UID", "UUID", "URI", "URL", "UTF8", "VM", "XML", "XMPP", "XSRF", "XSS" ] 77 | -------------------------------------------------------------------------------- /cmd/ipfs-pinner/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "bytes" 5 | "flag" 6 | "fmt" 7 | "os" 8 | "strings" 9 | 10 | "github.com/ipfs/go-cid" 11 | 12 | pinner "github.com/wabarc/ipfs-pinner" 13 | ) 14 | 15 | type pin struct { 16 | path string 17 | isCid bool 18 | } 19 | 20 | func main() { 21 | var ( 22 | target string 23 | apikey string 24 | secret string 25 | ) 26 | 27 | flag.Usage = func() { 28 | usage := `A CLI tool for pin files or directory to IPFS. 29 | 30 | Usage: 31 | 32 | ipfs-pinner [flags] [path]... 33 | 34 | Flags: 35 | ` 36 | fmt.Fprintln(os.Stdout, usage) 37 | flag.PrintDefaults() 38 | fmt.Fprintln(os.Stdout, "") 39 | } 40 | 41 | flag.StringVar(&target, "t", "infura", "IPFS pinner, supports pinners: infura, pinata, nftstorage, web3storage.") 42 | flag.StringVar(&apikey, "u", "", "Pinner apikey or username.") 43 | flag.StringVar(&secret, "p", "", "Pinner sceret or password.") 44 | flag.Parse() 45 | 46 | files := flag.Args() 47 | target = strings.ToLower(target) 48 | switch target { 49 | case pinner.Pinata: 50 | if apikey == "" { 51 | apikey = os.Getenv("IPFS_PINNER_PINATA_API_KEY") 52 | } 53 | if secret == "" { 54 | secret = os.Getenv("IPFS_PINNER_PINATA_SECRET_API_KEY") 55 | } 56 | case pinner.NFTStorage, pinner.Web3Storage: 57 | if apikey == "" { 58 | fmt.Println(target + " requires an apikey.") 59 | os.Exit(1) 60 | } 61 | case pinner.Infura: 62 | // Permit request without authorization 63 | default: 64 | flag.Usage() 65 | os.Exit(0) 66 | } 67 | if len(files) < 1 { 68 | flag.Usage() 69 | fmt.Println("file path is missing.") 70 | os.Exit(1) 71 | } 72 | 73 | pins := []pin{} 74 | for _, p := range files { 75 | pins = append(pins, pin{ 76 | path: p, 77 | isCid: isCid(p), 78 | }) 79 | } 80 | 81 | mustExist(pins) 82 | 83 | handler := pinner.Config{ 84 | Pinner: target, 85 | Apikey: apikey, 86 | Secret: secret, 87 | } 88 | var cid string 89 | var err error 90 | for _, p := range pins { 91 | if p.isCid { 92 | cid, err = handler.PinHash(p.path) 93 | } else { 94 | cid, err = handler.Pin(p.path) 95 | } 96 | 97 | if err != nil { 98 | fmt.Fprintf(os.Stderr, "ipfs-pinner: %v\n", err) 99 | } else { 100 | fmt.Fprintf(os.Stdout, "%s %s\n", cid, p.path) 101 | } 102 | } 103 | } 104 | 105 | func mustExist(path []pin) { 106 | b := &bytes.Buffer{} 107 | for _, p := range path { 108 | if p.isCid { 109 | continue 110 | } 111 | _, err := os.Stat(p.path) 112 | if _, ok := err.(*os.PathError); ok { 113 | fmt.Fprintln(b, err) 114 | } 115 | } 116 | if b.Len() > 0 { 117 | fmt.Println(b.String()) 118 | os.Exit(1) 119 | } 120 | } 121 | 122 | func isCid(s string) bool { 123 | _, err := cid.Parse(s) 124 | if err != nil { 125 | return false 126 | } 127 | return true 128 | } 129 | -------------------------------------------------------------------------------- /.github/workflows/builder.yml: -------------------------------------------------------------------------------- 1 | name: Builder 2 | 3 | on: 4 | push: 5 | branches: "*" 6 | paths: 7 | - "**/*.go" 8 | - "go.mod" 9 | - "go.sum" 10 | - "Makefile" 11 | - "build/**" 12 | - ".github/workflows/builder.yml" 13 | pull_request: 14 | branches: "*" 15 | paths: 16 | - "**/*.go" 17 | - "go.mod" 18 | - "go.sum" 19 | workflow_dispatch: 20 | 21 | env: 22 | PRODUCT: ipfs-pinner 23 | 24 | permissions: 25 | contents: read 26 | 27 | jobs: 28 | build: 29 | name: Build 30 | strategy: 31 | matrix: 32 | os: [ linux, freebsd, openbsd, dragonfly, windows, darwin ] 33 | arch: [ amd64, 386 ] 34 | include: 35 | - os: linux 36 | arch: arm 37 | arm: 5 38 | - os: linux 39 | arch: arm 40 | arm: 6 41 | - os: linux 42 | arch: arm 43 | arm: 7 44 | - os: linux 45 | arch: arm64 46 | - os: linux 47 | arch: mips 48 | mips: softfloat 49 | - os: linux 50 | arch: mips 51 | mips: hardfloat 52 | - os: linux 53 | arch: mipsle 54 | mipsle: softfloat 55 | - os: linux 56 | arch: mipsle 57 | mipsle: hardfloat 58 | - os: linux 59 | arch: mips64 60 | - os: linux 61 | arch: mips64le 62 | - os: linux 63 | arch: ppc64 64 | - os: linux 65 | arch: ppc64le 66 | - os: linux 67 | arch: s390x 68 | - os: windows 69 | arch: arm 70 | - os: windows 71 | arch: arm64 72 | - os: android 73 | arch: arm64 74 | - os: darwin 75 | arch: arm64 76 | - os: freebsd 77 | arch: arm64 78 | exclude: 79 | - os: darwin 80 | arch: 386 81 | - os: dragonfly 82 | arch: 386 83 | fail-fast: false 84 | uses: wabarc/.github/.github/workflows/reusable-builder-go.yml@main 85 | with: 86 | product: ipfs-pinner 87 | go-version: '^1.19' 88 | go-os: ${{ matrix.os }} 89 | go-arch: ${{ matrix.arch }} 90 | go-arm: ${{ matrix.arm }} 91 | go-mips: ${{ matrix.mips }} 92 | go-mips64: ${{ matrix.mips64 }} 93 | go-mipsle: ${{ matrix.mipsle }} 94 | artifact-path: ./build/binary/ipfs-pinner* 95 | 96 | snapcraft: 97 | name: Build Snap 98 | uses: wabarc/.github/.github/workflows/reusable-builder-snap.yml@main 99 | with: 100 | product: ipfs-pinner 101 | channel: edge 102 | publish: ${{ github.repository == 'wabarc/ipfs-pinner' && github.event_name == 'push' }} 103 | secrets: 104 | snapcraft-token: ${{ secrets.SNAPCRAFT_TOKEN }} 105 | -------------------------------------------------------------------------------- /.github/workflows/release.yml: -------------------------------------------------------------------------------- 1 | name: Release 2 | 3 | on: 4 | push: 5 | tags: 6 | - 'v*' # Push events to matching v*, i.e. v1.0, v20.15.10 7 | 8 | env: 9 | PRODUCT: ipfs-pinner 10 | 11 | permissions: 12 | contents: read 13 | 14 | jobs: 15 | build: 16 | name: Build 17 | strategy: 18 | matrix: 19 | os: [ linux, freebsd, openbsd, dragonfly, windows, darwin ] 20 | arch: [ amd64, 386 ] 21 | include: 22 | - os: linux 23 | arch: arm 24 | arm: 5 25 | - os: linux 26 | arch: arm 27 | arm: 6 28 | - os: linux 29 | arch: arm 30 | arm: 7 31 | - os: linux 32 | arch: arm64 33 | - os: linux 34 | arch: mips 35 | mips: softfloat 36 | - os: linux 37 | arch: mips 38 | mips: hardfloat 39 | - os: linux 40 | arch: mipsle 41 | mipsle: softfloat 42 | - os: linux 43 | arch: mipsle 44 | mipsle: hardfloat 45 | - os: linux 46 | arch: mips64 47 | - os: linux 48 | arch: mips64le 49 | - os: linux 50 | arch: ppc64 51 | - os: linux 52 | arch: ppc64le 53 | - os: linux 54 | arch: s390x 55 | - os: windows 56 | arch: arm 57 | - os: windows 58 | arch: arm64 59 | - os: android 60 | arch: arm64 61 | - os: darwin 62 | arch: arm64 63 | - os: freebsd 64 | arch: arm64 65 | exclude: 66 | - os: darwin 67 | arch: 386 68 | - os: dragonfly 69 | arch: 386 70 | fail-fast: false 71 | uses: wabarc/.github/.github/workflows/reusable-builder-go.yml@main 72 | with: 73 | product: ipfs-pinner 74 | release: true 75 | go-version: '^1.19' 76 | go-os: ${{ matrix.os }} 77 | go-arch: ${{ matrix.arch }} 78 | go-arm: ${{ matrix.arm }} 79 | go-mips: ${{ matrix.mips }} 80 | go-mips64: ${{ matrix.mips64 }} 81 | go-mipsle: ${{ matrix.mipsle }} 82 | artifact-path: build/package/ipfs-pinner* 83 | 84 | release: 85 | name: Create and upload release 86 | needs: [ build, debpkg, rpmpkg, aurpkg, snapcraft, flatpak ] 87 | permissions: 88 | contents: write 89 | uses: wabarc/.github/.github/workflows/reusable-releaser-go.yml@main 90 | with: 91 | product: ipfs-pinner 92 | 93 | notification: 94 | if: github.repository == 'wabarc/ipfs-pinner' 95 | name: Send Notification 96 | runs-on: ubuntu-latest 97 | needs: [release] 98 | steps: 99 | - name: Download artifact 100 | uses: actions/download-artifact@v2 101 | with: 102 | name: release-note 103 | path: . 104 | 105 | - name: Send release note to Telegram channel 106 | continue-on-error: true 107 | run: | 108 | TEXT="$(cat release-note.md)" 109 | echo -e "${TEXT}" 110 | curl --silent --output /dev/null --show-error --fail -X POST \ 111 | -H 'Content-Type: application/json' \ 112 | -d '{"chat_id": "${{ secrets.TELEGRAM_TO }}", "text": "'"${TEXT}"'", "parse_mode": "markdown"}' \ 113 | "https://api.telegram.org/bot${{ secrets.TELEGRAM_TOKEN }}/sendMessage" 114 | 115 | -------------------------------------------------------------------------------- /pkg/nftstorage/nftstorage.go: -------------------------------------------------------------------------------- 1 | package nftstorage 2 | 3 | import ( 4 | "bytes" 5 | "encoding/json" 6 | "fmt" 7 | "io" 8 | "io/ioutil" 9 | "net/http" 10 | "os" 11 | 12 | "github.com/wabarc/ipfs-pinner/file" 13 | 14 | httpretry "github.com/wabarc/ipfs-pinner/http" 15 | ) 16 | 17 | const api = "https://api.nft.storage" 18 | 19 | // NFTStorage represents an NFTStorage configuration. 20 | type NFTStorage struct { 21 | *http.Client 22 | 23 | Apikey string 24 | } 25 | 26 | type value struct { 27 | Cid string 28 | Size int64 `json:",omitempty"` 29 | Created string `json:",omitempty"` 30 | Type string `json:",omitempty"` 31 | } 32 | 33 | type er struct { 34 | Name, Message string 35 | } 36 | 37 | type addEvent struct { 38 | Ok bool 39 | Value value 40 | Error er 41 | } 42 | 43 | // PinFile pins content to NFTStorage by providing a file path, it returns an IPFS 44 | // hash and an error. 45 | func (nft *NFTStorage) PinFile(fp string) (string, error) { 46 | fi, err := os.Stat(fp) 47 | if err != nil { 48 | return "", err 49 | } 50 | 51 | // For regular file 52 | if fi.Mode().IsRegular() { 53 | f, err := os.Open(fp) 54 | if err != nil { 55 | return "", err 56 | } 57 | defer f.Close() 58 | 59 | return nft.pinFile(f, file.MediaType(f)) 60 | } 61 | 62 | // For directory, or etc 63 | f, err := file.NewSerialFile(fp) 64 | if err != nil { 65 | return "", err 66 | } 67 | 68 | mfr, err := file.CreateMultiForm(f, true) 69 | if err != nil { 70 | return "", err 71 | } 72 | boundary := "multipart/form-data; boundary=" + mfr.Boundary() 73 | 74 | return nft.pinFile(mfr, boundary) 75 | } 76 | 77 | // PinWithReader pins content to NFTStorage by given io.Reader, it returns an IPFS hash and an error. 78 | func (nft *NFTStorage) PinWithReader(rd io.Reader) (string, error) { 79 | return nft.pinFile(rd, file.MediaType(rd)) 80 | } 81 | 82 | // PinWithBytes pins content to NFTStorage by given byte slice, it returns an IPFS hash and an error. 83 | func (nft *NFTStorage) PinWithBytes(buf []byte) (string, error) { 84 | return nft.pinFile(bytes.NewReader(buf), file.MediaType(buf)) 85 | } 86 | 87 | func (nft *NFTStorage) pinFile(r io.Reader, boundary string) (string, error) { 88 | endpoint := api + "/upload" 89 | 90 | req, err := http.NewRequest(http.MethodPost, endpoint, r) 91 | if err != nil { 92 | return "", err 93 | } 94 | req.Header.Add("Content-Type", boundary) 95 | req.Header.Add("Authorization", "Bearer "+nft.Apikey) 96 | client := httpretry.NewClient(nft.Client) 97 | resp, err := client.Do(req) 98 | if err != nil { 99 | return "", err 100 | } 101 | defer resp.Body.Close() 102 | 103 | if resp.StatusCode != http.StatusOK { 104 | return "", fmt.Errorf(resp.Status) 105 | } 106 | 107 | data, err := ioutil.ReadAll(resp.Body) 108 | if err != nil { 109 | return "", err 110 | } 111 | 112 | var out addEvent 113 | if err := json.Unmarshal(data, &out); err != nil { 114 | if e, ok := err.(*json.SyntaxError); ok { 115 | return "", fmt.Errorf("json syntax error at byte offset %d", e.Offset) 116 | } 117 | return "", err 118 | } 119 | 120 | return out.Value.Cid, nil 121 | } 122 | 123 | // PinHash pins content to NFTStorage by giving an IPFS hash, it returns the result and an error. 124 | // Note: unsupported 125 | func (nft *NFTStorage) PinHash(hash string) (bool, error) { 126 | return false, fmt.Errorf("not yet supported") 127 | } 128 | 129 | // PinDir pins a directory to the NFT.Storage pinning service. 130 | // It alias to PinFile. 131 | func (nft *NFTStorage) PinDir(name string) (string, error) { 132 | return nft.PinFile(name) 133 | } 134 | -------------------------------------------------------------------------------- /.github/workflows/linter.yml: -------------------------------------------------------------------------------- 1 | name: Linter 2 | 3 | on: 4 | push: 5 | branches: 6 | - '**' 7 | pull_request: 8 | branches: 9 | - '**' 10 | types: [ opened, synchronize, reopened ] 11 | 12 | permissions: write-all 13 | jobs: 14 | lint: 15 | runs-on: ubuntu-latest 16 | steps: 17 | - name: Check out code base 18 | if: github.event_name == 'push' 19 | uses: actions/checkout@v3 20 | with: 21 | fetch-depth: 0 22 | 23 | - name: Check out code base 24 | if: github.event_name == 'pull_request' 25 | uses: actions/checkout@v3 26 | with: 27 | fetch-depth: 0 28 | ref: ${{ github.event.pull_request.head.sha }} 29 | 30 | - name: Lint Code Base 31 | uses: github/super-linter@v4 32 | env: 33 | DEFAULT_BRANCH: 'main' 34 | VALIDATE_MARKDOWN: true 35 | VALIDATE_DOCKERFILE: true 36 | VALIDATE_BASH: true 37 | VALIDATE_BASH_EXEC: true 38 | GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} 39 | 40 | go: 41 | runs-on: ubuntu-latest 42 | steps: 43 | - name: Check out code base 44 | if: github.event_name == 'push' 45 | uses: actions/checkout@v3 46 | with: 47 | fetch-depth: 0 48 | 49 | - name: Check out code base 50 | if: github.event_name == 'pull_request' 51 | uses: actions/checkout@v3 52 | with: 53 | fetch-depth: 0 54 | ref: ${{ github.event.pull_request.head.sha }} 55 | 56 | - name: Golang linter 57 | uses: golangci/golangci-lint-action@v2 58 | 59 | shellcheck: 60 | runs-on: ubuntu-latest 61 | steps: 62 | - name: Check out code base 63 | if: github.event_name == 'push' 64 | uses: actions/checkout@v3 65 | with: 66 | fetch-depth: 0 67 | 68 | - name: Check out code base 69 | if: github.event_name == 'pull_request' 70 | uses: actions/checkout@v3 71 | with: 72 | fetch-depth: 0 73 | ref: ${{ github.event.pull_request.head.sha }} 74 | 75 | - name: Run shellcheck with reviewdog 76 | uses: reviewdog/action-shellcheck@v1 77 | 78 | misspell: 79 | runs-on: ubuntu-latest 80 | steps: 81 | - name: Check out code base 82 | if: github.event_name == 'push' 83 | uses: actions/checkout@v3 84 | with: 85 | fetch-depth: 0 86 | 87 | - name: Check out code base 88 | if: github.event_name == 'pull_request' 89 | uses: actions/checkout@v3 90 | with: 91 | fetch-depth: 0 92 | ref: ${{ github.event.pull_request.head.sha }} 93 | 94 | - name: Run misspell with reviewdog 95 | uses: reviewdog/action-misspell@v1 96 | 97 | alex: 98 | runs-on: ubuntu-latest 99 | steps: 100 | - name: Check out code base 101 | if: github.event_name == 'push' 102 | uses: actions/checkout@v3 103 | with: 104 | fetch-depth: 0 105 | 106 | - name: Check out code base 107 | if: github.event_name == 'pull_request' 108 | uses: actions/checkout@v3 109 | with: 110 | fetch-depth: 0 111 | ref: ${{ github.event.pull_request.head.sha }} 112 | 113 | - name: Run alex with reviewdog 114 | uses: reviewdog/action-alex@v1 115 | 116 | goreportcard: 117 | if: ${{ github.ref == 'refs/heads/main' }} 118 | runs-on: ubuntu-latest 119 | steps: 120 | - name: Run Go report card 121 | run: | 122 | path=$(curl -sf -X POST -F "repo=github.com/$GITHUB_REPOSITORY" https://goreportcard.com/checks | jq -r '.redirect') 123 | echo -e "\nSee report for https://goreportcard.com${path}" 124 | -------------------------------------------------------------------------------- /pkg/web3storage/web3storage.go: -------------------------------------------------------------------------------- 1 | package web3storage 2 | 3 | import ( 4 | "encoding/json" 5 | "fmt" 6 | "io" 7 | "io/ioutil" 8 | "mime/multipart" 9 | "net/http" 10 | 11 | "github.com/wabarc/helper" 12 | "github.com/wabarc/ipfs-pinner/file" 13 | 14 | httpretry "github.com/wabarc/ipfs-pinner/http" 15 | ) 16 | 17 | const api = "https://api.web3.storage" 18 | 19 | // Web3Storage represents a Web3Storage configuration. 20 | type Web3Storage struct { 21 | *http.Client 22 | 23 | Apikey string 24 | } 25 | 26 | type addEvent struct { 27 | Cid string 28 | } 29 | 30 | // PinFile pins content to Web3Storage by providing a file path, it returns an IPFS 31 | // hash and an error. 32 | func (web3 *Web3Storage) PinFile(fp string) (string, error) { 33 | f, err := file.NewSerialFile(fp) 34 | if err != nil { 35 | return "", err 36 | } 37 | f.MapDirectory(helper.RandString(32, "lower")) 38 | 39 | mfr, err := file.CreateMultiForm(f, true) 40 | if err != nil { 41 | return "", err 42 | } 43 | boundary := "multipart/form-data; boundary=" + mfr.Boundary() 44 | 45 | return web3.pinFile(mfr, boundary) 46 | } 47 | 48 | // PinWithReader pins content to Web3Storage by given io.Reader, it returns an IPFS hash and an error. 49 | func (web3 *Web3Storage) PinWithReader(rd io.Reader) (string, error) { 50 | r, w := io.Pipe() 51 | m := multipart.NewWriter(w) 52 | fn := helper.RandString(6, "lower") 53 | 54 | go func() { 55 | defer w.Close() 56 | defer m.Close() 57 | 58 | part, err := m.CreateFormFile("file", fn) 59 | if err != nil { 60 | return 61 | } 62 | 63 | if _, err = io.Copy(part, rd); err != nil { 64 | return 65 | } 66 | }() 67 | 68 | return web3.pinFile(r, m.FormDataContentType()) 69 | } 70 | 71 | // PinWithBytes pins content to Web3Storage by given byte slice, it returns an IPFS hash and an error. 72 | func (web3 *Web3Storage) PinWithBytes(buf []byte) (string, error) { 73 | r, w := io.Pipe() 74 | m := multipart.NewWriter(w) 75 | fn := helper.RandString(6, "lower") 76 | 77 | go func() { 78 | defer w.Close() 79 | defer m.Close() 80 | 81 | part, err := m.CreateFormFile("file", fn) 82 | if err != nil { 83 | return 84 | } 85 | 86 | if _, err = part.Write(buf); err != nil { 87 | return 88 | } 89 | }() 90 | 91 | return web3.pinFile(r, m.FormDataContentType()) 92 | } 93 | 94 | func (web3 *Web3Storage) pinFile(r io.Reader, boundary string) (string, error) { 95 | endpoint := api + "/upload" 96 | 97 | req, err := http.NewRequest(http.MethodPost, endpoint, r) 98 | if err != nil { 99 | return "", err 100 | } 101 | req.Header.Add("Content-Type", boundary) 102 | req.Header.Add("Authorization", "Bearer "+web3.Apikey) 103 | client := httpretry.NewClient(web3.Client) 104 | resp, err := client.Do(req) 105 | if err != nil { 106 | return "", err 107 | } 108 | defer resp.Body.Close() 109 | 110 | if resp.StatusCode != http.StatusOK { 111 | return "", fmt.Errorf(resp.Status) 112 | } 113 | 114 | data, err := ioutil.ReadAll(resp.Body) 115 | if err != nil { 116 | return "", err 117 | } 118 | 119 | var out addEvent 120 | if err := json.Unmarshal(data, &out); err != nil { 121 | if e, ok := err.(*json.SyntaxError); ok { 122 | return "", fmt.Errorf("json syntax error at byte offset %d", e.Offset) 123 | } 124 | return "", err 125 | } 126 | 127 | return out.Cid, nil 128 | } 129 | 130 | // PinHash pins content to Web3Storage by giving an IPFS hash, it returns the result and an error. 131 | // Note: unsupported 132 | func (web3 *Web3Storage) PinHash(hash string) (bool, error) { 133 | return false, fmt.Errorf("not yet supported") 134 | } 135 | 136 | // PinDir pins a directory to the Pinata pinning service. 137 | // It alias to PinFile. 138 | func (web3 *Web3Storage) PinDir(name string) (string, error) { 139 | return web3.PinFile(name) 140 | } 141 | -------------------------------------------------------------------------------- /.github/workflows/codeql-analysis.yml: -------------------------------------------------------------------------------- 1 | # For most projects, this workflow file will not need changing; you simply need 2 | # to commit it to your repository. 3 | # 4 | # You may wish to alter this file to override the set of languages analyzed, 5 | # or to provide custom queries or build logic. 6 | # 7 | # ******** NOTE ******** 8 | # We have attempted to detect the languages in your repository. Please check 9 | # the `language` matrix defined below to confirm you have the correct set of 10 | # supported CodeQL languages. 11 | # ******** NOTE ******** 12 | 13 | name: "CodeQL" 14 | 15 | on: 16 | push: 17 | branches: [ main ] 18 | pull_request: 19 | # The branches below must be a subset of the branches above 20 | branches: [ main ] 21 | schedule: 22 | - cron: '33 23 * * 4' 23 | 24 | permissions: write-all 25 | jobs: 26 | analyze: 27 | name: Analyze 28 | runs-on: ubuntu-latest 29 | 30 | strategy: 31 | fail-fast: false 32 | matrix: 33 | language: [ 'go' ] 34 | # CodeQL supports [ 'cpp', 'csharp', 'go', 'java', 'javascript', 'python' ] 35 | # Learn more: 36 | # https://docs.github.com/github/finding-security-vulnerabilities-and-errors-in-your-code/configuring-code-scanning#changing-the-languages-that-are-analyzed 37 | 38 | steps: 39 | - name: Check out code base 40 | if: github.event_name == 'push' || github.event_name == 'schedule' 41 | uses: actions/checkout@v3 42 | with: 43 | fetch-depth: 0 44 | 45 | - name: Check out code base 46 | if: github.event_name == 'pull_request' 47 | uses: actions/checkout@v3 48 | with: 49 | fetch-depth: 0 50 | ref: ${{ github.event.pull_request.head.sha }} 51 | 52 | # Initializes the CodeQL tools for scanning. 53 | - name: Initialize CodeQL 54 | uses: github/codeql-action/init@v1 55 | with: 56 | languages: ${{ matrix.language }} 57 | # If you wish to specify custom queries, you can do so here or in a config file. 58 | # By default, queries listed here will override any specified in a config file. 59 | # Prefix the list here with "+" to use these queries and those in the config file. 60 | # queries: ./path/to/local/query, your-org/your-repo/queries@main 61 | 62 | # Autobuild attempts to build any compiled languages (C/C++, C#, or Java). 63 | # If this step fails, then you should remove it and run the build manually (see below) 64 | - name: Autobuild 65 | uses: github/codeql-action/autobuild@v1 66 | 67 | # ℹ️ Command-line programs to run using the OS shell. 68 | # 📚 https://git.io/JvXDl 69 | 70 | # ✏️ If the Autobuild fails above, remove it and uncomment the following three lines 71 | # and modify them (or add more) to build your code if your project 72 | # uses a compiled language 73 | 74 | #- run: | 75 | # make bootstrap 76 | # make release 77 | 78 | - name: Perform CodeQL Analysis 79 | uses: github/codeql-action/analyze@v1 80 | 81 | nancy: 82 | name: Sonatype Nancy 83 | runs-on: ubuntu-latest 84 | steps: 85 | - name: Check out code base 86 | if: github.event_name == 'push' || github.event_name == 'schedule' 87 | uses: actions/checkout@v3 88 | with: 89 | fetch-depth: 0 90 | 91 | - name: Check out code base 92 | if: github.event_name == 'pull_request' 93 | uses: actions/checkout@v3 94 | with: 95 | fetch-depth: 0 96 | ref: ${{ github.event.pull_request.head.sha }} 97 | 98 | - name: Set up Go 1.x 99 | uses: actions/setup-go@v2 100 | with: 101 | go-version: ^1.17 102 | 103 | - name: Write Go module list 104 | run: go list -json -m all > go.list 105 | 106 | - name: Perform Nancy 107 | uses: sonatype-nexus-community/nancy-github-action@main 108 | continue-on-error: true 109 | 110 | -------------------------------------------------------------------------------- /pinner.go: -------------------------------------------------------------------------------- 1 | package pinner // import "github.com/wabarc/ipfs-pinner" 2 | 3 | import ( 4 | "fmt" 5 | "io" 6 | "net/http" 7 | "os" 8 | 9 | "github.com/wabarc/ipfs-pinner/pkg/infura" 10 | "github.com/wabarc/ipfs-pinner/pkg/nftstorage" 11 | "github.com/wabarc/ipfs-pinner/pkg/pinata" 12 | "github.com/wabarc/ipfs-pinner/pkg/web3storage" 13 | ) 14 | 15 | var ErrPinner = fmt.Errorf("unsupported pinner") 16 | 17 | const ( 18 | Infura = "infura" 19 | Pinata = "pinata" 20 | NFTStorage = "nftstorage" 21 | Web3Storage = "web3storage" 22 | ) 23 | 24 | // Config represents pinner's configuration. Pinner is the identifier of 25 | // the target IPFS service. 26 | type Config struct { 27 | *http.Client 28 | 29 | Pinner string 30 | Apikey string 31 | Secret string 32 | } 33 | 34 | // Pin pins a file to a network and returns a content id and an error. The file 35 | // is an interface to access the file. It's contents may be either stored in 36 | // memory or on disk. If stored on disk, it's underlying concrete type should 37 | // be a file path. If it is in memory, it should be an *io.Reader or byte slice. 38 | // 39 | //nolint:gocyclo 40 | func (cfg *Config) Pin(path interface{}) (cid string, err error) { 41 | // TODO using generics 42 | err = ErrPinner 43 | switch v := path.(type) { 44 | case string: 45 | _, err = os.Lstat(v) 46 | if err != nil { 47 | return 48 | } 49 | switch cfg.Pinner { 50 | case Infura: 51 | inf := &infura.Infura{Apikey: cfg.Apikey, Secret: cfg.Secret, Client: cfg.Client} 52 | cid, err = inf.PinFile(v) 53 | case Pinata: 54 | pnt := &pinata.Pinata{Apikey: cfg.Apikey, Secret: cfg.Secret, Client: cfg.Client} 55 | cid, err = pnt.PinFile(v) 56 | case NFTStorage: 57 | nft := &nftstorage.NFTStorage{Apikey: cfg.Apikey, Client: cfg.Client} 58 | cid, err = nft.PinFile(v) 59 | case Web3Storage: 60 | web3 := &web3storage.Web3Storage{Apikey: cfg.Apikey, Client: cfg.Client} 61 | cid, err = web3.PinFile(v) 62 | } 63 | case io.Reader: 64 | switch cfg.Pinner { 65 | case Infura: 66 | inf := &infura.Infura{Apikey: cfg.Apikey, Secret: cfg.Secret, Client: cfg.Client} 67 | cid, err = inf.PinWithReader(v) 68 | case Pinata: 69 | pnt := &pinata.Pinata{Apikey: cfg.Apikey, Secret: cfg.Secret, Client: cfg.Client} 70 | cid, err = pnt.PinWithReader(v) 71 | case NFTStorage: 72 | nft := &nftstorage.NFTStorage{Apikey: cfg.Apikey, Client: cfg.Client} 73 | cid, err = nft.PinWithReader(v) 74 | case Web3Storage: 75 | web3 := &web3storage.Web3Storage{Apikey: cfg.Apikey, Client: cfg.Client} 76 | cid, err = web3.PinWithReader(v) 77 | } 78 | case []byte: 79 | switch cfg.Pinner { 80 | case Infura: 81 | inf := &infura.Infura{Apikey: cfg.Apikey, Secret: cfg.Secret, Client: cfg.Client} 82 | cid, err = inf.PinWithBytes(v) 83 | case Pinata: 84 | pnt := &pinata.Pinata{Apikey: cfg.Apikey, Secret: cfg.Secret, Client: cfg.Client} 85 | cid, err = pnt.PinWithBytes(v) 86 | case NFTStorage: 87 | nft := &nftstorage.NFTStorage{Apikey: cfg.Apikey, Client: cfg.Client} 88 | cid, err = nft.PinWithBytes(v) 89 | case Web3Storage: 90 | web3 := &web3storage.Web3Storage{Apikey: cfg.Apikey, Client: cfg.Client} 91 | cid, err = web3.PinWithBytes(v) 92 | } 93 | } 94 | if err != nil { 95 | err = fmt.Errorf("%s: %w", cfg.Pinner, err) 96 | } 97 | 98 | return cid, err 99 | } 100 | 101 | // PinHash pins from any IPFS node, returns the original cid and an error. 102 | func (cfg *Config) PinHash(cid string) (string, error) { 103 | ok := false 104 | err := ErrPinner 105 | switch cfg.Pinner { 106 | case Infura: 107 | inf := &infura.Infura{Apikey: cfg.Apikey, Secret: cfg.Secret, Client: cfg.Client} 108 | ok, err = inf.PinHash(cid) 109 | case Pinata: 110 | pnt := &pinata.Pinata{Apikey: cfg.Apikey, Secret: cfg.Secret, Client: cfg.Client} 111 | ok, err = pnt.PinHash(cid) 112 | } 113 | if ok { 114 | return cid, nil 115 | } 116 | 117 | return "", err 118 | } 119 | 120 | // WithClient attach http.Client 121 | func (cfg *Config) WithClient(c *http.Client) *Config { 122 | cfg.Client = c 123 | return cfg 124 | } 125 | -------------------------------------------------------------------------------- /go.sum: -------------------------------------------------------------------------------- 1 | github.com/crackcomm/go-gitignore v0.0.0-20170627025303-887ab5e44cc3 h1:HVTnpeuvF6Owjd5mniCL8DEXo7uYXdQEmOP4FJbV5tg= 2 | github.com/crackcomm/go-gitignore v0.0.0-20170627025303-887ab5e44cc3/go.mod h1:p1d6YEZWvFzEh4KLyvBcVSnrfNDDvK2zfK/4x2v/4pE= 3 | github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= 4 | github.com/fortytw2/leaktest v1.3.0 h1:u8491cBMTQ8ft8aeV+adlcytMZylmA5nnwwkRZjI8vw= 5 | github.com/fortytw2/leaktest v1.3.0/go.mod h1:jDsjWgpAGjm2CA7WthBh/CdZYEPF31XHquHwclZch5g= 6 | github.com/ipfs/boxo v0.8.1 h1:3DkKBCK+3rdEB5t77WDShUXXhktYwH99mkAsgajsKrU= 7 | github.com/ipfs/boxo v0.8.1/go.mod h1:xJ2hVb4La5WyD7GvKYE0lq2g1rmQZoCD2K4WNrV6aZI= 8 | github.com/ipfs/go-cid v0.4.0 h1:a4pdZq0sx6ZSxbCizebnKiMCx/xI/aBBFlB73IgH4rA= 9 | github.com/ipfs/go-cid v0.4.0/go.mod h1:uQHwDeX4c6CtyrFwdqyhpNcxVewur1M7l7fNU7LKwZk= 10 | github.com/kennygrant/sanitize v1.2.4 h1:gN25/otpP5vAsO2djbMhF/LQX6R7+O1TB4yv8NzpJ3o= 11 | github.com/kennygrant/sanitize v1.2.4/go.mod h1:LGsjYYtgxbetdg5owWB2mpgUL6e2nfw2eObZ0u0qvak= 12 | github.com/klauspost/cpuid/v2 v2.0.4/go.mod h1:FInQzS24/EEf25PyTYn52gqo7WaD8xa0213Md/qVLRg= 13 | github.com/klauspost/cpuid/v2 v2.0.9/go.mod h1:FInQzS24/EEf25PyTYn52gqo7WaD8xa0213Md/qVLRg= 14 | github.com/klauspost/cpuid/v2 v2.2.3 h1:sxCkb+qR91z4vsqw4vGGZlDgPz3G7gjaLyK3V8y70BU= 15 | github.com/klauspost/cpuid/v2 v2.2.3/go.mod h1:RVVoqg1df56z8g3pUjL/3lE5UfnlrJX8tyFgg4nqhuY= 16 | github.com/mattn/go-isatty v0.0.18 h1:DOKFKCQ7FNG2L1rbrmstDN4QVRdS89Nkh85u68Uwp98= 17 | github.com/mattn/go-isatty v0.0.18/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y= 18 | github.com/minio/sha256-simd v1.0.0 h1:v1ta+49hkWZyvaKwrQB8elexRqm6Y0aMLjCNsrYxo6g= 19 | github.com/minio/sha256-simd v1.0.0/go.mod h1:OuYzVNI5vcoYIAmbIvHPl3N3jUzVedXbKy5RFepssQM= 20 | github.com/mr-tron/base58 v1.2.0 h1:T/HDJBh4ZCPbU39/+c3rRvE0uKBQlU27+QI8LJ4t64o= 21 | github.com/mr-tron/base58 v1.2.0/go.mod h1:BinMc/sQntlIE1frQmRFPUoPA1Zkr8VRgBdjWI2mNwc= 22 | github.com/multiformats/go-base32 v0.1.0 h1:pVx9xoSPqEIQG8o+UbAe7DNi51oej1NtK+aGkbLYxPE= 23 | github.com/multiformats/go-base32 v0.1.0/go.mod h1:Kj3tFY6zNr+ABYMqeUNeGvkIC/UYgtWibDcT0rExnbI= 24 | github.com/multiformats/go-base36 v0.2.0 h1:lFsAbNOGeKtuKozrtBsAkSVhv1p9D0/qedU9rQyccr0= 25 | github.com/multiformats/go-base36 v0.2.0/go.mod h1:qvnKE++v+2MWCfePClUEjE78Z7P2a1UV0xHgWc0hkp4= 26 | github.com/multiformats/go-multibase v0.1.1 h1:3ASCDsuLX8+j4kx58qnJ4YFq/JWTJpCyDW27ztsVTOI= 27 | github.com/multiformats/go-multibase v0.1.1/go.mod h1:ZEjHE+IsUrgp5mhlEAYjMtZwK1k4haNkcaPg9aoe1a8= 28 | github.com/multiformats/go-multihash v0.2.1 h1:aem8ZT0VA2nCHHk7bPJ1BjUbHNciqZC/d16Vve9l108= 29 | github.com/multiformats/go-multihash v0.2.1/go.mod h1:WxoMcYG85AZVQUyRyo9s4wULvW5qrI9vb2Lt6evduFc= 30 | github.com/multiformats/go-varint v0.0.7 h1:sWSGR+f/eu5ABZA2ZpYKBILXTTs9JWpdEM/nEGOHFS8= 31 | github.com/multiformats/go-varint v0.0.7/go.mod h1:r8PUYw/fD/SjBCiKOoDlGF6QawOELpZAu9eioSos/OU= 32 | github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= 33 | github.com/spaolacci/murmur3 v1.1.0 h1:7c1g84S4BPRrfL5Xrdp6fOJ206sU9y293DDHaoy0bLI= 34 | github.com/spaolacci/murmur3 v1.1.0/go.mod h1:JwIasOWyU6f++ZhiEuf87xNszmSA2myDM2Kzu9HwQUA= 35 | github.com/stretchr/testify v1.8.2 h1:+h33VjcLVPDHtOdpUCuF+7gSuG3yGIftsP1YvFihtJ8= 36 | github.com/wabarc/helper v0.0.0-20230418130954-be7440352bcb h1:psEAY4wXvhXp/Hp5CJWgAOKWqhvAom+/hOjK+Qscx7o= 37 | github.com/wabarc/helper v0.0.0-20230418130954-be7440352bcb/go.mod h1:S1N1F/2lwcHYqCowYTrR6i0DZ/1lcXKU+s+7rv5dUno= 38 | github.com/ybbus/httpretry v1.0.2 h1:QIU8dfSF+kZx5xO1bUcLKyxYNEUsLX/hsN6gN6Up1So= 39 | github.com/ybbus/httpretry v1.0.2/go.mod h1:fwOEa1URVFYikEqgQLCBtLyExFt5danZrxF5xF2qZh8= 40 | golang.org/x/crypto v0.6.0 h1:qfktjS5LUO+fFKeJXZ+ikTRijMmljikvG68fpMMruSc= 41 | golang.org/x/crypto v0.6.0/go.mod h1:OFC/31mSvZgRz0V1QTNCzfAI1aIRzbiufJtkMIlEp58= 42 | golang.org/x/net v0.9.0 h1:aWJ/m6xSmxWBx+V0XRHTlrYrPG56jKsLdTFmsSsCzOM= 43 | golang.org/x/net v0.9.0/go.mod h1:d48xBJpPfHeWQsugry2m+kC02ZBRGRgulfHnEXEuWns= 44 | golang.org/x/sys v0.0.0-20220704084225-05e143d24a9e/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= 45 | golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= 46 | golang.org/x/sys v0.7.0 h1:3jlCCIQZPdOYu1h8BkNvLz8Kgwtae2cagcG/VamtZRU= 47 | golang.org/x/sys v0.7.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= 48 | golang.org/x/text v0.9.0 h1:2sjJmO8cDvYveuX97RDLsxlyUxLl+GHoLxBiRdHllBE= 49 | golang.org/x/text v0.9.0/go.mod h1:e1OnstbJyHTd6l/uOt8jFFHp6TRDWZR/bV3emEE/zU8= 50 | gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= 51 | lukechampine.com/blake3 v1.1.7 h1:GgRMhmdsuK8+ii6UZFDL8Nb+VyMwadAgcJyfYHxG6n0= 52 | lukechampine.com/blake3 v1.1.7/go.mod h1:tkKEOtDkNtklkXtLNEOGNq5tcV90tJiA1vAA12R78LA= 53 | mvdan.cc/xurls/v2 v2.5.0 h1:lyBNOm8Wo71UknhUs4QTFUNNMyxy2JEIaKKo0RWOh+8= 54 | mvdan.cc/xurls/v2 v2.5.0/go.mod h1:yQgaGQ1rFtJUzkmKiHYSSfuQxqfYmd//X6PxvholpeE= 55 | -------------------------------------------------------------------------------- /Makefile: -------------------------------------------------------------------------------- 1 | export GO111MODULE = on 2 | export CGO_ENABLED = 0 3 | export GOPROXY = https://proxy.golang.org 4 | 5 | NAME = ipfs-pinner 6 | REPO = github.com/wabarc/ipfs-pinner 7 | BINDIR ?= ./build/binary 8 | PACKDIR ?= ./build/package 9 | LDFLAGS := $(shell echo "-X '${REPO}/version.Version=`git describe --tags --abbrev=0`'") 10 | LDFLAGS := $(shell echo "${LDFLAGS} -X '${REPO}/version.Commit=`git rev-parse --short HEAD`'") 11 | LDFLAGS := $(shell echo "${LDFLAGS} -X '${REPO}/version.BuildDate=`date +%FT%T%z`'") 12 | GOBUILD ?= go build -trimpath --ldflags "-s -w ${LDFLAGS} -buildid=" -v 13 | VERSION ?= $(shell git describe --tags `git rev-list --tags --max-count=1` | sed -e 's/v//g') 14 | GOFILES ?= $(wildcard ./cmd/ipfs-pinner/*.go) 15 | PROJECT := github.com/wabarc/ipfs-pinner 16 | PACKAGES ?= $(shell go list ./...) 17 | DOCKER ?= $(shell which docker || which podman) 18 | DOCKER_IMAGE := wabarc/ipfs-pinner 19 | DEB_IMG_ARCH := amd64 20 | 21 | .DEFAULT_GOAL := help 22 | 23 | .PHONY: help 24 | help: ## show help message 25 | @awk 'BEGIN {FS = ":.*##"; printf "Usage:\n make \n\nTargets: \033[36m\033[0m\n"} /^[$$()% 0-9a-zA-Z_-]+:.*?##/ { printf " \033[36m%-15s\033[0m %s\n", $$1, $$2 } /^##@/ { printf "\n\033[1m%s\033[0m\n", substr($$0, 5) } ' $(MAKEFILE_LIST) 26 | 27 | PLATFORM_LIST = \ 28 | darwin-amd64 \ 29 | darwin-arm64 \ 30 | linux-386 \ 31 | linux-amd64 \ 32 | linux-armv5 \ 33 | linux-armv6 \ 34 | linux-armv7 \ 35 | linux-arm64 \ 36 | linux-mips-softfloat \ 37 | linux-mips-hardfloat \ 38 | linux-mipsle-softfloat \ 39 | linux-mipsle-hardfloat \ 40 | linux-mips64 \ 41 | linux-mips64le \ 42 | linux-ppc64 \ 43 | linux-ppc64le \ 44 | linux-s390x \ 45 | freebsd-386 \ 46 | freebsd-amd64 \ 47 | freebsd-arm64 \ 48 | openbsd-386 \ 49 | openbsd-amd64 \ 50 | dragonfly-amd64 \ 51 | android-arm64 52 | 53 | WINDOWS_ARCH_LIST = \ 54 | windows-386 \ 55 | windows-amd64 \ 56 | windows-arm \ 57 | windows-arm64 58 | 59 | .PHONY: \ 60 | all-arch \ 61 | tar_releases \ 62 | zip_releases \ 63 | releases \ 64 | clean \ 65 | test \ 66 | fmt 67 | 68 | .SECONDEXPANSION: 69 | %: ## Build binary, format: linux-amd64, darwin-arm64, full list: https://golang.org/doc/install/source#environment 70 | $(eval OS := $(shell echo $@ | cut -d'-' -f1)) 71 | $(eval ARM := $(shell echo $@ | cut -d'-' -f2 | grep arm | sed -e 's/arm64//' | tr -dc '[0-9]')) 72 | $(eval ARCH := $(shell echo $@ | cut -d'-' -f2 | sed -e 's/armv.*/arm/' | grep -v $(OS))) 73 | $(eval MIPS := $(shell echo $@ | cut -d'-' -f3)) 74 | $(if $(strip $(OS)),,$(error missing OS)) 75 | $(if $(strip $(ARCH)),,$(error missing ARCH)) 76 | GOOS="$(OS)" GOARCH="$(ARCH)" GOMIPS="$(MIPS)" GOARM="$(ARM)" $(GOBUILD) -o $(BINDIR)/$(NAME)-$@ $(GOFILES) 77 | 78 | .PHONY: build 79 | build: ## Build binary for current OS 80 | $(GOBUILD) -o $(BINDIR)/$(NAME) $(GOFILES) 81 | 82 | .PHONY: linux-armv8 83 | linux-armv8: linux-arm64 84 | 85 | ifeq ($(TARGET),) 86 | tar_releases := $(addsuffix .gz, $(PLATFORM_LIST)) 87 | zip_releases := $(addsuffix .zip, $(WINDOWS_ARCH_LIST)) 88 | else 89 | ifeq ($(findstring windows,$(TARGET)),windows) 90 | zip_releases := $(addsuffix .zip, $(TARGET)) 91 | else 92 | tar_releases := $(addsuffix .gz, $(TARGET)) 93 | endif 94 | endif 95 | 96 | $(tar_releases): %.gz : % 97 | chmod +x $(BINDIR)/$(NAME)-$(basename $@) 98 | tar -czf $(PACKDIR)/$(NAME)-$(basename $@)-$(VERSION).tar.gz --transform "s/.*\///g" $(BINDIR)/$(NAME)-$(basename $@) LICENSE README.md 99 | 100 | $(zip_releases): %.zip : % 101 | @mv $(BINDIR)/$(NAME)-$(basename $@) $(BINDIR)/$(NAME)-$(basename $@).exe 102 | zip -m -j $(PACKDIR)/$(NAME)-$(basename $@)-$(VERSION).zip $(BINDIR)/$(NAME)-$(basename $@).exe LICENSE README.md 103 | 104 | all-arch: $(PLATFORM_LIST) $(WINDOWS_ARCH_LIST) ## Build binary for all architecture 105 | 106 | releases: $(tar_releases) $(zip_releases) ## Packaging all binaries 107 | 108 | clean: ## Clean workspace 109 | rm -f $(BINDIR)/* 110 | rm -f $(PACKDIR)/* 111 | rm -rf data-dir* 112 | rm -rf coverage* 113 | rm -rf *.out 114 | 115 | fmt: ## Format codebase 116 | @echo "-> Running go fmt" 117 | @go fmt $(PACKAGES) 118 | 119 | vet: ## Vet codebase 120 | @echo "-> Running go vet" 121 | @go vet $(PACKAGES) 122 | 123 | test: ## Run testing 124 | @echo "-> Running go test" 125 | @go clean -testcache 126 | @CGO_ENABLED=1 go test -v -race -cover -coverprofile=coverage.out -covermode=atomic -parallel=1 ./... 127 | 128 | test-integration: ## Run integration testing 129 | @echo 'mode: atomic' > coverage.out 130 | @go list ./... | xargs -n1 -I{} sh -c 'CGO_ENABLED=1 go test -race -tags=integration -covermode=atomic -coverprofile=coverage.tmp -coverpkg $(go list ./... | tr "\n" ",") {} && tail -n +2 coverage.tmp >> coverage.out || exit 255' 131 | @rm coverage.tmp 132 | 133 | test-cover: ## Collect code coverage 134 | @echo "-> Running go tool cover" 135 | @go tool cover -func=coverage.out 136 | @go tool cover -html=coverage.out -o coverage.html 137 | 138 | scan: ## Scan vulnerabilities 139 | @echo "-> Scanning vulnerabilities..." 140 | @go list -json -m all | $(DOCKER) run --rm -i sonatypecommunity/nancy sleuth --skip-update-check 141 | -------------------------------------------------------------------------------- /file/multifile.go: -------------------------------------------------------------------------------- 1 | package file 2 | 3 | import ( 4 | "bytes" 5 | "fmt" 6 | "io" 7 | "mime/multipart" 8 | "net/textproto" 9 | "os" 10 | "path/filepath" 11 | "sync" 12 | 13 | "github.com/ipfs/boxo/files" 14 | ) 15 | 16 | // MultiFileReader reads from a `commands.Node` (which can be a directory of 17 | // files or a regular file) as HTTP multipart encoded data. 18 | type MultiFileReader struct { 19 | io.Reader 20 | 21 | mpWriter *multipart.Writer 22 | mutex *sync.Mutex 23 | } 24 | 25 | // NewMultiFileReader constructs a files.MultiFileReader via github.com/ipfs/go-ipfs-files. 26 | // `path` can be any `commands.Directory`. If `form` is set to true, the Content-Disposition 27 | // will be "form-data". Otherwise, it will be "attachment". 28 | // 29 | // It returns an io.Reader and error. 30 | func NewMultiFileReader(path string, form bool) (*files.MultiFileReader, error) { 31 | stat, err := os.Lstat(path) 32 | if err != nil { 33 | return nil, err 34 | } 35 | 36 | file, err := files.NewSerialFile(path, false, stat) 37 | if err != nil { 38 | return nil, err 39 | } 40 | d := files.NewMapDirectory(map[string]files.Node{"": file}) // unwrapped on the other side 41 | 42 | return files.NewMultiFileReader(d, form), nil 43 | } 44 | 45 | // CreateMultiForm constructs a MultiFileReader. `path` should be a Node in serialfile. 46 | // If `form` is set to true, the Content-Disposition will be "form-data". 47 | // Otherwise, it will be "attachment". 48 | // 49 | // It returns an io.Reader and error. 50 | // 51 | // Example: 52 | // 53 | // > node, err := file.NewSerialFile("directory-path") 54 | // > 55 | // > node.MapDirectory("a-dir-name-show-in-pinning-service") 56 | func CreateMultiForm(node *Node, form bool) (mfr *MultiFileReader, err error) { 57 | if len(node.files) == 0 { 58 | return mfr, fmt.Errorf("node.files empty") 59 | } 60 | 61 | dispositionPrefix := "attachment" 62 | if form { 63 | dispositionPrefix = "form-data" 64 | } 65 | 66 | // New multipart writer. 67 | body := &bytes.Buffer{} 68 | writer := multipart.NewWriter(body) 69 | 70 | // // Metadata part. 71 | // metadataHeader := textproto.MIMEHeader{} 72 | // metadataHeader.Set("Content-Disposition", fmt.Sprintf(`%s; filename="folderName"`, dispositionPrefix)) 73 | // metadataHeader.Set("Content-Type", "application/x-directory") 74 | // // Metadata content. 75 | // part, err := writer.CreatePart(metadataHeader) 76 | // if err != nil { 77 | // return nil, fmt.Errorf("Error writing metadata headers: %v", err) 78 | // } 79 | // part.Write([]byte(metadataHeader)) 80 | 81 | type meta struct { 82 | key string 83 | name string 84 | data string 85 | } 86 | metadata := []meta{ 87 | // For pinata 88 | { 89 | key: "Content-Disposition", 90 | name: fmt.Sprintf(`%s; name="pinataMetadata"`, dispositionPrefix), 91 | data: fmt.Sprintf(`{"name":"%s"}`, filepath.Base(node.base)), 92 | }, 93 | { 94 | key: "Content-Disposition", 95 | name: fmt.Sprintf(`%s; name="pinataOptions"`, dispositionPrefix), 96 | data: `{"cidVersion":"1","wrapWithDirectory":false}`, 97 | }, 98 | } 99 | for _, m := range metadata { 100 | header := textproto.MIMEHeader{} 101 | header.Set(m.key, m.name) 102 | part, err := writer.CreatePart(header) 103 | if err != nil { 104 | return nil, fmt.Errorf("error writing metadata headers: %v", err) 105 | } 106 | _, _ = part.Write([]byte(m.data)) 107 | } 108 | 109 | for _, fp := range node.paths { 110 | fn := node.root 111 | switch { 112 | case node.stat.IsDir(): 113 | fn = filepath.Join(node.root, fp) 114 | case node.stat.Mode().IsRegular(): 115 | fp = filepath.Base(fn) 116 | } 117 | f, err := os.Open(fn) 118 | if err != nil { 119 | return mfr, fmt.Errorf("error reading media file: %v", err) 120 | } 121 | defer f.Close() 122 | 123 | filename := filepath.Join(node.base, fp) 124 | // absPath, _ := filepath.Abs(fn) 125 | mediaHeader := textproto.MIMEHeader{} 126 | // mediaHeader.Set("Abspath", absPath) 127 | mediaHeader.Set("Content-Disposition", fmt.Sprintf(`%s; name="file"; filename="%s"`, dispositionPrefix, filename)) 128 | mediaHeader.Set("Content-Type", "application/octet-stream") 129 | part, err := writer.CreatePart(mediaHeader) 130 | if err != nil { 131 | return mfr, fmt.Errorf("error writing media headers: %v", err) 132 | } 133 | 134 | if _, err := io.Copy(part, f); err != nil { 135 | return mfr, fmt.Errorf("error writing media: %v", err) 136 | } 137 | } 138 | 139 | // Close multipart writer. 140 | if err := writer.Close(); err != nil { 141 | return mfr, fmt.Errorf("error closing multipart writer: %v", err) 142 | } 143 | 144 | return &MultiFileReader{ 145 | bytes.NewReader(body.Bytes()), 146 | writer, 147 | &sync.Mutex{}, 148 | }, nil 149 | } 150 | 151 | // TODO: create multipart via Read 152 | // func (mfr *MultiFileReader) Read(buf []byte) (written int, err error) { 153 | // return 154 | // } 155 | 156 | func (mfr *MultiFileReader) Write(header textproto.MIMEHeader, content []byte) error { 157 | part, err := mfr.mpWriter.CreatePart(header) 158 | if err != nil { 159 | return fmt.Errorf("write header failed: %v", err) 160 | } 161 | _, _ = part.Write(content) 162 | 163 | return nil 164 | } 165 | 166 | // Boundary returns the boundary string to be used to separate files in the multipart data 167 | func (mfr *MultiFileReader) Boundary() string { 168 | return mfr.mpWriter.Boundary() 169 | } 170 | -------------------------------------------------------------------------------- /pkg/web3storage/web3storage_test.go: -------------------------------------------------------------------------------- 1 | package web3storage 2 | 3 | import ( 4 | "bytes" 5 | "io" 6 | "io/ioutil" 7 | "mime" 8 | "mime/multipart" 9 | "net/http" 10 | "os" 11 | "strings" 12 | "testing" 13 | 14 | "github.com/ipfs/go-cid" 15 | "github.com/wabarc/helper" 16 | ) 17 | 18 | var ( 19 | unauthorizedJSON = `{ 20 | "name": "HTTP Error", 21 | "message": "Unauthorized" 22 | }` 23 | badRequestJSON = `{ 24 | "name": "string", 25 | "message": "string" 26 | }` 27 | uploadJSON = `{ 28 | "cid": "bafkreidivzimqfqtoqxkrpge6bjyhlvxqs3rhe73owtmdulaxr5do5in7u" 29 | }` 30 | ) 31 | 32 | func handleResponse(w http.ResponseWriter, r *http.Request) { 33 | authorization := r.Header.Get("Authorization") 34 | if len(authorization) < 10 { 35 | w.WriteHeader(http.StatusUnauthorized) 36 | _, _ = w.Write([]byte(unauthorizedJSON)) 37 | return 38 | } 39 | switch r.URL.Path { 40 | case "/upload": 41 | _ = r.ParseMultipartForm(32 << 20) 42 | _, params, parseErr := mime.ParseMediaType(r.Header.Get("Content-Type")) 43 | if parseErr != nil { 44 | w.WriteHeader(http.StatusBadRequest) 45 | _, _ = w.Write([]byte(badRequestJSON)) 46 | return 47 | } 48 | 49 | multipartReader := multipart.NewReader(r.Body, params["boundary"]) 50 | defer r.Body.Close() 51 | 52 | // Pin directory 53 | if multipartReader != nil && len(r.MultipartForm.File["file"]) > 1 { 54 | _, _ = w.Write([]byte(uploadJSON)) 55 | return 56 | } 57 | // Pin file 58 | if multipartReader != nil && len(r.MultipartForm.File["file"]) == 1 { 59 | _, _ = w.Write([]byte(uploadJSON)) 60 | return 61 | } 62 | } 63 | w.WriteHeader(http.StatusBadRequest) 64 | _, _ = w.Write([]byte(badRequestJSON)) 65 | } 66 | 67 | func TestPinFile(t *testing.T) { 68 | httpClient, mux, server := helper.MockServer() 69 | mux.HandleFunc("/", handleResponse) 70 | defer server.Close() 71 | 72 | content := []byte(helper.RandString(6, "lower")) 73 | tmpfile, err := ioutil.TempFile("", "ipfs-pinner-") 74 | if err != nil { 75 | t.Fatal(err) 76 | } 77 | defer os.Remove(tmpfile.Name()) 78 | 79 | if _, err := tmpfile.Write(content); err != nil { 80 | t.Fatal(err) 81 | } 82 | 83 | web3 := &Web3Storage{Apikey: "fake-web3-storage-apikey", Client: httpClient} 84 | if _, err := web3.PinFile(tmpfile.Name()); err != nil { 85 | t.Error(err) 86 | } 87 | } 88 | 89 | func TestPinWithReader(t *testing.T) { 90 | httpClient, mux, server := helper.MockServer() 91 | mux.HandleFunc("/", handleResponse) 92 | defer server.Close() 93 | 94 | content := []byte(helper.RandString(6, "lower")) 95 | tmpfile, err := ioutil.TempFile("", "ipfs-pinner-") 96 | if err != nil { 97 | t.Fatal(err) 98 | } 99 | defer os.Remove(tmpfile.Name()) 100 | if _, err := tmpfile.Write(content); err != nil { 101 | t.Fatal(err) 102 | } 103 | 104 | fr, _ := os.Open(tmpfile.Name()) 105 | tests := []struct { 106 | name string 107 | file interface{} 108 | }{ 109 | {"os.File", fr}, 110 | {"strings.Reader", strings.NewReader(helper.RandString(6, "lower"))}, 111 | {"bytes.Buffer", bytes.NewBufferString(helper.RandString(6, "lower"))}, 112 | } 113 | 114 | web3 := &Web3Storage{Apikey: "fake-web3-storage-apikey", Client: httpClient} 115 | for _, test := range tests { 116 | t.Run(test.name, func(t *testing.T) { 117 | file := test.file.(io.Reader) 118 | if _, err := web3.PinWithReader(file); err != nil { 119 | t.Error(err) 120 | } 121 | }) 122 | } 123 | } 124 | 125 | func TestPinWithBytes(t *testing.T) { 126 | httpClient, mux, server := helper.MockServer() 127 | mux.HandleFunc("/", handleResponse) 128 | defer server.Close() 129 | 130 | web3 := &Web3Storage{Apikey: "fake-web3-storage-apikey", Client: httpClient} 131 | buf := []byte(helper.RandString(6, "lower")) 132 | if _, err := web3.PinWithBytes(buf); err != nil { 133 | t.Error(err) 134 | } 135 | } 136 | 137 | func TestPinDir(t *testing.T) { 138 | dir, err := ioutil.TempDir("", "ipfs-pinner-dir-") 139 | if err != nil { 140 | t.Fatalf("Unexpected create directory: %v", err) 141 | } 142 | defer os.RemoveAll(dir) 143 | subdir, err := ioutil.TempDir(dir, "ipfs-pinner-subdir-") 144 | 145 | // Create files 146 | for i := 1; i <= 2; i++ { 147 | f, err := ioutil.TempFile(dir, "file-") 148 | if err != nil { 149 | t.Fatal("Unexpected create file") 150 | } 151 | content := []byte(helper.RandString(6, "lower")) 152 | if _, err := f.Write(content); err != nil { 153 | t.Fatal("Unexpected write content to file") 154 | } 155 | } 156 | // Write file to subdirectory 157 | f, err := ioutil.TempFile(subdir, "file-in-subdir-") 158 | if err != nil { 159 | t.Fatal("Unexpected create file") 160 | } 161 | content := []byte(helper.RandString(6, "lower")) 162 | if _, err := f.Write(content); err != nil { 163 | t.Fatal("Unexpected write content to file") 164 | } 165 | 166 | httpClient, mux, server := helper.MockServer() 167 | mux.HandleFunc("/", handleResponse) 168 | defer server.Close() 169 | 170 | web3 := &Web3Storage{Apikey: "fake-web3-storage-apikey", Client: httpClient} 171 | o, err := web3.PinDir(dir) 172 | if err != nil { 173 | t.Fatalf("Unexpected pin directory: %v", err) 174 | } 175 | _, err = cid.Parse(o) 176 | if err != nil { 177 | t.Fatalf("Invalid cid: %v", o) 178 | } 179 | } 180 | 181 | func TestPinHash(t *testing.T) { 182 | t.Skip("Not yet supported") 183 | 184 | httpClient, mux, server := helper.MockServer() 185 | mux.HandleFunc("/", handleResponse) 186 | defer server.Close() 187 | 188 | hash := "Qmaisz6NMhDB51cCvNWa1GMS7LU1pAxdF4Ld6Ft9kZEP2a" 189 | 190 | web3 := &Web3Storage{Apikey: "fake-web3-storage-apikey", Client: httpClient} 191 | if ok, err := web3.PinHash(hash); !ok || err != nil { 192 | t.Error(err) 193 | } 194 | } 195 | -------------------------------------------------------------------------------- /pkg/infura/infura.go: -------------------------------------------------------------------------------- 1 | package infura 2 | 3 | import ( 4 | "encoding/json" 5 | "fmt" 6 | "io" 7 | "io/ioutil" 8 | "mime/multipart" 9 | "net/http" 10 | 11 | "github.com/ipfs/boxo/files" 12 | "github.com/wabarc/helper" 13 | "github.com/wabarc/ipfs-pinner/file" 14 | 15 | httpretry "github.com/wabarc/ipfs-pinner/http" 16 | ) 17 | 18 | const api = "https://ipfs.infura.io:5001" 19 | 20 | // Infura represents an Infura configuration. If there is no Apikey or 21 | // Secret, it will make API calls using anonymous requests. 22 | type Infura struct { 23 | *http.Client 24 | 25 | Apikey string 26 | Secret string 27 | } 28 | 29 | type addEvent struct { 30 | Name string 31 | Hash string `json:",omitempty"` 32 | Bytes int64 `json:",omitempty"` 33 | Size string `json:",omitempty"` 34 | } 35 | 36 | // PinFile alias to *Infura.PinFile, the purpose is to be backwards 37 | // compatible with the original function. 38 | // 39 | // Deprecated: use `Infura.PinFile` instead. 40 | func PinFile(fp string) (string, error) { 41 | return (&Infura{}).PinFile(fp) 42 | } 43 | 44 | // PinFile pins content to Infura by providing a file path, it returns an IPFS 45 | // hash and an error. 46 | func (inf *Infura) PinFile(fp string) (string, error) { 47 | mfr, err := file.NewMultiFileReader(fp, false) 48 | if err != nil { 49 | return "", fmt.Errorf("unexpected creates multipart file: %v", err) 50 | } 51 | boundary := "multipart/form-data; boundary=" + mfr.Boundary() 52 | 53 | return inf.pinFile(mfr, boundary) 54 | } 55 | 56 | // PinWithReader pins content to Infura by given io.Reader, it returns an IPFS hash and an error. 57 | func (inf *Infura) PinWithReader(rd io.Reader) (string, error) { 58 | r, w := io.Pipe() 59 | m := multipart.NewWriter(w) 60 | fn := helper.RandString(6, "lower") 61 | 62 | go func() { 63 | defer w.Close() 64 | defer m.Close() 65 | 66 | part, err := m.CreateFormFile("file", fn) 67 | if err != nil { 68 | return 69 | } 70 | 71 | if _, err = io.Copy(part, rd); err != nil { 72 | return 73 | } 74 | }() 75 | 76 | return inf.pinFile(r, m.FormDataContentType()) 77 | } 78 | 79 | // PinWithBytes pins content to Infura by given byte slice, it returns an IPFS hash and an error. 80 | func (inf *Infura) PinWithBytes(buf []byte) (string, error) { 81 | r, w := io.Pipe() 82 | m := multipart.NewWriter(w) 83 | fn := helper.RandString(6, "lower") 84 | 85 | go func() { 86 | defer w.Close() 87 | defer m.Close() 88 | 89 | part, err := m.CreateFormFile("file", fn) 90 | if err != nil { 91 | return 92 | } 93 | 94 | if _, err = part.Write(buf); err != nil { 95 | return 96 | } 97 | }() 98 | 99 | return inf.pinFile(r, m.FormDataContentType()) 100 | } 101 | 102 | func (inf *Infura) pinFile(r io.Reader, boundary string) (string, error) { 103 | endpoint := api + "/api/v0/add?cid-version=1&pin=true" 104 | client := httpretry.NewClient(inf.Client) 105 | 106 | req, err := http.NewRequest(http.MethodPost, endpoint, r) 107 | if err != nil { 108 | return "", err 109 | } 110 | if inf.Apikey != "" && inf.Secret != "" { 111 | req.SetBasicAuth(inf.Apikey, inf.Secret) 112 | } 113 | req.Header.Add("Content-Type", boundary) 114 | req.Header.Set("Content-Disposition", `form-data; name="files"`) 115 | resp, err := client.Do(req) 116 | if err != nil { 117 | return "", err 118 | } 119 | defer resp.Body.Close() 120 | 121 | // It limits anonymous requests to 12 write requests/min. 122 | // https://infura.io/docs/ipfs#section/Rate-Limits/API-Anonymous-Requests 123 | if resp.StatusCode != http.StatusOK { 124 | return "", fmt.Errorf(resp.Status) 125 | } 126 | 127 | var out addEvent 128 | dec := json.NewDecoder(resp.Body) 129 | loop: 130 | for { 131 | var evt addEvent 132 | switch err := dec.Decode(&evt); err { 133 | case nil: 134 | case io.EOF: 135 | break loop 136 | default: 137 | return "", err 138 | } 139 | out = evt 140 | } 141 | 142 | return out.Hash, nil 143 | } 144 | 145 | // PinHash alias to *Infura.PinHash, the purpose is to be backwards 146 | // compatible with the original function. 147 | func PinHash(hash string) (bool, error) { 148 | return (&Infura{}).PinHash(hash) 149 | } 150 | 151 | // PinHash pins content to Infura by giving an IPFS hash, it returns the result and an error. 152 | func (inf *Infura) PinHash(hash string) (bool, error) { 153 | if hash == "" { 154 | return false, fmt.Errorf("invalid hash: %s", hash) 155 | } 156 | 157 | endpoint := fmt.Sprintf("%s/api/v0/pin/add?arg=%s", api, hash) 158 | req, err := http.NewRequest(http.MethodPost, endpoint, nil) 159 | if err != nil { 160 | return false, err 161 | } 162 | if inf.Apikey != "" && inf.Secret != "" { 163 | req.SetBasicAuth(inf.Apikey, inf.Secret) 164 | } 165 | client := httpretry.NewClient(inf.Client) 166 | resp, err := client.Do(req) 167 | if err != nil { 168 | return false, err 169 | } 170 | defer resp.Body.Close() 171 | 172 | // It limits anonymous requests to 12 write requests/min. 173 | // https://infura.io/docs/ipfs#section/Rate-Limits/API-Anonymous-Requests 174 | if resp.StatusCode != http.StatusOK { 175 | return false, fmt.Errorf(resp.Status) 176 | } 177 | 178 | data, err := ioutil.ReadAll(resp.Body) 179 | if err != nil { 180 | return false, err 181 | } 182 | 183 | var dat map[string]interface{} 184 | if err := json.Unmarshal(data, &dat); err != nil { 185 | if e, ok := err.(*json.SyntaxError); ok { 186 | return false, fmt.Errorf("json syntax error at byte offset %d", e.Offset) 187 | } 188 | return false, err 189 | } 190 | 191 | if h, ok := dat["Pins"].([]interface{}); ok && len(h) > 0 { 192 | return h[0] == hash, nil 193 | } 194 | 195 | return false, fmt.Errorf("pin hash to Infura failed") 196 | } 197 | 198 | // PinDir pins a directory to the Infura pinning service. 199 | func (inf *Infura) PinDir(mfr *files.MultiFileReader) (string, error) { 200 | boundary := "multipart/form-data; boundary=" + mfr.Boundary() 201 | return inf.pinFile(mfr, boundary) 202 | } 203 | -------------------------------------------------------------------------------- /pkg/pinata/pinata.go: -------------------------------------------------------------------------------- 1 | package pinata 2 | 3 | import ( 4 | "bytes" 5 | "encoding/json" 6 | "fmt" 7 | "io" 8 | "io/ioutil" 9 | "mime/multipart" 10 | "net/http" 11 | "path/filepath" 12 | 13 | "github.com/wabarc/helper" 14 | "github.com/wabarc/ipfs-pinner/file" 15 | 16 | httpretry "github.com/wabarc/ipfs-pinner/http" 17 | ) 18 | 19 | const ( 20 | PIN_FILE_URL = "https://api.pinata.cloud/pinning/pinFileToIPFS" 21 | PIN_HASH_URL = "https://api.pinata.cloud/pinning/pinByHash" 22 | ) 23 | 24 | // Pinata represents a Pinata configuration. 25 | type Pinata struct { 26 | *http.Client 27 | 28 | Apikey string 29 | Secret string 30 | } 31 | 32 | type addEvent struct { 33 | IpfsHash string 34 | PinSize int64 `json:",omitempty"` 35 | Timestamp string `json:",omitempty"` 36 | } 37 | 38 | // PinFile pins content to Pinata by providing a file path, it returns an IPFS 39 | // hash and an error. 40 | func (p *Pinata) PinFile(fp string) (string, error) { 41 | f, err := file.NewSerialFile(fp) 42 | if err != nil { 43 | return "", err 44 | } 45 | f.MapDirectory(filepath.Base(fp)) 46 | 47 | mfr, err := file.CreateMultiForm(f, true) 48 | if err != nil { 49 | return "", err 50 | } 51 | boundary := "multipart/form-data; boundary=" + mfr.Boundary() 52 | 53 | return p.pinFile(mfr, boundary) 54 | } 55 | 56 | // PinWithReader pins content to Pinata by given io.Reader, it returns an IPFS hash and an error. 57 | func (p *Pinata) PinWithReader(rd io.Reader) (string, error) { 58 | r, w := io.Pipe() 59 | m := multipart.NewWriter(w) 60 | fn := helper.RandString(6, "lower") 61 | 62 | go func() { 63 | defer w.Close() 64 | defer m.Close() 65 | 66 | part, err := m.CreateFormFile("file", fn) 67 | if err != nil { 68 | return 69 | } 70 | 71 | if _, err = io.Copy(part, rd); err != nil { 72 | return 73 | } 74 | }() 75 | 76 | return p.pinFile(r, m.FormDataContentType()) 77 | } 78 | 79 | // PinWithBytes pins content to Infura by given byte slice, it returns an IPFS hash and an error. 80 | func (p *Pinata) PinWithBytes(buf []byte) (string, error) { 81 | r, w := io.Pipe() 82 | m := multipart.NewWriter(w) 83 | fn := helper.RandString(6, "lower") 84 | 85 | go func() { 86 | defer w.Close() 87 | defer m.Close() 88 | 89 | // m.WriteField("pinataOptions", `{cidVersion: 1}`) 90 | part, err := m.CreateFormFile("file", fn) 91 | if err != nil { 92 | return 93 | } 94 | 95 | if _, err = part.Write(buf); err != nil { 96 | return 97 | } 98 | }() 99 | 100 | return p.pinFile(r, m.FormDataContentType()) 101 | } 102 | 103 | func (p *Pinata) pinFile(r io.Reader, boundary string) (string, error) { 104 | // if fr, ok := r.(*file.MultiFileReader); ok { 105 | // // Metadata part. 106 | // metadataHeader := textproto.MIMEHeader{} 107 | // metadataHeader.Set("Content-Disposition", `form-data; name="pinataMetadata"`) 108 | // // Metadata content. 109 | // metadata := fmt.Sprintf(`{"name":"%s"}`, "adsasdfa") 110 | // fr.Write(metadataHeader, []byte(metadata)) 111 | 112 | // // options part. 113 | // optsHeader := textproto.MIMEHeader{} 114 | // optsHeader.Set("Content-Disposition", `form-data; name="pinataOptions"`) 115 | // // options content. 116 | // opts := `{"cidVersion":"1","wrapWithDirectory":false}` 117 | // fr.Write(optsHeader, []byte(opts)) 118 | // } 119 | req, err := http.NewRequest(http.MethodPost, PIN_FILE_URL, r) 120 | if err != nil { 121 | return "", err 122 | } 123 | req.Header.Add("Content-Type", boundary) 124 | if p.Secret != "" && p.Apikey != "" { 125 | req.Header.Add("pinata_secret_api_key", p.Secret) 126 | req.Header.Add("pinata_api_key", p.Apikey) 127 | } else { 128 | req.Header.Add("Authorization", "Bearer "+p.Apikey) 129 | } 130 | 131 | client := httpretry.NewClient(p.Client) 132 | resp, err := client.Do(req) 133 | if err != nil { 134 | return "", err 135 | } 136 | defer resp.Body.Close() 137 | 138 | if resp.StatusCode != http.StatusOK { 139 | return "", fmt.Errorf(resp.Status) 140 | } 141 | 142 | data, err := ioutil.ReadAll(resp.Body) 143 | if err != nil { 144 | return "", err 145 | } 146 | 147 | var out addEvent 148 | if err := json.Unmarshal(data, &out); err != nil { 149 | if e, ok := err.(*json.SyntaxError); ok { 150 | return "", fmt.Errorf("json syntax error at byte offset %d", e.Offset) 151 | } 152 | return "", err 153 | } 154 | 155 | return out.IpfsHash, nil 156 | } 157 | 158 | // PinHash pins content to Pinata by giving an IPFS hash, it returns the result and an error. 159 | func (p *Pinata) PinHash(hash string) (bool, error) { 160 | if hash == "" { 161 | return false, fmt.Errorf("invalid hash: %s", hash) 162 | } 163 | 164 | jsonValue, _ := json.Marshal(map[string]string{"hashToPin": hash}) 165 | 166 | req, err := http.NewRequest(http.MethodPost, PIN_HASH_URL, bytes.NewBuffer(jsonValue)) 167 | if err != nil { 168 | return false, err 169 | } 170 | req.Header.Set("Content-Type", "application/json") 171 | if p.Secret != "" && p.Apikey != "" { 172 | req.Header.Add("pinata_secret_api_key", p.Secret) 173 | req.Header.Add("pinata_api_key", p.Apikey) 174 | } else { 175 | req.Header.Add("Authorization", "Bearer "+p.Apikey) 176 | } 177 | 178 | client := httpretry.NewClient(p.Client) 179 | resp, err := client.Do(req) 180 | if err != nil { 181 | return false, err 182 | } 183 | defer resp.Body.Close() 184 | 185 | if resp.StatusCode != http.StatusOK { 186 | return false, fmt.Errorf(resp.Status) 187 | } 188 | 189 | data, err := ioutil.ReadAll(resp.Body) 190 | if err != nil { 191 | return false, err 192 | } 193 | 194 | var dat map[string]interface{} 195 | if err := json.Unmarshal(data, &dat); err != nil { 196 | if e, ok := err.(*json.SyntaxError); ok { 197 | return false, fmt.Errorf("json syntax error at byte offset %d", e.Offset) 198 | } 199 | return false, err 200 | } 201 | 202 | if h, ok := dat["hashToPin"].(string); ok { 203 | return h == hash, nil 204 | } 205 | 206 | return false, fmt.Errorf("pin hash to Pinata failed") 207 | } 208 | 209 | // PinDir pins a directory to the Pinata pinning service. 210 | // It alias to PinFile. 211 | func (p *Pinata) PinDir(name string) (string, error) { 212 | return p.PinFile(name) 213 | } 214 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # ipfs-pinner 2 | 3 | [![Go Report Card](https://goreportcard.com/badge/github.com/wabarc/ipfs-pinner)](https://goreportcard.com/report/github.com/wabarc/ipfs-pinner) 4 | [![Go Reference](https://img.shields.io/badge/godoc-reference-blue.svg)](https://pkg.go.dev/github.com/wabarc/ipfs-pinner) 5 | [![Releases](https://img.shields.io/github/v/release/wabarc/ipfs-pinner.svg?include_prereleases&color=blue)](https://github.com/wabarc/ipfs-pinner/releases) 6 | [![ipfs-pinner](https://snapcraft.io/ipfs-pinner/badge.svg)](https://snapcraft.io/ipfs-pinner) 7 | 8 | `ipfs-pinner` is a toolkit to help upload files or specific content id to IPFS pinning services. 9 | 10 | Supported Golang version: See [.github/workflows/testing.yml](./.github/workflows/testing.yml) 11 | 12 | ## Installation 13 | 14 | Via Golang package get command 15 | 16 | ```sh 17 | go get -u github.com/wabarc/ipfs-pinner/cmd/ipfs-pinner 18 | ``` 19 | 20 | Using [Snapcraft](https://snapcraft.io/ipfs-pinner) (on GNU/Linux) 21 | 22 | ```sh 23 | snap install ipfs-pinner 24 | ``` 25 | 26 | ## Usage 27 | 28 | ### Supported Pinning Services 29 | 30 | #### [Infura](https://infura.io) 31 | 32 | Infura is a freemium pinning service that doesn't require any additional setup. 33 | It's the default one used. Please bear in mind that Infura is a free service, 34 | so there is probably a rate-limiting. 35 | 36 | ##### How to enable 37 | 38 | Command-line: 39 | 40 | Use flag `-p infura`. 41 | 42 | ```sh 43 | $ ipfs-pinner 44 | A CLI tool for pin files or directory to IPFS. 45 | 46 | Usage: 47 | 48 | ipfs-pinner [flags] [path]... 49 | 50 | Flags: 51 | 52 | -p string 53 | Pinner sceret or password. 54 | -t string 55 | IPFS pinner, supports pinners: infura, pinata, nftstorage, web3storage. (default "infura") 56 | -u string 57 | Pinner apikey or username. 58 | ``` 59 | 60 | 61 | Go package: 62 | ```go 63 | import ( 64 | "fmt" 65 | 66 | "github.com/wabarc/ipfs-pinner/pkg/infura" 67 | ) 68 | 69 | func main() { 70 | cid, err := infura.PinFile("file-to-path"); 71 | if err != nil { 72 | fmt.Sprintln(err) 73 | return 74 | } 75 | fmt.Println(cid) 76 | } 77 | ``` 78 | 79 | or requests with project authentication 80 | 81 | ```go 82 | import ( 83 | "fmt" 84 | 85 | "github.com/wabarc/ipfs-pinner/pkg/infura" 86 | ) 87 | 88 | func main() { 89 | inf := &infura.Infura{ProjectID: "your-project-id", ProjectSecret: "your-project-secret"} 90 | cid, err := inf.PinFile("file-to-path"); 91 | if err != nil { 92 | fmt.Sprintln(err) 93 | return 94 | } 95 | fmt.Println(cid) 96 | } 97 | ``` 98 | 99 | #### [Pinata](https://pinata.cloud) 100 | 101 | Pinata is another freemium pinning service. It gives you more control over 102 | what's uploaded. You can delete, label and add custom metadata. This service 103 | requires signup. 104 | 105 | ##### Environment variables 106 | 107 | Unix*: 108 | ```sh 109 | IPFS_PINNER_PINATA_API_KEY= 110 | IPFS_PINNER_PINATA_SECRET_API_KEY= 111 | ``` 112 | 113 | Windows: 114 | ```sh 115 | set IPFS_PINNER_PINATA_API_KEY= 116 | set IPFS_PINNER_PINATA_SECRET_API_KEY= 117 | ``` 118 | 119 | ##### How to enable 120 | 121 | Command-line: 122 | 123 | Use flag `-p pinata`. 124 | ```sh 125 | ipfs-pinner -p pinata file-to-path 126 | ``` 127 | 128 | Go package: 129 | ```go 130 | import ( 131 | "fmt" 132 | 133 | "github.com/wabarc/ipfs-pinner/pkg/pinata" 134 | ) 135 | 136 | func main() { 137 | pnt := pinata.Pinata{Apikey: "your api key", Secret: "your secret key"} 138 | cid, err := pnt.PinFile("file-to-path"); 139 | if err != nil { 140 | fmt.Sprintln(err) 141 | return 142 | } 143 | fmt.Println(cid) 144 | } 145 | ``` 146 | 147 | #### [NFT.Storage](https://nft.storage) 148 | 149 | NFT.Storage is a long-term storage service designed for off-chain NFT data 150 | (like metadata, images, and other assets) for up to 31GiB in size. Data is 151 | content addressed using IPFS, meaning the URL pointing to a piece of data 152 | (“ipfs://…”) is completely unique to that data. 153 | 154 | ##### How to enable 155 | 156 | Command-line: 157 | 158 | Use flag `-p nftstorage`. 159 | ```sh 160 | ipfs-pinner -p nftstorage file-to-path 161 | ``` 162 | 163 | Go package: 164 | ```go 165 | import ( 166 | "fmt" 167 | 168 | "github.com/wabarc/ipfs-pinner/pkg/nftstorage" 169 | ) 170 | 171 | func main() { 172 | nft := nftstorage.NFTStorage{Apikey: "your api key"} 173 | cid, err := nft.PinFile("file-to-path"); 174 | if err != nil { 175 | fmt.Sprintln(err) 176 | return 177 | } 178 | fmt.Println(cid) 179 | } 180 | ``` 181 | 182 | #### [Web3.Storage](https://web3.storage) 183 | 184 | 185 | 186 | Web3.Storage is a service to make building on top of Filecoin as simple as 187 | possible - giving the developers the power of open, distributed networks via 188 | a friendly JS client library. Behind the scenes, Web3.Storage is backed by 189 | Filecoin and makes content available via IPFS leveraging the unique 190 | properties of each network. 191 | 192 | 193 | 194 | ##### How to enable 195 | 196 | Command-line: 197 | 198 | Use flag `-p web3storage`. 199 | ```sh 200 | ipfs-pinner -p web3storage file-to-path 201 | ``` 202 | 203 | Go package: 204 | ```go 205 | import ( 206 | "fmt" 207 | 208 | "github.com/wabarc/ipfs-pinner/pkg/web3storage" 209 | ) 210 | 211 | func main() { 212 | web3 := web3storage.Web3Storage{Apikey: "your api key"} 213 | cid, err := web3.PinFile("file-to-path"); 214 | if err != nil { 215 | fmt.Sprintln(err) 216 | return 217 | } 218 | fmt.Println(cid) 219 | } 220 | ``` 221 | 222 | ## License 223 | 224 | Permissive GPL 3.0 license, see the [LICENSE](https://github.com/wabarc/ipfs-pinner/blob/main/LICENSE) file for details. 225 | -------------------------------------------------------------------------------- /pkg/pinata/pinata_test.go: -------------------------------------------------------------------------------- 1 | package pinata 2 | 3 | import ( 4 | "bytes" 5 | "io" 6 | "io/ioutil" 7 | "mime" 8 | "mime/multipart" 9 | "net/http" 10 | "os" 11 | "strings" 12 | "testing" 13 | 14 | "github.com/ipfs/go-cid" 15 | "github.com/wabarc/helper" 16 | ) 17 | 18 | var ( 19 | pinataKey = "fake-project-id" 20 | pinataSec = "fake-project-secret" 21 | pinHashJSON = `{ 22 | "hashToPin": "Qmaisz6NMhDB51cCvNWa1GMS7LU1pAxdF4Ld6Ft9kZEP2a" 23 | }` 24 | pinFileJSON = `{ 25 | "IpfsHash": "Qmaisz6NMhDB51cCvNWa1GMS7LU1pAxdF4Ld6Ft9kZEP2a", 26 | "PinSize": 1234, 27 | "Timestamp": "1979-01-01 00:00:00Z" 28 | }` 29 | badRequestJSON = `{}` 30 | unauthorizedJSON = `{}` 31 | ) 32 | 33 | func handleResponse(w http.ResponseWriter, r *http.Request) { 34 | authorization := r.Header.Get("Authorization") 35 | apiKey := r.Header.Get("pinata_api_key") 36 | apiSec := r.Header.Get("pinata_secret_api_key") 37 | switch { 38 | case apiKey != "" && apiSec != "": 39 | // access 40 | case authorization != "" && !strings.HasPrefix(authorization, "Bearer"): 41 | w.WriteHeader(http.StatusUnauthorized) 42 | _, _ = w.Write([]byte(unauthorizedJSON)) 43 | return 44 | default: 45 | w.WriteHeader(http.StatusUnauthorized) 46 | _, _ = w.Write([]byte(unauthorizedJSON)) 47 | return 48 | } 49 | 50 | switch r.URL.Path { 51 | case "/pinning/pinFileToIPFS": 52 | _ = r.ParseMultipartForm(32 << 20) 53 | _, params, parseErr := mime.ParseMediaType(r.Header.Get("Content-Type")) 54 | if parseErr != nil { 55 | w.WriteHeader(http.StatusBadRequest) 56 | _, _ = w.Write([]byte(badRequestJSON)) 57 | return 58 | } 59 | 60 | multipartReader := multipart.NewReader(r.Body, params["boundary"]) 61 | defer r.Body.Close() 62 | 63 | // Pin directory 64 | if multipartReader != nil && len(r.MultipartForm.File["file"]) > 1 { 65 | _, _ = w.Write([]byte(pinFileJSON)) 66 | return 67 | } 68 | // Pin file 69 | if multipartReader != nil && len(r.MultipartForm.File["file"]) == 1 { 70 | _, _ = w.Write([]byte(pinFileJSON)) 71 | return 72 | } 73 | case "/pinning/pinByHash": 74 | _, _ = w.Write([]byte(pinHashJSON)) 75 | return 76 | } 77 | w.WriteHeader(http.StatusBadRequest) 78 | _, _ = w.Write([]byte(badRequestJSON)) 79 | } 80 | 81 | func TestPinFile(t *testing.T) { 82 | httpClient, mux, server := helper.MockServer() 83 | mux.HandleFunc("/", handleResponse) 84 | defer server.Close() 85 | 86 | content := []byte(helper.RandString(6, "lower")) 87 | tmpfile, err := ioutil.TempFile("", "ipfs-pinner-") 88 | if err != nil { 89 | t.Fatal(err) 90 | } 91 | defer os.Remove(tmpfile.Name()) 92 | 93 | if _, err := tmpfile.Write(content); err != nil { 94 | t.Fatal(err) 95 | } 96 | 97 | pinata := &Pinata{httpClient, pinataKey, pinataSec} 98 | o, err := pinata.PinFile(tmpfile.Name()) 99 | if err != nil { 100 | t.Fatal(err) 101 | } 102 | _, err = cid.Parse(o) 103 | if err != nil { 104 | t.Fatalf("Invalid cid: %v", o) 105 | } 106 | } 107 | 108 | func TestPinWithReader(t *testing.T) { 109 | httpClient, mux, server := helper.MockServer() 110 | mux.HandleFunc("/", handleResponse) 111 | defer server.Close() 112 | 113 | content := []byte(helper.RandString(6, "lower")) 114 | tmpfile, err := ioutil.TempFile("", "ipfs-pinner-") 115 | if err != nil { 116 | t.Fatal(err) 117 | } 118 | defer os.Remove(tmpfile.Name()) 119 | if _, err := tmpfile.Write(content); err != nil { 120 | t.Fatal(err) 121 | } 122 | 123 | fr, _ := os.Open(tmpfile.Name()) 124 | tests := []struct { 125 | name string 126 | file interface{} 127 | }{ 128 | {"os.File", fr}, 129 | {"strings.Reader", strings.NewReader(helper.RandString(6, "lower"))}, 130 | {"bytes.Buffer", bytes.NewBufferString(helper.RandString(6, "lower"))}, 131 | } 132 | 133 | for _, test := range tests { 134 | t.Run(test.name, func(t *testing.T) { 135 | pinata := &Pinata{httpClient, pinataKey, pinataSec} 136 | file := test.file.(io.Reader) 137 | o, err := pinata.PinWithReader(file) 138 | if err != nil { 139 | t.Fatal(err) 140 | } 141 | _, err = cid.Parse(o) 142 | if err != nil { 143 | t.Fatalf("Invalid cid: %v", o) 144 | } 145 | }) 146 | } 147 | } 148 | 149 | func TestPinWithBytes(t *testing.T) { 150 | httpClient, mux, server := helper.MockServer() 151 | mux.HandleFunc("/", handleResponse) 152 | defer server.Close() 153 | 154 | buf := []byte(helper.RandString(6, "lower")) 155 | pinata := &Pinata{httpClient, pinataKey, pinataSec} 156 | o, err := pinata.PinWithBytes(buf) 157 | if err != nil { 158 | t.Errorf("Unexpected pin directory: %v", err) 159 | } 160 | _, err = cid.Parse(o) 161 | if err != nil { 162 | t.Fatalf("Invalid cid: %v", o) 163 | } 164 | } 165 | 166 | func TestPinDir(t *testing.T) { 167 | httpClient, mux, server := helper.MockServer() 168 | mux.HandleFunc("/", handleResponse) 169 | defer server.Close() 170 | 171 | dir, err := ioutil.TempDir("", "ipfs-pinner-dir-") 172 | if err != nil { 173 | t.Fatalf("Unexpected create directory: %v", err) 174 | } 175 | defer os.RemoveAll(dir) 176 | subdir, err := ioutil.TempDir(dir, "ipfs-pinner-subdir-") 177 | 178 | // Create files 179 | for i := 1; i <= 2; i++ { 180 | f, err := ioutil.TempFile(dir, "file-") 181 | if err != nil { 182 | t.Fatal("Unexpected create file") 183 | } 184 | content := []byte(helper.RandString(6, "lower")) 185 | if _, err := f.Write(content); err != nil { 186 | t.Fatal("Unexpected write content to file") 187 | } 188 | } 189 | // Write file to subdirectory 190 | f, err := ioutil.TempFile(subdir, "file-in-subdir-") 191 | if err != nil { 192 | t.Fatal("Unexpected create file") 193 | } 194 | content := []byte(helper.RandString(6, "lower")) 195 | if _, err := f.Write(content); err != nil { 196 | t.Fatal("Unexpected write content to file") 197 | } 198 | 199 | pinata := &Pinata{httpClient, pinataKey, pinataSec} 200 | o, err := pinata.PinDir(dir) 201 | if err != nil { 202 | t.Fatalf("Unexpected pin directory: %v", err) 203 | } 204 | _, err = cid.Parse(o) 205 | if err != nil { 206 | t.Fatalf("Invalid cid: %v", o) 207 | } 208 | } 209 | 210 | func TestPinHash(t *testing.T) { 211 | httpClient, mux, server := helper.MockServer() 212 | mux.HandleFunc("/", handleResponse) 213 | defer server.Close() 214 | 215 | hash := "Qmaisz6NMhDB51cCvNWa1GMS7LU1pAxdF4Ld6Ft9kZEP2a" 216 | 217 | pinata := &Pinata{httpClient, pinataKey, pinataSec} 218 | if ok, err := pinata.PinHash(hash); !ok || err != nil { 219 | t.Error(err) 220 | } 221 | } 222 | -------------------------------------------------------------------------------- /pinner_test.go: -------------------------------------------------------------------------------- 1 | package pinner // import "github.com/wabarc/ipfs-pinner" 2 | 3 | import ( 4 | "bytes" 5 | "encoding/base64" 6 | "io" 7 | "io/ioutil" 8 | "mime" 9 | "mime/multipart" 10 | "net/http" 11 | "os" 12 | "strings" 13 | "testing" 14 | 15 | "github.com/wabarc/helper" 16 | ) 17 | 18 | var ( 19 | apikey = "8864aeb47a5d4b2801c6" 20 | secret = "7f70e2a3720efbfee0905fb5b3af8994c58a4a09766bca190d5259d34b03d345" 21 | badRequestJSON = `{}` 22 | unauthorizedJSON = `{}` 23 | addJSON = `{ 24 | "Bytes": 0, 25 | "Hash": "Qmaisz6NMhDB51cCvNWa1GMS7LU1pAxdF4Ld6Ft9kZEP2a", 26 | "Name": "name", 27 | "Size": "string" 28 | }` 29 | pinHashJSON = `{ 30 | "hashToPin": "Qmaisz6NMhDB51cCvNWa1GMS7LU1pAxdF4Ld6Ft9kZEP2a" 31 | }` 32 | pinFileJSON = `{ 33 | "IpfsHash": "Qmaisz6NMhDB51cCvNWa1GMS7LU1pAxdF4Ld6Ft9kZEP2a", 34 | "PinSize": 1234, 35 | "Timestamp": "1979-01-01 00:00:00Z" 36 | }` 37 | ) 38 | 39 | func handleResponse(w http.ResponseWriter, r *http.Request) { 40 | switch r.URL.Hostname() { 41 | case "ipfs.infura.io": 42 | pinHashJSON = `{ 43 | "Pins": [ 44 | "Qmaisz6NMhDB51cCvNWa1GMS7LU1pAxdF4Ld6Ft9kZEP2a" 45 | ], 46 | "Progress": 0 47 | }` 48 | authorization := r.Header.Get("Authorization") 49 | if len(authorization) < 10 { 50 | w.WriteHeader(http.StatusUnauthorized) 51 | _, _ = w.Write([]byte(unauthorizedJSON)) 52 | return 53 | } 54 | 55 | switch r.URL.Path { 56 | case "/api/v0/add": 57 | _ = r.ParseMultipartForm(32 << 20) 58 | _, params, parseErr := mime.ParseMediaType(r.Header.Get("Content-Type")) 59 | if parseErr != nil { 60 | w.WriteHeader(http.StatusBadRequest) 61 | _, _ = w.Write([]byte(badRequestJSON)) 62 | return 63 | } 64 | 65 | multipartReader := multipart.NewReader(r.Body, params["boundary"]) 66 | defer r.Body.Close() 67 | 68 | // Pin directory 69 | if len(r.MultipartForm.File) == 0 && multipartReader != nil { 70 | _, _ = w.Write([]byte(addJSON)) 71 | return 72 | } 73 | // Pin file 74 | if len(r.MultipartForm.File["file"]) > 0 { 75 | _, _ = w.Write([]byte(addJSON)) 76 | return 77 | } 78 | case "/api/v0/pin/add": 79 | _, _ = w.Write([]byte(pinHashJSON)) 80 | return 81 | } 82 | w.WriteHeader(http.StatusBadRequest) 83 | case "api.pinata.cloud": 84 | authorization := r.Header.Get("Authorization") 85 | apiKey := r.Header.Get("pinata_api_key") 86 | apiSec := r.Header.Get("pinata_secret_api_key") 87 | switch { 88 | case apiKey != "" && apiSec != "": 89 | // access 90 | case authorization != "" && !strings.HasPrefix(authorization, "Bearer"): 91 | w.WriteHeader(http.StatusUnauthorized) 92 | _, _ = w.Write([]byte(unauthorizedJSON)) 93 | return 94 | default: 95 | w.WriteHeader(http.StatusUnauthorized) 96 | _, _ = w.Write([]byte(unauthorizedJSON)) 97 | return 98 | } 99 | 100 | switch r.URL.Path { 101 | case "/pinning/pinFileToIPFS": 102 | _ = r.ParseMultipartForm(32 << 20) 103 | _, params, parseErr := mime.ParseMediaType(r.Header.Get("Content-Type")) 104 | if parseErr != nil { 105 | w.WriteHeader(http.StatusBadRequest) 106 | _, _ = w.Write([]byte(badRequestJSON)) 107 | return 108 | } 109 | 110 | multipartReader := multipart.NewReader(r.Body, params["boundary"]) 111 | defer r.Body.Close() 112 | 113 | // Pin directory 114 | if multipartReader != nil && len(r.MultipartForm.File["file"]) > 1 { 115 | _, _ = w.Write([]byte(pinFileJSON)) 116 | return 117 | } 118 | // Pin file 119 | if multipartReader != nil && len(r.MultipartForm.File["file"]) == 1 { 120 | _, _ = w.Write([]byte(pinFileJSON)) 121 | return 122 | } 123 | case "/pinning/pinByHash": 124 | _, _ = w.Write([]byte(pinHashJSON)) 125 | return 126 | } 127 | default: 128 | w.WriteHeader(http.StatusBadRequest) 129 | _, _ = w.Write([]byte(badRequestJSON)) 130 | } 131 | } 132 | 133 | func TestPinNonExistFile(t *testing.T) { 134 | fakeFilepath := base64.StdEncoding.EncodeToString([]byte("this is a fake filepath")) 135 | handle := Config{} 136 | if _, err := handle.Pin(fakeFilepath); err == nil { 137 | t.Fail() 138 | } 139 | } 140 | 141 | func TestPinFile(t *testing.T) { 142 | content := []byte(helper.RandString(6, "lower")) 143 | tmpfile, err := ioutil.TempFile("", "ipfs-pinner-") 144 | if err != nil { 145 | t.Fatal(err) 146 | } 147 | defer os.Remove(tmpfile.Name()) 148 | 149 | if _, err := tmpfile.Write(content); err != nil { 150 | t.Fatal(err) 151 | } 152 | 153 | httpClient, mux, server := helper.MockServer() 154 | mux.HandleFunc("/", handleResponse) 155 | defer server.Close() 156 | 157 | fr, _ := os.Open(tmpfile.Name()) 158 | tests := []struct { 159 | pinner string 160 | apikey string 161 | secret string 162 | source string 163 | file interface{} 164 | }{ 165 | {"infura", apikey, secret, "os.File", fr}, 166 | {"infura", apikey, secret, "strings.Reader", strings.NewReader(helper.RandString(6, "lower"))}, 167 | {"infura", apikey, secret, "bytes.Buffer", bytes.NewBufferString(helper.RandString(6, "lower"))}, 168 | {"pinata", apikey, secret, "os.File", tmpfile}, 169 | {"pinata", apikey, secret, "strings.Reader", strings.NewReader(helper.RandString(6, "lower"))}, 170 | {"pinata", apikey, secret, "bytes.Buffer", bytes.NewBufferString(helper.RandString(6, "lower"))}, 171 | } 172 | 173 | for _, test := range tests { 174 | name := test.pinner + "-" + test.source 175 | t.Run(name, func(t *testing.T) { 176 | file := test.file.(io.Reader) 177 | pinner := Config{Pinner: test.pinner, Apikey: test.apikey, Secret: test.secret} 178 | if _, err := pinner.WithClient(httpClient).Pin(file); err != nil { 179 | t.Error(err) 180 | } 181 | }) 182 | } 183 | } 184 | 185 | func TestPinFileWithBytes(t *testing.T) { 186 | tests := []struct { 187 | pinner string 188 | apikey string 189 | secret string 190 | source string 191 | file interface{} 192 | }{ 193 | {"infura", apikey, secret, "bytes", []byte(helper.RandString(6, "lower"))}, 194 | {"pinata", apikey, secret, "bytes", []byte(helper.RandString(6, "lower"))}, 195 | } 196 | 197 | httpClient, mux, server := helper.MockServer() 198 | mux.HandleFunc("/", handleResponse) 199 | defer server.Close() 200 | 201 | for _, test := range tests { 202 | name := test.pinner + "-" + test.source 203 | t.Run(name, func(t *testing.T) { 204 | file := test.file.([]byte) 205 | pinner := Config{Pinner: test.pinner, Apikey: test.apikey, Secret: test.secret} 206 | if _, err := pinner.WithClient(httpClient).Pin(file); err != nil { 207 | t.Error(err) 208 | } 209 | }) 210 | } 211 | } 212 | -------------------------------------------------------------------------------- /pkg/nftstorage/nftstorage_test.go: -------------------------------------------------------------------------------- 1 | package nftstorage 2 | 3 | import ( 4 | "bytes" 5 | "io" 6 | "io/ioutil" 7 | "mime" 8 | "mime/multipart" 9 | "net/http" 10 | "os" 11 | "strings" 12 | "testing" 13 | 14 | "github.com/ipfs/go-cid" 15 | "github.com/wabarc/helper" 16 | ) 17 | 18 | var ( 19 | unauthorizedJSON = `{ 20 | "ok": false, 21 | "error": { 22 | "name": "string", 23 | "message": "string" 24 | } 25 | }` 26 | badRequestJSON = `{ 27 | "ok": false, 28 | "error": { 29 | "name": "string", 30 | "message": "string" 31 | } 32 | }` 33 | uploadJSON = `{ 34 | "ok": true, 35 | "value": { 36 | "cid": "bafkreidivzimqfqtoqxkrpge6bjyhlvxqs3rhe73owtmdulaxr5do5in7u", 37 | "size": 132614, 38 | "created": "2021-03-12T17:03:07.787Z", 39 | "type": "image/jpeg", 40 | "scope": "default", 41 | "pin": { 42 | "cid": "bafkreidivzimqfqtoqxkrpge6bjyhlvxqs3rhe73owtmdulaxr5do5in7u", 43 | "name": "pin name", 44 | "meta": {}, 45 | "status": "queued", 46 | "created": "2021-03-12T17:03:07.787Z", 47 | "size": 132614 48 | }, 49 | "files": [ 50 | { 51 | "name": "logo.jpg", 52 | "type": "image/jpeg" 53 | } 54 | ], 55 | "deals": [ 56 | { 57 | "batchRootCid": "bafkreidivzimqfqtoqxkrpge6bjyhlvxqs3rhe73owtmdulaxr5do5in7u", 58 | "lastChange": "2021-03-18T11:46:50.000Z", 59 | "miner": "f05678", 60 | "network": "nerpanet", 61 | "pieceCid": "bafkreidivzimqfqtoqxkrpge6bjyhlvxqs3rhe73owtmdulaxr5do5in7u", 62 | "status": "queued", 63 | "statusText": "miner rejected my data", 64 | "chainDealID": 138, 65 | "dealActivation": "2021-03-18T11:46:50.000Z", 66 | "dealExpiration": "2021-03-18T11:46:50.000Z" 67 | } 68 | ] 69 | } 70 | }` 71 | ) 72 | 73 | func handleResponse(w http.ResponseWriter, r *http.Request) { 74 | authorization := r.Header.Get("Authorization") 75 | if len(authorization) < 10 { 76 | w.WriteHeader(http.StatusUnauthorized) 77 | _, _ = w.Write([]byte(unauthorizedJSON)) 78 | return 79 | } 80 | switch r.URL.Path { 81 | case "/upload": 82 | _ = r.ParseMultipartForm(32 << 20) 83 | contentType, params, parseErr := mime.ParseMediaType(r.Header.Get("Content-Type")) 84 | if parseErr != nil { 85 | w.WriteHeader(http.StatusBadRequest) 86 | _, _ = w.Write([]byte(badRequestJSON)) 87 | return 88 | } 89 | 90 | multipartReader := multipart.NewReader(r.Body, params["boundary"]) 91 | defer r.Body.Close() 92 | 93 | // Pin directory 94 | if strings.HasPrefix(contentType, "multipart/form-data") { 95 | if len(r.MultipartForm.File["file"]) > 1 { 96 | _, _ = w.Write([]byte(uploadJSON)) 97 | return 98 | } 99 | } 100 | // Pin file 101 | if multipartReader != nil { 102 | _, _ = w.Write([]byte(uploadJSON)) 103 | return 104 | } 105 | } 106 | w.WriteHeader(http.StatusBadRequest) 107 | _, _ = w.Write([]byte(badRequestJSON)) 108 | } 109 | 110 | func TestPinFile(t *testing.T) { 111 | httpClient, mux, server := helper.MockServer() 112 | mux.HandleFunc("/", handleResponse) 113 | defer server.Close() 114 | 115 | content := []byte(helper.RandString(6, "lower")) 116 | tmpfile, err := ioutil.TempFile("", "ipfs-pinner-") 117 | if err != nil { 118 | t.Fatal(err) 119 | } 120 | defer os.Remove(tmpfile.Name()) 121 | 122 | if _, err := tmpfile.Write(content); err != nil { 123 | t.Fatal(err) 124 | } 125 | 126 | nft := &NFTStorage{Apikey: "fake-nft-storage-apikey", Client: httpClient} 127 | if _, err := nft.PinFile(tmpfile.Name()); err != nil { 128 | t.Error(err) 129 | } 130 | } 131 | 132 | func TestPinWithReader(t *testing.T) { 133 | httpClient, mux, server := helper.MockServer() 134 | mux.HandleFunc("/", handleResponse) 135 | defer server.Close() 136 | 137 | content := []byte(helper.RandString(6, "lower")) 138 | tmpfile, err := ioutil.TempFile("", "ipfs-pinner-") 139 | if err != nil { 140 | t.Fatal(err) 141 | } 142 | defer os.Remove(tmpfile.Name()) 143 | if _, err := tmpfile.Write(content); err != nil { 144 | t.Fatal(err) 145 | } 146 | 147 | fr, _ := os.Open(tmpfile.Name()) 148 | tests := []struct { 149 | name string 150 | file interface{} 151 | }{ 152 | {"os.File", fr}, 153 | {"strings.Reader", strings.NewReader(helper.RandString(6, "lower"))}, 154 | {"bytes.Buffer", bytes.NewBufferString(helper.RandString(6, "lower"))}, 155 | } 156 | 157 | nft := &NFTStorage{Apikey: "fake-nft-storage-apikey", Client: httpClient} 158 | for _, test := range tests { 159 | t.Run(test.name, func(t *testing.T) { 160 | file := test.file.(io.Reader) 161 | if _, err := nft.PinWithReader(file); err != nil { 162 | t.Error(err) 163 | } 164 | }) 165 | } 166 | } 167 | 168 | func TestPinWithBytes(t *testing.T) { 169 | httpClient, mux, server := helper.MockServer() 170 | mux.HandleFunc("/", handleResponse) 171 | defer server.Close() 172 | 173 | nft := &NFTStorage{Apikey: "fake-nft-storage-apikey", Client: httpClient} 174 | buf := []byte(helper.RandString(6, "lower")) 175 | if _, err := nft.PinWithBytes(buf); err != nil { 176 | t.Error(err) 177 | } 178 | } 179 | 180 | func TestPinDir(t *testing.T) { 181 | dir, err := ioutil.TempDir("", "ipfs-pinner-dir-") 182 | if err != nil { 183 | t.Fatalf("Unexpected create directory: %v", err) 184 | } 185 | defer os.RemoveAll(dir) 186 | subdir, err := ioutil.TempDir(dir, "ipfs-pinner-subdir-") 187 | 188 | // Create files 189 | for i := 1; i <= 2; i++ { 190 | f, err := ioutil.TempFile(dir, "file-") 191 | if err != nil { 192 | t.Fatal("Unexpected create file") 193 | } 194 | content := []byte(helper.RandString(6, "lower")) 195 | if _, err := f.Write(content); err != nil { 196 | t.Fatal("Unexpected write content to file") 197 | } 198 | } 199 | // Write file to subdirectory 200 | f, err := ioutil.TempFile(subdir, "file-in-subdir-") 201 | if err != nil { 202 | t.Fatal("Unexpected create file") 203 | } 204 | content := []byte(helper.RandString(6, "lower")) 205 | if _, err := f.Write(content); err != nil { 206 | t.Fatal("Unexpected write content to file") 207 | } 208 | 209 | httpClient, mux, server := helper.MockServer() 210 | mux.HandleFunc("/", handleResponse) 211 | defer server.Close() 212 | 213 | nft := &NFTStorage{Apikey: "fake-nft-storage-apikey", Client: httpClient} 214 | o, err := nft.PinDir(dir) 215 | if err != nil { 216 | t.Fatalf("Unexpected pin directory: %v", err) 217 | } 218 | _, err = cid.Parse(o) 219 | if err != nil { 220 | t.Fatalf("Invalid cid: %v", o) 221 | } 222 | } 223 | 224 | func TestPinHash(t *testing.T) { 225 | t.Skip("Not yet supported") 226 | 227 | httpClient, mux, server := helper.MockServer() 228 | mux.HandleFunc("/", handleResponse) 229 | defer server.Close() 230 | 231 | hash := "Qmaisz6NMhDB51cCvNWa1GMS7LU1pAxdF4Ld6Ft9kZEP2a" 232 | 233 | nft := &NFTStorage{Apikey: "fake-nft-storage-apikey", Client: httpClient} 234 | if ok, err := nft.PinHash(hash); !ok || err != nil { 235 | t.Error(err) 236 | } 237 | } 238 | -------------------------------------------------------------------------------- /pkg/infura/infura_test.go: -------------------------------------------------------------------------------- 1 | package infura 2 | 3 | import ( 4 | "bytes" 5 | "io" 6 | "io/ioutil" 7 | "mime" 8 | "mime/multipart" 9 | "net/http" 10 | "os" 11 | "strings" 12 | "sync/atomic" 13 | "testing" 14 | 15 | "github.com/ipfs/go-cid" 16 | "github.com/wabarc/helper" 17 | "github.com/wabarc/ipfs-pinner/file" 18 | ) 19 | 20 | var ( 21 | apikey = "fake-project-id" 22 | secret = "fake-project-secret" 23 | addJSON = `{ 24 | "Bytes": 0, 25 | "Hash": "Qmaisz6NMhDB51cCvNWa1GMS7LU1pAxdF4Ld6Ft9kZEP2a", 26 | "Name": "name", 27 | "Size": "string" 28 | }` 29 | pinHashJSON = `{ 30 | "Pins": [ 31 | "Qmaisz6NMhDB51cCvNWa1GMS7LU1pAxdF4Ld6Ft9kZEP2a" 32 | ], 33 | "Progress": 0 34 | }` 35 | badRequestJSON = `{}` 36 | unauthorizedJSON = `{}` 37 | tooManyRequestsJSON = `{}` 38 | ) 39 | 40 | func handleResponse(w http.ResponseWriter, r *http.Request) { 41 | authorization := r.Header.Get("Authorization") 42 | if len(authorization) < 10 { 43 | w.WriteHeader(http.StatusUnauthorized) 44 | _, _ = w.Write([]byte(unauthorizedJSON)) 45 | return 46 | } 47 | 48 | switch r.URL.Path { 49 | case "/api/v0/add": 50 | _ = r.ParseMultipartForm(32 << 20) 51 | _, params, parseErr := mime.ParseMediaType(r.Header.Get("Content-Type")) 52 | if parseErr != nil { 53 | w.WriteHeader(http.StatusBadRequest) 54 | _, _ = w.Write([]byte(badRequestJSON)) 55 | return 56 | } 57 | 58 | multipartReader := multipart.NewReader(r.Body, params["boundary"]) 59 | defer r.Body.Close() 60 | 61 | // Pin directory 62 | if len(r.MultipartForm.File) == 0 && multipartReader != nil { 63 | _, _ = w.Write([]byte(addJSON)) 64 | return 65 | } 66 | // Pin file 67 | if len(r.MultipartForm.File["file"]) > 0 { 68 | _, _ = w.Write([]byte(addJSON)) 69 | return 70 | } 71 | case "/api/v0/pin/add": 72 | _, _ = w.Write([]byte(pinHashJSON)) 73 | return 74 | } 75 | w.WriteHeader(http.StatusBadRequest) 76 | _, _ = w.Write([]byte(badRequestJSON)) 77 | } 78 | 79 | func TestPinFile(t *testing.T) { 80 | httpClient, mux, server := helper.MockServer() 81 | mux.HandleFunc("/", handleResponse) 82 | defer server.Close() 83 | 84 | content := []byte(helper.RandString(6, "lower")) 85 | tmpfile, err := ioutil.TempFile("", "ipfs-pinner-") 86 | if err != nil { 87 | t.Fatal(err) 88 | } 89 | defer os.Remove(tmpfile.Name()) 90 | 91 | if _, err := tmpfile.Write(content); err != nil { 92 | t.Fatal(err) 93 | } 94 | 95 | inf := &Infura{httpClient, apikey, secret} 96 | o, err := inf.PinFile(tmpfile.Name()) 97 | if err != nil { 98 | t.Fatal(err) 99 | } 100 | _, err = cid.Parse(o) 101 | if err != nil { 102 | t.Fatalf("Invalid cid: %v", o) 103 | } 104 | } 105 | 106 | func TestPinWithReader(t *testing.T) { 107 | httpClient, mux, server := helper.MockServer() 108 | mux.HandleFunc("/", handleResponse) 109 | defer server.Close() 110 | 111 | content := []byte(helper.RandString(6, "lower")) 112 | tmpfile, err := ioutil.TempFile("", "ipfs-pinner-") 113 | if err != nil { 114 | t.Fatal(err) 115 | } 116 | defer os.Remove(tmpfile.Name()) 117 | if _, err := tmpfile.Write(content); err != nil { 118 | t.Fatal(err) 119 | } 120 | 121 | fr, _ := os.Open(tmpfile.Name()) 122 | tests := []struct { 123 | name string 124 | file interface{} 125 | }{ 126 | {"os.File", fr}, 127 | {"strings.Reader", strings.NewReader(helper.RandString(6, "lower"))}, 128 | {"bytes.Buffer", bytes.NewBufferString(helper.RandString(6, "lower"))}, 129 | } 130 | 131 | inf := &Infura{httpClient, apikey, secret} 132 | for _, test := range tests { 133 | t.Run(test.name, func(t *testing.T) { 134 | file := test.file.(io.Reader) 135 | o, err := inf.PinWithReader(file) 136 | if err != nil { 137 | t.Fatal(err) 138 | } 139 | _, err = cid.Parse(o) 140 | if err != nil { 141 | t.Fatalf("Invalid cid: %v", o) 142 | } 143 | }) 144 | } 145 | } 146 | 147 | func TestPinWithBytes(t *testing.T) { 148 | httpClient, mux, server := helper.MockServer() 149 | mux.HandleFunc("/", handleResponse) 150 | defer server.Close() 151 | 152 | inf := &Infura{httpClient, apikey, secret} 153 | buf := []byte(helper.RandString(6, "lower")) 154 | o, err := inf.PinWithBytes(buf) 155 | if err != nil { 156 | t.Fatal(err) 157 | } 158 | _, err = cid.Parse(o) 159 | if err != nil { 160 | t.Fatalf("Invalid cid: %v", o) 161 | } 162 | } 163 | 164 | func TestPinHash(t *testing.T) { 165 | httpClient, mux, server := helper.MockServer() 166 | mux.HandleFunc("/", handleResponse) 167 | defer server.Close() 168 | 169 | hash := "Qmaisz6NMhDB51cCvNWa1GMS7LU1pAxdF4Ld6Ft9kZEP2a" 170 | 171 | inf := &Infura{httpClient, apikey, secret} 172 | if ok, err := inf.PinHash(hash); !ok || err != nil { 173 | t.Error(err) 174 | } 175 | } 176 | 177 | func TestPinDir(t *testing.T) { 178 | dir, err := ioutil.TempDir("", "ipfs-pinner-dir-") 179 | if err != nil { 180 | t.Fatalf("Unexpected create directory: %v", err) 181 | } 182 | defer os.RemoveAll(dir) 183 | subdir, err := ioutil.TempDir(dir, "ipfs-pinner-subdir-") 184 | 185 | // Create files 186 | for i := 1; i <= 2; i++ { 187 | f, err := ioutil.TempFile(dir, "file-") 188 | if err != nil { 189 | t.Fatal("Unexpected create file") 190 | } 191 | content := []byte(helper.RandString(6, "lower")) 192 | if _, err := f.Write(content); err != nil { 193 | t.Fatal("Unexpected write content to file") 194 | } 195 | } 196 | // Write file to subdirectory 197 | f, err := ioutil.TempFile(subdir, "file-in-subdir-") 198 | if err != nil { 199 | t.Fatal("Unexpected create file") 200 | } 201 | content := []byte(helper.RandString(6, "lower")) 202 | if _, err := f.Write(content); err != nil { 203 | t.Fatal("Unexpected write content to file") 204 | } 205 | 206 | httpClient, mux, server := helper.MockServer() 207 | mux.HandleFunc("/", handleResponse) 208 | defer server.Close() 209 | 210 | body, err := file.NewMultiFileReader(dir, false) 211 | if err != nil { 212 | t.Fatalf("Unexpected creates multipart file") 213 | } 214 | inf := &Infura{httpClient, apikey, secret} 215 | o, err := inf.PinDir(body) 216 | if err != nil { 217 | t.Fatalf("Unexpected pin directory: %v", err) 218 | } 219 | _, err = cid.Parse(o) 220 | if err != nil { 221 | t.Fatalf("Invalid cid: %v", o) 222 | } 223 | } 224 | 225 | func TestRateLimit(t *testing.T) { 226 | if testing.Short() { 227 | t.Skip("skip in short mode") 228 | } 229 | 230 | httpClient, mux, server := helper.MockServer() 231 | var retries int32 232 | mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { 233 | // Retry one times 234 | if retries < 1 { 235 | atomic.AddInt32(&retries, 1) 236 | w.WriteHeader(http.StatusTooManyRequests) 237 | _, _ = w.Write([]byte(tooManyRequestsJSON)) 238 | } else { 239 | _, _ = w.Write([]byte(addJSON)) 240 | } 241 | }) 242 | defer server.Close() 243 | 244 | content := []byte(helper.RandString(6, "lower")) 245 | tmpfile, err := ioutil.TempFile("", "ipfs-pinner-") 246 | if err != nil { 247 | t.Fatal(err) 248 | } 249 | defer os.Remove(tmpfile.Name()) 250 | 251 | if _, err := tmpfile.Write(content); err != nil { 252 | t.Fatal(err) 253 | } 254 | 255 | inf := &Infura{httpClient, apikey, secret} 256 | o, err := inf.PinFile(tmpfile.Name()) 257 | if err != nil { 258 | t.Error(err) 259 | } 260 | _, err = cid.Parse(o) 261 | if err != nil { 262 | t.Fatalf("Invalid cid: %v", o) 263 | } 264 | } 265 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | --------------------------------------------------------------------------------