liberic 1.3.1 → 1.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,210 @@
1
+ require "fileutils"
2
+ require "net/http"
3
+ require "uri"
4
+ require "liberic/sdk/configuration"
5
+
6
+ module Liberic
7
+ # Downloads and extracts the official ERiC SDK for Linux x86-64.
8
+ #
9
+ # This file is not loaded by <tt>require "liberic"</tt>, so the installer can
10
+ # run before ERiC is available. Rake users can load the +eric:install+ task
11
+ # with <tt>require "liberic/tasks"</tt>.
12
+ #
13
+ # Extracting the archives requires rubyzip 3.4 or newer, which is not a
14
+ # runtime dependency of this gem. Add <tt>gem "rubyzip", ">= 3.4"</tt> to the
15
+ # Gemfile of the project that runs the installer.
16
+ #
17
+ # Liberic::EricInstaller.new(root: Rails.root.to_s).install
18
+ # # => ".../.eric/ERiC-43.5.4.0/Linux-x86_64"
19
+ class EricInstaller
20
+ DEFAULT_VERSION = SDK::Configuration::LIBERICAPI_VERSION.last
21
+ BASE_URL = "https://download.elster.de/download/eric"
22
+ ARTIFACT_SUFFIXES = [
23
+ "Linux-x86_64.jar",
24
+ "Dokumentation.zip",
25
+ "Schemadokumentation.zip"
26
+ ].freeze
27
+ # rubyzip before 3.4 allows path traversal during extraction.
28
+ MINIMUM_RUBYZIP_VERSION = "3.4"
29
+
30
+ class InstallError < StandardError; end
31
+
32
+ attr_reader :version, :root
33
+
34
+ # +version+ full ERiC release, such as "43.5.4.0"
35
+ # +root+ directory that receives the +.eric+ folder (default: current directory)
36
+ def initialize(version: DEFAULT_VERSION, root: Dir.pwd, output: $stdout)
37
+ @version = version
38
+ @root = File.expand_path(root)
39
+ @output = output
40
+ validate_version!
41
+ end
42
+
43
+ def major_version
44
+ version.split(".").first
45
+ end
46
+
47
+ def filenames
48
+ ARTIFACT_SUFFIXES.map { |suffix| "ERiC-#{version}-#{suffix}" }
49
+ end
50
+
51
+ def urls
52
+ filenames.map { |filename| "#{BASE_URL}/eric_#{major_version}/#{filename}" }
53
+ end
54
+
55
+ def install_root
56
+ File.join(root, ".eric")
57
+ end
58
+
59
+ def downloads_path
60
+ File.join(install_root, "downloads")
61
+ end
62
+
63
+ def sdk_home
64
+ File.join(install_root, "ERiC-#{version}", "Linux-x86_64")
65
+ end
66
+
67
+ def expected_library
68
+ File.join(sdk_home, "lib", "libericapi.so")
69
+ end
70
+
71
+ def install
72
+ check_platform!
73
+ FileUtils.mkdir_p(downloads_path)
74
+
75
+ if installed?
76
+ @output.puts "ERiC #{version} is already installed."
77
+ print_environment_setup
78
+ return sdk_home
79
+ end
80
+
81
+ archives = urls.zip(filenames).map do |url, filename|
82
+ path = File.join(downloads_path, filename)
83
+ download(url, path) unless File.file?(path)
84
+ path
85
+ end
86
+
87
+ archives.each { |archive| extract(archive) }
88
+ validate_installation!
89
+ File.write(installation_marker, "#{version}\n")
90
+
91
+ @output.puts "Installed ERiC #{version} in #{install_root}."
92
+ print_environment_setup
93
+ sdk_home
94
+ rescue InstallError
95
+ raise
96
+ rescue SystemCallError => error
97
+ raise InstallError, error.message
98
+ end
99
+
100
+ def download(url, destination, redirects: 5)
101
+ @output.puts "Downloading #{url}"
102
+ part = "#{destination}.part"
103
+ FileUtils.rm_f(part)
104
+
105
+ stream_download(URI(url), part, redirects)
106
+ File.rename(part, destination)
107
+ rescue StandardError => error
108
+ FileUtils.rm_f(part) if part
109
+ raise error if error.is_a?(InstallError)
110
+
111
+ raise InstallError, "download failed for #{url}: #{error.message}"
112
+ end
113
+
114
+ def extract(path)
115
+ if File.extname(path) == ".pdf"
116
+ FileUtils.cp(path, install_root)
117
+ return
118
+ end
119
+
120
+ load_rubyzip!
121
+ destination_root = File.expand_path(install_root)
122
+
123
+ Zip::File.open(path) do |archive|
124
+ archive.each do |entry|
125
+ destination = File.expand_path(entry.name, destination_root)
126
+ unless destination == destination_root || destination.start_with?("#{destination_root}#{File::SEPARATOR}")
127
+ raise InstallError, "invalid archive #{path}: unsafe entry #{entry.name.inspect}"
128
+ end
129
+
130
+ FileUtils.mkdir_p(File.dirname(destination))
131
+ entry.extract(entry.name, destination_directory: destination_root) { true }
132
+ end
133
+ end
134
+ rescue InstallError
135
+ # Listed first so a missing rubyzip is not masked by resolving Zip::Error.
136
+ raise
137
+ rescue Zip::Error, Errno::ENOENT, Errno::EACCES => error
138
+ raise InstallError, "invalid archive #{path}: #{error.message}"
139
+ end
140
+
141
+ private
142
+
143
+ def load_rubyzip!
144
+ require "zip"
145
+ return if Gem::Version.new(Zip::VERSION) >= Gem::Version.new(MINIMUM_RUBYZIP_VERSION)
146
+
147
+ raise InstallError,
148
+ "rubyzip >= #{MINIMUM_RUBYZIP_VERSION} is required (found #{Zip::VERSION}); " \
149
+ "older versions are vulnerable to path traversal"
150
+ rescue LoadError
151
+ raise InstallError,
152
+ "rubyzip is required; add gem \"rubyzip\", \">= #{MINIMUM_RUBYZIP_VERSION}\" to your Gemfile " \
153
+ "and run bundle install before eric:install"
154
+ end
155
+
156
+ def installation_marker
157
+ File.join(install_root, ".installed-#{version}")
158
+ end
159
+
160
+ def installed?
161
+ File.file?(installation_marker) && File.file?(expected_library)
162
+ end
163
+
164
+ def validate_version!
165
+ return if version.match?(/\A\d+\.\d+\.\d+\.\d+\z/)
166
+
167
+ raise InstallError, "invalid ERIC_VERSION #{version.inspect}; expected a version such as 43.5.4.0"
168
+ end
169
+
170
+ def check_platform!
171
+ return if RUBY_PLATFORM.match?(/x86_64-linux/)
172
+
173
+ raise InstallError, "eric:install supports Linux x86-64 only (current platform: #{RUBY_PLATFORM})"
174
+ end
175
+
176
+ def validate_installation!
177
+ return if File.file?(expected_library)
178
+
179
+ raise InstallError, "installation is incomplete: expected #{expected_library}"
180
+ end
181
+
182
+ def stream_download(uri, destination, redirects)
183
+ request = Net::HTTP::Get.new(uri)
184
+ Net::HTTP.start(uri.host, uri.port, use_ssl: uri.scheme == "https") do |http|
185
+ http.request(request) do |response|
186
+ case response
187
+ when Net::HTTPSuccess
188
+ File.open(destination, "wb") { |file| response.read_body { |chunk| file.write(chunk) } }
189
+ when Net::HTTPRedirection
190
+ raise InstallError, "too many redirects while downloading #{uri}" if redirects.zero?
191
+
192
+ location = response["location"]
193
+ raise InstallError, "redirect without a Location header while downloading #{uri}" unless location
194
+
195
+ stream_download(URI.join(uri, location), destination, redirects - 1)
196
+ else
197
+ raise InstallError, "download failed for #{uri}: HTTP #{response.code} #{response.message}"
198
+ end
199
+ end
200
+ end
201
+ end
202
+
203
+ def print_environment_setup
204
+ @output.puts
205
+ @output.puts "Set ERIC_HOME in your shell:"
206
+ @output.puts %(export ERIC_HOME="#{sdk_home}")
207
+ @output.puts "Rake cannot permanently modify the environment of its parent shell."
208
+ end
209
+ end
210
+ end
@@ -1,26 +1,63 @@
1
1
  module Liberic
2
2
  module Helpers
3
3
  module Invocation
4
+ # Raised when an ERiC function returns a code other than +ERIC_OK+.
5
+ #
6
+ # The message is the name of the code (as in earlier versions); +code+,
7
+ # +error+ and +buffer+ carry the numeric code, its name and the content
8
+ # of the result buffer (if any).
4
9
  class Error < StandardError
10
+ attr_reader :code, :buffer
11
+
12
+ def initialize(message = nil, code: nil, buffer: nil)
13
+ @code = code
14
+ @buffer = buffer
15
+ super(message || Invocation.error_name(code))
16
+ end
17
+
18
+ # The name of the ERiC return code, e.g. "ERIC_GLOBAL_PRUEF_FEHLER".
19
+ def error
20
+ Invocation.error_name(code) if code
21
+ end
5
22
  end
6
23
 
7
24
  extend self
8
25
 
9
- def raise_on_error(value)
26
+ def raise_on_error(value, buffer = nil)
10
27
  return value if value == SDK::Fehlercodes::ERIC_OK
11
- raise Error.new(SDK::Fehlercodes::CODES[value])
28
+ raise Error.new(code: value, buffer: buffer)
12
29
  end
13
30
 
31
+ # Creates a result buffer, yields its handle and returns the buffer's
32
+ # content.
33
+ #
34
+ # With +raise_on_error+ (the default), a return code of the block other
35
+ # than +ERIC_OK+ raises +Error+, which carries the code and the buffer
36
+ # content. With +raise_on_error = false+ the return code is ignored; use
37
+ # +call_with_result_buffer+ to receive it.
14
38
  def with_result_buffer(raise_on_error = true, &block)
39
+ code, result = call_with_result_buffer(&block)
40
+ raise_on_error(code, result) if raise_on_error
41
+ result
42
+ end
43
+
44
+ # Creates a result buffer, yields its handle and returns
45
+ # <tt>[return_code, buffer_content]</tt>, where +return_code+ is the
46
+ # block's value (the return code of the ERiC function called in it).
47
+ def call_with_result_buffer
15
48
  handle = SDK::API.rueckgabepuffer_erzeugen
16
- if raise_on_error
17
- raise_on_error(yield(handle))
18
- else
19
- yield(handle)
49
+ begin
50
+ code = yield(handle)
51
+ [code, SDK::API.rueckgabepuffer_inhalt(handle)]
52
+ ensure
53
+ SDK::API.rueckgabepuffer_freigeben(handle)
20
54
  end
21
- result = Liberic::SDK::API.rueckgabepuffer_inhalt(handle)
22
- SDK::API.rueckgabepuffer_freigeben(handle)
23
- result
55
+ end
56
+
57
+ # The name of an ERiC return code, e.g. "ERIC_OK". Unknown codes are
58
+ # returned as "ERIC_UNKNOWN_CODE_<code>".
59
+ def error_name(code)
60
+ SDK::Fehlercodes::CODES[code] || "ERIC_UNKNOWN_CODE_#{code}"
24
61
  end
25
62
  end
26
63
  end
@@ -13,95 +13,286 @@ module Liberic
13
13
  class ExecutionError < StandardError
14
14
  end
15
15
 
16
+ # Raised by +execute!+ when ERiC returns a code other than +ERIC_OK+.
17
+ # +result+ is the +Result+ of the call, including the result buffers.
18
+ class ProcessingError < ExecutionError
19
+ attr_reader :result
20
+
21
+ def initialize(result)
22
+ @result = result
23
+ super("#{result.error} (#{result.code})")
24
+ end
25
+
26
+ def code
27
+ result.code
28
+ end
29
+
30
+ def error
31
+ result.error
32
+ end
33
+ end
34
+
35
+ # The result of +execute+.
36
+ #
37
+ # For backwards compatibility this is a Hash with the keys +:result+ (the
38
+ # content of ERiC's result buffer, an XML string or empty) and
39
+ # +:server_result+ (the server's response, if anything was sent). In
40
+ # addition it carries ERiC's return code:
41
+ #
42
+ # result = filing.execute
43
+ # result.ok? # => false
44
+ # result.code # => 610001002
45
+ # result.error # => "ERIC_GLOBAL_PRUEF_FEHLER" (nil if ok)
46
+ # result[:result] # => "<EricBearbeiteVorgang ...><Fehler..."
47
+ #
48
+ # An empty +:result+ does not mean success: always check +ok?+.
49
+ class Result < Hash
50
+ # ERiC's return code.
51
+ attr_reader :code
52
+
53
+ # The PDFs created with <tt>pdf: :memory</tt>, as a Hash from ERiC's
54
+ # name of each PDF (the Nutzdatenticket of the data block, or
55
+ # "Uebertragungsprotokoll") to its content (a binary String). Empty
56
+ # otherwise.
57
+ attr_reader :pdfs
58
+
59
+ def initialize(code:, result:, server_result:, pdfs: {})
60
+ super()
61
+ @code = code
62
+ @pdfs = pdfs
63
+ self[:result] = result
64
+ self[:server_result] = server_result
65
+ end
66
+
67
+ # +true+ if ERiC found no errors: the return code is +ERIC_OK+, or
68
+ # +ERIC_GLOBAL_HINWEISE+, which ERiC returns only for the action
69
+ # +:validate_with_hints+ when it found hints but no errors.
70
+ def ok?
71
+ code == SDK::Fehlercodes::ERIC_OK || hints?
72
+ end
73
+
74
+ # +true+ if ERiC returned +ERIC_GLOBAL_HINWEISE+: the data has no errors,
75
+ # and the +<Hinweis>+ elements in +:result+ list hints.
76
+ def hints?
77
+ code == SDK::Fehlercodes::ERIC_GLOBAL_HINWEISE
78
+ end
79
+
80
+ # The name of the return code, e.g. "ERIC_GLOBAL_PRUEF_FEHLER", or +nil+
81
+ # if the call succeeded.
82
+ def error
83
+ Helpers::Invocation.error_name(code) unless ok?
84
+ end
85
+
86
+ def result
87
+ self[:result]
88
+ end
89
+
90
+ def server_result
91
+ self[:server_result]
92
+ end
93
+
94
+ def inspect
95
+ "#<#{self.class.name} code=#{code} error=#{error.inspect} #{super}>"
96
+ end
97
+ end
98
+
99
+ # The +EricTransferHandle+ that bundles the calls of a Datenabholung
100
+ # (request, retrieval and optional acknowledgement). Create one per
101
+ # Datenabholung and pass it to every call with +:transfer_handle+:
102
+ #
103
+ # handle = Liberic::Process::TransferHandle.new
104
+ # request = Liberic::Process.new(request_xml, type).execute(action: :submit, encryption: params, transfer_handle: handle)
105
+ # retrieval = Liberic::Process.new(retrieval_xml, type).execute(action: :submit, encryption: params, transfer_handle: handle)
106
+ #
107
+ # ERiC requires NULL for all other use cases, which +execute+ passes
108
+ # without +:transfer_handle+.
109
+ class TransferHandle
110
+ def initialize
111
+ @pointer = FFI::MemoryPointer.new(:uint32, 1) # zero-filled, as ERiC requires
112
+ end
113
+
114
+ # The handle's current value, set by ERiC.
115
+ def value
116
+ @pointer.get_uint32(0)
117
+ end
118
+
119
+ def to_ptr
120
+ @pointer
121
+ end
122
+ end
123
+
16
124
  def initialize(xml, type)
17
125
  @xml = xml
18
126
  @type = type
19
127
  end
20
128
 
129
+ # Checks the XML against ERiC's schema (+EricCheckXML()+).
130
+ #
131
+ # Returns the (usually empty) content of the result buffer. Raises
132
+ # +Helpers::Invocation::Error+ if the check fails; its +buffer+ contains
133
+ # ERiC's error text, one line per error, for example
134
+ # <tt>EC(1000): Fehler: EDS-XML in Zeile 39 in Spalte 40: ...</tt>.
21
135
  def check
22
136
  Helpers::Invocation.with_result_buffer do |handle|
23
137
  SDK::API.check_xml(@xml, @type, handle)
24
138
  end
25
139
  end
26
140
 
27
- # Executes the actual call to +EricBearbeiteVorgang()+
141
+ # Executes the actual call to +EricBearbeiteVorgang()+ and returns a +Result+.
142
+ #
143
+ # The call does not raise if ERiC returns an error code; check +Result#ok?+
144
+ # or use +execute!+.
28
145
  #
29
146
  # Taken an optional hash with an +:action+ parameter, which can be one of the following:
30
147
  #
31
148
  # * +:validate+ validate the tax filing and return errors (local processing only)
32
- # * +:print+ validate the tax filing and create summary PDF
33
- # * +:print_and_submit+ validate the tax filing, create summary PDF and submit filing to ELSTER (server).
149
+ # * +:validate_with_hints+ validate the tax filing and return errors and hints (+<Hinweis>+ elements,
150
+ # see +Result#hints?+) in one call (local processing only)
151
+ # * +:print+ validate the tax filing and create a preview PDF (local processing only)
152
+ # * +:print_and_submit+ validate the tax filing, submit it to ELSTER (server) and create
153
+ # the PDF of the submitted filing (+ERIC_VALIDIERE+, +ERIC_SENDE+ and +ERIC_DRUCKE+)
154
+ # * +:submit+ validate and submit the tax filing without creating a PDF
155
+ # * +:print_and_submit_auth+ deprecated alias of +:print_and_submit+
156
+ #
157
+ # Whether a submission is authenticated depends on +:encryption+, not on the action.
34
158
  #
35
159
  # Options for controlling the PDF output (printing)
36
160
  #
37
- # * +:filename+ (set a filename including path where to store the PDF file)
38
- # * +:draft+ (set to +false+ to remove the the text "*** ENTWURF ***" on every page)
39
- # * +:footer+ (set a string that will be printed on ever page footer)
161
+ # * +:filename+ (path of the PDF file to create)
162
+ # * +:pdf+ (set to +:memory+ to receive the PDFs in +Result#pdfs+ instead of a file;
163
+ # do not pass +:filename+ then)
164
+ # * +:draft+ (+true+ prints the text "*** ENTWURF ***" on every page. Defaults to +true+
165
+ # for +:print+, which ERiC 43 allows only as a preview, and to +false+ for
166
+ # +:print_and_submit+, which ERiC rejects with +draft: true+ before sending)
167
+ # * +:footer+ (set a string that will be printed on ever page footer, at most 30 characters;
168
+ # see the README for the characters ERiC accepts)
40
169
  # * +:duplex+ (set to +true+ to generate pages for duplex printing (alternating margin left and right)
41
170
  #
42
171
  # Other options
43
172
  # * +:encryption+ An instance of +SDK::Types::VerschluesselungsParameter+ (Leave this empty when requesting BescheidRueckuebermittlung with CEZ (locally generated certificate))
44
- # No use case tested yet.
173
+ # See +Certificate#encryption_params+.
174
+ # * +:transfer_handle+ A +TransferHandle+, only for the calls of a Datenabholung.
45
175
  #
46
- # TODO: Please note that some parameter combinations might result in errors and will return empty strings for the XML
47
- # (these errors are currently not checked). One example is using +draft: false+ with test data
176
+ # ERiC 43 has no default directory for PDFs. An action that prints needs
177
+ # +:filename+ or <tt>pdf: :memory</tt>; without either, it returns
178
+ # +ERIC_GLOBAL_NULL_PARAMETER+, for +:print_and_submit+ before sending
179
+ # (measured with ERiC 43.5.4.0). A relative +:filename+ is resolved
180
+ # against the current working directory.
48
181
  #
49
- # Set +Liberic.config.data_path+ to the location where the PDF should be stored, if +:filename+ is not provided.
182
+ # Some parameter combinations result in errors, for example +draft: false+
183
+ # with +:print+ (ERiC prints locally only as a preview) or +draft: true+
184
+ # with +:print_and_submit+. They are reported through +Result#code+.
50
185
  #
51
186
  # Example:
52
187
  #
53
- # filing = Liberic::Process.new(xml_tax_filing, 'ESt_2011')
54
- # filing.execute(action: :print)
188
+ # filing = Liberic::Process.new(xml_tax_filing, 'ESt_2020')
189
+ # result = filing.execute(action: :print, filename: '/tmp/est_2020.pdf')
190
+ # raise result.error unless result.ok?
191
+ #
192
+ # result = filing.execute(action: :print, pdf: :memory)
193
+ # result.pdfs # => {"<Nutzdatenticket>" => "%PDF-1.4..."}
55
194
  #
56
- # Will generate a PDF in the current directory if not specified otherwise.
57
195
  # *WARNING* method signature and parameters are WIP and subject to change
58
196
  def execute(options = {})
59
197
  action = options[:action] ||= :validate
60
198
  eric_action = ACTIONS[action] || (raise ExecutionError.new("Invalid action: #{action}. Valid actions are #{ACTIONS.keys.join(', ')}"))
61
- is_printing = %w[submit print_and_submit print_and_submit_auth].include?(action.to_s)
62
- print_params = create_print_params(options)
199
+ if action == :print_and_submit_auth
200
+ warn('Liberic::Process action :print_and_submit_auth is deprecated; use :print_and_submit',
201
+ category: :deprecated, uplevel: 1)
202
+ end
203
+ pdfs = {}
204
+ print_params = create_print_params(options, pdfs)
63
205
  server_buffer = SDK::API.rueckgabepuffer_erzeugen
64
- result = Helpers::Invocation.with_result_buffer(false) do |local_buffer|
65
- SDK::API.bearbeite_vorgang(@xml, @type,
66
- eric_action,
67
- (action == :submit ? nil : print_params),
68
- options[:encryption],
69
- (is_printing ? FFI::MemoryPointer.new(:uint32, 1) : nil), # transferHandle
70
- local_buffer,
71
- server_buffer)
72
- end
73
- server_result = SDK::API.rueckgabepuffer_inhalt(server_buffer)
74
- SDK::API.rueckgabepuffer_freigeben(server_buffer)
75
- print_params.pointer.free
76
- {
77
- result: result,
78
- server_result: server_result
79
- }
206
+ begin
207
+ code, result = Helpers::Invocation.call_with_result_buffer do |local_buffer|
208
+ SDK::API.bearbeite_vorgang(@xml, @type,
209
+ eric_action,
210
+ (PRINTS.include?(action) ? print_params : nil),
211
+ options[:encryption],
212
+ options[:transfer_handle],
213
+ local_buffer,
214
+ server_buffer)
215
+ end
216
+ raise @pdf_callback_error if @pdf_callback_error
217
+ Result.new(code: code, result: result, server_result: SDK::API.rueckgabepuffer_inhalt(server_buffer), pdfs: pdfs)
218
+ ensure
219
+ @pdf_callback_error = nil
220
+ SDK::API.rueckgabepuffer_freigeben(server_buffer)
221
+ end
222
+ end
223
+
224
+ # Like +execute+, but raises +ProcessingError+ unless +Result#ok?+.
225
+ # The exception carries the +Result+ (code, name and buffer contents).
226
+ def execute!(options = {})
227
+ result = execute(options)
228
+ raise ProcessingError.new(result) unless result.ok?
229
+ result
80
230
  end
81
231
 
82
232
  private
83
233
 
234
+ flags = SDK::Types::BearbeitungFlag
235
+ # Sending and printing needs ERIC_DRUCKE together with ERIC_SENDE
236
+ # (ERiC-Entwicklerhandbuch, Tabelle 6-2, EBV-4 and EBV-6). With
237
+ # ERIC_SENDE alone, ERiC 43.5.4.0 sends but ignores the print parameters.
238
+ # The flags are the same for authenticated and unauthenticated sending;
239
+ # +:encryption+ decides.
240
+ SEND_AND_PRINT = flags[:validiere] | flags[:sende] | flags[:drucke]
241
+
84
242
  ACTIONS = {
85
243
  validate: :validiere,
244
+ # ERIC_PRUEFE_HINWEISE alone skips validation, so it is always combined
245
+ # with ERIC_VALIDIERE.
246
+ validate_with_hints: flags[:validiere] | flags[:pruefe_hinweise],
86
247
  print: :drucke,
87
- print_and_submit: :sende,
248
+ print_and_submit: SEND_AND_PRINT,
88
249
  submit: :sende,
89
- print_and_submit_auth: :sende_auth
90
- }
250
+ # Deprecated alias of :print_and_submit.
251
+ print_and_submit_auth: SEND_AND_PRINT
252
+ }.freeze
91
253
 
92
- # TODO: check for updates regarding version
93
- def create_print_params(options)
254
+ # Actions that pass the print parameters to ERiC.
255
+ PRINTS = %i[print print_and_submit print_and_submit_auth].freeze
256
+
257
+ # Actions that send and print. ERiC prints the final document then and
258
+ # rejects a preview (vorschau=1) with ERIC_GLOBAL_UNGUELTIGER_PARAMETER
259
+ # before sending, so +:draft+ defaults to +false+ for them.
260
+ SENDS_AND_PRINTS = %i[print_and_submit print_and_submit_auth].freeze
261
+
262
+ # The returned struct holds references to the native copies of
263
+ # +:filename+ and +:footer+ and to the PDF callback, so they stay
264
+ # allocated while it is in use. With <tt>pdf: :memory</tt> the callback
265
+ # adds the PDFs to +pdfs+.
266
+ def create_print_params(options, pdfs)
94
267
  params = SDK::Types::DruckParameter.new
95
268
  params[:version] = 4
96
269
  params[:duplexDruck] = options[:duplex] ? 1 : 0
97
- params[:vorschau] = options.has_key?(:draft) ? (options[:draft] ? 1 : 0) : 1
98
- {pdfName: :filename,
99
- fussText: :footer}.each do |eric_param, ruby_param|
100
- if options[ruby_param]
101
- params[eric_param] = FFI::MemoryPointer.from_string(options[ruby_param]).address
102
- end
270
+ params[:vorschau] = options.fetch(:draft, !SENDS_AND_PRINTS.include?(options[:action])) ? 1 : 0
271
+ params.set_string(:pdfName, options[:filename]) if options[:filename]
272
+ # ERiC expects the footer in UTF-8.
273
+ params.set_string(:fussText, options[:footer].to_s.encode(Encoding::UTF_8)) if options[:footer]
274
+ case options[:pdf]
275
+ when nil, :file
276
+ when :memory
277
+ raise ExecutionError.new('Pass either :filename or pdf: :memory, not both') if options[:filename]
278
+ params.set_pdf_callback(pdf_callback(pdfs))
279
+ else
280
+ raise ExecutionError.new("Invalid pdf option: #{options[:pdf].inspect}. Valid values are :file, :memory")
103
281
  end
104
282
  params
105
283
  end
284
+
285
+ # ERiC cannot unwind a Ruby exception raised in the callback. It is kept
286
+ # and raised by +execute+ after ERiC returns; ERiC aborts printing with
287
+ # ERIC_PRINT_PDFCALLBACK.
288
+ def pdf_callback(pdfs)
289
+ SDK::API.generate_pdf_callback do |name, data|
290
+ pdfs[name] = data
291
+ 0
292
+ rescue Exception => error # rubocop:disable Lint/RescueException
293
+ @pdf_callback_error = error
294
+ 1
295
+ end
296
+ end
106
297
  end
107
298
  end
@@ -196,6 +196,15 @@ module Liberic
196
196
  # const byteChar* steuernummer);
197
197
  attach_eric_function :pruefe_steuernummer, [:string], :int
198
198
 
199
+ # ERICAPI_IMPORT int STDCALL EricZertifikatOeffnenAusBytes(
200
+ # EricZertifikatHandle* hToken,
201
+ # const byteChar *pkcs12Container,
202
+ # uint32_t containerGroesse,
203
+ # const byteChar *pkcs12Passwort);
204
+ # The container is binary data and the password is wiped after the call
205
+ # (see Certificate.from_bytes), so both are passed as pointers.
206
+ attach_eric_function :zertifikat_oeffnen_aus_bytes, [:pointer, :pointer, :uint32, :pointer], :int
207
+
199
208
  # TODO
200
209
  # ERICAPI_IMPORT int STDCALL EricPruefeZertifikatPin(
201
210
  # const byteChar *pathToKeystore,
@@ -212,7 +221,6 @@ module Liberic
212
221
  # EricFortschrittCallback funktion,
213
222
  # void* benutzerdaten);
214
223
 
215
- # check if this still works...
216
224
  # typedef void(STDCALL *EricLogCallback)(
217
225
  # const char* kategorie,
218
226
  # eric_log_level_t loglevel,
@@ -232,6 +240,25 @@ module Liberic
232
240
  end
233
241
  end
234
242
 
243
+ # typedef int(STDCALL *EricPdfCallback)(
244
+ # const char *pdfBezeichner,
245
+ # const BYTE *pdfDaten,
246
+ # uint32_t pdfGroesse,
247
+ # void *benutzerDaten);
248
+ #
249
+ # Returns an FFI::Function for eric_druck_parameter_t.pdfCallback. The
250
+ # block receives the PDF's name (the Nutzdatenticket, or
251
+ # "Uebertragungsprotokoll") and its content as a binary String. The
252
+ # block's value is returned to ERiC: 0 for success; anything else makes
253
+ # ERiC abort printing with ERIC_PRINT_PDFCALLBACK. Keep a reference to
254
+ # the function while ERiC may call it (DruckParameter#set_pdf_callback
255
+ # does). Exceptions must not leave the block: ERiC cannot unwind them.
256
+ def self.generate_pdf_callback(&block)
257
+ FFI::Function.new(:int, [:string, :pointer, :uint32, :pointer]) do |name, data, size, _user_data|
258
+ block.call(name, data.read_bytes(size))
259
+ end
260
+ end
261
+
235
262
  # ERICAPI_IMPORT EricRueckgabepufferHandle STDCALL EricRueckgabepufferErzeugen(
236
263
  # void);
237
264
  attach_eric_function :rueckgabepuffer_erzeugen, [], :pointer
@@ -1,7 +1,7 @@
1
1
  module Liberic
2
2
  module SDK
3
3
  module Configuration
4
- LIBERICAPI_VERSION = %w(40.3.2.0)
4
+ LIBERICAPI_VERSION = %w(43.5.4.0)
5
5
  ENCODING = 'iso-8859-15'
6
6
  end
7
7
  end