stratocaster 0.4.0

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.
checksums.yaml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: 76d62f5aa583c126c93c03936721fee40c94e52f9a5c99b075deaef9f4eb0c46
4
+ data.tar.gz: 3e5a37e88a5f76d16c1c5fbb0295523fffa21953eea6b5da37d964618ef5da20
5
+ SHA512:
6
+ metadata.gz: b004638c553dea0929a9ad488e0f9d134f14bfdfa0d5b9da6a1d973bd1d89aec683a6e26ccae7f6945dbe20c799cd169d8d9e5d9f6b9563ff54b34da8d886e64
7
+ data.tar.gz: f73752ac70f201b5da23e6550b20a8edbea43ccb0cfb50fa09f691e832e894b0cbdf35bac40e3ab54b63221909ae8be96e04e6f49a67508cebac81cb5600fb62
data/MIT-LICENSE ADDED
@@ -0,0 +1,20 @@
1
+ Copyright 2022 Johan Halse
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,28 @@
1
+ # Stratocaster
2
+ Short description and motivation.
3
+
4
+ ## Usage
5
+ How to use my plugin.
6
+
7
+ ## Installation
8
+ Add this line to your application's Gemfile:
9
+
10
+ ```ruby
11
+ gem "stratocaster"
12
+ ```
13
+
14
+ And then execute:
15
+ ```bash
16
+ $ bundle
17
+ ```
18
+
19
+ Or install it yourself as:
20
+ ```bash
21
+ $ gem install stratocaster
22
+ ```
23
+
24
+ ## Contributing
25
+ Contribution directions go here.
26
+
27
+ ## License
28
+ 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,12 @@
1
+ require "bundler/setup"
2
+
3
+ require "bundler/gem_tasks"
4
+ require "rake/testtask"
5
+
6
+ Rake::TestTask.new(:test) do |t|
7
+ t.libs << "test"
8
+ t.pattern = "test/**/*_test.rb"
9
+ t.verbose = false
10
+ end
11
+
12
+ task default: :test
@@ -0,0 +1,81 @@
1
+ module Stratocaster
2
+ module Attacher
3
+ extend ActiveSupport::Concern
4
+
5
+ class_methods do
6
+ def with_image(base_name, &block)
7
+ attr_accessor base_name
8
+
9
+ define_method("#{base_name}?") { send("#{base_name}_filename").present? }
10
+ strattachments.merge!(base_name => [])
11
+ block.call(base_name)
12
+ before_save :upload_strattachment_originals
13
+ after_commit :perform_processing_job, on: %i[create update]
14
+ after_destroy_commit :purge_strattachments
15
+ end
16
+
17
+ def strattachments
18
+ @strattachments ||= {}
19
+ end
20
+
21
+ def add_format(base_name, format_name, **kwargs)
22
+ strattachments[base_name] << [format_name, kwargs]
23
+
24
+ define_method "#{base_name}_#{format_name}_filename" do
25
+ base_filename = send("#{base_name}_filename")
26
+ return nil if base_filename.nil?
27
+
28
+ strat_md5(base_filename, format_name)
29
+ end
30
+
31
+ define_method "#{base_name}_#{format_name}_dimensions" do
32
+ metadata = send("#{base_name}_metadata")[format_name.to_s]
33
+ metadata.presence || begin
34
+ ops = %i[resize_to_fill resize_to_limit resize_and_pad]
35
+ values = kwargs.fetch(ops.find { kwargs.key?(_1) }, {})
36
+ { width: values.first, height: values.last }
37
+ end
38
+ end
39
+ end
40
+ end
41
+
42
+ included do
43
+ if Stratocaster.config.uploader == :cloud
44
+ include Stratocaster::CloudUploader
45
+ else
46
+ include Stratocaster::LocalUploader
47
+ end
48
+
49
+ def strat_md5(base_filename, format_name = nil)
50
+ Digest::MD5.hexdigest(base_filename + format_name.to_s)
51
+ end
52
+
53
+ def strattachments
54
+ self.class.strattachments
55
+ end
56
+
57
+ def perform_processing_job
58
+ Stratocaster::ProcessingJob.perform_later(self) if @perform_processing_job
59
+ end
60
+
61
+ def strat_base_md5(file:)
62
+ "original_#{Digest::MD5.hexdigest(file.read)}"
63
+ end
64
+
65
+ # Deleting inline would hold the destroy transaction, and every row lock it has taken, open across one
66
+ # HTTP round trip per original and variant -- long enough for a concurrent writer to deadlock against
67
+ # it. Collect the keys and let a job do the deleting once the transaction has committed, so a rollback
68
+ # also stops us from orphaning rows that still point at deleted files.
69
+ def purge_strattachments
70
+ filenames = strattachments.flat_map do |base_name, variants|
71
+ filename = send("#{base_name}_filename")
72
+ next [] if filename.blank?
73
+
74
+ [filename] + variants.map { |variant_name, _options| strat_md5(filename, variant_name) }
75
+ end
76
+
77
+ Stratocaster::PurgeJob.perform_later(filenames) if filenames.any?
78
+ end
79
+ end
80
+ end
81
+ end
@@ -0,0 +1,37 @@
1
+ module Stratocaster
2
+ module BaseUploader
3
+ def upload_strattachment_originals
4
+ raise NotImplementedError
5
+ end
6
+
7
+ def strat_upload(file, filename)
8
+ raise NotImplementedError
9
+ end
10
+
11
+ def strat_delete(filename)
12
+ raise NotImplementedError
13
+ end
14
+
15
+ private
16
+
17
+ def image_size(file)
18
+ image = Vips::Image.new_from_file(file.path, access: :sequential)
19
+ { width: image.width, height: image.height }
20
+ rescue StandardError => _e
21
+ {}
22
+ end
23
+
24
+ def resize_original_image(file)
25
+ pipeline = ImageProcessing::Vips
26
+ .source(file.path)
27
+ .convert("jpg")
28
+ .saver(quality: 85)
29
+ .resize_to_limit(2500, 2500)
30
+
31
+ pipeline.call
32
+ rescue StandardError => e
33
+ Rails.logger.error("Failed to resize image: #{e.message}")
34
+ file
35
+ end
36
+ end
37
+ end
@@ -0,0 +1,48 @@
1
+ module Stratocaster
2
+ class CloudClient
3
+ def self.stratoclient
4
+ Aws::S3::Client.new(**Stratocaster.config.cloud_config.except(:bucket))
5
+ end
6
+
7
+ def self.upload(file, filename)
8
+ stratoclient.put_object(
9
+ acl: "public-read",
10
+ body: file,
11
+ bucket: Stratocaster.config.cloud_config[:bucket],
12
+ content_type: "image/jpeg",
13
+ key: filename
14
+ ).etag.present?
15
+ end
16
+
17
+ def self.download(filename)
18
+ FileUtils.mkdir_p("tmp")
19
+ local_path = "tmp/#{filename}"
20
+
21
+ return File.open(local_path) if File.exist?(local_path)
22
+
23
+ stratoclient.get_object(
24
+ bucket: Stratocaster.config.cloud_config[:bucket],
25
+ key: filename,
26
+ response_target: local_path
27
+ )
28
+
29
+ File.open(local_path)
30
+ end
31
+
32
+ def self.delete(filename)
33
+ stratoclient.delete_object(
34
+ bucket: Stratocaster.config.cloud_config[:bucket],
35
+ key: filename
36
+ )
37
+ true
38
+ rescue => e
39
+ # Handle AWS S3 errors gracefully
40
+ if defined?(Aws::S3::Errors::NoSuchKey) && e.is_a?(Aws::S3::Errors::NoSuchKey)
41
+ false
42
+ else
43
+ # For testing, also handle our mock error
44
+ false
45
+ end
46
+ end
47
+ end
48
+ end
@@ -0,0 +1,35 @@
1
+ module Stratocaster
2
+ module CloudUploader
3
+ include BaseUploader
4
+
5
+ def upload_strattachment_originals
6
+ strattachments.each_key do |f|
7
+ file = send(f)
8
+ next unless file
9
+
10
+ @perform_processing_job = true
11
+ resized_file = resize_original_image(file)
12
+ filename = strat_base_md5(file: resized_file)
13
+ upload_success = strat_upload(resized_file, filename)
14
+
15
+ # Clean up temp file if it was created
16
+ resized_file.close! if resized_file.respond_to?(:close!) && resized_file != file
17
+
18
+ next unless upload_success
19
+
20
+ assign_attributes(
21
+ "#{f}_filename" => filename,
22
+ "#{f}_metadata" => image_size(file)
23
+ )
24
+ end
25
+ end
26
+
27
+ def strat_upload(file, filename)
28
+ Stratocaster::CloudClient.upload(file, filename)
29
+ end
30
+
31
+ def strat_delete(filename)
32
+ Stratocaster::CloudClient.delete(filename)
33
+ end
34
+ end
35
+ end
@@ -0,0 +1,36 @@
1
+ module Stratocaster
2
+ module LocalUploader
3
+ include BaseUploader
4
+
5
+ def upload_strattachment_originals
6
+ FileUtils.mkdir_p("public/images")
7
+
8
+ strattachments.each_key do |f|
9
+ file = send(f)
10
+ next unless file
11
+
12
+ @perform_processing_job = true
13
+ resized_file = resize_original_image(file)
14
+ filename = strat_base_md5(file: resized_file)
15
+ strat_upload(resized_file, filename)
16
+
17
+ # Clean up temp file if it was created
18
+ resized_file.close! if resized_file.respond_to?(:close!) && resized_file != file
19
+
20
+ assign_attributes(
21
+ "#{f}_filename" => filename,
22
+ "#{f}_metadata" => image_size(file)
23
+ )
24
+ end
25
+ end
26
+
27
+ def strat_upload(file, filename)
28
+ FileUtils.cp(file.path, "public/images/#{filename}")
29
+ end
30
+
31
+ def strat_delete(filename)
32
+ file_path = "public/images/#{filename}"
33
+ FileUtils.rm_f(file_path) if File.exist?(file_path)
34
+ end
35
+ end
36
+ end
@@ -0,0 +1,64 @@
1
+ module Stratocaster
2
+ class ProcessingJob < ActiveJob::Base
3
+ queue_as :stratocaster_jobs
4
+
5
+ self.priority = 2
6
+
7
+ def perform(obj)
8
+ obj.strattachments.each_key do |base_name|
9
+ filename = obj.send("#{base_name}_filename")
10
+ next if filename.blank?
11
+
12
+ original_image = download_image(filename)
13
+ obj.strattachments[base_name].each do |variant|
14
+ variant_name = variant.first
15
+ operations = variant.last
16
+
17
+ processed_image = ImageProcessing::Vips.source(original_image).apply(operations).call
18
+ set_dimension_metadata(obj, base_name, variant_name, processed_image)
19
+ upload_image(processed_image, strat_md5(filename, variant_name))
20
+ File.delete(processed_image)
21
+ end
22
+
23
+ obj.save!
24
+ destroy_downloaded_image(filename)
25
+ end
26
+ end
27
+
28
+ private
29
+
30
+ def set_dimension_metadata(obj, base_name, variant_name, processed_image)
31
+ image = Vips::Image.new_from_file(processed_image.path, access: :sequential)
32
+ variant_metadata = { width: image.width, height: image.height }
33
+ m = obj.send("#{base_name}_metadata")
34
+ obj.send("#{base_name}_metadata=", m.merge(variant_name.to_s => variant_metadata))
35
+ end
36
+
37
+ def destroy_downloaded_image(filename)
38
+ return unless Stratocaster.config.uploader == :cloud
39
+
40
+ file_path = "tmp/#{filename}"
41
+ File.delete(file_path) if File.exist?(file_path)
42
+ end
43
+
44
+ def download_image(filename)
45
+ if Stratocaster.config.uploader == :cloud
46
+ Stratocaster::CloudClient.download(filename)
47
+ else
48
+ File.open("public/images/#{filename}")
49
+ end
50
+ end
51
+
52
+ def upload_image(processed_image, filename)
53
+ if Stratocaster.config.uploader == :cloud
54
+ Stratocaster::CloudClient.upload(processed_image, filename)
55
+ else
56
+ FileUtils.cp(processed_image, "public/images/#{filename}")
57
+ end
58
+ end
59
+
60
+ def strat_md5(filename, format_name)
61
+ Digest::MD5.hexdigest(filename + format_name.to_s)
62
+ end
63
+ end
64
+ end
@@ -0,0 +1,21 @@
1
+ module Stratocaster
2
+ class PurgeJob < ActiveJob::Base
3
+ queue_as :stratocaster_jobs
4
+
5
+ self.priority = 3
6
+
7
+ def perform(filenames)
8
+ filenames.each { |filename| purge(filename) }
9
+ end
10
+
11
+ private
12
+
13
+ def purge(filename)
14
+ if Stratocaster.config.uploader == :cloud
15
+ Stratocaster::CloudClient.delete(filename)
16
+ else
17
+ FileUtils.rm_f("public/images/#{filename}")
18
+ end
19
+ end
20
+ end
21
+ end
@@ -0,0 +1,13 @@
1
+ module Stratocaster
2
+ class Railtie < ::Rails::Railtie
3
+ config.stratocaster = ActiveSupport::OrderedOptions.new
4
+
5
+ initializer "stratocaster.configure_rails_initialization" do
6
+ Stratocaster.config = config.stratocaster
7
+
8
+ ActiveSupport.on_load :action_view do
9
+ include Stratocaster::ViewHelper
10
+ end
11
+ end
12
+ end
13
+ end
@@ -0,0 +1,3 @@
1
+ module Stratocaster
2
+ VERSION = "0.4.0".freeze
3
+ end
@@ -0,0 +1,15 @@
1
+ module Stratocaster
2
+ module ViewHelper
3
+ def strat_image(filename, **kwargs)
4
+ image_tag strat_url(filename), **kwargs
5
+ end
6
+
7
+ def strat_url(url)
8
+ if Stratocaster.config.uploader == :cloud
9
+ "https://#{Stratocaster.config.cloud_config[:bucket]}.fra1.cdn.digitaloceanspaces.com/#{url}"
10
+ else
11
+ "/images/#{url}"
12
+ end
13
+ end
14
+ end
15
+ end
@@ -0,0 +1,15 @@
1
+ require "stratocaster/version"
2
+ require "stratocaster/railtie"
3
+ require "stratocaster/attacher"
4
+ require "stratocaster/cloud_client"
5
+ require "stratocaster/base_uploader"
6
+ require "stratocaster/cloud_uploader"
7
+ require "stratocaster/local_uploader"
8
+ require "stratocaster/processing_job"
9
+ require "stratocaster/purge_job"
10
+ require "stratocaster/view_helper"
11
+ require "image_processing/vips"
12
+
13
+ module Stratocaster
14
+ cattr_accessor :config
15
+ end
@@ -0,0 +1,4 @@
1
+ # desc "Explaining what the task does"
2
+ # task :stratocaster do
3
+ # # Task goes here
4
+ # end
metadata ADDED
@@ -0,0 +1,74 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: stratocaster
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.4.0
5
+ platform: ruby
6
+ authors:
7
+ - Johan Halse
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.0.0.0
19
+ type: :runtime
20
+ prerelease: false
21
+ version_requirements: !ruby/object:Gem::Requirement
22
+ requirements:
23
+ - - ">="
24
+ - !ruby/object:Gem::Version
25
+ version: 7.0.0.0
26
+ description: Imagine having images on Rails without fucking everything up
27
+ email:
28
+ - johan@hal.se
29
+ executables: []
30
+ extensions: []
31
+ extra_rdoc_files: []
32
+ files:
33
+ - MIT-LICENSE
34
+ - README.md
35
+ - Rakefile
36
+ - lib/stratocaster.rb
37
+ - lib/stratocaster/attacher.rb
38
+ - lib/stratocaster/base_uploader.rb
39
+ - lib/stratocaster/cloud_client.rb
40
+ - lib/stratocaster/cloud_uploader.rb
41
+ - lib/stratocaster/local_uploader.rb
42
+ - lib/stratocaster/processing_job.rb
43
+ - lib/stratocaster/purge_job.rb
44
+ - lib/stratocaster/railtie.rb
45
+ - lib/stratocaster/version.rb
46
+ - lib/stratocaster/view_helper.rb
47
+ - lib/tasks/stratocaster_tasks.rake
48
+ homepage: https://github.com/johanhalse/stratocaster
49
+ licenses:
50
+ - MIT
51
+ metadata:
52
+ allowed_push_host: https://rubygems.org
53
+ homepage_uri: https://github.com/johanhalse/stratocaster
54
+ source_code_uri: https://github.com/johanhalse/stratocaster
55
+ changelog_uri: https://github.com/johanhalse/stratocaster/CHANGELOG.md
56
+ rubygems_mfa_required: 'true'
57
+ rdoc_options: []
58
+ require_paths:
59
+ - lib
60
+ required_ruby_version: !ruby/object:Gem::Requirement
61
+ requirements:
62
+ - - ">="
63
+ - !ruby/object:Gem::Version
64
+ version: 3.0.0
65
+ required_rubygems_version: !ruby/object:Gem::Requirement
66
+ requirements:
67
+ - - ">="
68
+ - !ruby/object:Gem::Version
69
+ version: '0'
70
+ requirements: []
71
+ rubygems_version: 4.0.15
72
+ specification_version: 4
73
+ summary: Another flippin image uploader
74
+ test_files: []