Skip to content

Instantly share code, notes, and snippets.

@mankind
Last active March 18, 2020 11:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mankind/352639a8e8173b18822953b670a4c9ed to your computer and use it in GitHub Desktop.
Save mankind/352639a8e8173b18822953b670a4c9ed to your computer and use it in GitHub Desktop.
api-work
module Ubiquity
class ApiSerializer
attr_accessor :data
def initialize (data)
@data ||= data
end
def license_for_api
if data.try(:license).present?
remap_license
end
end
def rights_statements_for_api
if data.try(:license).present?
remap_rights_statement
end
end
def member_of_collections_for_api
if data.try(:member_of_collections) && data.class != FileSet
data.member_of_collections.map do |collection_object|
{uuid: collection_object.id, title: collection_object.title.first}
end
end
end
def alternate_identifier_for_api
if data.try(:alternate_identifier) && data.class != FileSet
remap_alternate_identifier
end
end
def related_identifier_for_api
if data.try(:related_identifier) && data.class != FileSet
remap_related_identifier
end
end
def data_filesets_summary_for_api
if data.try(:file_sets)
get_file_sets_totals
end
end
def hash_map
creator = JSON.parse(data.creator.try(:first)) if valid_json?(creator)
editor = JSON.parse(data.try(:editor).try(:first) ) if valid_json?(editor)
contributor = JSON.parse(data.contributor.try(:first) )if valid_json?(contributor)
event = JSON.parse(data.try(:event).try(:first)) if valid_json?(event)
{
uuid: data.id,
related_url: data.try(:related_url),
type: 'work',
data_type: data.try(:has_model).try(:first),
title: data.title.try(:first),
alternative_title: data.try(:alternative_title),
resource_type: data.resource_type.first.try(:split).try(:first),
creator: creator,
contributor: contributor,
editor: editor,
abstract: data.try(:abstract),
date_published: data.date_published,
institution: data.institution,
organisational_unit: data.org_unit,
project_name: data.project_name,
funder: data.funder,
publisher: data.publisher,
date_accepted: data.date_accepted,
date_submitted: data.date_submitted,
official_url: data.try(:official_url),
language: data.language,
license: data.license_for_api,
rights_statement: data.rights_statements_for_api,
rights_holder: data.rights_holder,
doi: data.doi,
alternate_identifier: data.alternate_identifier_for_api,
peer_reviewed: data.try(:peer_reviewed),
keywords: data.keyword,
dewey: data.dewey,
library_of_congress_classification: data.library_of_congress_classification,
additional_info: data.try(:add_info),
related_identifier: data.related_identifier_for_api,
version: data.try(:version),
duration: data.try(:duration),
pagination: data.pagination,
series_name: data.try(:series_name),
issue: data.try(:issue),
volume: data.try(:volume),
material_media: data.try(:material_media),
edition: data.try(:edition),
event: event,
journal_title: data.try(:journal_title),
book_title: data.try(:book_title),
article_number: data.try(:article_number),
eissn: data.try(:eissn),
issn: data.try(:issn),
isbn: data.try(:isbn),
current_he_institution: data.try(:current_he_institution),
qualification: data.try(:qualification),
alternative_journal_title: data.try(:alternative_journal_title),
thumbnail_url: img_path,
files: data.data_filesets_summary_for_api,
collections: data.member_of_collections_for_api
}
end
private
#leave it as a public method because it used in other files
# return false if == String
def valid_?(data)
!!JSON.parse(data) if data.class == String
rescue ::ParserError
false
end
def img_path
if @data.thumbnail.present?
img_path = CGI.escape(ActiveFedora::File.uri_to_id(data.thumbnail.original_file.versions.all.last.uri))
img_path.presence?
end
end
def remap_rights_statement
rights_statement_hash = Hyrax::RightsStatementService.new.select_all_options.to_h
data.rights_statement.map do |item|
if rights_statement_hash.key(item)
{
name: rights_statement_hash.key(item),
link: item
}
end
end
end
def remap_license
license_hash = Hyrax::LicenseService.new.select_all_options.to_h
data.license.map do |item|
if license_hash.key(item)
{
name: license_hash.key(item),
link: item
}
end
end
end
def remap_alternate_identifier
if valid_json?(data.alternate_identifier.first)
alternate_identifier_array = JSON.parse(data.alternate_identifier.first)
alternate_identifier_array.map do |hash|
{
name: hash['alternate_identifier'],
type: hash['alternate_identifier_type'],
postion: hash["alternate_identifier_position"].to_i
}
end
end
end
def remap_related_identifier
if valid_json?(data.related_identifier.first)
related_identifier_array = JSON.parse(data.related_identifier.first)
related_identifier_array.map do |hash|
{
name: hash['related_identifier'],
type: hash['related_identifier_type'],
relationship: hash['relation_type'],
postion: hash["related_identifier_position"].to_i
}
end
end
end
def get_file_sets_totals
file_count = data.file_sets.count
#
#returns hash that group files by their visibility eg {"open"=>2}
total_summary = data.file_sets.group_by(&:visibility).transform_values(&:count)
total_summary.merge({total: file_count})
end
end
end
git branch
api-user-signup
api_baae_controller
protect_from_forgery unless: -> { request.format.json? }
class API::V1::SessionsController < API::V1::ApiBaseController
include Ubiquity::ApiUserUtils
def create
user = User.find_for_database_authentication(email: api_user_params[:email])
if user && user.valid_password?(api_user_params[:password])
token = payload(user)
set_response_cookie(token)
participants = adminset_permissions(user)
user_type = user_roles(user)
render json: user.slice(:email).merge({participants: participants, type: user_type })
else
user_error
end
end
def destroy
domain = ('.' + request.host)
cookies.delete(:jwt, domain: domain)
render json: {message: "Successfully logged out"}, status: 200
end
def refresh
if current_user.present?
token = payload(current_user)
set_response_cookie(token)
participants = adminset_permissions(user)
user_type = user_roles(user)
render json: current_user.slice(:email).merge({participants: participants, type: user_type })
else
user_error
end
end
private
#def session_params
#params.permit(:email, :password, :expire)
#end
def user_error
message = 'This is not a valid token, inorder to refresh you must send back a valid token or you must re-log in'
error_object = Ubiquity::ApiError::NotFound.new(status: 401, code: 'Invalid credentials', message: message)
render json: error_object.error_hash
end
=begin
def payload(user)
expire = session_params[:expire]
if expire.present?
@auth_token = Ubiquity::Api::JwtGenerator.encode({id: user.id, exp: (Time.now + expire.to_i.hours).to_i})
else
@auth_token = Ubiquity::Api::JwtGenerator.encode({id: user.id})
end
end
def set_response_cookie(token)
expire = session_params[:expire].try(:hour).try(:from_now) || 1.hour.from_now
response.set_cookie(
:jwt,
{
value: token, expires: expire, path: '/',
domain: ('.' + request.host), secure: true, httponly: true
}
)
end
def adminset_permissions(user)
if user.present?
AdminSet.all.map do |admin_set|
permission_template_access = Hyrax::PermissionTemplateAccess.where(permission_template_id: admin_set.permission_template)
{
"#{admin_set.title.first}" => permission_template_access.find {
|participant_access| participant_access.try(:agent_id) == user.email
}.try(:access)
}
end
end
end
def user_roles(user)
if user.present?
roles = user.roles.map {|role| role.try(:name)}
roles - ["super_admin"]
end
end
=end
end
#Included in all models
#
module Ubiquity
module ApiUtilityMethods
extend ActiveSupport::Concern
def license_for_api
if self.try(:license).present?
remap_license
end
end
def rights_statements_for_api
if self.try(:license).present?
remap_rights_statement
end
end
def member_of_collections_for_api
if self.try(:member_of_collections) && self.class != FileSet
self.member_of_collections.map do |collection_object|
{uuid: collection_object.id, title: collection_object.title.first}
end
end
end
def alternate_identifier_for_api
if self.try(:alternate_identifier) && self.class != FileSet
remap_alternate_identifier
end
end
def related_identifier_for_api
if self.try(:related_identifier) && self.class != FileSet
remap_related_identifier
end
end
def work_filesets_summary_for_api
if self.try(:file_sets)
get_file_sets_totals
end
end
private
#leave it as a public method because it used in other files
# return false if json == String
def valid_json?(data)
!!JSON.parse(data) if data.class == String
rescue JSON::ParserError
false
end
def remap_rights_statement
rights_statement_hash = Hyrax::RightsStatementService.new.select_all_options.to_h
self.rights_statement.map do |item|
if rights_statement_hash.key(item)
{
name: rights_statement_hash.key(item),
link: item
}
end
end
end
def remap_license
license_hash = Hyrax::LicenseService.new.select_all_options.to_h
self.license.map do |item|
if license_hash.key(item)
{
name: license_hash.key(item),
link: item
}
end
end
end
def remap_alternate_identifier
if valid_json?(self.alternate_identifier.first)
alternate_identifier_array = JSON.parse(self.alternate_identifier.first)
alternate_identifier_array.map do |hash|
{
name: hash['alternate_identifier'],
type: hash['alternate_identifier_type'],
postion: hash["alternate_identifier_position"].to_i
}
end
end
end
def remap_related_identifier
if valid_json?(self.related_identifier.first)
related_identifier_array = JSON.parse(self.related_identifier.first)
related_identifier_array.map do |hash|
{
name: hash['related_identifier'],
type: hash['related_identifier_type'],
relationship: hash['relation_type'],
postion: hash["related_identifier_position"].to_i
}
end
end
end
def get_file_sets_totals
file_count = self.file_sets.count
#
#returns hash that group files by their visibility eg {"open"=>2}
total_summary = self.file_sets.group_by(&:visibility).transform_values(&:count)
total_summary.merge({total: file_count})
end
end
end
module Ubiquity
class ApiUtils
# #collection is a solr_document or a hash
def self.query_for_collection_works(collection, current_user = nil)
if collection.present? && !current_user.present?
cache_key = "child_works/#{collection['account_cname_tesim'].first}/#{collection['id']}/#{collection['system_modified_dtsi']}"
works = Rails.cache.fetch(cache_key) do
using_works_in_collecton = fetch_works_in_collection_member_objects(collection, current_user)
using_collection_ids_in_works= fetch_work_using_collection_ids_stored_in_work_metadatafield(collection, current_user)
combined_record = using_works_in_collecton['response']['docs'] | using_collection_ids_in_works['response']['docs']
using_collection_ids_in_works['response']['docs'] = combined_record
using_collection_ids_in_works['response']['numFound'] = combined_record.size
using_collection_ids_in_works
end
works['response']['docs']
elsif collection.present? && !current_user.present?
using_works_in_collecton = fetch_works_in_collection_member_objects(collection, current_user)
using_collection_ids_in_works= fetch_work_using_collection_ids_stored_in_work_metadatafield(collection, current_user)
combined_record = using_works_in_collecton['response']['docs'] | using_collection_ids_in_works['response']['docs']
using_collection_ids_in_works['response']['docs'] = combined_record
using_collection_ids_in_works['response']['numFound'] = combined_record.size
works = using_collection_ids_in_work
works['response']['docs']
else
[ ]
end
end
#collection is a solr_document or a hash
def self.group_collection_works_by_volumes(collection, current_user = nil, options = {})
group_limit = options['group_limit'] || 3000
field = options['group_parent_field']
child_group = options['group_child_field'] || "issue_tesim"
if collection.present? && !current_user.present?
id = collection.with_indifferent_access['id']
cache_key = "works_by_volumes/#{collection['account_cname_tesim'].first}/#{id}/#{collection['system_modified_dtsi']}/#{field}/#{group_limit}"
works = Rails.cache.fetch(cache_key) do
response = CatalogController.new.repository.search({ q: '', fl: 'issue_tesim, volume_tesim, title_tesim, id', fq: ['has_model_ssim:ArticleWork', "{!terms f=collection_id_sim}#{id}"],
'group.field': field, 'group.query': "#{child_group}:[* TO *]", 'group.facet': true, group: true, rows: 3000, 'group.limit': group_limit })
response_volume_grouping = response["grouped"]['volume_tesim']['groups']
remap_response_by_volumes(response_volume_grouping)
end
elsif collection.present? && current_user.present?
id = collection.with_indifferent_access['id']
response = CatalogController.new.repository.search({ q: '', fl: 'issue_tesim, volume_tesim, title_tesim, id', fq: ['has_model_ssim:ArticleWork', "{!terms f=collection_id_sim}#{id}"],
'group.field': field, 'group.query': "#{child_group}:[* TO *]", 'group.facet': true, group: true, rows: 3000, 'group.limit': group_limit })
response_volume_grouping = response["grouped"]['volume_tesim']['groups']
remap_response_by_volumes(response_volume_grouping)
end
end
def self.query_for_parent_collections(work, current_user = nil, skip_run = nil)
member_of_collection_ids = work["member_of_collection_ids_ssim"] || []
collection_id_in_works = work["collection_id_tesim"] || []
combined_collection_ids = member_of_collection_ids | collection_id_in_works
if work.present? && combined_collection_ids.present? && skip_run == 'true' && !current_user.present?
cache_key = "parent_collection/#{work['account_cname_tesim'].first}/#{work['id']}/#{combined_collection_ids.try(:size).to_i}/#{work['system_modified_dtsi']}"
parent_collections = Rails.cache.fetch(cache_key) do
collection_ids = combined_collection_ids
collections_list = CatalogController.new.repository.search(q: "", fq: ["{!terms f=id}#{collection_ids.join(',')}"
])
collections_list['response']['docs'].map do |doc|
{uuid: doc['id'], title: doc['title_tesim'].try(:first)}
end
end
parent_collections
elsif work.present? && combined_collection_ids.present? && skip_run == 'true' && current_user.present?
collection_ids = combined_collection_ids
collections_list = CatalogController.new.repository.search(q: "", fq: ["{!terms f=id}#{collection_ids.join(',')}"
])
collections_list['response']['docs'].map do |doc|
{uuid: doc['id'], title: doc['title_tesim'].try(:first)}
end
else
[ ]
end
end
def self.query_for_files(work, current_user = nil, skip_run = nil)
fq = filter_by_user(current_user)
if work.present? && work['file_set_ids_ssim'].present? && skip_run == 'true' && !current_user.present?
cache_key = "work_files/#{work['account_cname_tesim'].first}/#{work['id']}/#{work["file_set_ids_ssim"].try(:size).to_i}/#{work['system_modified_dtsi']}"
child_files = Rails.cache.fetch(cache_key) do
file_ids = work['file_set_ids_ssim'].join(',')
work_files = CatalogController.new.repository.search(q: "", fq: ["{!terms f=id}#{file_ids}"], rows: 100, "sort" => "score desc, system_modified_dtsi desc")
#child_files #['response']['docs']
file_count = work_files['response']['numFound']
summary = work_files['response']['docs'].group_by {|hash| hash['visibility_ssi']}.transform_values(&:count)
summary.merge(total: file_count)
end
child_files
elsif work.present? && work['file_set_ids_ssim'].present? && skip_run == 'true' && current_user.present?
file_ids = work['file_set_ids_ssim'].join(',')
work_files = CatalogController.new.repository.search(q: "", fq: ["{!terms f=id}#{file_ids}"].concat(fq), rows: 100, "sort" => "score desc, system_modified_dtsi desc")
#child_files #['response']['docs']
file_count = work_files['response']['numFound']
summary = work_files['response']['docs'].group_by {|hash| hash['visibility_ssi']}.transform_values(&:count)
child_files = summary.merge(total: file_count)
else
[ ]
end
end
def self.fetch_and_covert_thumbnail_to_base64_string(record, skip_run = nil)
if skip_run == 'true' && record['thumbnail_path_ss'].present?
get_thumbnail_from_fedora(record)
end
end
private
def self.get_thumbnail_from_fedora(record)
cname = record['account_cname_tesim'].first
AccountElevator.switch!(cname)
cache_type = record.fetch('has_model_ssim').try(:first) == 'Collection' ? 'fedora/collection' : 'fedora/work'
get_work = get_work_from_fedora(record, cache_type)
if get_work && get_work.visibility == 'open' && get_work.thumbnail.present? && get_work.thumbnail.visibility == 'open'
thumbnail_string = Rails.cache.fetch("single/#{cache_type}-thumbnail/#{record.fetch('account_cname_tesim').first}/#{record['id']}") do
file = get_work.thumbnail
file_path = Hyrax::DerivativePath.derivative_path_for_reference(file, 'thumbnail')
file_content = File.read(file_path)
Base64.strict_encode64(file_content)
end
thumbnail_string
else
nil
end
rescue Errno::ENOENT, StandardError => e
puts "file-path--missing-error reading a thumbnail file. #{e.inspect}"
nil
end
def self.get_work_from_fedora(record, cache_type)
if record.fetch('account_cname_tesim').present?
Rails.cache.fetch("single/#{cache_type}/#{record.fetch('account_cname_tesim').first}/#{record['id']}") do
ActiveFedora::Base.find(record['id'])
end
else
nil
end
end
def self.fetch_works_in_collection_member_objects(collection, current_user = nil)
if current_user.present?
fq = filter_by_user(current_user)
CatalogController.new.repository.search(q: "member_of_collection_ids_ssim:#{collection['id']}", rows: 200, "sort" => "score desc, system_modified_dtsi desc",
fq: fq)
else
CatalogController.new.repository.search(q: "member_of_collection_ids_ssim:#{collection['id']}", rows: 200, "sort" => "score desc, system_modified_dtsi desc",
fq: ["({!terms f=edit_access_group_ssim}public) OR ({!terms f=discover_access_group_ssim}public) OR ({!terms f=read_access_group_ssim}public)", "-suppressed_bsi:true", "", "-suppressed_bsi:true"]
)
end
end
def self.fetch_work_using_collection_ids_stored_in_work_metadatafield(collection, current_user = nil)
if current_user.present?
fq = filter_by_user(current_user)
CatalogController.new.repository.search(q: "collection_id_sim:#{collection['id']}", rows: 200, "sort" => "score desc, system_modified_dtsi desc",
fq: fq)
else
CatalogController.new.repository.search(q: "collection_id_sim:#{collection['id']}", rows: 200, "sort" => "score desc, system_modified_dtsi desc",
fq: ["({!terms f=edit_access_group_ssim}public) OR ({!terms f=discover_access_group_ssim}public) OR ({!terms f=read_access_group_ssim}public)", "-suppressed_bsi:true", "", "-suppressed_bsi:true"]
)
end
end
def self.remap_response_by_volumes(response_data)
response_array = []
response_hash = {label: '', children: [] }
response_data.each do |h|
h['doclist']['docs'].each do |ch|
response_hash[:label] = "Volume #{h['groupValue']}"
response_hash[:children] << {label: "Issue #{ch['issue_tesim'].try(:first)}",
data: {issue: "#{ch['issue_tesim'].try(:first)}", volume: "#{ch['volume_tesim'].try(:first)}"}
}
response_hash[:children].uniq!
response_array << response_hash
end
end
response_array.uniq!
end
def self.filter_by_user(user)
current_ability = Ability.new(user)
if user && current_ability.admin?
puts "baddo"
["-suppressed_bsi:true"]
elsif user && user.user_key.present?
puts "baga"
["-suppressed_bsi:true", "_query_:\"{!raw f=depositor_ssim}#{user.user_key}\""]
end
end
end
end
#/home/edward/dev-2/hyku/app/controllers/api/v1/collection_controller.rb
class API::V1::CollectionController < ApplicationController
before_action :switch_tenant
before_action :fetch_collection, only: [:show]
def index
=begin
collections = CatalogController.new.repository.search(q: '', fq: 'has_model_ssim:Collection', "sort"=>"score desc, system_create_dtsi desc",
"facet.field"=>["resource_type_sim", "creator_search_sim", "keyword_sim", "member_of_collections_ssim", "institution_sim",
"language_sim", "file_availability_sim"])
render json: collections
=end
@collections = Collection.all
end
def show
puts "nana #{@collection}"
#render json: @collection
end
private
def find_parent
@tenant = Account.find_by(tenant: params[:tenant_id])
end
def switch_tenant
find_parent
tenant_name = @tenant.cname
AccountElevator.switch!(tenant_name)
end
def fetch_collection
@collection = Collection.find(params[:id])
=begin
@collection = CatalogController.new.repository.search(q: params[:id])
add_members(@collection['response']['docs'].first['title_tesim'].first)
=end
=begin
"tata params[:id]"
collection = Collection.find(params[:id])
puts "sama #{collection.to_solr}"
@collection = {'response' => {}}
@collection['response']['docs'] = collection.to_solr
add_members(collection)
@collection
=end
end
def add_members(collection)
member_works = CatalogController.new.repository.search(q: "member_of_collections_ssim:#{collection}")
@collection['response']['member_works'] = member_works['response']['docs']
@collection
=begin
member_works = collection.member_objects
puts "lina #{member_works}"
if member_works.present?
@collection['response']['docs']['member_works'] = member_works.map(&:to_solr)
@collection
else
@collection['response']['docs']['member_works']
@collection
end
=end
=begin
def add_members(collection)
member_works = CatalogController.new.repository.search(q: "member_of_collections_ssim:#{collection}")
@collection['response']['member_works'] = member_works['response']['docs']
@collection
end
=end
end
end
class API::V1::CollectionController < ActionController::Base
include Ubiquity::ApiControllerUtilityMethods
#include Ubiquity::ApiErrorHandlers
before_action :fetch_collection, only: [:show]
def index
@collections = get_all_collections
#fresh_when(last_modified: @collections.first.to_solr["system_modified_dtsi"].try(:to_time), public: true)
end
def show
# if @collection.present?
#fresh_when(last_modified: @collection.to_solr["system_modified_dtsi"].try(:to_time), public: true)
#end
puts "lasu #{@collection}"
@single_collection = @collection
end
private
def fetch_collection
puts "nana #{params[:id]}"
collection = CatalogController.new.repository.search(q: "id:#{params[:id]}")
add_works = collection['response']['docs'].map do |hash|
hash.merge({'work_objects' => CatalogController.new.repository.search(q: "member_of_collection_ids_ssim:#{hash['id']}")} )
end
#collection['response']['docs'] = add_works
puts "ewo #{collection}"
@collection = collection['response']["docs"].first
end
def get_all_collections
#@total_count = Collection.try(:count)
total_record = CatalogController.new.repository.search(q: "id:*", fq: "has_model_ssim:Collection" , rows: 0)
total_count = total_record['response']['numFound']
#return Collection.order('system_create_dtsi desc').offset(offset).limit(limit) if limit != 0 && offset < @total_count
#Collection.order('system_create_dtsi desc')
collection = CatalogController.new.repository.search(q: '', fq: "has_model_ssim:Collection", "sort"=>"score desc, system_create_dtsi desc",
"facet.field"=>["resource_type_sim", "creator_search_sim", "keyword_sim", "member_of_collections_ssim", "institution_sim",
"language_sim", "file_availability_sim"], rows: limit, start: offset) if params[:per_page].present? && offset < total_count
collection = CatalogController.new.repository.search(q: '', fq: "has_model_ssim:Collection", "sort"=>"score desc, system_create_dtsi desc",
"facet.field"=>["resource_type_sim", "creator_search_sim", "keyword_sim", "member_of_collections_ssim", "institution_sim",
"language_sim", "file_availability_sim"], rows: 100_000_000) if params[:per_page].blank? || offset > total_count
end
end
json.total @total_count
json.items do
json.partial! 'collection', single_collection: @collection
#json.array! @collections do |collection|
#json.partial! 'collection', single_collection: collection
#end
end
#json.total @total_count
=begin
json.items do
@collections.map do |collection|
puts "david #{collections}"
#Rails.cache.fetch('all_collections' expires_in: 3.minutes) do
json.partial! 'collection', single_collection: collection
#end
end
end
=end
=begin
json.total @collections['response']['numFound']
json.items do
json.array! @collections['response']['docs'] do |single_collection|
puts "sasa #{single_collection}"
json.partial! 'api/v1/collection/collection', single_collection: single_collection #, as: :single_collection
end
end
=end
class CollectionIndexer < Hyrax::CollectionIndexer
# This indexes the default metadata. You can remove it if you want to
# provide your own metadata and indexing.
include Hyrax::IndexesBasicMetadata
# Use thumbnails served by RIIIF
self.thumbnail_path_service = IIIFCollectionThumbnailPathService
# Uncomment this block if you want to add custom indexing behavior:
def generate_solr_document
super.tap do |solr_doc|
solr_doc[Solrizer.solr_name('collection_tenant_url', :stored_searchable)] = Ubiquity::FetchTenantUrl.new(object).process_url
solr_doc[Solrizer.solr_name('license_for_api', :stored_searchable)] = object.license_for_api.presence
solr_doc[Solrizer.solr_name('rights_statements_for_api', :stored_searchable)] = object.rights_statements_for_api.presence
end
end
end
#/home/edward/dev-2/hyku/app/views/api/v1/collection/show.json.jbuilder
=begin
["id", "account_cname", "depositor", "title", "date_uploaded", "date_modified", "label", "relative_path", "import_url",
"resource_type", "creator", "contributor", "description", "keyword", "license", "rights_statement", "publisher", "date_created",
"subject", "language", "identifier", "based_near", "related_url", "bibliographic_citation", "source", "access_control_id",
"representative_id", "thumbnail_id"]
=end
json.partial! 'collection', single_collection: @collection
=begin
@collection['response']['docs'].each do |work|
puts "baba #{work}"
end
puts "coli #{@collection['response']['docs']}"
@collection['response']['docs'].each do |collection|
puts "winy #{@collection}"
json.uuid collection['id']
json.related_url collection['related_url_tesim']
json.title collection['title_tesim'].try(:first)
json.resource_type collection['resource_type_sim'].try(:first)
json.date_created collection['date_created_tesim']
creator = collection['creator_tesim'].try(:first)
if valid_json?(creator)
json.creator JSON.parse(creator)
end
contributor = collection['contributor_tesim'].try(:first)
if valid_json?(contributor)
json.contributor JSON.parse(contributor)
end
editor = collection['editor_tesim'].try(:first)
if valid_json?(editor)
json.editor JSON.parse(editor)
end
json.description collection['description_tesim'].try(:first)
json.date_published collection['date_published_tesim']
json.keywords collection['keyword_tesim']
json.license_for_api_tesim collection['license_for_api_tesim']
json.rights_statements_for_api_tesim collection['rights_statements_for_api_tesim']
json.language collection['language_tesim']
json.publisher collection['publisher_tesim']
json.thumbnail_url ('https://' + collection['account_cname_tesim'].first + collection['thumbnail_path_ss'])
json.visbility collection['visibility_ssi']
end
=end
=begin
json.works do
json.array! @collection['response']['member_works'] do |work|
puts "taru #{work}"
json.partial! 'api/v1/work/work', work: work
end
end
=end
//https://github.com/ubiquitypress/hyku/blob/test/app/assets/javascripts/ubiquity/creator.js#L82-L100
function displayFields(self){
var _this = $(self);
if (self.value == 'Personal') {
hideCreatorOrganization(_this);
$(self).siblings(".ubiquity_organization_fields").hide();
_this = $(self).siblings(".ubiquity_personal_fields:last");
creatorAddOrRemoveRequiredAndMessage(_this);
$(this).siblings(".ubiquity_personal_fields").show();
} else if(self.value == "Organisational") {
hideCreatorPersonal(_this);
$(this).siblings(".ubiquity_personal_fields").hide();
var _this = $(self).siblings('.ubiquity_organization_fields:last');
creatorOrganizationAddOrRemoveRequiredAndMessage(_this);
} else{
$('.ubiquity_creator_name_type:last').val('Personal').change()
}
}
//https://github.com/ubiquitypress/hyku/blob/test/app/assets/javascripts/ubiquity/creator.js#L154-L159
function hideCreatorPersonal(self){
self.siblings(".ubiquity_personal_fields").find(".ubiquity_creator_family_name:last").val('').removeAttr('required').next("span.error").hide();
self.siblings(".ubiquity_personal_fields").find(".ubiquity_creator_given_name:last").val('').removeAttr('required').next("span.error").hide();
self.siblings(".ubiquity_personal_fields").find(".ubiquity_creator_orcid:last").val('');
self.siblings(".ubiquity_personal_fields").find(".ubiquity_creator_institutional_relationship:last").val('');
self.siblings(".ubiquity_personal_fields").hide();
}
module Ubiquity
module Api
class GetFormFields
attr_accessor :work_name, :tenant_settings
def initialize(work_name)
@work_name = work_name
@tenant_settings = settings_hash
end
def form_object
#Hyrax.const_get("#{curation_concern.model_name.name}Form")
form_name = work_name + "_form"
"Hyrax::#{form_name.classify}".camelize.constantize
rescue NameError => e
nil
end
def required_fields
if form_object.present?
form_object.required_fields - unwanted_fields
end
end
def optional_fields
if form_object.present?
form_object.terms - unwanted_fields
end
end
def array_fields
if form_object.present?
array_1 = required_fields.map {|field| field if form_object.multiple? field}.compact
array_2 = optional_fields.map {|field| field if form_object.multiple? field}.compact
array_1.concat(array_2)
end
end
def permitted_params
if form_object.present?
form_object.build_permitted_params
end
end
def work_names
if @tenant_settings.present?
@tenant_settings["registered_curation_concern_types"]
end
end
def unwanted_fields
if tenant_settings.present?
keys = tenant_settings["work_unwanted_fields"][work_name]
keys_array = keys.split(',')
keys_array.present? ? keys_array.map(&:to_sym) : []
end
end
private
def settings_hash
env = ENV['TENANTS_WORK_SETTINGS']
if env.present? && env.class == String
JSON.parse(env)
end
rescue JSON::ParserError => e
{}
end
end
end
end
class API::V1::HighlightsController < ActionController::Base
#defines :limit, :default_limit, :models_to_search, :switche_tenant
include Ubiquity::ApiControllerUtilityMethods
include Ubiquity::ApiErrorHandlers
def index
@collections = get_collections
@featured_works = get_featured_works
@recent_documents = get_recent_documents
end
private
def get_featured_works
featured_works = FeaturedWorkList.new.featured_works
end
def get_collections
#collections = CatalogController.new.repository.search(q: 'id:*', fq: 'has_model_ssim:Collection', rows: offset, sort: 'system_created_dtsi desc')
#add_works = collections['response']['docs'].map{|hash| hash.merge({'work_objects' => CatalogController.new.repository.search(q: "member_of_collection_ids_ssim:#{hash['id']}")} ) }
#collections['response']['docs'] = add_works
return Collection.order('system_create_dtsi desc').limit(default_limit) if params[:per_page].blank?
Collection.order('system_create_dtsi desc').limit(limit)
end
def get_recent_documents
## CatalogController.new.repository.search(:q=>"id:*", sort: 'system_create_dtsi desc', rows: 5, fq: models_to_search)
retun ActiveFedora::Base.where(models_to_search).order('system_create_dtsi desc').limit(default_limit) if params[:per_page].blank?
ActiveFedora::Base.where(models_to_search).order('system_create_dtsi desc').limit(limit)
end
def return_featured_works
ids = featured_works.map(&:work_id)
if params[:per_page].blank?
records = ActiveFedora::Base.where(id: ids).limit(default_limit)
else
records = ActiveFedora::Base.where(id: ids).limit(limit)
end
end
def add_caching(search_query, records)
record = ActiveFedora::Base.where(search_query)
if record.present?
fresh_when(etag: records,
last_modified: record.order('system_modified_dtsi desc').last.date_modified.to_time,
public: true)
end
end
end
class API::V1::HighlightsController < API::V1::ApiBaseController
#defines :limit, :default_limit, :models_to_search, :switche_tenant
include Ubiquity::ApiControllerUtilityMethods
include Ubiquity::ApiCacheKeyGenerator
before_action :set_limit
def index
@collections = get_collections || []
@featured_works = get_featured_works || []
@recent_documents = get_recent_documents || []
if !current_user.present?
json = Rails.cache.fetch("multiple/highlights/#{@tenant.try(:cname)}/#{set_last_modified_date}") do
render_to_string(:template => 'api/v1/highlights/index.json.jbuilder', locals: {collections: @collections, featured_works: @featured_works,
recent_documents: @recent_documents })
end
elsif current_user.present?
puts "london"
json = render_to_string(:template => 'api/v1/highlights/index.json.jbuilder', locals: {collections: @collections, featured_works: @featured_works,
recent_documents: @recent_documents })
end
render json: json
end
private
def get_collections
record = CatalogController.new.repository.search(q: "id:*", fq: "has_model_ssim:Collection" , rows: 1, "sort" => "score desc, system_modified_dtsi desc")
collection_id = record.dig('response','docs').presence && record.dig('response','docs').first['id']
#last_updated_child = CatalogController.new.repository.search(q: "member_of_collection_ids_ssim:#{collection_id}", rows: 1, "sort" => "score desc, system_modified_dtsi desc")
using_works_in_collecton = CatalogController.new.repository.search(q: "member_of_collection_ids_ssim:#{collection_id}", rows: 1, "sort" => "score desc, system_modified_dtsi desc")
using_collection_ids_in_works = CatalogController.new.repository.search(q: "collection_id_sim:#{collection_id}", rows: 1, "sort" => "score desc, system_modified_dtsi desc")
combined_record = using_works_in_collecton['response']['docs'] | using_collection_ids_in_works['response']['docs']
using_collection_ids_in_works['response']['docs'] = combined_record
using_collection_ids_in_works['response']['numFound'] = combined_record.size
last_updated_child = using_collection_ids_in_works
if record.dig('response','docs').try(:present?) && !current_user.present?
set_cache_key = add_filter_by_class_type_with_pagination_cache_key(record, last_updated_child)
fq = ['has_model_ssim:Collection'].concat(filter_using_visibility)
collections_json = Rails.cache.fetch(set_cache_key) do
CatalogController.new.repository.search(q: 'id:*', fq: fq, rows: limit, sort: 'system_created_dtsi desc')
end
elsif current_user.present?
fq = ['has_model_ssim:Collection'].concat(filter_by_role(current_user))
CatalogController.new.repository.search(q: 'id:*', fq: fq, rows: limit, sort: 'system_created_dtsi desc')
end
end
def get_recent_documents
record = CatalogController.new.repository.search(q: "id:*", fq: models_to_search , rows: 1, "sort" => "score desc, system_modified_dtsi desc")
total_count = record['response']['numFound']
file_ids = record && record['response']['docs'].presence && record['response']['docs'].first["file_set_ids_ssim"]
new_file_ids = file_ids.present? ? file_ids.join(',') : nil
last_updated_child = CatalogController.new.repository.search(q: "", fq: ["{!terms f=id}#{new_file_ids}"] , rows: 1, "sort" => "score desc, system_modified_dtsi desc")
if record.dig('response','docs').try(:present?) && !current_user.present?
puts "enter"
set_cache_key = add_filter_by_class_type_with_pagination_cache_key(record, last_updated_child)
Rails.cache.fetch(set_cache_key) do
CatalogController.new.repository.search(:q=>"id:*", sort: 'system_create_dtsi desc', rows: limit, fq: visibility_check)
end
elsif current_user.present?
puts "indian #{current_user.inspect}"
CatalogController.new.repository.search(:q=>"id:*", sort: 'system_create_dtsi desc', rows: limit, fq: visibility_check_by_role(current_user) )
end
end
def get_featured_works
@featured = FeaturedWorkList.new.featured_works
ids = @featured.map(&:work_id)
joined_ids = ids.present? ? ids.join(',') : nil
record = CatalogController.new.repository.search(q: "", fq: ["{!terms f=id}#{joined_ids}"], rows: 1, "sort" => "score desc, system_modified_dtsi desc")
file_ids = record && record['response']['docs'].presence && record['response']['docs'].first["file_set_ids_ssim"]
new_file_ids = file_ids.present? ? file_ids.join(',') : nil
last_updated_child = CatalogController.new.repository.search(q: "", fq: ["{!terms f=id}#{new_file_ids}"], rows: 1, "sort" => "score desc, system_modified_dtsi desc")
recently_updated = recency_between_files_and_featured_work(last_updated_child)
fq = ["{!terms f=id}#{ids.join(',')}"].concat(visibility_check)
if record.dig('response','docs').try(:present?) && !current_user.present?
set_cache_key = add_filter_by_class_type_with_pagination_cache_key(record, recently_updated)
Rails.cache.fetch(set_cache_key) do
data = CatalogController.new.repository.search(q: "", fq: fq, rows: limit)
end
elsif current_user.present?
fq = ["{!terms f=id}#{ids.join(',')}"].concat(visibility_check_by_role(current_user) )
data = CatalogController.new.repository.search(q: "", fq: fq, rows: limit)
end
end
def recency_between_files_and_featured_work(last_updated_child)
latest_featured = @featured.try(:max)
latest_file_from_work = last_updated_child['response']['docs'].presence && last_updated_child['response']['docs'].first['system_modified_dtsi']
latest_from_time_stamp = [latest_featured.to_s, latest_file_from_work.to_s].max
if latest_from_time_stamp == latest_featured
@featured
else
last_updated_child
end
end
def set_limit
if filter_strong_params[:per_page].blank?
@limit = default_limit_for_hightlights
end
end
def set_last_modified_date
collection_records = get_collections.presence && get_collections['response']['docs'].try(:first).dig('system_modified_dtsi')
featured_records = get_featured_works.presence && get_featured_works['response']['docs'].map{|h| h['system_modified_dtsi']}.try(:max)
recent_records = get_recent_documents.presence && get_recent_documents['response']['docs'].try(:first).dig('system_modified_dtsi')
featured_works = recent_updated_featured_works_time_stamp
dates_array = [collection_records, featured_records, recent_records, featured_works].compact.max
end
def recent_updated_featured_works_time_stamp
@featured && @featured.map{|record| record.updated_at}.try(:max).try(:to_time).try(:utc).try(:iso8601)
end
end
#json.explore_collections do
#json.partial! 'api/v1/collection/collection', collection: @collections, as: :single_collection, cached: true
#end
#json.featured_works do
#json.partial! 'api/v1/work/work_only', collection: @featured_works, as: :work, cached: true
#end
#json.recent_works do
#json.partial! 'api/v1/work/work_only', collection: @recent_documents, as: :work, cached: true
#end
#/home/edward/dev-2/hyku/app/controllers/api/v1/home_controller.rb
class API::V1::HomeController < ApplicationController
before_action :switch_tenant
def index
@collections = CatalogController.new.repository.search(q: 'id:*', fq: 'has_model_ssim:Collection', rows: 5, "sort"=>"system_create_dtsi desc")
@featured_works = featured_work
puts "lingo #{@featured_works}"
@recent_documents = CatalogController.new.repository.search(q: '', fq: models_to_search, "sort"=>"score desc, system_create_dtsi desc",
"facet.field"=>["resource_type_sim", "creator_search_sim", "keyword_sim", "member_of_collections_ssim", "institution_sim", "language_sim",
"file_availability_sim"], rows: 5)
render json: {collections: @collections['response']['docs'], featured: @featured_works['response']['docs'],
recent: @recent_documents['response']['docs'] }
end
private
def find_parent
@tenant = Account.find_by(tenant: params[:tenant_id])
end
def models_to_search
'has_model_ssim:Article OR has_model_ssim:Book OR has_model_ssim:BookContribution OR has_model_ssim:ConferenceItem OR has_model_ssim: Dataset OR has_model_ssim:ExhibitionItem OR has_model_ssim:Image OR has_model_ssim:Report OR has_model_ssim:ThesisOrDissertation OR has_model_ssim:TimeBasedMedia OR has_model_ssim:GenericWork'
end
def switch_tenant
find_parent
tenant_name = @tenant.cname
AccountElevator.switch!(tenant_name)
end
def featured_work
featured_works = FeaturedWorkList.new.featured_works
puts "gbemi #{featured_works}"
records = ActiveFedora::Base.where(id: featured_works.map(&:work_id))
puts "roland #{records}"
work = {'response' => {} }
solr_docs = records.map(&:to_solr)
puts "sari #{solr_docs}"
work['response']['docs'] = solr_docs
work
end
end
#/home/edward/dev-2/hyku/app/controllers/ubiquity/oai_extension.rb
# Overriding the oai config to display the request url in the OAI template
# Overriding the oai_config method
# projectblacklight/blacklight_oai_provider/blob/master/app/controllers/concerns/blacklight_oai_provider/controller.rb#L29
module Ubiquity
module OaiExtension
extend ActiveSupport::Concern
def oai_config
#swap_hash = JSON.parse(ENV['TENANTS_WORK_SETTINGS'])
#swap_values = swap_hash && swap_hash['oai_name_swap']
oai_name_swap = {"oar": "iro", "collections": "collection"}
if oai_name_swap #swap_hash
subdomain = ActionDispatch::Http::URL.extract_subdomains(request.host, 1).first
#redirect_url = request.original_url.gsub(/subdomain/) {|key| oai_name_swap[key]}
redirect_url = 'https://bl.oar.bl.uk//catalog/oai'.gsub(/oar/) {|key| oai_name_swap.with_indifferent_access[key]}
puts "wasiu #{redirect_url}"
blacklight_config.oai.merge(provider: { repository_url: redirect_url }) || {provider: { repository_url: redirect_url }}
else
blacklight_config.oai.merge(provider: { repository_url: request.original_url }) || {provider: { repository_url: request.original_url }}
end
end
end
end
#/home/edward/dev-2/hyku/app/services/ubiquity/fetch_tenant_url.rb
module Ubiquity
class FetchTenantUrl
def initialize(object)
@account_cname = object.try(:account_cname)
@id = object.try(:id)
@work_type = object.try(:has_model).try(:first).to_s
@is_collection = object.collection?
end
def process_url
return nil if @account_cname.nil?
work_type = @work_type.tableize
#if @account_cname.split('.').include? 'localhost'
#@is_collection ? "http://#{@account_cname}:3000/#{work_type}/#{@id}" : "http://#{@account_cname}:3000/concern/#{work_type}/#{@id}"
#else
@is_collection ? "https://#{@account_cname}/#{work_type}/#{@id}" : "https://#{@account_cname}/concern/#{work_type}/#{@id}"
#end
end
end
end
class SharedIndexer < Hyrax::WorkIndexer
# Use thumbnails served by RIIIF
self.thumbnail_path_service = IIIFWorkThumbnailPathService
def generate_solr_document
super.tap do |solr_doc|
solr_doc[Solrizer.solr_name('contributor_list', :stored_searchable)] = Ubiquity::ParseJson.new(object.contributor.first).fetch_value_based_on_key('contributor')
solr_doc['date_published_si'] = Ubiquity::ParseDate.return_date_part(object.date_published, 'year')
solr_doc[Solrizer.solr_name('all_orcid_isni', :stored_searchable)] = Ubiquity::FetchAllOrcidIsni.new(object).fetch_data
solr_doc[Solrizer.solr_name('work_tenant_url', :stored_searchable)] = Ubiquity::FetchTenantUrl.new(object).process_url
# Following values were showing in OAI when the value is blank, Added a new field to display if the valuse is present
solr_doc[Solrizer.solr_name('abstract_oai', :stored_searchable)] = object.abstract.presence
solr_doc[Solrizer.solr_name('official_link_oai', :stored_searchable)] = object.official_link.presence
solr_doc[Solrizer.solr_name('doi_oai', :stored_searchable)] = object.doi.presence
puts "huhu #{object.member_of_collections_for_api.presence}"
solr_doc['member_of_collections_for_api_tesim'] = object.member_of_collections_for_api.presence
=begin
solr_doc[Solrizer.solr_name('license_for_api', :stored_searchable)] = object.license_for_api.presence
solr_doc[Solrizer.solr_name('rights_statements_for_api', :stored_searchable)] = object.rights_statements_for_api.presence
solr_doc[Solrizer.solr_name('alternate_identifier_for_api', :stored_searchable)] = object. alternate_identifier_for_api.presence
solr_doc[Solrizer.solr_name('related_identifier_for_api', :stored_searchable)] = object.related_identifier_for_api.presence
=end
puts "habi #{object.work_filesets_summary_for_api.presence}"
#solr_doc[Solrizer.solr_name('work_filesets_summary_for_api', :stored_searchable)] = object.work_filesets_summary_for_api.presence
solr_doc['work_filesets_summary_for_api_tesim'] = object.work_filesets_summary_for_api.presence
end
end
end
module Ubiquity
module ApiErrorHandlers
extend ActiveSupport::Concern
included do
rescue_from StandardError do |exception|
other_errors(exception)
end
rescue_from RSolr::Error::Http, ActiveFedora::ObjectNotFoundError do |exception|
render_error(exception)
end
rescue_from Ubiquity::ApiError do |exception|
render_custom_error(exception)
end
end
private
def render_error(exception)
if exception.class == ActiveFedora::ObjectNotFoundError
message = exception.to_s.gsub('ActiveFedora::Base', 'record')
error_object = Ubiquity::ApiError::NotFound.new(status: '500', code: 'not_found', message: message)
end
if exception.class == RSolr::Error::Http
message = "Please check the request path #{request.path} & ensure you add per_page if you" \
"send back just #{request.fullpath}. That is do not send only ?page=number given"
error_object = Ubiquity::ApiError::NotFound.new(status: '400', code: 'Bad Request', message: message)
end
render json: error_object.error_hash
end
def render_custom_error(message)
redirect_to api_v1_errors_path(errors: message.error_hash)
end
def other_errors(exception)
message = "This request #{request.original_fullpath} threw an error #{exception}, please check it and try again"
error_object = Ubiquity::ApiError::NotFound.new(status: '500', code: 'Server Error', message: message)
render json: error_object.error_hash
end
end
end
# rails g controller api/v1/work/under_review --no-helper --no-assets --no-view-specs
#route
scope module: 'work' do
resources :under_review, only: [:index], defaults: {format: :json}
end
class API::V1::Work::UnderReviewController < API::V1::ApiBaseController
#defines :limit, :default_limit, :models_to_search, :switche_tenant
include Ubiquity::ApiControllerUtilityMethods
include Ubiquity::ApiCacheKeyGenerator
def index
@works = CatalogController.new.repository.search(q: '', fq: ["({!terms f=workflow_state_name_ssim}pending_review) OR ({!terms f=workflow_state_name_ssim}changes_required)"], "sort" => "score desc, system_create_dtsi desc", rows: default_limit, start: offset)
if current_ability.can?(:review, :submissions) && @works['response']['docs'].present?
works_json = render_to_string(:template => 'api/v1/work/index.json.jbuilder', locals: {works: @works })
render json: works_json
else
raise Ubiquity::ApiError::NotFound.new(status: 404, code: 'not_found', message: "This tenant has no works under review or you are not permitted to manage works under review")
end
end
end
### work/under_review/index.json.jbuilder
json.total @works.presence && @works['response']['numFound']
work_records = @works.presence && @works['response']['docs']
json.items do
if work_records.present?
json.array! @works['response']['docs'] do |work|
json.partial! 'api/v1/work/work', work: work
end
end
end
class API::V1::WorkController < ActionController::Base
#defines :limit, :default_limit, :models_to_search, :switche_tenant
include Ubiquity::ApiControllerUtilityMethods
#include Ubiquity::ApiErrorHandlers
before_action :fetch_work, only: [:show, :manifest]
def index
if request.query_parameters.blank? || request.query_parameters.keys.to_set == ["per_page", "page"].to_set || request.query_parameters.keys == ["per_page"]
fetch_all_works
elsif params[:type].present?
filter_by_resource_type
else
filter_by_metadata
end
end
def show
#fresh_when(etag: @fedora_work, last_modified: @fedora_work.date_modified, public: true)
end
def manifest
#work_class = ActiveFedora::Base.find(params[:id]).class.to_s.pluralize
work_class = @work['has_model_ssim']
controller_in_use = "Hyrax::#{work_class}Controller".camelize.constantize.new
#request.env["HTTP_HOST"] = @fedora_work.account_cname
request.env["HTTP_HOST"] = @work['account_cname_tesim']
controller_in_use.request = request
controller_in_use.response = response
record = controller_in_use.manifest
render json: record
end
private
def fetch_work
work = CatalogController.new.repository.search(q: params[:id], "sort" => "score desc, system_create_dtsi desc",
"facet.field "=> ["resource_type_sim", "creator_search_sim", "keyword_sim", "member_of_collections_ssim", "institution_sim",
"language_sim", "file_availability_sim"])
@work = work['response']['docs'].first
end
=begin
def fetch_all_works
@works_cache_name = 'fetch_all_works_jbuilder'
@total_count = ActiveFedora::Base.where(models_to_search).count
@last_modified = ActiveFedora::Base.where(models_to_search).order('system_modified_dtsi desc').last.date_modified.to_time
json = Rails.cache.fetch('fetch_all_work', expires_in: 30.seconds) do
@works = ActiveFedora::Base.where(models_to_search).order('system_create_dtsi desc').offset(offset).limit(limit) if limit != 0 && offset < @total_count
@works = ActiveFedora::Base.where(models_to_search).order('system_create_dtsi desc') if params[:per_page].blank?
render_to_string(:template => 'api/v1/work/index.json.jbuilder', locals: {works: @works, total_count: @total_count, cache_name: @works_cache_name })
end
if stale?(last_modified: @last_modified, public: true)
render json: json
end
end
=end
def fetch_all_works
total_record = CatalogController.new.repository.search(q: "id:*", fq: models_to_search , rows: 0)
total_count = total_record['response']['numFound']
puts "tallou #{total_count}"
puts "limo #{limit}"
puts "efo #{offset}"
@works = CatalogController.new.repository.search(q: '', fq: models_to_search, "sort" => "score desc, system_create_dtsi desc",
"facet.field" => ["resource_type_sim", "creator_search_sim", "keyword_sim", "member_of_collections_ssim", "institution_sim",
"language_sim", "file_availability_sim"], rows: limit, start: offset) if params[:per_page].present? && offset < total_count
puts "masa #{@work}"
return @work if params[:per_page].present? && offset < total_count
@limit = default_limit
@works = CatalogController.new.repository.search(q: '', fq: models_to_search, "sort" => "score desc, system_create_dtsi desc",
"facet.field" => ["resource_type_sim", "creator_search_sim", "keyword_sim", "member_of_collections_ssim", "institution_sim",
"language_sim", "file_availability_sim"], rows: limit) if params[:per_page].blank? || offset > total_count
#
puts "dadi #{@works['response']['numFound']}"
#puts "dani #{@works['response']['facet_fields']['resource_type_sim']}"
#render :template => 'api/v1/work/t', :collection => @works['response']['docs'], as: :work
#render :partial => "api/v1/work/work.json.jbuilder", :collection => @works['response']['docs'], as: :work
#render json: @works
@works
end
=begin
def filter_by_resource_type
@works_cache_name = 'filter_by_resource_type_jbuilder'
klass = params[:type].camelize.constantize
@total_count = klass.order('system_create_dtsi desc').count
@last_modified = ActiveFedora::Base.where("has_model_ssim:#{params[:type].camelize}").order('system_modified_dtsi desc').last.date_modified.to_time
puts "lula #{offset}"
puts "lali #{limit}"
puts "goga #{params[:per_page]}"
puts "paga #{params[:page]}"
json = Rails.cache.fetch('filter_by_resource_type_jbuilder', expires_in: 30.seconds) do
@works = klass.order('system_create_dtsi desc').offset(offset).limit(limit) if limit != 0 && offset < @total_count
@works = klass.order('system_create_dtsi desc') if params[:per_page].blank? || offset > @total_count
puts "wawo #{@works.size}"
render_to_string(:template => 'api/v1/work/index.json.jbuilder', locals: {works: @works, total_count: @total_count, cache_name: @works_cache_name })
end
#if stale?(last_modified: @last_modified, public: true)
render json: json
#end
end
=end
def filter_by_resource_type
total_record = CatalogController.new.repository.search(q: "id:*", fq: "has_model_ssim:#{params[:type].camelize.constantize}" , rows: 0)
total_count = total_record['response']['numFound']
return @works = CatalogController.new.repository.search(q: "id:*", fq: "has_model_ssim:#{params[:type].camelize.constantize}", rows: limit, start: offset ) if params[:per_page].present? && offset < total_count
@limit = default_limit
@works = CatalogController.new.repository.search(q: "id:*", fq: "has_model_ssim:#{params[:type].camelize.constantize}", rows: limit ) if params[:per_page].blank? || offset > total_count
#render json: works
#@works = params[:type].camelize.all
end
def filter_by_metadata
#metadata_field = request.query_parameters.keys.first.to_sym
#value = request.query_parameters[metadata_field]
extracted_params = request.query_parameters.except(*['per_page', 'page'])
metadata_field = extracted_params.keys.first.try(:to_sym)
puts "sola #{metadata_field}"
value = extracted_params[metadata_field]
if [:availability].include? metadata_field
puts "loma #{value}"
puts "lani #{map_search_values[value.to_sym]}"
puts "soro #{map_search_keys[metadata_field]}"
total_record = CatalogController.new.repository.search(q: "id:*", fq: ["{!term f=file_availability_sim}#{map_search_values[value.to_sym]}", "{!terms f=has_model_ssim}#{model_list}"], rows: 0)
total_count = total_record['response']['numFound']
##goood
#@works = CatalogController.new.repository.search(:q=>"", fq: ["{!term f=file_availability_sim}File not available", "{!terms f=has_model_ssim}#{model_list}"])
#@works = CatalogController.new.repository.search(q: "#{map_search_keys[metadata_field]}:#{map_search_values[value.to_sym]}")
return @works = CatalogController.new.repository.search(:q=>"", fq: ["{!term f=file_availability_sim}#{map_search_values[value.to_sym]}", "{!terms f=has_model_ssim}#{model_list}"], rows: limit, start: offset) if params[:per_page].present? && offset < total_count
@limit = default_limit
@works = CatalogController.new.repository.search(:q=>"", rows: limit, fq: ["{!term f=file_availability_sim}#{map_search_values[value.to_sym]}", "{!terms f=has_model_ssim}#{model_list}"]) if params[:per_page].blank? || offset > total_count
##
#work = CatalogController.new.repository.search(q: '', fq: ["{!term f=file_availability_sim}File not available"])
#@works = CatalogController.new.repository.search(q: '', fq: ["{!term f=#{map_search_keys[metadata_field]}}#{map_search_values[value.to_sym]}"])
#render json: work
else
puts "yeye"
total_record = CatalogController.new.repository.search(q: "#{map_search_keys[metadata_field]}:#{value}", rows: 0)
total_count = total_record['response']['numFound']
return @works = CatalogController.new.repository.search(q: "#{map_search_keys[metadata_field]}:#{value}", rows: limit, start: offset) if params[:per_page].present? && offset < total_count
@limit = default_limit
@works = CatalogController.new.repository.search(q: "#{map_search_keys[metadata_field]}:#{value}", rows: limit) if params[:per_page].blank? || offset > total_count
#render json: work
end
end
=begin
def filter_by_metadata
extracted_params = request.query_parameters.except(*['per_page', 'page'])
metadata_field = extracted_params.keys.first.try(:to_sym)
value = extracted_params[metadata_field]
if metadata_field.present? && [:availability].include?(metadata_field)
query_by_availability(metadata_field, value)
elsif [:collection_uuid].include? metadata_field
query_by_collection(metadata_field, value)
elsif metadata_field.present?
query_by_metadata(metadata_field, value)
else
raise Ubiquity::ApiError::BadRequest.new(status: 400, code: 'Bad Request', message: "Please check the request path #{request.path} & ensure you add per_page if you send back just #{request.original_fullpath}. That is do not send only ?page=number given" )
end
end
=end
def query_by_availability(metadata_field, value)
@total_count = ActiveFedora::Base.where("#{map_search_keys[metadata_field]}:#{map_search_values[value.to_sym]}").count
if limit != 0 && offset < @total_count
@works = ActiveFedora::Base.where("#{map_search_keys[metadata_field]}:#{map_search_values[value.to_sym]}").offset(offset).limit(limit)
else
@works = ActiveFedora::Base.where("#{map_search_keys[metadata_field]}:#{map_search_values[value.to_sym]}")
end
raise Ubiquity::ApiError::NotFound.new(status: '404', code: 'not_found', message: "No record was found for #{metadata_field} with value of #{value}") if @works.blank?
add_caching("#{map_search_keys[metadata_field]}:#{map_search_values[value.to_sym]}")
end
def query_by_collection(metadata_field, value)
@query_by_collection_jbuilder_cache_name = 'query_by_collection_jbuilder'
@total_count = collection.try(:member_objects).try(:count)
collection = Collection.find(value)
last_modified = [collection.member_objects.try(:first).try(:date_modified).try(:to_time), collection.to_solr["system_modified_dtsi"].try(:to_time)].compact.max
json = Rails.cache.fetch('query_by_collectio_jbuilder', expires_in: 3.minutes) do
@works = collection.try(:member_objects)
render_to_string(:template => 'api/v1/work/index.json.jbuilder', locals: {works: @works, total_count: @total_count, cache_name: @query_by_collection_jbuilder_cache_name })
end
raise Ubiquity::ApiError::NotFound.new(status: '404', code: 'not_found', message: "Collection with id #{value} has no works") if @works.blank?
#collection.member_objects returns the most recently modified work first
if stale?(last_modified: @last_modified, public: true)
render json: json
end
end
def query_by_metadata(metadata_field, value)
@total_count = ActiveFedora::Base.where("#{map_search_keys[metadata_field]}:#{value}").count
if limit != 0 && offset < @total_count
@works = ActiveFedora::Base.where("#{map_search_keys[metadata_field]}:#{value}").offset(offset).limit(limit)
else
@works = ActiveFedora::Base.where("#{map_search_keys[metadata_field]}:#{value}")
end
raise Ubiquity::ApiError::NotFound.new(status: '404', code: 'not_found', message: "No record was found for #{metadata_field} with value of #{value}") if @works.blank?
add_caching("#{map_search_keys[metadata_field]}:#{value}")
end
def add_caching(search_query)
record = ActiveFedora::Base.where(search_query)
if record.present?
fresh_when(last_modified: record.order('system_modified_dtsi desc').last.date_modified.to_time,
public: true)
end
end
def map_search_keys
{
creator: 'creator_tesim',
keyword: 'keyword_sim',
#collection_uuid: 'id',
collection_uuid: 'member_of_collection_ids_ssim', #'member_of_collections_ssim',
language: 'language_sim',
availability: 'file_availability_sim'
}
end
def map_search_values
{
not_available: 'File not available', # 'File+not+available',
available: 'File available from this repository', #'File+available+from+this+repository',
external_link: 'External link (access may be restricted)' #'External+link+access+may+be+restricted'
}
end
end
#/home/edward/dev-2/hyku/app/views/api/v1/work/_work.json.jbuilder
#mime_type_ssi
#file_size_lts
#date_uploaded_dtsi
#visibility_ssi
#alternate_identifier_for_api_tesim
#rights_statements_for_api_tesim
#license_for_api_tesim
#related_identifier_for_api_tesim
#member_of_collections_for_api
#work_filesets_summary_for_api
#json.cache! work, expires_in: 1.minutes do
json.uuid work['id']
json.related_url work['related_url_tesim']
json.work_type work['has_model_ssim'].try(:first)
json.title work['title_tesim'].try(:first)
json.alternative_title work['alternative_title_tesim']
json.resource_type work['resource_type_sim'].try(:first)
json.visibility work['visibility_ssi']
creator = work['creator_tesim'].try(:first)
if valid_json?(creator)
json.creator JSON.parse(creator)
end
contributor = work['contributor_tesim'].try(:first)
if valid_json?(contributor)
json.contributor JSON.parse(contributor)
end
editor = work['editor_tesim'].try(:first)
if valid_json?(editor)
json.editor JSON.parse(editor)
end
# json.editor JSON.parse(work['editor_tesim'].try(:firsts)]
json.abstract work['abstract_tesim'].try(:first)
json.date_published work['date_published_tesim']
json.institution work['institution_tesim']
json.organisational_unit work['org_unit_tesim']
json.project_name work['project_name_tesim']
json.funder work['funder_tesim']
json.publisher work['publisher_tesim']
json.date_accepted work['date_accepted_tesim']
json.date_submitted work['date_submitted_tesim']
json.official_url work['official_url_tesim']
json.language work['language_tesim']
json.license work['license_for_api_tesim']
json.rights_statement work['rights_statements_for_api_tesim']
json.rights_holder work['rights_holder_tesim']
json.doi work['doi_tesim']
#json.alternate_identifier work['alternate_identifier_for_api_tesim']
alternate_identifier = work['alternate_identifier_tesim'].try(:first)
if valid_json?(alternate_identifier)
#json.alternate_identifier JSON.parse(alternate_identifier)
alternate_identifier_array = JSON.parse(alternate_identifier)
json.alternate_identifier do
json.array! alternate_identifier_array do |hash|
json.name hash['alternate_identifier']
json.type hash['alternate_identifier_type']
json.postion hash["alternate_identifier_position"].to_i
end
end
end
json.peer_reviewed work['peer_reviewed_tesim']
json.keywords work['keyword_tesim']
json.dewey work['dewey_tesim']
json.library_of_congress_classification work['library_of_congress_classification_tesim']
json.additional_info work['add_info_tesim']
#json.related_identifier work['related_identifier_for_api_tesim']
related_identifier = work['related_identifier_tesim'].try(:first)
if valid_json?(related_identifier)
#json.related_identifier JSON.parse(related_identifier)
related_identifier_array = JSON.parse(related_identifier)
json.related_identifier do
json.array! related_identifier_array do |hash|
json.name hash['related_identifier']
json.type hash['related_identifier_type']
json.relationship hash['relation_type']
json.postion hash["related_identifier_position"].to_i
end
end
end
json.thumbnail_url ('https://' + work['account_cname_tesim'].first + work['thumbnail_path_ss'])
json.download_link ('https://' + work['account_cname_tesim'].first + '/' + 'downloads' + '/' + work[:id])
json.version work['version_tesim']
json.duration work['duration_tesim']
json.pagination work['pagination_tesim']
json.series_name work['series_name']
json.issue work['issue_tesim']
json.volume work['volume_tesim']
json.material_media work['media_tesim']
json.edition work['edition_tesim']
#json.event
event = work['event_tesim'].try(:first)
if valid_json?(event)
json.event JSON.parse(event)
end
json.journal_title work['journal_title_tesim']
json.book_title work['book_title_tesim']
json.article_number work['article_number_tesim']
json.eissn work['eissn_tesim']
json.issn work['issn_tesim']
json.isbn work['isbn_tesim']
json.current_he_institution work['current_he_institution_tesim']
json.qualification_name work['qualification_name_tesim']
json.qualification_levale work['qualification_level_tesim']
json.alternative_journal_title work['alternative_journal_title_tesim']
json.article_number work['article_num_tesim']
json.alternative_alternative work['alt_title_tesim']
json.place_of_publication work['place_of_publication_tesim']
json.funder_project_reference work['fndr_project_ref_tesim']
json.official_url work['official_link_tesim']
json.event_title work['event_title_tesim']
json.event_location work['event_location_tesim']
json.event_date work['event_date_tesim']
json.related_exhibition work['related_exhibition_tesim']
json.related_exhibition_date work['related_exhibition_date_tesim']
json.related_exhibition_venue work['related_exhibition_venue_tesim']
#json.files work['work_filesets_summary_for_api_tesim']
#json.collections work['member_of_collections_for_api_tesim']
puts "wali #{work}"
get_files = Ubiquity::ApiUtils.query_for_files(work["file_set_ids_ssim"])
if get_files.present?
json.files get_files
else
json.files nil
end
get_collections = Ubiquity::ApiUtils.query_for_parent_collections(work["member_of_collection_ids_ssim"])
if get_collections.present?
json.collections do
json.array! get_collections
#json.array! get_collections do |collection|
#json.uuid collection['id']
#json.title collection["title_tesim"].try(:first)
#end
end
else
json.collections nil
end
#end #closes cache
#/home/edward/dev-2/hyku/app/controllers/api/v1/work_controller.rb
class API::V1::WorkController < ActionController::Base
#defines :limit, :default_limit, :models_to_search, :switche_tenant
include Ubiquity::ApiControllerUtilityMethods
include Ubiquity::ApiErrorHandlers
before_action :get_fedora_work, only: [:show]
def index
if request.query_parameters.blank? || request.query_parameters.keys == ["per_page", "page"] || request.query_parameters.keys == ["per_page"]
#, template: 'api/v1/work/index.json.jbuilder'
fetch_all_works
elsif params[:type].present?
puts "babu #{request.query_parameters.keys.first.to_sym}"
filter_by_resource_type
else
puts "sabi #{request.query_parameters.keys}"
filter_by_metadata
end
end
def show
fresh_when(etag: @fedora_work, last_modified: @fedora_work.date_modified, public: true)
end
def manifest
work_class = ActiveFedora::Base.find(params[:id]).class.to_s.pluralize
controller_in_use = "Hyrax::#{work_class}Controller".camelize.constantize.new
controller_in_use.request = request
controller_in_use.response = response
record = controller_in_use.manifest
render json: record
end
private
def get_fedora_work
@fedora_work = ActiveFedora::Base.find(params[:id])
end
def fetch_all_works
@total_count = [ActiveFedora::Base.where(models_to_search).offset(offset).count]
return @works = ActiveFedora::Base.where(models_to_search).order('system_create_dtsi desc').offset(offset).limit(limit) if limit != 0
@works = ActiveFedora::Base.where(models_to_search).order('system_create_dtsi desc')
fresh_when(etag: @works,
last_modified: ActiveFedora::Base.where(models_to_search).order('system_modified_dtsi desc').last.date_modified.to_time,
public: true)
end
def filter_by_resource_type
klass = params[:type].camelize.constantize
@total_count = [klass.order('system_create_dtsi desc').count]
return @works = klass.order('system_create_dtsi desc').offset(offset).limit(limit) if limit != 0 && offset < @total_count.first
@works = klass.order('system_create_dtsi desc')
fresh_when(etag: @works,
last_modified: ActiveFedora::Base.where("has_model_ssim:#{params[:type].camelize}").order('system_modified_dtsi desc').last.date_modified.to_time,
public: true)
end
def filter_by_metadata
extracted_params = request.query_parameters.except(*['per_page', 'page'])
metadata_field = extracted_params.keys.first.try(:to_sym)
#metadata_field = request.query_parameters.keys.first.to_sym
puts "sasha #{metadata_field}"
#value = request.query_parameters[metadata_field]
value = extracted_params[metadata_field]
if metadata_field.present? && [:availability].include?(metadata_field)
@total_count = [ActiveFedora::Base.where("#{map_search_keys[metadata_field]}:#{map_search_values[value.to_sym]}").count]
return @works = ActiveFedora::Base.where("#{map_search_keys[metadata_field]}:#{map_search_values[value.to_sym]}").offset(offset).limit(limit) if limit != 0 && offset < @total_count.first
@works = ActiveFedora::Base.where("#{map_search_keys[metadata_field]}:#{map_search_values[value.to_sym]}")
fresh_when(etag: @works,
last_modified: ActiveFedora::Base.where("#{map_search_keys[metadata_field]}:#{map_search_values[value.to_sym]}").order('system_modified_dtsi desc').last.date_modified.to_time,
public: true)
elsif [:collection_uuid].include? metadata_field
#collection = Collection.find(value)
#@works = collection.member_objects
query_by_collection(value)
elsif metadata_field.present?
query_by_metadata(metadata_field, value)
#@total_count = [ActiveFedora::Base.where("#{map_search_keys[metadata_field]}:#{value}").count]
#return @works = ActiveFedora::Base.where("#{map_search_keys[metadata_field]}:#{value}").offset(offset).limit(limit) if limit != 0 && offset < @total_count.first
#@works = ActiveFedora::Base.where("#{map_search_keys[metadata_field]}:#{value}")
#raise 500 record not found
#raise Ubiquity::ApiError::NotFound.new(status: '500', code: 'not_found', message: 'nothing')
#add_caching("#{map_search_keys[metadata_field]}:#{value}")
=begin
fresh_when(etag: @works,
last_modified: ActiveFedora::Base.where("#{map_search_keys[metadata_field]}:#{value}").order('system_modified_dtsi desc').last.date_modified.to_time,
public: true)
=end
else
#render json: {error: {code: 400, message: 'Bad Request', details: "Please check the request path #{request.path} & ensure you add per_page if you send back page as the query parameter. That is do not send only ?page=number given" }}
raise Ubiquity::ApiError::BadRequest.new(status: 400, code: 'Bad Request', message: "Please check the request path #{request.path} & ensure you add per_page if you send back just #{request.original_fullpath}. That is do not send only ?page=number given" )
end
end
def query_by__availability(metadata_field, value)
@total_count = [ActiveFedora::Base.where("#{map_search_keys[metadata_field]}:#{map_search_values[value.to_sym]}").count]
if limit != 0 && offset < @total_count.first
@works = ActiveFedora::Base.where("#{map_search_keys[metadata_field]}:#{map_search_values[value.to_sym]}").offset(offset).limit(limit)
else
@works = ActiveFedora::Base.where("#{map_search_keys[metadata_field]}:#{map_search_values[value.to_sym]}")
end
raise Ubiquity::ApiError::NotFound.new(status: '500', code: 'not_found', message: 'nothing') if @works.blank?
add_caching("#{map_search_keys[metadata_field]}:#{map_search_values[value.to_sym]}")
end
def query_by_collection(metadata_field, value)
collection = Collection.find(value)
@works = collection.member_objects
raise Ubiquity::ApiError::NotFound.new(status: '500', code: 'not_found', message: 'nothing') if @works.blank?
end
def query_by_metadata(metadata_field, value)
@total_count = [ActiveFedora::Base.where("#{map_search_keys[metadata_field]}:#{value}").count]
if limit != 0 && offset < @total_count.first
@works = ActiveFedora::Base.where("#{map_search_keys[metadata_field]}:#{value}").offset(offset).limit(limit)
else
@works = ActiveFedora::Base.where("#{map_search_keys[metadata_field]}:#{value}")
end
raise Ubiquity::ApiError::NotFound.new(status: '500', code: 'not_found', message: 'nothing') if @works.blank?
add_caching("#{map_search_keys[metadata_field]}:#{value}")
end
def add_caching(search_query)
record = ActiveFedora::Base.where(search_query)
puts "lina #{record}"
if record.present?
fresh_when(etag: @works,
last_modified: record.order('system_modified_dtsi desc').last.date_modified.to_time,
public: true)
end
end
def map_search_keys
{
creator: 'creator_tesim',
keyword: 'keyword_sim',
collection_uuid: 'id',
collection_name: 'member_of_collections_ssim',
language: 'language_sim',
availability: 'file_availability_tesim'
}
end
def map_search_values
{
not_available: 'File+not+available',
available: 'File+available+from+this+repository',
external_link: 'External+link+access+may+be+restricted'
}
end
end
#/home/edward/dev-2/hyku/app/controllers/api/v1/work_controller.rb
class API::V1::WorkController < ApplicationController
before_action :switch_tenant
before_action :fetch_work, only: [:show]
before_action :get_fedora_work, only: [:show]
def index
puts "sami #{request.query_parameters.blank?}"
if request.query_parameters.blank?
puts "solo #{request.query_parameters}"
fetch_all_works
elsif params[:type].present?
puts "momi #{request.query_parameters}"
puts "nunu #{request.query_parameters[:type]}"
puts "kayo #{request.query_parameters.keys}"
filter_by_resource_type
else
puts "dani"
filter_by_metadata
end
end
def show
#render json: @work
#@work
@fedora_work
@col = @fedora_work.member_of_collections
end
def manifest
work_class = ActiveFedora::Base.find(params[:id]).class.to_s.pluralize
controller_in_use = "Hyrax::#{work_class}Controller".camelize.constantize.new
controller_in_use.request = request
controller_in_use.response = response
record = controller_in_use.manifest
render json: record
end
private
def ind2
ActiveFedora::Base.where('has_model_ssim:Article OR has_model_ssim:Book OR has_model_ssim:BookContribution OR has_model_ssim:ConferenceItem OR has_model_ssim:Dataset OR has_model_ssim:ExhibitionItem OR has_model_ssim:Image OR has_model_ssim:Report OR has_model_ssim:ThesisOrDissertation OR has_model_ssim:TimeBasedMedia OR has_model_ssim:GenericWork')
end
def find_parent
@tenant = Account.find_by(tenant: params[:tenant_id])
end
def switch_tenant
find_parent
tenant_name = @tenant.cname
AccountElevator.switch!(tenant_name)
end
def get_fedora_work
@fedora_work = ActiveFedora::Base.find(params[:id])
#@fedora = TimeBasedMedia.find(params[:id])
end
def fetch_work
@work = CatalogController.new.repository.search(q: params[:id], "sort" => "score desc, system_create_dtsi desc",
"facet.field "=> ["resource_type_sim", "creator_search_sim", "keyword_sim", "member_of_collections_ssim", "institution_sim",
"language_sim", "file_availability_sim"])
end
def models_to_search
'has_model_ssim:Article OR has_model_ssim:Book OR has_model_ssim: BookContribution OR has_model_ssim:ConferenceItem
OR has_model_ssim: Dataset OR has_model_ssim:ExhibitionItem OR has_model_ssim:Image OR has_model_ssim:Report
OR has_model_ssim:ThesisOrDissertation OR has_model_ssim:TimeBasedMedia OR has_model_ssim:GenericWork'
end
def fetch_all_works
@works = CatalogController.new.repository.search(q: '', fq: models_to_search, "sort"=>"score desc, system_create_dtsi desc",
"facet.field"=>["resource_type_sim", "creator_search_sim", "keyword_sim", "member_of_collections_ssim", "institution_sim",
"language_sim", "file_availability_sim"], rows: 100_000_000)
#
puts "dada #{@works['response']['numFound']}"
#puts "dani #{@works['response']['facet_fields']['resource_type_sim']}"
#render :template => 'api/v1/work/t', :collection => @works['response']['docs'], as: :work
#render :partial => "api/v1/work/work.json.jbuilder", :collection => @works['response']['docs'], as: :work
puts "mali #{ind2.to_a}"
@works = ind2
#render json: @works
end
def filter_by_resource_type
#works = CatalogController.new.repository.search(q: "id:*", fq: "has_model_ssim:#{params[:type].camelize}" )
#render json: works
@works = params[:type].camelize.all
end
def filter_by_metadata
metadata_field = request.query_parameters.keys.first.to_sym
puts "sola #{metadata_field}"
value = request.query_parameters[metadata_field]
=begin
if [:availability].include? metadata_field
puts "loma #{value}"
puts "lani #{map_search_values[value.to_sym]}"
puts "soro #{map_search_keys[metadata_field]}"
#work = CatalogController.new.repository.search(q: "#{map_search_keys[metadata_field]}:#{map_search_values[value.to_sym]}")
#work = CatalogController.new.repository.search(q: '', fq: ["{!term f=file_availability_sim}File not available"])
work = CatalogController.new.repository.search(q: '', fq: ["{!term f=#{map_search_keys[metadata_field]}}#{map_search_values[value.to_sym]}"])
render json: work
else
puts "yeye"
work = CatalogController.new.repository.search(q: "#{map_search_keys[metadata_field]}:#{value}")
render json: work
end
=end
if [:availability].include? metadata_field
puts "manu"
@works = ActiveFedora::Base.where("#{map_search_keys[metadata_field]}:#{map_search_values[value.to_sym]}")
elsif [:collection_uuid].include? metadata_field
collection = Collection.find(value)
@works = collection.member_objects
else
puts "samo #{value}"
@works = ActiveFedora::Base.where("#{map_search_keys[metadata_field]}:#{value}")
end
end
def map_search_keys
{
creator: 'creator_tesim',
keyword: 'keyword_sim',
collection_uuid: 'id',
collection_name: 'member_of_collections_ssim',
language: 'language_sim',
availability: 'file_availability_tesim'
}
end
def map_search_values
{
not_available: 'File+not+available',
available: 'File+available+from+this+repository',
external_link: 'External+link+access+may+be+restricted'
}
end
end
#/home/edward/dev-2/hyku/app/views/api/v1/work/_work_expanded.json.jbuilder
json.extract! fedora_work, *[:id] + fedora_work.class.fields.reject { |f| [:has_model, :title, :creator, :contributor, :editor, :head, :tail].include? f }
#/home/edward/dev-2/hyku/app/views/api/v1/work/index.json.jbuilder
=begin
json.total @total_count
json.items do
json.array! @works do |work|
#Rails.cache.fetch(@works_cache_name, expires_in: 30.seconds) do
Rails.cache.fetch(['work_json', work], expires_in: 30.seconds) do
#json.cache! ['work_json', work], expires_in: 30.seconds do
json.partial! 'api/v1/work/work_only', work: work
end
end
end
=end
=begin
json.items do
@works.map do |work|
json.cache! ['work_json', work], expires_in: 30.seconds do
#Rails.cache.fetch(['work_json', work], expires_in: 30.seconds) do
json.partial! 'api/v1/work/work_only', work: work
end
end
end
=end
#puts "manu #{@works['response']['docs'].size}"
puts "ani #{@works.to_a}"
#json.array! @works do |work|
#json.partial! 'work_only', collection: work, as: :work
#end
json.partial! 'work_only', collection: @works, as: :work #, cached: true
=begin
json.array! @works['response']['docs'] do |work|
#json.partial! 'work', collection: work, as: :work
json.related_url work['related_url_tesim']
json.work_type work['has_model_ssim'].try(:first)
json.title work['title_tesim'].try(:first)
json.alternative_title work['alternative_title_tesim']
json.resource_type work['resource_type_sim'].try(:first)
creator = work['creator_tesim'].try(:first)
if valid_json?(creator)
json.creator JSON.parse(creator)
end
contributor = work['contributor_tesim'].try(:first)
if valid_json?(contributor)
json.contributor JSON.parse(contributor)
end
editor = work['editor_tesim'].try(:first)
if valid_json?(editor)
json.editor JSON.parse(editor)
end
# json.editor JSON.parse(work['editor_tesim'].try(:firsts)]
json.abstract work['abstract_tesim'].try(:first)
json.date_published work['date_published_tesim']
json.institution work['institution_tesim']
json.organisational_unit work['org_unit_tesim']
json.project_name work['project_name_tesim']
json.funder work['funder_tesim']
json.publisher work['publisher_tesim']
json.date_accepted work['date_accepted_tesim']
json.date_submitted work['date_submitted_tesim']
json.official_url work['official_url_tesim']
json.language work['language_tesim']
#json.license
#json.rights_statement
json.rights_holder work['rights_holder_tesim']
json.doi work['doi_tesim']
alternate_identifier = work['alternate_identifier_tesim'].try(:first)
if valid_json?(alternate_identifier)
json.alternate_identifier JSON.parse(alternate_identifier)
end
json.peer_reviewed work['peer_reviewed_tesim']
json.keywords work['keyword_tesim']
json.dewey work['dewey_tesim']
json.library_of_congress_classification work['library_of_congress_classification_tesim']
json.additional_info work['add_info_tesim']
related_identifier = work['related_identifier_tesim'].try(:first)
if valid_json?(related_identifier)
json.related_identifier JSON.parse(related_identifier)
end
json.thumbnail_url ('https://' + work['account_cname_tesim'].first + work['thumbnail_path_ss'])
#json.collections
json.version work['version_tesim']
json.duration work['duration_tesim']
json.pagination work['pagination_tesim']
json.series_name work['series_name']
json.issue work['issue_tesim']
json.volume work['volume_tesim']
json.material_media work['material_media_tesim']
json.edition work['edition_tesim']
#json.event
event = work['event_tesim'].try(:first)
if valid_json?(event)
json.event JSON.parse(event)
end
json.journal_title work['journal_title_tesim']
json.book_title work['book_title_tesim']
json.article_number work['article_number_tesim']
json.eissn work['eissn_tesim']
json.issn work['issn_tesim']
json.isbn work['isbn_tesim']
json.current_he_institution work['current_he_institution_tesim']
json.qualification work['qualification_tesim']
json.alternative_journal_title work['alternative_journal_title_tesim']
end
=end
#in use
#json.cache! @works['response']['docs'], expires_in: 1.minutes do
#json.partial! 'work', collection: @works['response']['docs'], as: :work #, cached: true
#end
#json.array! @works['response']['docs'], partial: 'work', as: :work
#json.cache! @works do
json.array! @total_count do |count|
json.total_count_for_pagination count
end
#end
json.partial! 'api/v1/work/work_only', collection: @works, as: :work, cached: true
json.items do
#json.array! @works do |work|
#json.partial! 'api/v1/work/work_only', work: work
#end
json.partial! 'api/v1/work/work_only', collection: @works, as: :work, cached: true
end
=begin
json.cache! @works do
json.array! @works do |work|
puts "worki #{work}"
json.partial! 'work_only', work: work #, collection_object: @fedora_work.member_of_collection
end
end
=end
#/home/edward/dev-2/hyku/app/views/api/v1/work/_work.json.jbuilder
#mime_type_ssi
#file_size_lts
#date_uploaded_dtsi
#visibility_ssi
#alternate_identifier_for_api_tesim
#rights_statements_for_api_tesim
#license_for_api_tesim
#related_identifier_for_api_tesim
#member_of_collections_for_api
#work_filesets_summary_for_api
json.cache! work, expires_in: 1.minutes do
json.related_url work['related_url_tesim']
json.work_type work['has_model_ssim'].try(:first)
json.title work['title_tesim'].try(:first)
json.alternative_title work['alternative_title_tesim']
json.resource_type work['resource_type_sim'].try(:first)
json.visibility work['visibility_ssi']
creator = work['creator_tesim'].try(:first)
if valid_json?(creator)
json.creator JSON.parse(creator)
end
contributor = work['contributor_tesim'].try(:first)
if valid_json?(contributor)
json.contributor JSON.parse(contributor)
end
editor = work['editor_tesim'].try(:first)
if valid_json?(editor)
json.editor JSON.parse(editor)
end
# json.editor JSON.parse(work['editor_tesim'].try(:firsts)]
json.abstract work['abstract_tesim'].try(:first)
json.date_published work['date_published_tesim']
json.institution work['institution_tesim']
json.organisational_unit work['org_unit_tesim']
json.project_name work['project_name_tesim']
json.funder work['funder_tesim']
json.publisher work['publisher_tesim']
json.date_accepted work['date_accepted_tesim']
json.date_submitted work['date_submitted_tesim']
json.official_url work['official_url_tesim']
json.language work['language_tesim']
json.license work['license_for_api_tesim']
json.rights_statement work['rights_statements_for_api_tesim']
json.rights_holder work['rights_holder_tesim']
json.doi work['doi_tesim']
#json.alternate_identifier work['alternate_identifier_for_api_tesim']
alternate_identifier = work['alternate_identifier_tesim'].try(:first)
if valid_json?(alternate_identifier)
#json.alternate_identifier JSON.parse(alternate_identifier)
alternate_identifier_array = JSON.parse(alternate_identifier)
json.alternate_identifier do
json.array! alternate_identifier_array do |hash|
json.name hash['alternate_identifier']
json.type hash['alternate_identifier_type']
json.postion hash["alternate_identifier_position"].to_i
end
end
end
json.peer_reviewed work['peer_reviewed_tesim']
json.keywords work['keyword_tesim']
json.dewey work['dewey_tesim']
json.library_of_congress_classification work['library_of_congress_classification_tesim']
json.additional_info work['add_info_tesim']
#json.related_identifier work['related_identifier_for_api_tesim']
related_identifier = work['related_identifier_tesim'].try(:first)
if valid_json?(related_identifier)
#json.related_identifier JSON.parse(related_identifier)
related_identifier_array = JSON.parse(related_identifier)
json.related_identifier do
json.array! related_identifier_array do |hash|
json.name hash['related_identifier']
json.type hash['related_identifier_type']
json.relationship hash['relation_type']
json.postion hash["related_identifier_position"].to_i
end
end
end
json.thumbnail_url ('https://' + work['account_cname_tesim'].first + work['thumbnail_path_ss'])
json.version work['version_tesim']
json.duration work['duration_tesim']
json.pagination work['pagination_tesim']
json.series_name work['series_name']
json.issue work['issue_tesim']
json.volume work['volume_tesim']
json.material_media work['material_media_tesim']
json.edition work['edition_tesim']
#json.event
event = work['event_tesim'].try(:first)
if valid_json?(event)
json.event JSON.parse(event)
end
json.journal_title work['journal_title_tesim']
json.book_title work['book_title_tesim']
json.article_number work['article_number_tesim']
json.eissn work['eissn_tesim']
json.issn work['issn_tesim']
json.isbn work['isbn_tesim']
json.current_he_institution work['current_he_institution_tesim']
json.qualification work['qualification_tesim']
json.alternative_journal_title work['alternative_journal_title_tesim']
json.files work['work_filesets_summary_for_api_tesim']
json.collections work['member_of_collections_for_api_tesim']
=begin
json.collections do
json.array! @fedora_work.member_of_collections do |collection|
json.uuid collection.id
json.title collection.title.first
end
end
=end
end
#/home/edward/dev-2/hyku/app/views/api/v1/work/_work_only.json.jbuilder
json.related_url work.related_url
json.work_type work.has_model.try(:first)
json.title work.title.try(:first)
json.alternative_title work.try(:alternative_title)
json.resource_type work.resource_type.try(:first)
creator = work.creator.try(:first)
if valid_json?(creator)
json.creator JSON.parse(creator)
end
contributor = work.contributor.try(:first)
if valid_json?(contributor)
json.contributor JSON.parse(contributor)
end
editor = work.try(:editor).try(:first)
if valid_json?(editor)
json.editor JSON.parse(editor)
end
# json.editor JSON.parse(work['editor_tesim'].try(:firsts)]
json.abstract work.abstract.try(:first)
json.date_published work.date_published
json.institution work.institution
json.organisational_unit work.org_unit
json.project_name work.project_name
json.funder work.funder
json.publisher work.publisher
json.date_accepted work.date_accepted
json.date_submitted work.date_submitted
json.official_url work.try(:official_url)
json.language work.language
json.license work.license_for_api
json.rights_statement work.rights_statements_for_api
json.rights_holder work.rights_holder
json.doi work.doi
json.alternate_identifier work.alternate_identifier_for_api
=begin
alternate_identifier = work.alternate_identifier.try(:first)
if valid_json?(alternate_identifier)
json.alternate_identifier JSON.parse(alternate_identifier)
end
=end
json.peer_reviewed work.try(:peer_reviewed)
json.keywords work.keyword
json.dewey work.dewey
json.library_of_congress_classification work.library_of_congress_classification
json.additional_info work.try(:add_info)
json.related_identifier work.related_identifier_for_api
=begin
related_identifier = work.related_identifier.try(:first)
if valid_json?(related_identifier)
json.related_identifier JSON.parse(related_identifier)
end
=end
#json.thumbnail_url ('https://' + work.account_cname.first + work.thumbnail_path)
json.version work.try(:version)
json.duration work.try(:duration)
json.pagination work.pagination
json.series_name work.try(:series_name)
json.issue work.try(:issue)
json.volume work.try(:volume)
json.material_media work.try(:material_media)
json.edition work.try(:edition)
#json.event
event = work.try(:event).try(:first)
if valid_json?(event)
json.event JSON.parse(event)
end
json.journal_title work.try(:journal_title)
json.book_title work.try(:book_title)
json.article_number work.try(:article_number)
json.eissn work.try(:eissn)
json.issn work.try(:issn)
json.isbn work.try(:isbn)
json.current_he_institution work.try(:current_he_institution)
json.qualification work.try(:qualification)
json.alternative_journal_title work.try(:alternative_journal_title)
json.files work.work_filesets_summary_for_api
json.collections work.member_of_collections_for_api
#/home/edward/dev-2/hyku/app/views/api/v1/work/show.json.jbuilder
#json.extract! @fedora_work, *[:id] + @fedora_work.class.fields.reject { |f| [:has_model, :title, :creator, :contributor, :editor, :editor, :head, :tail].include? f }
puts "zoro #{@fedora_work}"
json.partial! 'work_only', work: @fedora_work #, as: :work
#json.partial! 'work_expanded', fedora_work: @fedora_work
#puts "zoro #{@work}"
#in use for solr solr_docs=begin
=begin
@work['response']['docs'].each do |work|
puts "worki #{work}"
json.partial! 'work', work: work #, collection_object: @fedora_work.member_of_collection
end
=end
=begin
json.collections do
json.array! @fedora_work.member_of_collections do |collection|
json.uuid collection.id
json.title collection.title.first
end
end
=end
#{"resource_type_sim"=>["Book default Book", 1], "creator_search_sim"=>["ffgghj", 1], "keyword_sim"=>[], "member_of_collections_ssim"=>["collection-library1", 1], "institution_sim"=>["British Library", 1],
#json.facet_counts @work['facet_counts']['facet_fields'] do |work|
#in use
#json.facet_counts do #|work|
#["resource_type_sim", ["Book default Book", 1]]
#puts "lima #{work}"
#json.resource_type_sim work['resource_type_sim'].each_slice(2).entries.to_h.presence
#in use
#json.resource_type_sim @work['facet_counts']['facet_fields']["resource_type_sim"].each_slice(2).entries.to_h.presence
=begin
json.resource_type_sim work.last.each_slice(2).entries.to_h.presence if work.first == "resource_type_sim"
json.creator_search_sim work.last.each_slice(2).entries.to_h.presence if work.first == "creator_search_sim"
json.keyword_sim work.last.each_slice(2).entries.to_h.presence if work.first == "keyword_sim"
json.member_of_collections_ssim work.last.each_slice(2).to_a.to_h.presence if work.first == "member_of_collections_ssim"
json.language_sim work.last.each_slice(2).entries.to_h.presence if work.first == "language_sim"
json.file_availability_sim work.last.each_slice(2).entries.to_h.presence if work.first == "file_availability_sim"
=end
#end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment