選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。
 
 
 
 
 
 

202 行
5.8 KiB

  1. # Copyright (c) 2012 Web Notes Technologies Pvt Ltd (http://erpnext.com)
  2. #
  3. # MIT License (MIT)
  4. #
  5. # Permission is hereby granted, free of charge, to any person obtaining a
  6. # copy of this software and associated documentation files (the "Software"),
  7. # to deal in the Software without restriction, including without limitation
  8. # the rights to use, copy, modify, merge, publish, distribute, sublicense,
  9. # and/or sell copies of the Software, and to permit persons to whom the
  10. # Software is furnished to do so, subject to the following conditions:
  11. #
  12. # The above copyright notice and this permission notice shall be included in
  13. # all copies or substantial portions of the Software.
  14. #
  15. # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
  16. # INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
  17. # PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
  18. # HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
  19. # CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE
  20. # OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  21. #
  22. from __future__ import unicode_literals
  23. import webnotes
  24. import os, conf
  25. from webnotes.utils import cstr, get_path
  26. from webnotes import _
  27. class MaxFileSizeReachedError(webnotes.ValidationError): pass
  28. def upload():
  29. # get record details
  30. dt = webnotes.form_dict.doctype
  31. dn = webnotes.form_dict.docname
  32. at_id = webnotes.form_dict.at_id
  33. file_url = webnotes.form_dict.file_url
  34. filename = webnotes.form_dict.filename
  35. if not filename and not file_url:
  36. webnotes.msgprint(_("Please select a file or url"),
  37. raise_exception=True)
  38. # save
  39. if filename:
  40. fid, fname = save_uploaded(dt, dn)
  41. elif file_url:
  42. fid, fname = save_url(file_url, dt, dn)
  43. if fid:
  44. return fid
  45. def save_uploaded(dt, dn):
  46. fname, content = get_uploaded_content()
  47. if content:
  48. fid = save_file(fname, content, dt, dn)
  49. return fid, fname
  50. else:
  51. raise Exception
  52. def save_url(file_url, dt, dn):
  53. if not (file_url.startswith("http://") or file_url.startswith("https://")):
  54. webnotes.msgprint("URL must start with 'http://' or 'https://'")
  55. return None, None
  56. f = webnotes.doc("File Data")
  57. f.file_url = file_url
  58. f.file_name = file_url.split('/')[-1]
  59. f.attached_to_doctype = dt
  60. f.attached_to_name = dn
  61. f.save(new=1)
  62. return f.name, file_url
  63. def get_uploaded_content():
  64. # should not be unicode when reading a file, hence using webnotes.form
  65. if 'filedata' in webnotes.form_dict:
  66. import base64
  67. webnotes.uploaded_content = base64.b64decode(webnotes.form_dict.filedata)
  68. webnotes.uploaded_filename = webnotes.form_dict.filename
  69. return webnotes.uploaded_filename, webnotes.uploaded_content
  70. else:
  71. webnotes.msgprint('No File')
  72. return None, None
  73. def save_file(fname, content, dt, dn):
  74. from filecmp import cmp
  75. files_path = get_files_path()
  76. file_size = check_max_file_size(content)
  77. temp_fname = write_file(content)
  78. fname = scrub_file_name(fname)
  79. fpath = os.path.join(files_path, fname)
  80. if os.path.exists(fpath):
  81. if cmp(fpath, temp_fname):
  82. # remove new file, already exists!
  83. os.remove(temp_fname)
  84. else:
  85. # get_new_version name
  86. fname = get_new_fname_based_on_version(file_path, fname)
  87. # rename
  88. os.rename(temp_fname, os.path.join(files_path, fname))
  89. else:
  90. # rename new file
  91. os.rename(temp_fname, os.path.join(files_path, fname))
  92. f = webnotes.doc('File Data')
  93. f.file_name = fname
  94. f.attached_to_doctype = dt
  95. f.attached_to_name = dn
  96. f.file_size = file_size
  97. f.save(1)
  98. return f.name
  99. def get_new_fname_based_on_version(files_path, fname):
  100. # new version of the file is being uploaded, add a revision number?
  101. versions = filter(lambda f: f.startswith(fname), os.listdir(files_path))
  102. versions.sort()
  103. if "-" in versions[-1]:
  104. version = int(versions.split("-")[-1]) or 1
  105. else:
  106. version = 1
  107. new_fname = fname + "-" + str(version)
  108. while os.path.exists(os.path.join(files_path, new_fname)):
  109. version += 1
  110. new_fname = fname + "-" + str(version)
  111. if version > 100:
  112. break # let there be an exception
  113. return new_fname
  114. def scrub_file_name(fname):
  115. if '\\' in fname:
  116. fname = fname.split('\\')[-1]
  117. if '/' in fname:
  118. fname = fname.split('/')[-1]
  119. return fname
  120. def check_max_file_size(content):
  121. max_file_size = getattr(conf, 'max_file_size', 1000000)
  122. file_size = len(content)
  123. if file_size > max_file_size:
  124. webnotes.msgprint(_("File size exceeded the maximum allowed size"),
  125. raise_exception=MaxFileSizeReachedError)
  126. return file_size
  127. def write_file(content):
  128. """write file to disk with a random name (to compare)"""
  129. # create account folder (if not exists)
  130. webnotes.create_folder(get_files_path())
  131. fname = os.path.join(get_files_path(), webnotes.generate_hash())
  132. # write the file
  133. with open(fname, 'w+') as f:
  134. f.write(content)
  135. return fname
  136. def remove_all(dt, dn):
  137. """remove all files in a transaction"""
  138. try:
  139. for fid in webnotes.conn.sql_list("""select name from `tabFile Data` where
  140. attached_to_doctype=%s and attached_to_name=%s""", (dt, dn)):
  141. remove_file(fid)
  142. except Exception, e:
  143. if e.args[0]!=1054: raise e # (temp till for patched)
  144. def remove_file(fid):
  145. """Remove file and File Data entry"""
  146. webnotes.delete_doc("File Data", fid)
  147. def get_file_system_name(fname):
  148. # get system name from File Data table
  149. return webnotes.conn.sql("""select name, file_name from `tabFile Data`
  150. where name=%s or file_name=%s""", (fname, fname))
  151. def get_file(fname):
  152. f = get_file_system_name(fname)
  153. if f:
  154. file_name = f[0][1]
  155. else:
  156. file_name = fname
  157. # read the file
  158. import os
  159. with open(os.path.join(get_files_path(), file_name), 'r') as f:
  160. content = f.read()
  161. return [file_name, content]
  162. files_path = None
  163. def get_files_path():
  164. global files_path
  165. if not files_path:
  166. files_path = get_path("public", "files")
  167. return files_path