summaryrefslogtreecommitdiff
path: root/sqwarea/__init__.py
blob: 98c56ca57c595db4bfd5e33cbe1a930f11cf2bbf (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
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
125
126
127
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
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
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
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
373
374
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
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
452
453
454
455
456
457
458
459
460
461
462
463
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
import httplib, urllib, urllib2, urlparse
import cookielib
httplib.HTTPConnection.debuglevel = 1
import os
import sys
import hashlib
import logging
import time, datetime
import math

try:
    if sys.version_info >= (2, 6):
        import json as simplejson
    else:
        import simplejson
    from BeautifulSoup import BeautifulSoup
except ImportError:
    print "HTML/json stuff not available, most features are now broken"

#logging.basicConfig (level = logging.DEBUG)

DOMAIN = "sqwarea.cloudapp.net"
BASEPATH = ""

COOKIEFILE = "cookies-%s.lwp"

def md5 (data):
    return hashlib.md5 (data).hexdigest ()

def redbg (data):
    return "\033[41m%s\033[0m" % data

def gray (data):
    return "\033[1;30m%s\033[0m" % data

def blue (data):
    return "\033[1;34m%s\033[0m" % data

def cyan (data):
    return "\033[0;36m%s\033[0m" % data

def green (data):
    return "\033[1;32m%s\033[0m" % data

def purple (data):
    return "\033[0;35m%s\033[0m" % data

def red (data):
    return "\033[1;31m%s\033[0m" % data

def bold (data):
    return "\033[1;37m%s\033[0m" % data

def timedelta_to_mins (d):
    return d.seconds / 60 + d.days * 24 * 60

class Client (object):

  _openId = None
  _cookiejar = None
  _cookiejar_path = None
  _opener = None
  sessionId = None

  def __init__ (self, openid):
    self._openId = openid
    # Setup cookie jar
    self._cookiejar_path = COOKIEFILE % md5 (self._openId)
    self._cookiejar = cookielib.LWPCookieJar ()
    if os.path.isfile (self._cookiejar_path):
      self._cookiejar.load (self._cookiejar_path)
    cookie_processor = urllib2.HTTPCookieProcessor (self._cookiejar)
    cookie_opener = urllib2.build_opener (cookie_processor)
    self._opener = cookie_opener

  def request (self, path, data):
    path = "http://" + DOMAIN + os.path.join (BASEPATH, path)
    if self.sessionId:
      data["sessionId"] = self.sessionId
    data = urllib.urlencode (data)
    conn = self._opener.open (path, data)
    return conn

  def jsrequest (self, path, data):
    return simplejson.load (self.request (path, data))

  def save (self):
    self._cookiejar.save (self._cookiejar_path)

SPECIAL_HOSTS = {
    "openid.ulminfo.fr": ("index.php", "name", "digest", {"pass": ""})
}

def ulminfo_digester (login, password, extra_fields):
    nonce = extra_fields["nonce"]
    return md5 (nonce + ":" + md5 (login + ":" + password))

SPECIAL_DIGESTERS = {
    "openid.ulminfo.fr": ulminfo_digester,
}

def find_auth_form (reply):
  """
  Finds a potential login form ;
  Returns (formpath, loginfield, passwordfield, extrafields)
  """
  html = reply.read ()
  soup = BeautifulSoup (html)
  host = urlparse.urlparse (reply.url).netloc
  for form in soup.findAll ("form"):
    hidden_fields = form.findAll ("input", attrs = {"type": "hidden"})
    hidden_fields = dict ([(field["name"], field["value"])
                           for field in hidden_fields])
    if host in SPECIAL_HOSTS:
      entry = SPECIAL_HOSTS[host]
      hidden_fields.update (entry[3])
      return entry[:3] + (hidden_fields,)
    login_fields = form.findAll ("input", attrs = {"type": "text"})
    password_fields = form.findAll ("input", attrs = {"type": "password"})
    submit_fields = form.findAll ("input", attrs = {"type": "submit"})
    if password_fields:
      if submit_fields \
       and submit_fields[0].has_key ("name") \
       and submit_fields[0].has_key ("value"):
        submit_field = submit_fields[0]["name"], submit_fields[0]["value"]
        hidden_fields.update (dict([submit_field]))
      else:
        submit_field = None
      if login_fields:
        return form["action"], \
               login_fields[0]["name"], \
               password_fields[0]["name"], \
               hidden_fields
      else:
        return form["action"], \
               None, \
               password_fields[0]["name"], \
               hidden_fields
  raise RuntimeError, "Couldn't find login form"

def parseSessionId (data):
  for line in data.split ("\n"):
    line = line.strip ()
    if line.startswith ("sessionId"):
      return line.split (":")[1].strip ()

def try_continue_form (reply, client):
  html = reply.read ()
  soup = BeautifulSoup (html)
  for form in soup.findAll ("form"):
    fields = form.findAll ("input")
    fields = dict ([(field["name"], field["value"])
                    for field in fields
                    if field.has_key ("name") and field.has_key ("value")])
    submit_fields = form.findAll ("input", attrs = {"type": "submit"})
    if submit_fields:
      fields.update ({submit_fields[0]["name"]: submit_fields[0]["value"]})
    data = urllib.urlencode (fields)
    headers = {"Referer": reply.url}
    form_path = form["action"]
    if not form_path.startswith ("http"):
      form_path = urlparse.urljoin (reply.url, form_path)
    req = urllib2.Request (form_path, data, headers)
    return client._opener.open (req)
  # No valid form in there, no redirection either, hm.. let's try the dumb way
  for anchor in soup.findAll ("a"):
    href = anchor["href"]
    if urlparse.urlparse (href).netloc == DOMAIN:
      headers = {"Referer": reply.url}
      req = urllib2.Request (href, None, headers)
      return client._opener.open (req)
  logging.log (logging.CRITICAL, "Couldn't find a form or link to continue")

class Point (object):

  x = None
  y = None
  p = None # p = (x, y)

  def __init__ (self, x, y):
    self.x = int (x)
    self.y = int (y)
    self.p = (self.x, self.y)

  def __add__ (self, other):
    assert isinstance (other, Point)
    return Point (self.x + other.x,
                  self.y + other.y)
    
  def __sub__ (self, other):
    assert isinstance (other, Point)
    return Point (self.x - other.x,
                  self.y - other.y)

  def __neg__ (self):
    return Point (-self.x, -self.y)

  def __eq__ (self, other):
    assert isinstance (other, Point)
    return self.x == other.x and self.y == other.y

  @classmethod
  def parse (cls, data):
    return cls (*data.split (","))

  def __str__ (self):
    return "%d,%d" % (self.x, self.y)

class Rectangle (object):

  x = None
  y = None
  width = None
  height = None

  def __init__ (self, x, y, width, height):
    self.x = int (x)
    self.y = int (y)
    self.width = int (width)
    self.height = int (height)

  def __add__ (self, other):
    assert isinstance (other, Rectangle)
    self_x2, self_y2 = self.x + self.width, self.y + self.height
    other_x2, other_y2 = other.x + other.width, other.y + other.height
    new_x = min (self.x, other.x)
    new_y = min (self.y, other.y)
    new_x2 = max (self_x2, other_x2)
    new_y2 = max (self_y2, other_y2)
    new_width = new_x2 - new_x
    new_height = new_y2 - new_y
    return Rectangle (new_x, new_y, new_width, new_height)

  def inter (self, other):
    assert isinstance (other, Rectangle)
    self_x2, self_y2 = self.x + self.width, self.y + self.height
    other_x2, other_y2 = other.x + other.width, other.y + other.height
    new_x = max (self.x, other.x)
    new_y = max (self.y, other.y)
    new_x2 = min (self_x2, other_x2)
    new_y2 = min (self_y2, other_y2)
    new_width = new_x2 - new_x
    new_height = new_y2 - new_y
    return Rectangle (new_x, new_y, new_width, new_height)

  @classmethod
  def parse (cls, data):
    return cls (*data.split (","))

  def __str__ (self):
    return "%d,%d,%d,%d" % (self.x, self.y, self.width, self.height)

class Date (object):

  date = None

  def __init__ (self, date):
    self.date = date

  @classmethod
  def parse (cls, data):
    stamp = int (data.split ("(")[1].split("+")[0])
    return datetime.datetime.fromtimestamp (stamp / 1000)

  def __str__ (self):
    return "/Date(%s+0000)/"

class King (object):

  id = None
  pos = None
  lastMove = None

  def __init__ (self, id, pos, lastMove):
    self.id = id
    self.pos = pos
    self.lastMove = lastMove

  @classmethod
  def parse (cls, data):
    return cls (data["Id"],
                Point.parse (data["Position"]),
                Date.parse (data["LastKingMoveDate"]))

  def __str__ (self):
    return "King %d at %s (last moved on %s)" \
              % (self.id, self.pos, self.lastMove)

class Cell (object):

  id = None
  nickname = None
  troops = None
  hasKing = None

  def __init__ (self, id, nickname, troops, hasKing):
    self.id = id
    self.nickname = nickname
    self.troops = troops
    self.hasKing = hasKing

class Map (object):

  _data = None
  _extents = None

  _api = None
  _ourId = None

  def __init__ (self, api, ourId):
    self._api = api
    self._ourId = ourId
    self._data = {}

  def update (self, squares):
    named_squares = 0
    for square in squares:
      square = [s.strip () for s in square.split (",")]
      x, y, hasKing, troops, ownerId, nick = square
      x, y = int (x), int (y)
      troops = int (troops) if troops else None
      ownerId = int (ownerId) if ownerId else None
      if ownerId:
        named_squares += 1
      hasKing = hasKing == "1"
      self._data[x, y] = Cell (ownerId, nick, troops, hasKing)
      if not self._extents:
        self._extents = Rectangle (x, y, 1, 1)
      else:
        self._extents += Rectangle (x, y, 1, 1)
    return named_squares

  def __contains__ (self, key):
    return key in self._data

  def __getitem__ (self, key):
    if key in self._data:
      return self._data[key]
    else:
      raise KeyError

  def __str__ (self):
    ret = ""
    for dy in range (self._extents.height):
      for dx in range (self._extents.width):
        x, y = self._extents.x + dx, self._extents.y + dy
        if (x, y) in  self._data:
          cell = self._data[x, y]
          if (x, y) in self._api.ongoingAttacks \
             or (x, y) in self._api.incomingAttacks:
            w = redbg
          else:
            w = lambda x:x
          if cell.id == self._ourId: # Us
            if cell.hasKing:
              ret += w (blue (cell.nickname[0]))
            else:
              ret += w (green (cell.nickname[0]))
          elif cell.id: # Ennemy
            if cell.hasKing:
              ret += w (purple (cell.nickname[0]))
            else:
              ret += w (red (cell.nickname[0]))
          else: # Neutral
            ret += w (bold ("-"))
        else:
          ret += gray ("?")
      ret += "\n"
    return ret.strip ()
        
class Attack (object):

  dest = None
  troops = None
  arrival = None
  sender = None

  def __init__ (self, dest, troops, arrival, sender):
    self.dest = dest
    self.troops = troops
    self.arrival = arrival
    self.sender = sender

  @classmethod
  def parse (cls, data):
    return cls (Point.parse (data["Destination"]),
                data["TroopsNumber"],
                Date.parse (data["ArrivalDate"]),
                data["SenderName"])

class OngoingAttack (Attack):

  def __str__ (self):
    return u"Ongoing Attack to %s with %d troops, arriving at %s" \
              % (self.dest, self.troops, self.arrival)

class IncomingAttack (Attack):

  def __str__ (self):
    return u"Incoming Attack to %s from %s arriving at %s" \
              % (self.dest, self.sender, self.arrival)

KING_DIRECTIONS = ["EAST", "WEST", "NORTH", "SOUTH"]

class API (object):

  _client = None
  academyTroops = None
  king = None
  viewport = None
  map = None
  ongoingAttacks = None
  incomingAttacks = None

  def  __init__ (self, openid, login = None, password = None, sessionId = None):
    self.ongoingAttacks = {}
    self.incomingAttacks = {}
    self._client = Client (openid)
    if sessionId:
      logging.log (logging.DEBUG, "sessionId provided, skipping login")
      self._client.sessionId = sessionId
      return
    reply = self._client.request ("/Game", {})
    if reply.url.endswith ("/Game"):
      self._logged_in (openid, reply)
      return
    logging.log (logging.INFO, "Logging in as %s", openid)
    reply = self._client.request ("/Account/LogOn", {"openId": openid,
                                                     "rememberMe": "true"})
    if reply.url.endswith ("/Game"):
      logging.log (logging.DEBUG, "Logged in after initial LogOn")
      self._logged_in (openid, reply)
      return
    if not login or not password:
      raise RuntimeError, "Not logged in and too few login data to proceed"
    reply_host = urlparse.urlparse (reply.url).netloc
    form_path, login_field, pwd_field, extra_fields = find_auth_form (reply)
    login_data = extra_fields
    if reply_host in SPECIAL_DIGESTERS:
      password = SPECIAL_DIGESTERS[reply_host] (login, password, extra_fields)
    if login_field: 
      login_data.update ({login_field: login})
    login_data.update ({pwd_field: password})
    login_data = urllib.urlencode (login_data)
    login_headers = {"Referer": reply.url}
    if not form_path.startswith ("http"):
      form_path = urlparse.urljoin (reply.url, form_path)
    login_req = urllib2.Request (form_path, login_data, login_headers)
    login_conn = self._client._opener.open (login_req)
    conn = login_conn
    while reply_host in conn.url: # Probably a continue form, let's try !
      logging.log (logging.DEBUG, "Still at openid provider")
      conn = try_continue_form (conn, self._client)
    if conn.url.endswith ("/Account/Register"):
      raise RuntimeError, "Please register with %s first" % openid
    elif conn.url.endswith ("/Game"):
      self._logged_in (openid, conn)
    else:
      logging.log (logging.INFO, "Ended at %s" % conn.url)
      raise RuntimeError, "Couldn't log in as %s" % openid

  def _logged_in (self, openid, conn):
    logging.log (logging.INFO, "Logged in as %s", openid)
    self._client.save ()
    self._client.sessionId = parseSessionId (conn.read ())
    logging.log (logging.DEBUG, "sessionId = %s", self._client.sessionId)
    self.sync ()

  def _handleSync (self, reply):
    self.academyTroops = reply["King"]["AcademyTroops"]
    self.king = King.parse (reply["King"])
    rect = Rectangle.parse (reply["King"]["SquaresRectangle"])
    if not self.viewport:
      self.viewport = rect
    else:
      self.viewport += rect
    if "OngoingAttacks" in reply:
      attacks = [OngoingAttack.parse (attack)
                 for attack in reply["OngoingAttacks"]]
      self.ongoingAttacks = dict ([(attack.dest.p, attack)
                                   for attack in attacks])
    if "IncomingAttacks" in reply:
      attacks = [IncomingAttack.parse (attack)
                 for attack in reply["IncomingAttacks"]]
      self.incomingAttacks =  dict ([(attack.dest.p, attack)
                                     for attack in attacks])

  def _handleSyncMap (self, reply):
    if not self.map:
      self.map = Map (self, self.king.id)
    return self.map.update (reply["Squares"])

  def distTo (self, dest):
    assert isinstance (dest, Point)
    return round (math.sqrt ((dest.x - self.king.pos.x) ** 2 \
                           + (dest.y - self.king.pos.y) ** 2), 3)

  def timeTo (self, dest):
    assert isinstance (dest, Point)
    return datetime.timedelta (seconds = self.distTo (dest) * 600)

  def sendTroops (self, dest, amount, print_success = False):
    logging.log (logging.DEBUG, "sendTroops (%s, %d)", dest, amount)
    if amount <= 0:
      raise ValueError, "amount must be > 0"
    x, y = dest.x, dest.y
    reply = self._client.jsrequest ("/Game/SendTroops",
                                    {"x": x, "y": y, "troops": amount})
    self._handleSync (reply)
    if not reply["Success"]:
      if print_success:
        print red ("ERROR") + " : Couldn't send troops"
      return False
    else:
      if print_success:
        print green ("SUCCESS") + " : %d troops successfully sent to %s" \
                                      % (amount, dest)
      return True
  
  def moveKing (self, direction, print_success = False):
    logging.log (logging.DEBUG, "moveKing (%s)", direction)
    if direction not in KING_DIRECTIONS:
      raise ValueError, "direction must be in %s" % KING_DIRECTIONS
    reply = self._client.jsrequest ("/Game/MoveKing",
                                    {"direction": direction})
    self._handleSync (reply)
    self._handleSyncMap (reply)
    if not reply["Success"]:
      if print_success:
        print red ("ERROR") + " : Couldn't move king"
      return False
    else:
      if print_success:
        print green ("SUCCESS") + " : king successfully moved to " + direction
      return True

  def canMoveKing (self):
    delta = datetime.datetime.now () - self.king.lastMove
    return delta > datetime.timedelta (seconds = 3600 * 12)

  def sync (self):
    logging.log (logging.DEBUG, "sync ()")
    reply = self._client.jsrequest ("/Game/Synchronize", {})
    self._handleSync (reply)

  def _syncMapRequest (self, viewport):
    return self._client.jsrequest ("/Game/SynchronizeMap",
                                   {"rectangles": viewport})

  def syncMap (self):
    logging.log (logging.DEBUG, "syncMap ()")
    reply = self._syncMapRequest (self.viewport)
    return self._handleSyncMap (reply)

  def view (self, rectangle):
    assert isinstance (rectangle, Rectangle)
    self.viewport += rectangle
    self.syncMap ()

  def clip (self, rectangle):
    assert isinstance (rectangle, Rectangle)
    self.viewport = self.viewport.inter (rectangle)
    self.syncMap ()