1 package user.jobengine.server.steps;
\r
3 import java.io.OutputStream;
\r
4 import java.net.InetAddress;
\r
6 import java.util.Calendar;
\r
7 import java.util.Date;
\r
8 import java.util.List;
\r
10 import org.apache.commons.lang.StringUtils;
\r
11 import org.apache.commons.net.ftp.FTP;
\r
12 import org.apache.commons.net.ftp.FTPClient;
\r
13 import org.apache.commons.net.ftp.FTPReply;
\r
14 import org.apache.logging.log4j.LogManager;
\r
15 import org.apache.logging.log4j.Logger;
\r
17 import com.ibm.nosql.json.api.BasicDBObject;
\r
18 import com.ibm.nosql.json.api.DB;
\r
19 import com.ibm.nosql.json.api.DBCollection;
\r
20 import com.ibm.nosql.json.api.DBCursor;
\r
21 import com.ibm.nosql.json.api.DBObject;
\r
23 import user.commons.CalendarUtils;
\r
24 import user.commons.ListUtils;
\r
25 import user.commons.StoreUri;
\r
26 import user.commons.nosql.NoSQLUtils;
\r
27 import user.commons.octopus.IOctopusAPI;
\r
28 import user.commons.octopus.OctopusAPI;
\r
29 import user.commons.remotestore.FtpDirectoryLister;
\r
30 import user.commons.remotestore.RemoteStoreProtocol;
\r
31 import user.jobengine.db.IItemManager;
\r
32 import user.jobengine.server.IJobEngine;
\r
33 import user.jobengine.server.IJobRuntime;
\r
34 import user.jobengine.server.steps.MetadataTypeDetector.MetadataType;
\r
36 public class CopyForArchiveNEXIOMaterialsStep extends JobStep {
\r
37 private static final String SCHEDULED_FORMAT = "yyyy.MM.dd HH:mm";
\r
38 private static final Logger logger = LogManager.getLogger();
\r
39 private static final String UTF_8 = "utf-8";
\r
40 private static final String JSON_EXT = ".json";
\r
41 private static final String XML_EXT = ".xml";
\r
42 private static final String DURATION = "duration";
\r
43 private static final String MXFEXT = ".MXF";
\r
44 private static final String NEXIOCLIPS = "nexioclips";
\r
45 private static final String LONGNAMEID = "longnameid";
\r
46 private static final String ARCHIVEDRUNDOWNS = "archivedrundowns";
\r
47 private static final String ID = "id";
\r
48 private static final String MEDIATYPE = "Hír bejátszó";
\r
49 private OctopusAPI octopusAPI;
\r
50 private IItemManager manager;
\r
53 private FTPClient sourceFtp;
\r
54 private FTPClient targetFtp;
\r
55 private StoreUri sourceUri;
\r
56 private StoreUri targetUri;
\r
57 private int nexioKillDateDays;
\r
58 private String nexioAgency;
\r
60 private int check(int value, String name) {
\r
62 logger.error(getMarker(), "A folyamat '{}' bemeneti paramétere 0.", name);
\r
63 throw new NullPointerException(String.format("System is not configured properly, missing '%s' input parameter.", name));
\r
68 private String check(String value, String name) {
\r
69 if (value == null) {
\r
70 logger.error(getMarker(), "A folyamat '{}' bemeneti paramétere üres.", name);
\r
71 throw new NullPointerException(String.format("System is not configured properly, missing '%s' input parameter.", name));
\r
76 private void copy(RundownArchive rundownArchive) throws Exception {
\r
77 for (StoryArchive storyArchive : rundownArchive.getStoryArchives()) {
\r
78 for (FileArchive fileArchive : storyArchive.getFileArchives()) {
\r
80 copyFile(fileArchive, rundownArchive, storyArchive);
\r
81 } catch (Exception e) {
\r
82 logger.error(getMarker(), "A '{}' clip archiválása sikertelen. A rendszer üzenete: {}", fileArchive.getFileName(), e.getMessage());
\r
88 private void copyFile(FileArchive fileArchive, RundownArchive rundownArchive, StoryArchive storyArchive) throws Exception {
\r
89 String origFileName = fileArchive.getFileName();
\r
90 String fileName = String.format("%s-%s", origFileName, rundownArchive.getItemHouseId());
\r
91 String videoFileName = fileName + MXFEXT;
\r
93 //A mar letezo mozikat nem archivaljuk le ujra, csak a metaadatot
\r
94 long existingMediaId = manager.getExistingRundownMedia(origFileName);
\r
95 if (existingMediaId == 0)
\r
96 transferFile(origFileName + MXFEXT, videoFileName);
\r
98 transferChunk(origFileName);
\r
100 BasicDBObject metadata = createMetadata(rundownArchive, storyArchive, fileArchive, existingMediaId);
\r
101 transferMetadata(videoFileName, metadata);
\r
102 createSourceKillDateFile(rundownArchive, origFileName);
\r
105 private BasicDBObject createMetadata(RundownArchive rundownArchive, StoryArchive storyArchive, FileArchive fileArchive, long existingMediaId) {
\r
106 BasicDBObject result = new BasicDBObject();
\r
107 result.put("itemHouseId", rundownArchive.getItemHouseId());
\r
108 result.put("itemTitle", rundownArchive.getItemTitle());
\r
109 result.put("itemDescription", rundownArchive.getItemDesc());
\r
110 result.put("userName", "mediacube");
\r
111 result.put("mediaHouseId", storyArchive.getMediaHouseId());
\r
112 result.put("mediaTitle", storyArchive.getMediaTitle());
\r
113 result.put("mediaDescription", storyArchive.getMediaDesc());
\r
114 result.put("mediaType", MEDIATYPE);
\r
115 result.put("duration", fileArchive.getDuration());
\r
116 result.put("existingMediaId", existingMediaId);
\r
120 private void createSourceKillDateFile(RundownArchive rundownArchive, String fileName) throws Exception {
\r
121 logger.info("Create killdate/agency for {}", fileName);
\r
122 OutputStream outStream = null;
\r
124 sourceFtp = ((FtpDirectoryLister) sourceUri.getLister()).connect();
\r
125 Calendar killDate = CalendarUtils.createCalendar(rundownArchive.getScheduleDate());
\r
126 killDate.add(Calendar.DAY_OF_YEAR, nexioKillDateDays);
\r
127 byte[] killDateFile = EscortFiles.createNEXIOKillDateFile(fileName, killDate.getTime(), null, nexioAgency);
\r
128 outStream = sourceFtp.storeFileStream(fileName + XML_EXT);
\r
129 if (outStream == null) {
\r
130 throw new NullPointerException("Can not open: " + fileName + XML_EXT + " Reply:" + sourceFtp.getReplyString());
\r
132 outStream.write(killDateFile);
\r
134 } catch (Exception e) {
\r
135 logger.catching(e);
\r
138 if (outStream != null)
\r
140 sourceUri.cleanUp();
\r
145 public Object[] execute(int nexioPort, String nexioUserName, String nexioPassword, String archiveFtp, String archiveUserName, String archivePassword,
\r
146 int daysBeforeNow, int nexioKillDateDays, String nexioAgency, IJobEngine jobEngine, IJobRuntime jobRuntime) throws Exception {
\r
147 setAndCheck(nexioPort, nexioUserName, nexioPassword, archiveFtp, archiveUserName, archivePassword, nexioKillDateDays, nexioAgency, jobEngine);
\r
148 octopusAPI = new OctopusAPI();
\r
149 Calendar scheduledDate = Calendar.getInstance();
\r
150 scheduledDate.add(Calendar.DAY_OF_YEAR, -1 * daysBeforeNow);
\r
151 List<DBObject> rundowns = octopusAPI.getRundowns(scheduledDate.getTime());
\r
152 if (rundowns == null) {
\r
153 logger.warn(getMarker(), "Nem található adástükör a {} napra.", CalendarUtils.toDateString(scheduledDate));
\r
157 processRundowns(rundowns);
\r
161 // private String getVersionedFileName(String fileName, String extension) throws Exception {
\r
162 // String result = fileName;
\r
164 // targetFtp = ((FtpDirectoryLister) targetUri.getLister()).connect();
\r
165 // FTPFile[] listFiles = targetFtp.listFiles();
\r
166 // List<String> fileNames = new ArrayList<>();
\r
167 // for (FTPFile ftpFile : listFiles) {
\r
168 // fileNames.add(ftpFile.getName());
\r
170 // while (fileNames.contains(result + extension)) {
\r
174 // } catch (Exception e) {
\r
175 // logger.catching(e);
\r
178 // targetUri.cleanUp();
\r
183 private FileArchive processMosObject(BasicDBObject rundown, BasicDBObject story, BasicDBObject mosObject) throws Exception {
\r
184 String mosID = mosObject.getString(IOctopusAPI.OBJ_ID);
\r
185 if (MetadataTypeDetector.GuessMetadataType(mosID) != MetadataType.OCTOPUSPLACEHOLDER) {
\r
186 logger.trace("Skipping MOS object {}", mosID);
\r
189 DBCollection clips = db.getCollection(NEXIOCLIPS);
\r
190 BasicDBObject clip = (BasicDBObject) clips.findOne(new BasicDBObject(LONGNAMEID, mosID));
\r
191 if (clip == null) {
\r
192 logger.debug("File NOT exists {}", mosID);
\r
194 //throw new Exception(String.format("File NOT exists %s", mosID));
\r
196 logger.debug("File exists {}", mosID);
\r
198 long duration = NoSQLUtils.asLong(clip, DURATION);
\r
199 return new FileArchive(mosID, duration);
\r
202 private RundownArchive processRundow(DBObject r) throws Exception {
\r
203 BasicDBObject rundown = (BasicDBObject) r;
\r
204 long rundownID = rundown.getLong(ID);
\r
205 logger.info("Processing rundown {} {}", rundownID, rundown.getString(IOctopusAPI.NAME));
\r
206 List<DBObject> stories = octopusAPI.getRundownFullStories(rundownID);
\r
207 if (stories == null)
\r
209 RundownArchive result = new RundownArchive();
\r
211 long id = NoSQLUtils.asLong(rundown, IOctopusAPI.ID);
\r
214 String name = NoSQLUtils.asString(NoSQLUtils.asDBObject(rundown, IOctopusAPI.RUNDOWN_TYPE), IOctopusAPI.NAME);
\r
215 if (StringUtils.isBlank(name))
\r
217 String channel = NoSQLUtils.asString(NoSQLUtils.asDBObject(rundown, IOctopusAPI.CHANNEL), IOctopusAPI.NAME);
\r
218 Date scheduledStart = rundown.getDate(IOctopusAPI.SCHEDULED_START);
\r
219 if (scheduledStart == null)
\r
221 String start = CalendarUtils.toString(CalendarUtils.createCalendar(scheduledStart), SCHEDULED_FORMAT);
\r
222 result.setScheduleDate(scheduledStart);
\r
223 result.setItemHouseId(String.valueOf(id));
\r
224 result.setItemTitle(String.format("%s %s %s", start, name, channel));
\r
226 for (DBObject s : stories) {
\r
227 StoryArchive storyArchive = processStory(rundown, s);
\r
228 if (storyArchive == null)
\r
230 result.addStoryArchive(storyArchive);
\r
235 private void processRundowns(List<DBObject> rundowns) {
\r
237 //TODO kiveni publikálás előtt
\r
238 //db.getCollection(ARCHIVEDRUNDOWNS).drop();
\r
239 List<BasicDBObject> archivedRundowns = queryArchivedRundowns();
\r
243 for (DBObject r : rundowns) {
\r
244 BasicDBObject rundown = (BasicDBObject) r;
\r
245 setProgress(index * 100 / rundowns.size());
\r
246 long rundownID = NoSQLUtils.asLong(rundown, IOctopusAPI.ID);
\r
247 String rundownName = NoSQLUtils.asString(rundown, IOctopusAPI.NAME);
\r
249 BasicDBObject currentRundownID = new BasicDBObject(IOctopusAPI.ID, rundownID);
\r
250 if (archivedRundowns != null && archivedRundowns.contains(currentRundownID)) {
\r
251 logger.info("Skipping archived rundown {} {}", rundownID, rundownName);
\r
255 RundownArchive rundownArchive = processRundow(r);
\r
256 if (rundownArchive == null || rundownArchive.isEmpty()) {
\r
257 logger.info("Skipping rundown {} {}", rundownID, rundownName);
\r
261 logger.info("Saving rundown {} {}", rundownID, rundownName);
\r
262 copy(rundownArchive);
\r
264 db.getCollection(ARCHIVEDRUNDOWNS).save(currentRundownID);
\r
265 } catch (Exception e) {
\r
266 logger.catching(e);
\r
267 logger.error(getMarker(),
\r
268 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
269 rundownName, e.getMessage()));
\r
276 private StoryArchive processStory(BasicDBObject rundown, DBObject s) throws Exception {
\r
277 BasicDBObject story = (BasicDBObject) s;
\r
278 String parentStoryID = story.getString(IOctopusAPI.PARENT_STORY_ID);
\r
279 if (StringUtils.isBlank(parentStoryID)) {
\r
280 logger.warn("Story parentStoryID is null: {}", story.toPrettyString(null));
\r
283 logger.debug("Processing story {}", parentStoryID);
\r
284 List<BasicDBObject> mosObjects = NoSQLUtils.asList(story, IOctopusAPI.MOS_OBJECTS);
\r
285 if (mosObjects == null)
\r
287 StoryArchive storyArchive = null;
\r
288 for (BasicDBObject mosObject : mosObjects) {
\r
289 FileArchive fileArchive = processMosObject(rundown, story, mosObject);
\r
290 if (fileArchive == null)
\r
292 if (storyArchive == null) {
\r
293 storyArchive = new StoryArchive();
\r
294 storyArchive.setMediaHouseId(parentStoryID);
\r
295 storyArchive.setMediaTitle(story.getString(IOctopusAPI.NAME));
\r
296 storyArchive.setMediaDesc(story.getString(IOctopusAPI.SCRIPT_CONTENT));
\r
299 storyArchive.addFileArchive(fileArchive);
\r
301 return storyArchive;
\r
305 private List<BasicDBObject> queryArchivedRundowns() {
\r
306 List<BasicDBObject> result = null;
\r
307 DBCollection collection = db.getCollection(ARCHIVEDRUNDOWNS);
\r
308 DBCursor find = collection.find(new BasicDBObject(), new BasicDBObject(IOctopusAPI._ID, 0).append(IOctopusAPI.ID, 1));
\r
309 if (find.hasNext())
\r
310 result = ListUtils.cast(find.toArray());
\r
314 private void setAndCheck(int nexioPort, String nexioUserName, String nexioPassword, String archiveFtp, String archiveUserName, String archivePassword,
\r
315 int nexioKillDateDays, String nexioAgency, IJobEngine jobEngine) throws Exception {
\r
316 db = NoSQLUtils.getNoSQLDB();
\r
318 logger.error(getMarker(), "Az NoSQL adatkezelő réteg nem elérhető.");
\r
319 throw new NullPointerException("Internal error, missing NoSQL DB reference.");
\r
322 if (jobEngine == null) {
\r
323 logger.error(getMarker(), "Az folyamatkezelő réteg nem elérhető.");
\r
324 throw new NullPointerException("Internal error, missing JobEngine reference.");
\r
326 manager = jobEngine.getItemManager();
\r
327 if (manager == null) {
\r
328 logger.error(getMarker(), "Az adatbáziskezelő réteg nem elérhető.");
\r
329 throw new NullPointerException("Internal error, missing ItemManager reference.");
\r
331 String nexioHost = System.getProperty("nexio.host");
\r
332 if (StringUtils.isBlank(nexioHost)) {
\r
333 logger.error(getMarker(), "A 'nexio.host' rendszer paraméter nem található.");
\r
334 throw new NullPointerException("System is not configured properly, 'jobengine.selenio.address' startup parameter missing.");
\r
336 check(nexioPort, "nexioPort");
\r
337 check(nexioUserName, "nexioUserName");
\r
338 check(nexioPassword, "nexioPassword");
\r
340 check(nexioKillDateDays, "nexioKillDateDays");
\r
341 this.nexioKillDateDays = nexioKillDateDays;
\r
342 check(nexioAgency, "nexioAgency");
\r
343 this.nexioAgency = nexioAgency;
\r
345 sourceUri = manager.createStoreUri(RemoteStoreProtocol.FTP, nexioHost);
\r
346 sourceUri.setPortNumber(nexioPort);
\r
347 sourceUri.setUserName(nexioUserName);
\r
348 sourceUri.setPassword(nexioPassword);
\r
349 if (sourceUri == null) {
\r
350 logger.error(getMarker(), "A forrás nem elérhető.");
\r
351 throw new NullPointerException("Internal error, missing 'sourceUri'.");
\r
354 check(archiveFtp, "archiveFtp");
\r
355 check(archiveUserName, "archiveUserName");
\r
356 check(archivePassword, "archivePassword");
\r
358 targetUri = manager.createStoreUri(new URI(archiveFtp));
\r
359 targetUri.setUserName(archiveUserName);
\r
360 targetUri.setPassword(archivePassword);
\r
361 if (targetUri == null) {
\r
362 logger.error(getMarker(), "A cél nem elérhető.");
\r
363 throw new NullPointerException("Internal error, missing 'targetUri'.");
\r
368 private void transferChunk(String fileName) throws Exception {
\r
369 logger.info("Transfer chunk {}", fileName);
\r
370 OutputStream outStream = null;
\r
372 outStream = targetFtp.storeFileStream(fileName + MXFEXT);
\r
373 if (outStream == null) {
\r
374 throw new NullPointerException("Can not open: " + fileName + MXFEXT + " Reply:" + targetFtp.getReplyString());
\r
376 } catch (Exception e) {
\r
377 logger.catching(e);
\r
380 if (outStream != null)
\r
382 targetUri.cleanUp();
\r
386 private void transferFile(String sourceFileName, String targetFileName) throws Exception {
\r
388 logger.info("Transfer clip {}", sourceFileName);
\r
390 sourceFtp = ((FtpDirectoryLister) sourceUri.getLister()).connect();
\r
391 targetFtp = ((FtpDirectoryLister) targetUri.getLister()).connect();
\r
392 if (!targetFtp.enterRemotePassiveMode())
\r
393 throw new Exception("!PASV");
\r
395 reply = sourceFtp.port(InetAddress.getByName(targetFtp.getPassiveHost()), targetFtp.getPassivePort());
\r
396 if (!FTPReply.isPositiveCompletion(reply))
\r
397 throw new Exception("PORT parancs válasza: " + sourceFtp.getReplyString());
\r
399 if (!sourceFtp.setFileType(FTP.BINARY_FILE_TYPE))
\r
400 throw new Exception("!SOURCE TYPE");
\r
402 reply = sourceFtp.retr(sourceFileName);
\r
403 if (!FTPReply.isPositivePreliminary(reply))
\r
404 throw new Exception("RETR parancs válasza: " + sourceFtp.getReplyString());
\r
406 if (!targetFtp.setFileType(FTP.BINARY_FILE_TYPE))
\r
407 throw new Exception("!TARGET TYPE");
\r
409 reply = targetFtp.stor(targetFileName);
\r
410 if (!FTPReply.isPositivePreliminary(reply))
\r
411 throw new Exception("STOR parancs válasza: " + sourceFtp.getReplyString());
\r
414 reply = sourceFtp.stat();
\r
415 if (!FTPReply.isPositiveCompletion(reply))
\r
416 throw new Exception("STAT parancs válasza: " + sourceFtp.getReplyString());
\r
418 logger.info("Status: {}", sourceFtp.getReplyString());
\r
419 if (reply == 226) {
\r
422 Thread.sleep(1000);
\r
424 } catch (Exception e) {
\r
425 logger.catching(e);
\r
428 sourceUri.cleanUp();
\r
429 targetUri.cleanUp();
\r
434 private void transferMetadata(String fileName, BasicDBObject metadata) throws Exception {
\r
435 logger.info("Transfer metadata {}", fileName);
\r
436 OutputStream outStream = null;
\r
438 targetFtp = ((FtpDirectoryLister) targetUri.getLister()).connect();
\r
439 if (!targetFtp.changeWorkingDirectory(EscortFiles.STATUSFOLDER)) {
\r
440 targetFtp.makeDirectory(EscortFiles.STATUSFOLDER);
\r
441 if (!targetFtp.changeWorkingDirectory(EscortFiles.STATUSFOLDER))
\r
442 throw new Exception("!STATUSFOLDER");
\r
445 outStream = targetFtp.storeFileStream(fileName + JSON_EXT);
\r
446 if (outStream == null) {
\r
447 throw new NullPointerException("Can not open: " + fileName + JSON_EXT + " Reply:" + targetFtp.getReplyString());
\r
449 outStream.write(metadata.toString().getBytes(UTF_8));
\r
451 //targetFtp.changeToParentDirectory();
\r
452 } catch (Exception e) {
\r
453 logger.catching(e);
\r
456 if (outStream != null)
\r
458 targetUri.cleanUp();
\r