目录

本章节主要介绍接入华为云空间服务的开发步骤,以帮助开发者快速了解华为云空间服务提供的客户端接口及其调用方法。请开发者基于应用自身的使用场景,自行选择相应的开发章节。

1 功能描述

Drive SDK提供的主要能力以及调用方法如下:

  1. 获取鉴权信息。        

  2. 调用About.get()接口获取用户信息及授权页面。        

  3. 调用Files接口进行文件管理和搜索。        

  4. 调用Changes接口注册资源变化通知channel,开启文件变化通知功能。

  5. 调用Comments接口评论文件。

  6. 调用Replies接口对评论进行回复。

2 获取鉴权信息

2.1 场景介绍

华为帐号是用户访问并使用个人云端文件的凭证,因此在使用Drive SDK时,需要先引导用户登录华为帐号。在登录成功后,将用户相关信息保存,在调用Drive SDK相关接口时使用。

2.2 业务流程

基本流程如下:

2.3 开发步骤

2.3.1 集成HMS

如上所述,使用Drive SDK时,应用需要先通过HMS SDK获取用户信息,详见集成Drive SDK和HMS SDK。

2.3.2 设置HMS Scope

通过HMS SDK登录时,需要通过HMS的HuaweiIdAuthParamsHelper.setScopeList接口设置Drive Scope,用于获取访问Drive接口的权限:

  1. List<Scope> scopeList = new ArrayList<>();
  2. scopeList.add(new Scope(DriveScopes.SCOPE_DRIVE)); //所有权限,除了应用文件夹权限
  3. scopeList.add(new Scope(DriveScopes.SCOPE_DRIVE_READONLY)); // 只允许查看文件内容和元数据
  4. scopeList.add(new Scope(DriveScopes.SCOPE_DRIVE_FILE)); //允许查看和管理文件
  5. scopeList.add(new Scope(DriveScopes.SCOPE_DRIVE_METADATA)); //允许查看和管理文件元数据,但不包括文件实体
  6. scopeList.add(new Scope(DriveScopes.SCOPE_DRIVE_METADATA_READONLY)); //只允许查看文件元数据,但不包括文件实体
  7. scopeList.add(new Scope(DriveScopes.SCOPE_DRIVE_APPDATA)); //支持APP数据上传和存储
  8. scopeList.add(HuaweiIdAuthAPIManager.HUAWEIID_BASE_SCOPE); // 账号基本权限
  9. HuaweiIdAuthParams authParams = new HuaweiIdAuthParamsHelper(DEFAULT_AUTH_REQUEST_PARAM)
  10.           .setAccessToken()
  11.           .setIdToken()
  12.           .setScopeList(scopeList)
  13.           .createParams();

不同的DriveScope对应不同的权限, 第三方开发者可以根据自己的业务需要申请对应权限。具体登录流程请参考《华为帐号服务开发指南》。

2.3.3 存储鉴权信息

获取用户信息后,将用户的unionId和AccessToken(即at)保存,后续调用Drive SDK相关使用。如下示例描述了一种实现方法,开发者也可自行实现。

示例代码:

创建CredentialManager类:

  1. /**   
  2. * Credential管理类
  3. * <p>
  4. * since 1.0
  5. */
  6. public class CredentialManager {
  7.    /**  
  8.    * Drive鉴权信息
  9.    */
  10.    private DriveCredential mCredential;
  11.    private CredentialManager() {
  12.    }
  13.    private static class InnerHolder {
  14.        private static CredentialManager sInstance = new CredentialManager();
  15.    }
  16.    /**
  17.    * 单例CredentialManager instance。
  18.    *
  19.    * @return CredentialManager
  20.    */
  21.    public static CredentialManager getInstance() {
  22.        return InnerHolder.sInstance;
  23.    }
  24.    /**
  25.    * 通过上下文context和华为账号信息(unionId,countrycode,accessToken)初始化drive。
  26.    * 当accessToken失效时,注册一个AccessMethod去获取一个新的accessToken,传入的refreshAT不为null。
  27.    *
  28.    * @param unionID   HwID中的unionID
  29.    * @param at        access token
  30.    * @param refreshAT 刷新AT的回调函数,不能传入null
  31.    */
  32.    public int init(String unionID, String at, DriveCredential.AccessMethod refreshAT) {
  33.        if (StringUtils.isNullOrEmpty(unionID) || StringUtils.isNullOrEmpty(at)) {
  34.            return DriveCode.ERROR;        
  35.        }        
  36.        DriveCredential.Builder builder = new DriveCredential.Builder(unionID, refreshAT);  
  37.        mCredential = builder.build().setAccessToken(at);    
  38.        return DriveCode.SUCCESS;    
  39.    }
  40.    /**    
  41.    * 获取DriveCredential    
  42.    *    
  43.    * @return DriveCredential    
  44.    */    
  45.    public DriveCredential getCredential() {      
  46.        return mCredential;    
  47.    }
  48.    /**    
  49.    * 退出Drive,清理Drive使用过程中所有的缓存信息
  50.    */    
  51.    public void exit(Context context) {      
  52.        // 清理缓存文件        
  53.        deleteFile(context.getCacheDir());      
  54.        deleteFile(context.getFilesDir());    
  55.    }
  56.    /**    
  57.    * 删除缓存文件    
  58.    *      
  59.    * @param file 指定的缓存文件      
  60.    */    
  61.    private static void deleteFile(java.io.File file) {    
  62.        if (null == file || !file.exists()) {      
  63.            return;        
  64.        }        
  65.        if (file.isDirectory()) {      
  66.            java.io.File[] files = file.listFiles();  
  67.            if (files != null) {                
  68.                for (java.io.File f : files) {      
  69.                    deleteFile(f);              
  70.                }            
  71.            }        
  72.        }    
  73.    }
  74. }

在登录成功onActivityResult回调中调用initDrive。

  1. private static DriveCredential.AccessMethod refreshAT = new DriveCredential.AccessMethod() {
  2.    @Override
  3.    public String refreshToken() {
  4.        // 重新通过HMS获取accessToken
  5.        return refreshAccessToken();
  6.    }
  7. };
  8. private void initDrive() {
  9.    // signInHuaweiId为登录HMS后获取到的用户帐号信息,通过signInHuaweiId获取unionId及accessToken
  10.    final String unionID = signInHuaweiId.getUnionId();
  11.    final String accessToken = signInHuaweiId.getAccessToken();
  12.    int returnCode = CredentialManager.getInstance().init(unionID, accessToken, refreshAT);
  13.    if (DriveCode.SUCCESS == returnCode) {
  14.        // 初始化成功后跳转到应用主页面
  15.       jumpToMainActivity();
  16.    }
  17. }
注意:

获取鉴权信息成功后,开发者必须先检查用户安全策略是否需要更新,具体参见“获取用户信息”操作。

3 获取用户信息

3.1 场景介绍

第三方应用可以通过About.get接口获取到用户华为云空间信息,例如空间容量大小,允许上传的最大文件大小等。

3.2 开发步骤

步骤1 调用Drive.Builder.build接口创建Drive对象。

  1. private Drive buildDrive() {    
  2.    Drive service = new Drive.Builder(CredentialManager.getInstance().getCredential(), context).build();      
  3.    return service;  
  4. }

步骤2 调用About.get接口获取用户信息,设置字段setFields("*")表示返回所有字段。

  1. private About getAbout() {
  2.    About response = null;
  3.    try {
  4.        Drive drive = buildDrive();
  5.        Drive.About about = drive.about();
  6.        response = about.get().setFields("*").execute();
  7.        String res = response.toString();
  8.    } catch (Exception e) {
  9.        Log.e(TAG, "getInfo error: " + e.toString());
  10.    }
  11.    return response;
  12. }
注意:
获取用户信息接口是联网耗时接口,需要放在子线程中调用。

步骤3 如果About.get接口返回响应中needUpdate字段值为true,表示需要用户更新安全策略,开发者需要根据返回的地址,跳转到授权页面,用户同意后可继续使用业务。

  1. /**
  2. * 判断是否要提示用户更新协议
  3. *
  4. * @param about 返回的About响应
  5. */
  6. private void checkUpdateProtocol(About about) {
  7.    if (about == null) {
  8.        return;
  9.    }
  10.    Log.d(TAG, "checkUpdate: " + about.toString());
  11.    Object updateValue = about.get("needUpdate");
  12.    boolean isNeedUpdate = false;
  13.    if (updateValue instanceof Boolean) {
  14.        isNeedUpdate = (Boolean) updateValue;
  15.    }
  16.    if (!isNeedUpdate) {
  17.        return;
  18.    }
  19.    Object urlValue = about.get("updateUrl");
  20.    String url = "";
  21.    if (urlValue instanceof String) {
  22.        url = (String) urlValue;
  23.    }
  24.    if (TextUtils.isEmpty(url)) {
  25.        return;
  26.    }
  27.    Uri uri = Uri.parse(url);
  28.    if (!"https".equals(uri.getScheme())) {
  29.        return;
  30.    }
  31.    Intent intent = new Intent(Intent.ACTION_VIEW, uri);
  32.    try {
  33.        startActivity(intent);
  34.    } catch (ActivityNotFoundException e) {
  35.        Logger.e(TAG, "Activity Not found");
  36.    }
  37. }
注意:
needUpdate字段为可选字段,About.get接口可能并不返回该字段。

4 文件管理和搜索

4.1 场景介绍

华为云空间服务的核心能力是对云端文件的管理,用户可以通过华为云空间服务方便快捷的管理、编辑华为云盘上的文件,支持创建、获取文件列表、拷贝、修改文件、移入回收站、清空回收站文件及搜索云盘上的文件等能力。

4.2 开发步骤

步骤1 调用Drive.Builder.build接口创建Drive对象。

  1. private Drive buildDrive() {      
  2.    Drive service = new Drive.Builder(CredentialManager.getInstance().getCredential(), context).build();      
  3.    return service;  
  4. }

步骤2 调用Files接口能力。

说明:

示例代码中使用的常量:

private static final int DIRECT_UPLOAD_MAX_SIZE = 20 * 1024 * 1024;

private static final int DIRECT_DOWNLOAD_MAX_SIZE = 20 * 1024 * 1024;

       

调用Files.create接口创建目录:

  1. /**
  2. * 创建目录
  3. */
  4. private File createDirectory() {
  5.    File directory = null;
  6.    try {
  7.        Drive drive = buildDrive();
  8.        Map<String, String> appProperties = new HashMap<>();
  9.        appProperties.put("appProperties", "property");
  10.        SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMdd_HHmmss_SSS");
  11.        String dirName = formatter.format(new Date());
  12.        File file = new File();
  13.        file.setFileName(dirName)
  14.                .setAppSettings(appProperties)
  15.                .setMimeType("application/vnd.huawei-apps.folder");
  16.        directory = drive.files().create(file).execute();
  17.    } catch (Exception e) {
  18.        Logger.e(TAG, "createDirectory error: " + e.toString());
  19.    }
  20.    return directory;
  21. }

调用Files.create接口创建文件:

文件上传方式分为直接上传和断点续传两种,其中直接上传支持的最大文件大小为20M,推荐低于5M的文件通过直接上传的方式上传,而断点续传不限制文件大小,推荐超过5M的文件使用断点续传的方式上传。

方式一:直接上传文件。

  1. /**    
  2. * 上传文件,该方式支持上传进度保存功能  
  3. * (用户上传过程中断网等,下次再上传同一个文件时会接着上次的进度上传)
  4. *    
  5. * @param filePath 文件路径    
  6. * @param parentId 文件所在目录ID    
  7. * @param thumbnailImageBuffer 缩略图数据    
  8. * @param thumbnailMimeType 缩略图文件类型    
  9. */  
  10. private void createFile(String filePath, String parentId, byte[] thumbnailImageBuffer, String thumbnailMimeType) {    
  11.    try {      
  12.        if (filePath == null) {  
  13.            Logger.e(TAG, "createFile error, filePath is null.");
  14.            return;        
  15.        }        
  16.        java.io.File file = new java.io.File(filePath);
  17.        FileContent fileContent = new FileContent(null, file);      
  18.        // 设置缩略图数据        
  19.        File.ContentExtras contentExtras = new File.ContentExtras();    
  20.        File.ContentExtras.Thumbnail thumbnail = new File.ContentExtras.Thumbnail();
  21.        thumbnail.setContent(Base64.encodeBase64String(thumbnailImageBuffer));        
  22.        thumbnail.setMimeType(thumbnailMimeType);        
  23.        contentExtras.setThumbnail(thumbnail);        
  24.        File content = new File()                
  25.            .setFileName(file.getName())                
  26.            .setParentFolder(Collections.singletonList(parentId))    
  27.            .setContentExtras(contentExtras);        
  28.        Drive drive = buildDrive();        
  29.        Drive.Files.Create request = drive.files().create(content, fileContent);    
  30.        boolean isDirectUpload = false;        
  31.        // 文件小于20M时可以使用直接上传        
  32.        if (file.length() < DIRECT_UPLOAD_MAX_SIZE) {        
  33.            isDirectUpload = true;        
  34.        }        
  35.        // 设置上传方式,默认使用断点续传。当文件小于20M时可以使用直接上传,即设置为true。
  36.        request.getMediaHttpUploader().setDirectUploadEnabled(isDirectUpload);    
  37.        request.execute();    
  38.    } catch (Exception e) {        
  39.        Logger.e(TAG, "createFile exception: " + filePath + e.toString());    
  40.    }
  41. }

方式二:通过媒体流创建文件。

  1. /**
  2. * 通过InputStream创建文件
  3. *
  4. * @param inputStream 媒体流
  5. * @param parentId 文件所在目录ID
  6. * @param mimeType MIME类型,如image/jpeg、video/mp4等
  7. * @param inputStreamLength stream流长度
  8. */
  9. private void createFile(InputStream inputStream, String parentId, String mimeType, int inputStreamLength) {
  10.    try {
  11.        InputStreamContent streamContent = new InputStreamContent(mimeType, inputStream);
  12.        streamContent.setLength(inputStreamLength);
  13.        File content = new File()
  14.                .setFileName("video.mp4")
  15.                .setParentFolder(Collections.singletonList(parentId));
  16.        Drive drive = buildDrive();
  17.        drive.files().create(content, streamContent).execute();
  18.    } catch (Exception e) {
  19.        Logger.e(TAG, "createFile exception: " + e.toString());
  20.    }
  21. }

调用Files.copy接口拷贝文件:

  1. /**  
  2. * 拷贝文件到指定目录  
  3. *      
  4. * @param file 待拷贝的文件
  5. * @param dstDir 拷贝文件到指定的目录
  6. */
  7. private void copyFile(File file, ArrayList<String> dstDir) {    
  8.    try {          
  9.        File copyFile = new File();            
  10.        if (file == null || file.getFileName() == null ||dstDir == null) {        
  11.            Log.e(TAG, "copyFile arguments error");                
  12.            sendHandleMessage(R.id.drive_files_button_copy, FAIL);  
  13.            return;            
  14.        }        
  15.        SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMdd_HHmmss");
  16.        String suffix = formatter.format(new Date());      
  17.        copyFile.setFileName(file.getFileName() + "_copy" +  "_" + suffix);    
  18.        copyFile.setDescription("copyFile");            
  19.        copyFile.setParentFolder(dstDir);            
  20.        copyFile.setFavorite(true);            
  21.        copyFile.setEditedTime(new DateTime(System.currentTimeMillis()));
  22.        Drive drive = buildDrive();      
  23.        Drive.Files.Copy copyFileReq = drive.files().copy(file.getId(), copyFile);
  24.        copyFileReq.setFields("*");    
  25.        File result = copyFileReq.execute();      
  26.    } catch (IOException ex) {          
  27.        Log.e(TAG, "copyFile error: " + ex.toString());      
  28.    }  
  29. }

调用Files.update接口修改文件(目录)的元数据:

  1. /**    
  2. * 修改文件(目录),通过MIMEType区分是文件还是目录
  3. *    
  4. * @param file 待修改的文件(目录)    
  5. */  
  6. private void updateFile(File file) {      
  7.    try {          
  8.        if (file == null) {              
  9.            Logger.e(TAG, "updateFile error, need to create file.");  
  10.            return;          
  11.        }            
  12.        Drive drive = buildDrive();      
  13.        File updateFile = new File();      
  14.        updateFile.setFileName(file.getFileName() +"_update")      
  15.            .setMimeType("application/vnd.huawei-apps.folder")    
  16.            .setDescription("update folder")                  
  17.            .setFavorite(true);      
  18.        drive.files().update(file.getId(), updateFile).execute();      
  19.    } catch (Exception e) {          
  20.        Logger.e(TAG, "updateFile error: " + e.toString());      
  21.    }  
  22. }

调用Files.update接口修改文件的元数据或内容:

  1. /**    
  2. * 修改文件  
  3. *    
  4. * @param oldFile 源文件    
  5. * @param newFilePath 更新后文件路径    
  6. */
  7. private void updateFile(File oldFile, String newFilePath) {      
  8.    try {          
  9.        if (oldFile == null || TextUtils.isEmpty(newFilePath)) {      
  10.            Logger.e(TAG, "updateFile error, need to create file.");      
  11.            return;          
  12.        }                    
  13.        java.io.File sourceFile = new java.io.File(newFilePath);    
  14.        FileContent fileContent = new FileContent(null, sourceFile);    
  15.        File updateFile = new File();          
  16.        updateFile.setFileName(oldFile.getFileName() + "_update")      
  17.            .setDescription("update folder")                
  18.            .setFavorite(true);                    
  19.        Drive drive = buildDrive();          
  20.        Drive.Files.Update update = drive.files().update(oldFile.getId(), updateFile, fileContent);
  21.        boolean isDirectUpload = false;  
  22.        // 文件小于20M时可以使用直接上传      
  23.        if (sourceFile.length() < DIRECT_UPLOAD_MAX_SIZE) {    
  24.            isDirectUpload = true;          
  25.        }          
  26.        // 设置上传方式,默认使用断点续传。当文件小于20M时可以使用直接上传,即设置为true。
  27.        update.getMediaHttpUploader().setDirectUploadEnabled(isDirectUpload);        
  28.        update.execute();      
  29.    } catch (Exception e) {        
  30.        Logger.e(TAG, "updateFile error: " + e.toString());      
  31.    }  
  32. }

调用Files.delete接口永久删除文件(或者目录):

  1. /**  
  2. * 永久删除文件(目录)  
  3. *  
  4. * @param file 待删除的文件或目录  
  5. */
  6. private void deleteFile(File file) {    
  7.    try {        
  8.        Drive drive = buildDrive();        
  9.        Drive.Files.Delete deleteFile = drive.files().delete(file.getId());    
  10.        deleteFile.execute();    
  11.    } catch (IOException ex) {        
  12.        Log.e(TAG, "deleteFile error: " + ex.toString());    
  13.    }
  14. }

调用Files.get接口获取文件元数据:

  1. /**
  2. *获取文件元数据
  3. *
  4. * @param fileId 文件Id
  5. */
  6. private File getFileMetadata(String fileId) {
  7.    File file = null;
  8.    try {
  9.        Drive drive = buildDrive();
  10.        Drive.Files.Get request = drive.files().get(fileId);
  11.        request.setFields("*");
  12.        file = request.execute();
  13.    } catch (Exception e) {
  14.        Logger.e(TAG, "get metadata error: " + e.toString());
  15.    }
  16.    return file;
  17. }

调用Files.get接口下载元数据及实体文件:

文件下载不限制文件大小。针对小文件(小于20M)可以通过设置参数directDownloadEnabled的值为true,通过一个网络请求,简单下载文件。

  1. /**  
  2. * 下载文件元数据及文件实体  
  3. *  
  4. * @param fileId 文件Id    
  5. * @param destFile 目标文件  
  6. */
  7. private void downLoadFile(String fileId, java.io.File destFile) {  
  8.    if (fileId == null || destFile == null) {    
  9.        return;    
  10.    }    
  11.    try {        
  12.        Drive drive = buildDrive();      
  13.        Drive.Files.Get request = drive.files().get(fileId);        
  14.        File fileContent = request.execute();        
  15.        long size = fileContent.getSize();      
  16.        Drive.Files.Get downloadRequest = drive.files().get(fileId);  
  17.        MediaHttpDownloader downloader = downloadRequest.getMediaHttpDownloader();    
  18.        boolean isDirectDownload = false;      
  19.        // 文件小于20M时可以使用简单下载        
  20.        if (size < DIRECT_DOWNLOAD_MAX_SIZE) {        
  21.            isDirectDownload = true;        
  22.        }        
  23.        // 设置下载Range,非简单下载时必须设置该参数。      
  24.        downloader.setContentRange(0, size - 1);      
  25.        // 设置下载方式,默认使用非简单下载。当文件小于20M时可以使用简单下载,即设置为true。
  26.        downloader.setDirectDownloadEnabled(isDirectDownload);      
  27.        // 设置进度回调通知       
  28.        downloadRequest.getMediaHttpDownloader().setProgressListener(new MediaHttpDownloaderProgressListener() {
  29.            @Override            
  30.            public void progressChanged(MediaHttpDownloader downloader) throws IOException {
  31.                //下载进度通知            
  32.            }        
  33.        });        
  34.        downloadRequest.executeContentAndDownloadTo(new FileOutputStream(destFile));    
  35.    } catch (Exception e) {
  36.        Logger.e(TAG, "download file error:" + fileId + e.getMessage());        
  37.        if (destFile != null) {            
  38.            // 下载失败后,删除临时文件            
  39.            if (destFile.exists()) {              
  40.                boolean isDeleteSuccess = destFile.delete();        
  41.                if (!isDeleteSuccess) {        
  42.                    Logger.e(TAG, "downLoadFile delete file fail");          
  43.                }            
  44.            }      
  45.        }    
  46.    }
  47. }

调用Files.list接口实现搜索文件:

  1. /**
  2. * 搜索文件
  1. * @param query 查询参数,详见Q查询语句
  2. * @param orderBy 排序字段
  3. * @param pageSize 分页大小
  4. * @param fields 设置请求返回时携带内容
  5. */
  6. private List<File> getFileList(String query, String orderBy, int pageSize, String fields){
  7.    List<File> fileList = null;
  8.    try{
  9.        Drive drive = buildDrive();
  10.        Drive.Files.List request = drive.files().list();
  11.        String cursor = null;
  12.        fileList = new ArrayList<>();
  13.        do {
  14.            FileList result = null;
  15.            result = request.setQueryParam(query)
  16.                .setOrderBy(orderBy)
  17.                .setPageSize(pageSize)
  18.                .setFields(fields)
  19.                .execute();
  20.            for (File file : result.getFiles()) {
  21.                fileList.add(file);
  22.            }
  23.            cursor = result.getNextCursor();
  24.            request.setCursor(cursor);
  25.        }while(!StringUtils.isNullOrEmpty(cursor));
  26.    }catch (Exception e) {
  27.        Logger.e(TAG, "executeFilesList exception: " + e.toString());
  28.    }
  29.    return fileList;
  30. }

调用Files.subscribe接口注册指定文件变化通知channel,开启指定文件变化通知功能:

  1. /**  
  2. * 注册指定文件变化通知channel,开启指定文件变化通知
  3. *    
  4. * @param fileId 文件id  
  5. */  
  6. private void filesWatch(String fileId) {  
  7.    try {  
  8.        Drive drive = buildDrive();  
  9.        Channel content = new Channel();    
  10.        content.setType("web_hook");      
  11.        content.setUrl("https://xxxx.com"); //文件变化通知服务器地址,开发者需搭建该服务器    
  12.        Drive.Files.Subscribe request = drive.files().subscribe(fileId, content);        
  13.        Channel channel = request.execute();    
  14.        SharedPreferences prefs = context.getSharedPreferences("channel_config", Context.MODE_PRIVATE);    
  15.        SharedPreferences.Editor editor = prefs.edit();    
  16.        editor.putString("id", channel.getId());  
  17.        editor.putString("resourceId", channel.getResourceId());        
  18.        editor.commit();  
  19.    } catch (Exception e) {  
  20.        Log.e(TAG, "Exception" + e.getCause());  
  21.    }
  22. }
注意:
文件操作接口是联网耗时接口,需要放在子线程中调用。

5 开启文件变化通知

5.1 场景介绍

华为云空间服务提供当文件发生变化时推送通知的能力,从而保持云端与本地文件同步。使用Changes功能需要第三方实现可实时接收变化的Server服务器,该Server可以接收变化并将变化信息实时推送给相应的客户端,客户端接收消息后可以及时刷新变化。

5.2 开发步骤

步骤1 第三方实现可以接收文件变化的Server服务器,需要将该Server的地址注册到Drive,Drive在发送变化消息时需要校验Server地址的有效性。

登录AppGallery Connect网站,将Server服务器域名注册到Drive方法如下图:

步骤2 开发者Server服务器需要能解析Drive发送的文件变化消息,Drive消息的消息头格式如下:

表1 

参数

类型

可选

说明

X-HW-Channel-ID

varchar(255)

必选

第三方开发者指定的,通过Changes.subscribe接口上报给Drive服务器的用户唯一标识。

X-HW-Channel-Token

varchar(255)

可选

通过Changes.subscribe接口Drive服务器返回的Cursor,Server需要对Cursor进行校验。

X-HW-Channel-Expiration

varchar(255)

可选

Channel通知到期的日期和时间

格式例如:Tue,18 Jun 2019 14:21:46 GMT。

X-HW-Resource-ID

varchar(255)

必选

资源ID,标识Channel正在监测的资源,当该资源变化时会推送通知。

X-HW-Resource-URI

varchar(255)

必选

资源版本标识符。

X-HW-Resource-State

varchar(255)

必选

资源状态,可选值:

sync:订阅成功,Channel创建成功。

add:资源增加。

remove:资源被删除。

update:资源属性被更新。

recycle:资源移动到回收站。

unrecycle:资源从回收站移出。

change:资源变化。

X-HW-Message-Number

Int64

必选

消息号,后面的消息总是大于前面的,但是并不是连续的。Sync消息总是为1。

X-HW-Changed

varchar(255)

可选

Change的详细信息,state为update时有效,可选值。

content: 资源内容更新。

properties: 资源属性更新。

parents: 资源的父目录变化,暂时不涉及。

children: 资源的子文件变化。

步骤3 第三方Server服务器下发变化通知应用。

第三方Server服务器能够将Drive发送的变化消息下发通知到应用,让应用刷新变化内容;Drive不限制第三方Server下发变化通知的实现方式,但推荐开发者使用华为推送服务,华为推送服务已经实现了将服务器消息推送到指定应用的功能,使用华为推送服务需要对接HMS Core Push SDK,具体参考《消息推送服务》。若不使用华为推送服务,则不需要集成HMS Core Push SDK,但第三方Server需要自己实现消息推送的功能。

步骤4 获取StartCursor,通过subscribe注册推送通知功能。

应用调用Changes.getStartCursor接口,获取Changes.subscribe需要使用的cursor值,调用Changes.subscribe接口注册文件变化时的推送通知功能,该接口会返回注册成功后的Channel对象,开发者需要将Channel中的channelToken回传给第三方Server,用于后续Server接口消息的鉴权使用,同时开发者可以根据该Channel进行后续的刷新变化、停止推送通知等接口处理。

  1. /**  
  2. * 注册文件变化通知
  3. * @param context 上下文环境
  4. * @param id UUID或其他字符串,唯一标识channel
  5. */
  6. private void watchChanges(Context context, String id) {      
  7.    try {      
  8.        Drive drive = buildDrive();
  9.        StartCursor startCursor = drive.changes().getStartCursor().execute();
  10.        String cursor = startCursor.getStartCursor();      
  11.        Channel content = new Channel();        
  12.        // id可以自定义,注意和Channels.stop接口保持一致      
  13.        content.setId(id);          
  14.        // 固定web_hook        
  15.        content.setType("web_hook");        
  16.        // 提供开发者用于接收变化的Server服务器地址    
  17.        content.setUrl("https://addr.xxx.com:8086/path/to/webhook");        
  18.        content.setExpirationTime(System.currentTimeMillis() + 300 * 1000L);    
  19.        Channel channel = drive.changes().subscribe(cursor, content).execute();    
  20.        // 需要将channelToken回传给三方Server服务器Url    
  21.        String channelToken = channel.getUserToken();              
  22.        SharedPreferences prefs = context.getSharedPreferences("channel_config", Context.MODE_PRIVATE);        
  23.        SharedPreferences.Editor editor = prefs.edit();        
  24.        editor.putString("startPageVersion", cursor);    
  25.        editor.putString("resourceId", channel.getResourceId());        
  26.        editor.commit();
  27.    } catch (Exception e) {      
  28.        Log.e(TAG, "watchChanges error: " + e.toString());  
  29.    }
  30. }
注意:
获取StartCursor及Channel接口是联网耗时接口,需要放在子线程中调用。
       

步骤5 获取用户文件变化。

应用收到第三方下发的通知后,调用Changes.list接口,获取用户文件变化,注意cursor入参为之前subscribe时传入的cursor。

  1. /**
  2. * 获取文件变化
  3. *
  4. * @param cursor 之前调用changes.subscribe传入的cursor
  5. */
  6. private List<Change> getChangesList(String cursor) {
  7.    List<Change> changes = null;
  8.    try {
  9.        Drive drive = buildDrive();
  10.        Drive.Changes.List listRequest = drive.changes().list(cursor);
  11.        listRequest.setFields("*");
  12.        ChangeList changeList = listRequest.execute();
  13.        changes = changeList.getChanges();
  14.    } catch (Exception e) {
  15.        Log.e(TAG, "doChangesList error: " + e.toString());
  16.    }
  17.    return changes;
  18. }
注意:
获取用户文件变化是联网耗时接口,需要放在子线程中调用。
       

6停止文件变化通知

6.1 场景介绍

华为云空间服务支持第三方应用关闭推送指定的Channel的变化通知,关闭后,该Channel不再收到文件变化通知。注意构造的Channel对象中的Id和resourceId与Changes中subscribe的Channel对象的Id和resourceId一致。

6.2 开发步骤

步骤1调用Drive.Builder.build接口构造Drive对象。

  1. private Drive buildDrive() {
  2.  Drive service = new Drive.Builder(CredentialManager.getInstance().getCredential(), context).build();
  3.  return service;
  4. }

步骤2获取之前注册推送通知时缓存的Id和resourceId,调用Channels.stop接口停止指定channel的文件变化通知。

  1. /**
  2. * 关闭指定的Channel
  3. * @param context 上下文环境
  4. * @param id UUID或其他字符串,唯一标识channel, 与subscribe接口的id保持一致
  5. */
  6. private void stopChannel(Context context, String id) {
  7.  try {
  8.    Drive drive = buildDrive();
  9.    SharedPreferences preferences = context.getSharedPreferences("channel_config", Context.MODE_PRIVATE);
  10.    String resourceId = preferences.getString("resourceId", "");
  11.    Channel channel = new Channel();
  12.    channel.setId(id);
  13.    channel.setCategory("api#channel");
  14.    channel.setResourceId(resourceId);
  15.    Drive.Channels.Stop stopReq = drive.channels().stop(channel);
  16.    stopReq.execute();
  17.  } catch (Exception e) {  
  18.    Log.e(TAG, "stopChannels error: " + e.toString());
  19.  }
  20. }
注意:
停止指定channel的文件变化通知接口是联网耗时接口,需要放在子线程中调用。

7文件评论

7.1 场景介绍

华为云空间服务支持用户对云端文件进行评论,并对评论进行查看、更新和删除操作。

7.2 开发步骤

步骤1调用Drive.Builder.build接口构造Drive对象。

  1. private Drive buildDrive() {
  2.    Drive service = new Drive.Builder(CredentialManager.getInstance().getCredential(), context).build();
  3.    return service;
  4. }

步骤2调用Comments

调用Comments.Create接口创建文件评论:

  1. /**
  2. * 创建文件评论
  3. *
  4. * @param fileId 文件id
  5. */
  6. private Comment createComments(String fileId) {
  7.    Comment comment = null;
  8.    Drive drive = buildDrive();
  9.    try {
  10.        Comment content = new Comment();
  11.        content.setDescription("interface test");
  12.        content.setCreatedTime(new DateTime(System.currentTimeMillis()));
  13.        comment = drive.comments().create(fileId, content).setFields("*").execute();
  14.    } catch (Exception ex) {
  15.        Log.e(TAG, "createComments error: " + ex.toString());
  16.    }
  17.    return comment;
  18. }

调用Comments.List接口获取文件评论列表:

  1. /**
  2. * 获取文件评论列表
  3. *
  4. * @param fileId 文件id
  5. */
  6. private List<Comment> listComments(String fileId) {
  7.    Drive drive = buildDrive();
  8.    ArrayList<Comment> commentArrayList = new ArrayList<>();
  9.    String nextCursor = null;
  10.    try {
  11.        Drive.Comments.List request = drive.comments().list(fileId);
  12.        do {
  13.            if (nextCursor != null) {
  14.                request.setCursor(nextCursor);
  15.            }
  16.            CommentList commentList = request.setPageSize(100).setFields("*").execute();
  17.            ArrayList<Comment> comments = (ArrayList<Comment>) commentList.getComments();
  18.            if (comments == null) {
  19.                break;
  20.            }
  21.            commentArrayList.addAll(comments);
  22.            nextCursor = commentList.getNextCursor();
  23.        } while (!StringUtils.isNullOrEmpty(nextCursor));
  24.    } catch (IOException e) {
  25.        Logger.e(TAG, "comments list error: " + e.toString());
  26.    }
  27.    return commentArrayList;
  28. }

调用Comments.Get接口获取文件评论详情:

  1. /**
  2. * 获取文件评论详情
  3. *
  4. * @param fileId 文件id
  5. * @param commentId 评论id
  6. */
  7. private Comment getComments(String fileId, String commentId) {
  8.    Comment comment = null;
  9.    Drive drive = buildDrive();
  10.    try {
  11.        comment = drive.comments().get(fileId, commentId).setFields("*").execute();
  12.        Log.d(TAG, "comment: " + comment.getDescription());
  13.    } catch (Exception ex) {
  14.        Log.e(TAG, "getComments error: " + ex.toString());
  15.    }
  16.    return comment;
  17. }

调用Comments.Update接口更新文件评论:

  1. /**
  2. * 更新文件评论
  3. *
  4. * @param fileId 文件id
  5. * @param commentId 评论id
  6. */
  7. private void updateComments(String fileId, String commentId) {
  8.    Drive drive = buildDrive();
  9.    try {
  10.        Comment content = new Comment();
  11.        content.setDescription("update interface test");
  12.        drive.comments().update(fileId, commentId, content).execute();
  13.    } catch (Exception ex) {
  14.        Log.e(TAG, "updateComments error: " + ex.toString());
  15.    }
  16. }

调用Comments.Delete接口删除文件评论:

  1. /**
  2. * 删除文件评论
  3. *
  4. * @param fileId 文件id
  5. * @param commentId 评论id
  6. */
  7. private void deleteComments(String fileId, String commentId) {
  8.    Drive drive = buildDrive();
  9.    try {
  10.        drive.comments().delete(fileId, commentId).execute();
  11.    } catch (Exception ex) {
  12.        Log.e(TAG, "deleteComments error: " + ex.toString());
  13.    }
  14. }
注意:
文件评论接口是联网耗时接口,需要放在子线程中调用。

8评论回复

8.1 场景介绍

华为云空间服务支持用户对云端文件的评论进行行回复,并对回复进行查看、更新和删除操作。

8.2 开发步骤

步骤1调用Drive.Builder.build接口构造Drive对象。

  1. private Drive buildDrive() {
  2.    Drive service = new Drive.Builder(CredentialManager.getInstance().getCredential(), context).build();
  3.    return service;
  4. }

步骤2调用Replies接口能力

调用Replies.Create接口创建评论回复:

  1. /**
  2. * 创建文件评论回复
  3. *
  4. * @param fileId 文件id
  5. * @param commentId 文件评论id
  6. */
  7. private Reply createReplies(String fileId, String commentId) {
  8.    Reply replyResponse = null;
  9.    Drive drive = buildDrive();
  10.    try {
  11.        Reply reply = new Reply();
  12.        reply.setDescription("interface test reply");
  13.        reply.setOperate("resolve");
  14.        replyResponse = drive.replies().create(fileId, commentId, reply).setFields("*").execute();
  15.    } catch (Exception ex) {
  16.        Log.e(TAG, "createReplies error: " + ex.toString());
  17.    }
  18.    return replyResponse;
  19. }

调用Replies.List接口获取评论回复列表:

  1. /**
  2. * 获取评论回复列表
  3. *
  4. * @param fileId 文件id
  5. * @param commentId 评论id
  6. */
  7. private List<Reply> listReplies(String fileId, String commentId) {
  8.    Drive drive = buildDrive();
  9.    List<Reply> replyResponse = new ArrayList<>();
  10.    String nextCursor = null;
  11.    try {
  12.        Drive.Replies.List listReq = drive.replies().list(fileId, commentId);
  13.        do {
  14.            if (nextCursor != null) {
  15.                listReq.setCursor(nextCursor);
  16.            }
  17.            ReplyList replyList = listReq.setFields("*").execute();
  18.            List<Reply> replies = replyList.getReplies();
  19.            if (replies == null) {
  20.                break;
  21.            }
  22.            replyResponse.addAll(replies);
  23.            nextCursor = replyList.getNextCursor();
  24.        } while (StringUtils.isNullOrEmpty(nextCursor));
  25.    } catch (Exception ex) {
  26.        Log.e(TAG, "listReplies error: " + ex.toString());
  27.    }
  28.    return replyResponse;
  29. }

调用Replies.Get接口获取评论回复详情:

  1. /**
  2. * 获取评论回复详情
  3. *
  4. * @param fileId 文件id
  5. * @param commentId 评论id
  6. * @param replyId 回复id
  7. */
  8. private Reply getReplies(String fileId, String commentId, String replyId) {
  9.    Reply reply = null;
  10.    Drive drive = buildDrive();
  11.    try {
  12.        reply = drive.replies().get(fileId, commentId, replyId).setFields("*").execute();
  13.    } catch (Exception ex) {
  14.        Log.e(TAG, "getReplies error: " + ex.toString());
  15.    }
  16.    return reply;
  17. }

调用Replies.Update接口更新评论回复:

  1. /**
  2. * 更新评论回复
  3. *
  4. * @param fileId 文件id
  5. * @param commenId 评论id
  6. * @param replyId 回复id
  7. */
  8. private void updateReplies(String fileId, String commentId, String replyId) {
  9.    Drive drive = buildDrive();
  10.    try {
  11.        Reply reply = new Reply();
  12.        reply.setDescription("interface test reply");
  13.        reply.setOperate("reopen");
  14.        drive.replies().update(fileId, commentId, replyId, reply).execute();
  15.    } catch (Exception ex) {
  16.        Log.e(TAG, "updateReplies error: " + ex.toString());
  17.    }
  18. }

调用Replies.Delete接口删除评论回复:

  1. /**
  2. * 删除评论回复
  3. *
  4. * @param fileId 文件id
  5. * @param commenId 评论id
  6. * @param replyId 回复id
  7. */
  8. private void deleteReplies(String fileId, String commentId, String replyId) {
  9.    Drive drive = buildDrive();
  10.    try {
  11.        drive.replies().delete(fileId, commentId, replyId).execute();
  12.    } catch (Exception ex) {
  13.        Log.e(TAG, "deleteReplies error: " + ex.toString());
  14.    }
  15. }
注意:
回复评论接口是联网耗时接口,需要放在子线程中调用。

9 批量操作

9.1 场景介绍

华为云空间服务支持第三方应用对某些接口进行批量操作,具体接口如下:文件(夹)的批量操作,如创建文件夹、创建文件元数据、复制、更新、删除、订阅等,评论及回复的批量操作,如评论及回复的新增、更新、删除等。

9.2 开发步骤

以批量创建文件夹为例来说明具体开发步骤:

步骤1 调用Drive.Builder.build接口构造Drive对象。

  1. private Drive buildDrive() {
  2.    Drive service = new Drive.Builder(CredentialManager.getInstance().getCredential(), context).build();
  3.    return service;
  4. }

步骤2 创建JsonBatchCallback回调对象,调用Drive的batch函数获取BatchRequest对象,再调用Files.Create的queue函数将操作添加到队列中,再执行BatchRequest.execute即可完成批量操作。

  1. /**
  2. * 批量创建回调
  3. */
  4. JsonBatchCallback<File> callback = new JsonBatchCallback<File>() {
  5.    @Override
  6.    public void onFailure(JsonError e, HttpHeaders responseHeaders) throws IOException {
  7.        Logger.i(TAG, "callback error: " + e.toString());
  8.    }
  9.    @Override
  10.    public void onSuccess(File file, HttpHeaders responseHeaders) throws IOException {
  11.        Logger.i(TAG, "callback sucessful: " + file.toString());
  12.    }
  13. };
  14. /**
  15. * 批量创建目录
  16. */
  17. private void batchCreateDirectory() {
  18.    Drive drive = buildDrive();
  19.    BatchRequest batch = drive.batch();
  20.    try {
  21.        for (int i = 0; i < 2; i++) {
  22.            Map<String, String> appProperties = new HashMap<>();
  23.            appProperties.put("appProperties", "property");
  24.            SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMdd_HHmmss_SSS");
  25.            String dirName = formatter.format(new Date()) + "_" + i;
  26.            Logger.i(TAG, "executeFilesCreate: " + dirName);
  27.            File file = new File();
  28.            file.setFileName(dirName)
  29.                    .setAppSettings(appProperties)
  30.                    .setMimeType("application/vnd.huawei-apps.folder");
  31.            Drive.Files.Create create = drive.files().create(file);
  32.            create.queue(batch, callback);
  33.        }
  34.        batch.execute();
  35.    } catch (Exception e) {
  36.        Logger.e(TAG, "batchCreateDirectory error: " + e.toString());
  37.    }
  38. }