-
Notifications
You must be signed in to change notification settings - Fork 2
/
bynder_local.module
185 lines (157 loc) · 6.42 KB
/
bynder_local.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
<?php
use Drupal\bynder\Plugin\Field\FieldType\BynderMetadataItem;
use Drupal\bynder\Plugin\media\Source\Bynder;
use Drupal\Component\Serialization\Json;
use Drupal\Core\File\FileSystemInterface;
use Drupal\Core\Form\FormStateInterface;
use Drupal\media\MediaInterface;
use GuzzleHttp\Exception\ConnectException;
/**
* @file
* Hooks for the Bynder Local module.
*/
/**
* Implements hook_ENTITY_TYPE_presave() for media.
*/
function bynder_local_media_presave(MediaInterface $media) {
$source = $media->getSource();
if ($source instanceof Bynder && $media->hasField('field_bynder_image') && !$media->get('field_bynder_image')->entity) {
$source->ensureMetadata($media);
$item = Json::decode($media->get(BynderMetadataItem::METADATA_FIELD_NAME)->value);
$image_url = bynder_local_get_image_url($item);
if (!$image_url) {
\Drupal::logger('bynder_local')->warning('Missing asset for media @label (@id)', ['@label' => $media->label(), '@id' => $media->id()]);
return;
}
$field_definition = $media->getFieldDefinition('field_bynder_image');
$location = $field_definition->getFieldStorageDefinition()->getSetting('uri_scheme') . '://' . $field_definition->getSetting('file_directory');
$location = \Drupal::token()->replace($location);
\Drupal::service('file_system')->prepareDirectory($location, FileSystemInterface::CREATE_DIRECTORY | FileSystemInterface::MODIFY_PERMISSIONS);
if ($file = system_retrieve_file($image_url, $location, TRUE)) {
$media->set('field_bynder_image', $file);
}
}
}
/**
* Implements hook_ENTITY_TYPE_presave() for media.
*/
/**
* Implements hook_bynder_media_update_alter().
*/
function bynder_local_bynder_media_update_alter(MediaInterface $media, array $item, &$has_changed) {
$source = $media->getSource();
if ($source instanceof Bynder && $media->hasField('field_bynder_image')) {
$image_url = bynder_local_get_image_url($item);
if (!$image_url) {
\Drupal::logger('bynder_local')->warning('Missing asset for media @label (@id)', ['@label' => $media->label(), '@id' => $media->id()]);
return;
}
// Check the asset date, if it changed after the local file or if there is
// no local file, fetch it again.
if ($media->get('field_bynder_image')->entity) {
try {
$modified = new \DateTime($item['dateModified']);
if ($modified->getTimestamp() < $media->get('field_bynder_image')->entity->getCreatedTime()) {
return;
}
}
catch (\Exception $e) {
watchdog_exception('bynder_local', $e);
}
}
$field_definition = $media->getFieldDefinition('field_bynder_image');
$location = $field_definition->getFieldStorageDefinition()->getSetting('uri_scheme') . '://' . $field_definition->getSetting('file_directory');
$location = \Drupal::token()->replace($location);
\Drupal::service('file_system')->prepareDirectory($location, FileSystemInterface::CREATE_DIRECTORY | FileSystemInterface::MODIFY_PERMISSIONS);
if ($file = system_retrieve_file($image_url, $location, TRUE)) {
// If there already is a local file, mark it as temporary.
if ($media->get('field_bynder_image')->entity) {
$old_file = $media->get('field_bynder_image')->entity;
$old_file->setTemporary();
$old_file->save();
}
$media->set('field_bynder_image', $file);
$has_changed = TRUE;
}
}
}
/**
* Returns the image URL to download based on the configuration.
*
* @param array $item
* The raw asset information.
*
* @return string|null
* The image URL or NULL if it can't be fetched.
*/
function bynder_local_get_image_url(array $item) {
$config = \Drupal::config('bynder_local.settings');
if ($config->get('derivative') == 'original') {
return $item['original'] ?? NULL;
}
elseif ($config->get('derivative') == '_download') {
/** @var \Drupal\bynder\BynderApi $api */
$api = \Drupal::service('bynder_api');
try {
$response = $api->getAssetBankManager()->getMediaDownloadLocation($item['id'])->wait();
return $response['s3_file'];
}
catch (\Exception $e) {
watchdog_exception('bynder_local', $e);
}
}
else {
return $item['thumbnails'][$config->get('derivative')] ?? NULL;
}
}
/**
* Implements hook_form_FORM_ID_alter().
*/
function bynder_local_form_bynder_configuration_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state) {
$field_map = \Drupal::service('entity_field.manager')->getFieldMap();
try {
$derivatives = array_merge(array_map(function ($item) {
return $item['prefix'];
}, \Drupal::service('bynder_api')->getDerivatives()),
['mini', 'webimage', 'thul', 'original']
);
$derivatives = array_combine($derivatives, $derivatives);
$derivatives['_download'] = t('Download through API');
}
catch (ConnectException $e) {
$derivatives = [];
}
$form['bynder_local'] = [
'#type' => 'details',
'#title' => 'Local assets',
'#open' => TRUE,
];
if (empty($field_map['media']['field_bynder_image']['bundles'])) {
$form['bynder_local']['#description'] = t('The Field "field_bynder_image" has not been added to any media types, this functionality is not active.');
}
else {
$labels = [];
$bundles = \Drupal::service('entity_type.bundle.info')->getBundleInfo('media');
foreach ($field_map['media']['field_bynder_image']['bundles'] as $bundle) {
$labels[] = $bundles[$bundle]['label'];
}
$form['bynder_local']['#description'] = t('The following media types are storing a local asset: @labels.', ['@labels' => implode(', ', $labels)]);
}
$config = \Drupal::configFactory()->getEditable('bynder_local.settings');
$form['bynder_local']['local_derivative'] = [
'#type' => 'select',
'#title' => t('Derivative to store as local asset'),
'#options' => $derivatives,
'#default_value' => $config->get('derivative'),
'#description' => t('This should be a very large derivative, or the original. Note that the original only works on public assets. API Download allows to fetch an updated asset immediately after the change but might require extra permissions.'),
];
$form['#submit'][] = 'bynder_local_settings_submit';
}
/**
* Form submit callback.
*/
function bynder_local_settings_submit($form, FormStateInterface $form_state) {
$config = \Drupal::configFactory()->getEditable('bynder_local.settings');
$config->set('derivative', $form_state->getValue('local_derivative'));
$config->save();
}