Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Update tweet screenshot mechanism #46

Open
wants to merge 4 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 11 additions & 5 deletions lib/twitter.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@
'use strict';

const _path = require( 'path' );
const _sharp = require( 'sharp' );
const _fs = require( 'fs' );

// time in milliseconds to wait after the last response before taking the screenshot
const WAIT_AFTER_RESPONSE = 1000;
Expand All @@ -15,13 +17,17 @@ const sleep = timeInMs => new Promise( resolve => setTimeout( resolve, timeInMs
const isTweetEmbed = url => url.startsWith( 'https://platform.twitter.com/embed/index.html?' );

const snapTweet = async ( { page, filename, logger, makeDirIfRequired } ) => {
const elements = await page.$x( '//*[@id="app"]//article' );
if ( elements.length !== 1 ) {
logger.error( `${process.pid}: xpath selector returned ${elements.length} elements` );
const tmpFilename = filename + '_tmp';
makeDirIfRequired( _path.dirname( filename ) );
const bodyHandle = await page.$( 'body' );
await bodyHandle.screenshot( { path: tmpFilename, type: 'jpeg' } );
await _sharp( tmpFilename ).trim().jpeg( { quality: 90 } ).toFile( filename );
try {
_fs.unlinkSync( tmpFilename );
} catch ( err ) {
logger.error( `${process.pid}: could not unlink temporary screenshot file: ${err}` );
return false;
}
makeDirIfRequired( _path.dirname( filename ) );
await elements[0].screenshot( { path: filename, type: 'jpeg', quality: 90 } );
return true;
};

Expand Down
Loading