FileAccess.py 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226
  1. #
  2. # This file is part of the LibreOffice project.
  3. #
  4. # This Source Code Form is subject to the terms of the Mozilla Public
  5. # License, v. 2.0. If a copy of the MPL was not distributed with this
  6. # file, You can obtain one at http://mozilla.org/MPL/2.0/.
  7. #
  8. # This file incorporates work covered by the following license notice:
  9. #
  10. # Licensed to the Apache Software Foundation (ASF) under one or more
  11. # contributor license agreements. See the NOTICE file distributed
  12. # with this work for additional information regarding copyright
  13. # ownership. The ASF licenses this file to you under the Apache
  14. # License, Version 2.0 (the "License"); you may not use this file
  15. # except in compliance with the License. You may obtain a copy of
  16. # the License at http://www.apache.org/licenses/LICENSE-2.0 .
  17. #
  18. import traceback
  19. from os import sep as FileSeparator
  20. '''
  21. This class delivers static convenience methods
  22. to use with ucb SimpleFileAccess service.
  23. You can also instantiate the class, to encapsulate
  24. some functionality of SimpleFileAccess. The instance
  25. keeps a reference to an XSimpleFileAccess and an
  26. XFileIdentifierConverter, saves the permanent
  27. overhead of querying for those interfaces, and delivers
  28. convenience methods for using them.
  29. These Convenience methods include mainly Exception-handling.
  30. '''
  31. class FileAccess(object):
  32. def __init__(self, xmsf):
  33. #get the file identifier converter
  34. self.filenameConverter = xmsf.createInstance(
  35. "com.sun.star.ucb.FileContentProvider")
  36. self.xInterface = xmsf.createInstance(
  37. "com.sun.star.ucb.SimpleFileAccess")
  38. @classmethod
  39. def deleteLastSlashfromUrl(self, _sPath):
  40. if _sPath.endswith("/"):
  41. return _sPath[:-1]
  42. else:
  43. return _sPath
  44. '''
  45. Further information on arguments value see in OO Developer Guide,
  46. chapter 6.2.7
  47. @param xMSF
  48. @param sPath
  49. @param xSimpleFileAccess
  50. @return the respective path of the office application.
  51. A probable following "/" at the end is trimmed.
  52. '''
  53. @classmethod
  54. def getOfficePath(self, xMSF, sPath, xSimpleFileAccess):
  55. try:
  56. ResultPath = ""
  57. xInterface = xMSF.createInstance("com.sun.star.util.PathSettings")
  58. ResultPath = str(getattr(xInterface, sPath))
  59. ResultPath = self.deleteLastSlashfromUrl(ResultPath)
  60. return ResultPath
  61. except Exception:
  62. traceback.print_exc()
  63. return ""
  64. @classmethod
  65. def getFolderTitles(self, xMSF, FilterName, FolderName, resDict=None):
  66. #Returns and ordered dict containing the template's name and path
  67. locLayoutFiles = []
  68. try:
  69. xDocInterface = xMSF.createInstance(
  70. "com.sun.star.document.DocumentProperties")
  71. xInterface = xMSF.createInstance(
  72. "com.sun.star.ucb.SimpleFileAccess")
  73. nameList = xInterface.getFolderContents(FolderName, False)
  74. if FilterName is None or FilterName == "":
  75. FilterName = None
  76. else:
  77. FilterName += "-"
  78. locLayoutDict = {}
  79. for i in nameList:
  80. fileName = self.getFilename(i)
  81. if FilterName is None or fileName.startswith(FilterName):
  82. xDocInterface.loadFromMedium(i, tuple())
  83. if resDict is None:
  84. title = xDocInterface.Title
  85. else:
  86. if xDocInterface.Title in resDict:
  87. # localise string at runtime
  88. title = resDict[xDocInterface.Title]
  89. else:
  90. title = xDocInterface.Title
  91. locLayoutDict[title] = i
  92. #sort the dictionary and create a list containing the
  93. #keys list and the values list
  94. keysList = sorted(locLayoutDict.keys())
  95. valuesList= []
  96. for i in keysList:
  97. valuesList.append(locLayoutDict[i])
  98. locLayoutFiles.append(keysList)
  99. locLayoutFiles.append(valuesList)
  100. except Exception:
  101. traceback.print_exc()
  102. return locLayoutFiles
  103. @classmethod
  104. def getTitle(self, xMSF, _sFile):
  105. sTitle = ""
  106. try:
  107. xDocInterface = xMSF.createInstance(
  108. "com.sun.star.document.DocumentProperties")
  109. noArgs = []
  110. xDocInterface.loadFromMedium(_sFile, noArgs)
  111. sTitle = xDocInterface.getTitle()
  112. except Exception:
  113. traceback.print_exc()
  114. return sTitle
  115. def getPath(self, parentURL, childURL):
  116. string = ""
  117. if childURL is not None and childURL != "":
  118. string = "/" + childURL
  119. return self.filenameConverter.getSystemPathFromFileURL(
  120. parentURL + string)
  121. def copy(self, source, target):
  122. try:
  123. self.xInterface.copy(source, target)
  124. return True
  125. except Exception:
  126. traceback.print_exc()
  127. return False
  128. def exists(self, filename, default):
  129. try:
  130. return self.xInterface.exists(filename)
  131. except Exception:
  132. traceback.print_exc()
  133. return default
  134. def delete(self, filename):
  135. try:
  136. self.xInterface.kill(filename)
  137. return True
  138. except Exception:
  139. traceback.print_exc()
  140. return False
  141. # lists the files in a given directory
  142. # @param dir
  143. # @param includeFolders
  144. # @return
  145. def listFiles(self, folder, includeFolders):
  146. try:
  147. return self.xInterface.getFolderContents(folder, includeFolders)
  148. except Exception:
  149. traceback.print_exc()
  150. return [""]
  151. def getSize(self, url):
  152. try:
  153. return self.xInterface.getSize(url)
  154. except Exception:
  155. traceback.print_exc()
  156. return -1
  157. def getURL(self, parentURL, childPath):
  158. if len(childPath) > 0 and childPath[0] == "/":
  159. path = parentURL + childPath
  160. else:
  161. path = parentURL + "/" + childPath
  162. return path
  163. @classmethod
  164. def getFilename(self, path, pathSeparator = "/"):
  165. return path.split(pathSeparator)[-1]
  166. '''
  167. if the path points to file, gives the directory in which the file is.
  168. '''
  169. @classmethod
  170. def getParentDir(self, url):
  171. while url[-1] == "/":
  172. url = url[:-1]
  173. return url[:url.rfind("/")]
  174. @classmethod
  175. def connectURLs(self, urlFolder, urlFilename):
  176. stringFolder = ""
  177. stringFileName = urlFilename
  178. if not urlFolder.endswith("/"):
  179. stringFolder = "/"
  180. if urlFilename.startswith("/"):
  181. stringFileName = urlFilename[1:]
  182. return urlFolder + stringFolder + stringFileName
  183. # @param filename
  184. # @return the extension of the given filename.
  185. @classmethod
  186. def getExtension(self, filename):
  187. p = filename.find(".")
  188. if (p == -1):
  189. return ""
  190. else:
  191. while (True):
  192. filename = filename[(p+1):]
  193. p = filename.find(".")
  194. if (p == -1):
  195. break
  196. return filename
  197. @classmethod
  198. def filename(self, name, ext, i):
  199. return name + ("" if (i == 0) else str(i)) + ("" if (ext == "") else ("." + ext))