File: bitly.rb

package info (click to toggle)
tdiary-contrib 5.4.0-1
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 2,772 kB
  • sloc: ruby: 17,305; javascript: 8,263; lisp: 562; xml: 451; php: 61; sql: 40; makefile: 18
file content (39 lines) | stat: -rw-r--r-- 1,099 bytes parent folder | download | duplicates (6)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
#
# bitly.rb - shorten URL by bit.ly.
#
# usage: shorten_url_you_got = bitly( 'long_url' ) || long_url
#        (because bitly returns nil sometime.)
#
# required some options below:
#    @options['biyly.login'] : your login ID of bit.ly.
#    @options['biyly.key']   : your API key of biy.ly.
#
# Copyright (C) 2010, TADA Tadashi <t@tdtds.jp>
# You can redistribute it and/or modify it under GPL.
#

require 'json'
require 'net/http'

def bitly( long_url )
	return nil if !long_url or long_url.empty?

	@bitly_cache ||= {} # cached only on memory
	return @bitly_cache[long_url] if @bitly_cache[long_url]

	login = @conf['bitly.login']
	key = @conf['bitly.key']

	# proxy
	px_host, px_port = (@conf['proxy'] || '').split( /:/ )
	px_port = 80 if px_host and !px_port

	query = "/v3/shorten?longUrl=#{CGI::escape long_url}&login=#{login}&apiKey=#{key}&format=json"
	begin
		Net::HTTP.version_1_2
		res = Net::HTTP::Proxy(px_host, px_port).get('api.bit.ly', "#{query}")
		@bitly_cache[long_url] = JSON::parse(res, &:read)['data']['url']
	rescue TypeError => te# biy.ly returns an error.
		nil
	end
end