var VideoRetriever = function() { var yt = google.youtube('v3'); this.retrieve = function(song, query) { return new Promise(function(resolve,reject) { yt.search.list({ part: "snippet", maxResults: "3", q: song.title + " " + song.author + " " + query, type: "video", key: process.env.GOOGLE_API_KEY }, function(err,data) { if(err) { reject(err); } else { var ids = data.items.map(function(item) { return item.id.videoId; }); /*.map(function(id) { return "https://youtube.com/watch?v=" + id; });*/ if(!song.videos) { song.videos = {}; } song.videos[query] = ids; resolve(song); } }); }); }; };
return new Promise(function(resolve, reject) { var youtube = google.youtube({version: 'v3', auth: ytKey.apikey}); youtube.videos.list({ part: 'id,snippet', id: [args.showID], }, function(err, result) { if (err) { console.error('Error when using the YouTube API'); console.error(err); return; } if (!result.items || result.items.length === 0) { reject('Unable to get the YouTube data for "' + args.showID + '"'); return; } if (result.items.length > 1) { reject('Received more than one result for video ID: "' + args.showID + '"'); return; } var videoDetails = result.items[0]; var showDetails = createShowObject(videoDetails); args.shows = [showDetails]; resolve(args); }); });
return new Promise(function(resolve, reject) { var youtube = google.youtube({version: 'v3', auth: ytKey.apikey}); youtube.playlistItems.list({ part: 'id,snippet', playlistId: args.playlistID, maxResults: 50 }, function(err, result) { if (err) { reject('A problem occured fetching playlist with the YouTube API', err); return; } if (!result.items || result.items.length === 0) { reject('No videos founds for playlist Id "' + args.playlistID + '"', err); return; } args.shows = []; for (var i = 0; i < result.items.length; i++) { var videoDetails = result.items[i]; var showDetails = createShowObject(videoDetails); args.shows.push(showDetails); } resolve(args); }); });
function uploadToYoutube(video_file, title, description,tokens, callback){ var google = require("googleapis"), yt = google.youtube('v3'); var oauth2Client = new google.auth.OAuth2("710857957569-cjc5k4m5d7nsqt73dpi16a9aab7aqo7f.apps.googleusercontent.com", "3pqlkqT0QhTJsy3LMlv4x3G1", '/'); oauth2Client.setCredentials(tokens); google.options({auth: oauth2Client}); return yt.videos.insert({ part: 'status,snippet', resource: { snippet: { title: title, description: description }, status: { privacyStatus: 'private' //if you want the video to be private } }, media: { body: fs.createReadStream(video_file) } }, function(error, data){ if(error){ callback(error, null); } else { callback(null, data.id); } }); };
(function () { var config = {}; /** * authenticate * Sets an authentication method to have access to protected resources. * * @name authenticate * @function * @param {Object} options An object containing the authentication information. * @return {Object} The authentication object */ this.authenticate = function (options) { if (!options) { config.auth = undefined; return; } var authObj = null; switch (options.type) { case "oauth": authObj = new Google.auth.OAuth2(options.client_id, options.client_secret, options.redirect_url); authObj.setCredentials({ access_token: options.access_token || options.token, refresh_token: options.refresh_token }); break; case "key": authObj = options.key; break; } Google.options({ auth: authObj }); config.auth = options; return authObj; }; /** * getConfig * Returns Client configuration object * * @name getConfig * @function * @return {Object} Client configuration object */ this.getConfig = function () { return config; }; // Add Google YouTube API functions var GoogleYoutube = Google.youtube("v3"); for (var f in GoogleYoutube) { this[f] = GoogleYoutube[f]; } }).call(Client);
oauth2Client.getToken(code, function(err, tokens) { if (err) { console.log(err); res.send(err); return; } // console.log(tokens); // EJEMPLO DE OBTENER LOS DATOS DE GOOGLE + DEL USUARIO QUE HA HECHO LOGIN. oauth2Client.setCredentials(tokens); googleapis.options({ auth: oauth2Client }); plus.people.get({ userId: 'me', auth: oauth2Client }, function(err, response) { if (err) { console.log(err); res.send(err); return; } console.log(" ------------- Detalles de usuario ---------------"); console.log("id: " + response.id); console.log("Name: " + response.displayName); console.log("Image url: " + response.image.url); }); // EJEMPLO DE BÚSQUEDA DE UN VIDEO EN YOUTUBE. var youtube = googleapis.youtube({ version: 'v3', auth: oauth2Client }); youtube.search.list({ part: 'snippet', q: 'rubius', maxResults: 1 }, function(err, response) { console.log("----------- Test buscar video ------------"); if (err) { console.log(err); res.send(err); return; } console.log(response.items); }); res.send("check node console for access tokens and personal information"); });
Youtube.prototype.updateYtApiAccessToken = function () { var self = this; var oauth2Client = new OAuth2Client( secrets.volumio.client_id, secrets.volumio.client_secret, secrets.volumio.redirect_uris[0] ); oauth2Client.setCredentials(self.accessToken); self.yt = gapis.youtube({ version: 'v3', auth: oauth2Client }); }
function Youtube(context) { var self = this; self.context = context; self.commandRouter = self.context.coreCommand; self.logger = self.context.logger; self.configManager = self.context.configManager; self.addQueue = []; self.state = {}; self.stateMachine = self.commandRouter.stateMachine; self.yt = gapis.youtube({ version: 'v3', auth: ytapi_key }); }
export const createLiveStream = async({ room, access_token, refresh_token, clientId, clientSecret, }) => { const auth = new OAuth2(clientId, clientSecret); auth.setCredentials({ access_token, refresh_token, }); const youtube = google.youtube({ version:'v3', auth }); const [stream, broadcast] = await Promise.all([p((resolve) => youtube.liveStreams.insert({ part: 'id,snippet,cdn,contentDetails,status', resource: { snippet: { title: room.name || 'RocketChat Broadcast', }, cdn: { format: '480p', ingestionType: 'rtmp', }, }, }, resolve)), p((resolve) => youtube.liveBroadcasts.insert({ part: 'id,snippet,contentDetails,status', resource: { snippet: { title: room.name || 'RocketChat Broadcast', scheduledStartTime : new Date().toISOString(), }, status: { privacyStatus: 'unlisted', }, }, }, resolve))]); await p((resolve) => youtube.liveBroadcasts.bind({ part: 'id,snippet,status', // resource: { id: broadcast.id, streamId: stream.id, }, resolve)); return { id: stream.cdn.ingestionInfo.streamName, stream, broadcast }; };
authenticate: function() { var CREDENTIALS = {}; var readFile = fs.readFileSync('./config.json'); if (readFile) { CREDENTIALS = JSON.parse(readFile); } if (!CREDENTIALS.API_KEY) { console.log("Please, set your API Key on auth.js"); console.log("You can generate it here:"); console.log("https://console.developers.google.com/apis (YouTube Data API)"); return false; } return google.youtube({ version: 'v3', auth: CREDENTIALS.API_KEY }); }
export const getBroadcastStatus = async({ id, access_token, refresh_token, clientId, clientSecret, }) => { const auth = new OAuth2(clientId, clientSecret); auth.setCredentials({ access_token, refresh_token, }); const youtube = google.youtube({ version:'v3', auth }); const result = await p((resolve) => youtube.liveBroadcasts.list({ part:'id,status', id, }, resolve)); return result.items && result.items[0] && result.items[0].status.lifeCycleStatus; };
upload: function(videoId, info, token, callback) { var google = require("googleapis"); var yt = google.youtube('v3'); var oauth2Client = new google.auth.OAuth2(config.oath.client_id, config.oath.app_secret, config.oath.redirect_url); oauth2Client.setCredentials({ access_token: token.access_token, refresh_token: token.refresh_token }); google.options({auth: oauth2Client}); console.log('start uploading...') yt.videos.insert({ part: 'status,snippet', resource: { snippet: { title: info.title, description: info.description }, status: { // privacyStatus: 'public' //if you want the video to be private }, tags: info.tags, category: info.category }, media: { body: fs.createReadStream('assets/video/edited/'+ videoId +'.flv') } }, function(error, data){ if(error){ console.log(error) callback(error, null); } else { callback(null, data); } }); },
export function ytImFeelingLucky(orcabot, message, searchTerm) { const googleAPIKey = keys.googleAPIKey; const youtube = google.youtube('v3'); return new Promise((resolve, reject) => { // YouTube API search request youtube.search.list({ auth: googleAPIKey, part: 'snippet', q: searchTerm, }, (error, searchList) => { if (!error) { if (!searchList.pageInfo.totalResults) { // no results from query orcabot.reply(message, 'No results found!'); } else { // top search result = searchList.items[0] const { items: [{ id: { videoId: videoID } }] } = searchList; // get video info youtube.videos.list({ auth: googleAPIKey, part: 'snippet, contentDetails, status, statistics', id: videoID, }, err => { if (!err) { const url = `https://youtu.be/${videoID}`; resolve(url); } else { console.error(`TT YOUTUBE GET VIDEO INFO -- ${err}`); orcabot.reply(message, err); reject(err); } }); } } else { console.error(`TT YOUTUBE SEARCH -- ${error}`); } }); }); }
module.exports = function youtube() { const client = googleapis.youtube({ version: "v3", auth: youtubeCredentials.key, }) function search(q, callback) { client.search.list({ part: "id", q, }, function (err, {items}){ if(err) { return callback(err) } console.log(items) callback(null, items.filter(item => item.id.kind === "youtube#video").map(item => item.id.videoId)) }) } function download(id, filePath, callback) { ytdl(`http://www.youtube.com/watch?v=${id}`, { filter: mp4Filter, }) .on("error", function(err) { fs.unlink(filePath) callback(err) }) .on("finish", function() { console.log("finish") callback() }) .pipe(fs.createWriteStream(filePath)) } return { search, download, } }
export const setBroadcastStatus = ({ id, access_token, refresh_token, clientId, clientSecret, status, }) => { const auth = new OAuth2(clientId, clientSecret); auth.setCredentials({ access_token, refresh_token, }); const youtube = google.youtube({ version:'v3', auth }); return p((resolve) => youtube.liveBroadcasts.transition({ part:'id,status', id, broadcastStatus: status, }, resolve)); };
var request = require('request-promise'); var cheerio = require('cheerio'); var google = require('googleapis'); var Q = require('q'); var youtube = google.youtube({ version: 'v3', auth : 'AIzaSyDwKeuaiYTFhgDQYkQRl8UCCDoK64tzahs' }); module.exports = function() { return { arrPosts: [], arrPostsVideos: [], currentPage: 0, storePosts: function( $ ) { var posts = $( '.ttl4reg' ); var self = this; var postData; posts.filter(function(i, item) { var postReplaced = item.attribs.title.replace(/_/g, " "); postReplaced = postReplaced.split( '-(' )[ 0 ]; postData = { title: postReplaced, download: item.attribs.href };
const goog = require('googleapis'); const yt = goog.youtube({ version: 'v3' }); const moment = require('moment'); let apiKey = ''; module.exports.init = function (b) { b.getConfig('google.json', (err, conf) => { if (!err) { apiKey = conf.apiKey; } }); }; const ytRegex = /(?:youtube\.com\/(?:[^/]+\/.+\/|(?:v|e(?:mbed)?)\/|.*[?&]v=)|youtu\.be\/)([^"&?/ ]{11})/i; function formatPt50(pt50) { const duration = moment.duration(pt50); let hours = duration.hours(); let minutes = duration.minutes(); let seconds = duration.seconds(); if (hours < 10) { hours = `0${hours}`; } if (minutes < 10) { minutes = `0${minutes}`; } if (seconds < 10) { seconds = `0${seconds}`; } const time = `${hours}:${minutes}:${seconds}`; return time; } function likePercent(vid) { try {
googleAccessToken, googleRefreshToken, googleTokenType, googleExpiryDate, googleClientId, googleClientSecret, googleCallback, } = config; const OAuth2 = google.auth.OAuth2; export const oauth2Client = new OAuth2( googleClientId, googleClientSecret, googleCallback, ); oauth2Client.setCredentials({ access_token: googleAccessToken, token_type: googleTokenType, expiry_date: googleExpiryDate, refresh_token: googleRefreshToken, }); const youtube = google.youtube({ auth: oauth2Client, version: 'v3', }); export default youtube;
// Require Node Modules var http = require('http'), express = require('express'), bodyParser = require('body-parser'), Parse = require('parse/node'), ParseCloud = require('parse-cloud-express'); var google = require('googleapis'); var youtubedl = require('youtube-dl'); var Promise = require("node-promise").Promise; var when = require("node-promise").when; var youtube_api_key = 'AIzaSyCM3E6ir_giadOaPa_5REQAwXRcfcjvuk8'; var youtube = google.youtube({ version: 'v3', auth: youtube_api_key }); var youtube_video_url_prefix = 'https://www.youtube.com/watch?v='; var app = express(); // console.log("Sighhhh"); // var channels = [] // Import your cloud code (which configures the routes) require('./cloud/main.js'); // Mount the webhooks app to a specific path (must match what is used in scripts/register-webhooks.js) app.use('/webhooks', ParseCloud.app); // Host static files from public/ app.use(express.static(__dirname + '/public')); // Catch all unknown routes.
'use strict'; var rootHandler = require('./rootHandler'), server = require('../server'), config = require('config'), googleapis = require('googleapis'), log = require('loglevel'), Q = require('q'); var youtube = googleapis.youtube({version: 'v3', auth: config.youtube.apiKey}), getVideoData = Q.denodeify(youtube.videos.list); function getReformattedVideoData(videoData) { return { id: videoData.id, duration: videoData.contentDetails.duration, title: videoData.snippet.title, thumbnails: videoData.snippet.thumbnails }; } function createMessage(response) { var defer = Q.defer(); var videoData = response[0].items[0]; var video = getReformattedVideoData(videoData); var message = JSON.stringify({ type: 'video', body: {video: video} });
function buildFeeds(buildType, callback) { var apiKey; try { apiKey = process.env.YOUTUBE_API_KEY; if (!apiKey) { apiKey = fs.readFileSync('./src/data/youtubeAPIKey.txt', 'utf8'); } } catch (ex) { gutil.log(' ', 'YouTube feed build skipped, youtubeAPIKey.txt not found.'); if (buildType === 'production') { return callback('youtubeAPIKey.txt not found.'); } var videoPlaceholder = {snippet: {title: 'Lorem Ipsum - placeholder title', resourceId: {videoId: 'dQw4w9WgXcQ'}} }; var context = { videos: [videoPlaceholder, videoPlaceholder, videoPlaceholder, videoPlaceholder] }; var template = path.join(GLOBAL.WF.src.templates, 'shows', 'index.md'); var outputFile = path.join(GLOBAL.WF.src.content, 'shows', 'index.md'); wfTemplateHelper.renderTemplate(template, context, outputFile); callback(); return; } var youtube = google.youtube({version: 'v3', auth: apiKey}); var opts = { maxResults: 25, part: 'id,snippet', playlistId: 'UUnUYZLuoy1rq1aVMwx4aTzw', }; youtube.playlistItems.list(opts, function(err, response) { if (err) { gutil.log(' ', 'Error, unable to retreive playlist', err); callback(err); } else { var articles = []; response.items.forEach(function(video) { var iframe = '<iframe width="560" height="315" '; iframe += 'src="https://www.youtube.com/embed/'; iframe += video.snippet.resourceId.videoId + '" frameborder="0" '; iframe += 'allowfullscreen></iframe>\n<br>\n<br>'; var content = video.snippet.description.replace(/\n/g, '<br>\n'); content = iframe + content; var result = { url: video.snippet.resourceId.videoId, title: video.snippet.title, description: video.snippet.description, image: video.snippet.thumbnails.default, datePublished: video.snippet.publishedAt, dateUpdated: video.snippet.publishedAt, tags: [], analyticsUrl: '/web/videos/' + video.snippet.resourceId.videoId, content: content, atomAuthor: 'Google Developers', rssPubDate: moment(video.snippet.publishedAt).format('DD MMM YYYY HH:mm:ss [GMT]') }; articles.push(result); var shortDesc = video.snippet.description.replace(/\n/g, '<br>'); if (shortDesc.length > 256) { shortDesc = shortDesc.substring(0, 254) + '...'; } video.shortDesc = shortDesc; }); var context = { videos: response.items }; var template = path.join(GLOBAL.WF.src.templates, 'shows', 'index.md'); var outputFile = path.join(GLOBAL.WF.src.content, 'shows', 'index.md'); wfTemplateHelper.renderTemplate(template, context, outputFile); var context = { video: response.items[0] }; template = path.join(GLOBAL.WF.src.templates, 'shows', 'latest.html'); outputFile = path.join(GLOBAL.WF.src.content, '_shared', 'latest_show.html'); wfTemplateHelper.renderTemplate(template, context, outputFile); context = { title: 'Web Shows - Google Developers', description: 'YouTube videos from the Google Chrome Developers team', feedRoot: 'https://developers.google.com/web/shows/', host: 'https://youtu.be/', baseUrl: 'https://youtube.com/user/ChromeDevelopers/', analyticsQS: '', atomPubDate: moment().format('YYYY-MM-DDTHH:mm:ss[Z]'), rssPubDate: moment().format('ddd, DD MMM YYYY HH:mm:ss ZZ'), articles: articles }; template = path.join(GLOBAL.WF.src.templates, 'atom.xml'); outputFile = path.join(GLOBAL.WF.src.content, 'shows', 'atom.xml'); wfTemplateHelper.renderTemplate(template, context, outputFile); template = path.join(GLOBAL.WF.src.templates, 'rss.xml'); outputFile = path.join(GLOBAL.WF.src.content, 'shows', 'rss.xml'); wfTemplateHelper.renderTemplate(template, context, outputFile); callback(); } }); }
/* * This component provides a promise-based API to YouTube. * It takes care of authentication and exports two api objects: * * user: Will be authenticated via oauth and allows retrieval of stuff like the users subscriptions * system: Is authenticated via api key and allows general api access * * To allow oauth authentication a `/oauth` route is exported. If the `autenticated()` method returns false, * and the `user` api should be used, you have to redirect the user to this route so he may authorize our application. */ export default async function youtube(app, config) { await app.middleware; let koa = await app.webserver; let auth = new google.auth.OAuth2(config.oauth.id, config.oauth.secret, 'http://localhost:8000/oauth'); /* Set the refresh token on the auth object */ function setToken(token) { auth.setCredentials({ refresh_token: token }); } /* Save the token back to disk */ async function saveToken(token) { await promise(cb => fs.writeFile(config.token, token, 'utf8', cb)); } /* Check if we currently have a token */ function hasToken() { return !!auth.credentials.refresh_token; } /* Invalidate the current refresh token */ function invalidateToken() { auth.setCredentials({}); } /* Try to load the token from disk */ try { let token = await promise(cb => fs.readFile(config.token, 'utf8', cb)); setToken(token.trim()); } catch(e) { invalidateToken(); } /* Register oauth route */ koa.use($.get('/oauth', async (ctx) => { if(ctx.query.error) { /* We had an authorization error */ invalidateToken(); app.logger.warn(`Failed to authenticate: ${ctx.query.error}`); throw new UserError('Failed to authenticate your youtube account'); } else if(ctx.query.code) { /* If we have a token, try to add it to authenticator */ let code = ctx.query.code; try { let tokens = await promise(cb => auth.getToken(code, cb)); await saveToken(tokens.refresh_token); setToken(tokens.refresh_token); app.logger.info('Retrieved OAuth2 access and refresh tokens.'); } catch(e) { invalidateToken(); app.logger.warn(`Failed to retrieve OAuth2 tokens: ${e}`); throw new UserError('Failed to authenticate your youtube account'); } } else { /* If we still need a token, redirect the user */ return ctx.redirect(auth.generateAuthUrl({ access_type: 'offline', prompt: 'consent', scope: 'https://www.googleapis.com/auth/youtube.readonly', state: ctx.headers.referer || '/' })); } /* Try to redirect to where we came from if possible */ if(ctx.query.state) { return ctx.redirect(ctx.query.state); } else { return ctx.redirect('/'); } })); /* Handle authentication errors properly */ let api = wrap(google.youtube({ version: 'v3', auth }), e => { if(!hasToken() || e.message === 'invalid_grant') { /* Invalidate the token immediately */ invalidateToken(); /* Throw a user error so we can display something to the user */ let ue = new UserError('Failed to authenticate with YouTube'); ue.original = e; throw ue; } else { /* Catch it downstream */ app.logger.warn(`API Error: ${e.message}`); throw e; } }); return { user: api, system: wrap(google.youtube({ version: 'v3', auth: config.key})), authenticated: hasToken }; }
'use strict'; var Google = require('googleapis'); var youtube_client = Google.youtube('v3'); var oauth2Client = (() => { var OAuth2 = Google.auth.OAuth2; var oauth2Client = new OAuth2( process.env.GOOGLE_API_CLIENT_ID, process.env.GOOGLE_API_CLIENT_SECRET, process.env.GOOGLE_API_REDIRECT_URL ); oauth2Client.setCredentials({ access_token: process.env.GOOGLE_API_ACCESS_TOKEN, refresh_token: process.env.GOOGLE_API_REFRESH_TOKEN, }); return oauth2Client; })(); module.exports = class Youtube { constructor(callback){ oauth2Client.refreshAccessToken((err, tokens) => { oauth2Client.setCredentials(tokens); callback(err); }); } search(keyword, callback){ var param = { auth: oauth2Client,
var Youtube = function () { this.api = google.youtube({ version: 'v3', auth: config.apiKey }); }
const fs = require('fs') const path = require('path') const mime = require('mime') const merge = require('merge') const parseUrl = require('url').parse const google = require('googleapis') const Nightmare = require('nightmare') const NightmareGoogle = require('nightmare-google-oauth2') const version = require('./package.json').version const youtube = google.youtube('v3') const OAuth2Client = google.auth.OAuth2 const REDIRECT_URL = 'http://localhost:8488' const CREDENTIALS_FILENAME = '.google-oauth2-credentials.json' const SCOPE = [ 'https://www.googleapis.com/auth/youtube', 'https://www.googleapis.com/auth/youtube.upload' ].join(' ') exports = module.exports = function (opts) { return new YoutubeVideo(opts) } exports.google = google exports.youtube = youtube exports.VERSION = version function YoutubeVideo (opts) { this._authenticated = false
var OAuth2 = google.auth.OAuth2; var oauth2Client = new OAuth2(CLIENT_ID, CLIENT_SECRET, REDIRECT_URL); var scopes = [ 'https://www.googleapis.com/auth/youtube', 'https://www.googleapis.com/auth/youtube.readonly', 'https://www.googleapis.com/auth/yt-analytics-monetary.readonly', 'https://www.googleapis.com/auth/yt-analytics.readonly' ]; var url = oauth2Client.generateAuthUrl({ access_type: 'offline', // 'online' (default) or 'offline' (gets refresh_token) scope: scopes // If you only need one scope you can pass it as string }); var youtube = google.youtube('v3'); describe('GET /api/testYoutubes', function() { it('should respond with JSON array', function(done) { request(app) .get('/api/testYoutubes') .expect(200) .expect('Content-Type', /json/) .end(function(err, res) { if (err) return done(err); res.body.should.be.instanceof(Array); done(); }); });
var goog = require('googleapis'); var OAuth2 = goog.auth.OAuth2; var yt = goog.youtube({version: 'v3'}); var moment = require('moment'); var apiKey = ""; module.exports.init = function(b) { b.getConfig("google.json", function(err, conf) { if(!err) { apiKey = conf.apiKey; } }); }; var ytRegex = /(?:youtube\.com\/(?:[^\/]+\/.+\/|(?:v|e(?:mbed)?)\/|.*[?&]v=)|youtu\.be\/)([^"&?\/ ]{11})/i; function formatPt50(pt50) { var duration = moment.duration(pt50); var hours = duration.hours(); var minutes = duration.minutes(); var seconds = duration.seconds(); if (hours < 10) {hours = "0"+hours;} if (minutes < 10) {minutes = "0"+minutes;} if (seconds < 10) {seconds = "0"+seconds;} var time = hours+':'+minutes+':'+seconds; return time; } function likePercent(vid) { try {
function Ysm(opt) { // optional params opt = opt || {}; // private data var youtube = google.youtube('v3'); var subscriptions = []; // API/data for end-user return { setAuthClient: function setAuthClient(accessToken, refreshToken) { var OAuth2 = google.auth.OAuth2; var googleAuth = configAuth.googleAuth; var oauth2Client = new OAuth2( googleAuth.clientID, googleAuth.clientSecret, googleAuth.callbackURL); oauth2Client.setCredentials({ access_token: accessToken, refresh_token: refreshToken }); google.options({auth: oauth2Client}); }, requestUserSubscriptions: function requestUserSubscriptions(done, pageToken) { var requestOptions = { mine: true, part: 'id,snippet,contentDetails', maxResults: 10, order: "alphabetical" }; if (pageToken) { requestOptions.pageToken = pageToken; } else { subscriptions = []; } youtube.subscriptions.list(requestOptions, function(err, response) { if (err) { done(err, null); } else { subscriptions = subscriptions.concat(response.items); var nextPageToken = response.nextPageToken; if (nextPageToken) { requestUserSubscriptions(done, nextPageToken); } else { done(null, subscriptions); } } }); }, getSubscriptions: function getSubscriptions(done) { this.requestUserSubscriptions(done); }, getVideos: function getVideos(channelId, videoCount, done) { var requestOptions = { id: channelId, part: 'contentDetails' }; youtube.channels.list(requestOptions, function(err, response) { if (err) { done(err, null); } else { var uploadsPlaylistId = response.items[0].contentDetails.relatedPlaylists.uploads; requestOptions = { playlistId: uploadsPlaylistId, part: 'snippet', maxResults: videoCount }; youtube.playlistItems.list(requestOptions, function(err, response) { if (err) { done(err, null); } else { done(null, response.items); } }); } }); } } }
var config = require("./config/config.js"); var Discord = require("discord.js"); var fs = require("fs"); var Datastore = require("nedb"); var google = require("googleapis"); var request = require('request'); var youtube = google.youtube("v3"); var utilities = require("./johnbot-utilities.js"); var overwatchStats = require("./stats"); var quote = require("./quote"); var db = new Datastore({filename:"synctube.db"}); db.loadDatabase(); var mybot = new Discord.Client(); var text = null; var voice = null; var quiet = true; var fileUploadOverload = false; var insensitiveWords = []; var admins = []; var googleapikey = ""; //var regex = 'count\S,([a-z\s0-9,]*)'; var regex = '(count)'; var regex2 = /count',([a-z\s0-9,]*),/;
'use strict'; /** * Created by tpineau */ var extend = require('extend'); var async = require("async"); var googleapis = require('googleapis'); var keys = require('./../keys.json'); var youtube = googleapis.youtube('v3'); var googleKey = keys.googleKey; function videosSearch(keyword, num, opt_args, callback) { // Fonction de recherche de vidéos sur Youtube // Informations sur les arguments optionnels (opt_args): https://developers.google.com/youtube/v3/docs/search/list if (typeof opt_args === 'function') {callback = opt_args; opt_args = {};} var args = {q: keyword, maxResults: num, part: 'snippet', auth: googleKey}; if (opt_args.order === undefined) {opt_args.order = 'date';} if (opt_args.pageToken === undefined) {opt_args.pageToken = null;} if (opt_args.type === undefined) {opt_args.type = 'video';} extend(args, opt_args); go(args, callback); } function go(args, callback) { var args = args; var arr = listRequest(args); async.concatSeries( arr,