repo_name
stringlengths
6
97
path
stringlengths
3
341
text
stringlengths
8
1.02M
shirasagi/opendata
spec/models/ss/site_spec.rb
require 'spec_helper' describe SS::Site do subject(:model) { SS::Site } describe "#save and #find" do subject(:factory) { :ss_site } it_behaves_like "mongoid#save" it_behaves_like "mongoid#find" end describe "#attributes" do subject { ss_site } it { expect(subject.domain).not_to eq nil } it { expect(subject.path).not_to eq nil } it { expect(subject.url).not_to eq nil } it { expect(subject.full_url).not_to eq nil } end describe "#find_by_domain" do context "when domain can find" do let(:site) { ss_site } subject { model.find_by_domain site.domains[0] } it { expect(subject.domain).not_to eq nil } it { expect(subject.path).not_to eq nil } it { expect(subject.url).not_to eq nil } it { expect(subject.full_url).not_to eq nil } end context "when domain cannot find" do subject { model.find_by_domain "host-#{unique_id}" } it { expect(subject).to eq nil } end end describe "#root_group" do subject { create(:ss_site, host: "#{unique_id}", domains: ["#{unique_id}.com"], group_ids: [ss_group.id]) } it { expect(subject.root_group).not_to be_nil } end end
shirasagi/opendata
app/controllers/opendata/app/appfiles_controller.rb
class Opendata::App::AppfilesController < ApplicationController include Cms::BaseFilter include Cms::CrudFilter helper Opendata::FormHelper model Opendata::Appfile navi_view "opendata/main/navi" before_action :set_app private def app @app ||= Opendata::App.site(@cur_site).node(@cur_node).find params[:app_id] end def set_app raise "403" unless app.allowed?(:edit, @cur_user, site: @cur_site) @crumbs << [@app.name, opendata_app_path(id: @app)] end def set_item @item = app.appfiles.find params[:id] end public def index @items = @app.appfiles. search(params[:s]). order_by(name: 1). page(params[:page]).per(50) end def create @item = @app.appfiles.create get_params @item.status = params[:item][:state] @item.workflow = { workflow_reset: true } if @app.member.present? render_create @item.valid? end def update @item.attributes = get_params @item.status = params[:item][:state] @item.workflow = { workflow_reset: true } if @app.member.present? render_update @item.update end def download @item = @app.appfiles.find params[:appfile_id] send_file @item.file.path, type: @item.content_type, filename: @item.filename, disposition: :attachment, x_sendfile: true end end
shirasagi/opendata
app/models/concerns/opendata/addon/common_page_setting.rb
<reponame>shirasagi/opendata module Opendata::Addon::CommonPageSetting extend ActiveSupport::Concern included do field :show_point, type: String, default: 'show' field :show_tabs, type: SS::Extensions::Words field :tab_titles, type: Hash permit_params :show_point permit_params show_tabs: [] permit_params tab_titles: [ :released, :popular, :attention ] validates :show_point, inclusion: { in: %w(show hide), allow_blank: true } end def show_point_options %w(show hide).map do |v| [ I18n.t("views.options.state.#{v}"), v ] end end def hide_point? show_point == 'hide' end def show_point? !hide_point? end def show_tab?(option) return true if show_tabs.blank? show_tabs.include?(option) end def tab_title(option) tab_titles[option] if tab_titles.present? end end
shirasagi/opendata
app/controllers/chorg/changesets_controller.rb
class Chorg::ChangesetsController < ApplicationController include Cms::BaseFilter include Cms::CrudFilter model Chorg::Changeset navi_view "cms/main/navi" before_action :set_revision private def set_crumbs set_revision @crumbs << [:"chorg.revision", chorg_revisions_revisions_path] @crumbs << [@cur_revision.name, edit_chorg_revisions_revision_path(id: @cur_revision.id)] end def set_item super raise "404" unless @item.type == params[:type] end def set_revision @cur_revision ||= Chorg::Revision.site(@cur_site).where(id: params[:rid]).first raise "404" unless @cur_revision end def fix_params { cur_revision: @cur_revision, cur_type: params[:type] } end def append_view_paths append_view_path "app/views/chorg/changesets/#{params[:type]}" super end public def index redirect_to chorg_revisions_revision_path(id: params[:rid]) end end
shirasagi/opendata
spec/features/chorg/run_spec.rb
require 'spec_helper' describe "chorg_run", dbscope: :example do let(:site) { cms_site } let(:revision) { create(:revision, site_id: site.id) } let(:changeset) { create(:add_changeset, revision_id: revision.id) } let(:revision_show_path) { chorg_revisions_revision_path site.host, revision.id } context "with test run" do let(:test_run_path) { chorg_run_confirmation_path site.host, revision.id, "test" } it "without login" do # ensure that entities has existed. expect(changeset).not_to be_nil visit test_run_path expect(current_path).to eq sns_login_path end it "without auth" do # ensure that entities has existed. expect(changeset).not_to be_nil login_ss_user visit test_run_path expect(status_code).to eq 403 end it "runs test" do # ensure that entities has existed. expect(changeset).not_to be_nil login_cms_user visit test_run_path expect(status_code).to eq 200 within "form#item-form" do click_button I18n.t("chorg.views.run/confirmation.test.run_button") end expect(status_code).to eq 200 expect(current_path).to eq revision_show_path revision.reload expect(revision.job_ids.length).to eq 1 # job should be started within 1.minute timeout(60) do loop do count = Job::Log.where(site_id: site.id, job_id: revision.job_ids.first).count break if count > 0 sleep 0.1 end end log = Job::Log.where(site_id: site.id, job_id: revision.job_ids.first).first expect(log).not_to be_nil end end context "with main run" do let(:main_run_path) { chorg_run_confirmation_path site.host, revision.id, "main" } it "without login" do # ensure that entities has existed. expect(changeset).not_to be_nil visit main_run_path expect(current_path).to eq sns_login_path end it "without auth" do # ensure that entities has existed. expect(changeset).not_to be_nil login_ss_user visit main_run_path expect(status_code).to eq 403 end it "runs main" do # ensure that entities has existed. expect(changeset).not_to be_nil login_cms_user visit main_run_path expect(status_code).to eq 200 within "form#item-form" do click_button I18n.t("chorg.views.run/confirmation.main.run_button") end expect(status_code).to eq 200 expect(current_path).to eq revision_show_path revision.reload expect(revision.job_ids.length).to eq 1 # job should be started within 1.minute timeout(60) do loop do count = Job::Log.where(site_id: site.id, job_id: revision.job_ids.first).count break if count > 0 sleep 0.1 end end log = Job::Log.where(site_id: site.id, job_id: revision.job_ids.first).first expect(log).not_to be_nil end end end
shirasagi/opendata
app/controllers/cms/search_contents/pages_controller.rb
<reponame>shirasagi/opendata class Cms::SearchContents::PagesController < ApplicationController include Cms::BaseFilter include Cms::ApiFilter::Contents model Cms::Page append_view_path "app/views/cms/search_contents/pages" navi_view "cms/search_contents/navi" private def set_params @name = params[:s][:name] @filename = params[:s][:filename] @state = params[:s][:state] @released = params[:s][:released] @updated = params[:s][:updated] @category_ids = params[:s][:category_ids].select(&:present?).map(&:to_i) @categories = Category::Node::Base.in(_id: @category_ids).entries @categories = @category_ids.map { |id| @categories.find { |item| item.id == id } } @group_ids = params[:s][:group_ids].select(&:present?).map(&:to_i) @groups = SS::Group.in(_id: @group_ids).entries @groups = @group_ids.map { |id| @groups.find { |item| item.id == id } } end public def index @items = [] @categories = [] @groups = [] return unless params[:s] set_params filename = @filename.present? ? { filename: /^#{Regexp.escape(@filename)}/i } : {} categories = @category_ids.present? ? { category_ids: @category_ids } : {} groups = @group_ids.present? ? { group_ids: @group_ids } : {} state = @state ? { state: @state } : {} released = [] if @released start = @released[:start] close = @released[:close] released << { :released.gte => start } if start.present? released << { :released.lte => close } if close.present? end updated = [] if @updated start = @updated[:start] close = @updated[:close] updated << { :updated.gte => start } if start.present? updated << { :updated.lte => close } if close.present? end @items = @model.site(@cur_site). allow(:read, @cur_user). search(params[:s]). where(filename). in(categories). in(groups). where(state). and(released). and(updated). order_by(filename: 1). page(params[:page]).per(25) end end
shirasagi/opendata
app/models/ss/site.rb
class SS::Site include SS::Model::Site end
shirasagi/opendata
spec/support/webmock_helper.rb
# require 'webmock/rspec' # include WebMock::API # WebMock.disable! # # NOTE: Don't use WebMock now because existing tests for voice fail.
shirasagi/opendata
spec/factories/ss/groups.rb
<reponame>shirasagi/opendata FactoryGirl.define do factory :ss_group, class: SS::Group do name "ss_group" end end
shirasagi/opendata
db/seeds/opendata/load.rb
Dir.chdir @root = File.dirname(__FILE__) @site = SS::Site.find_by host: ENV["site"] ## ------------------------------------- puts "# roles" def add_permissions(name, permissions) puts name cond = { name: name, site_id: @site.id } item = Cms::Role.find_by cond rescue nil return unless item item.permissions = (item.permissions.dup + permissions).uniq.sort.select(&:present?) item.update item end add_permissions "記事編集権限", %w( read_other_opendata_datasets edit_other_opendata_datasets delete_other_opendata_datasets read_private_opendata_datasets edit_private_opendata_datasets delete_private_opendata_datasets read_other_opendata_apps edit_other_opendata_apps delete_other_opendata_apps read_private_opendata_apps edit_private_opendata_apps delete_private_opendata_apps read_other_opendata_ideas edit_other_opendata_ideas delete_other_opendata_ideas read_private_opendata_ideas edit_private_opendata_ideas delete_private_opendata_ideas ) ## ------------------------------------- puts "# files" Dir.glob "files/**/*.*" do |file| puts name = file.sub(/^files\//, "") Fs.binwrite "#{@site.path}/#{name}", File.binread(file) end def save_ss_files(path, data) puts path cond = { site_id: @site._id, filename: data[:filename], model: data[:model] } file = Fs::UploadedFile.create_from_file(path) file.original_filename = data[:filename] if data[:filename].present? item = SS::File.find_or_create_by(cond) item.in_file = file item.update item end ## ------------------------------------- puts "# members" def save_member(data) puts data[:name] cond = { site_id: @site._id, email: data[:email] } item = Cms::Member.find_or_create_by(cond) item.attributes = data item.update item end member = save_member email: "<EMAIL>", name: "member", in_password: "<PASSWORD>" ## ------------------------------------- puts "# layouts" def save_layout(data) puts data[:name] cond = { site_id: @site._id, filename: data[:filename] } html = File.read("layouts/" + data[:filename]) rescue nil item = Cms::Layout.find_or_create_by(cond) item.attributes = data.merge html: html item.update item.add_to_set group_ids: @site.group_ids item end save_layout filename: "app-bunya.layout.html", name: "アプリ:分野、アプリ検索" save_layout filename: "app-page.layout.html", name: "アプリ:詳細ページ" save_layout filename: "app-top.layout.html", name: "アプリ:トップ" save_layout filename: "dataset-bunya.layout.html", name: "データ:分野、データ検索、グループ検索" save_layout filename: "dataset-page.layout.html", name: "データ:詳細ページ" save_layout filename: "dataset-top.layout.html", name: "データ:トップ" save_layout filename: "idea-bunya.layout.html", name: "アイデア:分野、アイデア検索" save_layout filename: "idea-page.layout.html", name: "アイデア:詳細ページ" save_layout filename: "idea-top.layout.html", name: "アイデア:トップ" save_layout filename: "mypage-page.layout.html", name: "マイページ:詳細" save_layout filename: "mypage-top.layout.html", name: "マイページ:トップ、メンバー、SPARQL" save_layout filename: "portal-event.layout.html", name: "ポータル:イベント" save_layout filename: "portal-general.layout.html", name: "ポータル:汎用" save_layout filename: "portal-top.layout.html", name: "ポータル:トップ" array = Cms::Layout.where(site_id: @site._id).map {|m| [m.filename.sub(/\..*$/, '\1'), m] } layouts = Hash[*array.flatten] ## ------------------------------------- puts "# nodes" def save_node(data) puts data[:name] cond = { site_id: @site._id, filename: data[:filename] } upper_html ||= File.read("nodes/" + data[:filename] + ".upper_html") rescue nil loop_html ||= File.read("nodes/" + data[:filename] + ".loop_html") rescue nil lower_html ||= File.read("nodes/" + data[:filename] + ".lower_html") rescue nil summary_html ||= File.read("nodes/" + data[:filename] + ".summary_html") rescue nil item = Cms::Node.unscoped.find_or_create_by(cond).becomes_with_route(data[:route]) item.upper_html = upper_html if upper_html item.loop_html = loop_html if loop_html item.lower_html = lower_html if lower_html item.summary_html = summary_html if summary_html item.attributes = data item.update item.add_to_set group_ids: @site.group_ids item end save_node filename: "css", name: "CSS", route: "uploader/file" save_node filename: "js", name: "Javascript", route: "uploader/file" save_node filename: "img", name: "画像", route: "uploader/file" save_node filename: "ads", name: "広告", route: "ads/banner" save_node filename: "docs", name: "お知らせ", route: "article/page", shortcut: "show", layout_id: layouts["portal-general"].id save_node filename: "event", name: "イベント", route: "event/page", layout_id: layouts["portal-event"].id, page_layout_id: layouts["portal-event"].id save_node filename: "dataset", name: "データカタログ", route: "opendata/dataset", shortcut: "show", layout_id: layouts["dataset-top"].id, page_layout_id: layouts["dataset-page"].id save_node filename: "dataset/bunya", name: "分野", route: "opendata/dataset_category", layout_id: layouts["dataset-bunya"].id save_node filename: "dataset/search_group", name: "データセットグループ検索", route: "opendata/search_dataset_group", layout_id: layouts["dataset-bunya"].id save_node filename: "dataset/search", name: "データセット検索", route: "opendata/search_dataset", layout_id: layouts["dataset-bunya"].id save_node filename: "app", name: "アプリマーケット", route: "opendata/app", shortcut: "show", layout_id: layouts["app-top"].id, page_layout_id: layouts["app-page"].id save_node filename: "app/bunya", name: "分野", route: "opendata/app_category", layout_id: layouts["app-bunya"].id save_node filename: "app/search", name: "アプリ検索", route: "opendata/search_app", layout_id: layouts["app-bunya"].id save_node filename: "idea", name: "アイデアボックス", route: "opendata/idea", shortcut: "show", layout_id: layouts["idea-top"].id, page_layout_id: layouts["idea-page"].id save_node filename: "idea/bunya", name: "分野", route: "opendata/idea_category", layout_id: layouts["idea-bunya"].id save_node filename: "idea/search", name: "アイデア検索", route: "opendata/search_idea", layout_id: layouts["idea-bunya"].id save_node filename: "sparql", name: "SPARQL", route: "opendata/sparql", layout_id: layouts["mypage-top"].id save_node filename: "api", name: "API", route: "opendata/api" save_node filename: "member", name: "ユーザー", route: "opendata/member", layout_id: layouts["mypage-top"].id save_node filename: "auth", name: "ログイン", route: "member/login", layout_id: layouts["mypage-top"].id, redirect_url: "/mypage/", form_auth: "enabled", twitter_oauth: "enabled", facebook_oauth: "enabled", yahoojp_oauth: "enabled", google_oauth2_oauth: "enabled", github_oauth: "enabled" save_node filename: "mypage", name: "マイページ", route: "opendata/mypage", layout_id: layouts["mypage-top"].id save_node filename: "mypage/profile", name: "プロフィール", route: "opendata/my_profile", layout_id: layouts["mypage-page"].id save_node filename: "mypage/dataset", name: "データカタログ", route: "opendata/my_dataset", layout_id: layouts["mypage-page"].id save_node filename: "mypage/app", name: "アプリマーケット", route: "opendata/my_app", layout_id: layouts["mypage-page"].id save_node filename: "mypage/idea", name: "アイデアボックス", route: "opendata/my_idea", layout_id: layouts["mypage-page"].id save_node filename: "bunya", name: "分野", route: "cms/node" save_node filename: "bunya/kanko", name: "観光・文化・スポーツ", route: "opendata/category", order: 1 save_node filename: "bunya/kenko", name: "健康・福祉", route: "opendata/category", order: 2 save_node filename: "bunya/kosodate", name: "子育て・教育", route: "opendata/category", order: 3 save_node filename: "bunya/kurashi", name: "くらし・手続き", route: "opendata/category", order: 4 save_node filename: "bunya/sangyo", name: "産業・仕事", route: "opendata/category", order: 5 save_node filename: "bunya/shisei", name: "市政情報", route: "opendata/category", order: 6 save_node filename: "chiiki", name: "地域", route: "cms/node" save_node filename: "chiiki/shirasagi", name: "シラサギ市", route: "opendata/area", order: 1 [ %w(東区 higashi), %w(北区 kita), %w(南区 minami), %w(西区 nishi), ].each_with_index do |data, idx| save_node filename: "chiiki/shirasagi/#{data[1]}", name: data[0], route: "opendata/area", order: idx + 1 end # inquiry def save_inquiry_column(data) puts data[:name] cond = { node_id: data[:node_id], name: data[:name] } item = Inquiry::Column.find_or_create_by(cond) item.attributes = data item.update item end puts "# inquiry" inquiry_node = save_node route: "inquiry/form", filename: "inquiry", name: "お問い合わせ", layout_id: layouts["portal-general"].id, inquiry_html: "<p>下記事項を入力の上、確認画面へのボタンを押してください。</p>\n", inquiry_sent_html: "<p>お問い合わせを受け付けました。</p>\n", inquiry_captcha: "enabled", notice_state: "disabled", reply_state: "disabled" save_inquiry_column node_id: inquiry_node.id, name: "お名前", order: 10, input_type: "text_field", html: "", select_options: [], required: "required", site_id: @site._id save_inquiry_column node_id: inquiry_node.id, name: "企業・団体名", order: 20, input_type: "text_field", html: "", select_options: [], required: "optional", site_id: @site._id save_inquiry_column node_id: inquiry_node.id, name: "メールアドレス", order: 30, input_type: "email_field", html: "", select_options: [], required: "required", site_id: @site._id save_inquiry_column node_id: inquiry_node.id, name: "お問い合わせ内容", order: 40, input_type: "text_area", html: "", select_options: [], required: "required", site_id: @site._id ## ------------------------------------- puts "# parts" def save_part(data) puts data[:name] cond = { site_id: @site._id, filename: data[:filename] } html = File.read("parts/" + data[:filename]) rescue nil upper_html = File.read("parts/" + data[:filename].sub(/\.html$/, ".upper_html")) rescue nil loop_html = File.read("parts/" + data[:filename].sub(/\.html$/, ".loop_html")) rescue nil lower_html = File.read("parts/" + data[:filename].sub(/\.html$/, ".lower_html")) rescue nil item = Cms::Part.unscoped.find_or_create_by(cond).becomes_with_route(data[:route]) item.html = html if html item.upper_html = upper_html if upper_html item.loop_html = loop_html if loop_html item.lower_html = lower_html if lower_html item.attributes = data item.update item.add_to_set group_ids: @site.group_ids item end save_part filename: "ads/banner.part.html", name: "広告", route: "ads/banner" save_part filename: "app-attention.part.html", name: "アプリ:注目順", \ route: "opendata/app", limit: 10, sort: "attention" save_part filename: "app-head.part.html", name: "アプリ:ヘッダー", route: "cms/free" save_part filename: "app-kv.part.html", name: "アプリ:キービジュアル", route: "cms/free" save_part filename: "crumbs.part.html", name: "パンくず", route: "cms/crumb" save_part filename: "dataset-attention.part.html", name: "データ:注目順", \ route: "opendata/dataset", limit: 10, sort: "attention" save_part filename: "dataset-group.part.html", name: "データ:グループ", route: "opendata/dataset_group" save_part filename: "dataset-head.part.html", name: "データ:ヘッダー", route: "cms/free" save_part filename: "dataset-kv.part.html", name: "データ:キービジュアル", route: "cms/free" save_part filename: "event/calendar.part.html", name: "イベントカレンダー", route: "event/calendar" save_part filename: "foot.part.html", name: "フッター", route: "cms/free" save_part filename: "idea-attention.part.html", name: "アイデア:注目順", \ route: "opendata/idea", limit: 10, sort: "attention" save_part filename: "idea-head.part.html", name: "アイデア:ヘッダー", route: "cms/free" save_part filename: "idea-kv.part.html", name: "アイデア:キービジュアル", route: "cms/free" save_part filename: "mypage-login.part.html", name: "ログイン", \ route: "opendata/mypage_login", ajax_view: "enabled" save_part filename: "mypage-tabs.part.html", name: "マイページ:タブ", route: "cms/free" save_part filename: "portal-about.part.html", name: "ポータル:Our Open Dateとは", route: "cms/free" save_part filename: "portal-app.part.html", name: "ポータル:オープンアプリマーケット", \ route: "opendata/app", limit: 5, sort: "released" save_part filename: "portal-dataset.part.html", name: "ポータル:オープンデータカタログ", \ route: "opendata/dataset", limit: 5, sort: "released" save_part filename: "portal-idea.part.html", name: "ポータル:オープンアイデアボックス", \ route: "opendata/idea", limit: 5, sort: "released" save_part filename: "portal-kv.part.html", name: "ポータル:キービジュアル", route: "cms/free" save_part filename: "portal-tab.part.html", name: "ポータル:新着タブ", \ route: "cms/tabs", conditions: %w(docs event), limit: 5 save_part filename: "sns-share.part.html", name: "SNSシェアボタン", route: "cms/sns_share" save_part filename: "tab.part.html", name: "サイト切り替えタブ", route: "cms/free" ## ------------------------------------- puts "# pages" def save_page(data) puts data[:name] cond = { site_id: @site._id, filename: data[:filename] } html ||= File.read("pages/" + data[:filename]) rescue nil summary_html ||= File.read("pages/" + data[:filename].sub(/\.html$/, "") + ".summary_html") rescue nil item = Cms::Page.find_or_create_by(cond).becomes_with_route(data[:route]) item.html = html if html item.summary_html = summary_html if summary_html item.attributes = data item.update item.add_to_set group_ids: @site.group_ids item end contact_group = SS::Group.where(name: "シラサギ市/企画政策部/政策課").first contact_group_id = contact_group.id rescue nil contact_charge = contact_group_id ? "オープンデータ担当" : nil contact_email = contact_group_id ? "<EMAIL>" : nil contact_tel = contact_group_id ? "000-000-0000" : nil contact_fax = contact_group_id ? "000-000-0000" : nil save_page route: "cms/page", filename: "index.html", name: "トップページ", layout_id: layouts["portal-top"].id save_page route: "cms/page", filename: "tutorial-data.html", name: "データ登録手順", layout_id: layouts["portal-general"].id save_page route: "cms/page", filename: "tutorial-app.html", name: "アプリ登録手順", layout_id: layouts["portal-general"].id save_page route: "cms/page", filename: "tutorial-idea.html", name: "アイデア登録手順", layout_id: layouts["portal-general"].id page0 = save_page route: "article/page", filename: "docs/1.html", name: "○○が公開されました。", layout_id: layouts["portal-general"].id, \ map_points: Map::Extensions::Points.new([{loc: Map::Extensions::Loc.mongoize([34.067022, 134.589982])}]), \ contact_group_id: contact_group_id, contact_charge: contact_charge, contact_email: contact_email, \ contact_tel: contact_tel, contact_fax: contact_fax page1 = save_page route: "article/page", filename: "docs/2.html", name: "○○○○○○が公開されました。", \ layout_id: layouts["portal-general"].id, contact_group_id: contact_group_id, contact_charge: contact_charge, \ contact_email: contact_email, contact_tel: contact_tel, contact_fax: contact_fax page2 = save_page route: "article/page", filename: "docs/3.html", name: "○○○○○○○○が公開されました。", \ layout_id: layouts["portal-general"].id, contact_group_id: contact_group_id, contact_charge: contact_charge, \ contact_email: contact_email, contact_tel: contact_tel, contact_fax: contact_fax event0 = save_page route: "event/page", filename: "event/4.html", name: "オープンデータイベント", \ layout_id: layouts["portal-event"].id, schedule: "#{7.days.since.strftime("%m").sub(/^0+/, '')}月#{7.days.since.strftime("%d").sub(/^0+/, '')}日", \ venue: "シラサギ市図書館", related_url: "http://demo.ss-proj.org/", \ event_dates: 7.upto(18).map { |d| "#{d.days.since.strftime("%Y/%m/%d")}" }.join("\r\n") page0.related_page_ids = [ page2.id, event0.id ] page0.save! ## ------------------------------------- puts "# ads" banner1 = save_ss_files "ss_files/ads/banner1.gif", filename: "banner1.gif", model: "ads/banner" banner2 = save_ss_files "ss_files/ads/banner2.gif", filename: "banner2.gif", model: "ads/banner" banner3 = save_ss_files "ss_files/ads/banner3.gif", filename: "banner3.gif", model: "ads/banner" banner4 = save_ss_files "ss_files/ads/banner4.gif", filename: "banner4.gif", model: "ads/banner" banner5 = save_ss_files "ss_files/ads/banner5.gif", filename: "banner5.gif", model: "ads/banner" banner6 = save_ss_files "ss_files/ads/banner6.gif", filename: "banner6.gif", model: "ads/banner" banner1.set(state: "public") banner2.set(state: "public") banner3.set(state: "public") banner4.set(state: "public") banner5.set(state: "public") banner6.set(state: "public") save_page route: "ads/banner", filename: "ads/600.html", name: "シラサギ", link_url: "http://www.ss-proj.org/", file_id: banner1.id save_page route: "ads/banner", filename: "ads/601.html", name: "シラサギ", link_url: "http://www.ss-proj.org/", file_id: banner2.id save_page route: "ads/banner", filename: "ads/602.html", name: "シラサギ", link_url: "http://www.ss-proj.org/", file_id: banner3.id save_page route: "ads/banner", filename: "ads/603.html", name: "シラサギ", link_url: "http://www.ss-proj.org/", file_id: banner4.id save_page route: "ads/banner", filename: "ads/604.html", name: "シラサギ", link_url: "http://www.ss-proj.org/", file_id: banner5.id save_page route: "ads/banner", filename: "ads/605.html", name: "シラサギ", link_url: "http://www.ss-proj.org/", file_id: banner6.id ## ------------------------------------- puts "# licenses" def license_file(filename) file = Fs::UploadedFile.new("fixtures") file.binmode file.write File.read("fixtures/#{filename}") file.rewind file.original_filename = filename file.content_type = "image/png" file end def save_license(data) puts data[:name] cond = { site_id: @site._id, name: data[:name] } item = Opendata::License.find_or_create_by cond item.update data item end license_cc_by = save_license name: "表示(CC BY)", in_file: license_file("cc-by.png"), order: 1 save_license name: "表示-継承(CC BY-SA)", in_file: license_file("cc-by-sa.png"), order: 2 save_license name: "表示-改変禁止(CC BY-ND)", in_file: license_file("cc-by-nd.png"), order: 3 save_license name: "表示-非営利(CC BY-NC)", in_file: license_file("cc-by-nc.png"), order: 4 save_license name: "表示-非営利-継承(CC BY-NC-SA)", in_file: license_file("cc-by-nc-sa.png"), order: 5 save_license name: "表示-非営利-改変禁止(CC BY-NC-ND)", in_file: license_file("cc-by-nc-nd.png"), order: 6 save_license name: "いかなる権利も保有しない(CC 0)", in_file: license_file("cc-zero.png"), order: 7 ## ------------------------------------- puts "# opendata dataset_groups" def save_dataset_group(data) puts data[:name] cond = { site_id: @site._id, name: data[:name] } item = Opendata::DatasetGroup.find_or_create_by cond item.update data end 1.step(3) do |i| save_dataset_group name: "データセットグループ#{i}", category_ids: Opendata::Node::Category.site(@site).pluck(:_id).sample(1) end ## ------------------------------------- puts "# opendata datasets" def save_data(data) puts data[:name] cond = { site_id: @site.id, filename: data[:filename] } item = Opendata::Dataset.find_or_create_by cond puts item.errors.full_messages unless item.update data item end def save_resource(dataset, data) puts data[:name] cond = { name: data[:name] } path = "datasets/resources/#{data[:filename]}" data.delete :filename Fs::UploadedFile.create_from_file(path) do |file| item = dataset.resources.where(cond).first || dataset.resources.new item.in_file = file item.update_attributes! data puts item.errors.full_messages unless item.save end end 1.step(5) do |i| dataset = save_data filename: "dataset/#{i}.html", name: "サンプルデータ【#{i}】", text: "サンプルデータ【#{i}】", route: "opendata/dataset", layout_id: layouts["dataset-page"].id, member_id: member.id, tags: %w(タグ), category_ids: Opendata::Node::Category.site(@site).pluck(:_id).sample(1), dataset_group_ids: Opendata::DatasetGroup.site(@site).pluck(:_id).sample(1), area_ids: Opendata::Node::Area.site(@site).pluck(:_id).sample(1) if i == 1 save_resource(dataset, name: "サンプルリソース", filename: "sample.txt", license_id: license_cc_by.id) end end ## ------------------------------------- puts "# opendata apps" def save_app(data) puts data[:name] cond = { site_id: @site._id, name: data[:name] } item = Opendata::App.find_or_create_by cond puts item.errors.full_messages unless item.update data item end def save_appfile(app, data) puts data[:filename] cond = { filename: data[:filename] } path = "apps/appfiles/#{data[:filename]}" data.delete :filename Fs::UploadedFile.create_from_file(path) do |file| item = app.appfiles.where(cond).first || app.appfiles.new item.in_file = file item.update_attributes! data puts item.errors.full_messages unless item.save end end 1.step(5) do |i| app = save_app filename: "app/#{i}.html", name: "サンプルアプリ【#{i}】", text: "サンプルアプリ【#{i}】", license: %w(MIT BSD Apache).sample, route: "opendata/app", layout_id: layouts["app-page"].id, member_id: member.id, tags: %w(タグ), category_ids: Opendata::Node::Category.site(@site).pluck(:_id).sample(1), dataset_ids: Opendata::Dataset.site(@site).pluck(:_id).sample(1), area_ids: Opendata::Node::Area.site(@site).pluck(:_id).sample(1) if i == 1 save_appfile(app, filename: "index.html") end end ## ------------------------------------- puts "# opendata ideas" def save_idea(data) puts data[:name] cond = { site_id: @site._id, name: data[:name] } item = Opendata::Idea.find_or_create_by cond puts item.errors.full_messages unless item.update data item end 1.step(5) do |i| idea = save_idea filename: "idea/#{i}.html", name: "サンプルアイデア【#{i}】", text: "サンプルコメント", route: "opendata/idea", layout_id: layouts["idea-page"].id, member_id: member.id, tags: %w(タグ), category_ids: Opendata::Node::Category.site(@site).pluck(:_id).sample(1), dataset_ids: Opendata::Dataset.site(@site).pluck(:_id).sample(1), app_ids: Opendata::App.site(@site).pluck(:_id).sample(1), area_ids: Opendata::Node::Area.site(@site).pluck(:_id).sample(1) end ## ------------------------------------- puts "# rdf vocabs" def import_vocab(data) puts data[:prefix] Rdf::VocabImportJob.new.call(@site.host, data[:prefix], data[:file], data[:owner] || Rdf::Vocab::OWNER_SYSTEM, data[:order]) end import_vocab prefix: "xsd", file: "rdf/xsd.ttl", order: 2000 import_vocab prefix: "dcmitype", file: "rdf/dctype.ttl", order: 2000 import_vocab prefix: "dc11", file: "rdf/dcelements.ttl", order: 2000 import_vocab prefix: "dc", file: "rdf/dcterms.ttl", order: 2000 import_vocab prefix: "ic", file: "rdf/ipa-core.ttl", order: 1000 ## ------------------------------------- puts "# max file size" def save_max_file_size(data) # 100 MiB data = {size: 100 * 1_024 * 1_024}.merge(data) puts data[:name] cond = { name: data[:name] } item = SS::MaxFileSize.find_or_create_by cond puts item.errors.full_messages unless item.update data item end save_max_file_size name: '画像ファイル', extensions: %w(gif png jpg jpeg bmp), order: 1, state: 'enabled' save_max_file_size name: '音声ファイル', extensions: %w(wav wma mp3 ogg), order: 2, state: 'enabled' save_max_file_size name: '動画ファイル', extensions: %w(wmv avi mpeg mpg flv mp4), order: 3, state: 'enabled' save_max_file_size name: 'マクロソフト・オフィース', extensions: %w(doc docx ppt pptx xls xlsx), order: 4, state: 'enabled' save_max_file_size name: 'PDF', extensions: %w(pdf), order: 5, state: 'enabled' save_max_file_size name: 'その他', extensions: %w(*), order: 9999, state: 'enabled'
shirasagi/opendata
app/models/opendata/url_resource.rb
<gh_stars>1-10 class Opendata::UrlResource include SS::Document include Opendata::Resource::Model include SS::Relation::File include Opendata::Addon::UrlRdfStore field :original_url, type: String field :original_updated, type: DateTime field :crawl_state, type: String, default: "same" field :crawl_update, type: String embedded_in :dataset, class_name: "Opendata::Dataset", inverse_of: :url_resource permit_params :name, :text, :license_id, :original_url, :crawl_update validates :crawl_update, presence: true validate :validate_original_url after_save -> { dataset.save(validate: false) } after_destroy -> { dataset.save(validate: false) } public def context_path "/url_resource" end def crawl_update_options [ [I18n.t("opendata.crawl_update_name.none"), "none"], [I18n.t("opendata.crawl_update_name.auto"), "auto"] ] end def do_crawl(time_out: 30) require 'net/http' require "open-uri" puts self.original_url last_modified = timeout(time_out) do open(self.original_url, proxy: true) { |url_file| url_file.last_modified } end if last_modified.blank? last_modified = Time.zone.now end if self.crawl_update == "none" do_crawl_none(last_modified) elsif self.crawl_update == "auto" do_crawl_auto(last_modified) end rescue TimeoutError puts I18n.t("opendata.errors.messages.invalid_timeout") rescue => e puts "Error: #{e}" self.crawl_state = "deleted" self.save(validate: false) end private def do_crawl_none(last_modified) if last_modified.present? if self.original_updated.blank? self.crawl_state = "updated" elsif last_modified.to_i > self.original_updated.to_i self.crawl_state = "updated" elsif last_modified.to_i <= self.original_updated.to_i self.crawl_state = "same" end self.original_updated = last_modified else puts "no file or no last_modified" self.crawl_state = "deleted" end res = self.save(validate: false) if res == true puts "success" else puts "failure" end end def do_crawl_auto(last_modified) return if last_modified.blank? return if last_modified.to_i <= self.original_updated.to_i self.crawl_state = "same" # validate_original_url method is called inside save method, # and then download resource from internet and save it locally. self.save end def validate_original_url uri = URI.parse(original_url) if uri.path == '/' errors.add :original_url, :invalid return end Tempfile.open('temp') do |temp_file| last_modified = download_to(temp_file) break if last_modified.blank? self.original_updated = last_modified self.filename = ::File.basename(uri.path) if self.filename.blank? self.filename = URI.unescape(self.filename) ss_file = SS::File.new ss_file.in_file = ActionDispatch::Http::UploadedFile.new(tempfile: temp_file, filename: self.filename, type: 'application/octet-stream') ss_file.model = self.class.to_s.underscore ss_file.content_type = self.format = self.filename.sub(/.*\./, "").upcase ss_file.filename = self.filename ss_file.save send("file_id=", ss_file.id) self.crawl_state = "same" end rescue TimeoutError => e logger.warn("#{e.class} (#{e.message}):\n #{e.backtrace.join("\n ")}") errors.add :base, I18n.t("opendata.errors.messages.invalid_timeout") rescue => e logger.warn("#{e.class} (#{e.message}):\n #{e.backtrace.join("\n ")}") errors.add :original_url, :invalid ensure in_file.close(true) if in_file end def download_to(temp_file, time_out: 30) require 'net/http' require "open-uri" require "resolv-replace" require 'timeout' require 'nkf' temp_file.binmode timeout(time_out) do open(original_url, proxy: true) do |data| data.binmode temp_file.write(data.read) temp_file.rewind content_disposition = data.meta['content-disposition'] content_disposition = "Content-Disposition: attachment; filename= " if content_disposition.blank? self.filename = NKF.nkf "-w", content_disposition.match(/filename=(\"?)(.+)\1/)[2].to_s if data.last_modified.blank? break Time.zone.now else break data.last_modified end end end end end
shirasagi/opendata
app/models/concerns/ckan/addon/server.rb
module Ckan::Addon module Server extend ActiveSupport::Concern extend SS::Addon included do field :ckan_url, type: String field :ckan_basicauth_state, type: String field :ckan_basicauth_username, type: String field :ckan_basicauth_password, type: String field :ckan_max_docs, type: Integer field :ckan_item_url, type: String field :ckan_json_cache, type: String attr_accessor :in_ckan_basicauth_password permit_params :ckan_url, :ckan_max_docs permit_params :ckan_basicauth_state, :ckan_basicauth_username, :in_ckan_basicauth_password, :ckan_item_url before_validation :set_ckan_basicauth_password, if: ->{ in_ckan_basicauth_password.present? } validates :ckan_url, format: /\Ahttps?:\/\// validates :ckan_max_docs, numericality: { greater_than_or_equal_to: 0 } validates :ckan_item_url, format: /\Ahttps?:\/\// template_variable_handler :id, :template_variable_common template_variable_handler :revision_id, :template_variable_common template_variable_handler :name, :template_variable_common template_variable_handler :title, :template_variable_common template_variable_handler :license_id, :template_variable_common template_variable_handler :license_title, :template_variable_common template_variable_handler :license_url, :template_variable_common template_variable_handler :author, :template_variable_common template_variable_handler :author_email, :template_variable_common template_variable_handler :maintainer, :template_variable_common template_variable_handler :maintainer_email, :template_variable_common template_variable_handler :num_tags, :template_variable_common template_variable_handler :num_resources, :template_variable_common template_variable_handler :private, :template_variable_common template_variable_handler :state, :template_variable_common template_variable_handler :version, :template_variable_common template_variable_handler :type, :template_variable_common template_variable_handler :url, :template_variable_url template_variable_handler :summary, :template_variable_summary template_variable_handler :class, :template_variable_class template_variable_handler :new, :template_variable_new template_variable_handler :created_date, :template_variable_created_date template_variable_handler :'created_date.iso', ->(name, value){ template_variable_created_date(name, value, 'iso') } template_variable_handler :'created_date.long', ->(name, value){ template_variable_created_date(name, value, 'long') } template_variable_handler :updated_date, :template_variable_updated_date template_variable_handler :'updated_date.iso', ->(name, value){ template_variable_updated_date(name, value, 'iso') } template_variable_handler :'updated_date.long', ->(name, value){ template_variable_updated_date(name, value, 'long') } template_variable_handler :created_time, :template_variable_created_time template_variable_handler :'created_time.iso', ->(name, value){ template_variable_created_time(name, value, 'iso') } template_variable_handler :'created_time.long', ->(name, value){ template_variable_created_time(name, value, 'long') } template_variable_handler :updated_time, :template_variable_updated_time template_variable_handler :'updated_time.iso', ->(name, value){ template_variable_updated_time(name, value, 'iso') } template_variable_handler :'updated_time.long', ->(name, value){ template_variable_updated_time(name, value, 'long') } template_variable_handler :group, :template_variable_group template_variable_handler :groups, :template_variable_groups template_variable_handler :organization, :template_variable_organization template_variable_handler :add_or_update, :template_variable_add_or_update template_variable_handler :add_or_update_text, :template_variable_add_or_update_text end module ClassMethods public def template_variable_handler(name, handler) handlers = instance_variable_get(:@_template_variable_handlers) handlers ||= [] handlers << [name.to_sym, handler] instance_variable_set(:@_template_variable_handlers, handlers) end def template_variable_handlers instance_variable_get(:@_template_variable_handlers) || [] end end private def set_ckan_basicauth_password self.ckan_basicauth_password = <PASSWORD>(in_ckan_basicauth_password) end def find_template_variable_handler(name) name = name.to_sym handler_def = self.class.template_variable_handlers.find { |handler_name, _| handler_name == name } return nil unless handler_def case handler = handler_def[1] when ::Symbol, ::String method(handler) when ::Proc myself = self lambda { |name, value| myself.instance_exec(name, value, &handler) } else handler end end def template_variable_common(name, value) value[name].to_s end def template_variable_url(name, value) "#{ckan_item_url}/#{value['name']}" end def template_variable_summary(name, value) value['notes'] end def template_variable_class(name, value) value['name'] end def template_variable_new(name, value) in_new_days?(Time.zone.parse(value['metadata_modified']).to_date) ? "new" : nil end def template_variable_created_date(name, value, format = nil) if format.present? I18n.l Time.zone.parse(value['metadata_created']).to_date, format: format.to_sym else I18n.l Time.zone.parse(value['metadata_created']).to_date end end def template_variable_updated_date(name, value, format = nil) if format.present? I18n.l Time.zone.parse(value['metadata_modified']).to_date, format: format.to_sym else I18n.l Time.zone.parse(value['metadata_modified']).to_date end end def template_variable_created_time(name, value, format = nil) if format.present? I18n.l Time.zone.parse(value['metadata_created']), format: format.to_sym else I18n.l Time.zone.parse(value['metadata_created']) end end def template_variable_updated_time(name, value, format = nil) if format.present? I18n.l Time.zone.parse(value['metadata_modified']), format: format.to_sym else I18n.l Time.zone.parse(value['metadata_modified']) end end def template_variable_group(name, value) group = value['groups'].first group ? group['display_name'] : "" end def template_variable_groups(name, value) value['groups'].map { |g| g['display_name'] }.join(", ") end def template_variable_organization(name, value) organization = value['organization'] organization ? organization['title'] : "" end def template_variable_add_or_update(name, value) modified = Time.zone.parse(value['metadata_modified']) rescue Time.zone.at(0) created = Time.zone.parse(value['metadata_created']) rescue Time.zone.at(0) if in_new_days?(created.to_date) "add" elsif in_new_days?(modified.to_date) "update" end end def template_variable_add_or_update_text(name, value) label = template_variable_add_or_update(name, value) if label.present? label = I18n.t("ckan.node.page.#{label}") end label end public def ckan_basicauth_state_options %w(enabled disabled).map { |m| [ I18n.t("ckan.options.ckan_basicauth_state.#{m}"), m ] }.to_a end def ckan_basicauth_enabled? ckan_basicauth_state == 'enabled' end def values uri = URI.parse "#{ckan_url}/api/3/action/package_search?rows=#{ckan_max_docs}&sort=metadata_modified+desc" http = Net::HTTP.new(uri.host, uri.port) http.use_ssl = true if uri.scheme == 'https' req = Net::HTTP::Get.new(uri.path + '?' + uri.query) if ckan_basicauth_enabled? req.basic_auth(ckan_basicauth_username, SS::Crypt.decrypt(ckan_basicauth_password)) end res = begin res = http.request(req) if res.code != '200' res = nil end res rescue nil end if res.blank? # HTTP Error ckan_json_cache_restore else h = JSON.parse(res.body) if h['success'] ckan_json_cache_store res.body h['result']['results'] else # Failure ckan_json_cache_restore end end end def ckan_json_cache_restore if self.ckan_json_cache.present? JSON.parse(self.ckan_json_cache)['result']['results'] else [] end end def ckan_json_cache_store new_json self.update ckan_json_cache: new_json end def render_loop_html(value, html: nil) (html || loop_html).gsub(/\#\{(.*?)\}/) do |m| str = template_variable_get(value, $1) rescue false str == false ? m : str end end def template_variable_get(value, name) handler = find_template_variable_handler(name) return unless handler handler.call(name, value) end end end
shirasagi/opendata
spec/models/sitemap/node_spec.rb
<filename>spec/models/sitemap/node_spec.rb require 'spec_helper' describe Sitemap::Node::Base do subject(:model) { Sitemap::Node::Base } subject(:factory) { :sitemap_node_base } it_behaves_like "mongoid#save" it_behaves_like "mongoid#find" end describe Sitemap::Node::Page do subject(:model) { Sitemap::Node::Page } subject(:factory) { :sitemap_node_page } it_behaves_like "mongoid#save" it_behaves_like "mongoid#find" end
shirasagi/opendata
app/controllers/opendata/agents/nodes/member_controller.rb
<reponame>shirasagi/opendata<gh_stars>1-10 class Opendata::Agents::Nodes::MemberController < ApplicationController include Cms::NodeFilter::View helper Opendata::UrlHelper before_action :set_member, except: :index protected def set_member @member = Opendata::Member.site(@cur_site).where(id: params[:member]).first raise "404" unless @member @member_url = "#{@cur_node.url}#{@member.id}/" end public def index # @items = Opendata::Member.site(@cur_site). # order_by(id: -1). # page(params[:page]). # per(50) raise "404" end def show @datasets = Opendata::Dataset.site(@cur_site).public. where(member_id: @member.id). order_by(released: -1). limit(10) apps ideas end def datasets @datasets = Opendata::Dataset.site(@cur_site).public. where(member_id: @member.id). order_by(released: -1). page(params[:page]). per(50) end def apps @apps = Opendata::App.site(@cur_site).public. where(member_id: @member.id). order_by(released: -1). page(params[:page]). per(50) end def ideas @ideas = Opendata::Idea.site(@cur_site).public. where(member_id: @member.id). order_by(released: -1). page(params[:page]). per(50) end end
shirasagi/opendata
spec/factories/opendata/member_notices.rb
FactoryGirl.define do factory :opendata_member_notice, class: Opendata::MemberNotice do transient do site nil member nil end site_id { site.present? ? site.id : cms_site.id } member_id { member.present? ? member.id : nil } commented_count 11 confirmed { Time.zone.now } end end
shirasagi/opendata
app/controllers/opendata/agents/nodes/idea/idea_category_controller.rb
<gh_stars>1-10 class Opendata::Agents::Nodes::Idea::IdeaCategoryController < ApplicationController include Cms::NodeFilter::View include Opendata::UrlHelper include Opendata::Idea::IdeaFilter private def pages @cur_node.cur_subcategory = params[:name] @item = @cur_node.related_category raise "404" unless @item @cur_node.name = @item.name Opendata::Idea.site(@cur_site).search(site: @cur_site, category_id: @item.id).public end def node_url if name = params[:name] "#{@cur_node.url}#{name}/" else "#{@cur_node.url}" end end public def index @count = pages.size @node_url = node_url default_options = { "s[category_id]" => "#{@item.id}" } @search_path = ->(options = {}) { search_ideas_path(default_options.merge(options)) } @rss_path = ->(options = {}) { build_path("#{search_ideas_path}rss.xml", default_options.merge(options)) } @items = pages.order_by(updated: -1).limit(10) @point_items = pages.order_by(point: -1).limit(10) @comment_items = pages.excludes(commented: nil).order_by(commented: -1).limit(10) @idea_node = @cur_node.parent_idea_node controller.instance_variable_set :@cur_node, @item @tabs = [] if @idea_node.show_tab?("released") @tabs << { name: @idea_node.tab_title("released").presence || I18n.t("opendata.sort_options.released"), id: "released", url: "#{@search_path.call("sort" => "updated")}", pages: @items, rss: "#{@rss_path.call("sort" => "updated")}" } end if @idea_node.show_tab?("popular") @tabs << { name: @idea_node.tab_title("popular").presence || I18n.t("opendata.sort_options.popular"), id: "popular", url: "#{@search_path.call("sort" => "popular")}", pages: @point_items, rss: "#{@rss_path.call("sort" => "popular")}" } end if @idea_node.show_tab?("attention") @tabs << { name: @idea_node.tab_title("attention").presence || I18n.t("opendata.sort_options.attention"), id: "attention", url: "#{@search_path.call("sort" => "attention")}", pages: @comment_items, rss: "#{@rss_path.call("sort" => "attention")}" } end max = 50 @areas = aggregate_areas(max) @tags = aggregate_tags(max) end def rss @items = pages.order_by(updated: -1).limit(100) render_rss @cur_node, @items end end
shirasagi/opendata
lib/mobile/converter.rb
<filename>lib/mobile/converter.rb class Mobile::Converter < String @@tags = { remove: %w( area audio canvas caption col colgroup embed iframe keygen map noscript object optgroup output param progress script source track video), strip: %w( command datalist link rp rt style tbody tfoot thead), div: %w( article aside figure footer header nav section), span: %w( abbr address b bdi bdo code del detail dfn em fieldset figcaption figure hgroup i ins kbd label legend mark menu meter ruby s samp small strong sub summary sup time u var) } public def convert! downcase_tags! remove_comments! remove_cdata_sections! remove_other_namespace_tags! remove_convert_tags! strip_convert_tags! gsub_convert_tags! gsub_img! gsub_q! gsub_wbr! gsub_br! end def s_to_attr(str) str.scan(/\S+?=".+?"/m). map { |s| s.split(/=/).size == 2 ? s.gsub(/"/, "").split(/=/) : nil }. compact.to_h end def attr_to_s(attr) attr.map { |k, v| "#{k}=\"#{v}\"" }.join(" ") end def gsub_tag!(src_tag, dst_tag) self.gsub!(/<(\/?)#{src_tag}>/m) do head = $1 dst_tag.present? ? "<#{head}#{dst_tag}>" : "" end self.gsub!(/<#{src_tag} (.*?)(\/?)>/m) do src_attr = s_to_attr $1.to_s dst_attr = {} tail = $2 if dst_tag.present? dst_attr["id"] = src_attr["id"] if src_attr["id"] dst_attr["class"] = "tag-#{src_tag}" + ( src_attr["class"] ? " #{src_attr['class']}" : "" ) yield src_attr, dst_attr if block_given? "<#{dst_tag} #{attr_to_s(dst_attr)}#{tail}>" else "" end end end def remove_tag!(tag) gsub!(/<#{tag}[ >].*?<\/#{tag}>/m, "") gsub_tag!(tag, "") end def remove_convert_tags! @@tags[:remove].each { |tag| remove_tag!(tag) } end def strip_convert_tags! @@tags[:strip].each { |tag| gsub_tag!(tag, "") } end def gsub_convert_tags! @@tags[:div].each { |tag| gsub_tag!(tag, "div") } @@tags[:span].each { |tag| gsub_tag!(tag, "span") } end def gsub_img! self.gsub!(/<img(.*?)\/?>/) do |match| src_attr = s_to_attr $1.to_s dst_attr ={} ext = File.extname(src_attr["src"].to_s).downcase if ext =~ /^\.(jpeg|jpg|bmp)$/ href = src_attr["src"].presence name = src_attr["alt"].presence || src_attr["title"].presence || href.sub(/.*\//, "") cls = "tag-img" + ( src_attr["class"] ? " #{src_attr['class']}" : "" ) html = name html += %( <a href="#{href}" class="#{cls}" title="#{name}">[#{I18n.t("views.image")}]</a>) if href html else match end end end def gsub_q! self.gsub!("<q>", "\"") self.gsub!("</q>", "\"") end def gsub_wbr! self.gsub!("<wbr>", "<br />") self.gsub!("<wbr />", "<br />") end def gsub_br! self.gsub!("<br/>", "<br />") self.gsub!("<br>", "<br />") end def remove_other_namespace_tags! self.gsub!(/<\/?\w*?\:\w+?.*?>/m, "") end def remove_comments! self.gsub!(/<!--.*?-->/m, "") end def remove_cdata_sections! self.gsub!(/<!\[CDATA\[.*?\]\]>/m, "") end def downcase_tags! self.gsub!(/<(\/?)([A-Z]+)(.*?)(\/?)>/m) do ele = $2 src_attr = s_to_attr $3.to_s dst_attr = {} head = $1 tail = $4 src_attr.each { |k, v| dst_attr[k.downcase] = v } if dst_attr.present? "<#{head}#{ele.downcase} #{attr_to_s(dst_attr)} #{tail}>" else "<#{head}#{ele.downcase}#{tail}>" end end end end
shirasagi/opendata
app/controllers/sys/sites_controller.rb
class Sys::SitesController < ApplicationController include Sys::BaseFilter include Sys::CrudFilter model Sys::Site menu_view "sys/crud/menu" private def set_crumbs @crumbs << [:"sys.site", sys_sites_path] end public def index raise "403" unless @model.allowed?(:edit, @cur_user) @items = @model.allow(:edit, @cur_user). order_by(_id: -1) end def create @item = @model.new get_params raise "403" unless @item.allowed?(:edit, @cur_user) result = @item.save if result cond = { site_id: @item.id, name: "admin", permissions: Cms::Role.permission_names, permission_level: 3 } role = Cms::Role.find_or_create_by cond cms_user = Cms::User.find(@cur_user.id) cms_user.add_to_set cms_role_ids: role.id end render_create result end end
shirasagi/opendata
app/models/job/task.rb
class Job::Task extend SS::Translation include SS::Document include SS::Model::Task include SS::Reference::User #include SS::Reference::Site field :pool, type: String field :class_name, type: String field :args, type: Array field :priority, type: Integer, default: -> { Time.zone.now.to_i } field :at, type: Integer, default: -> { Time.zone.now.to_i } belongs_to :site, class_name: "SS::Site" before_validation :set_name scope :site, ->(site) { where(site_id: (site.nil? ? nil : site.id)) } class << self public def enqueue(entity) model = Job::Task.new(entity) yield model if block_given? model.save! model end def dequeue(name) criteria = Job::Task.where(pool: name, started: nil) criteria = criteria.lte(at: Time.zone.now) criteria = criteria.asc(:priority) criteria.find_and_modify({ '$set' => { started: Time.zone.now }}, new: true) end end private def set_name self.name = 'job:model' if self.name.blank? end end
shirasagi/opendata
spec/factories/cms/pages.rb
<reponame>shirasagi/opendata FactoryGirl.define do trait :cms_page do site_id { cms_site.id } user_id { cms_user.id } name { "#{unique_id}" } filename { "#{name}.html" } route "cms/page" end factory :cms_page, class: Cms::Page, traits: [:cms_page] do # end factory :cms_import_page, class: Cms::ImportPage, traits: [:cms_page] do route "cms/import_page" end end
shirasagi/opendata
spec/features/opendata/agents/nodes/mypage/dataset/my_dataset_spec.rb
<gh_stars>1-10 require 'spec_helper' describe "opendata_agents_nodes_my_dataset", dbscope: :example do let(:site) { cms_site } let(:member) { opendata_member(site: site) } let!(:node_member) { create :opendata_node_member } let!(:node_search_dataset) { create_once :opendata_node_search_dataset, basename: "dataset/search" } let!(:node_dataset) { create :opendata_node_dataset } let!(:upper_html) { '<a href="new/">新規作成</a><table class="opendata-datasets datasets"><tbody>' } let!(:node_mypage) { create :opendata_node_mypage, filename: "mypage" } let!(:node_my_dataset) do create :opendata_node_my_dataset, filename: "#{node_mypage.filename}/dataset", upper_html: upper_html end let!(:node_login) { create :member_node_login, redirect_url: node_my_dataset.url } let(:node_category_folder) { create_once(:cms_node_node, basename: "category") } let!(:category) do create_once( :opendata_node_category, name: "カテゴリー01", filename: "#{node_category_folder.filename}/#{unique_id}", depth: node_category_folder.depth + 1) end let!(:node_area) { create :opendata_node_area, name: "地域A" } let!(:node_search) { create :opendata_node_search_dataset } let(:index_url) { ::URI.parse "http://#{site.domain}#{node_my_dataset.url}" } # let(:new_path) { "#{node_myidea.url}new/" } # let(:show_path) { "#{node_myidea.url}1/" } # let(:edit_path) { "#{node_myidea.url}1/edit/" } # let(:delete_path) { "#{node_myidea.url}1/delete/" } let(:item_name) { "データセット01" } let(:item_name2) { "データセット02" } let(:item_text) { "データセット内容" } before do login_opendata_member(site, node_login, member) end after do logout_opendata_member(site, node_login, member) end describe "#index" do let!(:dataset) { create :opendata_dataset, node: node_dataset, member_id: member.id } it do visit index_url expect(current_path).to eq index_url.path expect(status_code).to eq 200 within "table.opendata-datasets" do expect(page).to have_content dataset.name end end end it "#new_create_edit_delete" do visit index_url click_link "新規作成" expect(status_code).to eq 200 fill_in "item_name", with: item_name fill_in "item_text", with: item_text check category.name click_button "公開保存" expect(status_code).to eq 200 within "table.opendata-datasets" do expect(page).to have_content item_name end click_link item_name expect(status_code).to eq 200 within "table.opendata-dataset" do expect(page).to have_content item_name expect(page).to have_content item_text expect(page).to have_content category.name end click_link "編集" expect(status_code).to eq 200 within "form#item-form" do fill_in "item_name", with: item_name2 end click_button "公開保存" expect(status_code).to eq 200 within "table.opendata-dataset" do expect(page).to have_content item_name2 expect(page).to have_content item_text expect(page).to have_content category.name end click_link "削除" click_button "削除" expect(status_code).to eq 200 expect(current_path).to eq index_url.path within "table.opendata-datasets" do expect(page).not_to have_content item_name2 end end end
shirasagi/opendata
app/models/chorg/main_runner.rb
<filename>app/models/chorg/main_runner.rb class Chorg::MainRunner < Chorg::Runner include Job::Worker private def save_or_collect_errors(entity) return true if entity.save entity.errors.full_messages.each do |message| put_error("#{message}") end false rescue ScriptError, StandardError => e Rails.logger.fatal("got error while saving #{entity.class}(id = #{entity.id})") raise end def delete_entity(entity) entity.delete end def move_users_group(from_id, to_id) substituter = Chorg::Substituter::IdSubstituter.new(from_id, to_id) with_all_entities([Cms::User]) do |user| old_ids = user.group_ids old_names = user.groups.pluck(:name).join(",") new_ids = substituter.call(user.group_ids) if old_ids != new_ids user.group_ids = new_ids save_or_collect_errors(user) new_names = user.groups.pluck(:name).join(",") put_log("moved user's group name=#{user.name}, from=#{old_names}, to=#{new_names}") end end end end
shirasagi/opendata
app/models/concerns/sys/reference/role.rb
<reponame>shirasagi/opendata<filename>app/models/concerns/sys/reference/role.rb module Sys::Reference module Role extend ActiveSupport::Concern included do embeds_ids :sys_roles, class_name: "Sys::Role" permit_params cms_role_ids: [] end public def sys_role_permissions return @sys_role_permissions if @sys_role_permissions @sys_role_permissions ||= {} sys_roles.each do |role| role.permissions.each do |name| @sys_role_permissions[name] = 1 end end @sys_role_permissions end end end
shirasagi/opendata
spec/features/ezine/members_spec.rb
require 'spec_helper' describe "ezine_members" do subject(:site) { cms_site } subject(:node) { create_once :ezine_node } subject(:item) { Ezine::Member.last } subject(:index_path) { ezine_members_path site.host, node } subject(:new_path) { new_ezine_member_path site.host, node } subject(:show_path) { ezine_member_path site.host, node, item } subject(:edit_path) { edit_ezine_member_path site.host, node, item } subject(:delete_path) { delete_ezine_member_path site.host, node, item } it "without login" do visit index_path expect(current_path).to eq sns_login_path end it "without auth" do login_ss_user visit index_path expect(status_code).to eq 403 end context "with auth" do before { login_cms_user } it "#index" do visit index_path expect(current_path).not_to eq sns_login_path end it "#new" do visit new_path within "form#item-form" do fill_in "item[email]", with: "<EMAIL>" find("input[name='item[email_type]'][value='text']").set(true) #choose "テキスト版" find("input[name='item[state]'][value='enabled']").set(true) #choose "配信する" click_button "保存" end expect(status_code).to eq 200 expect(current_path).not_to eq new_path expect(page).not_to have_css("form#item-form") end it "#show" do visit show_path expect(status_code).to eq 200 expect(current_path).not_to eq sns_login_path end it "#edit" do visit edit_path within "form#item-form" do find("input[name='item[email_type]'][value='html']").set(true) #choose "HTML版" find("input[name='item[state]'][value='disabled']").set(true) #choose "配信しない" click_button "保存" end expect(current_path).not_to eq sns_login_path expect(page).not_to have_css("form#item-form") end it "#delete" do visit delete_path within "form" do click_button "削除" end expect(current_path).to eq index_path end context "with column" do before do @column = create(:ezine_column, node: node, name: "text", input_type: "text_field", state: "public") end it "#new" do visit new_path within "form#item-form" do fill_in "item[email]", with: "<EMAIL>" find("input[name='item[email_type]'][value='text']").set(true) #choose "テキスト版" find("input[name='item[state]'][value='enabled']").set(true) #choose "配信する" fill_in "item[in_data][#{@column.id}]", with: "text" click_button "保存" end expect(status_code).to eq 200 expect(current_path).not_to eq new_path expect(page).not_to have_css("form#item-form") end end end end
shirasagi/opendata
app/models/ss/max_file_size.rb
class SS::MaxFileSize extend SS::Translation include SS::Document include Sys::Permission set_permission_name "sys_users", :edit # Upload limit size (Bytes) # 104857600 = 100MB(1024*1024*100) MAX_FILE_SIZE = 104_857_600 STATE_ENABLED = 'enabled'.freeze STATE_DISABLED = 'disabled'.freeze STATES = [STATE_ENABLED, STATE_DISABLED].freeze seqid :id field :name, type: String field :extensions, type: SS::Extensions::Words field :size, type: Integer field :order, type: Integer field :state, type: String permit_params :name, :extensions, :order, :state, :size before_save :normalize_extensions class << self public def find_size(ext) item = where(state: STATE_ENABLED, extensions: ext.downcase).order_by(order: 1, name: 1, _id: -1).first item ||= where(state: STATE_ENABLED, extensions: '*').order_by(order: 1, name: 1, _id: -1).first return item.size if item.present? find_default_limit_size(ext) end def find_default_limit_size(ext) limit_size = SS.config.env.max_filesize_ext[ext.downcase] limit_size ||= SS.config.env.max_filesize limit_size ||= MAX_FILE_SIZE limit_size end def search(params) criteria = self.where({}) return criteria if params.blank? if params[:name].present? criteria = criteria.search_text params[:name] end if params[:keyword].present? criteria = criteria.keyword_in params[:keyword], :name end criteria end end public def state_options STATES.map { |v| [ I18n.t("views.options.state.#{v}"), v ] }.to_a end private def normalize_extensions return if extensions.blank? # normalize extensions # 1. convert to downcase # 2. remove leading period self.extensions = extensions.map(&:downcase).map { |ext| ext.start_with?('.') ? ext[1..-1] : ext } end end
shirasagi/opendata
app/controllers/workflow/search_approvers_controller.rb
class Workflow::SearchApproversController < ApplicationController include Cms::ApiFilter model Cms::User private def group_id default_group_id = @cur_user.group_ids.first return default_group_id if params[:s].blank? return default_group_id if params[:s][:group].blank? group_id = params[:s][:group] case group_id when "false" then false else group_id.to_i end end def group_options groups = Cms::Group.site(@cur_site).each.select do |g| g.allowed?(:read, @cur_user, site: @cur_site) end groups.reduce([]) do |ret, g| ret << [ g.name, g.id ] end.to_a end public def index @level = params[:level] @group_id = group_id @group_options = group_options criteria = @model.site(@cur_site).search(params[:s]) criteria = criteria.in(group_ids: [ @group_id ]) if @group_id @items = criteria.order_by(_id: 1).page(params[:page]).per(50) end end
shirasagi/opendata
config/routes/workflow/routes.rb
<reponame>shirasagi/opendata SS::Application.routes.draw do concern :deletion do get :delete, on: :member post :request_update, on: :member post :approve_update, on: :member post :remand_update, on: :member end concern :branch do post :branch_create, on: :member end content "workflow" do get "/" => redirect { |p, req| "#{req.path}/pages" }, as: :main resources :pages, concerns: :deletion get "/wizard/:id/approver_setting" => "wizard#approver_setting" post "/wizard/:id/approver_setting" => "wizard#approver_setting" get "/wizard/:id" => "wizard#index" post "/wizard/:id" => "wizard#index" end namespace "workflow", path: ".:site/workflow" do get "/" => "main#index" resources :pages, concerns: [:deletion, :branch] get "/search_approvers" => "search_approvers#index" resources :routes, concerns: :deletion get "/wizard/:id/approver_setting" => "wizard#approver_setting" post "/wizard/:id/approver_setting" => "wizard#approver_setting" get "/wizard/:id" => "wizard#index" post "/wizard/:id" => "wizard#index" end end
shirasagi/opendata
app/models/rdf/owl.rb
<filename>app/models/rdf/owl.rb<gh_stars>1-10 # module Rdf::Owl # class Restriction # include SS::Document # # attr_accessor :in_vocab, :in_class # attr_accessor :in_property_namespace, :in_property_prefix, :in_property_name # # field :_id, type: String, default: ->{ property.try(:name) } # field :property, type: Rdf::Extensions::Reference::Prop # field :datatype, type: Rdf::Extensions::Reference::Class # field :cardinality, type: String # field :comments, type: Rdf::Extensions::LangHash # embedded_in :rdf_class, class_name: "Rdf::Class", inverse_of: :property # # permit_params :in_property_namespace, :in_property_prefix, :in_property_name # permit_params :property, :datatype, :cardinality, :comments # permit_params comments: Rdf::Extensions::LangHash::LANGS # # before_validation :set_property # before_validation :set_id # before_validation :set_datatype # # validates :_id, presence: true, uniqueness: true # validates :property, presence: true # validates :datatype, presence: true # validate :validate_property_and_datatype # # before_save :ensure_prop_exist # # class << self # def search(params) # # criteria = self.where({}) # # return criteria if params.blank? # # # # if params[:name].present? # # # criteria = criteria.search_text params[:name] # # words = params[:name] # # words = words.split(/[\s ]+/).uniq.compact.map { |w| /\Q#{Regexp.escape(w)}\E/i } if words.is_a?(String) # # criteria = criteria.all_in(:name => words) # # end # # # # criteria # self.where({}) # end # end # # def comment # comment = nil # if comments.present? # comment = comments.preferred_value # end # if comment.blank? && (prop = property.prop).present? # comment = prop.comments.preferred_value # end # comment # end # # private # def set_property # return if in_property_name.blank? # self.property ||= "#{in_vocab.uri}#{in_property_name}" # end # # def set_id # set_property # name = property.try(:name) # return if name.blank? # self._id ||= name # end # # def set_datatype # return if datatype.present? # # prop = property.try(:prop) # self.datatype ||= prop.ranges.first if prop.present? && prop.ranges.present? # end # # def validate_property_and_datatype # return if property.blank? # return if datatype.blank? # # prop = property.prop # if prop.present? && prop.ranges.present? # unless prop.ranges.include?(datatype) # errors.add(:property, :already_exists_as, range: prop.ranges.first.uri) # end # end # end # # def ensure_prop_exist # prop_id = self.property.prop_id # return if prop_id.present? # # # create rdf prop if rdf prop is not existed. # prop = Rdf::Prop.vocab(in_vocab).where(name: in_property_name).first # if prop.blank? # prop = Rdf::Prop.create({vocab_id: in_vocab.id, # name: in_property_name, # labels: { ja: in_property_name }, # comments: self.comments}) # end # # copy = {} # self.property.each do |k, v| # copy[k] = v # end # copy[Rdf::Extensions::Reference::Prop::PROP_ID_KEY] = prop.id # self.property = copy # end # end # end
shirasagi/opendata
spec/features/opendata/agents/nodes/mypage/mypage_spec.rb
require 'spec_helper' describe "opendata_agents_nodes_mypage", dbscope: :example do let(:site) { cms_site } let!(:node_dataset) { create :opendata_node_dataset } let(:node_mypage) { create :opendata_node_mypage, filename: "mypage", basename: "mypage" } let!(:node_my_dataset) { create :opendata_node_my_dataset, filename: "#{node_mypage.filename}/dataset" } let!(:member) { opendata_member } let!(:member_notice) { create(:opendata_member_notice, member: member) } context "with email and password" do let!(:node_login) { create :member_node_login, redirect_url: node_mypage.url, form_auth: "enabled" } let(:index_url) { ::URI.parse "http://#{site.domain}#{node_mypage.url}" } let(:dataset_url) { ::URI.parse "http://#{site.domain}#{node_mypage.url}dataset/" } let(:show_notice_url) { ::URI.parse "http://#{site.domain}#{node_mypage.url}notice/show.html" } let(:confirm_notice_url) { ::URI.parse "http://#{site.domain}#{node_mypage.url}notice/confirm.html" } let(:login_url) { ::URI.parse "http://#{site.domain}#{node_login.url}login.html" } let(:logout_url) { ::URI.parse "http://#{site.domain}#{node_login.url}logout.html" } it do visit index_url expect(status_code).to eq 200 expect(current_path).to eq login_url.path within "form.form-login" do fill_in "item[email]", with: member.email fill_in "item[password]", with: <PASSWORD> click_button "ログイン" end expect(status_code).to eq 200 expect(current_path).to eq dataset_url.path visit logout_url expect(status_code).to eq 200 expect(current_path).to eq login_url.path end it do visit index_url expect(status_code).to eq 200 expect(current_path).to eq login_url.path within "form.form-login" do fill_in "item[email]", with: member.email fill_in "item[password]", with: <PASSWORD> click_button "ログイン" end expect(status_code).to eq 200 expect(current_path).to eq dataset_url.path visit show_notice_url expect(status_code).to eq 200 expect(page).to have_link(member_notice.commented_count) visit confirm_notice_url expect(status_code).to eq 200 member_notice.reload expect(member_notice.commented_count).to eq 0 end end end
shirasagi/opendata
app/controllers/chorg/run_controller.rb
<reponame>shirasagi/opendata<gh_stars>1-10 class Chorg::RunController < ApplicationController include Cms::BaseFilter # include Cms::CrudFilter before_action :prepend_current_view_path before_action :append_view_paths before_action :set_item model Chorg::Revision navi_view "cms/main/navi" private def set_crumbs @crumbs << [:"chorg.revision", controller: :revisions, action: :index] end def prepend_current_view_path prepend_view_path "app/views/#{params[:controller]}" end def append_view_paths append_view_path "app/views/ss/crud" end def set_item @item = @model.find params[:rid] end def fix_params { cur_site: @cur_site } end def add_job_id(array, id) if array.blank? [id] else copy = Array.new(array) copy << id copy end end public def confirmation end def run begin add_group_to_site = params[:item][:add_newly_created_group_to_site].to_i @job = Chorg::Runner.call_async(@cur_site.host, @cur_user.id, @item.name, add_group_to_site, params[:type]) do |job| job.site_id = @cur_site.id end @item.job_ids = add_job_id(@item.job_ids, @job.id) rescue => e Rails.logger.error("#{e.class} (#{e.message}):\n #{e.backtrace.join("\n ")}") @item.errors.add :base, e.to_s end if @item.errors.empty? && @item.save SS::RakeRunner.run_async "job:run", "RAILS_ENV=#{Rails.env}" respond_to do |format| format.html do redirect_to({ controller: :revisions, action: :show, id: @item.id }, { notice: t("chorg.messages.job_started") }) end format.json { head :no_content } end else @job.try(:delete) respond_to do |format| format.html { render file: :confirmation, status: :unprocessable_entity } format.json { render json: @item.errors.full_messages, status: :unprocessable_entity } end end end end
shirasagi/opendata
app/models/opendata/app.rb
class Opendata::App include Cms::Model::Page include ::Workflow::Addon::Approver include Opendata::Addon::Appfile include Opendata::Addon::Category include Opendata::Addon::Area include Opendata::Addon::Dataset include Opendata::Reference::Member include Opendata::Common include Cms::Addon::Release include Contact::Addon::Page include Cms::Addon::RelatedPage include Cms::Addon::GroupPermission include Workflow::MemberPermission set_permission_name "opendata_apps" field :point, type: Integer, default: "0" field :text, type: String field :appurl, type: String field :tags, type: SS::Extensions::Words field :license, type: String field :executed, type: Integer has_many :points, primary_key: :app_id, class_name: "Opendata::AppPoint", dependent: :destroy embeds_ids :datasets, class_name: "Opendata::Dataset" has_many :ideas, primary_key: :app_id, class_name: "Opendata::Idea" permit_params :text, :appurl, :license, :dataset_ids, :tags, tags: [] validates :text, presence: true validates :category_ids, presence: true validates :license, presence: true validate :validate_appurl before_save :seq_filename, if: ->{ basename.blank? } default_scope ->{ where(route: "opendata/app") } public def point_url get_url(url, "/point.html") end def point_members_url get_url(url, "/point/members.html") end def app_ideas_url get_url(url, "/ideas/show.html") end def zip_url get_url(url, "/zip") end def executed_show_url get_url(url, "/executed/show.html") end def executed_add_url get_url(url, "/executed/add.html") end def full_screen_url get_url(url, "/full/") end def file_text_url get_url(url, "/file_text/") end def file_index_url get_url(url, "/file_index/") end def contact_present? return false if member_id.present? super end def create_zip zip_filename = self.class.zip_dir.join("#{id}.zip").to_s File.unlink(zip_filename) if File.exist?(zip_filename) Zip::Archive.open(zip_filename, Zip::CREATE) do |ar| appfiles.each do |appfile| ar.add_file(appfile.filename.encode('cp932', invalid: :replace, undef: :replace, replace: '_'), appfile.file.path) end end return zip_filename end private def validate_filename @basename.blank? ? nil : super end def seq_filename self.filename = dirname ? "#{dirname}#{id}.html" : "#{id}.html" end def validate_appurl if self.appurl.present? if self.appfiles.present? errors.add :appurl, I18n.t("opendata.errors.messages.validate_appurl") return end end end class << self public def to_app_path(path) suffix = %w(/point.html /point/members.html /ideas/show.html /zip /executed/show.html /executed/add.html /full/ /full/index.html).find { |suffix| path.end_with? suffix } if suffix.present? path[0..(path.length - suffix.length - 1)] + '.html' else path.sub(/\/file_text\/.*$/, '.html').sub(/\/file_index\/.*$/, '.html') end end def sort_options [ [I18n.t("opendata.sort_options.released"), "released"], [I18n.t("opendata.sort_options.popular"), "popular"], [I18n.t("opendata.sort_options.attention"), "attention"] ] end def sort_hash(sort) case sort when "released" { released: -1, _id: -1 } when "popular" { point: -1, _id: -1 } when "attention" { executed: -1, _id: -1 } else return { released: -1 } if sort.blank? { sort.sub(/ .*/, "") => (sort =~ /-1$/ ? -1 : 1) } end end def aggregate_field(name, opts = {}) Opendata::Common.get_aggregate_field(self, name, opts) end def aggregate_array(name, opts = {}) Opendata::Common.get_aggregate_array(self, name, opts) end def search_params params = [] params << :keyword params << :tag params << :area_id params << :category_id params << :license params << :option params end def search_options %w(all_keywords any_keywords any_conditions).map do |w| [I18n.t("opendata.search_options.#{w}"), w] end end def search(params) criteria = self.where({}) return criteria if params.blank? SEARCH_HANDLERS.each do |handler| criteria = send(handler, params, criteria) end criteria end def zip_dir dir = Rails.root.join('tmp', 'opendata') FileUtils.mkdir_p(dir) unless Dir.exist?(dir) dir end private SEARCH_HANDLERS = [ :search_keyword, :search_name, :search_tag, :search_area_id, :search_category_id, :search_license, :search_poster ].freeze def search_keyword(params, criteria) if params[:keyword].present? option = params[:option].presence || 'all_keywords' method = option == 'all_keywords' ? 'and' : 'any' criteria = criteria.keyword_in params[:keyword], :name, :text, "appfiles.name", "appfiles.filename", "appfiles.text", method: method end criteria end def search_name(params, criteria) criteria = criteria.keyword_in params[:keyword], :name if params[:name].present? criteria end def search_tag(params, criteria) operator = params[:option].presence == 'any_conditions' ? "$or" : "$and" criteria = criteria.where(operator => [ tags: params[:tag] ]) if params[:tag].present? criteria end def search_area_id(params, criteria) operator = params[:option].presence == 'any_conditions' ? "$or" : "$and" criteria = criteria.where(operator => [ area_ids: params[:area_id].to_i ]) if params[:area_id].present? criteria end def search_category_id(params, criteria) return criteria if params[:category_id].blank? category_id = params[:category_id].to_i category_node = Cms::Node.site(params[:site]).public.where(id: category_id).first return criteria if category_node.blank? category_ids = [ category_id ] category_node.all_children.public.each do |child| category_ids << child.id end operator = params[:option].presence == 'any_conditions' ? "$or" : "$and" criteria.where(operator => [ category_ids: { '$in' => category_ids } ]) end def search_license(params, criteria) operator = params[:option].presence == 'any_conditions' ? "$or" : "$and" criteria = criteria.where(operator => [ license: params[:license] ]) if params[:license].present? criteria end def search_poster(params, criteria) if params[:poster].present? cond = {} cond = { :workflow_member_id.exists => true } if params[:poster] == "member" cond = { :workflow_member_id => nil } if params[:poster] == "admin" operator = params[:option].presence == 'any_conditions' ? "$or" : "$and" criteria = criteria.where(operator => cond) end criteria end end end
shirasagi/opendata
app/controllers/facility/agents/nodes/search_controller.rb
class Facility::Agents::Nodes::SearchController < ApplicationController include Cms::NodeFilter::View helper Map::MapHelper append_view_path "app/views/facility/agents/addons/search_setting/view" append_view_path "app/views/facility/agents/addons/search_result/view" private def set_query @keyword = params[:keyword] @category_ids = params[:category_ids].select(&:present?).map(&:to_i) rescue [] @service_ids = params[:service_ids].select(&:present?).map(&:to_i) rescue [] @location_ids = params[:location_ids].select(&:present?).map(&:to_i) rescue [] @q_category = @category_ids.present? ? { category_ids: @category_ids } : {} @q_service = @service_ids.present? ? { service_ids: @service_ids } : {} @q_location = @location_ids.present? ? { location_ids: @location_ids } : {} @categories = Facility::Node::Category.in(_id: @category_ids) @services = Facility::Node::Service.in(_id: @service_ids) @locations = Facility::Node::Location.in(_id: @location_ids) end def set_items @items = Facility::Node::Page.site(@cur_site).public. where(@cur_node.condition_hash). search(name: @keyword). in(@q_category). in(@q_service). in(@q_location). order_by(name: 1) end def set_markers @items = [] @markers = [] images = SS::File.all.map {|image| [image.id, image.url]}.to_h Facility::Map.site(@cur_site).public.each do |map| parent_path = ::File.dirname(map.filename) item = Facility::Node::Page.site(@cur_site).public. where(@cur_node.condition_hash). in_path(parent_path). search(name: @keyword). in(@q_category). in(@q_service). in(@q_location).first next unless item @items << item categories = item.categories.entries category_ids = categories.map(&:id) image_id = categories.map(&:image_id).first image_url = images[image_id] marker_info = view_context.render_marker_info(item) map.map_points.each do |point| point[:facility_id] = item.id point[:html] = marker_info point[:category] = category_ids point[:image] = image_url if image_url.present? @markers.push point end end @items.sort_by!(&:name) end def set_filter_items @filter_categories = @cur_node.st_categories.in(_id: @items.map(&:category_ids).flatten) @filter_locations = @cur_node.st_locations.entries.select{ |l| l.center_point[:loc].present? } @focus_options = @filter_locations.map do |l| opts = {} opts.merge!({ "data-zoom-level" => l.center_point[:zoom_level] }) if l.center_point[:zoom_level] [l.name, l.center_point[:loc].join(","), opts] end @focus_options.unshift [I18n.t("facility.select_location"), ""] end public def index set_query render :index, locals: { search_path: "./map.html" } end def map set_query set_markers set_filter_items @current = "map" render :map end def result set_query set_items @current = "result" @items = @items.page(params[:page]). per(@cur_node.limit) render :result end def map_all params[:category_ids] = nil params[:service_ids] = nil params[:location_ids] = nil map end end
shirasagi/opendata
app/models/concerns/ckan/addon/status.rb
module Ckan::Addon module Status extend ActiveSupport::Concern extend SS::Addon included do field :ckan_url, type: String field :ckan_basicauth_state, type: String field :ckan_basicauth_username, type: String field :ckan_basicauth_password, type: String field :ckan_status, type: String field :ckan_value_url, type: String field :ckan_value_cache, type: Integer attr_accessor :in_ckan_basicauth_password permit_params :ckan_url, :ckan_basicauth_state, :ckan_basicauth_username, :in_ckan_basicauth_password permit_params :ckan_status, :ckan_value_url before_validation :set_ckan_basicauth_password, if: ->{ in_ckan_basicauth_password.present? } validates :ckan_url, format: /\Ahttps?:\/\// validates :ckan_basicauth_state, inclusion: { in: %w(enabled disabled) } validates :ckan_status, inclusion: { in: %w(dataset tag group related_item organization) } end private def set_ckan_basicauth_password self.ckan_basicauth_password = SS::Crypt.encrypt(in_ckan_basicauth_password) end def send_request uri = URI.parse ckan_url + '/api/3/action/' + action_name http = Net::HTTP.new(uri.host, uri.port) http.use_ssl = true if uri.scheme == 'https' req = Net::HTTP::Get.new(uri.path) if ckan_basicauth_enabled? req.basic_auth(ckan_basicauth_username, SS::Crypt.decrypt(ckan_basicauth_password)) end http.request(req) end def raw_value res = send_request return nil if res.code != '200' h = JSON.parse(res.body) return nil unless h['success'] h['result'].count end def refresh_ckan_value_cache value = raw_value ckan_value_cache_store(value) unless value.nil? end public def ckan_status_options %w(dataset tag group related_item organization).map { |m| [ I18n.t("ckan.options.ckan_status.#{m}"), m ] }.to_a end def ckan_basicauth_state_options %w(enabled disabled).map { |m| [ I18n.t("ckan.options.ckan_basicauth_state.#{m}"), m ] }.to_a end def ckan_basicauth_enabled? ckan_basicauth_state == 'enabled' end def value begin refresh_ckan_value_cache rescue end ckan_value_cache_restore end def action_name { 'dataset' => 'package_list', 'tag' => 'tag_list', 'group' => 'group_list', 'related_item' => 'related_list', 'organization' => 'organization_list' }[ckan_status] end def ckan_value_cache_restore self.ckan_value_cache || 'NaN' end def ckan_value_cache_store(new_value) self.update ckan_value_cache: new_value end end end
shirasagi/opendata
config/routes/voice/routes.rb
<filename>config/routes/voice/routes.rb SS::Application.routes.draw do Voice::Initializer concern :deletion do get :delete, on: :member end concern :file do get :file, on: :member end concern :download do get :download, on: :collection end namespace "voice", path: ".voice" do get "/*path" => "main#index", format: false get "/" => "main#index", format: false end namespace("voice", as: "voice", path: ".:site/voice", module: "voice") do resources :files, concerns: [:download, :deletion, :file], except: [:create, :edit, :new, :update] resources :error_files, concerns: [:download, :deletion, :file], except: [:create, :edit, :new, :update] end end
shirasagi/opendata
app/models/concerns/cms/addon/tabs.rb
<gh_stars>1-10 module Cms::Addon module Tabs extend ActiveSupport::Concern extend SS::Addon included do field :conditions, type: SS::Extensions::Words field :limit, type: Integer, default: 8 field :new_days, type: Integer, default: 1 permit_params :conditions, :limit, :new_days before_validation :validate_conditions end public def limit value = self[:limit].to_i (value < 1 || 1000 < value) ? 100 : value end def new_days value = self[:new_days].to_i (value < 0 || 30 < value) ? 30 : value end def in_new_days?(date) date + new_days > Time.zone.now end private def validate_conditions self.conditions = conditions.map do |m| m.strip.sub(/^\w+:\/\/.*?\//, "").sub(/^\//, "").sub(/\/$/, "") end.compact.uniq end end end
shirasagi/opendata
config/routes/inquiry/routes.rb
<gh_stars>1-10 SS::Application.routes.draw do Inquiry::Initializer concern :deletion do get :delete, on: :member end concern :download do get :download, on: :collection end content "inquiry" do get "/" => redirect { |p, req| "#{req.path}/columns" }, as: :main resources :nodes, concerns: :deletion resources :forms, concerns: :deletion resources :columns, concerns: :deletion resources :answers, concerns: [:deletion, :download], only: [:index, :show, :destroy] get "results" => "results#index", as: :results end node "inquiry" do get "form/(index.:format)" => "public#new", cell: "nodes/form" get "form/sent.html" => "public#sent", cell: "nodes/form" get "form/results.html" => "public#results", cell: "nodes/form" post "form/confirm.html" => "public#confirm", cell: "nodes/form" post "form/create.html" => "public#create", cell: "nodes/form" get "node/(index.:format)" => "public#index", cell: "nodes/node" end end
shirasagi/opendata
spec/factories/ezine/node.rb
FactoryGirl.define do factory :ezine_node, class: Cms::Node do site_id { cms_site.id } user_id { cms_user.id } name 'title' filename 'magazine' route 'magazine' end end
shirasagi/opendata
spec/features/opendata/dataset/resources_spec.rb
require 'spec_helper' describe "opendata_datasets", type: :feature, dbscope: :example do let(:site) { cms_site } let(:node) { create_once :opendata_node_dataset, name: "opendata_dataset" } let!(:node_search) { create_once :opendata_node_search_dataset } let!(:license_logo_file_path) { Rails.root.join("spec", "fixtures", "ss", "logo.png").to_s } let!(:license_logo_file) { Fs::UploadedFile.create_from_file(license_logo_file_path, basename: "spec") } let!(:license) { create(:opendata_license, site: site, file: license_logo_file) } let(:dataset) { create(:opendata_dataset, node: node) } let(:index_path) { opendata_dataset_resources_path site.host, node, dataset.id } it "without login" do visit index_path expect(current_path).to eq sns_login_path end it "without auth" do login_ss_user visit index_path expect(status_code).to eq 403 end context "with auth" do let(:resource_file_path) { "#{Rails.root}/spec/fixtures/opendata/shift_jis.csv" } let(:resource_tsv_path) { "#{Rails.root}/spec/fixtures/opendata/shift_jis.csv" } let(:new_path) { new_opendata_dataset_resource_path site.host, node, dataset.id } before { login_cms_user } describe "#index" do it do visit index_path expect(status_code).to eq 200 expect(current_path).to eq index_path end end describe "#new" do it do visit new_path within "form#item-form" do attach_file "item[in_file]", resource_file_path fill_in "item[name]", with: "#{unique_id}" select license.name, from: "item_license_id" attach_file "item[in_tsv]", resource_tsv_path click_button "保存" end expect(status_code).to eq 200 expect(current_path).not_to eq new_path expect(page).not_to have_css("form#item-form") end end context "with item" do let(:item) { dataset.resources.new(attributes_for(:opendata_resource)) } let(:show_path) { opendata_dataset_resource_path site.host, node, dataset, item } let(:edit_path) { edit_opendata_dataset_resource_path site.host, node, dataset, item } let(:delete_path) { delete_opendata_dataset_resource_path site.host, node, dataset, item } let(:download_path) { opendata_dataset_resource_file_path site.host, node, dataset, item } let(:download_tsv_path) { opendata_dataset_resource_tsv_path site.host, node, dataset, item } let(:content_path) { opendata_dataset_resource_content_path site.host, node, dataset, item } before do Fs::UploadedFile.create_from_file(resource_file_path, basename: "spec") do |f1| Fs::UploadedFile.create_from_file(resource_tsv_path, basename: "spec") do |f2| item.in_file = f1 item.license_id = license.id item.in_tsv = f2 item.save! end end item.reload end describe "#show" do it do visit show_path expect(status_code).to eq 200 expect(current_path).to eq show_path end end describe "#edit" do it do visit edit_path within "form#item-form" do fill_in "item[name]", with: "#{item.name}-modify" fill_in "item[text]", with: "sample-#{unique_id}" click_button "保存" end expect(current_path).to eq show_path expect(page).not_to have_css("form#item-form") end end describe "#delete" do it do visit delete_path within "form" do click_button "削除" end expect(current_path).to eq index_path end end describe "#download" do it do visit download_path expect(status_code).to eq 200 expect(current_path).to eq download_path end end describe "#download_tsv" do it do visit download_tsv_path expect(status_code).to eq 404 end end describe "#content" do it do visit content_path expect(status_code).to eq 200 expect(current_path).to eq content_path end end end context "with item having tsv" do let(:resource_file_path) { "#{Rails.root}/spec/fixtures/opendata/test.json" } let(:item) { dataset.resources.new(attributes_for(:opendata_resource)) } let(:download_tsv_path) { opendata_dataset_resource_tsv_path site.host, node, dataset, item } before do Fs::UploadedFile.create_from_file(resource_file_path, basename: "spec") do |f1| Fs::UploadedFile.create_from_file(resource_tsv_path, basename: "spec") do |f2| item.in_file = f1 item.license_id = license.id item.in_tsv = f2 item.save! end end item.reload end describe "#download_tsv" do it do visit download_tsv_path expect(status_code).to eq 200 expect(current_path).to eq download_tsv_path end end end context "when non-tsv file is given for tsv-file" do let(:resource_file_path) { "#{Rails.root}/spec/fixtures/opendata/test.json" } let(:resource_tsv_path) { Rails.root.join("spec", "fixtures", "ss", "logo.png").to_s } describe "new and show" do it do visit new_path within "form#item-form" do attach_file "item[in_file]", resource_file_path fill_in "item[name]", with: "#{unique_id}" select license.name, from: "item_license_id" attach_file "item[in_tsv]", resource_tsv_path click_button "保存" end expect(status_code).to eq 200 expect(current_path).to eq index_path within "div#errorExplanation" do expect(page).to have_content("問題が発生しました。") expect(page).to have_content("プレビュー用データは不正な値です。") end end end end context "when preview file is given even if upload file is csv/tsv" do let(:resource_file_path) { "#{Rails.root}/spec/fixtures/opendata/shift_jis.csv" } let(:resource_tsv_path) { "#{Rails.root}/spec/fixtures/opendata/shift_jis-2.csv" } describe "new and show" do it do visit new_path within "form#item-form" do fill_in "item[name]", with: "#{unique_id}" select license.name, from: "item_license_id" attach_file "item[in_tsv]", resource_tsv_path attach_file "item[in_file]", resource_file_path click_button "保存" end expect(status_code).to eq 200 dataset.reload item = dataset.resources.first show_path = opendata_dataset_resource_path site.host, node, dataset, item expect(current_path).to eq show_path # acquire that tsv file is not saved. expect(item.tsv).to be_nil end end end end end
shirasagi/opendata
spec/features/workflow/routes_spec.rb
require 'spec_helper' describe "workflow_routes", dbscope: :example do let!(:site) { cms_site } let!(:user) { cms_user } let!(:group) { cms_group } let(:index_path) { workflow_routes_path site.host } let(:new_path) { new_workflow_route_path site.host } it "without login" do visit index_path expect(current_path).to eq sns_login_path end it "without auth" do login_ss_user visit index_path expect(status_code).to eq 403 end context "with auth" do before { login_cms_user } describe "#index" do it do visit index_path expect(current_path).not_to eq sns_login_path end end describe "#new", js: true do it do visit new_path within "form#item-form" do fill_in "item[name]", with: "sample" end click_link "グループを選択する" wait_for_cbox within "div#ajax-box table.index" do click_link group.name end within "dl.workflow-level-1" do click_link "承認者を選択する" end # wait a while to load contents of dialog wait_for_cbox within "div#ajax-box table.index" do click_link user.name end within "form#item-form" do click_button "保存" end expect(status_code).to eq 200 expect(page).not_to have_css("form#item-form") end end end end
shirasagi/opendata
lib/voice/japanese_text_reconstructor.rb
# this class divides too long text, and also this class joins too small text. class Voice::JapaneseTextReconstructor include Enumerable SEPARATOR = /[\s 。、]+/ PAUSE_TEXT = '。' def initialize(texts, max_length) @texts = texts @max_length = max_length end def each # setup enumerable e = @texts.lazy # at first, split text into micro size. e = e.map do |text| chunk_text text end e = e.flat_map do |text| text end # and then slice into appropriate length. length = 0 e = e.slice_before do |text| length += text.length if length > @max_length length = text.length true else false end end e = e.map do |text_array| text_array.join(PAUSE_TEXT) + PAUSE_TEXT end # finally, yields text which has appropriate length e.each do |text| yield text end end private def chunk_text(text) text.split(/[\s 。、]+/) end end
shirasagi/opendata
spec/factories/inquiry/columns.rb
<filename>spec/factories/inquiry/columns.rb<gh_stars>1-10 FactoryGirl.define do factory :inquiry_column_name, class: Inquiry::Column do name "お名前" input_type "text_field" required "required" html "<p>お名前を入力してくだ さい。</p>" order 10 end factory :inquiry_column_optional, class: Inquiry::Column do name "企業・団体名" input_type "text_field" required "optional" html "<p>企業・団体名を入力してくだ さい。</p>" order 20 end factory :inquiry_column_email, class: Inquiry::Column do name "メールアドレス" input_type "email_field" required "required" input_confirm "enabled" html "<p>半角 英数字記号で入力してください。<br />\nお問い合わせへの返信に利用させていただきます。</p>" order 30 end factory :inquiry_column_radio, class: Inquiry::Column do name "性別" input_type "radio_button" required "optional" html "<p>性別を選択して ください。</p>" select_options ["男性", "女性"] order 40 end factory :inquiry_column_select, class: Inquiry::Column do name "年齢" input_type "select" required "optional" html "<p>年齢を選択してください。</p>" select_options ["10代", "20代", "30代", "40代", "50代", "60代", "70代", "80代"] order 50 end factory :inquiry_column_check, class: Inquiry::Column do name "お問い合わせ区分" input_type "check_box" required "optional" html "<p>お問い合わせ内容の区分を選択してください。</p>" select_options ["市政について", "ご意見・ご要望", "申請について", "その他"] order 60 end end
shirasagi/opendata
app/models/event/page.rb
class Event::Page include Cms::Model::Page include Workflow::Addon::Branch include Workflow::Addon::Approver include Cms::Addon::Meta include Cms::Addon::Body include Cms::Addon::File include Category::Addon::Category include Cms::Addon::ParentCrumb include Event::Addon::Body include Cms::Addon::AdditionalInfo include Event::Addon::Date include Map::Addon::Page include Cms::Addon::RelatedPage include Cms::Addon::Release include Cms::Addon::ReleasePlan include Cms::Addon::GroupPermission include History::Addon::Backup set_permission_name "event_pages" before_save :seq_filename, if: ->{ basename.blank? } default_scope ->{ where(route: "event/page") } private def validate_filename (@basename && @basename.blank?) ? nil : super end def seq_filename self.filename = dirname ? "#{dirname}#{id}.html" : "#{id}.html" end end
shirasagi/opendata
app/models/job/master_service.rb
require 'English' class Job::MasterService class << self public def run(config = nil) config ||= SS.config.job.default num_workers = config["num_workers"] if num_workers == 0 # execute jobs in-place Job::Service.run config return true end # execute jobs in external process start_slave_in_external_process(config) true end private def start_slave_in_external_process(config) name = config['name'] num_workers = config["num_workers"] cmd = "bundle exec rake job:worker RAILS_ENV=#{Rails.env}" cmd = "#{cmd} config=#{name}" unless name.blank? threads = [] num_workers.times do threads << Thread.new do Thread.pass Rails.logger.debug("system(#{cmd})") system(cmd) end end threads.each do |t| t.join rescue nil end end end end
shirasagi/opendata
app/controllers/chorg/results_controller.rb
class Chorg::ResultsController < ApplicationController include Cms::BaseFilter include Cms::CrudFilter before_action :filter_permission before_action :set_revision model Job::Log navi_view "cms/main/navi" private def set_crumbs @crumbs << [:"chorg.revision", controller: :revisions, action: :index] end def filter_permission raise "403" unless Cms::User.allowed?(:edit, @cur_user, site: @cur_site) end def set_revision @revision = Chorg::Revision.find(params[:rid]) raise "403" unless @revision.allowed?(:read, @cur_user, site: @cur_site, node: @cur_node) end public def index @items = @model.site(@cur_site). in(job_id: @revision.job_ids). order_by(_id: -1). page(params[:page]).per(50) end def show render end end
shirasagi/opendata
app/models/opendata/node.rb
module Opendata::Node class Base include Cms::Model::Node include Cms::Addon::GroupPermission default_scope ->{ where(route: /^opendata\//) } end class Category include Cms::Model::Node include Cms::Addon::NodeSetting include Cms::Addon::Release include Cms::Addon::Meta include Cms::Addon::GroupPermission include History::Addon::Backup default_scope ->{ where(route: "opendata/category") } end class Area include Cms::Model::Node include Cms::Addon::NodeSetting include Cms::Addon::Release include Cms::Addon::Meta include Cms::Addon::GroupPermission include History::Addon::Backup attr_accessor :count default_scope ->{ where(route: "opendata/area") } end class Dataset include Cms::Model::Node include Opendata::Addon::ListNodeSetting include Cms::Addon::Release include Cms::Addon::Meta include Opendata::Addon::DatasetPageSetting include Opendata::Addon::CategorySetting include Cms::Addon::GroupPermission include History::Addon::Backup default_scope ->{ where(route: "opendata/dataset") } end class DatasetCategory include Cms::Model::Node include Cms::Addon::NodeSetting include Cms::Addon::Release include Cms::Addon::Meta include Opendata::DatasetChildNode include Cms::Addon::GroupPermission include History::Addon::Backup default_scope ->{ where(route: "opendata/dataset_category") } end class SearchDatasetGroup include Cms::Model::Node include Opendata::Addon::ListNodeSetting include Cms::Addon::Release include Cms::Addon::Meta include Opendata::DatasetChildNode include Cms::Addon::GroupPermission include History::Addon::Backup default_scope ->{ where(route: "opendata/search_dataset_group") } end class SearchDataset include Cms::Model::Node include Opendata::Addon::ListNodeSetting include Cms::Addon::Release include Cms::Addon::Meta include Opendata::DatasetChildNode include Cms::Addon::GroupPermission include History::Addon::Backup default_scope ->{ where(route: "opendata/search_dataset") } end class Sparql include Cms::Model::Node include Cms::Addon::NodeSetting include Cms::Addon::Release include Cms::Addon::Meta include Cms::Addon::GroupPermission include History::Addon::Backup default_scope ->{ where(route: "opendata/sparql") } end class Api include Cms::Model::Node include Cms::Addon::NodeSetting include Cms::Addon::Release include Cms::Addon::Meta include Cms::Addon::GroupPermission include History::Addon::Backup default_scope ->{ where(route: "opendata/api") } end class App include Cms::Model::Node include Opendata::Addon::ListNodeSetting include Cms::Addon::Release include Cms::Addon::Meta include Opendata::Addon::AppPageSetting include Opendata::Addon::CategorySetting include Cms::Addon::GroupPermission include History::Addon::Backup default_scope ->{ where(route: "opendata/app") } end class AppCategory include Cms::Model::Node include Cms::Addon::NodeSetting include Cms::Addon::Release include Cms::Addon::Meta include Opendata::AppChildNode include Cms::Addon::GroupPermission include History::Addon::Backup default_scope ->{ where(route: "opendata/app_category") } end class SearchApp include Cms::Model::Node include Opendata::Addon::ListNodeSetting include Cms::Addon::Release include Cms::Addon::Meta include Opendata::AppChildNode include Cms::Addon::GroupPermission include History::Addon::Backup default_scope ->{ where(route: "opendata/search_app") } end class Idea include Cms::Model::Node include Opendata::Addon::ListNodeSetting include Cms::Addon::Release include Cms::Addon::Meta include Opendata::Addon::IdeaPageSetting include Opendata::Addon::CategorySetting include Cms::Addon::GroupPermission include History::Addon::Backup default_scope ->{ where(route: "opendata/idea") } end class IdeaCategory include Cms::Model::Node include Cms::Addon::NodeSetting include Cms::Addon::Release include Cms::Addon::Meta include Opendata::IdeaChildNode include Cms::Addon::GroupPermission include History::Addon::Backup default_scope ->{ where(route: "opendata/idea_category") } end class SearchIdea include Cms::Model::Node include Opendata::Addon::ListNodeSetting include Cms::Addon::Release include Cms::Addon::Meta include Opendata::IdeaChildNode include Cms::Addon::GroupPermission include History::Addon::Backup default_scope ->{ where(route: "opendata/search_idea") } end class Mypage include Cms::Model::Node include Cms::Addon::NodeSetting include Cms::Addon::Release include Cms::Addon::Meta include Cms::Addon::GroupPermission include History::Addon::Backup default_scope ->{ where(route: "opendata/mypage") } end class Member include Cms::Model::Node include Cms::Addon::NodeSetting include Cms::Addon::Release include Cms::Addon::Meta include Cms::Addon::GroupPermission include History::Addon::Backup default_scope ->{ where(route: "opendata/member") } end class MyProfile include Cms::Model::Node include Cms::Addon::NodeSetting include Cms::Addon::Release include Cms::Addon::Meta include Cms::Addon::GroupPermission include History::Addon::Backup default_scope ->{ where(route: "opendata/my_profile") } end class MyDataset include Cms::Model::Node include Cms::Addon::NodeSetting include Opendata::Addon::MyDatasetList include Cms::Addon::Release include Cms::Addon::Meta include Cms::Addon::GroupPermission include History::Addon::Backup default_scope ->{ where(route: "opendata/my_dataset") } end class MyApp include Cms::Model::Node include Cms::Addon::NodeSetting include Opendata::Addon::MyAppList include Cms::Addon::Release include Cms::Addon::Meta include Cms::Addon::GroupPermission include History::Addon::Backup default_scope ->{ where(route: "opendata/my_app") } end class MyIdea include Cms::Model::Node include Cms::Addon::NodeSetting include Opendata::Addon::MyIdeaList include Cms::Addon::Release include Cms::Addon::Meta include Cms::Addon::GroupPermission include History::Addon::Backup default_scope ->{ where(route: "opendata/my_idea") } end end
shirasagi/opendata
app/models/ezine/page.rb
<filename>app/models/ezine/page.rb class Ezine::Page include Cms::Model::Page include Ezine::Addon::Body include Ezine::Addon::DeliverPlan include Cms::Addon::Release include Cms::Addon::ReleasePlan include Cms::Addon::GroupPermission field :test_delivered, type: DateTime field :completed, type: Boolean, default: false embeds_many :results, class_name: "Ezine::Result" before_save :seq_filename, if: ->{ basename.blank? } default_scope ->{ where(route: "ezine/page") } public # Get members to deliver this page. # # Return an empty array when a delivery is completed. # # Return members array not included in sent logs when a delivery is # incompleted. # # このページを配信するべきメンバー一覧を取得する。 # # 配信が完了していれば空の配列が返る。 # # 配信が完了していない場合は配信ログが存在しないメンバー一覧が返る。 # # @return [Array<Ezine::Member>] # Members to deliver. # # 配信するべきメンバー一覧。 def members_to_deliver return [] if completed emails = Ezine::SentLog.where(page_id: id).map(&:email) Ezine::Member.where(state: "enabled", node_id: parent.id, email: {"$nin" => emails}) end # Deliver a mail to a member. # # Create a sent log if it is succeeded and isn't test delivery. # # 1メンバーにメールを配信する。 # # 成功しかつテスト配信でなければ配信ログを作成する。 # # @param [Ezine::Member, Ezine::TestMember] member # # @raise [Object] # An error object from `ActionMailer#deliver_now` # # `ActionMailer#deliver_now` メソッドからのエラーオブジェクト def deliver_to(member) Ezine::Mailer.page_mail(self, member).deliver_now Ezine::SentLog.create( node_id: parent.id, page_id: id, email: member.email ) unless member.test_member? end # Do a test delivery. # # テスト配信を行う。 def deliver_to_test_members Ezine::TestMember.where(node_id: parent.id).each do |test_member| deliver_to test_member end update test_delivered: Time.zone.now end private def validate_filename @basename.blank? ? nil : super end def seq_filename self.filename = dirname ? "#{dirname}#{id}.html" : "#{id}.html" end end
shirasagi/opendata
spec/factories/opendata/csv2rdf_settings.rb
<filename>spec/factories/opendata/csv2rdf_settings.rb FactoryGirl.define do factory :opendata_csv2rdf_setting, class: Opendata::Csv2rdfSetting do transient do site nil resource nil end site_id { site.present? ? site.id : nil } dataset_id { resource.dataset.id } resource_id { resource.id } end end
shirasagi/opendata
app/models/concerns/ss/addon.rb
module SS::Addon def self.extended(mod) mod.extend SS::Translation end public def addon_name SS::Addon::Name.new(self) end end
shirasagi/opendata
app/controllers/opendata/dataset/url_resources_controller.rb
<filename>app/controllers/opendata/dataset/url_resources_controller.rb<gh_stars>1-10 class Opendata::Dataset::UrlResourcesController < ApplicationController include Cms::BaseFilter include Cms::CrudFilter helper Opendata::FormHelper model Opendata::UrlResource navi_view "opendata/main/navi" before_action :set_dataset private def dataset @dataset ||= Opendata::Dataset.site(@cur_site).node(@cur_node).find params[:dataset_id] end def set_dataset raise "403" unless dataset.allowed?(:edit, @cur_user, site: @cur_site) @crumbs << [@dataset.name, opendata_dataset_path(id: @dataset)] end def set_item @item = dataset.url_resources.find params[:id] end public def index @items = @dataset.url_resources. search(params[:s]). order_by(name: 1). page(params[:page]).per(50) end def create @item = @dataset.url_resources.new get_params render_create @item.save end def download @item = @dataset.url_resources.find params[:url_resource_id] send_file @item.file.path, type: @item.content_type, filename: File.basename(@item.filename), disposition: :attachment, x_sendfile: true end def content @item = @dataset.url_resources.find params[:url_resource_id] @data = @item.parse_tsv end end
shirasagi/opendata
app/controllers/rdf/owl/restrictions_controller.rb
# class Rdf::Owl::RestrictionsController < ApplicationController # include Cms::BaseFilter # include Cms::CrudFilter # # model Rdf::Owl::Restriction # # navi_view "cms/main/navi" # # before_action :set_class # # private # def set_vocab # return if @vocab.present? # @vocab = Rdf::Vocab.site(@cur_site).find(params[:vid]) # raise "404" unless @vocab # end # # def set_class # set_vocab # return if @rdf_class.present? # @rdf_class = Rdf::Class.vocab(@vocab).find(params[:class_id]) # raise "404" unless @rdf_class # end # # def fix_params # set_vocab # set_class # { in_vocab: @vocab, in_class: @rdf_class } # end # # def set_crumbs # set_vocab # set_class # @crumbs << [:"rdf.vocabs", rdf_vocabs_path] # @crumbs << [@vocab.labels.preferred_value, rdf_vocab_path(id: @vocab)] # @crumbs << [@rdf_class.name, rdf_classes_class_path(vid: @vocab, id: @rdf_class)] # end # # def set_item # set_vocab # set_class # @item = @rdf_class.properties.find(params[:id]) # @item.attributes = fix_params # end # # public # def index # set_vocab # set_class # raise "403" unless @vocab.allowed?(:read, @cur_user, site: @cur_site, node: @cur_node) # # @items = @rdf_class.properties.search(params[:s]).order_by(_id: 1).page(params[:page]).per(50) # end # # def show # raise "403" unless @vocab.allowed?(:read, @cur_user, site: @cur_site, node: @cur_node) # render # end # # def new # @item = @rdf_class.properties.new pre_params.merge(fix_params) # raise "403" unless @vocab.allowed?(:edit, @cur_user, site: @cur_site, node: @cur_node) # end # # def create # @item = @rdf_class.properties.create get_params # render_create @item.valid? # end # # def edit # raise "403" unless @vocab.allowed?(:edit, @cur_user, site: @cur_site, node: @cur_node) # render # end # # def update # @item.attributes = get_params # @item.in_updated = params[:_updated] if @item.respond_to?(:in_updated) # raise "403" unless @vocab.allowed?(:edit, @cur_user, site: @cur_site, node: @cur_node) # render_update @item.update # end # # def delete # raise "403" unless @vocab.allowed?(:delete, @cur_user, site: @cur_site, node: @cur_node) # render # end # # def destroy # raise "403" unless @vocab.allowed?(:delete, @cur_user, site: @cur_site, node: @cur_node) # render_destroy @item.destroy # end # end
shirasagi/opendata
spec/models/job/worker_spec.rb
require 'spec_helper' describe Job::Worker do subject(:model) do Struct.new("J#{unique_id}") do include Job::Worker def call end end end jobs = [] describe ".call_async" do it "creates Job::Task" do expect { jobs << model.call_async }.to change { Job::Task.count }.by(1) end end describe ".call_in" do it "creates Job::Task" do expect { jobs << model.call_in(2.minutes.from_now) }.to change { Job::Task.count }.by(1) end end describe ".job_options" do it do expect(model.job_options).not_to be_nil expect(model.job_options).to be_a(Hash) end end after(:all) do jobs.each(&:delete) end end
shirasagi/opendata
app/controllers/concerns/opendata/api/package_show_filter.rb
<filename>app/controllers/concerns/opendata/api/package_show_filter.rb module Opendata::Api::PackageShowFilter extend ActiveSupport::Concern include Opendata::Api private def package_show_check(id) id_messages = [] id_messages << "Missing value" if id.blank? messages = {} messages[:name_or_id] = id_messages if id_messages.size > 0 if messages.size > 0 error = {__type: "Validation Error"} error = error.merge(messages) end return error end public def package_show help = t("opendata.api.package_show_help") id = params[:id] id = URI.decode(id) if id #use_default_schema = params[:use_default_schema] error = package_show_check(id) if error render json: {help: help, success: false, error: error} and return end datasets = Opendata::Dataset.site(@cur_site).public datasets = datasets.any_of({"id" => id}, {"name" => id}).order_by(name: 1) if datasets.count > 0 res = {help: help, success: true, result: convert_package(datasets[0])} else res = {help: help, success: false} res[:error] = {message: "Not found", __type: "Not Found Error"} end render json: res end end
shirasagi/opendata
spec/features/opendata/agents/nodes/sparql_spec.rb
require 'spec_helper' describe "opendata_agents_nodes_sparql", dbscope: :example do let(:node) { create_once :opendata_node_sparql, name: "opendata_sparql" } let(:index_path) { "#{node.url}" } let(:search_label) { "Run Query" } context "sparql is disabled" do before do @save_config = SS.config.opendata.fuseki SS.config.replace_value_at(:opendata, :fuseki, { "disable" => true }) end after do SS.config.replace_value_at(:opendata, :fuseki, @save_config) end describe "search" do it do page.driver.browser.with_session("public") do |session| session.env("HTTP_X_FORWARDED_HOST", cms_site.domain) visit index_path expect(current_path).to eq index_path select "HTML", from: "format" click_button search_label expect(page).to have_content("Disabled") end end end end context "sparql is enabled" do before do @save_config = SS.config.opendata.fuseki SS.config.replace_value_at(:opendata, :fuseki, { "disable" => false }) end after do SS.config.replace_value_at(:opendata, :fuseki, @save_config) end describe "search and get html with no data" do let(:data) { "" } before do allow(Opendata::Sparql).to receive(:select).and_return({ type: "text/html", data: data }) end it do page.driver.browser.with_session("public") do |session| session.env("HTTP_X_FORWARDED_HOST", cms_site.domain) visit index_path select "HTML", from: "format" click_button search_label expect(page).to have_content("No Data") end end end describe "search and get html with valid result" do let(:data) { "<table class=\"sparql\"><tr><td>spec</td></tr></table>" } before do allow(Opendata::Sparql).to receive(:select).and_return({ type: "text/html", data: data }) end it do page.driver.browser.with_session("public") do |session| session.env("HTTP_X_FORWARDED_HOST", cms_site.domain) visit index_path select "HTML", from: "format" click_button search_label expect(page).to have_content("spec") end end end describe "search and get html_table with no data" do let(:data) { "" } before do allow(Opendata::Sparql).to receive(:select).and_return({ type: "text/html", data: data }) end it do page.driver.browser.with_session("public") do |session| session.env("HTTP_X_FORWARDED_HOST", cms_site.domain) visit index_path select "HTML (TABLE Only)", from: "format" click_button search_label expect(page).to have_content("No Data") end end end describe "search and get html_table with valid data" do let(:data) { "<table class=\"sparql\"><tr><td>spec</td></tr></table>" } before do allow(Opendata::Sparql).to receive(:select).and_return({ type: "text/html", data: data }) end it do page.driver.browser.with_session("public") do |session| session.env("HTTP_X_FORWARDED_HOST", cms_site.domain) visit index_path select "HTML (TABLE Only)", from: "format" click_button search_label expect(page).to have_content("spec") end end end describe "search and get json" do let(:data) { "{ \"key\": \"spec\" }" } before do allow(Opendata::Sparql).to receive(:select).and_return({ type: "application/json", data: data, ext: "json" }) end it do page.driver.browser.with_session("public") do |session| session.env("HTTP_X_FORWARDED_HOST", cms_site.domain) visit index_path select "JSON", from: "format" click_button search_label expect(page).to have_content("spec") end end end describe "#csv" do let(:data) { "A,B,C" } before do allow(Opendata::Sparql).to receive(:select).and_return({ type: "text/csv", data: data, ext: "csv" }) end it do page.driver.browser.with_session("public") do |session| session.env("HTTP_X_FORWARDED_HOST", cms_site.domain) visit index_path select "CSV", from: "format" click_button search_label expect(page).to have_content("A,B,C") end end end describe "#TSV" do let(:data) { "A\tB\tC" } before do allow(Opendata::Sparql).to receive(:select).and_return({ type: "text/plain", data: data, ext: "txt" }) end it do page.driver.browser.with_session("public") do |session| session.env("HTTP_X_FORWARDED_HOST", cms_site.domain) visit index_path select "TSV", from: "format" click_button search_label expect(page).to have_content("A\tB\tC") end end end describe "#XML" do let(:data) { "<a>spec</a>" } before do allow(Opendata::Sparql).to receive(:select).and_return({ type: "application/xml", data: data, ext: "xml" }) end it do page.driver.browser.with_session("public") do |session| session.env("HTTP_X_FORWARDED_HOST", cms_site.domain) visit index_path select "XML", from: "format" click_button search_label expect(page).to have_content("spec") end end end end end
shirasagi/opendata
config/routes/ldap/routes.rb
SS::Application.routes.draw do Ldap::Initializer concern :deletion do get :delete, on: :member end namespace("ldap", as: "ldap", path: ".:site/ldap", module: "ldap") do get "server/:dn/group" => "server#group" get "server/:dn/user" => "server#user" get "server/:dn" => "server#index" get "server" => "server#index" get "import/import_confirmation" => "import#import_confirmation" post "import/import" => "import#import" get "import/sync_confirmation/:id" => "import#sync_confirmation" post "import/sync/:id" => "import#sync" get "import/results/:id" => "import#results" resources :import, concerns: :deletion, except: [:new, :create, :edit, :update] end end
shirasagi/opendata
spec/features/opendata/app/search_apps_spec.rb
require 'spec_helper' describe "opendata_search_apps", dbscope: :example do let(:site) { cms_site } let(:node) { create_once :opendata_node_search_app, name: "opendata_search_apps" } let(:index_path) { opendata_search_apps_path site.host, node } context "search_app" do before { login_cms_user } it "#index" do visit index_path expect(current_path).not_to eq sns_login_path end end end
shirasagi/opendata
app/models/concerns/cms/addon/release.rb
<gh_stars>1-10 module Cms::Addon module Release extend ActiveSupport::Concern extend SS::Addon end end
shirasagi/opendata
app/models/ezine/public_entry.rb
<filename>app/models/ezine/public_entry.rb<gh_stars>1-10 class Ezine::PublicEntry include Ezine::Entryable include Ezine::Addon::Data store_in session: :public, collection: :ezine_entries end
shirasagi/opendata
spec/factories/opendata/license.rb
FactoryGirl.define do factory :opendata_license, class: Opendata::License do transient do site nil user nil file nil end name { "#{unique_id}" } site_id { site.present? ? site.id : nil } user_id { user.present? ? user.id : nil } in_file { file } end end
shirasagi/opendata
app/controllers/ads/access_logs_controller.rb
<reponame>shirasagi/opendata class Ads::AccessLogsController < ApplicationController include Cms::BaseFilter model Ads::AccessLog navi_view "ads/main/navi" public def index if s = params[:s] @year = s[:year].presence @month = s[:month].presence end sy = Time.zone.today.year - 10 ey = Time.zone.today.year @years = (sy..ey).to_a.reverse.map { |d| ["#{d}#{t('datetime.prompts.year')}", d] } @months = (1..12).to_a.map { |d| ["#{d}#{t('datetime.prompts.month')}", d] } @items = @model.site(@cur_site).where(node_id: @cur_node.id) if @month monthly elsif @year yearly else recent end end private def recent @items = @items. order_by(date: -1, link_url: 1). page(params[:page]).per(50) end def monthly sdate = Date.new @year.to_i, @month.to_i, 1 edate = sdate + 1.months @max_cell = sdate.end_of_month.day @totals = {} @items = @items.where(date: { "$gte" => sdate, "$lt" => edate }) @items.order_by(link_url: 1).each do |item| @totals[item.link_url] ||= {} @totals[item.link_url][item.date.day] = item.count end render :total end def yearly sdate = Date.new @year.to_i, 1, 1 edate = sdate + 1.years @max_cell = 12 @totals = {} @items = @items.where(date: { "$gte" => sdate, "$lt" => edate }) pipes = [] pipes << { "$match" => @items.selector } pipes << { "$group" => { _id: { link_url: "$link_url", month: { "$month" => "$date" } }, count: { "$sum" => "$count" } } } pipes << { "$sort" => { "_id.link_url" => 1 } } @items.collection.aggregate(pipes).each do |data| url = data["_id"]["link_url"] month = data["_id"]["month"] @totals[url] ||= {} @totals[url][month] = data["count"] end render :total end end
shirasagi/opendata
app/models/concerns/ss/model/user.rb
module SS::Model::User extend ActiveSupport::Concern extend SS::Translation include SS::Document include SS::Fields::Normalizer include Ldap::Addon::User attr_accessor :cur_user, :in_password TYPE_SNS = "sns".freeze TYPE_LDAP = "ldap".freeze LOGIN_ROLE_DBPASSWD = "<PASSWORD>".freeze LOGIN_ROLE_LDAP = "ldap".freeze included do store_in collection: "ss_users" index({ email: 1 }, { sparse: true, unique: true }) index({ uid: 1 }, { sparse: true, unique: true }) seqid :id field :name, type: String field :uid, type: String field :email, type: String, metadata: { form: :email } field :password, type: String field :type, type: String field :login_roles, type: Array, default: [LOGIN_ROLE_DBPASSWD] field :last_loggedin, type: DateTime embeds_ids :groups, class_name: "SS::Group" permit_params :name, :uid, :email, :password, :type, :login_roles, group_ids: [] permit_params :in_password validates :name, presence: true, length: { maximum: 40 } validates :uid, length: { maximum: 40 } validates :uid, uniqueness: true, if: ->{ uid.present? } validates :email, email: true, length: { maximum: 80 } validates :email, uniqueness: true, if: ->{ email.present? } validates :email, presence: true, if: ->{ uid.blank? } validates :password, presence: true, if: ->{ ldap_dn.blank? } validate :validate_type validate :validate_uid before_validation :encrypt_password, if: ->{ in_password.present? } before_destroy :validate_cur_user, if: ->{ cur_user.present? } scope :uid_or_email, ->(id) { self.or({email: id}, {uid: id}) } end module ClassMethods public def auth_methods @auth_methods ||= [ :ldap_authenticate, :dbpasswd_authenticate ] end def authenticate(id, password) user = uid_or_email(id).first return nil unless user auth_methods.each do |method| return user if user.send(method, password) end nil end def search(params) criteria = self.where({}) return criteria if params.blank? if params[:name].present? criteria = criteria.search_text params[:name] end if params[:keyword].present? criteria = criteria.keyword_in params[:keyword], :name, :email end criteria end def type_options [ [ t(TYPE_SNS), TYPE_SNS ], [ t(TYPE_LDAP), TYPE_LDAP ] ] end end public def encrypt_password self.password = <PASSWORD>(in_password) end # detail, descriptive name def long_name uid = self.uid uid ||= email.split("@")[0] if email.present? if uid.present? "#{name}(#{uid})" else "#{name}" end end private def dbpasswd_authenticate(in_passwd) return false unless login_roles.include?(LOGIN_ROLE_DBPASSWD) return false if password.blank? password == <PASSWORD>(in_passwd) end def validate_type errors.add :type, :invalid unless type.blank? || type == TYPE_SNS || type == TYPE_LDAP end def validate_uid return if uid.blank? errors.add :uid, :invalid if uid !~ /^[\w\-]+$/ end def validate_cur_user if id == cur_user.id errors.add :base, :self_user return false else return true end end end
shirasagi/opendata
spec/features/opendata/app/appfiles_spec.rb
require 'spec_helper' describe "opendata_appfiles", dbscope: :example do def create_appfile(app, file) appfile = app.appfiles.new(text: "aaa", format: "csv") appfile.in_file = file appfile.save appfile end let(:site) { cms_site } let!(:node_search_app) { create(:opendata_node_search_app) } let(:node) { create_once :opendata_node_app, name: "opendata_app" } let(:app) { create(:opendata_app, node: node) } let(:file_path) { Rails.root.join("spec", "fixtures", "opendata", "utf-8.csv") } let(:file) { Fs::UploadedFile.create_from_file(file_path, basename: "spec") } let(:appfile) { create_appfile(app, file) } let(:index_path) { opendata_app_appfiles_path site.host, node, app_id: app.id } let(:new_path) { new_opendata_app_appfile_path site.host, node, app_id: app.id } let(:download_path) { opendata_app_appfile_file_path site.host, node, app_id: app.id, appfile_id: appfile.id } it "without login" do visit index_path expect(current_path).to eq sns_login_path end it "without auth" do login_ss_user visit index_path expect(status_code).to eq 403 end context "with auth" do before { login_cms_user } it "#index" do visit index_path expect(current_path).not_to eq sns_login_path end it "#new" do visit new_path within "form#item-form" do fill_in "item[text]", with: "sample" attach_file "item[in_file]", "#{Rails.root}/spec/fixtures/ss/logo.png" click_button "保存" end expect(status_code).to eq 200 expect(current_path).not_to eq new_path expect(page).not_to have_css("form#item-form") end it "#download" do visit download_path expect(current_path).not_to eq sns_login_path end end end
shirasagi/opendata
spec/models/opendata/dataset_group_spec.rb
<gh_stars>1-10 require 'spec_helper' describe Opendata::DatasetGroup, dbscope: :example do describe "#state_options" do subject { create(:opendata_dataset_group, site: cms_site, categories: [ OpenStruct.new({ _id: 1 }) ]) } its(:state_options) { is_expected.to include %w(公開 public) } end describe ".public" do it { expect(described_class.public.selector.to_h).to include("state" => "public") } end describe ".search" do it { expect(described_class.search({}).selector.to_h).to be_empty } it do expect(described_class.search(name: "名前").selector.to_h).to \ include("name" => include("$all" => include(/\Q名前\E/))) end it { expect(described_class.search(category_id: 1).selector.to_h).to include("category_ids" => 1) } end end
evilmartians/fias
lib/fias/name/canonical.rb
module Fias module Name module Canonical class << self def canonical(name) result = search(name) || search_exception(name) result || fail("Unknown abbrevation: #{name}") fix_republic_case(result) end private def search(key) long = Fias.config.index[Unicode.downcase(key)] return nil unless long short = short_for(long) short_stripped = short_for(long).gsub(/\.$/, '') [long, short_stripped, short, aliases_for(long)].flatten.compact end def short_for(long) Fias.config.shorts[Unicode.downcase(long)] end def aliases_for(long) Fias.config.aliases[Unicode.downcase(long)] end def search_exception(name) Fias.config.exceptions[Unicode.downcase(name)] end def fix_republic_case(canonical) return canonical unless canonical[0] == REPUBLIC canonical.map { |n| Unicode.upcase(n[0]) + n[1..-1] } end end REPUBLIC = 'республика' end end end
evilmartians/fias
tasks/download.rake
require 'fias' namespace :fias do desc 'Returns lastest url of FIAS db (bundle exec rake fias:download | xargs wget)' task :download do url = Fias::Import::DownloadService.url if url puts url else puts 'An error occured during SOAP call' return 999 end end end
evilmartians/fias
lib/fias/import/dbf.rb
module Fias module Import class Dbf def initialize(path, encoding = DEFAULT_ENCODING) @path = path @files = {} unless Dir.exist?(@path) fail ArgumentError, "FIAS database path #{@path} does not exists" end open_files(encoding) end def only(*names) return @files if names.empty? names = names.map do |name| name = name.to_sym name == :houses ? HOUSE_TABLES.keys : name name == :nordocs ? NORDOC_TABLES.keys : name end names.flatten! @files.slice(*names) end attr_reader :files private def open_files(encoding) TABLES.each do |accessor, dbf_filename| filename = File.join(@path, dbf_filename) next unless File.exist?(filename) dbf = DBF::Table.new(filename, nil, encoding) @files[accessor] = dbf if dbf end end def self.n_tables(title) tables = (1..99).map do |n| [ format('%s%0.2d', title, n).to_sym, format('%s%0.2d.DBF', title.upcase, n) ] end tables.flatten! Hash[*tables] end HOUSE_TABLES = n_tables('house') NORDOC_TABLES = n_tables('nordoc') TABLES = { address_object_types: 'SOCRBASE.DBF', current_statuses: 'CURENTST.DBF', actual_statuses: 'ACTSTAT.DBF', operation_statuses: 'OPERSTAT.DBF', center_statuses: 'CENTERST.DBF', interval_statuses: 'INTVSTAT.DBF', estate_statues: 'ESTSTAT.DBF', structure_statuses: 'STRSTAT.DBF', address_objects: 'ADDROBJ.DBF', house_intervals: 'HOUSEINT.DBF', landmarks: 'LANDMARK.DBF', house_state_statuses: 'HSTSTAT.DBF' }.merge( HOUSE_TABLES ).merge( NORDOC_TABLES ) DEFAULT_ENCODING = Encoding::CP866 end end end
evilmartians/fias
lib/fias/import/tables.rb
<filename>lib/fias/import/tables.rb module Fias module Import class Tables def initialize(db, files, prefix = DEFAULT_PREFIX) @db = db @files = files @prefix = prefix end attr_reader :files def create @files.each do |name, dbf| next if dbf.blank? create_table(name, dbf) end end def copy @files.map do |name, dbf| Copy.new(@db, table_name(name), dbf, uuid_column_types(name)) end end private def table_name(name) [@prefix, name].delete_if(&:blank?).join('_').to_sym end def create_table(name, dbf) columns = columns_for(name, dbf) @db.create_table(table_name(name)) do primary_key :id columns.each { |args| column(*args) } end end def columns_for(name, dbf) dbf.columns.map do |column| column_for(name, column) end end def column_for(name, column) alter = UUID[name] column_name = column.name.downcase parse_c_def(column.schema_definition).tap do |c_def| c_def[1] = :uuid if alter && alter.include?(column_name) c_def[1] = :text if c_def[1] == :string end end def parse_c_def(c_def) c_def = c_def.strip.split(',').map(&:strip) name = c_def[0][1..-2] type = c_def[1][1..-1] [name, type].map(&:to_sym) end def uuid_column_types(name) uuid = UUID[name] || [] Hash[*uuid.zip([:uuid] * uuid.size).flatten] end UUID = { address_objects: %w(aoguid aoid previd nextid parentguid) } DEFAULT_PREFIX = 'fias' end end end
evilmartians/fias
lib/fias/config.rb
<filename>lib/fias/config.rb<gh_stars>10-100 module Fias class Config def initialize @index = {} @longs = {} @shorts = {} @aliases = {} @exceptions = {} @proper_names = [] @replacements = {} @synonyms = [] @synonyms_index = {} yield(self) finalize_index end attr_reader :index, :longs, :shorts, :aliases, :exceptions, :replacements attr_reader :proper_names, :synonyms, :synonyms_index def cache @cache ||= {} end def add_name(long, short, aliases = []) @longs[Unicode.downcase(short)] = long @shorts[Unicode.downcase(long)] = short @aliases[Unicode.downcase(long)] = aliases populate_index(long, short, aliases) end def add_replacement(target, value) @replacements[Unicode.downcase(target)] = value end def add_exception(long, short) @exceptions[Unicode.downcase(short)] = [long, short] @exceptions[Unicode.downcase(long)] = [long, short] end def add_proper_name(name) @proper_names << name end def add_synonym(*names) @synonyms << names populate_synonyms_index(names) end private def populate_index(long, short, aliases) long_downcase = Unicode.downcase(long) short_downcase = Unicode.downcase(short) populate_long_permutations(long) if long_downcase != short_downcase @index[short_downcase] = long @index[short_downcase[0..-2]] = long if short_downcase[-1] == '.' end aliases.each { |al| @index[Unicode.downcase(al)] = long } end def populate_long_permutations(long) Unicode.downcase(long).split(' ').permutation.each do |variant| @index[variant.join(' ')] = long end end def finalize_index @index = @index.sort_by { |key, _| key.size }.reverse @index = Hash[*@index.flatten] end def populate_synonyms_index(names) names.each { |name| @synonyms_index[name] = names } end end end
evilmartians/fias
lib/fias/name/house_number.rb
module Fias module Name module HouseNumber class << self def extract(name) return [name, nil] unless contains_number?(name) name, number = try_split_by_colon(name) || try_housing(name) || try_house_word(name) || try_ends_with_number(name) [name.strip, number.strip] end private def contains_number?(name) !(name =~ JUST_A_NUMBER) && !(name =~ LINE_OR_MICRODISTRICT) && ( name =~ COLON || name =~ ENDS_WITH_NUMBER || name =~ HOUSE_WORD || name =~ NUMBER_WITH_HOUSING ) end def try_split_by_colon(name) name.split(/\s*,\s*/, 2) if name =~ COLON end def try_housing(name) match = name.match(NUMBER_WITH_HOUSING) [match.pre_match, "#{match} #{match.post_match}"] if match end def try_house_word(name) match = name.match(HOUSE_WORD) [match.pre_match, match.post_match] if match end def try_ends_with_number(name) match = name.match(ENDS_WITH_NUMBER) [match.pre_match, match[1]] if match end def or_words(words) words .sort_by(&:length) .reverse .map { |w| Regexp.escape(w) } .join('|') end end COLON = /\,/ JUST_A_NUMBER = /^[\s\d]+$/ STOPWORDS = /(микрорайон|линия|микр|мкрн|мкр|лин)/ui LINE_OR_MICRODISTRICT = /#{STOPWORDS}\.?[\s\w+]?\d+$/ui NUMBER = /\d+\/?#{Fias::LETTERS}?\d*/ui ENDS_WITH_NUMBER = /(#{NUMBER})$/ui HOUSE_WORDS = %w(ом д дом вл кв) HOUSE_WORD = /(\s|\,|\.|^)(#{or_words(HOUSE_WORDS)})(\s|\,|\.|$)/ui HOUSING_WORDS = %w(корпус корп к) NUMBER_WITH_HOUSING = /#{NUMBER}[\s\,\.]+(#{or_words(HOUSING_WORDS)})[\s\,\.]+#{NUMBER}/ui end end end
evilmartians/fias
spec/lib/name/house_number_spec.rb
<reponame>evilmartians/fias<gh_stars>10-100 require 'spec_helper' describe Fias::Name::HouseNumber do { '14' => ['14', nil], 'мкр. 14' => ['мкр. 14', nil], 'лин. 5' => ['лин. 5', nil], 'линия 14' => ['линия 14', nil], '2 мкр' => ['2 мкр', nil], '2-я советская' => ['2-я советская', nil], '50 лет октября' => ['50 лет октября', nil], 'советская 2-я' => ['советская 2-я', nil], 'Советской Армии ул,238а' => ['Советской Армии ул', '238а'], 'Советской Армии ул,181,корп.в' => ['Советской Армии ул', '181,корп.в'], 'пр.Энергетиков, 72/2' => ['пр.Энергетиков', '72/2'], 'Засечное с, 34' => ['Засечное с', '34'], 'Ново-Садовая ул,303а' => ['Ново-Садовая ул', '303а'], 'ЖК Бутово Парк-2, корп. 11' => ['ЖК Бутово Парк-2', 'корп. 11'], 'Вербицкого 25' => %w(Вербицкого 25), 'Новоколомяжский 11к1' => %w(Новоколомяжский 11к1), 'пр.Энергетиков 72/2' => ['пр.Энергетиков', '72/2'], '2-я линия В.О. 12' => ['2-я линия В.О.', '12'], 'Шуваловский пр.88к1' => ['Шуваловский пр.', '88к1'], '<NAME>, вл.1А' => ['<NAME>', 'вл.1А'], 'Московское ш,43 а,корп.стр.' => ['Московское ш', '43 а,корп.стр.'], 'Заводская ул 35-А' => ['Заводская ул 35-А', nil], 'ул 1905 года 28' => ['ул 1905 года', '28'], 'Новослободская 29 корп 3' => ['Новослободская', '29 корп 3'], 'Александрова д 29' => %w(Александрова 29), 'Николаева дом 29' => %w(Николаева 29), 'Невский д. 29' => %w(Невский 29), 'ул 1905 года' => ['ул 1905 года', nil], 'М<NAME>я ом. 29' => ['<NAME>', '29'], '26 линия В.О. д.15 к.A' => ['26 линия В.О.', '15 к.A'], 'Дунайский пр.' => ['Дунайский пр.', nil], 'Пионерстроя ул. 14 к 1' => ['<NAME>л.', '14 к 1'] }.each do |street, extracted| it "Must extract house_number from #{street}" do expect(described_class.extract(street)).to eq(extracted) end end end
evilmartians/fias
tasks/db.rake
<gh_stars>10-100 require 'fias' require 'ruby-progressbar' require 'sequel' namespace :fias do desc 'Create FIAS tables (PREFIX, FIAS_PATH to dbfs, DATABASE_URL and TABLES)' task :create_tables do within_connection do |tables| tables.create puts "#{tables.files.keys.join(', ')} created." end end desc 'Import FIAS data (PREFIX, FIAS_PATH to dbfs, DATABASE_URL and TABLES)' task :import do within_connection do |tables| tables.copy.each do |table| puts "Encoding #{table.table_name}..." bar = ProgressBar.create( total: table.dbf.record_count, format: '%a |%B| [%E] (%c/%C) %p%%' ) table.encode { bar.increment } table.copy end end end private def connect_db if ENV['DATABASE_URL'].blank? fail 'Specify DATABASE_URL (eg. postgres://localhost/fias)' end Sequel.connect(ENV['DATABASE_URL']) end def within_connection(&block) db = Sequel.connect(ENV['DATABASE_URL']) fias_path = ENV['FIAS_PATH'] || 'tmp/fias' only = *ENV['TABLES'].to_s.split(',') files = Fias::Import::Dbf.new(fias_path).only(*only) prefix = ENV['PREFIX'] tables = Fias::Import::Tables.new(db, files, *[prefix].compact) diff = only - files.keys.map(&:to_s) puts "WARNING: Missing DBF files for: #{diff.join(', ')}" if diff.any? yield(tables) end end
wooga/rack-flash
lib/rack/flash.rb
<filename>lib/rack/flash.rb module Rack class Flash # Raised when the session passed to FlashHash initialize is nil. This # is usually an indicator that session middleware is not in use. class SessionUnavailable < StandardError; end # Implements bracket accessors for storing and retrieving flash entries. class FlashHash attr_reader :flagged def initialize(store, opts={}) raise Rack::Flash::SessionUnavailable \ .new('Rack::Flash depends on session middleware.') unless store @opts = opts @store = store if accessors = @opts[:accessorize] accessors.each { |opt| def_accessor(opt) } end end # Remove an entry from the session and return its value. Cache result in # the instance cache. def [](key) key = key.to_sym cache[key] ||= values.delete(key) end # Store the entry in the session, updating the instance cache as well. def []=(key,val) key = key.to_sym cache[key] = values[key] = val end # Store a flash entry for only the current request, swept regardless of # whether or not it was actually accessed. Useful for AJAX requests, where # you want a flash message, even though you're response isn't redirecting. def now cache end # Checks for the presence of a flash entry without retrieving or removing # it from the cache or store. def has?(key) [cache, values].any? { |store| store.keys.include?(key.to_sym) } end alias_method :include?, :has? # Mark existing entries to allow for sweeping. def flag! @flagged = values.keys end # Remove flagged entries from flash session, clear flagged list. def sweep! Array(flagged).each { |key| values.delete(key) } flagged.clear end # Hide the underlying :__FLASH__ session key and only expose values stored # in the flash. def inspect '#<FlashHash @values=%s @cache=%s>' % [values.inspect, cache.inspect] end # Human readable for logging. def to_s values.inspect end private # Maintain an instance-level cache of retrieved flash entries. These # entries will have been removed from the session, but are still available # through the cache. def cache @cache ||= {} end # Helper to access flash entries from :__FLASH__ session value. This key # is used to prevent collisions with other user-defined session values. def values @store[:__FLASH__] ||= {} end # Generate accessor methods for the given entry key if :accessorize is true. def def_accessor(key) raise ArgumentError.new('Invalid entry type: %s' % key) if respond_to?(key) class << self; self end.class_eval do define_method(key) { |*args| val = args.first; val ? (self[key]=val) : self[key] } define_method("#{key}=") { |val| self[key] = val } define_method("#{key}!") { |val| cache[key] = val } end end end # ------------------------------------------------------------------------- # - Rack Middleware implementation def initialize(app, opts={}) if klass = app_class(app, opts) klass.class_eval do def flash; env['x-rack.flash'] end end end @app, @opts = app, opts end def call(env) env['x-rack.flash'] ||= Rack::Flash::FlashHash.new(env['rack.session'], @opts) if @opts[:sweep] env['x-rack.flash'].flag! end res = @app.call(env) if @opts[:sweep] env['x-rack.flash'].sweep! end res end private def app_class(app, opts) return nil if opts.has_key?(:helper) and not opts[:helper] opts[:flash_app_class] || defined?(Sinatra::Base) && Sinatra::Base || self.class.rack_builder.leaf_app.class end end end
louismerlin/croque
api/public.rb
<gh_stars>0 class PublicApp < Sinatra::Base # Gives the menu for the day get '/' do @menu = Menu.where(:date => Date.today).first if @menu @menu.questions.map{ |q| { id: q.id, body: q.body, answers: q.answers.map{|a| {place: a.place, body: a.body}} } }.to_json else "CLOSED".to_json end end # Setting basic options set :port, 8080 set :bind, '0.0.0.0' end
louismerlin/croque
admin/algo.rb
def distribute # Creation of distribution objects @prop = Distribution.where { (proportion > 0) }.all.select { |d| d.size > 1 } @sum = 0 @prop.each do |p| @sum += p.proportion end # Default distribution if this one is not valid if @sum.zero? @prop = [{ size: 2, proportion: 1 }, { size: 3, proportion: 1 }] # As many 2s than 3s @sum = 2 end @small = @prop[0].size @prop.each { |p| @small = p.size if p.size < @small } @portions = 1 @reqs = Lunchrequest.all # Find all tables for a specific time def findTable(time) @exact = @prop.index { |p| p.size == Lunchrequest.where(time: time).all.size } if !@exact.nil? createLunch(@prop[@exact][:proportion], time) else @rand = rand(@sum) @te = 0 @count = 0 while @rand > @te @te += @prop[@count][:proportion] @count += 1 end createLunch(@prop[@count].size, time) end end # Create a lunch for num persons at the specified time def createLunch(num, time) log = Logger.new(STDERR) log.fatal(num) log.fatal(time) @timeReqs = Lunchrequest.where(time: time).all @chosen = @timeReqs.first(num) @lunch = Lunch.new(time: time, date: Date.today).save @chosen.each do |req| @lunch.add_user(req[:user_id]) req.delete end end @times = [11, 12, 13] # Create tables for each time slot for @time in @times do findTable(@time) while Lunchrequest.where(time: @time).all.size >= @small end end scheduler = Rufus::Scheduler.new scheduler.cron '0,10,20,30,40,50 7-12 * * *' do # Do something every 10 minutes from 7:00 to 12:50 distribute end
louismerlin/croque
api/lunches.rb
<reponame>louismerlin/croque<gh_stars>0 class LunchApp < Sinatra::Base # Check if you have a lunch assigned for today get '/lunch' do protected! @lunch = User[session[:logged]].lunches_dataset.where(date: Date.today).first if @lunch {id: @lunch[:lunch_id], users: @lunch.users.map{|u| {id: u[:id], name: getDescription(u[:description])}}}.to_json else "No lunch prepared yet".to_json end end # Create a lunch request for you at a specified time for today post '/lunch' do protected! @data = JSON.parse(request.body.read) @time = @data['time'] @answers = @data['answers'] if @time == nil halt 400, 'time must not be empty' elsif !([11, 12, 13].include? @time.to_i) halt 400, 'time must be 11, 12 or 13' end if @answers != nil && @answers != [] && !Lunchrequest.where(user_id: session[:logged]).first && !User[session[:logged]].lunches_dataset.where(date: Date.today).first @lr = Lunchrequest.new(time: @time.to_i, user_id: session[:logged]).save @answers.each {|a| if Answer[a] @lr.add_answer(Answer[a]) end } 200 else 400 end end # Get all your lunches get '/lunches' do protected! @lunches = User[session[:logged]].lunches_dataset.all @lunches.to_json end # Setting basic options set :port, 8080 set :bind, '0.0.0.0' helpers HelpersApp end
louismerlin/croque
api/users.rb
class UserApp < Sinatra::Base # Creates a new user (temporary) post '/users' do @data = JSON.parse(request.body.read) @email = @data['email'] @firstname = @data['firstname'] @lastname = @data['lastname'] @password = @data['password'] if @email != nil && @firstname != nil && @lastname != nil && @password != nil # Adds a user to the database using the User object (see models.rb) User.new(:email => @email, :firstname => @firstname, :lastname => @lastname, :password => BCrypt::Password.create(@password)).save 200 else 400 end end # Lists all users (temporary) get '/users' do @out = "" User.each { |u| @out+=u.email+"<br/>" } @out end post '/users/login' do @data = JSON.parse(request.body.read) @email= @data['email'] @password = @data['password'] if @email != nil && @password != nil @user = User.where(:email => @email).first if @user if BCrypt::Password.new(@user.password) == @password session[:logged] = @user.id halt 200 end end halt 401 end halt 400 end get '/users/me' do protected! session[:logged].to_s.to_json end # Get a tequila token get '/users/gettoken' do @proxy = Net::HTTP.new('tequila.epfl.ch', 80) @res = @proxy.post('/cgi-bin/tequila/createrequest', 'urlaccess=/users/checklogin') if @res.code == "200" return @res.body[4..-1] else return 500 end end # Confirm Login was done well and get info post '/users/checklogin' do @proxy = Net::HTTP.new('tequila.epfl.ch', 80) if params['key'] @res = @proxy.post('/cgi-bin/tequila/fetchattributes', 'key='+params['key']) if @res.code == "200" puts @res.body return @res.body['name'] else return 406 end else return 406 end end # Setting basic options set :port, 8080 set :bind, '0.0.0.0' helpers HelpersApp end def getDescription(desc) "Un nouvel arrivant" end
louismerlin/croque
api/models.rb
# Sequel => access to database Sequel::Model.plugin :force_encoding, 'UTF-8' DB = Sequel.connect('postgres://hello:coffee@db/') class User < Sequel::Model many_to_many :lunches end User.unrestrict_primary_key class Lunch < Sequel::Model many_to_many :users end class Lunchrequest < Sequel::Model many_to_many :answers end class Question < Sequel::Model many_to_many :menus one_to_many :answers end class Answer < Sequel::Model many_to_one :question many_to_many :lunchrequests end class Menu < Sequel::Model many_to_many :questions end
louismerlin/croque
admin/app.rb
#!/usr/local/bin/ruby require 'sinatra/base' require 'rack/mount' require 'sequel' require 'date' require 'rufus-scheduler' require './models' require './algo' class Admin < Sinatra::Base # Stats page get '/' do protected! erb :index, layout: :layout end # Login page get '/login' do erb :login, layout: :layout end # Login action post '/login' do if params[:login] == 'admin' && params[:password] == '<PASSWORD>' # Session uses cookies to differenciate users session[:logged] = 'admin_true' redirect '/' else redirect '/login' end end # Listing of all questions get '/questions' do protected! # Queries all questions, in descending order @questions = Question.order(Sequel.desc(:id)) erb :'questions/index', layout: :layout end # Adding a question post '/questions' do protected! Question.new(body: params[:question]).save if params[:question] redirect '/questions' end # See a specific question, to edit it get '/questions/:id' do protected! @q = Question[params[:id].to_i] if @q erb :'questions/edit', layout: :layout else redirect '/questions' end end # Edit a specific question post '/questions/:id' do protected! @q = Question[params[:id].to_i] @q.update(body: params[:question]).save if @q && params[:question] redirect '/questions' end # Delete a question get '/questions/:id/delete' do protected! @q = Question[params[:id].to_i] if @q Menu.where(questions: @q).each { |m| m.remove_question(@q) } Answer.where(question: @q).each(&:delete) @q.delete end redirect '/questions' end # Create an answer for a question post '/questions/:id/answers' do protected! @q = Question[params[:id].to_i] if @q if params[:body] != "" @q.add_answer(Answer.new(body: params[:body], place: params[:place] || 0, score: 0).save) end end redirect back end # Edit an answer post '/answers/:id' do protected! @a = Answer[params[:id].to_i] if @a if params[:body] != "" if params[:place] != "" @a.update(body: params[:body], place: params[:place]) else @a.update(body: params[:body]) end else if params[:place] != "" @a.update(place: params[:place]) end end end redirect back end # Delete an answer get '/answers/:id/delete' do protected! @a = Answer[params[:id].to_i] @a.delete if @a redirect back end # Menu list for today and the ten days surounding it get '/menus' do protected! @today = Date.today @menus = [*-5..5].map do |i| { date: @today + i, menu: Menu.where(date: @today + i.to_i).first } end erb :'menus/index', layout: :layout end # This will create a new menu get '/menus/:date' do protected! if real_date? params[:date] unless Menu.where(date: Date.parse(params[:date])).first Menu.new(date: Date.parse(params[:date])).save end @menu = Menu.where(date: Date.parse(params[:date])).first erb :'menus/edit', layout: :layout else redirect '/menus' end end # Adding or deleting a question to a menu get '/menus/:date/questions/:id' do protected! if real_date? params[:date] @menu = Menu.where(date: Date.parse(params[:date])).first @question = Question[params[:id].to_i] if @menu && @question if !@menu.questions.include? @question @menu.add_question(@question) else @menu.remove_question(@question) end redirect "/menus/#{@menu.date}" end end redirect '/menus' end get '/tests' do protected! @requests = Lunchrequest.all @lunches = Lunch.where(date: Date.today).all erb :'tests/index', layout: :layout end get '/tests/distribute' do protected! distribute redirect back end helpers do # A protected page will only be available if you are authorized def protected! if authorized? true else halt 401, "401 - Not authorized. <a href=\"/login\">Login &raquo;</a>\n" end end # You are autorized if you have logged in def authorized? if session[:logged] == 'admin_true' true else false end end # Is this string a valid date ? def real_date?(date) Date.valid_date? *date.split('-').map(&:to_i) end end set :port, 8080 set :bind, '0.0.0.0' # Using sessions use Rack::Session::Cookie, key: 'rack.session', path: '/', secret: 'MANGER' run! end
louismerlin/croque
api/app.rb
<reponame>louismerlin/croque #!/usr/local/bin/ruby require 'sinatra/base' require 'rack/mount' require 'net/http' require 'sequel' require 'date' require 'json' require 'bcrypt' require './helpers' require './models' require './users' require './lunches' require './public' class Routes < Sinatra::Base get('/users*') { UserApp.call(env) } post('/users*') { UserApp.call(env) } get('/lunch*') { LunchApp.call(env) } post('/lunch*') { LunchApp.call(env) } get('/*') { PublicApp.call(env) } post('/*') { PublicApp.call(env) } use Rack::Session::Cookie, :key => 'rack.session', :path => '/', :secret => 'BURGERRR' set :port, 8080 set :bind, '0.0.0.0' run! end
louismerlin/croque
api/helpers.rb
<reponame>louismerlin/croque module HelpersApp # A protected page will only be available if you are authorized def protected! if authorized? true else halt 401 end end # You are autorized if you have logged in def authorized? if session[:logged] true else false end end end
louismerlin/croque
admin/models.rb
<gh_stars>0 # Sequel => access to database DB = Sequel.connect('postgres://hello:coffee@db/') class User < Sequel::Model many_to_many :lunches end # Makes it able to use sciper as key User.unrestrict_primary_key Sequel.inflections do |inflect| inflect.irregular 'lunch', 'lunches' end class Lunch < Sequel::Model many_to_many :users end class Question < Sequel::Model many_to_many :menus one_to_many :answers end class Menu < Sequel::Model many_to_many :questions end class Answer < Sequel::Model many_to_one :question end class Lunchrequest < Sequel::Model end class Distribution < Sequel::Model end
kritikagarg/cs595-s21
assignments/Garg/4/framable/http-responses/ria.ru
HTTP/1.1 301 Moved Permanently Server: QRATOR Date: Thu, 01 Apr 2021 16:20:44 GMT Content-Length: 0 Connection: keep-alive Keep-Alive: timeout=15 Location: https://ria.ru/ HTTP/1.1 200 OK Server: QRATOR Date: Thu, 01 Apr 2021 16:20:44 GMT Content-Type: text/html; charset=utf-8 Connection: keep-alive Keep-Alive: timeout=15 Expires: Thu, 19 Nov 1981 08:52:00 GMT Cache-Control: public Pragma: no-cache Access-Control-Allow-Origin: https://ria.ru
nuthintrue/AuthEngine
app/api/auth_engine/v1/helpers/auth_token.rb
<reponame>nuthintrue/AuthEngine<filename>app/api/auth_engine/v1/helpers/auth_token.rb module AuthEngine module V1 module Helpers module AuthToken extend Grape::API::Helpers def authenticate_credentials! unless credential.authenticate(auth_params[:password]) error!('Invalid Credentials', 401) end rescue ActiveRecord::RecordNotFound error!('Invalid Credentials', 401) end def auth_token <PASSWORD>.new payload: { sub: credential.id } end def credential AuthEngine::Credential.find_by!(email: auth_params[:email]) end def auth_params declared(params, include_missing: false)[:auth] end end end end end
nuthintrue/AuthEngine
app/api/auth_engine/v1/base.rb
module AuthEngine module V1 class Base < Grape::API mount V1::Health mount V1::Apply mount V1::User::Token add_swagger_documentation mount_path: '/v1/doc', api_version: 'v1', info: { title: "auth api", description: "auth api", contact_name: "auth api" } end end end
nuthintrue/AuthEngine
test/dummy/config/initializers/swagger.rb
GrapeSwaggerRails.options.app_name = 'auth_engine' GrapeSwaggerRails.options.url = '/api/v1/doc.json' GrapeSwaggerRails.options.app_url = 'http://localhost:3000' GrapeSwaggerRails.options.before_filter_proc = proc { GrapeSwaggerRails.options.app_url = request.protocol + request.host_with_port } GrapeSwaggerRails.options.doc_expansion = 'list'
nuthintrue/AuthEngine
app/models/auth_engine/user.rb
<gh_stars>0 module AuthEngine class User < ApplicationRecord has_one :credential delegate :email, to: :credential end end
nuthintrue/AuthEngine
app/models/auth_engine/credential.rb
module AuthEngine class Credential < ApplicationRecord has_secure_password validates :email, uniqueness: true validates :password, length: { minimum: 6 }, if: :setting_password? belongs_to :user def generate_new_confirmation_token self.update_attributes(confirmation_token_expires_at: new_confirmation_token_expires_at, confirmation_token: new_confirmation_token) end def confirmation_token_expired? Time.current >= confirmation_token_expires_at end private def setting_password? password.present? end def new_confirmation_token self.confirmation_token = SecureRandom.urlsafe_base64 end def new_confirmation_token_expires_at self.confirmation_token_expires_at = Time.current + 1.day end end end
nuthintrue/AuthEngine
app/api/auth_engine/v1/defaults.rb
module AuthEngine module V1 module Defaults extend ActiveSupport::Concern included do # Common Grape settings version 'v1' format :json # Common helpers helpers do def permitted_params @permitted_params ||= declared(params, include_missing: false) end end end end end end
nuthintrue/AuthEngine
app/api/auth_engine/v1/apply.rb
<gh_stars>0 module AuthEngine module V1 class Apply < Grape::API include V1::Defaults namespace :apply do params do requires :email, type: String requires :password, type: String optional :first_name, type: String optional :last_name, type: String optional :mobile_phone_number, type: String end post do result = AuthEngine::Api::Apply::PostCoordinator.new(params: permitted_params, headers: headers).call status result.status result.body end end end end end
nuthintrue/AuthEngine
db/migrate/20160810185237_create_credentials.rb
<filename>db/migrate/20160810185237_create_credentials.rb class CreateCredentials < ActiveRecord::Migration[5.0] def change create_table :auth_engine_credentials do |t| t.string :email, null: false, index: { unique: true } t.string :password_digest t.belongs_to :user t.timestamps null: false end end end
nuthintrue/AuthEngine
lib/auth_engine/engine.rb
<gh_stars>0 module AuthEngine class Engine < ::Rails::Engine isolate_namespace AuthEngine end end
nuthintrue/AuthEngine
app/api/auth_engine/v1/error/api_error.rb
<reponame>nuthintrue/AuthEngine<filename>app/api/auth_engine/v1/error/api_error.rb<gh_stars>0 module AuthEngine module V1 module Error class ApiError < StandardError attr_reader :data, :message, :status, :code def initialize(status:, message:, data: nil, code: nil) @status = status @message = message @data = data @code = code end end end end end
nuthintrue/AuthEngine
test/dummy/config/routes.rb
<reponame>nuthintrue/AuthEngine Rails.application.routes.draw do #mount AuthEngine::Engine => "/auth_engine" mount AuthEngine::Base => '/api' mount GrapeSwaggerRails::Engine => 'api/documentation' end
nuthintrue/AuthEngine
app/api/auth_engine/v1/health.rb
<reponame>nuthintrue/AuthEngine<gh_stars>0 module AuthEngine module V1 class Health < Grape::API include V1::Defaults helpers V1::Helpers::Authentication before do authenticate_token! end namespace :health do desc 'headers', { headers: { "Authorization" => { description: "JWT Token", required: true } } } get :health do status 200 "OK" end end end end end
nuthintrue/AuthEngine
app/coordinators/auth_engine/api/health/post_coordinator.rb
module AuthEngine module Api module Health class PostCoordinator < Api::ApiCoordinator def call result.status = 200 result.body = 'Success! The service is healthy!' result rescue StandardError => e result.status = e.status result.body = e.message result end private def verify_credential!(credential) if credential.invalid? if credential.errors.messages.key?(:email) && credential.errors.messages[:email].include?('has already been taken') raise_api_error!('Email is invalid, please try a new one.', 409, credential.errors.messages) else raise_api_error!('User information is invalid!', 422, credential.errors.messages) end end end end end end end
nuthintrue/AuthEngine
app/helpers/auth_engine/application_helper.rb
module AuthEngine module ApplicationHelper end end
nuthintrue/AuthEngine
app/coordinators/auth_engine/api/api_coordinator_result.rb
module AuthEngine module Api class ApiCoordinatorResult attr_accessor :status, :body def initialize(status: '', body: '') @status = status @body = body end end end end
nuthintrue/AuthEngine
app/coordinators/auth_engine/api/apply/post_coordinator.rb
<filename>app/coordinators/auth_engine/api/apply/post_coordinator.rb module AuthEngine module Api module Apply class PostCoordinator < Api::ApiCoordinator def call user = AuthEngine::User.create!(first_name: params[:first_name], last_name: params[:last_name]) # credential = user.create_credential(email: params[:email], password: params[:password]) verify_credential!(credential) user.save! result.status = 201 result.body = 'account created!' result rescue V1::Error::ApiError => e result.status = e.status result.body = e.message result end private def verify_credential!(credential) if credential.invalid? if credential.errors.messages.key?(:email) && credential.errors.messages[:email].include?('has already been taken') raise_api_error!('Email is invalid, please try a new one.', 409, credential.errors.messages) else raise_api_error!('User information is invalid!', 422, credential.errors.messages) end end end end end end end
nuthintrue/AuthEngine
app/coordinators/auth_engine/base_coordinator.rb
<reponame>nuthintrue/AuthEngine module AuthEngine class BaseCoordinator def raise_api_error!(message, status, data = nil, code = nil) raise V1::Error::ApiError, status: status, message: message, data: data, code: code end end end
nuthintrue/AuthEngine
auth_engine.gemspec
$:.push File.expand_path("../lib", __FILE__) # Maintain your gem's version: require "auth_engine/version" # Describe your gem and declare its dependencies: Gem::Specification.new do |s| s.name = "auth_engine" s.version = AuthEngine::VERSION s.authors = ["<NAME>"] s.email = ["<EMAIL>"] s.homepage = "http://github.com/nuthintrue" s.summary = "http://github.com/nuthintrue" s.description = "http://github.com/nuthintrue" s.license = "MIT" s.files = Dir["{app,config,db,lib}/**/*", "MIT-LICENSE", "Rakefile", "README.md"] s.add_dependency "rails", "~> 5.0.0", ">= 5.0.0.1" s.add_dependency "grape", "~> 0.17.0" s.add_dependency 'grape-swagger', '~> 0.23' s.add_dependency 'grape-swagger-rails', '~> 0.2' s.add_dependency 'knock', '~> 1.5' s.add_development_dependency "pg" s.add_development_dependency "rspec-rails", "~> 3.4" s.add_development_dependency "timecop", "~> 0.8" s.add_development_dependency "factory_girl_rails", "~> 4.7" s.add_development_dependency "faker", "~> 1.6.5" s.add_development_dependency "byebug" s.add_development_dependency "shoulda-matchers" end
nuthintrue/AuthEngine
app/api/auth_engine/v1/user/token.rb
<reponame>nuthintrue/AuthEngine<filename>app/api/auth_engine/v1/user/token.rb module AuthEngine module V1 module User class Token < Grape::API include V1::Defaults helpers V1::Helpers::AuthToken after_validation do authenticate_credentials! end params do requires :auth, type: Hash do requires :email, type: String requires :password, type: String end end desc 'Create an auth token' post '/token' do { jwt: auth_token.token } end end end end end