Class: Brand2csv::Swissreg

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

Defined Under Namespace

Classes: Vereinfachte

Constant Summary collapse

BekannteFehler =

Weitere gesehene Fehler

['Das Datum ist ung', # ültig'
 '500 Internal Server Error',
 'Vereinfachte Trefferliste anzeigen',
  'Es wurden keine Daten gefunden.',
  'Die Suchkriterien sind teilweise unzul', # ässig',
  'Geben Sie mindestens ein Suchkriterium ein',
  'Die Suche wurde abgebrochen, da die maximale Suchzeit von 60 Sekunden',
 'Erweiterte Suche',
]
Base_uri =
'https://www.swissreg.ch'
Start_uri =
"#{Base_uri}/srclient/faces/jsp/start.jsp"
Sr1 =
"#{Base_uri}/srclient/faces/jsp/trademark/sr1.jsp"
Sr2 =
"#{Base_uri}/srclient/faces/jsp/trademark/sr2.jsp"
Sr3 =
"#{Base_uri}/srclient/faces/jsp/trademark/sr3.jsp"
Sr30 =
"#{Base_uri}/srclient/faces/jsp/trademark/sr30.jsp"
Sr300 =
"#{Base_uri}/srclient/faces/jsp/trademark/sr300.jsp"
DetailRegexp =
/d_swissreg:mainContent:data:(\d*):tm_no_detail:id_detail/i
AddressRegexp =
/^(\d\d\d\d)\W*(.*)/
LineSplit =
', '
DefaultCountry =
'Schweiz'
TMChoiceFields =

Angezeigte Spalten “id_swissreg:mainContent:id_ckbTMChoice”

[ 
"tm_lbl_tm_text", # Marke
# "tm_lbl_state"], # Status
# "tm_lbl_nizza_class"], # Nizza Klassifikation Nr.
# "tm_lbl_no"], # disabled="disabled"], # Nummer
"tm_lbl_applicant", # Inhaber/in
"tm_lbl_country", # Land (Inhaber/in)
"tm_lbl_agent", # Vertreter/in
# "tm_lbl_licensee"], # Lizenznehmer/in
"tm_lbl_app_date", # Hinterlegungsdatum
]
MaxZeilen =
5
HitsPerPage =
250
LogDir =
'log'
UseClick =
false

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(timespan, marke = nil, swiss_only = false) ⇒ Swissreg



93
94
95
96
97
98
99
100
101
102
103
# File 'lib/brand2csv.rb', line 93

def initialize(timespan, marke = nil, swiss_only=false)
  @timespan = timespan
  @marke = marke
  @swiss_only = swiss_only
  @number = nil
  @results = []
  @all_trademark_numbers = []
  @errors  = Hash.new
  @lastDetail =nil
  @counterDetails = 0
end

Instance Attribute Details

#markeObject

Returns the value of attribute marke.



91
92
93
# File 'lib/brand2csv.rb', line 91

def marke
  @marke
end

#resultsObject

Returns the value of attribute results.



91
92
93
# File 'lib/brand2csv.rb', line 91

def results
  @results
end

#timespanObject

Returns the value of attribute timespan.



91
92
93
# File 'lib/brand2csv.rb', line 91

def timespan
  @timespan
end

Class Method Details

.emitCsv(results, filename = 'ausgabe.csv') ⇒ Object



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

def Swissreg::emitCsv(results, filename='ausgabe.csv')
  return if results == nil or results.size == 0
  all_inhaber = {}
  results.each do |result|
    next if all_inhaber[result.inhaber]
    all_inhaber[result.inhaber] = result
  end
  if /^1\.8/.match(RUBY_VERSION)
    ausgabe = File.open(filename, 'w+')
    # Write header
    s=''
    results[0].members.each { |member| s += member + ';' }
    ausgabe.puts s.chop
    # write all line
    all_inhaber.values.each{
      |result| 
        s = ''
        result.members.each{ |member| 
                              unless eval("result.#{member}") 
                                s += ';'
                              else
                                value = eval("result.#{member.to_s}")
                                value = "\"#{value}\"" if value.index(';')
                                s += value + ';' 
                              end
                           }
        ausgabe.puts s.chop
    }
    ausgabe.close
  else
    CSV.open(filename,  'w', :headers=>results[0].members,
                              :write_headers => true,
                              :col_sep => ';'
                            ) do |csv| all_inhaber.values.each{ |x| csv << x }
    end
  end
end

.getInputValuesFromPage(body) ⇒ Object

body of HTML page



272
273
274
275
276
277
278
279
# File 'lib/brand2csv.rb', line 272

def Swissreg::getInputValuesFromPage(body) # body of HTML page
  contentData = []
  body.search('input').each{ |input| 
                            # puts "name: #{input.attribute('name')} value #{input.attribute('value')}" 
                            contentData << [ input.attribute('name').to_s, input.attribute('value').to_s ]
                            }
  contentData
end

.getMarkenInfoFromDetail(doc) ⇒ Object



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

def Swissreg::getMarkenInfoFromDetail(doc)
  marke = nil
  number = 'invalid'
  bezeichnung = nil
  inhaber = nil
  hinterlegungsdatum = nil
  hatVertreter = 'Nein'
  doc.xpath("//html/body/form/div/div/fieldset/div/table/tbody/tr").each{ 
    |x|
      if x.children.first.text.eql?('Marke')
        if x.children[1].text.index('Markenabbildung')
          # we must fetch the link to the image
          bezeichnung =  x.children[1].elements.first.attribute('href').text
        else # we got a trademark
          bezeichnung = x.children[1].text 
        end
      end

      if x.children.first.text.eql?('Inhaber/in')
         inhaber = />(.*)<\/td/.match(x.children[1].to_s)[1].gsub('<br>',LineSplit)
      end
      
      if x.children.first.text.eql?('Vertreter/in')
        hatVertreter = 'Ja' if x.children[1].text.length > 0
      end
      hinterlegungsdatum = x.children[1].text if x.children.first.text.eql?('Hinterlegungsdatum')           
      number = x.children[1].text if x.children.first.text.eql?('Gesuch Nr.')           
  }
  zeile_1, zeile_2, zeile_3, zeile_4, zeile_5, plz, ort = Swissreg::parseAddress(number, inhaber)
  inhaber = inhaber.split(', , ')[0] # Catch cases where Inhaber has several postal addresses
  marke = Marke.new(bezeichnung, number,  inhaber, DefaultCountry, hatVertreter, hinterlegungsdatum, zeile_1, zeile_2, zeile_3, zeile_4, zeile_5, plz, ort )
end

.getTrademarkNumbers(doc) ⇒ Object



416
417
418
419
420
421
422
423
424
425
# File 'lib/brand2csv.rb', line 416

def Swissreg::getTrademarkNumbers(doc)
  trademark_numbers = []
  doc.search('a').each{ 
    |link| 
      if DetailRegexp.match(link.attribute('id'))
        trademark_numbers << link.children.first.children.first.content
      end
  }
  trademark_numbers
end

.inputValue(values, key) ⇒ Object

return value of an array of POST values



282
283
284
285
286
287
# File 'lib/brand2csv.rb', line 282

def Swissreg::inputValue(values, key)
  values.each{ |val| 
               return val[1] if key.eql?(val[0])
            }
  return nil
end

.parseAddress(number, inhaber) ⇒ Object

the number is only passed to facilitate debugging lines are the address lines



230
231
232
233
234
235
236
237
238
239
240
241
242
243
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
# File 'lib/brand2csv.rb', line 230

def Swissreg::parseAddress(number, inhaber)
  ort = nil
  plz = nil
  if inhaber
    lines = CGI.unescapeHTML(inhaber).split(LineSplit)
    # Search for plz/address
    1.upto(lines.length-1).each  {
      |cnt|
        if    m = AddressRegexp.match(lines[cnt])
          lines[cnt+1] = nil
          plz = m[1]; ort = m[2]
          cnt.upto(MaxZeilen-1).each{ |cnt2| lines[cnt2] = nil }
          break
        end
    }
  end
  unless plz
    puts "Achtung! Konnte Marke #{number} mit Inhaber #{lines.inspect} nicht parsen" if $VERBOSE
    return nil,   nil,     nil,     nil,     nil,     nil,     nil, nil
  end
  # search for lines with only digits
  found = false
  1.upto(lines.length-1).each  {
    |cnt|
      break if lines[cnt] == nil
      if /^\d*$/.match(lines[cnt])
        found = true
        if lines[cnt+1] == nil
          found = 'before'
          lines[cnt-1] += LineSplit + lines[cnt]
          lines.delete_at(cnt)
        else
          found = 'after'
          lines[cnt] += LineSplit + lines[cnt+1]
          lines.delete_at(cnt+1)
        end
      end        
  }
  puts "found #{found}: #{lines.inspect}" if found and $VERBOSE
  return lines[0], lines[1], lines[2], lines[3], lines[4], plz, ort
end

.setAllInputValue(form, values) ⇒ Object



300
301
302
303
304
305
306
307
308
# File 'lib/brand2csv.rb', line 300

def Swissreg::setAllInputValue(form, values)
  values.each{ |newValue|
#                 puts "x: 0 #{ newValue[0].to_s} 1 #{newValue[1].to_s}"
                form.field(:name => newValue[0].to_s) { |elem| 
                                                        next if elem == nil # puts "Cannot set #{newValue[0].to_s}"
                                                        elem.value = newValue[1].to_s 
                                                      }
             }
end

.setInputValue(values, key, newValue) ⇒ Object

set value for a key of an array of POST values



290
291
292
293
294
295
296
297
298
# File 'lib/brand2csv.rb', line 290

def Swissreg::setInputValue(values, key, newValue)
  values.each{ |val| 
                if key.eql?(val[0])
                  val[1] = newValue
                  return
                end
            }
  return
end

Instance Method Details

#checkErrors(body, exitIfFailure = true) ⇒ Object



115
116
117
118
119
120
121
122
123
124
125
126
127
# File 'lib/brand2csv.rb', line 115

def checkErrors(body, exitIfFailure = true)
  BekannteFehler.each {
  |errMsg|
    if body.to_s.index(errMsg)
      if exitIfFailure
        puts "Tut mir leid. Suche wurde mit Fehlermeldung <#{errMsg}> abgebrochen."
        exit 2
      else
        puts "Info: Suche meldet <#{errMsg}> "
      end
    end
  }
end

#fetchDetails(nummer) ⇒ Object

takes a long time!



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
373
374
375
376
# File 'lib/brand2csv.rb', line 343

def fetchDetails(nummer) # takes a long time!
  @counterDetails += 1
  init_swissreg if @counterDetails % 90 == 0 # it seems that swissreg is artificially slowing down serving request after 100 hits
  filename = "#{LogDir}/detail_#{sprintf('%05d', @counterDetails)}_#{nummer.gsub('/','.')}.html"
  if File.exists?(filename)
    doc = Nokogiri::Slop(File.open(filename))
  else
    url = "#{Sr300}?language=de&section=tm&id=#{nummer}"
    pp "#{Time.now.strftime("%H:%M:%S")}: Opening #{filename}" if $VERBOSE
    $stdout.flush
    nrRetries = 0
    begin
      content = @agent.get_file url
      body = @agent.page.body
    rescue 'getaddrinfo: Name or service not known', Exception => e
      nrRetries += 1
      puts e.backtrace
      if nrRetries <= 3
        puts "get_file did not work reinit session and retry for #{nummer}. nrRetries #{nrRetries}/3. e #{e}"
        sleep 60  # Sleep a minute to let network recover
        init_swissreg
        retry
      else
        puts "get_file did not work reinit session raise Interrupt"
        raise Interrupt
      end
    end
    body.force_encoding('utf-8') unless /^1\.8/.match(RUBY_VERSION)
    doc = Nokogiri::Slop(body)
    writeResponse(filename)
  end
  marke =  Swissreg::getMarkenInfoFromDetail(doc)
  @results << marke
end

#fetchresult(filename = "#{LogDir}/fetch_1.html", counter = 1) ⇒ Object



535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
# File 'lib/brand2csv.rb', line 535

def fetchresult(filename =  "#{LogDir}/fetch_1.html", counter = 1)
  if filename && File.exists?(filename)
    doc = Nokogiri::Slop(File.open(filename))        
  else
    body = @agent.page.body
    body.force_encoding('utf-8') unless /^1\.8/.match(RUBY_VERSION)
    doc = Nokogiri::Slop(body)
    writeResponse(filename)
  end
  
  if /Vereinfachte Trefferliste anzeigen/i.match(doc.text)
    form = @agent.page.forms.first
    button = form.button_with(:value => /Vereinfachte/i)
    # submit the form using that button
    @agent.submit(form, button)
    filename =  "#{LogDir}/vereinfacht.html"
    writeResponse(filename)
  end
  getAllHits(doc, counter)
  puts"getAllHits: returned #{@all_trademark_numbers ? @all_trademark_numbers.size : 0} hits "
  if @all_trademark_numbers
    @all_trademark_numbers.each{ 
      |nr|
        nrRetries = 0
        begin
          fetchDetails(nr)
        rescue SocketError, Exception => e
          nrRetries += 1
          puts e.backtrace
          if nrRetries <= 3
            puts "fetchDetails did not work reinit session and retry for #{nr}. nrRetries #{nrRetries}/3. e #{e}"
            sleep 60  # Sleep a minute to let network recover
            init_swissreg
            retry
          else
            puts "fetchDetails did not work reinit session raise Interrupt"
            raise Interrupt
          end
        end
    
    }
  else
    puts "Could not find any trademarks in #{filename}"
  end
end

#getAllHits(filename = nil, pageNr = 1) ⇒ Object



497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
# File 'lib/brand2csv.rb', line 497

def getAllHits(filename = nil, pageNr = 1)
  if filename && File.exists?(filename)
    doc = Nokogiri::Slop(File.open(filename))        
  else
    form = @agent.page.form
    btn  = form.buttons.last
    if btn && btn.name == "id_swissreg:mainContent:id_show_simple_view_hitlist"
      res = @agent.submit(form, btn)
      body = res.body
    else
     body = @agent.page.body
    end
    body.force_encoding('utf-8') unless /^1\.8/.match(RUBY_VERSION)
    doc = Nokogiri::Slop(body)
    filename = "#{LogDir}/vereinfachte_#{pageNr}.html"
    writeResponse(filename)
  end
  einfach = Swissreg::Vereinfachte.new(doc)
  puts "#{Time.now.strftime("%H:%M:%S")} status: getAllHits for #{pageNr} of #{einfach.nrSubPages} pages"  if $VERBOSE
  subPage2Fetch = pageNr + 1
  data2 = einfach.getPostDataForSubpage(subPage2Fetch).clone
  if (HitsPerPage < einfach.nrHits - einfach.firstHit)
    itemsToFetch = HitsPerPage
  else
    itemsToFetch = einfach.nrHits - einfach.firstHit
  end
  @all_trademark_numbers += Swissreg::getTrademarkNumbers(doc)

  filename = "#{LogDir}/vereinfachte_#{pageNr}_back.html"
  writeResponse(filename)
  if pageNr < (einfach.nrSubPages)
    Swissreg::setAllInputValue(@agent.page.forms.first, data2)
    @agent.page.forms.first.submit
    getAllHits(nil, subPage2Fetch)
  end      
  @all_trademark_numbers
end

#init_swissregObject

Initialize a session with swissreg and save the cookie as @state



132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
# File 'lib/brand2csv.rb', line 132

def init_swissreg
  begin
    @agent = Mechanize.new { |agent|
      agent.user_agent = 'Mozilla/5.0 (X11; Linux x86_64; rv:16.0) Gecko/20100101 Firefox/16.0'
      agent.verify_mode = OpenSSL::SSL::VERIFY_NONE
      FileUtils.makedirs(LogDir) if $VERBOSE or defined?(RSpec)
      agent.log = Logger.new("#{LogDir}/mechanize.log") if $VERBOSE
    }
    @agent.get_file  Start_uri # 'https://www.swissreg.ch/srclient/faces/jsp/start.jsp'
    writeResponse("#{LogDir}/session_expired.html")
    checkErrors(@agent.page.body, false)
    @agent.page.links[3].click
    writeResponse("#{LogDir}/homepage.html")
    @state = @agent.page.form["javax.faces.ViewState"]
  rescue Net::HTTPInternalServerError, Mechanize::ResponseCodeError
    puts "Net::HTTPInternalServerError oder Mechanize::ResponseCodeError gesehen.\n   #{Base_uri} hat wahrscheinlich Probleme"
    exit 3
  end
end

#parse_swissreg(timespan = @timespan, marke = @marke, nummer = @number) ⇒ Object

sollte 377 Treffer ergeben, für 01.06.2007-10.06.2007, 559271 wurde in diesem Zeitraum registriert



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

def parse_swissreg(timespan = @timespan,  # sollte 377 Treffer ergeben, für 01.06.2007-10.06.2007, 559271 wurde in diesem Zeitraum registriert
                  marke = @marke,    
                  nummer =@number) #  nummer = "559271" ergibt genau einen treffer

  init_swissreg
  data = [
    ["autoScroll", "0,0"],
    ["id_swissreg:_link_hidden_", ""],
    ["id_swissreg_SUBMIT", "1"],
    ["id_swissreg:_idcl", "id_swissreg_sub_nav_ipiNavigation_item0"],
    ["javax.faces.ViewState", @state],
  ]
  @agent.page.form['id_swissreg:_idcl'] = 'id_swissreg_sub_nav_ipiNavigation_item0'
  @agent.page.forms.first.submit
  writeResponse("#{LogDir}/trademark_simple.html")
  data = [
    ["autoScroll", "0,0"],
    ["id_swissreg:_link_hidden_", ""],
    ["id_swissreg_SUBMIT", "1"],
    ["id_swissreg:_idcl", "id_swissreg_sub_nav_ipiNavigation_item0_item3"],
    ["javax.faces.ViewState", @state],
  ]
  @agent.page.form['id_swissreg:_idcl'] = 'id_swissreg_sub_nav_ipiNavigation_item0_item3'
  @agent.page.forms.first.submit
  writeResponse("#{LogDir}/trademark_extended.html")
  
  data = [
    ["autoScroll", "0,829"],
    ["id_swissreg:_link_hidden_", ""],
    ["id_swissreg:mainContent:id_ckbTMState", "1"], # Hängige Gesuche 1
    ["id_swissreg:mainContent:id_ckbTMState", "3"], # Aktive Marken 3
    ["id_swissreg:mainContent:id_txf_tm_no", ""],# Marken Nr
    ["id_swissreg:mainContent:id_txf_app_no", ""],                       # Gesuch Nr.
    ["id_swissreg:mainContent:id_txf_tm_text", "#{marke}"],
    ["id_swissreg:mainContent:id_txf_applicant", ""],                    # Inhaber/in
    ["id_swissreg:mainContent:id_cbxCountry", @swiss_only ? 'CH' : '_ALL'],
    ["id_swissreg:mainContent:id_txf_agent", ""],                         # Vertreter/in
    ["id_swissreg:mainContent:id_txf_licensee", ""], # Lizenznehmer
    ["id_swissreg:mainContent:id_txf_nizza_class", ""], # Nizza Klassifikation Nr.
    ["id_swissreg:mainContent:id_txf_appDate", "#{timespan}"] ,
    ["id_swissreg:mainContent:id_txf_expiryDate", ""], # Ablauf Schutzfrist
    ["id_swissreg:mainContent:id_cbxTMTypeGrp", "_ALL"],  # Markenart
    ["id_swissreg:mainContent:id_cbxTMForm", "_ALL"],  # Markentyp
    ["id_swissreg:mainContent:id_cbxTMColorClaim", "_ALL"],  # Farbanspruch
    ["id_swissreg:mainContent:id_txf_pub_date", ""], # Publikationsdatum
    ["id_swissreg:mainContent:id_ckbTMPubReason", '1'],
    ["id_swissreg:mainContent:id_ckbTMPubReason", '2'],
    ["id_swissreg:mainContent:id_ckbTMPubReason", '3'],
    ["id_swissreg:mainContent:id_ckbTMPubReason", '4'],
    ["id_swissreg:mainContent:id_ckbTMPubReason", '5'],
    ["id_swissreg:mainContent:id_ckbTMPubReason", '6'],
    ["id_swissreg:mainContent:id_ckbTMPubReason", '7'],
    ["id_swissreg:mainContent:id_ckbTMPubReason", '8'],
    ["id_swissreg:mainContent:id_cbxFormatChoice", "1"],
    ["id_swissreg:mainContent:id_ckbTMChoice", "tm_lbl_tm_text"],
    ["id_swissreg:mainContent:id_ckbTMChoice", "tm_lbl_applicant"],
    ["id_swissreg:mainContent:id_ckbTMChoice", "tm_lbl_country"],
    ["id_swissreg:mainContent:id_ckbTMChoice", "tm_lbl_agent"],
    ["id_swissreg:mainContent:id_ckbTMChoice", "tm_lbl_app_date"],
    ["id_swissreg:mainContent:id_cbxHitsPerPage", HitsPerPage],   # Treffer pro Seite
    ["id_swissreg:mainContent:sub_fieldset:id_submit", "suchen"],
    ["id_swissreg_SUBMIT", "1"],
    ["id_swissreg:_idcl", ""],
    ["id_swissreg:_link_hidden_", ""],
    ["javax.faces.ViewState", @state],
  ]
  begin
    @agent.post(Sr3, data)
  rescue Timeout::Error 
    puts "Timeout!"
    retry
  end
  writeResponse("#{LogDir}/first_results.html")
  checkErrors(@agent.page.body, false)
end

#writeResponse(filename) ⇒ Object



105
106
107
108
109
110
111
112
113
# File 'lib/brand2csv.rb', line 105

def writeResponse(filename)
  if defined?(RSpec) or $VERBOSE
    ausgabe = File.open(filename, 'w+')
    ausgabe.puts @agent.page.body
    ausgabe.close
  else
    puts "Skipping writing #{filename}" if $VERBOSE
  end
end