This is an automated email from the ASF dual-hosted git repository.
Xuanwo pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/opendal.git
The following commit(s) were added to refs/heads/main by this push:
new f4860ce2f5 feat(services/baidu-netdisk): add Baidu Netdisk support
(#8516)
f4860ce2f5 is described below
commit f4860ce2f50a83c0fd08e011b3c910f029157fd9
Author: Suyan <[email protected]>
AuthorDate: Mon Nov 30 22:13:49 2026 +0800
feat(services/baidu-netdisk): add Baidu Netdisk support (#8516)
* feat(services/baidu-netdisk): add Baidu Netdisk support
* fix(services/baidu-netdisk): validate directory operations
* fix(services/baidu-netdisk): preserve directory and prefix semantics
* test(services/baidu-netdisk): remove operation mock tests
* test(services/baidu-netdisk): remove remaining unit and doc tests
* fix(services/baidu-netdisk): bound writes and guard provider-specific
operations
* fix(services/baidu-netdisk): report confirmed upload metadata and HTTP
errors
* fix(services/baidu-netdisk): use native deletion for exact directory paths
* fix(services/baidu-netdisk): guard directory deletion and ambiguous
mutation retries
* fix(services/baidu-netdisk): distinguish explicit rejections from
ambiguous HTTP errors
* fix(services/baidu-netdisk): prevent replay after cancellation and verify
copy metadata
* fix(services/baidu-netdisk): leave timeout retries to the configured
layers
* refactor(services/baidu-netdisk): keep the copy destination ID local
* fix(services/baidu-netdisk): retry metadata lookup after acknowledged copy
* fix(http-transport-reqwest): redact credentials in error URLs
* fix(bindings/java): omit Baidu access tokens from diagnostic strings
* chore: format the Baidu Netdisk manifest
---------
Co-authored-by: Xuanwo <[email protected]>
---
.github/services/baidu_netdisk/README.md | 29 ++
bindings/dotnet/Cargo.toml | 1 +
.../ServiceConfig/BaiduNetdiskServiceConfig.cs | 57 ++++
bindings/java/Cargo.toml | 1 +
.../java/org/apache/opendal/ServiceConfig.java | 38 +++
bindings/python/Cargo.toml | 2 +
bindings/python/python/opendal/config.py | 13 +
bindings/python/python/opendal/services.pyi | 1 +
bindings/python/src/services.rs | 4 +
core/Cargo.lock | 27 ++
core/Cargo.toml | 2 +
core/services/baidu-netdisk/Cargo.toml | 45 +++
core/services/baidu-netdisk/README.md | 48 ++++
core/services/baidu-netdisk/src/backend.rs | 233 ++++++++++++++++
core/services/baidu-netdisk/src/config.rs | 57 ++++
core/services/baidu-netdisk/src/core.rs | 305 +++++++++++++++++++++
core/services/baidu-netdisk/src/deleter.rs | 73 +++++
core/services/baidu-netdisk/src/lib.rs | 38 +++
core/services/baidu-netdisk/src/lister.rs | 91 ++++++
core/services/baidu-netdisk/src/reader.rs | 126 +++++++++
core/services/baidu-netdisk/src/writer.rs | 219 +++++++++++++++
core/src/lib.rs | 5 +
core/tests/behavior/async_copy.rs | 29 ++
dev/src/generate/java.j2 | 15 +-
website/data/capabilities.json | 23 ++
website/data/services.json | 50 ++++
26 files changed, 1531 insertions(+), 1 deletion(-)
diff --git a/.github/services/baidu_netdisk/README.md
b/.github/services/baidu_netdisk/README.md
new file mode 100644
index 0000000000..f2d35ffe76
--- /dev/null
+++ b/.github/services/baidu_netdisk/README.md
@@ -0,0 +1,29 @@
+# Baidu Netdisk behavior tests
+
+Create a personal software application in the [Baidu Netdisk Open
Platform](https://pan.baidu.com/union/console/applist)
+and follow the [authorization flow](https://pan.baidu.com/union/doc/al0rwqzzl)
with the `basic,netdisk` OAuth scope.
+
+Each contributor can run the suite with their own development account and
+application. Keep the AppKey, SecretKey and tokens in a private credential
+store. For each run, supply a current access token and a dedicated directory
+under the application's root, for example `/apps/MyApp/opendal-tests/`.
+Keep the trailing slash. The testkit appends a random subdirectory and writes
+real files there. Remove that run directory after checking the results.
+
+Set only `OPENDAL_BAIDU_NETDISK_ACCESS_TOKEN` and `OPENDAL_BAIDU_NETDISK_ROOT`
+for this service in the shell or local `.env`, then run:
+
+```sh
+cd core
+OPENDAL_TEST=baidu-netdisk OPENDAL_TEST_IO_TIMEOUT=300 cargo test --locked
--test behavior --features tests,services-baidu-netdisk -- --test-threads=1
+```
+
+Only the access token reaches the test processes. Renew it before a run when
+necessary. Have one credential owner exchange the latest refresh token and
+atomically save the new token pair before starting another run. If the exchange
+outcome is unknown or the latest refresh token was lost, authorize the account
+again. Each contributor can obtain a separate grant without sharing
credentials.
+
+The shared emoji copy case skips Baidu. The Baidu-specific filename case
+checks that those emoji names are rejected, then copies a Chinese filename
+to an accented Latin filename and verifies the contents.
diff --git a/bindings/dotnet/Cargo.toml b/bindings/dotnet/Cargo.toml
index ef1063f6f0..b8aabc8a4c 100644
--- a/bindings/dotnet/Cargo.toml
+++ b/bindings/dotnet/Cargo.toml
@@ -133,6 +133,7 @@ opendal = { version = ">=0", path = "../../core", features
= [
"services-swift",
"services-goosefs",
"services-b2",
+ "services-baidu-netdisk",
"services-seafile",
"services-upyun",
"services-yandex-disk",
diff --git a/bindings/dotnet/OpenDAL/ServiceConfig/BaiduNetdiskServiceConfig.cs
b/bindings/dotnet/OpenDAL/ServiceConfig/BaiduNetdiskServiceConfig.cs
new file mode 100644
index 0000000000..e065833dfd
--- /dev/null
+++ b/bindings/dotnet/OpenDAL/ServiceConfig/BaiduNetdiskServiceConfig.cs
@@ -0,0 +1,57 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+// DO NOT EDIT IT MANUALLY. This file is generated by
opendal/dev/src/generate/dotnet.rs.
+
+using OpenDAL.ServiceConfig.Abstractions;
+
+namespace OpenDAL.ServiceConfig
+{
+ /// <summary>
+ /// Configuration for service baidu-netdisk.
+ /// </summary>
+ public sealed class BaiduNetdiskServiceConfig : IServiceConfig
+ {
+ /// <summary>
+ /// Required access token for the Baidu Netdisk Open Platform.
+ /// </summary>
+ public string? AccessToken { get; init; }
+ /// <summary>
+ /// Required absolute root inside `/apps/<application name>/`.
+ /// </summary>
+ public string? Root { get; init; }
+
+ public string Scheme => "baidu-netdisk";
+
+ public IReadOnlyDictionary<string, string> ToOptions()
+ {
+ var map = new Dictionary<string, string>();
+ if (AccessToken is not null)
+ {
+ map["access_token"] = Utilities.ToOptionString(AccessToken);
+ }
+ if (Root is not null)
+ {
+ map["root"] = Utilities.ToOptionString(Root);
+ }
+ return map;
+ }
+ }
+
+}
diff --git a/bindings/java/Cargo.toml b/bindings/java/Cargo.toml
index 9f24e2b7de..d9fede6c84 100644
--- a/bindings/java/Cargo.toml
+++ b/bindings/java/Cargo.toml
@@ -144,6 +144,7 @@ opendal = { version = ">=0", path = "../../core",
default-features = false, feat
"services-swift",
"services-goosefs",
"services-b2",
+ "services-baidu-netdisk",
"services-seafile",
"services-upyun",
"services-yandex-disk",
diff --git a/bindings/java/src/main/java/org/apache/opendal/ServiceConfig.java
b/bindings/java/src/main/java/org/apache/opendal/ServiceConfig.java
index 85cbd0fc02..a53915470a 100644
--- a/bindings/java/src/main/java/org/apache/opendal/ServiceConfig.java
+++ b/bindings/java/src/main/java/org/apache/opendal/ServiceConfig.java
@@ -687,6 +687,44 @@ public interface ServiceConfig {
}
}
+ /**
+ * Configuration for service baidu-netdisk.
+ */
+ @Builder
+ @Data
+ @ToString(exclude = "accessToken")
+ @RequiredArgsConstructor(access = AccessLevel.PRIVATE)
+ class BaiduNetdisk implements ServiceConfig {
+ /**
+ * <p>Required access token for the Baidu Netdisk Open Platform.</p>
+ */
+ public final @NonNull String accessToken;
+ /**
+ * <p>Required absolute root inside <code>/apps/<application
name>/</code>.</p>
+ */
+ public final @NonNull String root;
+
+ public static class BaiduNetdiskBuilder {
+ @Override
+ public String toString() {
+ return "BaiduNetdiskBuilder";
+ }
+ }
+
+ @Override
+ public String scheme() {
+ return "baidu-netdisk";
+ }
+
+ @Override
+ public Map<String, String> configMap() {
+ final HashMap<String, String> map = new HashMap<>();
+ map.put("access_token", accessToken);
+ map.put("root", root);
+ return map;
+ }
+ }
+
/**
* Configuration for service cacache.
*/
diff --git a/bindings/python/Cargo.toml b/bindings/python/Cargo.toml
index 7d6fc1446e..60274e65ab 100644
--- a/bindings/python/Cargo.toml
+++ b/bindings/python/Cargo.toml
@@ -84,6 +84,7 @@ services-all = [
'services-aliyun-drive',
'services-azfile',
'services-b2',
+ 'services-baidu-netdisk',
'services-cacache',
'services-dashmap',
'services-dropbox',
@@ -133,6 +134,7 @@ services-azdls = ["opendal/services-azdls"]
services-azfile = ["opendal/services-azfile"]
services-b2 = ["opendal/services-b2"]
services-b2-s3 = ["opendal/services-b2-s3"]
+services-baidu-netdisk = ["opendal/services-baidu-netdisk"]
services-cacache = ["opendal/services-cacache"]
services-ceph-rgw = ["opendal/services-ceph-rgw"]
services-cloudflare-kv = [
diff --git a/bindings/python/python/opendal/config.py
b/bindings/python/python/opendal/config.py
index 0360c9243f..1dc64c30ce 100644
--- a/bindings/python/python/opendal/config.py
+++ b/bindings/python/python/opendal/config.py
@@ -326,6 +326,17 @@ class B2S3Config(TypedDict):
"""Backblaze application key (`applicationKey`)."""
+class BaiduNetdiskConfig(TypedDict):
+ """Configuration for the `baidu-netdisk` service."""
+
+ scheme: Required[Literal["baidu-netdisk"]]
+ """The service scheme; fixed to `"baidu-netdisk"`."""
+ access_token: Required[str]
+ """Required access token for the Baidu Netdisk Open Platform."""
+ root: Required[str | os.PathLike[str]]
+ """Required absolute root inside `/apps/<application name>/`."""
+
+
class CacacheConfig(TypedDict):
"""Configuration for the `cacache` service."""
@@ -1898,6 +1909,7 @@ ServiceConfig = (
| AzfileConfig
| B2Config
| B2S3Config
+ | BaiduNetdiskConfig
| CacacheConfig
| CephRgwConfig
| CosConfig
@@ -1990,6 +2002,7 @@ __all__ = [
"AzfileConfig",
"B2Config",
"B2S3Config",
+ "BaiduNetdiskConfig",
"CacacheConfig",
"CephRgwConfig",
"CosConfig",
diff --git a/bindings/python/python/opendal/services.pyi
b/bindings/python/python/opendal/services.pyi
index 60d3cdf2f1..544754b3c2 100644
--- a/bindings/python/python/opendal/services.pyi
+++ b/bindings/python/python/opendal/services.pyi
@@ -28,6 +28,7 @@ class Scheme:
Azfile: Final[Scheme]
B2: Final[Scheme]
B2s3: Final[Scheme]
+ BaiduNetdisk: Final[Scheme]
Cacache: Final[Scheme]
CephRgw: Final[Scheme]
Cos: Final[Scheme]
diff --git a/bindings/python/src/services.rs b/bindings/python/src/services.rs
index 59a36db3a1..3817003c9e 100644
--- a/bindings/python/src/services.rs
+++ b/bindings/python/src/services.rs
@@ -43,6 +43,8 @@ pub enum Scheme {
B2,
#[cfg(feature = "services-b2-s3")]
B2S3,
+ #[cfg(feature = "services-baidu-netdisk")]
+ BaiduNetdisk,
#[cfg(feature = "services-cacache")]
Cacache,
#[cfg(feature = "services-ceph-rgw")]
@@ -243,6 +245,8 @@ impl_enum_to_str!(
B2 => "b2",
#[cfg(feature = "services-b2-s3")]
B2S3 => "b2-s3",
+ #[cfg(feature = "services-baidu-netdisk")]
+ BaiduNetdisk => "baidu-netdisk",
#[cfg(feature = "services-cacache")]
Cacache => "cacache",
#[cfg(feature = "services-ceph-rgw")]
diff --git a/core/Cargo.lock b/core/Cargo.lock
index 250f65d723..282b9bde86 100644
--- a/core/Cargo.lock
+++ b/core/Cargo.lock
@@ -7057,6 +7057,7 @@ dependencies = [
"opendal-service-azdls",
"opendal-service-azfile",
"opendal-service-b2",
+ "opendal-service-baidu-netdisk",
"opendal-service-cacache",
"opendal-service-cloudflare-kv",
"opendal-service-compfs",
@@ -7733,6 +7734,21 @@ dependencies = [
"tokio",
]
+[[package]]
+name = "opendal-service-baidu-netdisk"
+version = "0.59.5"
+dependencies = [
+ "bytes",
+ "form_urlencoded",
+ "hex",
+ "http 1.5.0",
+ "md-5",
+ "opendal-core",
+ "reqsign-baidu-netdisk",
+ "serde",
+ "serde_json",
+]
+
[[package]]
name = "opendal-service-cacache"
version = "0.59.5"
@@ -10105,6 +10121,17 @@ dependencies = [
"serde_json",
]
+[[package]]
+name = "reqsign-baidu-netdisk"
+version = "1.0.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "5ec06d236458fef3a11f5c1a7a6900a5ef003caf88156fd937d6dbedc812ce80"
+dependencies = [
+ "form_urlencoded",
+ "http 1.5.0",
+ "reqsign-core",
+]
+
[[package]]
name = "reqsign-command-execute-tokio"
version = "4.0.0"
diff --git a/core/Cargo.toml b/core/Cargo.toml
index de543fb808..e8ca186039 100644
--- a/core/Cargo.toml
+++ b/core/Cargo.toml
@@ -182,6 +182,7 @@ services-azdls = ["dep:opendal-service-azdls"]
services-azfile = ["dep:opendal-service-azfile"]
services-b2 = ["dep:opendal-service-b2"]
services-b2-s3 = ["dep:opendal-service-s3"]
+services-baidu-netdisk = ["dep:opendal-service-baidu-netdisk"]
services-cacache = ["dep:opendal-service-cacache"]
services-ceph-rgw = ["dep:opendal-service-s3"]
services-cloudflare-kv = ["dep:opendal-service-cloudflare-kv"]
@@ -343,6 +344,7 @@ opendal-service-azblob = { path = "services/azblob",
version = "0.59.5", optiona
opendal-service-azdls = { path = "services/azdls", version = "0.59.5",
optional = true, default-features = false }
opendal-service-azfile = { path = "services/azfile", version = "0.59.5",
optional = true, default-features = false }
opendal-service-b2 = { path = "services/b2", version = "0.59.5", optional =
true, default-features = false }
+opendal-service-baidu-netdisk = { path = "services/baidu-netdisk", version =
"0.59.5", optional = true, default-features = false }
opendal-service-cacache = { path = "services/cacache", version = "0.59.5",
optional = true, default-features = false }
opendal-service-cloudflare-kv = { path = "services/cloudflare-kv", version =
"0.59.5", optional = true, default-features = false }
opendal-service-compfs = { path = "services/compfs", version = "0.59.5",
optional = true, default-features = false }
diff --git a/core/services/baidu-netdisk/Cargo.toml
b/core/services/baidu-netdisk/Cargo.toml
new file mode 100644
index 0000000000..5efd04a4b7
--- /dev/null
+++ b/core/services/baidu-netdisk/Cargo.toml
@@ -0,0 +1,45 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+
+[package]
+description = "Apache OpenDAL Baidu Netdisk service implementation"
+name = "opendal-service-baidu-netdisk"
+readme = "README.md"
+
+authors = { workspace = true }
+edition = { workspace = true }
+homepage = { workspace = true }
+license = { workspace = true }
+repository = { workspace = true }
+rust-version = { workspace = true }
+version = { workspace = true }
+
+[package.metadata.docs.rs]
+all-features = true
+
+[dependencies]
+bytes = { workspace = true }
+form_urlencoded = "1"
+hex = "0.4"
+http = { workspace = true }
+md-5 = "0.11"
+opendal-core = { path = "../../core", version = "0.59.5", default-features =
false, features = [
+ "reqsign",
+] }
+reqsign-baidu-netdisk = "1.0.0"
+serde = { workspace = true, features = ["derive"] }
+serde_json = { workspace = true }
diff --git a/core/services/baidu-netdisk/README.md
b/core/services/baidu-netdisk/README.md
new file mode 100644
index 0000000000..29be4620f3
--- /dev/null
+++ b/core/services/baidu-netdisk/README.md
@@ -0,0 +1,48 @@
+# Baidu Netdisk
+
+Baidu Netdisk Open Platform support, using the official xpan APIs.
+
+Set `root` to `/apps/<application name>/` or a directory below it, and set
+`access_token` to a token authorized for `basic,netdisk`.
+
+```rust,ignore
+use opendal_core::Operator;
+use opendal_service_baidu_netdisk::BaiduNetdisk;
+
+let operator = Operator::new(BaiduNetdisk::default()
+ .root("/apps/MyApp/data/")
+ .access_token("access-token"))?;
+```
+
+The service supports stat, list, ranged reads, create directory, write, copy
+and delete. Baidu requires all block hashes before it opens an upload. Each
+writer accepts one payload of up to 16 MiB, retains it until close or abort,
+and uploads it in 4 MiB blocks. Larger writes and a second write to the same
+writer return `Unsupported`. A successful write returns the stored size. Use
+stat to obtain the server modification time. Account membership affects
download speed.
+
+Baidu accepts ordinary Chinese and accented Latin names. The metadata lookup
+before upload rejects the tested emoji and supplementary character `𠮷` with
+parameter error `31023`. The create API can also reject names with error `-7`
+and identify the characters in `illegal_chars`. The service preserves the path
+and returns the API error.
+
+Copy accepts file sources and rejects existing directory destinations. After
+a successful copy, the service looks up the destination metadata by path and
+checks its file ID against the copy response. Once Baidu acknowledges the copy,
+a retry of this lookup reuses the returned ID.
+Baidu's native move rejects an existing destination, so the service omits
rename.
+
+Delete targets the exact file or directory. Ordinary deletion checks a
directory
+for children and rejects a non-empty directory. Baidu only provides recursive
+directory deletion, so the emptiness check and deletion are separate requests.
+Callers must serialize writes into the directory and replacements of the target
+when using ordinary deletion. An explicit recursive delete removes the target
+directory and its contents. Similarly named siblings are preserved.
+
+The caller obtains and renews the access token and builds a new operator when
+the token changes. Baidu returns `PermissionDenied` for an expired token.
+
+Official documentation: <https://pan.baidu.com/union/doc/>.
+
+Licensed under the Apache License, Version 2.0.
diff --git a/core/services/baidu-netdisk/src/backend.rs
b/core/services/baidu-netdisk/src/backend.rs
new file mode 100644
index 0000000000..7ffa494b60
--- /dev/null
+++ b/core/services/baidu-netdisk/src/backend.rs
@@ -0,0 +1,233 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+use crate::{
+ BAIDU_NETDISK_SCHEME,
+ config::BaiduNetdiskConfig,
+ core::BaiduNetdiskCore,
+ deleter::BaiduNetdiskDeleter,
+ lister::BaiduNetdiskLister,
+ reader::BaiduNetdiskReader,
+ writer::{BaiduNetdiskWriter, MAX_WRITE_SIZE},
+};
+use opendal_core::reqsign_core::{Context, Signer};
+use opendal_core::{raw::*, *};
+use reqsign_baidu_netdisk::{RequestSigner, StaticCredentialProvider};
+use std::sync::{Arc, OnceLock};
+
+/// Builds an operator for the Baidu Netdisk Open Platform.
+///
+/// The root must be inside the application's `/apps/<application name>/`
folder.
+/// Writes require the complete file before uploading so all block hashes are
known.
+#[derive(Default)]
+pub struct BaiduNetdiskBuilder {
+ pub(super) config: BaiduNetdiskConfig,
+}
+
+impl std::fmt::Debug for BaiduNetdiskBuilder {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ f.debug_struct("BaiduNetdiskBuilder")
+ .field("config", &self.config)
+ .finish_non_exhaustive()
+ }
+}
+
+impl BaiduNetdiskBuilder {
+ /// Set the application directory used for every operation.
+ pub fn root(mut self, root: &str) -> Self {
+ self.config.root = Some(root.into());
+ self
+ }
+ /// Set the access token. The caller manages authorization and renewal.
+ pub fn access_token(mut self, token: &str) -> Self {
+ self.config.access_token = Some(token.into());
+ self
+ }
+}
+
+impl Builder for BaiduNetdiskBuilder {
+ type Config = BaiduNetdiskConfig;
+ fn build(self) -> Result<impl Service> {
+ let root =
normalize_root(self.config.root.as_deref().unwrap_or_default());
+ if !root.starts_with("/apps/") ||
root.trim_matches('/').split('/').count() < 2 {
+ return Err(Error::new(
+ ErrorKind::ConfigInvalid,
+ "root must be inside /apps/<application name>/",
+ ));
+ }
+ let access_token = self
+ .config
+ .access_token
+ .filter(|v| !v.is_empty())
+ .ok_or_else(|| Error::new(ErrorKind::ConfigInvalid, "access_token
is required"))?;
+ Ok(BaiduNetdiskBackend {
+ core: Arc::new(BaiduNetdiskCore {
+ info: ServiceInfo::new(BAIDU_NETDISK_SCHEME, &root, ""),
+ root,
+ signer: Signer::new(
+ Context::new(),
+ StaticCredentialProvider::new(access_token),
+ RequestSigner::new(),
+ ),
+ }),
+ })
+ }
+}
+
+#[derive(Debug, Clone)]
+pub struct BaiduNetdiskBackend {
+ pub core: Arc<BaiduNetdiskCore>,
+}
+
+impl Service for BaiduNetdiskBackend {
+ type Reader = oio::StreamReader<BaiduNetdiskReader>;
+ type Writer = BaiduNetdiskWriter;
+ type Lister = oio::PageLister<BaiduNetdiskLister>;
+ type Deleter = oio::OneShotDeleter<BaiduNetdiskDeleter>;
+ type Copier = oio::OneShotCopier;
+ type Composer = ();
+
+ fn info(&self) -> ServiceInfo {
+ self.core.info.clone()
+ }
+ fn capability(&self) -> Capability {
+ Capability {
+ stat: true,
+ read: true,
+ read_with_suffix: true,
+ write: true,
+ write_can_empty: true,
+ write_total_max_size: Some(MAX_WRITE_SIZE),
+ create_dir: true,
+ list: true,
+ list_with_limit: true,
+ delete: true,
+ delete_with_recursive: true,
+ copy: true,
+ shared: true,
+ ..Default::default()
+ }
+ }
+ async fn presign(&self, _: &OperationContext, _: &str, _: OpPresign) ->
Result<RpPresign> {
+ Err(Error::new(
+ ErrorKind::Unsupported,
+ "Baidu Netdisk does not support presigning",
+ ))
+ }
+ async fn stat(&self, ctx: &OperationContext, path: &str, _: OpStat) ->
Result<RpStat> {
+ Ok(RpStat::new(self.core.stat(ctx, path).await?.metadata()?))
+ }
+ async fn create_dir(
+ &self,
+ ctx: &OperationContext,
+ path: &str,
+ _: OpCreateDir,
+ ) -> Result<RpCreateDir> {
+ self.core.create_dir(ctx, path).await?;
+ Ok(RpCreateDir::default())
+ }
+ fn read(&self, ctx: &OperationContext, path: &str, _: OpRead) ->
Result<Self::Reader> {
+ Ok(oio::StreamReader::new(BaiduNetdiskReader {
+ core: self.core.clone(),
+ ctx: ctx.clone(),
+ path: path.into(),
+ }))
+ }
+ fn write(&self, ctx: &OperationContext, path: &str, _: OpWrite) ->
Result<Self::Writer> {
+ Ok(BaiduNetdiskWriter {
+ buffer: None,
+ core: self.core.clone(),
+ ctx: ctx.clone(),
+ path: path.into(),
+ })
+ }
+ fn list(&self, ctx: &OperationContext, path: &str, args: OpList) ->
Result<Self::Lister> {
+ Ok(oio::PageLister::new(BaiduNetdiskLister {
+ core: self.core.clone(),
+ ctx: ctx.clone(),
+ path: path.into(),
+ limit: args.limit().unwrap_or(1000).clamp(1, 1000),
+ }))
+ }
+ fn delete(&self, ctx: &OperationContext) -> Result<Self::Deleter> {
+ Ok(oio::OneShotDeleter::new(BaiduNetdiskDeleter {
+ core: self.core.clone(),
+ ctx: ctx.clone(),
+ }))
+ }
+ fn copy(
+ &self,
+ ctx: &OperationContext,
+ from: &str,
+ to: &str,
+ _: OpCopy,
+ ) -> Result<Self::Copier> {
+ let core = self.core.clone();
+ let ctx = ctx.clone();
+ let from = from.to_string();
+ let to = to.to_string();
+ let destination_id = Arc::new(OnceLock::new());
+ // Rebuild the request so RetryLayer can retry filemanager's busy
errors.
+ Ok(oio::OneShotCopier::new_with(move || {
+ let core = core.clone();
+ let ctx = ctx.clone();
+ let from = from.clone();
+ let to = to.clone();
+ let destination_id = destination_id.clone();
+ async move {
+ let id = match destination_id.get() {
+ Some(id) => *id,
+ None => {
+ let source = core.stat(&ctx, &from).await?;
+ if source.isdir == 1 {
+ return Err(Error::new(
+ ErrorKind::IsADirectory,
+ "copy source is a directory",
+ ));
+ }
+ if from == to {
+ return source.metadata();
+ }
+ let id = core.copy(&ctx, &from, &to).await?;
+ // A retry after this point must only repeat the
metadata lookup.
+ *destination_id.get_or_init(|| id)
+ }
+ };
+ let destination = core.stat(&ctx, &to).await?;
+ if destination.fs_id != id {
+ return Err(Error::new(
+ ErrorKind::Unexpected,
+ "copy destination was replaced",
+ ));
+ }
+ destination.metadata()
+ }
+ }))
+ }
+ async fn rename(
+ &self,
+ _: &OperationContext,
+ _: &str,
+ _: &str,
+ _: OpRename,
+ ) -> Result<RpRename> {
+ Err(Error::new(
+ ErrorKind::Unsupported,
+ "Baidu Netdisk does not support rename with overwrite",
+ ))
+ }
+}
diff --git a/core/services/baidu-netdisk/src/config.rs
b/core/services/baidu-netdisk/src/config.rs
new file mode 100644
index 0000000000..8f33140894
--- /dev/null
+++ b/core/services/baidu-netdisk/src/config.rs
@@ -0,0 +1,57 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+use crate::backend::BaiduNetdiskBuilder;
+use opendal_core::*;
+use serde::{Deserialize, Serialize};
+use std::fmt;
+
+/// Configuration for the Baidu Netdisk Open Platform.
+#[derive(Default, Clone, Serialize, Deserialize, PartialEq, Eq)]
+#[serde(default)]
+#[non_exhaustive]
+pub struct BaiduNetdiskConfig {
+ /// Required absolute root inside `/apps/<application name>/`.
+ /// <!-- @required true -->
+ /// <!-- @example /apps/MyApp/data/ -->
+ pub root: Option<String>,
+ /// Required access token for the Baidu Netdisk Open Platform.
+ /// <!-- @required true -->
+ pub access_token: Option<String>,
+}
+
+impl fmt::Debug for BaiduNetdiskConfig {
+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+ f.debug_struct("BaiduNetdiskConfig")
+ .field("root", &self.root)
+ .finish_non_exhaustive()
+ }
+}
+
+impl Configurator for BaiduNetdiskConfig {
+ type Builder = BaiduNetdiskBuilder;
+ fn from_uri(uri: &OperatorUri) -> Result<Self> {
+ let mut map = uri.options().clone();
+ if let Some(root) = uri.root() {
+ map.insert("root".into(), root.into());
+ }
+ Self::from_iter(map)
+ }
+ fn into_builder(self) -> Self::Builder {
+ BaiduNetdiskBuilder { config: self }
+ }
+}
diff --git a/core/services/baidu-netdisk/src/core.rs
b/core/services/baidu-netdisk/src/core.rs
new file mode 100644
index 0000000000..858c85460e
--- /dev/null
+++ b/core/services/baidu-netdisk/src/core.rs
@@ -0,0 +1,305 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+use bytes::Buf;
+use http::{Request, Response, StatusCode, header};
+use opendal_core::reqsign_core::Signer;
+use opendal_core::{raw::*, *};
+use reqsign_baidu_netdisk::Credential;
+use serde::Deserialize;
+use serde_json::{Value, json};
+
+pub const FILE_API: &str = "https://pan.baidu.com/rest/2.0/xpan/file";
+
+pub struct BaiduNetdiskCore {
+ pub info: ServiceInfo,
+ pub root: String,
+ pub signer: Signer<Credential>,
+}
+
+impl std::fmt::Debug for BaiduNetdiskCore {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ f.debug_struct("BaiduNetdiskCore")
+ .field("root", &self.root)
+ .finish_non_exhaustive()
+ }
+}
+
+impl BaiduNetdiskCore {
+ pub fn absolute_path(&self, path: &str) -> String {
+ build_rooted_absolute_path(&self.root, path)
+ .trim_end_matches('/')
+ .to_string()
+ }
+ pub async fn sign(&self, req: Request<Buffer>) -> Result<Request<Buffer>> {
+ let (mut parts, body) = req.into_parts();
+ parts.headers.insert(
+ header::USER_AGENT,
+ header::HeaderValue::from_static("pan.baidu.com"),
+ );
+ self.signer
+ .sign(&mut parts, None)
+ .await
+ .map_err(|err| new_request_sign_error(err.into()))?;
+ Ok(Request::from_parts(parts, body))
+ }
+
+ pub async fn send(&self, ctx: &OperationContext, req: Request<Buffer>) ->
Result<Value> {
+ let uri = req.uri().clone();
+ let method = uri.query().and_then(|query| {
+ query
+ .split('&')
+ .find_map(|pair| pair.strip_prefix("method="))
+ });
+ let req = self.sign(req).await?;
+ let commit = matches!(method, Some("create" | "filemanager"));
+ let response = ctx
+ .http_transport()
+ .send(req)
+ .await
+ .map_err(|e| if commit { e.set_permanent() } else { e })?;
+ parse_response(response, method)
+ }
+ pub async fn stat(&self, ctx: &OperationContext, path: &str) ->
Result<FileMetadata> {
+ let query = form_urlencoded::Serializer::new(String::new())
+ .append_pair("method", "meta")
+ .append_pair("path", &self.absolute_path(path))
+ .finish();
+ let req = Request::get(format!("{FILE_API}?{query}"))
+ .body(Buffer::new())
+ .map_err(new_request_build_error)?;
+ let response = self.send(ctx, req).await?;
+ let result: FileList =
+
serde_json::from_value(response).map_err(new_json_deserialize_error)?;
+ let file =
+ result.list.into_iter().next().ok_or_else(|| {
+ Error::new(ErrorKind::NotFound, "Baidu Netdisk path does not
exist")
+ })?;
+ if path.ends_with('/') && file.isdir != 1 {
+ return Err(Error::new(ErrorKind::NotFound, "path is not a
directory"));
+ }
+ Ok(file)
+ }
+ pub async fn create_dir(&self, ctx: &OperationContext, path: &str) ->
Result<()> {
+ let form = form_urlencoded::Serializer::new(String::new())
+ .append_pair("path", &self.absolute_path(path))
+ .append_pair("isdir", "1")
+ .append_pair("rtype", "0")
+ .finish();
+ let req = Request::post(format!("{FILE_API}?method=create"))
+ .header(header::CONTENT_TYPE, "application/x-www-form-urlencoded")
+ .body(Buffer::from(form))
+ .map_err(new_request_build_error)?;
+ match self.send(ctx, req).await {
+ Ok(_) => Ok(()),
+ Err(e) if e.kind() == ErrorKind::AlreadyExists => {
+ if self.stat(ctx, path.trim_end_matches('/')).await?.isdir ==
1 {
+ Ok(())
+ } else {
+ Err(Error::new(ErrorKind::NotADirectory, "path is a file"))
+ }
+ }
+ Err(e) => Err(e),
+ }
+ }
+ pub async fn manage(
+ &self,
+ ctx: &OperationContext,
+ operation: &str,
+ files: Value,
+ ) -> Result<Value> {
+ let form = form_urlencoded::Serializer::new(String::new())
+ .append_pair("async", "0")
+ .append_pair("ondup", "overwrite")
+ .append_pair("filelist", &files.to_string())
+ .finish();
+ let req =
Request::post(format!("{FILE_API}?method=filemanager&opera={operation}"))
+ .header(header::CONTENT_TYPE, "application/x-www-form-urlencoded")
+ .body(Buffer::from(form))
+ .map_err(new_request_build_error)?;
+ let result = self.send(ctx, req).await?;
+ if result.get("taskid").is_some() {
+ return Err(Error::new(
+ ErrorKind::Unexpected,
+ "Baidu Netdisk returned an asynchronous task for a synchronous
request",
+ ));
+ }
+ let item = result["info"]
+ .as_array()
+ .and_then(|items| items.first())
+ .ok_or_else(|| Error::new(ErrorKind::Unexpected, "missing
filemanager result"))?;
+ let code = item["errno"]
+ .as_i64()
+ .ok_or_else(|| Error::new(ErrorKind::Unexpected, "missing
filemanager result errno"))?;
+ if code != 0 {
+ return Err(api_error(code));
+ }
+ Ok(item.clone())
+ }
+ pub async fn copy(&self, ctx: &OperationContext, from: &str, to: &str) ->
Result<u64> {
+ match self.stat(ctx, to).await {
+ Ok(file) if file.isdir == 1 => {
+ return Err(Error::new(
+ ErrorKind::IsADirectory,
+ "copy destination is a directory",
+ ));
+ }
+ Err(e) if e.kind() != ErrorKind::NotFound => return Err(e),
+ _ => {}
+ }
+ self.create_dir(ctx, get_parent(to)).await?;
+ let item = self.manage(ctx, "copy",
json!([{"path":self.absolute_path(from),
+ "dest":self.absolute_path(get_parent(to)),
"newname":get_basename(to), "ondup":"overwrite"}])).await?;
+ item["to_fs_id"]
+ .as_u64()
+ .ok_or_else(|| Error::new(ErrorKind::Unexpected, "missing copy
destination ID"))
+ }
+}
+
+#[derive(Deserialize)]
+pub struct FileList {
+ pub list: Vec<FileMetadata>,
+}
+
+#[derive(Deserialize)]
+pub struct FileMetadata {
+ pub fs_id: u64,
+ pub path: String,
+ pub isdir: u8,
+ #[serde(default)]
+ pub size: u64,
+ pub mtime: Option<i64>,
+ pub server_mtime: Option<i64>,
+ pub dlink: Option<String>,
+}
+
+impl FileMetadata {
+ pub fn metadata(&self) -> Result<Metadata> {
+ let mut metadata = if self.isdir == 1 {
+ MetadataBuilder::dir()
+ } else {
+ MetadataBuilder::file(self.size)
+ };
+ if let Some(time) = self.server_mtime.or(self.mtime) {
+ metadata.last_modified(Timestamp::from_second(time).map_err(|e| {
+ Error::new(
+ ErrorKind::Unexpected,
+ "invalid Baidu Netdisk modification time",
+ )
+ .set_source(e)
+ })?);
+ }
+ Ok(metadata.build())
+ }
+}
+
+pub fn api_error(code: i64) -> Error {
+ let kind = match code {
+ -9 | 31066 | 31190 => ErrorKind::NotFound,
+ -8 => ErrorKind::AlreadyExists,
+ -7 | 6 | 110 | 31024 | 31045 | 20011 => ErrorKind::PermissionDenied,
+ // The metadata lookup before upload can return this parameter error
for emoji paths.
+ 31023 => ErrorKind::ConfigInvalid,
+ 31034 => ErrorKind::RateLimited,
+ _ => ErrorKind::Unexpected,
+ };
+ let error = Error::new(kind, "Baidu Netdisk API request failed")
+ .with_context("errno", code.to_string());
+ if code == 111 || code == 31034 {
+ error.set_temporary()
+ } else {
+ error
+ }
+}
+
+fn response_json(response: Response<Buffer>, method: Option<&str>) ->
Result<Value> {
+ let status = response.status();
+ serde_json::from_reader(response.into_body().reader()).map_err(|source| {
+ let mut error = if status.is_success() {
+ new_json_deserialize_error(source).with_context("status",
status.as_str())
+ } else {
+ http_error(status, method).set_source(source)
+ };
+ if let Some(method) = method {
+ error = error.with_context("baidu_method", method);
+ }
+ error
+ })
+}
+
+pub fn parse_response(response: Response<Buffer>, method: Option<&str>) ->
Result<Value> {
+ check_response(response.status(), response_json(response, method)?, method)
+}
+
+fn check_response(status: StatusCode, value: Value, method: Option<&str>) ->
Result<Value> {
+ if value["error_code"].as_i64() == Some(111) {
+ return Err(Error::new(
+ ErrorKind::PermissionDenied,
+ "Baidu Netdisk access token expired",
+ ));
+ }
+ if value["errno"].as_i64() == Some(12)
+ && let Some(items) = value["info"].as_array()
+ && let Some(code) = items
+ .iter()
+ .filter_map(|item| item["errno"].as_i64())
+ .find(|code| *code != 0)
+ {
+ return Err(api_error(code));
+ }
+ if let Some(code) = value["errno"]
+ .as_i64()
+ .or_else(|| value["error_code"].as_i64())
+ .filter(|code| *code != 0)
+ {
+ if code == -7
+ && let Some(chars) = value["illegal_chars"].as_str().filter(|v|
!v.is_empty())
+ {
+ return Err(Error::new(
+ ErrorKind::PermissionDenied,
+ "Baidu Netdisk rejected characters in the file name",
+ )
+ .with_context("errno", "-7")
+ .with_context("illegal_chars", chars.to_string()));
+ }
+ return Err(api_error(code));
+ }
+ if !status.is_success() {
+ return Err(http_error(status, method));
+ }
+ Ok(value)
+}
+
+fn http_error(status: StatusCode, method: Option<&str>) -> Error {
+ let kind = match status {
+ StatusCode::NOT_FOUND => ErrorKind::NotFound,
+ StatusCode::FORBIDDEN | StatusCode::UNAUTHORIZED =>
ErrorKind::PermissionDenied,
+ StatusCode::TOO_MANY_REQUESTS => ErrorKind::RateLimited,
+ _ => ErrorKind::Unexpected,
+ };
+ let error = Error::new(kind, "Baidu Netdisk HTTP request failed")
+ .with_context("status", status.as_str());
+ // An unclassified server error after a mutation leaves its outcome
unknown.
+ // Explicit Baidu rejections (including filemanager busy) are parsed first.
+ if status == StatusCode::TOO_MANY_REQUESTS
+ || (status.is_server_error() && !matches!(method, Some("create" |
"filemanager")))
+ {
+ error.set_temporary()
+ } else {
+ error
+ }
+}
diff --git a/core/services/baidu-netdisk/src/deleter.rs
b/core/services/baidu-netdisk/src/deleter.rs
new file mode 100644
index 0000000000..a4fae221cb
--- /dev/null
+++ b/core/services/baidu-netdisk/src/deleter.rs
@@ -0,0 +1,73 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+use crate::core::{BaiduNetdiskCore, FILE_API, FileList};
+use http::Request;
+use opendal_core::{raw::*, *};
+use std::sync::Arc;
+
+pub struct BaiduNetdiskDeleter {
+ pub core: Arc<BaiduNetdiskCore>,
+ pub ctx: OperationContext,
+}
+impl oio::OneShotDelete for BaiduNetdiskDeleter {
+ async fn delete_once(&self, path: String, args: OpDelete) -> Result<()> {
+ let file = match self.core.stat(&self.ctx, &path).await {
+ Ok(file) => file,
+ Err(e) if e.kind() == ErrorKind::NotFound => return Ok(()),
+ Err(e) => return Err(e),
+ };
+ if !args.recursive() && file.isdir == 1 {
+ // Baidu always deletes directories recursively. Check for children
+ // before issuing a non-recursive delete, including paths without
'/'.
+ let query = form_urlencoded::Serializer::new(String::new())
+ .append_pair("method", "list")
+ .append_pair("dir", &self.core.absolute_path(&path))
+ .append_pair("start", "0")
+ .append_pair("limit", "1")
+ .finish();
+ let req = Request::get(format!("{FILE_API}?{query}"))
+ .body(Buffer::new())
+ .map_err(new_request_build_error)?;
+ let value = match self.core.send(&self.ctx, req).await {
+ Ok(value) => value,
+ Err(e) if e.kind() == ErrorKind::NotFound => return Ok(()),
+ Err(e) => return Err(e),
+ };
+ let children: FileList =
+
serde_json::from_value(value).map_err(new_json_deserialize_error)?;
+ if !children.list.is_empty() {
+ return Err(Error::new(
+ ErrorKind::IsADirectory,
+ "cannot delete a non-empty directory without
recursive=true",
+ ));
+ }
+ }
+ match self
+ .core
+ .manage(
+ &self.ctx,
+ "delete",
+ serde_json::json!([self.core.absolute_path(&path)]),
+ )
+ .await
+ {
+ Err(e) if e.kind() == ErrorKind::NotFound => Ok(()),
+ result => result.map(|_| ()),
+ }
+ }
+}
diff --git a/core/services/baidu-netdisk/src/lib.rs
b/core/services/baidu-netdisk/src/lib.rs
new file mode 100644
index 0000000000..21a316cd89
--- /dev/null
+++ b/core/services/baidu-netdisk/src/lib.rs
@@ -0,0 +1,38 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+#![doc = include_str!("../README.md")]
+#![deny(missing_docs)]
+
+/// URI scheme for Baidu Netdisk.
+pub const BAIDU_NETDISK_SCHEME: &str = "baidu-netdisk";
+
+/// Register Baidu Netdisk for scheme-driven operator construction.
+pub fn register_baidu_netdisk_service(registry:
&opendal_core::OperatorRegistry) {
+ registry.register::<BaiduNetdisk>(BAIDU_NETDISK_SCHEME);
+}
+
+mod backend;
+mod config;
+mod core;
+mod deleter;
+mod lister;
+mod reader;
+mod writer;
+
+pub use backend::BaiduNetdiskBuilder as BaiduNetdisk;
+pub use config::BaiduNetdiskConfig;
diff --git a/core/services/baidu-netdisk/src/lister.rs
b/core/services/baidu-netdisk/src/lister.rs
new file mode 100644
index 0000000000..ecbe7426ea
--- /dev/null
+++ b/core/services/baidu-netdisk/src/lister.rs
@@ -0,0 +1,91 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+use crate::core::{BaiduNetdiskCore, FILE_API, FileList};
+use http::Request;
+use opendal_core::{raw::*, *};
+use std::sync::Arc;
+
+pub struct BaiduNetdiskLister {
+ pub core: Arc<BaiduNetdiskCore>,
+ pub ctx: OperationContext,
+ pub path: String,
+ pub limit: usize,
+}
+impl oio::PageList for BaiduNetdiskLister {
+ async fn next_page(&self, page: &mut oio::PageContext) -> Result<()> {
+ let mut entries = Vec::new();
+ if page.token.is_empty() {
+ let file = match self.core.stat(&self.ctx, &self.path).await {
+ Ok(file) => file,
+ Err(e) if e.kind() == ErrorKind::NotFound => {
+ page.done = true;
+ return Ok(());
+ }
+ Err(e) => return Err(e),
+ };
+ let mut path = self.path.clone();
+ if file.isdir == 1 && !path.ends_with('/') {
+ path.push('/');
+ }
+ entries.push(oio::Entry::new(&path, file.metadata()?));
+ if !self.path.ends_with('/') || file.isdir != 1 {
+ page.entries.extend(entries);
+ page.done = true;
+ return Ok(());
+ }
+ }
+ let start = if page.token.is_empty() {
+ 0
+ } else {
+ page.token.parse::<usize>().map_err(|e| {
+ Error::new(ErrorKind::Unexpected, "invalid list
offset").set_source(e)
+ })?
+ };
+ let query = form_urlencoded::Serializer::new(String::new())
+ .append_pair("method", "list")
+ .append_pair("dir", &self.core.absolute_path(&self.path))
+ .append_pair("start", &start.to_string())
+ .append_pair("limit", &self.limit.to_string())
+ .append_pair("order", "name")
+ .finish();
+ let req = Request::get(format!("{FILE_API}?{query}"))
+ .body(Buffer::new())
+ .map_err(new_request_build_error)?;
+ let value = match self.core.send(&self.ctx, req).await {
+ Ok(v) => v,
+ Err(e) if e.kind() == ErrorKind::NotFound => {
+ page.done = true;
+ return Ok(());
+ }
+ Err(e) => return Err(e),
+ };
+ let result: FileList =
serde_json::from_value(value).map_err(new_json_deserialize_error)?;
+ let count = result.list.len();
+ for file in result.list {
+ let mut path = build_relative_path(&self.core.root, &file.path);
+ if file.isdir == 1 {
+ path.push('/');
+ }
+ entries.push(oio::Entry::new(&path, file.metadata()?));
+ }
+ page.entries.extend(entries);
+ page.done = count < self.limit;
+ page.token = (start + count).to_string();
+ Ok(())
+ }
+}
diff --git a/core/services/baidu-netdisk/src/reader.rs
b/core/services/baidu-netdisk/src/reader.rs
new file mode 100644
index 0000000000..aa71ae1eef
--- /dev/null
+++ b/core/services/baidu-netdisk/src/reader.rs
@@ -0,0 +1,126 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+use crate::core::{BaiduNetdiskCore, FileList, parse_response};
+use http::{Request, Response, StatusCode, header};
+use opendal_core::{raw::*, *};
+use std::sync::Arc;
+
+pub struct BaiduNetdiskReader {
+ pub core: Arc<BaiduNetdiskCore>,
+ pub ctx: OperationContext,
+ pub path: String,
+}
+impl oio::StreamRead for BaiduNetdiskReader {
+ async fn open(&self, range: BytesRange) -> Result<(RpRead, Box<dyn
oio::ReadStreamDyn>)> {
+ let file = self.core.stat(&self.ctx, &self.path).await?;
+ if file.isdir == 1 {
+ return Err(Error::new(
+ ErrorKind::IsADirectory,
+ "cannot read a directory",
+ ));
+ }
+ if !range.is_full() {
+ if range.size() == Some(0) || (range.is_suffix() && file.size ==
0) {
+ return Ok((RpRead::new(file.metadata()?),
Box::new(Buffer::new())));
+ }
+ if !range.is_suffix() && range.offset() >= file.size {
+ if range.size().is_none() {
+ return Ok((RpRead::new(file.metadata()?),
Box::new(Buffer::new())));
+ }
+ return Err(Error::new(
+ ErrorKind::RangeNotSatisfied,
+ "range starts beyond the file",
+ ));
+ }
+ }
+ let query = form_urlencoded::Serializer::new(String::new())
+ .append_pair("method", "filemetas")
+ .append_pair("fsids", &format!("[{}]", file.fs_id))
+ .append_pair("dlink", "1")
+ .finish();
+ let req = Request::get(format!(
+ "https://pan.baidu.com/rest/2.0/xpan/multimedia?{query}"
+ ))
+ .body(Buffer::new())
+ .map_err(new_request_build_error)?;
+ let value = self.core.send(&self.ctx, req).await?;
+ let files: FileList =
serde_json::from_value(value).map_err(new_json_deserialize_error)?;
+ let link = files
+ .list
+ .into_iter()
+ .find(|item| item.fs_id == file.fs_id)
+ .and_then(|item| item.dlink)
+ .ok_or_else(|| {
+ Error::new(
+ ErrorKind::Unexpected,
+ "Baidu Netdisk did not return a download URL",
+ )
+ })?;
+ let mut builder = Request::get(link);
+ if !range.is_full() {
+ builder = builder.header(header::RANGE, range.to_header());
+ }
+ let req = builder
+ .body(Buffer::new())
+ .map_err(new_request_build_error)?;
+ let req = self.core.sign(req).await?;
+ let mut response = self.ctx.http_transport().fetch(req).await?;
+ match response.status() {
+ StatusCode::RANGE_NOT_SATISFIABLE => Err(Error::new(
+ ErrorKind::RangeNotSatisfied,
+ "Baidu Netdisk rejected the requested byte range",
+ )),
+ StatusCode::OK if !range.is_full() => Err(Error::new(
+ ErrorKind::Unexpected,
+ "Baidu Netdisk ignored the requested byte range",
+ )),
+ StatusCode::OK | StatusCode::PARTIAL_CONTENT => {
+ // Baidu sends raw UTF-8 filenames in Content-Disposition,
which
+ // HeaderValue::to_str rejects because it only accepts visible
ASCII.
+ let disposition =
response.headers_mut().remove(header::CONTENT_DISPOSITION);
+ let mut metadata =
+ parse_into_metadata(&self.path,
response.headers())?.into_builder();
+ if let Some(value) = disposition {
+ let value =
std::str::from_utf8(value.as_bytes()).map_err(|e| {
+ Error::new(
+ ErrorKind::Unexpected,
+ "invalid UTF-8 in Baidu Netdisk
Content-Disposition",
+ )
+ .set_source(e)
+ })?;
+ metadata.content_disposition(value);
+ }
+ Ok((
+ RpRead::new(metadata.build()),
+ Box::new(response.into_body()),
+ ))
+ }
+ _ => {
+ let (parts, mut body) = response.into_parts();
+ parse_response(
+ Response::from_parts(parts, body.to_buffer().await?),
+ Some("download"),
+ )?;
+ Err(Error::new(
+ ErrorKind::Unexpected,
+ "unexpected Baidu Netdisk download response",
+ ))
+ }
+ }
+ }
+}
diff --git a/core/services/baidu-netdisk/src/writer.rs
b/core/services/baidu-netdisk/src/writer.rs
new file mode 100644
index 0000000000..4335f1d876
--- /dev/null
+++ b/core/services/baidu-netdisk/src/writer.rs
@@ -0,0 +1,219 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+use crate::core::{BaiduNetdiskCore, FILE_API, FileMetadata};
+use http::{Request, header};
+use md5::{Digest, Md5};
+use opendal_core::{raw::*, *};
+use serde::Deserialize;
+use std::sync::Arc;
+
+const BLOCK_SIZE: usize = 4 * 1024 * 1024;
+pub const MAX_WRITE_SIZE: usize = 4 * BLOCK_SIZE;
+
+pub struct BaiduNetdiskWriter {
+ pub buffer: Option<Buffer>,
+ pub core: Arc<BaiduNetdiskCore>,
+ pub ctx: OperationContext,
+ pub path: String,
+}
+
+#[derive(Deserialize)]
+struct Precreate {
+ uploadid: String,
+ block_list: Vec<usize>,
+}
+#[derive(Deserialize)]
+struct LocateUpload {
+ servers: Vec<UploadServer>,
+}
+#[derive(Deserialize)]
+struct UploadServer {
+ server: String,
+}
+#[derive(Deserialize)]
+struct UploadPart {
+ md5: String,
+}
+
+impl oio::Write for BaiduNetdiskWriter {
+ async fn write(&mut self, data: Buffer) -> Result<()> {
+ if data.len() > MAX_WRITE_SIZE {
+ return Err(Error::new(
+ ErrorKind::Unsupported,
+ "Baidu Netdisk writes are limited to 16 MiB",
+ ));
+ }
+ if self.buffer.is_some() {
+ return Err(Error::new(
+ ErrorKind::Unsupported,
+ "Baidu Netdisk accepts a single write per file",
+ ));
+ }
+ self.buffer = Some(data);
+ Ok(())
+ }
+
+ async fn abort(&mut self) -> Result<()> {
+ self.buffer = None;
+ Ok(())
+ }
+
+ async fn close(&mut self) -> Result<Metadata> {
+ let data = self.buffer.clone().unwrap_or_default();
+ match self.core.stat(&self.ctx, &self.path).await {
+ Ok(file) if file.isdir == 1 => {
+ return Err(Error::new(
+ ErrorKind::IsADirectory,
+ "write destination is a directory",
+ ));
+ }
+ Err(e) if e.kind() != ErrorKind::NotFound => return Err(e),
+ _ => {}
+ }
+ self.core
+ .create_dir(&self.ctx, get_parent(&self.path))
+ .await?;
+ let path = self.core.absolute_path(&self.path);
+ let blocks: Vec<Buffer> = if data.is_empty() {
+ vec![Buffer::new()]
+ } else {
+ (0..data.len())
+ .step_by(BLOCK_SIZE)
+ .map(|start| data.slice(start..(start +
BLOCK_SIZE).min(data.len())))
+ .collect()
+ };
+ let hashes: Vec<String> = blocks
+ .iter()
+ .map(|block| {
+ let mut md5 = Md5::new();
+ for chunk in block.clone() {
+ md5.update(chunk);
+ }
+ hex::encode(md5.finalize())
+ })
+ .collect();
+ let block_list =
serde_json::to_string(&hashes).map_err(new_json_serialize_error)?;
+ let size = data.len().to_string();
+ let form = form_urlencoded::Serializer::new(String::new())
+ .append_pair("path", &path)
+ .append_pair("size", &size)
+ .append_pair("isdir", "0")
+ .append_pair("autoinit", "1")
+ .append_pair("rtype", "3")
+ .append_pair("block_list", &block_list)
+ .finish();
+ let req = Request::post(format!("{FILE_API}?method=precreate"))
+ .header(header::CONTENT_TYPE, "application/x-www-form-urlencoded")
+ .body(Buffer::from(form))
+ .map_err(new_request_build_error)?;
+ let response = self.core.send(&self.ctx, req).await?;
+ let mut pre: Precreate =
+
serde_json::from_value(response).map_err(new_json_deserialize_error)?;
+ // The API defines an empty list as a request to upload block zero.
+ if pre.block_list.is_empty() {
+ pre.block_list.push(0);
+ }
+ let query = form_urlencoded::Serializer::new(String::new())
+ .append_pair("method", "locateupload")
+ .append_pair("appid", "250528")
+ .append_pair("upload_version", "2.0")
+ .append_pair("path", &path)
+ .append_pair("uploadid", &pre.uploadid)
+ .finish();
+ let req =
Request::get(format!("https://d.pcs.baidu.com/rest/2.0/pcs/file?{query}"))
+ .body(Buffer::new())
+ .map_err(new_request_build_error)?;
+ let response = self.core.send(&self.ctx, req).await?;
+ let locate: LocateUpload =
+
serde_json::from_value(response).map_err(new_json_deserialize_error)?;
+ let server = locate
+ .servers
+ .into_iter()
+ .find(|item| item.server.starts_with("https://"))
+ .ok_or_else(|| {
+ Error::new(
+ ErrorKind::Unexpected,
+ "Baidu Netdisk did not return an HTTPS upload server",
+ )
+ })?
+ .server;
+ for index in pre.block_list {
+ let block = blocks.get(index).ok_or_else(|| {
+ Error::new(
+ ErrorKind::Unexpected,
+ "Baidu Netdisk requested an invalid block index",
+ )
+ })?;
+ let query = form_urlencoded::Serializer::new(String::new())
+ .append_pair("method", "upload")
+ .append_pair("type", "tmpfile")
+ .append_pair("path", &path)
+ .append_pair("uploadid", &pre.uploadid)
+ .append_pair("partseq", &index.to_string())
+ .finish();
+ let part = FormDataPart::new("file")
+ .header(
+ header::CONTENT_DISPOSITION,
+ http::HeaderValue::from_static(r#"form-data; name="file";
filename="part""#),
+ )
+ .header(
+ header::CONTENT_TYPE,
+ http::HeaderValue::from_static("application/octet-stream"),
+ )
+ .content(block.clone());
+ let req = Multipart::new().part(part).apply(Request::post(format!(
+ "{}/rest/2.0/pcs/superfile2?{query}",
+ server.trim_end_matches('/')
+ )))?;
+ let response = self.core.send(&self.ctx, req).await?;
+ let uploaded: UploadPart =
+
serde_json::from_value(response).map_err(new_json_deserialize_error)?;
+ if uploaded.md5 != hashes[index] {
+ return Err(Error::new(
+ ErrorKind::Unexpected,
+ "Baidu Netdisk uploaded block MD5 mismatch",
+ ));
+ }
+ }
+ let form = form_urlencoded::Serializer::new(String::new())
+ .append_pair("path", &path)
+ .append_pair("size", &size)
+ .append_pair("isdir", "0")
+ .append_pair("rtype", "3")
+ .append_pair("uploadid", &pre.uploadid)
+ .append_pair("block_list", &block_list)
+ .finish();
+ let req = Request::post(format!("{FILE_API}?method=create"))
+ .header(header::CONTENT_TYPE, "application/x-www-form-urlencoded")
+ .body(Buffer::from(form))
+ .map_err(new_request_build_error)?;
+ let response = self.core.send(&self.ctx, req).await?;
+ let file: FileMetadata =
+
serde_json::from_value(response).map_err(new_json_deserialize_error)?;
+ if file.isdir != 0 || file.size != data.len() as u64 {
+ return Err(Error::new(
+ ErrorKind::Unexpected,
+ "Baidu Netdisk returned an unexpected upload result",
+ ));
+ }
+ // The create response's mtime can differ from the server_mtime
returned by stat.
+ let metadata = MetadataBuilder::file(file.size).build();
+ self.buffer = None;
+ Ok(metadata)
+ }
+}
diff --git a/core/src/lib.rs b/core/src/lib.rs
index ca5927073d..8432ff3f9c 100644
--- a/core/src/lib.rs
+++ b/core/src/lib.rs
@@ -152,6 +152,9 @@ fn init_default_registry_inner(registry: &OperatorRegistry)
{
#[cfg(feature = "services-b2-s3")]
opendal_service_s3::register_b2_s3_service(registry);
+ #[cfg(feature = "services-baidu-netdisk")]
+ opendal_service_baidu_netdisk::register_baidu_netdisk_service(registry);
+
#[cfg(feature = "services-cacache")]
opendal_service_cacache::register_cacache_service(registry);
@@ -477,6 +480,8 @@ pub mod services {
pub use opendal_service_azfile::*;
#[cfg(feature = "services-b2")]
pub use opendal_service_b2::*;
+ #[cfg(feature = "services-baidu-netdisk")]
+ pub use opendal_service_baidu_netdisk::*;
#[cfg(feature = "services-cacache")]
pub use opendal_service_cacache::*;
#[cfg(feature = "services-cloudflare-kv")]
diff --git a/core/tests/behavior/async_copy.rs
b/core/tests/behavior/async_copy.rs
index 8a6136cd2c..05f24c02be 100644
--- a/core/tests/behavior/async_copy.rs
+++ b/core/tests/behavior/async_copy.rs
@@ -41,6 +41,11 @@ pub fn tests(op: &Operator, tests: &mut Vec<Trial>) {
))
}
+ #[cfg(feature = "services-baidu-netdisk")]
+ if op.info().scheme() == services::BAIDU_NETDISK_SCHEME {
+ tests.extend(async_trials!(op, test_baidu_netdisk_filename_copy));
+ }
+
if cap.read && cap.write && cap.copy && cap.copy_can_multi {
tests.extend(async_trials!(
op,
@@ -192,6 +197,12 @@ pub async fn test_copy_file_with_non_ascii_name(op:
Operator) -> Result<()> {
return Ok(());
}
+ // Baidu Netdisk rejects the emoji in these filenames before the copy.
+ #[cfg(feature = "services-baidu-netdisk")]
+ if op.info().scheme() == services::BAIDU_NETDISK_SCHEME {
+ return Ok(());
+ }
+
let source_path = "🐂🍺中文.docx";
let target_path = "😈🐅Français.docx";
let (source_content, _) = gen_bytes(op.info().capability());
@@ -214,6 +225,24 @@ pub async fn test_copy_file_with_non_ascii_name(op:
Operator) -> Result<()> {
Ok(())
}
+#[cfg(feature = "services-baidu-netdisk")]
+pub async fn test_baidu_netdisk_filename_copy(op: Operator) -> Result<()> {
+ for name in ["🐂🍺中文.docx", "😈🐅Français.docx"] {
+ let err = op.write(name, "filename probe").await.unwrap_err();
+ assert_eq!(err.kind(), ErrorKind::ConfigInvalid);
+ assert!(err.to_string().contains("errno: 31023"), "{err}");
+ }
+
+ let source = "中文.docx";
+ let target = "Français.docx";
+ op.write(source, "copy contents").await?;
+ op.copy(source, target).await?;
+ assert_eq!(op.read(target).await?.to_bytes().as_ref(), b"copy contents");
+ op.delete(source).await?;
+ op.delete(target).await?;
+ Ok(())
+}
+
/// Copy a nonexistent source should return an error.
pub async fn test_copy_non_existing_source(op: Operator) -> Result<()> {
let source_path = uuid::Uuid::new_v4().to_string();
diff --git a/dev/src/generate/java.j2 b/dev/src/generate/java.j2
index ca4e8a381c..91dd0d0956 100644
--- a/dev/src/generate/java.j2
+++ b/dev/src/generate/java.j2
@@ -61,7 +61,9 @@ public interface ServiceConfig {
*/
@Builder
@Data
- {%- if srv == "swift" %}
+ {%- if srv == "baidu-netdisk" %}
+ @ToString(exclude = "accessToken")
+ {%- elif srv == "swift" %}
@ToString(exclude = {"password", "token", "tempUrlKey"})
{%- endif %}
@RequiredArgsConstructor(access = AccessLevel.PRIVATE)
@@ -79,6 +81,17 @@ public interface ServiceConfig {
}
{%- endif %}
+ {%- if srv == "baidu-netdisk" %}
+
+ public static class BaiduNetdiskBuilder {
+ @Override
+ public String toString() {
+ return "BaiduNetdiskBuilder";
+ }
+ }
+
+ {%- endif %}
+
@Override
public String scheme() {
return "{{srv}}";
diff --git a/website/data/capabilities.json b/website/data/capabilities.json
index e8b50bd318..6db6c82a1c 100644
--- a/website/data/capabilities.json
+++ b/website/data/capabilities.json
@@ -1103,6 +1103,29 @@
}
}
},
+ {
+ "name": "baidu-netdisk",
+ "scheme": "baidu-netdisk",
+ "native": {
+ "copy": true,
+ "create_dir": true,
+ "delete": true,
+ "delete_with_recursive": true,
+ "list": true,
+ "list_with_limit": true,
+ "read": true,
+ "read_with_suffix": true,
+ "shared": true,
+ "stat": true,
+ "write": true,
+ "write_can_empty": true
+ },
+ "limits": {
+ "write_total_max_size": {
+ "display": "16 MiB"
+ }
+ }
+ },
{
"name": "cacache",
"scheme": "cacache",
diff --git a/website/data/services.json b/website/data/services.json
index 364c20bb6a..d4309f1678 100644
--- a/website/data/services.json
+++ b/website/data/services.json
@@ -813,6 +813,56 @@
}
]
},
+ {
+ "name": "baidu-netdisk",
+ "scheme": "baidu-netdisk",
+ "groups": [
+ "General"
+ ],
+ "configs": [
+ {
+ "name": "root",
+ "type": "string",
+ "required": true,
+ "group": "General",
+ "example": "/apps/MyApp/data/",
+ "comments": "Required absolute root inside `/apps/<application
name>/`."
+ },
+ {
+ "name": "access_token",
+ "type": "string",
+ "required": true,
+ "group": "General",
+ "comments": "Required access token for the Baidu Netdisk Open
Platform."
+ }
+ ],
+ "examples": [
+ {
+ "binding": "rust",
+ "language": "rust",
+ "minimal": "use opendal::Operator;\n\nlet operator =
Operator::via_iter(\"baidu-netdisk\", [\n (\"root\".to_string(),
\"/apps/MyApp/data/\".to_string()),\n (\"access_token\".to_string(),
\"...\".to_string()),\n])?;",
+ "full": "use opendal::Operator;\n\nlet operator =
Operator::via_iter(\"baidu-netdisk\", [\n // Required absolute root inside
`/apps/<application name>/`.\n (\"root\".to_string(),
\"/apps/MyApp/data/\".to_string()),\n\n // Required access token for the
Baidu Netdisk Open Platform.\n (\"access_token\".to_string(),
\"...\".to_string()),\n])?;"
+ },
+ {
+ "binding": "java",
+ "language": "java",
+ "minimal": "import java.util.HashMap;\nimport java.util.Map;\nimport
org.apache.opendal.Operator;\n\nMap<String, String> config = new
HashMap<>();\nconfig.put(\"root\",
\"/apps/MyApp/data/\");\nconfig.put(\"access_token\", \"...\");\nOperator
operator = Operator.of(\"baidu-netdisk\", config);",
+ "full": "import java.util.HashMap;\nimport java.util.Map;\nimport
org.apache.opendal.Operator;\n\nMap<String, String> config = new
HashMap<>();\n// Required absolute root inside `/apps/<application
name>/`.\nconfig.put(\"root\", \"/apps/MyApp/data/\");\n\n// Required access
token for the Baidu Netdisk Open Platform.\nconfig.put(\"access_token\",
\"...\");\nOperator operator = Operator.of(\"baidu-netdisk\", config);"
+ },
+ {
+ "binding": "python",
+ "language": "python",
+ "minimal": "import opendal\n\noperator = opendal.Operator(\n
\"baidu-netdisk\",\n root=\"/apps/MyApp/data/\",\n
access_token=\"...\",\n)",
+ "full": "import opendal\n\noperator = opendal.Operator(\n
\"baidu-netdisk\",\n # Required absolute root inside `/apps/<application
name>/`.\n root=\"/apps/MyApp/data/\",\n\n # Required access token for
the Baidu Netdisk Open Platform.\n access_token=\"...\",\n)"
+ },
+ {
+ "binding": "go",
+ "language": "go",
+ "minimal": "import
(\n\t\"github.com/apache/opendal-go-services/baidu_netdisk\"\n\topendal
\"github.com/apache/opendal/bindings/go\"\n)\n\noperator, err :=
opendal.NewOperator(baidu_netdisk.Scheme, opendal.OperatorOptions{\n\t\"root\":
\"/apps/MyApp/data/\",\n\t\"access_token\": \"...\",\n})",
+ "full": "import
(\n\t\"github.com/apache/opendal-go-services/baidu_netdisk\"\n\topendal
\"github.com/apache/opendal/bindings/go\"\n)\n\noperator, err :=
opendal.NewOperator(baidu_netdisk.Scheme, opendal.OperatorOptions{\n\t//
Required absolute root inside `/apps/<application name>/`.\n\t\"root\":
\"/apps/MyApp/data/\",\n\n\t// Required access token for the Baidu Netdisk Open
Platform.\n\t\"access_token\": \"...\",\n})"
+ }
+ ]
+ },
{
"name": "cacache",
"scheme": "cacache",