bitly 2.0.0.beta.1 → 2.0.0.beta.2

Sign up to get free protection for your applications and to get access to all the features.
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: 9f5ea77a3cf31565edfd92df7f3e5295e0921592d46ab2c6a82544c1bdc3b9aa
4
- data.tar.gz: 64a22df3165af72fd65954fb70d3af7e04c5e743d52bcc1c94dbb57a8b8c97ea
3
+ metadata.gz: 4936c99089af48f7096225e8f9a320978a52152d7650644099f1c2e79bfdb212
4
+ data.tar.gz: 246fc9e55eeb72aabcdba418cf7fa9df8b29f02fc5e6079fa0ed32979b6c5c37
5
5
  SHA512:
6
- metadata.gz: a30418e79a7c1af67a7b2ab3c98fd21c385fcb6ac690a0a704755e0c5b037da5175c27ef8d1c6ea8d1baa59836e607dfc72416f60178e1781ae203e6056bd4dd
7
- data.tar.gz: 4db248dccaf1ef70932ccf1ff3264b22da25d3cc2d0f8c168e6b857afc7ec365ed044ec72d797a513d4349fc3dd0a3294d082291cb9d9947e95c6d2d4a069393
6
+ metadata.gz: 16a268a0383fff569797929ad3fe90bcf46d38897b1aed760bfe878f5e0dd22b7d9ce126e725c59b76a43d5d96fe571e0d46ffab083af008cabc35bf5a05228e
7
+ data.tar.gz: d1700910090cd61c35438dafb6050f6d3bdaf8dace92b3d790741f13f6a21e5b2b6e7237d3f4575e469c9f501b44a17e48e4f0981a12e5fc8969f83726efafff
@@ -9,6 +9,7 @@ rvm:
9
9
  - 2.6
10
10
  - 2.5
11
11
  - 2.4
12
+ - 2.3
12
13
  - ruby-head
13
14
  - jruby-19mode
14
15
  - jruby-head
@@ -2,6 +2,10 @@
2
2
 
3
3
  ...
4
4
 
5
+ === 2.0.0.beta.2 / 2020-03-02
6
+
7
+ * Uses autoload to improve memory consumption
8
+
5
9
  === 2.0.0.beta.1 / 2020-02-15
6
10
 
7
11
  * Complete overhaul of the gem.
data/Rakefile CHANGED
@@ -1,3 +1,5 @@
1
+ # frozen_string_literal: true
2
+
1
3
  require "bundler/gem_tasks"
2
4
  require "rspec/core/rake_task"
3
5
 
@@ -1,3 +1,4 @@
1
+ # frozen_string_literal: true
1
2
 
2
3
  lib = File.expand_path("../lib", __FILE__)
3
4
  $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
@@ -9,22 +10,30 @@ Gem::Specification.new do |spec|
9
10
  spec.authors = ["Phil Nash"]
10
11
  spec.email = ["philnash@gmail.com"]
11
12
 
12
- spec.summary = %q{Use the bit.ly API to shorten or expand URLs}
13
- spec.description = %q{Use the bit.ly API to shorten or expand URLs. Check out the API documentation at https://dev.bitly.com/.}
13
+ spec.summary = %q{Use the Bitly API to shorten or expand URLs}
14
+ spec.description = %q{Use the Bitly API version 4 to shorten or expand URLs. Check out the API documentation at https://dev.bitly.com/.}
14
15
  spec.homepage = "https://github.com/philnash/bitly"
15
16
  spec.license = "MIT"
16
17
 
18
+ spec.metadata = {
19
+ "bug_tracker_uri" => "https://github.com/philnash/bitly/issues",
20
+ "changelog_uri" => "https://github.com/philnash/bitly/blob/master/History.txt",
21
+ "documentation_uri" => "https://www.rubydoc.info/gems/bitly/",
22
+ "homepage_uri" => "https://github.com/philnash/bitly",
23
+ "source_code_uri" => "https://github.com/philnash/bitly"
24
+ }
25
+
17
26
  spec.files = `git ls-files -z`.split("\x0").reject do |f|
18
- f.match(%r{^(test|spec|features)/})
27
+ f.match(%r{^(test|spec|features|bin|docs)/})
19
28
  end
20
- spec.bindir = "exe"
21
- spec.executables = spec.files.grep(%r{^exe/}) { |f| File.basename(f) }
22
29
  spec.require_paths = ["lib"]
23
30
 
24
- spec.add_dependency "oauth2", "< 2.0", ">= 0.5.0"
31
+ spec.required_ruby_version = ">= 2.3.0"
32
+
33
+ spec.add_runtime_dependency "oauth2", "< 2.0", ">= 0.5.0"
25
34
 
26
35
  spec.add_development_dependency "bundler", "~> 2.0"
27
- spec.add_development_dependency "rake", "~> 10.0"
36
+ spec.add_development_dependency "rake", "~> 13.0"
28
37
  spec.add_development_dependency "rspec", "~> 3.0"
29
38
  spec.add_development_dependency "simplecov", "~> 0.17.1"
30
39
  spec.add_development_dependency "webmock", "~> 3.7.6"
@@ -1,7 +1,10 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  require "bitly/version"
4
- require "bitly/error"
5
- require "bitly/oauth"
6
- require "bitly/http"
7
- require "bitly/api"
4
+
5
+ module Bitly
6
+ autoload :Error, "bitly/error"
7
+ autoload :OAuth, "bitly/oauth"
8
+ autoload :HTTP, "bitly/http"
9
+ autoload :API, "bitly/api"
10
+ end
@@ -3,14 +3,16 @@
3
3
  module Bitly
4
4
  module API
5
5
  BASE_URL = URI("https://api-ssl.bitly.com/v4")
6
+
7
+ autoload :Base, File.join(File.dirname(__FILE__), "api/base.rb")
8
+ autoload :Client, File.join(File.dirname(__FILE__), "api/client.rb")
9
+ autoload :ClickMetric, File.join(File.dirname(__FILE__), "api/click_metric.rb")
10
+ autoload :Bitlink, File.join(File.dirname(__FILE__), "api/bitlink.rb")
11
+ autoload :Organization, File.join(File.dirname(__FILE__), "api/organization.rb")
12
+ autoload :Group, File.join(File.dirname(__FILE__), "api/group.rb")
13
+ autoload :User, File.join(File.dirname(__FILE__), "api/user.rb")
14
+ autoload :BSD, File.join(File.dirname(__FILE__), "api/bsd.rb")
15
+ autoload :OAuthApp, File.join(File.dirname(__FILE__), "api/oauth_app.rb")
16
+ autoload :ShortenCounts, File.join(File.dirname(__FILE__), "api/shorten_counts.rb")
6
17
  end
7
18
  end
8
-
9
- require_relative "./api/client"
10
- require_relative "./api/click_metric"
11
- require_relative "./api/bitlink"
12
- require_relative "./api/organization"
13
- require_relative "./api/group"
14
- require_relative "./api/user"
15
- require_relative "./api/bsd"
16
- require_relative "./api/oauth_app"
@@ -1,16 +1,17 @@
1
1
  # frozen_string_literal: true
2
2
  require_relative "./base"
3
3
  require_relative "./list"
4
- require_relative "./bitlink/paginated_list"
5
- require_relative "./bitlink/deeplink"
6
- require_relative "./bitlink/clicks_summary"
7
- require_relative "./bitlink/link_click"
8
4
 
9
5
  module Bitly
10
6
  module API
11
7
  ##
12
8
  # A Bitlink represents a shortened link within Bitly.
13
9
  class Bitlink
10
+ autoload :PaginatedList, File.join(File.dirname(__FILE__), "bitlink/paginated_list.rb")
11
+ autoload :Deeplink, File.join(File.dirname(__FILE__), "bitlink/deeplink.rb")
12
+ autoload :ClicksSummary, File.join(File.dirname(__FILE__), "bitlink/clicks_summary.rb")
13
+ autoload :LinkClick, File.join(File.dirname(__FILE__), "bitlink/link_click.rb")
14
+
14
15
  include Base
15
16
 
16
17
  class List < Bitly::API::List ; end
@@ -1,8 +1,6 @@
1
1
  # frozen_string_literal: true
2
2
  require_relative "./base"
3
3
  require_relative "./list"
4
- require_relative "./group/preferences"
5
- require_relative "./shorten_counts"
6
4
 
7
5
  module Bitly
8
6
  module API
@@ -11,6 +9,8 @@ module Bitly
11
9
  # taken on behalf of a user and group and groups become a container for
12
10
  # Bitlinks and metrics.
13
11
  class Group
12
+ autoload :Preferences, File.join(File.dirname(__FILE__), "group/preferences.rb")
13
+
14
14
  include Base
15
15
 
16
16
  ##
@@ -1,6 +1,10 @@
1
1
  # frozen_string_literal: true
2
2
 
3
- require_relative "./http/adapters/net_http"
4
- require_relative "./http/response"
5
- require_relative "./http/request"
6
- require_relative "./http/client"
3
+ module Bitly
4
+ module HTTP
5
+ autoload :Adapters, File.join(File.dirname(__FILE__), "http/adapters.rb")
6
+ autoload :Response, File.join(File.dirname(__FILE__), "http/response.rb")
7
+ autoload :Request, File.join(File.dirname(__FILE__), "http/request.rb")
8
+ autoload :Client, File.join(File.dirname(__FILE__), "http/client.rb")
9
+ end
10
+ end
@@ -0,0 +1,9 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Bitly
4
+ module HTTP
5
+ module Adapters
6
+ autoload :NetHTTP, File.join(File.dirname(__FILE__), "adapters/net_http.rb")
7
+ end
8
+ end
9
+ end
@@ -1,5 +1,5 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  module Bitly
4
- VERSION = "2.0.0.beta.1"
4
+ VERSION = "2.0.0.beta.2"
5
5
  end
metadata CHANGED
@@ -1,14 +1,14 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: bitly
3
3
  version: !ruby/object:Gem::Version
4
- version: 2.0.0.beta.1
4
+ version: 2.0.0.beta.2
5
5
  platform: ruby
6
6
  authors:
7
7
  - Phil Nash
8
8
  autorequire:
9
- bindir: exe
9
+ bindir: bin
10
10
  cert_chain: []
11
- date: 2020-02-15 00:00:00.000000000 Z
11
+ date: 2020-03-02 00:00:00.000000000 Z
12
12
  dependencies:
13
13
  - !ruby/object:Gem::Dependency
14
14
  name: oauth2
@@ -50,14 +50,14 @@ dependencies:
50
50
  requirements:
51
51
  - - "~>"
52
52
  - !ruby/object:Gem::Version
53
- version: '10.0'
53
+ version: '13.0'
54
54
  type: :development
55
55
  prerelease: false
56
56
  version_requirements: !ruby/object:Gem::Requirement
57
57
  requirements:
58
58
  - - "~>"
59
59
  - !ruby/object:Gem::Version
60
- version: '10.0'
60
+ version: '13.0'
61
61
  - !ruby/object:Gem::Dependency
62
62
  name: rspec
63
63
  requirement: !ruby/object:Gem::Requirement
@@ -128,8 +128,8 @@ dependencies:
128
128
  - - ">="
129
129
  - !ruby/object:Gem::Version
130
130
  version: '0'
131
- description: Use the bit.ly API to shorten or expand URLs. Check out the API documentation
132
- at https://dev.bitly.com/.
131
+ description: Use the Bitly API version 4 to shorten or expand URLs. Check out the
132
+ API documentation at https://dev.bitly.com/.
133
133
  email:
134
134
  - philnash@gmail.com
135
135
  executables: []
@@ -145,19 +145,8 @@ files:
145
145
  - LICENSE.md
146
146
  - README.md
147
147
  - Rakefile
148
- - bin/console
149
- - bin/oauth
150
- - bin/setup
151
148
  - bitly.gemspec
152
149
  - config/env.yml.example
153
- - docs/authentication.md
154
- - docs/bitlinks.md
155
- - docs/branded_short_domains.md
156
- - docs/groups.md
157
- - docs/oauth_apps.md
158
- - docs/organizations.md
159
- - docs/premium_apis.md
160
- - docs/users.md
161
150
  - lib/bitly.rb
162
151
  - lib/bitly/api.rb
163
152
  - lib/bitly/api/base.rb
@@ -176,22 +165,24 @@ files:
176
165
  - lib/bitly/api/organization.rb
177
166
  - lib/bitly/api/shorten_counts.rb
178
167
  - lib/bitly/api/user.rb
179
- - lib/bitly/client.rb
180
- - lib/bitly/config.rb
181
168
  - lib/bitly/error.rb
182
169
  - lib/bitly/http.rb
170
+ - lib/bitly/http/adapters.rb
183
171
  - lib/bitly/http/adapters/net_http.rb
184
172
  - lib/bitly/http/client.rb
185
173
  - lib/bitly/http/request.rb
186
174
  - lib/bitly/http/response.rb
187
175
  - lib/bitly/oauth.rb
188
- - lib/bitly/v3/client.rb
189
- - lib/bitly/v3/user.rb
190
176
  - lib/bitly/version.rb
191
177
  homepage: https://github.com/philnash/bitly
192
178
  licenses:
193
179
  - MIT
194
- metadata: {}
180
+ metadata:
181
+ bug_tracker_uri: https://github.com/philnash/bitly/issues
182
+ changelog_uri: https://github.com/philnash/bitly/blob/master/History.txt
183
+ documentation_uri: https://www.rubydoc.info/gems/bitly/
184
+ homepage_uri: https://github.com/philnash/bitly
185
+ source_code_uri: https://github.com/philnash/bitly
195
186
  post_install_message:
196
187
  rdoc_options: []
197
188
  require_paths:
@@ -200,7 +191,7 @@ required_ruby_version: !ruby/object:Gem::Requirement
200
191
  requirements:
201
192
  - - ">="
202
193
  - !ruby/object:Gem::Version
203
- version: '0'
194
+ version: 2.3.0
204
195
  required_rubygems_version: !ruby/object:Gem::Requirement
205
196
  requirements:
206
197
  - - ">"
@@ -210,5 +201,5 @@ requirements: []
210
201
  rubygems_version: 3.0.3
211
202
  signing_key:
212
203
  specification_version: 4
213
- summary: Use the bit.ly API to shorten or expand URLs
204
+ summary: Use the Bitly API to shorten or expand URLs
214
205
  test_files: []
@@ -1,14 +0,0 @@
1
- #!/usr/bin/env ruby
2
-
3
- require "bundler/setup"
4
- require "bitly"
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(__FILE__)
data/bin/oauth DELETED
@@ -1,10 +0,0 @@
1
- #!/usr/bin/env ruby
2
-
3
- require "bundler/setup"
4
- require "bitly"
5
- require "envyable"
6
-
7
- Envyable.load('./config/env.yml')
8
-
9
- oauth = Bitly::OAuth.new(client_id: ENV['CLIENT_ID'], client_secret: ENV['CLIENT_SECRET'])
10
- puts oauth.authorize_uri('http://example.com/oauth/redirect')
data/bin/setup DELETED
@@ -1,8 +0,0 @@
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
@@ -1,51 +0,0 @@
1
- # Authentication
2
-
3
- Bitly requires OAuth access tokens to use the API. You will need to [register your application with the Bitly API](bitly.com/a/oauth_apps), you will get a `client_id` and `client_secret`.
4
-
5
- There are 3 methods you can use to get an OAuth access token:
6
-
7
- - [Account Generic Access Token](#account-generic-access-token)
8
- - [OAuth Web Flow](#oauth-web-flow)
9
- - [Resource Owner Credential Grant Flow](#resource-owner-credential-grant-flow)
10
-
11
- ## Account Generic Access Token
12
-
13
- You can get your own OAuth token for your account from the [Bitly console](https://app.bitly.com/). Click on the account drop down menu, then _Profile Settings_ then _Generic Access Token_. Fill in your password and you can generate an OAuth access token.
14
-
15
- ## OAuth Web Flow
16
-
17
- Redirect the user to the Bitly authorization page using your `client_id` and a `redirect_uri` that Bitly should redirect your user to after authorization. You can get the URL like so:
18
-
19
- ```ruby
20
- oauth = Bitly::OAuth.new(client_id: client_id, client_secret: client_secret)
21
- oauth.authorize_uri("http://myexamplewebapp.com/oauth_page")
22
- #=> "https://bitly.com/oauth/authorize?client_id=client_id&redirect_uri=http%3A%2F%2Fmyexamplewebapp.com%2Foauth_page"
23
- ```
24
-
25
- You can pass an optional `state` parameter that will be included, unchanged, in the redirect.
26
-
27
- ```ruby
28
- oauth.authorize_uri("http://myexamplewebapp.com/oauth_page", state: "state")
29
- #=> "https://bitly.com/oauth/authorize?client_id=client_id&redirect_uri=http%3A%2F%2Fmyexamplewebapp.com%2Foauth_page&state=state"
30
- ```
31
-
32
- Once the user has authorized you to use their Bitly account, you will get a
33
- `code` parameter in the redirect. You can exchange that code, along with the
34
- redirect_uri, for the access token.
35
-
36
- ```ruby
37
- oauth.access_token(redirect_uri: "http://myexamplewebapp.com/oauth_page", code: "code")
38
- #=> "<ACCESS_TOKEN>"
39
- ```
40
-
41
- ## Resource Owner Credential Grant Flow
42
-
43
- If you cannot perform a web flow, the resource owner credential grant flow allows you to take a user's username and password and exchange it for an OAuth access token. If you use this method you _should_ store only the user's access token and never the password.
44
-
45
- To use the resource owner credential grant flow, create an OAuth client object then request the access token with the username and password:
46
-
47
- ```ruby
48
- oauth = Bitly::OAuth.new(client_id: client_id, client_secret: client_secret)
49
- oauth.access_token(username: username, password: password)
50
- #=> "<ACCESS_TOKEN>"
51
- ```
@@ -1,2 +0,0 @@
1
- # Bitlinks
2
-
@@ -1,20 +0,0 @@
1
- # Branded Short Domains
2
-
3
- BSDs is an acronym for branded short domains. A branded short domain is a custom 15 character or less domain for bitlinks. This allows you to customize the domain to your brand.
4
-
5
- See the full [Bitly API documentation for BSDs](https://dev.bitly.com/v4/#tag/BSDs).
6
-
7
- ## List BSDs
8
-
9
- With an API client you can list the BSDs available to the authorized user.
10
-
11
- ```ruby
12
- client = Bitly::API::Client.new(token: token)
13
- bsds = client.bsds
14
- ```
15
-
16
- Or with the class method
17
-
18
- ```ruby
19
- bsds = Bitly::API::BSD.list(client: client)
20
- ```
@@ -1,80 +0,0 @@
1
- # Groups
2
-
3
- Groups are a subdivision within an [organization](./organizations.md). A [user](./users.md) belongs to a group within an organization. Most actions in the API are on behalf of a group. For example, when you shorten a link, it will be on behalf of a user and a group.
4
-
5
- See the full [Bitly API documentation for Groups](https://dev.bitly.com/v4/#tag/Groups).
6
-
7
- ## List Groups
8
-
9
- With an API client you can list the groups available to the authorized user.
10
-
11
- ```ruby
12
- client = Bitly::API::Client.new(token: token)
13
- groups = client.groups
14
- ```
15
-
16
- Or with the class method
17
-
18
- ```ruby
19
- groups = Bitly::API::Group.list(client: client)
20
- ```
21
-
22
- You can also filter groups by an organization guid or an organization object, using the client.
23
-
24
- ```ruby
25
- groups = client.groups(organization: organization_guid)
26
- groups = client.groups(organization: organization)
27
- ```
28
-
29
- Or the class method
30
-
31
- ```ruby
32
- groups = Bitly::API::Group.list(client: client, organization: organization_guid)
33
- groups = Bitly::API::Group.list(client: client, organization: organization)
34
- ```
35
-
36
- ## Fetch a Group
37
-
38
- If you have the guid of an group, you can fetch it directly.
39
-
40
- ```ruby
41
- group = client.group(guid)
42
- ```
43
-
44
- Or with the class method
45
-
46
- ```ruby
47
- group = Bitly::API::Group.fetch(client: client, guid: guid)
48
- ```
49
-
50
- ## Group attributes
51
-
52
- Groups have the following attributes:
53
-
54
- * `name`
55
- * `guid`
56
- * `is_active`
57
- * `role`
58
- * `bsds`
59
- * `organization_guid`
60
- * `created`
61
- * `modified`
62
-
63
- ### A Group's organization
64
-
65
- With the `organization_guid` we can get the group's organization directly from the group object.
66
-
67
- ```ruby
68
- organization = group.organization
69
- ```
70
-
71
- ### Group preferences
72
-
73
- You can set one preference for a group, the domain that is used to shorten links. Free accounts can only choose `bit.ly` and pro accounts can use any domains they have set up.
74
-
75
- ```ruby
76
- preferences = group.preferences
77
- puts preferences.domain_preference
78
-
79
- preferences.update(domain_preference: 'bit.ly')
80
- ```
@@ -1,20 +0,0 @@
1
- # OAuth Apps
2
-
3
- You can fetch the details of an OAuth app you have in your account by the `client_id`.
4
-
5
- See the full [Bitly documentation for OAuth apps](https://dev.bitly.com/v4/#operation/getOAuthApp)
6
-
7
- ## Fetch an OAuth app
8
-
9
- With the `client_id` of an OAuth app, you can fetch it directly.
10
-
11
- ```ruby
12
- client = Bitly::API::Client.new(token: token)
13
- oauth_app = client.oauth_app(client_id: client_id)
14
- ```
15
-
16
- Or with the class method
17
-
18
- ```ruby
19
- oauth_app = Bitly::API::OAuthApp.fetch(client: client, client_id: client_id)
20
- ```
@@ -1,74 +0,0 @@
1
- # Organizations
2
-
3
- An organization is the top level of the Bitly user hierarchy. Both [Users](./users.md) and [Groups](./groups.md) live within an organization.
4
-
5
- See the full [Bitly API documentation for Organizations](https://dev.bitly.com/v4/#tag/Organizations).
6
-
7
- ## List Organizations
8
-
9
- With an API client you can list the organizations available to the authorized user.
10
-
11
- ```ruby
12
- client = Bitly::API::Client.new(token: token)
13
- organizations = client.organizations
14
- ```
15
-
16
- Or with the class method:
17
-
18
- ```ruby
19
- organizations = Bitly::API::Organization.list(client: client)
20
- ```
21
-
22
- ## Fetch an Organization
23
-
24
- If you have the guid of an organization, you can fetch it directly.
25
-
26
- ```ruby
27
- client = Bitly::API::Client.new(token: token)
28
- organization = client.organization(guid)
29
- ```
30
-
31
- Or with the class method
32
-
33
- ```ruby
34
- organization = Bitly::API::Organization.fetch(client: client, organization_guid: guid)
35
- ```
36
-
37
- ## Organization attributes
38
-
39
- Organizations have the following attributes:
40
-
41
- * `name`
42
- * `guid`
43
- * `is_active`
44
- * `tier`
45
- * `tier_family`
46
- * `tier_display_name`
47
- * `role`
48
- * `bsds`
49
- * `created`
50
- * `modified`
51
-
52
- ### Organization groups
53
-
54
- With an organization you can fetch its related [groups](./groups.md).
55
-
56
- ```ruby
57
- client = Bitly::API::Client.new(token: token)
58
- organization = client.organization(guid)
59
- groups = organization.groups
60
- ```
61
-
62
- This is the same as fetching groups and filtering by an organization guid.
63
-
64
- ```ruby
65
- client = Bitly::API::Client.new(token: token)
66
- organization = client.organization(guid)
67
- groups = client.groups(organization: organization)
68
- ```
69
-
70
- Or filtering in the class method directly.
71
-
72
- ```ruby
73
- groups = Bitly::API::Group.list(client: client, organization: organization)
74
- ```
File without changes
@@ -1 +0,0 @@
1
- # Users
@@ -1,145 +0,0 @@
1
- require 'rubygems'
2
- require 'net/http'
3
- require 'uri'
4
-
5
- module Bitly
6
- extend Config
7
- API_URL = 'https://api-ssl.bitly.com/'
8
- API_VERSION = '2.0.1'
9
-
10
- def self.new(login, api_key = nil, timeout=nil)
11
- if api_version == 3
12
- Bitly::V3::Client.new(login, api_key, timeout)
13
- else
14
- Bitly::Client.new(login,api_key)
15
- end
16
- end
17
-
18
- def self.use_api_version_3
19
- self.api_version = 3
20
- end
21
-
22
- def self.use_api_version_2
23
- self.api_version = 2
24
- end
25
-
26
- # get and initialize a client if configured using Config
27
- def self.client
28
- # api_verison, login, and api_key are set in Config
29
- if api_version == 3
30
- Bitly::V3::Client.new(login, api_key, timeout)
31
- else
32
- Bitly::Client.new(login, api_key)
33
- end
34
- end
35
-
36
- class Client
37
-
38
- include Bitly::Utils
39
- attr_accessor(*Config::OPTION_KEYS)
40
-
41
- def initialize(login,api_key)
42
- warn "[DEPRECATION] The bit.ly version 2 API has been superseded by version 3 and will be removed. See the README for details"
43
- @login = login
44
- @api_key = api_key
45
- end
46
-
47
- def shorten(input, opts={})
48
- if input.is_a? String
49
- request = create_url("shorten", :longUrl => input, :history => (opts[:history] ? 1 : nil))
50
- result = get_result(request)
51
- result = {:long_url => input}.merge result[input]
52
- Bitly::Url.new(@login,@api_key,result)
53
- elsif input.is_a? Array
54
- request = create_url("shorten", :history => (opts[:history] ? 1 : nil))
55
- request.query << "&" + input.map { |long_url| "longUrl=#{CGI.escape(long_url)}" }.join("&") unless input.nil?
56
- result = get_result(request)
57
- input.map do |long_url|
58
- new_url = {:long_url => long_url}.merge result[long_url]
59
- long_url = Bitly::Url.new(@login,@api_key,new_url)
60
- end
61
- else
62
- raise ArgumentError.new("Shorten requires either a url or an array of urls")
63
- end
64
- end
65
-
66
- def expand(input)
67
- if input.is_a? String
68
- if input.include?('bit.ly/') || input.include?('j.mp/')
69
- hash = create_hash_from_url(input)
70
- request = create_url "expand", :hash => hash
71
- result = get_result(request)
72
- result = { :short_url => input, :hash => hash }.merge result[hash]
73
- else
74
- request = create_url "expand", :hash => input
75
- result = get_result(request)
76
- result = { :hash => input, :short_url => "http://bit.ly/#{input}" }.merge result[input]
77
- end
78
- Bitly::Url.new(@login,@api_key,result)
79
- elsif input.is_a? Array
80
- request = create_url "expand", :hash => input.join(',')
81
- result = get_result(request)
82
- input.map do |hsh|
83
- new_url = {:hash => hsh, :short_url => "http://bit.ly/#{hsh}"}.merge result[hsh]
84
- hsh = Bitly::Url.new(@login,@api_key,new_url)
85
- end
86
- else
87
- raise ArgumentError('Expand requires either a short url, a hash or an array of hashes')
88
- end
89
- end
90
-
91
- def info(input)
92
- if input.is_a? String
93
- if input.include? "bit.ly/"
94
- hash = create_hash_from_url(input)
95
- request = create_url 'info', :hash => hash
96
- result = get_result(request)
97
- result = { :short_url => "http://bit.ly/#{hash}", :hash => hash }.merge result[hash]
98
- else
99
- request = create_url 'info', :hash => input
100
- result = get_result(request)
101
- result = { :short_url => "http://bit.ly/#{input}", :hash => input }.merge result[input]
102
- end
103
- Bitly::Url.new(@login,@api_key,result)
104
- elsif input.is_a? Array
105
- request = create_url "info", :hash => input.join(',')
106
- result = get_result(request)
107
- input.map do |hsh|
108
- new_url = {:hash => hsh, :short_url => "http://bit.ly/#{hsh}"}.merge result[hsh]
109
- hsh = Bitly::Url.new(@login,@api_key,:info => new_url)
110
- end
111
- else
112
- raise ArgumentError.new('Info requires either a short url, a hash or an array of hashes')
113
- end
114
- end
115
-
116
- def stats(input)
117
- if input.is_a? String
118
- if input.include? "bit.ly/"
119
- hash = create_hash_from_url(input)
120
- request = create_url 'stats', :hash => hash
121
- result = get_result(request)
122
- result = { :short_url => "http://bit.ly/#{hash}", :hash => hash }.merge result
123
- else
124
- request = create_url 'stats', :hash => input
125
- result = get_result(request)
126
- result = { :short_url => "http://bit.ly/#{input}", :hash => input }.merge result
127
- end
128
- Bitly::Url.new(@login,@api_key,:stats => result)
129
- else
130
- raise ArgumentError.new("Stats requires either a short url or a hash")
131
- end
132
- end
133
-
134
- end
135
-
136
- end
137
-
138
- class BitlyError < StandardError
139
- attr_reader :code
140
- alias :msg :message
141
- def initialize(msg, code)
142
- @code = code
143
- super("#{msg} - '#{code}'")
144
- end
145
- end
@@ -1,29 +0,0 @@
1
- module Bitly
2
- module Config
3
-
4
- # bitly client options
5
- OPTION_KEYS = [
6
- :login,
7
- :api_key,
8
- :api_version,
9
- :timeout
10
- ]
11
-
12
- attr_accessor(*OPTION_KEYS)
13
-
14
- alias_method :access_token, :login
15
- alias_method :access_token=, :login=
16
-
17
- def configure
18
- yield self
19
- self
20
- end
21
-
22
- def options
23
- options = {}
24
- OPTION_KEYS.each{|key| options[key] = send(key)}
25
- options
26
- end
27
-
28
- end
29
- end
@@ -1,207 +0,0 @@
1
- module Bitly
2
- module V3
3
- # The client is the main part of this gem. You need to initialize the client with your
4
- # username and API key and then you will be able to use the client to perform
5
- # all the rest of the actions available through the API.
6
- class Client
7
- include HTTParty
8
- base_uri 'https://api-ssl.bitly.com/v3/'
9
-
10
- # Requires a generic OAuth2 access token or -deprecated- login and api key.
11
- # http://dev.bitly.com/authentication.html#apikey
12
- # Generic OAuth2 access token: https://bitly.com/a/oauth_apps
13
- # ApiKey: Get yours from your account page at https://bitly.com/a/your_api_key
14
- # Visit your account at http://bit.ly/a/account
15
- def initialize(*args)
16
- args.compact!
17
- self.timeout = args.last.is_a?(0.class) ? args.pop : nil
18
- if args.count == 1
19
- # Set generic OAuth2 access token
20
- @default_query_opts = { :access_token => args.first }
21
- else
22
- # Deprecated ApiKey authentication
23
- @default_query_opts = {
24
- :login => args[0],
25
- :apiKey => args[1]
26
- }
27
- end
28
- end
29
-
30
- # Validates a login and api key
31
- def validate(x_login, x_api_key)
32
- response = get('/validate', :query => { :x_login => x_login, :x_apiKey => x_api_key })
33
- return response['data']['valid'] == 1
34
- end
35
- alias :valid? :validate
36
-
37
- # Checks whether a domain is a bitly.Pro domain
38
- def bitly_pro_domain(domain)
39
- response = get('/bitly_pro_domain', :query => { :domain => domain })
40
- return response['data']['bitly_pro_domain']
41
- end
42
- alias :pro? :bitly_pro_domain
43
-
44
- # Shortens a long url
45
- #
46
- # Options can be:
47
- #
48
- # [domain] choose bit.ly or j.mp (bit.ly is default)
49
- #
50
- # [x_login and x_apiKey] add this link to another user's history (both required)
51
- #
52
- def shorten(long_url, opts={})
53
- query = { :longUrl => long_url }.merge(opts)
54
- response = get('/shorten', :query => query)
55
- return Bitly::V3::Url.new(self, response['data'])
56
- end
57
-
58
- # Expands either a hash, short url or array of either.
59
- #
60
- # Returns the results in the order they were entered
61
- def expand(input)
62
- get_method(:expand, input)
63
- end
64
-
65
- # Expands either a hash, short url or array of either and gets click data too.
66
- #
67
- # Returns the results in the order they were entered
68
- def clicks(input)
69
- get_method(:clicks, input)
70
- end
71
-
72
- # Like expand, but gets the title of the page and who created it
73
- def info(input)
74
- get_method(:info, input)
75
- end
76
-
77
- # Looks up the short url and global hash of a url or array of urls
78
- #
79
- # Returns the results in the order they were entered
80
- def lookup(input)
81
- input = arrayize(input)
82
- query = input.inject([]) { |q, i| q << "url=#{CGI.escape(i)}" }
83
- query = "/lookup?" + query.join('&')
84
- response = get(query)
85
- results = response['data']['lookup'].inject([]) do |rs, url|
86
- url['long_url'] = url['url']
87
- url['url'] = nil
88
- if url['error'].nil?
89
- # builds the results array in the same order as the input
90
- rs[input.index(url['long_url'])] = Bitly::V3::Url.new(self, url)
91
- # remove the key from the original array, in case the same hash/url was entered twice
92
- input[input.index(url['long_url'])] = nil
93
- else
94
- rs[input.index(url['long_url'])] = Bitly::V3::MissingUrl.new(url)
95
- input[input.index(url['long_url'])] = nil
96
- end
97
- rs
98
- end
99
- return results.length > 1 ? results : results[0]
100
- end
101
-
102
- # Expands either a short link or hash and gets the referrer data for that link
103
- #
104
- # This method does not take an array as an input
105
- def referrers(input)
106
- get_single_method('referrers', input)
107
- end
108
-
109
- # Expands either a short link or hash and gets the country data for that link
110
- #
111
- # This method does not take an array as an input
112
- def countries(input)
113
- get_single_method('countries', input)
114
- end
115
-
116
- # Takes a short url, hash or array of either and gets the clicks by minute of each of the last hour
117
- def clicks_by_minute(input)
118
- get_method(:clicks_by_minute, input)
119
- end
120
-
121
- # Takes a short url, hash or array of either and gets the clicks by day
122
- def clicks_by_day(input, opts={})
123
- opts.reject! { |k, v| k.to_s != 'days' }
124
- get_method(:clicks_by_day, input, opts)
125
- end
126
-
127
- def timeout=(timeout=nil)
128
- self.class.default_timeout(timeout) if timeout
129
- end
130
-
131
- private
132
-
133
- def arrayize(arg)
134
- if arg.is_a?(String)
135
- [arg]
136
- else
137
- arg.dup
138
- end
139
- end
140
-
141
- def get(method, opts={})
142
- opts[:query] ||= {}
143
- opts[:query].merge!(@default_query_opts)
144
-
145
- begin
146
- response = self.class.get(method, opts)
147
- rescue Timeout::Error
148
- raise BitlyTimeout.new("Bitly didn't respond in time", "504")
149
- end
150
-
151
- if response['status_code'] == 200
152
- return response
153
- else
154
- raise BitlyError.new(response['status_txt'], response['status_code'])
155
- end
156
- end
157
-
158
- def is_a_short_url?(input)
159
- input.match(/^https?:\/\//)
160
- end
161
-
162
- def get_single_method(method, input)
163
- raise ArgumentError.new("This method only takes a hash or url input") unless input.is_a? String
164
- if is_a_short_url?(input)
165
- query = "shortUrl=#{CGI.escape(input)}"
166
- else
167
- query = "hash=#{CGI.escape(input)}"
168
- end
169
- query = "/#{method}?" + query
170
- response = get(query)
171
- return Bitly::V3::Url.new(self,response['data'])
172
- end
173
-
174
- def get_method(method, input, opts={})
175
- input = arrayize(input)
176
- query = input.inject([]) do |q, i|
177
- if is_a_short_url?(i)
178
- q << "shortUrl=#{CGI.escape(i)}"
179
- else
180
- q << "hash=#{CGI.escape(i)}"
181
- end
182
- end
183
- query = opts.inject(query) do |q, (k,v)|
184
- q<< "#{k}=#{v}"
185
- end
186
- query = "/#{method}?" + query.join('&')
187
- response = get(query)
188
- results = response['data'][method.to_s].inject([]) do |rs, url|
189
- result_index = input.index(url['short_url'] || url['hash']) || input.index(url['global_hash'])
190
- if url['error'].nil?
191
- # builds the results array in the same order as the input
192
- rs[result_index] = Bitly::V3::Url.new(self, url)
193
- # remove the key from the original array, in case the same hash/url was entered twice
194
- input[result_index] = nil
195
- else
196
- rs[result_index] = Bitly::V3::MissingUrl.new(url)
197
- input[result_index] = nil
198
- end
199
- rs
200
- end
201
- return results.length > 1 ? results : results[0]
202
- end
203
- end
204
- end
205
- end
206
-
207
- class BitlyTimeout < BitlyError; end
@@ -1,134 +0,0 @@
1
- module Bitly
2
- module V3
3
- # A user requires an oauth access token. The flow is as follows:
4
- #
5
- # o = Bitly::V3::OAuth.new(consumer_token, consumer_secret)
6
- # o.authorize_url(redirect_url)
7
- # #=> "https://bit.ly/oauth/authorize?client_id=#{consumer_token}&type=web_server&redirect_uri=http%3A%2F%2Ftest.local%2Fbitly%2Fauth"
8
- # Redirect your users to this url, when they authorize your application
9
- # they will be redirected to the url you provided with a code parameter.
10
- # Use that parameter, and the exact same redirect url as follows:
11
- #
12
- # o.get_access_token_from_code(params[:code], redirect_url)
13
- # #=> #<OAuth2::AccessToken ...>
14
- #
15
- # Then use that access token to create your user object.
16
- #
17
- # u=Bitly::V3::User.new(o.access_token)
18
- class User
19
- include HTTParty
20
- base_uri 'https://api-ssl.bit.ly/v3/'
21
- attr_accessor :login, :api_key
22
-
23
- def initialize(access_token)
24
- @access_token = access_token
25
- @login = access_token['login'] || access_token['username']
26
- @api_key = access_token['apiKey'] || access_token['api_key']
27
- end
28
-
29
- # OAuth 2 endpoint that provides a list of top referrers (up to 500 per
30
- # day) for a given user's bit.ly links, and the number of clicks per referrer.
31
- #
32
- # http://code.google.com/p/bitly-api/wiki/ApiDocumentation#/v3/user/referrers
33
- def referrers(opts={})
34
- if @referrers.nil? || opts.delete(:force)
35
- @referrers = get_method(:referrers, Bitly::V3::Referrer, opts)
36
- end
37
- @referrers
38
- end
39
-
40
- # OAuth 2 endpoint that provides a list of countries from which clicks
41
- # on a given user's bit.ly links are originating, and the number of clicks per country.
42
- #
43
- # http://code.google.com/p/bitly-api/wiki/ApiDocumentation#/v3/user/countries
44
- def countries(opts={})
45
- if @countries.nil? || opts.delete(:force)
46
- @countries = get_method(:countries, Bitly::V3::Country, opts)
47
- end
48
- @countries
49
- end
50
-
51
- # OAuth 2 endpoint that provides a given user's 100 most popular links
52
- # based on click traffic in the past hour, and the number of clicks per link.
53
- #
54
- # http://code.google.com/p/bitly-api/wiki/ApiDocumentation#/v3/user/realtime_links
55
- def realtime_links(opts={})
56
- if @realtime_links.nil? || opts.delete(:force)
57
- opts.merge!(:access_token => @access_token.token)
58
- result = self.class.get("/user/realtime_links", :query => opts)
59
- if result['status_code'] == 200
60
- @realtime_links = result['data']['realtime_links'].map { |rs| Bitly::V3::RealtimeLink.new(rs) }
61
- else
62
- raise BitlyError.new(result['status_txt'], result['status_code'])
63
- end
64
- end
65
- @realtime_links
66
- end
67
-
68
- # OAuth 2 endpoint that provides the total clicks per day on a user's bit.ly links.
69
- #
70
- # http://code.google.com/p/bitly-api/wiki/ApiDocumentation#/v3/user/clicks
71
- def clicks(opts={})
72
- get_clicks(opts)
73
- @clicks
74
- end
75
-
76
- # Displays the total clicks returned from the clicks method.
77
- def total_clicks(opts={})
78
- get_clicks(opts)
79
- @total_clicks
80
- end
81
-
82
- # Returns a Bitly Client using the credentials of the user.
83
- def client
84
- @client ||= Bitly::V3::Client.new(login, api_key)
85
- end
86
-
87
- # OAuth 2 endpoint that provides a given user's link shortening history,
88
- # in reverse chronological order (most recent to least recent).
89
- def link_history(opts={})
90
- opts.merge!(:access_token => @access_token.token)
91
- result = self.class.get("/user/link_history", :query => opts)
92
- if result['status_code'] == 200
93
- results = result['data']['link_history'].inject([]) do |rs, obj|
94
- obj['short_url'] = obj['link']
95
- obj['hash'] = obj['link'].split('/').last
96
- rs << Url.new(client, obj)
97
- end
98
- return results
99
- else
100
- raise BitlyError.new(result['status_txt'], result['status_code'])
101
- end
102
- end
103
-
104
- private
105
-
106
- def get_method(method, klass, opts)
107
- opts.merge!(:access_token => @access_token.token)
108
- result = self.class.get("/user/#{method.to_s}", :query => opts)
109
- if result['status_code'] == 200
110
- result['data'][method.to_s].map do |rs|
111
- rs.inject([]) do |results, obj|
112
- results << klass.new(obj)
113
- end
114
- end
115
- else
116
- raise BitlyError.new(result['status_txt'], result['status_code'])
117
- end
118
- end
119
-
120
- def get_clicks(opts={})
121
- if @clicks.nil? || opts.delete(:force)
122
- opts.merge!(:access_token => @access_token.token)
123
- result = self.class.get("/user/clicks", :query => opts)
124
- if result['status_code'] == 200
125
- @clicks = result['data']['clicks'].map { |rs| Bitly::V3::Day.new(rs) }
126
- @total_clicks = result['data']['total_clicks']
127
- else
128
- raise BitlyError.new(result['status_txt'], result['status_code'])
129
- end
130
- end
131
- end
132
- end
133
- end
134
- end