Nie możesz wybrać więcej, niż 25 tematów Tematy muszą się zaczynać od litery lub cyfry, mogą zawierać myślniki ('-') i mogą mieć do 35 znaków.
 
 
 
 
 
 

395 wiersze
12 KiB

  1. # Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors
  2. # MIT License. See license.txt
  3. from __future__ import unicode_literals
  4. import frappe
  5. import os, base64, re
  6. import hashlib
  7. import mimetypes
  8. from frappe.utils import get_hook_method, get_files_path, random_string, encode, cstr, call_hook_method, cint
  9. from frappe import _
  10. from frappe import conf
  11. from copy import copy
  12. from six.moves.urllib.parse import unquote
  13. from six import text_type
  14. class MaxFileSizeReachedError(frappe.ValidationError): pass
  15. def get_file_url(file_data_name):
  16. data = frappe.db.get_value("File", file_data_name, ["file_name", "file_url"], as_dict=True)
  17. return data.file_url or data.file_name
  18. def upload():
  19. # get record details
  20. dt = frappe.form_dict.doctype
  21. dn = frappe.form_dict.docname
  22. df = frappe.form_dict.docfield
  23. file_url = frappe.form_dict.file_url
  24. filename = frappe.form_dict.filename
  25. frappe.form_dict.is_private = cint(frappe.form_dict.is_private)
  26. if not filename and not file_url:
  27. frappe.msgprint(_("Please select a file or url"),
  28. raise_exception=True)
  29. file_doc = get_file_doc()
  30. comment = {}
  31. if dt and dn:
  32. comment = frappe.get_doc(dt, dn).add_comment("Attachment",
  33. _("added {0}").format("<a href='{file_url}' target='_blank'>{file_name}</a>{icon}".format(**{
  34. "icon": ' <i class="fa fa-lock text-warning"></i>' \
  35. if file_doc.is_private else "",
  36. "file_url": file_doc.file_url.replace("#", "%23") \
  37. if file_doc.file_name else file_doc.file_url,
  38. "file_name": file_doc.file_name or file_doc.file_url
  39. })))
  40. return {
  41. "name": file_doc.name,
  42. "file_name": file_doc.file_name,
  43. "file_url": file_doc.file_url,
  44. "is_private": file_doc.is_private,
  45. "comment": comment.as_dict() if comment else {}
  46. }
  47. def get_file_doc(dt=None, dn=None, folder=None, is_private=None, df=None):
  48. '''returns File object (Document) from given parameters or form_dict'''
  49. r = frappe.form_dict
  50. if dt is None: dt = r.doctype
  51. if dn is None: dn = r.docname
  52. if df is None: df = r.docfield
  53. if folder is None: folder = r.folder
  54. if is_private is None: is_private = r.is_private
  55. if r.filedata:
  56. file_doc = save_uploaded(dt, dn, folder, is_private, df)
  57. elif r.file_url:
  58. file_doc = save_url(r.file_url, r.filename, dt, dn, folder, is_private, df)
  59. return file_doc
  60. def save_uploaded(dt, dn, folder, is_private, df=None):
  61. fname, content = get_uploaded_content()
  62. if content:
  63. return save_file(fname, content, dt, dn, folder, is_private=is_private, df=df);
  64. else:
  65. raise Exception
  66. def save_url(file_url, filename, dt, dn, folder, is_private, df=None):
  67. # if not (file_url.startswith("http://") or file_url.startswith("https://")):
  68. # frappe.msgprint("URL must start with 'http://' or 'https://'")
  69. # return None, None
  70. file_url = unquote(file_url)
  71. f = frappe.get_doc({
  72. "doctype": "File",
  73. "file_url": file_url,
  74. "file_name": filename,
  75. "attached_to_doctype": dt,
  76. "attached_to_name": dn,
  77. "attached_to_field": df,
  78. "folder": folder,
  79. "is_private": is_private
  80. })
  81. f.flags.ignore_permissions = True
  82. try:
  83. f.insert();
  84. except frappe.DuplicateEntryError:
  85. return frappe.get_doc("File", f.duplicate_entry)
  86. return f
  87. def get_uploaded_content():
  88. # should not be unicode when reading a file, hence using frappe.form
  89. if 'filedata' in frappe.form_dict:
  90. if "," in frappe.form_dict.filedata:
  91. frappe.form_dict.filedata = frappe.form_dict.filedata.rsplit(",", 1)[1]
  92. frappe.uploaded_content = base64.b64decode(frappe.form_dict.filedata)
  93. frappe.uploaded_filename = frappe.form_dict.filename
  94. return frappe.uploaded_filename, frappe.uploaded_content
  95. else:
  96. frappe.msgprint(_('No file attached'))
  97. return None, None
  98. def save_file(fname, content, dt, dn, folder=None, decode=False, is_private=0, df=None):
  99. if decode:
  100. if isinstance(content, text_type):
  101. content = content.encode("utf-8")
  102. if "," in content:
  103. content = content.split(",")[1]
  104. content = base64.b64decode(content)
  105. file_size = check_max_file_size(content)
  106. content_hash = get_content_hash(content)
  107. content_type = mimetypes.guess_type(fname)[0]
  108. fname = get_file_name(fname, content_hash[-6:])
  109. file_data = get_file_data_from_hash(content_hash, is_private=is_private)
  110. if not file_data:
  111. call_hook_method("before_write_file", file_size=file_size)
  112. write_file_method = get_hook_method('write_file', fallback=save_file_on_filesystem)
  113. file_data = write_file_method(fname, content, content_type=content_type, is_private=is_private)
  114. file_data = copy(file_data)
  115. file_data.update({
  116. "doctype": "File",
  117. "attached_to_doctype": dt,
  118. "attached_to_name": dn,
  119. "attached_to_field": df,
  120. "folder": folder,
  121. "file_size": file_size,
  122. "content_hash": content_hash,
  123. "is_private": is_private
  124. })
  125. f = frappe.get_doc(file_data)
  126. f.flags.ignore_permissions = True
  127. try:
  128. f.insert()
  129. except frappe.DuplicateEntryError:
  130. return frappe.get_doc("File", f.duplicate_entry)
  131. return f
  132. def get_file_data_from_hash(content_hash, is_private=0):
  133. for name in frappe.db.sql_list("select name from `tabFile` where content_hash=%s and is_private=%s", (content_hash, is_private)):
  134. b = frappe.get_doc('File', name)
  135. return {k:b.get(k) for k in frappe.get_hooks()['write_file_keys']}
  136. return False
  137. def save_file_on_filesystem(fname, content, content_type=None, is_private=0):
  138. fpath = write_file(content, fname, is_private)
  139. if is_private:
  140. file_url = "/private/files/{0}".format(fname)
  141. else:
  142. file_url = "/files/{0}".format(fname)
  143. return {
  144. 'file_name': os.path.basename(fpath),
  145. 'file_url': file_url
  146. }
  147. def get_max_file_size():
  148. return conf.get('max_file_size') or 10485760
  149. def check_max_file_size(content):
  150. max_file_size = get_max_file_size()
  151. file_size = len(content)
  152. if file_size > max_file_size:
  153. frappe.msgprint(_("File size exceeded the maximum allowed size of {0} MB").format(
  154. max_file_size / 1048576),
  155. raise_exception=MaxFileSizeReachedError)
  156. return file_size
  157. def write_file(content, fname, is_private=0):
  158. """write file to disk with a random name (to compare)"""
  159. file_path = get_files_path(is_private=is_private)
  160. # create directory (if not exists)
  161. frappe.create_folder(file_path)
  162. # write the file
  163. if isinstance(content, text_type):
  164. content = content.encode()
  165. with open(os.path.join(file_path.encode('utf-8'), fname.encode('utf-8')), 'wb+') as f:
  166. f.write(content)
  167. return get_files_path(fname, is_private=is_private)
  168. def remove_all(dt, dn, from_delete=False):
  169. """remove all files in a transaction"""
  170. try:
  171. for fid in frappe.db.sql_list("""select name from `tabFile` where
  172. attached_to_doctype=%s and attached_to_name=%s""", (dt, dn)):
  173. remove_file(fid, dt, dn, from_delete)
  174. except Exception as e:
  175. if e.args[0]!=1054: raise # (temp till for patched)
  176. def remove_file_by_url(file_url, doctype=None, name=None):
  177. if doctype and name:
  178. fid = frappe.db.get_value("File", {"file_url": file_url,
  179. "attached_to_doctype": doctype, "attached_to_name": name})
  180. else:
  181. fid = frappe.db.get_value("File", {"file_url": file_url})
  182. if fid:
  183. return remove_file(fid)
  184. def remove_file(fid, attached_to_doctype=None, attached_to_name=None, from_delete=False):
  185. """Remove file and File entry"""
  186. file_name = None
  187. if not (attached_to_doctype and attached_to_name):
  188. attached = frappe.db.get_value("File", fid,
  189. ["attached_to_doctype", "attached_to_name", "file_name"])
  190. if attached:
  191. attached_to_doctype, attached_to_name, file_name = attached
  192. ignore_permissions, comment = False, None
  193. if attached_to_doctype and attached_to_name and not from_delete:
  194. doc = frappe.get_doc(attached_to_doctype, attached_to_name)
  195. ignore_permissions = doc.has_permission("write") or False
  196. if frappe.flags.in_web_form:
  197. ignore_permissions = True
  198. if not file_name:
  199. file_name = frappe.db.get_value("File", fid, "file_name")
  200. comment = doc.add_comment("Attachment Removed", _("Removed {0}").format(file_name))
  201. frappe.delete_doc("File", fid, ignore_permissions=ignore_permissions)
  202. return comment
  203. def delete_file_data_content(doc, only_thumbnail=False):
  204. method = get_hook_method('delete_file_data_content', fallback=delete_file_from_filesystem)
  205. method(doc, only_thumbnail=only_thumbnail)
  206. def delete_file_from_filesystem(doc, only_thumbnail=False):
  207. """Delete file, thumbnail from File document"""
  208. if only_thumbnail:
  209. delete_file(doc.thumbnail_url)
  210. else:
  211. delete_file(doc.file_url)
  212. delete_file(doc.thumbnail_url)
  213. def delete_file(path):
  214. """Delete file from `public folder`"""
  215. if path:
  216. if ".." in path.split("/"):
  217. frappe.msgprint(_("It is risky to delete this file: {0}. Please contact your System Manager.").format(path))
  218. parts = os.path.split(path.strip("/"))
  219. if parts[0]=="files":
  220. path = frappe.utils.get_site_path("public", "files", parts[-1])
  221. else:
  222. path = frappe.utils.get_site_path("private", "files", parts[-1])
  223. path = encode(path)
  224. if os.path.exists(path):
  225. os.remove(path)
  226. def get_file(fname):
  227. """Returns [`file_name`, `content`] for given file name `fname`"""
  228. file_path = get_file_path(fname)
  229. # read the file
  230. with open(encode(file_path), 'r') as f:
  231. content = f.read()
  232. return [file_path.rsplit("/", 1)[-1], content]
  233. def get_file_path(file_name):
  234. """Returns file path from given file name"""
  235. f = frappe.db.sql("""select file_url from `tabFile`
  236. where name=%s or file_name=%s""", (file_name, file_name))
  237. if f:
  238. file_name = f[0][0]
  239. file_path = file_name
  240. if "/" not in file_path:
  241. file_path = "/files/" + file_path
  242. if file_path.startswith("/private/files/"):
  243. file_path = get_files_path(*file_path.split("/private/files/", 1)[1].split("/"), is_private=1)
  244. elif file_path.startswith("/files/"):
  245. file_path = get_files_path(*file_path.split("/files/", 1)[1].split("/"))
  246. else:
  247. frappe.throw(_("There is some problem with the file url: {0}").format(file_path))
  248. return file_path
  249. def get_content_hash(content):
  250. if isinstance(content, text_type):
  251. content = content.encode()
  252. return hashlib.md5(content).hexdigest()
  253. def get_file_name(fname, optional_suffix):
  254. # convert to unicode
  255. fname = cstr(fname)
  256. n_records = frappe.db.sql("select name from `tabFile` where file_name=%s", fname)
  257. if len(n_records) > 0 or os.path.exists(encode(get_files_path(fname))):
  258. f = fname.rsplit('.', 1)
  259. if len(f) == 1:
  260. partial, extn = f[0], ""
  261. else:
  262. partial, extn = f[0], "." + f[1]
  263. return '{partial}{suffix}{extn}'.format(partial=partial, extn=extn, suffix=optional_suffix)
  264. return fname
  265. @frappe.whitelist()
  266. def download_file(file_url):
  267. """
  268. Download file using token and REST API. Valid session or
  269. token is required to download private files.
  270. Method : GET
  271. Endpoint : frappe.utils.file_manager.download_file
  272. URL Params : file_name = /path/to/file relative to site path
  273. """
  274. file_doc = frappe.get_doc("File", {"file_url":file_url})
  275. file_doc.check_permission("read")
  276. with open(getattr(frappe.local, "site_path", None) + file_url, "rb") as fileobj:
  277. filedata = fileobj.read()
  278. frappe.local.response.filename = file_url[file_url.rfind("/")+1:]
  279. frappe.local.response.filecontent = filedata
  280. frappe.local.response.type = "download"
  281. def extract_images_from_doc(doc, fieldname):
  282. content = doc.get(fieldname)
  283. content = extract_images_from_html(doc, content)
  284. if frappe.flags.has_dataurl:
  285. doc.set(fieldname, content)
  286. def extract_images_from_html(doc, content):
  287. frappe.flags.has_dataurl = False
  288. def _save_file(match):
  289. data = match.group(1)
  290. data = data.split("data:")[1]
  291. headers, content = data.split(",")
  292. if "filename=" in headers:
  293. filename = headers.split("filename=")[-1]
  294. # decode filename
  295. if not isinstance(filename, text_type):
  296. filename = text_type(filename, 'utf-8')
  297. else:
  298. mtype = headers.split(";")[0]
  299. filename = get_random_filename(content_type=mtype)
  300. doctype = doc.parenttype if doc.parent else doc.doctype
  301. name = doc.parent or doc.name
  302. # TODO fix this
  303. file_url = save_file(filename, content, doctype, name, decode=True).get("file_url")
  304. if not frappe.flags.has_dataurl:
  305. frappe.flags.has_dataurl = True
  306. return '<img src="{file_url}"'.format(file_url=file_url)
  307. if content:
  308. content = re.sub('<img[^>]*src\s*=\s*["\'](?=data:)(.*?)["\']', _save_file, content)
  309. return content
  310. def get_random_filename(extn=None, content_type=None):
  311. if extn:
  312. if not extn.startswith("."):
  313. extn = "." + extn
  314. elif content_type:
  315. extn = mimetypes.guess_extension(content_type)
  316. return random_string(7) + (extn or "")