3570e1024d59684d8d70bfb9edda95690e50acd3
[mediacube.git] /
1 package user.jobengine.server.steps;\r
2 \r
3 import java.io.IOException;\r
4 import java.io.OutputStream;\r
5 import java.net.InetAddress;\r
6 import java.net.URI;\r
7 import java.net.URISyntaxException;\r
8 import java.util.Calendar;\r
9 import java.util.Date;\r
10 import java.util.List;\r
11 \r
12 import org.apache.commons.lang.StringUtils;\r
13 import org.apache.commons.net.ftp.FTP;\r
14 import org.apache.commons.net.ftp.FTPClient;\r
15 import org.apache.commons.net.ftp.FTPReply;\r
16 import org.apache.logging.log4j.LogManager;\r
17 import org.apache.logging.log4j.Logger;\r
18 \r
19 import com.ibm.nosql.json.api.BasicDBObject;\r
20 import com.ibm.nosql.json.api.DB;\r
21 import com.ibm.nosql.json.api.DBCollection;\r
22 import com.ibm.nosql.json.api.DBObject;\r
23 \r
24 import user.commons.CalendarUtils;\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.JobEngineException;\r
36 import user.jobengine.server.steps.MetadataTypeDetector.MetadataType;\r
37 \r
38 public class CopyForArchiveNEXIOMaterialsStep extends JobStep {\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 DURATION = "duration";\r
42         private static final String MXFEXT = ".MXF";\r
43         private static final Logger logger = LogManager.getLogger();\r
44         private static final String NEXIOCLIPS = "nexioclips";\r
45         private static final String KILLDATE = "killdate";\r
46         private static final String LONGNAMEID = "longnameid";\r
47         private static final String ID = "id";\r
48         private StoreUri sourceUri;\r
49         private StoreUri targetUri;\r
50         private OctopusAPI octopusAPI;\r
51         private IItemManager manager;\r
52 \r
53         private DB db;\r
54 \r
55         private int check(int value, String name) {\r
56                 if (value == 0) {\r
57                         logger.error(getMarker(), "A folyamat '{}' bemeneti paramétere 0.", name);\r
58                         throw new NullPointerException(String.format("System is not configured properly, missing '%s' input parameter.", name));\r
59                 }\r
60                 return value;\r
61         }\r
62 \r
63         private String check(String value, String name) {\r
64                 if (value == null) {\r
65                         logger.error(getMarker(), "A folyamat '{}' bemeneti paramétere üres.", name);\r
66                         throw new NullPointerException(String.format("System is not configured properly, missing '%s' input parameter.", name));\r
67                 }\r
68                 return value;\r
69         }\r
70 \r
71         private void copy(RundownArchive rundownArchive) throws Exception {\r
72                 for (StoryArchive storyArchive : rundownArchive.getStoryArchives()) {\r
73                         for (FileArchive fileArchive : storyArchive.getFileArchives()) {\r
74                                 copyFile(fileArchive, rundownArchive, storyArchive);\r
75                         }\r
76                 }\r
77         }\r
78 \r
79         private void copyFile(FileArchive fileArchive, RundownArchive rundownArchive, StoryArchive storyArchive) throws Exception {\r
80                 FTPClient source = ((FtpDirectoryLister) RemoteFileHandler.createLister(sourceUri)).connect();\r
81                 FTPClient target = ((FtpDirectoryLister) RemoteFileHandler.createLister(targetUri)).connect();\r
82                 String fileName = fileArchive.getFileName();\r
83                 transferFile(source, target, fileName);\r
84                 BasicDBObject metadata = createMetadata(rundownArchive, storyArchive, fileArchive);\r
85                 try {\r
86                         if (!target.changeWorkingDirectory(EscortFiles.STATUSFOLDER))\r
87                                 target.makeDirectory(EscortFiles.STATUSFOLDER);\r
88                         if (!target.changeWorkingDirectory(EscortFiles.STATUSFOLDER))\r
89                                 throw new Exception("!STATUSFOLDER");\r
90                 } catch (Exception e) {\r
91                         logger.catching(e);\r
92                         throw e;\r
93                 }\r
94                 transferMetadata(target, fileName, metadata);\r
95                 createSourceKillDateFile(source, fileName);\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(FTPClient source, String fileName) {\r
124         }\r
125 \r
126         @StepEntry\r
127         public Object[] execute(int nexioPort, String nexioUserName, String nexioPassword, String archiveFtp, String archiveUserName, String archivePassword,\r
128                         int daysBeforeNow, IJobEngine jobEngine, IJobRuntime jobRuntime) throws Exception {\r
129                 setAndCheck(nexioPort, nexioUserName, nexioPassword, archiveFtp, archiveUserName, archivePassword, jobEngine);\r
130                 octopusAPI = new OctopusAPI();\r
131                 Calendar scheduledDate = Calendar.getInstance();\r
132                 scheduledDate.add(Calendar.DAY_OF_YEAR, -1 * daysBeforeNow);\r
133                 List<DBObject> rundowns = octopusAPI.getRundowns(scheduledDate.getTime());\r
134                 if (rundowns == null) {\r
135                         logger.warn(getMarker(), "Nem található adástükör a {} napra.", CalendarUtils.toDateString(scheduledDate));\r
136                         return null;\r
137                 }\r
138                 int index = 1;\r
139 \r
140                 for (DBObject r : rundowns) {\r
141                         setProgress(index * 100 / rundowns.size());\r
142                         try {\r
143                                 RundownArchive rundownArchive = processRundow(r);\r
144                                 if (rundownArchive == null || rundownArchive.isEmpty())\r
145                                         continue;\r
146                                 copy(rundownArchive);\r
147 \r
148                         } catch (Exception e) {\r
149                                 logger.catching(e);\r
150                                 logger.error(getMarker(),\r
151                                                 "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
152                         }\r
153                         index++;\r
154                 }\r
155                 return null;\r
156         }\r
157 \r
158         private FileArchive processMosObject(BasicDBObject rundown, BasicDBObject story, BasicDBObject mosObject) throws Exception {\r
159                 String mosID = mosObject.getString(IOctopusAPI.OBJ_ID);\r
160                 if (MetadataTypeDetector.GuessMetadataType(mosID) != MetadataType.OCTOPUSPLACEHOLDER) {\r
161                         logger.warn("Skipping MOS object {}", mosID);\r
162                         return null;\r
163                 }\r
164                 DBCollection clips = db.getCollection(NEXIOCLIPS);\r
165                 BasicDBObject clip = (BasicDBObject) clips.findOne(new BasicDBObject(LONGNAMEID, mosID));\r
166                 if (clip == null) {\r
167                         logger.info("File NOT exists {}", mosID);\r
168                         throw new Exception(String.format("File NOT exists %s", mosID));\r
169                 } else {\r
170                         logger.info("File exists {}", mosID);\r
171                 }\r
172                 long duration = NoSQLUtils.asLong(clip, DURATION);\r
173                 return new FileArchive(mosID + MXFEXT, duration);\r
174         }\r
175 \r
176         private RundownArchive processRundow(DBObject r) throws Exception {\r
177                 BasicDBObject rundown = (BasicDBObject) r;\r
178                 long rundownID = rundown.getLong(ID);\r
179                 logger.info("Processing rundown {} {}", rundownID, rundown.getString(IOctopusAPI.NAME));\r
180                 List<DBObject> stories = octopusAPI.getRundownFullStories(rundownID);\r
181                 if (stories == null)\r
182                         return null;\r
183                 RundownArchive result = new RundownArchive();\r
184                 //              {\r
185                 //                      "id":22358752,\r
186                 //                      "rundownType":{"name":"Híradó"},\r
187                 //                      "scheduledStart":{"$date":"2017-12-09T19:00:00.000Z"}\r
188                 //              }\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                 Date scheduledStart = rundown.getDate(IOctopusAPI.SCHEDULED_START);\r
197                 if (scheduledStart == null)\r
198                         return null;\r
199                 String start = CalendarUtils.toHunString(CalendarUtils.createCalendar(scheduledStart));\r
200 \r
201                 result.setItemHouseId(String.valueOf(id));\r
202                 result.setItemTitle(String.format("%s - %s", start, name));\r
203 \r
204                 for (DBObject s : stories) {\r
205                         StoryArchive storyArchive = processStory(rundown, s);\r
206                         if (storyArchive == null)\r
207                                 continue;\r
208                         result.addStoryArchive(storyArchive);\r
209                 }\r
210                 return result;\r
211         }\r
212 \r
213         private StoryArchive processStory(BasicDBObject rundown, DBObject s) throws Exception {\r
214                 BasicDBObject story = (BasicDBObject) s;\r
215                 String parentStoryID = story.getString(IOctopusAPI.PARENT_STORY_ID);\r
216                 if (StringUtils.isBlank(parentStoryID)) {\r
217                         logger.warn("Story parentStoryID is null: {}", story.toPrettyString(null));\r
218                         return null;\r
219                 } else\r
220                         logger.info("Processing story {}", parentStoryID);\r
221                 List<BasicDBObject> mosObjects = NoSQLUtils.asList(story, IOctopusAPI.MOS_OBJECTS);\r
222                 if (mosObjects == null)\r
223                         return null;\r
224                 StoryArchive storyArchive = null;\r
225                 for (BasicDBObject mosObject : mosObjects) {\r
226                         FileArchive fileArchive = processMosObject(rundown, story, mosObject);\r
227                         if (fileArchive == null)\r
228                                 continue;\r
229                         if (storyArchive == null) {\r
230                                 storyArchive = new StoryArchive();\r
231                                 storyArchive.setMediaHouseId(parentStoryID);\r
232                                 storyArchive.setMediaTitle(story.getString(IOctopusAPI.NAME));\r
233                                 storyArchive.setMediaDesc(story.getString(IOctopusAPI.SCRIPT_CONTENT));\r
234 \r
235                         }\r
236                         storyArchive.addFileArchive(fileArchive);\r
237                 }\r
238                 return storyArchive;\r
239 \r
240         }\r
241 \r
242         private void setAndCheck(int nexioPort, String nexioUserName, String nexioPassword, String archiveFtp, String archiveUserName, String archivePassword,\r
243                         IJobEngine jobEngine) throws JobEngineException, IOException, URISyntaxException {\r
244                 db = NoSQLUtils.getNoSQLDB();\r
245                 if (db == null) {\r
246                         logger.error(getMarker(), "Az NoSQL adatkezelő réteg nem elérhető.");\r
247                         throw new NullPointerException("Internal error, missing NoSQL DB reference.");\r
248                 }\r
249 \r
250                 if (jobEngine == null) {\r
251                         logger.error(getMarker(), "Az folyamatkezelő réteg nem elérhető.");\r
252                         throw new NullPointerException("Internal error, missing JobEngine reference.");\r
253                 }\r
254                 manager = jobEngine.getItemManager();\r
255                 if (manager == null) {\r
256                         logger.error(getMarker(), "Az adatbáziskezelő réteg nem elérhető.");\r
257                         throw new NullPointerException("Internal error, missing ItemManager reference.");\r
258                 }\r
259                 String nexioHost = System.getProperty("nexio.host");\r
260                 if (StringUtils.isBlank(nexioHost)) {\r
261                         logger.error(getMarker(), "A 'nexio.host' rendszer paraméter nem található.");\r
262                         throw new NullPointerException("System is not configured properly, 'jobengine.selenio.address' startup parameter missing.");\r
263                 }\r
264                 check(nexioPort, "nexioPort");\r
265                 check(nexioUserName, "nexioUserName");\r
266                 check(nexioPassword, "nexioPassword");\r
267 \r
268                 sourceUri = manager.createStoreUri(RemoteStoreProtocol.FTP, nexioHost);\r
269                 sourceUri.setPortNumber(nexioPort);\r
270                 sourceUri.setUserName(nexioUserName);\r
271                 sourceUri.setPassword(nexioPassword);\r
272 \r
273                 check(archiveFtp, "archiveFtp");\r
274                 check(archiveUserName, "archiveUserName");\r
275                 check(archivePassword, "archivePassword");\r
276 \r
277                 targetUri = manager.createStoreUri(new URI(archiveFtp));\r
278                 targetUri.setUserName(archiveUserName);\r
279                 targetUri.setPassword(archivePassword);\r
280         }\r
281 \r
282         private void transferFile(FTPClient source, FTPClient target, String fileName) throws Exception {\r
283                 int reply = 0;\r
284 \r
285                 if (!target.enterRemotePassiveMode())\r
286                         throw new Exception("!PASV");\r
287 \r
288                 reply = source.port(InetAddress.getByName(target.getPassiveHost()), target.getPassivePort());\r
289                 if (!FTPReply.isPositiveCompletion(reply))\r
290                         throw new Exception("!PORT");\r
291 \r
292                 if (!source.setFileType(FTP.BINARY_FILE_TYPE))\r
293                         throw new Exception("!SOURCE TYPE");\r
294 \r
295                 source.retr(fileName);\r
296 \r
297                 if (!target.setFileType(FTP.BINARY_FILE_TYPE))\r
298                         throw new Exception("!TARGET TYPE");\r
299 \r
300                 target.stor(fileName);\r
301 \r
302                 while (true) {\r
303                         reply = source.stat();\r
304                         if (!FTPReply.isPositiveCompletion(reply))\r
305                                 throw new Exception("!STAT");\r
306                         String replyText = source.getReplyString();\r
307                         if ("Transaction completed".equals(replyText))\r
308                                 break;\r
309                         Thread.sleep(500);\r
310                 }\r
311         }\r
312 \r
313         private void transferMetadata(FTPClient target, String fileName, BasicDBObject metadata) throws Exception {\r
314                 try (OutputStream outStream = target.storeFileStream(fileName + JSON_EXT)) {\r
315                         outStream.write(metadata.toString().getBytes(UTF_8));\r
316                         outStream.flush();\r
317                 } catch (Exception e) {\r
318                         logger.catching(e);\r
319                         throw e;\r
320                 }\r
321         }\r
322 \r
323 }\r