File: Eval.py

package info (click to toggle)
emesene 1.0-dist-4
  • links: PTS, VCS
  • area: main
  • in suites: lenny
  • size: 4,596 kB
  • ctags: 3,006
  • sloc: python: 25,171; makefile: 14; sh: 1
file content (197 lines) | stat: -rw-r--r-- 6,145 bytes parent folder | download
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
# -*- coding: utf-8 -*-

#   This file is part of emesene.
#
#    Eval plugin is free software; you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation; either version 2 of the License, or
#    (at your option) any later version.
#
#    Eval plugin is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.
#
#    You should have received a copy of the GNU General Public License
#    along with emesene; if not, write to the Free Software
#    Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA

"""
Eval plugin v0.4
THIS IS A DEVELOPERS TOOL, USE AT YOUR OWN RISK!
Simple usage:
 /eval out("somestring")
 /eval out(dir())
 /eval out(slashAction.conversation.switchboard)
Remote usage:
 From the other side..:
   !eval out("somestring")
   !eval out(dir())
   !eval out(conversation.switchboard)
"""

VERSION = '0.4.2'

import sys
import time
import gobject
import traceback

import Plugin

class MainClass(Plugin.Plugin):
    '''Main plugin class'''
    
    def __init__(self, controller, msn):
        '''Constructor'''
        
        Plugin.Plugin.__init__(self, controller, msn)
        
        self.description = _('Evaluate python commands - USE AT YOUR OWN RISK')
        self.authors = {'Dx' : 'dx@dxzone.com.ar'}
        self.website = 'http://www.dxzone.com.ar'
        self.displayName = 'Eval'
        self.name = 'Eval'
        self.catchOutput = False
        self.controller = controller
        self.Slash = controller.Slash
        self.config = controller.config
        self.config.readPluginConfig(self.name)
        users = self.config.getPluginValue(self.name, 'users', '')
        self.allowed = users.split()
               
    def start(self):
        '''start the plugin'''
        self.Slash.register('eval', self.slashCommand, _('Run python commands'))
        conv_manager = self.controller.conversationManager
        self.receiveId = conv_manager.connect('receive-message', self.receive)
        self.enabled = True
        
    def slashCommand(self, slashAction):
        # variables init
        _ = None
        conversation = slashAction.conversation
        controller = self.controller
        msn = controller.msn
        params = str(slashAction.getParams())

        def out(text):
            slashAction.outputText(str(text))

        def send(text, includeCommand=False):
            text = str(text)
            if includeCommand:
                slashAction.outputText(' /eval ' + params + '\n' + \
                    str(text), True)
            else:
                slashAction.outputText(str(text), True)

        # keep old stdout
        if self.catchOutput:
            oldstdout = sys.stdout
        
        try:
            # catch output
            if self.catchOutput:
                sys.stdout = SlashOut(slashAction)
            # run the commands
            eval(compile(params, "<eval>", "exec"))
        except:
            exception = sys.exc_info()
            slashAction.outputText(traceback.format_exception(*exception)[-1])
            traceback.print_exception(*exception)
        
        # restore stdout
        if self.catchOutput:
            sys.stdout = oldstdout

    def receive(self, cm, conversation, mail, nick, message, format, charset):
    	'''Eval commands if mail is in allowed list'''
        if mail not in self.allowed or not message.startswith('!eval'):
            return
        cm.emit_stop_by_name('receive-message')
        message = message.replace('\r\n', '\n')
        _ = None
        controller = self.controller
        msn = controller.msn
        params = str(message.split('!eval ')[1] )

        def out(text):
            conversation.sendMessage(str(text))

        # keep old stdout
        if self.catchOutput:
            oldstdout = sys.stdout
        
        try:
            # catch output
            if self.catchOutput:
                sys.stdout = RemoteOut(conversation)
            # run the commands
            eval(compile(params, "<eval>", "exec"))
        except:
            exception = sys.exc_info()
            conversation.sendMessage(traceback.format_exception(*exception)[-1])
            traceback.print_exception(*exception)
        
        # restore stdout
        if self.catchOutput:
            sys.stdout = oldstdout

    def stop(self):
        '''stop the plugin'''
        self.Slash.unregister('eval')
        self.enabled = False
        
    def check(self):
        return (True, 'Ok')
        
    def configure(self):
    	'''Configuration Dialog'''
        l=[]
        l.append(Plugin.Option('users', str, _('Alowed users:'), '', 
                 self.config.getPluginValue( self.name, 'users', '' )))
        
        response = Plugin.ConfigWindow(_('Remote Configuration'), l).run()
        if response != None:
            self.users = str(response['users'].value)
            self.allowed = self.users.split()
            self.config.setPluginValue(self.name,'users', self.users)
        return True

# kept for historical purposes (not)
class FakeOut:
    def __init__(self):
        self.encoding = self.mode = self.name = self.newlines = None
        self.closed = False
        self.softspace = 0
    def close(self):
        pass
    def fileno(self):
        pass
    def flush(self):
        pass
    def isatty(self):
        pass
    def read(self):
        pass
    def tell(self):
        pass
    def write(self):
        pass
    def writelines(self):
        pass

class SlashOut(FakeOut):
    def __init__(self, slashAction):
        FakeOut.__init__(self)
        self.slashAction = slashAction
    def write(self,text):
        self.slashAction.outputText(text)

class RemoteOut(FakeOut):
    def __init__(self, slashAction):
        FakeOut.__init__(self)
        self.conversation = conversation
    def write(self,text):
        self.conversation.sendMessage(text)