Module: PandaPal::Platform::Canvas::OrgExtension

Extended by:
ActiveSupport::Concern
Defined in:
app/models/panda_pal/platform/canvas.rb

Instance Method Summary collapse

Instance Method Details

#_ensure_lti_v1p3_key(exists:, host:) ⇒ Object



150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
# File 'app/models/panda_pal/platform/canvas.rb', line 150

def _ensure_lti_v1p3_key(exists:, host:)
  current_client_id = self.key.split('/')[0]

  existing_keys = []
  existing_keys += bearcat_client.get("api/v1/accounts/self/developer_keys?per_page=100").filter do |devkey|
    devkey[:id].to_s == current_client_id
  end
  existing_keys += bearcat_client.get("api/v1/accounts/self/developer_keys?per_page=100", inherited: true).filter do |devkey|
    devkey[:id].to_s == current_client_id
  end

  ekey = existing_keys[0]

  lti_json_url = PandaPal::LaunchUrlHelpers.resolve_route(:v1p3_config_url, host: host)
  lti_json = JSON.parse(HTTParty.get(lti_json_url, format: :plain).body)

  valid_redirect_uris = [
    lti_json["target_link_uri"]
  ]

  prod_domain = PandaPal.lti_environments[:domain]
  if prod_domain.present?
    PandaPal.lti_environments.each do |env, domain|
      env = env.to_s
      next unless env.ends_with?("_domain")
      env = env.split('_')[0]
      valid_redirect_uris << lti_json["target_link_uri"].gsub(prod_domain, domain)
    end
  end

  valid_redirect_uris.uniq!

  if !ekey
    # Create New
    ekey = bearcat_client.post("api/lti/accounts/self/developer_keys/tool_configuration", {
      developer_key: {
        name: PandaPal.lti_options[:title],
        redirect_uris: valid_redirect_uris.join("\n"),
      },
      tool_configuration: {
        settings: lti_json,
      },
    })
  elsif exists == :replace || exists == :update
    # Update Existing
    ekey = bearcat_client.put("api/lti/developer_keys/#{ekey[:id]}/tool_configuration", {
      developer_key: {
        redirect_uris: valid_redirect_uris.join("\n"),
      },
      # tool_configuration: lti_json,
      tool_configuration: {
        settings: lti_json,
      },
    })
  end

  ekey = ekey[:developer_key] || ekey

  if ekey[:developer_key_account_binding][:workflow_state] == "off"
    bearcat_client.post("api/v1/accounts/self/developer_keys/#{ekey[:id]}/developer_key_account_bindings", {
      developer_key_account_binding: {
        workflow_state: "on",
      },
    })
  end

  ekey
end

#_find_existing_installs(context, exists: nil, &matcher) ⇒ Object



219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
# File 'app/models/panda_pal/platform/canvas.rb', line 219

def _find_existing_installs(context, exists: nil, &matcher)
  ctype, cid = _parse_lti_context(context)

  existing_installs = bearcat_client.send(:"#{ctype}_external_tools", cid).all_pages_each.filter do |cet|
    matcher.call(cet)
  end

  if exists.present? && existing_installs.present?
    case exists
    when :error
      raise "Tool with key #{self.key} already installed"
    when :duplicate
      []
    when :replace
      existing_installs.each do |install|
        bearcat_client.send(:"delete_#{ctype}_external_tool", cid, install[:id])
      end
      []
    when :update
      existing_installs
    else
      raise "exists: #{exists} is not supported"
    end
  else
    existing_installs
  end
end

#_install_lti(host: nil, context: :root_account, version: nil, exists: :error, dedicated_deployment: false) ⇒ Object



77
78
79
80
81
82
83
84
85
86
87
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
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
# File 'app/models/panda_pal/platform/canvas.rb', line 77

def _install_lti(host: nil, context: :root_account, version: nil, exists: :error, dedicated_deployment: false)
  raise "Automatically installing this LTI requires Bearcat." unless defined?(Bearcat)

  version = version || PandaPal.lti_options[:lti_spec_version] || 'v1p3'
  version = version.to_s

  if (vs = version.split(".")).count > 1
    version = "v#{vs[0]}p#{vs[0]}"
  end

  # TODO Ensure host is actually this LTI

  run_callbacks :lti_install do
    ctype, cid = _parse_lti_context(context)

    if version == 'v1p0'
      existing_installs = _find_existing_installs(context, exists: exists) do |lti|
        lti[:consumer_key] == self.key
      end

      conf = {
        name: PandaPal.lti_options[:title],
        description: PandaPal.lti_options[:description],
        consumer_key: self.key,
        shared_secret: self.secret,
        privacy_level: "public",
        config_type: 'by_url',
        config_url: PandaPal::LaunchUrlHelpers.resolve_route(:v1p0_config_url, host: host),
      }

      api_result = existing_installs[0] ? bearcat_client.send(:"edit_#{ctype}_external_tool", cid, existing_installs[0][:id], conf) : bearcat_client.send(:"create_#{ctype}_external_tool", cid, conf)

      @new_lti_installation = api_result
    elsif version == 'v1p3'
      ekey = _ensure_lti_v1p3_key(exists: exists, host: host)

      existing_installs = _find_existing_installs(context, exists: exists) do |lti|
        # TODO This may not be correct when actually inheriting LTI keys
        lti[:developer_key_id] == (ekey[:id] % 10_000_000_000_000)
      end

      scope_tool = existing_installs[0]

      # Don't need to do an update if it already exists - Settings are stored on the LTI Key instead of the installation
      unless scope_tool
        scope_tool = bearcat_client.send(:"create_#{ctype}_external_tool", cid, {
          client_id: ekey[:id],
        })

        new_client_id = "#{ekey[:id]}"
        new_client_id += "/#{scope_tool[:deployment_id]}" if dedicated_deployment

        self.key = new_client_id
        self.secret = ekey[:api_key]

        save! if changed?
      end

      @new_lti_installation = scope_tool
    else
      raise "Unrecognized LTI Version #{version}"
    end
  end

  save!
end

#_parse_lti_context(context) ⇒ Object



68
69
70
71
72
73
74
75
# File 'app/models/panda_pal/platform/canvas.rb', line 68

def _parse_lti_context(context)
  context = context.to_s
  context = 'account/self' if context == 'root_account'
  cid, ctype = context.split(/[\.\/]/).reverse
  ctype ||= 'account'

  [ctype, cid]
end

#bearcat_clientObject



330
331
332
333
334
335
336
337
338
# File 'app/models/panda_pal/platform/canvas.rb', line 330

def bearcat_client
  # Less than ideal, but `canvas_sync_client` has been the long-adopted tradition so we check for it so that we can continue to drop-in new versions of PandaPal
  return canvas_sync_client if defined?(canvas_sync_client)

  Bearcat::Client.new(
    prefix: canvas_url,
    token: canvas_api_token,
  )
end

#canvas_api_tokenObject



310
311
312
313
314
315
316
317
318
319
# File 'app/models/panda_pal/platform/canvas.rb', line 310

def canvas_api_token
  PandaPal::Platform.find_org_setting([
    "canvas.api_token",
    "canvas.api_key",
    "canvas.token",
    "canvas_api_token",
    "canvas_token",
    "api_token",
  ], self)
end

#canvas_urlObject



300
301
302
303
304
305
306
307
308
# File 'app/models/panda_pal/platform/canvas.rb', line 300

def canvas_url
  PandaPal::Platform.find_org_setting([
    "canvas.base_url",
    "canvas_url",
    "canvas_base_url",
    "canvas.url",
    "base_url",
  ], self) || (Rails.env.development? && 'http://localhost:3000') || 'https://canvas.instructure.com'
end

#install_lti(*args, **kwargs) ⇒ Object



144
145
146
147
148
# File 'app/models/panda_pal/platform/canvas.rb', line 144

def install_lti(*args, **kwargs)
  switch_tenant do
    _install_lti(*args, **kwargs)
  end
end

#lti_api_configuration(host: nil) ⇒ Object



251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
# File 'app/models/panda_pal/platform/canvas.rb', line 251

def lti_api_configuration(host: nil)
  PandaPal::LaunchUrlHelpers.with_uri_host(host) do
    domain = PandaPal.lti_properties[:domain] || host.host
    launch_url = PandaPal.lti_options[:secure_launch_url] ||
      "#{domain}#{PandaPal.lti_options[:secure_launch_path]}" ||
      PandaPal.lti_options[:launch_url] ||
      "#{domain}#{PandaPal.lti_options[:launch_path]}" ||
      domain

    lti_json = {
      name: PandaPal.lti_options[:title],
      description: PandaPal.lti_options[:description],
      domain: host.host,
      url: launch_url,
      consumer_key: self.key,
      shared_secret: self.secret,
      privacy_level: "public",

      custom_fields: {},

      environments: PandaPal.lti_environments,
    }

    lti_json = lti_json.with_indifferent_access
    lti_json.merge!(PandaPal.lti_properties)

    (PandaPal.lti_options[:custom_fields] || []).each do |k, v|
      lti_json[:custom_fields][k] = v
    end

    PandaPal.lti_paths.each do |k, options|
      options = PandaPal::LaunchUrlHelpers.normalize_lti_launch_desc(options)
      options[:url] = PandaPal::LaunchUrlHelpers.absolute_launch_url(
        k.to_sym,
        host: host,
        launch_handler: :v1p0_launch_path,
        default_auto_launch: false
      ).to_s
      lti_json[k] = options
    end

    lti_json
  end
end

#lti_installations(context = :root_account) ⇒ Object



296
297
298
# File 'app/models/panda_pal/platform/canvas.rb', line 296

def lti_installations(context= :root_account)
  _find_existing_installs(context)
end

#reinstall_lti!(*args, **kwargs) ⇒ Object



247
248
249
# File 'app/models/panda_pal/platform/canvas.rb', line 247

def reinstall_lti!(*args, **kwargs)
  install_lti(*args, exists: :replace, **kwargs)
end

#root_account_infoObject



321
322
323
324
325
326
327
# File 'app/models/panda_pal/platform/canvas.rb', line 321

def 
  Rails.cache.fetch("panda_pal/org:#{name}/root_account_info", expires_in: 24.hours) do
    response = bearcat_client.("self")
    response = bearcat_client.(response[:root_account_id]) if response[:root_account_id].present?
    response
  end
end