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 (1667)
Showing
with 1120 additions and 921 deletions
attributes:
- content
- foreign_key
- inheritance
disconnected: true
filename: erd
filetype: pdf
indirect: true
inheritance: true
markup: true
notation: bachman
orientation: horizontal
polymorphism: false
sort: true
warn: true
title: PortalMEC
exclude: null
only: null
prepend_primary: false
......@@ -22,6 +22,9 @@ Gemfile.lock
/public/assets
/config/orientdb.yml
/config/dspace.yml
/shared/*
dump.rdb
/public/system/*
# ignore server scripts
puma.sh
......
image: ruby:2.7
services:
- postgres
- postgres:11
- elasticsearch:6.5.1
- redis:latest
variables:
POSTGRES_DB: portalmec_test
POSTGRES_USER: portalmec
POSTGRES_PASSWORD: 123mudar
ELASTICSEARCH_URL: http://elasticsearch:9200
REDIS_HOST: redis:6379
REDIS_RATE_LIMIT_URL: redis://redis:6379/0
DSPACE_LOGIN: '$mecdb1_login'
DSPACE_PASS: '$mecdb1_password'
stages:
- test
- apidoc
- deploy
before_script:
- apt-get update -y
- apt-get install default-jre postgresql-client -y
- apt-get remove --purge --auto-remove 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
- export PGPASSWORD=$POSTGRES_PASSWORD
- psql -h "postgres" -U "$POSTGRES_USER" -d "$POSTGRES_DB" -c "SELECT 'OK' AS status;"
......@@ -24,21 +37,34 @@ test:
stage: test
script:
- bundle exec rake db:migrate:reset RAILS_ENV=test
- rake test
- bundle exec rake spec:acceptance
tags:
- ruby
- postgres
- elasticsearch
- redis
#deploy:
# stage: deploy
# script:
# - mina deploy
# only:
# - master
# tags:
doc:
stage: apidoc
script:
- bundle exec rake db:migrate:reset RAILS_ENV=test
- bundle exec rake docs:generate
- ./docploy.sh
only:
- stable
tags:
- ruby
- postgres
- elasticsearch
- redis
# deploy:
# stage: deploy
# script:
# # - mina deploy
# only:
# - master
# tags:
# - ruby
# - postgres
# - elasticsearch
# - redis
\ No newline at end of file
# - redis
2.2
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'
# Bundle edge Rails instead: gem 'rails', github: 'rails/rails'
gem 'rails', '4.2.6'
gem 'rails', '>=6.0.0'
# Use postgresql as the database for Active Record
gem 'pg'
# 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
gem 'bcrypt', '~> 3.1.7'
gem 'bcrypt', '>= 3.1.7'
# memcached
gem 'dalli'
# dalli multi thread gem
gem 'connection_pool'
# web server
gem 'puma'
# protection
gem 'rack-attack'
# scheduler
gem 'whenever', require: false
......@@ -24,16 +30,16 @@ gem 'whenever', require: false
gem 'devise'
# files
gem 'paperclip'
gem 'kt-paperclip', github: 'kreeti/kt-paperclip', branch: 'master'
# 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 'rmagick'
# Dspace REST API Integration
gem 'dspace_rest_client'
gem 'dspace_rest_client', github: 'c3sl/dspace-rest-client', branch: 'master'
# pretty logs
gem 'rainbow'
......@@ -47,9 +53,10 @@ gem 'stackprof'
group :development do
gem 'annotate'
gem 'immigrant'
gem 'derailed_benchmarks'
# Generate ER Diagram from database (use: rake erd)
# Github Page: https://github.com/voormedia/rails-erd
gem 'rails-erd'
......@@ -74,27 +81,38 @@ group :development do
# reduce queries - https://github.com/flyerhzm/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
gem 'byebug'
# 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
gem 'spring'
# JavaScript runtime
gem 'execjs'
# local mailbox
# gem 'mailcatcher'
end
group :test do
gem 'shoulda'
gem 'minitest-reporters'
gem 'faker'
gem 'database_cleaner'
end
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'
gem 'streamio-ffmpeg', '>= 1.0.0'
# sidekiq
gem 'sidekiq'
......@@ -102,13 +120,13 @@ gem 'sinatra', require: false
gem 'slim'
# CUrl
gem 'curb', '~> 0.8.8'
gem 'curb', '>= 0.8.8'
# libArchive (Zip, Rar, ...)
# C extension is required
# 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-static'
gem 'ffi-libarchive'
gem 'gitlab'
......@@ -127,7 +145,7 @@ gem 'activerecord-import'
# social connect
gem 'omniauth-facebook'
gem 'omniauth-twitter'
gem 'omniauth-google-oauth2'
gem 'omniauth-google-oauth2', '~>0.8.2'
# get mime type
gem 'mimemagic'
......@@ -135,9 +153,22 @@ gem 'mimemagic'
# html screenshot
gem 'screencap'
# using while rails 5 isn't released
gem 'rails-api'
# model json serializer
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
gem 'rubyzip'
# user activity
gem 'public_activity'
# gem 'rails-observers'
# soft-deleted for active record models
#gem 'paranoia', github: 'rubysherpas/paranoia', branch: 'rails4'
gem 'paranoia'
# models versioning
gem 'paper_trail'
gem 'acts_as_list'
This diff is collapsed.
# 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
* ruby >=2.2
* rvm
* Dspace server
* Postgres >=9.4
* Elasticsearch
* Redis
* Using rvm you will install ruby "3.0.1"
* ruby "3.0.1"
* Dspace server "6.x"
* 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
First of all, you need configure the dspace, elasticsearch and redis servers. An user for postgres database will be needed to.
After this setup, open the config files and update some vars:
First of all, you need to configure the dspace, elasticsearch and redis servers. Create an user for postgres database.
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/dspace.yml: change your dspace host and credentials for development and test environment.
* 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 )
### 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
You can use docker for your development environment. For that, run:
``` ./bin/docker-setup ```
You can use docker for your development environment. For that, run:
./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/...).
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 ```
<!--
Se a rotina de testes descrita pelo rake test for arrumada, o comando a baixo funcionara
### Running tests suite
For tests, TestUnit is used, and to run it:
``` bundle exec rake test ```
For tests, TestUnit is used, and to run it
``` 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
As you set development and test environment vars, now production vars will be needed to be set.
For that, open the file config/env_vars.sh and set them. After, run:
``` ./config/env_vars.sh ```
When working in the production environment, the environment variables must be set in the file config/env_vars.sh.
After setting the variables in the file, you must include the following line into your user's .bashrc file:
* ``` source /home/portalmec/portalmec/config/env_vars.sh ```
* Redis vars need to be set on config/sidekiq.yml
* In config/initializers/devise.rb, change the emails addresses. (Ex.: config.mailer_sender = 'suporte@c3sl.ufpr.br')
You will also need to make some other configurations:
Now, you can run and your application is ready to use:
``` ./bin/setup ```
* Redis vars need to be set on config/sidekiq.yml
* 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.
\ No newline at end of file
Now that your application is ready, you can run it with:
* ``` systemctl start portalmec portalmec-sidekiq ```
// This is a manifest file that'll be compiled into application.js, which will include all the files
// listed below.
//
// Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts,
// or any plugin's vendor/assets/javascripts directory can be referenced here using a relative path.
//
// It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the
// compiled file.
//
// Read Sprockets README (https://github.com/sstephenson/sprockets#sprockets-directives) for details
// about supported directives.
//
//= require jquery
//= require jquery.turbolinks
//= require jquery_ujs
//= require jquery-ui/autocomplete
//= require bootstrap-sprockets
//= require select2
//= require select2_locale_pt-BR
//= require bootstrap-tagsinput
//= require turbolinks
//= require social-share-button
//= require resumable
//= require_tree ./application
$(document).ready(function () {
$('[data-toggle="tooltip"]').tooltip();
$(document).on('ajax:success', '.bookmark-button', function(status, data, xhr) {
if ( $(this).hasClass('btn-default') ) {
$(this).removeClass('btn-default').addClass('btn-success');
$(this).data('method', 'delete');
}
else {
$(this).removeClass('btn-success').addClass('btn-default');
$(this).data('method', 'post');
}
});
});
$(function() {
return $(document).on('ajax:success', '.like', function(status, data, xhr) {
if ( $(this).hasClass('btn-default') ) {
$(this).removeClass('btn-default').addClass('btn-primary');
}
else {
$(this).removeClass('btn-primary').addClass('btn-default');
}
});
});
$ ->
# create collection popover
$('#create_collection_popover').popover
html: true
content: ->
$('#create_collection_popover_content').html()
title: ->
$('#create_collection_popover_title').html()
return
# add/remove learning object to collection
$(document).on 'click', '.add-to-collection', ->
$(document).trigger('open_collections_modal', [learning_object: [$(this).data('loid')], type: 'add'])
# change collection privacy
$(document).on 'click', 'input[name=privacy]', ->
url = '/collections/' + encodeURIComponent($(this).data('cid')) + '/change_privacy'
value = $('input[name=privacy]:checked').val()
$.post url, {'privacy':value}, (d) ->
d
$(document).on 'open_collections_modal', (evt, params) ->
id = if (params.collection == undefined) then "all" else encodeURIComponent(params.collection)
url = '/collections/' + id + '/list?type=' + params.type
url += '&learning_objects_ids=' + encodeURIComponent(params.learning_object) if params.learning_object != undefined
$.get url, (d) ->
$('#collections-modal').remove()
$('body').append d
$('#collections-modal').modal('show')
return
mount_modal_params = (e) ->
array = $(e).serializeArray()
object = {}
collection = ""
type = ""
collections = []
learning_objects = []
i = 0
length = array.length
while i < length
switch array[i].name
when 'collection' then collections.push(array[i].value)
when 'learning_object' then learning_objects.push(array[i].value)
when 'collection_id' then collection = array[i].value
when 'type' then type = array[i].value
++i
object.collection_id = collection
object.collections_ids = collections if collections.length > 0
object.learning_objects_ids = learning_objects if learning_objects.length > 0
object.type = type
return object
$(document).on 'submit', '#collections-modal-form', (evt, params) ->
evt.preventDefault()
data = mount_modal_params(this)
return false if (data.learning_objects_ids.length < 1) || (data.collections_ids.length < 1) || (permitted_types.indexOf(data.type) < 0)
id = if (data.collections_ids == undefined) then data.collection_id else data.collections_ids
url = '/collections/' + encodeURIComponent(id) + '/learning_objects/' + encodeURIComponent(data.learning_objects_ids.join())
$.ajax {method: "POST", url: url, data: data }
.done () ->
if (data.type == "move")
url = '/collections/' + encodeURIComponent(data.collection_id) + '/learning_objects/' + encodeURIComponent(data.learning_objects_ids.join())
$.ajax {method: "DELETE", url: url, data: data }
.done ->
$(document).trigger('refresh_comments')
$(document).trigger 'flash_notice', {text: 'Operação efetuada com sucesso!', type: 'notice'}
$(document).trigger('clear_collections')
$('#collections-modal').modal('hide')
return
# manipulate collections
# $(document).on 'ready page:load', ->
# if $('.collection-show-page').val() != undefined
# array with selected objects ids
selected_objects = []
$ ->
selected_objects = []
# valid types of operations in collections
permitted_types = ['add', 'download', 'copy', 'move', 'remove']
$(document).on 'ready page:load', ->
if $('.collection-show-page').val() != undefined
$(document).trigger('add_collection_selector')
# add selectors to learning objects
$(document).on 'add_collection_selector', (e) ->
$('.learning-object-vertical').each (e) ->
loid = $(this).data('loid')
type = $(this).data('type')
$('.learning-object-thumbnail', this).append '<input class="collection-selector" type="checkbox" value="' + loid + '" data-type="' + type + '" ></input>'
return
# add/remove object to array when click checkbox
$(document).on 'click', '.collection-selector', ->
if this.checked
if selected_objects.indexOf(this.value) < 0
selected_objects.push { "class" : $(this).attr('data-type'), "value" : this.value}
$(document).trigger('check_selected_collection')
return
else
i = 0
while i < selected_objects.length
if (selected_objects[i].value == this.value)
selected_objects.splice(i, 1)
i++
$(document).trigger('check_selected_collection')
return
# select all objects
$(document).on 'mark_all_collections', ->
selected_objects = []
$('.collection-selector').prop('checked', true)
$('.collection-selector').each () ->
selected_objects.push { "class" : $(this).attr('data-type'), "value" : this.value}
console.log(selected_objects)
$(document).trigger('check_selected_collection')
$(document).on 'change', '.count-collections-objects', ->
if ($(this).prop('checked'))
$(document).trigger('mark_all_collections')
else
$(document).trigger('clear_collections')
# clear selected objects
$(document).on 'clear_collections', ->
selected_objects = []
$('.collection-selector').attr('checked', false)
$(document).trigger('check_selected_collection')
# manipulation buttons
$(document).on 'click', '.collection-button', ->
collection = $('.collection-show-page').data('cid')
index = permitted_types.indexOf($(this).data('action'))
urls = []
learning_objects = []
if permitted_types[index] == 'remove'
if ($('.collection-button').data('class') == 'collections')
i = 0
while i < selected_objects.length
learning_objects.push selected_objects[i]["value"]
i++
urls.push '/collections/' + encodeURIComponent(collection) + '/learning_objects/' + encodeURIComponent(learning_objects.join(','))
else
i = 0
while i < selected_objects.length
urls.push '/bookmarks/' + encodeURIComponent(selected_objects[i]["class"]) + '/' + encodeURIComponent(selected_objects[i]["value"])
i++
if confirm('Você tem certeza?')
i = 0
while i < urls.length
$.ajax { method: 'DELETE', url: urls[i] }
.done ->
$(document).trigger 'refresh_comments'
i++
else
$(document).trigger('open_collections_modal', [collection: collection, type: permitted_types[index], learning_object: selected_objects ]) if !!(~index)
# refresh comments via ajax
$(document).on 'refresh_comments', (e) ->
selected_objects = []
$(document).trigger 'check_selected_collection'
$parent = $('.learning-object-columns')
url = window.location.pathname + '?list=true'
$parent.html('Carregando...')
$.get url, (data) ->
$parent.html('<br>' + data)
num = $('.learning-object-vertical').length
if num == 1
$('.object-number').html("1 objeto")
else if num > 1
$('.object-number').html( num + " objetos")
else
$('.object-number').html("coleção vazia")
$(document).trigger 'create-learning-object-columns'
$(document).trigger 'add_collection_selector'
# update interface when add/remove an object
$(document).on 'check_selected_collection', (e) ->
length = selected_objects.length
if length == 0
$('.count-collections-objects').prop('checked',false)
return $('.collection-show-select-nav').slideUp('slow')
else if (length == 1)
html = "1 objeto selecionado"
else
html = length + " objetos selecionados"
$('.collection-show-select-nav .navbar-brand').html html
$('.collection-show-select-nav').slideDown('slow')
$ ->
$(document).on 'ajax:success', 'a.vote', (status, data, xhr) ->
$('.votes-count[data-id=\'' + data.id + '\']').text data.count
if $('.vote img').attr('alt') == 'Descurtir'
$('.vote img').attr('src',"<%= image_path('icons/btn_like_up.png') %>")
$('.vote img').attr('alt', 'Curtir').reload()
else if $('.vote img').attr('alt') == 'Curtir'
$('.vote img').attr('src',"<%= image_path('icons/btn_like_down.png') %>")
$('.vote img').attr('alt', 'Descurtir').reload()
return
return
bookmarks_btn = ->
$(document).on 'ajax:success', '.bookmark', (status, data, xhr) ->
if $('.fa-bookmark').attr('id') == 'bookmarked'
$('.fa-bookmark').attr('style', '')
$('.fa-bookmark').attr('id', 'not-bookmarked')
$('.fa-bookmark').parent().data('method', 'post')
else
$('.fa-bookmark').attr('style', 'color:#27ae60')
$('.fa-bookmark').attr('id', 'bookmarked')
$('.fa-bookmark').parent().data('method', 'delete')
return
$(document).on('pageinit',bookmarks_btn())
# flash notice ()
$(document).on 'flash_notice', (e, params) ->
text = params.text
type = params.type
alert_type = if (type == 'alert') then 'alert-danger alert-dismissible' else 'alert-info'
html = '<div class="alert '+ alert_type + '" role="alert">
<button type="button" class="close" data-dismiss="alert" aria-label="Fechar">
<span aria-hidden="true">&times;</span></button>' + text + '</div>'
$('#content').prepend($(html)).fadeIn(800)
$("#content > .alert").first().delay(5000).fadeOut 800, () ->
$(this).remove()
$(document).ready(function(){
$('.review').each(function(){
review_id = this.getAttribute("id");
toogle_id= "#popovertoggle_" + review_id;
content_id = "#popovercontent_" + review_id;
content = $(content_id).html();
$(toogle_id).popover({
placement : 'right', //placement of the popover. also can use top, bottom, left or right
html: 'true', //needed to show html of course
content: content,
trigger: 'hover'
});
});
$('.review-button-approve').on('ajax:success', function() {
$(this).parent().children('.review-button-desapprove').removeClass('desapproved');
$(this).hasClass('approved') ? $(this).removeClass('approved') : $(this).addClass('approved');
});
$('.review-button-desapprove').on('ajax:success', function() {
$(this).parent().children('.review-button-approve').removeClass('approved');
$(this).hasClass('desapproved') ? $(this).removeClass('desapproved') : $(this).addClass('desapproved');
});
});
#s2id_myelement > .select2-choice{
background-color:green;
}
.autocomplete {
margin-right: 5px;
}
.search-sidebar {
margin-top: 40px;
display: none;
.bootstrap-tagsinput {
border: 0;
border-radius: 0;
box-shadow: 0px 0px 0px;
input {
display: none;
}
.label {
font-size: 16px;
font-weight: 300;
display: inline-block;
margin-bottom: 6px;
white-space: normal;
}
}
.open{
cursor: pointer;
}
.dropdown-element {
width: 95%;
margin-left: 3%;
.label-checkbox {
cursor: pointer;
width: 100%;
position: relative;
font-weight: 300;
margin-bottom: 8px;
padding-right: 15px;
input[type=checkbox] {
position: absolute;
right: 5px;
}
}
}
}
.nestedAccordion {
.dropdown {
margin-top: 10px !important;
margin-bottom: 10px !important;
}
}
.select2-container {
width: 100% !important;
}
.result-bar {
margin-top: 40px;
margin-bottom: 18px;
display: none;
.result-info {
font-size:24px;
font-weight: 400;
color: #88888D;
line-height: 1.1;
}
.result-order{
font-weight: 500;
color: #88888D;
}
.sort-dropdown {
border: 0;
border-radius: 3px;
color: #59585A;
padding-right: 20px;
}
}
class LearningObject::DraftBuilder
def self.build(publisher, params={})
@draft = LearningObject.new(sanitize_params(params))
@draft.draft
# build topics
params[:topics].try(:each) do |t|
@draft.topics << Topic.find(t)
end
#build language
@draft.language = Language.find(params[:language]) if params[:language].to_i > 0
# set publisher
@draft.publisher = publisher
@draft
end
private
def self.sanitize_params(args={})
_args = args.clone
%w(topics language link).each do |arg|
_args.delete(arg)
end
metadata = [{'key' => 'dc.object.url', 'value' => args[:link]}]
_args.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
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(
name: item.name,
id_dspace: item.id,
thumbnail: nil,
metadata: item.metadata.map(&:to_h)
name: item.name,
id_dspace: item.id,
thumbnail: nil,
metadata: dspace_metadata_to_hash(item.metadata)
)
institution = lo.get_metadata_values_of('dc.creator').first
institution = 'Desconhecido' if institution.blank?
lo.publisher = Institution.where(name: institution).first_or_create
lo.name = "Recurso Sem Nome" if lo.name.blank?
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 = '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')
lo.published_at = Time.iso8601(date) unless date.nil?
ot = ObjectType.where(name: object_type)
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 = 'pt' if code.blank?
language = Language.where(code: code).first
language = Language.create(name: code, code: code) if language.nil?
lo.language = language
language = Language.where(code: "Outro").first if language.nil?
# 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 = publisher.name if lo.author.blank?
lo.description = lo.get_metadata_value_of('dc.description')
lo
end
def self.build_form_params(params={}, publisher = nil)
_params = params.clone
_params.delete :link
lo.link = lo.get_metadata_value_of('dc.relation.uri')
lo.link = lo.get_metadata_value_of('dc.relation') if lo.link.blank?
# build topics
_params[:topics] = []
params[:topics].try(:each) do |t|
_params[:topics] << Topic.find(t)
end
# lo.state = LearningObject.states[:published]
#build language
_params[:language] = Language.find(params[:language]) if params[:language].to_i > 0
lo
end
# set publisher
_params[:publisher] = publisher unless publisher.nil?
_params
def self.dspace_metadata_to_hash(metadata)
hash = Hash.new { |h, k| h[k] = Array.new(&h.default_proc) }
metadata.each { |m| hash[m.key] << m.value }
hash
end
# private
private
#def self.sanitize_form_metadata(params={})
# if !params[:link].blank?
# metadata = [{'key' => 'dc.object.url', 'value' => params[:link]}]
# _args.merge(metadata: metadata)
# end
# _args
# end
def self.insert_tag(tag_str, lo, publisher)
tag = Tag.where(name: tag_str).first_or_create
if !lo.tags.include?(tag)
tagging = Tagging.new(tag: tag, tagger: publisher, taggable: lo)
lo.taggings << tagging
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
include ActionController::Serialization
include DeviseTokenAuth::Concerns::SetUserByToken
include Pundit
include PublicActivity::StoreController
# tracking user in papertrail
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.
before_action :allow_client_application, if: -> { Feature.active?(:allow_client_application) }
# Prevent CSRF attacks by raising an exception.
# For APIs, you may want to use :null_session instead.
# protect_from_forgery with: :null_session
before_action :configure_permitted_parameters, if: :devise_controller?
before_filter :link_return
rescue_from Pundit::NotAuthorizedError, with: :user_not_authorized
# ensure *current_user* can be called in PublicActivity models
# helper_method :current_user
# hide_action :current_user
protected
def configure_permitted_parameters
registration_params = [:name, :email, :avatar, :password, :password_confirmation]
if params[:action] == 'update'
devise_parameter_sanitizer.for(:account_update) {
|u| u.permit(registration_params << :current_password)
}
elsif params[:action] == 'create'
devise_parameter_sanitizer.for(:sign_up) {
|u| u.permit(registration_params << :terms_of_service)
}
end
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 :account_update, keys: registration_params
end
private
# handles storing return links in the session
def link_return
if params[:return_uri]
session[:original_uri] = params[:return_uri]
end
def allow_client_application
app = Application.find_or_initialize_by(application_id: request.headers["PortalMEC-AppID"].to_s)
user_not_authorized if app.domain != request.domain
end
def user_not_authorized
render status: :unauthorized
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
extend ActiveSupport::Concern
def deleted
render json: deleted_resource.only_deleted
end
protected
def deleted_resource
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 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
## When you use it, be sure that +set_followable+ method is implemented in your controller, otherwise an fatal error will raise.
module FollowableController
extend ActiveSupport::Concern
included do
before_action :authenticate_user!, only: [:follow, :unfollow]
before_action :authenticate_user!, only: [:follow, :unfollow, :follow_toggle]
end
# POST /v1/users/1/follow
......@@ -12,9 +31,9 @@ module FollowableController
def follow
if !current_user.following?(followable)
current_user.follow(followable)
render nothing: true, status: :created
render status: :created
else
render nothing: true, status: :forbidden
render status: :forbidden
end
end
......@@ -23,10 +42,23 @@ module FollowableController
def unfollow
if current_user.following?(followable)
current_user.unfollow(followable)
render nothing: true, status: :ok
render status: :ok
else
render nothing: true, status: :forbidden
render status: :forbidden
end
end
end
\ No newline at end of file
# 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