{"size": 6075, "ext": "js", "max_stars_repo_path": "server/src/config/setup.js", "max_stars_repo_name": "heardofdezz/HYPERTUBE", "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "server/src/config/setup.js", "max_issues_repo_name": "heardofdezz/HYPERTUBE", "max_issues_repo_issues_event_min_datetime": "2021-09-02T12:02:46.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-07T10:17:59.000Z", "max_forks_repo_path": "server/src/config/setup.js", "max_forks_repo_name": "heardofdezz/Hypertube", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null}
{"max_stars_count": null, "max_issues_count": 2, "max_forks_count": null, "avg_line_length": 34.3220338983, "max_line_length": 169, "alphanum_fraction": 0.46781893}
const request = require('request');
const Movie = require('../models/Movie');
const { asyncForEach } = require('../functions/back');
const imdb = require('imdb-api');

const getImdbData = async (movie) => {
    return imdb.get(movie.imdb_code ? {id: movie.imdb_code} : {name: movie.title}, { apiKey: '28b91dfb' }).then((data) => {
        if (!data) {
            throw 'There is not imdbcode for ' + movie.title;
        }
        if (data.type !== 'movie') {
            throw 'The movie is not a movie';
        }
        movie.title = data.title;
        movie.director = data.director ? data.director : '';
        movie.writer = data.writer ? data.writer : '';
        movie.imdb_code = data.imdbid ? data.imdbid : movie.imdb_code;
        movie.year = data.year;
        movie.rating = data.rating;
        movie.actors = data.actors ? data.actors : '';
        movie.country = data.country ? data.country : '';
        movie.genres = data.genres ? data.genres.split(',') : [];
        movie.summary = data.plot ? data.plot : '';
        movie.cover = data.poster ? data.poster : '';
        movie.runtime = data.runtime ? data.runtime : '';

        return movie;
    })
        .then(async (movie) => {
            await movie.save();
            console.log('\x1b[32m', movie.provider.toUpperCase(), ': Movie added!' ,'\x1b[0m');
            return Promise.resolve();
        })
        .catch((e) => {
            return Promise.reject(e);
        });
}

const saveEztv = async (data) => {
    try {
        const imdb_code = 'tt' + data.imdb_id;
        const magnet = data.magnet_url;
        const seeds = data.seeds ? data.seeds: 0;

        if (!imdb_code || !magnet) {
            return;
        }
        const findMovie = await Movie.findOne({provider: 'eztv', imdb_code: imdb_code});
        if (!!findMovie) {
            if (findMovie.magnet.every((elem) => elem.magnet !== magnet)) {
                findMovie.magnet.push({
                    magnet,
                    seeds
                });
                await findMovie.save();
                console.log('\x1b[32m', 'EZTV: Magnet successfully added to the movie ', findMovie.title , '\x1b[0m')
            } else {
                console.log('\x1b[34m', 'EZTV: Movie already added.' , '\x1b[0m');
            }
        } else {
            const movie = new Movie ({
                provider: 'eztv',
                imdb_code,
                magnet: [{
                    magnet,
                    seeds
                }]
            });
            await getImdbData(movie);
        }
    } catch (e) {
        if (e.statusCode && e.statusCode === 401) {
            return Promise.reject('Free IMDB API quota limit reached');
        }
        console.error('\x1b[31m', 'EZTV Error: ', e, '\x1b[0m');
    }
}


const saveYts = async (data) => {
    if (!data.torrents) {
        return;
    }
    const findMovie = await Movie.findOne({provider: 'yts', imdb_code: data.imdb_code});
    if (!findMovie) {
        const movie = new Movie({
            provider: 'yts',
            imdb_code: data.imdb_code,
            title: data.title,
            torrent: data.torrents
        });
        try {
            await getImdbData(movie);
        } catch (e) {
            if (e.statusCode && e.statusCode === 401) {
                return Promise.reject('Free IMDB API quota limit reached');
            }
            console.error('\x1b[31m', 'YTS Error: ', e, '\x1b[0m');
        }
    } else {
        console.log('\x1b[34m', 'YTS: Movie already added.' , '\x1b[0m')
    }
}

const downloadMovieData = async(page, provider) => {
    const url = provider === 'yts' ? 'https://ytss.unblocked.is/api/v2/list_movies.json?limit=100&page=' : 'https://eztv1.unblocked.is/api/get-torrents?limit=100&page=';

    return request(url + page, async (err, res, body) => {
        try  {
        if (err || !res) {
            console.error(err ? err : 'No results in page ' + page);
        } else if (res.statusCode !== 200) {
            console.error('Request status ' + res.statusCode + ' for page ' + page);
        } else {
            try {
                body = JSON.parse(body);

                if (provider === 'yts' ? !body.data : !body.torrents) {
                    return Promise.reject();
                }

                const movies = provider === 'yts' ? body.data.movies : body.torrents;

                if (!movies) {
                    return Promise.resolve();
                }

                try {
                    await asyncForEach(movies, async(movie) => {
                        try {
                            if (provider === 'yts') {
                                await saveYts(movie);
                            } else {
                                await saveEztv(movie);
                            }
                        } catch(e) {
                            return Promise.reject(e);
                        }
                    });
                } catch (e) {
                    throw new Error(e);
                }

            } catch (e) {
                throw new Error(e);
            }
        }
        try {
            await downloadMovieData(page + 1, provider);
        } catch(e) {
            throw new Error(e);
        }
        } catch (e) {
            console.error('\x1b[31m', 'An error occured in provider ' + provider + ' :\n' + e, '\x1b[0m')
        }
    });
}

const importMovies = async() => {
    try {
        const providers = [ 'yts', 'eztv' ];

        providers.forEach((provider) => {
            downloadMovieData(1, provider).then(() => {
                console.log('\x1b[32m', provider + ' successfully set up !', '\x1b[0m');
            }).catch((e) => {
                console.error('\x1b[31m', 'An error occured in provider ' + provider + ' :\n' + e, '\x1b[0m');
            });
        });
        /*Movie.deleteMany({provider: 'eztv'}).then(() => console.log('ok')).catch((e) => console.log(e));*/
    } catch(e) {
        console.log(e);
    }
};

module.exports = importMovies;
