Class: Skypost::Client

Inherits:
Object
  • Object
show all
Defined in:
lib/skypost/client.rb

Defined Under Namespace

Classes: AuthenticationError, ValidationError

Constant Summary collapse

BASE_URL =
"https://bsky.social"

Instance Method Summary collapse

Constructor Details

#initialize(identifier = nil, password = nil) ⇒ Client

Returns a new instance of Client.



11
12
13
14
15
16
# File 'lib/skypost/client.rb', line 11

def initialize(identifier = nil, password = nil)
  @identifier = identifier
  @password = password
  @session = nil
  validate_identifier if identifier
end

Instance Method Details

#authenticateObject



18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
# File 'lib/skypost/client.rb', line 18

def authenticate
  raise AuthenticationError, "Identifier and password are required" if @identifier.nil? || @password.nil?

  response = connection.post("/xrpc/com.atproto.server.createSession") do |req|
    req.headers["Content-Type"] = "application/json"
    req.body = JSON.generate({
      identifier: @identifier,
      password: @password
    })
  end

  @session = JSON.parse(response.body)
  @session
rescue Faraday::ResourceNotFound => e
  raise AuthenticationError, "Authentication failed: Invalid credentials or incorrect handle format. Your handle should be either your custom domain (e.g., 'username.com') or your Bluesky handle (e.g., 'username.bsky.social')"
rescue Faraday::Error => e
  raise AuthenticationError, "Failed to authenticate: #{e.message}"
end


88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
# File 'lib/skypost/client.rb', line 88

def extract_links(text)
  facets = []
  link_pattern = /<a href="([^"]*)">(.*?)<\/a>/
  
  # First, find all matches to calculate correct byte positions
  matches = text.to_enum(:scan, link_pattern).map { Regexp.last_match }
  plain_text = text.gsub(/<a href="[^"]*">|<\/a>/, '')
  
  matches.each do |match|
    url = match[1]
    link_text = match[2]
    
    # Find the link text in the plain text to get correct byte positions
    if link_position = plain_text.index(link_text)
      facets << {
        index: {
          byteStart: link_position,
          byteEnd: link_position + link_text.bytesize
        },
        features: [{
          "$type": "app.bsky.richtext.facet#link",
          uri: url
        }]
      }
    end
  end

  facets
end

#post(text) ⇒ Object



37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
# File 'lib/skypost/client.rb', line 37

def post(text)
  ensure_authenticated

  current_time = Time.now.utc.strftime("%Y-%m-%dT%H:%M:%S.%3NZ")
  facets = extract_links(text)
  
  request_body = {
    repo: @session["did"],
    collection: "app.bsky.feed.post",
    record: {
      text: text.gsub(/<a href="[^"]*">|<\/a>/, ''),  # Remove HTML tags but keep link text
      facets: facets,
      createdAt: current_time,
      "$type": "app.bsky.feed.post"
    }
  }

  response = connection.post("/xrpc/com.atproto.repo.createRecord") do |req|
    req.headers["Content-Type"] = "application/json"
    req.headers["Authorization"] = "Bearer #{@session["accessJwt"]}"
    req.body = JSON.generate(request_body)
  end

  JSON.parse(response.body)
rescue Faraday::ResourceNotFound => e
  raise "Failed to post: The API endpoint returned 404. Please check if you're authenticated and using the correct API endpoint."
rescue Faraday::Error => e
  raise "Failed to post: #{e.message}"
end