Ejemplo n.º 1
0
    def which_type(self, path):
        """
        Analyzes the image provided and attempts to determine whether it is a poster or banner.

        :param path: full path to the image
        :return: BANNER, POSTER if it concluded one or the other, or None if the image was neither (or didn't exist)
        """

        if not os.path.isfile(path):
            sickrage.app.log.warning("Couldn't check the type of " + str(path) + " cause it doesn't exist")
            return None

        with open(path, 'rb') as fh:
            img_metadata = extractMetadata(guessParser(StringInputStream(fh.read())))
            if not img_metadata:
                sickrage.app.log.debug(
                    "Unable to get metadata from " + str(path) + ", not using your existing image")
                return None

            img_ratio = float(img_metadata.get('width', 0)) / float(img_metadata.get('height', 0))

            # most posters are around 0.68 width/height ratio (eg. 680/1000)
            if 0.55 < img_ratio < 0.8:
                return self.POSTER

            # most banners are around 5.4 width/height ratio (eg. 758/140)
            elif 5 < img_ratio < 6:
                return self.BANNER

            # most fanart are around 1.77777 width/height ratio (eg. 1280/720 and 1920/1080)
            elif 1.7 < img_ratio < 1.8:
                return self.FANART
            else:
                sickrage.app.log.warning("Image has size ratio of " + str(img_ratio) + ", unknown type")
Ejemplo n.º 2
0
 def createInputStream(cis, source=None, **args):
     stream = cis(source=source)
     header = StringInputStream("FWS" +
                                self.stream.readBytes(3 * 8, 5))
     args.setdefault("tags", []).append(("class", SwfFile))
     return ConcatStream((header, stream),
                         source=stream.source,
                         **args)
Ejemplo n.º 3
0
def build_packet(typeid, target=None):
    """Build a new editable packet, based off the given Message type"""

    # Allow passing in payload classes
    if hasattr(typeid, 'typeid'):
        typeid = getattr(typeid, 'typeid')
    # Allow passing in names
    if isinstance(typeid, str):
        typeid = TYPE_IDS_BY_NAME.get(typeid)

    if typeid not in VALID_TYPE_IDS:
        raise ValueError("Unknown `typeid`!")

    def trim(pkt):
        fields = [f.name for f in pkt]
        assert fields[-1] == 'raw[]'
        del pkt['raw[]']
        pkt['size'].value = int(pkt.size / 8)  # bits!

    # Hachoir does not really support "building", so we instead
    # use a empty buffer, parse it, then convert that to an editable.

    buffer = bytes(1024)
    stream = StringInputStream(buffer)

    ro_packet = DeviceFrameParser(stream)

    packet = createEditor(ro_packet)
    packet['type'].value = typeid
    packet['protocol'].value = 1024

    if target:
        packet['target'].value = target

    packet['addressable'].value = 1
    packet['tagged'].value = (typeid == 2)

    trim(packet)

    if typeid in EMPTY_REQUEST_PAYLOADS_IDS:
        packet.proto = ro_packet
        return packet

    # Here's where the real fun begins!
    # We need to re-hydrate the packet, so that all the fields are known
    # This all feels quite dodgy, though...

    temp_data = serialise_packet(packet)
    new_ro_packet = parse_packet(temp_data + bytes(1024 - len(temp_data)))
    new_ro_packet.walk()

    new_packet = createEditor(new_ro_packet)
    new_packet.proto = new_ro_packet
    trim(new_packet)

    return new_packet
Ejemplo n.º 4
0
 def test_random_stream(self, tests=(1, 8)):
     a = array('L')
     parser_list = HachoirParserList()
     n = max(tests) * max(parser.getParserTags()["min_size"]
                          for parser in parser_list)
     k = 8 * a.itemsize
     for i in range((n - 1) // k + 1):
         a.append(random.getrandbits(k))
     a = StringInputStream(a.tobytes(), source="<random data>")
     for parser in parser_list:
         size = parser.getParserTags()["min_size"]
         for test in tests:
             a._size = a._current_size = size * test
             try:
                 parser(a, validate=True)
                 error("[%s] Parser didn't reject random data" %
                       parser.__name__)
             except ValidateError:
                 continue
Ejemplo n.º 5
0
 def createInputStream(cis, **args):
     tags = args.setdefault("tags", [])
     if parser_class:
         tags.append(("class", parser_class))
     if parser is not None:
         tags.append(("id", parser.PARSER_TAGS["id"]))
     if mime_type:
         tags.append(("mime", mime_type))
     if filename:
         tags.append(("filename", filename))
     return StringInputStream(decompressor(self.value), **args)
Ejemplo n.º 6
0
def parse_packet(file_or_data):
    """Parse a packet into a DeviceFrame object"""

    if isinstance(file_or_data, bytes):
        stream = StringInputStream(file_or_data)
    else:
        stream = FileInputStream(file_or_data, file_or_data)

    packet = DeviceFrameParser(stream)

    return packet
Ejemplo n.º 7
0
    def createInputStream(self):
        # FIXME: Use lazy stream creation
        data = []
        for item in self.items:
            data.append(item["rawdata"].value)
        data = "".join(data)

        tags = {"args": self.args}
        if self.parser is not None:
            tags["class"] = self.parser
        tags = iter(tags.items())
        return StringInputStream(data, "<fragment group>", tags=tags)
Ejemplo n.º 8
0
    def createInputStream(self):
        # FIXME: Use lazy stream creation
        data = []
        for item in self.items:
            data.append(item["rawdata"].value)
        data = b"".join(data)

        # FIXME: Use smarter code to send arguments
        self.args["ole2"] = self.items[0].root
        tags = {"class": self.parser, "args": self.args}
        tags = iter(tags.items())
        return StringInputStream(data, "<fragment group>", tags=tags)
Ejemplo n.º 9
0
 def createInputStream(cis, source=None, **args):
     stream = cis(source=source)
     tags = args.setdefault("tags", [])
     tags.extend(stream.tags)
     tags.append(("class", FolderParser))
     tags.append(("args", {'files': files}))
     for unused in self:
         pass
     if folder["compr_method"].value == 3:  # LZX
         self.uncompressed_data = lzx_decompress(
             self["block[0]/data"].getSubIStream(), folder["compr_level"].value)
     return StringInputStream(self.uncompressed_data, source=source, **args)