How to use the firebase-admin.storage function in firebase-admin

To help you get started, we’ve selected a few firebase-admin examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github TarikHuber / react-most-wanted / packages / firebase-function-tools / src / thumbnail.js View on Github external
const contentType = object.contentType // This is the image MIME type
  const fileDir = path.dirname(filePath)
  const fileName = path.basename(filePath)
  const thumbFilePath = path.normalize(
    path.join(fileDir, `${thumbPrefix}${fileName}`)
  )
  const tempLocalFile = path.join(os.tmpdir(), filePath)
  const tempLocalDir = path.dirname(tempLocalFile)
  const tempLocalThumbFile = path.join(os.tmpdir(), thumbFilePath)

  if (fileName.startsWith(thumbPrefix)) {
    console.log('Already a Thumbnail.')
    return false
  }

  const bucket = admin.storage().bucket(object.bucket)
  const file = bucket.file(filePath)
  const thumbFile = bucket.file(thumbFilePath)
  const metadata = {
    contentType: contentType,
    'Cache-Control': cacheControl,
  }

  await mkdirp(tempLocalDir)

  await file.download({
    destination: tempLocalFile,
  })

  await spawn(
    'convert',
    [
github deckgo / deckdeckgo / cloud / functions / src / watch / screenshot / generate-deck-screenshot.ts View on Github external
return;
        }

        if (!deckData || !deckData.meta || !deckData.meta.pathname) {
            reject('No deck or data');
            return;
        }

        const path: string[] = deckData.meta.pathname.split('/');

        if (!path || path.length < 3) {
            reject('Path not well formatted');
            return;
        }

        const bucket = admin.storage().bucket();

        // path[0] = ''
        // path[1] = user
        // path[2] = presentation-name
        const file = bucket.file(`${deckData.owner_id}/${Resources.Constants.PRESENTATION.FOLDER}/${path[2]}/${Resources.Constants.PRESENTATION.IMAGE}`);

        try {
            await file.save(imageBuffer);

            resolve();
        } catch (err) {
            reject(err);
        }
    });
}
github oddbit / tanam / src / app.ts View on Github external
// Fetch the name of the theme. Template files are located under the theme name in cloud storage
    const siteTheme = (await firebase.database().ref('site/settings/theme').once('value')).val() || 'default';

    // The data of the document contains meta data such as what template to use fo rendering etc
    const contentPost = firestoreDoc.data();

    // The content post has a corresponding template file in the theme folder. This makes it possible to display
    // 'blog' posts differently from 'event' posts etc
    const contentPostTemlateFile = firebase.storage().bucket().file(`/themes/${siteTheme}/${contentPost.template}.tmpl.html`);
    const contentPostTemplateHtml = (await contentPostTemlateFile.exists())
      ? (await contentPostTemlateFile.download())[0].toString('utf8')
      : '<div>This is default template for {{ title }}</div>';

    // The master template contains the header, footer and everything that wraps the content type
    const masterTemplateFile = firebase.storage().bucket().file(`/themes/${siteTheme}/master.tmpl.html`);
    const masterTemplateHtml = (await masterTemplateFile.exists())
      ? (await masterTemplateFile.download())[0].toString('utf8')
      : `
      

      
        
        <title>${firestoreDoc.id}</title>
        ${contentPostTemplateHtml}
      
    `;


    // Everything below here is just taken out of the example on VUE SSR documentation page
    // https://vuejs.org/v2/guide/ssr.html
    const app = new Vue.default({
github firebase / friendlypix-web / functions / cleanupAccount.js View on Github external
const checkPostComments = commentList.ref.orderByChild('author/uid').equalTo(deletedUid).once('value').then((snap) => {
        if (snap.exists()) {
          personalPaths[`/comments/${commentList.key}/${snap.key}`] = null;
        }
      });
      allPostsPromises.push(checkPostComments);
    });
    return Promise.all(allPostsPromises);
  });

  // Delete all personal Database path.
  const deleteDatabase = Promise.all([findPosts, findLikes, findComments])
      .then(() => admin.database().ref('/').update(personalPaths));

  // Delete all user's images stored in Storage.
  const deleteStorage = admin.storage().bucket().deleteFiles({prefix: `${deletedUid}/`});

  return Promise.all([deleteDatabase, deleteStorage]);
});
github oddbit / tanam / functions / src / triggers / storage.ts View on Github external
export const onUserImageUpload = functions.storage.object().onFinalize(async (storageObject) => {
  const regexNameMatch = storageObject.name.match(/^\/?tanam\/(.*)\/upload\//);
  if (!regexNameMatch) {
    console.log(`Not a user image upload task: ${storageObject.name} (${storageObject.contentType})`);
    return null;
  }

  if (!storageObject.contentType.startsWith('image/')) {
    console.log(`File is not an image: ${storageObject.name} (${storageObject.contentType})`);
    return null;
  }

  console.log(`Processing file: ${storageObject.name}`);
  const siteId = regexNameMatch[1];
  const bucket = admin.storage().bucket(storageObject.bucket);
  const [originalFileBuffer] = await bucket.file(storageObject.name).download();

  const resizeAndConvertImage = (size: number) =>
    sharp(originalFileBuffer)
      .resize(size, size, {
        withoutEnlargement: true,
        fit: sharp.fit.inside,
      })
      .toFormat(sharp.format.webp)
      .toBuffer();

  const originalSuffix = storageObject.name.lastIndexOf('.') > 0
    ? storageObject.name.substr(storageObject.name.lastIndexOf('.'))
    : '';

  const firestoreRef = admin.firestore()
github oddbit / tanam / functions / src / services / file.service.ts View on Github external
export async function getFileContents(storagePath: string) {
    console.log(`[getFileContents] ${JSON.stringify({ storagePath })}`);

    const contentFile = await admin.storage().bucket().file(storagePath);
    const [contentExists] = await contentFile.exists();
    if (!contentExists) {
        return null;
    }

    const [fileContent] = await contentFile.download();
    const bytesOfData = (fileContent.byteLength / 1024).toFixed(2);
    console.log(`[getFileContents] File '${storagePath}' size: ${bytesOfData} kB`);
    return fileContent;
}
github MobileTribe / panda-lab / functions / src / storage.ts View on Github external
appData['versionCode'] = manifest.versionCode;
        artifactData['versionCode'] = manifest.versionCode;
    }
    if (manifest.versionName) {
        appData['versionName'] = manifest.versionName;
        artifactData['versionName'] = manifest.versionName;
    }

    const doc = admin.firestore().collection("applications").doc(appName).collection("versions").doc(uuid);
    try {
        await admin.storage().bucket().file(fullPath).move(newPath);
        await doc.set(appData, {merge: true});
        await doc.collection('artifacts').doc(filename.replace('.apk', '')).set(artifactData, {merge: false});
    } catch (e) {
        console.warn("delete moved file in " + newPath);
        await admin.storage().bucket().file(newPath).delete()
    }
    return "ok"
}
github novoda / dashboards / server / src / index.js View on Github external
const functions = require('firebase-functions')
const admin = require('firebase-admin');
const http = require('request-promise-native')
const HtmlRepository = require('./html-repository')
const Scheduler = require('./scheduler/scheduler')
const cors = require('cors')({ origin: true });
const Actions = require('./actions')
admin.initializeApp()

const bucket = admin.storage().bucket()
const htmlRepository = new HtmlRepository(bucket)

const actions = new Actions(admin.database())

exports.onPluginInstanceWrite = functions.database.ref('/v2/plugin_instances/{pluginId}/{pluginInstanceId}/').onWrite((change, context) => {
    const payload = change.after.val()
    const pluginInstanceId = context.params.pluginInstanceId
    return actions.applyPluginInstanceName(pluginInstanceId, payload.name)
})

exports.onNewTopic = functions.database.ref('/v2/topics/{topicId}').onCreate((snapshot, context) => {
    const topicId = context.params.topicId
    return actions.applyInitialIndexToTopic(topicId)
})

exports.onPluginInstanceAddedToTopic = functions.database.ref('/v2/topics/{topicId}/plugin_instances/{instanceId}').onCreate((snapshot, context) => {
github phoqe / react-material-ui-firebase / functions / index.js View on Github external
const admin = require('firebase-admin');
const functions = require('firebase-functions');

admin.initializeApp();

const firestore = admin.firestore();
const storage = admin.storage();

exports.deleteAccount = functions.auth.user().onDelete((user) => {
  const uid = user.uid;

  if (!uid) {
    return null;
  }

  const deleteUser = firestore.collection('users').doc(uid).delete();
  const deleteAvatar = storage.bucket().deleteFiles({ prefix: `images/avatars/${uid}` });

  return Promise.all([ deleteUser, deleteAvatar ]);
});
github deckgo / deckdeckgo / cloud / functions / src / watch / delete / delete-user-storage.ts View on Github external
return new Promise(async (resolve, reject) =&gt; {
        try {
            if (!userId || userId === undefined || userId === '') {
                resolve();
                return;
            }

            const bucket = admin.storage().bucket();
            await bucket.deleteFiles({prefix: `${userId}/`});

            resolve();
        } catch (err) {
            reject(err);
        }
    });
}