Source

backend/cloud_sync/dropbox_sync.js

/* This file is part of Ezra Bible App.

   Copyright (C) 2019 - 2026 Ezra Bible App Development Team <contact@ezrabibleapp.net>

   Ezra Bible App is free software: you can redistribute it and/or modify
   it under the terms of the GNU General Public License as published by
   the Free Software Foundation, either version 2 of the License, or
   (at your option) any later version.

   Ezra Bible App is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   GNU General Public License for more details.

   You should have received a copy of the GNU General Public License
   along with Ezra Bible App. See the file LICENSE.
   If not, see <http://www.gnu.org/licenses/>. */

const Dropbox = require('dropbox');
const isomorphicFetch = require('isomorphic-fetch');
const fs = require('fs');
const path = require('path');
const dch = require('./dropbox_content_hasher.js');
const RemoteFileSync = require('./remote_file_sync.js');

const UPLOAD_FILE_SIZE_LIMIT = 150 * 1024 * 1024; // 150 MB

function isNotFoundError(e) {
  return !!(e && e.error && e.error.error_summary && e.error.error_summary.indexOf('not_found') != -1);
}

class DropboxSync extends RemoteFileSync {
  constructor(CLIENT_ID, TOKEN, REFRESH_TOKEN) {
    super();
    this.providerName = 'Dropbox';
    this._TOKEN = TOKEN;
    this._REFRESH_TOKEN = REFRESH_TOKEN;
    this._CLIENT_ID = CLIENT_ID;

    this._dbxAuth = new Dropbox.DropboxAuth({
      clientId: CLIENT_ID,
      refreshToken: REFRESH_TOKEN,
      accessToken: TOKEN
    });

    this._dbx = this._createClient();
  }

  _createClient() {
    return new Dropbox.Dropbox({
      clientId: this._CLIENT_ID,
      accessToken: this._TOKEN,
      refreshToken: this._REFRESH_TOKEN,
      fetch: isomorphicFetch
    });
  }

  async refreshAccessToken() {
    await this._dbxAuth.checkAndRefreshAccessToken();
    this._TOKEN = this._dbxAuth.getAccessToken();
    this._dbx = this._createClient();
    return this._TOKEN;
  }

  async getFolders() {
    let response = await this._withRetry(
      () => this._dbx.filesListFolder({path: ''}),
      'filesListFolder'
    );

    return response.result.entries.filter(item => item['.tag'] == 'folder');
  }

  async listFolder(folderPath) {
    let { result: response, retryCount } = await this._withRetry(
      () => this._dbx.filesListFolder({path: folderPath}),
      'filesListFolder',
      true
    );
    let entries = response.result.entries;
    let paginationCalls = 0;
    let totalRetries = retryCount;

    while (response.result.has_more) {
      paginationCalls++;
      const continueResult = await this._withRetry(
        () => this._dbx.filesListFolderContinue({cursor: response.result.cursor}),
        'filesListFolderContinue',
        true
      );
      response = continueResult.result;
      totalRetries += continueResult.retryCount;
      entries = entries.concat(response.result.entries);
    }

    return {
      entries: entries,
      retryCount: totalRetries,
      paginationCalls: paginationCalls
    };
  }

  async listFolderEntries(folderPath) {
    // The Dropbox API addresses the root folder with an empty string
    const dropboxPath = (folderPath === '/') ? '' : folderPath;
    let result;

    try {
      result = await this.listFolder(dropboxPath);
    } catch (e) {
      if (isNotFoundError(e)) {
        e.notFound = true;
      }
      throw e;
    }

    return result.entries
      .filter(entry => entry['.tag'] === 'file' || entry['.tag'] === 'folder')
      .map(entry => ({
        name: entry.name,
        path: entry.path_display,
        isFolder: entry['.tag'] === 'folder',
        size: entry.size || 0
      }));
  }

  async testAuthentication() {
    await this.getFolders();
  }

  async downloadFile(dropboxPath, destinationDir) {
    const response = await this._withRetry(
      () => this._dbx.filesDownload({path: dropboxPath}),
      'filesDownload'
    );

    const fileName = response.result.name;
    const destFilePath = path.join(destinationDir, fileName);

    try {
      fs.writeFileSync(destFilePath, response.result.fileBinary);
    } catch (err) {
      throw new Error(`Failed to write downloaded file to ${destFilePath}: ${err.message}`);
    }
  }

  async uploadFile(filePath, dropboxPath) {
    let fileBlob;

    try {
      fileBlob = fs.readFileSync(filePath);
    } catch (err) {
      throw new Error(`Failed to read file ${filePath} for upload: ${err.message}`);
    }

    if (fileBlob.byteLength < UPLOAD_FILE_SIZE_LIMIT) {
      return await this._withRetry(
        () => this._dbx.filesUpload({path: dropboxPath, contents: fileBlob, mode: 'overwrite'}),
        'filesUpload'
      );
    } else {
      throw new Error(`File ${filePath} is bigger than the Dropbox upload allows!`);
    }
  }

  async getRemoteFileInfo(dropboxPath) {
    try {
      const metaData = await this.getFileMetaData(dropboxPath);
      return {
        size: metaData.size,
        modified: new Date(metaData.server_modified),
        contentHash: metaData.content_hash
      };
    } catch (e) {
      if (isNotFoundError(e)) {
        return null;
      }

      // Network error or other API error - rethrow to abort sync rather than assuming file doesn't exist
      throw e;
    }
  }

  async isFileSynced(localFilePath, dropboxPath) {
    if (!fs.existsSync(localFilePath)) {
      throw Error(`File ${localFilePath} does not exist!`);
    }

    const localHash = await this.getLocalFileHash(localFilePath);
    const remoteInfo = await this.getRemoteFileInfo(dropboxPath);

    if (remoteInfo == null) {
      return false;
    }

    return localHash === remoteInfo.contentHash;
  }

  async getFileMetaData(dropboxPath) {
    const response = await this._withRetry(
      () => this._dbx.filesGetMetadata({path: dropboxPath}),
      'filesGetMetadata'
    );
    return response.result;
  }

  async getLocalFileHash(fileName) {
    const hasher = dch.create();
    const f = fs.createReadStream(fileName);

    return new Promise((resolve, reject) => {
      f.on('data', (buf) => hasher.update(buf));
      f.on('end', () => resolve(hasher.digest('hex')));
      f.on('error', (err) => reject(new Error('Error reading from file: ' + err)));
    });
  }
}

module.exports = DropboxSync;