From 94f441a4e23a79936bf52ddaefeae80e4d5ef3e6 Mon Sep 17 00:00:00 2001 From: LuanRT Date: Tue, 2 Nov 2021 07:45:16 -0300 Subject: [PATCH] chore: format code --- lib/Actions.js | 6 ++--- lib/Constants.js | 16 ++++++------ lib/Innertube.js | 64 ++++++++++++++++++++++++------------------------ lib/Livechat.js | 24 +++++++++--------- lib/NToken.js | 18 +++++++------- lib/Player.js | 4 +-- lib/Utils.js | 12 ++++----- 7 files changed, 72 insertions(+), 72 deletions(-) diff --git a/lib/Actions.js b/lib/Actions.js index 3bda4669..29108c8f 100644 --- a/lib/Actions.js +++ b/lib/Actions.js @@ -56,7 +56,7 @@ async function browse(session, action_type) { break; default: } - + const response = await Axios.post(`${Constants.URLS.YT_BASE_URL}/youtubei/v1/browse${session.logged_in && session.cookie.length < 1 ? '' : `?key=${session.key}`}`, JSON.stringify(data), Constants.INNERTUBE_REQOPTS({ session })).catch((error) => error); if (response instanceof Error) return { success: false, status_code: response.response.status, message: response.message }; return { @@ -104,7 +104,7 @@ async function notifications(session, action_type, args = {}) { async function livechat(session, action_type, args = {}) { let data; switch (action_type) { - case 'live_chat/send_message': + case 'live_chat/send_message': data = { context: session.context, params: Utils.generateMessageParams(args.channel_id, args.video_id), @@ -127,7 +127,7 @@ async function livechat(session, action_type, args = {}) { break; default: } - + const response = await Axios.post(`${Constants.URLS.YT_BASE_URL}/youtubei/v1/${action_type}${session.logged_in && session.cookie.length < 1 ? '' : `?key=${session.key}`}`, JSON.stringify(data), Constants.INNERTUBE_REQOPTS({ session, params: args.params })).catch((error) => error); if (response instanceof Error) return { success: false, status_code: response.response.status, message: response.message }; return { diff --git a/lib/Constants.js b/lib/Constants.js index 91b8f33c..0e7d3fb5 100644 --- a/lib/Constants.js +++ b/lib/Constants.js @@ -25,7 +25,7 @@ module.exports = { }, DEFAULT_HEADERS: (session) => { return { - headers: { + headers: { 'Cookie': session.cookie, 'user-agent': Utils.getRandomUserAgent('desktop').userAgent, 'Referer': 'https://www.google.com/', @@ -62,7 +62,7 @@ module.exports = { 'origin': info.desktop ? 'https://www.youtube.com' : 'https://m.youtube.com', } }; - + info.id && (req_opts.headers.referer = (info.desktop ? 'https://www.youtube.com' : 'https://m.youtube.com') + '/watch?v=' + info.id); if (info.session.logged_in && info.desktop) { @@ -134,8 +134,8 @@ module.exports = { metadata.has_ypc_metadata = data.microformat.playerMicroformatRenderer.hasYpcMetadata; metadata.category = data.microformat.playerMicroformatRenderer.category; metadata.channel_name = data.microformat.playerMicroformatRenderer.ownerChannelName; - metadata.publish_date = data.microformat.playerMicroformatRenderer.publishDate || 'N/A', - metadata.upload_date = data.microformat.playerMicroformatRenderer.uploadDate || 'N/A', + metadata.publish_date = data.microformat.playerMicroformatRenderer.publishDate || 'N/A'; + metadata.upload_date = data.microformat.playerMicroformatRenderer.uploadDate || 'N/A'; metadata.keywords = data.videoDetails.keywords || []; video_details.title = data.videoDetails.title; @@ -183,7 +183,7 @@ module.exports = { } return video_details; }, - filters: (order) => { + filters: (order) => { return (({ 'any,any,relevance': 'EgIQAQ%3D%3D', 'hour,any,relevance': 'EgIIAQ%3D%3D', @@ -191,7 +191,7 @@ module.exports = { 'week,any,relevance': 'EgQIAxAB', 'month,any,relevance': 'EgQIBBAB', 'year,any,relevance': 'EgQIBRAB', - 'any,short,relevance':'EgQQARgB', + 'any,short,relevance': 'EgQQARgB', 'hour,short,relevance': 'EgYIARABGAE%3D', 'day,short,relevance': 'EgYIAhABGAE%3D', 'week,short,relevance': 'EgYIAxABGAE%3D', @@ -208,7 +208,7 @@ module.exports = { 'day,any,age': 'CAISBAgCEAE%3D', 'week,any,age': 'CAISBAgDEAE%3D', 'month,any,age': 'CAISBAgEEAE%3D', - 'year,any,age':'CAISBAgFEAE%3D', + 'year,any,age': 'CAISBAgFEAE%3D', 'any,short,age': 'CAISBBABGAE%3D', 'hour,short,age': 'CAISBggBEAEYAQ%3D%3D', 'day,short,age': 'CAISBggCEAEYAQ%3D%3D', @@ -245,7 +245,7 @@ module.exports = { 'week,any,rating': 'CAESBAgDEAE%3D', 'month,any,rating': 'CAESBAgEEAE%3D', 'year,any,rating': 'CAESBAgFEAE%3D', - 'any,short,rating': 'CAESBBABGAE%3D', + 'any,short,rating': 'CAESBBABGAE%3D', 'hour,short,rating': 'CAESBggBEAEYAQ%3D%3D', 'day,short,rating': 'CAESBggCEAEYAQ%3D%3D', 'week,short,rating': 'CAESBggDEAEYAQ%3D%3D', diff --git a/lib/Innertube.js b/lib/Innertube.js index 6c3f3c68..3442263b 100644 --- a/lib/Innertube.js +++ b/lib/Innertube.js @@ -25,7 +25,7 @@ class Innertube extends EventEmitter { async init() { const response = await Axios.get(Constants.URLS.YT_BASE_URL, Constants.DEFAULT_HEADERS(this)).catch((error) => error); if (response instanceof Error) throw new Error(`Could not extract Innertube data: ${response.message}`); - + try { const innertube_data = JSON.parse(`{${Utils.getStringBetweenStrings(response.data, 'ytcfg.set({', '});')}}`); if (innertube_data.INNERTUBE_CONTEXT) { @@ -101,7 +101,7 @@ class Innertube extends EventEmitter { async search(query, options = { period: 'any', order: 'relevance', duration: 'any' }) { if (!query) throw new Error('No query was provided'); - + const response = await Axios.post(`${Constants.URLS.YT_BASE_URL}/youtubei/v1/search${this.logged_in && this.cookie.length < 1 ? '' : `?key=${this.key}`}`, JSON.stringify({ context: this.context, params: Constants.filters(options.period + ',' + options.duration + ',' + options.order), query }), Constants.INNERTUBE_REQOPTS({ session: this })).catch((error) => error); if (response instanceof Error) throw new Error(`Could not search on YouTube: ${response.message}`); @@ -156,7 +156,7 @@ class Innertube extends EventEmitter { } else { video_data.getLivechat = () => {}; } - + video_data.like = () => Actions.engage(this, 'like/like', { video_id: id }); video_data.dislike = () => Actions.engage(this, 'like/dislike', { video_id: id }); video_data.removeLike = () => Actions.engage(this, 'like/removelike', { video_id: id }); @@ -168,32 +168,32 @@ class Innertube extends EventEmitter { return video_data; } - + async getComments(video_id, token) { let comment_section_token; - + if (!token) { const data_continuation = await Actions.getContinuation(this, { video_id }); const item_section_renderer = data_continuation.data.contents.twoColumnWatchNextResults.results.results.contents.find((item) => item.itemSectionRenderer); comment_section_token = item_section_renderer.itemSectionRenderer.contents[0].continuationItemRenderer.continuationEndpoint.continuationCommand.token; } - + const response = await Actions.getContinuation(this, { continuation_token: comment_section_token || token }); if (!response.success) throw new Error('Could not fetch comments section'); - + const comments_section = { comments: [] }; !token && (comments_section.comment_count = response.data.onResponseReceivedEndpoints[0].reloadContinuationItemsCommand.continuationItems && response.data.onResponseReceivedEndpoints[0].reloadContinuationItemsCommand.continuationItems[0].commentsHeaderRenderer.countText.runs[0].text || 'N/A'); - + let continuation_token; - !token && (continuation_token = response.data.onResponseReceivedEndpoints[1].reloadContinuationItemsCommand.continuationItems.find((item) => item.continuationItemRenderer).continuationItemRenderer.continuationEndpoint.continuationCommand.token) - || (continuation_token = response.data.onResponseReceivedEndpoints[0].appendContinuationItemsAction.continuationItems.find((item) => item.continuationItemRenderer).continuationItemRenderer.continuationEndpoint.continuationCommand.token); - + !token && (continuation_token = response.data.onResponseReceivedEndpoints[1].reloadContinuationItemsCommand.continuationItems.find((item) => item.continuationItemRenderer).continuationItemRenderer.continuationEndpoint.continuationCommand.token) || + (continuation_token = response.data.onResponseReceivedEndpoints[0].appendContinuationItemsAction.continuationItems.find((item) => item.continuationItemRenderer).continuationItemRenderer.continuationEndpoint.continuationCommand.token); + comments_section.getContinuation = () => this.getComments(video_id, continuation_token); - + let contents; - !token && (contents = response.data.onResponseReceivedEndpoints[1].reloadContinuationItemsCommand.continuationItems) - || (contents = response.data.onResponseReceivedEndpoints[0].appendContinuationItemsAction.continuationItems); - + !token && (contents = response.data.onResponseReceivedEndpoints[1].reloadContinuationItemsCommand.continuationItems) || + (contents = response.data.onResponseReceivedEndpoints[0].appendContinuationItemsAction.continuationItems); + contents.forEach((thread) => { if (!thread.commentThreadRenderer) return; const comment = { @@ -214,26 +214,26 @@ class Innertube extends EventEmitter { }; comments_section.comments.push(comment); }); - + return comments_section; } - + async getSubscriptionsFeed() { const response = await Actions.browse(this, 'subscriptions_feed'); if (!response.success) throw new Error('Could not fetch subscriptions feed'); - + const contents = response.data.contents.twoColumnBrowseResultsRenderer.tabs[0].tabRenderer.content.sectionListRenderer.contents; const subscriptions_feed = {}; - + contents.forEach((section) => { if (!section.itemSectionRenderer) return; - + const section_contents = section.itemSectionRenderer.contents[0]; const section_items = section_contents.shelfRenderer.content.gridRenderer.items; - + const key = section_contents.shelfRenderer.title.runs[0].text; subscriptions_feed[key.toLowerCase().replace(/ +/g, '_')] = []; - + section_items.forEach((item) => { const content = { title: item.gridVideoRenderer.title.runs.map((run) => run.text).join(' '), @@ -247,18 +247,18 @@ class Innertube extends EventEmitter { owner_badges: item.gridVideoRenderer.ownerBadges && item.gridVideoRenderer.ownerBadges.map((badge) => badge.metadataBadgeRenderer.tooltip) || 'N/A' } }; - + subscriptions_feed[key.toLowerCase().replace(/ +/g, '_')].push(content); }); }); - + return subscriptions_feed; } async getNotifications() { const response = await Actions.notifications(this, 'get_notification_menu'); if (!response.success) throw new Error('Could not fetch notifications'); - + const contents = response.data.actions[0].openPopupAction.popup.multiPageMenuRenderer.sections[0]; if (!contents.multiPageMenuNotificationSectionRenderer) return { error: 'You don\'t have any notification.' }; return contents.multiPageMenuNotificationSectionRenderer.items.map((notification) => { @@ -285,8 +285,8 @@ class Innertube extends EventEmitter { async requestVideoInfo(id, desktop) { let response; - !desktop && (response = await Axios.get(`${Constants.URLS.YT_WATCH_PAGE}?v=${id}&t=8s&pbj=1`, Constants.INNERTUBE_REQOPTS({ session: this, id, desktop: false })).catch((error) => error)) - || (response = await Axios.post(`${Constants.URLS.YT_BASE_URL}/youtubei/v1/player${this.logged_in && this.cookie.length < 1 ? '' : `?key=${this.key}`}`, JSON.stringify(Constants.VIDEO_INFO_REQBODY(id, this.sts, this.context)), Constants.INNERTUBE_REQOPTS({ session: this, id, desktop: true })).catch((error) => error)); + !desktop && (response = await Axios.get(`${Constants.URLS.YT_WATCH_PAGE}?v=${id}&t=8s&pbj=1`, Constants.INNERTUBE_REQOPTS({ session: this, id, desktop: false })).catch((error) => error)) || + (response = await Axios.post(`${Constants.URLS.YT_BASE_URL}/youtubei/v1/player${this.logged_in && this.cookie.length < 1 ? '' : `?key=${this.key}`}`, JSON.stringify(Constants.VIDEO_INFO_REQBODY(id, this.sts, this.context)), Constants.INNERTUBE_REQOPTS({ session: this, id, desktop: true })).catch((error) => error)); if (response instanceof Error) throw new Error('Could not retrieve watch page info: ' + response.message); return response.data; } @@ -355,10 +355,10 @@ class Innertube extends EventEmitter { if (options.type != 'videoandaudio') { let streams; - - options.type != 'audio' && (streams = filtered_streams.filter((format) => format.mimeType.includes(options.format || 'mp4') && format.qualityLabel == options.quality)) - || (streams = filtered_streams.filter((format) => format.mimeType.includes(options.format || 'mp4'))); - + + options.type != 'audio' && (streams = filtered_streams.filter((format) => format.mimeType.includes(options.format || 'mp4') && format.qualityLabel == options.quality)) || + (streams = filtered_streams.filter((format) => format.mimeType.includes(options.format || 'mp4'))); + streams == undefined || streams.length == 0 && (streams = filtered_streams.filter((format) => format.quality == 'medium')); bitrates = streams.map((format) => format.bitrate); @@ -421,7 +421,7 @@ class Innertube extends EventEmitter { cancelToken: new CancelToken(function executor(c) { cancel = c; }), headers: Constants.STREAM_HEADERS }).catch((error) => error); - + if (response instanceof Error) { stream.emit('error', { message: response.message, type: 'REQUEST_FAILED' }); return stream; diff --git a/lib/Livechat.js b/lib/Livechat.js index 9bdab3ba..f4ed2296 100644 --- a/lib/Livechat.js +++ b/lib/Livechat.js @@ -21,7 +21,7 @@ class Livechat extends EventEmitter { this.poll(); } - + enqueueActionGroup(group) { group.forEach((action) => { if (!action.addChatItemAction) return; //TODO: handle different action types @@ -38,7 +38,7 @@ class Livechat extends EventEmitter { timestamp: message_content.timestampUsec, id: message_content.id }; - + this.message_queue.push(message); }); } @@ -62,9 +62,9 @@ class Livechat extends EventEmitter { setTimeout(() => this.emit('chat-update', message), message.timestamp / 1000 - new Date().getTime()); this.id_cache.push(message.id); }); - + this.message_queue = []; - + data = { context: this.session.context, videoId: this.video_id }; if (this.metadata_ctoken) data.continuation = this.metadata_ctoken; @@ -81,23 +81,23 @@ class Livechat extends EventEmitter { short_view_count: metadata[0].updateViewershipAction.viewCount.videoViewCountRenderer.extraShortViewCount.simpleText } }); - + this.livechat_poller = setTimeout(async () => await this.poll(), this.poll_intervals_ms); } - + async sendMessage(text) { const message = await Actions.livechat(this.session, 'live_chat/send_message', { text, channel_id: this.channel_id, video_id: this.video_id }); if (!message.success) return message; - + const deleteMessage = async () => { const menu = await Actions.livechat(this.session, 'live_chat/get_item_context_menu', { params: { params: message.data.actions[0].addChatItemAction.item.liveChatTextMessageRenderer.contextMenuEndpoint.liveChatItemContextMenuEndpoint.params, pbj: 1 } }); if (!menu.success) return menu; - + const chat_item_menu = menu.data.liveChatItemContextMenuSupportedRenderers.menuRenderer.items[0]; - + const cmd = await Actions.livechat(this.session, 'live_chat/moderate', { cmd_params: chat_item_menu.menuServiceItemRenderer.serviceEndpoint.moderateLiveChatEndpoint.params }); if (!cmd.success) return cmd; - + return { success: true, status_code: cmd.status_code }; }; @@ -117,9 +117,9 @@ class Livechat extends EventEmitter { } }; } - + async blockUser(msg_params) { - /* TODO: Implement this */ + /* TODO: Implement this */ throw new Error('Not implemented'); } diff --git a/lib/NToken.js b/lib/NToken.js index 4d5acc6d..3c48b455 100644 --- a/lib/NToken.js +++ b/lib/NToken.js @@ -12,7 +12,7 @@ class NToken { transform(n) { let n_token = n.split(''); - + try { let transformations = this.getTransformationData(this.raw_code); transformations = transformations.map((el, i) => { @@ -32,7 +32,7 @@ class NToken { } return el; }); - + // Fills the null placeholders with a copy of the transformations array. let null_placeholder_positions = [...this.raw_code.matchAll(this.null_placeholder_regex)].map((item) => parseInt(item[1])); null_placeholder_positions.forEach((pos) => transformations[pos] = transformations); @@ -50,11 +50,11 @@ class NToken { return n_token.join(''); } - + getFunc(el) { return el.match(Constants.FUNCS_REGEX); } - + getTransformationData() { const data = `[${Utils.getStringBetweenStrings(this.raw_code.replace(/\n/g, ''), 'c=[', '];c')}]`; return JSON.parse(Constants.formatNTransformData(data)); @@ -66,28 +66,28 @@ class NToken { this.push(loc[index] = characters[(characters.indexOf(char) - characters.indexOf(this[index]) + 64) % characters.length]); }, token.split('')); } - + swap0(arr, index) { const old_value = arr[0]; index = (index % arr.length + arr.length) % arr.length; arr[0] = arr[index]; arr[index] = old_value; } - + rotate(arr, index) { index = (index % arr.length + arr.length) % arr.length; arr.splice(-index).reverse().forEach((el) => arr.unshift(el)); } - + splice(arr, index) { index = (index % arr.length + arr.length) % arr.length; arr.splice(index, 1); } - + reverse(arr) { arr.reverse(); } - + push(arr, item) { arr.push(item); } diff --git a/lib/Player.js b/lib/Player.js index 5118c36c..98587ba9 100644 --- a/lib/Player.js +++ b/lib/Player.js @@ -20,13 +20,13 @@ class Player { } else { const response = await Axios.get(`${Constants.URLS.YT_BASE_URL}${this.session.player_url}`, { path: this.session.playerUrl, headers: { 'content-type': 'text/javascript', 'user-agent': Utils.getRandomUserAgent('desktop').userAgent } }).catch((error) => error); if (response instanceof Error) throw new Error('Could not download player script: ' + response.message); - + try { // Caches the current player so we don't have to download it all the time fs.mkdirSync(this.tmp_cache_dir, { recursive: true }); fs.writeFileSync(`${this.tmp_cache_dir}/${this.player_name}.js`, response.data); } catch (err) {} - + this.getSigDecipherCode(response.data); this.getNEncoder(response.data); } diff --git a/lib/Utils.js b/lib/Utils.js index e567ec23..7cb8cd89 100644 --- a/lib/Utils.js +++ b/lib/Utils.js @@ -39,7 +39,7 @@ function escapeStringRegexp(string) { function encodeNotificationPref(channel_id, index) { const youtube_proto = Proto(Fs.readFileSync(`${__dirname}/proto/youtube.proto`)); - + const buf = youtube_proto.NotificationPreferences.encode({ channel_id, pref_id: { @@ -48,24 +48,24 @@ function encodeNotificationPref(channel_id, index) { number_0: 0, number_1: 4 }); - + return encodeURIComponent(Buffer.from(buf).toString('base64')); } function generateMessageParams(channel_id, video_id) { const youtube_proto = Proto(Fs.readFileSync(`${__dirname}/proto/youtube.proto`)); - + const buf = youtube_proto.LiveMessageParams.encode({ params: { ids: { - channel_id, - video_id + channel_id, + video_id } }, number_0: 1, number_1: 4 }); - + return Buffer.from(encodeURIComponent(Buffer.from(buf).toString('base64'))).toString('base64'); }