-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathadapt.module
More file actions
298 lines (247 loc) · 8.98 KB
/
adapt.module
File metadata and controls
298 lines (247 loc) · 8.98 KB
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
<?php
use Drupal\Core\Entity\EntityInterface;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\Batch\BatchBuilder;
use Drupal\node\NodeInterface;
use Drupal\Core\StringTranslation\StringTranslationTrait;
/**
* Batch operation: Update a node from csv.
* Updates nodes from a CSV
*/
// function adapt_cron()
// {
// // Path to the CSV file.
// $csv_file_path = 'public://adapt_ids.csv';
// // Load the CSV file.
// $file_contents = file_get_contents($csv_file_path);
// // Parse the CSV file.
// $csv_data = str_getcsv($file_contents, "\n");
// // Loop through each row in the CSV data.
// foreach ($csv_data as $row) {
// $rowData = str_getcsv($row);
// // Check if the row contains all expected values.
// if (count($rowData) >= 3) {
// list($h5p_id, $email, $adapt_question_id) = $rowData;
// // Extract data from the CSV row.
// //list($h5p_id, $email, $adapt_question_id) = str_getcsv($row);
// // Load the node based on the h5p_id.
// $query = \Drupal::database()->select('node__field_h5p', 'nfhp');
// $query->fields('nfhp', ['entity_id']);
// $query->condition('nfhp.field_h5p_h5p_content_id', $h5p_id);
// $nid = $query->execute()->fetchField();
// // Check if the node exists.
// if ($nid) {
// // Update the node's field_adapt_id.
// $node = \Drupal::entityTypeManager()->getStorage('node')->load($nid);
// $node->set('field_adapt_id', $adapt_question_id);
// $node->save();
// \Drupal::logger('adapt_csv_update')->info('Updated field_adapt_id_value to @aid for h5p_id @h5p_id (nid: @nid)', [
// '@h5p_id' => $h5p_id,
// '@nid' => $nid,
// '@aid' => $adapt_question_id,
// ]);
// } else {
// \Drupal::logger('adapt_csv_update')->error('Record not found for h5p_id @h5p_id in node__field_h5p', [
// '@h5p_id' => $h5p_id,
// ]);
// }
// // Your existing code to process the row goes here...
// } else {
// \Drupal::logger('adapt_csv_update')->error('Invalid CSV row: @row', [
// '@row' => $row,
// ]);
// }
// }
// }
/**
* Implements hook_cron().
*/
function adapt_cron() {
// Load the node storage.
$node_storage = \Drupal::entityTypeManager()->getStorage('node');
// Retrieve the token.
$token = fetchToken();
// Get nodes that do not have a value for the field_adapt_id field.
$query = $node_storage->getQuery()
->condition('type', 'h5p')
->condition('field_adapt_id', NULL, 'IS NULL')
->range(0, 50) // Process 50 nodes per cron run.
->sort('changed','DESC');
$nids = $query->execute();
if (!empty($nids)) {
foreach ($nids as $nid) {
// Load the node.
$node = $node_storage->load($nid);
// H5P Content Id
$h5p_id = $node->get('field_h5p')->getValue()[0]['h5p_content_id'];
$request_body = [
'email' => 'yasin@libretexts.org',
];
if ($h5p_id) {
$api_url = 'https://adapt.libretexts.org/api/h5p-collections/get-adapt-question-id-by-h5p-id/' . $h5p_id;
// Make API request to fetch data.
try {
$response = \Drupal::httpClient()->request('PATCH', $api_url, [
'headers' => [
'Authorization' => 'Bearer ' . $token,
],
'json' => $request_body,
]);
// Process API response and update node field.
$data = json_decode($response->getBody(), TRUE);
if (!empty($data['adapt_question_id'])) {
// Update node field field_adapt_id with the API response.
$node->set('field_adapt_id', $data['adapt_question_id']);
$node->save();
\Drupal::logger('adapt')->info('Processed node ID @nid.', [
'@nid' => $nid,
]);
}
} catch (\Exception $e) {
// Log any errors.
\Drupal::logger('adapt')->error('An error occurred while updating field_adapt_id for node ID @nid: @message', [
'@nid' => $nid,
'@message' => $e->getMessage(),
]);
}
}
}
}
// // if (!empty($nids)) {
// // // Define batch operations.
// // $batch = array(
// // 'title' => \Drupal::translation()->translate('Updating Adapt IDs...'),
// // 'operations' => array(),
// // 'init_message' => \Drupal::translation()->translate('Starting to update Adapt IDs.'),
// // 'progress_message' => \Drupal::translation()->translate('Processed @current out of @total nodes.'),
// // 'error_message' => \Drupal::translation()->translate('An error occurred during node update.'),
// // 'finished' => 'adapt_cron_finished',
// // );
// // foreach ($nids as $nid) {
// // $batch['operations'][] = array('adapt_cron_update_node', array($nid));
// // }
// // // Start the batch process.
// // batch_set($batch);
// // }
}
/**
* Batch operation: Update a node.
*/
function adapt_cron_update_node($nid, &$context) {
$node = \Drupal\node\Entity\Node::load($nid);
if ($node) {
$h5p_id = $node->get('field_h5p')->getValue()[0]['h5p_content_id'];
// Retrieve the token.
/** ToDo:
* We shouldn't fetch token for each node. Move this process up.
*/
$token = fetchToken();
// Construct API URL with the H5P ID as a parameter.
$api_url = 'https://adapt.libretexts.org/api/h5p-collections/get-adapt-question-id-by-h5p-id/' . $h5p_id;
// Make API request to fetch data.
try {
$response = \Drupal::httpClient()->get($api_url, [
'headers' => [
'Authorization' => 'Bearer ' . $token,
],
]);
// Process API response and update node field.
$data = json_decode($response->getBody(), TRUE);
if (!empty($data['adapt_question_id'])) {
// Update node field field_adapt_id with the API response.
$node->set('field_adapt_id', $data['adapt_question_id']);
$node->save();
\Drupal::logger('adapt')->info('Processed node ID @nid.', [
'@nid' => $nid,
]);
}
} catch (\Exception $e) {
// Log any errors.
\Drupal::logger('adapt')->error('An error occurred while updating field_adapt_id for node ID @nid: @message', [
'@nid' => $nid,
'@message' => $e->getMessage(),
]);
}
}
}
/**
* Batch finished callback.
*/
function adapt_cron_finished($success, $results, $operations) {
if ($success) {
\Drupal::logger('adapt')->info('Batch processing completed successfully.');
}
else {
\Drupal::logger('adapt')->error('An error occurred during batch processing.');
}
}
/**
* Implements hook_ENTITY_TYPE_update() for nodes.
* No longer needed as updating field on node_presave doesn't make sense.
*/
/*
function adapt_node_presave(EntityInterface $entity) {
if ($entity instanceof NodeInterface) {
// Check if the node type is the one you want to update.
if ($entity->bundle() === 'h5p') {
//$h5p_id = $node->field_h5p->getValue()[0]['h5p_content_id'];
$h5p_id = $entity->get('field_h5p')->getValue()[0]['h5p_content_id'];
if (!empty($h5p_id)) {
$token = fetchToken();
// Construct API URL with the H5P ID as a parameter.
$api_url = 'https://adapt.libretexts.org/api/h5p-collections/get-adapt-question-id-by-h5p-id/' . $h5p_id;
// Make API request to fetch data.
try {
$response = \Drupal::httpClient()->get($api_url, [
'headers' => [
'Authorization' => 'Bearer ' . $token,
],
]);
// Process API response and update node field.
$data = json_decode($response->getBody(), TRUE);
if (!empty($data['adapt_question_id'])) {
// Update node field field_adapt_id with the API response.
// $entity->get('field_adapt_id')->setValue($data['adapt_question_id']);
// $entity->save();
$entity->set('field_adapt_id', $data['adapt_question_id']);
}
\Drupal::logger('adapt')->info('processed @nid: @message', [
'@nid' => $entity->id()
]);
} catch (\Exception $e) {
// Log any errors.
\Drupal::logger('adapt')->error('An error occurred while updating field_adapt_id for node @nid: @message', [
'@nid' => $entity->id(),
'@message' => $e->getMessage(),
]);
}
}
}
}
}
*/
/**
* Fetches authentication token from the Key module.
*
* @return string|null
* The authentication token, or NULL if not found.
*/
function fetchToken() {
try {
// Load the key.
$key_id = 'adapt_id';
$key = \Drupal::service('key.repository')->getKey($key_id);
// Check if the key exists and is valid.
if ($key && $key->getKeyValue()) {
return $key->getKeyValue();
} else {
return NULL;
}
} catch (\Exception $e) {
// Log error: Unable to load key.
\Drupal::logger('adapt')->error('Error loading key: @message', [
'@message' => $e->getMessage(),
]);
return NULL;
}
}