All files / client/methods remoteupload.js

100% Statements 20/20
42.86% Branches 3/7
92.31% Functions 12/13
100% Lines 20/20
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74                        12x 1x 1x           1x 1x         1x 1x       1x 1x         1x   1x     1x 1x 1x                     1x   1x 1x             1x   1x 1x          
/* @flow */
 
import invariant from "invariant";
import type {
  UploadOptions,
  RemoteUploadProgress,
  RemoteUploadProgressFile
} from "../../api/types";
import type { MethodApi } from "../types";
import { uniqueNumber, randomNumber } from "../../utils";
 
export default ({ client }: MethodApi) =>
  (urls: string, folderid: number = 0, options: UploadOptions = {}) => {
    invariant(urls, "`file` is required.");
    invariant(typeof urls === "string", "`file` must be supplied");
 
    const {
      onBegin = () => {},
      onProgress = () => {},
      onFinish = () => {}
    } = options;
    const progressId = "pcloud-sdk-remote-" + uniqueNumber() + "-" +
      randomNumber();
    var progressTimeout;
 
    function progress() {
      pollProgress();
      progressTimeout = setTimeout(progress, 200);
    }
 
    function stopProgress() {
      Eif (progressTimeout) {
        clearTimeout(progressTimeout);
      }
    }
 
    function pollProgress() {
      client
        .api("uploadprogress", { params: { progresshash: progressId } })
        .then(({ files }) => onProgress(calculateProgress(files)));
    }
 
    onBegin();
    progress();
    return client
      .api("downloadfile", {
        method: "post",
        params: {
          folderid: folderid,
          progresshash: progressId,
          nopartial: 1,
          url: urls
        }
      })
      .then(({ metadata}) => {
        stopProgress();
 
        onFinish({ metadata: metadata[0] });
        return { metadata: metadata[0] };
      });
  };
 
function calculateProgress(
  files: Array<RemoteUploadProgressFile>
): RemoteUploadProgress {
  return {
    all: {
      downloaded: files.reduce((n, file) => n + file.downloaded, 0),
      size: files.reduce((n, file) => n + file.size, 0)
    },
    files: files
  };
}