trapeze icon indicating copy to clipboard operation
trapeze copied to clipboard

Download file from external location if source: begins with http/s

Open matthewbecker1990 opened this issue 2 years ago • 1 comments

It would be amazing to be able to do something like this

    res:
      - path: drawable
        file: icon.png
        source: https://example.com/$BUNDLE_ID/icon.png

to grab files dynamically if you are creating multiple projects from the one code base.

matthewbecker1990 avatar Oct 18 '22 12:10 matthewbecker1990

If anyone needs to do something similar, you can use the Project API.

// FILE: scripts/download.mjs

import https from "https";
import fs from "fs";

function downloadAsset(url, dest) {
  return new Promise((resolve, reject) => {
    const file = fs.createWriteStream(dest);

    const request = https.get(url, (response) => {
      if (response.statusCode === 200) {
        response.pipe(file);
      } else {
        file.close();
        fs.unlink(dest, () => {}); // Delete temp file
        reject(`Server responded with ${response.statusCode}: ${response.statusMessage}`);
      }
    });

    request.on("error", (err) => {
      file.close();
      fs.unlink(dest, () => {}); // Delete temp file
      reject(err.message);
    });

    file.on("finish", () => {
      resolve();
    });

    file.on("error", (err) => {
      file.close();

      if (err.code === "EEXIST") {
        reject("File already exists");
      } else {
        fs.unlink(dest, () => {}); // Delete temp file
        reject(err.message);
      }
    });
  });
}

export { downloadAsset };
import { downloadAsset } from "./scripts/download.mjs";

await downloadAsset(
    "https://www.example.com/icon.png",
    process.cwd() + "/tmp/icons/icon.png"
);
project.android?.copyToResources("drawable", "icon.png", "tmp/icons/icon.png");

matthewbecker1990 avatar Oct 20 '22 22:10 matthewbecker1990

Supporting URLs in addition to file paths seems like a reasonable future enhancement. Thanks for the idea!

mlynch avatar Nov 02 '22 12:11 mlynch

I made a quick addition to support this in the ios and android copy commands (use a URL as the src option) and the Android res command (use a URL for the source) field. Out in 5.0.9

mlynch avatar Nov 08 '22 22:11 mlynch