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.RemoteFileHandler;
\r
31 import user.commons.remotestore.RemoteStoreProtocol;
\r
32 import user.jobengine.db.IItemManager;
\r
33 import user.jobengine.server.IJobEngine;
\r
34 import user.jobengine.server.IJobRuntime;
\r
35 import user.jobengine.server.steps.MetadataTypeDetector.MetadataType;
\r
37 public class CopyForArchiveNEXIOMaterialsStep extends JobStep {
\r
38 private static final String SCHEDULED_FORMAT = "yyyy.MM.dd HH:mm";
\r
39 private static final Logger logger = LogManager.getLogger();
\r
40 private static final String ARCHIVED = "ARCHIVED";
\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 OctopusAPI octopusAPI;
\r
51 private IItemManager manager;
\r
54 private FTPClient sourceFtp;
\r
55 private FTPClient targetFtp;
\r
56 private StoreUri sourceUri;
\r
57 private StoreUri targetUri;
\r
58 private int nexioKillDateDays;
\r
59 private String nexioAgency;
\r
61 private int check(int value, String name) {
\r
63 logger.error(getMarker(), "A folyamat '{}' bemeneti paramétere 0.", name);
\r
64 throw new NullPointerException(String.format("System is not configured properly, missing '%s' input parameter.", name));
\r
69 private String check(String value, String name) {
\r
70 if (value == null) {
\r
71 logger.error(getMarker(), "A folyamat '{}' bemeneti paramétere üres.", name);
\r
72 throw new NullPointerException(String.format("System is not configured properly, missing '%s' input parameter.", name));
\r
77 private void copy(RundownArchive rundownArchive) throws Exception {
\r
78 for (StoryArchive storyArchive : rundownArchive.getStoryArchives()) {
\r
79 for (FileArchive fileArchive : storyArchive.getFileArchives()) {
\r
80 copyFile(fileArchive, rundownArchive, storyArchive);
\r
85 private void copyFile(FileArchive fileArchive, RundownArchive rundownArchive, StoryArchive storyArchive) throws Exception {
\r
86 String fileName = fileArchive.getFileName();
\r
87 String videoFileName = fileName + MXFEXT;
\r
88 transferFile(videoFileName);
\r
89 BasicDBObject metadata = createMetadata(rundownArchive, storyArchive, fileArchive);
\r
91 if (!targetFtp.changeWorkingDirectory(EscortFiles.STATUSFOLDER))
\r
92 targetFtp.makeDirectory(EscortFiles.STATUSFOLDER);
\r
93 if (!targetFtp.changeWorkingDirectory(EscortFiles.STATUSFOLDER))
\r
94 throw new Exception("!STATUSFOLDER");
\r
95 } catch (Exception e) {
\r
99 transferMetadata(videoFileName, metadata);
\r
100 targetFtp.changeToParentDirectory();
\r
101 createSourceKillDateFile(rundownArchive, fileName);
\r
104 private BasicDBObject createMetadata(RundownArchive rundownArchive, StoryArchive storyArchive, FileArchive fileArchive) {
\r
106 // "itemHouseId": "43",
\r
107 // "itemTitle": "Hazahúzó",
\r
108 // "itemDescription": null,
\r
109 // "mediaHouseId": "002570",
\r
110 // "mediaTitle": "2017.12.13",
\r
111 // "mediaDescription": null,
\r
113 // "userName": "echotest"
\r
115 BasicDBObject result = new BasicDBObject();
\r
116 result.put("itemHouseID", rundownArchive.getItemHouseId());
\r
117 result.put("itemTitle", rundownArchive.getItemTitle());
\r
118 result.put("itemDescription", rundownArchive.getItemDesc());
\r
119 result.put("userName", "mediacube");
\r
121 result.put("mediaHouseId", storyArchive.getMediaHouseId());
\r
122 result.put("mediaTitle", storyArchive.getMediaTitle());
\r
123 result.put("mediaDescription", storyArchive.getMediaDesc());
\r
125 result.put("duration", fileArchive.getDuration());
\r
129 private void createSourceKillDateFile(RundownArchive rundownArchive, String fileName) throws Exception {
\r
130 Calendar killDate = CalendarUtils.createCalendar(rundownArchive.getScheduleDate());
\r
131 killDate.add(Calendar.DAY_OF_YEAR, nexioKillDateDays);
\r
132 byte[] killDateFile = EscortFiles.createNEXIOKillDateFile(fileName, killDate.getTime(), null, nexioAgency);
\r
133 try (OutputStream outStream = sourceFtp.storeFileStream(fileName + XML_EXT)) {
\r
134 outStream.write(killDateFile);
\r
136 } catch (Exception e) {
\r
137 logger.catching(e);
\r
143 public Object[] execute(int nexioPort, String nexioUserName, String nexioPassword, String archiveFtp, String archiveUserName, String archivePassword,
\r
144 int daysBeforeNow, int nexioKillDateDays, String nexioAgency, IJobEngine jobEngine, IJobRuntime jobRuntime) throws Exception {
\r
145 setAndCheck(nexioPort, nexioUserName, nexioPassword, archiveFtp, archiveUserName, archivePassword, nexioKillDateDays, nexioAgency, jobEngine);
\r
146 octopusAPI = new OctopusAPI();
\r
147 Calendar scheduledDate = Calendar.getInstance();
\r
148 scheduledDate.add(Calendar.DAY_OF_YEAR, -1 * daysBeforeNow);
\r
149 List<DBObject> rundowns = octopusAPI.getRundowns(scheduledDate.getTime());
\r
150 if (rundowns == null) {
\r
151 logger.warn(getMarker(), "Nem található adástükör a {} napra.", CalendarUtils.toDateString(scheduledDate));
\r
155 processRundowns(rundowns);
\r
156 if (sourceUri != null)
\r
157 sourceUri.cleanUp();
\r
158 if (targetUri != null)
\r
159 targetUri.cleanUp();
\r
163 private FileArchive processMosObject(BasicDBObject rundown, BasicDBObject story, BasicDBObject mosObject) throws Exception {
\r
164 String mosID = mosObject.getString(IOctopusAPI.OBJ_ID);
\r
165 if (MetadataTypeDetector.GuessMetadataType(mosID) != MetadataType.OCTOPUSPLACEHOLDER) {
\r
166 logger.trace("Skipping MOS object {}", mosID);
\r
169 DBCollection clips = db.getCollection(NEXIOCLIPS);
\r
170 BasicDBObject clip = (BasicDBObject) clips.findOne(new BasicDBObject(LONGNAMEID, mosID));
\r
171 if (clip == null) {
\r
172 logger.debug("File NOT exists {}", mosID);
\r
173 throw new Exception(String.format("File NOT exists %s", mosID));
\r
175 logger.debug("File exists {}", mosID);
\r
177 long duration = NoSQLUtils.asLong(clip, DURATION);
\r
178 return new FileArchive(mosID, duration);
\r
181 private RundownArchive processRundow(DBObject r) throws Exception {
\r
182 BasicDBObject rundown = (BasicDBObject) r;
\r
183 long rundownID = rundown.getLong(ID);
\r
184 logger.info("Processing rundown {} {}", rundownID, rundown.getString(IOctopusAPI.NAME));
\r
185 List<DBObject> stories = octopusAPI.getRundownFullStories(rundownID);
\r
186 if (stories == null)
\r
188 RundownArchive result = new RundownArchive();
\r
190 long id = NoSQLUtils.asLong(rundown, IOctopusAPI.ID);
\r
193 String name = NoSQLUtils.asString(NoSQLUtils.asDBObject(rundown, IOctopusAPI.RUNDOWN_TYPE), IOctopusAPI.NAME);
\r
194 if (StringUtils.isBlank(name))
\r
196 String channel = NoSQLUtils.asString(NoSQLUtils.asDBObject(rundown, IOctopusAPI.CHANNEL), IOctopusAPI.NAME);
\r
197 Date scheduledStart = rundown.getDate(IOctopusAPI.SCHEDULED_START);
\r
198 if (scheduledStart == null)
\r
200 String start = CalendarUtils.toString(CalendarUtils.createCalendar(scheduledStart), SCHEDULED_FORMAT);
\r
201 result.setScheduleDate(scheduledStart);
\r
202 result.setItemHouseId(String.valueOf(id));
\r
203 result.setItemTitle(String.format("%s %s %s", start, name, channel));
\r
205 for (DBObject s : stories) {
\r
206 StoryArchive storyArchive = processStory(rundown, s);
\r
207 if (storyArchive == null)
\r
209 result.addStoryArchive(storyArchive);
\r
214 private void processRundowns(List<DBObject> rundowns) {
\r
215 //db.getCollection(ARCHIVEDRUNDOWNS).drop();
\r
216 List<BasicDBObject> archivedRundowns = queryArchivedRundowns();
\r
219 for (DBObject r : rundowns) {
\r
220 BasicDBObject rundown = (BasicDBObject) r;
\r
221 setProgress(index * 100 / rundowns.size());
\r
223 long rundownID = NoSQLUtils.asLong(rundown, IOctopusAPI.ID);
\r
224 BasicDBObject currentRundownID = new BasicDBObject(IOctopusAPI.ID, rundownID);
\r
225 String rundownName = rundown.getString(IOctopusAPI.NAME);
\r
226 if (archivedRundowns != null && archivedRundowns.contains(currentRundownID)) {
\r
227 logger.info("Skipping archived rundown {} {}", rundownID, rundownName);
\r
231 RundownArchive rundownArchive = processRundow(r);
\r
232 if (rundownArchive == null || rundownArchive.isEmpty()) {
\r
233 logger.info("Skipping rundown {} {}", NoSQLUtils.asLong(rundown, IOctopusAPI.ID), rundown.getString(IOctopusAPI.NAME));
\r
237 logger.info("Saving rundown {} {}", rundownID, rundownName);
\r
238 copy(rundownArchive);
\r
240 db.getCollection(ARCHIVEDRUNDOWNS).save(currentRundownID);
\r
241 } catch (Exception e) {
\r
242 logger.catching(e);
\r
243 logger.error(getMarker(),
\r
244 "A {} tükör archiválása nem lehetséges, mert a annak ellenőrzése hibát jelzett. A rendszer üzenete: " + e.getMessage());
\r
250 private StoryArchive processStory(BasicDBObject rundown, DBObject s) throws Exception {
\r
251 BasicDBObject story = (BasicDBObject) s;
\r
252 String parentStoryID = story.getString(IOctopusAPI.PARENT_STORY_ID);
\r
253 if (StringUtils.isBlank(parentStoryID)) {
\r
254 logger.warn("Story parentStoryID is null: {}", story.toPrettyString(null));
\r
257 logger.debug("Processing story {}", parentStoryID);
\r
258 List<BasicDBObject> mosObjects = NoSQLUtils.asList(story, IOctopusAPI.MOS_OBJECTS);
\r
259 if (mosObjects == null)
\r
261 StoryArchive storyArchive = null;
\r
262 for (BasicDBObject mosObject : mosObjects) {
\r
263 FileArchive fileArchive = processMosObject(rundown, story, mosObject);
\r
264 if (fileArchive == null)
\r
266 if (storyArchive == null) {
\r
267 storyArchive = new StoryArchive();
\r
268 storyArchive.setMediaHouseId(parentStoryID);
\r
269 storyArchive.setMediaTitle(story.getString(IOctopusAPI.NAME));
\r
270 storyArchive.setMediaDesc(story.getString(IOctopusAPI.SCRIPT_CONTENT));
\r
273 storyArchive.addFileArchive(fileArchive);
\r
275 return storyArchive;
\r
279 private List<BasicDBObject> queryArchivedRundowns() {
\r
280 List<BasicDBObject> result = null;
\r
281 DBCollection collection = db.getCollection(ARCHIVEDRUNDOWNS);
\r
282 DBCursor find = collection.find(new BasicDBObject(), new BasicDBObject(IOctopusAPI._ID, 0).append(IOctopusAPI.ID, 1));
\r
283 if (find.hasNext())
\r
284 result = ListUtils.cast(find.toArray());
\r
288 private void setAndCheck(int nexioPort, String nexioUserName, String nexioPassword, String archiveFtp, String archiveUserName, String archivePassword,
\r
289 int nexioKillDateDays, String nexioAgency, IJobEngine jobEngine) throws Exception {
\r
290 db = NoSQLUtils.getNoSQLDB();
\r
292 logger.error(getMarker(), "Az NoSQL adatkezelő réteg nem elérhető.");
\r
293 throw new NullPointerException("Internal error, missing NoSQL DB reference.");
\r
296 if (jobEngine == null) {
\r
297 logger.error(getMarker(), "Az folyamatkezelő réteg nem elérhető.");
\r
298 throw new NullPointerException("Internal error, missing JobEngine reference.");
\r
300 manager = jobEngine.getItemManager();
\r
301 if (manager == null) {
\r
302 logger.error(getMarker(), "Az adatbáziskezelő réteg nem elérhető.");
\r
303 throw new NullPointerException("Internal error, missing ItemManager reference.");
\r
305 String nexioHost = System.getProperty("nexio.host");
\r
306 if (StringUtils.isBlank(nexioHost)) {
\r
307 logger.error(getMarker(), "A 'nexio.host' rendszer paraméter nem található.");
\r
308 throw new NullPointerException("System is not configured properly, 'jobengine.selenio.address' startup parameter missing.");
\r
310 check(nexioPort, "nexioPort");
\r
311 check(nexioUserName, "nexioUserName");
\r
312 check(nexioPassword, "nexioPassword");
\r
314 check(nexioKillDateDays, "nexioKillDateDays");
\r
315 this.nexioKillDateDays = nexioKillDateDays;
\r
316 check(nexioAgency, "nexioAgency");
\r
317 this.nexioAgency = nexioAgency;
\r
319 sourceUri = manager.createStoreUri(RemoteStoreProtocol.FTP, nexioHost);
\r
320 sourceUri.setPortNumber(nexioPort);
\r
321 sourceUri.setUserName(nexioUserName);
\r
322 sourceUri.setPassword(nexioPassword);
\r
324 check(archiveFtp, "archiveFtp");
\r
325 check(archiveUserName, "archiveUserName");
\r
326 check(archivePassword, "archivePassword");
\r
328 targetUri = manager.createStoreUri(new URI(archiveFtp));
\r
329 targetUri.setUserName(archiveUserName);
\r
330 targetUri.setPassword(archivePassword);
\r
332 sourceFtp = ((FtpDirectoryLister) RemoteFileHandler.createLister(sourceUri)).connect();
\r
333 targetFtp = ((FtpDirectoryLister) RemoteFileHandler.createLister(targetUri)).connect();
\r
337 private void transferFile(String fileName) throws Exception {
\r
340 if (!targetFtp.enterRemotePassiveMode())
\r
341 throw new Exception("!PASV");
\r
343 reply = sourceFtp.port(InetAddress.getByName(targetFtp.getPassiveHost()), targetFtp.getPassivePort());
\r
344 if (!FTPReply.isPositiveCompletion(reply))
\r
345 throw new Exception("!PORT");
\r
347 if (!sourceFtp.setFileType(FTP.BINARY_FILE_TYPE))
\r
348 throw new Exception("!SOURCE TYPE");
\r
350 sourceFtp.retr(fileName);
\r
352 if (!targetFtp.setFileType(FTP.BINARY_FILE_TYPE))
\r
353 throw new Exception("!TARGET TYPE");
\r
355 targetFtp.stor(fileName);
\r
358 reply = sourceFtp.stat();
\r
359 if (!FTPReply.isPositiveCompletion(reply))
\r
360 throw new Exception("!STAT");
\r
361 String replyText = sourceFtp.getReplyString();
\r
362 if ("226 RETR Transfer Complete(TRANSACTION_SUCCESS)".equals(replyText))
\r
368 private void transferMetadata(String fileName, BasicDBObject metadata) throws Exception {
\r
369 try (OutputStream outStream = targetFtp.storeFileStream(fileName + JSON_EXT)) {
\r
370 outStream.write(metadata.toString().getBytes(UTF_8));
\r
372 } catch (Exception e) {
\r
373 logger.catching(e);
\r