-
Notifications
You must be signed in to change notification settings - Fork 228
/
IngestServiceImpl.java
1915 lines (1734 loc) · 79.3 KB
/
IngestServiceImpl.java
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
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* Licensed to The Apereo Foundation under one or more contributor license
* agreements. See the NOTICE file distributed with this work for additional
* information regarding copyright ownership.
*
*
* The Apereo Foundation licenses this file to you under the Educational
* Community License, Version 2.0 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of the License
* at:
*
* http://opensource.org/licenses/ecl2.txt
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*
*/
package org.opencastproject.ingest.impl;
import static org.apache.commons.lang3.StringUtils.isBlank;
import static org.opencastproject.util.JobUtil.waitForJob;
import static org.opencastproject.util.data.Monadics.mlist;
import static org.opencastproject.util.data.Option.none;
import org.opencastproject.capture.CaptureParameters;
import org.opencastproject.ingest.api.IngestException;
import org.opencastproject.ingest.api.IngestService;
import org.opencastproject.ingest.impl.jmx.IngestStatistics;
import org.opencastproject.inspection.api.MediaInspectionService;
import org.opencastproject.job.api.AbstractJobProducer;
import org.opencastproject.job.api.Job;
import org.opencastproject.job.api.Job.Status;
import org.opencastproject.mediapackage.EName;
import org.opencastproject.mediapackage.MediaPackage;
import org.opencastproject.mediapackage.MediaPackageBuilderFactory;
import org.opencastproject.mediapackage.MediaPackageElement;
import org.opencastproject.mediapackage.MediaPackageElementFlavor;
import org.opencastproject.mediapackage.MediaPackageElementParser;
import org.opencastproject.mediapackage.MediaPackageElements;
import org.opencastproject.mediapackage.MediaPackageException;
import org.opencastproject.mediapackage.MediaPackageParser;
import org.opencastproject.mediapackage.MediaPackageSupport;
import org.opencastproject.mediapackage.Track;
import org.opencastproject.mediapackage.identifier.IdImpl;
import org.opencastproject.metadata.dublincore.DCMIPeriod;
import org.opencastproject.metadata.dublincore.DublinCore;
import org.opencastproject.metadata.dublincore.DublinCoreCatalog;
import org.opencastproject.metadata.dublincore.DublinCoreCatalogService;
import org.opencastproject.metadata.dublincore.DublinCoreValue;
import org.opencastproject.metadata.dublincore.EncodingSchemeUtils;
import org.opencastproject.scheduler.api.SchedulerException;
import org.opencastproject.scheduler.api.SchedulerService;
import org.opencastproject.security.api.OrganizationDirectoryService;
import org.opencastproject.security.api.SecurityService;
import org.opencastproject.security.api.TrustedHttpClient;
import org.opencastproject.security.api.UnauthorizedException;
import org.opencastproject.security.api.UserDirectoryService;
import org.opencastproject.series.api.SeriesService;
import org.opencastproject.serviceregistry.api.ServiceRegistry;
import org.opencastproject.serviceregistry.api.ServiceRegistryException;
import org.opencastproject.smil.api.util.SmilUtil;
import org.opencastproject.util.ConfigurationException;
import org.opencastproject.util.IoSupport;
import org.opencastproject.util.LoadUtil;
import org.opencastproject.util.MimeTypes;
import org.opencastproject.util.NotFoundException;
import org.opencastproject.util.ProgressInputStream;
import org.opencastproject.util.XmlSafeParser;
import org.opencastproject.util.XmlUtil;
import org.opencastproject.util.data.Function;
import org.opencastproject.util.data.Option;
import org.opencastproject.util.data.functions.Misc;
import org.opencastproject.util.jmx.JmxUtil;
import org.opencastproject.workflow.api.WorkflowDatabaseException;
import org.opencastproject.workflow.api.WorkflowDefinition;
import org.opencastproject.workflow.api.WorkflowException;
import org.opencastproject.workflow.api.WorkflowInstance;
import org.opencastproject.workflow.api.WorkflowService;
import org.opencastproject.workingfilerepository.api.WorkingFileRepository;
import com.entwinemedia.fn.Stream;
import com.entwinemedia.fn.data.Opt;
import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import org.apache.commons.compress.archivers.zip.ZipArchiveEntry;
import org.apache.commons.compress.archivers.zip.ZipArchiveInputStream;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.BooleanUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.cxf.jaxrs.ext.multipart.ContentDisposition;
import org.apache.http.Header;
import org.apache.http.HttpResponse;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.client.config.AuthSchemes;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.osgi.service.cm.ManagedService;
import org.osgi.service.component.ComponentContext;
import org.osgi.service.component.annotations.Activate;
import org.osgi.service.component.annotations.Component;
import org.osgi.service.component.annotations.Deactivate;
import org.osgi.service.component.annotations.Reference;
import org.osgi.service.component.annotations.ReferenceCardinality;
import org.osgi.service.component.annotations.ReferencePolicy;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.xml.sax.SAXException;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URI;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.Date;
import java.util.Dictionary;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Objects;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import javax.management.ObjectInstance;
/**
* Creates and augments Opencast MediaPackages. Stores media into the Working File Repository.
*/
@Component(
immediate = true,
service = {
IngestService.class,
ManagedService.class
},
property = {
"service.description=Ingest Service",
"service.pid=org.opencastproject.ingest.impl.IngestServiceImpl"
}
)
public class IngestServiceImpl extends AbstractJobProducer implements IngestService, ManagedService {
/** The logger */
private static final Logger logger = LoggerFactory.getLogger(IngestServiceImpl.class);
/** The source SMIL name */
private static final String PARTIAL_SMIL_NAME = "source_partial.smil";
/** The configuration key that defines the default workflow definition */
protected static final String WORKFLOW_DEFINITION_DEFAULT = "org.opencastproject.workflow.default.definition";
/** The workflow configuration property prefix **/
protected static final String WORKFLOW_CONFIGURATION_PREFIX = "org.opencastproject.workflow.config.";
/** The key for the legacy mediapackage identifier */
public static final String LEGACY_MEDIAPACKAGE_ID_KEY = "org.opencastproject.ingest.legacy.mediapackage.id";
public static final String JOB_TYPE = "org.opencastproject.ingest";
/** Methods that ingest zips create jobs with this operation type */
public static final String INGEST_ZIP = "zip";
/** Methods that ingest tracks directly create jobs with this operation type */
public static final String INGEST_TRACK = "track";
/** Methods that ingest tracks from a URI create jobs with this operation type */
public static final String INGEST_TRACK_FROM_URI = "uri-track";
/** Methods that ingest attachments directly create jobs with this operation type */
public static final String INGEST_ATTACHMENT = "attachment";
/** Methods that ingest attachments from a URI create jobs with this operation type */
public static final String INGEST_ATTACHMENT_FROM_URI = "uri-attachment";
/** Methods that ingest catalogs directly create jobs with this operation type */
public static final String INGEST_CATALOG = "catalog";
/** Methods that ingest catalogs from a URI create jobs with this operation type */
public static final String INGEST_CATALOG_FROM_URI = "uri-catalog";
/** The approximate load placed on the system by ingesting a file */
public static final float DEFAULT_INGEST_FILE_JOB_LOAD = 0.2f;
/** The approximate load placed on the system by ingesting a zip file */
public static final float DEFAULT_INGEST_ZIP_JOB_LOAD = 0.2f;
/** The key to look for in the service configuration file to override the {@link DEFAULT_INGEST_FILE_JOB_LOAD} */
public static final String FILE_JOB_LOAD_KEY = "job.load.ingest.file";
/** The key to look for in the service configuration file to override the {@link DEFAULT_INGEST_ZIP_JOB_LOAD} */
public static final String ZIP_JOB_LOAD_KEY = "job.load.ingest.zip";
/** The source to download from */
public static final String DOWNLOAD_SOURCE = "org.opencastproject.download.source";
/** The user for download from external sources */
public static final String DOWNLOAD_USER = "org.opencastproject.download.user";
/** The password for download from external sources */
public static final String DOWNLOAD_PASSWORD = "org.opencastproject.download.password";
/** By default, do not allow event ingest to modify existing series metadata */
public static final boolean DEFAULT_ALLOW_SERIES_MODIFICATIONS = false;
/** The default is to preserve existing Opencast flavors during ingest. */
public static final boolean DEFAULT_ALLOW_ONLY_NEW_FLAVORS = true;
/** The default is not to automatically skip attachments and catalogs from capture agent */
public static final boolean DEFAULT_SKIP = false;
/** The maximum length of filenames ingested by Opencast */
public static final int FILENAME_LENGTH_MAX = 75;
/** Managed Property key to allow Opencast series modification during ingest
* Deprecated, the param potentially causes an update chain reaction for all
* events associated to that series, for each ingest */
@Deprecated
public static final String MODIFY_OPENCAST_SERIES_KEY = "org.opencastproject.series.overwrite";
/** Managed Property key to allow new flavors of ingested attachments and catalogs
* to be added to the existing Opencast mediapackage. But, not catalogs and attachments
* that would overwrite existing ones in Opencast.
*/
public static final String ADD_ONLY_NEW_FLAVORS_KEY = "add.only.new.catalogs.attachments.for.existing.events";
/** Control if catalogs sent by capture agents for scheduled events are skipped. */
public static final String SKIP_CATALOGS_KEY = "skip.catalogs.for.existing.events";
/** Control if attachments sent by capture agents for scheduled events are skipped. */
public static final String SKIP_ATTACHMENTS_KEY = "skip.attachments.for.existing.events";
/** The approximate load placed on the system by ingesting a file */
private float ingestFileJobLoad = DEFAULT_INGEST_FILE_JOB_LOAD;
/** The approximate load placed on the system by ingesting a zip file */
private float ingestZipJobLoad = DEFAULT_INGEST_ZIP_JOB_LOAD;
/** The user for download from external sources */
private static String downloadUser = DOWNLOAD_USER;
/** The password for download from external sources */
private static String downloadPassword = DOWNLOAD_PASSWORD;
/** The external source dns name */
private static String downloadSource = DOWNLOAD_SOURCE;
/** The JMX business object for ingest statistics */
private IngestStatistics ingestStatistics = new IngestStatistics();
/** The JMX bean object instance */
private ObjectInstance registerMXBean;
/** The workflow service */
private WorkflowService workflowService;
/** The working file repository */
private WorkingFileRepository workingFileRepository;
/** The http client */
private TrustedHttpClient httpClient;
/** The series service */
private SeriesService seriesService;
/** The dublin core service */
private DublinCoreCatalogService dublinCoreService;
/** The opencast service registry */
private ServiceRegistry serviceRegistry;
/** The security service */
protected SecurityService securityService = null;
/** The user directory service */
protected UserDirectoryService userDirectoryService = null;
/** The organization directory service */
protected OrganizationDirectoryService organizationDirectoryService = null;
/** The scheduler service */
private SchedulerService schedulerService = null;
/** The media inspection service */
private MediaInspectionService mediaInspectionService = null;
/** The default workflow identifier, if one is configured */
protected String defaultWorkflowDefinionId;
/** The partial track start time map */
private Cache<String, Long> partialTrackStartTimes = CacheBuilder.newBuilder().expireAfterWrite(1, TimeUnit.DAYS)
.build();
/** Option to overwrite matching flavors (e.g. series and episode metadata) on ingest,
* tracks are always taken on ingest */
protected boolean isAddOnlyNew = DEFAULT_ALLOW_ONLY_NEW_FLAVORS;
protected boolean isAllowModifySeries = DEFAULT_ALLOW_SERIES_MODIFICATIONS;
private boolean skipCatalogs = DEFAULT_SKIP;
private boolean skipAttachments = DEFAULT_SKIP;
/**
* Creates a new ingest service instance.
*/
public IngestServiceImpl() {
super(JOB_TYPE);
}
/**
* OSGI callback for activating this component
*
* @param cc
* the osgi component context
*/
@Override
@Activate
public void activate(ComponentContext cc) {
super.activate(cc);
logger.info("Ingest Service started.");
defaultWorkflowDefinionId = StringUtils.trimToNull(cc.getBundleContext().getProperty(WORKFLOW_DEFINITION_DEFAULT));
if (defaultWorkflowDefinionId == null) {
defaultWorkflowDefinionId = "schedule-and-upload";
}
registerMXBean = JmxUtil.registerMXBean(ingestStatistics, "IngestStatistics");
}
/**
* Callback from OSGi on service deactivation.
*/
@Deactivate
public void deactivate() {
JmxUtil.unregisterMXBean(registerMXBean);
}
/**
* {@inheritDoc}
*
* @see org.osgi.service.cm.ManagedService#updated(java.util.Dictionary)
* Retrieve ManagedService configuration, including option to overwrite series
*/
@Override
public void updated(Dictionary<String, ?> properties) throws ConfigurationException {
if (properties == null) {
logger.info("No configuration available, using defaults");
return;
}
downloadPassword = StringUtils.trimToEmpty((String)properties.get(DOWNLOAD_PASSWORD));
downloadUser = StringUtils.trimToEmpty(((String) properties.get(DOWNLOAD_USER)));
downloadSource = StringUtils.trimToEmpty(((String) properties.get(DOWNLOAD_SOURCE)));
skipAttachments = BooleanUtils.toBoolean(Objects.toString(properties.get(SKIP_ATTACHMENTS_KEY),
BooleanUtils.toStringTrueFalse(DEFAULT_SKIP)));
skipCatalogs = BooleanUtils.toBoolean(Objects.toString(properties.get(SKIP_CATALOGS_KEY),
BooleanUtils.toStringTrueFalse(DEFAULT_SKIP)));
logger.debug("Skip attachments sent by agents for scheduled events: {}", skipAttachments);
logger.debug("Skip metadata catalogs sent by agents for scheduled events: {}", skipCatalogs);
ingestFileJobLoad = LoadUtil.getConfiguredLoadValue(properties, FILE_JOB_LOAD_KEY, DEFAULT_INGEST_FILE_JOB_LOAD,
serviceRegistry);
ingestZipJobLoad = LoadUtil.getConfiguredLoadValue(properties, ZIP_JOB_LOAD_KEY, DEFAULT_INGEST_ZIP_JOB_LOAD,
serviceRegistry);
isAllowModifySeries = BooleanUtils.toBoolean(Objects.toString(properties.get(MODIFY_OPENCAST_SERIES_KEY),
BooleanUtils.toStringTrueFalse(DEFAULT_ALLOW_SERIES_MODIFICATIONS)));
isAddOnlyNew = BooleanUtils.toBoolean(Objects.toString(properties.get(ADD_ONLY_NEW_FLAVORS_KEY),
BooleanUtils.toStringTrueFalse(DEFAULT_ALLOW_ONLY_NEW_FLAVORS)));
logger.info("Only allow new flavored catalogs and attachments on ingest:'{}'", isAddOnlyNew);
logger.info("Allowing series modification:'{}'", isAllowModifySeries);
}
/**
* Sets the trusted http client
*
* @param httpClient
* the http client
*/
@Reference
public void setHttpClient(TrustedHttpClient httpClient) {
this.httpClient = httpClient;
}
/**
* Sets the service registry
*
* @param serviceRegistry
* the serviceRegistry to set
*/
@Reference
public void setServiceRegistry(ServiceRegistry serviceRegistry) {
this.serviceRegistry = serviceRegistry;
}
/**
* Sets the media inspection service
*
* @param mediaInspectionService
* the media inspection service to set
*/
@Reference
public void setMediaInspectionService(MediaInspectionService mediaInspectionService) {
this.mediaInspectionService = mediaInspectionService;
}
public WorkflowInstance addZippedMediaPackage(InputStream zipStream)
throws IngestException, IOException, MediaPackageException {
try {
return addZippedMediaPackage(zipStream, null, null);
} catch (NotFoundException e) {
throw new IllegalStateException("A not found exception was thrown without a lookup");
}
}
@Override
public WorkflowInstance addZippedMediaPackage(InputStream zipStream, String wd, Map<String, String> workflowConfig)
throws MediaPackageException, IOException, IngestException, NotFoundException {
try {
return addZippedMediaPackage(zipStream, wd, workflowConfig, null);
} catch (UnauthorizedException e) {
throw new IllegalStateException(e);
}
}
/**
* {@inheritDoc}
*
* @see org.opencastproject.ingest.api.IngestService#addZippedMediaPackage(java.io.InputStream, java.lang.String,
* java.util.Map, java.lang.Long)
*/
@Override
public WorkflowInstance addZippedMediaPackage(InputStream zipStream, String workflowDefinitionId,
Map<String, String> workflowConfig, Long workflowInstanceId)
throws MediaPackageException, IOException, IngestException, NotFoundException, UnauthorizedException {
// Start a job synchronously. We can't keep the open input stream waiting around.
Job job = null;
if (StringUtils.isNotBlank(workflowDefinitionId)) {
try {
workflowService.getWorkflowDefinitionById(workflowDefinitionId);
} catch (WorkflowDatabaseException e) {
throw new IngestException(e);
} catch (NotFoundException nfe) {
logger.warn("Workflow definition {} not found, using default workflow {} instead", workflowDefinitionId,
defaultWorkflowDefinionId);
workflowDefinitionId = defaultWorkflowDefinionId;
}
}
if (workflowInstanceId != null) {
logger.warn("Deprecated method! Ingesting zipped mediapackage with workflow {}", workflowInstanceId);
} else {
logger.info("Ingesting zipped mediapackage");
}
ZipArchiveInputStream zis = null;
Set<String> collectionFilenames = new HashSet<>();
try {
// We don't need anybody to do the dispatching for us. Therefore we need to make sure that the job is never in
// QUEUED state but set it to INSTANTIATED in the beginning and then manually switch it to RUNNING.
job = serviceRegistry.createJob(JOB_TYPE, INGEST_ZIP, null, null, false, ingestZipJobLoad);
job.setStatus(Status.RUNNING);
job = serviceRegistry.updateJob(job);
// Create the working file target collection for this ingest operation
String wfrCollectionId = Long.toString(job.getId());
zis = new ZipArchiveInputStream(zipStream);
ZipArchiveEntry entry;
MediaPackage mp = null;
Map<String, URI> uris = new HashMap<>();
// Sequential number to append to file names so that, if two files have the same
// name, one does not overwrite the other (see MH-9688)
int seq = 1;
// Folder name to compare with next one to figure out if there's a root folder
String folderName = null;
// Indicates if zip has a root folder or not, initialized as true
boolean hasRootFolder = true;
// While there are entries write them to a collection
while ((entry = zis.getNextZipEntry()) != null) {
try {
if (entry.isDirectory() || entry.getName().contains("__MACOSX"))
continue;
if (entry.getName().endsWith("manifest.xml") || entry.getName().endsWith("index.xml")) {
// Build the media package
final InputStream is = new ZipEntryInputStream(zis, entry.getSize());
mp = MediaPackageParser.getFromXml(IOUtils.toString(is, StandardCharsets.UTF_8));
} else {
logger.info("Storing zip entry {}/{} in working file repository collection '{}'", job.getId(),
entry.getName(), wfrCollectionId);
// Since the directory structure is not being mirrored, makes sure the file
// name is different than the previous one(s) by adding a sequential number
String fileName = FilenameUtils.getBaseName(entry.getName()) + "_" + seq++ + "."
+ FilenameUtils.getExtension(entry.getName());
URI contentUri = workingFileRepository.putInCollection(wfrCollectionId, fileName,
new ZipEntryInputStream(zis, entry.getSize()));
collectionFilenames.add(fileName);
// Key is the zip entry name as it is
String key = entry.getName();
uris.put(key, contentUri);
ingestStatistics.add(entry.getSize());
logger.info("Zip entry {}/{} stored at {}", job.getId(), entry.getName(), contentUri);
// Figures out if there's a root folder. Does entry name starts with a folder?
int pos = entry.getName().indexOf('/');
if (pos == -1) {
// No, we can conclude there's no root folder
hasRootFolder = false;
} else if (hasRootFolder && folderName != null && !folderName.equals(entry.getName().substring(0, pos))) {
// Folder name different from previous so there's no root folder
hasRootFolder = false;
} else if (folderName == null) {
// Just initialize folder name
folderName = entry.getName().substring(0, pos);
}
}
} catch (IOException e) {
logger.warn("Unable to process zip entry {}: {}", entry.getName(), e);
throw e;
}
}
if (mp == null)
throw new MediaPackageException("No manifest found in this zip");
// Determine the mediapackage identifier
if (mp.getIdentifier() == null || isBlank(mp.getIdentifier().toString()))
mp.setIdentifier(IdImpl.fromUUID());
String mediaPackageId = mp.getIdentifier().toString();
logger.info("Ingesting mediapackage {} is named '{}'", mediaPackageId, mp.getTitle());
// Make sure there are tracks in the mediapackage
if (mp.getTracks().length == 0) {
logger.warn("Mediapackage {} has no media tracks", mediaPackageId);
}
// Update the element uris to point to their working file repository location
for (MediaPackageElement element : mp.elements()) {
// Key has root folder name if there is one
URI uri = uris.get((hasRootFolder ? folderName + "/" : "") + element.getURI().toString());
if (uri == null)
throw new MediaPackageException("Unable to map element name '" + element.getURI() + "' to workspace uri");
logger.info("Ingested mediapackage element {}/{} located at {}", mediaPackageId, element.getIdentifier(), uri);
URI dest = workingFileRepository.moveTo(wfrCollectionId, FilenameUtils.getName(uri.toString()), mediaPackageId,
element.getIdentifier(), FilenameUtils.getName(element.getURI().toString()));
element.setURI(dest);
// TODO: This should be triggered somehow instead of being handled here
if (MediaPackageElements.SERIES.equals(element.getFlavor())) {
logger.info("Ingested mediapackage {} contains updated series information", mediaPackageId);
updateSeries(element.getURI());
}
}
// Now that all elements are in place, start with ingest
logger.info("Initiating processing of ingested mediapackage {}", mediaPackageId);
WorkflowInstance workflowInstance = ingest(mp, workflowDefinitionId, workflowConfig, workflowInstanceId);
logger.info("Ingest of mediapackage {} done", mediaPackageId);
job.setStatus(Job.Status.FINISHED);
return workflowInstance;
} catch (ServiceRegistryException e) {
throw new IngestException(e);
} catch (MediaPackageException e) {
job.setStatus(Job.Status.FAILED, Job.FailureReason.DATA);
throw e;
} catch (Exception e) {
if (e instanceof IngestException)
throw (IngestException) e;
throw new IngestException(e);
} finally {
IOUtils.closeQuietly(zis);
finallyUpdateJob(job);
for (String filename : collectionFilenames) {
workingFileRepository.deleteFromCollection(Long.toString(job.getId()), filename, true);
}
}
}
/**
* {@inheritDoc}
*
* @see org.opencastproject.ingest.api.IngestService#createMediaPackage()
*/
@Override
public MediaPackage createMediaPackage() throws MediaPackageException, ConfigurationException {
MediaPackage mediaPackage;
try {
mediaPackage = MediaPackageBuilderFactory.newInstance().newMediaPackageBuilder().createNew();
} catch (MediaPackageException e) {
logger.error("INGEST:Failed to create media package " + e.getLocalizedMessage());
throw e;
}
mediaPackage.setDate(new Date());
logger.info("Created mediapackage {}", mediaPackage);
return mediaPackage;
}
/**
* {@inheritDoc}
*
* @see org.opencastproject.ingest.api.IngestService#createMediaPackage()
*/
@Override
public MediaPackage createMediaPackage(String mediaPackageId)
throws MediaPackageException, ConfigurationException {
MediaPackage mediaPackage;
try {
mediaPackage = MediaPackageBuilderFactory.newInstance().newMediaPackageBuilder()
.createNew(new IdImpl(mediaPackageId));
} catch (MediaPackageException e) {
logger.error("INGEST:Failed to create media package " + e.getLocalizedMessage());
throw e;
}
mediaPackage.setDate(new Date());
logger.info("Created mediapackage {}", mediaPackage);
return mediaPackage;
}
/**
* {@inheritDoc}
*
* @see org.opencastproject.ingest.api.IngestService#addTrack(java.net.URI,
* org.opencastproject.mediapackage.MediaPackageElementFlavor, org.opencastproject.mediapackage.MediaPackage)
*/
@Override
public MediaPackage addTrack(URI uri, MediaPackageElementFlavor flavor, MediaPackage mediaPackage)
throws IOException, IngestException {
String[] tags = null;
return this.addTrack(uri, flavor, tags, mediaPackage);
}
/**
* {@inheritDoc}
*
* @see org.opencastproject.ingest.api.IngestService#addTrack(java.net.URI,
* org.opencastproject.mediapackage.MediaPackageElementFlavor, String[] ,
* org.opencastproject.mediapackage.MediaPackage)
*/
@Override
public MediaPackage addTrack(URI uri, MediaPackageElementFlavor flavor, String[] tags, MediaPackage mediaPackage)
throws IOException, IngestException {
Job job = null;
try {
job = serviceRegistry
.createJob(
JOB_TYPE, INGEST_TRACK_FROM_URI, Arrays.asList(uri.toString(),
flavor == null ? null : flavor.toString(), MediaPackageParser.getAsXml(mediaPackage)),
null, false, ingestFileJobLoad);
job.setStatus(Status.RUNNING);
job = serviceRegistry.updateJob(job);
String elementId = UUID.randomUUID().toString();
logger.info("Start adding track {} from URL {} on mediapackage {}", elementId, uri, mediaPackage);
URI newUrl = addContentToRepo(mediaPackage, elementId, uri);
MediaPackage mp = addContentToMediaPackage(mediaPackage, elementId, newUrl, MediaPackageElement.Type.Track,
flavor);
if (tags != null && tags.length > 0) {
MediaPackageElement trackElement = mp.getTrack(elementId);
for (String tag : tags) {
logger.info("Adding Tag: " + tag + " to Element: " + elementId);
trackElement.addTag(tag);
}
}
job.setStatus(Job.Status.FINISHED);
logger.info("Successful added track {} on mediapackage {} at URL {}", elementId, mediaPackage, newUrl);
return mp;
} catch (IOException e) {
throw e;
} catch (ServiceRegistryException e) {
throw new IngestException(e);
} catch (NotFoundException e) {
throw new IngestException("Unable to update ingest job", e);
} finally {
finallyUpdateJob(job);
}
}
/**
* {@inheritDoc}
*
* @see org.opencastproject.ingest.api.IngestService#addTrack(java.io.InputStream, java.lang.String,
* org.opencastproject.mediapackage.MediaPackageElementFlavor, org.opencastproject.mediapackage.MediaPackage)
*/
@Override
public MediaPackage addTrack(InputStream in, String fileName, MediaPackageElementFlavor flavor,
MediaPackage mediaPackage) throws IOException, IngestException {
String[] tags = null;
return this.addTrack(in, fileName, flavor, tags, mediaPackage);
}
/**
* {@inheritDoc}
*
* @see org.opencastproject.ingest.api.IngestService#addTrack(java.io.InputStream, java.lang.String,
* org.opencastproject.mediapackage.MediaPackageElementFlavor, org.opencastproject.mediapackage.MediaPackage)
*/
@Override
public MediaPackage addTrack(InputStream in, String fileName, MediaPackageElementFlavor flavor, String[] tags,
MediaPackage mediaPackage) throws IOException, IngestException {
Job job = null;
try {
job = serviceRegistry.createJob(JOB_TYPE, INGEST_TRACK, null, null, false, ingestFileJobLoad);
job.setStatus(Status.RUNNING);
job = serviceRegistry.updateJob(job);
String elementId = UUID.randomUUID().toString();
logger.info("Start adding track {} from input stream on mediapackage {}", elementId, mediaPackage);
if (fileName.length() > FILENAME_LENGTH_MAX) {
final String extension = "." + FilenameUtils.getExtension(fileName);
final int length = Math.max(0, FILENAME_LENGTH_MAX - extension.length());
fileName = fileName.substring(0, length) + extension;
}
URI newUrl = addContentToRepo(mediaPackage, elementId, fileName, in);
MediaPackage mp = addContentToMediaPackage(mediaPackage, elementId, newUrl, MediaPackageElement.Type.Track,
flavor);
if (tags != null && tags.length > 0) {
MediaPackageElement trackElement = mp.getTrack(elementId);
for (String tag : tags) {
logger.debug("Adding tag `{}` to element {}", tag, elementId);
trackElement.addTag(tag);
}
}
job.setStatus(Job.Status.FINISHED);
logger.info("Successful added track {} on mediapackage {} at URL {}", elementId, mediaPackage, newUrl);
return mp;
} catch (IOException e) {
throw e;
} catch (ServiceRegistryException e) {
throw new IngestException(e);
} catch (NotFoundException e) {
throw new IngestException("Unable to update ingest job", e);
} finally {
finallyUpdateJob(job);
}
}
@Override
public MediaPackage addPartialTrack(URI uri, MediaPackageElementFlavor flavor, long startTime,
MediaPackage mediaPackage) throws IOException, IngestException {
Job job = null;
try {
job = serviceRegistry.createJob(
JOB_TYPE,
INGEST_TRACK_FROM_URI,
Arrays.asList(uri.toString(), flavor == null ? null : flavor.toString(),
MediaPackageParser.getAsXml(mediaPackage)), null, false);
job.setStatus(Status.RUNNING);
job = serviceRegistry.updateJob(job);
String elementId = UUID.randomUUID().toString();
logger.info("Start adding partial track {} from URL {} on mediapackage {}", elementId, uri, mediaPackage);
URI newUrl = addContentToRepo(mediaPackage, elementId, uri);
MediaPackage mp = addContentToMediaPackage(mediaPackage, elementId, newUrl, MediaPackageElement.Type.Track,
flavor);
job.setStatus(Job.Status.FINISHED);
// store startTime
partialTrackStartTimes.put(elementId, startTime);
logger.debug("Added start time {} for track {}", startTime, elementId);
logger.info("Successful added partial track {} on mediapackage {} at URL {}", elementId, mediaPackage, newUrl);
return mp;
} catch (ServiceRegistryException e) {
throw new IngestException(e);
} catch (NotFoundException e) {
throw new IngestException("Unable to update ingest job", e);
} finally {
finallyUpdateJob(job);
}
}
@Override
public MediaPackage addPartialTrack(InputStream in, String fileName, MediaPackageElementFlavor flavor, long startTime,
MediaPackage mediaPackage) throws IOException, IngestException {
Job job = null;
try {
job = serviceRegistry.createJob(JOB_TYPE, INGEST_TRACK, null, null, false);
job.setStatus(Status.RUNNING);
job = serviceRegistry.updateJob(job);
String elementId = UUID.randomUUID().toString();
logger.info("Start adding partial track {} from input stream on mediapackage {}", elementId, mediaPackage);
URI newUrl = addContentToRepo(mediaPackage, elementId, fileName, in);
MediaPackage mp = addContentToMediaPackage(mediaPackage, elementId, newUrl, MediaPackageElement.Type.Track,
flavor);
job.setStatus(Job.Status.FINISHED);
// store startTime
partialTrackStartTimes.put(elementId, startTime);
logger.debug("Added start time {} for track {}", startTime, elementId);
logger.info("Successful added partial track {} on mediapackage {} at URL {}", elementId, mediaPackage, newUrl);
return mp;
} catch (ServiceRegistryException e) {
throw new IngestException(e);
} catch (NotFoundException e) {
throw new IngestException("Unable to update ingest job", e);
} finally {
finallyUpdateJob(job);
}
}
/**
* {@inheritDoc}
*
* @see org.opencastproject.ingest.api.IngestService#addCatalog(java.net.URI,
* org.opencastproject.mediapackage.MediaPackageElementFlavor, org.opencastproject.mediapackage.MediaPackage)
*/
@Override
public MediaPackage addCatalog(URI uri, MediaPackageElementFlavor flavor, MediaPackage mediaPackage)
throws IOException, IngestException {
Job job = null;
try {
job = serviceRegistry.createJob(JOB_TYPE, INGEST_CATALOG_FROM_URI,
Arrays.asList(uri.toString(), flavor.toString(), MediaPackageParser.getAsXml(mediaPackage)), null, false,
ingestFileJobLoad);
job.setStatus(Status.RUNNING);
job = serviceRegistry.updateJob(job);
String elementId = UUID.randomUUID().toString();
logger.info("Start adding catalog {} from URL {} on mediapackage {}", elementId, uri, mediaPackage);
URI newUrl = addContentToRepo(mediaPackage, elementId, uri);
if (MediaPackageElements.SERIES.equals(flavor)) {
updateSeries(uri);
}
MediaPackage mp = addContentToMediaPackage(mediaPackage, elementId, newUrl, MediaPackageElement.Type.Catalog,
flavor);
job.setStatus(Job.Status.FINISHED);
logger.info("Successful added catalog {} on mediapackage {} at URL {}", elementId, mediaPackage, newUrl);
return mp;
} catch (ServiceRegistryException e) {
throw new IngestException(e);
} catch (NotFoundException e) {
throw new IngestException("Unable to update ingest job", e);
} finally {
finallyUpdateJob(job);
}
}
/**
* Updates the persistent representation of a series based on a potentially modified dublin core document.
*
* @param uri
* the URI to the dublin core document containing series metadata.
* @return
* true, if the series is created or overwritten, false if the existing series remains intact.
* @throws IOException if the series catalog was not found
* @throws IngestException if any other exception was encountered
*/
protected boolean updateSeries(URI uri) throws IOException, IngestException {
HttpResponse response = null;
InputStream in = null;
boolean isUpdated = false;
try {
HttpGet getDc = new HttpGet(uri);
response = httpClient.execute(getDc);
in = response.getEntity().getContent();
DublinCoreCatalog dc = dublinCoreService.load(in);
String id = dc.getFirst(DublinCore.PROPERTY_IDENTIFIER);
if (id == null) {
logger.warn("Series dublin core document contains no identifier, rejecting ingested series cagtalog.");
} else {
try {
try {
seriesService.getSeries(id);
if (isAllowModifySeries) {
// Update existing series
seriesService.updateSeries(dc);
isUpdated = true;
logger.debug("Ingest is overwriting the existing series {} with the ingested series", id);
} else {
logger.debug("Series {} already exists. Ignoring series catalog from ingest.", id);
}
} catch (NotFoundException e) {
logger.info("Creating new series {} with default ACL", id);
seriesService.updateSeries(dc);
isUpdated = true;
}
} catch (Exception e) {
throw new IngestException(e);
}
}
in.close();
} catch (IOException e) {
logger.error("Error updating series from DublinCoreCatalog: {}", e.getMessage());
} finally {
IOUtils.closeQuietly(in);
httpClient.close(response);
}
return isUpdated;
}
/**
* {@inheritDoc}
*
* @see org.opencastproject.ingest.api.IngestService#addCatalog(java.io.InputStream, java.lang.String,
* org.opencastproject.mediapackage.MediaPackageElementFlavor, org.opencastproject.mediapackage.MediaPackage)
*/
@Override
public MediaPackage addCatalog(InputStream in, String fileName, MediaPackageElementFlavor flavor,
MediaPackage mediaPackage) throws IOException, IngestException {
return addCatalog(in, fileName, flavor, null, mediaPackage);
}
/**
* {@inheritDoc}
*
* @see org.opencastproject.ingest.api.IngestService#addCatalog(java.io.InputStream, java.lang.String,
* org.opencastproject.mediapackage.MediaPackageElementFlavor, org.opencastproject.mediapackage.MediaPackage)
*/
@Override
public MediaPackage addCatalog(InputStream in, String fileName, MediaPackageElementFlavor flavor, String[] tags,
MediaPackage mediaPackage) throws IOException, IngestException, IllegalArgumentException {
Job job = null;
try {
job = serviceRegistry.createJob(JOB_TYPE, INGEST_CATALOG, null, null, false, ingestFileJobLoad);
job.setStatus(Status.RUNNING);
job = serviceRegistry.updateJob(job);
final String elementId = UUID.randomUUID().toString();
final String mediaPackageId = mediaPackage.getIdentifier().toString();
logger.info("Start adding catalog {} from input stream on mediapackage {}", elementId, mediaPackageId);
final URI newUrl = addContentToRepo(mediaPackage, elementId, fileName, in);
final boolean isJSON;
try (InputStream inputStream = workingFileRepository.get(mediaPackageId, elementId)) {
try (BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, StandardCharsets.UTF_8))) {
// Exception for current BBB integration and Extron SMP351 which is ingesting a JSON array/object as catalog
int firstChar = reader.read();
isJSON = firstChar == '[' || firstChar == '{';
}
}
if (isJSON) {
logger.warn("Input catalog seems to be JSON. This is a mistake and will fail in future Opencast versions."
+ "You will likely want to ingest this as a media package attachment instead.");
} else {
// Verify XML is not corrupted
try {
XmlSafeParser.parse(workingFileRepository.get(mediaPackageId, elementId));
} catch (SAXException e) {
workingFileRepository.delete(mediaPackageId, elementId);
throw new IllegalArgumentException("Catalog XML is invalid", e);
}
}
if (MediaPackageElements.SERIES.equals(flavor)) {
updateSeries(newUrl);
}
MediaPackage mp = addContentToMediaPackage(mediaPackage, elementId, newUrl, MediaPackageElement.Type.Catalog,
flavor);
if (tags != null && tags.length > 0) {
MediaPackageElement trackElement = mp.getCatalog(elementId);
for (String tag : tags) {
logger.info("Adding tag {} to element {}", tag, elementId);
trackElement.addTag(tag);
}
}
job.setStatus(Job.Status.FINISHED);
logger.info("Successful added catalog {} on mediapackage {} at URL {}", elementId, mediaPackage, newUrl);
return mp;
} catch (ServiceRegistryException e) {
throw new IngestException(e);
} catch (NotFoundException e) {
throw new IngestException("Unable to update ingest job", e);
} finally {
finallyUpdateJob(job);
}
}
/**
* {@inheritDoc}
*
* @see org.opencastproject.ingest.api.IngestService#addAttachment(java.net.URI,
* org.opencastproject.mediapackage.MediaPackageElementFlavor, org.opencastproject.mediapackage.MediaPackage)
*/
@Override
public MediaPackage addAttachment(URI uri, MediaPackageElementFlavor flavor, MediaPackage mediaPackage)
throws IOException, IngestException {
Job job = null;
try {
job = serviceRegistry.createJob(JOB_TYPE, INGEST_ATTACHMENT_FROM_URI,
Arrays.asList(uri.toString(), flavor.toString(), MediaPackageParser.getAsXml(mediaPackage)), null, false,
ingestFileJobLoad);
job.setStatus(Status.RUNNING);
job = serviceRegistry.updateJob(job);
String elementId = UUID.randomUUID().toString();
logger.info("Start adding attachment {} from URL {} on mediapackage {}", elementId, uri, mediaPackage);