-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathezcontent_smart_article.module
350 lines (336 loc) · 13.1 KB
/
ezcontent_smart_article.module
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
<?php
/**
* @file
* Module file for ezcontent_smart_article.
*/
use Drupal\Component\Serialization\Json;
use Drupal\Component\Utility\Html;
use Drupal\Core\Ajax\AjaxResponse;
use Drupal\Core\Ajax\InvokeCommand;
use Drupal\Core\Entity\ContentEntityForm;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Url;
/**
* Implements hook_views_data_alter().
*/
function ezcontent_smart_article_views_data_alter(array &$data) {
$data['media__field_smart_image_tags']['media_type_filter'] = [
'title' => t('Filter by smart image tags'),
'filter' => [
'title' => t('Filter by smart image tags'),
'help' => t('Provides a custom filter for smart image media by tags.'),
'field' => 'field_smart_image_tags_target_id',
'id' => 'taxonomy_index_tid',
],
];
}
/**
* Implements hook_form_FORM_ID_alter().
*/
function ezcontent_smart_article_form_node_form_alter(&$form, FormStateInterface $form_state) {
if (in_array($form['#form_id'], [
'node_smart_article_edit_form',
'node_smart_article_form',
])) {
$summary_config = \Drupal::config('ezcontent_smart_article.settings');
if (empty($summary_config->get('summary_generator_api_url')) ||
empty($summary_config->get('summary_generator_data_file')) ||
empty($summary_config->get('image_captioning_api_url')) ||
empty($summary_config->get('abstractive_summary_api_url')) ||
empty($summary_config->get('extractive_summary_api_url')) ||
empty($summary_config->get('smart_tags_api_url'))) {
$form['overlay_link'] = [
'#type' => 'link',
'#url' => Url::fromRoute('ezcontent_smart_article.invalid_subscription'),
'#attributes' => [
'class' => ['use-ajax'],
'data-dialog-type' => 'modal',
'data-dialog-options' => Json::encode([
'title' => t('Smart Article Settings'),
'width' => 700,
'closeOnEscape' => FALSE,
'modal' => TRUE,
]),
],
];
}
// Make Company name Autocomplete.
$form['field_company_name']['widget'][0]['value']['#autocomplete_route_name'] = 'ezcontent_smart_article.autocomplete.companies';
// Add a generate summary button and hide body field.
$form['field_company_name']['generate_summary'] = [
'#type' => 'submit',
'#name' => 'generate_summary',
'#value' => t('Generate Article Content'),
'#weight' => 11,
'#attributes' => empty($summary_config->get('summary_generator_api_url')) ? [
'disabled' => 'disabled',
] : [],
'#ajax' => [
'callback' => 'ezcontent_smart_article_generate_callback',
'wrapper' => 'form-summary-generate-wrapper',
'effect' => 'fade',
'event' => 'click',
'progress' => [
'type' => 'throbber',
'message' => 'Please wait...',
],
],
];
$form['#attached']['library'][] = 'ezcontent_smart_article/ezcontent_smart_article_libs';
if (isset($form['body'])) {
if ($form['body']['widget'][0]['#default_value'] == '') {
$form['body']['#attributes']['class'][] = 'hide-body--field';
$form['body']['#attributes']['style'] = 'display:none;';
}
}
// Check if smart summary exist.
if (isset($form['field_smart_text_summary']['widget'][0]['summary'])) {
$form['field_smart_text_summary']['widget'][0]['summary_container']['number_of_sentences']['#states'] = [
'visible' => [
':input[name="field_smart_text_summary[0][summary_container][summary_type]"]' => ['value' => 'extractive'],
],
];
$form['field_smart_text_summary']['widget'][0]['summary_container']['generate_smart_summary']['#ajax'] = [
'callback' => 'ezcontent_smart_summary_generate_callback',
'wrapper' => 'form-smart-summary-generate-wrapper',
'effect' => 'fade',
'event' => 'click',
'progress' => [
'type' => 'throbber',
'message' => 'Please wait...',
],
];
// Disable summary generate button if subscription keys not available.
$form['field_smart_text_summary']['widget'][0]['summary_container']['generate_smart_summary']['#attributes']
= (empty($summary_config->get('abstractive_summary_api_url')) || empty($summary_config->get('extractive_summary_api_url')))
? ['disabled' => 'disabled'] : [];
// Add submit handler to update summary.
$form['actions']['submit']['#submit'][] = 'update_summary_field_submit_handler';
}
// Code for Podcast.
$bundle = $entity_type = '';
$form_object = $form_state->getFormObject();
if ($form_object instanceof ContentEntityForm) {
$entity = $form_object->getEntity();
$bundle = $entity->bundle();
$entity_type = $entity->getEntityTypeId();
if (!empty($entity_type) && !empty($bundle)) {
// Custom submit handler for Podcast.
foreach ($entity->getFieldDefinitions() as $field_definition) {
if ($field_definition->getType() === 'ezcontent_smart_podcast') {
// Submit handler for podcast.
$form['actions']['submit']['#submit'][] = 'ezcontent_smart_podcast_submit_handler';
break;
}
}
}
}
}
}
/**
* Custom submit handler for podcast.
*
* @param array $form
* The form object.
* @param \Drupal\Core\Form\FormStateInterface $form_state
* The form state object.
*
* @throws \Drupal\Component\Plugin\Exception\InvalidPluginDefinitionException
* @throws \Drupal\Component\Plugin\Exception\PluginNotFoundException
*/
function ezcontent_smart_podcast_submit_handler(array &$form, FormStateInterface $form_state) {
$text = '';
$entity = $form_state->getFormObject()->getEntity();
foreach ($entity->getFieldDefinitions() as $field_definition) {
if ($field_definition->getType() === 'ezcontent_smart_podcast') {
$field_name = $field_definition->getName();
$text_to_speech_fields = $field_definition->getSettings()['text_to_speech_fields'];
}
}
if (isset($field_name) && isset($text_to_speech_fields)) {
if ($entity->$field_name->convert_text_to_speech && empty($entity->$field_name->target_id)) {
$entity_type_id = $entity->getEntityTypeId();
$entity_id = $entity->id();
$default_display_fields = \Drupal::entityTypeManager()
->getStorage('entity_view_display')
->load($entity_type_id . '.' . $entity->bundle() . '.default')
->getComponents();
uasort($default_display_fields, function ($a, $b) {
if ($a['weight'] === $b['weight']) {
return 0;
}
return $a['weight'] < $b['weight'] ? -1 : 1;
});
$default_display_fields = array_keys($default_display_fields);
$text_to_speech_content_fields = array_filter($text_to_speech_fields['content']);
$text_to_speech_reference_fields = $text_to_speech_fields['paragraphs'];
foreach ($default_display_fields as $default_display_field) {
if (isset($text_to_speech_content_fields[$default_display_field])) {
if (isset($text_to_speech_reference_fields[$default_display_field])) {
if ($entity->$default_display_field->entity) {
foreach ($entity->$default_display_field->referencedEntities() as $ref_entity) {
if (in_array($ref_entity->getType(), array_keys($text_to_speech_reference_fields[$default_display_field]))) {
$text = $text . ' ' . ezcontent_smart_podcast_get_ref_text_to_speech_fields($ref_entity);
}
}
}
}
else {
if ($entity->$default_display_field->value) {
$stripped_value = strip_tags(trim($entity->$default_display_field->value));
if (!preg_match("/[.]$/", $stripped_value)) {
$stripped_value = $stripped_value . '.';
}
$text = $text . ' ' . $stripped_value;
}
}
}
}
$data['entity_type_id'] = $entity_type_id;
$data['entity_id'] = $entity_id;
$data['field_name'] = $field_name;
$data['text'] = $text;
// Use key value to record an entry for the node being queued for podcast
// creation.
$key_value = \Drupal::keyValue('text_to_speech_node');
// If key_value has an entry for the node, it means the node is already
// added into the queue for conversion, then fetch the corresponding
// queue item id and update the data in the queue.
if ($key_value->has($entity_id)) {
$item_id = $key_value->get($entity_id)['item_id'];
\Drupal::database()->update('queue')
->fields(['data' => serialize($data)])
->condition('name', 'text_to_speech_queue')
->condition('item_id', $item_id)
->execute();
}
// The current node is being queued for the first time, so post queue
// creation set the node id and the queue item id in the key_value.
else {
$queue = \Drupal::queue('text_to_speech_queue');
$item_id = $queue->createItem($data);
$key_value->set($entity_id, ['item_id' => $item_id]);
}
}
}
}
/**
* Helper function to fetch textual fields from given paragraph entity.
*
* @param object $entity
* Paragraph entity.
*
* @return string
* Text string from textual fields of the given entity.
*
* @throws \Drupal\Component\Plugin\Exception\InvalidPluginDefinitionException
* @throws \Drupal\Component\Plugin\Exception\PluginNotFoundException
*
* @todo Move to a service.
*/
function ezcontent_smart_podcast_get_ref_text_to_speech_fields($entity) {
$text = '';
$types = [
'string',
'string_long',
'text',
'text_default',
'text_long',
'text_with_summary',
'smart_text_with_summary',
];
$default_display_fields = \Drupal::entityTypeManager()
->getStorage('entity_view_display')
->load($entity->getEntityTypeId() . '.' . $entity->getType() . '.default')
->getComponents();
uasort($default_display_fields, function ($a, $b) {
if ($a['weight'] === $b['weight']) {
return 0;
}
return $a['weight'] < $b['weight'] ? -1 : 1;
});
foreach ($default_display_fields as $field => $value) {
$field_definition = $entity->getFieldDefinition($field);
$field_type = $field_definition->getType();
$field_name = $field_definition->getName();
if (in_array($field_type, $types)) {
if ($entity->$field_name->value) {
$stripped_value = strip_tags(trim($entity->$field_name->value));
if (!preg_match("/[.]$/", $stripped_value)) {
$stripped_value = $stripped_value . '.';
}
$text = $text . ' ' . $stripped_value;
}
}
if ($field_type === 'entity_reference_revisions') {
$ref_entity = $entity->$field_name->entity;
$text = $text . ' ' . ezcontent_smart_podcast_get_ref_text_to_speech_fields($ref_entity);
}
}
return $text;
}
/**
* Summary generator callback.
*
* @todo Move to a service.
*/
function ezcontent_smart_article_generate_callback(&$form, FormStateInterface $form_state) {
$results = \Drupal::service('ezcontent_smart_article.companies_list');
$company_name = $form_state->getValue('field_company_name')[0]['value'];
$text = $results->getData($company_name, 'article');
$response = new AjaxResponse();
$arguments = [$text, 'edit-body-0-value'];
$response->addCommand(new InvokeCommand(NULL, "update_text_editor", $arguments));
$response->addCommand(new InvokeCommand('.hide-body--field', 'show'));
return $response;
}
/**
* Summary generator callback.
*
* @todo Move to a service.
*/
function ezcontent_smart_summary_generate_callback(&$form, FormStateInterface $form_state) {
$generate_summary = \Drupal::service('ezcontent_smart_article.generate_summary');
$summary_type = $form_state->getValue('field_smart_text_summary')[0]['summary_container']['summary_type'];
$number_of_sentences = $form_state->getValue('field_smart_text_summary')[0]['summary_container']['number_of_sentences'];
$article = Html::decodeEntities(strip_tags($form_state->getValue('field_smart_text_summary')[0]['value']));
$text = Json::decode($generate_summary->generateSummary($article, $summary_type, $number_of_sentences));
$summary = $text['data']['data']['summary'];
$response = new AjaxResponse();
$arguments = [
$summary,
'edit-field-smart-text-summary-0-summary-container-summary-area',
];
$response->addCommand(new InvokeCommand(NULL, "update_summary_text", $arguments));
return $response;
}
/**
* Summary generator callback.
*
* @todo Move to a service.
*/
function update_summary_field_submit_handler(&$form, FormStateInterface $form_state) {
$entity = $form_state->getFormObject()->getEntity();
$summary = $form_state->getValue('field_smart_text_summary')[0]['summary_container']['summary_area'];
$entity->get('field_smart_text_summary')->summary = $summary;
$entity->save();
}
/**
* Implements hook_theme().
*/
function ezcontent_smart_article_theme($existing, $type, $theme, $path) {
return [
'smarttag_template' => [
'variables' => ['tags' => []],
],
'smart_article_get_subscription_landing_page' => [
'variables' => [],
],
'smart_article_invalid_subscription_popup' => [
'variables' => [],
],
'autocomplete_deluxe_smart_tags' => [
'variables' => ['tags' => []],
],
];
}