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.

file_manager.py 6.4 KiB

13 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268
  1. import webnotes
  2. def upload():
  3. form = webnotes.form
  4. # get record details
  5. dt = form.getvalue('doctype')
  6. dn = form.getvalue('docname')
  7. at_id = form.getvalue('at_id')
  8. webnotes.response['type'] = 'iframe'
  9. if not webnotes.form['filedata'].filename:
  10. webnotes.response['result'] = """
  11. <script type='text/javascript'>
  12. window.parent.frms['%s'].attachments.dialog.hide();
  13. window.parent.msgprint("Please select a file!");
  14. </script>""" % dt
  15. return
  16. # save
  17. fid, fname = save_uploaded()
  18. # save it in the form
  19. updated = False
  20. if fid:
  21. updated = add_file_list(dt, dn, fname, fid)
  22. if fid and updated:
  23. # refesh the form!
  24. # with the new modified timestamp
  25. webnotes.response['result'] = """
  26. <script type='text/javascript'>
  27. window.parent.wn.widgets.form.file_upload_done('%(dt)s', '%(dn)s', '%(fid)s', '%(fname)s', '%(at_id)s', '%(mod)s');
  28. window.parent.frms['%(dt)s'].show_doc('%(dn)s');
  29. </script>
  30. """ % {
  31. 'dt': dt,
  32. 'dn': dn,
  33. 'fid': fid,
  34. 'fname': fname.replace("'", "\\'"),
  35. 'at_id': at_id,
  36. 'mod': webnotes.conn.get_value(dt, dn, 'modified')
  37. }
  38. # -------------------------------------------------------
  39. def add_file_list(dt, dn, fname, fid):
  40. """
  41. udpate file_list attribute of the record
  42. """
  43. try:
  44. # get the old file_list
  45. fl = webnotes.conn.get_value(dt, dn, 'file_list') or ''
  46. if fl:
  47. fl += '\n'
  48. # add new file id
  49. fl += fname + ',' + fid
  50. # save
  51. webnotes.conn.set_value(dt, dn, 'file_list', fl)
  52. return True
  53. except Exception, e:
  54. webnotes.response['result'] = """
  55. <script type='text/javascript'>
  56. window.parent.msgprint("Error while uploading: %s");
  57. </script>""" % str(e)
  58. def remove_all(dt, dn):
  59. """remove all files in a transaction"""
  60. file_list = webnotes.conn.get_value(dt, dn, 'file_list') or ''
  61. for afile in file_list.split('\n'):
  62. if afile:
  63. fname, fid = afile.split(',')
  64. remove_file_list(dt, dn, fid)
  65. delete_file(fid)
  66. def remove_file_list(dt, dn, fid):
  67. """
  68. Remove fid from the give file_list
  69. """
  70. # get the old file_list
  71. fl = webnotes.conn.get_value(dt, dn, 'file_list') or ''
  72. new_fl = []
  73. fl = fl.split('\n')
  74. for f in fl:
  75. if f.split(',')[1]!=fid:
  76. new_fl.append(f)
  77. # update the file_list
  78. webnotes.conn.set_value(dt, dn, 'file_list', '\n'.join(new_fl))
  79. # return the new timestamp
  80. return webnotes.conn.get_value(dt, dn, 'modified')
  81. def make_thumbnail(blob, size):
  82. from PIL import Image
  83. import cStringIO
  84. fobj = cStringIO.StringIO(blob)
  85. image = Image.open(fobj)
  86. image.thumbnail((tn,tn*2), Image.ANTIALIAS)
  87. outfile = cStringIO.StringIO()
  88. image.save(outfile, 'JPEG')
  89. outfile.seek(0)
  90. fcontent = outfile.read()
  91. return fcontent
  92. def save_uploaded(js_okay='window.parent.msgprint("File Upload Successful")', js_fail=''):
  93. import webnotes.utils
  94. webnotes.response['type'] = 'iframe'
  95. form, fid, fname = webnotes.form, None, None
  96. try:
  97. # has attachment?
  98. if 'filedata' in form:
  99. i = form['filedata']
  100. fname, content = i.filename, i.file.read()
  101. # get the file id
  102. fid = save_file(fname, content)
  103. # okay
  104. webnotes.response['result'] = """<script type='text/javascript'>%s</script>""" % js_okay
  105. else:
  106. webnotes.response['result'] = """<script type='text/javascript'>window.parent.msgprint("No file"); %s</script>""" % js_fail
  107. except Exception, e:
  108. webnotes.response['result'] = """<script type='text/javascript'>
  109. window.parent.msgprint("%s");
  110. window.parent.errprint("%s");
  111. %s</script>""" % (str(e), \
  112. webnotes.utils.getTraceback().replace('\n','<br>').replace('"', '\\"'), js_fail)
  113. return fid, fname
  114. # -------------------------------------------------------
  115. def save_file(fname, content, module=None):
  116. from webnotes.model.doc import Document
  117. # some browsers return the full path
  118. if '\\' in fname:
  119. fname = fname.split('\\')[-1]
  120. if '/' in fname:
  121. fname = fname.split('/')[-1]
  122. # generate the ID (?)
  123. f = Document('File Data')
  124. f.file_name = fname
  125. if module:
  126. f.module = module
  127. f.save(1)
  128. write_file(f.name, content)
  129. return f.name
  130. # -------------------------------------------------------
  131. def write_file(fid, content):
  132. import os, webnotes.defs
  133. # test size
  134. max_file_size = 1000000
  135. if hasattr(webnotes.defs, 'max_file_size'):
  136. max_file_size = webnotes.defs.max_file_size
  137. if len(content) > max_file_size:
  138. raise Exception, 'Maximum File Limit (%s MB) Crossed' % (int(max_file_size / 1000000))
  139. # no slashes
  140. fid = fid.replace('/','-')
  141. # save to a folder (not accessible to public)
  142. folder = webnotes.get_files_path()
  143. # create account folder (if not exists)
  144. webnotes.create_folder(folder)
  145. # write the file
  146. file = open(os.path.join(folder, fid),'w+')
  147. file.write(content)
  148. file.close()
  149. # -------------------------------------------------------
  150. def get_file_system_name(fname):
  151. # get system name from File Data table
  152. return webnotes.conn.sql("select name, file_name from `tabFile Data` where name=%s or file_name=%s", (fname, fname))
  153. # -------------------------------------------------------
  154. def delete_file(fname, verbose=0):
  155. import os
  156. for f in get_file_system_name(fname):
  157. webnotes.conn.sql("delete from `tabFile Data` where name=%s", f[0])
  158. # delete file
  159. file_id = f[0].replace('/','-')
  160. try:
  161. os.remove(os.path.join(webnotes.get_files_path(), file_id))
  162. except OSError, e:
  163. if e.args[0]!=2:
  164. raise e
  165. if verbose: webnotes.msgprint('File Deleted')
  166. # Get File
  167. # -------------------------------------------------------
  168. def get_file(fname):
  169. in_fname = fname
  170. # from the "File" table
  171. if webnotes.conn.exists('File',fname):
  172. fname = webnotes.conn.sql("select file_list from tabFile where name=%s", fname)
  173. fname = fname and fname[0][0]
  174. fname = fname.split('\n')[0].split(',')[1]
  175. if get_file_system_name(fname):
  176. f = get_file_system_name(fname)[0]
  177. else:
  178. f = None
  179. # read the file
  180. import os
  181. file_id = f[0].replace('/','-')
  182. file = open(os.path.join(webnotes.get_files_path(), file_id), 'r')
  183. content = file.read()
  184. file.close()
  185. return [f[1], content]
  186. # Conversion Patch
  187. # -------------------------------------------------------
  188. def convert_to_files(verbose=0):
  189. # nfiles
  190. fl = webnotes.conn.sql("select name from `tabFile Data`")
  191. for f in fl:
  192. # get the blob
  193. blob = webnotes.conn.sql("select blob_content from `tabFile Data` where name=%s", f[0])[0][0]
  194. if blob:
  195. if hasattr(blob, 'tostring'):
  196. blob = blob.tostring()
  197. # write the file
  198. write_file(f[0], blob)
  199. if verbose:
  200. webnotes.msgprint('%s updated' % f[0])
  201. # -------------------------------------------------------