1 package user.jobengine.server.steps;
\r
3 import java.io.OutputStream;
\r
4 import java.net.InetAddress;
\r
6 import java.text.ParseException;
\r
7 import java.text.SimpleDateFormat;
\r
8 import java.util.ArrayList;
\r
9 import java.util.Calendar;
\r
10 import java.util.Date;
\r
11 import java.util.List;
\r
13 import org.apache.commons.lang.StringUtils;
\r
14 import org.apache.commons.net.ftp.FTP;
\r
15 import org.apache.commons.net.ftp.FTPClient;
\r
16 import org.apache.commons.net.ftp.FTPReply;
\r
17 import org.apache.logging.log4j.LogManager;
\r
18 import org.apache.logging.log4j.Logger;
\r
19 import org.apache.logging.log4j.Marker;
\r
21 import com.ibm.nosql.json.api.BasicDBList;
\r
22 import com.ibm.nosql.json.api.BasicDBObject;
\r
23 import com.ibm.nosql.json.api.DB;
\r
24 import com.ibm.nosql.json.api.DBCollection;
\r
25 import com.ibm.nosql.json.api.DBCursor;
\r
26 import com.ibm.nosql.json.api.DBObject;
\r
27 import com.ibm.nosql.json.api.QueryBuilder;
\r
29 import user.commons.CalendarUtils;
\r
30 import user.commons.ListUtils;
\r
31 import user.commons.StoreUri;
\r
32 import user.commons.nosql.NoSQLUtils;
\r
33 import user.commons.octopus.IOctopusAPI;
\r
34 import user.commons.octopus.OctopusAPI;
\r
35 import user.commons.remotestore.FtpDirectoryLister;
\r
36 import user.commons.remotestore.RemoteStoreProtocol;
\r
37 import user.jobengine.db.IItemManager;
\r
38 import user.jobengine.server.IJobEngine;
\r
39 import user.jobengine.server.IJobRuntime;
\r
41 public class CopyForArchiveNEXIORecordingsStep extends JobStep {
\r
42 private static final String MEDIATYPE = "Visszarögzített";
\r
43 private static final String SCHEDULED_FORMAT = "yyyy.MM.dd HH:mm";
\r
44 private static final String STARTTIME_FORMAT = "HHmm";
\r
45 private static final Logger logger = LogManager.getLogger();
\r
46 private static final String UTF_8 = "utf-8";
\r
47 private static final String JSON_EXT = ".json";
\r
48 private static final String XML_EXT = ".xml";
\r
49 private static final String DURATION = "duration";
\r
50 private static final String MXFEXT = ".MXF";
\r
51 private static final String NEXIOCLIPS = "nexioclips";
\r
52 private static final String LONGNAMEID = "longnameid";
\r
53 private static final String ID = "id";
\r
54 private static final String EXTAGENCY = "extagency";
\r
55 private static final String RECORDDATE = "recorddate";
\r
56 private static final SimpleDateFormat startTimeformat = new SimpleDateFormat(STARTTIME_FORMAT);
\r
58 private OctopusAPI octopusAPI;
\r
59 private IItemManager manager;
\r
62 private FTPClient sourceFtp;
\r
63 private FTPClient targetFtp;
\r
64 private StoreUri sourceUri;
\r
65 private StoreUri targetUri;
\r
66 private int nexioKillDateDays;
\r
67 private String nexioAgency;
\r
68 private Object[] filterAgencies;
\r
69 private Marker systemMarker;
\r
71 private int check(int value, String name) {
\r
73 logger.error(systemMarker, "A folyamat '{}' bemeneti paramétere 0.", name);
\r
74 throw new NullPointerException(String.format("System is not configured properly, missing '%s' input parameter.", name));
\r
79 private String check(String value, String name) {
\r
80 if (StringUtils.isBlank(value)) {
\r
81 logger.error(systemMarker, "A folyamat '{}' bemeneti paramétere üres.", name);
\r
82 throw new NullPointerException(String.format("System is not configured properly, missing '%s' input parameter.", name));
\r
87 private void copy(RundownArchive rundownArchive) {
\r
88 for (StoryArchive storyArchive : rundownArchive.getStoryArchives()) {
\r
89 for (FileArchive fileArchive : storyArchive.getFileArchives()) {
\r
91 copyFile(fileArchive, rundownArchive, storyArchive);
\r
92 logger.info(systemMarker, "Sikeres fájl archiválás a '{}' tükörhöz: '{}'.", rundownArchive.getItemTitle(), fileArchive.getFileName());
\r
93 } catch (Exception e) {
\r
94 logger.error(systemMarker, "Az '{}' fájl archiválása sikertelen. A rendszer üzenete: {}", fileArchive.getFileName(), e.getMessage());
\r
100 private void copyFile(FileArchive fileArchive, RundownArchive rundownArchive, StoryArchive storyArchive) throws Exception {
\r
101 String origFileName = fileArchive.getFileName();
\r
102 String videoFileName = transferFile(origFileName);
\r
103 BasicDBObject metadata = createMetadata(rundownArchive, storyArchive, fileArchive);
\r
104 transferMetadata(videoFileName, metadata);
\r
105 createSourceKillDateFile(rundownArchive, origFileName);
\r
108 private BasicDBObject createMetadata(RundownArchive rundownArchive, StoryArchive storyArchive, FileArchive fileArchive) {
\r
109 BasicDBObject result = new BasicDBObject();
\r
110 result.put("itemHouseId", rundownArchive.getItemHouseId());
\r
111 result.put("itemTitle", rundownArchive.getItemTitle());
\r
112 result.put("itemDescription", rundownArchive.getItemDesc());
\r
113 result.put("userName", "mediacube");
\r
115 result.put("mediaHouseId", storyArchive.getMediaHouseId());
\r
116 result.put("mediaTitle", storyArchive.getMediaTitle());
\r
117 result.put("mediaDescription", storyArchive.getMediaDesc());
\r
119 result.put("duration", fileArchive.getDuration());
\r
120 result.put("mediaType", MEDIATYPE);
\r
124 private void createSourceKillDateFile(RundownArchive rundownArchive, String fileName) throws Exception {
\r
125 logger.info("Create killdate/agency for {}", fileName);
\r
126 OutputStream outStream = null;
\r
128 sourceFtp = ((FtpDirectoryLister) sourceUri.getLister()).connect();
\r
129 Calendar killDate = CalendarUtils.createCalendar(rundownArchive.getScheduleDate());
\r
130 killDate.add(Calendar.DAY_OF_YEAR, nexioKillDateDays);
\r
131 byte[] killDateFile = EscortFiles.createNEXIOKillDateFile(fileName, killDate.getTime(), null, nexioAgency);
\r
132 outStream = sourceFtp.storeFileStream(fileName + XML_EXT);
\r
133 if (outStream == null) {
\r
134 throw new NullPointerException("Can not open: " + fileName + XML_EXT + " Reply:" + sourceFtp.getReplyString());
\r
136 outStream.write(killDateFile);
\r
138 } catch (Exception e) {
\r
139 logger.catching(e);
\r
142 if (outStream != null)
\r
144 sourceUri.cleanUp();
\r
149 public Object[] execute(int nexioPort, String nexioUserName, String nexioPassword, String archiveFtp, String archiveUserName, String archivePassword,
\r
150 String filterAgencies, int limit, int nexioKillDateDays, String targetAgency, IJobEngine jobEngine, IJobRuntime jobRuntime) throws Exception {
\r
151 systemMarker = jobRuntime.getMarker();
\r
152 setAndCheck(nexioPort, nexioUserName, nexioPassword, archiveFtp, archiveUserName, archivePassword, filterAgencies, limit, nexioKillDateDays,
\r
153 targetAgency, jobEngine);
\r
154 octopusAPI = new OctopusAPI();
\r
155 List<BasicDBObject> clips = queryClips();
\r
156 processClips(clips, limit);
\r
160 private Date getScheduledStart(String clipName, Date recordDate) {
\r
161 if (StringUtils.isBlank(clipName)) {
\r
162 logger.warn(systemMarker, "A fájlnak nincs neve, ezért nem archiválható.");
\r
165 if (recordDate == null) {
\r
166 logger.warn(systemMarker, "Az '{}' fájl rögzítésének ideje nem meghatározható, ezért nem archiválható.", clipName);
\r
170 Date timePart = null;
\r
172 String clipNameTime = clipName.split("_")[0];
\r
173 timePart = startTimeformat.parse(clipNameTime);
\r
174 } catch (ParseException e) {
\r
175 logger.warn(systemMarker, "A '{}' fájl neve nem időbélyeggel kezdődik, ezért nem archiválható.", clipName);
\r
178 return CalendarUtils.createCalendar(CalendarUtils.createCalendar(recordDate), timePart).getTime();
\r
181 private String getTargetFileName(String sourceFileName, String[] names) {
\r
182 String result = sourceFileName + MXFEXT;
\r
183 if (names == null || names.length == 0)
\r
185 List<String> remoteNames = new ArrayList<>();
\r
186 for (String name : names) {
\r
188 remoteNames.add(name.toLowerCase());
\r
191 while (remoteNames.contains(result.toLowerCase())) {
\r
192 result = String.format("%s-%d%s", sourceFileName, version, MXFEXT);
\r
197 private RundownArchive processClip(BasicDBObject clip) {
\r
198 RundownArchive result = null;
\r
199 String clipName = NoSQLUtils.asString(clip, LONGNAMEID);
\r
200 Date recordDate = clip.getDate(RECORDDATE);
\r
201 long duration = NoSQLUtils.asLong(clip, DURATION);
\r
202 logger.info("Processing {} {}", clipName, recordDate);
\r
203 Date scheduledStart = getScheduledStart(clipName, recordDate);
\r
204 if (scheduledStart == null)
\r
206 DBObject rundown = octopusAPI.getRundown(scheduledStart);
\r
207 if (rundown == null) {
\r
208 logger.error(systemMarker, "A '{}' anyaghoz nem található tükör '{}' kezdéssel, ezért nem archiválható.", clipName, scheduledStart);
\r
213 result = processRundow(rundown, clipName, duration);
\r
214 } catch (Exception e) {
\r
215 logger.catching(e);
\r
216 logger.error(systemMarker, "A '{}' anyag metaadatainak transzformálása sikertelen, ezért az nem archiválható. A rendszer hibaüzenete: {}",
\r
223 private void processClips(List<BasicDBObject> clips, int limit) {
\r
224 logger.info(systemMarker, "A folyamat {} archiválható anyagot érzékelt.", clips.size());
\r
226 for (BasicDBObject clip : clips) {
\r
227 RundownArchive rundownArchive = processClip(clip);
\r
228 if (rundownArchive == null)
\r
231 copy(rundownArchive);
\r
234 if (current == limit)
\r
236 setProgress(current * 100 / limit);
\r
240 private RundownArchive processRundow(DBObject r, String clipName, long duration) throws Exception {
\r
241 BasicDBObject rundown = (BasicDBObject) r;
\r
242 long rundownID = rundown.getLong(ID);
\r
243 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 String name = NoSQLUtils.asString(NoSQLUtils.asDBObject(rundown, IOctopusAPI.RUNDOWN_TYPE), IOctopusAPI.NAME);
\r
251 if (StringUtils.isBlank(name))
\r
253 String channel = NoSQLUtils.asString(NoSQLUtils.asDBObject(rundown, IOctopusAPI.CHANNEL), IOctopusAPI.NAME);
\r
254 Date scheduledStart = rundown.getDate(IOctopusAPI.SCHEDULED_START);
\r
255 if (scheduledStart == null)
\r
257 String start = CalendarUtils.toString(CalendarUtils.createCalendar(scheduledStart), SCHEDULED_FORMAT);
\r
258 result.setScheduleDate(scheduledStart);
\r
259 result.setItemHouseId(String.valueOf(rundownID));
\r
260 result.setItemTitle(String.format("%s %s %s", start, name, channel));
\r
262 StringBuilder sb = new StringBuilder();
\r
263 for (DBObject s : stories) {
\r
264 BasicDBObject story = (BasicDBObject) s;
\r
265 sb.append(story.getString(IOctopusAPI.PARENT_STORY_ID));
\r
266 sb.append(" [" + story.getString(IOctopusAPI.FORMAT) + "] ");
\r
267 sb.append(story.getString(IOctopusAPI.NAME));
\r
270 StoryArchive storyArchive = new StoryArchive();
\r
271 storyArchive.setMediaHouseId(result.getItemHouseId());
\r
272 storyArchive.setMediaTitle(clipName);
\r
273 storyArchive.setMediaDesc(sb.toString());
\r
274 result.addStoryArchive(storyArchive);
\r
275 storyArchive.addFileArchive(new FileArchive(clipName, duration));
\r
279 private List<BasicDBObject> queryClips() {
\r
280 DBCollection collection = db.getCollection(NEXIOCLIPS);
\r
281 BasicDBList agencies = new BasicDBList(filterAgencies);
\r
283 Calendar now = CalendarUtils.createZeroCalendar();
\r
284 QueryBuilder dateQueryBuilder = QueryBuilder.start(RECORDDATE).lessThan(now.getTime());
\r
285 QueryBuilder queryBuilder = QueryBuilder.start(EXTAGENCY).in(agencies).and(dateQueryBuilder.get());
\r
286 DBCursor cursor = collection.find(queryBuilder.get()).sort(RECORDDATE, -1);
\r
287 if (!cursor.hasNext())
\r
289 return ListUtils.cast(cursor.toArray());
\r
292 private void setAndCheck(int nexioPort, String nexioUserName, String nexioPassword, String archiveFtp, String archiveUserName, String archivePassword,
\r
293 String agencies, int limit, int nexioKillDateDays, String nexioAgency, IJobEngine jobEngine) throws Exception {
\r
294 db = NoSQLUtils.getNoSQLDB();
\r
296 logger.error(systemMarker, "Az NoSQL adatkezelő réteg nem elérhető.");
\r
297 throw new NullPointerException("Internal error, missing NoSQL DB reference.");
\r
300 if (jobEngine == null) {
\r
301 logger.error(systemMarker, "Az folyamatkezelő réteg nem elérhető.");
\r
302 throw new NullPointerException("Internal error, missing JobEngine reference.");
\r
304 manager = jobEngine.getItemManager();
\r
305 if (manager == null) {
\r
306 logger.error(systemMarker, "Az adatbáziskezelő réteg nem elérhető.");
\r
307 throw new NullPointerException("Internal error, missing ItemManager reference.");
\r
309 String nexioHost = System.getProperty("nexio.host");
\r
310 if (StringUtils.isBlank(nexioHost)) {
\r
311 logger.error(systemMarker, "A 'nexio.host' rendszer paraméter nem található.");
\r
312 throw new NullPointerException("System is not configured properly, 'jobengine.selenio.address' startup parameter missing.");
\r
314 check(nexioPort, "nexioPort");
\r
315 check(nexioUserName, "nexioUserName");
\r
316 check(nexioPassword, "nexioPassword");
\r
318 check(agencies, "filterAgencies");
\r
319 filterAgencies = agencies.split(",");
\r
321 check(limit, "limit");
\r
323 check(nexioKillDateDays, "nexioKillDateDays");
\r
324 this.nexioKillDateDays = nexioKillDateDays;
\r
325 check(nexioAgency, "nexioAgency");
\r
326 this.nexioAgency = nexioAgency;
\r
328 sourceUri = manager.createStoreUri(RemoteStoreProtocol.FTP, nexioHost);
\r
329 sourceUri.setPortNumber(nexioPort);
\r
330 sourceUri.setUserName(nexioUserName);
\r
331 sourceUri.setPassword(nexioPassword);
\r
332 if (sourceUri == null) {
\r
333 logger.error(systemMarker, "A forrás nem elérhető.");
\r
334 throw new NullPointerException("Internal error, missing 'sourceUri'.");
\r
337 check(archiveFtp, "archiveFtp");
\r
338 check(archiveUserName, "archiveUserName");
\r
339 check(archivePassword, "archivePassword");
\r
341 targetUri = manager.createStoreUri(new URI(archiveFtp));
\r
342 targetUri.setUserName(archiveUserName);
\r
343 targetUri.setPassword(archivePassword);
\r
344 if (targetUri == null) {
\r
345 logger.error(systemMarker, "A cél nem elérhető.");
\r
346 throw new NullPointerException("Internal error, missing 'targetUri'.");
\r
351 private String transferFile(String sourceFileName) throws Exception {
\r
352 String result = null;
\r
354 logger.info("Transfer clip {}", sourceFileName);
\r
356 sourceFtp = ((FtpDirectoryLister) sourceUri.getLister()).connect();
\r
357 targetFtp = ((FtpDirectoryLister) targetUri.getLister()).connect();
\r
359 result = getTargetFileName(sourceFileName, targetFtp.listNames());
\r
361 if (!targetFtp.enterRemotePassiveMode())
\r
362 throw new Exception("!PASV");
\r
364 reply = sourceFtp.port(InetAddress.getByName(targetFtp.getPassiveHost()), targetFtp.getPassivePort());
\r
365 if (!FTPReply.isPositiveCompletion(reply))
\r
366 throw new Exception("PORT parancs válasza: " + sourceFtp.getReplyString());
\r
368 if (!sourceFtp.setFileType(FTP.BINARY_FILE_TYPE))
\r
369 throw new Exception("!SOURCE TYPE");
\r
371 reply = sourceFtp.retr(sourceFileName);
\r
372 if (!FTPReply.isPositivePreliminary(reply))
\r
373 throw new Exception("RETR parancs válasza: " + sourceFtp.getReplyString());
\r
375 if (!targetFtp.setFileType(FTP.BINARY_FILE_TYPE))
\r
376 throw new Exception("!TARGET TYPE");
\r
378 reply = targetFtp.stor(result);
\r
379 if (!FTPReply.isPositivePreliminary(reply))
\r
380 throw new Exception("STOR parancs válasza: " + sourceFtp.getReplyString());
\r
383 reply = sourceFtp.stat();
\r
384 if (!FTPReply.isPositiveCompletion(reply))
\r
385 throw new Exception("STAT parancs válasza: " + sourceFtp.getReplyString());
\r
387 //logger.info("Status: {}", sourceFtp.getReplyString());
\r
388 if (reply == 226) {
\r
391 Thread.sleep(1000);
\r
393 } catch (Exception e) {
\r
394 logger.catching(e);
\r
397 sourceUri.cleanUp();
\r
398 targetUri.cleanUp();
\r
404 private void transferMetadata(String fileName, BasicDBObject metadata) throws Exception {
\r
405 logger.info("Transfer metadata {}", fileName);
\r
406 OutputStream outStream = null;
\r
408 targetFtp = ((FtpDirectoryLister) targetUri.getLister()).connect();
\r
409 if (!targetFtp.changeWorkingDirectory(EscortFiles.STATUSFOLDER)) {
\r
410 targetFtp.makeDirectory(EscortFiles.STATUSFOLDER);
\r
411 if (!targetFtp.changeWorkingDirectory(EscortFiles.STATUSFOLDER))
\r
412 throw new Exception("!STATUSFOLDER");
\r
415 outStream = targetFtp.storeFileStream(fileName + JSON_EXT);
\r
416 if (outStream == null) {
\r
417 throw new NullPointerException("Can not open: " + fileName + JSON_EXT + " Reply:" + targetFtp.getReplyString());
\r
419 outStream.write(metadata.toString().getBytes(UTF_8));
\r
421 //targetFtp.changeToParentDirectory();
\r
422 } catch (Exception e) {
\r
423 logger.catching(e);
\r
426 if (outStream != null)
\r
428 targetUri.cleanUp();
\r