Skip to content
Snippets Groups Projects

Compare revisions

Changes are shown as if the source revision was being merged into the target revision. Learn more about comparing revisions.

Source

Select target project
No results found

Target

Select target project
  • portalmec/portalmec
  • rfhferreira/cleanning-portalmec
2 results
Show changes
Commits on Source (1336)
Showing
with 1334 additions and 552 deletions
image: ruby:2.7
services: services:
- postgres - postgres:11
- elasticsearch - elasticsearch:6.5.1
- redis - redis:latest
variables: variables:
POSTGRES_DB: portalmec_test POSTGRES_DB: portalmec_test
...@@ -10,9 +12,12 @@ variables: ...@@ -10,9 +12,12 @@ variables:
ELASTICSEARCH_URL: http://elasticsearch:9200 ELASTICSEARCH_URL: http://elasticsearch:9200
REDIS_HOST: redis:6379 REDIS_HOST: redis:6379
REDIS_RATE_LIMIT_URL: redis://redis:6379/0 REDIS_RATE_LIMIT_URL: redis://redis:6379/0
DSPACE_LOGIN: '$mecdb1_login'
DSPACE_PASS: '$mecdb1_password'
stages: stages:
- test - test
- apidoc
- deploy - deploy
before_script: before_script:
...@@ -20,6 +25,7 @@ before_script: ...@@ -20,6 +25,7 @@ before_script:
- apt-get install default-jre postgresql-client -y - apt-get install default-jre postgresql-client -y
- apt-get remove --purge --auto-remove redis-server -y - apt-get remove --purge --auto-remove redis-server -y
- apt-get install redis-server -y - apt-get install redis-server -y
- apt-get install nodejs -y
# official way to provide password to psql: http://www.postgresql.org/docs/9.3/static/libpq-envars.html # official way to provide password to psql: http://www.postgresql.org/docs/9.3/static/libpq-envars.html
- export PGPASSWORD=$POSTGRES_PASSWORD - export PGPASSWORD=$POSTGRES_PASSWORD
- psql -h "postgres" -U "$POSTGRES_USER" -d "$POSTGRES_DB" -c "SELECT 'OK' AS status;" - psql -h "postgres" -U "$POSTGRES_USER" -d "$POSTGRES_DB" -c "SELECT 'OK' AS status;"
...@@ -31,20 +37,33 @@ test: ...@@ -31,20 +37,33 @@ test:
stage: test stage: test
script: script:
- bundle exec rake db:migrate:reset RAILS_ENV=test - bundle exec rake db:migrate:reset RAILS_ENV=test
- rake test - bundle exec rake spec:acceptance
tags: tags:
- ruby - ruby
- postgres - postgres
- elasticsearch - elasticsearch
- redis - redis
#deploy: doc:
# stage: deploy stage: apidoc
# script: script:
# - mina deploy - bundle exec rake db:migrate:reset RAILS_ENV=test
# only: - bundle exec rake docs:generate
# - master - ./docploy.sh
# tags: only:
- stable
tags:
- ruby
- postgres
- elasticsearch
- redis
# deploy:
# stage: deploy
# script:
# # - mina deploy
# only:
# - master
# tags:
# - ruby # - ruby
# - postgres # - postgres
# - elasticsearch # - elasticsearch
......
2.3.1 3.0.1
# v0.1.0
## Features
* Activities
* Show activities from a specific user
* Show all activities that logged user can see (feed)
* Show all users public activities
* Show logged user activities
* Bookmarks
* Create a bookmark
* Get a list of bookmarks
* Remove a bookmark
* Collections
* Add items to a collection
* Create a collection
* Destroy a collection
* Get a collection
* Get a list of collections
* Get all collection versions
* Like a collection
* Remove items from a collection
* Unlike a collection
* Update a collection
* Complaints
* Create a complaint
* Get a list of complaints
* Contacts
* Create contacts
* Destroy a contact
* Get a contact
* Get all contacts
* Update contacts
* Downloads
* Download the content (files) of a learning object or collection
* Educational Stages
* Create an educational stage
* Get a list of educational stages
* Remove an educational stage
* Follows
* Follow an user or collection
* Unfollow an user or collection
* Institutions
* Create an institution
* Destroy an institution
* Get a list of institutions
* Get an institution
* Update an institution
* Languages
* Create a language
* Destroy a language
* Get a language
* Get a list of languages
* Update languages
* Learning Objects
* Create a learning object draft
* Destroy an attachment (file) of a learning object
* Destroy a learning object
* Get a learning object
* Get a list of learning objects
* Get all learning object versions
* Like a learning object
* Publish a learning object
* Unlike a learning object
* Update a learning object
* Mime Types
* Create a mime type
* Destroy a mime type
* Get a mime type
* Get a list of mime types
* Update a mime type
* Object Type
* Create an object type
* Destroy an object type
* Get a list of object types
* Get an object type
* Update an object type
* Reviews
* Create a review
* Delete a review
* Get a list of reviews
* Rate a review
* Update a review
* Statistics
* Show statistics about the API usage
* Subjects
* Create a subject
* Get a list of subjects
* Remove a subject
* Suggestions
* Create suggestions
* Destroy suggestions
* Get a suggestion
* Get all suggestions
* Update suggestions
* Tags
* Create a tag
* Untag an object or collection
* Users
* Create an user
* Create an user by admin
* Login with an user account
* Logout of an user account
* Destroy an user
* Destroy an user by admin
* Get a list of users
* Get an user
* Get all user versions
* Show an user’s collections
* Show an user’s drafts
* Show an user’s learning objects
* Show an user’s liked collections
* Show an user’s liked learning objects
* Show an user’s own reviews
* Show an user’s received reviews
* Show what the user is following
* Update an user
source 'https://rubygems.org' source 'https://rubygems.org'
# Bundle edge Rails instead: gem 'rails', github: 'rails/rails' # Bundle edge Rails instead: gem 'rails', github: 'rails/rails'
gem 'rails', '5.0.0' gem 'rails', '>=6.0.0'
# Use postgresql as the database for Active Record # Use postgresql as the database for Active Record
gem 'pg' gem 'pg'
# bundle exec rake doc:rails generates the API under doc/api. # bundle exec rake doc:rails generates the API under doc/api.
gem 'sdoc', '~> 0.4.0', group: :doc gem 'sdoc', '>= 0.4.0', group: :doc
# Use ActiveModel has_secure_password # Use ActiveModel has_secure_password
gem 'bcrypt', '~> 3.1.7' gem 'bcrypt', '>= 3.1.7'
# memcached # memcached
gem 'dalli' gem 'dalli'
# dalli multi thread gem
gem 'connection_pool'
# web server # web server
gem 'puma' gem 'puma'
# protection
gem 'rack-attack'
# scheduler # scheduler
gem 'whenever', require: false gem 'whenever', require: false
...@@ -24,16 +30,16 @@ gem 'whenever', require: false ...@@ -24,16 +30,16 @@ gem 'whenever', require: false
gem 'devise' gem 'devise'
# files # files
gem 'paperclip' gem 'kt-paperclip', github: 'kreeti/kt-paperclip', branch: 'master'
# enable login via rest # enable login via rest
gem 'devise_token_auth' gem 'devise_token_auth', github: 'lynndylanhurley/devise_token_auth', branch: 'master'
gem 'rack-cors', require: 'rack/cors' gem 'rack-cors', require: 'rack/cors'
gem 'rmagick' gem 'rmagick'
# Dspace REST API Integration # Dspace REST API Integration
gem 'dspace_rest_client' gem 'dspace_rest_client', github: 'c3sl/dspace-rest-client', branch: 'master'
# pretty logs # pretty logs
gem 'rainbow' gem 'rainbow'
...@@ -49,6 +55,8 @@ group :development do ...@@ -49,6 +55,8 @@ group :development do
gem 'annotate' gem 'annotate'
gem 'immigrant' gem 'immigrant'
gem 'derailed_benchmarks'
# Generate ER Diagram from database (use: rake erd) # Generate ER Diagram from database (use: rake erd)
# Github Page: https://github.com/voormedia/rails-erd # Github Page: https://github.com/voormedia/rails-erd
gem 'rails-erd' gem 'rails-erd'
...@@ -73,13 +81,13 @@ group :development do ...@@ -73,13 +81,13 @@ group :development do
# reduce queries - https://github.com/flyerhzm/bullet # reduce queries - https://github.com/flyerhzm/bullet
gem 'bullet' gem 'bullet'
gem 'better_errors' gem 'better_errors', '~>2.8.0'
# Call 'byebug' anywhere in the code to stop execution and get a debugger console # Call 'byebug' anywhere in the code to stop execution and get a debugger console
gem 'byebug' gem 'byebug'
# Access an IRB console on exception pages or by using <%= console %> in views # Access an IRB console on exception pages or by using <%= console %> in views
gem 'web-console', '~> 2.0' gem 'web-console', '~>4.0.4'
# Spring speeds up development by keeping your application running in the background. Read more: https://github.com/rails/spring # Spring speeds up development by keeping your application running in the background. Read more: https://github.com/rails/spring
gem 'spring' gem 'spring'
...@@ -94,12 +102,17 @@ end ...@@ -94,12 +102,17 @@ end
group :test do group :test do
gem 'shoulda' gem 'shoulda'
gem 'minitest-reporters' gem 'minitest-reporters'
gem 'rspec-rails'
gem 'faker' gem 'faker'
gem 'factory_girl_rails' gem 'database_cleaner'
end end
gem 'streamio-ffmpeg', '~> 1.0.0' group :development, :test do
gem 'rspec-rails', '>= 3.8' #original is 3.6
gem 'rspec_api_documentation'
gem 'factory_bot_rails'
end
gem 'streamio-ffmpeg', '>= 1.0.0'
# sidekiq # sidekiq
gem 'sidekiq' gem 'sidekiq'
...@@ -107,13 +120,13 @@ gem 'sinatra', require: false ...@@ -107,13 +120,13 @@ gem 'sinatra', require: false
gem 'slim' gem 'slim'
# CUrl # CUrl
gem 'curb', '~> 0.8.8' gem 'curb', '>= 0.8.8'
# libArchive (Zip, Rar, ...) # libArchive (Zip, Rar, ...)
# C extension is required # C extension is required
# For Mac OSX: brew install libarchive && bundle config build.libarchive "--with-opt-dir=/usr/local/opt/libarchive" # For Mac OSX: brew install libarchive && bundle config build.libarchive "--with-opt-dir=/usr/local/opt/libarchive"
# gem 'libarchive', '~> 0.1.2', :require => 'libarchive_ruby' # gem 'libarchive', '~> 0.1.2', :require => 'libarchive_ruby'
gem 'libarchive-static' gem 'ffi-libarchive'
gem 'gitlab' gem 'gitlab'
...@@ -132,7 +145,7 @@ gem 'activerecord-import' ...@@ -132,7 +145,7 @@ gem 'activerecord-import'
# social connect # social connect
gem 'omniauth-facebook' gem 'omniauth-facebook'
gem 'omniauth-twitter' gem 'omniauth-twitter'
gem 'omniauth-google-oauth2' gem 'omniauth-google-oauth2', '~>0.8.2'
# get mime type # get mime type
gem 'mimemagic' gem 'mimemagic'
...@@ -140,13 +153,9 @@ gem 'mimemagic' ...@@ -140,13 +153,9 @@ gem 'mimemagic'
# html screenshot # html screenshot
gem 'screencap' gem 'screencap'
# using while rails 5 isn't released # model json serializer
# gem 'rails-api'
gem 'active_model_serializers' gem 'active_model_serializers'
# limit the number of requests by user to api
gem 'redis-throttle', git: 'git://github.com/lelylan/redis-throttle.git'
# zip files # zip files
gem 'rubyzip' gem 'rubyzip'
...@@ -156,7 +165,10 @@ gem 'public_activity' ...@@ -156,7 +165,10 @@ gem 'public_activity'
# gem 'rails-observers' # gem 'rails-observers'
# soft-deleted for active record models # soft-deleted for active record models
gem 'paranoia', github: 'rubysherpas/paranoia', branch: 'rails4' #gem 'paranoia', github: 'rubysherpas/paranoia', branch: 'rails4'
gem 'paranoia'
# models versioning # models versioning
gem 'paper_trail' gem 'paper_trail'
gem 'acts_as_list'
This diff is collapsed.
# Portal MEC # Portal MEC
## License
Copyright (C) 2015 Centro de Computacao Cientifica e Software Livre
Departamento de Informatica - Universidade Federal do Parana
This file is part of portalmec.
portalmec 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, either version 3 of the License, or
(at your option) any later version.
portalmec 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 portalmec. If not, see <http://www.gnu.org/licenses/>.
## Requirements ## Requirements
* ruby >=2.2
* rvm * rvm
* Dspace server * Using rvm you will install ruby "3.0.1"
* Postgres >=9.4 * ruby "3.0.1"
* Elasticsearch * Dspace server "6.x"
* Redis * Postgres "13"
* Elasticsearch "6.8.13"
* Redis ">=5.0"
* nvm
* Using nvm you will install Node.js "14.15.1"
## NVM and Node.js
For install NVM and Node.js, use this follwing commands:
```
$ wget -qO- https://raw.githubusercontent.com/nvm-sh/nvm/v0.37.0/install.sh | bash
```
```
$ nvm install 14.15.1
```
## Postgres
After the first install, you can run this commands:
* ``` sudo passwd postgres ```
* ``` su postgres```
* ``` psql -c "ALTER USER postgres WITH PASSWORD '$PASSWORD'" -d template1 ```
* ``` createuser -h localhost -U postgres -d $USER_DB ```
* ``` psql -c "ALTER USER $USER_DB WITH PASSWORD '$PASSWORD'" -d template1 ```
Note: You can ask for the database dump for someone in the project.
You need to modify the file "/etc/postgresql/11/main/pg_hba.conf", the modification is
* comment the 1st and 2nd lines with "peer" and copy them replacing "peer" with "md5".
After this, run this command:
* ``` systemctl restart postgresql ```
## Rvm
After finish the installer, you will need to add in your ~/.bashrc this commands:
* ``` export PATH="$PATH:$HOME/.rvm/bin" ```
* ``` source /home/Your_user/.rvm/scripts/rvm ```
After this, run the command ```source ~/.bashrc```.
``` Note ``` : If does not work, you can try modify the commands above, for this:
* ```export PATH="$PATH:/usr/share/rvm/bin" ```
* ```source /usr/share/rvm/scripts/rvm```
## Setup ## Setup
First of all, you need configure the dspace, elasticsearch and redis servers. An user for postgres database will be needed to. First of all, you need to configure the dspace, elasticsearch and redis servers. Create an user for postgres database.
After this setup, open the config files and update some vars: After this setup, open the configuration files inside the project repository and update the following files:
* config/database.yml: change your postgres credentials for development and test environment. * config/database.yml: change your postgres credentials for development and test environment.
* config/dspace.yml: change your dspace host and credentials for development and test environment. * config/dspace.yml: change your dspace host and credentials for development and test environment.
* config/sidekiq.yml: change your redis hosts and ports. * config/sidekiq.yml: change your redis hosts and ports.
* config/initializers/elasticsearch.rb: inside elsif Rails.env.test? change url 'elasticsearch:9200' to 'localhost:9200'.
* config/initializers/gitlab.rb: change your gitlab host for bug reports and set env var with private token. ( $ export GITLAB_PORTALMEC_PRIVATE_TOKEN=131237128937128937 ) * config/initializers/gitlab.rb: change your gitlab host for bug reports and set env var with private token. ( $ export GITLAB_PORTALMEC_PRIVATE_TOKEN=131237128937128937 )
### Development environment
## Install
After installed the requeriments, the first you will need to do is run:
* ``` bundle install ```
This command will install all required gems for the project.
```Note ```: Sometimes some gems throw errors. That is because there is a chance that you do not have all the required dependecies for the installation of the gem that failed to install. Please install the dependencies and try again.
After all gems were installed succesfuly. Please create the database using the following commands:
* ``` rake db:create ```
* If you have the dump of the database, use it before db:migrate.
* To use the dump, run this commands: ```psql -U $DATABASE_USER -d $DATABASE_NAME < $DATABASE_PATH/dump_name.sql ```
* ``` rake db:migrate ```
``` Note ``` : You need to load the dump in the database_dev.
This procedure will create and configure all table in the project database
For the search mechanism to works, execute the CMD in the portalmec directory ``` rake searchkick:reindex:all ```.
<!--### Development environment-->
<!-- Se algum dia o docker do projeto for arrumado, essa parte deve bastar como explicação -->
<!--
#### Using docker for development env #### Using docker for development env
You can use docker for your development environment. For that, run: You can use docker for your development environment. For that, run:
``` ./bin/docker-setup ``` ./bin/docker-setup
Now, redis, elasticsearch and postgres are running as services and linked to PortalMEC application. Database migrations were execute and the configs (database.yml, sidekiq.yml was replaced by config/docker/...). Now, redis, elasticsearch and postgres are running as services and linked to PortalMEC application. Database migrations were execute and the configs (database.yml, sidekiq.yml was replaced by config/docker/...).
If all development and test vars are set, run: If all development and test vars are set, run:
``` ./bin/setup ```
This command will install the rubygems, create/reset your database schema, seed some default data and import all dspace data.
After this, your application is ready to use and you can access it with:
* ```rake db:create```
This command will install the rubygems, create/reset your database schema, seed some default data and import all dspace data.-->
Once finished, your application is read to be used. To acess it, run CMD:
``` bundle exec rails s ``` ``` bundle exec rails s ```
<!--
Se a rotina de testes descrita pelo rake test for arrumada, o comando a baixo funcionara
### Running tests suite ### Running tests suite
For tests, TestUnit is used, and to run it: For tests, TestUnit is used, and to run it
``` bundle exec rake test ``` ``` bundle exec rake test ```-->
For tests, run this commands:
* ``` export DSPACE_LOGIN=your_login ```
* ``` export DSPACE_PASS=your_password ```
* ``` source ~/.bashrc ```
* ``` bundle exec rake spec:acceptance ```
### Production environment ### Production environment
As you set development and test environment vars, now production vars will be needed to be set. When working in the production environment, the environment variables must be set in the file config/env_vars.sh.
For that, open the file config/env_vars.sh and set them. After, run: After setting the variables in the file, you must include the following line into your user's .bashrc file:
``` ./config/env_vars.sh ``` * ``` source /home/portalmec/portalmec/config/env_vars.sh ```
* Redis vars need to be set on config/sidekiq.yml You will also need to make some other configurations:
* In config/initializers/devise.rb, change the emails addresses. (Ex.: config.mailer_sender = 'suporte@c3sl.ufpr.br')
Now, you can run and your application is ready to use: * Redis vars need to be set on config/sidekiq.yml
``` ./bin/setup ``` * In config/initializers/devise.rb, change the e-mail addresses. (Ex.: config.mailer_sender = 'suporte@suporte.com')
* In app/services/learning_object_publisher.rb, in the create_dspace_item change the DSpace collection where the items are gonna be created.
* Change the paths in the *.sh and *.service files in the root of the project to the absolute path of the project in the production server.
* As root, copy the *.service files to the server's systemd directory (Ex.: /lib/systemd/system), then run systemctl enable portalmec and systemctl enable portalmec-sidekiq.
* As root, copy the sidekiq_log.conf file to the rsyslog directory (/etc/rsyslog.d/) and give the shared/logs/sidekiq.log file the same permissions and ownership as the /var/log/syslog file.
After the setup, link your webserver to the app. Some OS services are in root of the project and can be used. Now that your application is ready, you can run it with:
\ No newline at end of file * ``` systemctl start portalmec portalmec-sidekiq ```
class LearningObject::DraftBuilder
def self.build(publisher, params={})
@draft = LearningObject.new(sanitize_params(params))
@draft.draft!
#build language
@draft.language = Language.find(params[:language]) if params[:language].to_i > 0
# set publisher
@draft.publisher = publisher
@draft.save
# build tags
params[:tags].try(:each) do |t|
tag = Tag.where(name: t['name']).first_or_create
Tagging.where(tag: tag, taggable: @draft, tagger: publisher).first_or_create
end
@draft.save
@draft
end
def self.sanitize_params(args={})
params = args.clone
%w(tags language link).each do |arg|
params.delete(arg)
end
metadata = { 'dc.object.url' => args[:link] }
params.merge(metadata: metadata)
end
end
# Copyright (C) 2015 Centro de Computacao Cientifica e Software Livre
# Departamento de Informatica - Universidade Federal do Parana
#
# This file is part of portalmec.
#
# portalmec 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, either version 3 of the License, or
# (at your option) any later version.
#
# portalmec 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 portalmec. If not, see <http://www.gnu.org/licenses/>.
class LearningObjectBuilder class LearningObjectBuilder
def self.build_from_dspace(item)
I_KNOW_THAT_OPENSSL_VERIFY_PEER_EQUALS_VERIFY_NONE_IS_WRONG = nil
def self.build_from_dspace(item, publisher)
lo = LearningObject.new( lo = LearningObject.new(
name: item.name, name: item.name,
id_dspace: item.id, id_dspace: item.id,
...@@ -7,47 +29,64 @@ class LearningObjectBuilder ...@@ -7,47 +29,64 @@ class LearningObjectBuilder
metadata: dspace_metadata_to_hash(item.metadata) metadata: dspace_metadata_to_hash(item.metadata)
) )
institution = lo.get_metadata_value_of('dc.creator') lo.name = "Recurso Sem Nome" if lo.name.blank?
institution = 'Desconhecido' if institution.blank?
lo.publisher = Institution.where(name: institution).first_or_create lo.curator = lo.get_metadata_value_of('dc.curator')
# institution = lo.get_metadata_value_of('dc.creator')
# institution = 'Desconhecido' if institution.blank?
# lo.publisher = Institution.where(name: institution).first_or_create
lo.publisher = publisher
object_type = lo.get_metadata_value_of('dc.type') object_type = lo.get_metadata_value_of('dc.type')
object_type = 'Desconhecido' if object_type.blank? object_type = 'Desconhecido' if object_type.blank?
lo.object_type = ObjectType.where(name: object_type).first_or_create
date = lo.get_metadata_value_of('dc.date.issued') ot = ObjectType.where(name: object_type)
lo.published_at = Time.iso8601(date) unless date.nil? if ot.blank?
lo.object_type = ObjectType.where(name: 'Outros').first
else
lo.object_type = ot.first
end
subjects = lo.get_metadata_values_of('dc.subject')
subjects = ['Outros'] if subjects.blank?
subjects.uniq.each do |subject|
s = Subject.where(name: subject)
if s.blank?
insert_tag(subject, lo, publisher)
else
lo.subjects << s
end
end
tags = lo.get_metadata_values_of('dc.subject.keyword')
tags = ['Outros'] if tags.blank?
tags.uniq.each do |tg|
insert_tag(tg, lo, publisher)
end
# date = lo.get_metadata_value_of('dc.date.issued')
# lo.published_at = Time.iso8601(date) unless date.nil?
lo.published_at = Time.current
code = lo.get_metadata_value_of('dc.language') code = lo.get_metadata_value_of('dc.language')
code = 'pt' if code.blank? code = 'pt' if code.blank?
language = Language.where(code: code).first language = Language.where(code: code).first
language = Language.create(name: code, code: code) if language.nil? language = Language.where(code: "Outro").first if language.nil?
lo.language = language # language = Language.create(name: code, code: code) if language.nil?
lo.language << language
lo.author = lo.get_metadata_values_of('dc.contributor.author').join(', ') lo.author = lo.get_metadata_values_of('dc.contributor.author').join(', ')
lo.author = publisher.name if lo.author.blank?
lo.description = lo.get_metadata_value_of('dc.description') lo.description = lo.get_metadata_value_of('dc.description')
lo.state = :published lo.link = lo.get_metadata_value_of('dc.relation.uri')
lo.link = lo.get_metadata_value_of('dc.relation') if lo.link.blank?
lo
end
def self.build_form_params(params={}, publisher = nil)
_params = params.clone
_params.delete :link
# build tags # lo.state = LearningObject.states[:published]
_params[:tags] = []
params[:tags].try(:each) do |t|
_params[:tags] << Tag.find(t['id'])
end
#build language lo
_params[:language] = Language.find(params[:language]) if params[:language].to_i > 0
# set publisher
_params[:publisher] = publisher unless publisher.nil?
_params
end end
def self.dspace_metadata_to_hash(metadata) def self.dspace_metadata_to_hash(metadata)
...@@ -56,11 +95,13 @@ class LearningObjectBuilder ...@@ -56,11 +95,13 @@ class LearningObjectBuilder
hash hash
end end
# def self.sanitize_form_metadata(params={}) private
# if !params[:link].blank?
# metadata = [{'key' => 'dc.object.url', 'value' => params[:link]}] def self.insert_tag(tag_str, lo, publisher)
# _args.merge(metadata: metadata) tag = Tag.where(name: tag_str).first_or_create
# end if !lo.tags.include?(tag)
# _args tagging = Tagging.new(tag: tag, tagger: publisher, taggable: lo)
# end lo.taggings << tagging
end
end
end end
# Copyright (C) 2015 Centro de Computacao Cientifica e Software Livre
# Departamento de Informatica - Universidade Federal do Parana
#
# This file is part of portalmec.
#
# portalmec 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, either version 3 of the License, or
# (at your option) any later version.
#
# portalmec 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 portalmec. If not, see <http://www.gnu.org/licenses/>.
class ApplicationController < ActionController::API class ApplicationController < ActionController::API
include ActionController::Serialization include ActionController::Serialization
include DeviseTokenAuth::Concerns::SetUserByToken include DeviseTokenAuth::Concerns::SetUserByToken
...@@ -7,6 +26,15 @@ class ApplicationController < ActionController::API ...@@ -7,6 +26,15 @@ class ApplicationController < ActionController::API
# tracking user in papertrail # tracking user in papertrail
before_action :set_paper_trail_whodunnit before_action :set_paper_trail_whodunnit
rescue_from Exception do |exception|
logger.fatal "The request raised an exception:"
logger.fatal exception
logger.fatal exception.backtrace.first(10).join("\n")
unless response_body
render status: :internal_server_error
end
end
# check if client application is allowed to consumes the API. # check if client application is allowed to consumes the API.
before_action :allow_client_application, if: -> { Feature.active?(:allow_client_application) } before_action :allow_client_application, if: -> { Feature.active?(:allow_client_application) }
...@@ -23,7 +51,7 @@ class ApplicationController < ActionController::API ...@@ -23,7 +51,7 @@ class ApplicationController < ActionController::API
protected protected
def configure_permitted_parameters def configure_permitted_parameters
registration_params = [:name, :email, :avatar, :password, :password_confirmation, :current_password, :terms_of_service] registration_params = [:name, :email, :description, :teacher_id, :birthday, :avatar, :cover, :password, :password_confirmation, :current_password, :terms_of_service]
devise_parameter_sanitizer.permit :sign_up, keys: registration_params devise_parameter_sanitizer.permit :sign_up, keys: registration_params
devise_parameter_sanitizer.permit :account_update, keys: registration_params devise_parameter_sanitizer.permit :account_update, keys: registration_params
end end
......
# Copyright (C) 2015 Centro de Computacao Cientifica e Software Livre
# Departamento de Informatica - Universidade Federal do Parana
#
# This file is part of portalmec.
#
# portalmec 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, either version 3 of the License, or
# (at your option) any later version.
#
# portalmec 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 portalmec. If not, see <http://www.gnu.org/licenses/>.
module DeletedObjectsController module DeletedObjectsController
extend ActiveSupport::Concern extend ActiveSupport::Concern
......
# Copyright (C) 2015 Centro de Computacao Cientifica e Software Livre
# Departamento de Informatica - Universidade Federal do Parana
#
# This file is part of portalmec.
#
# portalmec 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, either version 3 of the License, or
# (at your option) any later version.
#
# portalmec 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 portalmec. If not, see <http://www.gnu.org/licenses/>.
module DownloadableController
extend ActiveSupport::Concern
# GET /learning_objects/1/download
def download
# Change request.remote_ip to req.env["HTTP_X_REAL_IP"] in production
downloadable.download(current_user, request.remote_ip)
link = downloadable.download_link
if !link.blank?
redirect_to link
else
render status: :internal_server_error
end
end
protected
def downloadable
raise NotImplementedError
end
end
# Copyright (C) 2015 Centro de Computacao Cientifica e Software Livre
# Departamento de Informatica - Universidade Federal do Parana
#
# This file is part of portalmec.
#
# portalmec 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, either version 3 of the License, or
# (at your option) any later version.
#
# portalmec 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 portalmec. If not, see <http://www.gnu.org/licenses/>.
## This concern has +follow+ and +unfollow+ controller actions ## This concern has +follow+ and +unfollow+ controller actions
## When you use it, be sure that +set_followable+ method is implemented in your controller, otherwise an fatal error will raise. ## When you use it, be sure that +set_followable+ method is implemented in your controller, otherwise an fatal error will raise.
module FollowableController module FollowableController
extend ActiveSupport::Concern extend ActiveSupport::Concern
included do included do
before_action :authenticate_user!, only: [:follow, :unfollow] before_action :authenticate_user!, only: [:follow, :unfollow, :follow_toggle]
end end
# POST /v1/users/1/follow # POST /v1/users/1/follow
...@@ -28,4 +47,18 @@ module FollowableController ...@@ -28,4 +47,18 @@ module FollowableController
render status: :forbidden render status: :forbidden
end end
end end
# PUT /v1/users/1/follow
# PUT /v1/users/1/follow.json
def follow_toggle
if !current_user.following?(followable)
current_user.follow(followable)
render status: :created
elsif current_user.following?(followable)
current_user.unfollow(followable)
render status: :ok
else
render status: :forbidden
end
end
end end
# Copyright (C) 2015 Centro de Computacao Cientifica e Software Livre
# Departamento de Informatica - Universidade Federal do Parana
#
# This file is part of portalmec.
#
# portalmec 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, either version 3 of the License, or
# (at your option) any later version.
#
# portalmec 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 portalmec. If not, see <http://www.gnu.org/licenses/>.
module HighlightsController module HighlightsController
extend ActiveSupport::Concern extend ActiveSupport::Concern
......
# Copyright (C) 2015 Centro de Computacao Cientifica e Software Livre
# Departamento de Informatica - Universidade Federal do Parana
#
# This file is part of portalmec.
#
# portalmec 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, either version 3 of the License, or
# (at your option) any later version.
#
# portalmec 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 portalmec. If not, see <http://www.gnu.org/licenses/>.
module Paginator module Paginator
extend ActiveSupport::Concern extend ActiveSupport::Concern
def paginate (model) def paginate(model)
set_header model model = params_actions(model)
total_count model
return model.limit(limit).offset(offset) if model.respond_to?('limit') return model.limit(limit).offset(offset) if model.respond_to?('limit')
return model[offset..limit] return model[offset..limit]
end end
private private
def limit def limit
return 50 if params[:limit].blank? return params[:limit].to_i if !params[:limit].blank?
params[:limit].to_i return params[:results_per_page].to_i if !params[:results_per_page].blank?
end return 12
end
def offset
return 0 if params[:offset].blank?
params[:offset].to_i
end
def set_header(model) def offset
headers['X-Total-Count'] = model.count return params[:offset].to_i if !params[:offset].blank?
end return params[:page].to_i*limit if !params[:page].blank?
return 0
end
def params_actions(model)
# filtering
if !params[:filter].blank?
(JSON.parse params[:filter]).each do |key, value|
if(model.columns_hash[key].type == :integer)
model = model.where("#{key}": value)
else
model = model.where("#{key} ILIKE '%'|| ? || '%'", value)
end
end
end
# ordering
to_sort = JSON.parse params[:sort] if !params[:sort].blank?
model = model.order("\"#{model.table_name}\".\"#{to_sort[0]}\" #{to_sort[1]}") if !to_sort.blank?
return model
end
def total_count(model)
headers['X-Total-Count'] = model.count
end
end end
# Copyright (C) 2015 Centro de Computacao Cientifica e Software Livre
# Departamento de Informatica - Universidade Federal do Parana
#
# This file is part of portalmec.
#
# portalmec 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, either version 3 of the License, or
# (at your option) any later version.
#
# portalmec 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 portalmec. If not, see <http://www.gnu.org/licenses/>.
module PublisherController
extend ActiveSupport::Concern
include Paginator
included do
before_action :authenticate, only: [:show_all_drafts, :show_liked_learning_objects, :show_submissions, :show_liked_collections]
before_action :set_publisher, only: [:show_all_drafts, :show_all_learning_objects, :show_submissions, :show_all_collections, :show_liked_learning_objects, :show_liked_collections]
before_action -> { authorize @publisher }, only: [:show_all_drafts, :show_submissions, :show_liked_learning_objects, :show_liked_collections]
end
def show_all_drafts
learning_objects = paginate LearningObject.where(publisher: @publisher, state: LearningObject.states[:draft])
render json: learning_objects
end
# GET /v1/users/1/learning_objects
def show_all_learning_objects
learning_objects = paginate LearningObject.where(publisher: @publisher, state: LearningObject.states[:published])
render json: learning_objects
end
# GET /v1/users/:id/submissions
def show_submissions
status = params[:status]
if !status.nil? && !Submission.statuses.has_key?(status) && status != 'all'
render json: {"error": "Status not found."}, status: :unprocessable_entity
else
if current_user.is_curator?
submissions = current_user.assignments
else
submissions = current_user.submissions
end
submissions = submissions.where(status: status) unless status.nil? || status == 'all'
render json: paginate(submissions), status: :ok
end
end
def show_all_collections
collections = paginate ::UserPolicy::CollectionScope.new(current_user, @publisher, Collection).resolve.where(owner: @publisher)
render json: collections
end
def show_liked_learning_objects
includes = [:taggings, :tags, :subject_relations, :subjects, :stage_relations, :educational_stages, :publisher, :language, :license]
learning_objects = paginate LearningObject.includes(includes).where(id: Like.where(user: @publisher, likeable_type: 'LearningObject').pluck(:likeable_id)
)
render json: learning_objects
end
def show_liked_collections
collections = paginate Collection.where( id: Like.where(user: @publisher, likeable_type: 'Collection').pluck(:likeable_id)
)
render json: collections
end
protected
def authenticate
authenticate_user!
end
def set_publisher
user, id = request.path.split('/')[2, 2]
return nil unless %w(users institutions).include? user
publisher_model = user.singularize.classify.constantize
@publisher = publisher_model.where(id: params[:id]).first
render status: :not_found if @publisher.blank?
@publisher
end
end
# Copyright (C) 2015 Centro de Computacao Cientifica e Software Livre
# Departamento de Informatica - Universidade Federal do Parana
#
# This file is part of portalmec.
#
# portalmec 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, either version 3 of the License, or
# (at your option) any later version.
#
# portalmec 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 portalmec. If not, see <http://www.gnu.org/licenses/>.
module ResourceModel module ResourceModel
extend ActiveSupport::Concern extend ActiveSupport::Concern
......
# Copyright (C) 2015 Centro de Computacao Cientifica e Software Livre
# Departamento de Informatica - Universidade Federal do Parana
#
# This file is part of portalmec.
#
# portalmec 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, either version 3 of the License, or
# (at your option) any later version.
#
# portalmec 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 portalmec. If not, see <http://www.gnu.org/licenses/>.
## This concern has all default resource methods for CRUD operations ## This concern has all default resource methods for CRUD operations
## When you use it, be sure that +reviewable+ method is implemented in your controller, otherwise an fatal error will raise. ## When you use it, be sure that +reviewable+ method is implemented in your controller, otherwise an fatal error will raise.
module ReviewableController module ReviewableController
...@@ -10,7 +29,7 @@ module ReviewableController ...@@ -10,7 +29,7 @@ module ReviewableController
# GET /v1/collections/1/reviews # GET /v1/collections/1/reviews
def index def index
render json: Review.where(reviewable: reviewable) render json: paginate(Review.where(reviewable: reviewable)), each_serializer: ReviewSerializer
end end
# GET /v1/collections/1/reviews/1 # GET /v1/collections/1/reviews/1
......
# Copyright (C) 2015 Centro de Computacao Cientifica e Software Livre
# Departamento de Informatica - Universidade Federal do Parana
#
# This file is part of portalmec.
#
# portalmec 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, either version 3 of the License, or
# (at your option) any later version.
#
# portalmec 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 portalmec. If not, see <http://www.gnu.org/licenses/>.
## This concern has +like+, +unlike+ controller actions ## This concern has +like+, +unlike+ controller actions
## When you use it, be sure that +set_sociable+ method is implemented in your controller, otherwise an fatal error will raise. ## When you use it, be sure that +set_sociable+ method is implemented in your controller, otherwise a fatal error will raise.
module SociableController module SociableController
extend ActiveSupport::Concern extend ActiveSupport::Concern
VIEWABLE_METHODS = [:show] VIEWABLE_METHODS = [:show]
included do included do
before_action :authenticate_user!, only: [:like, :unlike] before_action :authenticate_user!, only: [:like]
before_action :authorize_sociable!, only: [:like, :unlike] before_action :authorize_sociable!, only: [:like]
before_action :view_object!, only: VIEWABLE_METHODS before_action :view_object!, only: VIEWABLE_METHODS
end end
# POST /v1/learning_objects/1/like # PUT /v1/learning_objects/1/like
# POST /v1/learning_objects/1/like.json # PUT /v1/learning_objects/1/like.json
def like def like
if !sociable.liked? current_user if !sociable.liked? current_user
sociable.like current_user sociable.like current_user
render json: {count: sociable.likes.count}, status: :created render json: {count: sociable.likes.count}, status: :created
else elsif sociable.liked? current_user
render status: :forbidden
end
end
# DELETE /v1/learning_objects/1/unlike
# DELETE /v1/learning_objects/1/unlike.json
def unlike
if sociable.liked? current_user
sociable.dislike current_user sociable.dislike current_user
render json: {count: sociable.likes.count}, status: :ok render json: {count: sociable.likes.count}, status: :ok
else else
...@@ -44,7 +56,8 @@ module SociableController ...@@ -44,7 +56,8 @@ module SociableController
end end
def view_object! def view_object!
sociable.view current_user if user_signed_in? # Change request.remote_ip to req.env["HTTP_X_REAL_IP"] in production
sociable.view(current_user, request.remote_ip) unless sociable.nil?
end end
end end
# Copyright (C) 2015 Centro de Computacao Cientifica e Software Livre
# Departamento de Informatica - Universidade Federal do Parana
#
# This file is part of portalmec.
#
# portalmec 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, either version 3 of the License, or
# (at your option) any later version.
#
# portalmec 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 portalmec. If not, see <http://www.gnu.org/licenses/>.
module StageableController
extend ActiveSupport::Concern
included do
before_action :authenticate_user!, only: [:add_stages, :remove_stages]
end
# POST /v1/learning_objects/1/educational_stages
# POST /v1/learning_objects/1/educational_stages.json
def add_stages
stageable.add_educational_stages(ids: params[:educational_stages])
render json: stageable.educational_stages, status: :created
end
# DELETE /v1/learning_objects/1/educational_stages
# DELETE /v1/learning_objects/1/educational_stages.json
def remove_stages
stageable.remove_educational_stages(ids: params[:educational_stages])
render json: stageable.educational_stages, status: :ok
end
protected
def stageable
raise NotImplementedError
end
end
# Copyright (C) 2015 Centro de Computacao Cientifica e Software Livre
# Departamento de Informatica - Universidade Federal do Parana
#
# This file is part of portalmec.
#
# portalmec 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, either version 3 of the License, or
# (at your option) any later version.
#
# portalmec 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 portalmec. If not, see <http://www.gnu.org/licenses/>.
module SubjectableController
extend ActiveSupport::Concern
included do
before_action :authenticate_user!, only: [:subjecting, :unsubjecting]
end
# POST /v1/learning_objects/1/subjects
# POST /v1/learning_objects/1/subjects.json
def subjecting
subjectable.add_subjects(ids: params[:subjects])
render json: subjectable.subjects, status: :created
end
# DELETE /v1/learning_objects/1/subjects
# DELETE /v1/learning_objects/1/subjects.json
def unsubjecting
subjectable.remove_subjects(ids: params[:subjects])
render json: subjectable.subjects, status: :ok
end
protected
def subjectable
raise NotImplementedError
end
end