Skip to content

Commit 53517fb

Browse files
authoredJul 4, 2022
feat: upload and delete files (#1)
* feat: binary file upload * feat: upload files from `tokio::fs::File` * feat: uploads ferris image to server * feat: deserialize response from server * feat: document types * chore: documentation * chore: ignore `.DS_Store` file * fix: remove `.DS_Store` files * fix: add env vars to ci workflows * fix: do not ignore lock file * fix: remove title from readme
1 parent 51a6207 commit 53517fb

20 files changed

+1885
-5
lines changed
 

‎.github/PULL_REQUEST_TEMPLATE.md

+27
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
<!--
2+
Developer's Certificate of Origin 1.1
3+
4+
By making a contribution to this project, I certify that:
5+
6+
(a) The contribution was created in whole or in part by me and I
7+
have the right to submit it under the open source license
8+
indicated in the file; or
9+
10+
(b) The contribution is based upon previous work that, to the best
11+
of my knowledge, is covered under an appropriate open source
12+
license and I have the right under that license to submit that
13+
work with modifications, whether created in whole or in part
14+
by me, under the same open source license (unless I am
15+
permitted to submit under a different license), as indicated
16+
in the file; or
17+
18+
(c) The contribution was provided directly to me by some other
19+
person who certified (a), (b) or (c) and I have not modified
20+
it.
21+
22+
(d) I understand and agree that this project and the contribution
23+
are public and that a record of the contribution (including all
24+
personal information I submit with it, including my sign-off) is
25+
maintained indefinitely and may be redistributed consistent with
26+
this project or the open source license(s) involved.
27+
-->

‎.github/workflows/build.yml

+45
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
name: build
2+
on:
3+
pull_request:
4+
push:
5+
branches:
6+
- main
7+
8+
jobs:
9+
build:
10+
name: Builds for ${{ matrix.os }}
11+
runs-on: ${{ matrix.os }}
12+
strategy:
13+
matrix:
14+
name:
15+
- linux
16+
- macos
17+
- windows
18+
19+
include:
20+
- name: linux
21+
os: ubuntu-latest
22+
- name: windows
23+
os: windows-latest
24+
- name: macos
25+
os: macos-latest
26+
27+
steps:
28+
- uses: actions/checkout@v2
29+
30+
- name: Cache .cargo and target
31+
uses: actions/cache@v2
32+
with:
33+
path: |
34+
~/.cargo
35+
./target
36+
key: ${{ runner.os }}-cargo-build-${{ hashFiles('**/Cargo.toml') }}
37+
restore-keys: |
38+
${{ runner.os }}-cargo-build-${{ hashFiles('**/Cargo.lock') }}
39+
${{ runner.os }}-cargo-build
40+
41+
- name: cargo build
42+
uses: actions-rs/cargo@v1
43+
with:
44+
command: build
45+
args: --release --locked

‎.github/workflows/clippy.yml

+37
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
name: clippy
2+
on:
3+
pull_request:
4+
push:
5+
branches:
6+
- main
7+
8+
jobs:
9+
clippy:
10+
runs-on: ubuntu-latest
11+
12+
steps:
13+
- uses: actions/checkout@v2
14+
15+
- uses: actions-rs/toolchain@v1
16+
with:
17+
profile: minimal
18+
toolchain: stable
19+
override: true
20+
components: clippy
21+
22+
- name: Cache .cargo and target
23+
uses: actions/cache@v2
24+
with:
25+
path: |
26+
~/.cargo
27+
./target
28+
key: ${{ runner.os }}-cargo-clippy-${{ hashFiles('**/Cargo.lock') }}
29+
restore-keys: |
30+
${{ runner.os }}-cargo-clippy-${{ hashFiles('**/Cargo.lock') }}
31+
${{ runner.os }}-cargo-clippy
32+
33+
- name: cargo clippy
34+
uses: actions-rs/cargo@v1
35+
with:
36+
command: clippy
37+
args: -- -D warnings

‎.github/workflows/fmt.yml

+39
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
name: fmt
2+
on:
3+
pull_request:
4+
push:
5+
branches:
6+
- main
7+
8+
jobs:
9+
fmt:
10+
name: fmt
11+
runs-on: ubuntu-latest
12+
13+
steps:
14+
- name: Checkout
15+
uses: actions/checkout@v2
16+
17+
- uses: actions-rs/toolchain@v1
18+
with:
19+
profile: minimal
20+
toolchain: stable
21+
override: true
22+
components: rustfmt
23+
24+
- name: Cache .cargo and target
25+
uses: actions/cache@v2
26+
with:
27+
path: |
28+
~/.cargo
29+
./target
30+
key: ${{ runner.os }}-cargo-fmt-${{ hashFiles('**/Cargo.lock') }}
31+
restore-keys: |
32+
${{ runner.os }}-cargo-fmt-${{ hashFiles('**/Cargo.lock') }}
33+
${{ runner.os }}-cargo-fmt
34+
35+
- name: Run fmt
36+
uses: actions-rs/cargo@v1
37+
with:
38+
command: fmt
39+
args: --all -- --check

‎.github/workflows/publish.yml

+67
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,67 @@
1+
name: release
2+
3+
on:
4+
push:
5+
tags:
6+
- 'v*'
7+
8+
jobs:
9+
test:
10+
name: Runs tests
11+
runs-on: ubuntu-latest
12+
env:
13+
IMAGEKIT_PUBLIC_KEY: ${{ secrets.IMAGEKIT_PUBLIC_KEY }}
14+
IMAGEKIT_PRIVATE_KEY: ${{ secrets.IMAGEKIT_PRIVATE_KEY }}
15+
IMAGEKIT_URL_ENDPOINT: ${{ secrets.IMAGEKIT_URL_ENDPOINT }}
16+
run: cargo test
17+
18+
publish-dry-run:
19+
name: "Runs cargo publish --dry-run"
20+
needs: test
21+
runs-on: ubuntu-latest
22+
steps:
23+
- uses: actions/checkout@v1
24+
25+
- uses: actions-rs/toolchain@v1
26+
with:
27+
profile: minimal
28+
toolchain: stable
29+
30+
- name: publish crate
31+
run: cargo publish --dry-run
32+
33+
create-release:
34+
name: Create Release
35+
needs: publish-dry-run
36+
runs-on: ubuntu-latest
37+
steps:
38+
- name: Checkout code
39+
uses: actions/checkout@v2
40+
41+
- name: Create Release with Notes
42+
uses: actions/github-script@v5
43+
with:
44+
github-token: ${{secrets.GITHUB_TOKEN}}
45+
script: |
46+
await github.request(`POST /repos/${{ github.repository }}/releases`, {
47+
tag_name: "${{ github.ref }}",
48+
generate_release_notes: true
49+
});
50+
51+
publish-crate:
52+
name: Publish to crates.io
53+
needs: create-release
54+
runs-on: ubuntu-latest
55+
steps:
56+
- uses: actions/checkout@v1
57+
58+
- uses: actions-rs/toolchain@v1
59+
with:
60+
profile: minimal
61+
toolchain: stable
62+
- run: cargo login ${CRATES_IO_TOKEN}
63+
env:
64+
CRATES_IO_TOKEN: ${{ secrets.CRATES_IO_TOKEN }}
65+
66+
- name: publish crate
67+
run: cargo publish

‎.github/workflows/test.yml

+31
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
name: test
2+
on:
3+
pull_request:
4+
push:
5+
branches:
6+
- main
7+
8+
jobs:
9+
test:
10+
runs-on: ubuntu-latest
11+
12+
steps:
13+
- uses: actions/checkout@v2
14+
15+
- name: Cache .cargo and target
16+
uses: actions/cache@v2
17+
with:
18+
path: |
19+
~/.cargo
20+
./target
21+
key: ${{ runner.os }}-cargo-test-${{ hashFiles('**/Cargo.lock') }}
22+
restore-keys: |
23+
${{ runner.os }}-cargo-test-${{ hashFiles('**/Cargo.lock') }}
24+
${{ runner.os }}-cargo-test
25+
26+
- name: Tests
27+
env:
28+
IMAGEKIT_PUBLIC_KEY: ${{ secrets.IMAGEKIT_PUBLIC_KEY }}
29+
IMAGEKIT_PRIVATE_KEY: ${{ secrets.IMAGEKIT_PRIVATE_KEY }}
30+
IMAGEKIT_URL_ENDPOINT: ${{ secrets.IMAGEKIT_URL_ENDPOINT }}
31+
run: cargo test

‎.gitignore

+1-1
Original file line numberDiff line numberDiff line change
@@ -1,2 +1,2 @@
1+
.DS_Store
12
/target
2-
/Cargo.lock

‎Cargo.lock

+1,017
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

‎Cargo.toml

+14-1
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,21 @@
11
[package]
22
name = "imagekit"
3-
version = "0.1.0"
3+
version = "0.1.0-beta+1"
44
edition = "2021"
5+
authors = ["Esteban Borai <estebanborai@gmail.com>"]
6+
description = "Simple and configurable command-line HTTP server"
7+
repository = "https://github.com/EstebanBorai/imagekit"
8+
categories = ["web-programming"]
9+
keywords = ["imagekit", "api", "bindings", "image", "upload", "sdk"]
10+
readme = "README.md"
511

612
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
713

814
[dependencies]
15+
anyhow = "1.0.58"
16+
async-trait = "0.1.56"
17+
reqwest = { version = "0.11.11", features = ["json", "multipart", "stream"] }
18+
serde = { version = "1.0.138", features = ["derive"] }
19+
serde_json = "1.0.82"
20+
tokio = { version = "1.19.2", features = ["macros", "rt-multi-thread"] }
21+
tokio-util = { version = "0.7.3", features = ["codec"] }

‎LICENSE-APACHE

+201
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,201 @@
1+
Apache License
2+
Version 2.0, January 2004
3+
http://www.apache.org/licenses/
4+
5+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6+
7+
1. Definitions.
8+
9+
"License" shall mean the terms and conditions for use, reproduction,
10+
and distribution as defined by Sections 1 through 9 of this document.
11+
12+
"Licensor" shall mean the copyright owner or entity authorized by
13+
the copyright owner that is granting the License.
14+
15+
"Legal Entity" shall mean the union of the acting entity and all
16+
other entities that control, are controlled by, or are under common
17+
control with that entity. For the purposes of this definition,
18+
"control" means (i) the power, direct or indirect, to cause the
19+
direction or management of such entity, whether by contract or
20+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
21+
outstanding shares, or (iii) beneficial ownership of such entity.
22+
23+
"You" (or "Your") shall mean an individual or Legal Entity
24+
exercising permissions granted by this License.
25+
26+
"Source" form shall mean the preferred form for making modifications,
27+
including but not limited to software source code, documentation
28+
source, and configuration files.
29+
30+
"Object" form shall mean any form resulting from mechanical
31+
transformation or translation of a Source form, including but
32+
not limited to compiled object code, generated documentation,
33+
and conversions to other media types.
34+
35+
"Work" shall mean the work of authorship, whether in Source or
36+
Object form, made available under the License, as indicated by a
37+
copyright notice that is included in or attached to the work
38+
(an example is provided in the Appendix below).
39+
40+
"Derivative Works" shall mean any work, whether in Source or Object
41+
form, that is based on (or derived from) the Work and for which the
42+
editorial revisions, annotations, elaborations, or other modifications
43+
represent, as a whole, an original work of authorship. For the purposes
44+
of this License, Derivative Works shall not include works that remain
45+
separable from, or merely link (or bind by name) to the interfaces of,
46+
the Work and Derivative Works thereof.
47+
48+
"Contribution" shall mean any work of authorship, including
49+
the original version of the Work and any modifications or additions
50+
to that Work or Derivative Works thereof, that is intentionally
51+
submitted to Licensor for inclusion in the Work by the copyright owner
52+
or by an individual or Legal Entity authorized to submit on behalf of
53+
the copyright owner. For the purposes of this definition, "submitted"
54+
means any form of electronic, verbal, or written communication sent
55+
to the Licensor or its representatives, including but not limited to
56+
communication on electronic mailing lists, source code control systems,
57+
and issue tracking systems that are managed by, or on behalf of, the
58+
Licensor for the purpose of discussing and improving the Work, but
59+
excluding communication that is conspicuously marked or otherwise
60+
designated in writing by the copyright owner as "Not a Contribution."
61+
62+
"Contributor" shall mean Licensor and any individual or Legal Entity
63+
on behalf of whom a Contribution has been received by Licensor and
64+
subsequently incorporated within the Work.
65+
66+
2. Grant of Copyright License. Subject to the terms and conditions of
67+
this License, each Contributor hereby grants to You a perpetual,
68+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69+
copyright license to reproduce, prepare Derivative Works of,
70+
publicly display, publicly perform, sublicense, and distribute the
71+
Work and such Derivative Works in Source or Object form.
72+
73+
3. Grant of Patent License. Subject to the terms and conditions of
74+
this License, each Contributor hereby grants to You a perpetual,
75+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76+
(except as stated in this section) patent license to make, have made,
77+
use, offer to sell, sell, import, and otherwise transfer the Work,
78+
where such license applies only to those patent claims licensable
79+
by such Contributor that are necessarily infringed by their
80+
Contribution(s) alone or by combination of their Contribution(s)
81+
with the Work to which such Contribution(s) was submitted. If You
82+
institute patent litigation against any entity (including a
83+
cross-claim or counterclaim in a lawsuit) alleging that the Work
84+
or a Contribution incorporated within the Work constitutes direct
85+
or contributory patent infringement, then any patent licenses
86+
granted to You under this License for that Work shall terminate
87+
as of the date such litigation is filed.
88+
89+
4. Redistribution. You may reproduce and distribute copies of the
90+
Work or Derivative Works thereof in any medium, with or without
91+
modifications, and in Source or Object form, provided that You
92+
meet the following conditions:
93+
94+
(a) You must give any other recipients of the Work or
95+
Derivative Works a copy of this License; and
96+
97+
(b) You must cause any modified files to carry prominent notices
98+
stating that You changed the files; and
99+
100+
(c) You must retain, in the Source form of any Derivative Works
101+
that You distribute, all copyright, patent, trademark, and
102+
attribution notices from the Source form of the Work,
103+
excluding those notices that do not pertain to any part of
104+
the Derivative Works; and
105+
106+
(d) If the Work includes a "NOTICE" text file as part of its
107+
distribution, then any Derivative Works that You distribute must
108+
include a readable copy of the attribution notices contained
109+
within such NOTICE file, excluding those notices that do not
110+
pertain to any part of the Derivative Works, in at least one
111+
of the following places: within a NOTICE text file distributed
112+
as part of the Derivative Works; within the Source form or
113+
documentation, if provided along with the Derivative Works; or,
114+
within a display generated by the Derivative Works, if and
115+
wherever such third-party notices normally appear. The contents
116+
of the NOTICE file are for informational purposes only and
117+
do not modify the License. You may add Your own attribution
118+
notices within Derivative Works that You distribute, alongside
119+
or as an addendum to the NOTICE text from the Work, provided
120+
that such additional attribution notices cannot be construed
121+
as modifying the License.
122+
123+
You may add Your own copyright statement to Your modifications and
124+
may provide additional or different license terms and conditions
125+
for use, reproduction, or distribution of Your modifications, or
126+
for any such Derivative Works as a whole, provided Your use,
127+
reproduction, and distribution of the Work otherwise complies with
128+
the conditions stated in this License.
129+
130+
5. Submission of Contributions. Unless You explicitly state otherwise,
131+
any Contribution intentionally submitted for inclusion in the Work
132+
by You to the Licensor shall be under the terms and conditions of
133+
this License, without any additional terms or conditions.
134+
Notwithstanding the above, nothing herein shall supersede or modify
135+
the terms of any separate license agreement you may have executed
136+
with Licensor regarding such Contributions.
137+
138+
6. Trademarks. This License does not grant permission to use the trade
139+
names, trademarks, service marks, or product names of the Licensor,
140+
except as required for reasonable and customary use in describing the
141+
origin of the Work and reproducing the content of the NOTICE file.
142+
143+
7. Disclaimer of Warranty. Unless required by applicable law or
144+
agreed to in writing, Licensor provides the Work (and each
145+
Contributor provides its Contributions) on an "AS IS" BASIS,
146+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147+
implied, including, without limitation, any warranties or conditions
148+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149+
PARTICULAR PURPOSE. You are solely responsible for determining the
150+
appropriateness of using or redistributing the Work and assume any
151+
risks associated with Your exercise of permissions under this License.
152+
153+
8. Limitation of Liability. In no event and under no legal theory,
154+
whether in tort (including negligence), contract, or otherwise,
155+
unless required by applicable law (such as deliberate and grossly
156+
negligent acts) or agreed to in writing, shall any Contributor be
157+
liable to You for damages, including any direct, indirect, special,
158+
incidental, or consequential damages of any character arising as a
159+
result of this License or out of the use or inability to use the
160+
Work (including but not limited to damages for loss of goodwill,
161+
work stoppage, computer failure or malfunction, or any and all
162+
other commercial damages or losses), even if such Contributor
163+
has been advised of the possibility of such damages.
164+
165+
9. Accepting Warranty or Additional Liability. While redistributing
166+
the Work or Derivative Works thereof, You may choose to offer,
167+
and charge a fee for, acceptance of support, warranty, indemnity,
168+
or other liability obligations and/or rights consistent with this
169+
License. However, in accepting such obligations, You may act only
170+
on Your own behalf and on Your sole responsibility, not on behalf
171+
of any other Contributor, and only if You agree to indemnify,
172+
defend, and hold each Contributor harmless for any liability
173+
incurred by, or claims asserted against, such Contributor by reason
174+
of your accepting any such warranty or additional liability.
175+
176+
END OF TERMS AND CONDITIONS
177+
178+
APPENDIX: How to apply the Apache License to your work.
179+
180+
To apply the Apache License to your work, attach the following
181+
boilerplate notice, with the fields enclosed by brackets "[]"
182+
replaced with your own identifying information. (Don't include
183+
the brackets!) The text should be enclosed in the appropriate
184+
comment syntax for the file format. We also recommend that a
185+
file or class name and description of purpose be included on the
186+
same "printed page" as the copyright notice for easier
187+
identification within third-party archives.
188+
189+
Copyright 2022 Esteban Borai and Contributors
190+
191+
Licensed under the Apache License, Version 2.0 (the "License");
192+
you may not use this file except in compliance with the License.
193+
You may obtain a copy of the License at
194+
195+
http://www.apache.org/licenses/LICENSE-2.0
196+
197+
Unless required by applicable law or agreed to in writing, software
198+
distributed under the License is distributed on an "AS IS" BASIS,
199+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200+
See the License for the specific language governing permissions and
201+
limitations under the License.

‎LICENSE-MIT

+25
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
Copyright (c) 2022 Esteban Borai and Contributors
2+
3+
Permission is hereby granted, free of charge, to any
4+
person obtaining a copy of this software and associated
5+
documentation files (the "Software"), to deal in the
6+
Software without restriction, including without
7+
limitation the rights to use, copy, modify, merge,
8+
publish, distribute, sublicense, and/or sell copies of
9+
the Software, and to permit persons to whom the Software
10+
is furnished to do so, subject to the following
11+
conditions:
12+
13+
The above copyright notice and this permission notice
14+
shall be included in all copies or substantial portions
15+
of the Software.
16+
17+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF
18+
ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
19+
TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
20+
PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
21+
SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
22+
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
23+
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR
24+
IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
25+
DEALINGS IN THE SOFTWARE.

‎README.md

+115
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,115 @@
1+
<div>
2+
<div align="center">
3+
<img
4+
alt="ImageKit Logo"
5+
src="https://raw.githubusercontent.com/EstebanBorai/imagekit/main/assets/imagekit.svg"
6+
height="52"
7+
width="250"
8+
/>
9+
</div>
10+
<h4 align="center">
11+
Rust API Client for ImageKit.io a file storage and image processing
12+
service
13+
</h4>
14+
</div>
15+
16+
<div align="center">
17+
18+
[![Crates.io](https://img.shields.io/crates/v/imagekit.svg)](https://crates.io/crates/imagekit)
19+
[![Documentation](https://docs.rs/imagekit/badge.svg)](https://docs.rs/imagekit)
20+
![Build](https://github.com/EstebanBorai/imagekit/workflows/build/badge.svg)
21+
![Clippy](https://github.com/EstebanBorai/imagekit/workflows/clippy/badge.svg)
22+
![Formatter](https://github.com/EstebanBorai/imagekit/workflows/fmt/badge.svg)
23+
![Tests](https://github.com/EstebanBorai/imagekit/workflows/test/badge.svg)
24+
25+
</div>
26+
27+
## Usage
28+
29+
You must retrieve your Public and Private Keys from the
30+
[ImageKit Developer Options][1].
31+
32+
Then create an instance of `ImageKit` and initialize the client.
33+
34+
```rust
35+
use imagekit::ImageKit;
36+
use imagekit::delete::Delete;
37+
use imagekit::upload::types::FileType;
38+
use imagekit::upload::{Options, Upload, UploadFile};
39+
use tokio::fs::File;
40+
41+
#[tokio::main]
42+
async fn main() -> Result<(), Box<dyn std::error::Error>> {
43+
let mut image_kit = ImageKit::new(
44+
"your_public_api_key",
45+
"your_private_api_key",
46+
"https://ik.imagekit.io/your_imagekit_id/",
47+
);
48+
49+
// Upload an image from File
50+
let file = File::open("assets/ferris.jpeg").await.unwrap();
51+
let opts = Options::new(upload_file, "ferris");
52+
let upload_result = imagekit.upload(opts).await.unwrap();
53+
54+
// Delete a file
55+
let delete_result = imagekit.delete(upload_result.file_id).await;
56+
}
57+
```
58+
59+
## Features
60+
61+
The main goal of this crate is to support the main three functionalities
62+
provided by ImageKit. URL Generation, File Upload and File Management.
63+
64+
The following list, provides a closer view to supported features and planned
65+
features which are not yet implemented. Feel free to contribute by opening
66+
an issue, pull request or discussion.
67+
68+
- [ ] URL Generation
69+
- [x] File Upload ([File Upload API][2])
70+
- [x] From `tokio::fs::File` (Binary)
71+
- [ ] From `std::fs::File` (Binary)
72+
- [ ] From URL
73+
- [ ] From Base64
74+
- [ ] File Management
75+
- [ ] List Files
76+
- [ ] Search Files
77+
- [ ] Get File Details
78+
- [ ] Get File Versions
79+
- [ ] Get File Metadata
80+
- [ ] Custom Metadata Fields
81+
- [ ] Create
82+
- [ ] List
83+
- [ ] Update
84+
- [ ] Delete
85+
- [x] Delete File
86+
- [ ] Update File Details
87+
- [ ] Tags
88+
- [ ] Bulk Addition
89+
- [ ] Bulk Deletion
90+
- [ ] AI Tags
91+
- [ ] Bulk Deletion
92+
- [ ] Delete File Version
93+
- [ ] Bulk Delete Files
94+
- [ ] Copy File
95+
- [ ] Move File
96+
- [ ] Rename File
97+
- [ ] Restore File Version
98+
- [ ] Folders
99+
- [ ] Create
100+
- [ ] Copy
101+
- [ ] Delete
102+
- [ ] Move
103+
- [ ] Bulk Job Status
104+
- [ ] Cache
105+
- [ ] Purge
106+
107+
> If you notice theres missing features in this list, please open an issue or PR.
108+
109+
## License
110+
111+
As most Rust projects, this crate is licensed under both, the Apache License
112+
and the MIT License.
113+
114+
[1]: https://imagekit.io/dashboard/developer/api-keys
115+
[2]: https://docs.imagekit.io/api-reference/upload-file-api/server-side-file-upload

‎assets/ferris.jpeg

78 KB
Loading

‎assets/imagekit.svg

+1
Loading

‎src/client.rs

+32-3
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,9 @@
1-
pub const UPLOAD_ENDPOINT: &'static str = "https://upload.imagekit.io/api/v1/files/upload";
1+
use anyhow::{bail, Result};
2+
use reqwest::Client;
3+
use std::env::var;
4+
5+
pub const FILES_ENDPOINT: &str = "https://api.imagekit.io/v1/files";
6+
pub const UPLOAD_ENDPOINT: &str = "https://upload.imagekit.io/api/v1/files/upload";
27

38
/// An ImageKit.io API Client Instance
49
///
@@ -16,22 +21,46 @@ pub const UPLOAD_ENDPOINT: &'static str = "https://upload.imagekit.io/api/v1/fil
1621
/// `upload_endpoint` method.
1722
pub struct ImageKit {
1823
pub(crate) upload_endpoint: String,
24+
#[allow(dead_code)]
1925
pub(crate) public_key: String,
2026
pub(crate) private_key: String,
27+
#[allow(dead_code)]
2128
pub(crate) url_endpoint: String,
29+
pub(crate) client: Client,
2230
}
2331

2432
impl ImageKit {
2533
pub fn new<T: ToString>(public_key: T, private_key: T, url_endpoint: T) -> Self {
34+
let client = Client::new();
35+
2636
Self {
2737
upload_endpoint: UPLOAD_ENDPOINT.to_string(),
2838
public_key: public_key.to_string(),
2939
private_key: private_key.to_string(),
3040
url_endpoint: url_endpoint.to_string(),
41+
client,
42+
}
43+
}
44+
45+
pub fn from_env() -> Result<Self> {
46+
let public_key = ImageKit::env("IMAGEKIT_PUBLIC_KEY")?;
47+
let private_key = ImageKit::env("IMAGEKIT_PRIVATE_KEY")?;
48+
let url_endpoint = ImageKit::env("IMAGEKIT_URL_ENDPOINT")?;
49+
let imagekit = Self::new(public_key, private_key, url_endpoint);
50+
51+
Ok(imagekit)
52+
}
53+
54+
fn env(key: &str) -> Result<String> {
55+
match var(key) {
56+
Ok(value) => Ok(value),
57+
Err(err) => bail!(err),
3158
}
3259
}
3360

34-
/// Updates the `upload_endpoint` used for this client instance.
61+
/// Returns a mutable reference to the `upload_endpoint` used by this
62+
/// ImageKit client instance. Can be used to update the instance value
63+
/// or retrieve the value.
3564
///
3665
/// ```
3766
/// use imagekit::client::ImageKit;
@@ -57,7 +86,7 @@ mod tests {
5786
use super::ImageKit;
5887

5988
#[test]
60-
fn it_updates_the_upload_endpoint() {
89+
fn updates_the_upload_endpoint() {
6190
let mut image_kit = ImageKit::new(
6291
"your_public_api_key",
6392
"your_private_api_key",

‎src/delete/mod.rs

+36
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
use anyhow::{bail, Result};
2+
use async_trait::async_trait;
3+
use reqwest::{StatusCode, Url};
4+
5+
use crate::client::FILES_ENDPOINT;
6+
use crate::{ErrorResponse, ImageKit};
7+
8+
#[async_trait]
9+
pub trait Delete {
10+
/// Deletes the file with the provided File ID
11+
async fn delete<T: ToString + Send>(&self, file_id: T) -> Result<()>;
12+
}
13+
14+
#[async_trait]
15+
impl Delete for ImageKit {
16+
async fn delete<T: ToString + Send>(&self, file_id: T) -> Result<()> {
17+
let url_string = format!("{}/{}", FILES_ENDPOINT, file_id.to_string());
18+
let endpoint_url = Url::parse(&url_string).unwrap();
19+
let private_key = self.private_key.to_owned();
20+
let response = self
21+
.client
22+
.delete(endpoint_url)
23+
.basic_auth::<String, String>(private_key, None)
24+
.send()
25+
.await
26+
.unwrap();
27+
28+
if matches!(response.status(), StatusCode::NO_CONTENT) {
29+
return Ok(());
30+
}
31+
32+
let result = response.json::<ErrorResponse>().await.unwrap();
33+
34+
bail!(result.message);
35+
}
36+
}

‎src/lib.rs

+33
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,36 @@
11
pub mod client;
2+
pub mod delete;
3+
pub mod types;
4+
pub mod upload;
25

36
pub use client::ImageKit;
7+
pub use delete::Delete;
8+
pub use types::ErrorResponse;
9+
pub use upload::Upload;
10+
11+
#[cfg(test)]
12+
mod tests {
13+
use tokio::fs::File;
14+
15+
use super::delete::Delete;
16+
use super::upload::types::FileType;
17+
use super::upload::{Options, Upload, UploadFile};
18+
use super::ImageKit;
19+
20+
#[tokio::test]
21+
async fn uploads_then_deletes_file() {
22+
let imagekit = ImageKit::from_env().unwrap();
23+
let file = File::open("assets/ferris.jpeg").await.unwrap();
24+
let upload_file = UploadFile::from(file);
25+
let opts = Options::new(upload_file, "ferris");
26+
let upload_result = imagekit.upload(opts).await.unwrap();
27+
28+
assert_eq!(upload_result.file_type, FileType::Image);
29+
assert_eq!(upload_result.height.unwrap(), 640);
30+
assert_eq!(upload_result.width.unwrap(), 640);
31+
32+
let delete_result = imagekit.delete(upload_result.file_id).await;
33+
34+
assert!(delete_result.is_ok());
35+
}
36+
}

‎src/types.rs

+8
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
use serde::Deserialize;
2+
3+
/// Response struct returned on failed requests
4+
#[derive(Debug, Deserialize)]
5+
#[serde(rename_all = "camelCase")]
6+
pub struct ErrorResponse {
7+
pub message: String,
8+
}

‎src/upload/mod.rs

+92
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,92 @@
1+
pub mod types;
2+
3+
use anyhow::{bail, Result};
4+
use async_trait::async_trait;
5+
use reqwest::multipart::{Form, Part};
6+
use reqwest::{Body, StatusCode};
7+
use tokio::fs::File;
8+
use tokio_util::codec::{BytesCodec, FramedRead};
9+
10+
use crate::{ErrorResponse, ImageKit};
11+
12+
use self::types::Response;
13+
14+
pub enum UploadFile {
15+
Binary(File),
16+
}
17+
18+
impl From<File> for UploadFile {
19+
fn from(file: File) -> Self {
20+
UploadFile::Binary(file)
21+
}
22+
}
23+
24+
/// Options sent to the server as part of the `Form` when uploding a file.
25+
///
26+
/// Refer: https://docs.imagekit.io/api-reference/upload-file-api/server-side-file-upload#request-structure-multipart-form-data
27+
pub struct Options {
28+
/// File to upload
29+
file: UploadFile,
30+
/// Name to set to the file being uploaded
31+
///
32+
/// The filename must only have alphanumeric characters (a-z, A-Z and/or 0-9),
33+
/// allowed symbols include `.`, `_`, and `-`.
34+
file_name: String,
35+
}
36+
37+
impl Options {
38+
/// Creates a new instance of `Options` with the provided `UploadFile` and
39+
/// file name.
40+
pub fn new<T: ToString>(file: UploadFile, file_name: T) -> Self {
41+
Self {
42+
file,
43+
file_name: file_name.to_string(),
44+
}
45+
}
46+
}
47+
48+
#[async_trait]
49+
pub trait Upload {
50+
/// Uploads an image with the provided `Options`
51+
async fn upload(&self, opts: Options) -> Result<Response>;
52+
}
53+
54+
#[async_trait]
55+
impl Upload for ImageKit {
56+
async fn upload(&self, opts: Options) -> Result<Response> {
57+
let mut form = Form::new();
58+
59+
form = form.text("fileName", opts.file_name.clone());
60+
match opts.file {
61+
UploadFile::Binary(file) => {
62+
let stream = FramedRead::new(file, BytesCodec::new());
63+
let file_body = Body::wrap_stream(stream);
64+
let form_file = Part::stream(file_body)
65+
.file_name(opts.file_name)
66+
.mime_str("image/jpeg")
67+
.unwrap();
68+
form = form.part("file", form_file);
69+
}
70+
}
71+
72+
let private_key = self.private_key.to_owned();
73+
let response = self
74+
.client
75+
.post(&self.upload_endpoint)
76+
.basic_auth::<String, String>(private_key, None)
77+
.multipart(form)
78+
.send()
79+
.await
80+
.unwrap();
81+
82+
if matches!(response.status(), StatusCode::OK) {
83+
let result = response.json::<Response>().await.unwrap();
84+
85+
return Ok(result);
86+
}
87+
88+
let result = response.json::<ErrorResponse>().await.unwrap();
89+
90+
bail!(result.message);
91+
}
92+
}

‎src/upload/types.rs

+64
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,64 @@
1+
use serde::Deserialize;
2+
3+
/// An object containing the file or file version's id (versionId) and name.
4+
#[derive(Debug, Deserialize)]
5+
#[serde(rename_all = "camelCase")]
6+
pub struct VersionInfo {
7+
pub id: String,
8+
pub name: String,
9+
}
10+
11+
/// Array of AITags associated with the image. If no AITags are set, it
12+
/// will be null. These tags can be added using the google-auto-tagging
13+
/// or aws-auto-tagging extensions.
14+
#[derive(Debug, Deserialize)]
15+
#[serde(rename_all = "camelCase")]
16+
pub struct AiTag {
17+
pub name: String,
18+
pub confidence: f32,
19+
pub source: String,
20+
}
21+
22+
/// The type of file could be either `image` or `non-image`.
23+
#[derive(Debug, Deserialize, PartialEq)]
24+
pub enum FileType {
25+
#[serde(rename = "image")]
26+
Image,
27+
#[serde(rename = "non-image")]
28+
NonImage,
29+
}
30+
31+
/// Response struct returned from successful requests to the ImageKit API.
32+
///
33+
/// Refer: https://docs.imagekit.io/api-reference/upload-file-api/server-side-file-upload#response-code-and-structure-json
34+
/// Fields Documentation: https://docs.imagekit.io/api-reference/upload-file-api/server-side-file-upload#understanding-response
35+
#[derive(Debug, Deserialize)]
36+
#[serde(rename_all = "camelCase")]
37+
pub struct Response {
38+
/// Unique fileId. Store this fileld in your database, as this will be used
39+
/// to perform update action on this file
40+
pub file_id: String,
41+
/// Name of the file or folder.
42+
pub name: String,
43+
/// Size of the image file in Bytes
44+
pub size: u64,
45+
/// An object containing the file or file version's id (versionId) and name.
46+
pub version_info: VersionInfo,
47+
/// The relative path of the file. In the case of an image, you can use
48+
/// this path to construct different transformations.
49+
pub file_path: String,
50+
/// A publicly accessible URL of the file.
51+
pub url: String,
52+
/// The type of file could be either `image` or `non-image`.
53+
pub file_type: FileType,
54+
/// Height of the image in pixels (Only for images)
55+
pub height: Option<u64>,
56+
/// Width of the image in pixels (Only for Images)
57+
pub width: Option<u64>,
58+
/// In the case of an image, a small thumbnail URL.
59+
pub thumbnail_url: String,
60+
/// Array of AITags associated with the image. If no AITags are set, it
61+
/// will be null. These tags can be added using the google-auto-tagging
62+
/// or aws-auto-tagging extensions.
63+
pub ai_tags: Option<Vec<AiTag>>,
64+
}

0 commit comments

Comments
 (0)
Please sign in to comment.