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