You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 
 

231 lines
6.0 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. def upload():
  25. form = webnotes.form
  26. # get record details
  27. dt = form.getvalue('doctype')
  28. dn = form.getvalue('docname')
  29. at_id = form.getvalue('at_id')
  30. webnotes.response['type'] = 'iframe'
  31. if not webnotes.form['filedata'].filename:
  32. webnotes.response['result'] = """
  33. <script type='text/javascript'>
  34. window.parent.wn.views.fomrview['%s'].frm.attachments.dialog.hide();
  35. window.parent.msgprint("Please select a file!");
  36. </script>""" % dt
  37. return
  38. # save
  39. fid, fname = save_uploaded()
  40. # save it in the form
  41. updated = False
  42. if fid:
  43. updated = add_file_list(dt, dn, fname, fid)
  44. if fid and updated:
  45. # refesh the form!
  46. # with the new modified timestamp
  47. webnotes.response['result'] = """
  48. <script type='text/javascript'>
  49. window.parent.wn.widgets.form.file_upload_done('%(dt)s', '%(dn)s', '%(fid)s', '%(fname)s', '%(at_id)s', '%(mod)s');
  50. window.parent.wn.views.formview['%(dt)s'].frm.show_doc('%(dn)s');
  51. </script>
  52. """ % {
  53. 'dt': dt,
  54. 'dn': dn,
  55. 'fid': fid,
  56. 'fname': fname.replace("'", "\\'"),
  57. 'at_id': at_id,
  58. 'mod': webnotes.conn.get_value(dt, dn, 'modified')
  59. }
  60. # -------------------------------------------------------
  61. def add_file_list(dt, dn, fname, fid):
  62. """
  63. udpate file_list attribute of the record
  64. """
  65. fl = webnotes.conn.get_value(dt, dn, 'file_list') or ''
  66. if fl:
  67. fl += '\n'
  68. # add new file id
  69. fl += fname + ',' + fid
  70. # save
  71. webnotes.conn.set_value(dt, dn, 'file_list', fl)
  72. return True
  73. def remove_all(dt, dn):
  74. """remove all files in a transaction"""
  75. file_list = webnotes.conn.get_value(dt, dn, 'file_list') or ''
  76. for afile in file_list.split('\n'):
  77. if afile:
  78. fname, fid = afile.split(',')
  79. remove_file(dt, dn, fid)
  80. def remove_file(dt, dn, fid):
  81. """Remove fid from the give file_list"""
  82. # get the old file_list
  83. fl = webnotes.conn.get_value(dt, dn, 'file_list') or ''
  84. new_fl = []
  85. fl = fl.split('\n')
  86. for f in fl:
  87. if f and f.split(',')[1]!=fid:
  88. new_fl.append(f)
  89. # delete
  90. delete_file(fid)
  91. # update the file_list
  92. webnotes.conn.set_value(dt, dn, 'file_list', '\n'.join(new_fl))
  93. # return the new timestamp
  94. return webnotes.conn.get_value(dt, dn, 'modified')
  95. def make_thumbnail(blob, size):
  96. from PIL import Image
  97. import cStringIO
  98. fobj = cStringIO.StringIO(blob)
  99. image = Image.open(fobj)
  100. image.thumbnail((tn,tn*2), Image.ANTIALIAS)
  101. outfile = cStringIO.StringIO()
  102. image.save(outfile, 'JPEG')
  103. outfile.seek(0)
  104. fcontent = outfile.read()
  105. return fcontent
  106. def get_uploaded_content():
  107. import webnotes
  108. if 'filedata' in webnotes.form:
  109. i = webnotes.form['filedata']
  110. webnotes.uploaded_filename, webnotes.uploaded_content = i.filename, i.file.read()
  111. return webnotes.uploaded_filename, webnotes.uploaded_content
  112. else:
  113. webnotes.msgprint('No File');
  114. return None, None
  115. def save_uploaded():
  116. import webnotes.utils
  117. webnotes.response['type'] = 'iframe'
  118. form = webnotes.form
  119. fname, content = get_uploaded_content()
  120. if content:
  121. fid = save_file(fname, content)
  122. return fid, fname
  123. else:
  124. return None, fname
  125. # -------------------------------------------------------
  126. def save_file(fname, content, module=None):
  127. from webnotes.model.doc import Document
  128. # some browsers return the full path
  129. if '\\' in fname:
  130. fname = fname.split('\\')[-1]
  131. if '/' in fname:
  132. fname = fname.split('/')[-1]
  133. # generate the ID (?)
  134. f = Document('File Data')
  135. f.file_name = fname
  136. if module:
  137. f.module = module
  138. f.save(1)
  139. write_file(f.name, content)
  140. return f.name
  141. # -------------------------------------------------------
  142. def write_file(fid, content):
  143. import os, conf
  144. # test size
  145. max_file_size = 1000000
  146. if hasattr(conf, 'max_file_size'):
  147. max_file_size = conf.max_file_size
  148. if len(content) > max_file_size:
  149. raise Exception, 'Maximum File Limit (%s MB) Crossed' % (int(max_file_size / 1000000))
  150. # no slashes
  151. fid = fid.replace('/','-')
  152. # save to a folder (not accessible to public)
  153. folder = webnotes.get_files_path()
  154. # create account folder (if not exists)
  155. webnotes.create_folder(folder)
  156. # write the file
  157. file = open(os.path.join(folder, fid),'w+')
  158. file.write(content)
  159. file.close()
  160. def get_file_system_name(fname):
  161. # get system name from File Data table
  162. return webnotes.conn.sql("""select name, file_name from `tabFile Data`
  163. where name=%s or file_name=%s""", (fname, fname))
  164. def delete_file(fid, verbose=0):
  165. """delete file from file system"""
  166. import os
  167. webnotes.conn.sql("delete from `tabFile Data` where name=%s", fid)
  168. path = os.path.join(webnotes.get_files_path(), fid.replace('/','-'))
  169. if os.path.exists(path):
  170. os.remove(path)
  171. def get_file(fname):
  172. f = get_file_system_name(fname)
  173. if f:
  174. file_id = f[0][0].replace('/','-')
  175. file_name = f[0][1]
  176. else:
  177. file_id = fname
  178. file_name = fname
  179. # read the file
  180. import os
  181. with open(os.path.join(webnotes.get_files_path(), file_id), 'r') as f:
  182. content = f.read()
  183. return [file_name, content]