common = $common;
}
/**
* Important. Run whenever new post is being created (or updated). The method generates a background task to generate the audio file.
*
* @since 0.1
*/
public function save_post( $post_id, $post, $updated ) {
$common = $this->common;
$logger = new Logger();
$logger->log( sprintf( '%s Saving post ( id=%s )', __METHOD__, $post_id ) );
// Check if this isn't an auto save.
if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) {
return;
}
if ( wp_is_post_revision( $post_id ) || wp_is_post_autosave( $post_id ) ) {
return;
}
// Validate if this post which is being saved is one of supported types. If not, return.
$post_types_supported = $common->get_posttypes_array();
$post_type = get_post_type( $post_id );
if ( ! in_array( $post_type, $post_types_supported ) ) {
return;
}
// Core fires wp_after_insert_post after REST fields and post metadata are saved.
if ( current_user_can( 'edit_post', $post_id ) && isset( $_POST[ self::NONCE_NAME ] ) && is_string( $_POST[ self::NONCE_NAME ] ) && wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST[ self::NONCE_NAME ] ) ), 'itron-polly-tts' ) ) {
if ( $common->is_polly_enabled() && isset( $_POST['itron_polly_tts_settings_present'] ) ) {
update_post_meta( $post_id, 'itron_polly_tts_enable', (int) isset( $_POST['itron_polly_tts_enable'] ) );
}
if ( $common->is_post_voice_override_disabled() ) {
delete_post_meta( $post_id, 'itron_polly_tts_voice_id' );
} elseif ( isset( $_POST['itron_polly_tts_voice_id'] ) ) {
// Update post voice ID
$voice_id = sanitize_text_field( wp_unslash( $_POST['itron_polly_tts_voice_id'] ) );
try {
if ( $common->is_polly_enabled() ) {
$voice_id = $common->resolve_polly_voice_id(
$common->get_post_source_language( $post_id ),
$voice_id,
$common->get_voice_id()
);
}
} catch ( \Exception $e ) {
$logger->log( sprintf( '%s Unable to validate selected voice while saving post ( id=%s ): %s', __METHOD__, $post_id, get_class( $e ) ) );
}
update_post_meta( $post_id, 'itron_polly_tts_voice_id', $voice_id );
}
}
if ( ! $common->is_polly_enabled() || ! ( new AudioConsent( $common ) )->is_allowed( (int) $post_id ) ) {
try {
$this->generate_audio( $post_id );
} catch ( ConcurrentAudioGenerationException $e ) {
( new BackgroundTask() )->queue_audio( $post_id );
}
} else {
$logger->log( sprintf( '%s Starting background task process ( id=%s )', __METHOD__, $post_id ) );
$background_task = new BackgroundTask();
$background_task->queue_audio( $post_id );
}
}
/**
* Important. Executes the Amazon Polly API to create audio file and save to the configured storage location
*
* @throws ConcurrentAudioGenerationException
* @since 0.1
*/
public function generate_audio( $post_id ) {
$logger = new Logger();
$common = $this->common;
$logger->log( sprintf( '%s Generating audio for post ( id=%s )', __METHOD__, $post_id ) );
// The generate audio file lock is to prevent multiple processes from generating audio for the same post.
$lock = new WP_Lock( self::LOCK_PREFIX . $post_id );
$allowed = $lock->acquire( WP_Lock::WRITE, false, 300 );
/**
* Fires before attempting to generate and save the Amazon Polly audio files.
* This hook can be used to prevent the audio files from being generated.
*
* @param int $post_id The post id to generate audio files for.
* @param bool $continue Whether to continue with generating the audio files. Default true.
* @param bool $allowed Whether the audio generation is allowed for the post now.
*/
$continue = true;
do_action_ref_array( 'itron_polly_tts_pre_generate_audio', array( $post_id, &$continue, $allowed ) );
if ( ! $continue ) {
$allowed && $lock->release();
$logger->log( sprintf( '%s Skipping audio generation for post ( id=%s )', __METHOD__, $post_id ) );
return;
}
if ( ! $allowed ) {
// Another process is already generating audio for this post.
do_action( 'itron_polly_tts_post_generate_audio_locked', $post_id );
$logger->log( sprintf( '%s Audio is already being generated by another process. Skipping audio generating for the post ( id=%s )', __METHOD__, $post_id ) );
throw new ConcurrentAudioGenerationException();
}
$is_polly_enabled = (bool) get_post_meta( $post_id, 'itron_polly_tts_enable', true );
try {
$post = get_post( $post_id );
if ( ! $post || ! in_array( $post->post_type, $common->get_posttypes_array(), true ) || in_array( $post->post_status, array( 'trash', 'auto-draft', 'inherit' ), true ) ) {
return;
}
if ( ! ( new AudioConsent( $common ) )->is_allowed( (int) $post_id ) ) {
if ( $common->has_post_audio( $post_id ) ) {
$common->delete_post_audio( $post_id );
}
return;
}
if ( ! $common->is_polly_enabled() ) {
if ( $common->has_post_audio( $post_id ) && ! $common->is_post_audio_current( (int) $post_id ) ) {
$common->delete_post_audio( $post_id );
}
return;
}
if ( $is_polly_enabled ) {
if ( ! $common->validate_itron_polly_tts_access( true, false ) ) {
throw new CredentialsException( 'AWS configuration is unavailable.' );
}
if ( ! $common->has_post_audio( $post_id ) ) {
$common->set_post_audio_state( $post_id, Common::AUDIO_STATE_RUNNING );
}
$voice_request = $common->get_audio_voice_request( (int) $post_id );
$resolved_voice_id = $common->resolve_polly_voice_id(
$voice_request['language'],
$voice_request['voice'],
$common->get_voice_id()
);
if ( $resolved_voice_id !== $voice_request['voice'] ) {
$logger->log(
sprintf(
'%s Voice adjusted for post ( id=%s ): requested=%s resolved=%s language=%s',
__METHOD__,
$post_id,
$voice_request['voice'],
'' !== $resolved_voice_id ? $resolved_voice_id : '[empty]',
$voice_request['language']
)
);
}
$voice_id = $resolved_voice_id;
if ( empty( $voice_id ) ) {
throw new \Exception( 'No supported Amazon Polly voices are available for this post language in the selected AWS region.' );
}
$audio_hash = get_post_meta( $post_id, 'itron_polly_tts_audio_hash', true );
$clean_text = $common->clean_text( $post_id, true, false );
$current_hash = $common->get_audio_hash( $post_id, $clean_text, $voice_id );
$audio_voice = array(
'request' => $voice_request,
'resolved' => $voice_id,
);
$this->assert_generation_current( (int) $post_id, $current_hash, $audio_voice );
// If the hash is the same, we don't need to regenerate the audio.
if ( $common->is_post_audio_current( (int) $post_id, $current_hash ) ) {
update_post_meta( $post_id, 'itron_polly_tts_audio_voice', $audio_voice );
do_action( 'itron_polly_tts_post_identical_audio', $post_id, $audio_hash );
$common->set_post_audio_state( $post_id, Common::AUDIO_STATE_READY );
throw new IdenticalAudioException();
}
do_action( 'itron_polly_tts_post_generate_audio_validated', $post_id );
$logger->log( sprintf( '%s Basic validation OK', __METHOD__ ) );
// Sammple Rate
$sample_rate = $common->get_sample_rate();
// Breaking text into smaller parts, which will be then send to Amazon Polly for conversion.
$sentences = $common->break_text( $clean_text );
// We will be operating on local file system for stiching files together.
$wp_filesystem = $common->prepare_wp_filesystem();
// Actual invocation of method which will call Amazon Polly API and create audio file.
$this->convert_to_audio( $post_id, $sample_rate, $voice_id, $sentences, $wp_filesystem, $current_hash, $audio_voice );
update_post_meta( $post_id, 'itron_polly_tts_audio_hash', $current_hash );
update_post_meta( $post_id, 'itron_polly_tts_audio_voice', $audio_voice );
$common->set_post_audio_state( $post_id, Common::AUDIO_STATE_READY );
$this->assert_saved_audio_current( (int) $post_id, $current_hash, $audio_voice );
// update_post_meta() invalidates post meta caches, but it does not flush post query caches.
// Hosted environments with persistent object cache can otherwise keep stale admin list results
// for filters like "Without audio" even after the final audio link has been saved.
clean_post_cache( $post_id );
} else { // Remove audio files and post meta (if existing) if Polly is not enabled
$common->delete_post_audio( $post_id );
}
/**
* Fires after attempting to generate and save the Amazon Polly audio files
*
* @param int $post_id The post id to generate audio files for
*/
do_action( 'itron_polly_tts_post_generate_audio', $post_id, $is_polly_enabled );
} catch ( \Throwable $e ) {
if ( ! $common->has_post_audio( $post_id ) ) {
$common->set_post_audio_state( $post_id, Common::AUDIO_STATE_ERROR );
}
$logger->log( sprintf( '%s Error: %s', __METHOD__, get_class( $e ) ) );
} finally {
$lock->release();
}
}
/**
* Method execute Amazon Polly API and convert content which was provided to audio file.
*
* @param string $post_id ID of the posts which is being converted.
* @param string $sample_rate Sample rate for speech conversion.
* @param string $voice_id Amazon Polly voice ID.
* @param string $sentences Sentences which should be converted to audio.
* @param string $wp_filesystem Reference to WP File system variable.
* @since 0.1
*/
public function convert_to_audio( $post_id, $sample_rate, $voice_id, $sentences, $wp_filesystem, string $expected_hash, array $voice_snapshot ) {
$logger = new Logger();
$logger->log( sprintf( '%s Converting to Audio', __METHOD__ ) );
// Creating new standard common object for interacting with other methods of the plugin.
$common = $this->common;
if ( empty( $voice_id ) ) {
throw new \InvalidArgumentException( 'A resolved Polly voice is required for synthesis.' );
}
// Just in case we check if sample rate is valid, if not we will set default value.
$sample_rate_values = array( '24000', '22050', '16000', '8000' );
if ( ! in_array( $sample_rate, $sample_rate_values, true ) ) {
$sample_rate = '24000';
}
// Preparing locations and names of temporary files which will be used.
$random = wp_rand( 100000, PHP_INT_MAX );
$upload_dir = wp_upload_dir()['basedir'];
$file_prefix = 'itron_polly_tts_';
$file_name = $file_prefix . $post_id . '.mp3';
$file_temp_full_name = trailingslashit( $upload_dir ) . 'temp_' . $file_name . $random;
$dir_final_full_name = trailingslashit( $upload_dir );
if ( get_option( 'uploads_use_yearmonth_folders' ) ) {
$dir_final_full_name .= get_the_date( 'Y', $post_id ) . '/' . get_the_date( 'm', $post_id ) . '/';
}
$file_final_full_name = $dir_final_full_name . $file_name;
// Delete temporary file if already exists.
if ( $wp_filesystem->exists( $file_temp_full_name ) ) {
$wp_filesystem->delete( $file_temp_full_name );
}
try {
// We might be stiching multiple smaller audio files. This variable will
// be used to detact the first part.
$first_part = true;
// Iterating through each of text parts.
foreach ( $sentences as $key => $text_content ) {
$this->assert_generation_current( (int) $post_id, $expected_hash, $voice_snapshot );
// Remove all tags
$text_content = wp_strip_all_tags( $text_content, false );
// Modify Speed
$text_content = $common->modify_sentence_speed( $text_content );
// Adding breaths sounds (if enabled).
$text_content = $this->add_breaths( $common, $text_content );
// If plugin SSML support option is enabled, plugin will try to decode all SSML tags.
$text_content = $this->ssml_support( $common, $text_content );
// Adding special polly mark.
$text_content = $this->add_mark_tag( $common, $text_content );
// Adding newscaster style tag
$text_content = $this->add_newscaster_tag( $common, $text_content, $voice_id );
// Adding speak polly mark.
$text_content = $this->add_speak_tags( $common, $text_content );
//Preparing lexicons which will be used create audio.
$lexicons = $common->get_lexicons();
$lexicons_array = explode( ' ', $lexicons );
//Preparing Amazon Polly client object.
$polly_client = $common->get_polly_client();
//Detect Polly Engine (Standard / Neural).
$engine = $common->get_polly_engine( $voice_id );
$news_style = $common->should_news_style_be_used( $voice_id );
$logger->log( sprintf( '%s Synthesis post=%d part=%d engine=%s voice=%s sample_rate=%s news=%d', __METHOD__, $post_id, $key, $engine, $voice_id, $sample_rate, $news_style ) );
//Call Amazon Polly service.
if ( ! empty( $lexicons ) and ( count( $lexicons_array ) > 0 ) ) {
$result = $polly_client->synthesizeSpeech(
array(
'Engine' => $engine,
'OutputFormat' => 'mp3',
'SampleRate' => $sample_rate,
'Text' => $text_content,
'TextType' => 'ssml',
'VoiceId' => $voice_id,
'LexiconNames' => $lexicons_array,
)
);
} else {
$result = $polly_client->synthesizeSpeech(
array(
'Engine' => $engine,
'OutputFormat' => 'mp3',
'SampleRate' => $sample_rate,
'Text' => $text_content,
'TextType' => 'ssml',
'VoiceId' => $voice_id,
)
);
}
$logger->log( sprintf( '%s Audio returned from Polly', __METHOD__ ) );
// Grab the stream and output to a file.
$contents = $result['AudioStream']->getContents();
// Save first part of the audio stream in the parial temporary file.
if ( ! $wp_filesystem->put_contents( $file_temp_full_name . '_part_' . $key, $contents ) ) {
throw new \RuntimeException( 'Could not write the temporary audio part.' );
}
$logger->log( sprintf( '%s Part created post=%d part=%d', __METHOD__, $post_id, $key ) );
// Merge new temporary file with previous ones.
if ( $first_part ) {
if ( ! $wp_filesystem->put_contents( $file_temp_full_name, $contents ) ) {
throw new \RuntimeException( 'Could not write temporary audio.' );
}
$first_part = false;
} else {
$common->remove_id3( $file_temp_full_name . '_part_' . $key, $wp_filesystem );
$previous_audio = $wp_filesystem->get_contents( $file_temp_full_name );
$next_audio = $wp_filesystem->get_contents( $file_temp_full_name . '_part_' . $key );
if ( ! is_string( $previous_audio ) || ! is_string( $next_audio ) ) {
throw new \RuntimeException( 'Could not read the temporary audio parts.' );
}
$merged_file = $previous_audio . $next_audio;
if ( ! $wp_filesystem->put_contents( $file_temp_full_name, $merged_file ) ) {
throw new \RuntimeException( 'Could not merge temporary audio.' );
}
}
// Deleting partial audio file.
$wp_filesystem->delete( $file_temp_full_name . '_part_' . $key );
}
$this->assert_generation_current( (int) $post_id, $expected_hash, $voice_snapshot );
// The old locator must remain available until guarded cleanup has run.
$common->delete_post_audio( $post_id );
// Saving the duration of an audio file as the string 00:00.
$playtime_string = $this->get_audio_playtime_string( $file_temp_full_name );
if ( $playtime_string ) {
update_post_meta( $post_id, 'itron_polly_tts_audio_playtime', $playtime_string );
}
// Saving audio file in final destination.
$file_handler = $common->get_file_handler();
if ( $file_handler instanceof LocalFileHandler ) {
$destination = $file_handler->get_destination( (int) $post_id, $file_name );
$dir_final_full_name = trailingslashit( dirname( $destination['path'] ) );
$file_final_full_name = $destination['path'];
}
$audio_location_link = $file_handler->save( $wp_filesystem, $file_temp_full_name, $dir_final_full_name, $file_final_full_name, $post_id, $file_name );
// This will bust the browser cache when a content revision is made.
$audio_location_link = add_query_arg( 'version', time(), $audio_location_link );
$this->assert_saved_audio_current( (int) $post_id, $expected_hash, $voice_snapshot );
if ( ! $common->get_audio_storage()->set_delivery_url( (int) $post_id, $audio_location_link ) ) {
$common->delete_post_audio( $post_id );
throw new \RuntimeException( 'Could not record the final audio URL.' );
}
update_post_meta( $post_id, 'itron_polly_tts_audio_link_location', $audio_location_link );
update_post_meta( $post_id, 'itron_polly_tts_audio_location', $file_handler->get_type() );
update_post_meta( $post_id, 'itron_polly_tts_generated_voice_id', $voice_id );
$this->assert_saved_audio_current( (int) $post_id, $expected_hash, $voice_snapshot );
$logger->log( sprintf( '%s Final audio created!', __METHOD__ ) );
} finally {
foreach ( array_merge( array( $file_temp_full_name ), array_map( static fn( $key ) => $file_temp_full_name . '_part_' . $key, array_keys( $sentences ) ) ) as $temporary_path ) {
if ( $wp_filesystem->exists( $temporary_path ) ) {
$wp_filesystem->delete( $temporary_path );
}
}
}
}
private function assert_saved_audio_current( int $post_id, string $expected_hash, array $voice_snapshot ): void {
try {
$this->assert_generation_current( $post_id, $expected_hash, $voice_snapshot );
} catch ( \Throwable $e ) {
$this->common->delete_post_audio( $post_id );
throw $e;
}
}
private function assert_generation_current( int $post_id, string $expected_hash, array $voice_snapshot ): void {
// Re-read inputs after network work; another request may have saved this post or disabled TTS.
clean_post_cache( $post_id );
wp_cache_delete( 'alloptions', 'options' );
foreach ( array( 'polly_enable', 'voice_id', 'source_language', 's3_region', 'sample_rate', 'speed', 'lexicons', 'neural', 'speaking_style', 'auto_breaths', 'ssml', 'add_post_title', 'add_post_excerpt', 'skip_tags', 'disable_post_voice_override' ) as $option ) {
wp_cache_delete( 'itron_polly_tts_' . $option, 'options' );
}
$common = $this->common;
$post = get_post( $post_id );
if (
! $post || in_array( $post->post_status, array( 'trash', 'auto-draft', 'inherit' ), true )
|| ! $common->is_polly_enabled()
|| '1' !== (string) get_post_meta( $post_id, 'itron_polly_tts_enable', true )
|| ! ( new AudioConsent( $common ) )->is_allowed( $post_id )
|| $voice_snapshot['request'] !== $common->get_audio_voice_request( $post_id )
|| ! hash_equals( $expected_hash, $common->get_audio_hash( $post_id, null, $voice_snapshot['resolved'] ) )
) {
throw new \RuntimeException( 'Audio generation was cancelled because its inputs or permissions changed.' );
}
}
private function get_audio_playtime_string( string $file_path ): string {
if ( ! function_exists( 'wp_read_audio_metadata' ) ) {
require_once ABSPATH . 'wp-admin/includes/media.php';
}
if ( ! function_exists( 'wp_read_audio_metadata' ) ) {
return '';
}
$metadata = wp_read_audio_metadata( $file_path );
if ( ! is_array( $metadata ) || empty( $metadata['length_formatted'] ) ) {
return '';
}
return (string) $metadata['length_formatted'];
}
/**
* Method add SSML breaths tags if functionality is enabled.
*
* @param string $common Plugin common object.
* @param string $text_content Existing text.
* @since 0.1
*/
private function add_breaths( $common, $text_content) {
// Depending on the plugin configuration SSML tags for automated breaths sound will be added.
$is_breaths_enabled = $common->is_auto_breaths_enabled();
if ( $is_breaths_enabled ) {
$text_content = '' . $text_content . '';
}
return $text_content;
}
/**
* Method decode SSML tags if functionality is enabled.
*
* @param string $common Plugin common object.
* @param string $text_content Existing text.
* @since 0.1
*/
private function ssml_support( $common, $text_content) {
// If plugin SSML support option is enabled, plugin will try to decode all SSML tags.
$is_ssml_enabled = $common->is_ssml_enabled();
if ( $is_ssml_enabled ) {
$text_content = $common->decode_ssml_tags( $text_content );
}
$text_content = str_replace( '**AMAZONPOLLY*SSML*BREAK*time=***300ms***SSML**', '', $text_content );
$text_content = str_replace( '**AMAZONPOLLY*SSML*BREAK*time=***500ms***SSML**', '', $text_content );
$text_content = str_replace( '**AMAZONPOLLY*SSML*BREAK*time=***1s***SSML**', '', $text_content );
return $text_content;
}
/**
* Method add special mark tag for output text.
*
* @param string $common Plugin common object.
* @param string $text_content Existing text.
* @since 0.1
*/
private function add_mark_tag( $common, $text_content) {
$itron_polly_tts_mark_value = 'itron-polly-tts';
$itron_polly_tts_mark_value = apply_filters( 'itron_polly_tts_mark_value', $itron_polly_tts_mark_value );
$text_content = '' . $text_content . '';
return $text_content;
}
private function add_newscaster_tag( $common, $text_content, $voice) {
if ($common->should_news_style_be_used( $voice )) {
$text_content = '' . $text_content . '';
}
return $text_content;
}
/**
* Method add speak tags for output text.
*
* @param string $common Plugin common object.
* @param string $text_content Existing text.
* @since 0.1
*/
private function add_speak_tags( $common, $text_content) {
$text_content = '' . $text_content . '';
return $text_content;
}
}