0c9655b796d6946f60dc6dc3a23eaec24b8346af
[mediacube.git] /
1 package hu.user.mediacube.executors.tests;\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.ArrayList;\r
7 import java.util.Calendar;\r
8 import java.util.Date;\r
9 import java.util.List;\r
10 \r
11 import org.apache.commons.lang.StringUtils;\r
12 import org.apache.commons.net.ftp.FTP;\r
13 import org.apache.commons.net.ftp.FTPClient;\r
14 import org.apache.commons.net.ftp.FTPReply;\r
15 import org.apache.logging.log4j.LogManager;\r
16 import org.apache.logging.log4j.Logger;\r
17 import org.apache.logging.log4j.Marker;\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.DBObject;\r
22 \r
23 import user.commons.CalendarUtils;\r
24 import user.commons.StoreUri;\r
25 import user.commons.configuration.SystemConfiguration;\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.steps.EscortFiles;\r
33 import user.jobengine.server.steps.FileArchive;\r
34 import user.jobengine.server.steps.RundownArchive;\r
35 import user.jobengine.server.steps.StoryArchive;\r
36 \r
37 public class RescueNEXIOMaterials {\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 UTF_8 = "utf-8";\r
41         private static final String JSON_EXT = ".json";\r
42         private static final String XML_EXT = ".xml";\r
43         private static final String MXFEXT = ".MXF";\r
44         private static String NEXIO_HOST = SystemConfiguration.getInstance().value("services.nexio.host");\r
45         private static final String ID = "id";\r
46         private static final String MEDIATYPE = "Hír bejátszó";\r
47         private OctopusAPI octopusAPI;\r
48 \r
49         private DB db;\r
50         private FTPClient sourceFtp;\r
51         private FTPClient targetFtp;\r
52         private StoreUri sourceUri;\r
53         private StoreUri targetUri;\r
54         private int nexioKillDateDays;\r
55         private String nexioAgency;\r
56         private Marker systemMarker;\r
57         private List<String> transferredFileNames = null;\r
58         private boolean demo = false;\r
59 \r
60         public void copy(RundownArchive rundownArchive) throws Exception {\r
61                 for (StoryArchive storyArchive : rundownArchive.getStoryArchives()) {\r
62                         for (FileArchive fileArchive : storyArchive.getFileArchives()) {\r
63                                 try {\r
64                                         copyFile(fileArchive, rundownArchive, storyArchive);\r
65                                 } catch (Exception e) {\r
66                                         logger.error(systemMarker, "A '{}' clip archiválása sikertelen. A rendszer üzenete: {}", fileArchive.getFileName(), e.getMessage());\r
67                                         throw e;\r
68                                 }\r
69                         }\r
70                 }\r
71         }\r
72 \r
73         private void copyFile(FileArchive fileArchive, RundownArchive rundownArchive, StoryArchive storyArchive) throws Exception {\r
74                 String origFileName = fileArchive.getFileName();\r
75                 String fileName = String.format("%s-%s", origFileName, rundownArchive.getItemHouseId());\r
76                 String videoFileName = fileName + MXFEXT;\r
77 \r
78                 if (transferredFileNames == null)\r
79                         transferredFileNames = new ArrayList<>();\r
80 \r
81                 //A mar letezo mozikat nem archivaljuk le ujra, csak a metaadatot\r
82                 long existingMediaId = 0;\r
83                 if (!transferredFileNames.contains(origFileName)) {\r
84                         transferredFileNames.add(origFileName);\r
85                         if (!demo)\r
86                                 transferFile(origFileName + MXFEXT, videoFileName);\r
87                         logger.info(systemMarker, "A '{}' file archiválásra felkészítése sikeres volt.", origFileName);\r
88                 }\r
89 \r
90                 if (!demo) {\r
91                         BasicDBObject metadata = createMetadata(rundownArchive, storyArchive, fileArchive, existingMediaId);\r
92                         transferMetadata(videoFileName, metadata);\r
93                         createSourceKillDateFile(rundownArchive, origFileName);\r
94                 }\r
95         }\r
96 \r
97         private BasicDBObject createMetadata(RundownArchive rundownArchive, StoryArchive storyArchive, FileArchive fileArchive, long existingMediaId) {\r
98                 BasicDBObject result = new BasicDBObject();\r
99                 result.put("itemHouseId", rundownArchive.getItemHouseId());\r
100                 result.put("itemTitle", rundownArchive.getItemTitle());\r
101                 result.put("itemDescription", rundownArchive.getItemDesc());\r
102                 result.put("userName", "mediacube");\r
103                 result.put("mediaHouseId", storyArchive.getMediaHouseId());\r
104                 result.put("mediaTitle", storyArchive.getMediaTitle());\r
105                 result.put("mediaDescription", storyArchive.getMediaDesc());\r
106                 result.put("mediaType", MEDIATYPE);\r
107                 result.put("duration", fileArchive.getDuration());\r
108                 result.put("existingMediaId", existingMediaId);\r
109                 return result;\r
110         }\r
111 \r
112         private void createSourceKillDateFile(RundownArchive rundownArchive, String fileName) throws Exception {\r
113                 logger.info("Create killdate/agency for {}", fileName);\r
114                 OutputStream outStream = null;\r
115                 try {\r
116                         sourceFtp = ((FtpDirectoryLister) sourceUri.getLister()).connect();\r
117                         Calendar killDate = CalendarUtils.createCalendar(rundownArchive.getScheduleDate());\r
118                         killDate.add(Calendar.DAY_OF_YEAR, nexioKillDateDays);\r
119                         byte[] killDateFile = EscortFiles.createNEXIOKillDateFile(fileName, killDate.getTime(), null, nexioAgency);\r
120                         outStream = sourceFtp.storeFileStream(fileName + XML_EXT);\r
121                         if (outStream == null) {\r
122                                 throw new NullPointerException("Can not open: " + fileName + XML_EXT + " Reply:" + sourceFtp.getReplyString());\r
123                         }\r
124                         outStream.write(killDateFile);\r
125                         outStream.flush();\r
126                 } catch (Exception e) {\r
127                         logger.catching(e);\r
128                         throw e;\r
129                 } finally {\r
130                         if (outStream != null)\r
131                                 outStream.close();\r
132                         sourceUri.cleanUp();\r
133                 }\r
134         }\r
135 \r
136         private FileArchive processMosObject(BasicDBObject rundown, BasicDBObject story, BasicDBObject mosObject, String clipName, long duration) throws Exception {\r
137                 String mosID = mosObject.getString(IOctopusAPI.OBJ_ID);\r
138                 if (!mosID.equals(clipName))\r
139                         return null;\r
140                 return new FileArchive(mosID, duration);\r
141         }\r
142 \r
143         public RundownArchive processRundow(String clipName, long duration) throws Exception {\r
144                 octopusAPI = new OctopusAPI();\r
145                 List<DBObject> rds = octopusAPI.getRundownsByPlaceHolderID(clipName);\r
146                 if (rds == null || rds.size() == 0)\r
147                         return null;\r
148                 BasicDBObject rundown = (BasicDBObject) rds.get(0);\r
149                 long rundownID = rundown.getLong(ID);\r
150                 if (!demo)\r
151                         logger.info("Processing rundown {} {}", rundownID, rundown.getString(IOctopusAPI.NAME));\r
152                 List<DBObject> stories = octopusAPI.getRundownFullStories(rundownID);\r
153                 if (stories == null)\r
154                         return null;\r
155                 RundownArchive result = new RundownArchive();\r
156 \r
157                 long id = NoSQLUtils.asLong(rundown, IOctopusAPI.ID);\r
158                 if (id == 0)\r
159                         return null;\r
160                 String name = NoSQLUtils.asString(NoSQLUtils.asDBObject(rundown, IOctopusAPI.RUNDOWN_TYPE), IOctopusAPI.NAME);\r
161                 if (StringUtils.isBlank(name))\r
162                         return null;\r
163                 String channel = NoSQLUtils.asString(NoSQLUtils.asDBObject(rundown, IOctopusAPI.CHANNEL), IOctopusAPI.NAME);\r
164                 Date scheduledStart = rundown.getDate(IOctopusAPI.SCHEDULED_START);\r
165                 if (scheduledStart == null)\r
166                         return null;\r
167                 String start = CalendarUtils.toString(CalendarUtils.createCalendar(scheduledStart), SCHEDULED_FORMAT);\r
168                 result.setScheduleDate(scheduledStart);\r
169                 result.setItemHouseId(String.valueOf(id));\r
170                 result.setItemTitle(String.format("%s %s %s", start, name, channel));\r
171 \r
172                 for (DBObject s : stories) {\r
173                         StoryArchive storyArchive = processStory(rundown, s, clipName, duration);\r
174                         if (storyArchive == null)\r
175                                 continue;\r
176                         result.addStoryArchive(storyArchive);\r
177                         break;\r
178                 }\r
179                 return result;\r
180         }\r
181 \r
182         private StoryArchive processStory(BasicDBObject rundown, DBObject s, String clipName, long duration) throws Exception {\r
183                 BasicDBObject story = (BasicDBObject) s;\r
184                 String parentStoryID = story.getString(IOctopusAPI.PARENT_STORY_ID);\r
185                 if (StringUtils.isBlank(parentStoryID)) {\r
186                         logger.warn("Story parentStoryID is null: {}", story.toPrettyString(null));\r
187                         return null;\r
188                 } else\r
189                         logger.debug("Processing story {}", parentStoryID);\r
190                 List<BasicDBObject> mosObjects = NoSQLUtils.asList(story, IOctopusAPI.MOS_OBJECTS);\r
191                 if (mosObjects == null)\r
192                         return null;\r
193 \r
194                 StoryArchive storyArchive = null;\r
195                 for (BasicDBObject mosObject : mosObjects) {\r
196                         FileArchive fileArchive = processMosObject(rundown, story, mosObject, clipName, duration);\r
197                         if (fileArchive == null)\r
198                                 continue;\r
199                         if (storyArchive == null) {\r
200                                 storyArchive = new StoryArchive();\r
201                                 storyArchive.setMediaHouseId(parentStoryID);\r
202                                 storyArchive.setMediaTitle(story.getString(IOctopusAPI.NAME));\r
203                                 storyArchive.setMediaDesc(story.getString(IOctopusAPI.SCRIPT_CONTENT));\r
204 \r
205                         }\r
206                         storyArchive.addFileArchive(fileArchive);\r
207                 }\r
208                 return storyArchive;\r
209 \r
210         }\r
211 \r
212         public void set(int nexioPort, String nexioUserName, String nexioPassword, String archiveFtp, String archiveUserName, String archivePassword,\r
213                         int nexioKillDateDays, String nexioAgency, IItemManager manager) throws Exception {\r
214                 db = NoSQLUtils.getNoSQLDB();\r
215                 if (db == null) {\r
216                         logger.error(systemMarker, "Az NoSQL adatkezelő réteg nem elérhető.");\r
217                         throw new NullPointerException("Internal error, missing NoSQL DB reference.");\r
218                 }\r
219 \r
220                 if (manager == null) {\r
221                         logger.error(systemMarker, "Az adatbáziskezelő réteg nem elérhető.");\r
222                         throw new NullPointerException("Internal error, missing ItemManager reference.");\r
223                 }\r
224                 if (StringUtils.isBlank(NEXIO_HOST)) {\r
225                         logger.error(systemMarker, "A 'nexio.host' rendszer paraméter nem található.");\r
226                         throw new NullPointerException("System is not configured properly, 'jobengine.selenio.address' startup parameter missing.");\r
227                 }\r
228                 this.nexioKillDateDays = nexioKillDateDays;\r
229                 this.nexioAgency = nexioAgency;\r
230 \r
231                 sourceUri = manager.createStoreUri(RemoteStoreProtocol.FTP, NEXIO_HOST);\r
232                 sourceUri.setPortNumber(nexioPort);\r
233                 sourceUri.setUserName(nexioUserName);\r
234                 sourceUri.setPassword(nexioPassword);\r
235                 if (sourceUri == null) {\r
236                         logger.error(systemMarker, "A forrás nem elérhető.");\r
237                         throw new NullPointerException("Internal error, missing 'sourceUri'.");\r
238                 }\r
239 \r
240                 targetUri = manager.createStoreUri(new URI(archiveFtp));\r
241                 targetUri.setUserName(archiveUserName);\r
242                 targetUri.setPassword(archivePassword);\r
243                 if (targetUri == null) {\r
244                         logger.error(systemMarker, "A cél nem elérhető.");\r
245                         throw new NullPointerException("Internal error, missing 'targetUri'.");\r
246                 }\r
247 \r
248         }\r
249 \r
250         private void transferFile(String sourceFileName, String targetFileName) throws Exception {\r
251                 int reply = 0;\r
252                 logger.info("Transfer clip {}", sourceFileName);\r
253                 try {\r
254                         sourceFtp = ((FtpDirectoryLister) sourceUri.getLister()).connect();\r
255                         targetFtp = ((FtpDirectoryLister) targetUri.getLister()).connect();\r
256                         if (!targetFtp.enterRemotePassiveMode())\r
257                                 throw new Exception("!PASV");\r
258 \r
259                         reply = sourceFtp.port(InetAddress.getByName(targetFtp.getPassiveHost()), targetFtp.getPassivePort());\r
260                         if (!FTPReply.isPositiveCompletion(reply))\r
261                                 throw new Exception("PORT parancs válasza: " + sourceFtp.getReplyString());\r
262 \r
263                         if (!sourceFtp.setFileType(FTP.BINARY_FILE_TYPE))\r
264                                 throw new Exception("!SOURCE TYPE");\r
265 \r
266                         reply = sourceFtp.retr(sourceFileName);\r
267                         if (!FTPReply.isPositivePreliminary(reply))\r
268                                 throw new Exception("RETR parancs válasza: " + sourceFtp.getReplyString());\r
269 \r
270                         if (!targetFtp.setFileType(FTP.BINARY_FILE_TYPE))\r
271                                 throw new Exception("!TARGET TYPE");\r
272 \r
273                         reply = targetFtp.stor(targetFileName);\r
274                         if (!FTPReply.isPositivePreliminary(reply))\r
275                                 throw new Exception("STOR parancs válasza: " + sourceFtp.getReplyString());\r
276 \r
277                         while (true) {\r
278                                 reply = sourceFtp.stat();\r
279                                 if (!FTPReply.isPositiveCompletion(reply))\r
280                                         throw new Exception("STAT parancs válasza: " + sourceFtp.getReplyString());\r
281 \r
282                                 logger.info("Status: {}", sourceFtp.getReplyString());\r
283                                 if (reply == 226) {\r
284                                         break;\r
285                                 }\r
286                                 Thread.sleep(1000);\r
287                         }\r
288                 } catch (Exception e) {\r
289                         logger.catching(e);\r
290                         throw e;\r
291                 } finally {\r
292                         sourceUri.cleanUp();\r
293                         targetUri.cleanUp();\r
294                 }\r
295 \r
296         }\r
297 \r
298         private void transferMetadata(String fileName, BasicDBObject metadata) throws Exception {\r
299                 logger.info("Transfer metadata {}", fileName);\r
300                 OutputStream outStream = null;\r
301                 try {\r
302                         targetFtp = ((FtpDirectoryLister) targetUri.getLister()).connect();\r
303                         if (!targetFtp.changeWorkingDirectory(EscortFiles.STATUSFOLDER)) {\r
304                                 targetFtp.makeDirectory(EscortFiles.STATUSFOLDER);\r
305                                 if (!targetFtp.changeWorkingDirectory(EscortFiles.STATUSFOLDER))\r
306                                         throw new Exception("!STATUSFOLDER");\r
307                         }\r
308 \r
309                         outStream = targetFtp.storeFileStream(fileName + JSON_EXT);\r
310                         if (outStream == null) {\r
311                                 throw new NullPointerException("Can not open: " + fileName + JSON_EXT + " Reply:" + targetFtp.getReplyString());\r
312                         }\r
313                         outStream.write(metadata.toString().getBytes(UTF_8));\r
314                         outStream.flush();\r
315                         //targetFtp.changeToParentDirectory();\r
316                 } catch (Exception e) {\r
317                         logger.catching(e);\r
318                         throw e;\r
319                 } finally {\r
320                         if (outStream != null)\r
321                                 outStream.close();\r
322                         targetUri.cleanUp();\r
323                 }\r
324         }\r
325 \r
326 }\r