/doc/
.markdown-preview.html
+/sinatra/.bundle/
+/sinatra/.ruby-version
+/sinatra/Gemfile.lock
+/sinatra/vendor/
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, minimal-ui">
<title>Markdown preview</title>
- <link rel="stylesheet" type="text/css" href="http://thomasf.github.io/solarized-css/solarized-dark.min.css">
+ <link rel="stylesheet" type="text/css" href="github.css">
<script src="http://code.jquery.com/jquery-1.12.4.min.js"></script>
<script>
var socket = new WebSocket("ws://localhost:7379");
socket.onopen = function() {
console.log("Connection established.");
- socket.send("MDPM-Register-UUID: 3cb46385-5b3d-454f-be06-14c04b2d5607");
+ socket.send("MDPM-Register-UUID: 376644d6-8910-496a-9255-9edf49316520");
};
socket.onclose = function(event) {
if (event.wasClean) {
--- /dev/null
+Style/AsciiComments:
+ Enabled: false
+Lint/AmbiguousBlockAssociation:
+ Enabled: false
+Style/HashSyntax:
+ EnforcedStyle: hash_rockets
+Style/MultilineTernaryOperator:
+ Enabled: false
+Style/IfUnlessModifier:
+ Enabled: false
+Metrics/BlockLength:
+ Max: 80
+Style/NegatedIf:
+ Enabled: false
+Style/RedundantReturn:
+ Enabled: false
+Naming/MethodName:
+ Enabled: false
+Metrics/MethodLength:
+ Max: 80
+Style/GuardClause:
+ Enabled: false
+Metrics/ClassLength:
+ Max: 2000
+Style/Encoding:
+ Enabled: false
+Style/ClassCheck:
+ EnforcedStyle: kind_of?
+Style/SymbolProc:
+ Enabled: false
+Metrics/AbcSize:
+ Max: 100
+Metrics/CyclomaticComplexity:
+ Max: 10
+Metrics/PerceivedComplexity:
+ Max: 10
# coding: utf-8
+# frozen_string_literal: true
+
# Web GUI用コントローラ
# @author OHASHI, Norikazu
# 書籍管理サーバ WebGUI Controller
class WebGui < Sinatra::Base
-
# エラーステータス設定
# @attr_reader [Hash] params エラー処理用パラメータ
class WebError < StandardError
- attr_reader :params
+ attr_reader :params
# @param [Hash] params エラー処理用パラメータ
def initialize(params)
+ super
@params = params
end
end
set :root, File.join(File.dirname(__FILE__), '..')
- set :views, Proc.new {File.join(root, "views")}
- set :public_dir, Proc.new {File.join(root, "../public")}
+ set :views, proc { File.join(root, 'views') }
+ set :public_dir, proc { File.join(root, '../public') }
set :haml, :format => :html5
set :environment, :production
-
+
use Rack::Session::Cookie,
:expire_after => 1200,
:secret => 'change'
helpers do
# ページIDを保存して、viewに渡す
- # @params [Symble] pageId 表示するページID
- def goPage(pageId)
- @pageId = pageId
- haml pageId
+ # @params [Symble] pageId 表示するページID
+ def goPage(page_id)
+ @page_id = page_id
+ haml page_id
end
# アップロード用にファイルからデータを読む
# @params [Hash] Upload用パラメータ
# @return [Hash] Uploadデータ情報
def getUploadData(upload_param)
- if (upload_param == nil)
+ if upload_param.nil?
return nil
end
- upload_data = Hash.new
- file = upload_param[:tempfile]
+
+ upload_data = {}
+ file = upload_param[:tempfile]
upload_data[:mime_type] = upload_param[:type]
upload_data[:data] = file.read
# ユーザID が nil ならばセッションエラー
# @params [int] id ユーザid
def checkSession(id)
- if (id == nil)
- raise WebError.new(status: 408, message: "セッション期限切れです。再ログインをしてください。")
+ if id.nil?
+ raise WebError.new(:status => 408, :message => 'セッション期限切れです。再ログインをしてください。')
end
end
# 更新用の書籍情報を作成する。
# @param [Hash] params Postで取得した全パラメータ
+ # @param [Boolean] image_f 書影データの有無
# @return [Hash] 更新用書籍情報
def makeBookInfo(params, image_f)
- book_info = Hash.new
+ book_info = {}
params.each do |key, value|
case key
when 'summary', 'book_rank', 'cover_base64',
# 対象キーは書籍情報ではないので飛す
next
end
- if ((key == 'cover_uri') && (image_f))
+ if key == 'cover_uri' && image_f
# 登録するイメージがあるのでURIの登録は飛す
next
end
+
book_info[key.to_sym] = value
end
return book_info
# 書影情報の作成
# @param [Boolean] image_f Base64のイメージデータ有
# @param [Hash] params Postで取得した全パラメータ
- # @param [String] book_url 書影URL
+ # @param [String] book_url 書影URL
# @return [Hash] 作成した書影データ
def setBookImage(image_f, params, book_url)
- cover_image = Hash.new
+ cover_image = {}
# 書影情報の更新
- if (image_f)
+ if image_f
cover_image[:data] = Base64.decode64(params[:cover_base64])
cover_image[:mime_type] = params[:mime_type]
end
- if ((not image_f) && (book_url == nil) &&
- (params[:cover_file] != nil))
+
+ if !image_f && book_url.nil? && !params[:cover_file].nil?
cover_image = getUploadData(params[:cover_file])
end
+
return cover_image
end
end
-
+
# スタイルシート
get '/css/style.css' do
cache_control :public, :must_revalidate, :max_age => 120
begin
# アカウント作成
id = UserAccount.createAccount(name, full_name, email, passwd)
- session[:userId] = id;
+ session[:userId] = id
redirect to('/user_home')
- rescue UserAccount::AlreadyInstanceError
- raise WebError.new(status: 406, message: "すでに登録済みのアカウント名が指定されています。")
+ rescue UserAccount::AlreadyInstanceError
+ raise WebError.new(:status => 406, :message => 'すでに登録済みのアカウント名が指定されています。')
end
end
begin
# パスワードチェック
- id = UserAccount.checkPasswd(name, passwd);
- session[:userId] = id;
+ id = UserAccount.checkPasswd(name, passwd)
+ session[:userId] = id
redirect to('/user_home')
rescue UserAccount::NotFoundInstanceError,
UserAccount::AuthenticationError
- raise WebError.new(status: 401, message: "認証に失敗しました アカウント、 パスワードを確認してください。")
+ raise WebError.new(:status => 401, :message => '認証に失敗しました アカウント、 パスワードを確認してください。')
end
end
checkSession(id)
begin
user = UserAccount.getUser(id)
- @is_admin = UserAccount.checkAdmin(id);
+ @is_admin = UserAccount.checkAdmin(id)
@admin_type = false
@id = id
@username = user.full_name
@account = user.user_name
@email = user.email
rescue UserAccount::NotFoundInstanceError
- raise WebError.new(status: 400, message: "該当するユーザが存在しません。")
+ raise WebError.new(:status => 400, :message => '該当するユーザが存在しません。')
end
goPage :user_edit
end
id = session[:userId]
edit_id = params[:editId]
checkSession(id)
- if (not UserAccount.checkAdmin(id))
- raise WebError.new(status: 405, message: "管理者アカウントでないと操作できません。")
+ if !UserAccount.checkAdmin(id)
+ raise WebError.new(:status => 405, :message => '管理者アカウントでないと操作できません。')
end
+
begin
user = UserAccount.getUser(id)
edit_user = UserAccount.getUser(edit_id)
@admin_type = true
- @is_admin = UserAccount.checkAdmin(id);
+ @is_admin = UserAccount.checkAdmin(id)
@id = edit_id
@username = user.full_name
@editname = edit_user.full_name
@account = edit_user.user_name
@email = edit_user.email
rescue UserAccount::NotFoundInstanceError
- raise WebError.new(status: 400, message: "該当するユーザが存在しません。")
+ raise WebError.new(:status => 400, :message => '該当するユーザが存在しません。')
end
goPage :user_edit
end
-
+
# ユーザ情報編集ページ(POST)
# @post_param name [String] ログインユーザ名,
# @post_param try_pass [String] 旧パスワード
# @raise [WebError] ユーザ情報編集失敗
post '/user_edit' do
id = session[:userId]
- name = params[:name]; full_name = params[:full_name]
- email = params[:email]; try_pass = params[:try_pass]
+ name = params[:name]
+ full_name = params[:full_name]
+ email = params[:email]
+ try_pass = params[:try_pass]
new_pass = params[:new_pass]
-
+
checkSession(id)
begin
- if (new_pass != "")
+ if new_pass != ''
check_id = UserAccount.checkPasswd(name, try_pass)
- if (check_id != id)
- raise StandardError, "アカウント名とIDが不正"
+ if check_id != id
+ raise StandardError, 'アカウント名とIDが不正'
end
end
- params = {passwd: new_pass,
- full_name: full_name,
- email: email}
+ params = { :passwd => new_pass, :full_name => full_name, :email => email }
UserAccount.updateUser(id, params)
redirect to('/user_home')
rescue UserAccount::NotFoundInstanceError,
UserAccount::AuthenticationError
- raise WebError.new(status: 400, message: "ユーザ情報の編集に失敗しました。", refs: "/user_edit")
+ raise WebError.new(:status => 400, :message => 'ユーザ情報の編集に失敗しました。',
+ :refs => '/user_edit')
end
end
full_name = params[:full_name]
email = params[:email]
new_pass = params[:new_pass]
-
+
checkSession(id)
- if (not UserAccount.checkAdmin(id))
- raise WebError.new(status: 405, message: "管理者アカウントでないと操作できません。")
+ if !UserAccount.checkAdmin(id)
+ raise WebError.new(:status => 405, :message => '管理者アカウントでないと操作できません。')
end
+
begin
- params = {passwd: new_pass,
- full_name: full_name,
- email: email}
+ params = { :passwd => new_pass, :full_name => full_name, :email => email }
UserAccount.updateUser(edit_id, params)
redirect to('/user_list')
rescue UserAccount::NotFoundInstanceError,
UserAccount::AuthenticationError
- raise WebError.new(status: 400, message: "ユーザ情報の編集に失敗しました。", refs: "/user_edit/#{edit_id}")
+ raise WebError.new(:status => 400, :message => 'ユーザ情報の編集に失敗しました。',
+ :refs => "/user_edit/#{edit_id}")
end
end
book_update_f = false
session[:book_update_f] = book_update_f
checkSession(id)
- if (not UserAccount.checkAdmin(id))
- raise WebError.new(status: 405, message: "管理者アカウントでないと操作できません。")
+ if !UserAccount.checkAdmin(id)
+ raise WebError.new(:status => 405, :message => '管理者アカウントでないと操作できません。')
end
+
begin
user = UserAccount.getUser(id)
- @user_list = UserAccount.getUserList(id);
+ @user_list = UserAccount.getUserList(id)
@username = user.full_name
- @is_admin = UserAccount.checkAdmin(id);
+ @is_admin = UserAccount.checkAdmin(id)
rescue UserAccount::AuthenticationError
- raise WebError.new(status: 405, message: "管理者でしか利用できません。")
+ raise WebError.new(:status => 405, :message => '管理者でしか利用できません。')
end
goPage :user_list
end
-
# ユーザ情報の削除
# @path_param [Integer] deletId 削除対象のユーザId
get '/user_delete/:deleteId' do
cache_control :public, :must_revalidate, :max_age => 30
id = session[:userId]
- delete_id = params[:deleteId]
+ delete_id = params[:deleteId]
checkSession(id)
- if (not UserAccount.checkAdmin(id))
- raise WebError.new(status: 405, message: "管理者アカウントでないと操作できません。")
+ if !UserAccount.checkAdmin(id)
+ raise WebError.new(:status => 405, :message => '管理者アカウントでないと操作できません。')
end
+
begin
user = UserAccount.getUser(id)
@delete_user = UserAccount.getUser(delete_id)
@username = user.full_name
rescue UserAccount::NotFoundInstanceError
- raise WebError.new(status: 404, message: "ユーザ情報が存在しません。")
+ raise WebError.new(:status => 404, :message => 'ユーザ情報が存在しません。')
end
goPage :user_delete
end
get '/user_delete/result/:deleteId' do
cache_control :public, :must_revalidate, :max_age => 30
id = session[:userId]
- delete_id = params[:deleteId]
+ delete_id = params[:deleteId]
checkSession(id)
- if (not UserAccount.checkAdmin(id))
- raise WebError.new(status: 405, message: "管理者アカウントでないと操作できません。")
+ if !UserAccount.checkAdmin(id)
+ raise WebError.new(:status => 405, :message => '管理者アカウントでないと操作できません。')
end
+
begin
BookManager.deleteBookCollectOfUser(delete_id)
UserAccount.deleteUser(delete_id)
-
rescue UserAccount::NotFoundInstanceError
- raise WebError.new(status: 404, message: "ユーザ情報が存在しません。")
+ raise WebError.new(:status => 404, :message => 'ユーザ情報が存在しません。')
rescue UserAccount::AuthenticationError
- raise WebError.new(status: 405, message: "管理者でしか利用できません。")
+ raise WebError.new(:status => 405, :message => '管理者でしか利用できません。')
end
redirect to('/user_list')
end
-
+
# 蔵書の登録ページ
# @raise [WebError] セッションの期限切れ
# @raise [WebError] ユーザID不正
user = UserAccount.getUser(id)
@id = id
@username = user.full_name
- @book_info = Hash.new
+ @book_info = {}
@update_f = book_update_f
@is_admin = UserAccount.checkAdmin(id)
rescue UserAccount::NotFoundInstanceError
- raise WebError.new(status: 404, message: "ユーザ情報が存在しません。")
+ raise WebError.new(:status => 404, :message => 'ユーザ情報が存在しません。')
end
goPage :book_regist
end
@is_admin = UserAccount.checkAdmin(id)
@is_admin_books = is_admin_books
rescue UserAccount::NotFoundInstanceError
- raise WebError.new(status: 404, message: "ユーザ情報が存在しません。")
+ raise WebError.new(:status => 404, :message => 'ユーザ情報が存在しません。')
end
- goPage :book_regist
+ goPage :book_regist
end
-
+
# 蔵書の登録/編集 (POST)
# @post_param isbn [String] ISBN
# @post_param title [String] 書名
book_update_f = session[:book_update_f]
checkSession(id)
is_admin_books = UserAccount.checkAdmin(id) & session[:is_admin]
-
+
# 書影の新規登録があるかを確認
- image_f = (params[:cover_base64] != nil)
+ image_f = !params[:cover_base64].nil?
# 書籍の設定情報を選出
book_info = makeBookInfo(params, image_f)
-
+
begin
isbn = book_info[:isbn]
# 書籍情報の更新
- if (BookManager.isBook(isbn))
+ if BookManager.isBook(isbn)
book_info.delete(:isbn)
BookManager.updateBook(isbn, book_info)
else
end
cover_image = setBookImage(image_f, params, book_info[:cover_uri])
-
+
# 書影情報の更新
- if (cover_image[:data] != nil)
+ if !cover_image[:data].nil?
image_hash = BookManager.addBookCover(isbn, cover_image)
- cover_uri = '/book_image/' + image_hash
- BookManager.updateBook(isbn, cover_uri: cover_uri)
+ cover_uri = "/book_image/#{image_hash}"
+ BookManager.updateBook(isbn, :cover_uri => cover_uri)
end
- if (!is_admin_books)
+ if !is_admin_books
# 蔵書情報の更新
- summary = params[:summary]; book_rank = params[:book_rank]
- if (book_update_f)
+ summary = params[:summary]
+ book_rank = params[:book_rank]
+ if book_update_f
BookManager.updateBookCollect(isbn, id, summary, book_rank)
else
BookManager.createBookCollect(isbn, id, summary, book_rank)
end
- end
+ end
rescue BookManager::NotFoundInstanceError,
BookManager::AlreadyInstanceError
- raise WebError.new(status: 400, message: "蔵書情報の登録に失敗しました。", refs: "/book_regist")
+ raise WebError.new(:status => 400, :message => '蔵書情報の登録に失敗しました。',
+ :refs => '/book_regist')
end
redirect to("/book_info/#{isbn}")
end
post '/book_search_isbn' do
id = session[:userId]
checkSession(id)
-
+
isbn = params[:isbn]
begin
user = UserAccount.getUser(id)
@id = id
@username = user.full_name
- if (isbn != nil && isbn.length > 0)
+ if !isbn.nil? && !isbn.empty?
@book_info = BookManager.searchISBN(isbn, id)
end
@is_admin = UserAccount.checkAdmin(id)
rescue UserAccount::NotFoundInstanceError
- raise WebError.new(status: 404, message: "ユーザ情報が存在しません。")
+ raise WebError.new(:status => 404, :message => 'ユーザ情報が存在しません。')
rescue BookManager::AlreadyInstanceError
- raise WebError.new(status: 409, message: "あなたの蔵書にすでに該当する書籍があります。", refs: "/book_regist")
+ raise WebError.new(:status => 409, :message => 'あなたの蔵書にすでに該当する書籍があります。',
+ :refs => 'book_regist')
rescue BookManager::FailedGetInstance
- raise WebError.new(status: 500, message: "ISBNによる書籍検索に失敗しました。", refs: "/book_regist")
+ raise WebError.new(:status => 500, :message => 'ISBNによる書籍検索に失敗しました。',
+ :refs => '/book_regist')
end
- if (isbn == nil || isbn.length == 0)
- @book_info = Hash.new
- @warning = "ISBNを入力してください。"
- elsif (@book_info[:title] == nil )
- @warning = "ISBN探索にて対象の書籍が見付かりませんでした。"
+ if isbn.nil? || isbn.empty?
+ @book_info = {}
+ @warning = 'ISBNを入力してください。'
+ elsif @book_info[:title].nil?
+ @warning = 'ISBN探索にて対象の書籍が見付かりませんでした。'
end
goPage :book_regist
end
-
+
# 書影データのアップロード
# @post_param [Hash] cover_file イメージファイル情報
# @raise [WebError] セッションの期限切れ
begin
user = UserAccount.getUser(id)
rescue UserAccount::NotFoundInstanceError
- raise WebError.new(status: 404, message: "ユーザ情報が存在しません。")
+ raise WebError.new(:status => 404, :message => 'ユーザ情報が存在しません。')
end
-
+
@id = id
@username = user.full_name
@book_info = params
@is_admin = UserAccount.checkAdmin(id)
@update_f = session[:book_update_f]
cover_image = getUploadData(params[:cover_file])
- if (cover_image != nil)
+ if !cover_image.nil?
base64 = Base64.encode64(cover_image[:data])
mime_type = cover_image[:mime_type]
@book_info[:cover_base64] = base64
@book_info[:mime_type] = mime_type
- @book_info[:cover_uri] = "data:" + mime_type + ";base64," + base64
+ @book_info[:cover_uri] = "data:#{mime_type};base64,#{base64}"
else
- @warning = "書影のファイルを指定してください"
+ @warning = '書影のファイルを指定してください'
end
goPage :book_regist
end
-
# 書影の表示
# @path_param [String] hash 書影のハッシュキー
get '/book_image/:hash' do
cache_control :public, :must_revalidate, :max_age => 30
image_hash = params[:hash]
book_cover = BookManager.getBookCover(image_hash)
-
+
status 200
headers \
- "Content-Type" => "image/jpeg",
- "Last-Modified" => book_cover.create_at.httpdate
+ 'Content-Type' => 'image/jpeg',
+ 'Last-Modified' => book_cover.create_at.httpdate
body book_cover.cover
-
end
# 蔵書情報の取得ページ
BookManager.getBookCollect(isbn, id)
@is_admin = UserAccount.checkAdmin(id)
rescue UserAccount::NotFoundInstanceError
- raise WebError.new(status: 404, message: "ユーザ情報が存在しません。")
+ raise WebError.new(:status => 404, :message => 'ユーザ情報が存在しません。')
rescue BookManager::NotFoundInstanceError
- raise WebError.new(status: 404, message: "蔵書情報が見付かりません。", refs: "/user_home")
+ raise WebError.new(:status => 404, :message => '蔵書情報が見付かりません。',
+ :refs => '/user_home')
end
goPage :book_info
end
# @raise [WebError] セッションの期限切れ
get '/book_list' do
checkSession(session[:userId])
- session[:list_status] = {position: {start: 0, step: 10},
- find_status: nil}
+ session[:list_status] = { :position => { :start => 0, :step => 10 },
+ :find_status => nil }
session[:is_admin] = false
redirect to('/book_list/main')
end
-
+
# 管理用の蔵書一覧の取得(トリガページ)
# @raise [WebError] セッションの期限切れ
get '/book_admin' do
checkSession(session[:userId])
- session[:list_status] = {position: {start: 0, step: 10},
- find_status: nil}
+ session[:list_status] = { :position => { :start => 0, :step => 10 },
+ :find_status => nil }
session[:is_admin] = true
redirect to('/book_list/main')
end
-
+
# 蔵書一覧の取得(表示件数変更ページ)
# @raise [WebError] セッションの期限切れ
post '/book_list/change_step' do
checkSession(session[:userId])
step = params[:step].to_i
- session[:list_status][:position] = {start: 0, step: step}
+ session[:list_status][:position] = { :start => 0, :step => step }
redirect to('/book_list/main')
end
-
+
# 蔵書一覧の取得(次ページ)
# @raise [WebError] セッションの期限切れ
post '/book_list/next' do
session[:list_status][:position][:start] += step
redirect to('/book_list/main')
end
-
+
# 蔵書一覧の取得(前ページ)
# @raise [WebError] セッションの期限切れ
post '/book_list/before' do
redirect to('/book_list/main')
end
-
# 蔵書一覧の取得(検索後)
# @raise [WebError] セッションの期限切れ
post '/book_list/find' do
find_status = session[:list_status][:find_status]
find_key = params[:kind].to_sym
find_value = params[:find_value]
- if (find_status == nil)
- find_status = {find_key => find_value}
+ if find_status.nil?
+ find_status = { find_key => find_value }
else
find_status[find_key] = find_value
end
session[:list_status][:position][:start] = 0
redirect to('/book_list/main')
end
-
+
# 蔵書一覧の取得 (蔵書情報取得から)
# @raise [WebError] セッションの期限切れ
get '/book_list/fromInfo' do
checkSession(session[:userId])
list_status = session[:list_status]
- if (list_status == nil)
- session[:list_status] = {position: {start:0, step: 10},
- find_status: nil}
+ if list_status.nil?
+ session[:list_status] = { :position => { :start => 0, :step => 10 },
+ :find_status => nil }
end
redirect to('/book_list/main')
end
-
+
# 蔵書一覧の取得(メインページ)
# @raise [WebError] セッションの期限切れ
get '/book_list/main' do
@is_admin = UserAccount.checkAdmin(id)
@is_admin_books = is_admin_books
rescue UserAccount::NotFoundInstanceError
- raise WebError.new(status: 404, message: "ユーザ情報が存在しません。")
+ raise WebError.new(:status => 404, :message => 'ユーザ情報が存在しません。')
end
position = list_status[:position]
find_status = list_status[:find_status]
@book_list, @full_size = is_admin_books ?
BookManager.narrowBooks(position[:start],
- position[:step], find_status) :
+ position[:step], find_status) :
BookManager.narrowBookOfId(id, position[:start],
position[:step], find_status)
@start = position[:start]
@step = position[:step]
@find_status = find_status
- if (@book_list == nil)
- raise WebError.new(status: 404, message: "対象の蔵書が見つかりません。", refs: "/user_home")
+ if @book_list.nil?
+ raise WebError.new(:status => 404, :message => '対象の蔵書が見つかりません。',
+ :refs => '/user_home')
end
goPage :book_list
get '/book_delete/:isbn' do
cache_control :public, :must_revalidate, :max_age => 30
id = session[:userId]
- isbn = params[:isbn]
+ isbn = params[:isbn]
checkSession(id)
begin
user = UserAccount.getUser(id)
@id = id
@username = user.full_name
@book_info = is_admin_books ? BookManager.getBook(isbn) :
- BookManager.getBookCollect(isbn, id)
+ BookManager.getBookCollect(isbn, id)
@is_admin = UserAccount.checkAdmin(id)
rescue UserAccount::NotFoundInstanceError
- raise WebError.new(status: 404, message: "ユーザ情報が存在しません。")
+ raise WebError.new(:status => 404, :message => 'ユーザ情報が存在しません。')
rescue BookManager::NotFoundInstanceError
- raise WebError.new(status: 404, message: "蔵書情報が見付かりません。", refs: "/user_home")
+ raise WebError.new(:status => 404, :message => '蔵書情報が見付かりません。',
+ :refs => '/user_home')
end
goPage :book_delete
end
cache_control :public, :must_revalidate, :max_age => 30
id = session[:userId]
is_admin_books = UserAccount.checkAdmin(id) & session[:is_admin]
- isbn = params[:isbn]
+ isbn = params[:isbn]
begin
is_admin_books ? BookManager.deleteBook(isbn) :
BookManager.deleteBookCollect(isbn, id)
rescue UserAccount::NotFoundInstanceError
- raise WebError.new(status: 404, message: "ユーザ情報が存在しません。")
+ raise WebError.new(:status => 404, :message => 'ユーザ情報が存在しません。')
rescue BookManager::NotFoundInstanceError
- raise WebError.new(status: 404, message: "蔵書情報が見付かりません。", refs: "/user_home")
+ raise WebError.new(:status => 404, :message => '蔵書情報が見付かりません。',
+ :refs => '/user_home')
end
redirect to('/user_home')
end
-
+
# ログアウトページ
get '/logout' do
cache_control :public, :must_revalidate, :max_age => 30
goPage :logout
end
-
# エラーページ
error WebError do
e = env['sinatra.error']
goPage :error
end
end
-
# coding: utf-8
+# frozen_string_literal: true
+
# 書籍系DBアクセス処理
# @author OHASHI, Norikazu
require 'mysql2'
require 'httpclient'
require 'json'
-require "rexml/document"
+require 'rexml/document'
require 'digest/sha2'
# DB設定ファイルの読み込み
ActiveRecord::Base.configurations = YAML.load_file(db_config)
ActiveRecord::Base.establish_connection(:development)
-#書籍情報
+# 書籍情報
class Book < ActiveRecord::Base
# 正規表現によるレコード探索
# @param [Symbol] key カラム名
end
end
-#蔵書情報
+# 蔵書情報
class BookCollection < ActiveRecord::Base
# 正規表現によるレコード探索
# @param [Symbol] key カラム名
end
end
-#書影情報
+# 書影情報
class BookCover < ActiveRecord::Base
# 正規表現によるレコード探索
# @param [Symbol] key カラム名
end
end
-#ユーザ書籍情報
+# ユーザ書籍情報
class BookFull < ActiveRecord::Base
# 正規表現によるレコード探索
# @param [Symbol] key カラム名
# ユーザ管理
class BookManager
-
# 対象の書籍情報がすでに存在している
class AlreadyInstanceError < StandardError
end
# Google Books から取得
SEARCH_ON_GBS = 3
-
+
# 国立国会図書館 から取得
SEARCH_ON_NDL = 4
# @return [String] 変換後のISBN
def self.toIsbn(isbn)
if isbn.kind_of?(String)
- return isbn.gsub(/-/, "")
+ return isbn.gsub(/-/, '')
end
+
return isbn
end
# 蔵書テーブルから ISBN の蔵書情報を削除
# @param [String] isbn 処理対象のISBN
def self.deleteBookOfCollection(isbn)
- begin
- colections = BookCollection.where(isbn: isbn)
- BookCollection.transcation do
- colections.each do |item|
- item.destroy!
- end
+ colections = BookCollection.where(:isbn => isbn)
+ BookCollection.transcation do
+ colections.each do |item|
+ item.destroy!
end
- rescue
- raise DbAccessError
end
+ rescue StandardError
+ raise DbAccessError
end
-
# ISBNから書籍情報検索してハッシュで返却
- # @param [String] isbn
+ # @param [String] isbn
# @return [Hash] 書籍情報
def self.getHashOfBooks(isbn)
- book = Book.find_by(isbn: isbn)
- if (book == nil)
+ book = Book.find_by(:isbn => isbn)
+ if book.nil?
return nil
end
+
book_hash = {
- search_type: SEARCH_ON_BOOKS,
- isbn: book.isbn,
- title: book.title,
- subtitle: book.subtitle,
- volume: book.volume,
- series: book.series,
- author: book.author,
- original_author: book.original_author,
- illustrator: book.illustrator,
- translator: book.translator,
- supervisor: book.supervisor,
- publisher: book.publisher,
- pubdate: book.pubdate,
- cover_uri: book.cover_uri
+ :search_type => SEARCH_ON_BOOKS,
+ :isbn => book.isbn,
+ :title => book.title,
+ :subtitle => book.subtitle,
+ :volume => book.volume,
+ :series => book.series,
+ :author => book.author,
+ :original_author => book.original_author,
+ :illustrator => book.illustrator,
+ :translator => book.translator,
+ :supervisor => book.supervisor,
+ :publisher => book.publisher,
+ :pubdate => book.pubdate,
+ :cover_uri => book.cover_uri
}
return book_hash
end
client = HTTPClient.new
res = client.get(cover_uri)
- if (res.status == 200)
+ if res.status == 200
return cover_uri
else
return nil
end
end
-
+
# 著者種別から各関係者ハッシュのキーを取得
# @param [String] job 著者種別
# @return [Symbol] ハッシュキー
def self.getParsonKey(job)
case job
- when "著", "著者", "作者", "作" then
+ when '著', '著者', '作者', '作'
key = :author
- when "イラスト", "画", "作画" then
+ when 'イラスト', '画', '作画'
key = :illustrator
- when "翻訳", "訳" then
+ when '翻訳', '訳'
key = :translator
- when "原著", "原" then
+ when '原著', '原'
key = :original_author
- when "監修", "監" then
+ when '監修', '監'
key = :supervisor
else
key = :author
end
return key
end
-
+
# openBDの著者情報から各関係者ハッシュを作成
# @param [String] parsons 著者情報
# @return [Hash] 関係者ハッシュ
def self.getParsonsFromOpenBD(parsons)
parsons_hash = {}
- parsons.split(" ").each do |item|
- name, job = item.split("/")
+ parsons.split(' ').each do |item|
+ name, job = item.split('/')
key = getParsonKey(job)
- if ( parsons_hash[key] == nil || parsons_hash[key] = "")
+ if parsons_hash[key].nil? || parsons_hash[key].empty?
parsons_hash[key] = name
else
- parsons_hash[key] += ", " + name
+ parsons_hash[key] += ", #{name}"
end
end
return parsons_hash
end
-
+
# ISBNからopenBDを検索してハッシュで返却
- # @param [String] isbn
+ # @param [String] isbn
# @return [Hash] 書籍情報
def self.getHashOfOpenBD(isbn)
client = HTTPClient.new
- res = client.get("http://api.openbd.jp/v1/get", isbn: isbn)
- if (res.status != HTTP::Status::OK)
+ res = client.get('http://api.openbd.jp/v1/get', :isbn => isbn)
+ if res.status != HTTP::Status::OK
raise FailedGetInstance
end
+
books = JSON.parse(res.body)
- if (books.size > 1)
+ if books.size > 1
raise FailedGetInstance
end
- if (books.size < 1)
+
+ if books.empty?
return nil
end
- if (books[0] == nil)
+
+ if books[0].nil?
return nil
end
- book = books[0]["summary"]
- parsons = getParsonsFromOpenBD(book["author"])
+
+ book = books[0]['summary']
+ parsons = getParsonsFromOpenBD(book['author'])
book_hash = {
- search_type: SEARCH_ON_OPENBD,
- isbn: book["isbn"],
- title: book["title"],
- volume: book["volume"],
- series: book["series"],
- author: parsons[:author],
- original_author: parsons[:original_author],
- translator: parsons[:translator],
- supervisor: parsons[:supervisor],
- illustrator: parsons[:illustrator],
- publisher: book["publisher"],
- pubdate: book["pubdate"],
- cover_uri: (book["cover"] != nil) && (book["cover"] != "") ? book["cover"] : getCover(isbn)
+ :search_type => SEARCH_ON_OPENBD,
+ :isbn => book['isbn'],
+ :title => book['title'],
+ :volume => book['volume'],
+ :series => book['series'],
+ :author => parsons[:author],
+ :original_author => parsons[:original_author],
+ :translator => parsons[:translator],
+ :supervisor => parsons[:supervisor],
+ :illustrator => parsons[:illustrator],
+ :publisher => book['publisher'],
+ :pubdate => book['pubdate'],
+ :cover_uri => book['cover'].nil? || book['cover'].empty? ? getCover(isbn) : book['cover']
}
return book_hash
end
-
+
# 国立国会図書館の著者情報から各関係者ハッシュを作成
# @param [String] parsons 著者情報
# @return [Hash] 関係者ハッシュ
def self.getParsonsFromNDL(parsons)
parsons_hash = {}
parsons.each do |item|
- splitData = item.split(" ")
- name = splitData[0...splitData.size-1].join(" ")
- job = splitData[splitData.size-1]
+ split_data = item.split(' ')
+ name = split_data[0...split_data.size - 1].join(' ')
+ job = split_data[split_data.size - 1]
key = getParsonKey(job)
- if ( parsons_hash[key] == nil || parsons_hash[key] = "")
+ if parsons_hash[key].nil? || parsons_hash[key].empty?
parsons_hash[key] = name
else
- parsons_hash[key] += ", " + name
+ parsons_hash[key] += ", #{name}"
end
end
return parsons_hash
end
-
+
# ISBNから国立図書館を検索してハッシュで返却
- # @param [String] isbn
+ # @param [String] isbn
# @return [Hash] 書籍情報
def self.getHashOfNDL(isbn)
client = HTTPClient.new
- res = client.get("https://iss.ndl.go.jp/api/sru",
- {'operation' => 'searchRetrieve',
- 'query' => "isbn=#{isbn}",
- 'recordSchema' => 'dcndl'})
- if (res.status != HTTP::Status::OK)
+ res = client.get('https://iss.ndl.go.jp/api/sru',
+ { 'operation' => 'searchRetrieve',
+ 'query' => "isbn=#{isbn}",
+ 'recordSchema' => 'dcndl' })
+ if res.status != HTTP::Status::OK
raise FailedGetInstance
end
+
library_param = REXML::Document.new(res.body)
book_num = library_param.elements['//searchRetrieveResponse/numberOfRecords'].text.to_i
- if (book_num < 1)
+ if book_num < 1
return nil
end
+
element_str = library_param.elements["//searchRetrieveResponse/records/record[#{book_num}]/recordData"].text
book_xml = REXML::Document.new(element_str)
book = book_xml.elements['//rdf:RDF/dcndl:BibResource/']
end
parsons = getParsonsFromNDL(creators)
book_hash = {
- search_type: SEARCH_ON_NDL,
- isbn: isbn,
- title: book.elements['dcterms:title'] != nil ? book.elements['dcterms:title'].text : nil,
- volume: book.elements['dcndl:volume/rdf:Description/rdf:value'] != nil ? book.elements['dcndl:volume/rdf:Description/rdf:value'].text.gsub(/[^\d]/, "").to_i : nil,
- series: book.elements['dcndl:seriesTitle/rdf:Description/rdf:value'] != nil ? book.elements['dcndl:seriesTitle/rdf:Description/rdf:value'].text : nil,
- author: parsons[:author],
- original_author: parsons[:original_author],
- translator: parsons[:translator],
- supervisor: parsons[:supervisor],
- illustrator: parsons[:illustrator],
- publisher: book.elements['dcterms:publisher/foaf:Agent/foaf:name'] != nil ? book.elements['dcterms:publisher/foaf:Agent/foaf:name'].text : nil,
- pubdate: book.elements['dcterms:date'] != nil ? book.elements['dcterms:date'].text.gsub(".","-") : nil,
- cover_uri: getCover(isbn)
+ :search_type => SEARCH_ON_NDL,
+ :isbn => isbn,
+ :title => book.elements['dcterms:title'].nil? ? nil : book.elements['dcterms:title'].text,
+ :volume => book.elements['dcndl:volume/rdf:Description/rdf:value'].nil? ? nil :
+ book.elements['dcndl:volume/rdf:Description/rdf:value'].text.gsub(/[^\d]/, '').to_i,
+ :series => book.elements['dcndl:seriesTitle/rdf:Description/rdf:value'].nil? ? nil :
+ book.elements['dcndl:seriesTitle/rdf:Description/rdf:value'].text,
+ :author => parsons[:author],
+ :original_author => parsons[:original_author],
+ :translator => parsons[:translator],
+ :supervisor => parsons[:supervisor],
+ :illustrator => parsons[:illustrator],
+ :publisher => book.elements['dcterms:publisher/foaf:Agent/foaf:name'].nil? ? nil :
+ book.elements['dcterms:publisher/foaf:Agent/foaf:name'].text,
+ :pubdate => book.elements['dcterms:date'].nil? ? nil : book.elements['dcterms:date'].text.gsub('.', '-'),
+ :cover_uri => getCover(isbn)
}
return book_hash
end
# ISBNからGoogleBooksを検索してハッシュで返却
- # @param [String] isbn
+ # @param [String] isbn
# @return [Hash] 書籍情報
def self.getHashOfGBS(isbn)
client = HTTPClient.new
- res = client.get("https://www.googleapis.com/books/v1/volumes", q: "isbn:#{isbn}")
- if (res.status != HTTP::Status::OK)
+ res = client.get('https://www.googleapis.com/books/v1/volumes', :q => "isbn:#{isbn}")
+ if res.status != HTTP::Status::OK
raise FailedGetInstance
end
+
books = JSON.parse(res.body)
- if (books["totalItems"] > 1)
+ if books['totalItems'] > 1
raise FailedGetInstance
end
- if (books["totalItems"] < 1)
+
+ if books['totalItems'] < 1
return nil
end
- if (books["items"] == nil || books["items"][0] == nil)
+
+ if books['items'].nil? || books['items'][0].nil?
return nil
end
- book = books["items"][0]["volumeInfo"]
+
+ book = books['items'][0]['volumeInfo']
book_hash = {
- search_type: SEARCH_ON_GBS,
- isbn: isbn,
- title: book["title"],
- volume: book["volume"],
- series: nil,
- author: book["authors"].join(", "),
- original_author: nil,
- translator: nil,
- supervisor: nil,
- illustrator:nil,
- publisher: book["publisher"],
- pubdate: book["publishedDate"],
- cover_uri: (book["imageLinks"] != nil) ? book["imageLinks"]["thumbnail"] : getCover(isbn)
+ :search_type => SEARCH_ON_GBS,
+ :isbn => isbn,
+ :title => book['title'],
+ :volume => book['volume'],
+ :series => nil,
+ :author => book['authors'].join(', '),
+ :original_author => nil,
+ :translator => nil,
+ :supervisor => nil,
+ :illustrator => nil,
+ :publisher => book['publisher'],
+ :pubdate => book['publishedDate'],
+ :cover_uri => book['imageLinks'].nil? ? getCover(isbn) : book['imageLinks']['thumbnail']
}
return book_hash
end
-
+
# 各ユーザ用の書籍情報を作成
# @param [Book] book 書籍情報
# @param [BookCollection] book_collect 蔵書情報
# @return [Hash] 書籍情報
def self.createBookHash(book, book_collect)
- {
- isbn: book[:isbn],
- title: book[:title],
- subtitle: book[:subtitle],
- volume: book[:volume],
- series: book[:series],
- author: book[:author],
- original_author: book[:original_author],
- translator: book[:translator],
- supervisor: book[:supervisor],
- illustrator: book[:illustrator],
- publisher: book[:publisher],
- pubdate: book[:pubdate],
- cover_uri: book[:cover_uri],
- summary: book_collect[:summary],
- book_rank: book_collect[:book_rank]
+ {
+ :isbn => book[:isbn],
+ :title => book[:title],
+ :subtitle => book[:subtitle],
+ :volume => book[:volume],
+ :series => book[:series],
+ :author => book[:author],
+ :original_author => book[:original_author],
+ :translator => book[:translator],
+ :supervisor => book[:supervisor],
+ :illustrator => book[:illustrator],
+ :publisher => book[:publisher],
+ :pubdate => book[:pubdate],
+ :cover_uri => book[:cover_uri],
+ :summary => book_collect[:summary],
+ :book_rank => book_collect[:book_rank]
}
end
-
+
private_class_method :toIsbn, :deleteBookOfCollection,
:getHashOfBooks, :getParsonKey, :getCover,
:getParsonsFromOpenBD, :getHashOfOpenBD,
cover = cover_image[:data]
mime_type = cover_image[:mime_type]
key_hash = Digest::SHA256.hexdigest(cover)
- book_cover = BookCover.find_by(isbn: isbn)
- if (book_cover != nil)
- if (not book_cover.destroy)
- raise DbAccessError
- end
+ book_cover = BookCover.find_by(:isbn => isbn)
+ if !book_cover.nil? && !book_cover.destroy
+ raise DbAccessError
end
+
book_cover = BookCover.new
book_cover.key_hash = key_hash
book_cover.isbn = isbn
book_cover.cover = cover
book_cover.create_at = DateTime.now
book_cover.update_at = DateTime.now
- if (not book_cover.save)
+ if !book_cover.save
raise DbAccessError
end
+
return key_hash
-
end
# 書影イメージを取得
# @param [String] key_hash 書影イメージのハッシュ
# @return [BookCover] 書影情報
def self.getBookCover(key_hash)
- book_cover = BookCover.find_by(key_hash: key_hash)
- if (book_cover == nil)
+ book_cover = BookCover.find_by(:key_hash => key_hash)
+ if book_cover.nil?
raise NotFoundInstanceError
end
+
return book_cover
end
# @param [String] isbn_str 削除対象のISBN
def self.deleteBookCover(isbn_str)
isbn = toIsbn(isbn_str)
- book_cover = BookCover.find_by(isbn: isbn)
- if (book_cover)
+ book_cover = BookCover.find_by(:isbn => isbn)
+ if book_cover
raise NotFoundInstanceError
end
- if (not book_cover.destroy)
+ if !book_cover.destroy
raise DbAccessError
end
end
# @return [Boolean] 対象書籍の有無を確認
def self.isBook(isbn_str)
isbn = toIsbn(isbn_str)
- book = Book.find_by(isbn: isbn)
- return book != nil
+ book = Book.find_by(:isbn => isbn)
+ return !book.nil?
end
# 書籍探索(ISBN)
# @return [Hash] 書籍情報
def self.searchISBN(isbn_str, user_id)
isbn = toIsbn(isbn_str)
- collection = BookCollection.find_by(isbn: isbn, user_id: user_id)
- if (collection != nil)
- #ユーザが保持しているのですでにあることを例外で通知
+ collection = BookCollection.find_by(:isbn => isbn, :user_id => user_id)
+ if !collection.nil?
+ # ユーザが保持しているのですでにあることを例外で通知
raise AlreadyInstanceError
end
+
book_info = getHashOfBooks(isbn)
- if (book_info == nil)
+ if book_info.nil?
book_info = getHashOfOpenBD(isbn)
end
- if (book_info == nil)
+ if book_info.nil?
book_info = getHashOfNDL(isbn)
end
- if (book_info == nil)
+ if book_info.nil?
book_info = getHashOfGBS(isbn)
end
- if (book_info == nil)
- book_info = {isbn: isbn}
+ if book_info.nil?
+ book_info = { :isbn => isbn }
end
+ p "book_info=#{book_info}"
return book_info
end
# @param [Hash] book_info 書籍情報のハッシュ
def self.createBook(book_info)
isbn = book_info[:isbn]
- if (Book.find_by(isbn: isbn) != nil)
+ if !Book.find_by(:isbn => isbn).nil?
raise AlreadyInstanceError
end
+
book = Book.new
book_info.each do |key, value|
- if (key == :pubdate)
+ if key == :pubdate
book.pubdate = Date.parse(value)
else
- method = key.to_s + "="
+ method = "#{key}="
book.send(method, value)
end
end
# 登録日時の設定
book.create_at = DateTime.now
book.update_at = DateTime.now
- if (not book.save)
+ if !book.save
raise DbAccessError
end
end
# @return [Book]
def self.getBook(isbn_str)
isbn = toIsbn(isbn_str)
- book = Book.find_by(isbn: isbn)
- if (book == nil)
+ book = Book.find_by(:isbn => isbn)
+ if book.nil?
# 対象の書籍情報がなかった。
raise NotFoundInstanceError
end
+
return book
end
# @param [Hash] columns 変更するカラムと値のハッシュ
def self.updateBook(isbn_str, columns)
isbn = toIsbn(isbn_str)
- book = Book.find_by(isbn: isbn)
+ book = Book.find_by(:isbn => isbn)
change_f = false
- if (book == nil)
+ if book.nil?
raise NotFoundInstanceError
end
columns.each do |key, value|
- if ((value == nil))
- # 値がない、値が空文字の場合は対象としない。
- next
- end
- if (value != book.send(key))
- if (key == :pubdate)
- book.pubdate = Date.parse(value)
- else
- method = key.to_s + "="
- book.send(method, value)
- end
- change_f = true
+ # 値がない、値が空文字の場合は対象としない。
+ next if value.nil?
+ next if value == book.send(key)
+
+ if key == :pubdate
+ book.pubdate = Date.parse(value)
+ else
+ method = "#{key}="
+ book.send(method, value)
end
+ change_f = true
end
-
+
# 更新内容の適用
- if (change_f)
+ if change_f
book.update_at = DateTime.now
- if (not book.save)
+ if !book.save
raise DbAccessError
end
end
# @param [Hash] find_keys 検索キー情報
# @return [Array<Book>] 検索結果
def self.findBook(find_keys)
-
books = Book.all
-
- if (find_keys == nil)
+
+ if find_keys.nil?
return books
end
- find_keys.each do |key, value|
- if (books == nil)
+ find_keys.each do |key, value|
+ if books.nil?
break
end
- if (value =~ /^\/(.+)\/$/)
- reg_value = $~[1]
+
+ if value =~ %r{^/(.+)/$}
+ reg_value = Regexp.last_match[1]
books = books.with_regexp(key, reg_value)
else
books = books.where(key => value)
end
return books
end
-
+
# 書籍情報の削除
# @param [String] isbn_str 削除対象のISBN
def self.deleteBook(isbn_str)
isbn = toIsbn(isbn_str)
- book = Book.find_by(isbn: isbn)
- if (book == nil)
+ book = Book.find_by(:isbn => isbn)
+ if book.nil?
# 対象の書籍情報がなかった。
raise NotFoundInstanceError
end
deleteBookOfCollection(isbn)
# 書影情報を削除
- cover = BookCover.find_by(isbn: isbn)
- if (cover != nil)
- if (not cover.destroy)
- raise DbAccessError
- end
+ cover = BookCover.find_by(:isbn => isbn)
+ if !cover.nil? && !cover.destroy
+ raise DbAccessError
end
# 書籍情報を削除
- if (not book.destroy)
+ if !book.destroy
raise DbAccessError
end
end
- #全書籍取得
+ # 全書籍取得
# @param [Integer] start 表示開始位置
# @param [Integer] step 表示数
# @param [Hash] find_keys 検索対象
# @return [Array<Hash>] 絞り込んだ書籍情報
def self.narrowBooks(start, step, find_keys)
return narrowBookList(Book.all,
- start, step, find_keys);
+ start, step, find_keys)
end
-
- #ユーザでの絞り込み
+
+ # ユーザでの絞り込み
# @param [Integer] user_id ユーザID
# @param [Integer] start 表示開始位置
# @param [Integer] step 表示数
# @return [Array<Hash>] 絞り込んだ書籍情報
def self.narrowBookOfId(user_id, start, step, find_keys)
# ユーザに関連する書籍の一覧を取得する。
- return narrowBookList(BookFull.where(user_id: user_id),
- start, step, find_keys);
+ return narrowBookList(BookFull.where(:user_id => user_id),
+ start, step, find_keys)
end
- #指定範囲の書籍一覧を取得
+ # 指定範囲の書籍一覧を取得
# @param [Array<Books>] find_books 探索の一覧
# @param [Integer] start 表示開始位置
# @param [Integer] step 表示数
# @return [Array<Hash>] 絞り込んだ書籍情報
def self.narrowBookList(find_books, start, step, find_keys)
# 条件に合う書籍を検索
- if (find_keys != nil)
- find_keys.each do |key, value|
- if (find_books == nil)
- break
- end
- if (key == :image_unregist)
- # 書影の有無を確認するための検索
- find_books = find_books.where(cover_uri: nil)
- else
- # 通常の要素検索
- if (value =~ /^\/(.+)\/$/)
- reg_value = $~[1]
- find_books = find_books.with_regexp(key, reg_value)
- else
- find_books = find_books.where(key => value)
- end
- end
+ find_keys&.each do |key, value|
+ if find_books.nil?
+ break
+ end
+
+ if key == :image_unregist
+ # 書影の有無を確認するための検索
+ find_books = find_books.where(:cover_uri => nil)
+ elsif value =~ %r{^/(.+)/$}
+ # 通常の要素の正規表現検索
+ reg_value = Regexp.last_match[1]
+ find_books = find_books.with_regexp(key, reg_value)
+ else
+ # 通常の要素の全マッチ検索
+ find_books = find_books.where(key => value)
end
end
narrow_books = find_books.limit(step).offset(start)
return narrow_books, find_books.size
end
- #蔵書情報の取得
+
+ # 蔵書情報の取得
# @param [String] isbn_str 取得対象のISBN
# @param [Integer] user_id 取得対象のユーザID
# @return [Array<Hash>] 絞り込んだ書籍情報
def self.getBookCollect(isbn_str, user_id)
isbn = toIsbn(isbn_str)
- book = Book.find_by(isbn: isbn)
- if (book == nil)
+ book = Book.find_by(:isbn => isbn)
+ if book.nil?
raise NotFoundInstanceError
end
- book_collect = BookCollection.find_by(isbn: isbn, user_id: user_id)
- if (book_collect == nil)
+
+ book_collect = BookCollection.find_by(:isbn => isbn, :user_id => user_id)
+ if book_collect.nil?
raise NotFoundInstanceError
end
+
return createBookHash(book, book_collect)
end
-
+
# 蔵書情報を登録
# @param [String] isbn 登録するISBN
# @param [Integer] user_id 登録対象のユーザID
# @param [string] book_rank ユーザの評価
# @return [BookCollection] 蔵書情報
def self.createBookCollect(isbn, user_id, summary, book_rank)
- if (BookCollection.find_by(isbn: isbn, user_id: user_id) != nil)
+ if !BookCollection.find_by(:isbn => isbn, :user_id => user_id).nil?
raise NotFoundInstanceError
end
-
+
book_collect = BookCollection.new
book_collect.isbn = isbn
book_collect.user_id = user_id
- if ((summary != nil) && (summary != ""))
+ if !summary.nil? && !summary.empty?
book_collect.summary = summary
end
+
book_collect.book_rank = book_rank
book_collect.create_at = DateTime.now
book_collect.update_at = DateTime.now
- if (not book_collect.save)
+
+ if !book_collect.save
raise DbAccessError
end
end
# @param [string] book_rank ユーザの評価
def self.updateBookCollect(isbn_str, user_id, summary, book_rank)
isbn = toIsbn(isbn_str)
- book_collect = BookCollection.find_by(isbn: isbn, user_id: user_id )
+ book_collect = BookCollection.find_by(:isbn => isbn, :user_id => user_id)
change_f = false
- if (book_collect == nil)
+ if book_collect.nil?
raise NotFoundInstanceError
end
- if ((summary != nil) &&
- (summary != book_collect.summary))
- # 値が異なれば更新
- book_collect.summary = summary
- change_f = true
+ if !summary.nil? && (summary != book_collect.summary)
+ # 値が異なれば更新
+ book_collect.summary = summary
+ change_f = true
end
- if ((book_rank != book_collect.book_rank))
- # 値が異なれば更新
- book_collect.book_rank = book_rank
- change_f = true
+ if book_rank != book_collect.book_rank
+ # 値が異なれば更新
+ book_collect.book_rank = book_rank
+ change_f = true
end
-
+
# 更新内容の適用
- if (change_f)
+ if change_f
book_collect.update_at = DateTime.now
- if (not book_collect.save)
+ if !book_collect.save
raise DbAccesError
end
end
# @param [Integer] num 件数
# @return [Array<Book>] 取得した書籍情報
def self.newestListOfBooks(user_id, num)
- books = Array.new
- book_collects = BookCollection.where(user_id: user_id).
- order(create_at: :desc).first(num)
+ books = []
+ book_collects = BookCollection.where(:user_id => user_id)
+ .order(:create_at => :desc).first(num)
book_collects.each do |item|
- book = Book.find_by(isbn: item.isbn)
+ book = Book.find_by(:isbn => item.isbn)
books.push(book)
end
return books
end
-
+
# 蔵書情報の削除
# @param [String] isbn_str 削除対象のISBN
# @param [Integer] user_id 削除対象のユーザID
def self.deleteBookCollect(isbn_str, user_id)
isbn = toIsbn(isbn_str)
- book_collect = BookCollection.find_by(isbn: isbn, user_id: user_id )
- if (book_collect == nil)
+ book_collect = BookCollection.find_by(:isbn => isbn, :user_id => user_id)
+ if book_collect.nil?
raise NotFoundInstanceError
end
- if (not book_collect.destroy)
+ if !book_collect.destroy
raise DbAccessError
end
end
# 蔵書情報の削除 (ユーザ所有をすべて削除)
# @param [Integer] user_id 削除対象のユーザID
def self.deleteBookCollectOfUser(user_id)
- book_collects = BookCollection.where(user_id: user_id)
+ book_collects = BookCollection.where(:user_id => user_id)
book_collects.each do |book_collect|
- if (not book_collect.destroy)
+ if !book_collect.destroy
raise DbAccessError
end
end
# coding: utf-8
+# frozen_string_literal: true
+
# ユーザDBアクセス処理
# @author OHASHI, Norikazu
# ユーザ情報
class User < ActiveRecord::Base
# ユーザロール
- #管理者権限
+ # 管理者権限
ROLE_ADMIN = 0
- #一般権限
+ # 一般権限
ROLE_NORMAL = 8
- #パスワード忘れ中
+ # パスワード忘れ中
ROLE_FORGOT = 10
-
+
# 正規表現によるレコード探索
# @param [Symbol] key カラム名
# @param [String] pattern 正規表現パターン
# ユーザ管理
class UserAccount
-
# ユーザ認証エラー
- class AuthenticationError < SecurityError
+ class AuthenticationError < StandardError
end
# 対象のユーザがすでに存在している
class DbAccessError < StandardError
end
-
# SALT と Password Hash を生成する
# @param [String] passwd パスワード
# @return [String, String] SALT, パスワードハッシュ
- def self.makeHash(passwd)
+ def self.makeHash(passwd)
passwd_salt = BCrypt::Engine.generate_salt
passwd_hash = BCrypt::Engine.hash_secret(passwd, passwd_salt)
return passwd_salt, passwd_hash
end
-
+
private_class_method :makeHash
-
+
# ユーザが管理者であるかをチェック
# @param [Integer] id チェック対象ユーザID
# @return [Boolean] true: 管理者
# @return [Boolean] false: 管理者ではない
def self.checkAdmin(id)
- user = User.find_by(user_id: id)
- if (user == nil)
+ user = User.find_by(:user_id => id)
+ if user.nil?
return false
end
+
return user.user_role == User::ROLE_ADMIN
end
-
+
# ユーザアカウントを作成
# @param [String] name ユーザ名
# @param [String] full_name フルネーム
# @param [String] passwd パスワード
# @return [Integer] 採番されたユーザID
# @raise [AlreadyInstanceError] すでにユーザ情報を登録済み
-
def self.createAccount(name, full_name, email, passwd)
-
# ユーザの有無をチェック
- if (User.find_by(user_name: name) != nil)
+ if !User.find_by(:user_name => name).nil?
raise AlreadyInstanceError
end
user.user_role = User::ROLE_NORMAL
user.create_at = DateTime.now
user.update_at = DateTime.now
- if (not user.save)
+ if !user.save
raise DbAccessError
end
+
return user.id
end
-
# パスワードをチェックする
# @param [String] name ユーザ名
# @param [String] passwd パスワード
# @raise [NotFoundInstanceError] ユーザ情報の取得に失敗
# @raise [AuthenticationError] 認証失敗
def self.checkPasswd(name, passwd)
- user = User.find_by(user_name: name)
+ user = User.find_by(:user_name => name)
# ユーザの有無をチェック
- if (user == nil)
+ if user.nil?
raise NotFoundInstanceError
end
passwd_hash = BCrypt::Engine.hash_secret(passwd, user.passwd_salt)
# 登録されているパスワードハッシュと比較
- if (user.passwd_hash != passwd_hash)
+ if user.passwd_hash != passwd_hash
raise AuthenticationError
end
# @return [User] ユーザ情報
# @raise [NotFoundInstanceError] ユーザ情報の取得に失敗
def self.getUser(id)
- user = User.find_by(user_id: id)
- if (user == nil)
+ user = User.find_by(:user_id => id)
+ if user.nil?
raise NotFoundInstanceError
end
+
return user
end
# @return [Array<User>] 全ユーザ情報の一覧
# @raise [AuthenticationError] ユーザ権限不正
def self.getUserList(id)
- if (not checkAdmin(id))
+ if !checkAdmin(id)
raise AuthenticationError
end
+
return User.all
end
# @param [Integer] id 変更対象のユーザID
# @param [Hash] columns 変更するカラムと値のハッシュ
def self.updateUser(id, columns)
- user = User.find_by(user_id: id)
+ user = User.find_by(:user_id => id)
change_f = false
- if (user == nil)
+ if user.nil?
raise NotFoundInstanceError
end
columns.each do |key, value|
- if ((value == nil) || (value == ""))
+ if value.nil? || value.empty?
# 値がない、値が空文字の場合は対象としない。
next
end
- if (key == :passwd)
+
+ if key == :passwd
# パスワード更新
user.passwd_salt, user.passwd_hash = makeHash(value)
change_f = true
- else
- if (value != user.send(key))
- # その他のステータス、値が異なれば更新
- method = key.to_s + "="
- user.send(method, value)
- change_f = true
- end
+ elsif value != user.send(key)
+ # その他のステータス、値が異なれば更新
+ method = "#{key}="
+ user.send(method, value)
+ change_f = true
end
end
# 更新内容の適用
- if (change_f)
+ if change_f
user.update_at = DateTime.now
- if (not user.save)
+ if !user.save
raise DbAccessError
end
end
# ユーザ情報の削除
# @param [Integer] id 削除対象のユーザID
def self.deleteUser(id)
- user = User.find_by(user_id: id)
- if (user == nil)
+ user = User.find_by(:user_id => id)
+ if user.nil?
raise NotFoundInstanceError
end
- if (not user.destroy)
+ if !user.destroy
raise DbAccessError
end
end
-
end
- isbn = @book_info[:isbn]
- title = @book_info[:title]
- volume = @book_info[:volume]
-- if volume != nil
+- if !volume.nil?
- title += ' : ' + volume.to_s + '巻'
%h2
- id = @id
- book_info = @book_info
- book_title = book_info[:title]
-- if book_info [:volume] != nil
+- if !book_info[:volume].nil?
- book_title += ": #{book_info[:volume]} 巻"
%h2
「#{book_title}」
書名
%td
#{book_title}
- - if book_info[:subtitle] != nil and book_info[:subtitle] != ""
+ - if !book_info[:subtitle].nil? and !book_info[:subtitle].empty?
%tr
%th
副題
%td
#{book_info[:subtitle]}
- - if book_info[:series] != nil and book_info[:series] != ""
+ - if !book_info[:series].nil? and !book_info[:series].empty?
%tr
%th
単行本シリーズ
%td
#{book_info[:series]}
- - if book_info[:author] != nil and book_info[:author] != ""
+ - if !book_info[:author].nil? and !book_info[:author].empty?
%tr
%th
著者
%td
#{book_info[:author]}
- - if book_info[:original_author] != nil and book_info[:original_author] != ""
+ - if !book_info[:original_author].nil? and !book_info[:original_author].empty?
%tr
%th
原作者
%td
#{book_info[:original_author]}
- - if book_info[:illustrator] != nil && book_info[:illustrator] != ""
+ - if !book_info[:illustrator].nil? && !book_info[:illustrator].empty?
%tr
%th
作画
%td
#{book_info[:illustrator]}
- - if book_info[:translator] != nil and book_info[:translator] != ""
+ - if !book_info[:translator].nil? and !book_info[:translator].empty?
%tr
%th
翻訳
%td
#{book_info[:translator]}
- - if book_info[:supervisor] != nil and book_info[:supervisor] != ""
+ - if !book_info[:supervisor].nil? and !book_info[:supervisor].empty?
%tr
%th
監修
%td
#{book_info[:supervisor]}
- - if book_info[:publisher] != nil and book_info[:publisher] != ""
+ - if !book_info[:publisher].nil? and !book_info[:publisher].empty?
%tr
%th
出版社
%td
#{book_info[:publisher]}
- - if book_info[:pubdate] != nil and book_info[:pubdate] != ""
+ - if !book_info[:pubdate].nil?
%tr
%th
出版日
%td
#{book_info[:pubdate]}
- - if book_info[:summary] != nil and book_info[:summary] != ""
+ - if !book_info[:summary].nil? and !book_info[:summary].empty?
%tr
%th
書籍概要
%td
%pre
#{book_info[:summary]}
- - if book_info[:book_rank] != nil and book_info[:book_rank] != ""
+ - if !book_info[:book_rank].nil? and book_info[:book_rank].empty?
%tr
%th
評価
#{user_name} さんの蔵書一覧は以下となります。
.message
- - if find_params == nil
+ - if find_params.nil?
登録されている蔵書は #{full_size}冊になります。
- else
「#{find_params}」の条件にマッチする蔵書は #{full_size}冊になります。
- book_list.each do |book|
- index += 1
- isbn = book[:isbn]; publisher = book[:publisher]; pubdate = book[:pubdate]
- - if book[:volume] != nil
+ - if !book[:volume].nil?
- title = "#{book[:title]} : #{book[:volume]} 巻"
- else
- title = book[:title]
- - if book [:author] != nil and book[:author] !=""
+ - if !book[:author].nil? and !book[:author].empty?
- author = book[:author]
- else
- author = ""
- - if book [:original_author] != nil and book[:orignal_author] != ""
+ - if !book[:original_author].nil? and !book[:orignal_author].empty?
- author += "原作:#{book[:oritnal_author]} "
- - if book[:illustrator] != nil and book[:illustrator] != ""
+ - if !book[:illustrator].nil? and !book[:illustrator].empty?
- author += "作画:#{book[:illustrator]} "
%tr
%td.number
- is_admin = @is_admin; id = @id; book_info = @book_info
- update_f = @update_f; is_admin_books = @is_admin_books
- warning = @warning
-- if book_info[:title] != nil && book_info[:title].length > 0
+- if !book_info[:title].nil? && !book_info[:title].empty?
- isbn_regist_f = true
- else
- isbn_regist_f = false
}
.item_center
- - if book_info[:cover_uri] != nil
+ - if !book_info[:cover_uri].nil?
%image{ :id => 'cover_image', :border => '1', :src => book_info[:cover_uri], :class => 'cover_image', :width => '128', :height => '182'}
%input{ :name => 'cover_uri', :type => 'hidden', :value => book_info[:cover_uri]}
- - if book_info[:cover_base64] != nil
+ - if !book_info[:cover_base64].nil?
%input{ :name => 'cover_base64', :type => 'hidden', :value => book_info[:cover_base64]}
%input{ :name => 'mime_type', :type => 'hidden', :value => book_info[:mime_type]}
%p= error_message
.buttons
- - if refs == nil
+ - if refs.nil?
%input{ :type => 'button', :class=>'push_button', :onclick => "location.href='/'", :value => 'メインにもどる'}
- else
%input{ :type => 'button', :class=>'push_button', :onclick => "location.href='#{refs}'", :value => 'もどる'}
- # encoding: utf-8
-- if @username != nil
+- if !@username.nil?
- title_name = @username+" 蔵書管理 "
- user_name = @username
- else
%script{ :src => '/scripts/check_form.js'}
%body
- - if user_name == nil
+ - if user_name.nil?
#main1= yield
- else
#head
%ul
- newest_list.each do |item|
- - if item[:volume] == nil
+ - if item[:volume].nil?
%li #{item[:title]} (登録日時:#{item[:create_at].strftime("%Y/%m/%d %T")})
- else
%li #{item[:title]} : #{item[:volume]} 巻 (登録日時:#{item[:create_at].strftime("%Y/%m/%d %T")})
require_relative './app/models/users_db'
require 'bcrypt'
-require 'bcrypt'
-
passwd_salt = BCrypt::Engine.generate_salt
passwd_hash = BCrypt::Engine.hash_secret("admin000", passwd_salt)
# Web GUI 用のRoute
'/' => WebGui,
# Web API 用のRoute
-# '/webapi' => RESTfulAPI,
+ # '/webapi' => RESTfulAPI,
}
end