Class: Narou::API

Inherits:
Object
  • Object
show all
Defined in:
lib/narou/api.rb

Overview

小説家になろうデベロッパーAPI操作クラス

Constant Summary collapse

INFO_SETTING_FILE =
"narou_novel_info.yaml"
NOVEL_TYPE =
{ "連載中" => 1, "完結済" =>  1, "短編" =>  2 }
@@novel_info_parameters =
{}

Instance Method Summary collapse

Constructor Details

#initialize(setting, of) ⇒ API

なろうデベロッパーAPIから情報を取得

setting: なろうの SiteSetting of: 出力パラメータ(dev.syosetu.com/man/api/#of_parm 参照)



27
28
29
30
31
32
# File 'lib/narou/api.rb', line 27

def initialize(setting, of)
  @setting = setting
  @api_url = @setting["narou_api_url"]
  @ncode = @setting["ncode"]
  request_api(of)
end

Instance Method Details

#[](key) ⇒ Object



34
35
36
# File 'lib/narou/api.rb', line 34

def [](key)
  @api_result[key]
end

#date_string_to_time(date) ⇒ Object



85
86
87
# File 'lib/narou/api.rb', line 85

def date_string_to_time(date)
  date ? Time.parse(date.tr("年月日時分秒", "///:::")) : nil
end

#parse_novel_infoObject

小説情報ページをパースして必要な情報を取り出す



65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
# File 'lib/narou/api.rb', line 65

def parse_novel_info
  return @@novel_info_parameters[@ncode] if @@novel_info_parameters[@ncode]
  result = {}
  of = "nt-s-gf-nu-gl"
  request_output_parameters = of.split("-")
  info_source = ""
  open(@setting["narou_info_url"]) do |fp|
    info_source = Helper.pretreatment_source(fp.read)
  end
  info_setting = SiteSetting.load_file(File.join(Narou.get_preset_dir, INFO_SETTING_FILE))
  info_setting.multi_match(info_source, *request_output_parameters)
  result["novel_type"] = NOVEL_TYPE[info_setting["novel_type"]].to_s
  result["story"] = info_setting["story"].gsub("<br />", "")
  %w(general_firstup novelupdated_at general_lastup).each do |elm|
    result[elm] = date_string_to_time(info_setting[elm])
  end
  @@novel_info_parameters[@ncode] = result
  result
end

#request_api(of, gzip = 5) ⇒ Object



38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
# File 'lib/narou/api.rb', line 38

def request_api(of, gzip = 5)
  # Ruby 2.0 以上だと gzip 自動デコード

  gzip_opt = RUBY_VERSION >= "2.0.0" ? "gzip=#{gzip}&" : ""
  url = "#{@api_url}?#{gzip_opt}ncode=#{@ncode}&of=#{of}"
  open(url) do |fp|
    result = YAML.load(fp.read)
    if result[0]["allcount"] == 1
      @api_result = result[1]
      if of.length > 0
        @api_result["novel_type"] = @api_result["noveltype"]
      end
    else
      # なろうAPIからデータを取得出来なかった

      # 開示設定が検索から除外に設定されるとAPIからはアクセスできなくなる

      result = parse_novel_info
      unless result
        error "小説家になろうからデータを取得出来ませんでした"
        exit
      end
      @api_result = result
    end
  end
end