diff --git a/app/channels/application_cable/connection.rb b/app/channels/application_cable/connection.rb index af25058ad707f8107aa72d6a5983c06975e3ef4e..a427edb998d3f2c629e5f3a64db971bf591b67d4 100644 --- a/app/channels/application_cable/connection.rb +++ b/app/channels/application_cable/connection.rb @@ -1,21 +1,22 @@ module ApplicationCable - ## - # This class identifies the current user in a websocket communication using ApplicationCable + ## + # This class identifies the current user in a websocket communication using ApplicationCable class Connection < ActionCable::Connection::Base - identified_by :current_user + identified_by :current_user - def connect - self.current_user = find_user - end + def connect + self.current_user = find_user + end - def find_user - user_id = cookies.signed["user.id"] - current_user = User.find_by(id: user_id) - if current_user - current_user - else - reject_unauthorized_connection - end + def find_user + current_user = User.find_by(labs_user_id: "2") + if current_user + puts "Current user case, id #{current_user.id}" + current_user + else + puts "Unauthorized connection rejected" + reject_unauthorized_connection end + end end end diff --git a/app/controllers/application_controller.rb b/app/controllers/application_controller.rb index 81692ba10881bc1382451b92cbf2931dbee1e43d..3863792f9c01b9642dfa79457ca3798a0e38b640 100644 --- a/app/controllers/application_controller.rb +++ b/app/controllers/application_controller.rb @@ -1,10 +1,9 @@ class ApplicationController < ActionController::Base - include Authentication - - def send_file - File.open("tmp/#{params[:filename]}", 'r') do |f| - send_data f.read, type: "text/json", filename: params[:filename] - end - end + include Authentication + def send_file + File.open("tmp/#{params[:filename]}", "r") do |f| + send_data f.read, type: "text/json", filename: params[:filename] + end + end end diff --git a/app/controllers/catalog_controller.rb b/app/controllers/catalog_controller.rb index 2b7a4aadb88fc1af252e7cab37f6b438f9067e0f..ecd7a53bdef6c73b582507b83ac04b7cce08ea5c 100644 --- a/app/controllers/catalog_controller.rb +++ b/app/controllers/catalog_controller.rb @@ -1,220 +1,220 @@ class CatalogController < ApplicationController + before_action :authenticate_user!, :strip_input_fields - before_action :authenticate_user!, :strip_input_fields + def home + end - def home - - end - - ## - # Creates a search query and submit it to the index. Retrieve and displays results + metadata. - def index - if params[:q] - @search_type = params[:search_type].nil? ? "exact" : params[:search_type] - @solr_params = SolrQuery.new(@search_type).to_params - @solr_params[:q] = params[:q] - @solr_params[:rows] = params[:per_page] if params[:per_page] - @current_page = params[:page].to_i != 0 ? params[:page].to_i : 1 - @solr_params[:start] = params[:page].to_i != 0 ? @solr_params[:rows] * (params[:page].to_i-1) : 0 - @solr_params[:sort] = params[:sort] if params[:sort] - if params[:f] - params[:f].each do |k,v| - if k == "date_created_dtsi" # v is a hash {to: "", from: ""} - @solr_params[:fq] << "#{k}:[#{v['from']}T00:00:00Z TO #{v['to']}T00:00:00Z]" - else - if v.is_a? Array - v.each do |val| - @solr_params[:fq] << "#{k}:#{val}" - end - end - end - end + ## + # Creates a search query and submit it to the index. Retrieve and displays results + metadata. + def index + if params[:q] + @search_type = params[:search_type].nil? ? "exact" : params[:search_type] + @solr_params = SolrQuery.new(@search_type).to_params + @solr_params[:q] = params[:q] + @solr_params[:rows] = params[:per_page] if params[:per_page] + @current_page = params[:page].to_i != 0 ? params[:page].to_i : 1 + @solr_params[:start] = params[:page].to_i != 0 ? @solr_params[:rows] * (params[:page].to_i - 1) : 0 + @solr_params[:sort] = params[:sort] if params[:sort] + if params[:f] + params[:f].each do |k, v| + if k == "date_created_dtsi" # v is a hash {to: "", from: ""} + @solr_params[:fq] << "#{k}:[#{v["from"]}T00:00:00Z TO #{v["to"]}T00:00:00Z]" + else + if v.is_a? Array + v.each do |val| + @solr_params[:fq] << "#{k}:#{val}" + end end - session['search_params'] = @solr_params - session['query_params'] = params.to_unsafe_h.slice('q', 'page', 'per_page','sort', 'f') - @results = SolrSearcher.query @solr_params - puts @results.to_json if Rails.env == "development" - @resulting_docs = @results['response']['docs'].map do |solr_doc| - case solr_doc['has_model_ssim'] - when ['Article'] - Article.from_solr_doc solr_doc - when ['Issue'] - Issue.from_solr_doc solr_doc - end - end - entities_fields = I18n.t("newspapers.solr_fields").values_at(:persons, :locations, :organisations, :human_productions) - @entities_labels = [] - entities_fields.each do |entity_field| - (@entities_labels << @results['facets'][entity_field]['buckets'].map{|ne| ne['val']}).flatten! if @results['facets'][entity_field] - end - @entities_labels = helpers.get_entity_label @entities_labels + end + end + end + session["search_params"] = @solr_params + session["query_params"] = params.to_unsafe_h.slice("q", "page", "per_page", "sort", "f") + @results = SolrSearcher.query @solr_params + # puts @results.to_json if Rails.env == "development" + @resulting_docs = @results["response"]["docs"].map do |solr_doc| + case solr_doc["has_model_ssim"] + when ["Article"] + Article.from_solr_doc solr_doc + when ["Issue"] + Issue.from_solr_doc solr_doc end + end + entities_fields = I18n.t("newspapers.solr_fields").values_at(:persons, :locations, :organisations, :human_productions) + @entities_labels = [] + entities_fields.each do |entity_field| + (@entities_labels << @results["facets"][entity_field]["buckets"].map { |ne| ne["val"] }).flatten! if @results["facets"][entity_field] + end + @entities_labels = helpers.get_entity_label @entities_labels end + end - ## - # Display an issue - def show - @issue = Issue.from_solr params[:id], with_pages=true, with_articles=true - session['named_entities'] = Issue.named_entities @issue.id - session['named_entities_labels'] = helpers.get_linked_entities session['named_entities'].map{ |k,v| v.keys }.flatten.uniq - end + ## + # Display an issue + def show + @issue = Issue.from_solr params[:id], with_pages = true, with_articles = true + session["named_entities"] = Issue.named_entities @issue.id + session["named_entities_labels"] = helpers.get_linked_entities session["named_entities"].map { |k, v| v.keys }.flatten.uniq + puts session.inspect + end - ## - # Retrieve named entities for a list of documents (issue and/or articles) - def named_entities_for_docs - named_entities = {LOC: {}, PER: {}, ORG: {}, HumanProd: {}} - params[:docs_ids].each do |doc_id| - if doc_id.index('_article_').nil? - doc_named_entities = session['named_entities'] - else # if article, filter stored list - doc_named_entities = session['named_entities'].map{ |ne_type, ne_list| - [ne_type,ne_list.select{ |linked_id, namedentities| - namedentities.any?{ |ne| - ne['article_id_ssi'] == doc_id - } - }.map{ |k,v| [k,v.select{ |ne| ne['article_id_ssi'] == doc_id }] }.to_h] - }.to_h - end - named_entities[:LOC] = named_entities[:LOC].merge(doc_named_entities[:LOC]) do |key,oldval,newval| - oldval.concat newval - end - named_entities[:ORG] = named_entities[:ORG].merge(doc_named_entities[:ORG]) do |key,oldval,newval| - oldval.concat newval - end - named_entities[:PER] = named_entities[:PER].merge(doc_named_entities[:PER]) do |key,oldval,newval| - oldval.concat newval - end - named_entities[:HumanProd] = named_entities[:HumanProd].merge(doc_named_entities[:HumanProd]) do |key,oldval,newval| - oldval.concat newval - end - end - render partial: 'named_entities/named_entities', locals: {named_entities: named_entities, linked_entities: session['named_entities_labels']} + ## + # Retrieve named entities for a list of documents (issue and/or articles) + def named_entities_for_docs + named_entities = { LOC: {}, PER: {}, ORG: {}, HumanProd: {} } + params[:docs_ids].each do |doc_id| + if doc_id.index("_article_").nil? + doc_named_entities = session["named_entities"] + else # if article, filter stored list + doc_named_entities = session["named_entities"].map { |ne_type, ne_list| + [ne_type, ne_list.select { |linked_id, namedentities| + namedentities.any? { |ne| + ne["article_id_ssi"] == doc_id + } + }.map { |k, v| [k, v.select { |ne| ne["article_id_ssi"] == doc_id }] }.to_h] + }.to_h + end + named_entities[:LOC] = named_entities[:LOC].merge(doc_named_entities[:LOC]) do |key, oldval, newval| + oldval.concat newval + end + named_entities[:ORG] = named_entities[:ORG].merge(doc_named_entities[:ORG]) do |key, oldval, newval| + oldval.concat newval + end + named_entities[:PER] = named_entities[:PER].merge(doc_named_entities[:PER]) do |key, oldval, newval| + oldval.concat newval + end + named_entities[:HumanProd] = named_entities[:HumanProd].merge(doc_named_entities[:HumanProd]) do |key, oldval, newval| + oldval.concat newval + end end + render partial: "named_entities/named_entities", locals: { named_entities: named_entities, linked_entities: session["named_entities_labels"] } + end - ## - # Retrieve named entities for a dataset - def named_entities_for_dataset - dataset = Dataset.find(params[:dataset_id]) - named_entities = dataset.named_entities - named_entities_labels = helpers.get_linked_entities named_entities.map{ |k,v| v.keys }.flatten.uniq - render partial: 'named_entities/named_entities', locals: {named_entities: named_entities, linked_entities: named_entities_labels} - end + ## + # Retrieve named entities for a dataset + def named_entities_for_dataset + dataset = Dataset.find(params[:dataset_id]) + named_entities = dataset.named_entities + named_entities_labels = helpers.get_linked_entities named_entities.map { |k, v| v.keys }.flatten.uniq + render partial: "named_entities/named_entities", locals: { named_entities: named_entities, linked_entities: named_entities_labels } + end - ## - # Retrieve and display paginated facets - def paginate_facets - out = {} - if params[:field_name] != "" - search_params = session['search_params'] - search_params['rows'] = 0 - search_params['json.facet'] = {"#{params[:field_name]}": {terms: { - field: params[:field_name], - limit: 15, - numBuckets: true, - offset: (params[:current_page].to_i-1) * 15}}}.to_json - res = SolrSearcher.query search_params - entities_labels = [res['facets'][params[:field_name]]['buckets'].map{|ne| ne['val']}] - entities_labels = helpers.get_entity_label entities_labels - facet_constraints = search_params['fq'].select { |fq| fq.split(':')[0] == params[:field_name] }.map{|fq| {label: params[:field_name], value: fq.split(':')[1]} } - out[:facets_entries] = [] - res['facets'][params[:field_name]]['buckets'].each do |facet_entry| - out[:facets_entries] << render_to_string(layout: false, partial: "facet_entry", locals: { - entities_labels: entities_labels, - facet_constraints: facet_constraints, - field: params[:field_name], - facet: facet_entry, - index: params[:current_page].to_i, - per_page: 15 - }) - end - end - out[:pagination] = render_to_string(layout: false, partial: 'facet_pagination', locals: {nb_pages: params[:nb_pages].to_i, current_page: params[:current_page].to_i}) - render json: out + ## + # Retrieve and display paginated facets + def paginate_facets + out = {} + if params[:field_name] != "" + search_params = session["search_params"] + search_params["rows"] = 0 + search_params["json.facet"] = { "#{params[:field_name]}": { terms: { + field: params[:field_name], + limit: 15, + numBuckets: true, + offset: (params[:current_page].to_i - 1) * 15, + } } }.to_json + res = SolrSearcher.query search_params + entities_labels = [res["facets"][params[:field_name]]["buckets"].map { |ne| ne["val"] }] + entities_labels = helpers.get_entity_label entities_labels + facet_constraints = search_params["fq"].select { |fq| fq.split(":")[0] == params[:field_name] }.map { |fq| { label: params[:field_name], value: fq.split(":")[1] } } + out[:facets_entries] = [] + res["facets"][params[:field_name]]["buckets"].each do |facet_entry| + out[:facets_entries] << render_to_string(layout: false, partial: "facet_entry", locals: { + entities_labels: entities_labels, + facet_constraints: facet_constraints, + field: params[:field_name], + facet: facet_entry, + index: params[:current_page].to_i, + per_page: 15, + }) + end end + out[:pagination] = render_to_string(layout: false, partial: "facet_pagination", locals: { nb_pages: params[:nb_pages].to_i, current_page: params[:current_page].to_i }) + render json: out + end - ## - # Open modal for date frequencies histogram in wide format - def wide_dates_histogram - out = {} - out[:modal_content] = render_to_string(layout: false, partial: "wide_dates_histogram") - render json: out - end + ## + # Open modal for date frequencies histogram in wide format + def wide_dates_histogram + out = {} + out[:modal_content] = render_to_string(layout: false, partial: "wide_dates_histogram") + render json: out + end - ## - # Open Modal to confirm the creation of a compound article - def confirm_compound_creation - out = {} - out[:modal_content] = render_to_string(layout: false, partial: "confirm_compound_creation", locals: {article_parts: params[:article_parts]}) - render json: out - end + ## + # Open Modal to confirm the creation of a compound article + def confirm_compound_creation + out = {} + out[:modal_content] = render_to_string(layout: false, partial: "confirm_compound_creation", locals: { article_parts: params[:article_parts] }) + render json: out + end - ## - # Create a new compound article - def create_compound - compound = CompoundArticle.new - compound.user = current_user - compound.title = params[:title] - compound.issue_id = params[:issue_id] - issue = Issue.from_solr params[:issue_id] - compound.newspaper = issue.newspaper - compound.date_created = issue.date_created - compound.thumbnail_url = issue.thumbnail_url - compound.language = issue.language - compound.all_text = params[:all_text] - compound.parts = params[:article_parts_ids] - begin - compound.save! - render json: {status: 'ok', html: render_to_string(layout: false, partial: "compound_articles_panel", locals: {issue_id: params[:issue_id]})} - rescue ActiveRecord::RecordNotUnique - render json: {status: "error", message: "A compound article with this title already exists."} - rescue ActiveRecord::RecordInvalid - render json: {status: "error", message: "The title should not be blank."} - end + ## + # Create a new compound article + def create_compound + compound = CompoundArticle.new + compound.user = current_user + compound.title = params[:title] + compound.issue_id = params[:issue_id] + issue = Issue.from_solr params[:issue_id] + compound.newspaper = issue.newspaper + compound.date_created = issue.date_created + compound.thumbnail_url = issue.thumbnail_url + compound.language = issue.language + compound.all_text = params[:all_text] + compound.parts = params[:article_parts_ids] + begin + compound.save! + render json: { status: "ok", html: render_to_string(layout: false, partial: "compound_articles_panel", locals: { issue_id: params[:issue_id] }) } + rescue ActiveRecord::RecordNotUnique + render json: { status: "error", message: "A compound article with this title already exists." } + rescue ActiveRecord::RecordInvalid + render json: { status: "error", message: "The title should not be blank." } end + end - ## - # Delete an existing compound - def delete_compound - compound = CompoundArticle.find(params[:compound_id]) - issue_id = compound.issue_id - current_user.datasets.each do |dataset| - if dataset.documents.any?{|doc| doc['id'].to_s == compound.id.to_s} - dataset.documents = dataset.documents.select{|doc| doc['id'].to_s != compound.id.to_s} - dataset.save! - end - end - compound.destroy - out = {} - out[:html] = render_to_string(layout: false, partial: "compound_articles_panel", locals: {issue_id: issue_id}) - out[:datasets] = render_to_string(layout: false, partial: "manage_datasets_content_show_page") - render json: out + ## + # Delete an existing compound + def delete_compound + compound = CompoundArticle.find(params[:compound_id]) + issue_id = compound.issue_id + current_user.datasets.each do |dataset| + if dataset.documents.any? { |doc| doc["id"].to_s == compound.id.to_s } + dataset.documents = dataset.documents.select { |doc| doc["id"].to_s != compound.id.to_s } + dataset.save! + end end + compound.destroy + out = {} + out[:html] = render_to_string(layout: false, partial: "compound_articles_panel", locals: { issue_id: issue_id }) + out[:datasets] = render_to_string(layout: false, partial: "manage_datasets_content_show_page") + render json: out + end - ## - # Retrieve and display a random sample of the result of a search - def random_sample - search_params = session['search_params'].with_indifferent_access - search_params[:fq] = search_params[:fq].select {|elt| !elt.start_with? "has_model_ssim:" } if search_params[:fq] - search_params[:fq] ||= [] - search_params[:fq] << "has_model_ssim:Article" - search_params[:sort] = "rand#{(0...8).map { (65 + rand(26)).chr }.join} asc" - results = SolrSearcher.query search_params - results = results['response']['docs'].map do |solr_doc| - case solr_doc['has_model_ssim'] - when ['Article'] - Article.from_solr_doc solr_doc - when ['Issue'] - Issue.from_solr_doc solr_doc - end - end - render json: {content: render_to_string(layout: false, partial: "random_sample", locals: {resulting_docs: results}) } + ## + # Retrieve and display a random sample of the result of a search + def random_sample + search_params = session["search_params"].with_indifferent_access + search_params[:fq] = search_params[:fq].select { |elt| !elt.start_with? "has_model_ssim:" } if search_params[:fq] + search_params[:fq] ||= [] + search_params[:fq] << "has_model_ssim:Article" + search_params[:sort] = "rand#{(0...8).map { (65 + rand(26)).chr }.join} asc" + results = SolrSearcher.query search_params + results = results["response"]["docs"].map do |solr_doc| + case solr_doc["has_model_ssim"] + when ["Article"] + Article.from_solr_doc solr_doc + when ["Issue"] + Issue.from_solr_doc solr_doc + end end + render json: { content: render_to_string(layout: false, partial: "random_sample", locals: { resulting_docs: results }) } + end - private + private - def strip_input_fields - params.each do |key, value| - params[key] = value.strip if value.respond_to?("strip") - end + def strip_input_fields + params.each do |key, value| + params[key] = value.strip if value.respond_to?("strip") end + end end diff --git a/app/controllers/dataset_controller.rb b/app/controllers/dataset_controller.rb index e04f4b4e1265ad806aea318f755e5a70647f3a1f..ca0fbbceabd839850ae16861d9d0255ab0f08246 100644 --- a/app/controllers/dataset_controller.rb +++ b/app/controllers/dataset_controller.rb @@ -1,194 +1,203 @@ class DatasetController < ApplicationController - - before_action :authenticate_user! - - ## - # List all datasets - def index - end - - ## - # Display a single dataset - def show - @dataset = Dataset.find(params[:id]) - @current_page = params[:page] || 1 - @per_page = params[:per_page] || 10 - session[:working_dataset] = @dataset.id - end - - ## - # Create a new empty dataset - def create_dataset - dataset = Dataset.new - dataset.user = current_user - dataset.title = params[:title] - begin - dataset.save! - render json: {status: 'ok'} - rescue ActiveRecord::RecordNotUnique - render json: {status: "error", message: "A dataset with this title already exists."} - rescue ActiveRecord::RecordInvalid - render json: {status: "error", message: "The title should not be blank."} - end - end - - ## - # Rename an existing dataset - def rename_dataset - dataset = Dataset.find(params[:id]) - dataset.title = params[:title] + before_action :authenticate_user! + + ## + # List all datasets + def index + puts "Listing datasets" + puts session.inspect + end + + ## + # Display a single dataset + def show + puts "Finding dataset with id " + String(params[:id]) + @dataset = Dataset.find(params[:id]) + @current_page = params[:page] || 1 + @per_page = params[:per_page] || 10 + session[:working_dataset] = @dataset.id + puts "The session now has working_dataset " + String(session[:working_dataset]) + end + + ## + # Create a new empty dataset + def create_dataset + dataset = Dataset.new + dataset.user = current_user + dataset.title = params[:title] + begin + dataset.save! + render json: { status: "ok" } + rescue ActiveRecord::RecordNotUnique + render json: { status: "error", message: "A dataset with this title already exists." } + rescue ActiveRecord::RecordInvalid + render json: { status: "error", message: "The title should not be blank." } + end + end + + ## + # Rename an existing dataset + def rename_dataset + dataset = Dataset.find(params[:id]) + dataset.title = params[:title] + begin + dataset.save! + render json: { status: "ok" } + rescue ActiveRecord::RecordNotUnique + render json: { status: "error", message: "A dataset with this title already exists." } + rescue ActiveRecord::RecordInvalid + render json: { status: "error", message: "The title should not be blank." } + end + end + + ## + # Import a public dataset + def import_dataset + to_copy = Dataset.find params[:original_dataset_id] + render json: { status: "error", message: "This dataset is not public." } unless to_copy.public? + new_dataset = Dataset.new + new_dataset.user_id = current_user.id + new_dataset.title = params[:title] + to_copy.documents.each do |doc| + if doc["type"] == "compound" + ca = CompoundArticle.find(doc["id"]).dup + ca.user = current_user begin - dataset.save! - render json: {status: 'ok'} + ca.save! rescue ActiveRecord::RecordNotUnique - render json: {status: "error", message: "A dataset with this title already exists."} - rescue ActiveRecord::RecordInvalid - render json: {status: "error", message: "The title should not be blank."} + ca.title = "_#{(0...8).map { (65 + rand(26)).chr }.join}_#{ca.title}" + ca.save! end - end - - ## - # Import a public dataset - def import_dataset - to_copy = Dataset.find params[:original_dataset_id] - render json: {status: "error", message: "This dataset is not public."} unless to_copy.public? - new_dataset = Dataset.new - new_dataset.user_id = current_user.id - new_dataset.title = params[:title] - to_copy.documents.each do |doc| - if doc['type'] == "compound" - ca = CompoundArticle.find(doc['id']).dup - ca.user = current_user - begin - ca.save! - rescue ActiveRecord::RecordNotUnique - ca.title = "_#{(0...8).map { (65 + rand(26)).chr }.join}_#{ca.title}" - ca.save! - end - new_dataset.documents << {id: ca.id, type: "compound"} - else - new_dataset.documents << doc - end - end - begin - new_dataset.save! - render json: {status: 'ok'} - rescue ActiveRecord::RecordNotUnique - render json: {status: "error", message: "A dataset with this title already exists."} - rescue ActiveRecord::RecordInvalid - render json: {status: "error", message: "The title should not be blank."} - end - end - - ## - # Delete an existing dataset - def delete_dataset - dataset = Dataset.find(params[:dataset_id]) - dataset_id = dataset.id - dataset.destroy - if session[:working_dataset] == dataset_id - if current_user.datasets.first - session[:working_dataset] = current_user.datasets.first.id - else - session[:working_dataset] = nil - end - end - end - - ## - # Update the view of the list of datasets - def update_datasets_list - respond_to do |format| - format.js - end - end - - ## - # - def set_working_dataset - session[:working_dataset] = params[:dataset_id] - @title = Dataset.find(session[:working_dataset]).title - respond_to do |format| - format.js - end - end - - def add_selected_documents - out = {} - @nb_added_docs = params[:documents_ids].size - dataset = Dataset.find(session[:working_dataset]) - existing = dataset.add_documents params[:documents_ids] # Add docs and return existing ids - @nb_added_docs -= existing.size - title = dataset.title - message = "
#{@nb_added_docs} document#{@nb_added_docs > 1 ? "s were" : " was"} added to your dataset.
" - message.concat "#{existing.size} document#{existing.size > 1 ? "s" : ""} already exist in this dataset.
" unless existing.empty? - # render partial: "shared/notification", locals: {notif_title: title, notif_content: message.html_safe} - out['notif'] = render_to_string layout: false, partial: "shared/notification", locals: {notif_title: title, notif_content: message.html_safe} - out['nbissues'] = dataset.documents.select{|d| d['type'] == "issue" }.size - out['nbarticles'] = dataset.documents.select{|d| d['type'] == "article" }.size - out['nbdocs'] = out['nbissues'] + out['nbarticles'] - out['title'] = title - out['results_datasets'] = params[:documents_ids].map{ |docid| [docid, render_to_string(layout: false, partial: 'catalog/result_datasets', locals: {doc_id: docid})] }.to_h - render json: out - end - - def add_compound - out = {} - dataset = Dataset.find(session[:working_dataset]) - existing = dataset.add_compound params[:compound_id] # Add docs and return existing ids - title = dataset.title - message = "The compound article was added to your dataset.
" - out['notif'] = render_to_string layout: false, partial: "shared/notification", locals: {notif_title: title, notif_content: message.html_safe} - out['nbissues'] = dataset.documents.select{|d| d['type'] == "issue" }.size - out['nbarticles'] = dataset.documents.select{|d| d['type'] == "article" }.size - out['nbcompounds'] = dataset.documents.select{|d| d['type'] == "compound" }.size - out['nbdocs'] = out['nbissues'] + out['nbarticles'] + out['nbcompounds'] - out['title'] = title - render json: out - end - - def remove_selected_documents - @nb_removed_docs = params[:documents_ids].size - dataset = Dataset.find(session[:working_dataset]) - dataset.remove_documents params[:documents_ids] - redirect_to action: "show", id: dataset.id - end - - def add_all_documents - SearchToDatasetWorker.perform_async(current_user.id, session[:working_dataset], params[:search_params].to_unsafe_h) - title = Dataset.find(session[:working_dataset]).title - message = "Documents are being added to your dataset. You will be notified when the operation is done.
" - render partial: "shared/notification", locals: {notif_title: title, notif_content: message.html_safe} - end - - def export_dataset - ExportDatasetWorker.perform_async(current_user.id, params[:dataset_id], params[:export_type]) - title = Dataset.find(params[:dataset_id]).title - message = "The export is being prepared. You will be notified when the operation is done.
" - render partial: "shared/notification", locals: {notif_title: title, notif_content: message.html_safe} - end - - def toggle_sharing_status - @dataset = Dataset.find(params[:dataset_id]) - @dataset.toggle!(:public) - render partial: 'dataset_info' - end - - def paginate - out = {} - d = Dataset.find params['id'] - rows = params[:per_page].to_i - res = d.fetch_paginated_documents(params[:page].to_i, rows, params[:sort], params[:sort_order], params[:type]) - out[:documents] = render_to_string(layout: false, - partial: "documents", - locals: {docs: res[:docs], rows: rows, pagenum: params[:page].to_i}) - out[:pagination] = render_to_string(layout: false, - partial: "pagination", - locals: {nb_pages: res[:nb_pages].to_i, current_page: params[:page].to_i}) - render json: out - end - - def list_datasets - render json: current_user.datasets.to_json - end + new_dataset.documents << { id: ca.id, type: "compound" } + else + new_dataset.documents << doc + end + end + begin + new_dataset.save! + render json: { status: "ok" } + rescue ActiveRecord::RecordNotUnique + render json: { status: "error", message: "A dataset with this title already exists." } + rescue ActiveRecord::RecordInvalid + render json: { status: "error", message: "The title should not be blank." } + end + end + + ## + # Delete an existing dataset + def delete_dataset + dataset = Dataset.find(params[:dataset_id]) + dataset_id = dataset.id + dataset.destroy + if session[:working_dataset] == dataset_id + if current_user.datasets.first + session[:working_dataset] = current_user.datasets.first.id + else + session[:working_dataset] = nil + end + end + end + + ## + # Update the view of the list of datasets + def update_datasets_list + respond_to do |format| + format.js + end + end + + ## + # + def set_working_dataset + session[:working_dataset] = params[:dataset_id] + @title = Dataset.find(session[:working_dataset]).title + puts "Setting working dataset to " + String(session[:working_dataset]) + puts session.inspect + respond_to do |format| + format.js + end + end + + def add_selected_documents + puts session.inspect + puts "User id from session is " + String(session[:current_user_id]) + " and working dataset is " + String(session[:working_dataset]) + out = {} + @nb_added_docs = params[:documents_ids].size + dataset = Dataset.find(session[:working_dataset]) + existing = dataset.add_documents params[:documents_ids] # Add docs and return existing ids + @nb_added_docs -= existing.size + title = dataset.title + message = "#{@nb_added_docs} document#{@nb_added_docs > 1 ? "s were" : " was"} added to your dataset.
" + message.concat "#{existing.size} document#{existing.size > 1 ? "s" : ""} already exist in this dataset.
" unless existing.empty? + # render partial: "shared/notification", locals: {notif_title: title, notif_content: message.html_safe} + out["notif"] = render_to_string layout: false, partial: "shared/notification", locals: { notif_title: title, notif_content: message.html_safe } + out["nbissues"] = dataset.documents.select { |d| d["type"] == "issue" }.size + out["nbarticles"] = dataset.documents.select { |d| d["type"] == "article" }.size + out["nbdocs"] = out["nbissues"] + out["nbarticles"] + out["title"] = title + out["results_datasets"] = params[:documents_ids].map { |docid| [docid, render_to_string(layout: false, partial: "catalog/result_datasets", locals: { doc_id: docid })] }.to_h + render json: out + end + + def add_compound + out = {} + dataset = Dataset.find(session[:working_dataset]) + # dataset = Dataset.find(params[:working_dataset]) + existing = dataset.add_compound params[:compound_id] # Add docs and return existing ids + title = dataset.title + message = "The compound article was added to your dataset.
" + out["notif"] = render_to_string layout: false, partial: "shared/notification", locals: { notif_title: title, notif_content: message.html_safe } + out["nbissues"] = dataset.documents.select { |d| d["type"] == "issue" }.size + out["nbarticles"] = dataset.documents.select { |d| d["type"] == "article" }.size + out["nbcompounds"] = dataset.documents.select { |d| d["type"] == "compound" }.size + out["nbdocs"] = out["nbissues"] + out["nbarticles"] + out["nbcompounds"] + out["title"] = title + render json: out + end + + def remove_selected_documents + @nb_removed_docs = params[:documents_ids].size + puts "Remove selected documents called, session has working dataset with id " + String(session[:working_dataset]) + dataset = Dataset.find(session[:working_dataset]) + dataset.remove_documents params[:documents_ids] + redirect_to action: "show", id: dataset.id + end + + def add_all_documents + SearchToDatasetWorker.perform_async(current_user.id, session[:working_dataset], params[:search_params].to_unsafe_h) + title = Dataset.find(session[:working_dataset]).title + message = "Documents are being added to your dataset. You will be notified when the operation is done.
" + render partial: "shared/notification", locals: { notif_title: title, notif_content: message.html_safe } + end + + def export_dataset + ExportDatasetWorker.perform_async(current_user.id, params[:dataset_id], params[:export_type]) + title = Dataset.find(params[:dataset_id]).title + message = "The export is being prepared. You will be notified when the operation is done.
" + render partial: "shared/notification", locals: { notif_title: title, notif_content: message.html_safe } + end + + def toggle_sharing_status + @dataset = Dataset.find(params[:dataset_id]) + @dataset.toggle!(:public) + render partial: "dataset_info" + end + + def paginate + out = {} + d = Dataset.find params["id"] + rows = params[:per_page].to_i + res = d.fetch_paginated_documents(params[:page].to_i, rows, params[:sort], params[:sort_order], params[:type]) + out[:documents] = render_to_string(layout: false, + partial: "documents", + locals: { docs: res[:docs], rows: rows, pagenum: params[:page].to_i }) + out[:pagination] = render_to_string(layout: false, + partial: "pagination", + locals: { nb_pages: res[:nb_pages].to_i, current_page: params[:page].to_i }) + render json: out + end + + def list_datasets + render json: current_user.datasets.to_json + end end diff --git a/app/controllers/experiment_controller.rb b/app/controllers/experiment_controller.rb index 5c89c48070c3dc380564f8752cb3399d970b4618..61d9bce3e41c0894c275c4b3bebd612b2fe9b1eb 100644 --- a/app/controllers/experiment_controller.rb +++ b/app/controllers/experiment_controller.rb @@ -1,118 +1,117 @@ class ExperimentController < ApplicationController + before_action :authenticate_user! - before_action :authenticate_user! + def index + end - def index + def create + experiment = Experiment.new + experiment.user = current_user + experiment.title = params[:title] + begin + experiment.save! + render json: { status: "ok" } + rescue ActiveRecord::RecordNotUnique + render json: { status: "error", message: "An experiment with this title already exists." } + rescue ActiveRecord::RecordInvalid + render json: { status: "error", message: "The title should not be blank." } end + end - def create - experiment = Experiment.new - experiment.user = current_user - experiment.title = params[:title] - begin - experiment.save! - render json: {status: 'ok'} - rescue ActiveRecord::RecordNotUnique - render json: {status: "error", message: "An experiment with this title already exists."} - rescue ActiveRecord::RecordInvalid - render json: {status: "error", message: "The title should not be blank."} - end + def delete + experiment = Experiment.find(params[:experiment_id]) + root_ids = experiment.description["children"].map { |root| root["tool"]["id"] } + root_ids.each do |root_id| + Tool.destroy(experiment.delete_tool(root_id)) end + experiment.destroy + end - def delete - experiment = Experiment.find(params[:experiment_id]) - root_ids = experiment.description["children"].map{|root| root['tool']['id'] } - root_ids.each do |root_id| - Tool.destroy(experiment.delete_tool(root_id)) - end - experiment.destroy - end - - def show - @experiment = Experiment.find params[:id] - @tools = @experiment.load_tools - @tools = JSON.parse(File.read("#{Rails.root}/lib/newspapers_tools.json")) - @tools['tools']['processors'].delete_if{ |h| h["type"] == "splitter" } - end + def show + @experiment = Experiment.find params[:id] + @tools = @experiment.load_tools + @tools = JSON.parse(File.read("#{Rails.root}/lib/newspapers_tools.json")) + @tools["tools"]["processors"].delete_if { |h| h["type"] == "splitter" } + end - def update_experiments_list - respond_to do |format| - format.js - end + def update_experiments_list + respond_to do |format| + format.js end + end - def add_tool - @experiment = Experiment.find(params[:id]) - tool_params = JSON.parse params[:tool] - tool = Tool.new - tool.tool_type = tool_params['type'] - tool.input_type = tool_params['input_type'] - tool.output_type = tool_params['output_type'] - tool.parameters = tool_params['parameters'] - tool.status = "created" - tool.parent_id = params[:parent_id]#(params[:parent_id] == "") ? nil : Tool.find(params[:parent_id]) - tool.experiment = @experiment - tool.save! - @experiment.add_tool(params[:parent_id].to_i, tool) - @experiment.save! - render 'experiment/update_experiment_area' - end + def add_tool + @experiment = Experiment.find(params[:id]) + tool_params = JSON.parse params[:tool] + tool = Tool.new + tool.tool_type = tool_params["type"] + tool.input_type = tool_params["input_type"] + tool.output_type = tool_params["output_type"] + tool.parameters = tool_params["parameters"] + tool.status = "created" + tool.parent_id = params[:parent_id] #(params[:parent_id] == "") ? nil : Tool.find(params[:parent_id]) + tool.experiment = @experiment + tool.save! + @experiment.add_tool(params[:parent_id].to_i, tool) + @experiment.save! + render "experiment/update_experiment_area" + end - def delete_tool - @experiment = Experiment.find(params[:id]) - tools_to_destroy_ids = @experiment.delete_tool(params[:tool_id].to_i) - @experiment.save! - Tool.destroy(tools_to_destroy_ids) - render 'experiment/update_experiment_area' - end + def delete_tool + @experiment = Experiment.find(params[:id]) + tools_to_destroy_ids = @experiment.delete_tool(params[:tool_id].to_i) + @experiment.save! + Tool.destroy(tools_to_destroy_ids) + render "experiment/update_experiment_area" + end - def edit_tool_form - @tool = Tool.find(params[:tool_id]) - render partial: 'tool/parameters', locals: {tool: @tool} - end + def edit_tool_form + @tool = Tool.find(params[:tool_id]) + render partial: "tool/parameters", locals: { tool: @tool } + end - def edit_tool - @experiment = Experiment.find(params[:id]) - @tool = Tool.find(params[:tool_id]) - modified = false - @tool.parameters.map! do |param| - if param['value'] != params[:parameters][param['name']] - modified = true - end - param['value'] = params[:parameters][param['name']] - param - end - @tool.status = "configured" if modified - @tool.save! - render 'experiment/update_experiment_area' + def edit_tool + @experiment = Experiment.find(params[:id]) + @tool = Tool.find(params[:tool_id]) + modified = false + @tool.parameters.map! do |param| + if param["value"] != params[:parameters][param["name"]] + modified = true + end + param["value"] = params[:parameters][param["name"]] + param end + @tool.status = "configured" if modified + @tool.save! + render "experiment/update_experiment_area" + end - def tool_results - @experiment = Experiment.find(params[:id]) - @tool = Tool.find(params[:tool_id]) - render partial: 'tool/results', locals: {tool: @tool, experiment: @experiment} - end + def tool_results + @experiment = Experiment.find(params[:id]) + @tool = Tool.find(params[:tool_id]) + render partial: "tool/results", locals: { tool: @tool, experiment: @experiment } + end - def run_tool - @experiment = Experiment.find(params[:id]) - @tool = Tool.find(params[:tool_id]) - @tool.run() - render 'experiment/update_experiment_area' - end + def run_tool + @experiment = Experiment.find(params[:id]) + @tool = Tool.find(params[:tool_id]) + @tool.run() + render "experiment/update_experiment_area" + end - def run_experiment - out = {} - @experiment = Experiment.find(params[:experiment_id]) - ids = @experiment.get_tool_ids - running = false - ids.map{|id| Tool.find(id)}.each do |tool| - if tool.runnable? - tool.run(true) - running = true - end - end - out[:html_tree] = render_to_string partial: "tree", locals: {experiment: @experiment} - out[:experiment_running] = running - render json: out + def run_experiment + out = {} + @experiment = Experiment.find(params[:experiment_id]) + ids = @experiment.get_tool_ids + running = false + ids.map { |id| Tool.find(id) }.each do |tool| + if tool.runnable? + tool.run(true) + running = true + end end + out[:html_tree] = render_to_string partial: "tree", locals: { experiment: @experiment } + out[:experiment_running] = running + render json: out + end end diff --git a/app/controllers/notification_controller.rb b/app/controllers/notification_controller.rb index 53306f026c34a52b604737965d3f45069ccf4ab3..43e7a448386440766ba963f829149080605773cf 100644 --- a/app/controllers/notification_controller.rb +++ b/app/controllers/notification_controller.rb @@ -1,3 +1,3 @@ class NotificationController < ApplicationController - -end \ No newline at end of file + before_action :authenticate_user! +end diff --git a/app/controllers/tool_controller.rb b/app/controllers/tool_controller.rb index d9fbf32fe8fd70f9fdd4e0191763b1bc5e9a62ff..2e047a96589e49ddef709a411faa2b229222ecab 100644 --- a/app/controllers/tool_controller.rb +++ b/app/controllers/tool_controller.rb @@ -1,26 +1,21 @@ class ToolController < ApplicationController + before_action :authenticate_user! - before_action :authenticate_user! + def show + end - def show + def create + end - end + def update + end - def create + def destroy + end - end + private - def update - - end - - def destroy - - end - - private - - def tool_params - params.require(:tool).permit(:parameters, :results, :status) - end + def tool_params + params.require(:tool).permit(:parameters, :results, :status) + end end diff --git a/app/helpers/application_helper.rb b/app/helpers/application_helper.rb index a69ed066bcadd2cfc54e470d06f04d076e83561c..15f2511626a73c1182080ec88be05629588196fc 100644 --- a/app/helpers/application_helper.rb +++ b/app/helpers/application_helper.rb @@ -1,7 +1,5 @@ module ApplicationHelper - - def set_page_title(title) - content_for :page_title, title - end - + def set_page_title(title) + content_for :page_title, title + end end diff --git a/app/helpers/experiment_helper.rb b/app/helpers/experiment_helper.rb index f03f142c96df04bd436fb1db1f7329e956f801bd..9bc2e4cf8fe718cfc7a8567a48f6f3bba357c6e5 100644 --- a/app/helpers/experiment_helper.rb +++ b/app/helpers/experiment_helper.rb @@ -1,17 +1,15 @@ module ExperimentHelper - - def recursive_display(tree, tools) - if tree.has_key? "tool" - concat "Your dataset is ready. Click here to download it.
" - ActionCable.server.broadcast("notifications.#{user_id}", { - type: "notify", - html: ApplicationController.render(partial: "shared/notification", locals: {notif_title: dataset.title, notif_content: content}) - }) + to_write << filename + end end - - def under_copyright(lang, date, user) - nlf_doc = ["fi", "se"].include? lang - nlf_under_copyright = Date.parse("1910-12-31T00:00:00Z") <= Date.parse(date) - nlf_doc and nlf_under_copyright and !user.groups.include? "researcher" + case export_type + when "json" + to_write = { "documents": to_write } + file.write to_write.to_json + file.close + when "zip" + Zip::File.open(file.path, Zip::File::CREATE) do |zipfile| + to_write.each do |filename| + zipfile.add filename, "/tmp/#{filename}" if filename + end + end + to_write.each do |filename| + File.delete("/tmp/#{filename}") if filename + end end -end \ No newline at end of file + content = "Your dataset is ready. Click here to download it.
" + ActionCable.server.broadcast("notifications.#{user_id}", { + type: "notify", + html: ApplicationController.render(partial: "shared/notification", locals: { notif_title: dataset.title, notif_content: content }), + }) + end + + def under_copyright(lang, date, user) + nlf_doc = ["fi", "se"].include? lang + nlf_under_copyright = Date.parse("1910-12-31T00:00:00Z") <= Date.parse(date) + nlf_doc and nlf_under_copyright and !user.groups.include? "researcher" + end +end diff --git a/app/workers/ngrams_worker.rb b/app/workers/ngrams_worker.rb index bc3dbee5e62d2c340b8312b6ef406d7f296d1884..348268e27553cd960d76f339e31dc08a866845a8 100644 --- a/app/workers/ngrams_worker.rb +++ b/app/workers/ngrams_worker.rb @@ -1,58 +1,59 @@ class NgramsWorker - include Sidekiq::Worker + include Sidekiq::Worker - def perform(tool_id, user_id, experiment_id, tool_type, tool_parameters, continue=false) - tool = Tool.find(tool_id) - tool.status = "running" - tool.save! - ActionCable.server.broadcast("notifications.#{user_id}", { - type: "refresh_display", - html: ApplicationController.render(partial: "experiment/tree", locals: {experiment: Experiment.find(tool.experiment.id)}), - message: 'Starting job...' }) - parent_output = Tool.find(tool.parent_id).results - docs = parent_output["docs"].map{ |doc| doc['text'] } - n = tool_parameters.select{|t| t['name'] == 'n'}[0]['value'].to_i - min_freq = tool_parameters.select{|t| t['name'] == 'minimum_frequency'}[0]['value'].to_i - ngrams = find_ngrams(tool_id, experiment_id, user_id, docs, n, min_freq) - tool.results = {type:"ngrams", ngrams: ngrams} - tool.status = "finished" - tool.save! - experiment = Experiment.find(tool.experiment.id) - out = { - type: "refresh_display", - html: ApplicationController.render(partial: "experiment/tree", locals: {experiment: experiment}), - message: 'Done.' - } - ActionCable.server.broadcast("notifications.#{user_id}", out) - if continue - experiment.continue_from(tool_id) - end - if experiment.finished? - out = { - type: "experiment_finished", - message: 'Experiment has finished running.' - } - ActionCable.server.broadcast("notifications.#{user_id}", out) - end + def perform(tool_id, user_id, experiment_id, tool_type, tool_parameters, continue = false) + tool = Tool.find(tool_id) + tool.status = "running" + tool.save! + ActionCable.server.broadcast("notifications.#{user_id}", { + type: "refresh_display", + html: ApplicationController.render(partial: "experiment/tree", locals: { experiment: Experiment.find(tool.experiment.id) }), + message: "Starting job...", + }) + parent_output = Tool.find(tool.parent_id).results + docs = parent_output["docs"].map { |doc| doc["text"] } + n = tool_parameters.select { |t| t["name"] == "n" }[0]["value"].to_i + min_freq = tool_parameters.select { |t| t["name"] == "minimum_frequency" }[0]["value"].to_i + ngrams = find_ngrams(tool_id, experiment_id, user_id, docs, n, min_freq) + tool.results = { type: "ngrams", ngrams: ngrams } + tool.status = "finished" + tool.save! + experiment = Experiment.find(tool.experiment.id) + out = { + type: "refresh_display", + html: ApplicationController.render(partial: "experiment/tree", locals: { experiment: experiment }), + message: "Done.", + } + ActionCable.server.broadcast("notifications.#{user_id}", out) + if continue + experiment.continue_from(tool_id) end + if experiment.finished? + out = { + type: "experiment_finished", + message: "Experiment has finished running.", + } + ActionCable.server.broadcast("notifications.#{user_id}", out) + end + end - def find_ngrams(tool_id, experiment_id, user_id, documents, n, minimum_frequency) - total = {} - documents.each_with_index do |document, idx| - out = { - type: "completion_rate", - tool_id: tool_id, - experiment_id: experiment_id, - completion: ((idx/(documents.size).to_f)*100).to_i - } - ActionCable.server.broadcast("notifications.#{user_id}", out) if idx%20 == 0 - ngrams = document.split.each_cons(n).to_a - ngrams.reject! { |w1, w2| w1 !~ /^\w+/ || w2 !~ /^\w+/ } - ngrams.map!{ |ngram| ngram.join(' ') } - total.merge!( ngrams.each_with_object(Hash.new(0)) do |word, obj| - obj[word.downcase] += 1 - end) - end - total.sort_by { |k, v| -v }.reject { |k, v| v < minimum_frequency } + def find_ngrams(tool_id, experiment_id, user_id, documents, n, minimum_frequency) + total = {} + documents.each_with_index do |document, idx| + out = { + type: "completion_rate", + tool_id: tool_id, + experiment_id: experiment_id, + completion: ((idx / (documents.size).to_f) * 100).to_i, + } + ActionCable.server.broadcast("notifications.#{user_id}", out) if idx % 20 == 0 + ngrams = document.split.each_cons(n).to_a + ngrams.reject! { |w1, w2| w1 !~ /^\w+/ || w2 !~ /^\w+/ } + ngrams.map! { |ngram| ngram.join(" ") } + total.merge!(ngrams.each_with_object(Hash.new(0)) do |word, obj| + obj[word.downcase] += 1 + end) end + total.sort_by { |k, v| -v }.reject { |k, v| v < minimum_frequency } + end end diff --git a/app/workers/preprocess_worker.rb b/app/workers/preprocess_worker.rb index f63433446efbb110e91fd48326d281096e6a1fc9..ee740c17a00ec0be6f1b75c341f0e3b9f7732082 100644 --- a/app/workers/preprocess_worker.rb +++ b/app/workers/preprocess_worker.rb @@ -1,55 +1,56 @@ class PreprocessWorker - include Sidekiq::Worker + include Sidekiq::Worker - def perform(tool_id, user_id, experiment_id, tool_type, tool_parameters, continue=false) - tool = Tool.find(tool_id) - tool.status = "running" - tool.save! - ActionCable.server.broadcast("notifications.#{user_id}", { - type: "refresh_display", - html: ApplicationController.render(partial: "experiment/tree", locals: {experiment: Experiment.find(tool.experiment.id)}), - message: 'Starting job...' }) - parent_output = Tool.find(tool.parent_id).results - docs = parent_output["docs"] - docs = docs.each_with_index.map do |doc, idx| - out = { - type: "completion_rate", - tool_id: tool.id, - experiment_id: experiment_id, - completion: ((idx/(docs.size).to_f)*100).to_i - } - ActionCable.server.broadcast("notifications.#{user_id}", out) if idx%20 == 0 + def perform(tool_id, user_id, experiment_id, tool_type, tool_parameters, continue = false) + tool = Tool.find(tool_id) + tool.status = "running" + tool.save! + ActionCable.server.broadcast("notifications.#{user_id}", { + type: "refresh_display", + html: ApplicationController.render(partial: "experiment/tree", locals: { experiment: Experiment.find(tool.experiment.id) }), + message: "Starting job...", + }) + parent_output = Tool.find(tool.parent_id).results + docs = parent_output["docs"] + docs = docs.each_with_index.map do |doc, idx| + out = { + type: "completion_rate", + tool_id: tool.id, + experiment_id: experiment_id, + completion: ((idx / (docs.size).to_f) * 100).to_i, + } + ActionCable.server.broadcast("notifications.#{user_id}", out) if idx % 20 == 0 - doc['text'] = PragmaticTokenizer::Tokenizer.new( - language: doc['language'], - remove_stop_words: tool_parameters.select{|t| t['name'] == 'stopwords'}[0]['value'], - punctuation: tool_parameters.select{|t| t['name'] == 'punctuation'}[0]['value'] ? "none" : "all", - numbers: tool_parameters.select{|t| t['name'] == 'lowercase'}[0]['value'] ? "none" : "all", - clean: true, - downcase: tool_parameters.select{|t| t['name'] == 'lowercase'}[0]['value'], - minimum_length: 3 - ).tokenize(doc['text']).join(' ') - doc - end - tool.results = {type:"documents", docs: docs} - tool.status = "finished" - tool.save! - experiment = Experiment.find(tool.experiment.id) - out = { - type: "refresh_display", - html: ApplicationController.render(partial: "experiment/tree", locals: {experiment: experiment}), - message: 'Done.' - } - ActionCable.server.broadcast("notifications.#{user_id}", out) - if continue - experiment.continue_from(tool_id) - end - if experiment.finished? - out = { - type: "experiment_finished", - message: 'Experiment has finished running.' - } - ActionCable.server.broadcast("notifications.#{user_id}", out) - end + doc["text"] = PragmaticTokenizer::Tokenizer.new( + language: doc["language"], + remove_stop_words: tool_parameters.select { |t| t["name"] == "stopwords" }[0]["value"], + punctuation: tool_parameters.select { |t| t["name"] == "punctuation" }[0]["value"] ? "none" : "all", + numbers: tool_parameters.select { |t| t["name"] == "lowercase" }[0]["value"] ? "none" : "all", + clean: true, + downcase: tool_parameters.select { |t| t["name"] == "lowercase" }[0]["value"], + minimum_length: 3, + ).tokenize(doc["text"]).join(" ") + doc end + tool.results = { type: "documents", docs: docs } + tool.status = "finished" + tool.save! + experiment = Experiment.find(tool.experiment.id) + out = { + type: "refresh_display", + html: ApplicationController.render(partial: "experiment/tree", locals: { experiment: experiment }), + message: "Done.", + } + ActionCable.server.broadcast("notifications.#{user_id}", out) + if continue + experiment.continue_from(tool_id) + end + if experiment.finished? + out = { + type: "experiment_finished", + message: "Experiment has finished running.", + } + ActionCable.server.broadcast("notifications.#{user_id}", out) + end + end end diff --git a/app/workers/search_to_dataset_worker.rb b/app/workers/search_to_dataset_worker.rb index ce1da67b2b33c9c5ec362162eea31d6687e622e8..231529423a761d68d8681ab4de63fc1c32fdf028 100644 --- a/app/workers/search_to_dataset_worker.rb +++ b/app/workers/search_to_dataset_worker.rb @@ -1,34 +1,34 @@ class SearchToDatasetWorker - include Sidekiq::Worker - include ActionView::Helpers::FormOptionsHelper + include Sidekiq::Worker + include ActionView::Helpers::FormOptionsHelper - def perform(user_id, dataset_id, search_params) - puts "### #{search_params}" - dataset = Dataset.find(dataset_id) - search_params['fl'] = 'id' - search_params['facet'] = false - search_params['rows'] = 100 - search_params['start'] = 0 - doc_ids = [] - res = SolrSearcher.query search_params - numFound = res['response']['numFound'] - doc_ids.concat res['response']['docs'].map{|d| d['id']} - while(doc_ids.size < numFound) - search_params['start'] += 100 - res = SolrSearcher.query search_params - numFound = res['response']['numFound'] - doc_ids.concat res['response']['docs'].map{|d| d['id']} - end - existing = dataset.add_documents doc_ids - nb_docs_added = doc_ids.size - existing.size - content = "#{nb_docs_added} document#{nb_docs_added > 1 ? "s were" : " was"} added to your dataset \"#{dataset.title}\"
" - content.concat "#{existing.size} document#{existing.size > 1 ? "s" : ""} already exist in this dataset.
" unless existing.empty? - # TODO: next line may cause bugs with the working dataset - dataset_options = options_for_select(User.find(user_id).datasets.map{|d| ["#{d.title} (#{d.documents.size} docs)", d.id]}) - ActionCable.server.broadcast("notifications.#{user_id}", { - type: "notify", - html: ApplicationController.render(partial: "shared/notification", locals: {notif_title: dataset.title, notif_content: content}), - dataset_options: dataset_options }) + def perform(user_id, dataset_id, search_params) + puts "### #{search_params}" + dataset = Dataset.find(dataset_id) + search_params["fl"] = "id" + search_params["facet"] = false + search_params["rows"] = 100 + search_params["start"] = 0 + doc_ids = [] + res = SolrSearcher.query search_params + numFound = res["response"]["numFound"] + doc_ids.concat res["response"]["docs"].map { |d| d["id"] } + while (doc_ids.size < numFound) + search_params["start"] += 100 + res = SolrSearcher.query search_params + numFound = res["response"]["numFound"] + doc_ids.concat res["response"]["docs"].map { |d| d["id"] } end - -end \ No newline at end of file + existing = dataset.add_documents doc_ids + nb_docs_added = doc_ids.size - existing.size + content = "#{nb_docs_added} document#{nb_docs_added > 1 ? "s were" : " was"} added to your dataset \"#{dataset.title}\"
" + content.concat "#{existing.size} document#{existing.size > 1 ? "s" : ""} already exist in this dataset.
" unless existing.empty? + # TODO: next line may cause bugs with the working dataset + dataset_options = options_for_select(User.find(user_id).datasets.map { |d| ["#{d.title} (#{d.documents.size} docs)", d.id] }) + ActionCable.server.broadcast("notifications.#{user_id}", { + type: "notify", + html: ApplicationController.render(partial: "shared/notification", locals: { notif_title: dataset.title, notif_content: content }), + dataset_options: dataset_options, + }) + end +end diff --git a/app/workers/source_dataset_worker.rb b/app/workers/source_dataset_worker.rb index bda0ec497511d3a0e16544d3971cbd98e5f996f2..d303b8f9477a826953c3abcbd381fc29a7d7ed35 100644 --- a/app/workers/source_dataset_worker.rb +++ b/app/workers/source_dataset_worker.rb @@ -1,62 +1,63 @@ class SourceDatasetWorker - include Sidekiq::Worker + include Sidekiq::Worker - def perform(tool_id, user_id, experiment_id, tool_type, tool_parameters, continue=false) - tool = Tool.find(tool_id) - tool.status = "running" - tool.save! - ActionCable.server.broadcast("notifications.#{user_id}", { - type: "refresh_display", - html: ApplicationController.render(partial: "experiment/tree", locals: {experiment: Experiment.find(tool.experiment.id)}), - message: 'Starting job...' }) - docs = fetch_docs_from_dataset(tool_id, experiment_id, user_id, tool_parameters.select{|t| t['name'] == 'dataset'}[0]['value']) - tool.results = {type:"documents", docs: docs} - tool.status = "finished" - tool.save! - experiment = Experiment.find(tool.experiment.id) - out = { - type: "refresh_display", - html: ApplicationController.render(partial: "experiment/tree", locals: {experiment: experiment}), - message: 'Done.' - } - ActionCable.server.broadcast("notifications.#{user_id}", out) - if continue - experiment.continue_from(tool_id) - end - if experiment.finished? - out = { - type: "experiment_finished", - message: 'Experiment has finished running.' - } - ActionCable.server.broadcast("notifications.#{user_id}", out) - end + def perform(tool_id, user_id, experiment_id, tool_type, tool_parameters, continue = false) + tool = Tool.find(tool_id) + tool.status = "running" + tool.save! + ActionCable.server.broadcast("notifications.#{user_id}", { + type: "refresh_display", + html: ApplicationController.render(partial: "experiment/tree", locals: { experiment: Experiment.find(tool.experiment.id) }), + message: "Starting job...", + }) + docs = fetch_docs_from_dataset(tool_id, experiment_id, user_id, tool_parameters.select { |t| t["name"] == "dataset" }[0]["value"]) + tool.results = { type: "documents", docs: docs } + tool.status = "finished" + tool.save! + experiment = Experiment.find(tool.experiment.id) + out = { + type: "refresh_display", + html: ApplicationController.render(partial: "experiment/tree", locals: { experiment: experiment }), + message: "Done.", + } + ActionCable.server.broadcast("notifications.#{user_id}", out) + if continue + experiment.continue_from(tool_id) + end + if experiment.finished? + out = { + type: "experiment_finished", + message: "Experiment has finished running.", + } + ActionCable.server.broadcast("notifications.#{user_id}", out) end + end - def fetch_docs_from_dataset(tool_id, experiment_id, user_id, dataset_id) - d = Dataset.find(dataset_id) - all_docs = [] - docs = [] - page = 0 - while page == 0 or docs.size == 100 - page += 1 - docs = d.fetch_paginated_documents(page, 100, "default", "asc", "all")[:docs] - all_docs.concat docs - out = { - type: "completion_rate", - tool_id: tool_id, - experiment_id: experiment_id, - completion: d.documents.size == 0 ? 0 : ((all_docs.size.to_f/d.documents.size)*100).to_i - } - ActionCable.server.broadcast("notifications.#{user_id}", out) - end - all_docs.map do |doc| - { + def fetch_docs_from_dataset(tool_id, experiment_id, user_id, dataset_id) + d = Dataset.find(dataset_id) + all_docs = [] + docs = [] + page = 0 + while page == 0 or docs.size == 100 + page += 1 + docs = d.fetch_paginated_documents(page, 100, "default", "asc", "all")[:docs] + all_docs.concat docs + out = { + type: "completion_rate", + tool_id: tool_id, + experiment_id: experiment_id, + completion: d.documents.size == 0 ? 0 : ((all_docs.size.to_f / d.documents.size) * 100).to_i, + } + ActionCable.server.broadcast("notifications.#{user_id}", out) + end + all_docs.map do |doc| + { id: doc.id, newspaper: doc.newspaper, language: doc.language, text: doc.all_text, - date: doc.date_created + date: doc.date_created, } - end end + end end diff --git a/app/workers/splitter_worker.rb b/app/workers/splitter_worker.rb index bb90f61f40c6f4dbdd5f4ca652a99612b6672a1f..a6444d969eecde7f5a456b18052cb6f9a4513bd4 100644 --- a/app/workers/splitter_worker.rb +++ b/app/workers/splitter_worker.rb @@ -1,8 +1,6 @@ class SplitterWorker - include Sidekiq::Worker - - def perform(tool_id, user_id, experiment_id, tool_type, tool_parameters) - - end + include Sidekiq::Worker + def perform(tool_id, user_id, experiment_id, tool_type, tool_parameters) + end end diff --git a/config/application.rb b/config/application.rb index 27558195263f4adcf130c9bf0038b799aaaf3dd8..7eaa9a2cc47f649a7c8e3951ff27ceb45c8272bf 100644 --- a/config/application.rb +++ b/config/application.rb @@ -7,22 +7,33 @@ require "rails/all" Bundler.require(*Rails.groups) module NewspapersPlatform - class Application < Rails::Application - # Initialize configuration defaults for originally generated Rails version. - config.load_defaults 6.1 + class Application < Rails::Application + # Initialize configuration defaults for originally generated Rails version. + config.load_defaults 6.1 - # Configuration for the application, engines, and railties goes here. - # - # These settings can be overridden in specific environments using the files - # in config/environments, which are processed later. - # - # config.time_zone = "Central Time (US & Canada)" - # config.eager_load_paths << Rails.root.join("extras") - config.solr = config_for('solr') - if File.exist? "#{Rails.root}/config/auths.yml" - config.auths = config_for('auths') - end - # config.active_job.queue_adapter = :sidekiq - config.iiif_sources = config_for("iiif_sources") + # Configuration for the application, engines, and railties goes here. + # + # These settings can be overridden in specific environments using the files + # in config/environments, which are processed later. + # + # config.time_zone = "Central Time (US & Canada)" + # config.eager_load_paths << Rails.root.join("extras") + config.solr = config_for("solr") + if File.exist? "#{Rails.root}/config/auths.yml" + config.auths = config_for("auths") end + # config.active_job.queue_adapter = :sidekiq + config.iiif_sources = config_for("iiif_sources") + + # Allow requests from different origins + config.middleware.use Rack::Cors do + allow do + origins "*" + resource "*", + headers: :any, + expose: %w(access-token expiry token-type uid client), + methods: %i(post) + end + end + end end diff --git a/config/boot.rb b/config/boot.rb index 3cda23b4db46f4304ea7df756bcefdf304bcd055..988a5ddc460f03c2cafb3b91d98f0cc930ebc8ed 100644 --- a/config/boot.rb +++ b/config/boot.rb @@ -1,4 +1,4 @@ -ENV['BUNDLE_GEMFILE'] ||= File.expand_path('../Gemfile', __dir__) +ENV["BUNDLE_GEMFILE"] ||= File.expand_path("../Gemfile", __dir__) require "bundler/setup" # Set up gems listed in the Gemfile. require "bootsnap/setup" # Speed up boot time by caching expensive operations. diff --git a/config/environments/production.rb b/config/environments/production.rb index 2a69174e9956abf725760b632992f09133b9868f..b67d74104fa16590f31855168bdcbe4bb74d1fea 100644 --- a/config/environments/production.rb +++ b/config/environments/production.rb @@ -13,7 +13,7 @@ Rails.application.configure do config.eager_load = true # Full error reports are disabled and caching is turned on. - config.consider_all_requests_local = false + config.consider_all_requests_local = false config.action_controller.perform_caching = true # Ensures that a master key has been made available in either ENV["RAILS_MASTER_KEY"] @@ -22,7 +22,7 @@ Rails.application.configure do # Disable serving static files from the `/public` folder by default since # Apache or NGINX already handles this. - config.public_file_server.enabled = ENV['RAILS_SERVE_STATIC_FILES'].present? + config.public_file_server.enabled = ENV["RAILS_SERVE_STATIC_FILES"].present? # Compress CSS using a preprocessor. # config.assets.css_compressor = :sass @@ -53,7 +53,7 @@ Rails.application.configure do config.log_level = :info # Prepend all log lines with the following tags. - config.log_tags = [ :request_id ] + config.log_tags = [:request_id] # Use a different cache store in production. # config.cache_store = :mem_cache_store @@ -89,9 +89,9 @@ Rails.application.configure do # config.logger = ActiveSupport::TaggedLogging.new(Syslog::Logger.new 'app-name') if ENV["RAILS_LOG_TO_STDOUT"].present? - logger = ActiveSupport::Logger.new(STDOUT) + logger = ActiveSupport::Logger.new(STDOUT) logger.formatter = config.log_formatter - config.logger = ActiveSupport::TaggedLogging.new(logger) + config.logger = ActiveSupport::TaggedLogging.new(logger) end # Do not dump schema after migrations. diff --git a/config/environments/test.rb b/config/environments/test.rb index 93ed4f1b78622a525958f919962735106b03152e..4fbe458abe9135b9463739cff523f19d4ff643d7 100644 --- a/config/environments/test.rb +++ b/config/environments/test.rb @@ -19,11 +19,11 @@ Rails.application.configure do # Configure public file server for tests with Cache-Control for performance. config.public_file_server.enabled = true config.public_file_server.headers = { - 'Cache-Control' => "public, max-age=#{1.hour.to_i}" + "Cache-Control" => "public, max-age=#{1.hour.to_i}", } # Show full error reports and disable caching. - config.consider_all_requests_local = true + config.consider_all_requests_local = true config.action_controller.perform_caching = false config.cache_store = :null_store diff --git a/config/initializers/assets.rb b/config/initializers/assets.rb index 4b828e80cb778244843194acf5f8a74238ec2c13..c1f948d0184dfaad4f51fb3bd04802046aad1afc 100644 --- a/config/initializers/assets.rb +++ b/config/initializers/assets.rb @@ -1,12 +1,12 @@ # Be sure to restart your server when you modify this file. # Version of your assets, change this if you want to expire all your assets. -Rails.application.config.assets.version = '1.0' +Rails.application.config.assets.version = "1.0" # Add additional assets to the asset load path. # Rails.application.config.assets.paths << Emoji.images_path # Add Yarn node_modules folder to the asset load path. -Rails.application.config.assets.paths << Rails.root.join('node_modules') +Rails.application.config.assets.paths << Rails.root.join("node_modules") # Precompile additional assets. # application.js, application.css, and all non-JS/CSS in the app/assets diff --git a/config/initializers/filter_parameter_logging.rb b/config/initializers/filter_parameter_logging.rb index 4b34a036689c21f4ccddb82823b2c2de065bb7fc..0af68a68b276c2ae8cff41ebae6908372594a1ec 100644 --- a/config/initializers/filter_parameter_logging.rb +++ b/config/initializers/filter_parameter_logging.rb @@ -2,5 +2,5 @@ # Configure sensitive parameters which will be filtered from the log file. Rails.application.config.filter_parameters += [ - :passw, :secret, :token, :_key, :crypt, :salt, :certificate, :otp, :ssn + :passw, :secret, :token, :_key, :crypt, :salt, :certificate, :otp, :ssn, ] diff --git a/config/initializers/session_store.rb b/config/initializers/session_store.rb index df3891e30f03bb67c0beabb4485d04d017db5c85..38f5f6928d320bd9e70c5d0a0a3b60ca337b0ad6 100644 --- a/config/initializers/session_store.rb +++ b/config/initializers/session_store.rb @@ -1,2 +1,2 @@ -Rails.application.config.session_store :active_record_store, :key => '_web_session' -# Run this regularly to clean up DB: 'rails db:sessions:trim' \ No newline at end of file +Rails.application.config.session_store :active_record_store, :key => "_web_session" +# Run this regularly to clean up DB: 'rails db:sessions:trim' diff --git a/config/routes.rb b/config/routes.rb index b753e954f0d2627604c85a8ffaee77f0e79a56bf..7ee124b150b46148416bef3989708ea143304970 100644 --- a/config/routes.rb +++ b/config/routes.rb @@ -1,58 +1,58 @@ # frozen_string_literal: true -require 'sidekiq/web' +require "sidekiq/web" Rails.application.routes.draw do - root to: 'catalog#home' + root to: "catalog#home" - get '/send', to: "application#send_file" + get "/send", to: "application#send_file" - get '/search', to: 'catalog#index' - get '/catalog/:id', to: 'catalog#show' - post '/catalog/facet_pagination', to: 'catalog#paginate_facets' - post '/named_entities', to: 'catalog#named_entities_for_docs' - post '/dataset_named_entities', to: 'catalog#named_entities_for_dataset' - post '/catalog/wide_dates_histogram', to: 'catalog#wide_dates_histogram' - post '/catalog/confirm_compound_creation', to: 'catalog#confirm_compound_creation' - post '/catalog/create_compound', to: 'catalog#create_compound' - post '/catalog/delete_compound', to: 'catalog#delete_compound' - post '/catalog/random_sample', to: 'catalog#random_sample' + get "/search", to: "catalog#index" + get "/catalog/:id", to: "catalog#show" + post "/catalog/facet_pagination", to: "catalog#paginate_facets" + post "/named_entities", to: "catalog#named_entities_for_docs" + post "/dataset_named_entities", to: "catalog#named_entities_for_dataset" + post "/catalog/wide_dates_histogram", to: "catalog#wide_dates_histogram" + post "/catalog/confirm_compound_creation", to: "catalog#confirm_compound_creation" + post "/catalog/create_compound", to: "catalog#create_compound" + post "/catalog/delete_compound", to: "catalog#delete_compound" + post "/catalog/random_sample", to: "catalog#random_sample" - get '/datasets', to: 'dataset#index' - get '/datasets/update', to: 'dataset#update_datasets_list' - post '/datasets/working_dataset', to: 'dataset#set_working_dataset' - post "/datasets/add_selected_documents", to: "dataset#add_selected_documents" - post "/datasets/add_compound", to: "dataset#add_compound" - post "/datasets/remove_selected_documents", to: "dataset#remove_selected_documents" - post "/datasets/add_all_documents", to: "dataset#add_all_documents" - post "/datasets/export_dataset", to: "dataset#export_dataset" - get "/datasets/list", to: "dataset#list_datasets" - get '/dataset/:id', to: 'dataset#show' - post "/dataset/toggle_sharing_status", to: "dataset#toggle_sharing_status" - post "/dataset/:id/paginate", to: "dataset#paginate" - post '/dataset/create', to: 'dataset#create_dataset' - post '/dataset/rename', to: 'dataset#rename_dataset' - post '/dataset/import', to: 'dataset#import_dataset' - post '/dataset/delete', to: 'dataset#delete_dataset' + get "/datasets", to: "dataset#index" + get "/datasets/update", to: "dataset#update_datasets_list" + post "/datasets/working_dataset", to: "dataset#set_working_dataset" + post "/datasets/add_selected_documents", to: "dataset#add_selected_documents" + post "/datasets/add_compound", to: "dataset#add_compound" + post "/datasets/remove_selected_documents", to: "dataset#remove_selected_documents" + post "/datasets/add_all_documents", to: "dataset#add_all_documents" + post "/datasets/export_dataset", to: "dataset#export_dataset" + get "/datasets/list", to: "dataset#list_datasets" + get "/dataset/:id", to: "dataset#show" + post "/dataset/toggle_sharing_status", to: "dataset#toggle_sharing_status" + post "/dataset/:id/paginate", to: "dataset#paginate" + post "/dataset/create", to: "dataset#create_dataset" + post "/dataset/rename", to: "dataset#rename_dataset" + post "/dataset/import", to: "dataset#import_dataset" + post "/dataset/delete", to: "dataset#delete_dataset" - get '/experiments', to: 'experiment#index' - get '/experiments/update', to: 'experiment#update_experiments_list' - post '/experiment/create', to: 'experiment#create' - post '/experiment/delete', to: 'experiment#delete' - post '/experiment/run', to: 'experiment#run_experiment' - get '/experiment/:id', to: "experiment#show" - get '/experiment/:id/load', to: "experiment#load" - post '/experiment/:id/save', to: "experiment#save" - post '/experiment/:id/add_tool', to: "experiment#add_tool" - post '/experiment/:id/delete_tool', to: "experiment#delete_tool" - post '/experiment/:id/edit_tool', to: "experiment#edit_tool" - post '/experiment/:id/edit_tool_form', to: "experiment#edit_tool_form" - post '/experiment/:id/tool_results', to: "experiment#tool_results" - post '/experiment/:id/run_tool', to: "experiment#run_tool" - post '/experiment/:id/run_experiment', to: "experiment#run_experiment" + get "/experiments", to: "experiment#index" + get "/experiments/update", to: "experiment#update_experiments_list" + post "/experiment/create", to: "experiment#create" + post "/experiment/delete", to: "experiment#delete" + post "/experiment/run", to: "experiment#run_experiment" + get "/experiment/:id", to: "experiment#show" + get "/experiment/:id/load", to: "experiment#load" + post "/experiment/:id/save", to: "experiment#save" + post "/experiment/:id/add_tool", to: "experiment#add_tool" + post "/experiment/:id/delete_tool", to: "experiment#delete_tool" + post "/experiment/:id/edit_tool", to: "experiment#edit_tool" + post "/experiment/:id/edit_tool_form", to: "experiment#edit_tool_form" + post "/experiment/:id/tool_results", to: "experiment#tool_results" + post "/experiment/:id/run_tool", to: "experiment#run_tool" + post "/experiment/:id/run_experiment", to: "experiment#run_experiment" - resources :tool, only: [:show, :create, :update, :destroy] + resources :tool, only: [:show, :create, :update, :destroy] - mount ActionCable.server => '/cable' - if Rails.env.development? - mount Sidekiq::Web => '/sidekiq' - end + mount ActionCable.server => "/cable" + if Rails.env.development? + mount Sidekiq::Web => "/sidekiq" + end end diff --git a/db/migrate/20210721081005_create_users.rb b/db/migrate/20210721081005_create_users.rb index 46e5b178dbe4817f5db36141574fbc7ccefdf04d..d2be7d5092714895ac83afaa2014b7cae8e91c5e 100644 --- a/db/migrate/20210721081005_create_users.rb +++ b/db/migrate/20210721081005_create_users.rb @@ -2,7 +2,7 @@ class CreateUsers < ActiveRecord::Migration[6.1] def change create_table :users do |t| t.string :labs_user_id, null: false, unique: true - + t.timestamps null: false end diff --git a/db/migrate/20210903194218_create_experiment.rb b/db/migrate/20210903194218_create_experiment.rb index 8c0761e3ecd7f5342a104fc383aa0912e81df7c9..3dc1d36c18d132931feea4de8ce45e96f5ef4fab 100644 --- a/db/migrate/20210903194218_create_experiment.rb +++ b/db/migrate/20210903194218_create_experiment.rb @@ -1,11 +1,11 @@ class CreateExperiment < ActiveRecord::Migration[6.1] - def change - create_table :experiments do |t| - t.string :title - t.references :user, foreign_key: true - t.jsonb :description, default: {children:[]} - t.timestamps - end - add_index :experiments, [:title, :user_id], unique: true + def change + create_table :experiments do |t| + t.string :title + t.references :user, foreign_key: true + t.jsonb :description, default: { children: [] } + t.timestamps end + add_index :experiments, [:title, :user_id], unique: true + end end diff --git a/db/migrate/20210909142841_create_datasets.rb b/db/migrate/20210909142841_create_datasets.rb index 2e54da39e1a46a9cd478cb3d5b56d68ff75bb6df..44dfd60da850c13425606b1c900b4c44da8fb700 100644 --- a/db/migrate/20210909142841_create_datasets.rb +++ b/db/migrate/20210909142841_create_datasets.rb @@ -1,12 +1,12 @@ class CreateDatasets < ActiveRecord::Migration[6.1] - def change - create_table :datasets do |t| - t.string :title - t.references :user, foreign_key: true - t.jsonb :documents, null: false, default: [] - t.boolean :public, default: false - t.timestamps - end - add_index :datasets, [:title, :user_id], unique: true + def change + create_table :datasets do |t| + t.string :title + t.references :user, foreign_key: true + t.jsonb :documents, null: false, default: [] + t.boolean :public, default: false + t.timestamps end + add_index :datasets, [:title, :user_id], unique: true + end end diff --git a/db/migrate/20210915140752_add_tool.rb b/db/migrate/20210915140752_add_tool.rb index b0363d37f12af95a8444c453bd1e47b7b75ba01a..2705fb61ace31e76bc139eed4b4b25ff5b586ee9 100644 --- a/db/migrate/20210915140752_add_tool.rb +++ b/db/migrate/20210915140752_add_tool.rb @@ -1,15 +1,15 @@ class AddTool < ActiveRecord::Migration[6.1] def change - create_table :tools do |t| - t.references :experiment, foreign_key: true - t.references :parent, foreign_key: {to_table: :tools} - t.string :tool_type - t.string :input_type - t.string :output_type - t.jsonb :parameters, default: {} - t.jsonb :results, default: {} - t.string :status, default: "created" - t.timestamps - end + create_table :tools do |t| + t.references :experiment, foreign_key: true + t.references :parent, foreign_key: { to_table: :tools } + t.string :tool_type + t.string :input_type + t.string :output_type + t.jsonb :parameters, default: {} + t.jsonb :results, default: {} + t.string :status, default: "created" + t.timestamps + end end end diff --git a/db/migrate/20211110092535_add_notifications_table.rb b/db/migrate/20211110092535_add_notifications_table.rb index 2b06ba89ee79db58fffcdf817a7f43b287c0baa6..9be63786e87014ca0b4f192c1545728041fb19ee 100644 --- a/db/migrate/20211110092535_add_notifications_table.rb +++ b/db/migrate/20211110092535_add_notifications_table.rb @@ -1,10 +1,10 @@ class AddNotificationsTable < ActiveRecord::Migration[6.1] def change - create_table :notifications do |t| - t.references :user, foreign_key: true - t.string :content - t.boolean :read, default: false - t.timestamps - end + create_table :notifications do |t| + t.references :user, foreign_key: true + t.string :content + t.boolean :read, default: false + t.timestamps + end end end diff --git a/db/migrate/20211123112405_create_compound_articles.rb b/db/migrate/20211123112405_create_compound_articles.rb index 53bc24fc2ef5fc07aceab6981ada783f07ad7cc8..3b34a12159ce04d1b68f04fb99a2d7326e92dcc2 100644 --- a/db/migrate/20211123112405_create_compound_articles.rb +++ b/db/migrate/20211123112405_create_compound_articles.rb @@ -1,17 +1,17 @@ class CreateCompoundArticles < ActiveRecord::Migration[6.1] - def change - create_table :compound_articles do |t| - t.string :title - t.string :issue_id - t.string :newspaper - t.string :date_created - t.string :thumbnail_url - t.string :language - t.text :all_text - t.references :user, foreign_key: true - t.string :parts, array: true, default: [] - t.timestamps - end - add_index :compound_articles, [:title, :user_id], unique: true + def change + create_table :compound_articles do |t| + t.string :title + t.string :issue_id + t.string :newspaper + t.string :date_created + t.string :thumbnail_url + t.string :language + t.text :all_text + t.references :user, foreign_key: true + t.string :parts, array: true, default: [] + t.timestamps end + add_index :compound_articles, [:title, :user_id], unique: true + end end diff --git a/db/schema.rb b/db/schema.rb index 164227fa5c68f127839130f3eb05d190a9f22819..bc77a9743cb6ef840820d50377795764c21df84e 100644 --- a/db/schema.rb +++ b/db/schema.rb @@ -45,7 +45,7 @@ ActiveRecord::Schema.define(version: 2021_12_02_095539) do create_table "experiments", force: :cascade do |t| t.string "title" t.bigint "user_id" - t.jsonb "description", default: {"children"=>[]} + t.jsonb "description", default: { "children" => [] } t.datetime "created_at", precision: 6, null: false t.datetime "updated_at", precision: 6, null: false t.index ["title", "user_id"], name: "index_experiments_on_title_and_user_id", unique: true diff --git a/test/test_helper.rb b/test/test_helper.rb index 47b598dee48a9c7280887f4f5a86339f39b02351..d713e377c9488bfa4cfc9e4a5ed03146e42988e0 100644 --- a/test/test_helper.rb +++ b/test/test_helper.rb @@ -1,4 +1,4 @@ -ENV['RAILS_ENV'] ||= 'test' +ENV["RAILS_ENV"] ||= "test" require_relative "../config/environment" require "rails/test_help" diff --git a/test/workers/tool_runner_worker_test.rb b/test/workers/tool_runner_worker_test.rb index 29db595b6f15a2c8dfe004c73b50df039d4f577c..95a67b1d902aabc4d8d63dd9941ec5e83b74a375 100644 --- a/test/workers/tool_runner_worker_test.rb +++ b/test/workers/tool_runner_worker_test.rb @@ -1,4 +1,5 @@ -require 'test_helper' +require "test_helper" + class ToolRunnerWorkerTest < Minitest::Test def test_example skip "add some examples to (or delete) #{__FILE__}"