Class: Unoconv::Listener

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

Overview

Usage: Unoconv::Listener.open do |unoconv_listener|

begin
  unoconv_listener.generate_pdf(doc_path) do |tmp_pdf_path|
    # Copy or move tmp_pdf_path to where you have to store it.
    # tmp_pdf_path is deleted after this block is executed.
  end
rescue DocumentNotFound, FailedToCreatePDF => e
  # handle exception
end

end

Defined Under Namespace

Classes: DocumentNotFound, FailedToCreatePDF, LibreOfficeAlreadyOpen, NotStarted, UnoconvAlreadyOpen

Constant Summary collapse

STARTUP_SLEEP =
20.0
OUTDIR =
'tmp'

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.open(&block) ⇒ Object



29
30
31
32
33
34
35
# File 'lib/unoconv/listener.rb', line 29

def self.open(&block)
  instance = new
  instance.start
  block.call(instance)
ensure
  instance&.stop
end

Instance Method Details

#generate_pdf(doc_path, output_format, &block) ⇒ Object



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

def generate_pdf(doc_path, output_format, &block)
  tmp_pdf_path = nil

  unless started?
    raise NotStarted, "Call #{self.class}#start before calling #{__method__}"
  end

  unless File.exists?(doc_path)
    raise DocumentNotFound, "File does not exist: #{doc_path}"
  end

  # Libre Office and unoconv can both crash,
  # so we need to wrap it in a timeout and restart the services if they time out
  Timeout::timeout(30) do
    begin
      tmp_pdf_path = unoconv_generate_pdf(doc_path, output_format)
      block.call(tmp_pdf_path)
    rescue Timeout::Error
      restart
      convert_to_pdf(doc_path, &block)
    end
  end

ensure
  File.delete(tmp_pdf_path) if tmp_pdf_path && File.exists?(tmp_pdf_path)
end

#startObject



64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
# File 'lib/unoconv/listener.rb', line 64

def start
  # If the unoconv process is already running, starting a new process will
  # make it freeze. The output is not returned when the process is frozen
  # but the output is shown in the terminal as:
  #   LibreOffice crashed - exit code: 0
  #
  # To avoid this I try to raise an error if unoconv is already open.
  raise_if_already_open

  puts "Starting: unoconv --listener"
  @unoconv_pid = Process.spawn("#{unoconv_cmd} --listener")

  puts "Waiting #{STARTUP_SLEEP} sec for Libre Office and unoconv to start..."
  sleep(STARTUP_SLEEP)
  puts "Expecting Libre Office and unoconv to be open and ready now!"
end

#stopObject



81
82
83
84
85
# File 'lib/unoconv/listener.rb', line 81

def stop
  puts "Stopping: unoconv --listener"
  kill_soffice
  kill_unoconv
end