Ejemplo n.º 1
0
def _get_ufile(file_indicator = None):
  ufile = UFile.query.filter(UFile.url == file_indicator).first()
  if not ufile:
    ufile = None
  
  if ufile is not None:
    # test whether file exists
    if not funcs.f_exists(ufile.filename):
      db_session.delete(ufile)
      db_session.commit()
      abort(404)
  else:
    if not funcs.f_exists(file_indicator):
      abort(404)
    
    ufile = UFile(
              name = funcs.get_name_from_filename(file_indicator),
              url = file_indicator,
              filename = file_indicator,
              filesize = funcs.get_file_size(file_indicator),
              mimetype = funcs.get_file_mimetype(file_indicator),
              created = datetime.utcnow()
            )
    db_session.add(ufile)
    db_session.commit()
    #if not r:
    #  logging.error('Failed to commit new record: %r' % ufile)
    #  abort(404)
  return ufile
Ejemplo n.º 2
0
def upload_page():
    if not funcs.is_admin_login():
        abort(403)

    if request.method == "POST":
        print request.form
        groupkey = request.form.get("groupkey", None)
        if groupkey is None:
            abort(403)
        try:
            file_num = int(request.form.get("file_num"))
        except:
            abort(403)
        if file_num <= 0:
            abort(403)

        def get_orig_filename(filename, group_key):
            pos = filename.rfind("-%s" % group_key)
            if pos != -1:
                return filename[:pos]
            else:
                return filename

        upload_dir = os.path.join(config.ROOT_PATH, config.UPLOAD_FOLDER)
        files = glob.glob(os.path.join(upload_dir, "*-%s" % groupkey))
        if not files:
            abort(403)
        elif len(files) == 1:
            o_fn = os.path.basename(get_orig_filename(files[0], groupkey))
            dst_fn = gen_dfn_filename(o_fn)

            shutil.copy(files[0], dst_fn)
            os.remove(files[0])
            d_fn = gen_file_item(dst_fn, o_fn)

            return redirect(url_for("edit_file", file_indicator=d_fn))
        else:
            o_fn = "ziparchive.zip"
            o_f_type = "zip"
            dst_fn = gen_dfn_filename(o_fn)
            d_fn = os.path.basename(dst_fn)
            d_basefn = d_fn[: d_fn.rfind(".")]
            newdir = os.path.join(upload_dir, d_basefn)
            os.mkdir(newdir)
            for f in files:
                o_fn = os.path.basename(get_orig_filename(f, groupkey))
                new_o_fn = os.path.join(newdir, o_fn)
                shutil.copy(f, new_o_fn)
                os.remove(f)
            make_archive(dst_fn[: dst_fn.rfind(".")], o_f_type, newdir)
            shutil.rmtree(newdir, True)

            d_fn2 = gen_file_item(dst_fn, "[Archive]%s" % datetime.utcnow().strftime("%Y-%m-%d %H:%I"))
            return redirect(url_for("edit_file", file_indicator=d_fn2))

    randkey = "%s-%s" % (sha1(str(datetime.utcnow())).hexdigest(), gen_passwd(8))
    return render_template("upload.html", title="Upload Files", randkey=randkey)
Ejemplo n.º 3
0
def delete_file(file_indicator=None):
  if not funcs.is_admin_login(): abort(403)
  ufile = UFile.query.filter(UFile.url == file_indicator).first()
  if not ufile: abort(404)
  
  fn = funcs.fullname(ufile.filename)
  db_session.delete(ufile)
  db_session.commit()
  try:
    os.remove(fn)
  except:
    pass
  return redirect(url_for('file_serve',file_indicator=file_indicator))
Ejemplo n.º 4
0
def static_file(file_id=None, filename = None):
  #if not funcs.f_exists(filename): abort(404)
  ufile = UFile.query.filter(UFile.id == file_id).first()
  if not ufile: abort(404)
  if not funcs.f_exists(ufile.filename): abort(404)
  
  is_download = request.args.get('download')
  
  if is_download == 'yes':
    if not ufile.download: abort(403)
    as_attachment = True
    try:
      attachment_filename = filename.encode('UTF-8')
    except:
      attachment_filename = None
  else:
    as_attachment = False
    attachment_filename = None
  
  # reference
  if not as_attachment and request.referrer.startswith(config.URL_ROOT):
    self_ref = True
  else:
    self_ref = False
    
  key = request.args.get('key')
  v_key = request.cookies.get(sf_cookie_name(ufile.filename))
  if self_ref or (key and v_key and v_key == sf_cookie_val(ufile.filename, key)):
    pass
  else:
    abort(403)
  
  return send_from_directory(os.path.normpath(os.path.join(config.ROOT_PATH, config.UPLOAD_FILE_PATH)), ufile.filename, as_attachment=as_attachment, attachment_filename=attachment_filename)
Ejemplo n.º 5
0
def recent_files(page_cur = None):
  is_admin = is_admin_login()
  if page_cur is None: page_cur = 1
  file_query = UFile.query
  if not is_admin:
    file_query = file_query.filter(UFile.homeshow == True)
  file_num = file_query.count()
  page_num = int(math.ceil(float(file_num)/float(config.ITEMS_PER_PAGE)))
  if page_num <= 0: abort(404)
  all_pages = range(1, page_num+1)
  if page_cur not in all_pages: abort(404)
  
  files = file_query.order_by(UFile.created.desc()).limit(config.ITEMS_PER_PAGE).offset((page_cur-1)*config.ITEMS_PER_PAGE).all()
  
  page_title = "Recent Files (Page %d/%d)" % (page_cur, page_num)
  return render_template('list.html', title=page_title, all_pages=all_pages, page_cur=page_cur, files=files)
Ejemplo n.º 6
0
def direct_file(file_id, filename):
  ufile = UFile.query.filter(UFile.id == file_id).first()
  if not ufile: abort(404)
  if not ufile.linkable: abort(403)
  if isinstance(ufile.expire_at, datetime) and datetime.utcnow()>ufile.expire_at:
    abort(403)
  
  if not funcs.f_exists(ufile.filename): abort(404)
  return send_from_directory(os.path.normpath(os.path.join(config.ROOT_PATH, config.UPLOAD_FILE_PATH)), filename)
Ejemplo n.º 7
0
def upload_file_receiver():
    if not funcs.is_admin_login():
        abort(403)
    return plupload(request)
Ejemplo n.º 8
0
def edit_file(file_indicator = None):
  if request.method == 'GET' and file_indicator is None: return homepage()
  if not funcs.is_admin_login(): 
    abort(403)
  
  ufile = None
  if request.method == 'POST':
    try:
      ufile = UFile.query.filter(UFile.id == int(request.form.get('file_id'))).first()
    except:
      ufile = None
    
    if not ufile:
      abort(403)
    err = False
    
    name = Markup(request.form.get('name')).striptags().strip()
    if not name:
      err = True
      flash('Title is empty or contains illegal characters.')
    else:
      ufile.name = name
    
    url = re.sub('[^%a-zA-Z0-9_\-\.]', '', request.form.get('url')).strip('-')
    if not url:
      err = True
      flash('URL is empty or contains illegal characters.')
    else:
      ufile.url = url
      if UFile.query.filter(UFile.url == 'url').count() > 0:
        err = True
        flash('URL has already existed.')
      
    ufile.password = request.form.get('password').strip()
    if not ufile.password: ufile.password = None
    
    ufile.description = request.form.get('description').strip()
    if not ufile.description: ufile.description = None
    
    try:
      expire_delta = int(request.form.get('expire_delta'))
    except:
      expire_delta = -1
    if expire_delta == -1:
      pass
    else:
      if expire_delta == 0:
        ufile.expire_at = None
      else:
        ufile.expire_at = datetime.utcnow()+timedelta(hours=expire_delta)
    
    for item in ['linkable', 'download', 'homeshow']:
      if request.form.get(item) == 'yes':
        setattr(ufile, item, True)
      else:
        setattr(ufile, item, False)
    
    if not err:
      db_session.add(ufile)
      try:
        db_session.commit()
        return redirect(url_for('file_serve',file_indicator=url))
      except:
        flash('Failed to update database.')
    
    
    
  if ufile is None: ufile = _get_ufile(file_indicator)
  preview = _get_preview(ufile)
  fileext = _get_fileext(ufile) 
  
  visitkey = gen_passwd()
  
  page_title = "Edit \"%s\"" % ufile.name
  
  if ufile.description is None: ufile.description = ''
  if ufile.password is None: ufile.password = ''
  
  response = make_response(render_template('edit.html', ufile=ufile, preview = preview, fileext = fileext, file_indicator = file_indicator, visitkey=visitkey, edit_page = False, title=page_title))
  response.set_cookie(sf_cookie_name(ufile.filename), sf_cookie_val(ufile.filename, visitkey))
  return response