1 package user.jobengine.server.steps;
\r
3 import java.io.OutputStream;
\r
4 import java.net.InetAddress;
\r
6 import java.util.ArrayList;
\r
7 import java.util.Calendar;
\r
8 import java.util.Date;
\r
9 import java.util.List;
\r
11 import org.apache.commons.lang.StringUtils;
\r
12 import org.apache.commons.net.ftp.FTP;
\r
13 import org.apache.commons.net.ftp.FTPClient;
\r
14 import org.apache.commons.net.ftp.FTPReply;
\r
15 import org.apache.logging.log4j.LogManager;
\r
16 import org.apache.logging.log4j.Logger;
\r
17 import org.apache.logging.log4j.Marker;
\r
19 import com.ibm.nosql.json.api.BasicDBObject;
\r
20 import com.ibm.nosql.json.api.DB;
\r
21 import com.ibm.nosql.json.api.DBCollection;
\r
22 import com.ibm.nosql.json.api.DBCursor;
\r
23 import com.ibm.nosql.json.api.DBObject;
\r
25 import user.commons.CalendarUtils;
\r
26 import user.commons.ListUtils;
\r
27 import user.commons.StoreUri;
\r
28 import user.commons.nosql.NoSQLUtils;
\r
29 import user.commons.octopus.IOctopusAPI;
\r
30 import user.commons.octopus.OctopusAPI;
\r
31 import user.commons.remotestore.FtpDirectoryLister;
\r
32 import user.commons.remotestore.RemoteStoreProtocol;
\r
33 import user.jobengine.db.IItemManager;
\r
34 import user.jobengine.server.IJobEngine;
\r
35 import user.jobengine.server.IJobRuntime;
\r
36 import user.jobengine.server.steps.MetadataTypeDetector.MetadataType;
\r
38 public class CopyForArchiveNEXIOMaterialsStep extends JobStep {
\r
39 private static final String SCHEDULED_FORMAT = "yyyy.MM.dd HH:mm";
\r
40 private static final Logger logger = LogManager.getLogger();
\r
41 private static final String UTF_8 = "utf-8";
\r
42 private static final String JSON_EXT = ".json";
\r
43 private static final String XML_EXT = ".xml";
\r
44 private static final String DURATION = "duration";
\r
45 private static final String MXFEXT = ".MXF";
\r
46 private static final String NEXIOCLIPS = "nexioclips";
\r
47 private static final String LONGNAMEID = "longnameid";
\r
48 private static final String ARCHIVEDRUNDOWNS = "archivedrundowns";
\r
49 private static final String ID = "id";
\r
50 private static final String MEDIATYPE = "Hír bejátszó";
\r
51 private OctopusAPI octopusAPI;
\r
52 private IItemManager manager;
\r
55 private FTPClient sourceFtp;
\r
56 private FTPClient targetFtp;
\r
57 private StoreUri sourceUri;
\r
58 private StoreUri targetUri;
\r
59 private int nexioKillDateDays;
\r
60 private String nexioAgency;
\r
61 private Marker systemMarker;
\r
62 private List<String> transferredFileNames = null;
\r
63 private boolean demo = false;
\r
65 private int check(int value, String name) {
\r
67 logger.error(systemMarker, "A folyamat '{}' bemeneti paramétere 0.", name);
\r
68 throw new NullPointerException(String.format("System is not configured properly, missing '%s' input parameter.", name));
\r
73 private String check(String value, String name) {
\r
74 if (value == null) {
\r
75 logger.error(systemMarker, "A folyamat '{}' bemeneti paramétere üres.", name);
\r
76 throw new NullPointerException(String.format("System is not configured properly, missing '%s' input parameter.", name));
\r
81 private void copy(RundownArchive rundownArchive) throws Exception {
\r
82 for (StoryArchive storyArchive : rundownArchive.getStoryArchives()) {
\r
83 for (FileArchive fileArchive : storyArchive.getFileArchives()) {
\r
85 copyFile(fileArchive, rundownArchive, storyArchive);
\r
86 } catch (Exception e) {
\r
87 logger.error(systemMarker, "A '{}' clip archiválása sikertelen. A rendszer üzenete: {}", fileArchive.getFileName(), e.getMessage());
\r
94 private void copyFile(FileArchive fileArchive, RundownArchive rundownArchive, StoryArchive storyArchive) throws Exception {
\r
95 String origFileName = fileArchive.getFileName();
\r
96 String fileName = String.format("%s-%s", origFileName, rundownArchive.getItemHouseId());
\r
97 String videoFileName = fileName + MXFEXT;
\r
99 if (transferredFileNames == null)
\r
100 transferredFileNames = new ArrayList<>();
\r
102 //A mar letezo mozikat nem archivaljuk le ujra, csak a metaadatot
\r
103 long existingMediaId = 0;
\r
104 if (transferredFileNames.contains(origFileName)) {
\r
105 logger.info(systemMarker, "A '{}' file archiválásra felkészítése egy másik story kapcsán már megtörtént, ezért csak metaadat archiválás szükséges.",
\r
108 transferChunk(videoFileName);
\r
110 existingMediaId = ItemManagerExtensions.getExistingRundownMedia(manager, origFileName);
\r
111 if (existingMediaId == 0) {
\r
112 transferredFileNames.add(origFileName);
\r
114 transferFile(origFileName + MXFEXT, videoFileName);
\r
115 logger.info(systemMarker, "A '{}' file archiválásra felkészítése sikeres volt.", origFileName);
\r
118 logger.info(systemMarker, "A '{}' file archiválása már megtörtént, ezért csak metaadat archiválás szükséges.", origFileName);
\r
120 transferChunk(videoFileName);
\r
125 BasicDBObject metadata = createMetadata(rundownArchive, storyArchive, fileArchive, existingMediaId);
\r
126 transferMetadata(videoFileName, metadata);
\r
127 createSourceKillDateFile(rundownArchive, origFileName);
\r
131 private BasicDBObject createMetadata(RundownArchive rundownArchive, StoryArchive storyArchive, FileArchive fileArchive, long existingMediaId) {
\r
132 BasicDBObject result = new BasicDBObject();
\r
133 result.put("itemHouseId", rundownArchive.getItemHouseId());
\r
134 result.put("itemTitle", rundownArchive.getItemTitle());
\r
135 result.put("itemDescription", rundownArchive.getItemDesc());
\r
136 result.put("userName", "mediacube");
\r
137 result.put("mediaHouseId", storyArchive.getMediaHouseId());
\r
138 result.put("mediaTitle", storyArchive.getMediaTitle());
\r
139 result.put("mediaDescription", storyArchive.getMediaDesc());
\r
140 result.put("mediaType", MEDIATYPE);
\r
141 result.put("duration", fileArchive.getDuration());
\r
142 result.put("existingMediaId", existingMediaId);
\r
146 private void createSourceKillDateFile(RundownArchive rundownArchive, String fileName) throws Exception {
\r
147 logger.info("Create killdate/agency for {}", fileName);
\r
148 OutputStream outStream = null;
\r
150 sourceFtp = ((FtpDirectoryLister) sourceUri.getLister()).connect();
\r
151 Calendar killDate = CalendarUtils.createCalendar(rundownArchive.getScheduleDate());
\r
152 killDate.add(Calendar.DAY_OF_YEAR, nexioKillDateDays);
\r
153 byte[] killDateFile = EscortFiles.createNEXIOKillDateFile(fileName, killDate.getTime(), null, nexioAgency);
\r
154 outStream = sourceFtp.storeFileStream(fileName + XML_EXT);
\r
155 if (outStream == null) {
\r
156 throw new NullPointerException("Can not open: " + fileName + XML_EXT + " Reply:" + sourceFtp.getReplyString());
\r
158 outStream.write(killDateFile);
\r
160 } catch (Exception e) {
\r
161 logger.catching(e);
\r
164 if (outStream != null)
\r
166 sourceUri.cleanUp();
\r
171 public Object[] execute(int nexioPort, String nexioUserName, String nexioPassword, String archiveFtp, String archiveUserName, String archivePassword,
\r
172 int daysBeforeNow, int nexioKillDateDays, String nexioAgency, IJobEngine jobEngine, IJobRuntime jobRuntime) throws Exception {
\r
173 systemMarker = jobRuntime.getMarker();
\r
174 setAndCheck(nexioPort, nexioUserName, nexioPassword, archiveFtp, archiveUserName, archivePassword, nexioKillDateDays, nexioAgency, jobEngine);
\r
175 octopusAPI = new OctopusAPI();
\r
176 Calendar scheduledDate = Calendar.getInstance();
\r
177 scheduledDate.add(Calendar.DAY_OF_YEAR, -1 * daysBeforeNow);
\r
178 List<DBObject> rundowns = octopusAPI.getRundowns(scheduledDate.getTime());
\r
179 if (rundowns == null) {
\r
180 logger.warn(systemMarker, "Nem található adástükör a {} napra.", CalendarUtils.toDateString(scheduledDate));
\r
184 processRundowns(rundowns);
\r
188 // private String getVersionedFileName(String fileName, String extension) throws Exception {
\r
189 // String result = fileName;
\r
191 // targetFtp = ((FtpDirectoryLister) targetUri.getLister()).connect();
\r
192 // FTPFile[] listFiles = targetFtp.listFiles();
\r
193 // List<String> fileNames = new ArrayList<>();
\r
194 // for (FTPFile ftpFile : listFiles) {
\r
195 // fileNames.add(ftpFile.getName());
\r
197 // while (fileNames.contains(result + extension)) {
\r
201 // } catch (Exception e) {
\r
202 // logger.catching(e);
\r
205 // targetUri.cleanUp();
\r
210 private FileArchive processMosObject(BasicDBObject rundown, BasicDBObject story, BasicDBObject mosObject) throws Exception {
\r
211 String mosID = mosObject.getString(IOctopusAPI.OBJ_ID);
\r
212 if (MetadataTypeDetector.GuessMetadataType(mosID) != MetadataType.OctopusPlaceholder) {
\r
213 logger.trace("Skipping MOS object {}", mosID);
\r
216 DBCollection clips = db.getCollection(NEXIOCLIPS);
\r
217 BasicDBObject clip = (BasicDBObject) clips.findOne(new BasicDBObject(LONGNAMEID, mosID));
\r
218 if (clip == null) {
\r
219 logger.debug("File {} NOT exists", mosID);
\r
221 //throw new Exception(String.format("File NOT exists %s", mosID));
\r
223 logger.debug("File {} exists", mosID);
\r
225 long duration = NoSQLUtils.asLong(clip, DURATION);
\r
227 if (duration == 0) {
\r
228 logger.debug("File {} exists with 0 frame length", mosID);
\r
231 if (duration == 1) {
\r
232 logger.debug("File {} exists with 1 frame length", mosID);
\r
235 return new FileArchive(mosID, duration);
\r
238 private RundownArchive processRundow(DBObject r) throws Exception {
\r
239 BasicDBObject rundown = (BasicDBObject) r;
\r
240 long rundownID = rundown.getLong(ID);
\r
242 logger.info("Processing rundown {} {}", rundownID, rundown.getString(IOctopusAPI.NAME));
\r
243 List<DBObject> stories = octopusAPI.getRundownFullStories(rundownID);
\r
244 if (stories == null)
\r
246 RundownArchive result = new RundownArchive();
\r
248 long id = NoSQLUtils.asLong(rundown, IOctopusAPI.ID);
\r
251 String name = NoSQLUtils.asString(NoSQLUtils.asDBObject(rundown, IOctopusAPI.RUNDOWN_TYPE), IOctopusAPI.NAME);
\r
252 if (StringUtils.isBlank(name))
\r
254 String channel = NoSQLUtils.asString(NoSQLUtils.asDBObject(rundown, IOctopusAPI.CHANNEL), IOctopusAPI.NAME);
\r
255 Date scheduledStart = rundown.getDate(IOctopusAPI.SCHEDULED_START);
\r
256 if (scheduledStart == null)
\r
258 String start = CalendarUtils.toString(CalendarUtils.createCalendar(scheduledStart), SCHEDULED_FORMAT);
\r
259 result.setScheduleDate(scheduledStart);
\r
260 result.setItemHouseId(String.valueOf(id));
\r
261 result.setItemTitle(String.format("%s %s %s", start, name, channel));
\r
263 for (DBObject s : stories) {
\r
264 StoryArchive storyArchive = processStory(rundown, s);
\r
265 if (storyArchive == null)
\r
267 result.addStoryArchive(storyArchive);
\r
272 private void processRundowns(List<DBObject> rundowns) {
\r
274 //TODO kiveni publikálás előtt
\r
275 //db.getCollection(ARCHIVEDRUNDOWNS).drop();
\r
276 List<BasicDBObject> archivedRundowns = queryArchivedRundowns();
\r
280 for (DBObject r : rundowns) {
\r
281 BasicDBObject rundown = (BasicDBObject) r;
\r
282 setProgress(index * 100 / rundowns.size());
\r
283 long rundownID = NoSQLUtils.asLong(rundown, IOctopusAPI.ID);
\r
284 String rundownName = NoSQLUtils.asString(rundown, IOctopusAPI.NAME);
\r
286 BasicDBObject currentRundownID = new BasicDBObject(IOctopusAPI.ID, rundownID);
\r
287 if (!demo && archivedRundowns != null && archivedRundowns.contains(currentRundownID)) {
\r
288 logger.info("Skipping archived rundown {} {}", rundownID, rundownName);
\r
292 RundownArchive rundownArchive = processRundow(r);
\r
293 if (rundownArchive == null || rundownArchive.isEmpty()) {
\r
295 logger.info("Skipping rundown {} {}", rundownID, rundownName);
\r
300 logger.info("Saving rundown {} {}", rundownID, rundownName);
\r
301 copy(rundownArchive);
\r
303 logger.info(systemMarker, "A '{}' tükör {}db bejátszójának archiválása sikeres volt", rundownArchive.getItemTitle(),
\r
304 rundownArchive.getStoryArchives().size());
\r
307 db.getCollection(ARCHIVEDRUNDOWNS).save(currentRundownID);
\r
308 } catch (Exception e) {
\r
309 logger.catching(e);
\r
310 logger.error(systemMarker,
\r
311 String.format("A %s %s tükör archiválása nem lehetséges, mert a annak ellenőrzése hibát jelzett. A rendszer üzenete: %s", rundownID,
\r
312 rundownName, e.getMessage()));
\r
319 private StoryArchive processStory(BasicDBObject rundown, DBObject s) throws Exception {
\r
320 BasicDBObject story = (BasicDBObject) s;
\r
321 String parentStoryID = story.getString(IOctopusAPI.PARENT_STORY_ID);
\r
322 if (StringUtils.isBlank(parentStoryID)) {
\r
323 logger.warn("Story parentStoryID is null: {}", story.toPrettyString(null));
\r
326 logger.debug("Processing story {}", parentStoryID);
\r
327 List<BasicDBObject> mosObjects = NoSQLUtils.asList(story, IOctopusAPI.MOS_OBJECTS);
\r
328 if (mosObjects == null)
\r
330 StoryArchive storyArchive = null;
\r
331 for (BasicDBObject mosObject : mosObjects) {
\r
332 FileArchive fileArchive = processMosObject(rundown, story, mosObject);
\r
333 if (fileArchive == null)
\r
335 if (storyArchive == null) {
\r
336 storyArchive = new StoryArchive();
\r
337 storyArchive.setMediaHouseId(parentStoryID);
\r
338 storyArchive.setMediaTitle(story.getString(IOctopusAPI.NAME));
\r
339 storyArchive.setMediaDesc(story.getString(IOctopusAPI.SCRIPT_CONTENT));
\r
342 storyArchive.addFileArchive(fileArchive);
\r
344 return storyArchive;
\r
348 private List<BasicDBObject> queryArchivedRundowns() {
\r
349 List<BasicDBObject> result = null;
\r
350 DBCollection collection = db.getCollection(ARCHIVEDRUNDOWNS);
\r
351 DBCursor find = collection.find(new BasicDBObject(), new BasicDBObject(IOctopusAPI._ID, 0).append(IOctopusAPI.ID, 1));
\r
352 if (find.hasNext())
\r
353 result = ListUtils.cast(find.toArray());
\r
357 private void setAndCheck(int nexioPort, String nexioUserName, String nexioPassword, String archiveFtp, String archiveUserName, String archivePassword,
\r
358 int nexioKillDateDays, String nexioAgency, IJobEngine jobEngine) throws Exception {
\r
359 db = NoSQLUtils.getNoSQLDB();
\r
361 logger.error(systemMarker, "Az NoSQL adatkezelő réteg nem elérhető.");
\r
362 throw new NullPointerException("Internal error, missing NoSQL DB reference.");
\r
365 if (jobEngine == null) {
\r
366 logger.error(systemMarker, "Az folyamatkezelő réteg nem elérhető.");
\r
367 throw new NullPointerException("Internal error, missing JobEngine reference.");
\r
369 manager = jobEngine.getItemManager();
\r
370 if (manager == null) {
\r
371 logger.error(systemMarker, "Az adatbáziskezelő réteg nem elérhető.");
\r
372 throw new NullPointerException("Internal error, missing ItemManager reference.");
\r
374 String nexioHost = System.getProperty("nexio.host");
\r
375 if (StringUtils.isBlank(nexioHost)) {
\r
376 logger.error(systemMarker, "A 'nexio.host' rendszer paraméter nem található.");
\r
377 throw new NullPointerException("System is not configured properly, 'jobengine.selenio.address' startup parameter missing.");
\r
379 check(nexioPort, "nexioPort");
\r
380 check(nexioUserName, "nexioUserName");
\r
381 check(nexioPassword, "nexioPassword");
\r
383 check(nexioKillDateDays, "nexioKillDateDays");
\r
384 this.nexioKillDateDays = nexioKillDateDays;
\r
385 check(nexioAgency, "nexioAgency");
\r
386 this.nexioAgency = nexioAgency;
\r
388 sourceUri = manager.createStoreUri(RemoteStoreProtocol.FTP, nexioHost);
\r
389 sourceUri.setPortNumber(nexioPort);
\r
390 sourceUri.setUserName(nexioUserName);
\r
391 sourceUri.setPassword(nexioPassword);
\r
392 if (sourceUri == null) {
\r
393 logger.error(systemMarker, "A forrás nem elérhető.");
\r
394 throw new NullPointerException("Internal error, missing 'sourceUri'.");
\r
397 check(archiveFtp, "archiveFtp");
\r
398 check(archiveUserName, "archiveUserName");
\r
399 check(archivePassword, "archivePassword");
\r
401 targetUri = manager.createStoreUri(new URI(archiveFtp));
\r
402 targetUri.setUserName(archiveUserName);
\r
403 targetUri.setPassword(archivePassword);
\r
404 if (targetUri == null) {
\r
405 logger.error(systemMarker, "A cél nem elérhető.");
\r
406 throw new NullPointerException("Internal error, missing 'targetUri'.");
\r
411 private void transferChunk(String fileName) throws Exception {
\r
412 logger.info("Transfer chunk {}", fileName);
\r
413 OutputStream outStream = null;
\r
415 targetFtp = ((FtpDirectoryLister) targetUri.getLister()).connect();
\r
416 outStream = targetFtp.storeFileStream(fileName);
\r
417 if (outStream == null) {
\r
418 throw new NullPointerException("Can not open: " + fileName + MXFEXT + " Reply:" + targetFtp.getReplyString());
\r
420 } catch (Exception e) {
\r
421 logger.catching(e);
\r
424 if (outStream != null)
\r
426 targetUri.cleanUp();
\r
430 private void transferFile(String sourceFileName, String targetFileName) throws Exception {
\r
432 logger.info("Transfer clip {}", sourceFileName);
\r
434 sourceFtp = ((FtpDirectoryLister) sourceUri.getLister()).connect();
\r
435 targetFtp = ((FtpDirectoryLister) targetUri.getLister()).connect();
\r
436 if (!targetFtp.enterRemotePassiveMode())
\r
437 throw new Exception("!PASV");
\r
439 reply = sourceFtp.port(InetAddress.getByName(targetFtp.getPassiveHost()), targetFtp.getPassivePort());
\r
440 if (!FTPReply.isPositiveCompletion(reply))
\r
441 throw new Exception("PORT parancs válasza: " + sourceFtp.getReplyString());
\r
443 if (!sourceFtp.setFileType(FTP.BINARY_FILE_TYPE))
\r
444 throw new Exception("!SOURCE TYPE");
\r
446 reply = sourceFtp.retr(sourceFileName);
\r
447 if (!FTPReply.isPositivePreliminary(reply))
\r
448 throw new Exception("RETR parancs válasza: " + sourceFtp.getReplyString());
\r
450 if (!targetFtp.setFileType(FTP.BINARY_FILE_TYPE))
\r
451 throw new Exception("!TARGET TYPE");
\r
453 reply = targetFtp.stor(targetFileName);
\r
454 if (!FTPReply.isPositivePreliminary(reply))
\r
455 throw new Exception("STOR parancs válasza: " + sourceFtp.getReplyString());
\r
458 reply = sourceFtp.stat();
\r
459 if (!FTPReply.isPositiveCompletion(reply))
\r
460 throw new Exception("STAT parancs válasza: " + sourceFtp.getReplyString());
\r
462 logger.info("Status: {}", sourceFtp.getReplyString());
\r
463 if (reply == 226) {
\r
466 Thread.sleep(1000);
\r
468 } catch (Exception e) {
\r
469 logger.catching(e);
\r
472 sourceUri.cleanUp();
\r
473 targetUri.cleanUp();
\r
478 private void transferMetadata(String fileName, BasicDBObject metadata) throws Exception {
\r
479 logger.info("Transfer metadata {}", fileName);
\r
480 OutputStream outStream = null;
\r
482 targetFtp = ((FtpDirectoryLister) targetUri.getLister()).connect();
\r
483 if (!targetFtp.changeWorkingDirectory(EscortFiles.STATUSFOLDER)) {
\r
484 targetFtp.makeDirectory(EscortFiles.STATUSFOLDER);
\r
485 if (!targetFtp.changeWorkingDirectory(EscortFiles.STATUSFOLDER))
\r
486 throw new Exception("!STATUSFOLDER");
\r
489 outStream = targetFtp.storeFileStream(fileName + JSON_EXT);
\r
490 if (outStream == null) {
\r
491 throw new NullPointerException("Can not open: " + fileName + JSON_EXT + " Reply:" + targetFtp.getReplyString());
\r
493 outStream.write(metadata.toString().getBytes(UTF_8));
\r
495 //targetFtp.changeToParentDirectory();
\r
496 } catch (Exception e) {
\r
497 logger.catching(e);
\r
500 if (outStream != null)
\r
502 targetUri.cleanUp();
\r