forked from open-runtimes/examples
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request open-runtimes#66 from vzsky/main
Add Compress Image for Ruby
- Loading branch information
Showing
4 changed files
with
191 additions
and
2 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,4 @@ | ||
source "https://rubygems.org" | ||
gem "base64" | ||
gem "tinify" | ||
gem "kraken-io" |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,65 @@ | ||
# Compress .png Images | ||
|
||
A Ruby Cloud Function that compresses png images. | ||
|
||
|
||
`image` and `provider` are recieved from the payload, where `image` is a base64 encoded string and `provider` is either [`tinypng`](https://tinypng.com) or [`krakenio`](https://kraken.io) | ||
|
||
_Example input:_ | ||
|
||
```json | ||
{ | ||
"image": "iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAACXBIWXMAAAsTAAALEwEAmpwYAAAAf0lEQVR4nO2Wuw2AMAxEbw1gpMwDDMBcGQpooDKydGVAoXCK6J7k6qyc83MCCFGP/Yz+CkDF4KHmjgowbQF0CKFrCDUiwztqxabHCL0/xwcNhoI2UdsjC8g0mQvaSs1zwkg0uQAsAEaGm9/UPCeU7eMj6loTEpf6ZOQWMxd98gAhZnS6XEZcNQAAAABJRU5ErkJggg==", | ||
"provider": "tinypng", | ||
} | ||
``` | ||
|
||
> `krakenio` is also a supported provider | ||
_Example output:_ | ||
|
||
```json | ||
{ | ||
"success": true, | ||
"image": "iVBORw0KGgoAAAANSUhEUgAAACAAAAAgBAMAAACBVGfHAAAAG1BMVEUAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACUUeIgAAAACHRSTlMA8712Sxr5g97cFtUAAAA9SURBVCjPY6Aa6AADfAIcDSA8KoBTgLGVgSFCAEmAqZmBwUIBSYClzTQ4wwE52Cs6OtpR4oFFUciBerEKAP58HnyLtZsYAAAAAElFTkSuQmCC" | ||
} | ||
``` | ||
|
||
## 📝 Variables | ||
|
||
> only selected provider's api keys are neccessary, ie. kraken's api keys are not neccessary when choosing tinypng as the provider. | ||
- **TINYPNG_API** - API key for tinypng service | ||
- **KRAKENIO_KEY** - API key for kraken-io service | ||
- **KRAKENIO_SECRET** - API Secret for kraken-io service | ||
|
||
## 🚀 Deployment | ||
|
||
1. Clone this repository, and enter this function folder: | ||
|
||
``` | ||
$ git clone https://github.com/open-runtimes/examples.git && cd examples | ||
$ cd ruby/compress-image | ||
``` | ||
|
||
2. Enter this function folder and build the code: | ||
``` | ||
docker run --rm --interactive --tty --volume $PWD:/usr/code openruntimes/ruby:v2-3.1 sh /usr/local/src/build.sh | ||
``` | ||
As a result, a `code.tar.gz` file will be generated. | ||
3. Start the Open Runtime: | ||
``` | ||
docker run -p 3000:3000 -e INTERNAL_RUNTIME_KEY=secret-key -e INTERNAL_RUNTIME_ENTRYPOINT=index.rb --rm --interactive --tty --volume $PWD/code.tar.gz:/tmp/code.tar.gz:ro openruntimes/ruby:v2-3.1 sh /usr/local/src/start.sh | ||
``` | ||
|
||
4. Execute function: | ||
|
||
```shell | ||
curl http:https://localhost:3000/ -d '{"variables":{"TINYPNG_API":"[YOUR_API_KEY]"},"payload":"{\"provider\":\"tinypng\",\"image\":\"iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAACXBIWXMAAAsTAAALEwEAmpwYAAAAf0lEQVR4nO2Wuw2AMAxEbw1gpMwDDMBcGQpooDKydGVAoXCK6J7k6qyc83MCCFGP/Yz+CkDF4KHmjgowbQF0CKFrCDUiwztqxabHCL0/xwcNhoI2UdsjC8g0mQvaSs1zwkg0uQAsAEaGm9/UPCeU7eMj6loTEpf6ZOQWMxd98gAhZnS6XEZcNQAAAABJRU5ErkJggg==\"}"}' -H "X-Internal-Challenge: secret-key" -H "Content-Type: application/json" | ||
``` | ||
|
||
Your function is now listening on port `3000`, and you can execute it by sending `POST` request with appropriate authorization headers. To learn more about runtime, you can visit Python runtime [README](https://github.com/open-runtimes/open-runtimes/tree/main/runtimes/ruby-3.1). | ||
|
||
## 📝 Notes | ||
- This function is designed for use with Appwrite Cloud Functions. You can learn more about it in [Appwrite docs](https://appwrite.io/docs/functions). | ||
- This example is compatible with Ruby 3.1. Other versions may work but are not guaranteed to work as they haven't been tested. |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,119 @@ | ||
require "json" | ||
require "base64" | ||
require "tinify" | ||
require "kraken-io" | ||
|
||
class NotImageException < StandardError; end | ||
class ApiError < StandardError; end | ||
class NoApiError < StandardError; end | ||
|
||
$invalidPayload = { | ||
success: false, message: "Invalid Payload" | ||
} | ||
$notImage = { | ||
success: false, message: "Input file is not an image." | ||
} | ||
$invalidApi = { | ||
success: false, message: "Invalid API." | ||
} | ||
$noApi = { | ||
success: false, message: "no API key was provided." | ||
} | ||
|
||
def tinypng(req, image) | ||
# Get api key | ||
if !req.variables['TINYPNG_API'] | ||
raise NoApiError | ||
end | ||
|
||
Tinify.key = req.variables['TINYPNG_API'] | ||
buffer = Base64.decode64(image) | ||
result = Tinify.from_buffer(buffer).to_buffer | ||
|
||
Base64.encode64(result) | ||
end | ||
|
||
def krakenio(req, image) | ||
if !req.variables['KRAKENIO_KEY'] or !req.variables['KRAKENIO_SECRET'] | ||
raise NoApiError | ||
end | ||
|
||
buffer = Base64.decode64(image) | ||
dir = Dir.mktmpdir("kraken_temp") | ||
|
||
File.open("#{dir}/file.png", 'wb') do |f| | ||
f.write(buffer) | ||
end | ||
|
||
kraken = Kraken::API.new( | ||
:api_key => req.variables['KRAKENIO_KEY'], | ||
:api_secret => req.variables['KRAKENIO_SECRET'] | ||
) | ||
|
||
data = kraken.upload("#{dir}/file.png") | ||
|
||
File.delete("#{dir}/file.png") if File.exist?("#{dir}/file.png") | ||
|
||
if data.success | ||
img = URI.open(data.kraked_url) | ||
Base64.encode64(img.read) | ||
else | ||
if data.message.include? 'Unknown API Key' | ||
raise ApiError | ||
end | ||
raise NotImageException | ||
end | ||
end | ||
|
||
def main(req, res) | ||
# Input validation | ||
provider = nil | ||
image = nil | ||
begin | ||
payload = JSON.parse(req.payload) | ||
provider = payload["provider"] | ||
image = payload["image"] | ||
rescue Exception => err | ||
return res.json($invalidPayload) | ||
end | ||
|
||
if provider.nil? or provider.empty? or image.nil? or image.empty? | ||
return res.json($invalidPayload) | ||
end | ||
|
||
if provider == 'tinypng' | ||
begin | ||
base64 = tinypng(req, image) | ||
return res.json({ | ||
success: true, | ||
image: base64.gsub("\n",'') | ||
}) | ||
rescue Tinify::ClientError | ||
return res.json($notImage) | ||
rescue Tinify::AccountError | ||
return res.json($invalidApi) | ||
rescue NoApiError | ||
return res.json($noApi) | ||
end | ||
end | ||
|
||
if provider == 'krakenio' | ||
begin | ||
base64 = krakenio(req, image) | ||
return res.json({ | ||
success: true, | ||
image: base64.gsub("\n",'') | ||
}) | ||
rescue ApiError | ||
return res.json($invalidApi) | ||
rescue NotImageException | ||
return res.json($notImage) | ||
rescue NoApiError | ||
return res.json($noApi) | ||
end | ||
end | ||
|
||
res.json({ | ||
success: false, message: "Unsupported Providers." | ||
}) | ||
end |