TarikHuber / rmw-shell

Shell of main components for the React Most Wanted project
26 stars 23 forks source link

Improve: Images are stored in high resolution for avatar #25

Open wortkotze opened 5 years ago

wortkotze commented 5 years ago

to create a thumbnail we are using cloudfunctions and change the photourl

`// Import functions and GCS const os = require("os"); const path = require("path"); // GCS for Image Compression Feature const spawn = require("child-process-promise").spawn; // The Cloud Functions for Firebase SDK to create Cloud Functions and setup triggers. const functions = require("firebase-functions"); const admin = require("firebase-admin"); const UUID4 = require("uuid-v4");

const uuid = UUID4();

try { admin.initializeApp(); } catch (e) { console.log(e); }

exports = module.exports = functions.storage .object() .onFinalize(async object => { const bucket = object.bucket; const contentType = object.contentType; const filePath = object.name;

console.log("File change detected, resizefunction execution started");

if (object.resourceState === "not_exists") {
  console.log("We deleted a file, exit...");
  return;
}

if (path.basename(filePath).endsWith("-resized")) {
  console.log("We already resized that file!");
  return;
}

const destBucket = admin.storage().bucket(bucket);
const testfile = destBucket.file(filePath);
const tmpFilePath = path.join(os.tmpdir(), path.basename(filePath));
const metadata = { contentType: contentType };

console.log("Image resizing for: " + filePath);

return destBucket
  .file(filePath)
  .download({
    destination: tmpFilePath
  })
  .then(() => {
    return spawn("convert", [
      tmpFilePath,
      "-resize",
      "400x400>",
      tmpFilePath
    ]);
  })
  .then(() => {
    destBucket
      .upload(tmpFilePath, {
        destination: filePath + "-resized",
        metadata: {
          contentType: "image/png",
          metadata: {
            optimized: true,
            firebaseStorageDownloadTokens: uuid
          }
        }
      })
      .then(res => {
        //File uploaded complete, can be found at:
        console.log(
          "File Uploaded to: " +
            "https://firebasestorage.googleapis.com/v0/b/" +
            destBucket.name +
            "/o/" +
            encodeURIComponent(filePath + "-resized") +
            "?alt=media&token=" +
            uuid
        );

        // filePath.split("/")[1] == UserId

        admin.auth().updateUser(filePath.split("/")[1], {
          photoURL:
            "https://firebasestorage.googleapis.com/v0/b/" +
            destBucket.name +
            "/o/" +
            encodeURIComponent(filePath + "-resized") +
            "?alt=media&token=" +
            uuid
        });

        return "upload complete";
      })
      .catch(err => {
        console.log("err", err);
      });

    return "uploaded complete";
  });

}); `

probably this could gelp someone to save some KBs