def BuildTypelib(idlfile="RDKitXL.idl"):
    this_dir = os.path.dirname(__file__)
    idl = os.path.abspath(os.path.join(this_dir, idlfile))
    basename = idlfile.split('.')[0]
    tlb = os.path.splitext(idl)[0] + '.tlb'
    prev_idl = idl + ".previous"

    this_idl_txt = "".join(open(idl, 'r').readlines())
    previous_idl_txt = "does not exist"
    if os.path.isfile(prev_idl):
        previous_idl_txt = "".join(open(prev_idl, 'r').readlines())

    if this_idl_txt != previous_idl_txt:
        print("Compiling %s." % (idl, ))
        rc = os.system('midl "%s"' % (idl, ))
        if rc:
            raise RuntimeError("Compiling MIDL failed!")
        # Can't work out how to prevent MIDL from generating the stubs.
        # just nuke them
        for fname in ("dlldata.c %s_i.c %s_p.c %s.h" %
                      (basename, basename, basename)).split():
            os.remove(os.path.join(this_dir, fname))
        open(prev_idl, 'w').write("".join(open(idl, 'r').readlines()))

    else:
        print("No IDL changes.")

    print("Registering %s." % (tlb, ))
    tli = pythoncom.LoadTypeLib(tlb)
    pythoncom.RegisterTypeLib(tli, tlb)
Beispiel #2
0
def BuildTypelib():
    from distutils.dep_util import newer
    this_dir = os.path.dirname(__file__)
    idl = os.path.abspath(os.path.join(this_dir, "pippo.idl"))
    tlb = os.path.splitext(idl)[0] + '.tlb'
    if newer(idl, tlb):
        print(("Compiling %s" % (idl, )))
        rc = os.system('midl "%s"' % (idl, ))
        if rc:
            raise RuntimeError("Compiling MIDL failed!")
        # Can't work out how to prevent MIDL from generating the stubs.
        # just nuke them
        for fname in "dlldata.c pippo_i.c pippo_p.c pippo.h".split():
            os.remove(os.path.join(this_dir, fname))

    print(("Registering %s" % (tlb, )))
    tli = pythoncom.LoadTypeLib(tlb)
    pythoncom.RegisterTypeLib(tli, tlb)
Beispiel #3
0

# busco el directorio de instalación (global para que no cambie si usan otra dll)
INSTALL_DIR = WSFEv1.InstallDir = get_install_dir()

if __name__ == '__main__':

    if "--register" in sys.argv or "--unregister" in sys.argv:
        import pythoncom
        if TYPELIB:
            if '--register' in sys.argv:
                tlb = os.path.abspath(
                    os.path.join(INSTALL_DIR, "typelib", "wsfev1.tlb"))
                print "Registering %s" % (tlb, )
                tli = pythoncom.LoadTypeLib(tlb)
                pythoncom.RegisterTypeLib(tli, tlb)
            elif '--unregister' in sys.argv:
                k = WSFEv1
                pythoncom.UnRegisterTypeLib(k._typelib_guid_,
                                            k._typelib_version_[0],
                                            k._typelib_version_[1], 0,
                                            pythoncom.SYS_WIN32)
                print "Unregistered typelib"
        import win32com.server.register
        #print "_reg_class_spec_", WSFEv1._reg_class_spec_
        win32com.server.register.UseCommandLine(WSFEv1)
    elif "/Automate" in sys.argv:
        # MS seems to like /automate to run the class factories.
        import win32com.server.localserver
        #win32com.server.localserver.main()
        # start the server.
Beispiel #4
0
def RegisterClasses(*classes, **flags):
  quiet = 'quiet' in flags and flags['quiet']
  debugging = 'debug' in flags and flags['debug']
  for cls in classes:
    clsid = cls._reg_clsid_
    progID = _get(cls, '_reg_progid_')
    desc = _get(cls, '_reg_desc_', progID)
    spec = _get(cls, '_reg_class_spec_')
    verProgID = _get(cls, '_reg_verprogid_')
    defIcon = _get(cls, '_reg_icon_')
    threadingModel = _get(cls, '_reg_threading_', 'both')
    catids = _get(cls, '_reg_catids_', [])
    options = _get(cls, '_reg_options_', {})
    policySpec = _get(cls, '_reg_policy_spec_')
    clsctx = _get(cls, '_reg_clsctx_')
    tlb_filename = _get(cls, '_reg_typelib_filename_')
    # default to being a COM category only when not frozen.
    addPyComCat = not _get(cls, '_reg_disable_pycomcat_', pythoncom.frozen!=0)
    addnPath = None
    if debugging:
      # If the class has a debugging dispatcher specified, use it, otherwise
      # use our default dispatcher.
      dispatcherSpec = _get(cls, '_reg_debug_dispatcher_spec_')
      if dispatcherSpec is None:
        dispatcherSpec = "win32com.server.dispatcher.DefaultDebugDispatcher"
      # And remember the debugging flag as servers may wish to use it at runtime.
      debuggingDesc = "(for debugging)"
      options['Debugging'] = "1"
    else:
      dispatcherSpec = _get(cls, '_reg_dispatcher_spec_')
      debuggingDesc = ""
      options['Debugging'] = "0"

    if spec is None:
      moduleName = cls.__module__
      if moduleName == '__main__':
        # Use argv[0] to determine the module name.
        try:
         # Use the win32api to find the case-sensitive name
          moduleName = os.path.splitext(win32api.FindFiles(sys.argv[0])[0][8])[0]
        except (IndexError, win32api.error):
          # Can't find the script file - the user must explicitely set the _reg_... attribute.
          raise TypeError("Can't locate the script hosting the COM object - please set _reg_class_spec_ in your object")

      spec = moduleName + "." + cls.__name__
      # Frozen apps don't need their directory on sys.path
      if not pythoncom.frozen:
        scriptDir = os.path.split(sys.argv[0])[0]
        if not scriptDir: scriptDir = "."
        addnPath = win32api.GetFullPathName(scriptDir)

    RegisterServer(clsid, spec, desc, progID, verProgID, defIcon,
                   threadingModel, policySpec, catids, options,
                   addPyComCat, dispatcherSpec, clsctx, addnPath)
    if not quiet:
      print('Registered:', progID or spec, debuggingDesc)
    # Register the typelibrary
    if tlb_filename:
      tlb_filename = os.path.abspath(tlb_filename)
      typelib = pythoncom.LoadTypeLib(tlb_filename)
      pythoncom.RegisterTypeLib(typelib, tlb_filename)
      if not quiet:
        print('Registered type library:', tlb_filename)
  extra = flags.get('finalize_register')
  if extra:
    extra()
Beispiel #5
0
def main():
    global H**O, TYPELIB, DEBUG
    safe_console()

    if "--register" in sys.argv or "--unregister" in sys.argv:
        import pythoncom

        if TYPELIB:
            if "--register" in sys.argv:
                tlb = os.path.abspath(
                    os.path.join(INSTALL_DIR, "typelib", "wsaa.tlb"))
                print("Registering %s" % (tlb, ))
                tli = pythoncom.LoadTypeLib(tlb)
                pythoncom.RegisterTypeLib(tli, tlb)
            elif "--unregister" in sys.argv:
                k = WSAA
                pythoncom.UnRegisterTypeLib(
                    k._typelib_guid_,
                    k._typelib_version_[0],
                    k._typelib_version_[1],
                    0,
                    pythoncom.SYS_WIN32,
                )
                print("Unregistered typelib")
        import win32com.server.register

        win32com.server.register.UseCommandLine(WSAA)
    elif "/Automate" in sys.argv:
        # MS seems to like /automate to run the class factories.
        import win32com.server.localserver

        # win32com.server.localserver.main()
        # start the server.
        win32com.server.localserver.serve([WSAA._reg_clsid_])
    elif "--crear_pedido_cert" in sys.argv:
        # instanciar el helper y revisar los parámetros
        wsaa = WSAA()
        args = [arg for arg in sys.argv if not arg.startswith("--")]
        # obtengo el CUIT y lo normalizo:
        cuit = len(args) > 1 and args[1] or input("Ingrese un CUIT: ")
        cuit = "".join([c for c in cuit if c.isdigit()])
        nombre = len(args) > 2 and args[2] or "PyAfipWs"
        # consultar el padrón online de AFIP si no se especificó razón social:
        empresa = len(args) > 3 and args[3] or ""
        if not empresa:
            from .padron import PadronAFIP

            padron = PadronAFIP()
            ok = padron.Consultar(cuit)
            if ok and padron.denominacion:
                print(u"Denominación según AFIP:", padron.denominacion)
                empresa = padron.denominacion
            else:
                print(u"CUIT %s no encontrado: %s..." %
                      (cuit, padron.Excepcion))
                empresa = input("Empresa: ")
        # longitud de la clave (2048 predeterminada a partir de 8/2016)
        key_length = len(args) > 4 and args[4] or ""
        try:
            key_length = int(key_length)
        except ValueError:
            key_length = 2048
        # generar los archivos (con fecha para no pisarlo)
        ts = datetime.datetime.now().strftime("%Y%m%d%M%S")
        clave_privada = "clave_privada_%s_%s.key" % (cuit, ts)
        pedido_cert = "pedido_cert_%s_%s.csr" % (cuit, ts)
        print("Longitud clave %s (bits)" % key_length)
        wsaa.CrearClavePrivada(clave_privada, key_length)
        wsaa.CrearPedidoCertificado(cuit, empresa, nombre, pedido_cert)
        print("Se crearon los archivos:")
        print(clave_privada)
        print(pedido_cert)
        # convertir a terminación de linea windows y abrir con bloc de notas
        if sys.platform == "win32":
            txt = open(pedido_cert + ".txt", "w")
            for linea in open(pedido_cert, "r"):
                txt.write("{}".format(linea))
            txt.close()
            os.startfile(pedido_cert + ".txt")
    else:

        # Leer argumentos desde la linea de comando (si no viene tomar default)
        args = [arg for arg in sys.argv if arg.startswith("--")]
        argv = [arg for arg in sys.argv if not arg.startswith("--")]
        crt = len(argv) > 1 and argv[1] or CERT
        key = len(argv) > 2 and argv[2] or PRIVATEKEY
        service = len(argv) > 3 and argv[3] or "wsfe"
        ttl = len(argv) > 4 and int(argv[4]) or 36000
        url = len(argv) > 5 and argv[5] or WSAAURL
        wrapper = len(argv) > 6 and argv[6] or None
        cacert = len(argv) > 7 and argv[7] or CACERT
        DEBUG = "--debug" in args

        print(
            "Usando CRT=%s KEY=%s URL=%s SERVICE=%s TTL=%s" %
            (crt, key, url, service, ttl),
            file=sys.stderr,
        )

        # creo el objeto para comunicarme con el ws
        wsaa = WSAA()
        wsaa.LanzarExcepciones = True

        print("WSAA Version %s %s" % (WSAA.Version, H**O), file=sys.stderr)

        if "--proxy" in args:
            proxy = sys.argv[sys.argv.index("--proxy") + 1]
            print("Usando PROXY:", proxy, file=sys.stderr)
        else:
            proxy = None

        if "--analizar" in sys.argv:
            wsaa.AnalizarCertificado(crt)
            print(wsaa.Identidad)
            print(wsaa.Caducidad)
            print(wsaa.Emisor)
            print(wsaa.CertX509)

        ta = wsaa.Autenticar(service, crt, key, url, proxy, wrapper, cacert)
        if not ta:
            if DEBUG:
                print(wsaa.Traceback, file=sys.stderr)
            sys.exit(u"Excepcion: %s" % wsaa.Excepcion)

        else:
            print(ta)

        if wsaa.Excepcion:
            print(wsaa.Excepcion, file=sys.stderr)

        if DEBUG:
            print("Source:", wsaa.ObtenerTagXml("source"))
            print("UniqueID Time:", wsaa.ObtenerTagXml("uniqueId"))
            print("Generation Time:", wsaa.ObtenerTagXml("generationTime"))
            print("Expiration Time:", wsaa.ObtenerTagXml("expirationTime"))
            print("Expiro?", wsaa.Expirado())