Class: Effective::LearndashApi

Inherits:
Object
  • Object
show all
Defined in:
app/models/effective/learndash_api.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(url:, username:, password:) ⇒ LearndashApi

Returns a new instance of LearndashApi.



10
11
12
13
14
# File 'app/models/effective/learndash_api.rb', line 10

def initialize(url:, username:, password:)
  @url = url
  @username = username
  @password = password
end

Instance Attribute Details

#password ⇒ Object

Returns the value of attribute password.



8
9
10
# File 'app/models/effective/learndash_api.rb', line 8

def password
  @password
end

#url ⇒ Object

Returns the value of attribute url.



6
7
8
# File 'app/models/effective/learndash_api.rb', line 6

def url
  @url
end

#username ⇒ Object

Returns the value of attribute username.



7
8
9
# File 'app/models/effective/learndash_api.rb', line 7

def username
  @username
end

Instance Method Details

#api_url ⇒ Object



242
243
244
# File 'app/models/effective/learndash_api.rb', line 242

def api_url
  url.chomp('/') + '/wp-json'
end

#course_id(resource) ⇒ Object



137
138
139
140
141
142
143
144
145
# File 'app/models/effective/learndash_api.rb', line 137

def course_id(resource)
  if resource.kind_of?(LearndashCourse)
    resource.course_id
  elsif resource.kind_of?(LearndashEnrollment)
    resource.learndash_course&.course_id
  else
    resource
  end
end

#courses ⇒ Object

List Courses



80
81
82
# File 'app/models/effective/learndash_api.rb', line 80

def courses
  get('/ldlms/v2/sfwd-courses')
end

#create_enrollment(enrollment) ⇒ Object



96
97
98
# File 'app/models/effective/learndash_api.rb', line 96

def create_enrollment(enrollment)
  create_user_course(enrollment.learndash_user, enrollment.learndash_course)
end

#create_user(owner) ⇒ Object

Create User Usernames can only contain lowercase letters (a-z) and numbers.



57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
# File 'app/models/effective/learndash_api.rb', line 57

def create_user(owner)
  raise ('expected a leardash owner') unless owner.class.respond_to?(:effective_learndash_owner?)
  raise('owner must have an email') unless owner.try(:email).present?

  username = username_for(owner)
  password = password_for(owner)

  payload = {
    username: username,
    password: password,

    name: owner.to_s,
    email: owner.email,
    roles: ['subscriber'],

    first_name: owner.try(:first_name),
    last_name: owner.try(:last_name)
  }.compact

  post("/wp/v2/users", payload.stringify_keys).merge(password: password)
end

#create_user_course(user, course) ⇒ Object

Crete Course User



109
110
111
112
113
114
115
116
117
118
119
120
# File 'app/models/effective/learndash_api.rb', line 109

def create_user_course(user, course)
  user = user_id(user) || raise('expected a user')
  course = course_id(course) || raise('expected a course')

  response = post("/ldlms/v2/sfwd-courses/#{course}/users", user_ids: [user])

  unless (response.first.fetch(:code) rescue nil) == 'learndash_rest_enroll_success'
    raise("unsuccessful course creation: #{response}")
  end

  find_user_course(user, course)
end

#find(endpoint, params = nil) ⇒ Object



160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
# File 'app/models/effective/learndash_api.rb', line 160

def find(endpoint, params = nil)
  response = get(endpoint, params)

  if response == false
    nil
  elsif response.kind_of?(Hash) && response.dig(:data, :status) == 404
    nil
  elsif response.kind_of?(Hash)
    response
  elsif response.kind_of?(Array)
    response.first
  else
    raise("unexpected Learndash API response #{response}")
  end
end

#find_by(endpoint, key, value) ⇒ Object

We can't just like, find by email, so we gotta search then filter on our side



177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
# File 'app/models/effective/learndash_api.rb', line 177

def find_by(endpoint, key, value)
  raise('expected a symbol key') unless key.kind_of?(Symbol)
  raise('expected a value') unless value.present?

  response = get(endpoint, { search: value, context: :edit })

  collection = Array(
    if response == false
      nil
    elsif response.kind_of?(Hash) && response.dig(:data, :status) == 404
      nil
    elsif response.kind_of?(Hash)
      response
    elsif response.kind_of?(Array)
      response
    else
      raise("unexpected Learndash API find_by response #{response}")
    end
  )

  resource = collection.find { |data| data[key] == value }
  resource
end

#find_enrollment(enrollment) ⇒ Object

Helper methods for enrollments



92
93
94
# File 'app/models/effective/learndash_api.rb', line 92

def find_enrollment(enrollment)
  find_user_course(enrollment.learndash_user, enrollment.learndash_course)
end

#find_user(value) ⇒ Object

Returns a WP Hash of User or nil This find by EMAIL doesn't work reliably



30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
# File 'app/models/effective/learndash_api.rb', line 30

def find_user(value)
  # Find by email
  if value.kind_of?(String) && value.include?('@')
    return find_by("/wp/v2/users", :email, value)
  end

  # Fetch by saved param value
  user_id = user_id(value)
  user = find("/wp/v2/users/#{user_id}", context: :edit) if user_id
  return user if user.present?

  # Find by email
  email = value.try(:email)
  user = find_by("/wp/v2/users", :email, email) if email
  return user if user.present?

  # Find by username
  username = username_for(value) if value.class.respond_to?(:effective_learndash_owner?)
  user = find_by("/wp/v2/users", :username, username) if username
  return user if user.present?

  # Otherwise none
  nil
end

#find_user_course(user, course) ⇒ Object

Find User Course Progress



101
102
103
104
105
106
# File 'app/models/effective/learndash_api.rb', line 101

def find_user_course(user, course)
  user = user_id(user) || raise('expected a user')
  course = course_id(course) || raise('expected a course')

  find("/ldlms/v2/users/#{user}/course-progress/#{course}")
end

#get(endpoint, params = nil) ⇒ Object



201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
# File 'app/models/effective/learndash_api.rb', line 201

def get(endpoint, params = nil)
  query = ('?' + params.compact.map { |k, v| "#{k}=#{v}" }.join('&')) if params.present?

  uri = URI.parse(api_url + endpoint + query.to_s)

  http = Net::HTTP.new(uri.host, uri.port)
  http.use_ssl = (uri.scheme == 'https')
  http.read_timeout = 10

  response = with_retries do
    puts("[GET] #{uri}") if Rails.env.development?
    http.get(uri, headers)
  end

  unless response.code.start_with?('2')
    puts("Response code: #{response.code} #{response.body}") if Rails.env.development?
    return false
  end

  JSON.parse(response.body, symbolize_names: true)
end

#headers ⇒ Object



246
247
248
249
250
251
252
# File 'app/models/effective/learndash_api.rb', line 246

def headers
  {
    'Authorization': "Basic #{Base64.strict_encode64("#{username}:#{password}")}",
    'Accept': 'application/json',
    'Content-Type': 'application/json'
  }
end

#me ⇒ Object



19
20
21
# File 'app/models/effective/learndash_api.rb', line 19

def me
  get('/wp/v2/users/me')
end

#password_for(resource) ⇒ Object



155
156
157
158
# File 'app/models/effective/learndash_api.rb', line 155

def password_for(resource)
  raise('expected a learndash owner') unless resource.class.respond_to?(:effective_learndash_owner?) # This is a user
  EffectiveLearndash.wp_password_for(resource)
end

#post(endpoint, params = nil) ⇒ Object



223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
# File 'app/models/effective/learndash_api.rb', line 223

def post(endpoint, params = nil)
  uri = URI.parse(api_url + endpoint)

  http = Net::HTTP.new(uri.host, uri.port)
  http.use_ssl = (uri.scheme == 'https')
  http.read_timeout = 10

  response = with_retries do
    puts("[POST] #{uri} #{params}") if Rails.env.development?
    http.post(uri.path, (params || {}).to_json, headers)
  end

  unless response.code.start_with?('2')
    raise("Invalid Learndash API request: #{response.body}")
  end

  JSON.parse(response.body, symbolize_names: true)
end

#user_enrollments(user) ⇒ Object

List User Course Progress



85
86
87
88
89
# File 'app/models/effective/learndash_api.rb', line 85

def user_enrollments(user)
  user = user_id(user) || raise('expected a user')

  get("/ldlms/v2/users/#{user}/course-progress")
end

#user_id(resource) ⇒ Object



125
126
127
128
129
130
131
132
133
134
135
# File 'app/models/effective/learndash_api.rb', line 125

def user_id(resource)
  if resource.class.respond_to?(:effective_learndash_owner?) # This is a user
    resource.learndash_user&.user_id
  elsif resource.kind_of?(LearndashEnrollment)
    resource.learndash_user&.user_id
  elsif resource.kind_of?(LearndashUser)
    resource.user_id
  else
    resource
  end
end

#username_for(resource) ⇒ Object



147
148
149
150
151
152
153
# File 'app/models/effective/learndash_api.rb', line 147

def username_for(resource)
  raise('expected a learndash owner') unless resource.class.respond_to?(:effective_learndash_owner?) # This is a user

  name = EffectiveLearndash.wp_username_for(resource)
  name = "test#{name}" unless Rails.env.production?
  name
end

#users ⇒ Object

List users



24
25
26
# File 'app/models/effective/learndash_api.rb', line 24

def users
  get('/wp/v2/users')
end

#with_retries(retries: 3, wait: 2, &block) ⇒ Object



254
255
256
257
258
259
260
261
262
263
264
265
266
# File 'app/models/effective/learndash_api.rb', line 254

def with_retries(retries: 3, wait: 2, &block)
  raise('expected a block') unless block_given?

  begin
    return yield
  rescue Exception => e
    if (retries -= 1) > 0
      sleep(wait); retry
    else
      raise
    end
  end
end