unofficial-cloudflare-images 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (25) hide show
  1. checksums.yaml +7 -0
  2. data/MIT-LICENSE +20 -0
  3. data/README.md +35 -0
  4. data/Rakefile +8 -0
  5. data/app/assets/stylesheets/unofficial_cloudflare_images/application.css +15 -0
  6. data/app/controllers/unofficial_cloudflare_images/application_controller.rb +4 -0
  7. data/app/controllers/unofficial_cloudflare_images/cloudflare_images_controller.rb +36 -0
  8. data/app/controllers/unofficial_cloudflare_images/direct_uploads_controller.rb +16 -0
  9. data/app/helpers/unofficial_cloudflare_images/application_helper.rb +4 -0
  10. data/app/jobs/unofficial_cloudflare_images/application_job.rb +4 -0
  11. data/app/jobs/unofficial_cloudflare_images/destroy_cloudflare_image_job.rb +8 -0
  12. data/app/mailers/unofficial_cloudflare_images/application_mailer.rb +6 -0
  13. data/app/models/unofficial_cloudflare_images/application_record.rb +5 -0
  14. data/app/services/unofficial_cloudflare_images/cloudflare_image_destroy_service.rb +41 -0
  15. data/app/services/unofficial_cloudflare_images/cloudflare_image_uploader_service.rb +81 -0
  16. data/app/views/layouts/unofficial_cloudflare_images/application.html.erb +17 -0
  17. data/config/routes.rb +6 -0
  18. data/lib/active_storage/active_storage.rb +7 -0
  19. data/lib/active_storage/service/cloudflare_image_service.rb +90 -0
  20. data/lib/tasks/unofficial_cloudflare_images_tasks.rake +4 -0
  21. data/lib/unofficial-cloudflare-images.rb +6 -0
  22. data/lib/unofficial_cloudflare_images/engine.rb +5 -0
  23. data/lib/unofficial_cloudflare_images/railtie.rb +19 -0
  24. data/lib/unofficial_cloudflare_images/version.rb +3 -0
  25. metadata +92 -0
checksums.yaml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: 5a03b334986d3cb2ae0b77e75d830d647bc02a438d15e0ed590f14d0c9d7c589
4
+ data.tar.gz: 15891097d89f87728d4bb651ecbf935f9eaa8e8eabb1e1c63ca08bd2baa55093
5
+ SHA512:
6
+ metadata.gz: c153622c7ceac696bfd183f373ceb2a045029504bfbb58de063bd2ac1b0225d1b98d7bfbb24588d7988fecbd97cd402aceb81910f9d6e033d4eca654ddc30db9
7
+ data.tar.gz: 77fe4d421704b47229e1bcc51f666e009ccfa337673f1e8da137f4e9b7aa17a43e78d80ca51b81a6286ee93e466f685568558353c7f71c36580dc30fdb134640
data/MIT-LICENSE ADDED
@@ -0,0 +1,20 @@
1
+ Copyright Paul Sojan
2
+
3
+ Permission is hereby granted, free of charge, to any person obtaining
4
+ a copy of this software and associated documentation files (the
5
+ "Software"), to deal in the Software without restriction, including
6
+ without limitation the rights to use, copy, modify, merge, publish,
7
+ distribute, sublicense, and/or sell copies of the Software, and to
8
+ permit persons to whom the Software is furnished to do so, subject to
9
+ the following conditions:
10
+
11
+ The above copyright notice and this permission notice shall be
12
+ included in all copies or substantial portions of the Software.
13
+
14
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
15
+ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
16
+ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
17
+ NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
18
+ LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
19
+ OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
20
+ WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
data/README.md ADDED
@@ -0,0 +1,35 @@
1
+ # UnofficialCloudflareImagesGem
2
+
3
+ Short description and motivation.
4
+
5
+ ## Usage
6
+
7
+ How to use my plugin.
8
+
9
+ ## Installation
10
+
11
+ Add this line to your application's Gemfile:
12
+
13
+ ```ruby
14
+ gem "unofficial_cloudflare_images"
15
+ ```
16
+
17
+ And then execute:
18
+
19
+ ```bash
20
+ $ bundle
21
+ ```
22
+
23
+ Or install it yourself as:
24
+
25
+ ```bash
26
+ $ gem install unofficial_cloudflare_images_gem
27
+ ```
28
+
29
+ ## Contributing
30
+
31
+ Contribution directions go here.
32
+
33
+ ## License
34
+
35
+ The gem is available as open source under the terms of the [MIT License](https://opensource.org/licenses/MIT).
data/Rakefile ADDED
@@ -0,0 +1,8 @@
1
+ require "bundler/setup"
2
+
3
+ APP_RAKEFILE = File.expand_path("test/dummy/Rakefile", __dir__)
4
+ load "rails/tasks/engine.rake"
5
+
6
+ load "rails/tasks/statistics.rake"
7
+
8
+ require "bundler/gem_tasks"
@@ -0,0 +1,15 @@
1
+ /*
2
+ * This is a manifest file that'll be compiled into application.css, which will include all the files
3
+ * listed below.
4
+ *
5
+ * Any CSS and SCSS file within this directory, lib/assets/stylesheets, vendor/assets/stylesheets,
6
+ * or any plugin's vendor/assets/stylesheets directory can be referenced here using a relative path.
7
+ *
8
+ * You're free to add application-wide styles to this file and they'll appear at the bottom of the
9
+ * compiled file so the styles you add here take precedence over styles defined in any other CSS/SCSS
10
+ * files in this directory. Styles in this file should be added after the last require_* statement.
11
+ * It is generally better to create a new file per style scope.
12
+ *
13
+ *= require_tree .
14
+ *= require_self
15
+ */
@@ -0,0 +1,4 @@
1
+ module UnofficialCloudflareImages
2
+ class ApplicationController < ActionController::Base
3
+ end
4
+ end
@@ -0,0 +1,36 @@
1
+ module UnofficialCloudflareImages
2
+ class CloudflareImagesController < ApplicationController
3
+ include HTTParty
4
+ base_uri "https://api.cloudflare.com/client/v4"
5
+
6
+ def create
7
+ response = create_direct_upload_request
8
+
9
+ if response.success?
10
+ render json: response.parsed_response
11
+ else
12
+ render json: {
13
+ error: "Upload failed",
14
+ message: response.parsed_response
15
+ }, status: response.code
16
+ end
17
+ rescue StandardError => e
18
+ render json: { error: e.message }, status: :internal_server_error
19
+ end
20
+
21
+ private
22
+
23
+ def create_direct_upload_request
24
+ account_id = Rails.application.credentials.dig(:cloudflare_image, :account_id)
25
+ token = Rails.application.credentials.dig(:cloudflare_image, :token)
26
+
27
+ self.class.post(
28
+ "/accounts/#{account_id}/images/v2/direct_upload",
29
+ headers: {
30
+ "Authorization" => "Bearer #{token}"
31
+ },
32
+ timeout: 10
33
+ )
34
+ end
35
+ end
36
+ end
@@ -0,0 +1,16 @@
1
+ module UnofficialCloudflareImages
2
+ class DirectUploadsController < ActiveStorage::DirectUploadsController
3
+ def create
4
+ blob = ActiveStorage::Blob.create_before_direct_upload!(**blob_params)
5
+ render json: direct_upload_json(blob)
6
+ end
7
+
8
+ private
9
+
10
+ def blob_params
11
+ params
12
+ .require(:blob)
13
+ .permit(:filename, :byte_size, :checksum, :service_name, :content_type, metadata: {}).to_h.symbolize_keys
14
+ end
15
+ end
16
+ end
@@ -0,0 +1,4 @@
1
+ module UnofficialCloudflareImages
2
+ module ApplicationHelper
3
+ end
4
+ end
@@ -0,0 +1,4 @@
1
+ module UnofficialCloudflareImages
2
+ class ApplicationJob < ActiveJob::Base
3
+ end
4
+ end
@@ -0,0 +1,8 @@
1
+ module UnofficialCloudflareImages
2
+ class DestroyCloudflareImageJob < ApplicationJob
3
+ def perform(blob)
4
+ service = UnofficialCloudflareImages::CloudflareImageDestroyService.new(blob)
5
+ service.process
6
+ end
7
+ end
8
+ end
@@ -0,0 +1,6 @@
1
+ module UnofficialCloudflareImages
2
+ class ApplicationMailer < ActionMailer::Base
3
+ default from: "from@example.com"
4
+ layout "mailer"
5
+ end
6
+ end
@@ -0,0 +1,5 @@
1
+ module UnofficialCloudflareImages
2
+ class ApplicationRecord < ActiveRecord::Base
3
+ self.abstract_class = true
4
+ end
5
+ end
@@ -0,0 +1,41 @@
1
+ module UnofficialCloudflareImages
2
+ class CloudflareImageDestroyService
3
+ class CloudflareDeleteError < StandardError; end
4
+
5
+ include HTTParty
6
+ base_uri "https://api.cloudflare.com/client/v4"
7
+
8
+ attr_reader :blob
9
+
10
+ def initialize(blob)
11
+ @blob = blob
12
+ end
13
+
14
+ def process
15
+ response = destroy_image
16
+
17
+ unless response.success?
18
+ raise CloudflareDeleteError,
19
+ "Cloudflare image delete failed. (#{response.code}): #{response.body}"
20
+ end
21
+
22
+ response
23
+ end
24
+
25
+ private
26
+
27
+ def destroy_image
28
+ account_id = Rails.application.credentials.dig(:cloudflare_image, :account_id)
29
+ token = Rails.application.credentials.dig(:cloudflare_image, :token)
30
+ image_id = blob["metadata"]["id"]
31
+
32
+ self.class.delete(
33
+ "/accounts/#{account_id}/images/v1/#{image_id}",
34
+ headers: {
35
+ "Authorization" => "Bearer #{token}",
36
+ "Content-Type" => "application/json"
37
+ }
38
+ )
39
+ end
40
+ end
41
+ end
@@ -0,0 +1,81 @@
1
+ require "multipart/post"
2
+
3
+ module UnofficialCloudflareImages
4
+ class CloudflareImageUploaderService
5
+ class UploadError < StandardError; end
6
+
7
+ attr_reader :io, :blob
8
+
9
+ def initialize(io, blob)
10
+ @io = io
11
+ @blob = blob
12
+ end
13
+
14
+ def upload
15
+ response = HTTParty.post(
16
+ upload_url,
17
+ headers: headers,
18
+ body: build_upload_body
19
+ )
20
+ handle_response(response)
21
+ update_blob(response)
22
+ end
23
+
24
+ private
25
+
26
+ def upload_url
27
+ account_id = Rails.application.credentials.dig(:cloudflare_image, :account_id)
28
+ "https://api.cloudflare.com/client/v4/accounts/#{account_id}/images/v1"
29
+ end
30
+
31
+ def headers
32
+ api_token = Rails.application.credentials.dig(:cloudflare_image, :token)
33
+ {
34
+ "Authorization" => "Bearer #{api_token}"
35
+ }
36
+ end
37
+
38
+ def build_upload_body
39
+ mime_type = blob.content_type.to_s
40
+
41
+ upload_io =
42
+ if io.respond_to?(:read)
43
+ UploadIO.new(io, mime_type, blob.filename.to_s)
44
+ else
45
+ UploadIO.new(StringIO.new(io), mime_type, filename)
46
+ end
47
+ {
48
+ file: upload_io
49
+ }
50
+ end
51
+
52
+ def update_blob(response)
53
+ blob.update!(
54
+ metadata: blob.metadata.merge(
55
+ {
56
+ **response["result"],
57
+ url: response["result"]["variants"][0],
58
+ isCropped: false
59
+ })
60
+ )
61
+ end
62
+
63
+ def handle_response(response)
64
+ unless response.success?
65
+ error_message = parse_error_message(response)
66
+ raise UploadError, "Cloudflare upload failed (#{response.code}): #{error_message}"
67
+ end
68
+
69
+ JSON.parse(response.body)
70
+ end
71
+
72
+ def parse_error_message(response)
73
+ body = JSON.parse(response.body) rescue {}
74
+ if body["errors"]&.any?
75
+ body["errors"].map { |e| e["message"] }.join(", ")
76
+ else
77
+ response.body
78
+ end
79
+ end
80
+ end
81
+ end
@@ -0,0 +1,17 @@
1
+ <!DOCTYPE html>
2
+ <html>
3
+ <head>
4
+ <title>Unofficial cloudflare images</title>
5
+ <%= csrf_meta_tags %>
6
+ <%= csp_meta_tag %>
7
+
8
+ <%= yield :head %>
9
+
10
+ <%= stylesheet_link_tag "unofficial_cloudflare_images/application", media: "all" %>
11
+ </head>
12
+ <body>
13
+
14
+ <%= yield %>
15
+
16
+ </body>
17
+ </html>
data/config/routes.rb ADDED
@@ -0,0 +1,6 @@
1
+ UnofficialCloudflareImages::Engine.routes.draw do
2
+ defaults format: :json do
3
+ resources :cloudflare_images, only: [ :index, :create ]
4
+ resources :direct_uploads, only: [ :create ]
5
+ end
6
+ end
@@ -0,0 +1,7 @@
1
+ require_relative "./service/cloudflare_image_service"
2
+
3
+ begin
4
+ require "active_storage"
5
+ rescue LoadError
6
+ puts "Add gem activestorage to use this service"
7
+ end
@@ -0,0 +1,90 @@
1
+ require "active_storage/service"
2
+
3
+ class DownloaderExtension < ::ActiveStorage::Downloader
4
+ def open(key, checksum:, name: "ActiveStorage-", tmpdir: nil, **options)
5
+ open_tempfile(name, tmpdir) do |file|
6
+ download key, file
7
+ yield file
8
+ end
9
+ end
10
+ end
11
+
12
+ module ActiveStorage
13
+ class Service::CloudflareImageService < Service
14
+ def initialize(**config)
15
+ super
16
+ @config = config
17
+ end
18
+
19
+ def upload(key, io, checksum: nil, content_type: nil, disposition: nil, filename: nil, custom_metadata: {}, **)
20
+ instrument :upload, key: key do
21
+ blob = ActiveStorage::Blob.find_by_key(key)
22
+ service = UnofficialCloudflareImages::CloudflareImageUploaderService.new(io, blob)
23
+ service.upload
24
+ end
25
+ end
26
+
27
+ def url_for_direct_upload(key, **options)
28
+ Rails.logger.warn("Direct upload is not supported for Cloudflare Images service")
29
+ end
30
+
31
+ def url(key, filename: nil, content_type: "", **options)
32
+ blob = ActiveStorage::Blob.find_by_key(key)
33
+ blob.metadata[:url]
34
+ end
35
+
36
+ def download(key, &block)
37
+ if block_given?
38
+ instrument(:stream_file, key:) do
39
+ stream_file(key, &block)
40
+ end
41
+ else
42
+ instrument(:download, key:) do
43
+ cloudflare_image_file(key)
44
+ end
45
+ end
46
+ end
47
+
48
+ def download_chunk(key, range)
49
+ raise NotImplementedError, "Chunk download is not implemented for Cloudflare Images service"
50
+ end
51
+
52
+ def delete_prefixed(prefix)
53
+ raise NotImplementedError, "Prefix deletion is not supported for Cloudflare Images service"
54
+ end
55
+
56
+ def delete(key)
57
+ blob = ActiveStorage::Blob.find_by_key(key)
58
+
59
+ nil unless blob
60
+
61
+ UnofficialCloudflareImages::DestroyCloudflareImageJob.perform_later(blob.as_json)
62
+ end
63
+
64
+ def open(*args, **options, &block)
65
+ DownloaderExtension.new(self).open(*args, **options, &block)
66
+ end
67
+
68
+ private
69
+
70
+ def cloudflare_image_file(key)
71
+ image_url = url(key)
72
+
73
+ response = HTTParty.get(image_url, stream_body: false)
74
+
75
+ unless response.success?
76
+ raise "Failed to download Cloudflare image (#{response.code})"
77
+ end
78
+
79
+ response.body
80
+ end
81
+
82
+ def stream_file(key)
83
+ image_url = url(key)
84
+
85
+ HTTParty.get(image_url, stream_body: true) do |fragment|
86
+ yield fragment
87
+ end
88
+ end
89
+ end
90
+ end
@@ -0,0 +1,4 @@
1
+ # desc "Explaining what the task does"
2
+ # task :unofficial_cloudflare_images do
3
+ # # Task goes here
4
+ # end
@@ -0,0 +1,6 @@
1
+ require "unofficial_cloudflare_images/version"
2
+ require "unofficial_cloudflare_images/engine"
3
+ require "unofficial_cloudflare_images/railtie"
4
+
5
+ module UnofficialCloudflareImages
6
+ end
@@ -0,0 +1,5 @@
1
+ module UnofficialCloudflareImages
2
+ class Engine < ::Rails::Engine
3
+ isolate_namespace UnofficialCloudflareImages
4
+ end
5
+ end
@@ -0,0 +1,19 @@
1
+ module UnofficialCloudflareImages
2
+ class Railtie < Rails::Railtie
3
+ initializer "unofficial_cloudflare_images.active_storage" do
4
+ ActiveSupport.on_load(:active_storage_blob) do
5
+ before_destroy :delete_from_cloudflare, if: :cloudflare_image_service?
6
+
7
+ private
8
+
9
+ def cloudflare_image_service?
10
+ service_name == "cloudflare_image"
11
+ end
12
+
13
+ def delete_from_cloudflare
14
+ service.delete(key)
15
+ end
16
+ end
17
+ end
18
+ end
19
+ end
@@ -0,0 +1,3 @@
1
+ module UnofficialCloudflareImages
2
+ VERSION = "0.1.1"
3
+ end
metadata ADDED
@@ -0,0 +1,92 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: unofficial-cloudflare-images
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.1.1
5
+ platform: ruby
6
+ authors:
7
+ - Paul Sojan
8
+ bindir: bin
9
+ cert_chain: []
10
+ date: 1980-01-02 00:00:00.000000000 Z
11
+ dependencies:
12
+ - !ruby/object:Gem::Dependency
13
+ name: rails
14
+ requirement: !ruby/object:Gem::Requirement
15
+ requirements:
16
+ - - ">="
17
+ - !ruby/object:Gem::Version
18
+ version: 7.2.2.2
19
+ type: :runtime
20
+ prerelease: false
21
+ version_requirements: !ruby/object:Gem::Requirement
22
+ requirements:
23
+ - - ">="
24
+ - !ruby/object:Gem::Version
25
+ version: 7.2.2.2
26
+ - !ruby/object:Gem::Dependency
27
+ name: multipart-post
28
+ requirement: !ruby/object:Gem::Requirement
29
+ requirements:
30
+ - - ">="
31
+ - !ruby/object:Gem::Version
32
+ version: '0'
33
+ type: :runtime
34
+ prerelease: false
35
+ version_requirements: !ruby/object:Gem::Requirement
36
+ requirements:
37
+ - - ">="
38
+ - !ruby/object:Gem::Version
39
+ version: '0'
40
+ email:
41
+ - paul.eliassojan@gmail.com
42
+ executables: []
43
+ extensions: []
44
+ extra_rdoc_files: []
45
+ files:
46
+ - MIT-LICENSE
47
+ - README.md
48
+ - Rakefile
49
+ - app/assets/stylesheets/unofficial_cloudflare_images/application.css
50
+ - app/controllers/unofficial_cloudflare_images/application_controller.rb
51
+ - app/controllers/unofficial_cloudflare_images/cloudflare_images_controller.rb
52
+ - app/controllers/unofficial_cloudflare_images/direct_uploads_controller.rb
53
+ - app/helpers/unofficial_cloudflare_images/application_helper.rb
54
+ - app/jobs/unofficial_cloudflare_images/application_job.rb
55
+ - app/jobs/unofficial_cloudflare_images/destroy_cloudflare_image_job.rb
56
+ - app/mailers/unofficial_cloudflare_images/application_mailer.rb
57
+ - app/models/unofficial_cloudflare_images/application_record.rb
58
+ - app/services/unofficial_cloudflare_images/cloudflare_image_destroy_service.rb
59
+ - app/services/unofficial_cloudflare_images/cloudflare_image_uploader_service.rb
60
+ - app/views/layouts/unofficial_cloudflare_images/application.html.erb
61
+ - config/routes.rb
62
+ - lib/active_storage/active_storage.rb
63
+ - lib/active_storage/service/cloudflare_image_service.rb
64
+ - lib/tasks/unofficial_cloudflare_images_tasks.rake
65
+ - lib/unofficial-cloudflare-images.rb
66
+ - lib/unofficial_cloudflare_images/engine.rb
67
+ - lib/unofficial_cloudflare_images/railtie.rb
68
+ - lib/unofficial_cloudflare_images/version.rb
69
+ homepage: https://github.com/paulsojan/unofficial-cloudflare-images-gem
70
+ licenses:
71
+ - MIT
72
+ metadata:
73
+ homepage_uri: https://github.com/paulsojan/unofficial-cloudflare-images-gem
74
+ source_code_uri: https://github.com/paulsojan/unofficial-cloudflare-images-gem
75
+ rdoc_options: []
76
+ require_paths:
77
+ - lib
78
+ required_ruby_version: !ruby/object:Gem::Requirement
79
+ requirements:
80
+ - - ">="
81
+ - !ruby/object:Gem::Version
82
+ version: '0'
83
+ required_rubygems_version: !ruby/object:Gem::Requirement
84
+ requirements:
85
+ - - ">="
86
+ - !ruby/object:Gem::Version
87
+ version: '0'
88
+ requirements: []
89
+ rubygems_version: 3.6.7
90
+ specification_version: 4
91
+ summary: Unofficial gem to upload images to Cloudflare Images
92
+ test_files: []