Obter informação da sessão

Para computar o perfil do usuário do LibreOffice e os caminhos do arquivo do sistema de módulos compartilhados, pode-se executar caminhos com Python e com a linguagem Basic. Locais de scripts BeanShell, Java, JavaScript e Python podem ser derivados dessas informações.

Exemplos:

Com o interpretador Python

>>> from <the_module> import Session

>>> print(Session.SharedPythonScripts()) # método estático

>>> print(Session().UserName) # propriedade do objeto

>>> input(Session().UserProfile) # propriedade do objeto

A partir do menu Ferramentas – Macros - Executar Macro.


        from <the_module> import Session
            
        def demo_session():
            import screen_io as ui
            ui.MsgBox(Session.Share(),title='Installation Share')  # método estático
            ui.Print(Session.SharedPythonScripts())  # método estático
            s = Session()  # criação de instância
            ui.MsgBox(s.UserName,title='Hello')  # propriedade do objeto
            ui.Print(s.UserPythonScripts)  # propriedade do objeto
            
        g_exportedScripts = (demo_session,)  # macros públicas
    

Com LibreOffice Basic


        Sub Session_example()
            Dim s As New Session ' instance of Session class
            Print "Local de scripts compartilhados:", s.SharedScripts
            MsgBox s.UserName,,"Olá"
            Print s.UserScripts, Chr(13), s.UserPythonScripts
        End Sub ' Session_example
    

Mediante COM/OLE e linguagem Visual Basic Scripting.


        'O service manager sempre é o ponto de entrada
        ' Se não houver uma aplicação office executando, inicie-a
        Set sm = WScript.CreateObject("com.sun.star.ServiceManager")
        ' O serviço PathSubstitution exibe informações a inferir
        ' Locais de <UserProfile|Share>/Scripts/python
        Set obj = sm.createInstance("com.sun.star.util.PathSubstitution")
            
        MsgBox CreateObject("WScript.Network").UserName,, "Hello"
        user = obj.getSubstituteVariableValue("$(user)")
        MsgBox user & "/Scripts",, "User scripts location"
        libO = Replace(obj.getSubstituteVariableValue("$(inst)"), "program/..", "Share")
        MsgBox libO & "/Scripts",, "Shared scripts location"
    

Classe Session de Python:


        import getpass, os, os.path, uno
            
        class Session():
            @staticmethod
            def substitute(var_name):
                ctx = uno.getComponentContext()
                ps = ctx.getServiceManager().createInstanceWithContext(
                    'com.sun.star.util.PathSubstitution', ctx)
                return ps.getSubstituteVariableValue(var_name)
            @staticmethod
            def Share():
                inst = uno.fileUrlToSystemPath(Session.substitute("$(prog)"))
                return os.path.normpath(inst.replace('program', "Share"))
            @staticmethod
            def SharedScripts():
                return ''.join([Session.Share(), os.sep, "Scripts"])
            @staticmethod
            def SharedPythonScripts():
                return ''.join([Session.SharedScripts(), os.sep, 'python'])
            @property  # alternativa à variável '$(username)'
            def UserName(self): return getpass.getuser()
            @property
            def UserProfile(self):
                return uno.fileUrlToSystemPath(Session.substitute("$(user)"))
            @property
            def UserScripts(self):
                return ''.join([self.UserProfile, os.sep, 'Scripts'])
            @property
            def UserPythonScripts(self):
                return ''.join([self.UserScripts, os.sep, "python"])
    
note

Diferente do Basic, a normalização dos nomes de caminho é feita dentro da classe Session do Python


Classe Session do LibreOffice Basic:


        Option Explicit
        Option Compatible
        Option ClassModule
            
        Private _ps As Object ' membro privado
            
        Private Sub Class_Initialize()
            GlobalScope.BasicLibraries.LoadLibrary("Tools")
            Set _ps = CreateUnoService("com.sun.star.util.PathSubstitution")
        End Sub ' construtor
            
        Private Sub Class_Terminate()
            _ps = Nothing
        End Sub ' destrutor
            
        Public Property Get SharedScripts() As String
            Dim inst As String, shr As String
            inst = ConvertFromURL(_ps.getSubstituteVariableValue("$(prog)"))
            shr = Tools.Strings.ReplaceString(inst,"Share","program")
            SharedScripts = shr & GetPathSeparator() &"Scripts"
        End Property ' Session.sharedScripts
            
        Public Property Get SharedPythonScripts() As String
            sharedPythonScripts = sharedScripts() & GetPathSeparator() &"python"
        End Property ' Session.sharedPythonScripts
            
        Public Property Get UserName() As String ' nome da conta do usuário
            userName = _ps.getSubstituteVariableValue("$(username)")
        End Property ' Session.userName
            
        Public Property Get UserProfile() As String ' caminho do perfil do usuário no sistema
            userProfile = ConvertFromURL(_ps.getSubstituteVariableValue("$(user)"))
        End Property ' Session.userProfile
            
        Public Property Get UserScripts() As String ' Caminho dos script do usuário no sistema
            userScripts = userProfile() & GetPathSeparator() &"Scripts"
        End Property ' Session.userScripts
            
        Public Property Get UserPythonScripts() As String ' Caminho dos script Python do usuário no sistema
            userPythonScripts = userScripts() & GetPathSeparator() &"python"
        End Property ' Session.userPythonScripts
    

♥ Doe para nosso projeto! ♥