| 1 |
""" |
| 2 |
Created by: Joris Bontje <[email protected]> |
| 3 |
|
| 4 |
This module stores bank account information. |
| 5 |
""" |
| 6 |
|
| 7 |
import os.path |
| 8 |
import shelve |
| 9 |
|
| 10 |
import Crossfire |
| 11 |
|
| 12 |
class CFBank: |
| 13 |
def __init__(self, bankfile): |
| 14 |
self.bankdb_file = os.path.join(Crossfire.LocalDirectory(), bankfile) |
| 15 |
self.bankdb = shelve.open(self.bankdb_file) |
| 16 |
|
| 17 |
def __enter__(self): |
| 18 |
return self |
| 19 |
|
| 20 |
def __exit__(self, exc_type, exc_value, traceback): |
| 21 |
self.close() |
| 22 |
|
| 23 |
def deposit(self, user, amount): |
| 24 |
if not user in self.bankdb: |
| 25 |
self.bankdb[user] = amount |
| 26 |
else: |
| 27 |
balance = self.bankdb[user] |
| 28 |
self.bankdb[user] = balance + amount |
| 29 |
|
| 30 |
def withdraw(self, user, amount): |
| 31 |
if user in self.bankdb: |
| 32 |
balance = self.getbalance(user) |
| 33 |
if balance >= amount: |
| 34 |
self.bankdb[user] = balance - amount |
| 35 |
return 1 |
| 36 |
return 0 |
| 37 |
|
| 38 |
def getbalance(self, user): |
| 39 |
self._convert(user) |
| 40 |
if user in self.bankdb: |
| 41 |
return self.bankdb[user] |
| 42 |
else: |
| 43 |
return 0 |
| 44 |
|
| 45 |
def remove_account(self, user): |
| 46 |
if user in self.bankdb: |
| 47 |
del self.bankdb[user] |
| 48 |
Crossfire.Log(Crossfire.LogDebug, |
| 49 |
"%s's bank account removed." % user) |
| 50 |
return 1 |
| 51 |
else: |
| 52 |
return 0 |
| 53 |
|
| 54 |
def close(self): |
| 55 |
self.bankdb.close() |
| 56 |
|
| 57 |
def _convert(self, name): |
| 58 |
"""Move a player's balance from the player file to the bank.""" |
| 59 |
player = Crossfire.FindPlayer(name) |
| 60 |
if player is None: |
| 61 |
return 0 |
| 62 |
old_balance = _balance_legacy(player) |
| 63 |
if old_balance > 0: |
| 64 |
Crossfire.Log(Crossfire.LogInfo, |
| 65 |
"Converting bank account for %s with %d silver" \ |
| 66 |
% (name, old_balance)) |
| 67 |
self.deposit(name, old_balance) |
| 68 |
player.WriteKey("balance", "moved-to-bank-file", 1) |
| 69 |
|
| 70 |
def open(): |
| 71 |
return CFBank('ImperialBank_DB') |
| 72 |
|
| 73 |
def _balance_legacy(player): |
| 74 |
"""Return the balance of the given player's bank account.""" |
| 75 |
try: |
| 76 |
balance_str = player.ReadKey("balance") |
| 77 |
return int(balance_str) |
| 78 |
except ValueError: |
| 79 |
return 0 |