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