Class: Fourcat::Catalog

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

Constant Summary

VERSION =
'0.9.2'
TAG_REGEX =
/<[^>]+>/i
PB_REGEX =
/[\u2028\u2029]/
LB_REGEX =
/<br\s?\/?>/i
PURGE_SKIP =
0.25

Instance Attribute Summary (collapse)

Class Method Summary (collapse)

Instance Method Summary (collapse)

Constructor Details

- (Catalog) initialize(board, opts = {})

Constructor

Examples:

Initialize a catalog

catalog = Catalog.new('jp', {
  title: '/jp/ - Neet Pride Worldwide',
  refresh_delay: 120,
  refresh_range: [ 120, 300 ]
})

Parameters:

  • board (String, Symbol)

    Remote board slug, ex: :jp or 'jp'

  • opts (Hash) (defaults to: {})

    Options, will be merged with the defaults

Options Hash (opts):

  • approot (String)

    Application root

  • loglevel (Fixnum)

    Logging severity, defaults to Logger::WARN

  • slug (String)

    Local board slug, defaults to the remote slug

  • title (String)

    Board's title, defaults to '/:slug/ - Catalog'

  • public_dir (String)

    Content directory. Defaults to 'approot/public/'

  • default_name (String)

    Default author for threads

  • default_title (String)

    Default title for threads

  • default_comment (String)

    Default comment for threads

  • precompress (true, false)

    Compress output, defaults to false

  • stats (true, false)

    Compile statistics, defaults to false

  • proxy (String, nil)

    Fuuka style archive URL. ex: 'archive.example.com/jp/thread/'

  • debug (true, false)

    Log everything to STDERR

  • front_page (String)

    Page 0 remote file name

  • extension (String)

    Remote files extension, including the dot

  • text_only (true, false)

    Don't fetch thumbnails. Defaults to false

  • write_html (true, false)

    Generate HTML, requires 'erubis' gem

  • html_template (String)

    Erubis template for HTML generation

  • write_rss (true, false)

    Generate RSS Feed, requires 'nokogiri' gem, 'web_uri' needs to be set

  • write_json (true, false)

    Generate JSON

  • rss_desc (String)

    RSS feed description, defaults to 'Meanwhile on /:slug/'

  • web_uri (String)

    Catalog root URL, required for RSS feeds, ex: 'catalog.neet.tv/'

  • content_uri (String)

    Thumbnails server URL, defaults to nil, ex: 'static.neet.tv/'

  • user_agent (String)

    User Agent string, defaults to '4cat/VERSION'

  • threads_pattern (Regexp)

    Threads regex

  • replies_pattern (Regexp)

    Omitted replies and images regex

  • date_pattern (Regexp)

    Date regex

  • pages_pattern (Regexp)

    Page navigation menu regex

  • datemap (Hash)

    Parens match map for the date pattern

  • matchmap (Hash)

    Parens match map for threads pattern

  • utc_offset (Integer)

    Remote server UTC offset in seconds, defaults to Time.zone_offset('EST')

  • req_delay (Numeric)

    Delay in seconds between requests, defaults to 1.2

  • req_timeout (Object)

    Socket open/read timeouts in seconds, defaults to 10

  • workers_limit (Fixnum)

    Maximum number of HTTP worker threads, prevents hammering on laggy days. Defaults to 3

  • retries (Integer)

    Number of retries before dropping the page or thumbnail, defaults to 2

  • no_partial (true, false)

    Aborts the refresh cycle if a page can't be retrived and if the refresh delay is less than the maximum allowed. Defaults to true

  • page_count (Array<Integer>)

    Maximum number of pages to fetch for each run. The default value of [16, 2] means that during a refresh cycle, the crawler will first fetch 16 pages, then will get the first 2 pages. This is fine for moderately fast boards, faster boards may need additional runs in order to avoid missing threads.

  • refresh_delay (Numeric)

    Base refresh delay in seconds, defaults to 60

  • refresh_range (Array(Numeric, Numeric))

    Min and max refresh delays in seconds, defaults to [60, 300]

  • refresh_step (Numeric)

    Refresh delay modifier in seconds. For every new thread crawled, the refresh delay is reduced by refresh_step. If no new threads were found the refresh delay is increased by refresh_step. Defaults to 10

  • teaser_length (Integer)

    Excerpt (teaser) character length. 0 disables teaser generation. Defaults to 200

  • server (String)

    Remote server URL, defaults to 'boards.4chan.org/'



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
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
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
363
364
365
366
367
368
369
370
371
372
# File 'lib/fourcat.rb', line 250

def initialize(board, opts = {})
  # Too lazy to validate every option properly
  raise "Invalid board #{board}" if (@board = board.to_s).empty?
  
  @opts = OpenStruct.new(
    opts ? self.class.defaults.merge(opts) : self.class.defaults
  )
  
  @opts.slug ||= @board # Local short name for the board
  
  @opts.title ||= "/#{@board}/ - Catalog"
  
  if @opts.proxy
    @opts.proxy << '/' if @opts.proxy[-1, 1] != '/'
  end
  
  if @opts.public_dir
    @opts.public_dir << '/' if @opts.public_dir[-1, 1] != '/'
  else
    @opts.public_dir = File.join(@opts.approot, '/public/')
  end
  
  if @opts.web_uri
    @opts.web_uri << '/' if @opts.web_uri[-1, 1] != '/'
  end
  
  if @opts.content_uri
    @opts.content_uri << '/' if @opts.content_uri[-1, 1] != '/'
  end
  
  @rss_content_uri = @opts.content_uri || @opts.web_uri
  
  # Board directory
  @board_dir = @opts.public_dir + @opts.slug + '/'
  
  # Thumbnails directory
  @thumbs_dir = @board_dir + 'src/'
  
  # Templates directory
  @templates_dir = File.join(@opts.approot, '/views/')
  
  # Stats directory
  @stats_dir = File.join(@opts.approot, '/stats/')
  
  if @opts.write_html
    require 'erubis'
    @tpl_file = @templates_dir << @opts.html_template
    unless File.exists?(@tpl_file)
      raise "Can't find template #{@tpl_file}" 
    end
    @tpl_mtime = File.mtime(@tpl_file)
    @template = load_template(@tpl_file)
  end
  
  if @opts.write_rss
    raise "RSS writer: web_uri can't be empty" if !@opts.web_uri
    @opts.rss_desc ||= "Meanwhile, on /#{@opts.slug}/"
    require 'nokogiri'
  end
  
  @headers = {
    'User-Agent' => @opts.user_agent,
    'Accept-Encoding' => 'gzip'
  }
  
  # Local HTML file
  @board_file = @board_dir + 'index.html'
  
  # Local RSS file
  @rss_file = @board_dir + 'feed.rss'
  
  # Local JSON file
  @json_file = @board_dir + 'threads.json'
  
  @entities = HTMLEntities.new
  
  @last_refresh_time = 0
  
  # Thumbnails that appear to be dead will be placed here and
  # deleted during the next refresh cycle
  @delete_queue = []
  
  # Highest thread id found
  @latest_thread = 0
  
  # For stats tracking
  @last_hour = false
  
  # Checking for the spoiler file (spoiler-SLUG.png)
  @spoiler_pic =
    if File.exist?(@opts.public_dir + "images/spoiler-#{@opts.slug}.png")
      "spoiler-#{@opts.slug}.png"
    else
      'spoiler-default.png'
    end
  
  # Checking for the placeholder file (thumb-404-SLUG.png)
  @thumb_404 =
    if File.exist?(@opts.public_dir + "images/thumb-404-#{@opts.slug}.png")
      "thumb-404-#{@opts.slug}.png"
    else
      'thumb-404.png'
    end
  
  @pages_uri = URI.parse(@opts.server)
  
  # Number of dropped pages during a refresh cycle
  @pages_dropped = 0
  
  # If too much pages were dropped, the thumbnail purging is skipped
  @page_drop_limit = (@opts.page_count[0] * PURGE_SKIP).ceil
  
  # jsonified threadlist cache for when write_json and write_html are true
  @json_cache = nil
  
  # Last full refresh cycle time (Time UTC)
  @last_full_cycle = 0
  
  # Last successful write time (Time UTC)
  @mtime = 0
  
  @halt = false
end

Instance Attribute Details

- (Object) opts

Returns the value of attribute opts



111
112
113
# File 'lib/fourcat.rb', line 111

def opts
  @opts
end

Class Method Details

+ (Object) defaults



107
108
109
# File 'lib/fourcat.rb', line 107

def self.defaults
  @defaults
end

+ (Object) defaults=(opts)



103
104
105
# File 'lib/fourcat.rb', line 103

def self.defaults=(opts)
  @defaults = opts
end

Instance Method Details

- (Object) adjust_speed(missed)

Adjusts the refresh speed

Parameters:

  • missed (Fixnum)

    Number of new threads since the last refresh cycle



419
420
421
422
423
424
425
426
427
428
429
430
431
# File 'lib/fourcat.rb', line 419

def adjust_speed(missed)
  if missed > 0
    @opts.refresh_delay -= missed * @opts.refresh_step
    if @opts.refresh_delay < @opts.refresh_range[0]
      @opts.refresh_delay = @opts.refresh_range[0]
    end
  else
    @opts.refresh_delay += @opts.refresh_step
    if @opts.refresh_delay > @opts.refresh_range[1]
      @opts.refresh_delay = @opts.refresh_range[1]
    end
  end
end

- (Object) cleanup

Cleans up stuff



434
435
436
437
# File 'lib/fourcat.rb', line 434

def cleanup
  @log.close unless @opts.debug
  @stats_io.close if @stats_io
end

- (Hash) count_replies(html)

Counts images and replies

Parameters:

  • html (String)

    raw HTML to process

Returns:

  • (Hash)


442
443
444
445
446
447
448
449
450
# File 'lib/fourcat.rb', line 442

def count_replies(html)
  reply_count = { :rep => Hash.new(0), :img => Hash.new(0) }
  replies = html.scan(@opts.replies_pattern)
  replies.each do |r|
    reply_count[:rep][r[0]] += 1
    reply_count[:img][r[0]] += 1 if r[1]
  end
  reply_count
end

- (String) cut_teaser(str)

Generates the excerpt (teaser)

Parameters:

  • Comment (String)

    body

Returns:

  • (String)


455
456
457
458
459
460
461
462
463
# File 'lib/fourcat.rb', line 455

def cut_teaser(str)
  teaser = @entities.decode(str)
  if teaser.length > @opts.teaser_length
    teaser = @entities.encode(teaser[0, @opts.teaser_length] +
      (teaser[@opts.teaser_length + 1] != ' ' ? '' : ' ')) + ''
  else
    str
  end
end

- (String) fetch(http, path)

HTTP requests

Parameters:

  • http (Net::HTTP)

    HTTP object to use for the connection

  • path (String)

Returns:

  • (String)

    Response body



469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
# File 'lib/fourcat.rb', line 469

def fetch(http, path)
  try = 1
  begin
    resp = http.request_get(path, @headers)
    if resp.code != '200'
      if resp.code == '404'
        raise HTTPNotFound, "Not Found #{http.address}#{path}"
      else
        raise HTTPError, "HTTP #{resp.code} for #{http.address}#{path}"
      end
    end
  rescue HTTPError => e
    raise e
  rescue StandardError => e
    if try > @opts.retries
      raise "Skipping after #{e.message}: #{http.address}#{path}"
    end
    @log.debug "Retrying after #{e.message} (#{try}): #{http.address}#{path}"
    try += 1
    sleep(@opts.req_delay)
    retry
  end
  resp
end

- (Object) get_error(e)

Generates an error message from an exception

Parameters:

  • e (Exception)

    Exception



496
497
498
# File 'lib/fourcat.rb', line 496

def get_error(e)
  "#{e.message} (#{e.backtrace.first})"
end

- (Object) get_image(url)

Fetches a thumbnail

Parameters:

  • url (String)

See Also:



503
504
505
506
507
508
# File 'lib/fourcat.rb', line 503

def get_image(url)
  uri = URI.parse(url)
  http = Net::HTTP.new(uri.host, uri.port)
  http.open_timeout = http.read_timeout = @opts.req_timeout
  fetch(http, uri.path).body
end

- (Object) get_page(page_num)

Fetches a page

Parameters:

  • page_num (Fixnum)

    Page number

See Also:

  • @fetch


513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
# File 'lib/fourcat.rb', line 513

def get_page(page_num)
  http = Net::HTTP.new(@pages_uri.host, @pages_uri.port)
  http.open_timeout = http.read_timeout = @opts.req_timeout
  
  path = "#{@pages_uri.path}#{@board}/" <<
    if page_num.zero?
      @opts.front_page
    else
      "#{page_num}#{@opts.extension}"
    end
  
  resp = fetch(http, path)
  
  data = 
    if resp['content-encoding'] == 'gzip'
      Zlib::GzipReader.new(StringIO.new(resp.body)).read
    else
      resp.body
    end
  
  data.force_encoding(Encoding::UTF_8)
  
  unless data.valid_encoding?
    @log.debug("Repacking invalid UTF-8 string: #{path}")
    data = data.unpack('C*').pack('U*')
  end
  
  data
end

- (Object) halt

Tells the crawler to stop after the current refresh cycle



413
414
415
# File 'lib/fourcat.rb', line 413

def halt
  @halt = true
end

- (Object) init_dirs

Creates board specific directories



544
545
546
547
548
549
# File 'lib/fourcat.rb', line 544

def init_dirs
  if !File.directory?(@thumbs_dir)
    @log.debug 'First run: creating directories'
    FileUtils.mkdir_p(@thumbs_dir)
  end
end

- (Object) init_logger

Sets up the logger object



552
553
554
555
556
557
558
559
560
561
562
563
# File 'lib/fourcat.rb', line 552

def init_logger
  if @opts.debug == true
    @log = Logger.new(STDERR)
    @log.level = Logger::DEBUG
  else
    log_dir = File.join(@opts.approot, 'logs')
    FileUtils.mkdir(log_dir) unless File.directory?(log_dir)
    log_file = File.join(log_dir, "fourcat.#{@opts.slug}.log")
    @log = Logger.new(log_file, 1, 512000)
    @log.level = @opts.loglevel
  end
end

- (Object) init_stats

Creates or reopens the stats file



566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
# File 'lib/fourcat.rb', line 566

def init_stats
  FileUtils.mkdir(@stats_dir) unless File.directory?(@stats_dir)
  
  time_now = Time.now.utc
  this_hour = time_now.hour
  last_hour_limit = time_now.to_i - 3599
  
  filename = "#{@stats_dir}#{@opts.slug}-current"
  
  mtime = 0
  
  if File.exist?(filename)
    entry = File.open(filename, 'r:UTF-8') do |f|
      f.read.split("\n")[-1].to_s.split(':')
    end
    if entry.length > 0
      mtime = entry[0].to_i
      @latest_thread = entry[1].to_i
    end
  end
  
  if mtime > last_hour_limit && Time.at(mtime).utc.hour == this_hour
    @log.debug 'init_stats: reopening file'
    @last_hour = this_hour
    @stats_io = File.open(filename, 'a+:UTF-8')
  else
    @log.debug 'init_stats: creating new file'
    @stats_io = File.open(filename, 'w+:UTF-8')
  end
end

- (Object) jsonify_threads(threadlist, order)

Returns the thread list as JSON

See Also:



599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
# File 'lib/fourcat.rb', line 599

def jsonify_threads(threadlist, order)
  return @json_cache if @json_cache
  threads = {}
  threadlist.each do |id, thread|
    threads[id] = {
      :date => thread[:date].to_i,
      :file => thread[:file]
    }
    threads[id][:teaser] = thread[:teaser] if thread[:teaser]
    threads[id][:author] = thread[:author] if thread[:author]
    threads[id][:r] = thread[:r] if thread[:r] != 0
    threads[id][:i] = thread[:i] if thread[:i]
    threads[id][:s] = true if thread[:s]
  end
  
  json = {
    :threads    => threads,
    :order      => order,
    :count      => threads.size,
    :slug       => @opts.slug,
    :delay      => @opts.refresh_delay,
    :anon       => @opts.default_name,
    :mtime      => @mtime.to_i,
    :proxy      => @opts.proxy,
    :server     => "#{@opts.server}#{@board}/",
    :ext        => @opts.extension,
  }.to_json
  
  if @opts.write_json && @opts.write_html
    @json_cache = json
  else
    json
  end
end

Generates links to threads

Parameters:

  • id (Integer)

    Thread id

Returns:

  • (String)

    the thread's URL



637
638
639
# File 'lib/fourcat.rb', line 637

def link_to_thread(id)
  "#{@opts.server}#{@board}/res/#{id}#{@opts.extension}"
end

- (Erubis::FastEruby) load_template(filename)

Creates a new erubis template from a file

Parameters:

  • filename (String)

    Path to the html template

Returns:

  • (Erubis::FastEruby)


644
645
646
647
648
649
# File 'lib/fourcat.rb', line 644

def load_template(filename)
  Erubis::FastEruby.new(
    File.open(filename, 'r:UTF-8') { |f| f.read },
    :bufvar => '@_out_buf'
  )
end

- (Object) purge_thumbnails(local, remote)

Removes dead thumbnails and updates the deletion queue

Parameters:

  • remote (Array<String>)

    an Array of absolute paths

  • local (Array<String>)

    an Array of absolute paths



654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
# File 'lib/fourcat.rb', line 654

def purge_thumbnails(local, remote)
  @log.debug 'Purging dead thumbnails'
  dead = local - remote
  if dead.length > 0
    purgelist = dead & @delete_queue
    @delete_queue = dead - @delete_queue
    begin
      FileUtils.rm(purgelist, force: true)
      @log.debug "Purged #{purgelist.length} dead thumbnails."
    rescue StandardError => e
      @log.error 'purge_thumbnails: ' << get_error(e)
    end
  else
    @log.debug 'Nothing to purge.'
  end
end

- (Object) refresh

Updates the catalog



672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
# File 'lib/fourcat.rb', line 672

def refresh
  @log.debug "Refreshing /#{@opts.slug}/"
  
  cycle_start = Time.now.utc
  threads = []
  workers = {}
  active_workers = 0
  @pages_dropped = 0
  @max_page = nil
  @spam_count = 0
  
  for run in 0...@opts.page_count.length
    @log.debug "Run #{run}"
    
    threads[run] = {}
    
    for page in 0...@opts.page_count[run]
      if @max_page && @max_page < page
        @log.debug "Page #{page} is empty, breaking"
        break
      end
      if workers[lw = "#{run - 1}-#{page}"] && workers[lw].alive?
        @log.debug "Last run worker is still alive, skipping page #{page}"
        next
      end
      while active_workers >= @opts.workers_limit
        sleep(@opts.req_delay)
      end
      @log.debug "Page #{page}"
      workers["#{run}-#{page}"] = Thread.new(threads[run], page) do |th, page|
        begin
          active_workers += 1
          html = get_page(page)
          @max_page =
            if @max_page = html.scan(@opts.pages_pattern).last
              @max_page[0].to_i
            else
              @log.error "Pattern: can't find max page"
              @opts.page_count[run] - 1
            end unless @max_page
          th[page] = scan_threads(html) if @max_page >= page
        rescue HTTPNotFound => e
          @log.debug "Page #{page} not found"
          @max_page = page
        rescue StandardError => e
          @pages_dropped += 1
          @log.error get_error(e)
        ensure
          active_workers -= 1
        end
      end
      sleep @opts.req_delay
    end
  end
  
  wait_for_workers(workers)
  
  threadlist = {}
  stickies = []
  natural_order = []
  missed = 0
  
  run = threads.length - 1
  while run >= 0
    page_order = []
    threads[run].each_value do |page_threads|
      page_threads.each do |id, thread|
        next if threadlist.has_key?(id)
        threadlist[id] = thread
        if id > @latest_thread
          missed += 1
        end
        next if thread[:sticky] && stickies << id
        page_order << id
      end
    end
    natural_order << page_order
    run -= 1
  end
  
  # Bailing out on empty threadlist
  if threadlist.empty?
    adjust_speed(0)
    return @log.error 'Breaking on empty threadlist'
  end
  
  order = {}
  order[:alt] = natural_order.flatten.unshift(*stickies)
  order[:date] = order[:alt].sort { |x, y| y <=> x }
  
  @latest_thread = order[:date][0] || 0
  
  # Fetching thumbnails
  unless @opts.text_only
    thumblist = {}
    
    threadlist.each do |id, thread|
      if !thread[:s]
        thumblist[thread[:local].freeze] = [thread[:src], id]
      end
    end
    
    remote_thumbs = thumblist.keys
    local_thumbs = Dir.glob("#{@thumbs_dir}*.jpg")
    new_thumbs = remote_thumbs - local_thumbs
    
    if @pages_dropped >= @page_drop_limit
      @log.warn 'Too many pages dropped, skipping purge'
    else
      purge_thumbnails(local_thumbs, remote_thumbs)
    end
    
    workers = {}
    active_workers = 0
    
    new_thumbs.each do |src|
      while active_workers >= @opts.workers_limit
        sleep(@opts.req_delay)
      end
      @log.debug "Thumbnail (#{thumblist[src][1]}) #{thumblist[src][0]}"
      workers[thumblist[src][1]] = Thread.new(src) do |src|
        begin
          active_workers += 1
          data = get_image(thumblist[src][0])
          write_image(src, data)
        rescue StandardError => e
          if e.kind_of?(HTTPNotFound)
            @log.debug e.message
          else
            @log.error get_error(e)
          end
          threadlist[thumblist[src][1]][:s] = true
          threadlist[thumblist[src][1]][:file] = @thumb_404
        ensure
          active_workers -= 1
        end
      end
      sleep @opts.req_delay
    end
    
    wait_for_workers(workers)
  end
  
  adjust_speed(missed)
  
  @log.debug "Missed #{missed} threads, delay is #{@opts.refresh_delay}"
  @log.debug "Most recent thread is #{@latest_thread}"
  
  if @opts.no_partial && @pages_dropped > 0 &&
      (cycle_start - @last_full_cycle).to_i < @opts.refresh_range[1]
    @log.warn 'Incomplete refresh cycle, skipping output'
  else
    @mtime = Time.now.utc
    
    if @pages_dropped == 0 || @last_full_cycle == 0
      @last_full_cycle = @mtime 
    end
    
    begin
      write_json(threadlist, order)
    rescue StandardError => e
      @log.error 'write_json: ' << get_error(e)
    end if @opts.write_json
    
    begin
      write_html(threadlist, order)
    rescue Exception => e
      @log.error 'write_html: ' << get_error(e)
    end if @opts.write_html
    
    begin
      write_rss(threadlist, order[:date])
    rescue StandardError => e
      @log.error 'write_rss: ' << get_error(e)
    end if @opts.write_rss
   
    @json_cache = nil if @json_cache
  end
  
  update_stats(missed) if @opts.stats
  
  @log.debug 'Done'
end

- (Object) run

Runs the main loop



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
# File 'lib/fourcat.rb', line 375

def run
  init_logger
  init_dirs
  
  @log.unknown "Running 4cat #{VERSION}"
  
  init_stats if @opts.stats
  
  loop do
    delta = Time.now.to_i - @last_refresh_time
    if delta < @opts.refresh_delay
      sleep(@opts.refresh_delay - delta)
    end
    @last_refresh_time = Time.now.to_i
    begin
      refresh
      raise CatalogHalt if @halt
    rescue Exception => e
      if e.kind_of?(CatalogHalt)
        @log.unknown 'Halting'
      else
        @log.fatal get_error(e)
      end
      cleanup
      raise e
    end
  end
end

- (Object) run_once

Runs the crawler once



405
406
407
408
409
410
# File 'lib/fourcat.rb', line 405

def run_once
  init_logger
  init_dirs
  refresh
  cleanup
end

- (Hash{thread_id(Integer) => Hash}) scan_threads(html)

Scans the page for threads

Parameters:

  • html (String)

    raw HTML to process

Returns:

  • (Hash{thread_id(Integer) => Hash})

    a Hash of threads



859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
# File 'lib/fourcat.rb', line 859

def scan_threads(html)
  if (matches = html.scan(@opts.threads_pattern))[0] == nil
    raise "Pattern: can't find any threads"
  end
  reply_count = count_replies(html)
  threads = {}
  
  mm = @opts.matchmap
  dm = @opts.datemap
  
  matches.each do |t|
    # Skipping threads with no image
    next if t[mm[:src]] == nil
    
    thread = {}
    
    # Link to thread
    thread[:href] = link_to_thread(t[mm[:id]])
    
    # Sticky thread? [true, false]
    thread[:sticky] = t[mm[:status]].include?('sticky') if mm[:status] != nil
    
    # Title [String]
    t[mm[:title]].gsub!(TAG_REGEX, '')
    thread[:title] = t[mm[:title]]
    
    # Comment [String]
    if t[mm[:body]]
      thread[:body] = t[mm[:body]].gsub(LB_REGEX, "\n")
      thread[:body].gsub!(TAG_REGEX, '')
      # Teaser [String, nil]
      if @opts.teaser_length > 0
        thread[:teaser] =
          if thread[:title] != @opts.default_title
            if thread[:body] != @opts.default_comment
              cut_teaser("#{thread[:title]}: #{thread[:body]}")
            else
              cut_teaser(thread[:title])
            end
          else
            cut_teaser(thread[:body])
          end
        thread[:teaser].gsub!(/\n+/, ' ')
        thread[:teaser].gsub!(PB_REGEX, '')
      end
      thread[:body].gsub!("\n", '<br>')
    end
    
    # Thumbnail filename or special file (spoiler, 404) [String]
    if @opts.text_only
      thread[:s] = true;
      thread[:file] = @thumb_404
    elsif t[mm[:file]].include?('spoiler')
      thread[:s] = true;
      thread[:file] = @spoiler_pic
    else
      thread[:file] = t[mm[:file]]
      thread[:local] = @thumbs_dir + t[mm[:file]]
    end
    
    # Thumbnail URL [String]
    thread[:src] = t[mm[:src]]
    
    # Author [String]
    t[mm[:author]].strip!
    t[mm[:author]].gsub!(PB_REGEX, '')
    t[mm[:author]].gsub!(TAG_REGEX, '') # Staff vanity posts clean up
    
    thread[:author] = t[mm[:author]] if t[mm[:author]] != @opts.default_name
    
    # Omitted replies [Integer]
    thread[:r] = reply_count[:rep][t[mm[:id]]]
    thread[:r] += t[mm[:orep]].to_i if t[mm[:orep]]
    
    # Omitted images [Integer]
    if mm[:oimg] != nil
      thread[:i] = reply_count[:img][t[mm[:id]]]
      thread[:i] += t[mm[:oimg]].to_i
    end
    
    # Date UTC [Time]
    d = t[mm[:date]].scan(@opts.date_pattern)[0]
    
    if (d == nil)
      @log.error "Pattern: can't find the date"
      thread[:date] = Time.now.utc
    else
      d[dm[:year]] = (d[dm[:year]].to_i + 2000) if d[dm[:year]][3] == nil
      thread[:date] =
        Time.utc(
          d[dm[:year]],
          d[dm[:month]],
          d[dm[:day]],
          d[dm[:hour]],
          d[dm[:minute]],
          dm[:second] ? d[dm[:second]] : nil
        ) - @opts.utc_offset
    end
    
    threads[t[mm[:id]].to_i] = thread
  end
  
  threads
end

- (Object) update_stats(missed)

Updates stats

Parameters:

  • missed (Fixnum)

    Number of new threads since the last refresh cycle



966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
# File 'lib/fourcat.rb', line 966

def update_stats(missed)
  now = Time.now.utc
  if @last_hour
    if @last_hour != now.hour
      @log.debug 'update_stats: updating daily stats'
      begin
        file = @stats_dir + @opts.slug + '-daily'
        if File.exists?(file)
          stats = JSON.parse(File.open(file, 'r:UTF-8') { |f| f.read })
        else
          stats = []
        end
        stats[@last_hour] = 0
        @stats_io.rewind
        lines = @stats_io.read.split("\n")
        lines.map { |val| stats[@last_hour] += val.split(':')[2].to_i }
        File.open(file, 'w:UTF-8') { |f| f.write(stats.to_json) }
      rescue StandardError => e
        @log.error 'update_stats: daily: ' << get_error(e)
      ensure
        @stats_io.reopen(@stats_io.path, 'w+')
      end
    end
    if missed > 0
      begin
        @log.debug "update_stats: adding #{missed} missed thread(s)"
        @stats_io.write("#{now.to_i}:#{@latest_thread}:#{missed}\n")
        @stats_io.flush
      rescue StandardError => e
        @log.error 'update_stats: current: ' << get_error(e)
      end
    end
  else
    @log.debug 'update_stats: skipping first run'
  end
  @last_hour = now.hour
end

- (Object) wait_for_workers(workers)

Waits until all workers are dead

Parameters:

  • workers (Hash)

    Hash of workers



1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
# File 'lib/fourcat.rb', line 1006

def wait_for_workers(workers)
  while !workers.empty?
    @log.debug 'Waiting for workers...'
    workers.each do |k, w|
      while w && w.alive?
        sleep 1
      end
      workers.delete(k)
    end
  end
end

- (Object) write_html(threadlist, order)

Renders the HTML page

See Also:



1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
# File 'lib/fourcat.rb', line 1020

def write_html(threadlist, order)
  # Template changed?
  if (mtime = File.mtime(@tpl_file)) > @tpl_mtime
    @log.unknown 'Reloading template'
    @tpl_mtime = mtime
    @template = load_template(@tpl_file)
  end
  
  html = @template.result(binding())
  
  File.open(@board_file, 'w:UTF-8') do |f|
    @log.debug "Writing #{@board_file}"
    f.write(html)
  end
  
  if @opts.precompress
    Zlib::GzipWriter.open("#{@board_file}.gz") do |f|
      @log.debug "Writing #{@board_file}.gz"
      f.write(html)
    end
  end
end

- (Object) write_image(name, data)

Writes thumbnail files



1044
1045
1046
# File 'lib/fourcat.rb', line 1044

def write_image(name, data)
  File.open(name, 'wb') { |f| f.write(data) }
end

- (Object) write_json(threadlist, order)

Outputs the thread list as JSON

See Also:



1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
# File 'lib/fourcat.rb', line 1050

def write_json(threadlist, order)
  data = jsonify_threads(threadlist, order)
  
  File.open(@json_file, 'w:UTF-8') do |f|
    @log.debug "Writing #{@json_file}"
    f.write(data)
  end
  
  if @opts.precompress
    Zlib::GzipWriter.open("#{@json_file}.gz") do |f|
      @log.debug "Writing #{@json_file}.gz"
      f.write(data)
    end
  end
end

- (Object) write_rss(threads, order)

Generates the RSS feed

See Also:



1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
# File 'lib/fourcat.rb', line 1068

def write_rss(threads, order)
  now = Time.now.gmtime.rfc2822
  builder = Nokogiri::XML::Builder.new do |xml|
    xml.rss('version' => '2.0') {
      xml.channel {
        xml.title @opts.title
        xml.description @opts.rss_desc
        xml.link @opts.web_uri + @opts.slug + '/'
        xml.lastBuildDate now
        order.each do |id|
          th = threads[id]
          xml.item {
            xml.title "No.#{id}"
            src = @rss_content_uri +
              if th[:s] || !th[:file]
                'images/'
              else
                @opts.slug + '/src/'
              end
            xml.description(
              '<img src="' << src << th[:file] <<
              '" alt="' << th[:file] << '" />' <<
              '<p>' << (th[:teaser] || th[:body]) << '</p>'
            )
            xml.link "#{th[:href]}"
            xml.guid "#{th[:href]}"
            xml.pubDate th[:date].rfc2822.to_s
          }
        end
      }
    }
  end
  
  output = builder.to_xml(:indent => 0, :encoding => 'UTF-8')
  File.open("#{@board_dir}feed.rss", 'w:UTF-8') do |f|
    @log.debug "Writing #{@board_dir}feed.rss"
    f.write(output)
  end
  
  if @opts.precompress
    Zlib::GzipWriter.open("#{@board_dir}feed.rss.gz") do |f|
      @log.debug "Writing #{@board_dir}feed.rss.gz"
      f.write(output)
    end
  end
end