Ejemplo n.º 1
0
 def test_set_time(self):
     """Test for changing time in the file system."""
     self.test_vfs.settimes('vfs.txt', accessed=epoch_to_datetime(103336010), modified=epoch_to_datetime(103336010))
     self.assertEqual(self.test_vfs.getinfo('vfs.txt', namespaces=['details']).accessed,
                      epoch_to_datetime(103336010))
     self.assertEqual(self.test_vfs.getinfo('vfs.txt', namespaces=['details']).modified,
                      epoch_to_datetime(103336010))
Ejemplo n.º 2
0
 def test_set_time(self):
     """Test for changing time in the file system."""
     self.test_vfs.settimes('vfs.txt',
                            accessed=epoch_to_datetime(103336010),
                            modified=epoch_to_datetime(103336010))
     self.assertEqual(
         self.test_vfs.getinfo('vfs.txt', namespaces=['details']).accessed,
         epoch_to_datetime(103336010))
     self.assertEqual(
         self.test_vfs.getinfo('vfs.txt', namespaces=['details']).modified,
         epoch_to_datetime(103336010))
Ejemplo n.º 3
0
    def setinfo(self, path, info):  # pylint: disable=too-many-branches
        _CheckPath(path)
        with self._lock:
            response = self.session.get(_PathUrl(path, ""))
            if response.status_code == 404:
                raise ResourceNotFound(path=path)
            existingItem = response.json()
            updatedData = {}

            for namespace in info:
                for name, value in info[namespace].items():
                    if namespace == "basic":
                        if name == "name":
                            assert False, "Unexpected to try and change the name this way"
                        elif name == "is_dir":
                            # can't change this - must be an error in the framework
                            assert False, "Can't change an item to and from directory"
                        else:
                            assert False, "Aren't we guaranteed that this is all there is in the basic namespace?"
                    elif namespace == "details":
                        if name == "accessed":
                            pass  # not supported by OneDrive
                        elif name == "created":
                            # incoming datetimes should be utc timestamps, OneDrive expects naive UTC datetimes
                            if "fileSystemInfo" not in updatedData:
                                updatedData["fileSystemInfo"] = {}
                            updatedData["fileSystemInfo"][
                                "createdDateTime"] = epoch_to_datetime(
                                    value).replace(
                                        tzinfo=None).isoformat() + "Z"
                        elif name == "metadata_changed":
                            pass  # not supported by OneDrive
                        elif name == "modified":
                            # incoming datetimes should be utc timestamps, OneDrive expects naive UTC datetimes
                            if "fileSystemInfo" not in updatedData:
                                updatedData["fileSystemInfo"] = {}
                            updatedData["fileSystemInfo"][
                                "lastModifiedDateTime"] = epoch_to_datetime(
                                    value).replace(
                                        tzinfo=None).isoformat() + "Z"
                        elif name == "size":
                            assert False, "Can't change item size"
                        elif name == "type":
                            assert False, "Can't change an item to and from directory"
                        else:
                            assert False, "Aren't we guaranteed that this is all there is in the details namespace?"
                    else:
                        # ignore namespaces that we don't recognize
                        pass
            response = self.session.patch(_ItemUrl(existingItem["id"], ""),
                                          json=updatedData)
            response.raise_for_status()
Ejemplo n.º 4
0
 def setinfo(self, path, info):  # pylint: disable=redefined-outer-name,too-many-branches,unused-argument
     _CheckPath(path)
     with self._lock:
         metadata = self._itemFromPath(path)
         if metadata is None or isinstance(metadata, list):
             raise ResourceNotFound(path=path)
         updatedData = {}
         for namespace in info:
             for name, value in info[namespace].items():
                 if namespace == "details":
                     if name == "modified":
                         # incoming datetimes should be utc timestamps, Google Drive expects RFC 3339
                         updatedData["modifiedTime"] = epoch_to_datetime(
                             value).replace(
                                 tzinfo=timezone.utc).isoformat()
                 elif namespace == "google":
                     if name == "indexableText":
                         updatedData["contentHints"] = {
                             "indexableText": value
                         }
                     elif name == "appProperties":
                         assert isinstance(value, dict)
                         updatedData["appProperties"] = value
         self.drive.files().update(
             fileId=metadata["id"],
             body=updatedData).execute(num_retries=self.retryCount)
Ejemplo n.º 5
0
 def setinfo(self, path, info):
     _log.info(f'setinfo({path}, {info})')
     path = self.validatepath(path)
     with self._lock:
         metadata = self._itemFromPath(path)
         if metadata is None:
             raise ResourceNotFound(path=path)
         updatedData = {}
         for namespace in info:
             for name, value in info[namespace].items():
                 if namespace == 'details':
                     if name == 'modified':
                         # incoming datetimes should be utc timestamps, Google Drive expects RFC 3339
                         updatedData['modifiedTime'] = epoch_to_datetime(
                             value).replace(
                                 tzinfo=timezone.utc).isoformat()
                 elif namespace == 'google':
                     if name == 'indexableText':
                         updatedData['contentHints'] = {
                             'indexableText': value
                         }
                     elif name == 'appProperties':
                         assert isinstance(value, dict)
                         updatedData['appProperties'] = value
         self._drive.files().update(
             fileId=metadata['id'],
             body=updatedData,
             **self._file_kwargs,
         ).execute(num_retries=self.retryCount)
    def setinfo(self, path, info):
        # type: (Text, RawInfo) -> None
        """Set info on a resource.

        This method is the complement to `~fs.base.FS.getinfo`
        and is used to set info values on a resource.

        Arguments:
            path (str): Path to a resource on the filesystem.
            info (dict): Dictionary of resource info.

        Raises:
            fs.errors.ResourceNotFound: If ``path`` does not exist
                on the filesystem

        The ``info`` dict should be in the same format as the raw
        info returned by ``getinfo(file).raw``.

        Example:
            >>> details_info = {"details": {
            ...     "modified": time.time()
            ... }}
            >>> my_fs.setinfo('file.txt', details_info)

        """
        with self._lock:
            _res = self._getresource(path)
            if not _res:
                raise errors.ResourceNotFound(path)

            if "details" in info:
                details = info["details"]
                if ("accessed" in details or "modified" in details
                        or "created" in details):
                    accessed_time = int(details.get("accessed", 0))
                    modified_time = int(details.get("modified", 0))
                    created_time = int(details.get("created", 0))
                    if accessed_time and not modified_time:
                        modified_time = accessed_time
                    if created_time:
                        pass
                    if modified_time:
                        dt = epoch_to_datetime(modified_time)
                        rfc1123_time = dt.strftime("%a, %d %b %Y %H:%M:%S GMT")
                        _res.set_last_modified(_res.path, rfc1123_time, False)

            if "properties" in info:
                prop_names = _res.get_property_names(True)
                for prop_name in prop_names:
                    # let the DAV provider handle the standard live properties
                    if prop_name.startswith("{DAV:}"):
                        continue
                    # skip unknonwn properties
                    if prop_name not in info["properties"]:
                        continue
                    _res.set_property_value(prop_name,
                                            info["properties"][prop_name])
Ejemplo n.º 7
0
	def setinfo(self, path, info): # pylint: disable=too-many-branches
		itemRequest = self.client.item(path=path)
		try:
			existingItem = itemRequest.get()
		except OneDriveError as e:
			raise ResourceNotFound(path=path, exc=e)

		itemUpdate = Item()
		itemUpdate.id = existingItem.id
		itemUpdate.file_system_info = FileSystemInfo()

		for namespace in info:
			for name, value in info[namespace].items():
				if namespace == "basic":
					if name == "name":
						assert False, "Unexpected to try and change the name this way"
					elif name == "is_dir":
						# can't change this - must be an error in the framework
						assert False, "Can't change an item to and from directory"
					else:
						assert False, "Aren't we guaranteed that this is all there is in the basic namespace?"
				elif namespace == "details":
					if name == "accessed":
						pass # not supported by OneDrive
					elif name == "created":
						# incoming datetimes should be utc timestamps, OneDrive expects naive UTC datetimes
						itemUpdate.file_system_info.created_date_time = epoch_to_datetime(value).replace(tzinfo=None)
					elif name == "metadata_changed":
						pass # not supported by OneDrive
					elif name == "modified":
						# incoming datetimes should be utc timestamps, OneDrive expects naive UTC datetimes
						itemUpdate.file_system_info.last_modified_date_time = epoch_to_datetime(value).replace(tzinfo=None)
					elif name == "size":
						assert False, "Can't change item size"
					elif name == "type":
						assert False, "Can't change an item to and from directory"
					else:
						assert False, "Aren't we guaranteed that this is all there is in the details namespace?"
				else:
					# ignore namespaces that we don't recognize
					pass
		itemRequest.update(itemUpdate)
    def _make_info_from_resource(_res, namespaces):
        st_size = _res.get_content_length()
        st_atime = _res.get_last_modified()
        st_mtime = st_atime
        st_ctime = _res.get_creation_date()

        info = {"basic": {"name": _res.name, "is_dir": _res.is_collection}}
        if "details" in namespaces:
            write = []
            try:
                dt = epoch_to_datetime(st_mtime)
                rfc1123_time = dt.strftime("%a, %d %b %Y %H:%M:%S GMT")
                _res.set_last_modified(_res.path, rfc1123_time, True)
                write.append("modified")
            except Exception as e:
                pass
            info["details"] = {
                # "_write": ["accessed", "modified"],
                "_write": write,
                "accessed": st_atime,
                "modified": st_mtime,
                "created": st_ctime,
                "size": st_size,
                # "type": int(cls._get_type_from_stat(stat_result)),
            }
            if _res.is_collection:
                info["details"]["type"] = 1
            else:
                info["details"]["type"] = 2
        if "stat" in namespaces:
            info["stat"] = {
                "st_size": st_size,
                "st_atime": st_atime,
                "st_mtime": st_mtime,
                "st_ctime": st_ctime,
            }
        if "properties" in namespaces:
            info["properties"] = _res.get_properties("allprop")
        # if "lstat" in namespaces:
        #     info["lstat"] = {
        #         k: getattr(_lstat, k) for k in dir(_lstat) if k.startswith("st_")
        #     }
        if "link" in namespaces:
            info["link"] = _res.get_href()
        # if "access" in namespaces:
        #     info["access"] = cls._make_access_from_stat(_stat)

        return Info(info)
Ejemplo n.º 9
0
 def test_epoch_to_datetime(self):
     self.assertEqual(epoch_to_datetime(142214400),
                      datetime(1974, 7, 5, tzinfo=timezone.utc))
Ejemplo n.º 10
0
 def test_epoch_to_datetime(self):
     self.assertEqual(epoch_to_datetime(142214400),
                      datetime(1974, 7, 5, tzinfo=pytz.UTC))