md-curcuma
Version:
A Typescript library for transporting and converting markdown and other data.
91 lines (90 loc) • 3.75 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.ImageDownloader_Mapping = void 0;
const uuid_1 = require("uuid");
const filesystem_1 = require("../../core/filesystem");
const fs = require("fs");
const client_http = require("http");
const client_https = require("https");
const url_1 = require("url");
class ImageDownloader_Mapping {
constructor(properties) {
this.properties = properties;
}
perform(mapping_properties) {
let source_property_name = mapping_properties.source_property_name;
let source_property_value = mapping_properties.source.data[source_property_name];
let image_url = source_property_value;
let image_target_folder = this.properties.image_target_folder;
let image_hugo_path = this.properties.image_hugo_path;
if (ImageDownloader_Mapping.is_valid_url(image_url)) {
const myURL = new url_1.URL(image_url);
let image_name = "";
if (myURL)
if (myURL.pathname.indexOf(".") > 0) {
image_name = myURL.pathname.substring(myURL.pathname.lastIndexOf("/"), myURL.pathname.length);
}
else {
image_name =
image_url.substring(image_url.lastIndexOf("/") + 1) + ".jpg";
}
let uuid = (0, uuid_1.v4)();
if (mapping_properties.source.hasOwnProperty(this.properties.filename_property_name)) {
uuid =
mapping_properties.source[this.properties.filename_property_name];
}
image_target_folder = filesystem_1.Filesystem.concat_path_filename(image_target_folder, image_name);
image_hugo_path = filesystem_1.Filesystem.concat_path_filename(image_hugo_path, image_name);
console.log(`Try to download from url: '${image_url}' to '${image_target_folder}'...`);
if (!this.properties.simulate) {
ImageDownloader_Mapping.download_image(image_url, image_target_folder)
.then(function (result) {
console.log(`Downloaded from url: '${image_url}' to '${image_target_folder}' with result '${result}'`);
})
.catch(console.error);
}
}
else {
image_hugo_path = "";
}
return image_hugo_path;
}
static is_valid_url_protocol(url) {
try {
const newUrl = new url_1.URL(url);
return newUrl.protocol === "http:" || newUrl.protocol === "https:";
}
catch (err) {
return false;
}
}
static is_valid_url(url) {
try {
const myURL = new url_1.URL(url);
return true;
}
catch (error) {
console.log(`${error.input} is not a valid url`);
return false;
}
}
static download_image(url, filepath) {
return new Promise((resolve, reject) => {
let client = url.startsWith("https://") ? client_https : client_http;
client.get(url, (response) => {
if (response.statusCode === 200) {
let write_stream = fs.createWriteStream(filepath);
response
.pipe(write_stream)
.on("error", reject)
.once("close", () => resolve(filepath));
}
else {
response.resume();
reject(new Error(`Download from ${url} Failed With Status Code: ${response.statusCode}`));
}
});
});
}
}
exports.ImageDownloader_Mapping = ImageDownloader_Mapping;