<s> from __future__ import unicode_literals <EOL> import logging <EOL> from . packages import dkim <EOL> from . packages . dkim import DKIMException , UnparsableKeyError <EOL> from . packages . dkim . crypto import parse_pem_private_key <EOL> from . compat import to_bytes , to_native <EOL> class DKIMSigner : <EOL> def __init__ ( self , selector , domain , key = None , ignore_sign_errors = False , ** kwargs ) : <EOL> self . ignore_sign_errors = ignore_sign_errors <EOL> self . _sign_params = kwargs <EOL> privkey = key or kwargs . pop ( '<STR_LIT>' , None ) <EOL> if not privkey : <EOL> raise TypeError ( "<STR_LIT>" ) <EOL> if privkey and hasattr ( privkey , '<STR_LIT>' ) : <EOL> privkey = privkey . read ( ) <EOL> try : <EOL> privkey = parse_pem_private_key ( to_bytes ( privkey ) ) <EOL> except UnparsableKeyError as exc : <EOL> raise DKIMException ( exc ) <EOL> self . _sign_params . update ( { '<STR_LIT>' : privkey , <EOL> '<STR_LIT>' : to_bytes ( domain ) , <EOL> '<STR_LIT>' : to_bytes ( selector ) } ) <EOL> def get_sign_string ( self , message ) : <EOL> try : <EOL> return dkim . sign ( message = message , ** self . _sign_params ) <EOL> except DKIMException : <EOL> if self . ignore_sign_errors : <EOL> logging . exception ( '<STR_LIT>' ) <EOL> else : <EOL> raise <EOL> def get_sign_header ( self , message ) : <EOL> s = self . get_sign_string ( message ) <EOL> if s : <EOL> ( header , value ) = to_native ( s ) . split ( '<STR_LIT>' , <NUM_LIT:1> ) <EOL> if value . endswith ( "<STR_LIT:\r\n>" ) : <EOL> value = value [ : - <NUM_LIT:2> ] <EOL> return header , value <EOL> def sign_message ( self , msg ) : <EOL> """<STR_LIT>""" <EOL> dkim_header = self . get_sign_header ( to_bytes ( msg . as_string ( ) ) ) <EOL> if dkim_header : <EOL> msg . _headers . insert ( <NUM_LIT:0> , dkim_header ) <EOL> return msg <EOL> def sign_message_string ( self , message_string ) : <EOL> """<STR_LIT>""" <EOL> s = self . get_sign_string ( to_bytes ( message_string ) ) <EOL> return s and to_native ( s ) + message_string or message_string </s>
