Example #1
0
def download(uid):
    with closing(
            g.db.cursor(cursor_factory=psycopg2.extras.DictCursor)) as cursor:
        try:
            cursor.execute(
                """
                SELECT * FROM minicloud_shared
                WHERE uid = %s LIMIT 1;
                """, [uid])

            shared = cursor.fetchone()
            # shared with a single user
            if shared['shared_type'] == SHARED_USER:
                if int(current_user.id) == shared['shared_id']:
                    return download_file(shared['user_id'], shared['file_uid'],
                                         uid)

            # shared with the cloud
            if shared['shared_type'] == SHARED_CLOUD:
                return download_file(shared['user_id'], shared['file_uid'],
                                     uid)

        except Warning:
            g.db.rollback()

    abort(500)
Example #2
0
def main(argv):
  # Parse the URL
  the_url = FLAGS.uri
  parsed_url = urlparse(the_url)
  the_path = parsed_url.path
  raw_filename = os.path.split(the_path)[-1]
  filename, file_extension = os.path.splitext(raw_filename)

  # Do the work if the flags allow

  if FLAGS.download: files.download_file(the_url, raw_filename)
  if FLAGS.bunzip2: files.bunzip2(raw_filename, filename)
  if FLAGS.gcs_upload: files.upload2gcs(FLAGS.bucket, filename, filename)
  if FLAGS.bq_load: files.load2bq(uri='gs://' + FLAGS.bucket + '/' + filename,
      dataset_id='LSST',
      table_id='mep_wise')

  if FLAGS.cleanup: 
    try:
      os.remove(filename)
    except:
      pass
    try:
     os.remove(raw_filename)
    except:
      pass
    try:
     files.gcs_remove(FLAGS.bucket, filename)
    except:
      pass
Example #3
0
def download_file(file_id):
    user = None
    group = None

    if 'user' in session:
        user = session['user']
    elif 'group' in session:
        group = session['group']

    ff = files.download_file(file_id, user_id=user.id if user else None, group_id=group.id if group else None)

    if ff:
        return send_file('%s%s' % (FILE_BASE, ff.location), mimetype=ff.type, as_attachment=True, attachment_filename=ff.name)

    abort(404)
Example #4
0
 def select_dir(self):
     f = self.tree.selectedIndexes()[0]
     new_dir = f.model().itemFromIndex(f).text()
     if new_dir == "..":
         index = self.current_dir.rfind("/", 0, self.current_dir.rfind("/"))
         self.current_dir = self.current_dir[:index + 1]
     else:
         if new_dir.startswith("[D] "):
             self.current_dir = self.current_dir + new_dir[4:] + "/"
             self.current_url = str(self.comboBox1.currentText())
             dir_listing = files.get_directory_listing(
                 self.current_dir, self.current_url)
             self.populateTree(dir_listing)
         elif new_dir.endswith(".gz"):
             # download prompt
             fname = files.download_file(self.current_dir + new_dir,
                                         self.current_url)
             msg = QMessageBox()
             msg.setIcon(QMessageBox.Information)
             msg.setText("File downloaded!")
             msg.setInformativeText(new_dir)
             msg.setWindowTitle("Success!")
             retval = msg.exec_()
         else:
             # get file
             d = QDialog()
             d.setWindowTitle(new_dir)
             d.resize(900, 720)
             textbox = QPlainTextEdit(d)
             textbox.resize(880, 700)
             textbox.setLineWrapMode(False)
             textbox.setPlainText(
                 files.get_file(self.current_dir + new_dir,
                                self.current_url))
             textbox.setReadOnly(True)
             d.setWindowModality(Qt.ApplicationModal)
             d.exec_()
def get(data_id, filename, path, data_format, database):
    url = database.url(data_id, data_format)
    filepath = download_file(url, filename, path)
    return data_format.parse(filepath)
Example #6
0
def main():
    """
    Main que gestiona todo el funcionamiento del sistema.
    :return:
    """
    # Creamos un parser para los argumentos de entrada del programa
    parser = argparse.ArgumentParser(description="Cliente SecureBox")

    # Ayuda

    # Gestion de usuarios
    parser.add_argument("--create_id", nargs=2, metavar=('name', 'email'))
    parser.add_argument("--search_id", nargs=1, metavar=('data'))
    parser.add_argument("--delete_id", nargs=1, metavar=('user_id'))

    # Gestion de ficheros
    parser.add_argument("--upload", nargs=1, metavar=('file'))
    parser.add_argument("--source_id", nargs=1, metavar=('user_id'))
    parser.add_argument("--dest_id", nargs=1, metavar=('user_id'))
    parser.add_argument("--list_files", action='store_true')
    parser.add_argument("--download", nargs=1, metavar=('file_id'))
    parser.add_argument("--delete_file", nargs=1, metavar=('file_id'))

    # Gestion del cifrado y firmado de documentos
    parser.add_argument("--encrypt", nargs=1, metavar=('file'))
    parser.add_argument("--sign", nargs=1, metavar=('file'))
    parser.add_argument("--enc_sign", nargs=1, metavar=('file'))

    # Se parsean los argumentos
    args = parser.parse_args()

    # Si no se encuentan los parametros suficientes
    if len(sys.argv) < 2:
        print(
            "Se necesitan mas argumentos de entrada para ejecutar el programa."
        )
        print("Si necesita ayuda ejecute el programa con la flag --help")
        return

    # Gestion de usuarios
    if args.create_id:
        users.register_user(name=args.create_id[0],
                            email=args.create_id[1],
                            token=token)
    elif args.search_id:
        users.search_user(data_search=args.search_id[0], token=token)
    elif args.delete_id:
        users.delete_user(user_id=args.delete_id[0], token=token)

    # Gestion de cifrado y firmado
    elif args.encrypt and args.dest_id:
        key = users.get_public_key(user_id=args.dest_id[0], token=token)
        crypto.encrypt(file=args.encrypt[0], public_key_receiver=key)
    elif args.sign:
        crypto.sign(file=args.sign[0])
    elif args.enc_sign and args.dest_id:
        key = users.get_public_key(user_id=args.dest_id[0], token=token)
        crypto.encrypt_and_sign(file=args.enc_sign[0], public_key_receiver=key)

    # Gestion de ficheros
    elif args.upload and args.dest_id:
        key = users.get_public_key(user_id=args.dest_id[0], token=token)
        files.upload_file(file=args.upload[0],
                          public_key_dest=key,
                          token=token)
    elif args.list_files:
        files.list_files(token=token)
    elif args.download and args.source_id:
        key = users.get_public_key(user_id=args.source_id[0], token=token)
        files.download_file(file_id=args.download[0],
                            public_key_receiver=key,
                            token=token)
    elif args.delete_file:
        files.delete_file(file_id=args.delete_file[0], token=token)
    else:
        print("Comando no soportado")
        print(
            "Revise con el comando --help los comandos que puede ejecutar el cliente SecureBox."
        )
Example #7
0
def load_xml(url_string, filename):
    e = ElementTree.parse(download_file(url_string, filename))
    return e.getroot()
Example #8
0
def get(data_id, filename, path, data_format, database):
    url = database.url(data_id, data_format)
    filepath = download_file(url, filename, path)
    return data_format.parse(filepath)
Example #9
0
    for asset in release["assets"]:
        if re.match(package["assetNameRegex"], asset["name"]):
            print(f"Found asset {asset['name']}")
            asset_url = asset["browser_download_url"]
            asset_name = ".".join(asset["name"].split(".")[:-1])
            break

    if asset_url is None:
        print(
            f"No asset matching '{package['assetNameRegex']}' for {package['repo']}"
        )
        continue

    # download target asset
    print("Downloading", asset_url)
    local = files.download_file(asset_url)

    # extract files
    with zipfile.ZipFile(local) as zf:
        for file in package["files"]:

            out = os.path.join(OUTPUT_DIR,
                               file["output"].replace("/", os.path.sep))

            dr = os.path.sep.join(out.split(os.path.sep)[:-1])
            if not os.path.exists(dr):
                os.makedirs(dr)

            src = file["source"].format(asset_name)
            print(f"Extracting {src} to {out}")
            with open(out, "wb") as out_file, zf.open(src) as src_file: