All files / src image-uploader.ts

11.27% Statements 8/71
12.5% Branches 4/32
0% Functions 0/11
11.27% Lines 8/71

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219  1x 1x 1x 1x 1x                 1x 1x                                                                                                                                                                                                                                                                                                                                                                         1x                                            
// sm.ms api
import * as fs from "fs";
import * as path from "path";
import * as request from "request";
import * as utility from "./utility";
import { getExtensionConfigPath } from "./mume";
 
// imgur api
// referred from node-imgur:
// https://github.com/kaimallea/node-imgur/blob/master/lib/imgur.js
// The following client ID is tied to the
// registered 'node-imgur' app and is available
// here for public, anonymous usage via this node
// module only.
const IMGUR_API_URL = process.env.IMGUR_API_URL || "https://api.imgur.com/3/";
const IMGUR_CLIENT_ID = process.env.IMGUR_CLIENT_ID || "f0ea04148a54268";
 
/**
 *
 * @param imageFilePath local image file path
 * @param imageUrl http://... image url
 */
async function addImageURLToHistory(imageFilePath, imageUrl) {
  let description;
  if (imageFilePath.lastIndexOf(".")) {
    description = imageFilePath.slice(0, imageFilePath.lastIndexOf("."));
  } else {
    description = imageFilePath;
  }
 
  const markdownImage = `![${description}](${imageUrl})`;
 
  // TODO: save to history
  const imageHistoryPath = path.resolve(
    getExtensionConfigPath(),
    "./image_history.md",
  );
  let data: string;
  try {
    data = await utility.readFile(imageHistoryPath, { encoding: "utf-8" });
  } catch (e) {
    data = "";
  }
  data =
    `
${markdownImage}
 
\`${markdownImage}\`
 
${new Date().toString()}
 
---
 
` + data;
  utility.writeFile(imageHistoryPath, data, { encoding: "utf-8" });
}
 
/**
 * Upload image to imgur
 * @param filePath
 */
function imgurUploadImage(filePath: string): Promise<string> {
  return new Promise((resolve, reject) => {
    const headers = {
      Authorization: `Client-ID ${IMGUR_CLIENT_ID}`,
    };
 
    request.post(
      {
        url: `${IMGUR_API_URL}image`,
        encoding: "utf8",
        formData: { image: fs.createReadStream(filePath) },
        json: true,
        headers,
      },
      (err, httpResponse, body) => {
        if (err) {
          return reject(err);
        }
        if (body.success) {
          const url = body.data.link;
          addImageURLToHistory(filePath, url);
          return resolve(url);
        } else {
          return resolve(body.data.error.message);
        }
      },
    );
  });
}
 
/**
 * Upload image to sm.ms
 * @param filePath
 */
function smmsUploadImage(filePath: string): Promise<string> {
  return new Promise((resolve, reject) => {
    const headers = {
      "authority": "sm.ms",
      "user-agent": "mume",
      "referer": "",
    };
    request.post(
      {
        url: "https://sm.ms/api/v2/upload",
        formData: { smfile: fs.createReadStream(filePath) },
        headers,
      },
      (err, httpResponse, body) => {
        try {
          body = JSON.parse(body);
          if (err) {
            return reject("Failed to upload image");
          } else if (body.code === "error") {
            return reject(body.msg);
          } else {
            const url = body.data.url;
            addImageURLToHistory(filePath, url);
            return resolve(url);
          }
        } catch (error) {
          return reject("Failed to connect to sm.ms host");
        }
      },
    );
  });
}
 
/**
 * Upload image to qiniu
 * @param filePath
 * @param AccessKey
 * @param SecretKey
 * @param Bucket
 * @param Domain
 */
function qiniuUploadImage(
  filePath: string,
  AccessKey: string,
  SecretKey: string,
  Bucket: string,
  Domain: string,
): Promise<string> {
  return new Promise((resolve, reject) => {
    if (!AccessKey) {
      return reject("Error: Qiniu AccessKey is missing");
    }
    if (!SecretKey) {
      return reject("Error: Qiniu SecretKey is missing");
    }
    if (!Bucket) {
      return reject("Error: Qiniu Bucket is missing");
    }
    if (!Domain) {
      return reject("Error: Qiniu Domain is missing");
    }
 
    const qiniu = require("qiniu");
    const mac = new qiniu.auth.digest.Mac(AccessKey, SecretKey);
    const putPolicy = new qiniu.rs.PutPolicy({ scope: Bucket });
    const uploadToken = putPolicy.uploadToken(mac);
    const config = new qiniu.conf.Config();
    const key = path.basename(filePath);
    const formUploader = new qiniu.form_up.FormUploader(config);
    const putExtra = new qiniu.form_up.PutExtra();
 
    return formUploader.putFile(
      uploadToken,
      key,
      filePath,
      putExtra,
      (respErr, respBody, respInfo) => {
        if (respErr) {
          // console.log(respErr);
          return reject(respErr.message);
        }
 
        if (respInfo.statusCode === 200) {
          const bucketManager = new qiniu.rs.BucketManager(mac, config);
          const url = bucketManager.publicDownloadUrl(Domain, key);
          return resolve(url);
        } else {
          // console.log(respInfo);
          return reject(respInfo.error);
        }
      },
    );
  });
}
 
/**
 * Upload image
 * @param imageFilePath
 * @param method 'imgur' or 'sm.ms'
 * @param qiniu {AccessKey, SecretKey, Bucket, Domain}
 */
export function uploadImage(
  imageFilePath: string,
  {
    method = "imgur",
    qiniu = { AccessKey: "", SecretKey: "", Bucket: "", Domain: "" },
  },
): Promise<string> {
  if (method === "imgur") {
    return imgurUploadImage(imageFilePath);
  } else if (method === "qiniu") {
    return qiniuUploadImage(
      imageFilePath,
      qiniu.AccessKey,
      qiniu.SecretKey,
      qiniu.Bucket,
      qiniu.Domain,
    );
  } else {
    // sm.ms
    return smmsUploadImage(imageFilePath);
  }
}