1aaa8e1057efe9ce8d68e49a938ea1d849595fbe
[mediacube.git] /
1 package user.jobengine.server.steps;\r
2 \r
3 import java.io.OutputStream;\r
4 import java.net.InetAddress;\r
5 import java.net.URI;\r
6 import java.text.ParseException;\r
7 import java.text.SimpleDateFormat;\r
8 import java.util.Calendar;\r
9 import java.util.Date;\r
10 import java.util.List;\r
11 import java.util.TimeZone;\r
12 \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
20 \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
28 \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
40 \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 String RUNDOWNDATE_FORMAT = "yyyyMMdd";\r
46         private static final Logger logger = LogManager.getLogger();\r
47         private static final String UTF_8 = "utf-8";\r
48         private static final String JSON_EXT = ".json";\r
49         private static final String XML_EXT = ".xml";\r
50         private static final String DURATION = "duration";\r
51         private static final String MXFEXT = ".MXF";\r
52         private static final String NEXIOCLIPS = "nexioclips";\r
53         private static final String LONGNAMEID = "longnameid";\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
57         private static final SimpleDateFormat rundownDateformat = new SimpleDateFormat(RUNDOWNDATE_FORMAT);\r
58 \r
59         private OctopusAPI octopusAPI;\r
60         private IItemManager manager;\r
61 \r
62         private DB db;\r
63         private FTPClient sourceFtp;\r
64         private FTPClient targetFtp;\r
65         private StoreUri sourceUri;\r
66         private StoreUri targetUri;\r
67         private int nexioKillDateDays;\r
68         private String nexioAgency;\r
69         private Object[] filterAgencies;\r
70         private Marker systemMarker;\r
71 \r
72         private int check(int value, String name) {\r
73                 if (value == 0) {\r
74                         logger.error(systemMarker, "A folyamat '{}' bemeneti paramétere 0.", name);\r
75                         throw new NullPointerException(String.format("System is not configured properly, missing '%s' input parameter.", name));\r
76                 }\r
77                 return value;\r
78         }\r
79 \r
80         private String check(String value, String name) {\r
81                 if (StringUtils.isBlank(value)) {\r
82                         logger.error(systemMarker, "A folyamat '{}' bemeneti paramétere üres.", name);\r
83                         throw new NullPointerException(String.format("System is not configured properly, missing '%s' input parameter.", name));\r
84                 }\r
85                 return value;\r
86         }\r
87 \r
88         private void copy(RundownArchive rundownArchive) {\r
89                 for (StoryArchive storyArchive : rundownArchive.getStoryArchives()) {\r
90                         for (FileArchive fileArchive : storyArchive.getFileArchives()) {\r
91                                 try {\r
92                                         copyFile(fileArchive, rundownArchive, storyArchive);\r
93                                         logger.info(systemMarker, "Sikeres fájl archiválás a '{}' tükörhöz: '{}'.", rundownArchive.getItemTitle(), fileArchive.getFileName());\r
94                                 } catch (Exception e) {\r
95                                         logger.error(systemMarker, "Az '{}' fájl archiválása sikertelen. A rendszer üzenete: {}", fileArchive.getFileName(), e.getMessage());\r
96                                 }\r
97                         }\r
98                 }\r
99         }\r
100 \r
101         private void copyFile(FileArchive fileArchive, RundownArchive rundownArchive, StoryArchive storyArchive) throws Exception {\r
102                 String sourceFileName = fileArchive.getFileName();\r
103                 String targetFileName = getTargetFileName(rundownArchive, sourceFileName);\r
104                 transferFile(sourceFileName, targetFileName);\r
105                 BasicDBObject metadata = createMetadata(rundownArchive, storyArchive, fileArchive);\r
106                 transferMetadata(targetFileName, metadata);\r
107                 createSourceKillDateFile(rundownArchive, sourceFileName);\r
108         }\r
109 \r
110         private BasicDBObject createMetadata(RundownArchive rundownArchive, StoryArchive storyArchive, FileArchive fileArchive) {\r
111                 BasicDBObject result = new BasicDBObject();\r
112                 result.put("itemHouseId", rundownArchive.getItemHouseId());\r
113                 result.put("itemTitle", rundownArchive.getItemTitle());\r
114                 result.put("itemDescription", rundownArchive.getItemDesc());\r
115                 result.put("userName", "mediacube");\r
116 \r
117                 result.put("mediaHouseId", storyArchive.getMediaHouseId());\r
118                 result.put("mediaTitle", storyArchive.getMediaTitle());\r
119                 result.put("mediaDescription", storyArchive.getMediaDesc());\r
120 \r
121                 result.put("duration", fileArchive.getDuration());\r
122                 result.put("mediaType", MEDIATYPE);\r
123                 return result;\r
124         }\r
125 \r
126         private void createSourceKillDateFile(RundownArchive rundownArchive, String fileName) throws Exception {\r
127                 logger.info("Create killdate/agency for {}", fileName);\r
128                 OutputStream outStream = null;\r
129                 try {\r
130                         sourceFtp = ((FtpDirectoryLister) sourceUri.getLister()).connect();\r
131                         Calendar killDate = CalendarUtils.createCalendar(rundownArchive.getScheduleDate());\r
132                         killDate.add(Calendar.DAY_OF_YEAR, nexioKillDateDays);\r
133                         byte[] killDateFile = EscortFiles.createNEXIOKillDateFile(fileName, killDate.getTime(), null, nexioAgency);\r
134                         outStream = sourceFtp.storeFileStream(fileName + XML_EXT);\r
135                         if (outStream == null) {\r
136                                 throw new NullPointerException("Can not open: " + fileName + XML_EXT + " Reply:" + sourceFtp.getReplyString());\r
137                         }\r
138                         outStream.write(killDateFile);\r
139                         outStream.flush();\r
140                 } catch (Exception e) {\r
141                         logger.catching(e);\r
142                         throw e;\r
143                 } finally {\r
144                         if (outStream != null)\r
145                                 outStream.close();\r
146                         sourceUri.cleanUp();\r
147                 }\r
148         }\r
149 \r
150         @StepEntry\r
151         public Object[] execute(int nexioPort, String nexioUserName, String nexioPassword, String archiveFtp, String archiveUserName, String archivePassword,\r
152                         String filterAgencies, int limit, int nexioKillDateDays, String targetAgency, IJobEngine jobEngine, IJobRuntime jobRuntime) throws Exception {\r
153                 systemMarker = jobRuntime.getMarker();\r
154                 setAndCheck(nexioPort, nexioUserName, nexioPassword, archiveFtp, archiveUserName, archivePassword, filterAgencies, limit, nexioKillDateDays,\r
155                                 targetAgency, jobEngine);\r
156                 octopusAPI = new OctopusAPI();\r
157                 List<BasicDBObject> clips = queryClips();\r
158                 processClips(clips, limit);\r
159                 return null;\r
160         }\r
161 \r
162         private Date getScheduledStart(String clipName, Date recordDate) {\r
163                 if (StringUtils.isBlank(clipName)) {\r
164                         logger.warn(systemMarker, "A fájlnak nincs neve, ezért nem archiválható.");\r
165                         return null;\r
166                 }\r
167                 if (recordDate == null) {\r
168                         logger.warn(systemMarker, "Az '{}' fájl rögzítésének ideje nem meghatározható, ezért nem archiválható.", clipName);\r
169                         return null;\r
170                 }\r
171 \r
172                 Date timePart = null;\r
173                 try {\r
174                         String clipNameTime = clipName.split("_")[0];\r
175                         timePart = startTimeformat.parse(clipNameTime);\r
176                 } catch (ParseException e) {\r
177                         logger.warn(systemMarker, "A '{}' fájl neve nem időbélyeggel kezdődik, ezért nem archiválható.", clipName);\r
178                         return null;\r
179                 }\r
180                 Calendar dateCal = CalendarUtils.createCalendar(recordDate);\r
181                 dateCal.setTimeZone(TimeZone.getTimeZone("Europe/Budapest"));\r
182                 Calendar wholeCal = CalendarUtils.createCalendar(CalendarUtils.createCalendar(recordDate), timePart);\r
183                 wholeCal.setTimeZone(TimeZone.getTimeZone("Europe/Budapest"));\r
184                 return wholeCal.getTime();\r
185         }\r
186 \r
187         private String getTargetFileName(RundownArchive rundownArchive, String sourceFileName) {\r
188                 String date = rundownDateformat.format(rundownArchive.getScheduleDate());\r
189                 return String.format("%s-%s%s", date, sourceFileName, MXFEXT);\r
190         }\r
191 \r
192         private RundownArchive processClip(BasicDBObject clip) {\r
193                 RundownArchive result = null;\r
194                 String clipName = NoSQLUtils.asString(clip, LONGNAMEID);\r
195                 Date recordDate = clip.getDate(RECORDDATE);\r
196                 long duration = NoSQLUtils.asLong(clip, DURATION);\r
197                 logger.info("Processing {} {}", clipName, recordDate);\r
198                 Date scheduledStart = getScheduledStart(clipName, recordDate);\r
199                 if (scheduledStart == null)\r
200                         return null;\r
201                 DBObject rundown = octopusAPI.getRundown(scheduledStart);\r
202                 if (rundown == null) {\r
203                         logger.error(systemMarker, "A '{}' anyaghoz nem található tükör '{}' kezdéssel, ezért nem archiválható.", clipName, scheduledStart);\r
204                         return null;\r
205                 }\r
206 \r
207                 try {\r
208                         result = processRundow(rundown, clipName, duration);\r
209                 } catch (Exception e) {\r
210                         logger.catching(e);\r
211                         logger.error(systemMarker, "A '{}' anyag metaadatainak transzformálása sikertelen, ezért az nem archiválható. A rendszer hibaüzenete: {}",\r
212                                         e.getMessage());\r
213                         return null;\r
214                 }\r
215                 /*\r
216                                 if (clipName.startsWith("1900_")) {\r
217                                         String clipNameNext = clipName.replace("1900_", "1908_");\r
218                                         scheduledStart = getScheduledStart(clipNameNext, recordDate);\r
219                                         rundown = octopusAPI.getRundown(scheduledStart);\r
220                                         if (rundown == null) {\r
221                                                 Calendar calendar = CalendarUtils.createCalendar(scheduledStart);\r
222                                                 int dow = calendar.get(Calendar.DAY_OF_WEEK);\r
223                                                 if (dow == Calendar.SATURDAY || dow == Calendar.SUNDAY) {\r
224                                                         logger.info(systemMarker, "A '{}' anyaghoz nem található tükör '{}' kezdéssel, de a hétvégi kivétel miatt archiválható.", clipName,\r
225                                                                         scheduledStart);\r
226                                                         return result;\r
227                                                 } else {\r
228                                                         logger.error(systemMarker, "A '{}' anyaghoz nem található tükör '{}' kezdéssel, ezért nem archiválható.", clipName, scheduledStart);\r
229                                                         return null;\r
230                                                 }\r
231                                         }\r
232                 \r
233                                         RundownArchive item2 = null;\r
234                 \r
235                                         try {\r
236                                                 item2 = processRundow(rundown, clipName, duration);\r
237                                         } catch (Exception e) {\r
238                                                 logger.catching(e);\r
239                                                 logger.error(systemMarker, "A '{}' anyag metaadatainak transzformálása sikertelen, ezért az nem archiválható. A rendszer hibaüzenete: {}",\r
240                                                                 e.getMessage());\r
241                                                 return null;\r
242                                         }\r
243                 \r
244                                         result.setItemTitle(result.getItemTitle() + " + NAPIAKT");\r
245                                         StoryArchive storyArchive = result.getStoryArchives().get(0);\r
246                                         StoryArchive storyArchive2 = item2.getStoryArchives().get(0);\r
247                                         storyArchive.setMediaDesc(storyArchive.getMediaDesc() + "\r\n\r\n****** NAPIAKT ******\r\n\r\n" + storyArchive2.getMediaDesc());\r
248                                 }\r
249                 */\r
250                 return result;\r
251         }\r
252 \r
253         private void processClips(List<BasicDBObject> clips, int limit) {\r
254                 logger.info(systemMarker, "A folyamat {} archiválható anyagot érzékelt.", clips.size());\r
255                 int current = 0;\r
256                 for (BasicDBObject clip : clips) {\r
257                         RundownArchive rundownArchive = processClip(clip);\r
258                         if (rundownArchive == null)\r
259                                 continue;\r
260 \r
261                         copy(rundownArchive);\r
262 \r
263                         current++;\r
264                         if (current == limit)\r
265                                 break;\r
266                         setProgress(current * 100 / limit);\r
267                 }\r
268         }\r
269 \r
270         private RundownArchive processRundow(DBObject r, String clipName, long duration) throws Exception {\r
271                 BasicDBObject rundown = (BasicDBObject) r;\r
272                 long rundownID = rundown.getLong(IOctopusAPI.ID);\r
273                 logger.info("Processing rundown {} {}", rundownID, rundown.getString(IOctopusAPI.NAME));\r
274 \r
275                 List<DBObject> stories = octopusAPI.getRundownFullStories(rundownID);\r
276                 if (stories == null)\r
277                         return null;\r
278                 RundownArchive result = new RundownArchive();\r
279 \r
280                 String name = NoSQLUtils.asString(NoSQLUtils.asDBObject(rundown, IOctopusAPI.RUNDOWN_TYPE), IOctopusAPI.NAME);\r
281                 if (StringUtils.isBlank(name))\r
282                         return null;\r
283                 String channel = NoSQLUtils.asString(NoSQLUtils.asDBObject(rundown, IOctopusAPI.CHANNEL), IOctopusAPI.NAME);\r
284                 Date scheduledStart = rundown.getDate(IOctopusAPI.SCHEDULED_START);\r
285                 if (scheduledStart == null)\r
286                         return null;\r
287                 String start = CalendarUtils.toString(CalendarUtils.createCalendar(scheduledStart), SCHEDULED_FORMAT);\r
288                 result.setScheduleDate(scheduledStart);\r
289                 result.setItemHouseId(String.valueOf(rundownID));\r
290                 result.setItemTitle(String.format("%s %s %s", start, name, channel));\r
291 \r
292                 StoryArchive storyArchive = new StoryArchive();\r
293                 storyArchive.setMediaHouseId(result.getItemHouseId());\r
294                 storyArchive.setMediaTitle(clipName);\r
295                 storyArchive.setMediaDesc(octopusAPI.getRundownContent(stories));\r
296                 result.addStoryArchive(storyArchive);\r
297                 storyArchive.addFileArchive(new FileArchive(clipName, duration));\r
298                 return result;\r
299         }\r
300 \r
301         private List<BasicDBObject> queryClips() {\r
302                 DBCollection collection = db.getCollection(NEXIOCLIPS);\r
303                 BasicDBList agencies = new BasicDBList(filterAgencies);\r
304 \r
305                 Calendar now = CalendarUtils.createZeroCalendar();\r
306                 QueryBuilder dateQueryBuilder = QueryBuilder.start(RECORDDATE).lessThan(now.getTime());\r
307                 QueryBuilder queryBuilder = QueryBuilder.start(EXTAGENCY).in(agencies).and(dateQueryBuilder.get());\r
308                 DBCursor cursor = collection.find(queryBuilder.get()).sort(RECORDDATE, -1);\r
309                 if (!cursor.hasNext())\r
310                         return null;\r
311                 return ListUtils.cast(cursor.toArray());\r
312         }\r
313 \r
314         private void setAndCheck(int nexioPort, String nexioUserName, String nexioPassword, String archiveFtp, String archiveUserName, String archivePassword,\r
315                         String agencies, int limit, int nexioKillDateDays, String nexioAgency, IJobEngine jobEngine) throws Exception {\r
316                 db = NoSQLUtils.getNoSQLDB();\r
317                 if (db == null) {\r
318                         logger.error(systemMarker, "Az NoSQL adatkezelő réteg nem elérhető.");\r
319                         throw new NullPointerException("Internal error, missing NoSQL DB reference.");\r
320                 }\r
321 \r
322                 if (jobEngine == null) {\r
323                         logger.error(systemMarker, "Az folyamatkezelő réteg nem elérhető.");\r
324                         throw new NullPointerException("Internal error, missing JobEngine reference.");\r
325                 }\r
326                 manager = jobEngine.getItemManager();\r
327                 if (manager == null) {\r
328                         logger.error(systemMarker, "Az adatbáziskezelő réteg nem elérhető.");\r
329                         throw new NullPointerException("Internal error, missing ItemManager reference.");\r
330                 }\r
331                 String nexioHost = System.getProperty("nexio.host");\r
332                 if (StringUtils.isBlank(nexioHost)) {\r
333                         logger.error(systemMarker, "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
335                 }\r
336                 check(nexioPort, "nexioPort");\r
337                 check(nexioUserName, "nexioUserName");\r
338                 check(nexioPassword, "nexioPassword");\r
339 \r
340                 check(agencies, "filterAgencies");\r
341                 filterAgencies = agencies.split(",");\r
342 \r
343                 check(limit, "limit");\r
344 \r
345                 check(nexioKillDateDays, "nexioKillDateDays");\r
346                 this.nexioKillDateDays = nexioKillDateDays;\r
347                 check(nexioAgency, "nexioAgency");\r
348                 this.nexioAgency = nexioAgency;\r
349 \r
350                 sourceUri = manager.createStoreUri(RemoteStoreProtocol.FTP, nexioHost);\r
351                 sourceUri.setPortNumber(nexioPort);\r
352                 sourceUri.setUserName(nexioUserName);\r
353                 sourceUri.setPassword(nexioPassword);\r
354                 if (sourceUri == null) {\r
355                         logger.error(systemMarker, "A forrás nem elérhető.");\r
356                         throw new NullPointerException("Internal error, missing 'sourceUri'.");\r
357                 }\r
358 \r
359                 check(archiveFtp, "archiveFtp");\r
360                 check(archiveUserName, "archiveUserName");\r
361                 check(archivePassword, "archivePassword");\r
362 \r
363                 targetUri = manager.createStoreUri(new URI(archiveFtp));\r
364                 targetUri.setUserName(archiveUserName);\r
365                 targetUri.setPassword(archivePassword);\r
366                 if (targetUri == null) {\r
367                         logger.error(systemMarker, "A cél nem elérhető.");\r
368                         throw new NullPointerException("Internal error, missing 'targetUri'.");\r
369                 }\r
370 \r
371         }\r
372 \r
373         private void transferFile(String sourceFileName, String targetFileName) throws Exception {\r
374                 int reply = 0;\r
375                 logger.info("Transfer clip {}", sourceFileName);\r
376                 try {\r
377                         sourceFtp = ((FtpDirectoryLister) sourceUri.getLister()).connect();\r
378                         targetFtp = ((FtpDirectoryLister) targetUri.getLister()).connect();\r
379 \r
380                         if (!targetFtp.enterRemotePassiveMode())\r
381                                 throw new Exception("!PASV");\r
382 \r
383                         reply = sourceFtp.port(InetAddress.getByName(targetFtp.getPassiveHost()), targetFtp.getPassivePort());\r
384                         if (!FTPReply.isPositiveCompletion(reply))\r
385                                 throw new Exception("PORT parancs válasza: " + sourceFtp.getReplyString());\r
386 \r
387                         if (!sourceFtp.setFileType(FTP.BINARY_FILE_TYPE))\r
388                                 throw new Exception("!SOURCE TYPE");\r
389 \r
390                         reply = sourceFtp.retr(sourceFileName);\r
391                         if (!FTPReply.isPositivePreliminary(reply))\r
392                                 throw new Exception("RETR parancs válasza: " + sourceFtp.getReplyString());\r
393 \r
394                         if (!targetFtp.setFileType(FTP.BINARY_FILE_TYPE))\r
395                                 throw new Exception("!TARGET TYPE");\r
396 \r
397                         reply = targetFtp.stor(targetFileName);\r
398                         if (!FTPReply.isPositivePreliminary(reply))\r
399                                 throw new Exception("STOR parancs válasza: " + sourceFtp.getReplyString());\r
400 \r
401                         while (true) {\r
402                                 reply = sourceFtp.stat();\r
403                                 if (!FTPReply.isPositiveCompletion(reply))\r
404                                         throw new Exception("STAT parancs válasza: " + sourceFtp.getReplyString());\r
405 \r
406                                 //logger.info("Status: {}", sourceFtp.getReplyString());\r
407                                 if (reply == 226) {\r
408                                         break;\r
409                                 }\r
410                                 Thread.sleep(1000);\r
411                         }\r
412                 } catch (Exception e) {\r
413                         logger.catching(e);\r
414                         throw e;\r
415                 } finally {\r
416                         sourceUri.cleanUp();\r
417                         targetUri.cleanUp();\r
418                 }\r
419 \r
420         }\r
421 \r
422         private void transferMetadata(String fileName, BasicDBObject metadata) throws Exception {\r
423                 logger.info("Transfer metadata {}", fileName);\r
424                 OutputStream outStream = null;\r
425                 try {\r
426                         targetFtp = ((FtpDirectoryLister) targetUri.getLister()).connect();\r
427                         if (!targetFtp.changeWorkingDirectory(EscortFiles.STATUSFOLDER)) {\r
428                                 targetFtp.makeDirectory(EscortFiles.STATUSFOLDER);\r
429                                 if (!targetFtp.changeWorkingDirectory(EscortFiles.STATUSFOLDER))\r
430                                         throw new Exception("!STATUSFOLDER");\r
431                         }\r
432 \r
433                         outStream = targetFtp.storeFileStream(fileName + JSON_EXT);\r
434                         if (outStream == null) {\r
435                                 throw new NullPointerException("Can not open: " + fileName + JSON_EXT + " Reply:" + targetFtp.getReplyString());\r
436                         }\r
437                         outStream.write(metadata.toString().getBytes(UTF_8));\r
438                         outStream.flush();\r
439                         //targetFtp.changeToParentDirectory();\r
440                 } catch (Exception e) {\r
441                         logger.catching(e);\r
442                         throw e;\r
443                 } finally {\r
444                         if (outStream != null)\r
445                                 outStream.close();\r
446                         targetUri.cleanUp();\r
447                 }\r
448         }\r
449 \r
450 }\r