Class: Dgs

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

Overview

require ‘pp’

Constant Summary collapse

LOGGED_IN =

text if not logged in

"Sorry, you have to be logged in to do that"
YOUR_TURN =

your turn message

"Your turn to move in the following games"
DGS_STATUS_PAGE =

DGS Status page

'http://www.dragongoserver.net/status.php/'
DGS_INDEX_PAGE =

DGS Index page

'http://www.dragongoserver.net/index.php'
DGS_WAITING_ROOM_PAGE =

DGS Waiting room page

'http://www.dragongoserver.net/waiting_room.php'
USER_AGENT_ALIAS =

User agent

'Mac Safari'
SAVE_WAIT =

if we are doing too many requests at DGS the account (YOUR ACCOUNT) will be temporarily blocked (for about 1 day) wait n seconds before each request

15

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(username = nil, password = nil) ⇒ Dgs

Returns a new instance of Dgs.



28
29
30
31
32
33
34
35
36
37
38
39
# File 'lib/dragongoserver/dragongoserver.rb', line 28

def initialize(username=nil,password=nil)
  @username = username
  @password = password
  if @username == nil or @password == nil
    @username = ENV['DGS_USERNAME']
    @password = ENV['DGS_PASSWORD']
    if @username == nil or @password == nil
      raise(RuntimeError, "username and/or password not set")
    end
  end
  @userinfo = Hash.new
end

Instance Attribute Details

#usernameObject (readonly)

Returns the value of attribute username.



26
27
28
# File 'lib/dragongoserver/dragongoserver.rb', line 26

def username
  @username
end

Instance Method Details

#add_gameObject

Create one or more games in the waiting room Default values are taken from the file ~/.dgs_default_add_game.yml if it exists (if not the DGS form is just submitted)



464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
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
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
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
580
581
# File 'lib/dragongoserver/dragongoserver.rb', line 464

def add_game
    dgs_default_add_game = File.join(ENV['HOME'],".dgs_default_add_game.yml")
  save_wait
  my_rank = get_rank
  my_rank_org = my_rank.dup

  @waiting_room = DGS_WAITING_ROOM_PAGE
  agent = WWW::Mechanize.new
  agent.user_agent_alias = USER_AGENT_ALIAS
  default_default_comment = 'added by dragongoserver ruby gem'
  #--
  #    default = {
  #      :number_of_games => 3,
  #      :size => 19,
  #      :main_time => [15, :days], # or: :main_time => [15, :days]
  #      # or: :main_time => [24, :hours]
  #      # or: :main_time => [6, :months]
  #      :japanese_byoyomi => [1, :hours, 24, :extra_periods],
  #      # :canadian_byoyomi => false
  #      # :fischer_time => false
  #
  #      :rated_game => true,
  #      :clock_runs_on_weekend => false,
  #      :require_rated_opponent => true,
  #      :relative_range => 9,
  #      :comment => default_default_comment,
  #    }
  #    open(File.join(ENV['HOME'],".dgs_default_add_game.yml"),"w") { |f|
  #      YAML.dump(default,f)
  #    }
  begin
    default = open(File.join(ENV['HOME'],".dgs_default_add_game.yml")) { |f|
      YAML.load(f)
    }
  rescue Errno::ENOENT
    # Datei nicht vorhanden.
    # Auch nicht schlimm, dann nehmen wir die Default-Werte von DGS
  end
  #--
  page = agent.get(@waiting_room)
  if page.body.include?(LOGGED_IN)
    # dann erst zum Einloggen gehen
    page = (agent)
    page = agent.get(DGS_WAITING_ROOM_PAGE)
  end
  form = page.form("addgame")
  if default
    # wenn default Konfiguration nicht vorhanden,
    # dann Formular in DGS einfach so lassen und bestätigen
    # => 1 Spiel, 3 Monate, ...
    if default[:number_of_games]
      form.fields.find {|f| f.name == 'nrGames'}.value = default[:number_of_games]
    end
    if default[:size]
      form.fields.find {|f| f.name == 'size'}.value = default[:size]
    end
    if default[:main_time]
      form.fields.find {|f| f.name == 'timevalue'}.value = default[:main_time][0]
      form.fields.find {|f| f.name == 'timeunit'}.value = default[:main_time][1].to_s
    end
    if default[:japanese_byoyomi]
      # form.radiobuttons_with(:name => 'box')[1].check

      form.radiobuttons_with(:name => 'byoyomitype')[0].check #e = 'JAP'
      form.fields.find {|f| f.name == 'byotimevalue_jap'}.value =
        default[:japanese_byoyomi][0]
      form.fields.find {|f| f.name == 'timeunit_jap'}.value =
        default[:japanese_byoyomi][1].to_s
      form.fields.find {|f| f.name == 'byoperiods_jap'}.value =
        default[:japanese_byoyomi][2]
      #        :japanese_byoyomi => [1, :hours, 24, :extra_periods],
  
    end


    if default[:comment]
      form.fields.find {|f| f.name == 'comment'}.value = default[:comment]
    end
    if default[:require_rated_opponent]
      form.checkbox_with(:name => 'must_be_rated').check
    else
      form.checkbox_with(:name => 'must_be_rated').uncheck
    end
    if default[:clock_runs_on_weekend]
      form.checkbox_with(:name => 'weekendclock').check
    else
      form.checkbox_with(:name => 'weekendclock').uncheck
    end
    if default[:rated_game]
      form.checkbox_with(:name => 'rated').check
    else
      form.checkbox_with(:name => 'rated').uncheck
    end
    if default[:relative_range]
      r = default[:relative_range]
      begin
        rating1 = my_rank - r
      rescue IndexError
        rating1 = GoRank.new 30, :kyu
      end
      my_rank = my_rank_org
      begin
        rating2 = my_rank + r
      rescue IndexError
        rating2 = GoRank.new 6, :dan # go-rank max 6 dan, dgs max 9 dan TODO:
      end
      form.fields.find {|f| f.name == 'rating1'}.value = rating1.to_s
      form.fields.find {|f| f.name == 'rating2'}.value = rating2.to_s
    end
  end # if default
  unless default
    form.fields.find {|f| f.name == 'comment'}.value = default_default_comment
  end
  page = agent.submit(form, form.buttons.first)
  # puts "neue Einladung erstellt" if page.body.include? 'Game added!'

  page.body.include? 'Game added!'
end

#finished_gamesObject



128
129
130
131
132
133
134
135
136
137
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
# File 'lib/dragongoserver/dragongoserver.rb', line 128

def finished_games
  save_wait
  games = []
  #@home = 'http://www.dragongoserver.net/show_games.php?uid=10737' #TODO:
  @home = DGS_STATUS_PAGE
  agent = WWW::Mechanize.new
  agent.user_agent_alias = USER_AGENT_ALIAS

  page = agent.get(@home)
  if page.body.include?(LOGGED_IN)
    page = (agent)
  end

  #if !page.body.include?(YOUR_TURN)
  #  raise "PageError: #{DGS_STATUS_PAGE} not found"
  #end

  #    page = agent.click page.links.text('Show finished games')
  page = agent.click page.link_with(:text => 'Show finished games')
  page.body.each_line {|line|
    if line =~ /gid=([0-9]+)"/
      games << {:id => $1.to_i, :finished_at => DateTime.now}
    end
  }
  page_no = 1
  
  #    p page.links.find { |l| l.title =~ /next page/ }
  #p page.links

  # naechste Seite
  #    while page.link_with(:text => '+')
  while page.link_with(:title => 'next page [&amp;&gt;]')
    page_no += 1
    puts "at page_no = #{page_no}"
    #      page = agent.click page.link_with(:text => '+')
    page = agent.click page.link_with(:title => 'next page [&amp;&gt;]') 
    # nochmal alle Spiele auf Folgeseite durchgehen
    page.body.each {|line|
      if line =~ /gid=([0-9]+)"/
        games << {:id => $1.to_i, :finished_at => DateTime.now}
      end
    }
  end
  
  # aus Bequemlichkeitsgruenden (gid= kommt mehrfach vor): uniq    
  games.uniq
end

#finished_games_for_user(user_id) ⇒ Object

www.dragongoserver.net/show_games.php?uid=31098&finished=1 the first page of finished games for this user



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

def finished_games_for_user(user_id)
  save_wait
  games = []
  @home = "http://www.dragongoserver.net/show_games.php?uid=#{user_id}&finished=1" #TODO:
  #p @home
  #@home = DGS_STATUS_PAGE
  agent = WWW::Mechanize.new
  agent.user_agent_alias = USER_AGENT_ALIAS

  page = agent.get(@home)
  if page.body.include?(LOGGED_IN)
    page = (agent)
    page = agent.click page.link_with(:text => 'Users')
    if !page.body.include?("Active users")
      raise "Active users not diplaying"
    end
    form = page.forms.first
    form.sf1 = user_id.to_s
    form.checkbox_with(:name => "active").uncheck # auch inaktive User beruecksichtigen
    page = agent.submit(form)
    #      page = agent.click page.links.text("#{user_id}")
    page = agent.click page.link_with(:text => "#{user_id}")
    #      page = agent.click page.links.text("Show finished games")
    # page = agent.click page.link_with(:text => "Show finished games")
    page = agent.click page.link_with(:text => "Finished games")
  end
  if !page.body.include?("Finished games for")
    #p page.body
    raise "Finished games for not on page"
  end
  #page = agent.click page.links.text('Show finished games')
  one_game = {}
  page.body.each_line {|line|
    #  p line
    #p one_game
    if line =~ /gid=([0-9]+)"/
      one_game[:id] = $1.to_i
    end
    # <td align=center><img src="17/w.gif" alt="w"></td>
    if line =~ /[wb].gif/ and
        one_game[:id]
      #p $1
      color = line.split('.gif')[0][-1,1]
      #p line.split('.gif')[0] #[-1,1]
      #p color
      if color == 'w'
        one_game[:player_color] = :white
      else
        one_game[:player_color] = :black
      end
    end
    # W+Time
    if line =~ /[WB]\+/ and
        one_game[:id]
      color,reason = line.split('+')
      if color[-1,1] == 'W'
        one_game[:winner] = :white
      else
        one_game[:winner] = :black
      end
    
      one_game[:reason] = reason[0,reason.index('<')]
    end
    #<td>2008-04-19 10:29</td>
    if line =~ /(\d+)-(\d+)-(\d+)/ and
        one_game[:id]
      d = Date.new($1.to_i,$2.to_i,$3.to_i)
      one_game[:finished_at] = d
      games << one_game
      one_game = {}
    end
  }
  # aus Bequemlichkeitsgruenden (gid= kommt mehrfach vor): uniq    
  #p games
  games  # .uniq
end

#finished_games_idsObject

same as finished_games but only the ids of the games



177
178
179
180
181
182
183
# File 'lib/dragongoserver/dragongoserver.rb', line 177

def finished_games_ids
  result = []
  finished_games.each { |e| 
    result << e[:id]
  }
  result
end

#gameinfo(game_id) ⇒ Object



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
416
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
# File 'lib/dragongoserver/dragongoserver.rb', line 388

def gameinfo(game_id)
  
  demo='
<table class=GameInfos>
<tr id="blackInfo">
<td class=Color><img class=InTextStone src="17/b.gif" alt="Black"></td>
<td class=Name><A href="userinfo.php?uid=41360" class=User>Lukas Zach (lukaszach)</A></td>
<td class=Ratings><span class=StartRating><a class=Rating href="ratinggraph.php?uid=41360">30&nbsp;kyu&nbsp;(+11%)</a></span><span class=Separator>-</span><span class=EndRating><a class=Rating href="ratinggraph.php?uid=41360">30&nbsp;kyu&nbsp;(0%)</a></span></td>

<td class=Prisoners>Prisoners: 18</td>
</tr>
<tr id="blackTime">
<td colspan="4">
Time remaining: 6&nbsp;days&nbsp;and&nbsp;1&nbsp;hour</td>
</tr>
<tr id="whiteInfo">
<td class=Color><img class=InTextStone src="17/w.gif" alt="White"></td>
<td class=Name><A href="userinfo.php?uid=10737" class=User>Thomas Preymesser (thopre)</A></td>
<td class=Ratings><span class=StartRating><a class=Rating href="ratinggraph.php?uid=10737">30&nbsp;kyu&nbsp;(0%)</a></span><span class=Separator>-</span><span class=EndRating><a class=Rating href="ratinggraph.php?uid=10737">29&nbsp;kyu&nbsp;(-11%)</a></span></td>

<td class=Prisoners>Prisoners: 2</td>
</tr>
<tr id="whiteTime">
<td colspan="4">
Time remaining: 9&nbsp;days&nbsp;and&nbsp;6&nbsp;hours</td>
</tr>
<tr id="gameRules">
<td colspan="4">Rules: Komi: 6.5,&nbsp;&nbsp;&nbsp;Handicap: 0,&nbsp;&nbsp;&nbsp;Rated game: Yes</td>

</tr>
<tr id="gameTime">
<td colspan="4">Time limit: Japanese byoyomi: 15&nbsp;days + 1&nbsp;day per move and 3 extra periods</td>
</tr>
</table>
  '
  save_wait
  agent = WWW::Mechanize.new
  agent.user_agent_alias = USER_AGENT_ALIAS
  p = "http://www.dragongoserver.net/game.php?gid=#{game_id}"
  page = agent.get(p)
  if page.body.include?(LOGGED_IN)
    page = (agent)
    page = agent.get(p)
  end
  #TODO: 
  if page.body.include?("Sorry, I can't find that game")
    raise 'no game with this id'
  end
  result = Hash.new
  result[:white] = {}
  result[:black] = {}
  
  doc = page
  #elements =   doc.search("//table[@class='GameInfos']").search('tr[@id='BlackInfo')
  elements =   doc.search("//table[@class='GameInfos']")
  blackinfo = (elements/"tr[@id='blackInfo']")
  whiteinfo = (elements/"tr[@id='whiteInfo']")
  whiteinfo_name = (whiteinfo/"td[@class='Name']/a").inner_text #2008-12-28 inner_html
  blackinfo_name = (blackinfo/"td[@class='Name']/a").inner_text #2008-12-28 inner_html
  result[:black][:name] = blackinfo_name
  result[:white][:name] = whiteinfo_name
  
  result
end

#gamesObject

all games of the own user finished games + running games TODO: should return an array of game instances



456
457
458
# File 'lib/dragongoserver/dragongoserver.rb', line 456

def games
  [4,5,6]
end

#get_rankObject Also known as: rank

your rank as a GoRank object



265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
# File 'lib/dragongoserver/dragongoserver.rb', line 265

def get_rank
  save_wait
  @home = DGS_STATUS_PAGE
  agent = WWW::Mechanize.new
  agent.user_agent_alias = USER_AGENT_ALIAS

  page = agent.get(@home)
  if page.body.include?(LOGGED_IN)
    page = (agent)
  end

  if !page.body.include?(YOUR_TURN)
    raise "PageError: #{DGS_STATUS_PAGE} not found"
  end
  a = show_regexp(page.body, /(\d+)&nbsp;(kyu|dan)/)
  num = a[0].to_i
  what = a[1].to_sym
  myRank = GoRank.new num, what
  myRank
end

#running_gamesObject



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
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
# File 'lib/dragongoserver/dragongoserver.rb', line 78

def running_games
  save_wait
  games = []
  #@home = 'http://www.dragongoserver.net/show_games.php?uid=10737' #TODO:
  @home = DGS_STATUS_PAGE
  agent = WWW::Mechanize.new
  agent.user_agent_alias = USER_AGENT_ALIAS

  page = agent.get(@home)
  if page.body.include?(LOGGED_IN)
    page = (agent)
  end

  if !page.body.include?(YOUR_TURN)
    raise "PageError: #{DGS_STATUS_PAGE} not found"
  end

  # page = agent.click page.links.text('Show running games')
  page = agent.click page.link_with(:text => 'Show running games')
  
  #    *_with(:text => "Show running games")
  page.body.each_line {|line|
    if line =~ /gid=([0-9]+)"/
      games << $1.to_i
    end
  }
  
  # BEGIN naechste Seite(n)
  #p page.links    
  #    page = agent.click page.link_with(:text => '=&gt;')
  while true
    begin
      page = agent.click page.link_with(:text => '=>')
    rescue
      break # keine weitere Seite vorhanden
    end
      
    page.body.each {|line|
      if line =~ /gid=([0-9]+)"/
        games << $1.to_i
      end
    }
  end
  # END  naechste Seite(n)
  # aus Bequemlichkeitsgruenden (gid= kommt mehrfach vor): uniq    
  games.uniq
end

#useridObject

your id at DGS



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

def userid
  save_wait
  @home = DGS_STATUS_PAGE
  agent = WWW::Mechanize.new
  agent.user_agent_alias = USER_AGENT_ALIAS

  page = agent.get(@home)
  if page.body.include?(LOGGED_IN)
    page = (agent)
  end

  if !page.body.include?(YOUR_TURN)
    raise "PageError: #{DGS_STATUS_PAGE} not found"
  end
  # Link 'http://www.dragongoserver.net/ratinggraph.php?uid=10737'
  # enthaelt die Userid
  #p page.links
  page.links.each { |link|
    if link.href =~ /ratinggraph/
      a = show_regexp(link.href, /^ratinggraph.php\?uid=(\d+)$/)
      @userid = a[0].to_i
      break
    end
  }
  @userid
end

#userinfo(user_id = nil) ⇒ Object

informations about a user at DGS returns a hash with attributes



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
373
374
375
376
377
378
379
380
381
382
383
384
# File 'lib/dragongoserver/dragongoserver.rb', line 319

def userinfo(user_id = nil)
  save_wait
  ## http://www.dragongoserver.net/userinfo.php?uid=10737
  agent = WWW::Mechanize.new
  agent.user_agent_alias = USER_AGENT_ALIAS
  user_id = 10737 unless user_id
  page = agent.get("http://www.dragongoserver.net/userinfo.php?uid=#{user_id}")
  if page.body.include?(LOGGED_IN)
    page = (agent)
    page = agent.get("http://www.dragongoserver.net/userinfo.php?uid=#{user_id}")
  end
  if page.body.include?("Sorry, I couldn't find this user.")
    raise 'no user with this id'
  end
  @userinfo[:city] = nil
  @userinfo[:country] = nil
    
  result = Hash.new    
  page.body.each_line {|line|
    #<td class="Rubric">Name</td><td>Thomas Preymesser</td>
    if line =~ /td class="Rubric"/
      #p line
      a = show_regexp(line, 
        /td class="Rubric">(.*)<\/td><td>(.*)<\/td>/)
      #          /td class="Rubric">(.+)<\/td><td>.+<\/td>"/)
      #p a
      if a[0]=="Name"
        result[:name] = a[1]
      elsif a[0]=="Userid"
        result[:userid] = a[1]
      elsif a[0]=="Country"
        b = show_regexp(a[1], /alt="(.*)" /)
        result[:country] = b[0]
      elsif a[0]=="City"
        result[:city] = a[1]
      elsif a[0]=="Rating"
        #
        
        if  a[1] =~ /(\d+)&nbsp;(kyu|dan)/
          b = show_regexp(a[1], /(\d+)&nbsp;(kyu|dan)/)
          num = b[0].to_i
          what = b[1].to_sym
          begin
            result[:rating] = GoRank.new num, what
          rescue
            raise "illegal rank: #{a[1]}\n#{num}/#{what}"
          end
        else
          result[:rating] = nil
        end
        ##
        #result[:rating] = a[1]
      elsif a[0]=="Last access"
        result[:lastaccess] = DateTime.parse(a[1].gsub(/&nbsp;/,' '))
      elsif a[0]=="Last move"
        begin
          result[:lastmove] = DateTime.parse(a[1].gsub(/&nbsp;/,' '))
        rescue
          puts "invalid " + a[1].to_s
        end
      end
    end      
  }
  #    @userinfo[:name]='Hugo Boss'
  return result
end

#waiting_gamesObject

Array of waiting games



42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
# File 'lib/dragongoserver/dragongoserver.rb', line 42

def waiting_games
  save_wait
  games = []
  @home = DGS_STATUS_PAGE
  agent = WWW::Mechanize.new
  agent.user_agent_alias = USER_AGENT_ALIAS

  page = agent.get(@home)
  if page.body.include?(LOGGED_IN)
    # dann erst zum Einloggen gehen
    page = (agent)
  end

  # muss kommen, sonst sind wir noch nicht auf der richtigen Seite
  if !page.body.include?(YOUR_TURN)
    raise "PageError: #{DGS_STATUS_PAGE} not found"
  end
  game_id=0
  user_id=0
  page.body.each_line {|line|
    if line =~ /gid=([0-9]+)"/
      game_id = $1.to_i
      # ??? games << {:game => game_id, :user => userid}
      #  games << $1.to_i
      games << game_id
    end
    if line =~ /uid=([0-9]+)"/ and game_id > 0
      user_id = $1.to_i
    end
  }
  # aus Bequemlichkeitsgruenden (gid= kommt mehrfach vor): uniq    
  games.uniq
end