Class: NHKore::App

Inherits:
Object
  • Object
show all
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

Attributes included from CLI::SiftCmd

#sift_datetime_text, #sift_search_criteria

Instance Method Summary collapse

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

#build_get_cmd, #run_get_cmd

Methods included from CLI::FXCmd

#build_fx_cmd, #run_fx_cmd, #test_fx_progress_bar, #test_fx_spinner

Constructor Details

#initialize(args = ARGV) ⇒ App

Returns a new instance of App.



76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
# File 'lib/nhkore/app.rb', line 76

def initialize(args=ARGV)
  super()

  @args = args
  @cmd = nil
  @cmd_args = nil
  @cmd_opts = nil
  @high = HighLine.new
  @rainbow = Rainbow.new
  @progress_bar = :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

#cmdObject (readonly)

Returns the value of attribute cmd.



68
69
70
# File 'lib/nhkore/app.rb', line 68

def cmd
  @cmd
end

#cmd_argsObject (readonly)

Returns the value of attribute cmd_args.



69
70
71
# File 'lib/nhkore/app.rb', line 69

def cmd_args
  @cmd_args
end

#cmd_optsObject (readonly)

Returns the value of attribute cmd_opts.



70
71
72
# File 'lib/nhkore/app.rb', line 70

def cmd_opts
  @cmd_opts
end

#progress_barObject

Returns the value of attribute progress_bar.



71
72
73
# File 'lib/nhkore/app.rb', line 71

def progress_bar
  @progress_bar
end

#scraper_kargsObject

Returns the value of attribute scraper_kargs.



72
73
74
# File 'lib/nhkore/app.rb', line 72

def scraper_kargs
  @scraper_kargs
end

#sleep_timeObject

Returns the value of attribute sleep_time.



73
74
75
# File 'lib/nhkore/app.rb', line 73

def sleep_time
  @sleep_time
end

#spinnerObject

Returns the value of attribute spinner.



74
75
76
# File 'lib/nhkore/app.rb', line 74

def spinner
  @spinner
end

Instance Method Details

#autodetect_colorObject



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
132
133
134
135
136
# File 'lib/nhkore/app.rb', line 104

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_cmdObject



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
230
231
232
233
234
# File 'lib/nhkore/app.rb', line 138

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 <<-DESC
      Scrapes NHK News Web (Easy) to create a list of each word and its
      frequency (how many times it was used) for Japanese language learners.

      This is similar to a core word/vocabulary list.
    DESC

    flag :s,:'classic-fx',<<-DESC do |value,cmd|
      use classic spinner/progress special effects (in case of no Unicode support) when running long tasks
    DESC
      app.progress_bar = :classic
      app.spinner = CLASSIC_SPINNER
    end
    flag COLOR_OPTS[0],COLOR_OPTS[1],"force color output (for commands like '| less -R')" do |value,cmd|
      app.enable_color(true)
    end
    flag :n,:'dry-run',<<-DESC
      do a dry run without making changes; do not write to files, create directories, etc.
    DESC
    # Big F because dangerous.
    flag :F,:force,"force overwriting files, creating directories, etc. (don't prompt); dangerous!"
    flag :h,:help,'show this help' do |value,cmd|
      puts cmd.help
      exit
    end
    option :m,:'max-retry',<<-DESC,argument: :required,default: 3 do |value,cmd|
      maximum number of times to retry URLs (-1 or integer >= 0)
    DESC
      value = value.to_i
      value = nil if value < 0

      app.scraper_kargs[:max_retries] = value
    end
    flag NO_COLOR_OPTS[0],NO_COLOR_OPTS[1],'disable color output' do |value,cmd|
      app.enable_color(false)
    end
    flag :X,:'no-fx','disable spinner/progress special effects when running long tasks' do |value,cmd|
      app.progress_bar = :no
      app.spinner = {} # Still outputs status & stores tokens
    end
    option :o,:'open-timeout',<<-DESC,argument: :required do |value,cmd|
      seconds for URL open timeouts (-1 or decimal >= 0)
    DESC
      value = value.to_f
      value = nil if value < 0.0

      app.scraper_kargs[:open_timeout] = value
    end
    option :r,:'read-timeout',<<-DESC,argument: :required do |value,cmd|
      seconds for URL read timeouts (-1 or decimal >= 0)
    DESC
      value = value.to_f
      value = nil if value < 0.0

      app.scraper_kargs[:read_timeout] = value
    end
    option :z,:sleep,<<-DESC,argument: :required,default: DEFAULT_SLEEP_TIME do |value,cmd|
      seconds to sleep per scrape (i.e., per page/article) so don't get banned (i.e., fake being human)
    DESC
      app.sleep_time = value.to_f
      app.sleep_time = 0.0 if app.sleep_time < 0.0
    end
    option :t,:timeout,<<-DESC,argument: :required do |value,cmd|
      seconds for all URL timeouts: [open, read] (-1 or decimal >= 0)
    DESC
      value = value.to_f
      value = nil if value < 0.0

      app.scraper_kargs[:open_timeout] = value
      app.scraper_kargs[:read_timeout] = value
    end
    option :u,:'user-agent',<<-DESC,argument: :required do |value,cmd|
      HTTP header field 'User-Agent' to use instead of a random one
    DESC
      value = app.check_empty_opt(:'user-agent',value)

      app.scraper_kargs[:header] ||= {}
      app.scraper_kargs[:header]['user-agent'] = value
    end
    flag :v,:version,'show the version and exit' do |value,cmd|
      app.show_version
      exit
    end

    run do |opts,args,cmd|
      puts cmd.help
    end
  end
end

#build_dir(opt_key, default_dir: '.') ⇒ Object



236
237
238
239
240
241
242
243
244
245
246
247
# File 'lib/nhkore/app.rb', line 236

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.expand_path(dir) unless dir.nil?

  return (@cmd_opts[opt_key] = dir)
end

#build_file(opt_key, default_dir: '.', default_filename: '') ⇒ Object



249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
# File 'lib/nhkore/app.rb', line 249

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?().
    if default_filename.empty?
      file = nil # nil is very important for BingScraper.init()!
    else
      file = File.join(default_dir,default_filename)
    end
  else
    # Directory?
    if 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)
    end
    # Else, passed in both: 'directory/file'
  end

  # '~' will expand to home, etc.
  file = File.expand_path(file) unless file.nil?

  return (@cmd_opts[opt_key] = file)
end

#build_in_dir(opt_key, **kargs) ⇒ Object



279
280
281
# File 'lib/nhkore/app.rb', line 279

def build_in_dir(opt_key,**kargs)
  return build_dir(opt_key,**kargs)
end

#build_in_file(opt_key, **kargs) ⇒ Object



283
284
285
# File 'lib/nhkore/app.rb', line 283

def build_in_file(opt_key,**kargs)
  return build_file(opt_key,**kargs)
end

#build_out_dir(opt_key, **kargs) ⇒ Object



287
288
289
# File 'lib/nhkore/app.rb', line 287

def build_out_dir(opt_key,**kargs)
  return build_dir(opt_key,**kargs)
end

#build_out_file(opt_key, **kargs) ⇒ Object



291
292
293
# File 'lib/nhkore/app.rb', line 291

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



295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
# File 'lib/nhkore/app.rb', line 295

def build_progress_bar(title,download: false,total: 100,type: @progress_bar,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_cmdObject



319
320
321
322
323
324
325
326
327
328
329
330
331
332
# File 'lib/nhkore/app.rb', line 319

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



334
335
336
337
338
339
340
341
342
# File 'lib/nhkore/app.rb', line 334

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



344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
# File 'lib/nhkore/app.rb', line 344

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



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
410
411
412
413
414
415
# File 'lib/nhkore/app.rb', line 370

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



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
457
458
459
460
461
462
# File 'lib/nhkore/app.rb', line 417

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



464
465
466
# File 'lib/nhkore/app.rb', line 464

def color(str)
  return @rainbow.wrap(str)
end

#color_alias(str) ⇒ Object



468
469
470
# File 'lib/nhkore/app.rb', line 468

def color_alias(str)
  return color(str).green
end

#enable_color(enabled) ⇒ Object



472
473
474
475
# File 'lib/nhkore/app.rb', line 472

def enable_color(enabled)
  Cri::Platform.color = enabled
  @rainbow.enabled = enabled
end

#opts_to_set(ary) ⇒ Object



477
478
479
480
481
482
483
484
# File 'lib/nhkore/app.rb', line 477

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



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
514
515
516
517
518
# File 'lib/nhkore/app.rb', line 486

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

#runObject



520
521
522
# File 'lib/nhkore/app.rb', line 520

def run
  @app_cmd.run(@args)
end

#show_versionObject



524
525
526
# File 'lib/nhkore/app.rb', line 524

def show_version
  puts "#{NAME} v#{VERSION}"
end

#sleep_scraperObject



528
529
530
531
532
533
534
# File 'lib/nhkore/app.rb', line 528

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



536
537
538
539
540
541
542
543
544
545
546
# File 'lib/nhkore/app.rb', line 536

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_spinObject



548
549
550
551
552
553
554
555
# File 'lib/nhkore/app.rb', line 548

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



557
558
559
560
561
562
563
564
565
# File 'lib/nhkore/app.rb', line 557

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