googol 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.
checksums.yaml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA1:
3
+ metadata.gz: 6945690068a1360419e43033caf75ed53ee0d231
4
+ data.tar.gz: 20ad10bdfe492d8bdbbc356c5c2b4d5758b83c07
5
+ SHA512:
6
+ metadata.gz: 4e674a9f13fa33db3184969ba36b02df88230165fdef7a67679a2622d6a8fc2dd919edd28f16c2fc7f9cef6f0a8f06d7cb56db58828d6a3020c26cb0292ab241
7
+ data.tar.gz: 4e73ed288bb6b2fe9ea416cbad761c82fac7e58816b18b3257bc4c18d153390276612606fc886c54f395be40b0a193784580cdbfd23376be95b6e056f74856af
data/MIT-LICENSE ADDED
@@ -0,0 +1,20 @@
1
+ Copyright 2014 Fullscreen, Inc.
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,234 @@
1
+ Googol
2
+ ======
3
+
4
+ Googol lets you interact with many resources provided by Google API V3.
5
+
6
+ [![Gem Version](https://badge.fury.io/rb/googol.svg)](http://badge.fury.io/rb/googol)
7
+ [![Dependency Status](https://gemnasium.com/fullscreeninc/googol.png)](https://gemnasium.com/fullscreeninc/googol)
8
+ [![Build Status](https://travis-ci.org/fullscreeninc/googol.png?branch=master)](https://travis-ci.org/fullscreeninc/googol)
9
+ [![Coverage Status](https://coveralls.io/repos/fullscreeninc/googol/badge.png)](https://coveralls.io/r/fullscreeninc/googol)
10
+ [![Code Climate](https://codeclimate.com/github/fullscreeninc/googol.png)](https://codeclimate.com/github/fullscreeninc/googol)
11
+
12
+
13
+ ```ruby
14
+ channel = Googol::YoutubeResource.new url: 'youtube.com/remhq'
15
+ channel.id #=> 'UC7eaRqtonpyiYw0Pns0Au_g'
16
+ channel.title #=> "remhq"
17
+ channel.description #=> "R.E.M.'s Official YouTube Channel"
18
+ ```
19
+
20
+ ```ruby
21
+ video = Googol::YoutubeResource.new url: 'youtu.be/Kd5M17e7Wek'
22
+ video.id #=> 'Kd5M17e7Wek'
23
+ video.title #=> "R.E.M. - Tongue (Video)"
24
+ video.description #=> "© 2006 WMG\nTongue (Video)"
25
+ ```
26
+
27
+ ```ruby
28
+ account = Googol::GoogleAccount.new auth_params
29
+ account.email #=> 'user@google.com'
30
+ ```
31
+
32
+ ```ruby
33
+ account = Googol::YoutubeAccount.new auth_params
34
+ account.perform! :like, :video, 'Kd5M17e7Wek' # => adds 'Tongue' to your 'Liked videos'
35
+ account.perform! :subscribe_to, :channel, 'UC7eaRqtonpyiYw0Pns0Au_g' # => subscribes to R.E.M.’s channel
36
+ ```
37
+
38
+ The full documentation is available at [rubydoc.info](http://rubydoc.info/github/fullscreeninc/googol/master/frames).
39
+
40
+ Available classes
41
+ =================
42
+
43
+ Googol exposes three different resources provided by Google API V3:
44
+ Google Accounts, Youtube Accounts and Youtube Resources.
45
+
46
+ Google accounts
47
+ ---------------
48
+
49
+ Use `Googol::GoogleAccount` to send and retrieve data to Google,
50
+ impersonating an existing Google account.
51
+
52
+ Available instance methods are `id`, `email`, `verified_email`, `name`,
53
+ `given_name`, `family_name`, `link`, `picture`, `gender`, `locale`, and `hd`.
54
+
55
+ These methods require user authentication (see below).
56
+
57
+ Youtube accounts
58
+ ----------------
59
+
60
+ Use `Googol::YoutubeAccount` to send and retrieve data to Youtube,
61
+ impersonating an existing Youtube account.
62
+
63
+ Available instance methods are `id`, `title`, `description`, and `thumbnail_url`.
64
+
65
+ Additionally, the `perform!` method lets you executes promotional actions as
66
+ a Youtube account, such as liking a video or subscribing to a channel.
67
+
68
+ These methods require user authentication (see below).
69
+
70
+ Youtube resources
71
+ -----------------
72
+
73
+ Use `Googol::YoutubeResource` to retrieve read-only information about
74
+ public Youtube channels and videos.
75
+
76
+ Available instance methods are `id`, `title`, `description`, and `thumbnail_url`.
77
+
78
+ These methods require do not require user authentication.
79
+
80
+ Authentication
81
+ ==============
82
+
83
+ In order to use Googol you must register your app in the [Google Developers Console](https://console.developers.google.com):
84
+
85
+ 1. Create a new app and enable access to Google+ API and YouTube Data API V3
86
+ 1. Generate a new OAuth client ID (web application) and write down the `client ID` and `client secret`
87
+ 1. Generate a new Public API access key (for server application) and write down the `server key`
88
+
89
+ Run the following command to make these tokens available to Googol:
90
+
91
+ ```ruby
92
+ require 'googol'
93
+ Googol::ClientTokens.client_id = '…'
94
+ Googol::ClientTokens.client_secret = '…'
95
+ Googol::ServerTokens.server_key = '…'
96
+ ```
97
+
98
+ replacing the ellipses with the values from the Google Developers Console.
99
+
100
+ For actions that impersonate a Google or Youtube account, you also need to
101
+ obtain authorization from the owner of the account you wish to impersonate:
102
+
103
+ 1. In your web site, add a link to the Google's OAuth login page. The URL is:
104
+
105
+ ```ruby
106
+ Googol::GoogleAccount.oauth_url(redirect_url) # to impersonate a Google Account
107
+ Googol::YoutubeAccount.oauth_url(redirect_url) # to impersonate a Youtube Account
108
+ ```
109
+
110
+ 1. Upon authorization, the user is redirected to the URL passed as an argument, with an extra 'code' query parameter which can be used to impersonate the account:
111
+
112
+ ```ruby
113
+ account = Googol::GoogleAccount.new(code: code, redirect_uri: url) # to impersonate a Google Account
114
+ account = Googol::YoutubeAccount.new(code: code, redirect_uri: url) # to impersonate a Youtube Account
115
+ ```
116
+
117
+ 1. To prevent the user from having to authorize the app every time, store the account’s refresh_token in your database:
118
+
119
+ ```ruby
120
+ refresh_token = account.credentials[:refresh_token] # Store to your DB
121
+ ```
122
+
123
+ 1. To impersonate an account that has already authorized your app, just use the refresh_token:
124
+
125
+ ```ruby
126
+ account = Googol::GoogleAccount.new(refresh_token: refresh_token) # to impersonate a Google Account
127
+ account = Googol::YoutubeAccount.new(refresh_token: refresh_token) # to impersonate a Youtube Account
128
+ ```
129
+
130
+ Remember to add every redirect URL that you plan to use in the Google Developers
131
+ Console, and to set a *Product name* in Consent screen (under API & Auth).
132
+
133
+ How to install
134
+ ==============
135
+
136
+ To install on your system, run
137
+
138
+ gem install googol
139
+
140
+ To use inside a bundled Ruby project, add this line to the Gemfile:
141
+
142
+ gem 'googol', '~> 0.1.0'
143
+
144
+ Since the gem follows [Semantic Versioning](http://semver.org),
145
+ indicating the full version in your Gemfile (~> *major*.*minor*.*patch*)
146
+ guarantees that your project won’t occur in any error when you `bundle update`
147
+ and a new version of Googol is released.
148
+
149
+ Remember that you need to set up a Google app and include its credentials
150
+ in order for the gem to work (see above). In a Rails project, for instance,
151
+ you can do so by writing the following code in `config/initializer/googol.rb`:
152
+
153
+ Googol::ClientTokens.client_id = '…'
154
+ Googol::ClientTokens.client_secret = '…'
155
+ Googol::ServerTokens.server_key = '…'
156
+
157
+ replacing the ellipses with your app values from the Google Developers Console.
158
+
159
+
160
+ Why you should use Googol…
161
+ --------------------------
162
+
163
+ … and not [youtube_it](https://github.com/kylejginavan/youtube_it)?
164
+ Because youtube_it does not support Google API V3 and the previous version
165
+ has already been deprecated by Google and will soon be dropped.
166
+
167
+ … and not [Google Api Client](https://github.com/google/google-api-ruby-client)?
168
+ Because Google Api Client is poorly coded, poorly documented and adds many
169
+ dependencies, bloating the size of your project.
170
+
171
+ … and not your own code? Because Googol is fully tested, well documented,
172
+ has few dependencies and helps you forget about the burden of dealing with
173
+ Google API!
174
+
175
+ How to test
176
+ ===========
177
+
178
+ To run the tests, you must give the test app permissions to access your
179
+ Google and Youtube accounts. They are free, so feel free to create a fake one.
180
+
181
+ 1. Run the following commands in a ruby session:
182
+
183
+ ```ruby
184
+ require 'googol'
185
+ Googol::GoogleAccount.oauth_url # => "https://accounts.google.com/o..."
186
+ ```
187
+
188
+ 1. Copy the last URL in a browser, and accept the terms. You will be redirected to a URL like http://example.com/?code=ABCDE
189
+
190
+ 1. Copy the `code` parameter (ABCDE in the example above) and run:
191
+
192
+ ```ruby
193
+ account = Googol::GoogleAccount.new code: 'ABCDE'
194
+ account.credentials[:refresh_token]
195
+ ```
196
+
197
+ 1. Copy the token returned by the last command (something like 1AUJZh2x1...) and store it in an environment variable before running the test suite:
198
+
199
+ ```ruby
200
+ export GOOGOL_TEST_GOOGLE_REFRESH_TOKEN="1AUJZh2x1..."
201
+ ```
202
+
203
+ 1. Repeat all the steps above replacing GoogleAccount with YoutubeAccount to authorize access to your Youtube account:
204
+
205
+ ```ruby
206
+ export GOOGOL_TEST_YOUTUBE_REFRESH_TOKEN="2B6T5x23..."
207
+ ```
208
+
209
+ 1. Finally run the tests running `rspec` or `rake`. If you prefer not to set environment variables, pass the refresh token in the same line:
210
+
211
+ ```ruby
212
+ GOOGOL_TEST_GOOGLE_REFRESH_TOKEN="1AUJZh2x1..." GOOGOL_TEST_YOUTUBE_REFRESH_TOKEN="2B6T5x23..." rspec
213
+ ```
214
+
215
+ How to contribute
216
+ =================
217
+
218
+ Before you submit a pull request, make sure all the tests are passing and the
219
+ code is fully test-covered.
220
+
221
+ To release an updated version of the gem to Rubygems, run:
222
+
223
+ rake release
224
+
225
+ Remember to *bump the version* before running the command, and to document
226
+ your changes in HISTORY.md and README.md if required.
227
+
228
+ The googol gem follows [Semantic Versioning](http://semver.org).
229
+ Any new release that is fully backward-compatible should bump the *patch* version (0.0.x).
230
+ Any new version that breaks compatibility should bump the *minor* version (0.x.0)
231
+
232
+
233
+ Don’t hesitate to send code comments, issues or pull requests through GitHub!
234
+ All feedback is appreciated. A [googol](http://en.wikipedia.org/wiki/Googol) of thanks! :)
data/lib/googol.rb ADDED
@@ -0,0 +1,3 @@
1
+ require 'googol/google_account'
2
+ require 'googol/youtube_account'
3
+ require 'googol/youtube_resource'
@@ -0,0 +1,96 @@
1
+ require 'uri'
2
+ require 'cgi'
3
+ require 'googol/client_tokens'
4
+ require 'googol/requestable'
5
+
6
+ module Googol
7
+ # Provides methods to authenticate as an account (either Google or Youtube).
8
+ module Authenticable
9
+ include ClientTokens
10
+ include Requestable
11
+
12
+ # Initialize an object with either an authorization code or a refresh token
13
+ #
14
+ # @see https://developers.google.com/accounts/docs/OAuth2
15
+ #
16
+ # @param [Hash] attrs Authentication credentials to access the account
17
+ # @option attrs [String] :code The OAuth2 authorization code
18
+ # @option attrs [String] :redirect_url The page to redirect after the OAuth2 page
19
+ # @option attrs [String] :refresh_token The refresh token for offline access
20
+ def initialize(attrs = {})
21
+ @code = attrs[:code]
22
+ @refresh_token = attrs[:refresh_token]
23
+ @redirect_url = attrs.fetch :redirect_url, 'http://example.com/'
24
+ end
25
+
26
+ # Return the authorization credentials of an account for this app.
27
+ #
28
+ # @see ...
29
+ #
30
+ # @return [Hash]
31
+ # * :client_id [String] ...
32
+ # * :client_secret [String] ...
33
+ # * ...
34
+ def credentials
35
+ @credentials ||= request! method: :post,
36
+ host: 'https://accounts.google.com',
37
+ path: '/o/oauth2/token',
38
+ body: credentials_params,
39
+ valid_if: -> response, body {response.code == '200'}
40
+ end
41
+
42
+ private
43
+
44
+ # Provides the credentials to access Google API as an authorized user.
45
+ #
46
+ # There are ways to do this:
47
+ # - For first-time users (who do not have a refresh token but only an
48
+ # authorization code): the code is submitted to Google to obtain an
49
+ # access token (to use immediately) and a refresh_token
50
+ # - For existing users (who have a refresh token): the refresh token is
51
+ # submitted to Google to obtain a new access token
52
+ def credentials_params
53
+ if @refresh_token
54
+ {grant_type: :refresh_token, refresh_token: @refresh_token}
55
+ else
56
+ {grant_type: :authorization_code, code: @code, redirect_uri: @redirect_url}
57
+ end.merge client_id: client_id, client_secret: client_secret
58
+ end
59
+
60
+ def self.included(base)
61
+ base.extend ClassMethods
62
+ end
63
+
64
+ module ClassMethods
65
+ include ClientTokens
66
+ # Returns the URL for users to authorize this app to access their account
67
+ #
68
+ # @param [String] redirect_url The page to redirect after the OAuth2 page
69
+ #
70
+ # @return [String] URL of the OAuth2 Authorization page.
71
+ #
72
+ # @note The redirect_url *must* match one of the redirect URLs whitelisted
73
+ # for the app in the Google Developers Console
74
+ #
75
+ # @see https://console.developers.google.com
76
+ def oauth_url(redirect_url = 'http://example.com/')
77
+ params = {
78
+ client_id: client_id,
79
+ scope: oauth_scopes.join(' '),
80
+ redirect_uri: redirect_url,
81
+ response_type: :code,
82
+ access_type: :offline,
83
+ approval_prompt: :force
84
+ }
85
+ q = params.map{|k,v| "#{CGI.escape k.to_s}=#{CGI.escape v.to_s}"}.join '&'
86
+ args = {host: 'accounts.google.com', path: '/o/oauth2/auth', query: q}
87
+ URI::HTTPS.build(args).to_s
88
+ end
89
+
90
+ # Set the scopes to grant access to an account.
91
+ # This method is meant to be overridden.
92
+ def oauth_scopes
93
+ end
94
+ end
95
+ end
96
+ end
@@ -0,0 +1,19 @@
1
+ module Googol
2
+ module ClientTokens
3
+ def client_id
4
+ @@client_id
5
+ end
6
+
7
+ def client_secret
8
+ @@client_secret
9
+ end
10
+
11
+ def self.client_id=(client_id)
12
+ @@client_id = client_id
13
+ end
14
+
15
+ def self.client_secret=(client_secret)
16
+ @@client_secret = client_secret
17
+ end
18
+ end
19
+ end
@@ -0,0 +1,74 @@
1
+ require 'googol/authenticable'
2
+
3
+ module Googol
4
+ # Provides read & write access to a Google (or Google+) account.
5
+ #
6
+ # @example Retrieve the email and given name of a Google account:
7
+ # * Set up two pages: one with a link to authenticate, one to redirect to
8
+ # * In the first page, add a link to the authentication page:
9
+ #
10
+ # Googol::GoogleAccount.oauth_url(redirect_url)
11
+ #
12
+ # * The user authenticates and lands on the second page, with an extra +code+ query parameter
13
+ # * Use the authorization code to initialize the GoogleAccount and retrieve information:
14
+ #
15
+ # account = Googol::GoogleAccount.new code: code, redirect_url: redirect_url
16
+ # account.email # => 'user@example.com'
17
+ # account.given_name # => 'Example user'
18
+ #
19
+ class GoogleAccount
20
+ include Authenticable
21
+ # Return the profile info of a Google account in OpenID Connect format.
22
+ #
23
+ # @see https://developers.google.com/+/api/latest/people/getOpenIdConnect
24
+ #
25
+ # @return [Hash]
26
+ # * :id [String] The ID of the authenticated account
27
+ # * :email [String] The account’s email address.
28
+ # * :verified_email [String] Boolean flag which is true if the email address is verified.
29
+ # * :name [String] The account’s full name.
30
+ # * :given_name [String] The account’s given (first) name.
31
+ # * :family_name [String] The account’s family (last) name.
32
+ # * :link [String] The URL of the account’s profile page.
33
+ # * :picture [String] The URL of the account’s profile picture.
34
+ # * :gender [String] The account’s gender
35
+ # * :locale [String] The account’s preferred locale.
36
+ # * :hd [String] The hosted domain name for the accounts’s Google Apps.
37
+ def info
38
+ @info ||= request! method: :get,
39
+ auth: credentials[:access_token],
40
+ host: 'https://www.googleapis.com',
41
+ path: '/oauth2/v2/userinfo',
42
+ valid_if: -> response, body {response.code == '200'}
43
+ end
44
+
45
+ # Define a method to return each attribute of the profile separately.
46
+ #
47
+ # @macro [attach] attribute.name
48
+ # @method $1()
49
+ # Return the $1 attribute of the Google Account.
50
+ #
51
+ def self.attribute(name)
52
+ define_method(name) { info[name] }
53
+ end
54
+
55
+ attribute :id
56
+ attribute :email
57
+ attribute :verified_email
58
+ attribute :name
59
+ attribute :given_name
60
+ attribute :family_name
61
+ attribute :link
62
+ attribute :picture
63
+ attribute :gender
64
+ attribute :locale
65
+ attribute :hd
66
+
67
+ # Set the scopes to grant access to Google user profile and email
68
+ #
69
+ # @see https://developers.google.com/+/api/oauth#profile
70
+ def self.oauth_scopes
71
+ %w(profile email)
72
+ end
73
+ end
74
+ end
@@ -0,0 +1,30 @@
1
+ module Googol
2
+ # Provides methods to read attributes for public objects (accounts, videos..)
3
+ module Readable
4
+
5
+ # Return the unique Youtube identifier of a Youtube object
6
+ def id
7
+ info[:id]
8
+ end
9
+
10
+ # Return the title of a Youtube object
11
+ def title
12
+ info[:snippet][:title]
13
+ end
14
+
15
+ # Return the description of a Youtube object
16
+ def description
17
+ info[:snippet][:description]
18
+ end
19
+
20
+ # Return the URL of the Youtube object thumbnail
21
+ def thumbnail_url
22
+ info[:snippet][:thumbnails][:default][:url]
23
+ end
24
+
25
+ # Return the kind of the Youtube object (either 'channel' or 'video')
26
+ def kind
27
+ info.fetch(:kind, '').split("#").last
28
+ end
29
+ end
30
+ end
@@ -0,0 +1,60 @@
1
+ require 'uri'
2
+ require 'json'
3
+
4
+ module Googol
5
+ # A custom class to rescue errors from interacting with Google V3 API
6
+ class RequestError < StandardError
7
+ end
8
+
9
+ # Provides methods to send HTTP requests to Google V3 API
10
+ module Requestable
11
+ ##
12
+ # Executes an HTTP request against the Google V3 API and returns the
13
+ # parsed result or raise an error in case of failure
14
+ #
15
+ # @note Not the best code quality, feel free to refactor!
16
+ #
17
+ def request!(params = {})
18
+ url = URI.parse params[:host]
19
+ http = Net::HTTP.new url.host, url.port
20
+ http.use_ssl = true
21
+ request = case params[:method]
22
+ when :get then Net::HTTP::Get.new params[:path]
23
+ when :post then
24
+ if params[:json]
25
+ Net::HTTP::Post.new params[:path], initheader = {'Content-Type' =>'application/json'}
26
+ else
27
+ Net::HTTP::Post.new params[:path]
28
+ end
29
+ end
30
+ if params[:json]
31
+ request.body = params[:body].to_json
32
+ else
33
+ request.set_form_data params[:body]
34
+ end if params[:body]
35
+
36
+ request['Authorization'] = 'Bearer ' + params[:auth] if params[:auth]
37
+ response = http.request(request)
38
+
39
+ body = JSON.parse response.body if response.body
40
+
41
+ if params[:valid_if] ? params[:valid_if].call(response, body) : true
42
+ body = params[:extract].call body if params[:extract]
43
+ body ? deep_symbolize_keys(body) : true
44
+ else
45
+ raise RequestError, body
46
+ end
47
+ end
48
+
49
+ private
50
+
51
+ def deep_symbolize_keys(hash)
52
+ {}.tap do |result|
53
+ hash.each do |k, v|
54
+ key = k.to_sym rescue k
55
+ result[key] = v.is_a?(Hash) ? deep_symbolize_keys(v) : v
56
+ end
57
+ end
58
+ end
59
+ end
60
+ end
@@ -0,0 +1,11 @@
1
+ module Googol
2
+ module ServerTokens
3
+ def server_key
4
+ @@server_key
5
+ end
6
+
7
+ def self.server_key=(server_key)
8
+ @@server_key = server_key
9
+ end
10
+ end
11
+ end
@@ -0,0 +1,3 @@
1
+ module Googol
2
+ VERSION = '0.1.1'
3
+ end
@@ -0,0 +1,78 @@
1
+ require 'googol/authenticable'
2
+ require 'googol/readable'
3
+
4
+ module Googol
5
+ # Provides read & write access to a Youtube account (also known as Channel).
6
+ #
7
+ # @example Like the video "Tongue" by R.E.M. as a specific Youtube account:
8
+ # * Set up two pages: one with a link to authenticate, one to redirect to
9
+ # * In the first page, add a link to the authentication page:
10
+ #
11
+ # Googol::YoutubeAccount.oauth_url(redirect_url)
12
+ #
13
+ # * The user authenticates and lands on the second page, with an extra +code+ query parameter
14
+ # * Use the authorization code to initialize the YoutubeAccount and like the video:
15
+ #
16
+ # account = Googol::YoutubeAccount.new code: code, redirect_url: redirect_url
17
+ # account.perform! :like, :video, 'Kd5M17e7Wek' # => likes the video
18
+ #
19
+ class YoutubeAccount
20
+ include Authenticable
21
+ include Readable
22
+ # Return the profile info of a Youtube account/channel.
23
+ #
24
+ # @see https://developers.google.com/youtube/v3/docs/channels#resource
25
+ #
26
+ # @return [Hash]
27
+ # * :id [String] The ID that YouTube uses to uniquely identify the channel.
28
+ # * :etag [String] The Etag of this resource.
29
+ # * :kind [String] The value will be youtube#channel.
30
+ # * :snippet [Hash]
31
+ # - :title [String] The channel's title.
32
+ # - :description [String] The channel's description.
33
+ # - :publishedAt [String] The date and time that the channel was created. The value is specified in ISO 8601 (YYYY-MM-DDThh:mm:ss.sZ) format.
34
+ # - :thumbnails [Hash]
35
+ # + :default [Hash] Default thumbnail URL (88px x 88px)
36
+ # + :medium [Hash] Medium thumbnail URL (88px x 88px)
37
+ # + :high [Hash] High thumbnail URL (88px x 88px)
38
+ def info
39
+ @info ||= request! method: :get,
40
+ auth: credentials[:access_token],
41
+ host: 'https://www.googleapis.com',
42
+ path: '/youtube/v3/channels?part=id,snippet&mine=true',
43
+ valid_if: -> resp, body {resp.code == '200' && body['items'].any?},
44
+ extract: -> body {body['items'].first}
45
+ end
46
+
47
+ ## Promote a Youtube target resource on this Youtube Channel
48
+ # Note that liking a video does not also subscribe to a channel
49
+ def perform!(activity, target_kind, target_id)
50
+ params = {}.tap do |params|
51
+ params[:method] = :post
52
+ params[:auth] = credentials[:access_token]
53
+ params[:host] = 'https://www.googleapis.com'
54
+
55
+ case [activity.to_sym, target_kind.to_sym]
56
+ when [:like, :video]
57
+ params[:path] = "/youtube/v3/videos/rate?rating=like&id=#{target_id}"
58
+ params[:valid_if] = -> response, body {response.code == '204'}
59
+ when [:subscribe_to, :channel]
60
+ params[:json] = true
61
+ params[:path] = '/youtube/v3/subscriptions?part=snippet'
62
+ params[:body] = {snippet: {resourceId: {channelId: target_id}}}
63
+ params[:valid_if] = -> response, body {response.code == '200'}
64
+ else
65
+ raise RequestError, "#{activity} invalid for #{target_kind} #{target_id}"
66
+ end
67
+ end
68
+ request! params
69
+ end
70
+
71
+ # Set the scopes to grant access to Youtube account
72
+ #
73
+ # @see https://developers.google.com/youtube/v3/guides/authentication
74
+ def self.oauth_scopes
75
+ %w(https://www.googleapis.com/auth/youtube)
76
+ end
77
+ end
78
+ end
@@ -0,0 +1,86 @@
1
+ require 'googol/requestable'
2
+ require 'googol/readable'
3
+ require 'googol/server_tokens'
4
+
5
+ module Googol
6
+ # Provides read-only access to a Youtube resource (a channel or a video).
7
+ #
8
+ # @example Get the description of the video "Tongue" by R.E.M.:
9
+ #
10
+ # resource = Googol::YoutubeResource.new url: 'youtu.be/Kd5M17e7Wek'
11
+ # resource.description # => "© 2006 WMG\nTongue (Video)"
12
+ #
13
+ # @example Get the description of the R.E.M. channel:
14
+ #
15
+ # resource = Googol::YoutubeResource.new url: 'youtube.com/remhq'
16
+ # resource.description # => "R.E.M.'s Official YouTube Channel"
17
+ #
18
+ # Note that this class does not require the user to authenticate.
19
+ #
20
+ class YoutubeResource
21
+ include Requestable
22
+ include Readable
23
+ include ServerTokens
24
+ # Initialize a resource by URL
25
+ #
26
+ # @param [Hash] attrs
27
+ # @option attrs [String] :url The URL of the Youtube channel or video
28
+ def initialize(attrs = {})
29
+ @url = attrs[:url]
30
+ end
31
+
32
+ # Return the profile info of a Youtube account/channel.
33
+ #
34
+ # @see https://developers.google.com/youtube/v3/docs/channels#resource
35
+ #
36
+ # @return [Hash]
37
+ # * :id [String] The ID that YouTube uses to uniquely identify the channel.
38
+ # * :etag [String] The Etag of this resource.
39
+ # * :kind [String] The value will be youtube#channel.
40
+ # * :snippet [Hash]
41
+ # - :title [String] The channel's title.
42
+ # - :description [String] The channel's description.
43
+ # - :publishedAt [String] The date and time that the channel was created. The value is specified in ISO 8601 (YYYY-MM-DDThh:mm:ss.sZ) format.
44
+ # - :thumbnails [Hash]
45
+ # + :default [Hash] Default thumbnail URL (88px x 88px)
46
+ # + :medium [Hash] Medium thumbnail URL (88px x 88px)
47
+ # + :high [Hash] High thumbnail URL (88px x 88px)
48
+ def info
49
+ @info ||= request! method: :get,
50
+ host: 'https://www.googleapis.com',
51
+ path: "/youtube/v3/#{info_path}",
52
+ valid_if: -> resp, body {resp.code == '200' && body['items'].any?},
53
+ extract: -> body {body['items'].first}
54
+ end
55
+
56
+ private
57
+
58
+ ##
59
+ # Return the path to execute the Google API request again.
60
+ # Channels and videos have different paths, so it depends on the type
61
+ #
62
+ # @return [String] Path
63
+ def info_path
64
+ @info_path ||= case @url
65
+ when regex?(:video_id) then "videos?id=#{$1}"
66
+ when regex?(:video_short_id) then "videos?id=#{$1}"
67
+ when regex?(:channel_id) then "channels?id=#{$1}"
68
+ when regex?(:channel_username) then "channels?forUsername=#{$1}"
69
+ when regex?(:channel_name) then "channels?forUsername=#{$1}"
70
+ else raise RequestError, "Invalid Youtube URL: #{@url}"
71
+ end + "&part=id,snippet&key=#{server_key}"
72
+ end
73
+
74
+ # Parses a URL to find the type and identifier of a Youtube resource
75
+ def regex?(key)
76
+ host, name = '^(?:https?://)?(?:www\.)?', '([a-zA-Z0-9_-]+)'
77
+ case key
78
+ when :video_id then %r{#{host}youtube\.com/watch\?v=#{name}}
79
+ when :video_short_id then %r{#{host}youtu\.be/#{name}}
80
+ when :channel_id then %r{#{host}youtube\.com/channel/#{name}}
81
+ when :channel_username then %r{#{host}youtube\.com/user/#{name}}
82
+ when :channel_name then %r{#{host}youtube\.com/#{name}}
83
+ end
84
+ end
85
+ end
86
+ end
metadata ADDED
@@ -0,0 +1,127 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: googol
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.1.1
5
+ platform: ruby
6
+ authors:
7
+ - Claudio Baccigalupo
8
+ autorequire:
9
+ bindir: bin
10
+ cert_chain: []
11
+ date: 2014-04-09 00:00:00.000000000 Z
12
+ dependencies:
13
+ - !ruby/object:Gem::Dependency
14
+ name: bundler
15
+ requirement: !ruby/object:Gem::Requirement
16
+ requirements:
17
+ - - "~>"
18
+ - !ruby/object:Gem::Version
19
+ version: '1.3'
20
+ type: :development
21
+ prerelease: false
22
+ version_requirements: !ruby/object:Gem::Requirement
23
+ requirements:
24
+ - - "~>"
25
+ - !ruby/object:Gem::Version
26
+ version: '1.3'
27
+ - !ruby/object:Gem::Dependency
28
+ name: rspec
29
+ requirement: !ruby/object:Gem::Requirement
30
+ requirements:
31
+ - - ">="
32
+ - !ruby/object:Gem::Version
33
+ version: '0'
34
+ type: :development
35
+ prerelease: false
36
+ version_requirements: !ruby/object:Gem::Requirement
37
+ requirements:
38
+ - - ">="
39
+ - !ruby/object:Gem::Version
40
+ version: '0'
41
+ - !ruby/object:Gem::Dependency
42
+ name: rake
43
+ requirement: !ruby/object:Gem::Requirement
44
+ requirements:
45
+ - - ">="
46
+ - !ruby/object:Gem::Version
47
+ version: '0'
48
+ type: :development
49
+ prerelease: false
50
+ version_requirements: !ruby/object:Gem::Requirement
51
+ requirements:
52
+ - - ">="
53
+ - !ruby/object:Gem::Version
54
+ version: '0'
55
+ - !ruby/object:Gem::Dependency
56
+ name: yard
57
+ requirement: !ruby/object:Gem::Requirement
58
+ requirements:
59
+ - - ">="
60
+ - !ruby/object:Gem::Version
61
+ version: '0'
62
+ type: :development
63
+ prerelease: false
64
+ version_requirements: !ruby/object:Gem::Requirement
65
+ requirements:
66
+ - - ">="
67
+ - !ruby/object:Gem::Version
68
+ version: '0'
69
+ - !ruby/object:Gem::Dependency
70
+ name: coveralls
71
+ requirement: !ruby/object:Gem::Requirement
72
+ requirements:
73
+ - - ">="
74
+ - !ruby/object:Gem::Version
75
+ version: '0'
76
+ type: :development
77
+ prerelease: false
78
+ version_requirements: !ruby/object:Gem::Requirement
79
+ requirements:
80
+ - - ">="
81
+ - !ruby/object:Gem::Version
82
+ version: '0'
83
+ description: Google + Youtube V3 API client.
84
+ email:
85
+ - claudio@fullscreen.net
86
+ executables: []
87
+ extensions: []
88
+ extra_rdoc_files: []
89
+ files:
90
+ - MIT-LICENSE
91
+ - README.md
92
+ - lib/googol.rb
93
+ - lib/googol/authenticable.rb
94
+ - lib/googol/client_tokens.rb
95
+ - lib/googol/google_account.rb
96
+ - lib/googol/readable.rb
97
+ - lib/googol/requestable.rb
98
+ - lib/googol/server_tokens.rb
99
+ - lib/googol/version.rb
100
+ - lib/googol/youtube_account.rb
101
+ - lib/googol/youtube_resource.rb
102
+ homepage: https://github.com/fullscreeninc/googol
103
+ licenses:
104
+ - MIT
105
+ metadata: {}
106
+ post_install_message:
107
+ rdoc_options: []
108
+ require_paths:
109
+ - lib
110
+ required_ruby_version: !ruby/object:Gem::Requirement
111
+ requirements:
112
+ - - ">="
113
+ - !ruby/object:Gem::Version
114
+ version: 2.0.0
115
+ required_rubygems_version: !ruby/object:Gem::Requirement
116
+ requirements:
117
+ - - ">="
118
+ - !ruby/object:Gem::Version
119
+ version: 1.3.6
120
+ requirements: []
121
+ rubyforge_project:
122
+ rubygems_version: 2.2.2
123
+ signing_key:
124
+ specification_version: 4
125
+ summary: Googol lets you interact with many resources provided by Google API V3.
126
+ test_files: []
127
+ has_rdoc: