forked from UoEMainLibrary/DSpace
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathRequestItemEmailNotifier.java
More file actions
381 lines (338 loc) · 15.4 KB
/
Copy pathRequestItemEmailNotifier.java
File metadata and controls
381 lines (338 loc) · 15.4 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
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
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
/**
* The contents of this file are subject to the license and copyright
* detailed in the LICENSE and NOTICE files at the root of the source
* tree and available online at
*
* http://www.dspace.org/license/
*/
package org.dspace.app.requestitem;
import java.io.IOException;
import java.sql.SQLException;
import java.util.List;
import jakarta.annotation.ManagedBean;
import jakarta.inject.Inject;
import jakarta.inject.Singleton;
import jakarta.mail.MessagingException;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.dspace.app.requestitem.service.RequestItemService;
import org.dspace.authorize.AuthorizeException;
import org.dspace.content.Bitstream;
import org.dspace.content.Bundle;
import org.dspace.content.Item;
import org.dspace.content.factory.ContentServiceFactory;
import org.dspace.content.service.BitstreamService;
import org.dspace.content.service.ItemService;
import org.dspace.core.Context;
import org.dspace.core.Email;
import org.dspace.core.I18nUtil;
import org.dspace.core.LogHelper;
import org.dspace.eperson.EPerson;
import org.dspace.handle.service.HandleService;
import org.dspace.services.ConfigurationService;
/**
* Send item requests and responses by email.
*
* <p>
* The "strategy" by which approvers are chosen is in an implementation of
* {@link RequestItemAuthorExtractor} which is injected by the name
* {@code requestItemAuthorExtractor}. See the DI configuration documents.
*
* @author Mark H. Wood <mwood@iupui.edu>
*/
@Singleton
@ManagedBean
public class RequestItemEmailNotifier {
private static final Logger LOG = LogManager.getLogger();
@Inject
protected BitstreamService bitstreamService;
@Inject
protected ConfigurationService configurationService;
@Inject
protected HandleService handleService;
@Inject
protected RequestItemService requestItemService;
protected final RequestItemAuthorExtractor requestItemAuthorExtractor;
// DATASHARE - start
private static final String ITEM_NOT_EMAILABLE_METADATA_TAG = "ds.not-emailable.item";
private static final String BITSTREAM_NOT_EMAILABLE_METADATA_TAG = "ds.not-emailable.bitstream";
protected ItemService itemService = ContentServiceFactory.getInstance().getItemService();
// DATASHARE - end
@Inject
public RequestItemEmailNotifier(RequestItemAuthorExtractor requestItemAuthorExtractor) {
this.requestItemAuthorExtractor = requestItemAuthorExtractor;
}
/**
* Send the request to the approver(s).
*
* @param context current DSpace session.
* @param ri the request.
* @param responseLink link back to DSpace to send the response.
* @throws IOException passed through.
* @throws SQLException if the message was not sent.
*/
public void sendRequest(Context context, RequestItem ri, String responseLink)
throws IOException, SQLException {
// Who is making this request?
List<RequestItemAuthor> authors = requestItemAuthorExtractor
.getRequestItemAuthor(context, ri.getItem());
// DATASHARE - start
// Build an email to the approver.
Email email;
if (isRequestItemEmailable(context, ri)) {
email = Email.getEmail(I18nUtil.getEmailFilename(context.getCurrentLocale(),
"request_item.author"));
} else {
email = Email.getEmail(I18nUtil.getEmailFilename(context.getCurrentLocale(),
"request_item.not_emailable.author"));
}
// DATASHARE - end
for (RequestItemAuthor author : authors) {
email.addRecipient(author.getEmail());
}
email.setReplyTo(ri.getReqEmail()); // Requester's address
email.addArgument(ri.getReqName()); // {0} Requester's name
email.addArgument(ri.getReqEmail()); // {1} Requester's address
email.addArgument(ri.isAllfiles() // {2} All bitstreams or just one?
? I18nUtil.getMessage("itemRequest.all")
: ri.getBitstream().getName());
email.addArgument(handleService.getCanonicalForm(ri.getItem().getHandle())); // {3}
email.addArgument(ri.getItem().getName()); // {4} requested item's title
email.addArgument(ri.getReqMessage()); // {5} message from requester
email.addArgument(responseLink); // {6} Link back to DSpace for action
StringBuilder names = new StringBuilder();
StringBuilder addresses = new StringBuilder();
for (RequestItemAuthor author : authors) {
if (names.length() > 0) {
names.append("; ");
addresses.append("; ");
}
names.append(author.getFullName());
addresses.append(author.getEmail());
}
email.addArgument(names.toString()); // {7} corresponding author name
email.addArgument(addresses.toString()); // {8} corresponding author email
email.addArgument(configurationService.getProperty("dspace.name")); // {9}
email.addArgument(configurationService.getProperty("mail.helpdesk")); // {10}
// Send the email.
try {
email.send();
Bitstream bitstream = ri.getBitstream();
String bitstreamID;
if (null == bitstream) {
bitstreamID = "null";
} else {
bitstreamID = ri.getBitstream().getID().toString();
}
LOG.info(LogHelper.getHeader(context,
"sent_email_requestItem",
"submitter_id={},bitstream_id={},requestEmail={}"),
ri.getReqEmail(), bitstreamID, ri.getReqEmail());
} catch (MessagingException e) {
LOG.warn(LogHelper.getHeader(context,
"error_mailing_requestItem", e.getMessage()));
throw new IOException("Request not sent: " + e.getMessage());
}
}
/**
* Send the approver's response back to the requester, with files attached
* if approved.
*
* @param context current DSpace session.
* @param ri the request.
* @param subject email subject header value.
* @param message email body (may be empty).
* @throws IOException if sending failed.
*/
public void sendResponse(Context context, RequestItem ri, String subject,
String message)
throws IOException {
// Who granted this request?
List<RequestItemAuthor> grantors;
try {
grantors = requestItemAuthorExtractor.getRequestItemAuthor(context, ri.getItem());
} catch (SQLException e) {
LOG.warn("Failed to get grantor's name and address: {}", e.getMessage());
grantors = List.of();
}
String grantorName;
String grantorAddress;
if (grantors.isEmpty()) {
grantorName = configurationService.getProperty("mail.admin.name");
grantorAddress = configurationService.getProperty("mail.admin");
} else {
RequestItemAuthor grantor = grantors.get(0); // XXX Cannot know which one
grantorName = grantor.getFullName();
grantorAddress = grantor.getEmail();
}
// Build an email back to the requester.
Email email = Email.getEmail(I18nUtil.getEmailFilename(context.getCurrentLocale(),
ri.isAccept_request() ? "request_item.granted" : "request_item.rejected"));
email.addArgument(ri.getReqName()); // {0} requestor's name
email.addArgument(handleService.getCanonicalForm(ri.getItem().getHandle())); // {1} URL of the requested Item
email.addArgument(ri.getItem().getName()); // {2} title of the requested Item
email.addArgument(grantorName); // {3} name of the grantor
email.addArgument(grantorAddress); // {4} email of the grantor
email.addArgument(message); // {5} grantor's optional message
email.setSubject(subject);
email.addRecipient(ri.getReqEmail());
// Attach bitstreams.
try {
if (ri.isAccept_request()) {
if (ri.isAllfiles()) {
Item item = ri.getItem();
List<Bundle> bundles = item.getBundles("ORIGINAL");
for (Bundle bundle : bundles) {
List<Bitstream> bitstreams = bundle.getBitstreams();
for (Bitstream bitstream : bitstreams) {
if (!bitstream.getFormat(context).isInternal() &&
requestItemService.isRestricted(context,
bitstream)) {
// #8636 Anyone receiving the email can respond to the
// request without authenticating into DSpace
context.turnOffAuthorisationSystem();
email.addAttachment(
bitstreamService.retrieve(context, bitstream),
bitstream.getName(),
bitstream.getFormat(context).getMIMEType());
context.restoreAuthSystemState();
}
}
}
} else {
Bitstream bitstream = ri.getBitstream();
// #8636 Anyone receiving the email can respond to the request without
// authenticating into DSpace
context.turnOffAuthorisationSystem();
email.addAttachment(bitstreamService.retrieve(context, bitstream),
bitstream.getName(),
bitstream.getFormat(context).getMIMEType());
context.restoreAuthSystemState();
}
email.send();
} else {
boolean sendRejectEmail = configurationService
.getBooleanProperty("request.item.reject.email", true);
// Not all sites want the "refusal" to be sent back to the requester via
// email. However, by default, the rejection email is sent back.
if (sendRejectEmail) {
email.send();
}
}
} catch (MessagingException | IOException | SQLException | AuthorizeException e) {
LOG.warn(LogHelper.getHeader(context,
"error_mailing_requestItem", e.getMessage()));
throw new IOException("Reply not sent: " + e.getMessage());
}
LOG.info(LogHelper.getHeader(context,
"sent_attach_requestItem", "token={}"), ri.getToken());
}
/**
* Send, to a repository administrator, a request to open access to a
* requested object.
*
* @param context current DSpace session
* @param ri the item request that the approver is handling
* @throws IOException if the message body cannot be loaded or the message
* cannot be sent.
*/
public void requestOpenAccess(Context context, RequestItem ri)
throws IOException {
Email message = Email.getEmail(I18nUtil.getEmailFilename(context.getCurrentLocale(),
"request_item.admin"));
// Which Bitstream(s) requested?
Bitstream bitstream = ri.getBitstream();
String bitstreamName;
if (bitstream != null) {
bitstreamName = bitstream.getName();
} else {
bitstreamName = "all"; // TODO localize
}
// Which Item?
Item item = ri.getItem();
// Fill the message's placeholders.
EPerson approver = context.getCurrentUser();
message.addArgument(bitstreamName); // {0} bitstream name or "all"
message.addArgument(item.getHandle()); // {1} Item handle
message.addArgument(ri.getToken()); // {2} Request token
if (approver != null) {
message.addArgument(approver.getFullName()); // {3} Approver's name
message.addArgument(approver.getEmail()); // {4} Approver's address
} else {
message.addArgument("anonymous approver"); // [3] Approver's name
message.addArgument(configurationService.getProperty("mail.admin")); // [4] Approver's address
}
// Who gets this message?
String recipient;
EPerson submitter = item.getSubmitter();
if (submitter != null) {
recipient = submitter.getEmail();
} else {
recipient = configurationService.getProperty("mail.helpdesk");
}
if (null == recipient) {
recipient = configurationService.getProperty("mail.admin");
}
message.addRecipient(recipient);
// Send the message.
try {
message.send();
} catch (MessagingException ex) {
LOG.warn(LogHelper.getHeader(context, "error_mailing_requestItem",
ex.getMessage()));
throw new IOException("Open Access request not sent: " + ex.getMessage());
}
}
// DATASHARE - start
/**
* Checks if requested item is emailable based on size constraints.
* Items/bitstreams larger than the configured maximum size emailable.bitstreams.max.size MB
* will not be emailed.
*
* @param context DSpace context
* @param ri The request item
* @return true if the item can be emailed, false otherwise
*/
private boolean isRequestItemEmailable(Context context, RequestItem ri) {
// Get maximum emailable size from configuration (default 50MB)
long maxEmailableSizeInBytes = configurationService.getLongProperty(
"emailable.bitstreams.max.size", 32) * 1048576; // Convert MB to bytes
try {
if (ri.isAllfiles()) {
// Check total size of all bitstreams in ORIGINAL bundle
List<Bundle> bundles = ri.getItem().getBundles("ORIGINAL");
long totalSizeInBytes = 0;
for (Bundle bundle : bundles) {
for (Bitstream bitstream : bundle.getBitstreams()) {
totalSizeInBytes += bitstream.getSizeBytes();
// If we exceed the size limit at any point, return false
if (totalSizeInBytes > maxEmailableSizeInBytes) {
LOG.info("Request item not emailable - all files exceed size limit of {} bytes",
maxEmailableSizeInBytes);
return false;
}
}
}
return true;
} else {
// Check size of single requested bitstream
Bitstream bitstream = ri.getBitstream();
if (bitstream != null) {
long bitstreamSize = bitstream.getSizeBytes();
if (bitstreamSize > maxEmailableSizeInBytes) {
LOG.info("Request item not emailable - bitstream {} exceeds size limit of {} bytes",
bitstream.getName(), maxEmailableSizeInBytes);
return false;
}
return true;
}
}
} catch (Exception e) {
// Log the actual exception for debugging purposes
LOG.warn("Error checking if request item is emailable", e);
}
// Default to true if we couldn't determine the size or no bitstreams found
return true;
}
// DATASHARE - end
}