front/modules/chartmetric/index.js

/* ============================================================================ *\
|| ########################################################################## ||
|| # Auction Software Marketplace          Release: 0.6   Build 0.7         # ||
|| # ---------------------------------------------------------------------- # ||
|| # License # 35YAHCNR9344X6O666C123AB                                     # ||
|| # ---------------------------------------------------------------------- # ||
|| # Copyright ©2014–2021 Develop Scripts LLC. All Rights Reserved          # ||
|| # This file may not be redistributed in whole or significant part.       # ||
|| # ------------- AUCTION SOFTWARE IS NOT FREE SOFTWARE ------------------ # ||
|| # http://www.auctionsoftwaremarketplace.com|support@auctionsoftware.com  # ||
|| # ---------------------------------------------------------------------- # ||
|| ########################################################################## ||
\* ============================================================================ */

const { default: axios } = require('axios')
const dateFormat = require('dateformat')
const mysqclass = require('../mysqli').default

let chartmetric = {}
if (require('config').has('Chartmetric')) {
    chartmetric = require('config').get('Chartmetric')
}

global.chartmetric = { ...chartmetric, token: '' }

/**
 * @class class to handle deposit functions
 */
class Chartmetric {
    constructor(config = chartmetric) {
        /* eslint new-cap: ["error", { "properties": false }] */
        this.baseUrl = config.base_url
        this.secret = ''
        this.header = {
            headers: { Authorization: `Bearer ${this.secret}`, 'Content-Type': 'application/json' },
        }
    }

    init(callback) {
        callback.bind(this)
    }
    /**
     * insert log
     *
     * @param {string} nameID email ID to check in the database.
     * @returns {object} sql response
     */
    async insertLog(data, options, type) {
        const mysql = {}
        const escapeData = [
            data.user_id,
            data.project_id,
            type,
            JSON.stringify(options.data),
            dateFormat(new Date(), 'yyyy-mm-dd HH:MM:ss'),
        ]
        const strQuery = await mysqclass.mysqli(mysql, 'chartmetric_log_insert')
        const dataReturn = await global.mysql.query(strQuery, escapeData)
        return dataReturn
    }
    /**
     * update log
     *
     * @param {string} data log data
     * @returns {object} sql response
     */
    async updateLog(data) {
        const mysql = {}
        const escapeData = [
            JSON.stringify(data.response),
            data.status,
            dateFormat(new Date(), 'yyyy-mm-dd HH:MM:ss'),
            data.id,
        ]
        const strQuery = await mysqclass.mysqli(mysql, 'chartmetric_log_update')
        const dataReturn = await global.mysql.query(strQuery, escapeData)
        return dataReturn
    }
    /**
     * get token
     *
     * @param {object} payload token
     * @returns {string} token or null
     */
    async getToken(payload = { refreshtoken: chartmetric.refreshtoken }, config = {}) {
        // if (global.chartmetric.token === '') {
        //     global.chartmetric.token = ''
        const res = await this.send('/api/token', payload, config)
        //     global.chartmetric.token = res.token
        // }
        if (res) {
            axios.defaults.headers.common.Authorization = `Bearer ${res.token}`
            this.header = {
                headers: {
                    Authorization: `Bearer ${res.token}`,
                    'Content-Type': 'application/json',
                },
            }
            return res.token // global.chartmetric.token
        }
        return null
    }

    // get all chartmetric info based on track id
    /**
     * get track chart metric
     *
     * @param {object} payload token
     * @returns {object} response object
     */
    async getTrackChartMetric(
        payload = { track_id: '', platform: '', otherData: '' },
        config = {},
    ) {
        const res = await this.send(
            `/api/track/${payload.track_id}/${payload.platform}/stats${payload.otherData}`,
            {},
            config,
            'get',
        )
        return res && res.obj ? res.obj : []
    }
    /**
     * get track info
     *
     * @param {object} payload token
     * @returns {object} response object
     */
    async getTrackInfo(payload = { track_id: '', platform: '', otherData: '' }, config = {}) {
        return this.send(`/api/track/${payload.track_id}/`, {}, config, 'get')
    }
    /**
     * get all chartmetric info based on track id
     *
     * @param {object} payload token
     * @returns {object} response object
     */
    async getAlbumsChartMetric(payload = { album_id: '' }, config = {}) {
        return this.send(`/api/album/${payload.album_id}/chartmetric/charts`, {}, config, 'get')
    }
    /**
     * get all chartmetric info based on track id
     *
     * @param {object} payload token
     * @returns {object} response object
     */
    async getArtist(payload = { artist_id: '' }, config = {}) {
        const res = await this.send(`/api/artist/${payload.artist_id}`, {}, config, 'get')
        return res && res.obj ? res.obj : null
    }
    /**
     * get all chartmetric info based on track id
     *
     * @param {object} payload token
     * @returns {object} response object
     */
    async getArtistChartMetric(
        payload = { artist_id: '', platform: '', otherData: '' },
        config = {},
    ) {
        const res = await this.send(
            `/api/artist/${payload.artist_id}/stat/${payload.platform}${payload.otherData}`,
            {},
            config,
            'get',
        )
        return res && res.obj ? res.obj : []
    }

    /**
     * get all chartmetric info based on track id
     *
     * @param {object} payload token
     * @returns {object} response object
     */
    async getChartMetricStats(payload = { album_id: '' }, config = {}) {
        return this.send(`/api/album/${payload.album_id}/spotify/followers`, {}, config, 'get')
    }
    /**
     * get all chartmetric info based on query
     *
     * @param {object} payload token
     * @returns {object} response object
     */
    async searchTrack(payload = { q: '', limit }, config = {}) {
        return this.send(`/api/search?limit=${payload.limit}&q=${payload.q}`, {}, config, get)
    }
    /**
     * api call to handle all chartmetric third party apis
     * @param {string} url url
     * @param {object} payload payload
     * @param {object} config config
     * @param {string} method method
     * @param {object} payload token
     * @returns {object} response object
     */
    async send(url, payload, config = {}, method = 'post') {
        const configs = { ...this.header, ...config }
        const uri = this.baseUrl + url
        // Add log
        const [log] = await Promise.all([
            this.insertLog(
                { project_id: 0, user_id: 0 },
                {
                    payload,
                    configs,
                    uri,
                    method,
                },
                url,
            ),
        ])
        const responseUpdate = {
            id: log.insertId,
        }

        return new Promise((reslove) => {
            if (method === 'post')
                axios
                    .post(uri, payload, configs)
                    .then(({ status, data }) => {
                        // console.log(data)
                        this.updateLog({
                            ...responseUpdate,
                            status,
                            response: data,
                        })
                        if (status === 201 || status === 200) reslove(data)
                        else reslove(null)
                    })
                    .catch((error) => {
                        this.updateLog({
                            ...responseUpdate,
                            status: '401',
                            response: error.message,
                        })
                        reslove(null)
                    })
            else
                axios
                    .get(uri, payload, configs)
                    .then(({ status, data }) => {
                        this.updateLog({
                            ...responseUpdate,
                            status,
                            response: data,
                        })
                        if (status === 201 || status === 200) reslove(data)
                        else reslove(null)
                    })
                    .catch((error) => {
                        this.updateLog({
                            ...responseUpdate,
                            status: '401',
                            response: error.message,
                        })
                        reslove(null)
                    })
        })
    }
}

module.exports.default = Chartmetric