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