ScriptForgeHelper.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330
  1. # -*- coding: utf-8 -*-
  2. # Copyright 2019-2022 Jean-Pierre LEDURE, Rafael LIMA, Alain ROMEDENNE
  3. # ======================================================================================================================
  4. # === The ScriptForge library and its associated libraries are part of the LibreOffice project. ===
  5. # === Full documentation is available on https://help.libreoffice.org/ ===
  6. # ======================================================================================================================
  7. # ScriptForge is distributed in the hope that it will be useful,
  8. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  9. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
  10. # ScriptForge is free software; you can redistribute it and/or modify it under the terms of either (at your option):
  11. # 1) The Mozilla Public License, v. 2.0. If a copy of the MPL was not
  12. # distributed with this file, you can obtain one at http://mozilla.org/MPL/2.0/ .
  13. # 2) The GNU Lesser General Public License as published by
  14. # the Free Software Foundation, either version 3 of the License, or
  15. # (at your option) any later version. If a copy of the LGPL was not
  16. # distributed with this file, see http://www.gnu.org/licenses/ .
  17. """
  18. Collection of Python helper functions called from the ScriptForge Basic libraries
  19. to execute specific services that are not or not easily available from Basic directly.
  20. When relevant, the methods present in the ScripForge Python module might call the
  21. functions below for compatibility reasons.
  22. """
  23. import getpass
  24. import os
  25. import platform
  26. import hashlib
  27. import filecmp
  28. import webbrowser
  29. import json
  30. class _Singleton(type):
  31. """
  32. A Singleton design pattern
  33. Credits: « Python in a Nutshell » by Alex Martelli, O'Reilly
  34. """
  35. instances = {}
  36. def __call__(cls, *args, **kwargs):
  37. if cls not in cls.instances:
  38. cls.instances[cls] = super(_Singleton, cls).__call__(*args, **kwargs)
  39. return cls.instances[cls]
  40. # #################################################################
  41. # Dictionary service
  42. # #################################################################
  43. def _SF_Dictionary__ConvertToJson(propval, indent = None) -> str:
  44. # used by Dictionary.ConvertToJson() Basic method
  45. """
  46. Given an array of PropertyValues as argument, convert it to a JSON string
  47. """
  48. # Array of property values => Dict(ionary) => JSON
  49. pvDict = {}
  50. for pv in propval:
  51. pvDict[pv.Name] = pv.Value
  52. return json.dumps(pvDict, indent=indent, skipkeys=True)
  53. def _SF_Dictionary__ImportFromJson(jsonstr: str): # used by Dictionary.ImportFromJson() Basic method
  54. """
  55. Given a JSON string as argument, convert it to a list of tuples (name, value)
  56. The value must not be a (sub)dict. This doesn't pass the python-basic bridge.
  57. """
  58. # JSON => Dictionary => Array of tuples/lists
  59. dico = json.loads(jsonstr)
  60. result = []
  61. for key in iter(dico):
  62. value = dico[key]
  63. item = value
  64. if isinstance(value, dict): # check that first level is not itself a (sub)dict
  65. item = None
  66. elif isinstance(value, list): # check every member of the list is not a (sub)dict
  67. for i in range(len(value)):
  68. if isinstance(value[i], dict): value[i] = None
  69. result.append((key, item))
  70. return result
  71. # #################################################################
  72. # Exception service
  73. # #################################################################
  74. def _SF_Exception__PythonPrint(string: str) -> bool:
  75. # used by SF_Exception.PythonPrint() Basic method
  76. """
  77. Write the argument to stdout.
  78. If the APSO shell console is active, the argument will be displayed in the console window
  79. """
  80. print(string)
  81. return True
  82. # #################################################################
  83. # FileSystem service
  84. # #################################################################
  85. def _SF_FileSystem__CompareFiles(filename1: str, filename2: str, comparecontents=True) -> bool:
  86. # used by SF_FileSystem.CompareFiles() Basic method
  87. """
  88. Compare the 2 files, returning True if they seem equal, False otherwise.
  89. By default, only their signatures (modification time, ...) are compared.
  90. When comparecontents == True, their contents are compared.
  91. """
  92. try:
  93. return filecmp.cmp(filename1, filename2, not comparecontents)
  94. except Exception:
  95. return False
  96. def _SF_FileSystem__GetFilelen(systemfilepath: str) -> str: # used by SF_FileSystem.GetFilelen() Basic method
  97. return str(os.path.getsize(systemfilepath))
  98. def _SF_FileSystem__HashFile(filename: str, algorithm: str) -> str: # used by SF_FileSystem.HashFile() Basic method
  99. """
  100. Hash a given file with the given hashing algorithm
  101. cfr. https://www.pythoncentral.io/hashing-files-with-python/
  102. Example
  103. hash = _SF_FileSystem__HashFile('myfile.txt','MD5')
  104. """
  105. algo = algorithm.lower()
  106. try:
  107. if algo in hashlib.algorithms_guaranteed:
  108. BLOCKSIZE = 65535 # Provision for large size files
  109. if algo == 'md5':
  110. hasher = hashlib.md5()
  111. elif algo == 'sha1':
  112. hasher = hashlib.sha1()
  113. elif algo == 'sha224':
  114. hasher = hashlib.sha224()
  115. elif algo == 'sha256':
  116. hasher = hashlib.sha256()
  117. elif algo == 'sha384':
  118. hasher = hashlib.sha384()
  119. elif algo == 'sha512':
  120. hasher = hashlib.sha512()
  121. else:
  122. return ''
  123. with open(filename, 'rb') as file: # open in binary mode
  124. buffer = file.read(BLOCKSIZE)
  125. while len(buffer) > 0:
  126. hasher.update(buffer)
  127. buffer = file.read(BLOCKSIZE)
  128. return hasher.hexdigest()
  129. else:
  130. return ''
  131. except Exception:
  132. return ''
  133. def _SF_FileSystem__Normalize(systemfilepath: str) -> str:
  134. # used by SF_FileSystem.Normalize() Basic method
  135. """
  136. Normalize a pathname by collapsing redundant separators and up-level references so that
  137. A//B, A/B/, A/./B and A/foo/../B all become A/B.
  138. On Windows, it converts forward slashes to backward slashes.
  139. """
  140. return os.path.normpath(systemfilepath)
  141. # #################################################################
  142. # Platform service
  143. # #################################################################
  144. def _SF_Platform(propertyname: str): # used by SF_Platform Basic module
  145. """
  146. Switch between SF_Platform properties (read the documentation about the ScriptForge.Platform service)
  147. """
  148. pf = Platform()
  149. if propertyname == 'Architecture':
  150. return pf.Architecture
  151. elif propertyname == 'ComputerName':
  152. return pf.ComputerName
  153. elif propertyname == 'CPUCount':
  154. return pf.CPUCount
  155. elif propertyname == 'CurrentUser':
  156. return pf.CurrentUser
  157. elif propertyname == 'Machine':
  158. return pf.Machine
  159. elif propertyname == 'OSName':
  160. return pf.OSName
  161. elif propertyname == 'OSPlatform':
  162. return pf.OSPlatform
  163. elif propertyname == 'OSRelease':
  164. return pf.OSRelease
  165. elif propertyname == 'OSVersion':
  166. return pf.OSVersion
  167. elif propertyname == 'Processor':
  168. return pf.Processor
  169. elif propertyname == 'PythonVersion':
  170. return pf.PythonVersion
  171. else:
  172. return None
  173. class Platform(object, metaclass = _Singleton):
  174. @property
  175. def Architecture(self): return platform.architecture()[0]
  176. @property # computer's network name
  177. def ComputerName(self): return platform.node()
  178. @property # number of CPU's
  179. def CPUCount(self): return os.cpu_count()
  180. @property
  181. def CurrentUser(self):
  182. try:
  183. return getpass.getuser()
  184. except Exception:
  185. return ''
  186. @property # machine type e.g. 'i386'
  187. def Machine(self): return platform.machine()
  188. @property # system/OS name e.g. 'Darwin', 'Java', 'Linux', ...
  189. def OSName(self): return platform.system().replace('Darwin', 'macOS')
  190. @property # underlying platform e.g. 'Windows-10-...'
  191. def OSPlatform(self): return platform.platform(aliased = True)
  192. @property # system's release e.g. '2.2.0'
  193. def OSRelease(self): return platform.release()
  194. @property # system's version
  195. def OSVersion(self): return platform.version()
  196. @property # real processor name e.g. 'amdk'
  197. def Processor(self): return platform.processor()
  198. @property # Python major.minor.patchlevel
  199. def PythonVersion(self): return 'Python ' + platform.python_version()
  200. # #################################################################
  201. # Session service
  202. # #################################################################
  203. def _SF_Session__OpenURLInBrowser(url: str): # Used by SF_Session.OpenURLInBrowser() Basic method
  204. """
  205. Display url using the default browser
  206. """
  207. try:
  208. webbrowser.open(url, new = 2)
  209. finally:
  210. return None
  211. # #################################################################
  212. # String service
  213. # #################################################################
  214. def _SF_String__HashStr(string: str, algorithm: str) -> str: # used by SF_String.HashStr() Basic method
  215. """
  216. Hash a given UTF-8 string with the given hashing algorithm
  217. Example
  218. hash = _SF_String__HashStr('This is a UTF-8 encoded string.','MD5')
  219. """
  220. algo = algorithm.lower()
  221. try:
  222. if algo in hashlib.algorithms_guaranteed:
  223. ENCODING = 'utf-8'
  224. bytestring = string.encode(ENCODING) # Hashing functions expect bytes, not strings
  225. if algo == 'md5':
  226. hasher = hashlib.md5(bytestring)
  227. elif algo == 'sha1':
  228. hasher = hashlib.sha1(bytestring)
  229. elif algo == 'sha224':
  230. hasher = hashlib.sha224(bytestring)
  231. elif algo == 'sha256':
  232. hasher = hashlib.sha256(bytestring)
  233. elif algo == 'sha384':
  234. hasher = hashlib.sha384(bytestring)
  235. elif algo == 'sha512':
  236. hasher = hashlib.sha512(bytestring)
  237. else:
  238. return ''
  239. return hasher.hexdigest()
  240. else:
  241. return ''
  242. except Exception:
  243. return ''
  244. # #################################################################
  245. # lists the scripts, that shall be visible inside the Basic/Python IDE
  246. # #################################################################
  247. g_exportedScripts = ()
  248. if __name__ == "__main__":
  249. print(_SF_Platform('Architecture'))
  250. print(_SF_Platform('ComputerName'))
  251. print(_SF_Platform('CPUCount'))
  252. print(_SF_Platform('CurrentUser'))
  253. print(_SF_Platform('Machine'))
  254. print(_SF_Platform('OSName'))
  255. print(_SF_Platform('OSPlatform'))
  256. print(_SF_Platform('OSRelease'))
  257. print(_SF_Platform('OSVersion'))
  258. print(_SF_Platform('Processor'))
  259. print(_SF_Platform('PythonVersion'))
  260. #
  261. print(hashlib.algorithms_guaranteed)
  262. print(_SF_FileSystem__HashFile('/opt/libreoffice7.3/program/libbootstraplo.so', 'md5'))
  263. print(_SF_FileSystem__HashFile('/opt/libreoffice7.3/share/Scripts/python/Capitalise.py', 'sha512'))
  264. print(_SF_FileSystem__Normalize('A/foo/../B/C/./D//E'))
  265. #
  266. print(_SF_String__HashStr('œ∑¡™£¢∞§¶•ªº–≠œ∑´®†¥¨ˆøπ“‘åß∂ƒ©˙∆˚¬', 'MD5')) # 616eb9c513ad07cd02924b4d285b9987
  267. #
  268. # _SF_Session__OpenURLInBrowser('https://docs.python.org/3/library/webbrowser.html')
  269. #
  270. js = """
  271. {"firstName": "John","lastName": "Smith","isAlive": true,"age": 27,
  272. "address": {"streetAddress": "21 2nd Street","city": "New York","state": "NY","postalCode": "10021-3100"},
  273. "phoneNumbers": [{"type": "home","number": "212 555-1234"},{"type": "office","number": "646 555-4567"}],
  274. "children": ["Q", "M", "G", "T"],"spouse": null}
  275. """
  276. arr = _SF_Dictionary__ImportFromJson(js)
  277. print(arr)