~exarkun/+junk/training

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
from twisted.protocols.basic import LineOnlyReceiver
from twisted.internet import reactor
from twisted.internet.protocol import ServerFactory


class CommandProtocol(LineOnlyReceiver):
    def connectionMade(self):
        self.username = None


    def hasPermission(self, command):
        return command in self.factory.permissions[self.username]


    def lineReceived(self, line):
        arguments = line.split()
        command = arguments.pop(0).upper()
        method = getattr(self, 'command_' + command, None)
        if method is None:
            self.sendLine("Invalid command")
        elif not self.hasPermission(command):
            self.sendLine("Permission denied")
        else:
            self.sendLine(method(*arguments))


    def command_ADD(self, left, right):
        return str(int(left) + int(right))


    def command_MUL(self, left, right):
        return str(int(left) * int(right))


    def command_DIV(self, left, right):
        return str(int(left) / int(right))



class CommandFactory(ServerFactory):
    protocol = CommandProtocol

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



def main():
    factory = CommandFactory({None: ['ADD', 'MUL']})
    reactor.listenTCP(12345, factory)
    reactor.run()


if __name__ == '__main__':
    main()