Skip to content

Commit

Permalink
Add thumbnails for all YouTube links
Browse files Browse the repository at this point in the history
  • Loading branch information
cookpete committed Jan 19, 2016
1 parent db446ac commit 6b9f745
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 1 deletion.
16 changes: 15 additions & 1 deletion src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ const REDDIT_URL = 'https://www.reddit.com'
const MATCH_REPLY_URLS = /(?:\[([^\]]+)\]\s*\()?(https?\:\/\/[^\)\s]+)\)?/gi
const REPLACE_CHAR = String.fromCharCode(0)
const INFER_TITLE_MAX_LENGTH = 128 // Max length of remaining text to use as a title for a link
const MATCH_YOUTUBE_URL = /^(?:https?:\/\/)?(?:www\.)?(?:youtu\.be\/|youtube\.com\/(?:embed\/|v\/|watch\?v=|watch\?.+&v=))((\w|-){11})(?:\S+)?$/

const KIND_COMMENT = 't1'
const KIND_POST = 't3'
Expand Down Expand Up @@ -108,9 +109,9 @@ function postFromPost (post) {
author: post.author,
score: post.score,
subreddit: post.subreddit,
thumbnail: getThumbnail(post),
permalink: getPermalink(post),
// Post-specific fields
thumbnail: post.thumbnail,
num_comments: post.num_comments
}
}
Expand All @@ -129,6 +130,7 @@ function postFromComment (post, match, title = null, url, offset, path) {
author: post.author,
score: post.score,
subreddit: post.subreddit,
thumbnail: getThumbnail(post, url),
permalink: getPermalink(post, path),
// Comment-specific fields
comment_id: post.id
Expand All @@ -147,6 +149,18 @@ function getPermalink (post, path = '') {
return REDDIT_URL + path + slash + post.id
}

function getThumbnail (post, url = post.url) {
if (post.thumbnail) {
return post.thumbnail
}
const matchYouTube = url.match(MATCH_YOUTUBE_URL)
if (matchYouTube) {
const id = matchYouTube[1]
return `http://img.youtube.com/vi/${id}/default.jpg`
}
return null
}

// Remove markdown bold/italics
// From https://github.com/stiang/remove-markdown
function removeMarkdown (string) {
Expand Down
1 change: 1 addition & 0 deletions test/test.js
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,7 @@ describe('extractPosts', () => {
links.forEach(verifyPost)
assert.propertyVal(links[0], 'title', 'Sabre Dance')
assert.propertyVal(links[0], 'url', 'http://www.youtube.com/watch?v=gqg3l3r_DRI')
assert.propertyVal(links[0], 'thumbnail', 'http://img.youtube.com/vi/gqg3l3r_DRI/default.jpg')
})

it('extracts links from self posts', () => {
Expand Down

0 comments on commit 6b9f745

Please sign in to comment.