2011-05-13 05:48:18 +08:00
|
|
|
#
|
2013-12-21 13:58:04 +08:00
|
|
|
# Copyright (C) 2011 - 2013 Instructure, Inc.
|
2011-05-13 05:48:18 +08:00
|
|
|
#
|
|
|
|
# This file is part of Canvas.
|
|
|
|
#
|
|
|
|
# Canvas is free software: you can redistribute it and/or modify it under
|
|
|
|
# the terms of the GNU Affero General Public License as published by the Free
|
|
|
|
# Software Foundation, version 3 of the License.
|
|
|
|
#
|
|
|
|
# Canvas is distributed in the hope that it will be useful, but WITHOUT ANY
|
|
|
|
# WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
|
|
|
|
# A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
|
|
|
|
# details.
|
|
|
|
#
|
|
|
|
# You should have received a copy of the GNU Affero General Public License along
|
|
|
|
# with this program. If not, see <http://www.gnu.org/licenses/>.
|
|
|
|
#
|
|
|
|
|
|
|
|
module Api
|
2011-09-13 23:21:00 +08:00
|
|
|
# find id in collection, by either id or sis_*_id
|
|
|
|
# if the collection is over the users table, `self` is replaced by @current_user.id
|
2013-12-21 13:58:04 +08:00
|
|
|
def api_find(collection, id, options = {account: nil})
|
|
|
|
options = options.merge limit: 1
|
|
|
|
api_find_all(collection, [id], options).first || raise(ActiveRecord::RecordNotFound, "Couldn't find #{collection.name} with API id '#{id}'")
|
2011-11-15 04:29:30 +08:00
|
|
|
end
|
2011-05-13 05:48:18 +08:00
|
|
|
|
2013-12-21 13:58:04 +08:00
|
|
|
def api_find_all(collection, ids, options = { limit: nil, account: nil })
|
2011-11-15 04:29:30 +08:00
|
|
|
if collection.table_name == User.table_name && @current_user
|
|
|
|
ids = ids.map{|id| id == 'self' ? @current_user.id : id }
|
2011-09-13 23:21:00 +08:00
|
|
|
end
|
2012-10-20 04:25:17 +08:00
|
|
|
if collection.table_name == Account.table_name
|
|
|
|
ids = ids.map do |id|
|
|
|
|
case id
|
|
|
|
when 'self'
|
|
|
|
@domain_root_account.id
|
|
|
|
when 'default'
|
|
|
|
Account.default.id
|
|
|
|
when 'site_admin'
|
|
|
|
Account.site_admin.id
|
|
|
|
else
|
|
|
|
id
|
|
|
|
end
|
|
|
|
end
|
|
|
|
end
|
2014-02-12 07:46:44 +08:00
|
|
|
if collection.table_name == EnrollmentTerm.table_name
|
|
|
|
current_term = nil
|
|
|
|
ids = ids.map do |id|
|
|
|
|
case id
|
|
|
|
when 'default'
|
|
|
|
@domain_root_account.default_enrollment_term
|
|
|
|
when 'current'
|
|
|
|
if !current_term
|
|
|
|
current_terms = @domain_root_account.enrollment_terms.active.
|
|
|
|
where("(start_at<=? OR start_at IS NULL) AND (end_at >=? OR end_at IS NULL) AND NOT (start_at IS NULL AND end_at IS NULL)", Time.now.utc, Time.now.utc).
|
|
|
|
limit(2).to_a
|
|
|
|
current_term = current_terms.length == 1 ? current_terms.first : :nil
|
|
|
|
end
|
|
|
|
current_term == :nil ? nil : current_term
|
|
|
|
else
|
|
|
|
id
|
|
|
|
end
|
|
|
|
end
|
|
|
|
end
|
2011-11-15 04:29:30 +08:00
|
|
|
|
2013-12-21 13:58:04 +08:00
|
|
|
find_params = Api.sis_find_params_for_collection(collection, ids, options[:account] || @domain_root_account)
|
2012-10-20 04:25:17 +08:00
|
|
|
return [] if find_params == :not_found
|
2013-12-21 13:58:04 +08:00
|
|
|
find_params[:limit] = options[:limit] unless options[:limit].nil?
|
2011-11-15 04:29:30 +08:00
|
|
|
return collection.all(find_params)
|
2011-05-13 05:48:18 +08:00
|
|
|
end
|
|
|
|
|
|
|
|
# map a list of ids and/or sis ids to plain ids.
|
2011-10-05 00:31:34 +08:00
|
|
|
# sis ids that can't be found in the db won't appear in the result, however
|
|
|
|
# AR object ids aren't verified to exist in the db so they'll still be
|
|
|
|
# returned in the result.
|
2011-11-15 04:29:30 +08:00
|
|
|
def self.map_ids(ids, collection, root_account)
|
|
|
|
sis_mapping = sis_find_sis_mapping_for_collection(collection)
|
|
|
|
columns = sis_parse_ids(ids, sis_mapping[:lookups])
|
|
|
|
result = columns.delete(sis_mapping[:lookups]["id"]) || []
|
|
|
|
unless columns.empty?
|
|
|
|
find_params = sis_make_params_for_sis_mapping_and_columns(columns, sis_mapping, root_account)
|
2012-10-20 04:25:17 +08:00
|
|
|
return result if find_params == :not_found
|
2013-04-26 04:09:12 +08:00
|
|
|
# pluck ignores include
|
|
|
|
find_params[:joins] = find_params.delete(:include) if find_params[:include]
|
2013-03-08 07:23:32 +08:00
|
|
|
result.concat collection.scoped(find_params).pluck(:id)
|
2011-11-15 04:29:30 +08:00
|
|
|
result.uniq!
|
2011-10-05 00:31:34 +08:00
|
|
|
end
|
|
|
|
result
|
2011-05-13 05:48:18 +08:00
|
|
|
end
|
|
|
|
|
2011-11-10 00:50:16 +08:00
|
|
|
SIS_MAPPINGS = {
|
2011-10-26 23:06:14 +08:00
|
|
|
'courses' =>
|
2011-11-15 04:29:30 +08:00
|
|
|
{ :lookups => { 'sis_course_id' => 'sis_source_id', 'id' => 'id' },
|
|
|
|
:is_not_scoped_to_account => ['id'].to_set,
|
|
|
|
:scope => 'root_account_id' },
|
2011-10-26 23:06:14 +08:00
|
|
|
'enrollment_terms' =>
|
2011-11-15 04:29:30 +08:00
|
|
|
{ :lookups => { 'sis_term_id' => 'sis_source_id', 'id' => 'id' },
|
|
|
|
:is_not_scoped_to_account => ['id'].to_set,
|
|
|
|
:scope => 'root_account_id' },
|
2011-10-26 23:06:14 +08:00
|
|
|
'users' =>
|
2011-11-15 04:29:30 +08:00
|
|
|
{ :lookups => { 'sis_user_id' => 'pseudonyms.sis_user_id', 'sis_login_id' => 'pseudonyms.unique_id', 'id' => 'users.id' },
|
|
|
|
:is_not_scoped_to_account => ['users.id'].to_set,
|
|
|
|
:scope => 'pseudonyms.account_id',
|
|
|
|
:joins => [:pseudonym] },
|
2011-10-26 23:06:14 +08:00
|
|
|
'accounts' =>
|
2011-11-15 04:29:30 +08:00
|
|
|
{ :lookups => { 'sis_account_id' => 'sis_source_id', 'id' => 'id' },
|
|
|
|
:is_not_scoped_to_account => ['id'].to_set,
|
|
|
|
:scope => 'root_account_id' },
|
2011-10-26 23:06:14 +08:00
|
|
|
'course_sections' =>
|
2011-11-15 04:29:30 +08:00
|
|
|
{ :lookups => { 'sis_section_id' => 'sis_source_id', 'id' => 'id' },
|
|
|
|
:is_not_scoped_to_account => ['id'].to_set,
|
|
|
|
:scope => 'root_account_id' },
|
2013-06-20 11:38:00 +08:00
|
|
|
'groups' =>
|
|
|
|
{ :lookups => { 'sis_group_id' => 'sis_source_id', 'id' => 'id' },
|
|
|
|
:is_not_scoped_to_account => ['id'].to_set,
|
|
|
|
:scope => 'root_account_id' },
|
2011-11-10 00:50:16 +08:00
|
|
|
}.freeze
|
2011-09-13 23:21:00 +08:00
|
|
|
|
2013-06-18 06:08:36 +08:00
|
|
|
# (digits in 2**63-1) - 1, so that any ID representable in MAX_ID_LENGTH
|
|
|
|
# digits is < 2**63, which is the max signed 64-bit integer, which is what's
|
|
|
|
# used for the DB ids.
|
|
|
|
MAX_ID_LENGTH = 18
|
|
|
|
ID_REGEX = %r{\A\d{1,#{MAX_ID_LENGTH}}\z}
|
2012-10-20 04:25:17 +08:00
|
|
|
|
2011-11-15 04:29:30 +08:00
|
|
|
def self.sis_parse_id(id, lookups)
|
|
|
|
# returns column_name, column_value
|
2014-01-10 02:56:07 +08:00
|
|
|
return lookups['id'], id if id.is_a?(Numeric) || id.is_a?(ActiveRecord::Base)
|
2011-11-15 04:29:30 +08:00
|
|
|
id = id.to_s.strip
|
|
|
|
if id =~ %r{\Ahex:(sis_[\w_]+):(([0-9A-Fa-f]{2})+)\z}
|
|
|
|
sis_column = $1
|
|
|
|
sis_id = [$2].pack('H*')
|
|
|
|
elsif id =~ %r{\A(sis_[\w_]+):(.+)\z}
|
|
|
|
sis_column = $1
|
|
|
|
sis_id = $2
|
2012-10-20 04:25:17 +08:00
|
|
|
elsif id =~ ID_REGEX
|
|
|
|
return lookups['id'], (id =~ /\A\d+\z/ ? id.to_i : id)
|
2011-05-13 05:48:18 +08:00
|
|
|
else
|
2011-11-15 04:29:30 +08:00
|
|
|
return nil, nil
|
|
|
|
end
|
|
|
|
|
|
|
|
column = lookups[sis_column]
|
|
|
|
return nil, nil unless column
|
|
|
|
return column, sis_id
|
|
|
|
end
|
2011-05-13 05:48:18 +08:00
|
|
|
|
2011-11-15 04:29:30 +08:00
|
|
|
def self.sis_parse_ids(ids, lookups)
|
|
|
|
# returns {column_name => [column_value,...].uniq, ...}
|
|
|
|
columns = {}
|
|
|
|
ids.compact.each do |id|
|
|
|
|
column, sis_id = sis_parse_id(id, lookups)
|
|
|
|
next unless column && sis_id
|
|
|
|
columns[column] ||= []
|
|
|
|
columns[column] << sis_id
|
|
|
|
end
|
|
|
|
columns.keys.each { |key| columns[key].uniq! }
|
|
|
|
return columns
|
|
|
|
end
|
|
|
|
|
2013-02-13 00:50:20 +08:00
|
|
|
# remove things that don't look like valid database IDs
|
|
|
|
# return in integer format if possible
|
|
|
|
# (note that ID_REGEX may be redefined by a plugin!)
|
|
|
|
def self.map_non_sis_ids(ids)
|
|
|
|
ids.map{ |id| id.to_s.strip }.select{ |id| id =~ ID_REGEX }.map do |id|
|
|
|
|
id =~ /\A\d+\z/ ? id.to_i : id
|
|
|
|
end
|
|
|
|
end
|
|
|
|
|
2011-11-15 04:29:30 +08:00
|
|
|
def self.sis_find_sis_mapping_for_collection(collection)
|
|
|
|
SIS_MAPPINGS[collection.table_name] or
|
2011-09-13 23:21:00 +08:00
|
|
|
raise(ArgumentError, "need to add support for table name: #{collection.table_name}")
|
2011-11-15 04:29:30 +08:00
|
|
|
end
|
|
|
|
|
|
|
|
def self.sis_find_params_for_collection(collection, ids, sis_root_account)
|
|
|
|
return sis_find_params_for_sis_mapping(sis_find_sis_mapping_for_collection(collection), ids, sis_root_account)
|
|
|
|
end
|
|
|
|
|
|
|
|
def self.sis_find_params_for_sis_mapping(sis_mapping, ids, sis_root_account)
|
|
|
|
return sis_make_params_for_sis_mapping_and_columns(sis_parse_ids(ids, sis_mapping[:lookups]), sis_mapping, sis_root_account)
|
|
|
|
end
|
2011-09-13 23:21:00 +08:00
|
|
|
|
2011-11-15 04:29:30 +08:00
|
|
|
def self.sis_make_params_for_sis_mapping_and_columns(columns, sis_mapping, sis_root_account)
|
|
|
|
raise ArgumentError, "sis_root_account required for lookups" unless sis_root_account.is_a?(Account)
|
2011-10-05 00:31:34 +08:00
|
|
|
|
2012-10-20 04:25:17 +08:00
|
|
|
return :not_found if columns.empty?
|
2011-11-15 04:29:30 +08:00
|
|
|
|
2012-10-20 04:25:17 +08:00
|
|
|
not_scoped_to_account = sis_mapping[:is_not_scoped_to_account] || []
|
|
|
|
|
|
|
|
if columns.length == 1 && not_scoped_to_account.include?(columns.keys.first)
|
|
|
|
find_params = {:conditions => columns}
|
|
|
|
else
|
|
|
|
args = []
|
|
|
|
query = []
|
|
|
|
columns.keys.sort.each do |column|
|
|
|
|
if not_scoped_to_account.include?(column)
|
|
|
|
query << "#{column} IN (?)"
|
|
|
|
else
|
|
|
|
raise ArgumentError, "missing scope for collection" unless sis_mapping[:scope]
|
|
|
|
query << "(#{sis_mapping[:scope]} = #{sis_root_account.id} AND #{column} IN (?))"
|
|
|
|
end
|
|
|
|
args << columns[column]
|
2011-09-13 23:21:00 +08:00
|
|
|
end
|
2012-10-20 04:25:17 +08:00
|
|
|
|
|
|
|
args.unshift(query.join(" OR "))
|
|
|
|
find_params = { :conditions => args }
|
2011-07-06 06:23:35 +08:00
|
|
|
end
|
2011-11-15 04:29:30 +08:00
|
|
|
|
|
|
|
find_params[:include] = sis_mapping[:joins] if sis_mapping[:joins]
|
|
|
|
return find_params
|
2011-07-06 06:23:35 +08:00
|
|
|
end
|
2012-01-04 04:30:49 +08:00
|
|
|
|
2013-11-07 05:03:21 +08:00
|
|
|
def self.max_per_page
|
|
|
|
Setting.get('api_max_per_page', '50').to_i
|
|
|
|
end
|
|
|
|
|
2013-11-08 05:37:20 +08:00
|
|
|
def self.per_page_for(controller, options={})
|
|
|
|
per_page = controller.params[:per_page] || options[:default] || Setting.get('api_per_page', '10')
|
2013-11-07 05:03:21 +08:00
|
|
|
max = options[:max] || max_per_page
|
2013-11-08 05:37:20 +08:00
|
|
|
[[per_page.to_i, 1].max, max.to_i].min
|
2012-08-28 02:48:38 +08:00
|
|
|
end
|
|
|
|
|
2011-07-22 00:35:46 +08:00
|
|
|
# Add [link HTTP Headers](http://www.w3.org/Protocols/9707-link-header.html) for pagination
|
2011-09-02 23:34:12 +08:00
|
|
|
# The collection needs to be a will_paginate collection (or act like one)
|
2011-08-23 00:47:40 +08:00
|
|
|
# a new, paginated collection will be returned
|
|
|
|
def self.paginate(collection, controller, base_url, pagination_args = {})
|
import ActiveModel::Serializers port and convert quizzes api to it
test plan:
- The quiz api should work like it normally does when you don't pass
an 'Accept: application/vnd.api+json' header.
- The quizzes index page and quiz edit page should work like they
always do.
- Testing the Quizzes API for "jsonapi" style:
- For all requests, you MUST have the "Accept" header set to
"application/vnd.api+json"
- Test all the endpoints (PUT, POST, GET, INDEX, DELETE) like you
normally would, except you'll need to format the data according to
the next few steps:
- For "POST" and "PUT" (create and update) requests, you should send
the data like: { "quizzes": [ { id: 1, title: "blah" } ]
- For all requests (except DELETE), you should get back a response
that looks like: { "quizzes": [ { quiz you requested } ]
- For the "delete" action, you should get a "no content" response
and the request should be successful
Change-Id: Ie91deaeb6772cbe52a0fc46a28ab93a4e3036061
Reviewed-on: https://gerrit.instructure.com/25997
Reviewed-by: Jacob Fugal <jacob@instructure.com>
Tested-by: Jenkins <jenkins@instructure.com>
QA-Review: Caleb Guanzon <cguanzon@instructure.com>
Product-Review: Stanley Stuart <stanley@instructure.com>
2013-12-05 03:06:32 +08:00
|
|
|
collection = paginate_collection!(collection, controller, pagination_args)
|
|
|
|
links = build_links(base_url, meta_for_pagination(controller, collection))
|
|
|
|
controller.response.headers["Link"] = links.join(',') if links.length > 0
|
|
|
|
collection
|
|
|
|
end
|
|
|
|
|
|
|
|
# Returns collection as the first return value, and the meta information hash
|
|
|
|
# as the second return value
|
|
|
|
def self.jsonapi_paginate(collection, controller, base_url, pagination_args={})
|
|
|
|
collection = paginate_collection!(collection, controller, pagination_args)
|
|
|
|
meta = jsonapi_meta(collection, controller, base_url)
|
|
|
|
|
|
|
|
return collection, meta
|
|
|
|
end
|
|
|
|
|
|
|
|
def self.jsonapi_meta(collection, controller, base_url)
|
|
|
|
pagination = meta_for_pagination(controller, collection)
|
|
|
|
|
|
|
|
meta = {
|
|
|
|
per_page: collection.per_page
|
|
|
|
}
|
|
|
|
|
|
|
|
meta.merge!(build_links_hash(base_url, pagination))
|
|
|
|
|
|
|
|
if collection.ordinal_pages?
|
|
|
|
meta[:page] = pagination[:current]
|
|
|
|
meta[:template] = meta[:current].sub(/page=\d+/, "page={page}")
|
|
|
|
end
|
|
|
|
|
|
|
|
meta[:count] = collection.total_entries if collection.total_entries
|
|
|
|
meta[:page_count] = collection.total_pages if collection.total_pages
|
2013-12-19 02:36:42 +08:00
|
|
|
|
import ActiveModel::Serializers port and convert quizzes api to it
test plan:
- The quiz api should work like it normally does when you don't pass
an 'Accept: application/vnd.api+json' header.
- The quizzes index page and quiz edit page should work like they
always do.
- Testing the Quizzes API for "jsonapi" style:
- For all requests, you MUST have the "Accept" header set to
"application/vnd.api+json"
- Test all the endpoints (PUT, POST, GET, INDEX, DELETE) like you
normally would, except you'll need to format the data according to
the next few steps:
- For "POST" and "PUT" (create and update) requests, you should send
the data like: { "quizzes": [ { id: 1, title: "blah" } ]
- For all requests (except DELETE), you should get back a response
that looks like: { "quizzes": [ { quiz you requested } ]
- For the "delete" action, you should get a "no content" response
and the request should be successful
Change-Id: Ie91deaeb6772cbe52a0fc46a28ab93a4e3036061
Reviewed-on: https://gerrit.instructure.com/25997
Reviewed-by: Jacob Fugal <jacob@instructure.com>
Tested-by: Jenkins <jenkins@instructure.com>
QA-Review: Caleb Guanzon <cguanzon@instructure.com>
Product-Review: Stanley Stuart <stanley@instructure.com>
2013-12-05 03:06:32 +08:00
|
|
|
{ pagination: meta }
|
|
|
|
end
|
|
|
|
|
|
|
|
def self.paginate_collection!(collection, controller, pagination_args)
|
|
|
|
wrap_pagination_args!(pagination_args, controller)
|
2013-12-19 02:36:42 +08:00
|
|
|
begin
|
|
|
|
paginated = collection.paginate(pagination_args)
|
|
|
|
rescue Folio::InvalidPage
|
|
|
|
if pagination_args[:page].to_s =~ /\d+/ && pagination_args[:page].to_i > 0 && collection.build_page.ordinal_pages?
|
|
|
|
# for backwards compatibility we currently require returning [] for
|
|
|
|
# pages beyond the end of an ordinal collection, rather than a 404.
|
|
|
|
paginated = Folio::Ordinal::Page.create
|
|
|
|
paginated.current_page = pagination_args[:page].to_i
|
|
|
|
else
|
|
|
|
# we're not dealing with a simple out-of-bounds on an ordinal
|
|
|
|
# collection, let the exception propagate (and turn into a 404)
|
|
|
|
raise
|
|
|
|
end
|
|
|
|
end
|
import ActiveModel::Serializers port and convert quizzes api to it
test plan:
- The quiz api should work like it normally does when you don't pass
an 'Accept: application/vnd.api+json' header.
- The quizzes index page and quiz edit page should work like they
always do.
- Testing the Quizzes API for "jsonapi" style:
- For all requests, you MUST have the "Accept" header set to
"application/vnd.api+json"
- Test all the endpoints (PUT, POST, GET, INDEX, DELETE) like you
normally would, except you'll need to format the data according to
the next few steps:
- For "POST" and "PUT" (create and update) requests, you should send
the data like: { "quizzes": [ { id: 1, title: "blah" } ]
- For all requests (except DELETE), you should get back a response
that looks like: { "quizzes": [ { quiz you requested } ]
- For the "delete" action, you should get a "no content" response
and the request should be successful
Change-Id: Ie91deaeb6772cbe52a0fc46a28ab93a4e3036061
Reviewed-on: https://gerrit.instructure.com/25997
Reviewed-by: Jacob Fugal <jacob@instructure.com>
Tested-by: Jenkins <jenkins@instructure.com>
QA-Review: Caleb Guanzon <cguanzon@instructure.com>
Product-Review: Stanley Stuart <stanley@instructure.com>
2013-12-05 03:06:32 +08:00
|
|
|
paginated
|
2012-09-12 05:12:36 +08:00
|
|
|
end
|
|
|
|
|
import ActiveModel::Serializers port and convert quizzes api to it
test plan:
- The quiz api should work like it normally does when you don't pass
an 'Accept: application/vnd.api+json' header.
- The quizzes index page and quiz edit page should work like they
always do.
- Testing the Quizzes API for "jsonapi" style:
- For all requests, you MUST have the "Accept" header set to
"application/vnd.api+json"
- Test all the endpoints (PUT, POST, GET, INDEX, DELETE) like you
normally would, except you'll need to format the data according to
the next few steps:
- For "POST" and "PUT" (create and update) requests, you should send
the data like: { "quizzes": [ { id: 1, title: "blah" } ]
- For all requests (except DELETE), you should get back a response
that looks like: { "quizzes": [ { quiz you requested } ]
- For the "delete" action, you should get a "no content" response
and the request should be successful
Change-Id: Ie91deaeb6772cbe52a0fc46a28ab93a4e3036061
Reviewed-on: https://gerrit.instructure.com/25997
Reviewed-by: Jacob Fugal <jacob@instructure.com>
Tested-by: Jenkins <jenkins@instructure.com>
QA-Review: Caleb Guanzon <cguanzon@instructure.com>
Product-Review: Stanley Stuart <stanley@instructure.com>
2013-12-05 03:06:32 +08:00
|
|
|
def self.wrap_pagination_args!(pagination_args, controller)
|
|
|
|
pagination_args.reverse_merge!(
|
|
|
|
page: controller.params[:page],
|
|
|
|
per_page: per_page_for(controller,
|
|
|
|
default: pagination_args.delete(:default_per_page),
|
|
|
|
max: pagination_args.delete(:max_per_page)))
|
|
|
|
end
|
|
|
|
|
|
|
|
def self.meta_for_pagination(controller, collection)
|
|
|
|
{
|
|
|
|
query_parameters: controller.request.query_parameters,
|
|
|
|
per_page: collection.per_page,
|
|
|
|
current: collection.current_page,
|
|
|
|
next: collection.next_page,
|
|
|
|
prev: collection.previous_page,
|
|
|
|
first: collection.first_page,
|
|
|
|
last: collection.last_page,
|
|
|
|
}
|
|
|
|
end
|
|
|
|
|
|
|
|
PAGINATION_PARAMS = [:current, :next, :prev, :first, :last]
|
2012-09-12 05:12:36 +08:00
|
|
|
EXCLUDE_IN_PAGINATION_LINKS = %w(page per_page access_token api_key)
|
|
|
|
def self.build_links(base_url, opts={})
|
import ActiveModel::Serializers port and convert quizzes api to it
test plan:
- The quiz api should work like it normally does when you don't pass
an 'Accept: application/vnd.api+json' header.
- The quizzes index page and quiz edit page should work like they
always do.
- Testing the Quizzes API for "jsonapi" style:
- For all requests, you MUST have the "Accept" header set to
"application/vnd.api+json"
- Test all the endpoints (PUT, POST, GET, INDEX, DELETE) like you
normally would, except you'll need to format the data according to
the next few steps:
- For "POST" and "PUT" (create and update) requests, you should send
the data like: { "quizzes": [ { id: 1, title: "blah" } ]
- For all requests (except DELETE), you should get back a response
that looks like: { "quizzes": [ { quiz you requested } ]
- For the "delete" action, you should get a "no content" response
and the request should be successful
Change-Id: Ie91deaeb6772cbe52a0fc46a28ab93a4e3036061
Reviewed-on: https://gerrit.instructure.com/25997
Reviewed-by: Jacob Fugal <jacob@instructure.com>
Tested-by: Jenkins <jenkins@instructure.com>
QA-Review: Caleb Guanzon <cguanzon@instructure.com>
Product-Review: Stanley Stuart <stanley@instructure.com>
2013-12-05 03:06:32 +08:00
|
|
|
links = build_links_hash(base_url, opts)
|
|
|
|
# iterate in order, but only using the keys present from build_links_hash
|
|
|
|
(PAGINATION_PARAMS & links.keys).map do |k|
|
|
|
|
v = links[k]
|
|
|
|
"<#{v}>; rel=\"#{k}\""
|
|
|
|
end
|
|
|
|
end
|
|
|
|
|
|
|
|
def self.build_links_hash(base_url, opts={})
|
2012-01-04 04:30:49 +08:00
|
|
|
base_url += (base_url =~ /\?/ ? '&': '?')
|
2012-09-12 05:12:36 +08:00
|
|
|
qp = opts[:query_parameters] || {}
|
|
|
|
qp = qp.with_indifferent_access.except(*EXCLUDE_IN_PAGINATION_LINKS)
|
|
|
|
base_url += "#{qp.to_query}&" if qp.present?
|
import ActiveModel::Serializers port and convert quizzes api to it
test plan:
- The quiz api should work like it normally does when you don't pass
an 'Accept: application/vnd.api+json' header.
- The quizzes index page and quiz edit page should work like they
always do.
- Testing the Quizzes API for "jsonapi" style:
- For all requests, you MUST have the "Accept" header set to
"application/vnd.api+json"
- Test all the endpoints (PUT, POST, GET, INDEX, DELETE) like you
normally would, except you'll need to format the data according to
the next few steps:
- For "POST" and "PUT" (create and update) requests, you should send
the data like: { "quizzes": [ { id: 1, title: "blah" } ]
- For all requests (except DELETE), you should get back a response
that looks like: { "quizzes": [ { quiz you requested } ]
- For the "delete" action, you should get a "no content" response
and the request should be successful
Change-Id: Ie91deaeb6772cbe52a0fc46a28ab93a4e3036061
Reviewed-on: https://gerrit.instructure.com/25997
Reviewed-by: Jacob Fugal <jacob@instructure.com>
Tested-by: Jenkins <jenkins@instructure.com>
QA-Review: Caleb Guanzon <cguanzon@instructure.com>
Product-Review: Stanley Stuart <stanley@instructure.com>
2013-12-05 03:06:32 +08:00
|
|
|
PAGINATION_PARAMS.each_with_object({}) do |param, obj|
|
|
|
|
if opts[param].present?
|
|
|
|
obj[param] = "#{base_url}page=#{opts[param]}&per_page=#{opts[:per_page]}"
|
2012-09-12 05:12:36 +08:00
|
|
|
end
|
2011-07-22 00:35:46 +08:00
|
|
|
end
|
|
|
|
end
|
2012-01-04 04:30:49 +08:00
|
|
|
|
2012-10-18 05:43:39 +08:00
|
|
|
def self.parse_pagination_links(link_header)
|
|
|
|
link_header.split(",").map do |link|
|
|
|
|
url, rel = link.match(%r{^<([^>]+)>; rel="([^"]+)"}).captures
|
|
|
|
uri = URI.parse(url)
|
|
|
|
raise(ArgumentError, "pagination url is not an absolute uri: #{url}") unless uri.is_a?(URI::HTTP)
|
|
|
|
Rack::Utils.parse_nested_query(uri.query).merge(:uri => uri, :rel => rel)
|
|
|
|
end
|
|
|
|
end
|
|
|
|
|
2011-10-08 05:41:19 +08:00
|
|
|
def media_comment_json(media_object_or_hash)
|
|
|
|
media_object_or_hash = OpenStruct.new(media_object_or_hash) if media_object_or_hash.is_a?(Hash)
|
|
|
|
{
|
|
|
|
'content-type' => "#{media_object_or_hash.media_type}/mp4",
|
|
|
|
'display_name' => media_object_or_hash.title,
|
|
|
|
'media_id' => media_object_or_hash.media_id,
|
|
|
|
'media_type' => media_object_or_hash.media_type,
|
|
|
|
'url' => user_media_download_url(:user_id => @current_user.id,
|
|
|
|
:entryId => media_object_or_hash.media_id,
|
|
|
|
:type => "mp4",
|
|
|
|
:redirect => "1")
|
|
|
|
}
|
|
|
|
end
|
|
|
|
|
2012-06-26 23:52:40 +08:00
|
|
|
# a hash of allowed html attributes that represent urls, like { 'a' => ['href'], 'img' => ['src'] }
|
2014-01-29 05:29:09 +08:00
|
|
|
UrlAttributes = CanvasSanitize::SANITIZE[:protocols].inject({}) { |h,(k,v)| h[k] = v.keys; h }
|
2012-06-26 23:52:40 +08:00
|
|
|
|
2013-07-09 03:08:06 +08:00
|
|
|
def api_bulk_load_user_content_attachments(htmls, context = @context, user = @current_user)
|
|
|
|
rewriter = UserContent::HtmlRewriter.new(context, user)
|
|
|
|
attachment_ids = []
|
|
|
|
rewriter.set_handler('files') do |m|
|
|
|
|
attachment_ids << m.obj_id if m.obj_id
|
|
|
|
end
|
|
|
|
|
|
|
|
htmls.each { |html| rewriter.translate_content(html) }
|
|
|
|
|
|
|
|
if attachment_ids.blank?
|
|
|
|
{}
|
|
|
|
else
|
|
|
|
attachments = if context.is_a?(User) || context.nil?
|
|
|
|
Attachment.where(id: attachment_ids)
|
|
|
|
else
|
|
|
|
context.attachments.where(id: attachment_ids)
|
|
|
|
end
|
|
|
|
attachments.index_by(&:id)
|
|
|
|
end
|
|
|
|
end
|
|
|
|
|
|
|
|
def api_user_content(html, context = @context, user = @current_user, preloaded_attachments = {})
|
2011-11-10 05:39:18 +08:00
|
|
|
return html if html.blank?
|
|
|
|
|
2012-03-28 02:41:55 +08:00
|
|
|
# if we're a controller, use the host of the request, otherwise let HostUrl
|
|
|
|
# figure out what host is appropriate
|
2012-04-04 04:17:56 +08:00
|
|
|
if self.is_a?(ApplicationController)
|
|
|
|
host = request.host_with_port
|
2012-06-26 23:52:40 +08:00
|
|
|
protocol = request.ssl? ? 'https' : 'http'
|
2012-04-04 04:17:56 +08:00
|
|
|
else
|
|
|
|
host = HostUrl.context_host(context, @account_domain.try(:host))
|
2012-06-26 23:52:40 +08:00
|
|
|
protocol = HostUrl.protocol
|
2012-04-04 04:17:56 +08:00
|
|
|
end
|
2012-03-28 02:41:55 +08:00
|
|
|
|
2011-10-08 00:36:22 +08:00
|
|
|
rewriter = UserContent::HtmlRewriter.new(context, user)
|
|
|
|
rewriter.set_handler('files') do |match|
|
2013-03-27 00:43:40 +08:00
|
|
|
if match.obj_id
|
2013-07-09 03:08:06 +08:00
|
|
|
obj = preloaded_attachments[match.obj_id]
|
|
|
|
obj ||= if context.is_a?(User) || context.nil?
|
|
|
|
Attachment.find_by_id(match.obj_id)
|
|
|
|
else
|
|
|
|
context.attachments.find_by_id(match.obj_id)
|
|
|
|
end
|
2013-03-27 00:43:40 +08:00
|
|
|
end
|
2011-11-29 03:40:48 +08:00
|
|
|
next unless obj && rewriter.user_can_view_content?(obj)
|
2013-04-12 00:57:09 +08:00
|
|
|
|
|
|
|
if ["Course", "Group", "Account", "User"].include?(obj.context_type)
|
|
|
|
if match.rest.start_with?("/preview")
|
2013-12-14 01:06:05 +08:00
|
|
|
url = self.send("#{obj.context_type.downcase}_file_preview_url", obj.context_id, obj.id, :verifier => obj.uuid, :only_path => true)
|
2013-04-12 00:57:09 +08:00
|
|
|
else
|
2013-12-14 01:06:05 +08:00
|
|
|
url = self.send("#{obj.context_type.downcase}_file_download_url", obj.context_id, obj.id, :verifier => obj.uuid, :download => '1', :only_path => true)
|
2013-04-12 00:57:09 +08:00
|
|
|
end
|
|
|
|
else
|
2013-12-14 01:06:05 +08:00
|
|
|
url = file_download_url(obj.id, :verifier => obj.uuid, :download => '1', :only_path => true)
|
2013-04-12 00:57:09 +08:00
|
|
|
end
|
|
|
|
url
|
2011-10-08 00:36:22 +08:00
|
|
|
end
|
|
|
|
html = rewriter.translate_content(html)
|
|
|
|
|
|
|
|
return html if html.blank?
|
|
|
|
|
|
|
|
# translate media comments into html5 video tags
|
|
|
|
doc = Nokogiri::HTML::DocumentFragment.parse(html)
|
|
|
|
doc.css('a.instructure_inline_media_comment').each do |anchor|
|
2013-04-25 01:38:40 +08:00
|
|
|
media_id = anchor['id'].try(:sub, /^media_comment_/, '')
|
2012-02-24 07:52:08 +08:00
|
|
|
next if media_id.blank?
|
2012-03-29 01:08:35 +08:00
|
|
|
|
|
|
|
if anchor['class'].try(:match, /\baudio_comment\b/)
|
|
|
|
node = Nokogiri::XML::Node.new('audio', doc)
|
|
|
|
node['data-media_comment_type'] = 'audio'
|
|
|
|
else
|
|
|
|
node = Nokogiri::XML::Node.new('video', doc)
|
2012-06-26 23:52:40 +08:00
|
|
|
thumbnail = media_object_thumbnail_url(media_id, :width => 550, :height => 448, :type => 3, :host => host, :protocol => protocol)
|
2012-03-29 01:08:35 +08:00
|
|
|
node['poster'] = thumbnail
|
|
|
|
node['data-media_comment_type'] = 'video'
|
|
|
|
end
|
|
|
|
|
|
|
|
node['preload'] = 'none'
|
|
|
|
node['class'] = 'instructure_inline_media_comment'
|
|
|
|
node['data-media_comment_id'] = media_id
|
2012-06-26 23:52:40 +08:00
|
|
|
media_redirect = polymorphic_url([context, :media_download], :entryId => media_id, :type => 'mp4', :redirect => '1', :host => host, :protocol => protocol)
|
2012-03-29 01:08:35 +08:00
|
|
|
node['controls'] = 'controls'
|
|
|
|
node['src'] = media_redirect
|
2012-07-20 07:35:03 +08:00
|
|
|
node.inner_html = anchor.inner_html
|
2012-03-29 01:08:35 +08:00
|
|
|
anchor.replace(node)
|
2011-10-08 00:36:22 +08:00
|
|
|
end
|
|
|
|
|
2012-07-10 05:05:05 +08:00
|
|
|
UserContent.find_user_content(doc) do |node, uc|
|
|
|
|
node['class'] = "instructure_user_content #{node['class']}"
|
|
|
|
node['data-uc_width'] = uc.width
|
|
|
|
node['data-uc_height'] = uc.height
|
|
|
|
node['data-uc_snippet'] = uc.node_string
|
|
|
|
node['data-uc_sig'] = uc.node_hmac
|
|
|
|
end
|
|
|
|
|
2012-06-26 23:52:40 +08:00
|
|
|
# rewrite any html attributes that are urls but just absolute paths, to
|
|
|
|
# have the canvas domain prepended to make them a full url
|
|
|
|
#
|
|
|
|
# relative urls and invalid urls are currently ignored
|
|
|
|
UrlAttributes.each do |tag, attributes|
|
|
|
|
doc.css(tag).each do |element|
|
|
|
|
attributes.each do |attribute|
|
|
|
|
url_str = element[attribute]
|
|
|
|
begin
|
|
|
|
url = URI.parse(url_str)
|
|
|
|
# if the url_str is "//example.com/a", the parsed url will have a host set
|
|
|
|
# otherwise if it starts with a slash, it's a path that needs to be
|
|
|
|
# made absolute with the canvas hostname prepended
|
|
|
|
if !url.host && url_str[0] == '/'[0]
|
|
|
|
element[attribute] = "#{protocol}://#{host}#{url_str}"
|
2012-08-15 05:47:53 +08:00
|
|
|
api_endpoint_info(protocol, host, url_str).each do |att, val|
|
|
|
|
element[att] = val
|
|
|
|
end
|
2012-06-26 23:52:40 +08:00
|
|
|
end
|
2012-08-23 06:07:32 +08:00
|
|
|
rescue URI::Error => e
|
2012-06-26 23:52:40 +08:00
|
|
|
# leave it as is
|
|
|
|
end
|
|
|
|
end
|
|
|
|
end
|
|
|
|
end
|
|
|
|
|
2011-10-08 00:36:22 +08:00
|
|
|
return doc.to_s
|
|
|
|
end
|
2012-05-22 00:11:48 +08:00
|
|
|
|
2013-04-13 05:46:13 +08:00
|
|
|
# This removes the verifier parameters that are added to attachment links by api_user_content
|
|
|
|
# and adds context (e.g. /courses/:id/) if it is missing
|
2013-06-18 05:24:00 +08:00
|
|
|
# exception: it leaves user-context file links alone
|
2013-04-13 05:46:13 +08:00
|
|
|
def process_incoming_html_content(html)
|
2013-04-25 01:38:40 +08:00
|
|
|
return html unless html.present?
|
|
|
|
# shortcut html documents that definitely don't have anything we're interested in
|
|
|
|
return html unless html =~ %r{verifier=|['"]/files|instructure_inline_media_comment}
|
2013-04-13 05:46:13 +08:00
|
|
|
|
|
|
|
attrs = ['href', 'src']
|
|
|
|
link_regex = %r{/files/(\d+)/(?:download|preview)}
|
|
|
|
verifier_regex = %r{(\?)verifier=[^&]*&?|&verifier=[^&]*}
|
|
|
|
|
2013-06-18 05:24:00 +08:00
|
|
|
context_types = ["Course", "Group", "Account"]
|
|
|
|
skip_context_types = ["User"]
|
2013-04-13 05:46:13 +08:00
|
|
|
|
|
|
|
doc = Nokogiri::HTML(html)
|
|
|
|
doc.search("*").each do |node|
|
|
|
|
attrs.each do |attr|
|
|
|
|
if link = node[attr]
|
|
|
|
if link =~ link_regex
|
|
|
|
if link.start_with?('/files')
|
|
|
|
att_id = $1
|
2013-06-18 05:24:00 +08:00
|
|
|
att = Attachment.find_by_id(att_id)
|
|
|
|
if att
|
|
|
|
next if skip_context_types.include?(att.context_type)
|
|
|
|
if context_types.include?(att.context_type)
|
|
|
|
link = "/#{att.context_type.underscore.pluralize}/#{att.context_id}" + link
|
|
|
|
end
|
2013-04-13 05:46:13 +08:00
|
|
|
end
|
|
|
|
end
|
|
|
|
if link.include?('verifier=')
|
|
|
|
link.gsub!(verifier_regex, '\1')
|
|
|
|
end
|
|
|
|
node[attr] = link
|
|
|
|
end
|
|
|
|
end
|
|
|
|
end
|
|
|
|
end
|
|
|
|
|
2013-04-25 01:38:40 +08:00
|
|
|
# translate audio and video tags generated by media comments back into anchor tags
|
|
|
|
# try to add the relevant attributes to media comment anchor tags to retain MediaObject info
|
|
|
|
doc.css('audio.instructure_inline_media_comment, video.instructure_inline_media_comment, a.instructure_inline_media_comment').each do |node|
|
|
|
|
if node.name == 'a'
|
|
|
|
media_id = node['id'].try(:sub, /^media_comment_/, '')
|
|
|
|
else
|
|
|
|
media_id = node['data-media_comment_id']
|
|
|
|
end
|
|
|
|
next if media_id.blank?
|
|
|
|
|
|
|
|
if node.name == 'a'
|
|
|
|
anchor = node
|
|
|
|
unless anchor['class'] =~ /\b(audio|video)_comment\b/
|
|
|
|
media_object = MediaObject.active.by_media_id(media_id).first
|
|
|
|
anchor['class'] += " #{media_object.media_type}_comment" if media_object
|
|
|
|
end
|
|
|
|
else
|
|
|
|
comment_type = "#{node.name}_comment"
|
|
|
|
anchor = Nokogiri::XML::Node.new('a', doc)
|
|
|
|
anchor['class'] = "instructure_inline_media_comment #{comment_type}"
|
|
|
|
anchor['id'] = "media_comment_#{media_id}"
|
|
|
|
node.replace(anchor)
|
|
|
|
end
|
|
|
|
|
|
|
|
anchor['href'] = "/media_objects/#{media_id}"
|
|
|
|
end
|
|
|
|
|
2013-04-13 05:46:13 +08:00
|
|
|
return doc.at_css('body').inner_html
|
|
|
|
end
|
|
|
|
|
2012-05-22 00:11:48 +08:00
|
|
|
def value_to_boolean(value)
|
|
|
|
Canvas::Plugin.value_to_boolean(value)
|
|
|
|
end
|
2012-08-15 05:47:53 +08:00
|
|
|
|
2014-01-07 07:45:51 +08:00
|
|
|
def self.value_to_array(value)
|
|
|
|
value.is_a?(String) ? value.split(',') : value
|
|
|
|
end
|
|
|
|
|
2012-08-15 05:47:53 +08:00
|
|
|
# regex for shard-aware ID
|
|
|
|
ID = '(?:\d+~)?\d+'
|
|
|
|
|
modules api, closes #10404
also modifies the discussion topic and assignment API
controllers to make sure "must_view" requirements are
fulfilled
test plan:
* check the API documentation; ensure it looks okay
* create a course with module items of each supported type
* set completion criteria of each supported type
* create another module, so you can set prerequisites
* use the list modules API and verify its output matches
the course and the documentation
* as a teacher, "state" should be missing
* as a student, "state" should be "locked", "unlocked",
"started", or "completed"
* use the show module API and verify the correct information
is returned for a single module
* use the list module items API and verify the output
* as a teacher, the "completion_requirement" omits the
"completed" flag
* as a student, "completed" should be true or false,
depending on whether the requirement was met
* use the show module API and verify the correct information
is returned for a single module item
* last but not least, verify "must view" requirements can
be fulfilled through the api_data_endpoints supplied
for files, pages, discussions, and assignments
* files are viewed when downloading their content
* pages are viewed by the show action (where content
is returned)
* discussions are viewed when marked read via the
mark_topic_read or mark_all_read actions
* assignments are viewed by the show action
(where description is returned). they are not viewed
if the assignment is locked and the user does not
have access to the content yet.
Change-Id: I0cbbbc542f69215e7b396a501d4d86ff2f76c149
Reviewed-on: https://gerrit.instructure.com/13626
Tested-by: Jenkins <jenkins@instructure.com>
Reviewed-by: Simon Williams <simon@instructure.com>
2012-09-12 01:16:48 +08:00
|
|
|
# maps a Canvas data type to an API-friendly type name
|
|
|
|
API_DATA_TYPE = { "Attachment" => "File",
|
|
|
|
"WikiPage" => "Page",
|
|
|
|
"DiscussionTopic" => "Discussion",
|
|
|
|
"Assignment" => "Assignment",
|
2014-01-15 06:11:27 +08:00
|
|
|
"Quizzes::Quiz" => "Quiz",
|
modules api, closes #10404
also modifies the discussion topic and assignment API
controllers to make sure "must_view" requirements are
fulfilled
test plan:
* check the API documentation; ensure it looks okay
* create a course with module items of each supported type
* set completion criteria of each supported type
* create another module, so you can set prerequisites
* use the list modules API and verify its output matches
the course and the documentation
* as a teacher, "state" should be missing
* as a student, "state" should be "locked", "unlocked",
"started", or "completed"
* use the show module API and verify the correct information
is returned for a single module
* use the list module items API and verify the output
* as a teacher, the "completion_requirement" omits the
"completed" flag
* as a student, "completed" should be true or false,
depending on whether the requirement was met
* use the show module API and verify the correct information
is returned for a single module item
* last but not least, verify "must view" requirements can
be fulfilled through the api_data_endpoints supplied
for files, pages, discussions, and assignments
* files are viewed when downloading their content
* pages are viewed by the show action (where content
is returned)
* discussions are viewed when marked read via the
mark_topic_read or mark_all_read actions
* assignments are viewed by the show action
(where description is returned). they are not viewed
if the assignment is locked and the user does not
have access to the content yet.
Change-Id: I0cbbbc542f69215e7b396a501d4d86ff2f76c149
Reviewed-on: https://gerrit.instructure.com/13626
Tested-by: Jenkins <jenkins@instructure.com>
Reviewed-by: Simon Williams <simon@instructure.com>
2012-09-12 01:16:48 +08:00
|
|
|
"ContextModuleSubHeader" => "SubHeader",
|
|
|
|
"ExternalUrl" => "ExternalUrl",
|
2013-08-22 06:36:47 +08:00
|
|
|
"ContextExternalTool" => "ExternalTool",
|
|
|
|
"ContextModule" => "Module",
|
|
|
|
"ContentTag" => "ModuleItem" }.freeze
|
|
|
|
|
|
|
|
# matches the other direction, case insensitively
|
|
|
|
def self.api_type_to_canvas_name(api_type)
|
|
|
|
unless @inverse_map
|
|
|
|
m = {}
|
|
|
|
API_DATA_TYPE.each do |k, v|
|
|
|
|
m[v.downcase] = k
|
|
|
|
end
|
|
|
|
@inverse_map = m
|
|
|
|
end
|
|
|
|
return nil unless api_type
|
|
|
|
@inverse_map[api_type.downcase]
|
|
|
|
end
|
modules api, closes #10404
also modifies the discussion topic and assignment API
controllers to make sure "must_view" requirements are
fulfilled
test plan:
* check the API documentation; ensure it looks okay
* create a course with module items of each supported type
* set completion criteria of each supported type
* create another module, so you can set prerequisites
* use the list modules API and verify its output matches
the course and the documentation
* as a teacher, "state" should be missing
* as a student, "state" should be "locked", "unlocked",
"started", or "completed"
* use the show module API and verify the correct information
is returned for a single module
* use the list module items API and verify the output
* as a teacher, the "completion_requirement" omits the
"completed" flag
* as a student, "completed" should be true or false,
depending on whether the requirement was met
* use the show module API and verify the correct information
is returned for a single module item
* last but not least, verify "must view" requirements can
be fulfilled through the api_data_endpoints supplied
for files, pages, discussions, and assignments
* files are viewed when downloading their content
* pages are viewed by the show action (where content
is returned)
* discussions are viewed when marked read via the
mark_topic_read or mark_all_read actions
* assignments are viewed by the show action
(where description is returned). they are not viewed
if the assignment is locked and the user does not
have access to the content yet.
Change-Id: I0cbbbc542f69215e7b396a501d4d86ff2f76c149
Reviewed-on: https://gerrit.instructure.com/13626
Tested-by: Jenkins <jenkins@instructure.com>
Reviewed-by: Simon Williams <simon@instructure.com>
2012-09-12 01:16:48 +08:00
|
|
|
|
2012-08-15 05:47:53 +08:00
|
|
|
# maps canvas URLs to API URL helpers
|
|
|
|
# target array is return type, helper, name of each capture, and optionally a Hash of extra arguments
|
|
|
|
API_ROUTE_MAP = {
|
|
|
|
# list discussion topics
|
|
|
|
%r{^/courses/(#{ID})/discussion_topics$} => ['[Discussion]', :api_v1_course_discussion_topics_url, :course_id],
|
|
|
|
%r{^/groups/(#{ID})/discussion_topics$} => ['[Discussion]', :api_v1_group_discussion_topics_url, :group_id],
|
|
|
|
|
|
|
|
# get a single topic
|
|
|
|
%r{^/courses/(#{ID})/discussion_topics/(#{ID})$} => ['Discussion', :api_v1_course_discussion_topic_url, :course_id, :topic_id],
|
|
|
|
%r{^/groups/(#{ID})/discussion_topics/(#{ID})$} => ['Discussion', :api_v1_group_discussion_topic_url, :group_id, :topic_id],
|
|
|
|
|
|
|
|
# List pages
|
modules api, closes #10404
also modifies the discussion topic and assignment API
controllers to make sure "must_view" requirements are
fulfilled
test plan:
* check the API documentation; ensure it looks okay
* create a course with module items of each supported type
* set completion criteria of each supported type
* create another module, so you can set prerequisites
* use the list modules API and verify its output matches
the course and the documentation
* as a teacher, "state" should be missing
* as a student, "state" should be "locked", "unlocked",
"started", or "completed"
* use the show module API and verify the correct information
is returned for a single module
* use the list module items API and verify the output
* as a teacher, the "completion_requirement" omits the
"completed" flag
* as a student, "completed" should be true or false,
depending on whether the requirement was met
* use the show module API and verify the correct information
is returned for a single module item
* last but not least, verify "must view" requirements can
be fulfilled through the api_data_endpoints supplied
for files, pages, discussions, and assignments
* files are viewed when downloading their content
* pages are viewed by the show action (where content
is returned)
* discussions are viewed when marked read via the
mark_topic_read or mark_all_read actions
* assignments are viewed by the show action
(where description is returned). they are not viewed
if the assignment is locked and the user does not
have access to the content yet.
Change-Id: I0cbbbc542f69215e7b396a501d4d86ff2f76c149
Reviewed-on: https://gerrit.instructure.com/13626
Tested-by: Jenkins <jenkins@instructure.com>
Reviewed-by: Simon Williams <simon@instructure.com>
2012-09-12 01:16:48 +08:00
|
|
|
%r{^/courses/(#{ID})/wiki$} => ['[Page]', :api_v1_course_wiki_pages_url, :course_id],
|
|
|
|
%r{^/groups/(#{ID})/wiki$} => ['[Page]', :api_v1_group_wiki_pages_url, :group_id],
|
2012-08-15 05:47:53 +08:00
|
|
|
|
|
|
|
# Show page
|
modules api, closes #10404
also modifies the discussion topic and assignment API
controllers to make sure "must_view" requirements are
fulfilled
test plan:
* check the API documentation; ensure it looks okay
* create a course with module items of each supported type
* set completion criteria of each supported type
* create another module, so you can set prerequisites
* use the list modules API and verify its output matches
the course and the documentation
* as a teacher, "state" should be missing
* as a student, "state" should be "locked", "unlocked",
"started", or "completed"
* use the show module API and verify the correct information
is returned for a single module
* use the list module items API and verify the output
* as a teacher, the "completion_requirement" omits the
"completed" flag
* as a student, "completed" should be true or false,
depending on whether the requirement was met
* use the show module API and verify the correct information
is returned for a single module item
* last but not least, verify "must view" requirements can
be fulfilled through the api_data_endpoints supplied
for files, pages, discussions, and assignments
* files are viewed when downloading their content
* pages are viewed by the show action (where content
is returned)
* discussions are viewed when marked read via the
mark_topic_read or mark_all_read actions
* assignments are viewed by the show action
(where description is returned). they are not viewed
if the assignment is locked and the user does not
have access to the content yet.
Change-Id: I0cbbbc542f69215e7b396a501d4d86ff2f76c149
Reviewed-on: https://gerrit.instructure.com/13626
Tested-by: Jenkins <jenkins@instructure.com>
Reviewed-by: Simon Williams <simon@instructure.com>
2012-09-12 01:16:48 +08:00
|
|
|
%r{^/courses/(#{ID})/wiki/([^/]+)$} => ['Page', :api_v1_course_wiki_page_url, :course_id, :url],
|
|
|
|
%r{^/groups/(#{ID})/wiki/([^/]+)$} => ['Page', :api_v1_group_wiki_page_url, :group_id, :url],
|
2012-08-15 05:47:53 +08:00
|
|
|
|
|
|
|
# List assignments
|
|
|
|
%r{^/courses/(#{ID})/assignments$} => ['[Assignment]', :api_v1_course_assignments_url, :course_id],
|
|
|
|
|
|
|
|
# Get assignment
|
|
|
|
%r{^/courses/(#{ID})/assignments/(#{ID})$} => ['Assignment', :api_v1_course_assignment_url, :course_id, :id],
|
|
|
|
|
|
|
|
# List files
|
|
|
|
%r{^/courses/(#{ID})/files$} => ['Folder', :api_v1_course_folder_url, :course_id, {:id => 'root'}],
|
|
|
|
%r{^/groups/(#{ID})/files$} => ['Folder', :api_v1_group_folder_url, :group_id, {:id => 'root'}],
|
|
|
|
%r{^/users/(#{ID})/files$} => ['Folder', :api_v1_user_folder_url, :user_id, {:id => 'root'}],
|
|
|
|
|
|
|
|
# Get file
|
modules api, closes #10404
also modifies the discussion topic and assignment API
controllers to make sure "must_view" requirements are
fulfilled
test plan:
* check the API documentation; ensure it looks okay
* create a course with module items of each supported type
* set completion criteria of each supported type
* create another module, so you can set prerequisites
* use the list modules API and verify its output matches
the course and the documentation
* as a teacher, "state" should be missing
* as a student, "state" should be "locked", "unlocked",
"started", or "completed"
* use the show module API and verify the correct information
is returned for a single module
* use the list module items API and verify the output
* as a teacher, the "completion_requirement" omits the
"completed" flag
* as a student, "completed" should be true or false,
depending on whether the requirement was met
* use the show module API and verify the correct information
is returned for a single module item
* last but not least, verify "must view" requirements can
be fulfilled through the api_data_endpoints supplied
for files, pages, discussions, and assignments
* files are viewed when downloading their content
* pages are viewed by the show action (where content
is returned)
* discussions are viewed when marked read via the
mark_topic_read or mark_all_read actions
* assignments are viewed by the show action
(where description is returned). they are not viewed
if the assignment is locked and the user does not
have access to the content yet.
Change-Id: I0cbbbc542f69215e7b396a501d4d86ff2f76c149
Reviewed-on: https://gerrit.instructure.com/13626
Tested-by: Jenkins <jenkins@instructure.com>
Reviewed-by: Simon Williams <simon@instructure.com>
2012-09-12 01:16:48 +08:00
|
|
|
%r{^/courses/#{ID}/files/(#{ID})/} => ['File', :api_v1_attachment_url, :id],
|
|
|
|
%r{^/groups/#{ID}/files/(#{ID})/} => ['File', :api_v1_attachment_url, :id],
|
|
|
|
%r{^/users/#{ID}/files/(#{ID})/} => ['File', :api_v1_attachment_url, :id],
|
|
|
|
%r{^/files/(#{ID})/} => ['File', :api_v1_attachment_url, :id],
|
2013-05-31 05:26:21 +08:00
|
|
|
|
2013-05-31 06:26:10 +08:00
|
|
|
# List quizzes
|
|
|
|
%r{^/courses/(#{ID})/quizzes$} => ['[Quiz]', :api_v1_course_quizzes_url, :course_id],
|
|
|
|
|
|
|
|
# Get quiz
|
|
|
|
%r{^/courses/(#{ID})/quizzes/(#{ID})$} => ['Quiz', :api_v1_course_quiz_url, :course_id, :id],
|
|
|
|
|
2013-05-31 05:26:21 +08:00
|
|
|
# Launch LTI tool
|
|
|
|
%r{^/courses/(#{ID})/external_tools/retrieve\?url=(.*)$} => ['SessionlessLaunchUrl', :api_v1_course_external_tool_sessionless_launch_url, :course_id, :url],
|
modules api, closes #10404
also modifies the discussion topic and assignment API
controllers to make sure "must_view" requirements are
fulfilled
test plan:
* check the API documentation; ensure it looks okay
* create a course with module items of each supported type
* set completion criteria of each supported type
* create another module, so you can set prerequisites
* use the list modules API and verify its output matches
the course and the documentation
* as a teacher, "state" should be missing
* as a student, "state" should be "locked", "unlocked",
"started", or "completed"
* use the show module API and verify the correct information
is returned for a single module
* use the list module items API and verify the output
* as a teacher, the "completion_requirement" omits the
"completed" flag
* as a student, "completed" should be true or false,
depending on whether the requirement was met
* use the show module API and verify the correct information
is returned for a single module item
* last but not least, verify "must view" requirements can
be fulfilled through the api_data_endpoints supplied
for files, pages, discussions, and assignments
* files are viewed when downloading their content
* pages are viewed by the show action (where content
is returned)
* discussions are viewed when marked read via the
mark_topic_read or mark_all_read actions
* assignments are viewed by the show action
(where description is returned). they are not viewed
if the assignment is locked and the user does not
have access to the content yet.
Change-Id: I0cbbbc542f69215e7b396a501d4d86ff2f76c149
Reviewed-on: https://gerrit.instructure.com/13626
Tested-by: Jenkins <jenkins@instructure.com>
Reviewed-by: Simon Williams <simon@instructure.com>
2012-09-12 01:16:48 +08:00
|
|
|
}.freeze
|
2012-08-15 05:47:53 +08:00
|
|
|
|
|
|
|
def api_endpoint_info(protocol, host, url)
|
|
|
|
API_ROUTE_MAP.each_pair do |re, api_route|
|
|
|
|
match = re.match(url)
|
|
|
|
next unless match
|
|
|
|
return_type = api_route[0]
|
|
|
|
helper = api_route[1]
|
|
|
|
args = { :protocol => protocol, :host => host }
|
|
|
|
args.merge! Hash[api_route.slice(2, match.captures.size).zip match.captures]
|
|
|
|
api_route.slice(match.captures.size + 2, 1).each { |opts| args.merge!(opts) }
|
|
|
|
return { 'data-api-endpoint' => self.send(helper, args), 'data-api-returntype' => return_type }
|
|
|
|
end
|
|
|
|
{}
|
|
|
|
end
|
|
|
|
|
2014-01-11 08:44:27 +08:00
|
|
|
def self.recursively_stringify_json_ids(value, opts = {})
|
2013-10-20 01:14:31 +08:00
|
|
|
case value
|
|
|
|
when Hash
|
2014-01-11 08:44:27 +08:00
|
|
|
stringify_json_ids(value, opts)
|
|
|
|
value.each_value { |v| recursively_stringify_json_ids(v, opts) if v.is_a?(Hash) || v.is_a?(Array) }
|
2013-10-20 01:14:31 +08:00
|
|
|
when Array
|
2014-01-11 08:44:27 +08:00
|
|
|
value.each { |v| recursively_stringify_json_ids(v, opts) if v.is_a?(Hash) || v.is_a?(Array) }
|
2013-10-20 01:14:31 +08:00
|
|
|
end
|
|
|
|
value
|
|
|
|
end
|
|
|
|
|
2014-01-11 08:44:27 +08:00
|
|
|
def self.stringify_json_ids(value, opts = {})
|
2013-08-31 05:30:56 +08:00
|
|
|
return unless value.is_a?(Hash)
|
|
|
|
value.keys.each do |key|
|
|
|
|
if key =~ /(^|_)id$/
|
|
|
|
# id, foo_id, etc.
|
2014-01-11 08:44:27 +08:00
|
|
|
value[key] = stringify_json_id(value[key], opts)
|
2013-08-31 05:30:56 +08:00
|
|
|
elsif key =~ /(^|_)ids$/ && value[key].is_a?(Array)
|
|
|
|
# ids, foo_ids, etc.
|
2014-01-11 08:44:27 +08:00
|
|
|
value[key].map!{ |id| stringify_json_id(id, opts) }
|
2013-08-31 05:30:56 +08:00
|
|
|
end
|
|
|
|
end
|
|
|
|
end
|
|
|
|
|
2014-01-11 08:44:27 +08:00
|
|
|
def self.stringify_json_id(id, opts = {})
|
|
|
|
if opts[:reverse]
|
|
|
|
id.is_a?(String) ? id.to_i : id
|
|
|
|
else
|
|
|
|
id.is_a?(Integer) ? id.to_s : id
|
|
|
|
end
|
2013-08-31 05:30:56 +08:00
|
|
|
end
|
2013-10-23 23:47:41 +08:00
|
|
|
|
|
|
|
def accepts_jsonapi?
|
|
|
|
!!(/application\/vnd\.api\+json/ =~ request.headers['Accept'].to_s)
|
|
|
|
end
|
Quiz Submissions API - Create & Complete
Allows users to start a "quiz-taking session" via the API by creating
a QuizSubmission and later on completing it.
Note that this patch isn't concerned with actually using the QS to
answer questions. That task will be the concern of a new API controller,
QuizSubmissionQuestions.
closes CNVS-8980
TEST PLAN
---- ----
- Create a quiz
- Keep a tab open on the Moderate Quiz (MQ from now) page
Create the quiz submission (ie, start a quiz-taking session):
- Via the API, as a student:
- POST to /courses/:course_id/quizzes/:quiz_id/submissions
- Verify that you receive a 200 response with the newly created
QuizSubmission in the JSON response.
- Copy the "validation_token" field down, you will need this later
- Go to the MQ tab and verify that it says the student has started a
quiz attempt
Complete the quiz submission (ie, finish a quiz-taking session):
- Via the API, as a student, prepare a request with:
- Method: POST
- URI: /courses/:course_id/quizzes/:quiz_id/submissions/:id/complete
- Parameter "validation_token" to what you copied earlier
- Parameter "attempt" to the current attempt number (starts at 1)
- Now perform the request, and:
- Verify that you receive a 200 response
- Go to the MQ tab and verify that it says the submission has been
completed (ie, Time column reads "finished in X seconds/minutes")
Other stuff to test (failure scenarios):
The first endpoint (one for starting a quiz attempt) should reject your
request in any of the following cases:
- The quiz has been locked
- You are not enrolled in the quiz course
- The Quiz has an Access Code that you either didn't pass, or passed
incorrectly
- The Quiz has an IP filter and you're not in the address range
- You are already taking the quiz (you've created the submission and
did not call /complete yet)
- You are not currently taking the quiz, but you already took it
earlier and the Quiz does not allow for multiple attempts
The second endpoint (one for completing the quiz attempt) should reject
your request in any of the following cases:
- You pass in an invalid "validation_token"
- You already completed that quiz submission (e.g, you called that
endpoint earlier)
Change-Id: Iff8a47859d7477c210de46ea034544d5e2527fb2
Reviewed-on: https://gerrit.instructure.com/27015
Reviewed-by: Derek DeVries <ddevries@instructure.com>
Tested-by: Jenkins <jenkins@instructure.com>
QA-Review: Myller de Araujo <myller@instructure.com>
Product-Review: Ahmad Amireh <ahmad@instructure.com>
2013-12-05 22:10:12 +08:00
|
|
|
|
|
|
|
# Reject the API request by halting the execution of the current handler
|
|
|
|
# and returning a helpful error message (and HTTP status code).
|
|
|
|
#
|
|
|
|
# @param [String] cause
|
|
|
|
# The reason the request is rejected for.
|
2014-01-18 05:01:49 +08:00
|
|
|
# @param [Optional, Fixnum|Symbol, Default :bad_request] status
|
|
|
|
# HTTP status code or symbol.
|
|
|
|
def reject!(cause, status=:bad_request)
|
|
|
|
raise Api::V1::ApiError.new(cause, status)
|
Quiz Submissions API - Create & Complete
Allows users to start a "quiz-taking session" via the API by creating
a QuizSubmission and later on completing it.
Note that this patch isn't concerned with actually using the QS to
answer questions. That task will be the concern of a new API controller,
QuizSubmissionQuestions.
closes CNVS-8980
TEST PLAN
---- ----
- Create a quiz
- Keep a tab open on the Moderate Quiz (MQ from now) page
Create the quiz submission (ie, start a quiz-taking session):
- Via the API, as a student:
- POST to /courses/:course_id/quizzes/:quiz_id/submissions
- Verify that you receive a 200 response with the newly created
QuizSubmission in the JSON response.
- Copy the "validation_token" field down, you will need this later
- Go to the MQ tab and verify that it says the student has started a
quiz attempt
Complete the quiz submission (ie, finish a quiz-taking session):
- Via the API, as a student, prepare a request with:
- Method: POST
- URI: /courses/:course_id/quizzes/:quiz_id/submissions/:id/complete
- Parameter "validation_token" to what you copied earlier
- Parameter "attempt" to the current attempt number (starts at 1)
- Now perform the request, and:
- Verify that you receive a 200 response
- Go to the MQ tab and verify that it says the submission has been
completed (ie, Time column reads "finished in X seconds/minutes")
Other stuff to test (failure scenarios):
The first endpoint (one for starting a quiz attempt) should reject your
request in any of the following cases:
- The quiz has been locked
- You are not enrolled in the quiz course
- The Quiz has an Access Code that you either didn't pass, or passed
incorrectly
- The Quiz has an IP filter and you're not in the address range
- You are already taking the quiz (you've created the submission and
did not call /complete yet)
- You are not currently taking the quiz, but you already took it
earlier and the Quiz does not allow for multiple attempts
The second endpoint (one for completing the quiz attempt) should reject
your request in any of the following cases:
- You pass in an invalid "validation_token"
- You already completed that quiz submission (e.g, you called that
endpoint earlier)
Change-Id: Iff8a47859d7477c210de46ea034544d5e2527fb2
Reviewed-on: https://gerrit.instructure.com/27015
Reviewed-by: Derek DeVries <ddevries@instructure.com>
Tested-by: Jenkins <jenkins@instructure.com>
QA-Review: Myller de Araujo <myller@instructure.com>
Product-Review: Ahmad Amireh <ahmad@instructure.com>
2013-12-05 22:10:12 +08:00
|
|
|
end
|
2013-12-03 04:42:07 +08:00
|
|
|
|
|
|
|
# Return a template url that follows the root links key for the jsonapi.org
|
|
|
|
# standard.
|
|
|
|
#
|
|
|
|
def templated_url(method, *args)
|
|
|
|
format = /^\{.*\}$/
|
|
|
|
placeholder = "PLACEHOLDER"
|
|
|
|
|
|
|
|
placeholders = args.each_with_index.map do |arg, index|
|
|
|
|
arg =~ format ? "#{placeholder}#{index}" : arg
|
|
|
|
end
|
|
|
|
|
|
|
|
url = send(method, *placeholders)
|
|
|
|
|
|
|
|
args.each_with_index do |arg, index|
|
|
|
|
url.sub!("#{placeholder}#{index}", arg) if arg =~ format
|
|
|
|
end
|
|
|
|
|
|
|
|
url
|
|
|
|
end
|
2011-05-13 05:48:18 +08:00
|
|
|
end
|