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.Arrays;
\r
8 import java.util.Calendar;
\r
9 import java.util.Date;
\r
10 import java.util.List;
\r
12 import org.apache.commons.lang.StringUtils;
\r
13 import org.apache.commons.net.ftp.FTP;
\r
14 import org.apache.commons.net.ftp.FTPClient;
\r
15 import org.apache.commons.net.ftp.FTPReply;
\r
16 import org.apache.logging.log4j.LogManager;
\r
17 import org.apache.logging.log4j.Logger;
\r
18 import org.apache.logging.log4j.Marker;
\r
20 import com.ibm.nosql.json.api.BasicDBObject;
\r
21 import com.ibm.nosql.json.api.DB;
\r
22 import com.ibm.nosql.json.api.DBCollection;
\r
23 import com.ibm.nosql.json.api.DBCursor;
\r
24 import com.ibm.nosql.json.api.DBObject;
\r
26 import user.commons.CalendarUtils;
\r
27 import user.commons.ListUtils;
\r
28 import user.commons.StoreUri;
\r
29 import user.commons.nosql.NoSQLUtils;
\r
30 import user.commons.octopus.IOctopusAPI;
\r
31 import user.commons.octopus.OctopusAPI;
\r
32 import user.commons.remotestore.FtpDirectoryLister;
\r
33 import user.commons.remotestore.RemoteStoreProtocol;
\r
34 import user.jobengine.db.IItemManager;
\r
35 import user.jobengine.server.IJobEngine;
\r
36 import user.jobengine.server.IJobRuntime;
\r
37 import user.jobengine.server.steps.MetadataTypeDetector.MetadataType;
\r
39 public class CopyForArchiveNEXIOMaterialsStep extends JobStep {
\r
40 private static final String SCHEDULED_FORMAT = "yyyy.MM.dd HH:mm";
\r
41 private static final Logger logger = LogManager.getLogger();
\r
42 private static final String UTF_8 = "utf-8";
\r
43 private static final String JSON_EXT = ".json";
\r
44 private static final String XML_EXT = ".xml";
\r
45 private static final String DURATION = "duration";
\r
46 private static final String MXFEXT = ".MXF";
\r
47 private static final String NEXIOCLIPS = "nexioclips";
\r
48 private static final String LONGNAMEID = "longnameid";
\r
49 private static final String ARCHIVEDRUNDOWNS = "archivedrundowns";
\r
50 private static final String ID = "id";
\r
51 private static final String MEDIATYPE = "Hír bejátszó";
\r
52 private OctopusAPI octopusAPI;
\r
53 private IItemManager manager;
\r
56 private FTPClient sourceFtp;
\r
57 private FTPClient targetFtp;
\r
58 private StoreUri sourceUri;
\r
59 private StoreUri targetUri;
\r
60 private int nexioKillDateDays;
\r
61 private String nexioAgency;
\r
62 private Marker systemMarker;
\r
63 private List<String> transferredFileNames = null;
\r
64 private boolean demo = false;
\r
66 private int check(int value, String name) {
\r
68 logger.error(systemMarker, "A folyamat '{}' bemeneti paramétere 0.", name);
\r
69 throw new NullPointerException(String.format("System is not configured properly, missing '%s' input parameter.", name));
\r
74 private String check(String value, String name) {
\r
75 if (value == null) {
\r
76 logger.error(systemMarker, "A folyamat '{}' bemeneti paramétere üres.", name);
\r
77 throw new NullPointerException(String.format("System is not configured properly, missing '%s' input parameter.", name));
\r
82 private void copy(RundownArchive rundownArchive) throws Exception {
\r
83 for (StoryArchive storyArchive : rundownArchive.getStoryArchives()) {
\r
84 for (FileArchive fileArchive : storyArchive.getFileArchives()) {
\r
86 copyFile(fileArchive, rundownArchive, storyArchive);
\r
87 } catch (Exception e) {
\r
88 logger.error(systemMarker, "A '{}' clip archiválása sikertelen. A rendszer üzenete: {}", fileArchive.getFileName(), e.getMessage());
\r
95 private void copyFile(FileArchive fileArchive, RundownArchive rundownArchive, StoryArchive storyArchive) throws Exception {
\r
96 String origFileName = fileArchive.getFileName();
\r
97 String fileName = String.format("%s-%s", origFileName, rundownArchive.getItemHouseId());
\r
98 String videoFileName = fileName + MXFEXT;
\r
100 if (transferredFileNames == null)
\r
101 transferredFileNames = new ArrayList<>();
\r
103 //A mar letezo mozikat nem archivaljuk le ujra, csak a metaadatot
\r
104 long existingMediaId = 0;
\r
105 boolean transferDone = false;
\r
106 if (transferredFileNames.contains(origFileName)) {
\r
107 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
110 transferDone = transferChunk(videoFileName);
\r
112 existingMediaId = ItemManagerExtensions.getExistingRundownMedia(manager, origFileName);
\r
113 if (existingMediaId == 0) {
\r
114 transferredFileNames.add(origFileName);
\r
116 transferDone = transferFile(origFileName + MXFEXT, videoFileName);
\r
117 logger.info(systemMarker, "A '{}' file archiválásra felkészítése sikeres volt.", origFileName);
\r
120 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
122 transferDone = transferChunk(videoFileName);
\r
126 if (!demo && transferDone) {
\r
127 BasicDBObject metadata = createMetadata(rundownArchive, storyArchive, fileArchive, existingMediaId);
\r
128 transferMetadata(videoFileName, metadata);
\r
129 createSourceKillDateFile(rundownArchive, origFileName);
\r
133 private BasicDBObject createMetadata(RundownArchive rundownArchive, StoryArchive storyArchive, FileArchive fileArchive, long existingMediaId) {
\r
134 BasicDBObject result = new BasicDBObject();
\r
135 result.put("itemHouseId", rundownArchive.getItemHouseId());
\r
136 result.put("itemTitle", rundownArchive.getItemTitle());
\r
137 result.put("itemDescription", rundownArchive.getItemDesc());
\r
138 result.put("userName", "mediacube");
\r
139 result.put("mediaHouseId", storyArchive.getMediaHouseId());
\r
140 result.put("mediaTitle", storyArchive.getMediaTitle());
\r
141 result.put("mediaDescription", storyArchive.getMediaDesc());
\r
142 result.put("mediaType", MEDIATYPE);
\r
143 result.put("duration", fileArchive.getDuration());
\r
144 result.put("existingMediaId", existingMediaId);
\r
148 private void createSourceKillDateFile(RundownArchive rundownArchive, String fileName) throws Exception {
\r
149 logger.info("Create killdate/agency for {}", fileName);
\r
150 OutputStream outStream = null;
\r
152 sourceFtp = ((FtpDirectoryLister) sourceUri.getLister()).connect();
\r
153 Calendar killDate = CalendarUtils.createCalendar(rundownArchive.getScheduleDate());
\r
154 killDate.add(Calendar.DAY_OF_YEAR, nexioKillDateDays);
\r
155 byte[] killDateFile = EscortFiles.createNEXIOKillDateFile(fileName, killDate.getTime(), null, nexioAgency);
\r
156 outStream = sourceFtp.storeFileStream(fileName + XML_EXT);
\r
157 if (outStream == null) {
\r
158 throw new NullPointerException("Can not open: " + fileName + XML_EXT + " Reply:" + sourceFtp.getReplyString());
\r
160 outStream.write(killDateFile);
\r
162 } catch (Exception e) {
\r
163 logger.catching(e);
\r
166 if (outStream != null)
\r
168 sourceUri.cleanUp();
\r
173 public Object[] execute(int nexioPort, String nexioUserName, String nexioPassword, String archiveFtp, String archiveUserName, String archivePassword,
\r
174 int daysBeforeNow, int nexioKillDateDays, String nexioAgency, IJobEngine jobEngine, IJobRuntime jobRuntime) throws Exception {
\r
175 systemMarker = jobRuntime.getSessionMarker();
\r
176 setAndCheck(nexioPort, nexioUserName, nexioPassword, archiveFtp, archiveUserName, archivePassword, nexioKillDateDays, nexioAgency, jobEngine);
\r
177 octopusAPI = new OctopusAPI();
\r
178 Calendar scheduledDate = Calendar.getInstance();
\r
179 scheduledDate.add(Calendar.DAY_OF_YEAR, -1 * daysBeforeNow);
\r
180 List<DBObject> rundowns = octopusAPI.getRundowns(scheduledDate.getTime());
\r
181 if (rundowns == null) {
\r
182 logger.warn(systemMarker, "Nem található adástükör a {} napra.", CalendarUtils.toDateString(scheduledDate));
\r
186 processRundowns(rundowns);
\r
190 // private String getVersionedFileName(String fileName, String extension) throws Exception {
\r
191 // String result = fileName;
\r
193 // targetFtp = ((FtpDirectoryLister) targetUri.getLister()).connect();
\r
194 // FTPFile[] listFiles = targetFtp.listFiles();
\r
195 // List<String> fileNames = new ArrayList<>();
\r
196 // for (FTPFile ftpFile : listFiles) {
\r
197 // fileNames.add(ftpFile.getName());
\r
199 // while (fileNames.contains(result + extension)) {
\r
203 // } catch (Exception e) {
\r
204 // logger.catching(e);
\r
207 // targetUri.cleanUp();
\r
212 private FileArchive processMosObject(BasicDBObject rundown, BasicDBObject story, BasicDBObject mosObject) throws Exception {
\r
213 String mosID = mosObject.getString(IOctopusAPI.OBJ_ID);
\r
214 if (MetadataTypeDetector.GuessMetadataType(mosID) != MetadataType.OctopusPlaceholder) {
\r
215 logger.trace("Skipping MOS object {}", mosID);
\r
218 DBCollection clips = db.getCollection(NEXIOCLIPS);
\r
219 BasicDBObject clip = (BasicDBObject) clips.findOne(new BasicDBObject(LONGNAMEID, mosID));
\r
220 if (clip == null) {
\r
221 logger.debug("File {} NOT exists", mosID);
\r
223 //throw new Exception(String.format("File NOT exists %s", mosID));
\r
225 logger.debug("File {} exists", mosID);
\r
227 long duration = NoSQLUtils.asLong(clip, DURATION);
\r
229 if (duration == 0) {
\r
230 logger.debug("File {} exists with 0 frame length", mosID);
\r
233 if (duration == 1) {
\r
234 logger.debug("File {} exists with 1 frame length", mosID);
\r
237 return new FileArchive(mosID, duration);
\r
240 private RundownArchive processRundow(DBObject r) throws Exception {
\r
241 BasicDBObject rundown = (BasicDBObject) r;
\r
242 long rundownID = rundown.getLong(ID);
\r
244 logger.info("Processing rundown {} {}", rundownID, rundown.getString(IOctopusAPI.NAME));
\r
245 List<DBObject> stories = octopusAPI.getRundownFullStories(rundownID);
\r
246 if (stories == null)
\r
248 RundownArchive result = new RundownArchive();
\r
250 long id = NoSQLUtils.asLong(rundown, IOctopusAPI.ID);
\r
253 String name = NoSQLUtils.asString(NoSQLUtils.asDBObject(rundown, IOctopusAPI.RUNDOWN_TYPE), IOctopusAPI.NAME);
\r
254 if (StringUtils.isBlank(name))
\r
256 String channel = NoSQLUtils.asString(NoSQLUtils.asDBObject(rundown, IOctopusAPI.CHANNEL), IOctopusAPI.NAME);
\r
257 Date scheduledStart = rundown.getDate(IOctopusAPI.SCHEDULED_START);
\r
258 if (scheduledStart == null)
\r
260 String start = CalendarUtils.toString(CalendarUtils.createCalendar(scheduledStart), SCHEDULED_FORMAT);
\r
261 result.setScheduleDate(scheduledStart);
\r
262 result.setItemHouseId(String.valueOf(id));
\r
263 result.setItemTitle(String.format("%s %s %s", start, name, channel));
\r
265 for (DBObject s : stories) {
\r
266 StoryArchive storyArchive = processStory(rundown, s);
\r
267 if (storyArchive == null)
\r
269 result.addStoryArchive(storyArchive);
\r
274 private void processRundowns(List<DBObject> rundowns) {
\r
276 //TODO kiveni publikálás előtt
\r
277 //db.getCollection(ARCHIVEDRUNDOWNS).drop();
\r
278 List<BasicDBObject> archivedRundowns = queryArchivedRundowns();
\r
282 for (DBObject r : rundowns) {
\r
283 BasicDBObject rundown = (BasicDBObject) r;
\r
284 setProgress(index * 100 / rundowns.size());
\r
285 long rundownID = NoSQLUtils.asLong(rundown, IOctopusAPI.ID);
\r
286 String rundownName = NoSQLUtils.asString(rundown, IOctopusAPI.NAME);
\r
288 BasicDBObject currentRundownID = new BasicDBObject(IOctopusAPI.ID, rundownID);
\r
289 if (!demo && archivedRundowns != null && archivedRundowns.contains(currentRundownID)) {
\r
290 logger.info("Skipping archived rundown {} {}", rundownID, rundownName);
\r
294 RundownArchive rundownArchive = processRundow(r);
\r
295 if (rundownArchive == null || rundownArchive.isEmpty()) {
\r
297 logger.info("Skipping rundown {} {}", rundownID, rundownName);
\r
302 logger.info("Saving rundown {} {}", rundownID, rundownName);
\r
303 copy(rundownArchive);
\r
305 logger.info(systemMarker, "A '{}' tükör {}db bejátszójának archiválása sikeres volt", rundownArchive.getItemTitle(),
\r
306 rundownArchive.getStoryArchives().size());
\r
309 db.getCollection(ARCHIVEDRUNDOWNS).save(currentRundownID);
\r
310 } catch (Exception e) {
\r
311 logger.catching(e);
\r
312 logger.error(systemMarker,
\r
313 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
314 rundownName, e.getMessage()));
\r
321 private StoryArchive processStory(BasicDBObject rundown, DBObject s) throws Exception {
\r
322 BasicDBObject story = (BasicDBObject) s;
\r
323 String parentStoryID = story.getString(IOctopusAPI.PARENT_STORY_ID);
\r
324 if (StringUtils.isBlank(parentStoryID)) {
\r
325 logger.warn("Story parentStoryID is null: {}", story.toPrettyString(null));
\r
328 logger.debug("Processing story {}", parentStoryID);
\r
329 List<BasicDBObject> mosObjects = NoSQLUtils.asList(story, IOctopusAPI.MOS_OBJECTS);
\r
330 if (mosObjects == null)
\r
332 StoryArchive storyArchive = null;
\r
333 for (BasicDBObject mosObject : mosObjects) {
\r
334 FileArchive fileArchive = processMosObject(rundown, story, mosObject);
\r
335 if (fileArchive == null)
\r
337 if (storyArchive == null) {
\r
338 storyArchive = new StoryArchive();
\r
339 storyArchive.setMediaHouseId(parentStoryID);
\r
340 storyArchive.setMediaTitle(story.getString(IOctopusAPI.NAME));
\r
341 storyArchive.setMediaDesc(story.getString(IOctopusAPI.SCRIPT_CONTENT));
\r
344 storyArchive.addFileArchive(fileArchive);
\r
346 return storyArchive;
\r
350 private List<BasicDBObject> queryArchivedRundowns() {
\r
351 List<BasicDBObject> result = null;
\r
352 DBCollection collection = db.getCollection(ARCHIVEDRUNDOWNS);
\r
353 DBCursor find = collection.find(new BasicDBObject(), new BasicDBObject(IOctopusAPI._ID, 0).append(IOctopusAPI.ID, 1));
\r
354 if (find.hasNext())
\r
355 result = ListUtils.cast(find.toArray());
\r
359 private void setAndCheck(int nexioPort, String nexioUserName, String nexioPassword, String archiveFtp, String archiveUserName, String archivePassword,
\r
360 int nexioKillDateDays, String nexioAgency, IJobEngine jobEngine) throws Exception {
\r
361 db = NoSQLUtils.getNoSQLDB();
\r
363 logger.error(systemMarker, "Az NoSQL adatkezelő réteg nem elérhető.");
\r
364 throw new NullPointerException("Internal error, missing NoSQL DB reference.");
\r
367 if (jobEngine == null) {
\r
368 logger.error(systemMarker, "Az folyamatkezelő réteg nem elérhető.");
\r
369 throw new NullPointerException("Internal error, missing JobEngine reference.");
\r
371 manager = jobEngine.getItemManager();
\r
372 if (manager == null) {
\r
373 logger.error(systemMarker, "Az adatbáziskezelő réteg nem elérhető.");
\r
374 throw new NullPointerException("Internal error, missing ItemManager reference.");
\r
376 String nexioHost = System.getProperty("nexio.host");
\r
377 if (StringUtils.isBlank(nexioHost)) {
\r
378 logger.error(systemMarker, "A 'nexio.host' rendszer paraméter nem található.");
\r
379 throw new NullPointerException("System is not configured properly, 'jobengine.selenio.address' startup parameter missing.");
\r
381 check(nexioPort, "nexioPort");
\r
382 check(nexioUserName, "nexioUserName");
\r
383 check(nexioPassword, "nexioPassword");
\r
385 check(nexioKillDateDays, "nexioKillDateDays");
\r
386 this.nexioKillDateDays = nexioKillDateDays;
\r
387 check(nexioAgency, "nexioAgency");
\r
388 this.nexioAgency = nexioAgency;
\r
390 sourceUri = manager.createStoreUri(RemoteStoreProtocol.FTP, nexioHost);
\r
391 sourceUri.setPortNumber(nexioPort);
\r
392 sourceUri.setUserName(nexioUserName);
\r
393 sourceUri.setPassword(nexioPassword);
\r
394 if (sourceUri == null) {
\r
395 logger.error(systemMarker, "A forrás nem elérhető.");
\r
396 throw new NullPointerException("Internal error, missing 'sourceUri'.");
\r
399 check(archiveFtp, "archiveFtp");
\r
400 check(archiveUserName, "archiveUserName");
\r
401 check(archivePassword, "archivePassword");
\r
403 targetUri = manager.createStoreUri(new URI(archiveFtp));
\r
404 targetUri.setUserName(archiveUserName);
\r
405 targetUri.setPassword(archivePassword);
\r
406 if (targetUri == null) {
\r
407 logger.error(systemMarker, "A cél nem elérhető.");
\r
408 throw new NullPointerException("Internal error, missing 'targetUri'.");
\r
413 private boolean transferChunk(String fileName) throws Exception {
\r
414 logger.info("Transfer chunk {}", fileName);
\r
415 OutputStream outStream = null;
\r
417 targetFtp = ((FtpDirectoryLister) targetUri.getLister()).connect();
\r
419 //ha ugyan abban a tukorben szerepel meg 1x a mozi, akkor a chunk felulirja a tenyleges file-t, es az sosem archivalodik
\r
420 String[] names = targetFtp.listNames();
\r
421 if (names != null) {
\r
422 if (Arrays.asList(names).contains(fileName))
\r
426 outStream = targetFtp.storeFileStream(fileName);
\r
427 if (outStream == null) {
\r
428 throw new NullPointerException("Can not open: " + fileName + " Reply:" + targetFtp.getReplyString());
\r
430 } catch (Exception e) {
\r
431 logger.catching(e);
\r
434 if (outStream != null)
\r
436 targetUri.cleanUp();
\r
441 private boolean transferFile(String sourceFileName, String targetFileName) throws Exception {
\r
442 boolean result = true;
\r
444 logger.info("Transfer clip {}", sourceFileName);
\r
446 sourceFtp = ((FtpDirectoryLister) sourceUri.getLister()).connect();
\r
447 targetFtp = ((FtpDirectoryLister) targetUri.getLister()).connect();
\r
448 if (!targetFtp.enterRemotePassiveMode())
\r
449 throw new Exception("!PASV");
\r
451 reply = sourceFtp.port(InetAddress.getByName(targetFtp.getPassiveHost()), targetFtp.getPassivePort());
\r
452 if (!FTPReply.isPositiveCompletion(reply))
\r
453 throw new Exception("PORT parancs válasza: " + sourceFtp.getReplyString());
\r
455 if (!sourceFtp.setFileType(FTP.BINARY_FILE_TYPE))
\r
456 throw new Exception("!SOURCE TYPE");
\r
458 reply = sourceFtp.retr(sourceFileName);
\r
459 if (!FTPReply.isPositivePreliminary(reply))
\r
460 throw new Exception("RETR parancs válasza: " + sourceFtp.getReplyString());
\r
462 if (!targetFtp.setFileType(FTP.BINARY_FILE_TYPE))
\r
463 throw new Exception("!TARGET TYPE");
\r
465 reply = targetFtp.stor(targetFileName);
\r
466 if (!FTPReply.isPositivePreliminary(reply))
\r
467 throw new Exception("STOR parancs válasza: " + sourceFtp.getReplyString());
\r
470 reply = sourceFtp.stat();
\r
471 if (!FTPReply.isPositiveCompletion(reply))
\r
472 throw new Exception("STAT parancs válasza: " + sourceFtp.getReplyString());
\r
474 logger.info("Status: {}", sourceFtp.getReplyString());
\r
475 if (reply == 226) {
\r
478 Thread.sleep(1000);
\r
480 } catch (Exception e) {
\r
481 logger.catching(e);
\r
484 sourceUri.cleanUp();
\r
485 targetUri.cleanUp();
\r
491 private void transferMetadata(String fileName, BasicDBObject metadata) throws Exception {
\r
492 logger.info("Transfer metadata {}", fileName);
\r
493 OutputStream outStream = null;
\r
495 targetFtp = ((FtpDirectoryLister) targetUri.getLister()).connect();
\r
496 if (!targetFtp.changeWorkingDirectory(EscortFiles.STATUSFOLDER)) {
\r
497 targetFtp.makeDirectory(EscortFiles.STATUSFOLDER);
\r
498 if (!targetFtp.changeWorkingDirectory(EscortFiles.STATUSFOLDER))
\r
499 throw new Exception("!STATUSFOLDER");
\r
502 outStream = targetFtp.storeFileStream(fileName + JSON_EXT);
\r
503 if (outStream == null) {
\r
504 throw new NullPointerException("Can not open: " + fileName + JSON_EXT + " Reply:" + targetFtp.getReplyString());
\r
506 outStream.write(metadata.toString().getBytes(UTF_8));
\r
508 //targetFtp.changeToParentDirectory();
\r
509 } catch (Exception e) {
\r
510 logger.catching(e);
\r
513 if (outStream != null)
\r
515 targetUri.cleanUp();
\r