<commit_before>'use strict'

console.log('Loading function')

const _ = require('lodash')
const _h = require('./_helpers')
const async = require('async')
const aws = require('aws-sdk')
const crypto = require('crypto')
const fs = require('fs')
const path = require('path')


const sql = fs.readFileSync(path.resolve(__dirname, 'sql', 'get_entity_picture.sql'), 'utf8')

exports.handler = (event, context, callback) => {
    context.callbackWaitsForEmptyEventLoop = false

    const db = event.pathParameters.db
    const entityId = event.pathParameters.id

    var cookie
    var sessionKey
    var connection
    var userEmail

    try {
        cookie = _.get(event,'headers.cookie') || _.get(event,'headers.Cookie')
        sessionKey = cookie.split(';').map(x => x.trim()).filter(x => x.startsWith('session='))[0].substr(8)
    } catch (e) {
        return callback(null, _h.error([403, 'Forbidden']))
    }

    if (!sessionKey) {
        return callback(null, _h.error([403, 'Forbidden']))
    }

    async.waterfall([
        (callback) => {
            _h.db('entu', callback)
        },
        (mongoConn, callback) => {
            mongoConn.collection('session').findOne({ key: sessionKey }, { fields: { _id: false, 'user.email': true } }, callback)
        },
        (sess, callback) => {
            if(_.get(sess, 'user.email')) {
                callback(null, sess.user.email)
            } else {
                callback([403, 'Forbidden'])
            }
        },
        (email, callback) => {
            _h.mysqlDb(db).query(sql, [entityId, entityId, entityId, email], (err, data) => {
                if (err) { return callback(err) }
                callback(null, data[0])
            })
        },
        (file, callback) => {
            if(!file) {
                let md5 = crypto.createHash('md5').update(entityId).digest('hex')
                return callback(null, `https://secure.gravatar.com/avatar/${md5}?d=identicon&s=150`)
            }

            if(!file.s3) {
                let md5 = crypto.createHash('md5').update(file.id).digest('hex')
                let d = file.type === 'person' ? 'robohash' : 'identicon'
                return callback(null, `https://secure.gravatar.com/avatar/${md5}?d=${d}&s=150`)
            }

            let conf
            if (process.env.S3_ENDPOINT) {
                conf = { endpoint: process.env.S3_ENDPOINT, s3BucketEndpoint: true }
            }

            aws.config = new aws.Config()
            const s3 = new aws.S3(conf)
            s3.getSignedUrl('getObject', { Bucket: process.env.S3_BUCKET, Key: file.s3, Expires: 10 }, callback)
        },
    ], (err, url) => {<commit_msg>Log external IP; Show public entity picture;<commit_after>'use strict'

console.log('Loading function')

const _ = require('lodash')
const _h = require('./_helpers')
const async = require('async')
const aws = require('aws-sdk')
const crypto = require('crypto')
const fs = require('fs')
const https = require('https')
const path = require('path')


const sql = fs.readFileSync(path.resolve(__dirname, 'sql', 'get_entity_picture.sql'), 'utf8')

exports.handler = (event, context, callback) => {
    context.callbackWaitsForEmptyEventLoop = false

    try {
        https.get({ host: 'api.ipify.org' }, (response) => {
            var ip = ''

            response.on('data', (d) => {
                ip += d
            })

            response.on('end', () => {
                console.log('IP:', ip)
            })
        })
    } catch (e) {
        console.log('IP: error')
    }

    const db = event.pathParameters.db
    const entityId = event.pathParameters.id

    var cookie
    var sessionKey
    var connection
    var userEmail

    try {
        cookie = _.get(event,'headers.cookie') || _.get(event,'headers.Cookie')
        sessionKey = cookie.split(';').map(x => x.trim()).filter(x => x.startsWith('session='))[0].substr(8)
    } catch (e) {
        // No session cookie
    }

    async.waterfall([
        (callback) => {
            _h.db('entu', callback)
        },
        (mongoConn, callback) => {
            if (sessionKey) {
                mongoConn.collection('session').findOne({ key: sessionKey }, { fields: { _id: false, 'user.email': true } }, callback)
            } else {
                callback(null, null)
            }
        },
        (sess, callback) => {
            _h.mysqlDb(db).query(sql, [entityId, entityId, entityId, _.get(sess, 'user.email', '__PUBLIC__')], (err, data) => {
                if (err) { return callback(err) }
                callback(null, data[0])
            })
        },
        (file, callback) => {
            if(!file) {
                let md5 = crypto.createHash('md5').update(entityId).digest('hex')
                return callback(null, `https://secure.gravatar.com/avatar/${md5}?d=identicon&s=150`)
            }

            if(!file.s3) {
                let md5 = crypto.createHash('md5').update(file.id).digest('hex')
                let d = file.type === 'person' ? 'robohash' : 'identicon'
                return callback(null, `https://secure.gravatar.com/avatar/${md5}?d=${d}&s=150`)
            }

            let conf
            if (process.env.S3_ENDPOINT) {
                conf = { endpoint: process.env.S3_ENDPOINT, s3BucketEndpoint: true }
            }

            aws.config = new aws.Config()
            const s3 = new aws.S3(conf)
            s3.getSignedUrl('getObject', { Bucket: process.env.S3_BUCKET, Key: file.s3, Expires: 10 }, callback)
        },
    ], (err, url) => {
{'fraction_non_alphanumeric': 0.16180705543556514, 'fraction_numerical': 0.011339092872570195, 'mean_word_length': 2.058337919647771, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 25, 'https://': 4, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '3928172', 'n_tokens_mistral': 1746, 'n_tokens_neox': 1691, 'n_words': 332}