b2a474c839d4a26778365123b3cf7b767996d4e7
[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.RemoteFileHandler;\r
31 import user.commons.remotestore.RemoteStoreProtocol;\r
32 import user.jobengine.db.IItemManager;\r
33 import user.jobengine.server.IJobEngine;\r
34 import user.jobengine.server.IJobRuntime;\r
35 import user.jobengine.server.steps.MetadataTypeDetector.MetadataType;\r
36 \r
37 public class CopyForArchiveNEXIOMaterialsStep extends JobStep {\r
38         private static final String SCHEDULED_FORMAT = "yyyy.MM.dd HH:mm";\r
39         private static final Logger logger = LogManager.getLogger();\r
40         private static final String ARCHIVED = "ARCHIVED";\r
41         private static final String UTF_8 = "utf-8";\r
42         private static final String JSON_EXT = ".json";\r
43         private static final String XML_EXT = ".xml";\r
44         private static final String DURATION = "duration";\r
45         private static final String MXFEXT = ".MXF";\r
46         private static final String NEXIOCLIPS = "nexioclips";\r
47         private static final String LONGNAMEID = "longnameid";\r
48         private static final String ARCHIVEDRUNDOWNS = "archivedrundowns";\r
49         private static final String ID = "id";\r
50         private OctopusAPI octopusAPI;\r
51         private IItemManager manager;\r
52 \r
53         private DB db;\r
54         private FTPClient sourceFtp;\r
55         private FTPClient targetFtp;\r
56         private StoreUri sourceUri;\r
57         private StoreUri targetUri;\r
58         private int nexioKillDateDays;\r
59         private String nexioAgency;\r
60 \r
61         private int check(int value, String name) {\r
62                 if (value == 0) {\r
63                         logger.error(getMarker(), "A folyamat '{}' bemeneti paramétere 0.", name);\r
64                         throw new NullPointerException(String.format("System is not configured properly, missing '%s' input parameter.", name));\r
65                 }\r
66                 return value;\r
67         }\r
68 \r
69         private String check(String value, String name) {\r
70                 if (value == null) {\r
71                         logger.error(getMarker(), "A folyamat '{}' bemeneti paramétere üres.", name);\r
72                         throw new NullPointerException(String.format("System is not configured properly, missing '%s' input parameter.", name));\r
73                 }\r
74                 return value;\r
75         }\r
76 \r
77         private void copy(RundownArchive rundownArchive) throws Exception {\r
78                 for (StoryArchive storyArchive : rundownArchive.getStoryArchives()) {\r
79                         for (FileArchive fileArchive : storyArchive.getFileArchives()) {\r
80                                 copyFile(fileArchive, rundownArchive, storyArchive);\r
81                         }\r
82                 }\r
83         }\r
84 \r
85         private void copyFile(FileArchive fileArchive, RundownArchive rundownArchive, StoryArchive storyArchive) throws Exception {\r
86                 String fileName = fileArchive.getFileName();\r
87                 String videoFileName = fileName + MXFEXT;\r
88                 transferFile(videoFileName);\r
89                 BasicDBObject metadata = createMetadata(rundownArchive, storyArchive, fileArchive);\r
90                 try {\r
91                         if (!targetFtp.changeWorkingDirectory(EscortFiles.STATUSFOLDER))\r
92                                 targetFtp.makeDirectory(EscortFiles.STATUSFOLDER);\r
93                         if (!targetFtp.changeWorkingDirectory(EscortFiles.STATUSFOLDER))\r
94                                 throw new Exception("!STATUSFOLDER");\r
95                 } catch (Exception e) {\r
96                         logger.catching(e);\r
97                         throw e;\r
98                 }\r
99                 transferMetadata(videoFileName, metadata);\r
100                 targetFtp.changeToParentDirectory();\r
101                 createSourceKillDateFile(rundownArchive, fileName);\r
102         }\r
103 \r
104         private BasicDBObject createMetadata(RundownArchive rundownArchive, StoryArchive storyArchive, FileArchive fileArchive) {\r
105                 //              {\r
106                 //                        "itemHouseId": "43",\r
107                 //                        "itemTitle": "Hazahúzó",\r
108                 //                        "itemDescription": null,\r
109                 //                        "mediaHouseId": "002570",\r
110                 //                        "mediaTitle": "2017.12.13",\r
111                 //                        "mediaDescription": null,\r
112                 //                        "ok": false,\r
113                 //                        "userName": "echotest"\r
114                 //              }\r
115                 BasicDBObject result = new BasicDBObject();\r
116                 result.put("itemHouseID", rundownArchive.getItemHouseId());\r
117                 result.put("itemTitle", rundownArchive.getItemTitle());\r
118                 result.put("itemDescription", rundownArchive.getItemDesc());\r
119                 result.put("userName", "mediacube");\r
120 \r
121                 result.put("mediaHouseId", storyArchive.getMediaHouseId());\r
122                 result.put("mediaTitle", storyArchive.getMediaTitle());\r
123                 result.put("mediaDescription", storyArchive.getMediaDesc());\r
124 \r
125                 result.put("duration", fileArchive.getDuration());\r
126                 return result;\r
127         }\r
128 \r
129         private void createSourceKillDateFile(RundownArchive rundownArchive, String fileName) throws Exception {\r
130                 Calendar killDate = CalendarUtils.createCalendar(rundownArchive.getScheduleDate());\r
131                 killDate.add(Calendar.DAY_OF_YEAR, nexioKillDateDays);\r
132                 byte[] killDateFile = EscortFiles.createNEXIOKillDateFile(fileName, killDate.getTime(), null, nexioAgency);\r
133                 try (OutputStream outStream = sourceFtp.storeFileStream(fileName + XML_EXT)) {\r
134                         outStream.write(killDateFile);\r
135                         outStream.flush();\r
136                 } catch (Exception e) {\r
137                         logger.catching(e);\r
138                         throw e;\r
139                 }\r
140         }\r
141 \r
142         @StepEntry\r
143         public Object[] execute(int nexioPort, String nexioUserName, String nexioPassword, String archiveFtp, String archiveUserName, String archivePassword,\r
144                         int daysBeforeNow, int nexioKillDateDays, String nexioAgency, IJobEngine jobEngine, IJobRuntime jobRuntime) throws Exception {\r
145                 setAndCheck(nexioPort, nexioUserName, nexioPassword, archiveFtp, archiveUserName, archivePassword, nexioKillDateDays, nexioAgency, jobEngine);\r
146                 octopusAPI = new OctopusAPI();\r
147                 Calendar scheduledDate = Calendar.getInstance();\r
148                 scheduledDate.add(Calendar.DAY_OF_YEAR, -1 * daysBeforeNow);\r
149                 List<DBObject> rundowns = octopusAPI.getRundowns(scheduledDate.getTime());\r
150                 if (rundowns == null) {\r
151                         logger.warn(getMarker(), "Nem található adástükör a {} napra.", CalendarUtils.toDateString(scheduledDate));\r
152                         return null;\r
153                 }\r
154 \r
155                 processRundowns(rundowns);\r
156                 if (sourceUri != null)\r
157                         sourceUri.cleanUp();\r
158                 if (targetUri != null)\r
159                         targetUri.cleanUp();\r
160                 return null;\r
161         }\r
162 \r
163         private FileArchive processMosObject(BasicDBObject rundown, BasicDBObject story, BasicDBObject mosObject) throws Exception {\r
164                 String mosID = mosObject.getString(IOctopusAPI.OBJ_ID);\r
165                 if (MetadataTypeDetector.GuessMetadataType(mosID) != MetadataType.OCTOPUSPLACEHOLDER) {\r
166                         logger.trace("Skipping MOS object {}", mosID);\r
167                         return null;\r
168                 }\r
169                 DBCollection clips = db.getCollection(NEXIOCLIPS);\r
170                 BasicDBObject clip = (BasicDBObject) clips.findOne(new BasicDBObject(LONGNAMEID, mosID));\r
171                 if (clip == null) {\r
172                         logger.debug("File NOT exists {}", mosID);\r
173                         throw new Exception(String.format("File NOT exists %s", mosID));\r
174                 } else {\r
175                         logger.debug("File exists {}", mosID);\r
176                 }\r
177                 long duration = NoSQLUtils.asLong(clip, DURATION);\r
178                 return new FileArchive(mosID, duration);\r
179         }\r
180 \r
181         private RundownArchive processRundow(DBObject r) throws Exception {\r
182                 BasicDBObject rundown = (BasicDBObject) r;\r
183                 long rundownID = rundown.getLong(ID);\r
184                 logger.info("Processing rundown {} {}", rundownID, rundown.getString(IOctopusAPI.NAME));\r
185                 List<DBObject> stories = octopusAPI.getRundownFullStories(rundownID);\r
186                 if (stories == null)\r
187                         return null;\r
188                 RundownArchive result = new RundownArchive();\r
189 \r
190                 long id = NoSQLUtils.asLong(rundown, IOctopusAPI.ID);\r
191                 if (id == 0)\r
192                         return null;\r
193                 String name = NoSQLUtils.asString(NoSQLUtils.asDBObject(rundown, IOctopusAPI.RUNDOWN_TYPE), IOctopusAPI.NAME);\r
194                 if (StringUtils.isBlank(name))\r
195                         return null;\r
196                 String channel = NoSQLUtils.asString(NoSQLUtils.asDBObject(rundown, IOctopusAPI.CHANNEL), IOctopusAPI.NAME);\r
197                 Date scheduledStart = rundown.getDate(IOctopusAPI.SCHEDULED_START);\r
198                 if (scheduledStart == null)\r
199                         return null;\r
200                 String start = CalendarUtils.toString(CalendarUtils.createCalendar(scheduledStart), SCHEDULED_FORMAT);\r
201                 result.setScheduleDate(scheduledStart);\r
202                 result.setItemHouseId(String.valueOf(id));\r
203                 result.setItemTitle(String.format("%s %s %s", start, name, channel));\r
204 \r
205                 for (DBObject s : stories) {\r
206                         StoryArchive storyArchive = processStory(rundown, s);\r
207                         if (storyArchive == null)\r
208                                 continue;\r
209                         result.addStoryArchive(storyArchive);\r
210                 }\r
211                 return result;\r
212         }\r
213 \r
214         private void processRundowns(List<DBObject> rundowns) {\r
215                 //db.getCollection(ARCHIVEDRUNDOWNS).drop();\r
216                 List<BasicDBObject> archivedRundowns = queryArchivedRundowns();\r
217 \r
218                 int index = 1;\r
219                 for (DBObject r : rundowns) {\r
220                         BasicDBObject rundown = (BasicDBObject) r;\r
221                         setProgress(index * 100 / rundowns.size());\r
222                         try {\r
223                                 long rundownID = NoSQLUtils.asLong(rundown, IOctopusAPI.ID);\r
224                                 BasicDBObject currentRundownID = new BasicDBObject(IOctopusAPI.ID, rundownID);\r
225                                 String rundownName = rundown.getString(IOctopusAPI.NAME);\r
226                                 if (archivedRundowns != null && archivedRundowns.contains(currentRundownID)) {\r
227                                         logger.info("Skipping archived rundown {} {}", rundownID, rundownName);\r
228                                         continue;\r
229                                 }\r
230 \r
231                                 RundownArchive rundownArchive = processRundow(r);\r
232                                 if (rundownArchive == null || rundownArchive.isEmpty()) {\r
233                                         logger.info("Skipping rundown {} {}", NoSQLUtils.asLong(rundown, IOctopusAPI.ID), rundown.getString(IOctopusAPI.NAME));\r
234                                         continue;\r
235                                 }\r
236 \r
237                                 logger.info("Saving rundown {} {}", rundownID, rundownName);\r
238                                 copy(rundownArchive);\r
239 \r
240                                 db.getCollection(ARCHIVEDRUNDOWNS).save(currentRundownID);\r
241                         } catch (Exception e) {\r
242                                 logger.catching(e);\r
243                                 logger.error(getMarker(),\r
244                                                 "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
245                         }\r
246                         index++;\r
247                 }\r
248         }\r
249 \r
250         private StoryArchive processStory(BasicDBObject rundown, DBObject s) throws Exception {\r
251                 BasicDBObject story = (BasicDBObject) s;\r
252                 String parentStoryID = story.getString(IOctopusAPI.PARENT_STORY_ID);\r
253                 if (StringUtils.isBlank(parentStoryID)) {\r
254                         logger.warn("Story parentStoryID is null: {}", story.toPrettyString(null));\r
255                         return null;\r
256                 } else\r
257                         logger.debug("Processing story {}", parentStoryID);\r
258                 List<BasicDBObject> mosObjects = NoSQLUtils.asList(story, IOctopusAPI.MOS_OBJECTS);\r
259                 if (mosObjects == null)\r
260                         return null;\r
261                 StoryArchive storyArchive = null;\r
262                 for (BasicDBObject mosObject : mosObjects) {\r
263                         FileArchive fileArchive = processMosObject(rundown, story, mosObject);\r
264                         if (fileArchive == null)\r
265                                 continue;\r
266                         if (storyArchive == null) {\r
267                                 storyArchive = new StoryArchive();\r
268                                 storyArchive.setMediaHouseId(parentStoryID);\r
269                                 storyArchive.setMediaTitle(story.getString(IOctopusAPI.NAME));\r
270                                 storyArchive.setMediaDesc(story.getString(IOctopusAPI.SCRIPT_CONTENT));\r
271 \r
272                         }\r
273                         storyArchive.addFileArchive(fileArchive);\r
274                 }\r
275                 return storyArchive;\r
276 \r
277         }\r
278 \r
279         private List<BasicDBObject> queryArchivedRundowns() {\r
280                 List<BasicDBObject> result = null;\r
281                 DBCollection collection = db.getCollection(ARCHIVEDRUNDOWNS);\r
282                 DBCursor find = collection.find(new BasicDBObject(), new BasicDBObject(IOctopusAPI._ID, 0).append(IOctopusAPI.ID, 1));\r
283                 if (find.hasNext())\r
284                         result = ListUtils.cast(find.toArray());\r
285                 return result;\r
286         }\r
287 \r
288         private void setAndCheck(int nexioPort, String nexioUserName, String nexioPassword, String archiveFtp, String archiveUserName, String archivePassword,\r
289                         int nexioKillDateDays, String nexioAgency, IJobEngine jobEngine) throws Exception {\r
290                 db = NoSQLUtils.getNoSQLDB();\r
291                 if (db == null) {\r
292                         logger.error(getMarker(), "Az NoSQL adatkezelő réteg nem elérhető.");\r
293                         throw new NullPointerException("Internal error, missing NoSQL DB reference.");\r
294                 }\r
295 \r
296                 if (jobEngine == null) {\r
297                         logger.error(getMarker(), "Az folyamatkezelő réteg nem elérhető.");\r
298                         throw new NullPointerException("Internal error, missing JobEngine reference.");\r
299                 }\r
300                 manager = jobEngine.getItemManager();\r
301                 if (manager == null) {\r
302                         logger.error(getMarker(), "Az adatbáziskezelő réteg nem elérhető.");\r
303                         throw new NullPointerException("Internal error, missing ItemManager reference.");\r
304                 }\r
305                 String nexioHost = System.getProperty("nexio.host");\r
306                 if (StringUtils.isBlank(nexioHost)) {\r
307                         logger.error(getMarker(), "A 'nexio.host' rendszer paraméter nem található.");\r
308                         throw new NullPointerException("System is not configured properly, 'jobengine.selenio.address' startup parameter missing.");\r
309                 }\r
310                 check(nexioPort, "nexioPort");\r
311                 check(nexioUserName, "nexioUserName");\r
312                 check(nexioPassword, "nexioPassword");\r
313 \r
314                 check(nexioKillDateDays, "nexioKillDateDays");\r
315                 this.nexioKillDateDays = nexioKillDateDays;\r
316                 check(nexioAgency, "nexioAgency");\r
317                 this.nexioAgency = nexioAgency;\r
318 \r
319                 sourceUri = manager.createStoreUri(RemoteStoreProtocol.FTP, nexioHost);\r
320                 sourceUri.setPortNumber(nexioPort);\r
321                 sourceUri.setUserName(nexioUserName);\r
322                 sourceUri.setPassword(nexioPassword);\r
323 \r
324                 check(archiveFtp, "archiveFtp");\r
325                 check(archiveUserName, "archiveUserName");\r
326                 check(archivePassword, "archivePassword");\r
327 \r
328                 targetUri = manager.createStoreUri(new URI(archiveFtp));\r
329                 targetUri.setUserName(archiveUserName);\r
330                 targetUri.setPassword(archivePassword);\r
331 \r
332                 sourceFtp = ((FtpDirectoryLister) RemoteFileHandler.createLister(sourceUri)).connect();\r
333                 targetFtp = ((FtpDirectoryLister) RemoteFileHandler.createLister(targetUri)).connect();\r
334 \r
335         }\r
336 \r
337         private void transferFile(String fileName) throws Exception {\r
338                 int reply = 0;\r
339 \r
340                 if (!targetFtp.enterRemotePassiveMode())\r
341                         throw new Exception("!PASV");\r
342 \r
343                 reply = sourceFtp.port(InetAddress.getByName(targetFtp.getPassiveHost()), targetFtp.getPassivePort());\r
344                 if (!FTPReply.isPositiveCompletion(reply))\r
345                         throw new Exception("!PORT");\r
346 \r
347                 if (!sourceFtp.setFileType(FTP.BINARY_FILE_TYPE))\r
348                         throw new Exception("!SOURCE TYPE");\r
349 \r
350                 sourceFtp.retr(fileName);\r
351 \r
352                 if (!targetFtp.setFileType(FTP.BINARY_FILE_TYPE))\r
353                         throw new Exception("!TARGET TYPE");\r
354 \r
355                 targetFtp.stor(fileName);\r
356 \r
357                 while (true) {\r
358                         reply = sourceFtp.stat();\r
359                         if (!FTPReply.isPositiveCompletion(reply))\r
360                                 throw new Exception("!STAT");\r
361                         String replyText = sourceFtp.getReplyString();\r
362                         if ("226 RETR Transfer Complete(TRANSACTION_SUCCESS)".equals(replyText))\r
363                                 break;\r
364                         Thread.sleep(500);\r
365                 }\r
366         }\r
367 \r
368         private void transferMetadata(String fileName, BasicDBObject metadata) throws Exception {\r
369                 try (OutputStream outStream = targetFtp.storeFileStream(fileName + JSON_EXT)) {\r
370                         outStream.write(metadata.toString().getBytes(UTF_8));\r
371                         outStream.flush();\r
372                 } catch (Exception e) {\r
373                         logger.catching(e);\r
374                         throw e;\r
375                 }\r
376         }\r
377 \r
378 }\r