Пример #1
0
    def __add(self, mp):
        self.__list[mp.getIdentifier()] = mp

        # This makes sure the series gets properly included/removed from the manifest                                                                                                                              
        # FIXME: Probably shouldn't go here                                                                                                                                                                        
        catalogs = mp.getCatalogs("dublincore/series")
        if mp.getSeriesIdentifier() and not catalogs:
                mp.add(os.path.join(mp.getURI(), 'series.xml'), mediapackage.TYPE_CATALOG, 'dublincore/series', 'text/xml')
        elif not mp.getSeriesIdentifier() and catalogs:
            mp.remove(catalogs[0])
            # FIXME: Remove the file from disk?                                                                                                                                                                     
        # Save the mediapackage in the repo
        serializer.save_in_dir(mp, self.logger)
        #FIXME write new XML metadata, episode, series                                                                                                                                                              
        return mp
Пример #2
0
    def __add(self, mp):
        self.__list[mp.getIdentifier()] = mp

        # This makes sure the series gets properly included/removed from the manifest                                                                                                                              
        # FIXME: Probably shouldn't go here                                                                                                                                                                        
        catalogs = mp.getCatalogs("dublincore/series")
        if mp.getSeriesIdentifier() and not catalogs:
                mp.add(os.path.join(mp.getURI(), 'series.xml'), mediapackage.TYPE_CATALOG, 'dublincore/series', 'text/xml')
        elif not mp.getSeriesIdentifier() and catalogs:
            mp.remove(catalogs[0])
            # FIXME: Remove the file from disk?                                                                                                                                                                     
        # Save the mediapackage in the repo
        serializer.save_in_dir(mp, self.logger)
        #FIXME write new XML metadata, episode, series                                                                                                                                                              
        return mp
Пример #3
0
    def save_current_mp_data(self, mp, bins_info):
        # Save the current mediapackage
        serializer.save_in_dir(mp, self.logger, self.get_rectemp_path())

        try:
            info           = mp.getAsDict()
            info['tracks'] = bins_info

            filename = os.path.join(self.get_rectemp_path(), 'info.json')
            f = open(filename, 'w')
            f.write(json.dumps(info, indent=4, sort_keys=True))
            f.close()

            self.logger and self.logger.info("Temporary data saved to {}".format(filename))
        except Exception as exc:
            self.logger and self.logger.error("Problem saving temporary data: {}".format(exc))
Пример #4
0
    def __add(self, mp):
        """Adds a mediapackage in the repository.
        Then checks if the mediapackage serie identifier and serie title are consistent.
        If not, updates appropriately.
        Args:
            mp (Mediapackage): the mediapackage that is going to be added.
        Returns:
            mp (Mediapackage): the added mediapackage.
        """
        self.__list[mp.getIdentifier()] = mp

        # This makes sure the series gets properly included/removed from the manifest
        # FIXME: Probably shouldn't go here
        catalogs = mp.getCatalogs("dublincore/series")
        if mp.getSeriesIdentifier() and not catalogs:
            mp.add(os.path.join(mp.getURI(), 'series.xml'), mediapackage.TYPE_CATALOG, 'dublincore/series', 'text/xml')
        elif not mp.getSeriesIdentifier() and catalogs:
            mp.remove(catalogs[0])
            # FIXME: Remove the file from disk?
        # Save the mediapackage in the repo
        serializer.save_in_dir(mp, self.logger)
        #FIXME write new XML metadata, episode, series
        return mp
Пример #5
0
 def __add(self, mp):
     self.__list[mp.getIdentifier()] = mp
     serializer.save_in_dir(mp)
     #FIXME escribir de nuevo los XML de metadata.xml y episode.xml y series.xml
     return mp
Пример #6
0
    def recover_recording(self):
        """Tries to recover a crashed mediapackage form the manifest.xml associated.
        If any exception occurs while recovering recording, calls save_crash_recording method.
        """
        try:
            self.logger and self.logger.info(
                "Trying to recover the crashed recording")

            ca_prop = None
            info = {}
            # Read info.json
            with open(os.path.join(self.get_rectemp_path(), "info.json"),
                      'r') as handle:
                info = json.load(handle)

            # Copy the capture agent properties from the original mediapackage folder (for scheduled recordings)
            if info['uri']:
                ca_prop = os.path.join(
                    info['uri'],
                    "org.opencastproject.capture.agent.properties")
                if os.path.exists(ca_prop):
                    with open(ca_prop, 'rb') as fsrc:
                        dst = os.path.join(
                            self.get_rectemp_path(),
                            "org.opencastproject.capture.agent.properties")
                        with open(dst, 'wb') as fdst:
                            self.logger.info("Copying file {} to {}".format(
                                ca_prop, dst))
                            shutil.copyfileobj(fsrc, fdst)
                            os.fsync(fdst)

            # Create MP
            mp = deserializer.fromXML(
                os.path.join(self.get_rectemp_path(), "manifest.xml"),
                self.logger)

            # Set saved data
            mp.setFromDict(info)
            # Overwrite some data
            mp.status = 4
            mp.setTitle("Recovered - " + mp.getTitle())
            if not mp.getIdentifier():
                mp.setNewIdentifier()

            # Change the filenames
            folder = self.add_after_rec(mp,
                                        info['tracks'],
                                        mp.getDuration(),
                                        add_catalogs=True,
                                        remove_tmp_files=False)
            try:
                mp.discoverDuration()
            except Exception as exc:
                self.logger and self.logger.error(
                    "Error trying to get duration of MP {}: {}".format(
                        mp.getIdentifier(), exc))
            serializer.save_in_dir(mp, self.logger, folder)
            self.logger and self.logger.info(
                "Crashed recording added to the repository")

            # Copy the capture agent properties from the original mediapackage folder (for scheduled recordings)
            if ca_prop and os.path.exists(ca_prop):
                with open(ca_prop, 'rb') as fsrc:
                    dst = os.path.join(
                        mp.getURI(),
                        "org.opencastproject.capture.agent.properties")
                    with open(dst, 'wb') as fdst:
                        self.logger.info("Copying file {} to {}".format(
                            ca_prop, dst))
                        shutil.copyfileobj(fsrc, fdst)
                        os.fsync(fdst)

            # Check if there is some extra files and move it to the mediapackage folder
            mp_dir = mp.getURI()
            for temp_file in os.listdir(self.get_rectemp_path()):
                full_path = os.path.join(self.get_rectemp_path(), temp_file)
                if os.path.isfile(full_path) and os.path.getsize(
                        full_path) and not "screenshot.jpg" in temp_file:
                    os.rename(full_path, os.path.join(mp_dir, temp_file))

        except Exception as exc:
            self.logger and self.logger.error(
                "There was an error trying to recover a recording: {}. Saving crashed recording to a rectemp folder..."
                .format(exc))
            self.save_crash_recordings()

        return
Пример #7
0
 def __add(self, mp):
     self.__list[mp.getIdentifier()] = mp
     serializer.save_in_dir(mp, self.logger)
     #FIXME write new XML metadata, episode, series
     return mp
Пример #8
0
def fromXML(xml, logger=None):
    # FIXME: xml could be a file or a path.
    # TODO: if does not exist.
    """
    Gets information from manifest.xml by parsing it. Then tries to get information from galicaster.xml if the file exists.
    At the end calls marshalDublinCore(), a mediaPackage method in which the instance from the Mediapackage class gets the information from series.xml and episode.xml files by parsing them.
    Args:
        xml (str): absolute path of the manifest.xml file.
        logger (Logger): the object that prints all the information, warning and error messages. See galicaster/context/logger.
    Returns:
        Mediapackage: the object that represent a set of records.
    """
    mp_uri = path.dirname(path.abspath(xml))
    mp = mediapackage.Mediapackage(uri=mp_uri)
    manifest = minidom.parse(xml)
    principal = manifest.getElementsByTagName("mediapackage")
    mp.setDuration(
        principal[0].getAttribute("duration") or 0
    )  # FIXME check if empty and take out patch in listing.populatetreeview
    mp.setIdentifier(principal[0].getAttribute("id"))

    if principal[0].hasAttribute("start"):
        mp.setDate(
            datetime.strptime(principal[0].getAttribute("start"),
                              '%Y-%m-%dT%H:%M:%S'))

    without_galicaster = False

    galicaster_json = False

    try:
        with open(path.join(mp.getURI(), 'galicaster.json')) as file:
            galicaster_json = json.load(file)
    except IOError:
        if logger:
            logger.warning(
                "The Mediapackage: " + mp.identifier +
                " : has no galicaster.json file. Trying to load outdated galicaster.xml"
            )
        # Keep The XML read logic for backwards compatibility:
        try:
            galicaster = minidom.parse(path.join(mp.getURI(),
                                                 'galicaster.xml'))

            mp.status = int(_checknget(galicaster, "status"))
            for i in galicaster.getElementsByTagName("operation"):
                op = str(i.getAttribute("key"))
                status = _checknget(i, "status")
                mp.setOpStatus(op, int(status))
            for i in galicaster.getElementsByTagName("property"):
                op = str(i.getAttribute("name"))
                value = _checkget(i)
                mp.properties[op] = str(value)
        except IOError:
            if logger:
                logger.error(
                    "The Mediapackage: " + mp.identifier +
                    " : has no galicaster.xml or galicaster.json file")
            without_galicaster = True

    if galicaster_json and 'galicaster' in galicaster_json:
        galicaster_json = galicaster_json['galicaster']
        mp.status = galicaster_json['status']
        mp.operations = galicaster_json['operations']
        mp.properties = galicaster_json['properties']

    for etype, tag in list(mediapackage.MANIFEST_TAGS.items()):
        for i in manifest.getElementsByTagName(tag):
            if i.hasAttribute("id"):
                identifier = str(i.getAttribute("id"))
            else:
                identifier = None
            uri = _checknget(i, "url")
            flavor = str(i.getAttribute("type"))
            mime = _checknget(i, "mimetype")
            duration = _checknget(i, "duration")
            element_path = _getElementAbsPath(uri, mp.getURI())
            ref = str(i.getAttribute("ref"))

            tags = []
            for tag_elem in i.getElementsByTagName("tags"):
                tag_text = str(_checknget(tag_elem, "tag"))
                tags.append(tag_text)

            if i.hasAttribute("ref"):
                ref = str(i.getAttribute("ref"))
            else:
                ref = None
            if not path.exists(element_path):
                raise IOError("Not exists the element {} in the MP {}".format(
                    element_path, mp.identifier))
            mp.add(element_path, etype, flavor, mime, duration, ref,
                   identifier, tags)

            if uri == 'org.opencastproject.capture.agent.properties' and etype == mediapackage.TYPE_ATTACHMENT:
                mp.manual = False

            if etype == mediapackage.TYPE_TRACK and mp.status == mediapackage.NEW and without_galicaster:
                mp.status = mediapackage.RECORDED

    mp.marshalDublincore()

    # To rewrite the galicaster.xml file with a galicaster.json file
    if not without_galicaster and not galicaster_json:
        from galicaster.mediapackage import serializer
        serializer.save_in_dir(mp)

    return mp
Пример #9
0
 def __add(self, mp):
     self.__list[mp.getIdentifier()] = mp
     serializer.save_in_dir(mp)
     #FIXME escribir de nuevo los XML de metadata.xml y episode.xml y series.xml
     return mp
Пример #10
0
 def __add(self, mp):
     self.__list[mp.getIdentifier()] = mp
     serializer.save_in_dir(mp, self.logger)
     #FIXME write new XML metadata, episode, series
     return mp
Пример #11
0
    def recover_recording(self):
        """Tries to recover a crashed mediapackage form the manifest.xml associated.
        If any exception occurs while recovering recording, calls save_crash_recording method.
        """
        try:
            self.logger and self.logger.info("Trying to recover the crashed recording")

            ca_prop = None
            info = {}
            # Read info.json
            with open(os.path.join(self.get_rectemp_path(), "info.json"), 'r') as handle:
                info = json.load(handle)

            # Copy the capture agent properties from the original mediapackage folder (for scheduled recordings)
            if info['uri']:
                ca_prop = os.path.join(info['uri'], "org.opencastproject.capture.agent.properties")
                if os.path.exists(ca_prop):
                    with open(ca_prop, 'rb') as fsrc:
                        dst = os.path.join(self.get_rectemp_path(), "org.opencastproject.capture.agent.properties")
                        with open(dst, 'wb') as fdst:
                            self.logger.info("Copying file {} to {}".format(ca_prop, dst))
                            shutil.copyfileobj(fsrc, fdst)
                            os.fsync(fdst)

            # Create MP
            mp = deserializer.fromXML(os.path.join(self.get_rectemp_path(), "manifest.xml"), self.logger)

            # Set saved data
            mp.setFromDict(info)
            # Overwrite some data
            mp.status = 4
            mp.setTitle("Recovered - " + mp.getTitle())
            if not mp.getIdentifier():
                mp.setNewIdentifier()

            # Change the filenames
            folder = self.add_after_rec(mp, info['tracks'], mp.getDuration(), add_catalogs=True, remove_tmp_files=False)
            try:
                mp.discoverDuration()
            except Exception as exc:
                self.logger and self.logger.error("Error trying to get duration of MP {}: {}".format(mp.getIdentifier(), exc))
            serializer.save_in_dir(mp, self.logger, folder)
            self.logger and self.logger.info("Crashed recording added to the repository")

            # Copy the capture agent properties from the original mediapackage folder (for scheduled recordings)
            if ca_prop and os.path.exists(ca_prop):
                with open(ca_prop, 'rb') as fsrc:
                    dst = os.path.join(mp.getURI(), "org.opencastproject.capture.agent.properties")
                    with open(dst, 'wb') as fdst:
                        self.logger.info("Copying file {} to {}".format(ca_prop, dst))
                        shutil.copyfileobj(fsrc, fdst)
                        os.fsync(fdst)


            # Check if there is some extra files and move it to the mediapackage folder
            mp_dir = mp.getURI()
            for temp_file in os.listdir(self.get_rectemp_path()):
                full_path = os.path.join(self.get_rectemp_path(), temp_file)
                if os.path.isfile(full_path) and os.path.getsize(full_path) and not "screenshot.jpg" in temp_file:
                    os.rename(full_path, os.path.join(mp_dir, temp_file))


        except Exception as exc:
            self.logger and self.logger.error("There was an error trying to recover a recording: {}. Saving crashed recording to a rectemp folder...".format(exc))
            self.save_crash_recordings()

        return