Class: SL::BitlySearch

Inherits:
Object
  • Object
show all
Defined in:
lib/searchlink/searches/bitly.rb

Overview

Bit.ly link shortening

Class Method Summary collapse

Class Method Details

.bitly_shorten(url, title = nil) ⇒ Object



42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
# File 'lib/searchlink/searches/bitly.rb', line 42

def bitly_shorten(url, title = nil)
  unless SL.config.key?("bitly_access_token") && !SL.config["bitly_access_token"].empty?
    SL.add_error("Bit.ly not configured", "Missing access token")
    return [false, title]
  end

  domain = SL.config.key?("bitly_domain") ? SL.config["bitly_domain"] : "bit.ly"
  long_url = url.dup
  curl = TTY::Which.which("curl")
  cmd = [
    %(#{curl} -SsL -H 'Authorization: Bearer #{SL.config['bitly_access_token']}'),
    %(-H 'Content-Type: application/json'),
    "-X POST", %(-d '{ "long_url": "#{url}", "domain": "#{domain}" }'), "https://api-ssl.bitly.com/v4/shorten"
  ]
  data = JSON.parse(`#{cmd.join(" ")}`.strip)
  link = data["link"]
  title ||= SL::URL.title(long_url)
  [link, title]
end

.search(_, search_terms, link_text) ⇒ Object



30
31
32
33
34
35
36
37
38
39
40
# File 'lib/searchlink/searches/bitly.rb', line 30

def search(_, search_terms, link_text)
  if SL::URL.url?(search_terms)
    link = search_terms
  else
    link, rtitle = SL.ddg(search_terms, link_text)
  end

  url, title = bitly_shorten(link, rtitle)
  link_text = title || url
  [url, title, link_text]
end

.settingsObject



7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
# File 'lib/searchlink/searches/bitly.rb', line 7

def settings
  {
    trigger: "b(l|itly)",
    searches: [
      ["bl", "bit.ly Shorten"],
      ["bitly", "bit.ly shorten"]
    ],
    config: [
      {
        key: "bitly_access_token",
        value: "xxxx",
        required: false,
        description: "Generate an access token at https://app.bitly.com/settings/api/"
      },
      {
        key: "bitly_domain",
        value: "bit.ly",
        required: false
      }
    ]
  }
end