Exemplo n.º 1
0
    def add_permissions_user(self, fileid: str, email: str, role: str) -> dict:
        """
        Share a given fileid with some other entity. Currently, the only supported entity
        is a single user addressed by their email. Role defines the level of access the entity can have
        The supported values for role are: owner, reader, writer or commenter.

        Permissions are idempotent. Adding the same permission twice will have no extra effect but
        the permission will have to be removed all the times it had been added to actually revoke it.

        Takes:
            id of the file to which permissions have to be added.
            email address of the entity to which permission is granted.
            the role granted to the entity.
        Returns:
            the metadata associated with the permission
        """
        logger.debug("Following information to be updated\n"
                     "fileid: {f}\nrole: {r}\n email: {e}\n".format(f=fileid,
                                                                    r=role,
                                                                    e=email))

        if not self.is_exists(fileid):
            logger.critical("File not found")
            raise FileNotFound("No file to add permission to")

        permission = {"type": "user", "role": role, "emailAddress": email}
        mdata = self.perm_service.create(fileId=fileid,
                                         body=permission).execute()
        logger.debug("The permission was created.\n{}".format(mdata))

        return mdata
Exemplo n.º 2
0
    def write(self, filename: str) -> dict:
        """
        Upload the file the Google Drive. The file should essentially exist before you try to upload it.
        It will return the metadata of the file, as set by Google. Most important of the metadata is the `id`
        which is unique to each file.
        Takes:
            path to the file as a string.
        Returns:
             The metadata dictionary
        """
        logger.debug("Trying to upload file: {}".format(filename))

        if not isfile(filename):
            logger.critical("No such file exists. Check path and try again")
            raise FileNotFound(filename + "does not exist")

        media = MediaFileUpload(filename=filename,
                                mimetype=guess_type(filename)[0],
                                chunksize=1024)
        file_metadata = {
            "name": filename.split("/")[-1],  # Get filename from path
            "description":
            "",  # Required so that the field actually exists when the file is uploaded.
        }

        f = self.file_service.create(body=file_metadata,
                                     media_body=media).execute()
        logger.info("File successfully uploaded.")
        logger.debug("File metadata: {}".format(f))
        return f
Exemplo n.º 3
0
    def run(self, args: Namespace):
        if not isfile(args.input_file):
            logger.critical("Input file does not exist. Exiting")
            raise FileNotFound("Unable to find file.")

        ff = ffmpy.FFmpeg(inputs={args.input_file: None},
                          outputs={args.output_file: None})
        ff.run()
Exemplo n.º 4
0
    def __init__(self, config_path: str = None):
        c = ConfigParser()

        # Load the default values first.
        c.read_dict(default_values)

        if config_path is not None:
            if not os.path.isfile(os.path.expanduser(config_path)):
                if config_path == CONFIG_FULL_PATH_DEFAULT:
                    raise FileNotFound(
                        "Default file not yet created. Try running `nephos init`"
                    )
                else:
                    raise FileNotFound("Specified config not found")
            else:
                c.read(config_path)

        self.conf_items = c
Exemplo n.º 5
0
    def read(self, fileid: str) -> str:
        """
        Read a file of the given id. Raises error if file does not already
        exist for some reason

        Takes:
            The id of the file to be read.
        Returns:
            The contents of the file as a binary string.
        """
        logger.debug("Trying to read file id: {}".format(fileid))

        if self.is_exists(fileid):
            return self.file_service.get_media(fileId=fileid).execute()
        else:
            logger.critical("Given file not found.")
            raise FileNotFound("{} not found on drive".format(fileid))
Exemplo n.º 6
0
    def search(self,
               name_subs: str = None,
               tag_subs: List[str] = None,
               do_and: bool = False) -> List[Tuple[str, str]]:
        """
        Search for a file in the drive. Many filters are supported but we currently only
        search for a substring on a filename and for tags. It returns the names as well as fileids for
        all matching objects.

        Takes:
            Substring to be searched.
        Returns:
             A list of tuples: [(filename, fileid)...]
        """
        # TODO: Improve this section
        if tag_subs is None:
            query = "name contains '{}'".format(name_subs)
        elif name_subs is None:
            query_set = ["fullText contains '{}'".format(x) for x in tag_subs]
            if do_and:
                query = " and ".join(query_set)
            else:
                query = " or ".join(query_set)
        else:
            qn = "name contains '{}'".format(name_subs)
            qt_set = ["fullText contains '{}'".format(x) for x in tag_subs]

            if do_and:
                query = qn + " and " + " and ".join(qt_set)

        logger.debug("Following is the search query: " + query)

        response = self.file_service.list(q=query,
                                          pageSize=5,
                                          includeTeamDriveItems=True,
                                          supportsTeamDrives=True).execute()

        items = response.get("files", [])
        if not items:
            logger.critical("No files were found matching the query.")
            raise FileNotFound("Query returned empty")

        response = [(f["name"], f["id"]) for f in items]
        logger.debug(
            "following information was returned.\n{}".format(response))
        return response
Exemplo n.º 7
0
    def tag(self, fileid: str, tags: List[str]) -> None:
        """
        Add the provided tag to a valid file. The current method of adding tags involves
        directly writing the tag onto the description field of the file on the drive.

        Note that this does not check if it is a valid tag. This is the caller's job.

        Takes:
            fileid of the object to be tagged.
            a list of tags to be added.
        """
        if not self.is_exists(fileid):
            logger.critical("Given file not found")
            raise FileNotFound(
                "The provided fileid {} does not exist".format(fileid))

        # so as to not delete old contents:
        info = self.file_service.get(fileId=fileid,
                                     fields="description").execute()
        old_description = info["description"]

        # TODO: We can do this better by overwriting repeating tags
        metadata = {"description": old_description + "\n" + " \n".join(tags)}
        self.file_service.update(fileId=fileid, body=metadata).execute()