ScriptForgeHelper.py 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291
  1. # -*- coding: utf-8 -*-
  2. # Copyright 2019-2020 Jean-Pierre LEDURE, Jean-François NIFENECKER, 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. """
  21. import getpass
  22. import os
  23. import platform
  24. import hashlib
  25. import filecmp
  26. import webbrowser
  27. import json
  28. class _Singleton(type):
  29. """
  30. A Singleton design pattern
  31. Credits: « Python in a Nutshell » by Alex Martelli, O'Reilly
  32. """
  33. instances = {}
  34. def __call__(cls, *args, **kwargs):
  35. if cls not in cls.instances:
  36. cls.instances[cls] = super(_Singleton, cls).__call__(*args, **kwargs)
  37. return cls.instances[cls]
  38. # #################################################################
  39. # Dictionary service
  40. # #################################################################
  41. def _SF_Dictionary__ConvertToJson(propval, indent = None) -> str:
  42. # used by Dictionary.ConvertToJson() Basic method
  43. """
  44. Given an array of PropertyValues as argument, convert it to a JSON string
  45. """
  46. # Array of property values => Dict(ionary) => JSON
  47. pvDict = {}
  48. for pv in propval:
  49. pvDict[pv.Name] = pv.Value
  50. return json.dumps(pvDict, indent=indent, skipkeys=True)
  51. def _SF_Dictionary__ImportFromJson(jsonstr: str): # used by Dictionary.ImportFromJson() Basic method
  52. """
  53. Given a JSON string as argument, convert it to a list of tuples (name, value)
  54. The value must not be a (sub)dict. This doesn't pass the python-basic bridge.
  55. """
  56. # JSON => Dictionary => Array of tuples/lists
  57. dico = json.loads(jsonstr)
  58. result = []
  59. for key in iter(dico):
  60. value = dico[key]
  61. item = value
  62. if isinstance(value, dict): # check that first level is not itself a (sub)dict
  63. item = None
  64. elif isinstance(value, list): # check every member of the list is not a (sub)dict
  65. for i in range(len(value)):
  66. if isinstance(value[i], dict): value[i] = None
  67. result.append((key, item))
  68. return result
  69. # #################################################################
  70. # FileSystem service
  71. # #################################################################
  72. def _SF_FileSystem__CompareFiles(filename1: str, filename2: str, comparecontents=True) -> bool:
  73. # used by SF_FileSystem.CompareFiles() Basic method
  74. """
  75. Compare the 2 files, returning True if they seem equal, False otherwise.
  76. By default, only their signatures (modification time, ...) are compared.
  77. When comparecontents == True, their contents are compared.
  78. """
  79. try:
  80. return filecmp.cmp(filename1, filename2, not comparecontents)
  81. except Exception:
  82. return False
  83. def _SF_FileSystem__GetFilelen(systemfilepath: str) -> str: # used by SF_FileSystem.GetFilelen() Basic method
  84. return str(os.path.getsize(systemfilepath))
  85. def _SF_FileSystem__HashFile(filename: str, algorithm: str) -> str: # used by SF_FileSystem.HashFile() Basic method
  86. """
  87. Hash a given file with the given hashing algorithm
  88. cfr. https://www.pythoncentral.io/hashing-files-with-python/
  89. Example
  90. hash = _SF_FileSystem__HashFile('myfile.txt','MD5')
  91. """
  92. algo = algorithm.lower()
  93. try:
  94. if algo in hashlib.algorithms_guaranteed:
  95. BLOCKSIZE = 65535 # Provision for large size files
  96. if algo == 'md5':
  97. hasher = hashlib.md5()
  98. elif algo == 'sha1':
  99. hasher = hashlib.sha1()
  100. elif algo == 'sha224':
  101. hasher = hashlib.sha224()
  102. elif algo == 'sha256':
  103. hasher = hashlib.sha256()
  104. elif algo == 'sha384':
  105. hasher = hashlib.sha384()
  106. elif algo == 'sha512':
  107. hasher = hashlib.sha512()
  108. else:
  109. return ''
  110. with open(filename, 'rb') as file: # open in binary mode
  111. buffer = file.read(BLOCKSIZE)
  112. while len(buffer) > 0:
  113. hasher.update(buffer)
  114. buffer = file.read(BLOCKSIZE)
  115. return hasher.hexdigest()
  116. else:
  117. return ''
  118. except Exception:
  119. return ''
  120. # #################################################################
  121. # Platform service
  122. # #################################################################
  123. def _SF_Platform(propertyname: str): # used by SF_Platform Basic module
  124. """
  125. Switch between SF_Platform properties (read the documentation about the ScriptForge.Platform service)
  126. """
  127. pf = Platform()
  128. if propertyname == 'Architecture':
  129. return pf.Architecture
  130. elif propertyname == 'ComputerName':
  131. return pf.ComputerName
  132. elif propertyname == 'CPUCount':
  133. return pf.CPUCount
  134. elif propertyname == 'CurrentUser':
  135. return pf.CurrentUser
  136. elif propertyname == 'Machine':
  137. return pf.Machine
  138. elif propertyname == 'OSName':
  139. return pf.OSName
  140. elif propertyname == 'OSPlatform':
  141. return pf.OSPlatform
  142. elif propertyname == 'OSRelease':
  143. return pf.OSRelease
  144. elif propertyname == 'OSVersion':
  145. return pf.OSVersion
  146. elif propertyname == 'Processor':
  147. return pf.Processor
  148. else:
  149. return None
  150. class Platform(object, metaclass = _Singleton):
  151. @property
  152. def Architecture(self): return platform.architecture()[0]
  153. @property # computer's network name
  154. def ComputerName(self): return platform.node()
  155. @property # number of CPU's
  156. def CPUCount(self): return os.cpu_count()
  157. @property
  158. def CurrentUser(self):
  159. try:
  160. return getpass.getuser()
  161. except Exception:
  162. return ''
  163. @property # machine type e.g. 'i386'
  164. def Machine(self): return platform.machine()
  165. @property # system/OS name e.g. 'Darwin', 'Java', 'Linux', ...
  166. def OSName(self): return platform.system().replace('Darwin', 'macOS')
  167. @property # underlying platform e.g. 'Windows-10-...'
  168. def OSPlatform(self): return platform.platform(aliased = True)
  169. @property # system's release e.g. '2.2.0'
  170. def OSRelease(self): return platform.release()
  171. @property # system's version
  172. def OSVersion(self): return platform.version()
  173. @property # real processor name e.g. 'amdk'
  174. def Processor(self): return platform.processor()
  175. # #################################################################
  176. # Session service
  177. # #################################################################
  178. def _SF_Session__OpenURLInBrowser(url: str): # Used by SF_Session.OpenURLInBrowser() Basic method
  179. """
  180. Display url using the default browser
  181. """
  182. try:
  183. webbrowser.open(url, new = 2)
  184. finally:
  185. return None
  186. # #################################################################
  187. # String service
  188. # #################################################################
  189. def _SF_String__HashStr(string: str, algorithm: str) -> str: # used by SF_String.HashStr() Basic method
  190. """
  191. Hash a given UTF-8 string with the given hashing algorithm
  192. Example
  193. hash = _SF_String__HashStr('This is a UTF-8 encoded string.','MD5')
  194. """
  195. algo = algorithm.lower()
  196. try:
  197. if algo in hashlib.algorithms_guaranteed:
  198. ENCODING = 'utf-8'
  199. bytestring = string.encode(ENCODING) # Hashing functions expect bytes, not strings
  200. if algo == 'md5':
  201. hasher = hashlib.md5(bytestring)
  202. elif algo == 'sha1':
  203. hasher = hashlib.sha1(bytestring)
  204. elif algo == 'sha224':
  205. hasher = hashlib.sha224(bytestring)
  206. elif algo == 'sha256':
  207. hasher = hashlib.sha256(bytestring)
  208. elif algo == 'sha384':
  209. hasher = hashlib.sha384(bytestring)
  210. elif algo == 'sha512':
  211. hasher = hashlib.sha512(bytestring)
  212. else:
  213. return ''
  214. return hasher.hexdigest()
  215. else:
  216. return ''
  217. except Exception:
  218. return ''
  219. if __name__ == "__main__":
  220. print(_SF_Platform('Architecture'))
  221. print(_SF_Platform('ComputerName'))
  222. print(_SF_Platform('CPUCount'))
  223. print(_SF_Platform('CurrentUser'))
  224. print(_SF_Platform('Machine'))
  225. print(_SF_Platform('OSName'))
  226. print(_SF_Platform('OSPlatform'))
  227. print(_SF_Platform('OSRelease'))
  228. print(_SF_Platform('OSVersion'))
  229. print(_SF_Platform('Processor'))
  230. #
  231. print(hashlib.algorithms_guaranteed)
  232. print(_SF_FileSystem__HashFile('/opt/libreoffice6.4/program/libbootstraplo.so', 'md5'))
  233. print(_SF_FileSystem__HashFile('/opt/libreoffice6.4/share/Scripts/python/Capitalise.py', 'sha512'))
  234. #
  235. print(_SF_String__HashStr('œ∑¡™£¢∞§¶•ªº–≠œ∑´®†¥¨ˆøπ“‘åß∂ƒ©˙∆˚¬', 'MD5')) # 616eb9c513ad07cd02924b4d285b9987
  236. #
  237. # _SF_Session__OpenURLInBrowser('https://docs.python.org/3/library/webbrowser.html')
  238. #
  239. js = """
  240. {"firstName": "John","lastName": "Smith","isAlive": true,"age": 27,
  241. "address": {"streetAddress": "21 2nd Street","city": "New York","state": "NY","postalCode": "10021-3100"},
  242. "phoneNumbers": [{"type": "home","number": "212 555-1234"},{"type": "office","number": "646 555-4567"}],
  243. "children": ["Q", "M", "G", "T"],"spouse": null}
  244. """
  245. arr = _SF_Dictionary__ImportFromJson(js)
  246. print(arr)