Class: NHKore::App
- Inherits:
-
Object
- Object
- NHKore::App
- Includes:
- CLI::FXCmd, CLI::GetCmd, CLI::NewsCmd, CLI::SearchCmd, CLI::SiftCmd
- Defined in:
- lib/nhkore/app.rb
Constant Summary collapse
- NAME =
'nhkore'- DEFAULT_SLEEP_TIME =
So that sites don’t ban us (i.e., think we are human)
0.1
- COLOR_OPTS =
i[c color].freeze
- NO_COLOR_OPTS =
i[C no-color].freeze
- SPINNER_MSG =
'[:spinner] :title:detail...'- CLASSIC_SPINNER =
TTY::Spinner.new(SPINNER_MSG,format: :classic)
- DEFAULT_SPINNER =
TTY::Spinner.new(SPINNER_MSG,interval: 5, frames: ['〜〜〜','日〜〜','日本〜','日本語'])
- NO_SPINNER_MSG =
'%{title}%{detail}...'
Constants included from CLI::SiftCmd
CLI::SiftCmd::DEFAULT_SIFT_EXT, CLI::SiftCmd::DEFAULT_SIFT_FUTSUU_FILE, CLI::SiftCmd::DEFAULT_SIFT_YASASHII_FILE, CLI::SiftCmd::SIFT_EXTS
Constants included from CLI::NewsCmd
CLI::NewsCmd::DEFAULT_NEWS_SCRAPE
Constants included from CLI::GetCmd
CLI::GetCmd::DEFAULT_GET_CHUNK_SIZE, CLI::GetCmd::DEFAULT_GET_URL_LENGTH, CLI::GetCmd::GET_URL, CLI::GetCmd::GET_URL_FILENAME
Instance Attribute Summary collapse
-
#cmd ⇒ Object
readonly
Returns the value of attribute cmd.
-
#cmd_args ⇒ Object
readonly
Returns the value of attribute cmd_args.
-
#cmd_opts ⇒ Object
readonly
Returns the value of attribute cmd_opts.
-
#progress_bar ⇒ Object
Returns the value of attribute progress_bar.
-
#scraper_kargs ⇒ Object
Returns the value of attribute scraper_kargs.
-
#sleep_time ⇒ Object
Returns the value of attribute sleep_time.
-
#spinner ⇒ Object
Returns the value of attribute spinner.
Attributes included from CLI::SiftCmd
#sift_datetime_text, #sift_search_criteria
Instance Method Summary collapse
- #autodetect_color ⇒ Object
- #build_app_cmd ⇒ Object
- #build_dir(opt_key, default_dir: '.') ⇒ Object
- #build_file(opt_key, default_dir: '.', default_filename: '') ⇒ Object
- #build_in_dir(opt_key, **kargs) ⇒ Object
- #build_in_file(opt_key, **kargs) ⇒ Object
- #build_out_dir(opt_key, **kargs) ⇒ Object
- #build_out_file(opt_key, **kargs) ⇒ Object
- #build_progress_bar(title, download: false, total: 100, type: @progress_bar, width: 33, **kargs) ⇒ Object
- #build_version_cmd ⇒ Object
- #check_empty_opt(key, value) ⇒ Object
- #check_in_file(opt_key, empty_ok: false) ⇒ Object
- #check_out_dir(opt_key) ⇒ Object
- #check_out_file(opt_key) ⇒ Object
- #color(str) ⇒ Object
- #color_alias(str) ⇒ Object
- #enable_color(enabled) ⇒ Object
-
#initialize(args = ARGV) ⇒ App
constructor
A new instance of App.
- #opts_to_set(ary) ⇒ Object
- #refresh_cmd(opts, args, cmd) ⇒ Object
- #run ⇒ Object
- #show_version ⇒ Object
- #sleep_scraper ⇒ Object
- #start_spin(title, detail: '') ⇒ Object
- #stop_spin ⇒ Object
- #update_spin_detail(detail) ⇒ Object
Methods included from CLI::SiftCmd
#build_sift_cmd, #build_sift_filename, #run_sift_cmd
Methods included from CLI::SearchCmd
#build_search_cmd, #run_search_cmd, #run_search_help, #show_search_urls
Methods included from CLI::NewsCmd
#build_news_cmd, #run_news_cmd, #scrape_news_article, #scraped_news_article?
Methods included from CLI::GetCmd
Methods included from CLI::FXCmd
#build_fx_cmd, #run_fx_cmd, #test_fx_progress_bar, #test_fx_spinner
Constructor Details
#initialize(args = ARGV) ⇒ App
71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 |
# File 'lib/nhkore/app.rb', line 71 def initialize(args = ARGV) super() @args = args @cmd = nil @cmd_args = nil @cmd_opts = nil @high = HighLine.new @rainbow = Rainbow.new = :default # [:default, :classic, :no] @scraper_kargs = {} @sleep_time = DEFAULT_SLEEP_TIME @spinner = DEFAULT_SPINNER autodetect_color build_app_cmd build_fx_cmd build_get_cmd build_news_cmd build_search_cmd build_sift_cmd build_version_cmd @app_cmd.add_command Cri::Command.new_basic_help end |
Instance Attribute Details
#cmd ⇒ Object (readonly)
Returns the value of attribute cmd.
63 64 65 |
# File 'lib/nhkore/app.rb', line 63 def cmd @cmd end |
#cmd_args ⇒ Object (readonly)
Returns the value of attribute cmd_args.
64 65 66 |
# File 'lib/nhkore/app.rb', line 64 def cmd_args @cmd_args end |
#cmd_opts ⇒ Object (readonly)
Returns the value of attribute cmd_opts.
65 66 67 |
# File 'lib/nhkore/app.rb', line 65 def cmd_opts @cmd_opts end |
#progress_bar ⇒ Object
Returns the value of attribute progress_bar.
66 67 68 |
# File 'lib/nhkore/app.rb', line 66 def end |
#scraper_kargs ⇒ Object
Returns the value of attribute scraper_kargs.
67 68 69 |
# File 'lib/nhkore/app.rb', line 67 def scraper_kargs @scraper_kargs end |
#sleep_time ⇒ Object
Returns the value of attribute sleep_time.
68 69 70 |
# File 'lib/nhkore/app.rb', line 68 def sleep_time @sleep_time end |
#spinner ⇒ Object
Returns the value of attribute spinner.
69 70 71 |
# File 'lib/nhkore/app.rb', line 69 def spinner @spinner end |
Instance Method Details
#autodetect_color ⇒ Object
99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 |
# File 'lib/nhkore/app.rb', line 99 def autodetect_color Cri::Platform.singleton_class.prepend(CriColorExt) color = nil # Must be nil, not true/false if !@args.empty? # Kind of hacky, but necessary for Rainbow. color_opts = opts_to_set(COLOR_OPTS) no_color_opts = opts_to_set(NO_COLOR_OPTS) @args.each do |arg| if color_opts.include?(arg) color = true break end if no_color_opts.include?(arg) color = false break end break if arg == '--' end end if color.nil? # - https://no-color.org/ color = ($stdout.tty? && ENV['TERM'] != 'dumb' && !ENV.key?('NO_COLOR')) end enable_color(color) end |
#build_app_cmd ⇒ Object
133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 |
# File 'lib/nhkore/app.rb', line 133 def build_app_cmd app = self @app_cmd = Cri::Command.define do name NAME usage "#{NAME} [OPTIONS] [COMMAND]..." summary 'NHK News Web (Easy) scraper for Japanese language learners.' description " Scrapes NHK News Web (Easy) to create a list of each word and its\n frequency (how many times it was used) for Japanese language learners.\n\n This is similar to a core word/vocabulary list.\n DESC\n\n flag :s,:'classic-fx',<<-DESC do |_value,_cmd|\n use classic spinner/progress special effects (in case of no Unicode support) when running long tasks\n DESC\n app.progress_bar = :classic\n app.spinner = CLASSIC_SPINNER\n end\n flag COLOR_OPTS[0],COLOR_OPTS[1],\"force color output (for commands like '| less -R')\" do |_value,_cmd|\n app.enable_color(true)\n end\n flag :n,:'dry-run',<<-DESC\n do a dry run without making changes; do not write to files, create directories, etc.\n DESC\n # Big F because dangerous.\n flag :F,:force,\"force overwriting files, creating directories, etc. (don't prompt); dangerous!\"\n flag :h,:help,'show this help' do |_value,cmd|\n puts cmd.help\n exit\n end\n option :m,:'max-retry',<<-DESC,argument: :required,default: 3 do |value,_cmd|\n maximum number of times to retry URLs (-1 or integer >= 0)\n DESC\n value = value.to_i\n value = nil if value < 0\n\n app.scraper_kargs[:max_retries] = value\n end\n flag NO_COLOR_OPTS[0],NO_COLOR_OPTS[1],'disable color output' do |_value,_cmd|\n app.enable_color(false)\n end\n flag :X,:'no-fx','disable spinner/progress special effects when running long tasks' do |_value,_cmd|\n app.progress_bar = :no\n app.spinner = {} # Still outputs status & stores tokens\n end\n option :o,:'open-timeout',<<-DESC,argument: :required do |value,_cmd|\n seconds for URL open timeouts (-1 or decimal >= 0)\n DESC\n value = value.to_f\n value = nil if value < 0.0\n\n app.scraper_kargs[:open_timeout] = value\n end\n option :r,:'read-timeout',<<-DESC,argument: :required do |value,_cmd|\n seconds for URL read timeouts (-1 or decimal >= 0)\n DESC\n value = value.to_f\n value = nil if value < 0.0\n\n app.scraper_kargs[:read_timeout] = value\n end\n option :z,:sleep,<<-DESC,argument: :required,default: DEFAULT_SLEEP_TIME do |value,_cmd|\n seconds to sleep per scrape (i.e., per page/article) so don't get banned (i.e., fake being human)\n DESC\n app.sleep_time = value.to_f\n app.sleep_time = 0.0 if app.sleep_time < 0.0\n end\n option :t,:timeout,<<-DESC,argument: :required do |value,_cmd|\n seconds for all URL timeouts: [open, read] (-1 or decimal >= 0)\n DESC\n value = value.to_f\n value = nil if value < 0.0\n\n app.scraper_kargs[:open_timeout] = value\n app.scraper_kargs[:read_timeout] = value\n end\n option :u,:'user-agent',<<-DESC,argument: :required do |value,_cmd|\n HTTP header field 'User-Agent' to use instead of a random one\n DESC\n value = app.check_empty_opt(:'user-agent',value)\n\n app.scraper_kargs[:header] ||= {}\n app.scraper_kargs[:header]['user-agent'] = value\n end\n flag :v,:version,'show the version and exit' do |_value,_cmd|\n app.show_version\n exit\n end\n\n run do |_opts,_args,cmd|\n puts cmd.help\n end\n end\nend\n" |
#build_dir(opt_key, default_dir: '.') ⇒ Object
231 232 233 234 235 236 237 238 239 240 241 242 |
# File 'lib/nhkore/app.rb', line 231 def build_dir(opt_key,default_dir: '.') # Protect against fat-fingering. default_dir = Util.strip_web_str(default_dir) dir = Util.strip_web_str(@cmd_opts[opt_key].to_s) dir = default_dir if dir.empty? # '~' will expand to home, etc. dir = File.(dir) unless dir.nil? return (@cmd_opts[opt_key] = dir) end |
#build_file(opt_key, default_dir: '.', default_filename: '') ⇒ Object
244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 |
# File 'lib/nhkore/app.rb', line 244 def build_file(opt_key,default_dir: '.',default_filename: '') # Protect against fat-fingering. default_dir = Util.strip_web_str(default_dir) default_filename = Util.strip_web_str(default_filename) file = Util.strip_web_str(@cmd_opts[opt_key].to_s) if file.empty? # Do not check `default_dir.empty?()`. file = if default_filename.empty? nil # NOTE: nil is very important for BingScraper.init()! else File.join(default_dir,default_filename) end # Directory? elsif File.directory?(file) || Util.dir_str?(file) file = File.join(file,default_filename) # File name only? (no directory) elsif Util.filename_str?(file) file = File.join(default_dir,file) else # Passed in both: 'directory/file' end # '~' will expand to home, etc. file = File.(file) unless file.nil? return (@cmd_opts[opt_key] = file) end |
#build_in_dir(opt_key, **kargs) ⇒ Object
273 274 275 |
# File 'lib/nhkore/app.rb', line 273 def build_in_dir(opt_key,**kargs) return build_dir(opt_key,**kargs) end |
#build_in_file(opt_key, **kargs) ⇒ Object
277 278 279 |
# File 'lib/nhkore/app.rb', line 277 def build_in_file(opt_key,**kargs) return build_file(opt_key,**kargs) end |
#build_out_dir(opt_key, **kargs) ⇒ Object
281 282 283 |
# File 'lib/nhkore/app.rb', line 281 def build_out_dir(opt_key,**kargs) return build_dir(opt_key,**kargs) end |
#build_out_file(opt_key, **kargs) ⇒ Object
285 286 287 |
# File 'lib/nhkore/app.rb', line 285 def build_out_file(opt_key,**kargs) return build_file(opt_key,**kargs) end |
#build_progress_bar(title, download: false, total: 100, type: @progress_bar, width: 33, **kargs) ⇒ Object
289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 |
# File 'lib/nhkore/app.rb', line 289 def (title,download: false,total: 100,type: ,width: 33,**kargs) case type when :default,:classic require 'tty-progressbar' msg = "#{title} [:bar] :percent :eta".dup msg << ' :byte_rate/s' if download return TTY::ProgressBar.new(msg,total: total,width: width,**kargs) do |config| if type == :default config.incomplete = '.' config.complete = '/' config.head = 'o' end # config.frequency = 5 # For a big download, set this config.interval = 1 if download end end # :no return NoProgressBar.new(title,total: total,**kargs) end |
#build_version_cmd ⇒ Object
313 314 315 316 317 318 319 320 321 322 323 324 325 326 |
# File 'lib/nhkore/app.rb', line 313 def build_version_cmd app = self @version_cmd = @app_cmd.define_command do name 'version' usage 'version [OPTIONS] [COMMAND]...' aliases :v summary "Show the version and exit (aliases: #{app.color_alias('v')})" run do |_opts,_args,_cmd| app.show_version end end end |
#check_empty_opt(key, value) ⇒ Object
328 329 330 331 332 333 334 335 336 |
# File 'lib/nhkore/app.rb', line 328 def check_empty_opt(key,value) value = Util.strip_web_str(value) unless value.nil? if value.nil? || value.empty? raise CLIError,"option[#{key}] cannot be empty[#{value}]" end return value end |
#check_in_file(opt_key, empty_ok: false) ⇒ Object
338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 |
# File 'lib/nhkore/app.rb', line 338 def check_in_file(opt_key,empty_ok: false) in_file = @cmd_opts[opt_key] if Util.empty_web_str?(in_file) if !empty_ok raise CLIError,"empty input path name[#{in_file}] in option[#{opt_key}]" end @cmd_opts[opt_key] = nil # nil is very important for BingScraper.init()! return true end in_file = Util.strip_web_str(in_file) if !File.exist?(in_file) raise CLIError,"input file[#{in_file}] does not exist for option[#{opt_key}]" end if File.directory?(in_file) raise CLIError,"input file[#{in_file}] cannot be a directory for option[#{opt_key}]" end return true end |
#check_out_dir(opt_key) ⇒ Object
364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 |
# File 'lib/nhkore/app.rb', line 364 def check_out_dir(opt_key) out_dir = @cmd_opts[opt_key] if Util.empty_web_str?(out_dir) raise CLIError,"empty output directory[#{out_dir}] in option[#{opt_key}]" end out_dir = Util.strip_web_str(out_dir) if File.file?(out_dir) raise CLIError,"output directory[#{out_dir}] cannot be a file for option[#{opt_key}]" end if @cmd_opts[:dry_run] puts 'No changes written (dry run).' puts "> #{out_dir}" puts return true end force = @cmd_opts[:force] if !force && Dir.exist?(out_dir) && !Dir.empty?(out_dir) puts 'Warning: output directory already exists with files!' puts ' : Files inside of this directory may be overwritten!' puts "> '#{out_dir}'" return false unless @high.agree('Is this okay (yes/no)? ') puts end if !Dir.exist?(out_dir) if !force puts 'Output directory does not exist.' puts "> '#{out_dir}'" return false unless @high.agree('Create this directory (yes/no)? ') end FileUtils.mkdir_p(out_dir,verbose: true) puts end return true end |
#check_out_file(opt_key) ⇒ Object
411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 |
# File 'lib/nhkore/app.rb', line 411 def check_out_file(opt_key) out_file = @cmd_opts[opt_key] if Util.empty_web_str?(out_file) raise CLIError,"empty output path name[#{out_file}] in option[#{opt_key}]" end out_file = Util.strip_web_str(out_file) if File.directory?(out_file) raise CLIError,"output file[#{out_file}] cannot be a directory for option[#{opt_key}]" end if @cmd_opts[:dry_run] puts 'No changes written (dry run).' puts "> #{out_file}" puts return true end force = @cmd_opts[:force] out_dir = File.dirname(out_file) if !force && File.exist?(out_file) puts 'Warning: output file already exists!' puts "> '#{out_file}'" return false unless @high.agree('Overwrite this file (yes/no)? ') puts end if !Dir.exist?(out_dir) if !force puts 'Output directory does not exist.' puts "> '#{out_dir}'" return false unless @high.agree('Create this directory (yes/no)? ') end FileUtils.mkdir_p(out_dir,verbose: true) puts end return true end |
#color(str) ⇒ Object
458 459 460 |
# File 'lib/nhkore/app.rb', line 458 def color(str) return @rainbow.wrap(str) end |
#color_alias(str) ⇒ Object
462 463 464 |
# File 'lib/nhkore/app.rb', line 462 def color_alias(str) return color(str).green end |
#enable_color(enabled) ⇒ Object
466 467 468 469 |
# File 'lib/nhkore/app.rb', line 466 def enable_color(enabled) Cri::Platform.color = enabled @rainbow.enabled = enabled end |
#opts_to_set(ary) ⇒ Object
471 472 473 474 475 476 477 478 |
# File 'lib/nhkore/app.rb', line 471 def opts_to_set(ary) set = Set.new set.add("-#{ary[0]}") unless ary[0].nil? set.add("--#{ary[1]}") unless ary[1].nil? return set end |
#refresh_cmd(opts, args, cmd) ⇒ Object
480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 |
# File 'lib/nhkore/app.rb', line 480 def refresh_cmd(opts,args,cmd) new_opts = {} # Change symbols with dashes to underscores, # so don't have to type @cmd_opts[:'dry-run'] all the time. opts.each do |key,value| # %s(max-retry) => :max_retry key = key.to_s.gsub('-','_').to_sym new_opts[key] = value end # For now don't set the default proc, as the original code # did not have this in mind. # Specifically, SiftCmd.build_sift_filename() is affected by # this due to relying on @cmd_opts[:ext] to be nil. # It's easy to change this one instance, but I'm not sure # at the moment where else might be affected # # # Cri has a default proc for default values # # that doesn't store the keys. # new_opts.default_proc = proc do |hash,key| # # :max_retry => %s(max-retry) # key = key.to_s.gsub('_','-').to_sym # # opts.default_proc.call(hash,key) # end @cmd = cmd @cmd_args = args @cmd_opts = new_opts return self end |
#run ⇒ Object
515 516 517 |
# File 'lib/nhkore/app.rb', line 515 def run @app_cmd.run(@args) end |
#show_version ⇒ Object
519 520 521 |
# File 'lib/nhkore/app.rb', line 519 def show_version puts "#{NAME} v#{VERSION}" end |
#sleep_scraper ⇒ Object
523 524 525 526 527 528 529 |
# File 'lib/nhkore/app.rb', line 523 def sleep_scraper # Do a range to better emulate being a human. r = rand(@sleep_time..(@sleep_time + 0.1111)) s = r.round(3) # Within 1000ms (0.000 - 0.999). sleep(s) end |
#start_spin(title, detail: '') ⇒ Object
531 532 533 534 535 536 537 538 539 540 541 |
# File 'lib/nhkore/app.rb', line 531 def start_spin(title,detail: '') if @spinner.is_a?(Hash) @spinner[:detail] = detail @spinner[:title] = title puts(NO_SPINNER_MSG % @spinner) else @spinner.update(title: title,detail: detail) @spinner.auto_spin end end |
#stop_spin ⇒ Object
543 544 545 546 547 548 549 550 |
# File 'lib/nhkore/app.rb', line 543 def stop_spin if @spinner.is_a?(Hash) puts "#{NO_SPINNER_MSG % @spinner} done!" else @spinner.reset @spinner.stop('done!') end end |
#update_spin_detail(detail) ⇒ Object
552 553 554 555 556 557 558 559 560 |
# File 'lib/nhkore/app.rb', line 552 def update_spin_detail(detail) if @spinner.is_a?(Hash) @spinner[:detail] = detail puts(NO_SPINNER_MSG % @spinner) else @spinner.tokens[:detail] = detail end end |