Skip to content

Instantly share code, notes, and snippets.

@bachya
Last active August 29, 2015 14:00
Show Gist options
  • Save bachya/11432428 to your computer and use it in GitHub Desktop.
Save bachya/11432428 to your computer and use it in GitHub Desktop.
#!/usr/bin/ruby
# encoding: utf-8
require 'net/http'
require 'net/https'
require 'uri'
require 'cgi'
### Config
# find your bit.ly key at <https://bitly.com/a/settings/advanced>
# under "Legacy API Key"
bitly_username = 'username'
bitly_key = 'xxxxxxxxxxxxx'
# if you have a custom domain, enter it here, otherwise leave blank
bitly_domain = ''
# if you have an iTunes affiliate acount, enter the string
# for `at` and optionally `ct`. Affiliate links are only
# appended to itunes.apple.com urls which don't already contain
# affiliate info
itunes_aff = 'at=10l4tL&ct=bitlyize'
### END CONFIG
$debug = false
if $debug
input = "https://itunes.apple.com/us/app/datalove-stats-tracker/id699097772"
else
if RUBY_VERSION.to_f > 1.9
Encoding.default_external = Encoding::UTF_8
Encoding.default_internal = Encoding::UTF_8
input = STDIN.read.force_encoding('utf-8')
else
input = STDIN.read
end
end
class String
def affiliatize(aff)
return self if aff == ''
if self =~ /^https?:\/\/itunes.apple.com/
return self if self =~ /[&\?]at=\S+/
delim = self =~ /\?\S+?=/ ? "&" : "?"
self.chomp + delim + aff.sub(/^[&\?]/,'')
else
self
end
end
end
class BitlyLink
def initialize(username, apikey)
@username = username
@apikey = apikey
end
def get_long_link(options)
if options.key?('shortURL')
shortURL = options['shortURL']
else
$stderr.puts "No short url provided"
return
end
begin
res = bitly_call('expand', {'shortURL' => shortURL})
return false unless res
json = JSON.parse(res)
p res if $debug
if json['status_code'] == 200
@long = json['data']['expand'][0]['long_url']
else
return false
end
return @long
rescue Exception => e
p e
$stderr.puts "Error expanding link"
return false
end
end
def get_short_link(options)
if options.key?('domain')
@domain = options['domain']
end
if options.key?('url')
@url = options['url'].affiliatize(options['itunes_aff'])
else
$stderr.puts "No url provided"
end
begin
res = bitly_call('shorten', {'longUrl' => @url, 'domain' => @domain})
return false unless res
json = JSON.parse(res)
p json
if json['status_code'] == 200
@short = json['data']['url']
else
return false
end
return @short
rescue Exception => e
p e
$stderr.puts "Error shortening link"
return false
end
end
def bitly_call(method, data = {})
begin
path = "/v3/#{method}"
res = nil
http = Net::HTTP.new('api-ssl.bitly.com', 443)
http.use_ssl = true
http.verify_mode = OpenSSL::SSL::VERIFY_NONE
http.start do |http|
request = Net::HTTP::Get.new(path+create_query(data))
res = http.request(request).body
end
return false if res.nil?
p res if $debug
return res
rescue Exception => e
p e
return false
end
end
def create_query(data = {})
components = []
data['login'] = @username
data['apiKey'] = @apikey
data.each {|k,v|
components.push("#{k}=#{CGI.escape(v)}")
}
"?" + components.join("&")
end
end
#
## Stupid small pure Ruby JSON parser & generator.
#
# Copyright © 2013 Mislav Marohnić
#
# Permission is hereby granted, free of charge, to any person obtaining a copy of this
# software and associated documentation files (the “Software”), to deal in the Software
# without restriction, including without limitation the rights to use, copy, modify,
# merge, publish, distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to the following
# conditions:
#
# The above copyright notice and this permission notice shall be included in all copies or
# substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
# INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
# PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT
# OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
# OTHER DEALINGS IN THE SOFTWARE.
require 'strscan'
require 'forwardable'
# Usage:
#
# JSON.parse(json_string) => Array/Hash
# JSON.generate(object) => json string
#
# Run tests by executing this file directly. Pipe standard input to the script to have it
# parsed as JSON and to display the result in Ruby.
#
class JSON
def self.parse(data) new(data).parse end
WSP = /\s+/
OBJ = /[{\[]/; HEN = /\}/; AEN = /\]/
COL = /\s*:\s*/; KEY = /\s*,\s*/
NUM = /-?\d+(?:\.\d+)?(?:[eE][+-]?\d+)?/
BOL = /true|false/; NUL = /null/
extend Forwardable
attr_reader :scanner
alias_method :s, :scanner
def_delegators :scanner, :scan, :matched
private :s, :scan, :matched
def initialize data
@scanner = StringScanner.new data.to_s
end
def parse
space
object
end
private
def space() scan WSP end
def endkey() scan(KEY) or space end
def object
matched == '{' ? hash : array if scan(OBJ)
end
def value
object or string or
scan(NUL) ? nil :
scan(BOL) ? matched.size == 4:
scan(NUM) ? eval(matched) :
error
end
def hash
obj = {}
space
repeat_until(HEN) { k = string; scan(COL); obj[k] = value; endkey }
obj
end
def array
ary = []
space
repeat_until(AEN) { ary << value; endkey }
ary
end
SPEC = {'b' => "\b", 'f' => "\f", 'n' => "\n", 'r' => "\r", 't' => "\t"}
UNI = 'u'; CODE = /[a-fA-F0-9]{4}/
STR = /"/; STE = '"'
ESC = '\\'
def string
if scan(STR)
str, esc = '', false
while c = s.getch
if esc
str << (c == UNI ? (s.scan(CODE) || error).to_i(16).chr : SPEC[c] || c)
esc = false
else
case c
when ESC then esc = true
when STE then break
else str << c
end
end
end
str
end
end
def error
raise "parse error at: #{scan(/.{1,10}/m).inspect}"
end
def repeat_until reg
until scan(reg)
pos = s.pos
yield
error unless s.pos > pos
end
end
module Generator
def generate(obj)
raise ArgumentError unless obj.is_a? Array or obj.is_a? Hash
generate_type(obj)
end
alias dump generate
private
def generate_type(obj)
type = obj.is_a?(Numeric) ? :Numeric : obj.class.name
begin send(:"generate_#{type}", obj)
rescue NoMethodError; raise ArgumentError, "can't serialize #{type}"
end
end
ESC_MAP = Hash.new {|h,k| k }.update \
"\r" => 'r',
"\n" => 'n',
"\f" => 'f',
"\t" => 't',
"\b" => 'b'
def quote(str) %("#{str}") end
def generate_String(str)
quote str.gsub(/[\r\n\f\t\b"\\]/) { "\\#{ESC_MAP[$&]}"}
end
def generate_simple(obj) obj.inspect end
alias generate_Numeric generate_simple
alias generate_TrueClass generate_simple
alias generate_FalseClass generate_simple
def generate_Symbol(sym) generate_String(sym.to_s) end
def generate_Time(time)
quote time.strftime(time.utc? ? "%F %T UTC" : "%F %T %z")
end
def generate_Date(date) quote date.to_s end
def generate_NilClass(*) 'null' end
def generate_Array(ary) '[%s]' % ary.map {|o| generate_type(o) }.join(', ') end
def generate_Hash(hash)
'{%s}' % hash.map { |key, value|
"#{generate_String(key.to_s)}: #{generate_type(value)}"
}.join(', ')
end
end
extend Generator
end
bl = BitlyLink.new(bitly_username, bitly_key)
input.gsub!(/((?:http|https):\/\/[\w\-_]+(?:\.[\w\-_]+)+(?:[\w\-\.,@?^=%&amp;:\/~\+#]*[\w\-\@^=%&amp;\/~\+#])?)/).each {|url|
bl.get_short_link({'url' => url, 'domain' => bitly_domain, 'itunes_aff' => itunes_aff})
}
print input
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment