File: Connections_Handler.py

package info (click to toggle)
xpn 1.2.6-5
  • links: PTS, VCS
  • area: main
  • in suites: jessie, jessie-kfreebsd, squeeze, wheezy
  • size: 2,500 kB
  • ctags: 1,685
  • sloc: python: 12,693; xml: 206; makefile: 16; sh: 1
file content (571 lines) | stat: -rw-r--r-- 24,845 bytes parent folder | download | duplicates (2)
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
564
565
566
567
568
569
570
571
import nntplib
import xpn_src.nntplib_ssl as nntplib_ssl
import smtplib
import sys
import time
import StringIO
import os
from urllib import quote as url_quote
from xpn_src.UserDir import get_wdir


def my_xover(self,start,end):
    """Process an XOVER command (optional server extension) Arguments:
    - start: start of range
    - end: end of range
    Returns:
    - resp: server response if successful
    - list: list of (art-nr, subject, poster, date,
                    id, references, size, lines,xref)"""

    resp, lines = self.longcmd('XOVER ' + start + '-' + end)
    xover_lines = []
    for line in lines:
        elem = line.split("\t")
        try:
            xover_lines.append((elem[0],
                                elem[1],
                                elem[2],
                                elem[3],
                                elem[4],
                                elem[5],
                                elem[6],
                                elem[7],
                                elem[8]))
        except IndexError:
            raise nntplib.NNTPDataError(line)
    return resp,xover_lines


class Connection:
    '''This class wraps an nntp connection.

    It has two types of methods, user-level methods and class-level methodos.
    The user is intended to use only user-level methods that astract nntp
    operation at a higher lever. Class-level methods are used internally
    also to implement user-level methods.

    User-level methods are: closeConnection, getBody, getHeaders, getXHDRHeaders, sendArticle

    Class-level methods are:__init__, _isUp, _tryConnection, _addLog, _enterGroup
   
    
    Attributes:
    serverConnection     : it is None or an nntplib.NNTP instance representing
                           the connection with the server
    serverAddress        : server address
    serverPort           : port number
    requireAuthentication: True if server requires authentication
    username             : username for the server
    password             : password for the server
    groupEntered         : the group we sent the command GROUP for
    '''
    
    def __init__(self,serverAddress,serverPort=119,requireAuthentication=False,username="",password=""):
        '''Class constructor'''
       
        self.serverConnection = None # when there is no connection with the server this attribute
                                     # should be None
        self.serverAddress = serverAddress
        self.serverPort = int(serverPort)
        self.requireAuthentication = requireAuthentication
        self.username = username
        self.password = password
        self.groupEntered= ""
        nntplib.NNTP.my_xover=my_xover

    def reInit(self,serverAddress,serverPort=119,requireAuthentication=False,username="",password=""):
        '''Reset the class attributes.

        It is useful when you change some attributes like server name and don't want to create
        a new object
        '''
        self.closeConnection()
        self.__init__(serverAddress,serverPort,requireAuthentication,username,password)
    
    def _isUp(self):
        '''Return the state of the connection.'''
        return self.serverConnection!=None
        
    def closeConnection(self):
        ''' Close connection and add a log of the operation.'''
        if self._isUp():
            self._addLog("QUIT",True)
            try:
                message=self.serverConnection.quit()
            except :
                message=str(sys.exc_info()[0])+","+str(sys.exc_info()[1])
            self.serverConnection=None
            self._addLog(message,False)
                
         
    def _addLog(self,message,is_command):
        ''' Adds an entry in server_logs.dat.

        Arguments:
        message    : is the entry to add
        is_command : if it is True we are adding a message sent to the server, else
                     we are adding a message received from the server
        '''
        
        try:
            f=open(os.path.join(get_wdir(),"server_logs.dat"),"a")
        except IOError:
            pass
        else:
            if is_command:
                f.write(time.ctime(time.time())+" :: >> "+message+"\n")
            else:
                f.write(time.ctime(time.time())+" :: << "+message+"\n")
            f.close()

            
    def _tryConnection(self):
        '''Tries to estabilish a connection with the server or check if it is still up.

        If self.serverConnection is None must set-up a new connection, else the connection
        could be still up, test it, and if it is down try to estabilish a new connection.

        Return: 
        message : you can use it to interact with the user.
        isUp : a boolean indicating the state of the connection
        '''
        if self.serverConnection==None:
            #we must set-up a new connection
            self.groupEntered=""
            try:
                if self.requireAuthentication=="True":
                    self._addLog("AUTHINFO USER "+self.username,True)
                    self._addLog("AUTHINFO PASS "+"".join(["*" for i in self.password]),True)
                self._addLog("MODE READER",True)
                self.serverConnection=nntplib.NNTP(self.serverAddress,port=self.serverPort,user=self.username,password=self.password,readermode=True)
            except :
                message=_("No connection with server : %s. Configure NNTP Server Address or try later.") % (self.serverAddress,)
                self._addLog(str(sys.exc_info()[0])+","+str(sys.exc_info()[1]),False)
                self.serverConnection=None
            else:
                message=_("Connection estabilished with server: %s") % (self.serverAddress,)
                self._addLog(self.serverConnection.getwelcome(),False)
            return message, self._isUp()
        else:
            #the connection probably is still up, let's test it
            try:
                # I use stat only to test if the connection is still up
                #self.serverConnection.stat("<>") # this stat seems to cause some problems to Hamster.
                #self.serverConnection.stat("")
                self.serverConnection.date() #devo vedere come risponde dopo il timeout
            except nntplib.NNTPPermanentError:
                # the connection is broken, I try to estabilish a new connection
                self.serverConnection=None
                message,isUp=self._tryConnection()
                return message,isUp
            #except nntplib.NNTPTemporaryError:
                # This exception is raised because the article <> doesn't exist
                # I haven't to do anything
            #    return "",True 
            except :
                #This is another type of exception, however we have problems with server
                message=_("No connection with server : %s. Configure NNTP Server Address or try later.") % (self.serverAddress,)
                self._addLog(str(sys.exc_info()[0])+","+str(sys.exc_info()[1]),False)
                self.serverConnection=None
                message,isUp=self._tryConnection()
                return message,isUp
            else:
                #the connection is active
                return "",True

    def _enterGroup(self,group,force=False):
        ''' Send GROUP command if it is needed.

        Arguments:
        group : the group to enter
        force : if force is True GROUP command is always sent
        
        Return:
        message : it can be used to interact with the user
        first   : first article in group
        last    : last article in group
        '''
        message,connectionIsUp=self._tryConnection()
        first=0
        last=0
        if connectionIsUp:
            if group!=self.groupEntered or force:
                #we have to send group command
                try:
                    self._addLog("GROUP "+group,True)
                    resp,count,first,last,name=self.serverConnection.group(group)
                except :
                    message=_("Server error: %s") % (str(sys.exc_info()[1]),)
                    self._addLog(str(sys.exc_info()[0])+","+str(sys.exc_info()[1]),False)
                else:
                    message=_("%s response : %s") % (self.serverAddress,resp)
                    self._addLog(resp,False)
                    self.groupEntered=group
        return message,first,last

    def getArticleNumber(self,group,msgid):
        '''Return the article number using the message-id to query the server'''
        number=-1
        header_list=[]
        message,first,last=self._enterGroup(group)
        if self._isUp():
            try:
                resp,number,msgid,header_list=self.serverConnection.head(msgid)
            except :
                message=_("Server error: %s") % (str(sys.exc_info()[1]),)
                self._addLog(str(sys.exc_info()[0])+","+str(sys.exc_info()[1]),False)
            else:
                message=_("%s response : %s") % (self.serverAddress,resp)
                self._addLog(resp,False)
            if int(number)==0:
                #some servers send a 0 when called with the message-id
                for header in header_list:
                    if header.lower().startswith("xref:"): 
                        try: number=int(header.split(group+":")[1].split()[0].strip())
                        except : number= -1
        return message,int(number)

                
            
        
        
    def getBody(self,number,msgid,group):
        '''Retrieve the body of the article.

        First need to enter the group, then retrieve with an HEAD the command
        the headers list and then retrieve the body.

        Arguments:
        number      : article number
        msgid       : article message-id
        group       : the group the article is in
        
        Return:
        message       : it can be used to interact with the user
        headerList    : the headers list, XPN uses it with xpn_src.Article.parse_header_list
        rawBody       : the body retrieved (or phantom article). XPN uses it with xpn_src.Article.set_body
                        (not in the case it is the phantom article)
        bodyRetrieved : True if the bosy has been successfully retrieved from the server (so rawBody isn't
                        [] or phantom article)
        '''
        bodyRetrieved=False
        headerList=[]
        rawBody=[]
        message,first,last=self._enterGroup(group)
        if self._isUp():
            try:
                self._addLog("ARTICLE "+number,True)
                resp,number,id,rawBody=self.serverConnection.article(number)
            except nntplib.NNTPTemporaryError:
                message=_("Server error: %s") % (str(sys.exc_info()[1]),)
                if str(sys.exc_info()[1])[:1]=="4":
                    #article is not on the server, we use a phantom article
                    link=r"http://groups.google.com/groups?selm="+url_quote(msgid[1:-1])
                    rawBody=(_("Server Error: ")+str(sys.exc_info()[1]),"",_("You can try on Google:"),"",link)
                self._addLog(str(sys.exc_info()[0])+","+str(sys.exc_info()[1]),False)
            except :
                #every other type of errors
                message=_("Server error: %s") % (str(sys.exc_info()[1]),)
                self._addLog(str(sys.exc_info()[0])+","+str(sys.exc_info()[1]),False)
            else:
                self._addLog(resp,False)
                message=_("%s response : %s") % (self.serverAddress,resp)
                ind=rawBody.index("")
                headerList=rawBody[:ind]
                rawBody=rawBody[ind+1:]
                bodyRetrieved=True
        return message,headerList,rawBody,bodyRetrieved 
        
         
    def getHeaders(self,group,first,last=None,count=None):
        '''Retrieve Headers in a given range.

        Arguments:
        group : the group to download the headers for
        first : the first article to consider
        last  : tha last article to consider, if it is None last will be the last article on group
        count : the number of article to headers, the 'count' newest headers will be downloaded.
                If you are subscribing the group, first=0 and then it is ignored.
                If you also pass the 'last' argument 'count' will be ignored

        Return:
        message     : it can be used to interact with the user
        headersList : a list of lists, every element is a list containing the headers of an article
        lastOnServer : last number on server
        '''
        headersList=[]
        lastOnServer=-1
        message,group_first,group_last=self._enterGroup(group,True)
        argumentLast=last
        if not last: last=group_last
        if count and not argumentLast: 
            first,last=max(int(group_last)-count+1,first),group_last
        if first<0: first=0
        if int(first)<=int(last):
            if self._isUp():
                try:
                    self._addLog("XOVER "+str(first)+"-"+str(last),True)
                    resp,headersList=self.serverConnection.my_xover(str(first),str(last))
                except :
                    message=_("Server error: %s") % (str(sys.exc_info()[1]),)
                    self._addLog(str(sys.exc_info()[0])+","+str(sys.exc_info()[1]),False)
                else:
                    lastOnServer=int(group_last)
                    message=_("%s response : %s") % (self.serverAddress,resp)
                    self._addLog(resp,False)
        return message,headersList,lastOnServer
        
    def getXHDRHeaders(self,group,headerName,first,last=None,count=None):
        '''Retrieve a given Header in a given range.

        Arguments:
        group     : the group to download the headers for
        headerName: the header to download
        first     : the first article to consider
        last      : tha last article to consider, if it is None last will be the last article on group
        count     : the number of article to headers, the 'count' newest headers will be downloaded,
                    'first' is ignored in this case. If you also pass the 'last' argument 'count' will be 
                    ignored

        Return:
        message      : it can be used to interact with the user
        headerList   : a list of the header values
        '''

        headerList=[]
        lastOnServer=-1
        message,group_first,group_last=self._enterGroup(group,True)
        argumentLast=last
        if not last: last=group_last
        if count and not argumentLast: first,last=int(group_last)-count+1,group_last
        if first<0: first=0
        if int(first)<=int(last):
            if self._isUp():
                try:
                    self._addLog("XHDR "+headerName+" "+str(first)+"-"+str(last),True)
                    resp,headerList=self.serverConnection.xhdr(headerName,str(first)+"-"+str(last))
                except :
                    message=_("Server error: %s") % (str(sys.exc_info()[1]),)
                    self._addLog(str(sys.exc_info()[0])+","+str(sys.exc_info()[1]),False)
                else:
                    lastOnServer=int(group_last)
                    message=_("%s response : %s") % (self.serverAddress,resp)
                    self._addLog(resp,False)
        return message,headerList

    def sendArticle(self,article):
        '''Send an article to the Server.

        Arguments:
        article : a string representing a well-formed usenet article
        
        Returns:
        message       : it can be used to interact with the user
        articlePosted : True if the article was correctly sent
        '''
        message,connectionIsUp=self._tryConnection()
        articlePosted=False
        if connectionIsUp:
            fileArticle=StringIO.StringIO(article)
            try:
                self._addLog("POST", True)
                resp=self.serverConnection.post(fileArticle)
            except :
                message=_("Server error: %s") % (str(sys.exc_info()[1]),)
                self._addLog(str(sys.exc_info()[0])+","+str(sys.exc_info()[1]),False)
                fileArticle.close()
            else:
                fileArticle.close()
                self._addLog(resp,False)
                message=_("%s response : %s") % (self.serverAddress,resp)
                articlePosted=True
        return message,articlePosted

class SSLConnection(Connection):
    def __init__(self,serverAddress,serverPort=563,requireAuthentication=False,username="",password=""):
        '''Class constructor'''
       
        self.serverConnection = None # when there is no connection with the server this attribute
                                     # should be None
        self.serverAddress = serverAddress
        self.serverPort = int(serverPort)
        self.requireAuthentication = requireAuthentication
        self.username = username
        self.password = password
        self.groupEntered= ""
        nntplib_ssl.NNTP_SSL.my_xover=my_xover


    def reInit(self,serverAddress,serverPort=563,requireAuthentication=False,username="",password=""):
        '''Reset the class attributes.

        It is useful when you change some attributes like server name and don't want to create
        a new object
        '''
        self.closeConnection()
        self.__init__(serverAddress,serverPort,requireAuthentication,username,password)

    def _tryConnection(self):
        '''Tries to estabilish a connection with the server or check if it is still up.

        If self.serverConnection is None must set-up a new connection, else the connection
        could be still up, test it, and if it is down try to estabilish a new connection.

        Return: 
        message : you can use it to interact with the user.
        isUp : a boolean indicating the state of the connection
        '''
        if self.serverConnection==None:
            #we must set-up a new connection
            self.groupEntered=""
            try:
                if self.requireAuthentication=="True":
                    self._addLog("AUTHINFO USER "+self.username,True)
                    self._addLog("AUTHINFO PASS "+"".join(["*" for i in self.password]),True)
                self._addLog("MODE READER",True)
                self.serverConnection=nntplib_ssl.NNTP_SSL(self.serverAddress,port=self.serverPort,user=self.username,password=self.password,readermode=True)
            except :
                message=_("No connection with server : %s. Configure NNTP Server Address or try later.") % (self.serverAddress,)
                self._addLog(str(sys.exc_info()[0])+","+str(sys.exc_info()[1]),False)
                self.serverConnection=None
            else:
                message=_("Connection estabilished with server: %s") % (self.serverAddress,)
                self._addLog(self.serverConnection.getwelcome(),False)
            return message, self._isUp()
        else:
            #the connection probably is still up, let's test it
            try:
                # I use stat only to test if the connection is still up
                #self.serverConnection.stat("<>") # this stat seems to cause some problems to Hamster.
                self.serverConnection.stat("")
            except nntplib.NNTPPermanentError:
                # the connection is broken, I try to estabilish a new connection
                self.serverConnection=None
                message,isUp=self._tryConnection()
                return message,isUp
            except nntplib.NNTPTemporaryError:
                # This exception is raised because the article <> doesn't exist
                # I haven't to do anything
                return "",True 
            except :
                #This is another type of exception, however we have problems with server
                message=_("No connection with server : %s. Configure NNTP Server Address or try later.") % (self.serverAddress,)
                self._addLog(str(sys.exc_info()[0])+","+str(sys.exc_info()[1]),False)
                self.serverConnection=None
                message,isUp=self._tryConnection()
                return message,isUp
            else:
                #This is only a fallback this leaf shouldn't never be reached
                return "",True


class SMTPConnection:
    '''This class wraps an SMTP Connection'''
    def __init__(self,serverAddress,serverPort=25,requireAuthentication=False,username="",password=""):
        self.serverConnection = None # when there is no connection with the server this attribute
                                     # should be None
        self.serverAddress = serverAddress
        self.serverPort = int(serverPort)
        self.requireAuthentication = requireAuthentication
        self.username = username
        self.password = password

    def reInit(self,serverAddress,serverPort=25,requireAuthentication=False,username="",password=""):
        '''Reset the class attributes.

        It is useful when you change some attributes like server name and don't want to create
        a new object
        '''
        self.closeConnection()
        self.__init__(serverAddress,serverPort,requireAuthentication,username,password)
    
    def _isUp(self):
        '''Return the state of the connection.'''
        return self.serverConnection!=None
        
    def closeConnection(self):
        ''' Close connection and add a log of the operation.'''
        if self._isUp():
            self._addLog("QUIT",True)
            try:
                self.serverConnection.quit()
            except :
                message=str(sys.exc_info()[0])+","+str(sys.exc_info()[1])
            else:
                message=_("Connection closed")
            self.serverConnection=None
            self._addLog(message,False)
                
         
    def _addLog(self,message,is_command):
        ''' Adds an entry in server_logs.dat.

        Arguments:
        message    : is the entry to add
        is_command : if it is True we are adding a message sent to the server, else
                     we are adding a message received from the server
        '''
        
        try:
            f=open(os.path.join(get_wdir(),"server_logs.dat"),"a")
        except IOError:
            pass
        else:
            if is_command:
                f.write(time.ctime(time.time())+" ::[SMTP] >> "+message+"\n")
            else:
                f.write(time.ctime(time.time())+" ::[SMTP] << "+message+"\n")
            f.close()

    def _tryConnection(self):
        '''Tries to estabilish a connection with the server or check if it is still up.

        If self.serverConnection is None must set-up a new connection, else the connection
        could be still up, test it, and if it is down try to estabilish a new connection.

        Return: 
        message : you can use it to interact with the user.
        isUp : a boolean indicating the state of the connection'''
        message=""
        if self.serverConnection==None:
            try:
                self.serverConnection = smtplib.SMTP(self.serverAddress,self.serverPort)
                if self.requireAuthentication=="True":
                    self._addLog("LOGIN "+self.username+" "+"".join(["*" for i in self.password]),True)
                    self.serverConnection.login(self.username,self.password)
            except:
                message=_("No connection with server : %s. Configure SMTP Server Address or try later.") % (self.serverAddress,)
                self._addLog(str(sys.exc_info()[0])+","+str(sys.exc_info()[1]),False)
                self.serverConnection=None
            else:
                message=_("Connection estabilished with: %s")  % (self.serverAddress,)
                self._addLog(message,False)
        return message,self._isUp()

    def sendMail(self,from_name,to_name,mail):
        ''' Send a well formed Email.

        Arguments:
        from_name: sender address
        to_name  : destination address
        mail     : a well formed e-mail

        Return:
        message  : you can use it to interact with the user.
        mailSent : True if the mail was correctly sent'''
        
        message,connectionIsUp=self._tryConnection()
        mailSent=False
        if connectionIsUp:
            try:
                self._addLog("SENDMAIL",True)
                self.serverConnection.sendmail(from_name,to_name,mail)
            except:
                message=_("Unable to send the message. Control Server Logs.")
                self._addLog(str(sys.exc_info()[0])+","+str(sys.exc_info()[1]),False)
            else:
                message=_("Email Sent")
                self._addLog(message,False)
                mailSent=True
        return message,mailSent