35bba94f9dda808d47d4e1ae4108eeba7f4477fd
[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.util.Calendar;\r
7 import java.util.Date;\r
8 import java.util.List;\r
9 \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
16 \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
22 \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
35 \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
51 \r
52         private DB db;\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
59 \r
60         private int check(int value, String name) {\r
61                 if (value == 0) {\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
64                 }\r
65                 return value;\r
66         }\r
67 \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
72                 }\r
73                 return value;\r
74         }\r
75 \r
76         private void copy(RundownArchive rundownArchive) throws Exception {\r
77                 for (StoryArchive storyArchive : rundownArchive.getStoryArchives()) {\r
78                         for (FileArchive fileArchive : storyArchive.getFileArchives()) {\r
79                                 try {\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
83                                 }\r
84                         }\r
85                 }\r
86         }\r
87 \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
92 \r
93                 transferFile(origFileName + MXFEXT, videoFileName);\r
94                 BasicDBObject metadata = createMetadata(rundownArchive, storyArchive, fileArchive);\r
95                 transferMetadata(videoFileName, metadata);\r
96                 createSourceKillDateFile(rundownArchive, origFileName);\r
97         }\r
98 \r
99         private BasicDBObject createMetadata(RundownArchive rundownArchive, StoryArchive storyArchive, FileArchive fileArchive) {\r
100                 BasicDBObject result = new BasicDBObject();\r
101                 result.put("itemHouseId", rundownArchive.getItemHouseId());\r
102                 result.put("itemTitle", rundownArchive.getItemTitle());\r
103                 result.put("itemDescription", rundownArchive.getItemDesc());\r
104                 result.put("userName", "mediacube");\r
105 \r
106                 result.put("mediaHouseId", storyArchive.getMediaHouseId());\r
107                 result.put("mediaTitle", storyArchive.getMediaTitle());\r
108                 result.put("mediaDescription", storyArchive.getMediaDesc());\r
109                 result.put("mediaType", MEDIATYPE);\r
110 \r
111                 result.put("duration", fileArchive.getDuration());\r
112                 return result;\r
113         }\r
114 \r
115         private void createSourceKillDateFile(RundownArchive rundownArchive, String fileName) throws Exception {\r
116                 logger.info("Create killdate/agency for {}", fileName);\r
117                 OutputStream outStream = null;\r
118                 try {\r
119                         sourceFtp = ((FtpDirectoryLister) sourceUri.getLister()).connect();\r
120                         Calendar killDate = CalendarUtils.createCalendar(rundownArchive.getScheduleDate());\r
121                         killDate.add(Calendar.DAY_OF_YEAR, nexioKillDateDays);\r
122                         byte[] killDateFile = EscortFiles.createNEXIOKillDateFile(fileName, killDate.getTime(), null, nexioAgency);\r
123                         outStream = sourceFtp.storeFileStream(fileName + XML_EXT);\r
124                         if (outStream == null) {\r
125                                 throw new NullPointerException("Can not open: " + fileName + XML_EXT + " Reply:" + sourceFtp.getReplyString());\r
126                         }\r
127                         outStream.write(killDateFile);\r
128                         outStream.flush();\r
129                 } catch (Exception e) {\r
130                         logger.catching(e);\r
131                         throw e;\r
132                 } finally {\r
133                         if (outStream != null)\r
134                                 outStream.close();\r
135                         sourceUri.cleanUp();\r
136                 }\r
137         }\r
138 \r
139         @StepEntry\r
140         public Object[] execute(int nexioPort, String nexioUserName, String nexioPassword, String archiveFtp, String archiveUserName, String archivePassword,\r
141                         int daysBeforeNow, int nexioKillDateDays, String nexioAgency, IJobEngine jobEngine, IJobRuntime jobRuntime) throws Exception {\r
142                 setAndCheck(nexioPort, nexioUserName, nexioPassword, archiveFtp, archiveUserName, archivePassword, nexioKillDateDays, nexioAgency, jobEngine);\r
143                 octopusAPI = new OctopusAPI();\r
144                 Calendar scheduledDate = Calendar.getInstance();\r
145                 scheduledDate.add(Calendar.DAY_OF_YEAR, -1 * daysBeforeNow);\r
146                 List<DBObject> rundowns = octopusAPI.getRundowns(scheduledDate.getTime());\r
147                 if (rundowns == null) {\r
148                         logger.warn(getMarker(), "Nem található adástükör a {} napra.", CalendarUtils.toDateString(scheduledDate));\r
149                         return null;\r
150                 }\r
151 \r
152                 processRundowns(rundowns);\r
153                 return null;\r
154         }\r
155 \r
156         //      private String getVersionedFileName(String fileName, String extension) throws Exception {\r
157         //              String result = fileName;\r
158         //              try {\r
159         //                      targetFtp = ((FtpDirectoryLister) targetUri.getLister()).connect();\r
160         //                      FTPFile[] listFiles = targetFtp.listFiles();\r
161         //                      List<String> fileNames = new ArrayList<>();\r
162         //                      for (FTPFile ftpFile : listFiles) {\r
163         //                              fileNames.add(ftpFile.getName());\r
164         //                      }\r
165         //                      while (fileNames.contains(result + extension)) {\r
166         //\r
167         //                      }\r
168         //\r
169         //              } catch (Exception e) {\r
170         //                      logger.catching(e);\r
171         //                      throw e;\r
172         //              } finally {\r
173         //                      targetUri.cleanUp();\r
174         //              }\r
175         //              return result;\r
176         //      }\r
177 \r
178         private FileArchive processMosObject(BasicDBObject rundown, BasicDBObject story, BasicDBObject mosObject) throws Exception {\r
179                 String mosID = mosObject.getString(IOctopusAPI.OBJ_ID);\r
180                 if (MetadataTypeDetector.GuessMetadataType(mosID) != MetadataType.OCTOPUSPLACEHOLDER) {\r
181                         logger.trace("Skipping MOS object {}", mosID);\r
182                         return null;\r
183                 }\r
184                 DBCollection clips = db.getCollection(NEXIOCLIPS);\r
185                 BasicDBObject clip = (BasicDBObject) clips.findOne(new BasicDBObject(LONGNAMEID, mosID));\r
186                 if (clip == null) {\r
187                         logger.debug("File NOT exists {}", mosID);\r
188                         return null;\r
189                         //throw new Exception(String.format("File NOT exists %s", mosID));\r
190                 } else {\r
191                         logger.debug("File exists {}", mosID);\r
192                 }\r
193                 long duration = NoSQLUtils.asLong(clip, DURATION);\r
194                 return new FileArchive(mosID, duration);\r
195         }\r
196 \r
197         private RundownArchive processRundow(DBObject r) throws Exception {\r
198                 BasicDBObject rundown = (BasicDBObject) r;\r
199                 long rundownID = rundown.getLong(ID);\r
200                 logger.info("Processing rundown {} {}", rundownID, rundown.getString(IOctopusAPI.NAME));\r
201                 List<DBObject> stories = octopusAPI.getRundownFullStories(rundownID);\r
202                 if (stories == null)\r
203                         return null;\r
204                 RundownArchive result = new RundownArchive();\r
205 \r
206                 long id = NoSQLUtils.asLong(rundown, IOctopusAPI.ID);\r
207                 if (id == 0)\r
208                         return null;\r
209                 String name = NoSQLUtils.asString(NoSQLUtils.asDBObject(rundown, IOctopusAPI.RUNDOWN_TYPE), IOctopusAPI.NAME);\r
210                 if (StringUtils.isBlank(name))\r
211                         return null;\r
212                 String channel = NoSQLUtils.asString(NoSQLUtils.asDBObject(rundown, IOctopusAPI.CHANNEL), IOctopusAPI.NAME);\r
213                 Date scheduledStart = rundown.getDate(IOctopusAPI.SCHEDULED_START);\r
214                 if (scheduledStart == null)\r
215                         return null;\r
216                 String start = CalendarUtils.toString(CalendarUtils.createCalendar(scheduledStart), SCHEDULED_FORMAT);\r
217                 result.setScheduleDate(scheduledStart);\r
218                 result.setItemHouseId(String.valueOf(id));\r
219                 result.setItemTitle(String.format("%s %s %s", start, name, channel));\r
220 \r
221                 for (DBObject s : stories) {\r
222                         StoryArchive storyArchive = processStory(rundown, s);\r
223                         if (storyArchive == null)\r
224                                 continue;\r
225                         result.addStoryArchive(storyArchive);\r
226                 }\r
227                 return result;\r
228         }\r
229 \r
230         private void processRundowns(List<DBObject> rundowns) {\r
231 \r
232                 //TODO kiveni publikálás előtt\r
233                 //db.getCollection(ARCHIVEDRUNDOWNS).drop();\r
234                 List<BasicDBObject> archivedRundowns = queryArchivedRundowns();\r
235 \r
236                 int index = 1;\r
237 \r
238                 for (DBObject r : rundowns) {\r
239                         BasicDBObject rundown = (BasicDBObject) r;\r
240                         setProgress(index * 100 / rundowns.size());\r
241                         long rundownID = NoSQLUtils.asLong(rundown, IOctopusAPI.ID);\r
242                         String rundownName = NoSQLUtils.asString(rundown, IOctopusAPI.NAME);\r
243                         try {\r
244                                 BasicDBObject currentRundownID = new BasicDBObject(IOctopusAPI.ID, rundownID);\r
245                                 if (archivedRundowns != null && archivedRundowns.contains(currentRundownID)) {\r
246                                         logger.info("Skipping archived rundown {} {}", rundownID, rundownName);\r
247                                         continue;\r
248                                 }\r
249 \r
250                                 RundownArchive rundownArchive = processRundow(r);\r
251                                 if (rundownArchive == null || rundownArchive.isEmpty()) {\r
252                                         logger.info("Skipping rundown {} {}", rundownID, rundownName);\r
253                                         continue;\r
254                                 }\r
255 \r
256                                 logger.info("Saving rundown {} {}", rundownID, rundownName);\r
257                                 copy(rundownArchive);\r
258 \r
259                                 db.getCollection(ARCHIVEDRUNDOWNS).save(currentRundownID);\r
260                         } catch (Exception e) {\r
261                                 logger.catching(e);\r
262                                 logger.error(getMarker(),\r
263                                                 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
264                                                                 rundownName, e.getMessage()));\r
265                         }\r
266                         index++;\r
267                 }\r
268 \r
269         }\r
270 \r
271         private StoryArchive processStory(BasicDBObject rundown, DBObject s) throws Exception {\r
272                 BasicDBObject story = (BasicDBObject) s;\r
273                 String parentStoryID = story.getString(IOctopusAPI.PARENT_STORY_ID);\r
274                 if (StringUtils.isBlank(parentStoryID)) {\r
275                         logger.warn("Story parentStoryID is null: {}", story.toPrettyString(null));\r
276                         return null;\r
277                 } else\r
278                         logger.debug("Processing story {}", parentStoryID);\r
279                 List<BasicDBObject> mosObjects = NoSQLUtils.asList(story, IOctopusAPI.MOS_OBJECTS);\r
280                 if (mosObjects == null)\r
281                         return null;\r
282                 StoryArchive storyArchive = null;\r
283                 for (BasicDBObject mosObject : mosObjects) {\r
284                         FileArchive fileArchive = processMosObject(rundown, story, mosObject);\r
285                         if (fileArchive == null)\r
286                                 continue;\r
287                         if (storyArchive == null) {\r
288                                 storyArchive = new StoryArchive();\r
289                                 storyArchive.setMediaHouseId(parentStoryID);\r
290                                 storyArchive.setMediaTitle(story.getString(IOctopusAPI.NAME));\r
291                                 storyArchive.setMediaDesc(story.getString(IOctopusAPI.SCRIPT_CONTENT));\r
292 \r
293                         }\r
294                         storyArchive.addFileArchive(fileArchive);\r
295                 }\r
296                 return storyArchive;\r
297 \r
298         }\r
299 \r
300         private List<BasicDBObject> queryArchivedRundowns() {\r
301                 List<BasicDBObject> result = null;\r
302                 DBCollection collection = db.getCollection(ARCHIVEDRUNDOWNS);\r
303                 DBCursor find = collection.find(new BasicDBObject(), new BasicDBObject(IOctopusAPI._ID, 0).append(IOctopusAPI.ID, 1));\r
304                 if (find.hasNext())\r
305                         result = ListUtils.cast(find.toArray());\r
306                 return result;\r
307         }\r
308 \r
309         private void setAndCheck(int nexioPort, String nexioUserName, String nexioPassword, String archiveFtp, String archiveUserName, String archivePassword,\r
310                         int nexioKillDateDays, String nexioAgency, IJobEngine jobEngine) throws Exception {\r
311                 db = NoSQLUtils.getNoSQLDB();\r
312                 if (db == null) {\r
313                         logger.error(getMarker(), "Az NoSQL adatkezelő réteg nem elérhető.");\r
314                         throw new NullPointerException("Internal error, missing NoSQL DB reference.");\r
315                 }\r
316 \r
317                 if (jobEngine == null) {\r
318                         logger.error(getMarker(), "Az folyamatkezelő réteg nem elérhető.");\r
319                         throw new NullPointerException("Internal error, missing JobEngine reference.");\r
320                 }\r
321                 manager = jobEngine.getItemManager();\r
322                 if (manager == null) {\r
323                         logger.error(getMarker(), "Az adatbáziskezelő réteg nem elérhető.");\r
324                         throw new NullPointerException("Internal error, missing ItemManager reference.");\r
325                 }\r
326                 String nexioHost = System.getProperty("nexio.host");\r
327                 if (StringUtils.isBlank(nexioHost)) {\r
328                         logger.error(getMarker(), "A 'nexio.host' rendszer paraméter nem található.");\r
329                         throw new NullPointerException("System is not configured properly, 'jobengine.selenio.address' startup parameter missing.");\r
330                 }\r
331                 check(nexioPort, "nexioPort");\r
332                 check(nexioUserName, "nexioUserName");\r
333                 check(nexioPassword, "nexioPassword");\r
334 \r
335                 check(nexioKillDateDays, "nexioKillDateDays");\r
336                 this.nexioKillDateDays = nexioKillDateDays;\r
337                 check(nexioAgency, "nexioAgency");\r
338                 this.nexioAgency = nexioAgency;\r
339 \r
340                 sourceUri = manager.createStoreUri(RemoteStoreProtocol.FTP, nexioHost);\r
341                 sourceUri.setPortNumber(nexioPort);\r
342                 sourceUri.setUserName(nexioUserName);\r
343                 sourceUri.setPassword(nexioPassword);\r
344                 if (sourceUri == null) {\r
345                         logger.error(getMarker(), "A forrás nem elérhető.");\r
346                         throw new NullPointerException("Internal error, missing 'sourceUri'.");\r
347                 }\r
348 \r
349                 check(archiveFtp, "archiveFtp");\r
350                 check(archiveUserName, "archiveUserName");\r
351                 check(archivePassword, "archivePassword");\r
352 \r
353                 targetUri = manager.createStoreUri(new URI(archiveFtp));\r
354                 targetUri.setUserName(archiveUserName);\r
355                 targetUri.setPassword(archivePassword);\r
356                 if (targetUri == null) {\r
357                         logger.error(getMarker(), "A cél nem elérhető.");\r
358                         throw new NullPointerException("Internal error, missing 'targetUri'.");\r
359                 }\r
360 \r
361         }\r
362 \r
363         private void transferFile(String sourceFileName, String targetFileName) throws Exception {\r
364                 int reply = 0;\r
365                 logger.info("Transfer clip {}", sourceFileName);\r
366                 try {\r
367                         sourceFtp = ((FtpDirectoryLister) sourceUri.getLister()).connect();\r
368                         targetFtp = ((FtpDirectoryLister) targetUri.getLister()).connect();\r
369                         if (!targetFtp.enterRemotePassiveMode())\r
370                                 throw new Exception("!PASV");\r
371 \r
372                         reply = sourceFtp.port(InetAddress.getByName(targetFtp.getPassiveHost()), targetFtp.getPassivePort());\r
373                         if (!FTPReply.isPositiveCompletion(reply))\r
374                                 throw new Exception("PORT parancs válasza: " + sourceFtp.getReplyString());\r
375 \r
376                         if (!sourceFtp.setFileType(FTP.BINARY_FILE_TYPE))\r
377                                 throw new Exception("!SOURCE TYPE");\r
378 \r
379                         reply = sourceFtp.retr(sourceFileName);\r
380                         if (!FTPReply.isPositivePreliminary(reply))\r
381                                 throw new Exception("RETR parancs válasza: " + sourceFtp.getReplyString());\r
382 \r
383                         if (!targetFtp.setFileType(FTP.BINARY_FILE_TYPE))\r
384                                 throw new Exception("!TARGET TYPE");\r
385 \r
386                         reply = targetFtp.stor(targetFileName);\r
387                         if (!FTPReply.isPositivePreliminary(reply))\r
388                                 throw new Exception("STOR parancs válasza: " + sourceFtp.getReplyString());\r
389 \r
390                         while (true) {\r
391                                 reply = sourceFtp.stat();\r
392                                 if (!FTPReply.isPositiveCompletion(reply))\r
393                                         throw new Exception("STAT parancs válasza: " + sourceFtp.getReplyString());\r
394 \r
395                                 logger.info("Status: {}", sourceFtp.getReplyString());\r
396                                 if (reply == 226) {\r
397                                         break;\r
398                                 }\r
399                                 Thread.sleep(1000);\r
400                         }\r
401                 } catch (Exception e) {\r
402                         logger.catching(e);\r
403                         throw e;\r
404                 } finally {\r
405                         sourceUri.cleanUp();\r
406                         targetUri.cleanUp();\r
407                 }\r
408 \r
409         }\r
410 \r
411         private void transferMetadata(String fileName, BasicDBObject metadata) throws Exception {\r
412                 logger.info("Transfer metadata {}", fileName);\r
413                 OutputStream outStream = null;\r
414                 try {\r
415                         targetFtp = ((FtpDirectoryLister) targetUri.getLister()).connect();\r
416                         if (!targetFtp.changeWorkingDirectory(EscortFiles.STATUSFOLDER)) {\r
417                                 targetFtp.makeDirectory(EscortFiles.STATUSFOLDER);\r
418                                 if (!targetFtp.changeWorkingDirectory(EscortFiles.STATUSFOLDER))\r
419                                         throw new Exception("!STATUSFOLDER");\r
420                         }\r
421 \r
422                         outStream = targetFtp.storeFileStream(fileName + JSON_EXT);\r
423                         if (outStream == null) {\r
424                                 throw new NullPointerException("Can not open: " + fileName + JSON_EXT + " Reply:" + targetFtp.getReplyString());\r
425                         }\r
426                         outStream.write(metadata.toString().getBytes(UTF_8));\r
427                         outStream.flush();\r
428                         //targetFtp.changeToParentDirectory();\r
429                 } catch (Exception e) {\r
430                         logger.catching(e);\r
431                         throw e;\r
432                 } finally {\r
433                         if (outStream != null)\r
434                                 outStream.close();\r
435                         targetUri.cleanUp();\r
436                 }\r
437         }\r
438 \r
439 }\r