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.configuration.SystemConfiguration;
\r
30 import user.commons.nosql.NoSQLUtils;
\r
31 import user.commons.octopus.IOctopusAPI;
\r
32 import user.commons.octopus.OctopusAPI;
\r
33 import user.commons.remotestore.FtpDirectoryLister;
\r
34 import user.commons.remotestore.RemoteStoreProtocol;
\r
35 import user.jobengine.db.IItemManager;
\r
36 import user.jobengine.server.IJobEngine;
\r
37 import user.jobengine.server.IJobRuntime;
\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 static String NEXIO_HOST = SystemConfiguration.getInstance().value("services.nexio.host");
\r
53 private OctopusAPI octopusAPI;
\r
54 private IItemManager manager;
\r
57 private FTPClient sourceFtp;
\r
58 private FTPClient targetFtp;
\r
59 private StoreUri sourceUri;
\r
60 private StoreUri targetUri;
\r
61 private int nexioKillDateDays;
\r
62 private String nexioAgency;
\r
63 private Marker systemMarker;
\r
64 private List<String> transferredFileNames = null;
\r
65 private boolean demo = false;
\r
67 private int check(int value, String name) {
\r
69 logger.error(systemMarker, "A folyamat '{}' bemeneti paramétere 0.", name);
\r
70 throw new NullPointerException(String.format("System is not configured properly, missing '%s' input parameter.", name));
\r
75 private String check(String value, String name) {
\r
76 if (value == null) {
\r
77 logger.error(systemMarker, "A folyamat '{}' bemeneti paramétere üres.", name);
\r
78 throw new NullPointerException(String.format("System is not configured properly, missing '%s' input parameter.", name));
\r
83 private void copy(RundownArchive rundownArchive) throws Exception {
\r
84 for (StoryArchive storyArchive : rundownArchive.getStoryArchives()) {
\r
85 for (FileArchive fileArchive : storyArchive.getFileArchives()) {
\r
87 copyFile(fileArchive, rundownArchive, storyArchive);
\r
88 } catch (Exception e) {
\r
89 logger.error(systemMarker, "A '{}' clip archiválása sikertelen. A rendszer üzenete: {}", fileArchive.getFileName(), e.getMessage());
\r
96 private void copyFile(FileArchive fileArchive, RundownArchive rundownArchive, StoryArchive storyArchive) throws Exception {
\r
97 String origFileName = fileArchive.getFileName();
\r
98 String fileName = String.format("%s-%s", origFileName, rundownArchive.getItemHouseId());
\r
99 String videoFileName = fileName + MXFEXT;
\r
101 if (transferredFileNames == null)
\r
102 transferredFileNames = new ArrayList<>();
\r
104 //A mar letezo mozikat nem archivaljuk le ujra, csak a metaadatot
\r
105 long existingMediaId = 0;
\r
106 boolean transferDone = false;
\r
107 if (transferredFileNames.contains(origFileName)) {
\r
108 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
111 transferDone = transferChunk(videoFileName);
\r
113 existingMediaId = ItemManagerExtensions.getExistingRundownMedia(manager, origFileName);
\r
114 if (existingMediaId == 0) {
\r
115 transferredFileNames.add(origFileName);
\r
117 transferDone = transferFile(origFileName + MXFEXT, videoFileName);
\r
118 logger.info(systemMarker, "A '{}' file archiválásra felkészítése sikeres volt.", origFileName);
\r
121 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
123 transferDone = transferChunk(videoFileName);
\r
127 if (!demo && transferDone) {
\r
128 BasicDBObject metadata = createMetadata(rundownArchive, storyArchive, fileArchive, existingMediaId);
\r
129 transferMetadata(videoFileName, metadata);
\r
130 createSourceKillDateFile(rundownArchive, origFileName);
\r
134 private BasicDBObject createMetadata(RundownArchive rundownArchive, StoryArchive storyArchive, FileArchive fileArchive, long existingMediaId) {
\r
135 BasicDBObject result = new BasicDBObject();
\r
136 result.put("itemHouseId", rundownArchive.getItemHouseId());
\r
137 result.put("itemTitle", rundownArchive.getItemTitle());
\r
138 result.put("itemDescription", rundownArchive.getItemDesc());
\r
139 result.put("userName", "mediacube");
\r
140 result.put("mediaHouseId", storyArchive.getMediaHouseId());
\r
141 result.put("mediaTitle", storyArchive.getMediaTitle());
\r
142 result.put("mediaDescription", storyArchive.getMediaDesc());
\r
143 result.put("mediaType", MEDIATYPE);
\r
144 result.put("duration", fileArchive.getDuration());
\r
145 result.put("existingMediaId", existingMediaId);
\r
149 private void createSourceKillDateFile(RundownArchive rundownArchive, String fileName) throws Exception {
\r
150 logger.info("Create killdate/agency for {}", fileName);
\r
151 OutputStream outStream = null;
\r
153 sourceFtp = ((FtpDirectoryLister) sourceUri.getLister()).connect();
\r
154 Calendar killDate = CalendarUtils.createCalendar(rundownArchive.getScheduleDate());
\r
155 killDate.add(Calendar.DAY_OF_YEAR, nexioKillDateDays);
\r
156 byte[] killDateFile = EscortFiles.createNEXIOKillDateFile(fileName, killDate.getTime(), null, nexioAgency);
\r
157 outStream = sourceFtp.storeFileStream(fileName + XML_EXT);
\r
158 if (outStream == null) {
\r
159 throw new NullPointerException("Can not open: " + fileName + XML_EXT + " Reply:" + sourceFtp.getReplyString());
\r
161 outStream.write(killDateFile);
\r
163 } catch (Exception e) {
\r
164 logger.catching(e);
\r
167 if (outStream != null)
\r
169 sourceUri.cleanUp();
\r
174 public Object[] execute(int nexioPort, String nexioUserName, String nexioPassword, String archiveFtp, String archiveUserName, String archivePassword,
\r
175 int daysBeforeNow, int nexioKillDateDays, String nexioAgency, IJobEngine jobEngine, IJobRuntime jobRuntime) throws Exception {
\r
176 systemMarker = jobRuntime.getSessionMarker();
\r
177 setAndCheck(nexioPort, nexioUserName, nexioPassword, archiveFtp, archiveUserName, archivePassword, nexioKillDateDays, nexioAgency, jobEngine);
\r
178 octopusAPI = new OctopusAPI();
\r
179 Calendar scheduledDate = Calendar.getInstance();
\r
180 scheduledDate.add(Calendar.DAY_OF_YEAR, -1 * daysBeforeNow);
\r
181 List<DBObject> rundowns = octopusAPI.getRundowns(scheduledDate.getTime());
\r
182 if (rundowns == null) {
\r
183 logger.warn(systemMarker, "Nem található adástükör a {} napra.", CalendarUtils.toDateString(scheduledDate));
\r
187 processRundowns(rundowns);
\r
191 // private String getVersionedFileName(String fileName, String extension) throws Exception {
\r
192 // String result = fileName;
\r
194 // targetFtp = ((FtpDirectoryLister) targetUri.getLister()).connect();
\r
195 // FTPFile[] listFiles = targetFtp.listFiles();
\r
196 // List<String> fileNames = new ArrayList<>();
\r
197 // for (FTPFile ftpFile : listFiles) {
\r
198 // fileNames.add(ftpFile.getName());
\r
200 // while (fileNames.contains(result + extension)) {
\r
204 // } catch (Exception e) {
\r
205 // logger.catching(e);
\r
208 // targetUri.cleanUp();
\r
213 private FileArchive processMosObject(BasicDBObject rundown, BasicDBObject story, BasicDBObject mosObject) throws Exception {
\r
214 String mosID = mosObject.getString(IOctopusAPI.OBJ_ID);
\r
215 if (MetadataTypeDetector.GuessMetadataType(mosID) != MetadataType.OctopusPlaceholder) {
\r
216 logger.trace("Skipping MOS object {}", mosID);
\r
219 DBCollection clips = db.getCollection(NEXIOCLIPS);
\r
220 BasicDBObject clip = (BasicDBObject) clips.findOne(new BasicDBObject(LONGNAMEID, mosID));
\r
221 if (clip == null) {
\r
222 logger.debug("File {} NOT exists", mosID);
\r
224 //throw new Exception(String.format("File NOT exists %s", mosID));
\r
226 logger.debug("File {} exists", mosID);
\r
228 long duration = NoSQLUtils.asLong(clip, DURATION);
\r
230 if (duration == 0) {
\r
231 logger.debug("File {} exists with 0 frame length", mosID);
\r
234 if (duration == 1) {
\r
235 logger.debug("File {} exists with 1 frame length", mosID);
\r
238 return new FileArchive(mosID, duration);
\r
241 private RundownArchive processRundow(DBObject r) throws Exception {
\r
242 BasicDBObject rundown = (BasicDBObject) r;
\r
243 long rundownID = rundown.getLong(ID);
\r
245 logger.info("Processing rundown {} {}", rundownID, rundown.getString(IOctopusAPI.NAME));
\r
246 List<DBObject> stories = octopusAPI.getRundownFullStories(rundownID);
\r
247 if (stories == null)
\r
249 RundownArchive result = new RundownArchive();
\r
251 long id = NoSQLUtils.asLong(rundown, IOctopusAPI.ID);
\r
254 String name = NoSQLUtils.asString(NoSQLUtils.asDBObject(rundown, IOctopusAPI.RUNDOWN_TYPE), IOctopusAPI.NAME);
\r
255 if (StringUtils.isBlank(name))
\r
257 String channel = NoSQLUtils.asString(NoSQLUtils.asDBObject(rundown, IOctopusAPI.CHANNEL), IOctopusAPI.NAME);
\r
258 Date scheduledStart = rundown.getDate(IOctopusAPI.SCHEDULED_START);
\r
259 if (scheduledStart == null)
\r
261 String start = CalendarUtils.toString(CalendarUtils.createCalendar(scheduledStart), SCHEDULED_FORMAT);
\r
262 result.setScheduleDate(scheduledStart);
\r
263 result.setItemHouseId(String.valueOf(id));
\r
264 result.setItemTitle(String.format("%s %s %s", start, name, channel));
\r
266 for (DBObject s : stories) {
\r
267 StoryArchive storyArchive = processStory(rundown, s);
\r
268 if (storyArchive == null)
\r
270 result.addStoryArchive(storyArchive);
\r
275 private void processRundowns(List<DBObject> rundowns) {
\r
277 //TODO kiveni publikálás előtt
\r
278 //db.getCollection(ARCHIVEDRUNDOWNS).drop();
\r
279 List<BasicDBObject> archivedRundowns = queryArchivedRundowns();
\r
283 for (DBObject r : rundowns) {
\r
284 BasicDBObject rundown = (BasicDBObject) r;
\r
285 setProgress(index * 100 / rundowns.size());
\r
286 long rundownID = NoSQLUtils.asLong(rundown, IOctopusAPI.ID);
\r
287 String rundownName = NoSQLUtils.asString(rundown, IOctopusAPI.NAME);
\r
289 BasicDBObject currentRundownID = new BasicDBObject(IOctopusAPI.ID, rundownID);
\r
290 if (!demo && archivedRundowns != null && archivedRundowns.contains(currentRundownID)) {
\r
291 logger.info("Skipping archived rundown {} {}", rundownID, rundownName);
\r
295 RundownArchive rundownArchive = processRundow(r);
\r
296 if (rundownArchive == null || rundownArchive.isEmpty()) {
\r
298 logger.info("Skipping rundown {} {}", rundownID, rundownName);
\r
303 logger.info("Saving rundown {} {}", rundownID, rundownName);
\r
304 copy(rundownArchive);
\r
306 logger.info(systemMarker, "A '{}' tükör {}db bejátszójának archiválása sikeres volt", rundownArchive.getItemTitle(),
\r
307 rundownArchive.getStoryArchives().size());
\r
310 db.getCollection(ARCHIVEDRUNDOWNS).save(currentRundownID);
\r
311 } catch (Exception e) {
\r
312 logger.catching(e);
\r
313 logger.error(systemMarker,
\r
314 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
315 rundownName, e.getMessage()));
\r
322 private StoryArchive processStory(BasicDBObject rundown, DBObject s) throws Exception {
\r
323 BasicDBObject story = (BasicDBObject) s;
\r
324 String parentStoryID = story.getString(IOctopusAPI.PARENT_STORY_ID);
\r
325 if (StringUtils.isBlank(parentStoryID)) {
\r
326 logger.warn("Story parentStoryID is null: {}", story.toPrettyString(null));
\r
329 logger.debug("Processing story {}", parentStoryID);
\r
330 List<BasicDBObject> mosObjects = NoSQLUtils.asList(story, IOctopusAPI.MOS_OBJECTS);
\r
331 if (mosObjects == null)
\r
333 StoryArchive storyArchive = null;
\r
334 for (BasicDBObject mosObject : mosObjects) {
\r
335 FileArchive fileArchive = processMosObject(rundown, story, mosObject);
\r
336 if (fileArchive == null)
\r
338 if (storyArchive == null) {
\r
339 storyArchive = new StoryArchive();
\r
340 storyArchive.setMediaHouseId(parentStoryID);
\r
341 storyArchive.setMediaTitle(story.getString(IOctopusAPI.NAME));
\r
342 storyArchive.setMediaDesc(story.getString(IOctopusAPI.SCRIPT_CONTENT));
\r
345 storyArchive.addFileArchive(fileArchive);
\r
347 return storyArchive;
\r
351 private List<BasicDBObject> queryArchivedRundowns() {
\r
352 List<BasicDBObject> result = null;
\r
353 DBCollection collection = db.getCollection(ARCHIVEDRUNDOWNS);
\r
354 DBCursor find = collection.find(new BasicDBObject(), new BasicDBObject(IOctopusAPI._ID, 0).append(IOctopusAPI.ID, 1));
\r
355 if (find.hasNext())
\r
356 result = ListUtils.cast(find.toArray());
\r
360 private void setAndCheck(int nexioPort, String nexioUserName, String nexioPassword, String archiveFtp, String archiveUserName, String archivePassword,
\r
361 int nexioKillDateDays, String nexioAgency, IJobEngine jobEngine) throws Exception {
\r
362 db = NoSQLUtils.getNoSQLDB();
\r
364 logger.error(systemMarker, "Az NoSQL adatkezelő réteg nem elérhető.");
\r
365 throw new NullPointerException("Internal error, missing NoSQL DB reference.");
\r
368 if (jobEngine == null) {
\r
369 logger.error(systemMarker, "Az folyamatkezelő réteg nem elérhető.");
\r
370 throw new NullPointerException("Internal error, missing JobEngine reference.");
\r
372 manager = jobEngine.getItemManager();
\r
373 if (manager == null) {
\r
374 logger.error(systemMarker, "Az adatbáziskezelő réteg nem elérhető.");
\r
375 throw new NullPointerException("Internal error, missing ItemManager reference.");
\r
378 if (StringUtils.isBlank(NEXIO_HOST)) {
\r
379 logger.error(systemMarker, "A 'nexio.host' rendszer paraméter nem található.");
\r
380 throw new NullPointerException("System is not configured properly, 'jobengine.selenio.address' startup parameter missing.");
\r
382 check(nexioPort, "nexioPort");
\r
383 check(nexioUserName, "nexioUserName");
\r
384 check(nexioPassword, "nexioPassword");
\r
386 check(nexioKillDateDays, "nexioKillDateDays");
\r
387 this.nexioKillDateDays = nexioKillDateDays;
\r
388 check(nexioAgency, "nexioAgency");
\r
389 this.nexioAgency = nexioAgency;
\r
391 sourceUri = manager.createStoreUri(RemoteStoreProtocol.FTP, NEXIO_HOST);
\r
392 sourceUri.setPortNumber(nexioPort);
\r
393 sourceUri.setUserName(nexioUserName);
\r
394 sourceUri.setPassword(nexioPassword);
\r
395 if (sourceUri == null) {
\r
396 logger.error(systemMarker, "A forrás nem elérhető.");
\r
397 throw new NullPointerException("Internal error, missing 'sourceUri'.");
\r
400 check(archiveFtp, "archiveFtp");
\r
401 check(archiveUserName, "archiveUserName");
\r
402 check(archivePassword, "archivePassword");
\r
404 targetUri = manager.createStoreUri(new URI(archiveFtp));
\r
405 targetUri.setUserName(archiveUserName);
\r
406 targetUri.setPassword(archivePassword);
\r
407 if (targetUri == null) {
\r
408 logger.error(systemMarker, "A cél nem elérhető.");
\r
409 throw new NullPointerException("Internal error, missing 'targetUri'.");
\r
414 private boolean transferChunk(String fileName) throws Exception {
\r
415 logger.info("Transfer chunk {}", fileName);
\r
416 OutputStream outStream = null;
\r
418 targetFtp = ((FtpDirectoryLister) targetUri.getLister()).connect();
\r
420 //ha ugyan abban a tukorben szerepel meg 1x a mozi, akkor a chunk felulirja a tenyleges file-t, es az sosem archivalodik
\r
421 String[] names = targetFtp.listNames();
\r
422 if (names != null) {
\r
423 if (Arrays.asList(names).contains(fileName))
\r
427 outStream = targetFtp.storeFileStream(fileName);
\r
428 if (outStream == null) {
\r
429 throw new NullPointerException("Can not open: " + fileName + " Reply:" + targetFtp.getReplyString());
\r
431 } catch (Exception e) {
\r
432 logger.catching(e);
\r
435 if (outStream != null)
\r
437 targetUri.cleanUp();
\r
442 private boolean transferFile(String sourceFileName, String targetFileName) throws Exception {
\r
443 boolean result = true;
\r
445 logger.info("Transfer clip {}", sourceFileName);
\r
447 sourceFtp = ((FtpDirectoryLister) sourceUri.getLister()).connect();
\r
448 targetFtp = ((FtpDirectoryLister) targetUri.getLister()).connect();
\r
449 if (!targetFtp.enterRemotePassiveMode())
\r
450 throw new Exception("!PASV");
\r
452 reply = sourceFtp.port(InetAddress.getByName(targetFtp.getPassiveHost()), targetFtp.getPassivePort());
\r
453 if (!FTPReply.isPositiveCompletion(reply))
\r
454 throw new Exception("PORT parancs válasza: " + sourceFtp.getReplyString());
\r
456 if (!sourceFtp.setFileType(FTP.BINARY_FILE_TYPE))
\r
457 throw new Exception("!SOURCE TYPE");
\r
459 reply = sourceFtp.retr(sourceFileName);
\r
460 if (!FTPReply.isPositivePreliminary(reply))
\r
461 throw new Exception("RETR parancs válasza: " + sourceFtp.getReplyString());
\r
463 if (!targetFtp.setFileType(FTP.BINARY_FILE_TYPE))
\r
464 throw new Exception("!TARGET TYPE");
\r
466 reply = targetFtp.stor(targetFileName);
\r
467 if (!FTPReply.isPositivePreliminary(reply))
\r
468 throw new Exception("STOR parancs válasza: " + sourceFtp.getReplyString());
\r
471 reply = sourceFtp.stat();
\r
472 if (!FTPReply.isPositiveCompletion(reply))
\r
473 throw new Exception("STAT parancs válasza: " + sourceFtp.getReplyString());
\r
475 logger.info("Status: {}", sourceFtp.getReplyString());
\r
476 if (reply == 226) {
\r
479 Thread.sleep(1000);
\r
481 } catch (Exception e) {
\r
482 logger.catching(e);
\r
485 sourceUri.cleanUp();
\r
486 targetUri.cleanUp();
\r
492 private void transferMetadata(String fileName, BasicDBObject metadata) throws Exception {
\r
493 logger.info("Transfer metadata {}", fileName);
\r
494 OutputStream outStream = null;
\r
496 targetFtp = ((FtpDirectoryLister) targetUri.getLister()).connect();
\r
497 if (!targetFtp.changeWorkingDirectory(EscortFiles.STATUSFOLDER)) {
\r
498 targetFtp.makeDirectory(EscortFiles.STATUSFOLDER);
\r
499 if (!targetFtp.changeWorkingDirectory(EscortFiles.STATUSFOLDER))
\r
500 throw new Exception("!STATUSFOLDER");
\r
503 outStream = targetFtp.storeFileStream(fileName + JSON_EXT);
\r
504 if (outStream == null) {
\r
505 throw new NullPointerException("Can not open: " + fileName + JSON_EXT + " Reply:" + targetFtp.getReplyString());
\r
507 outStream.write(metadata.toString().getBytes(UTF_8));
\r
509 //targetFtp.changeToParentDirectory();
\r
510 } catch (Exception e) {
\r
511 logger.catching(e);
\r
514 if (outStream != null)
\r
516 targetUri.cleanUp();
\r