shrine-google_drive_storage 0.1.0

Sign up to get free protection for your applications and to get access to all the features.
checksums.yaml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA1:
3
+ metadata.gz: 480f971537a7b3cb4789071faff19f8bc764c047
4
+ data.tar.gz: 1be95da4f2de7bb33af2f37048b587e7bddc070e
5
+ SHA512:
6
+ metadata.gz: 8129ea7b7e931aefe215dbd3454a84979d7e2c1e6f122206a47d4aab422c09ee481724832388625aaabf3681d85245a8e89301b247c55d044444925b8e5a7db0
7
+ data.tar.gz: 3ae7ef8862212b6de40a65e4b63b63c00e419c03c21d480a1b02c87540dc7afc6ed36afd876ff8e076ab4eed7cda73e2c95c5500a73fc14450907f384f75fd9d
data/.gitignore ADDED
@@ -0,0 +1,13 @@
1
+ /.bundle/
2
+ /.yardoc
3
+ /Gemfile.lock
4
+ /_yardoc/
5
+ /coverage/
6
+ /doc/
7
+ /pkg/
8
+ /spec/reports/
9
+ /tmp/
10
+ .config
11
+
12
+ # rspec failure tracking
13
+ .rspec_status
data/.travis.yml ADDED
@@ -0,0 +1,6 @@
1
+ sudo: false
2
+ language: ruby
3
+ rvm:
4
+ - 2.4.0
5
+ # uncomment and edit the following line if your project needs to run something other than `rake`:
6
+ script: bundle exec rspec spec
@@ -0,0 +1,74 @@
1
+ # Contributor Covenant Code of Conduct
2
+
3
+ ## Our Pledge
4
+
5
+ In the interest of fostering an open and welcoming environment, we as
6
+ contributors and maintainers pledge to making participation in our project and
7
+ our community a harassment-free experience for everyone, regardless of age, body
8
+ size, disability, ethnicity, gender identity and expression, level of experience,
9
+ nationality, personal appearance, race, religion, or sexual identity and
10
+ orientation.
11
+
12
+ ## Our Standards
13
+
14
+ Examples of behavior that contributes to creating a positive environment
15
+ include:
16
+
17
+ * Using welcoming and inclusive language
18
+ * Being respectful of differing viewpoints and experiences
19
+ * Gracefully accepting constructive criticism
20
+ * Focusing on what is best for the community
21
+ * Showing empathy towards other community members
22
+
23
+ Examples of unacceptable behavior by participants include:
24
+
25
+ * The use of sexualized language or imagery and unwelcome sexual attention or
26
+ advances
27
+ * Trolling, insulting/derogatory comments, and personal or political attacks
28
+ * Public or private harassment
29
+ * Publishing others' private information, such as a physical or electronic
30
+ address, without explicit permission
31
+ * Other conduct which could reasonably be considered inappropriate in a
32
+ professional setting
33
+
34
+ ## Our Responsibilities
35
+
36
+ Project maintainers are responsible for clarifying the standards of acceptable
37
+ behavior and are expected to take appropriate and fair corrective action in
38
+ response to any instances of unacceptable behavior.
39
+
40
+ Project maintainers have the right and responsibility to remove, edit, or
41
+ reject comments, commits, code, wiki edits, issues, and other contributions
42
+ that are not aligned to this Code of Conduct, or to ban temporarily or
43
+ permanently any contributor for other behaviors that they deem inappropriate,
44
+ threatening, offensive, or harmful.
45
+
46
+ ## Scope
47
+
48
+ This Code of Conduct applies both within project spaces and in public spaces
49
+ when an individual is representing the project or its community. Examples of
50
+ representing a project or community include using an official project e-mail
51
+ address, posting via an official social media account, or acting as an appointed
52
+ representative at an online or offline event. Representation of a project may be
53
+ further defined and clarified by project maintainers.
54
+
55
+ ## Enforcement
56
+
57
+ Instances of abusive, harassing, or otherwise unacceptable behavior may be
58
+ reported by contacting the project team at scott.near@elevateenergy.org. All
59
+ complaints will be reviewed and investigated and will result in a response that
60
+ is deemed necessary and appropriate to the circumstances. The project team is
61
+ obligated to maintain confidentiality with regard to the reporter of an incident.
62
+ Further details of specific enforcement policies may be posted separately.
63
+
64
+ Project maintainers who do not follow or enforce the Code of Conduct in good
65
+ faith may face temporary or permanent repercussions as determined by other
66
+ members of the project's leadership.
67
+
68
+ ## Attribution
69
+
70
+ This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4,
71
+ available at [http://contributor-covenant.org/version/1/4][version]
72
+
73
+ [homepage]: http://contributor-covenant.org
74
+ [version]: http://contributor-covenant.org/version/1/4/
data/Gemfile ADDED
@@ -0,0 +1,4 @@
1
+ source "https://rubygems.org"
2
+
3
+ # Specify your gem's dependencies in shrine-google_drive_storage.gemspec
4
+ gemspec
data/LICENSE.txt ADDED
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2017 Scott Near
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in
13
+ all copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
21
+ THE SOFTWARE.
data/README.md ADDED
@@ -0,0 +1,108 @@
1
+ # Shrine::GoogleDriveStorage
2
+
3
+ Welcome to your new gem! In this directory, you'll find the files you need to be able to package up your Ruby library into a gem. Put your Ruby code in the file `lib/shrine/google_drive_storage`. To experiment with that code, run `bin/console` for an interactive prompt.
4
+
5
+ Provides [Google Drive Storage] storage for [Shrine].
6
+
7
+ ## Installation
8
+
9
+ Add this line to your application's Gemfile:
10
+
11
+ ```ruby
12
+ gem 'shrine-google_drive_storage'
13
+ ```
14
+
15
+ And then execute:
16
+
17
+ $ bundle
18
+
19
+ Or install it yourself as:
20
+
21
+ $ gem install shrine-google_drive_storage
22
+
23
+ ## Google Drive Setup
24
+
25
+ Google Drive is a free service for file storage files. In order to use this storage you need a Google (or Google Apps) user which will own the files, and a Google API client.
26
+
27
+ 1. Go to the [Google Developers console](https://console.developers.google.com/project) and create a new project, this option is on the top, next to the Google APIs logo.
28
+
29
+ 2. Go to "API Manager > Library" in the section "Google Apps APIs" and enable "Drive API". If you are getting an "Access Not Configured" error while uploading files, this is due to this API not being enabled.
30
+
31
+ 3. Go to "API Manager > Credentials" and click on "OAuth Client ID" before to select "Other" type you must specify `http://localhost` for application home page.
32
+
33
+ 4. Now you will have a Client ID, Client Secret, and Redirect URL. So, download the client_secret_XXXXX.json file and rename it to client_secret.json.
34
+
35
+ 5. Run the authorization task:
36
+ ```sh
37
+ $ rake google_drive:authorize"[path/to/client_secret.json, 'application_name']"
38
+ ```
39
+ NOTE:
40
+ - the `path/to/client_secret.json` path is the file downloaded from Google console (it will be overrided with the fresh token).
41
+ - the `application_name` param is the name that you set for the application credentials on Google console.
42
+
43
+ 6. The Rake task will give you an auth url. Simply go to that url (while signed in as the designated uploads owner), authorize the app, then enter code from url in the console. The rake task will override valid `client_secret.json` which you can use to connect with GoogleDrive from now on.
44
+
45
+ 7. Create a folder in which the files will be uploaded; note the folder's ID.
46
+
47
+ ## Usage
48
+
49
+ ```rb
50
+ require "shrine/storage/google_drive_storage"
51
+
52
+ Shrine.storages = {
53
+ cache: Shrine::Storage::GoogleDriveStorage.new(prefix: "cache"),
54
+ store: Shrine::Storage::GoogleDriveStorage.new(prefix: "store"),
55
+ }
56
+ ```
57
+
58
+ ## Configuration
59
+
60
+ ```rb
61
+ Shrine::Storage::GoogleDriveStorage.new(
62
+ prefix: "store",
63
+ google_drive_client_secret_path: "#{Rails.root}/config/client_secret.json",
64
+ google_drive_options: {
65
+ path: proc { |style| "#{id}_#{photo.original_filename}_#{style}" },
66
+ public_folder_id: 'AAAARRRRGGGBBBFFFFadsasdX'
67
+ },
68
+ )
69
+ ```
70
+
71
+ The `:google_drive_client_secret_path` option
72
+
73
+ This is the path of the file downloaded from your Google Drive app settings by the authorization Rake task.
74
+
75
+ Example of the overridden `path/to/client_secret.json` file:
76
+ ```json
77
+ {
78
+ "client_id": "4444-1111.apps.googleusercontent.com",
79
+ "client_secret": "1yErh1pR_7asdf8tqdYM2LcuL",
80
+ "scope": "https://www.googleapis.com/auth/drive",
81
+ "refresh_token": "1/_sVZIgY5thPetbWDTTTasdDID5Rkvq6UEfYshaDs5dIKoUAKgjE9f"
82
+ }
83
+ ```
84
+ It is good practice to not include the credentials directly in the JSON file. Instead you can set them in environment variables and embed them with ERB.
85
+
86
+ ## Options
87
+
88
+ The `:google_drive_options` option
89
+
90
+ This is a hash containing any of the following options:
91
+ - `:path` – block
92
+ - `:public_folder_id`- id of folder that must be created in google drive and set public permissions on it
93
+ - `:default_image` - an image in Public folder that used for attachments if attachment is not present
94
+ - `:application_name` - is the name that you set for the application credentials on Google console.
95
+
96
+ The :path option should be a block which returns a path that the uploaded file should be saved to. The block yields the attachment style and is executed in the scope of the model instance.
97
+
98
+ ## Contributing
99
+
100
+ Bug reports and pull requests are welcome on GitHub at https://github.com/verynear/shrine-google_drive_storage. This project is intended to be a safe, welcoming space for collaboration, and contributors are expected to adhere to the [Contributor Covenant](http://contributor-covenant.org) code of conduct.
101
+
102
+ ## License
103
+
104
+ The gem is available as open source under the terms of the [MIT License](http://opensource.org/licenses/MIT).
105
+
106
+ ## Code of Conduct
107
+
108
+ Everyone interacting in the Shrine::GoogleDriveStorage project’s codebases, issue trackers, chat rooms and mailing lists is expected to follow the [code of conduct](https://github.com/verynear/shrine-google_drive_storage/blob/master/CODE_OF_CONDUCT.md).
data/Rakefile ADDED
@@ -0,0 +1,6 @@
1
+ #!/usr/bin/env rake
2
+ require "bundler/gem_tasks"
3
+
4
+ Bundler.setup
5
+
6
+ load "shrine/google_drive/tasks.rake"
data/bin/console ADDED
@@ -0,0 +1,14 @@
1
+ #!/usr/bin/env ruby
2
+
3
+ require "bundler/setup"
4
+ require "alegra"
5
+
6
+ # You can add fixtures and/or initialization code here to make experimenting
7
+ # with your gem easier. You can also use a different console, if you like.
8
+
9
+ # (If you use this, don't forget to add pry to your Gemfile!)
10
+ # require "pry"
11
+ # Pry.start
12
+
13
+ require "irb"
14
+ IRB.start
data/bin/setup ADDED
@@ -0,0 +1,8 @@
1
+ #!/usr/bin/env bash
2
+ set -euo pipefail
3
+ IFS=$'\n\t'
4
+ set -vx
5
+
6
+ bundle install
7
+
8
+ # Do any other automated setup that you need to do here
@@ -0,0 +1,44 @@
1
+ # Author: Mateusz Czerwinski <mtczerwinski@gmail.com>
2
+ # The license of this source is "New BSD Licence"
3
+ require 'json'
4
+ require 'googleauth'
5
+ require 'fileutils'
6
+
7
+ module Shrine
8
+ module GoogleDrive
9
+ # @api private
10
+ class Config
11
+ FIELDS = %w(client_id client_secret scope refresh_token).freeze
12
+ attr_accessor(*FIELDS)
13
+
14
+ def initialize(config_path)
15
+ @config_path = config_path
16
+ if ::File.exist?(config_path)
17
+ JSON.parse(::File.read(config_path)).each do |key, value|
18
+ instance_variable_set("@#{key}", value) if FIELDS.include?(key)
19
+ end
20
+ if !client_id
21
+ auth_client = Google::Auth::ClientId.from_file(config_path)
22
+ @client_id = auth_client.id
23
+ @client_secret = auth_client.secret
24
+ end
25
+ end
26
+ end
27
+
28
+ def save
29
+ ::File.open(@config_path, 'w', 0600) { |f| f.write(to_json) }
30
+ end
31
+
32
+ private
33
+
34
+ def to_json
35
+ hash = {}
36
+ FIELDS.each do |field|
37
+ value = __send__(field)
38
+ hash[field] = value if value
39
+ end
40
+ JSON.pretty_generate(hash)
41
+ end
42
+ end
43
+ end
44
+ end
@@ -0,0 +1,10 @@
1
+ require 'active_support/core_ext/module'
2
+ module Shrine
3
+ module GoogleDrive
4
+ class Railtie < Rails::Railtie
5
+ rake_tasks do
6
+ load "shrine/google_drive/tasks.rake"
7
+ end
8
+ end
9
+ end
10
+ end
@@ -0,0 +1,38 @@
1
+ require 'google/apis/drive_v3'
2
+ require 'googleauth'
3
+ require 'shrine/google_drive/session'
4
+
5
+ module Shrine
6
+ module GoogleDrive
7
+ module Rake
8
+ extend self
9
+ ##
10
+ # Ensure valid credentials, either by restoring from the saved credentials
11
+ # files or intitiating an OAuth2 authorization. If authorization is required,
12
+ # the user's default browser will be launched to approve the request.
13
+ #
14
+ # @param client_secret_path [ String ] with the location of the JSON file downloaded from Google console
15
+ # @param application_name [ String ] given in the Google console > credentials > OAuth 2.0 client IDs section
16
+ # @return [Google::Auth::UserRefreshCredentials] OAuth2 credentials
17
+ def authorize(client_secret_path, application_name)
18
+ client = Shrine::GoogleDrive::Session.from_config(client_secret_path, application_name: application_name)
19
+ # # List the 10 most recently modified files.
20
+ # response = client.list_files(page_size: 10, fields: 'nextPageToken, files(id, name)')
21
+ # puts 'Files:'
22
+ # puts 'No files found' if response.files.empty?
23
+ # response.files.each do |file|
24
+ # puts "#{file.name} (#{file.id})"
25
+ # end
26
+ if client
27
+ puts "\nAuthorization completed.\n\n"
28
+ puts "The credentials were saved into #{ client_secret_path}.\n"
29
+ puts "You can use these credentials as follows: \n"
30
+ puts "Shrine::GoogleDrive::Session.from_config(#{client_secret_path}, application_name: #{application_name})"
31
+ puts "\n"
32
+ else
33
+ raise 'There where something wrong in the initialization of the google client (Google::Apis::DriveV3::DriveService)'
34
+ end
35
+ end
36
+ end
37
+ end
38
+ end
@@ -0,0 +1,108 @@
1
+ # Author: Hiroshi Ichikawa <http://gimite.net/>
2
+ # The license of this source is "New BSD Licence"
3
+ require 'google/apis/drive_v3'
4
+ require 'googleauth'
5
+ require 'shrine/google_drive/config'
6
+ require 'fileutils'
7
+
8
+ module Shrine
9
+ module GoogleDrive
10
+ # A session for Google Drive operations.
11
+ #
12
+ # Use from_credentials, from_access_token, from_service_account_key or from_config
13
+ # class method to construct a Shrine::GoogleDrive::Session object.
14
+ class Session
15
+
16
+ DEFAULT_SCOPE = Google::Apis::DriveV3::AUTH_DRIVE
17
+
18
+ # Returns Google::Apis::DriveV3::DriveService constructed from a config JSON file at +config+.
19
+ #
20
+ # +config+ is the path to the config file.
21
+ #
22
+ # This will prompt the credential via command line for the first time and save it to
23
+ # +config+ for later usages.
24
+ #
25
+ # See https://github.com/gimite/google-drive-ruby/blob/master/doc/authorization.md for a usage example.
26
+ #
27
+ # You can also provide a config object that must respond to:
28
+ # client_id
29
+ # client_secret
30
+ # refesh_token
31
+ # refresh_token=
32
+ # scope
33
+ # scope=
34
+ # save
35
+ class << self
36
+ def from_config(config_path, options = {})
37
+ validate_options(options)
38
+ config = get_cofiguration(config_path, options)
39
+ credentials = Google::Auth::UserRefreshCredentials.new(
40
+ client_id: config.client_id,
41
+ client_secret: config.client_secret,
42
+ scope: config.scope,
43
+ redirect_uri: 'urn:ietf:wg:oauth:2.0:oob'
44
+ )
45
+ if config.refresh_token
46
+ credentials.refresh_token = config.refresh_token
47
+ credentials.fetch_access_token!
48
+ else
49
+ $stderr.print("\n1. Open this page:\n%s\n\n" % credentials.authorization_uri)
50
+ $stderr.print('2. Enter the authorization code shown in the page: ')
51
+ credentials.code = $stdin.gets.chomp
52
+ credentials.fetch_access_token!
53
+ config.refresh_token = credentials.refresh_token
54
+ end
55
+ config.save
56
+ init_drive_service(options[:application_name], credentials)
57
+ end
58
+
59
+ # @param config_path [ String ]
60
+ # @param options [ Hash ]
61
+ # @return [ Shrine::GoogleDrive::Config ]
62
+ def get_cofiguration(config_path, options)
63
+ if config_path.is_a?(String)
64
+ config = Shrine::GoogleDrive::Config.new(config_path)
65
+ else
66
+ raise(ArgumentError, 'You must set a valid config_path path')
67
+ end
68
+ config.scope ||= DEFAULT_SCOPE
69
+ config_from_options(config, options)
70
+ end
71
+
72
+ # @param options [ Hash ]
73
+ # @param config [ Shrine::GoogleDrive::Config ]
74
+ # @return [ Shrine::GoogleDrive::Config ]
75
+ def config_from_options(config, options)
76
+ if options[:client_id] && options[:client_secret]
77
+ config.client_id = options[:client_id]
78
+ config.client_secret = options[:client_secret]
79
+ end
80
+ config
81
+ end
82
+
83
+ # @param options [ Hash ]
84
+ def validate_options(options)
85
+ raise(ArgumentError, 'You must specify the application_name option') unless options[:application_name]
86
+ raise(ArgumentError, 'client_id and client_secret must be both specified or both omitted') if invalid_client_options?(options)
87
+ end
88
+
89
+ # @param options [ Hash ]
90
+ # @return [ Boolean ]
91
+ def invalid_client_options?(options)
92
+ (options[:client_id] && !options[:client_secret]) || (!options[:client_id] && options[:client_secret])
93
+ end
94
+
95
+ # @param application_name [ String ]
96
+ # @param credentials [ Google::Auth::UserRefreshCredentials ]
97
+ # @return [ Google::Apis::DriveV3::DriveService ]
98
+ def init_drive_service(application_name, credentials)
99
+ # Initialize the API
100
+ client = Google::Apis::DriveV3::DriveService.new
101
+ client.client_options.application_name = application_name
102
+ client.authorization = credentials
103
+ client
104
+ end
105
+ end
106
+ end
107
+ end
108
+ end
@@ -0,0 +1,10 @@
1
+ require "shrine/google_drive/rake"
2
+
3
+ namespace :google_drive do
4
+ desc "Authorize Google Drive account: "
5
+ task :authorize, [:client_secret_path, :application_name] do |_t, args|
6
+ client_secret_path = args[:client_secret_path]
7
+ application_name = args[:application_name]
8
+ Shrine::GoogleDrive::Rake.authorize(client_secret_path, application_name)
9
+ end
10
+ end
@@ -0,0 +1,2 @@
1
+ require "shrine/storage/google_drive_storage"
2
+ require "shrine/google_drive/railtie" if defined?(Rails)
@@ -0,0 +1,298 @@
1
+ require 'active_support/core_ext/hash/keys'
2
+ require 'active_support/inflector/methods'
3
+ require 'active_support/core_ext/object/blank'
4
+ require 'yaml'
5
+ require 'erb'
6
+
7
+ require 'shrine'
8
+ require 'google/apis/drive_v3'
9
+ require 'googleauth'
10
+ require 'shrine/google_drive/session'
11
+
12
+ require 'fileutils'
13
+
14
+ class Shrine
15
+ module Storage
16
+ class GoogleDriveStorage
17
+ attr_reader :prefix
18
+
19
+ def extended(base)
20
+ check_gem_is_installed
21
+ base.instance_eval do
22
+ @google_drive_client_secret_path = @options[:google_drive_client_secret_path]
23
+ @google_drive_options = @options[:google_drive_options] || { application_name: 'test-app' }
24
+ raise(ArgumentError, 'You must provide a valid google_drive_client_secret_path option') unless @google_drive_client_secret_path
25
+ raise(ArgumentError, 'You must set the public_folder_id option') unless @google_drive_options[:public_folder_id]
26
+ google_api_client # Force validations of credentials
27
+ end
28
+ end
29
+
30
+ def check_gem_is_installed
31
+ begin
32
+ require 'google-api-client'
33
+ rescue LoadError => e
34
+ e.message << '(You may need to install the google-api-client gem)'
35
+ raise e
36
+ end unless defined?(Google)
37
+ end
38
+
39
+
40
+ def initialize(prefix: nil, google_drive_options: {})
41
+ @prefix = prefix
42
+ @google_drive_client_secret_path = @options[:google_drive_client_secret_path]
43
+ @google_drive_options = @options[:google_drive_options]
44
+ end
45
+
46
+ def upload(io, id, shrine_metadata: {}, **_options)
47
+ # uploads `io` to the location `id`
48
+
49
+ @queued_for_write.each do |style, file|
50
+ raise FileExists, "file \"#{path(style)}\" already exists in your Google Drive" if exists?(path(style))
51
+
52
+ name, mime_type = filename_from(style), "#{ file.content_type }"
53
+
54
+ file_metadata = {
55
+ name: name,
56
+ description: 'shrine file on google drive',
57
+ mimeType: mime_type,
58
+ parents: [find_public_folder]
59
+ }
60
+
61
+ google_api_client.create_file(
62
+ file_metadata,
63
+ fields: 'id',
64
+ upload_source: file.binmode,
65
+ content_type: file.content_type,
66
+ )
67
+ end
68
+ after_upload
69
+ @queued_for_write = {}
70
+ end
71
+
72
+ def google_api_client
73
+ @google_api_client ||= begin
74
+ # Initialize the client & Google+ API
75
+ ::Shrine::GoogleDrive::Session.from_config(
76
+ @google_drive_client_secret_path,
77
+ application_name: @google_drive_options[:application_name]
78
+ )
79
+ end
80
+ end
81
+
82
+ alias_method :google_drive, :google_api_client
83
+
84
+ def url(id, **_options)
85
+ # URL to the remote file, accepts options for customizing the URL
86
+ if present?
87
+ style = args.first.is_a?(Symbol) ? args.first : default_style
88
+ options = args.last.is_a?(Hash) ? args.last : {}
89
+ if style == :custom_thumb && is_valid_for_custom_thumb?
90
+ custom_width = options[:width] || 220
91
+ file_name = filename_from(default_style)
92
+ public_url_custom_thumbnail_from(file_name, custom_width)
93
+ else
94
+ file_name = filename_from(style)
95
+ public_url_for(file_name)
96
+ end
97
+ else
98
+ default_image
99
+ end
100
+ end
101
+
102
+ def is_valid_for_custom_thumb?
103
+ content_type =~ /image/ || content_type =~ /pdf/
104
+ end
105
+
106
+ # def download(id)
107
+ # tempfile = Tempfile.new(["googlestorage", File.extname(id)], binmode: true)
108
+ # storage_api.get_object(@bucket, object_name(id), download_dest: tempfile)
109
+ # tempfile.tap(&:open)
110
+ # end
111
+
112
+ def open(id)
113
+ # returns the remote file as an IO-like object
114
+ if file_id.is_a? String
115
+ client = google_api_client
116
+ metadata = client.get_file(
117
+ file_id,
118
+ fields: 'id, name, thumbnailLink, webContentLink, webViewLink, trashed'
119
+ )
120
+ validate_metadata(metadata)
121
+ metadata
122
+ end
123
+ end
124
+
125
+ # Raises an error in case that the Google Drive API does not response
126
+ # with the minimum required information.
127
+ # @params [ Google::Apis::DriveV3::File ]
128
+ def validate_metadata(metadata)
129
+ raise 'the file id was not retrieved' if metadata.id.nil?
130
+ raise 'the file name was not retrieved' if metadata.name.nil?
131
+ raise 'the file web_content_link was not retrieved' if metadata.web_content_link.nil?
132
+ raise 'the file web_view_link was not retrieved' if metadata.web_view_link.nil?
133
+ raise 'the file trashed was not retrieved' if metadata.trashed.nil?
134
+ end
135
+
136
+ def exists?(id)
137
+ # checks if the file exists on the storage
138
+ return false if not present?
139
+ result_id = search_for_title(path(style))
140
+ if result_id.nil?
141
+ false
142
+ else
143
+ data = metadata_by_id(result_id)
144
+ !data.trashed # if trashed -> not exists
145
+ end
146
+ end
147
+
148
+ # Gets the file metadata if it exists
149
+ # in other case returns the defaul image
150
+ # @param title [ String ]
151
+ # @param block [ Proc ]
152
+ def metadata_or_default_img_from(title, &block)
153
+ searched_id = search_for_title(title) #return id if any or style
154
+ if searched_id.nil? # it finds some file
155
+ default_image
156
+ else
157
+ metadata = metadata_by_id(searched_id)
158
+ yield metadata
159
+ end
160
+ end
161
+
162
+ def default_image
163
+ if @google_drive_options[:default_url] #if default image is set
164
+ title = @google_drive_options[:default_url]
165
+ searched_id = search_for_title(title) # id
166
+ if searched_id.nil?
167
+ raise 'Default image not found, please double check its name'
168
+ else
169
+ metadata = metadata_by_id(searched_id)
170
+ effective_url_from(metadata.web_content_link)
171
+ end
172
+ else
173
+ 'No picture' # ---- ?
174
+ end
175
+ end
176
+
177
+ def find_public_folder
178
+ if @google_drive_options[:public_folder_id].is_a? Proc
179
+ instance.instance_exec(&@google_drive_options[:public_folder_id])
180
+ else
181
+ @google_drive_options[:public_folder_id]
182
+ end
183
+ end
184
+
185
+ def delete(id)
186
+ # deletes the file from the storage
187
+ @queued_for_delete.each do |path|
188
+ Shrine.log("Delete: #{ path }")
189
+ file_id = search_for_title(path)
190
+ google_api_client.delete_file(file_id) unless file_id.nil?
191
+ end
192
+ @queued_for_delete = []
193
+ end
194
+
195
+ def filename_from(style)
196
+ file_name = instance.instance_exec(style, &file_title)
197
+ style_suffix = (style != default_style ? "_#{style}" : "")
198
+ if original_extension.present? && file_name =~ /#{original_extension}$/
199
+ file_name.sub(original_extension, "#{style_suffix}#{original_extension}")
200
+ else
201
+ file_name + style_suffix + original_extension.to_s
202
+ end
203
+ end
204
+
205
+ alias_method :path, :filename_from
206
+
207
+ # Gets the public url for a passed filename
208
+ # @param title [ String ]
209
+ # @return [ String ] with url
210
+ def public_url_for(title)
211
+ metadata_or_default_img_from(title) do |metadata|
212
+ # effective_url_from(metadata.web_content_link)
213
+ if content_type =~ /image/
214
+ custom_thumbnail_image_for(metadata.thumbnail_link, 1000)
215
+ else
216
+ metadata.web_view_link
217
+ end
218
+ end
219
+ end
220
+
221
+ # Gets the public url for a passed filename
222
+ # @param title [ String ]
223
+ # @param custom_width [ Integer ]
224
+ # @return [ String ] with url
225
+ def public_url_custom_thumbnail_from(title, custom_width)
226
+ metadata_or_default_img_from(title) do |metadata|
227
+ custom_thumbnail_image_for(metadata.thumbnail_link, custom_width)
228
+ end
229
+ end
230
+
231
+ # Retrieves the specific image with a custom size. It is resized by GDrive API if you
232
+ # pass the :custom_thumb as style option. In other cases, it removes the last parameter
233
+ # `=s220` which is inchaged to do the scaling process.
234
+ # @param drive_thumbnail_link [ String ] with the form: https://<url value>=s220
235
+ # @param custom_width [ Integer ] ex. 512
236
+ # @return [ String ]
237
+ def custom_thumbnail_image_for(drive_thumbnail_link, custom_width)
238
+ file_url, current_width = drive_thumbnail_link.split(/=s/)
239
+ "#{ file_url }=s#{ custom_width }"
240
+ end
241
+
242
+ # TOO SLOW and PERMISSIONS ISSUES
243
+ # Seems that the retrieved file url is only visible for the
244
+ # user which is owner and is currently log in GDrive.
245
+ #
246
+ # Gets the effective url from the web content link
247
+ # These are a series of steps to hack the way that GDrive API
248
+ # handle its urls. It consists in catch a Google::Apis::RedirectError error
249
+ # and take the correct url where is located the file.
250
+ # @param driver_web_content_link [ String ]
251
+ # @return [ String ]
252
+ def effective_url_from(drive_web_content_link)
253
+ redirect_url = drive_web_content_link.split(/&export=/)[0]
254
+ google_drive.http(:get, redirect_url) do |result, err|
255
+ err.header[:location].split('&continue=')[1]
256
+ end
257
+ end
258
+
259
+ # Takes the file title/name and search it in a given folder
260
+ # If it finds a file, return id of a file or nil
261
+ # @param name [ String ]
262
+ # @return [ String ] or NilClass
263
+ def search_for_title(name)
264
+ raise 'You are trying to search a file with NO name' if name.nil? || name.empty?
265
+ client = google_api_client
266
+ result = client.list_files(page_size: 1,
267
+ q: "name contains '#{ name }' and '#{ find_public_folder }' in parents",
268
+ fields: 'files(id, name)'
269
+ )
270
+ if result.files.length > 0
271
+ result.files[0].id
272
+ else
273
+ nil
274
+ end
275
+ end
276
+
277
+ #
278
+ # Error classes
279
+ #
280
+
281
+ class FileExists < ArgumentError
282
+ end
283
+
284
+ private
285
+
286
+ def file_title
287
+ return @google_drive_options[:path] if @google_drive_options[:path] #path: proc
288
+ eval %(proc { |style| "\#{id}_\#{#{name}.original_filename}"})
289
+ end
290
+
291
+ # @return [String] with the extension of file
292
+ def original_extension
293
+ File.extname(original_filename)
294
+ end
295
+
296
+ end
297
+ end
298
+ end
@@ -0,0 +1,5 @@
1
+ module Shrine
2
+ module GoogleDriveStorage
3
+ VERSION = "0.1.0"
4
+ end
5
+ end
@@ -0,0 +1,4 @@
1
+ require 'active_support/core_ext/module'
2
+ require 'shrine'
3
+ require 'shrine/google_drive' if defined?(Rails)
4
+ require 'shrine/storage/google_drive_storage'
@@ -0,0 +1,43 @@
1
+ # coding: utf-8
2
+ lib = File.expand_path("../lib", __FILE__)
3
+ $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
4
+ require "shrine/version"
5
+
6
+ Gem::Specification.new do |spec|
7
+ spec.name = "shrine-google_drive_storage"
8
+ spec.version = Shrine::GoogleDriveStorage::VERSION
9
+ spec.authors = ["Scott Near"]
10
+ spec.email = ["scott.a.near@gmail.com"]
11
+
12
+ spec.summary = "Provides Google Cloud Storage storage for Shrine."
13
+ spec.description =
14
+ spec.homepage = "https://github.com/verynear/shrine-google_drive_storage"
15
+ spec.license = "MIT"
16
+
17
+ # Prevent pushing this gem to RubyGems.org. To allow pushes either set the 'allowed_push_host'
18
+ # to allow pushing to a single host or delete this section to allow pushing to any host.
19
+ # if spec.respond_to?(:metadata)
20
+ # spec.metadata["allowed_push_host"] = "TODO: Set to 'http://mygemserver.com'"
21
+ # else
22
+ # raise "RubyGems 2.0 or newer is required to protect against " \
23
+ # "public gem pushes."
24
+ # end
25
+
26
+ spec.executables = `git ls-files -- bin/*`.split("\n").map{ |f| File.basename(f) }
27
+
28
+ spec.files = `git ls-files -z`.split("\x0").reject do |f|
29
+ f.match(%r{^(test|spec|features)/})
30
+ end
31
+
32
+ spec.require_paths = ["lib"]
33
+
34
+ spec.add_dependency 'shrine', '~> 2.6', '>= 2.6.1'
35
+ spec.add_dependency 'google-api-client', '~> 0.13.0'
36
+
37
+ spec.add_development_dependency "bundler", "~> 1.15"
38
+ spec.add_development_dependency "rake", "~> 10.0"
39
+ spec.add_development_dependency "rspec"
40
+ spec.add_development_dependency "dotenv"
41
+ spec.add_development_dependency "activerecord", "~> 4.2", ">= 4.2.0"
42
+ spec.add_development_dependency "railties", "~> 4.2", ">= 4.2.0"
43
+ end
metadata ADDED
@@ -0,0 +1,195 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: shrine-google_drive_storage
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.1.0
5
+ platform: ruby
6
+ authors:
7
+ - Scott Near
8
+ autorequire:
9
+ bindir: bin
10
+ cert_chain: []
11
+ date: 2017-06-27 00:00:00.000000000 Z
12
+ dependencies:
13
+ - !ruby/object:Gem::Dependency
14
+ name: shrine
15
+ requirement: !ruby/object:Gem::Requirement
16
+ requirements:
17
+ - - "~>"
18
+ - !ruby/object:Gem::Version
19
+ version: '2.6'
20
+ - - ">="
21
+ - !ruby/object:Gem::Version
22
+ version: 2.6.1
23
+ type: :runtime
24
+ prerelease: false
25
+ version_requirements: !ruby/object:Gem::Requirement
26
+ requirements:
27
+ - - "~>"
28
+ - !ruby/object:Gem::Version
29
+ version: '2.6'
30
+ - - ">="
31
+ - !ruby/object:Gem::Version
32
+ version: 2.6.1
33
+ - !ruby/object:Gem::Dependency
34
+ name: google-api-client
35
+ requirement: !ruby/object:Gem::Requirement
36
+ requirements:
37
+ - - "~>"
38
+ - !ruby/object:Gem::Version
39
+ version: 0.13.0
40
+ type: :runtime
41
+ prerelease: false
42
+ version_requirements: !ruby/object:Gem::Requirement
43
+ requirements:
44
+ - - "~>"
45
+ - !ruby/object:Gem::Version
46
+ version: 0.13.0
47
+ - !ruby/object:Gem::Dependency
48
+ name: bundler
49
+ requirement: !ruby/object:Gem::Requirement
50
+ requirements:
51
+ - - "~>"
52
+ - !ruby/object:Gem::Version
53
+ version: '1.15'
54
+ type: :development
55
+ prerelease: false
56
+ version_requirements: !ruby/object:Gem::Requirement
57
+ requirements:
58
+ - - "~>"
59
+ - !ruby/object:Gem::Version
60
+ version: '1.15'
61
+ - !ruby/object:Gem::Dependency
62
+ name: rake
63
+ requirement: !ruby/object:Gem::Requirement
64
+ requirements:
65
+ - - "~>"
66
+ - !ruby/object:Gem::Version
67
+ version: '10.0'
68
+ type: :development
69
+ prerelease: false
70
+ version_requirements: !ruby/object:Gem::Requirement
71
+ requirements:
72
+ - - "~>"
73
+ - !ruby/object:Gem::Version
74
+ version: '10.0'
75
+ - !ruby/object:Gem::Dependency
76
+ name: rspec
77
+ requirement: !ruby/object:Gem::Requirement
78
+ requirements:
79
+ - - ">="
80
+ - !ruby/object:Gem::Version
81
+ version: '0'
82
+ type: :development
83
+ prerelease: false
84
+ version_requirements: !ruby/object:Gem::Requirement
85
+ requirements:
86
+ - - ">="
87
+ - !ruby/object:Gem::Version
88
+ version: '0'
89
+ - !ruby/object:Gem::Dependency
90
+ name: dotenv
91
+ requirement: !ruby/object:Gem::Requirement
92
+ requirements:
93
+ - - ">="
94
+ - !ruby/object:Gem::Version
95
+ version: '0'
96
+ type: :development
97
+ prerelease: false
98
+ version_requirements: !ruby/object:Gem::Requirement
99
+ requirements:
100
+ - - ">="
101
+ - !ruby/object:Gem::Version
102
+ version: '0'
103
+ - !ruby/object:Gem::Dependency
104
+ name: activerecord
105
+ requirement: !ruby/object:Gem::Requirement
106
+ requirements:
107
+ - - "~>"
108
+ - !ruby/object:Gem::Version
109
+ version: '4.2'
110
+ - - ">="
111
+ - !ruby/object:Gem::Version
112
+ version: 4.2.0
113
+ type: :development
114
+ prerelease: false
115
+ version_requirements: !ruby/object:Gem::Requirement
116
+ requirements:
117
+ - - "~>"
118
+ - !ruby/object:Gem::Version
119
+ version: '4.2'
120
+ - - ">="
121
+ - !ruby/object:Gem::Version
122
+ version: 4.2.0
123
+ - !ruby/object:Gem::Dependency
124
+ name: railties
125
+ requirement: !ruby/object:Gem::Requirement
126
+ requirements:
127
+ - - "~>"
128
+ - !ruby/object:Gem::Version
129
+ version: '4.2'
130
+ - - ">="
131
+ - !ruby/object:Gem::Version
132
+ version: 4.2.0
133
+ type: :development
134
+ prerelease: false
135
+ version_requirements: !ruby/object:Gem::Requirement
136
+ requirements:
137
+ - - "~>"
138
+ - !ruby/object:Gem::Version
139
+ version: '4.2'
140
+ - - ">="
141
+ - !ruby/object:Gem::Version
142
+ version: 4.2.0
143
+ description: https://github.com/verynear/shrine-google_drive_storage
144
+ email:
145
+ - scott.a.near@gmail.com
146
+ executables:
147
+ - console
148
+ - setup
149
+ extensions: []
150
+ extra_rdoc_files: []
151
+ files:
152
+ - ".gitignore"
153
+ - ".travis.yml"
154
+ - CODE_OF_CONDUCT.md
155
+ - Gemfile
156
+ - LICENSE.txt
157
+ - README.md
158
+ - Rakefile
159
+ - bin/console
160
+ - bin/setup
161
+ - lib/shrine-google-drive-storage.rb
162
+ - lib/shrine/google_drive.rb
163
+ - lib/shrine/google_drive/config.rb
164
+ - lib/shrine/google_drive/railtie.rb
165
+ - lib/shrine/google_drive/rake.rb
166
+ - lib/shrine/google_drive/session.rb
167
+ - lib/shrine/google_drive/tasks.rake
168
+ - lib/shrine/storage/google_drive_storage.rb
169
+ - lib/shrine/version.rb
170
+ - shrine-google_drive_storage.gemspec
171
+ homepage: https://github.com/verynear/shrine-google_drive_storage
172
+ licenses:
173
+ - MIT
174
+ metadata: {}
175
+ post_install_message:
176
+ rdoc_options: []
177
+ require_paths:
178
+ - lib
179
+ required_ruby_version: !ruby/object:Gem::Requirement
180
+ requirements:
181
+ - - ">="
182
+ - !ruby/object:Gem::Version
183
+ version: '0'
184
+ required_rubygems_version: !ruby/object:Gem::Requirement
185
+ requirements:
186
+ - - ">="
187
+ - !ruby/object:Gem::Version
188
+ version: '0'
189
+ requirements: []
190
+ rubyforge_project:
191
+ rubygems_version: 2.6.10
192
+ signing_key:
193
+ specification_version: 4
194
+ summary: Provides Google Cloud Storage storage for Shrine.
195
+ test_files: []