Show
Ignore:
Timestamp:
09/27/08 22:02:37 (16 years ago)
Author:
jerome
Message:

Removed unnecessary spaces at EOL.

Files:
1 modified

Legend:

Unmodified
Added
Removed
  • pykota/trunk/bin/pknotify

    r3411 r3413  
    99# the Free Software Foundation, either version 3 of the License, or 
    1010# (at your option) any later version. 
    11 #  
     11# 
    1212# This program is distributed in the hope that it will be useful, 
    1313# but WITHOUT ANY WARRANTY; without even the implied warranty of 
    1414# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the 
    1515# GNU General Public License for more details. 
    16 #  
     16# 
    1717# You should have received a copy of the GNU General Public License 
    1818# along with this program.  If not, see <http://www.gnu.org/licenses/>. 
     
    3030try : 
    3131    import PAM 
    32 except ImportError :     
     32except ImportError : 
    3333    hasPAM = False 
    34 else :     
     34else : 
    3535    hasPAM = True 
    3636 
     
    5353  -v | --version             Prints pknotify's version number then exits. 
    5454  -h | --help                Prints this message then exits. 
    55    
     55 
    5656  -d | --destination h[:p]   Sets the destination hostname and optional 
    5757                             port onto which contact the remote PyKotIcon 
    5858                             application. This option is mandatory. 
    5959                             When not specified, the port defaults to 7654. 
    60                               
     60 
    6161  -a | --ask                 Tells pknotify to ask something to the end 
    6262                             user. Then pknotify will output the result. 
    63                         
     63 
    6464  -C | --checkauth           When --ask is used and both an 'username' and a 
    6565                             'password' are asked to the end user, then 
     
    7070                             be printed. If the user is authenticated, then 
    7171                             "USERNAME=xxxx" will be printed as well. 
    72                               
    73   -c | --confirm             Tells pknotify to ask for either a confirmation                        
     72 
     73  -c | --confirm             Tells pknotify to ask for either a confirmation 
    7474                             or abortion. 
    75                               
    76   -D | --denyafter N         With --checkauth above, makes pknotify loop                            
     75 
     76  -D | --denyafter N         With --checkauth above, makes pknotify loop 
    7777                             up to N times if the password is incorrect. 
    7878                             After having reached the limit, "DENY" will 
     
    8080                             The default value of N is 1, meaning the job 
    8181                             is denied after the first unsuccessful try. 
    82                               
     82 
    8383  -N | --noremote action     If it's impossible to connect to the remote 
    8484                             PyKotIcon machine, do this action instead. 
    85                              Allowed actions are 'CONTINUE' and 'CANCEL',  
     85                             Allowed actions are 'CONTINUE' and 'CANCEL', 
    8686                             which will respectively allow the processing 
    8787                             of the print job to continue, or the job to 
    8888                             be cancelled. The default value is CANCEL. 
    89                               
     89 
    9090  -n | --notify              Tells pknotify to send an informational message 
    9191                             to the end user. 
    92                               
     92 
    9393  -q | --quit                Tells pknotify to send a message asking the 
    9494                             PyKotIcon application to exit. This option can 
    9595                             be combined with the other ones to make PyKotIcon 
    9696                             exit after having sent the answer from the dialog. 
    97                               
     97 
    9898  -t | --timeout T           Tells pknotify to ignore the end user's answer if 
    9999                             it comes past T seconds after the dialog box being 
    100                              opened. The default value is 0 seconds, which  
     100                             opened. The default value is 0 seconds, which 
    101101                             tells pknotify to wait indefinitely. 
    102102                             Use this option to avoid having an user who 
    103103                             leaved his computer stall a whole print queue. 
    104                               
     104 
    105105  You MUST specify either --ask, --confirm, --notify or --quit. 
    106106 
    107   arguments :              
    108    
     107  arguments : 
     108 
    109109    -a | --ask : Several arguments are accepted, of the form 
    110110                 "label:varname:defaultvalue". The result will 
     
    119119                 it is not printed, it will be used to check if 
    120120                 authentication is valid if you specify --checkauth. 
    121                   
     121 
    122122    -c | --confirm : A single argument is expected, representing the 
    123123                     message to display. If the dialog is confirmed 
    124124                     then pknotify will print OK, else CANCEL. 
    125                       
    126     -n | --notify : A single argument is expected, representing the                  
     125 
     126    -n | --notify : A single argument is expected, representing the 
    127127                    message to display. In this case pknotify will 
    128128                    always print OK. 
    129                      
    130 examples :                     
     129 
     130examples : 
    131131 
    132132  pknotify -d client:7654 --noremote CONTINUE --confirm "This job costs 10 credits" 
    133    
     133 
    134134  Would display the cost of the print job and asks for confirmation. 
    135135  If the end user doesn't have PyKotIcon running and accepting connections 
    136136  from the print server, PyKota will consider that the end user accepted 
    137137  to print this job. 
    138    
     138 
    139139  pknotify --destination $PYKOTAJOBORIGINATINGHOSTNAME:7654 \\ 
    140140           --checkauth --ask "Your name:username:" "Your password:password:" 
    141             
    142   Asks an username and password, and checks if they are valid.          
     141 
     142  Asks an username and password, and checks if they are valid. 
    143143  NB : The PYKOTAJOBORIGINATINGHOSTNAME environment variable is 
    144144  only set if you launch pknotify from cupspykota through a directive 
    145145  in ~pykota/pykota.conf 
    146    
     146 
    147147  The TCP port you'll use must be reachable on the client from the 
    148148  print server. 
    149149""") 
    150          
    151 class TimeoutError(Exception) :         
     150 
     151class TimeoutError(Exception) : 
    152152    """An exception for timeouts.""" 
    153153    def __init__(self, message = ""): 
     
    157157        return self.message 
    158158    __str__ = __repr__ 
    159      
    160 class PyKotaNotify(Tool) :         
     159 
     160class PyKotaNotify(Tool) : 
    161161    """A class for pknotify.""" 
    162162    def UTF8ToUserCharset(self, text) : 
     
    164164        if text is None : 
    165165            return None 
    166         else :     
    167             return text.decode("UTF-8", "replace").encode(self.charset, "replace")  
    168          
     166        else : 
     167            return text.decode("UTF-8", "replace").encode(self.charset, "replace") 
     168 
    169169    def userCharsetToUTF8(self, text) : 
    170170        """Converts from user's charset to UTF-8.""" 
    171171        if text is None : 
    172172            return None 
    173         else :     
    174             return text.decode(self.charset, "replace").encode("UTF-8", "replace")     
    175          
     173        else : 
     174            return text.decode(self.charset, "replace").encode("UTF-8", "replace") 
     175 
    176176    def sanitizeMessage(self, msg) : 
    177177        """Replaces \\n and returns a messagee in xmlrpclib Binary format.""" 
    178178        return xmlrpclib.Binary(self.userCharsetToUTF8(msg.replace("\\n", "\n"))) 
    179          
     179 
    180180    def convPAM(self, auth, queries=[], userdata=None) : 
    181181        """Prepares PAM datas.""" 
     
    191191        return response 
    192192 
    193     def checkAuth(self, username, password) :     
     193    def checkAuth(self, username, password) : 
    194194        """Checks if we could authenticate an username with a password.""" 
    195         if not hasPAM :     
     195        if not hasPAM : 
    196196            raise PyKotaToolError, _("You MUST install PyPAM for this functionnality to work !") 
    197         else :     
     197        else : 
    198198            retcode = False 
    199199            self.password = password 
     
    213213                retcode = True 
    214214            return retcode 
    215              
    216     def alarmHandler(self, signum, frame) :         
     215 
     216    def alarmHandler(self, signum, frame) : 
    217217        """Alarm handler.""" 
    218218        raise TimeoutError, _("The end user at %s:%i didn't answer within %i seconds. The print job will be cancelled.") % (self.destination, self.port, self.timeout) 
    219          
     219 
    220220    def main(self, arguments, options) : 
    221221        """Notifies or asks questions to end users through PyKotIcon.""" 
     
    226226            self.destination = options["destination"] 
    227227            self.port = 7654 
    228              
     228 
    229229        try : 
    230230            denyafter = int(options["denyafter"]) 
    231231            if denyafter < 1 : 
    232232                raise ValueError 
    233         except (ValueError, TypeError) :         
     233        except (ValueError, TypeError) : 
    234234            denyafter = 1 
    235              
    236         try :     
     235 
     236        try : 
    237237            self.timeout = int(options["timeout"]) 
    238238            if self.timeout < 0 : 
     
    240240        except (ValueError, TypeError) : 
    241241            self.timeout = 0 
    242              
     242 
    243243        if self.timeout : 
    244244            signal.signal(signal.SIGALRM, self.alarmHandler) 
    245245            signal.alarm(self.timeout) 
    246              
    247         try :     
    248             try :     
     246 
     247        try : 
     248            try : 
    249249                server = xmlrpclib.ServerProxy("http://%s:%s" % (self.destination, self.port)) 
    250250                if options["ask"] : 
     
    253253                        if denyafter < 1 : 
    254254                            raise ValueError 
    255                     except (ValueError, TypeError) :     
     255                    except (ValueError, TypeError) : 
    256256                        denyafter = 1 
    257257                    labels = [] 
     
    261261                        try : 
    262262                            (label, varname, varvalue) = arg.split(":", 2) 
    263                         except ValueError :     
     263                        except ValueError : 
    264264                            raise PyKotaCommandLineError, "argument '%s' is invalid !" % arg 
    265265                        labels.append(self.sanitizeMessage(label)) 
     
    267267                        varnames.append(varname) 
    268268                        varvalues[varname] = self.sanitizeMessage(varvalue) 
    269                          
    270                     passnumber = 1     
     269 
     270                    passnumber = 1 
    271271                    authok = None 
    272272                    while (authok != "AUTH=YES") and (passnumber <= denyafter) : 
    273                         result = server.askDatas(labels, varnames, varvalues)     
     273                        result = server.askDatas(labels, varnames, varvalues) 
    274274                        if not options["checkauth"] : 
    275275                            break 
    276276                        if result["isValid"] : 
    277277                            if ("username" in varnames) and ("password" in varnames) : 
    278                                 if self.checkAuth(self.UTF8ToUserCharset(result["username"].data[:]),  
     278                                if self.checkAuth(self.UTF8ToUserCharset(result["username"].data[:]), 
    279279                                                  self.UTF8ToUserCharset(result["password"].data[:])) : 
    280280                                    authok = "AUTH=YES" 
    281                                 else :     
     281                                else : 
    282282                                    authok = "AUTH=NO" 
    283                             else :         
    284                                 authok = "AUTH=IMPOSSIBLE"         
    285                         passnumber += 1         
    286                                      
     283                            else : 
     284                                authok = "AUTH=IMPOSSIBLE" 
     285                        passnumber += 1 
     286 
    287287                    if options["checkauth"] and options["denyafter"] \ 
    288288                       and (passnumber > denyafter) \ 
     
    294294                               and ((varname != "username") or (authok in (None, "AUTH=YES"))) : 
    295295                                print "%s=%s" % (varname.upper(), self.UTF8ToUserCharset(result[varname].data[:])) 
    296                         if authok is not None :         
    297                             print authok         
     296                        if authok is not None : 
     297                            print authok 
    298298                elif options["confirm"] : 
    299299                    print server.showDialog(self.sanitizeMessage(arguments[0]), True) 
    300300                elif options["notify"] : 
    301301                    print server.showDialog(self.sanitizeMessage(arguments[0]), False) 
    302                      
    303                 if options["quit"] :     
     302 
     303                if options["quit"] : 
    304304                    server.quitApplication() 
    305305            except (xmlrpclib.ProtocolError, socket.error, socket.gaierror), msg : 
     
    309309                #except (AttributeError, IndexError) : 
    310310                #    pass 
    311                 #else :     
     311                #else : 
    312312                #    if errnum == errno.ECONNREFUSED : 
    313313                #        raise PyKotaToolError, "%s : %s" % (str(msg), (_("Are you sure that PyKotIcon is running and accepting incoming connections on %s:%s ?") % (self.destination, self.port))) 
    314314                self.printInfo("%s : %s" % (_("Connection error"), str(msg)), "warn") 
    315             except TimeoutError, msg :     
     315            except TimeoutError, msg : 
    316316                self.printInfo(msg, "warn") 
    317317                print "CANCEL"      # Timeout occured : job is cancelled. 
    318         finally :     
    319             if self.timeout :     
    320                 signal.alarm(0)     
    321          
     318        finally : 
     319            if self.timeout : 
     320                signal.alarm(0) 
     321 
    322322if __name__ == "__main__" : 
    323323    retcode = 0 
     
    331331                        "timeout=", "ask", "checkauth", "confirm", "notify", \ 
    332332                        "quit", "noremote=" ] 
    333          
     333 
    334334        # Initializes the command line tool 
    335335        notifier = PyKotaNotify(doc=__doc__) 
    336336        notifier.deferredInit() 
    337          
     337 
    338338        # parse and checks the command line 
    339339        (options, args) = notifier.parseCommandline(sys.argv[1:], short_options, long_options) 
    340          
     340 
    341341        # sets long options 
    342342        options["help"] = options["h"] or options["help"] 
     
    351351        options["timeout"] = options["t"] or options["timeout"] or defaults["timeout"] 
    352352        options["noremote"] = (options["N"] or options["noremote"] or defaults["noremote"]).upper() 
    353          
     353 
    354354        if options["help"] : 
    355355            notifier.display_usage_and_quit() 
     
    370370        else : 
    371371            retcode = notifier.main(args, options) 
    372     except KeyboardInterrupt :         
     372    except KeyboardInterrupt : 
    373373        logerr("\nInterrupted with Ctrl+C !\n") 
    374374        retcode = -3 
    375     except PyKotaCommandLineError, msg :     
     375    except PyKotaCommandLineError, msg : 
    376376        logerr("%s : %s\n" % (sys.argv[0], msg)) 
    377377        print "CANCEL"  # Forces the cancellation of the print job if a command line switch is incorrect 
    378378        retcode = -2 
    379     except SystemExit :         
     379    except SystemExit : 
    380380        pass 
    381381    except : 
    382382        try : 
    383383            notifier.crashed("%s failed" % sys.argv[0]) 
    384         except :     
     384        except : 
    385385            crashed("%s failed" % sys.argv[0]) 
    386386        retcode = -1 
    387          
    388     sys.exit(retcode)     
     387 
     388    sys.exit(retcode)