Ejemplo n.º 1
0
    def refreshManualConnections(self):
        manualConnections = self.getManualConnections()
        if not manualConnections:
            return

        util.LOG("Refreshing {0} manual connections".format(
            len(manualConnections)))

        for conn in manualConnections:
            # Default to http, as the server will need to be signed in for https to work,
            # so the client should too. We'd also have to allow hostname entry, instead of
            # IP address for the cert to validate.

            proto = "http"
            port = conn.port or "32400"
            serverAddress = "{0}://{1}:{2}".format(proto, conn.connection,
                                                   port)

            request = http.HttpRequest(serverAddress + "/identity")
            context = request.createRequestContext(
                "manual_connections",
                callback.Callable(self.onManualConnectionsResponse))
            context.serverAddress = serverAddress
            context.address = conn.connection
            context.proto = proto
            context.port = port
            context.timeout = 10000
            plexapp.APP.startRequest(request, context)
Ejemplo n.º 2
0
    def buildTranscodeMkv(self, obj):
        util.DEBUG_LOG('buildTranscodeMkv()')
        obj.streamFormat = "mkv"
        obj.streamBitrates = [0]
        obj.transcodeEndpoint = "/video/:/transcode/universal/start.mkv"

        builder = http.HttpRequest(obj.transcodeServer.buildUrl(obj.transcodeEndpoint, True))
        builder.extras = []
        # builder.addParam("protocol", "http")
        builder.addParam("copyts", "1")

        obj.subtitleUrl = None
        if True:  # if self.choice.subtitleDecision == self.choice.SUBTITLES_BURN:  # Must burn transcoded because we can't set offset
            builder.addParam("subtitles", "burn")
            captionSize = captions.CAPTIONS.getBurnedSize()
            if captionSize is not None:
                builder.addParam("subtitleSize", captionSize)

        else:
            # TODO(rob): can we safely assume the id will also be 3 (one based index).
            # If not, we will have to get tricky and select the subtitle stream after
            # video playback starts via roCaptionRenderer: GetSubtitleTracks() and
            # ChangeSubtitleTrack()

            obj.subtitleConfig = {'TrackName': "mkv/3"}

            # Allow text conversion of subtitles if we only burn image formats
            if self.item.settings.getPreference("burn_subtitles") == "image":
                builder.addParam("advancedSubtitles", "text")

            builder.addParam("subtitles", "auto")

        # Augment the server's profile for things that depend on the Roku's configuration.
        if self.item.settings.supportsSurroundSound():
            if self.choice.audioStream is not None:
                numChannels = self.choice.audioStream.channels.asInt(6)
            else:
                numChannels = 6

            for codec in ("ac3", "eac3", "dca"):
                if self.item.settings.supportsAudioStream(codec, numChannels):
                    builder.extras.append("append-transcode-target-audio-codec(type=videoProfile&context=streaming&audioCodec=" + codec + ")")
                    builder.extras.append("add-direct-play-profile(type=videoProfile&container=matroska&videoCodec=*&audioCodec=" + codec + ")")
                    if codec == "dca":
                        builder.extras.append(
                            "add-limitation(scope=videoAudioCodec&scopeName=dca&type=upperBound&name=audio.channels&value=6&isRequired=false)"
                        )

        # AAC sample rate cannot be less than 22050hz (HLS is capable).
        if self.choice.audioStream is not None and self.choice.audioStream.samplingRate.asInt(22050) < 22050:
            builder.extras.append("add-limitation(scope=videoAudioCodec&scopeName=aac&type=lowerBound&name=audio.samplingRate&value=22050&isRequired=false)")

        # HEVC and VP9 support!
        if self.item.settings.getGlobal("hevcSupport"):
            builder.extras.append("append-transcode-target-codec(type=videoProfile&context=streaming&videoCodec=hevc)")

        if self.item.settings.getGlobal("vp9Support"):
            builder.extras.append("append-transcode-target-codec(type=videoProfile&context=streaming&videoCodec=vp9)")

        return builder
Ejemplo n.º 3
0
    def buildTranscodeHls(self, obj):
        util.DEBUG_LOG('buildTranscodeHls()')
        obj.streamFormat = "hls"
        obj.streamBitrates = [0]
        obj.switchingStrategy = "no-adaptation"
        obj.transcodeEndpoint = "/video/:/transcode/universal/start.m3u8"

        builder = http.HttpRequest(
            obj.transcodeServer.buildUrl(obj.transcodeEndpoint, True))
        builder.extras = []
        builder.addParam("protocol", "hls")

        if self.choice.subtitleDecision == self.choice.SUBTITLES_SOFT_ANY:
            builder.addParam("skipSubtitles", "1")
        else:  # elif self.choice.hasBurnedInSubtitles is True:  # Must burn transcoded because we can't set offset
            captionSize = captions.CAPTIONS.getBurnedSize()
            if captionSize is not None:
                builder.addParam("subtitleSize", captionSize)

        # Augment the server's profile for things that depend on the Roku's configuration.
        if self.item.settings.supportsAudioStream("ac3", 6):
            builder.extras.append(
                "append-transcode-target-audio-codec(type=videoProfile&context=streaming&protocol=hls&audioCodec=ac3)"
            )
            builder.extras.append(
                "add-direct-play-profile(type=videoProfile&container=matroska&videoCodec=*&audioCodec=ac3)"
            )

        return builder
Ejemplo n.º 4
0
    def testReachability(self, server, allowFallback=False):
        # Check if we will allow the connection test. If this is a fallback connection,
        # then we will defer it until we "allowFallback" (test insecure connections
        # after secure tests have completed and failed). Insecure connections will be
        # tested if the policy "always" allows them, or if set to "same_network" and
        # the current connection is local and server has (publicAddressMatches=1).

        allowConnectionTest = not self.isFallback
        if not allowConnectionTest:
            insecurePolicy = plexapp.INTERFACE.getPreference("allow_insecure")
            if insecurePolicy == "always" or (insecurePolicy == "same_network"
                                              and server.sameNetwork
                                              and self.isLocal):
                allowConnectionTest = allowFallback
                server.hasFallback = not allowConnectionTest
                util.LOG('{0} for {1}'.format(
                    allowConnectionTest
                    and "Continuing with insecure connection testing"
                    or "Insecure connection testing is deferred", server))
            else:
                util.LOG(
                    "Insecure connections not allowed. Ignore insecure connection test for {0}"
                    .format(server))
                self.state = self.STATE_INSECURE
                callable = callback.Callable(server.onReachabilityResult,
                                             [self], random.randint(0, 256))
                callable.deferCall()
                return True

        if allowConnectionTest:
            if not self.isSecure and (
                    not allowFallback and server.hasSecureConnections()
                    or server.activeConnection
                    and server.activeConnection.state != self.STATE_REACHABLE
                    and server.activeConnection.isSecure):
                util.DEBUG_LOG("Invalid insecure connection test in progress")
            self.request = http.HttpRequest(self.buildUrl(server, "/"))
            context = self.request.createRequestContext(
                "reachability", callback.Callable(self.onReachabilityResponse))
            context.server = server
            context.timeout = 10000
            util.addPlexHeaders(self.request, server.getToken())
            self.hasPendingRequest = plexapp.APP.startRequest(
                self.request, context)
            return True

        return False
Ejemplo n.º 5
0
 def __init__(self):
     self.symbols = {}
     # Create dummy objects for completion
     self.symbols['coal'] = CoalRecordGpb()
     self.symbols['msgData'] = MsgDataGpb()
     self.symbols['transaction'] = TransactionSummaryGpb()
     self.symbols['request'] = http.HttpRequest("GET / HTTP/1.1\r\n\r\n")
     self.symbols['response'] = http.HttpResponse("HTTP/1.1 200 OK\r\n\r\n")
     self.symbols['uri'] = http.Uri("http://host:80/path?var=value")
     runtimeNS = __import__('runtime', globals())
     self.symbols['runtime'] = runtimeNS
     for moduleName, moduleHandle in statements.importMap.iteritems():
         if moduleHandle:
             self.symbols[moduleName] = moduleHandle
     rlcompleter.Completer.__init__(self, self.symbols)
     self.noMore = False
     self.parentState = 0
     self.matchedVars = []
Ejemplo n.º 6
0
    def buildTranscode(self, obj):
        transcodeServer = self.item.getTranscodeServer(True, "audio")
        if not transcodeServer:
            return None

        obj.streamFormat = "mp3"
        obj.isTranscoded = True
        obj.transcodeServer = transcodeServer

        builder = http.HttpRequest(transcodeServer.buildUrl("/music/:/transcode/universal/start.m3u8", True))
        builder.addParam("protocol", "http")
        builder.addParam("path", self.item.getAbsolutePath("key"))
        builder.addParam("session", self.item.getGlobal("clientIdentifier"))
        builder.addParam("directPlay", "0")
        builder.addParam("directStream", "0")

        obj.url = builder.getUrl()

        return obj
Ejemplo n.º 7
0
 def get_http_request(self, service):
   return (http.HttpRequest(service.get_request_path("departureBoard"))
     .add_param(id=self.id)
     .add_param(date=self.get_date())
     .add_param(time=self.get_time()))
Ejemplo n.º 8
0
def create_request(request):
    client_socket = tests.fakes.FakeClientSocket(request)
    req = http.HttpRequest(client_socket)
    return req
Ejemplo n.º 9
0
 def get_http_request(self, service):
   return (http.HttpRequest(service.get_request_path("location"))
     .add_param(input=self.input))
Ejemplo n.º 10
0
 def get_http_request(self, service):
   return http.HttpRequest(self.url)
Ejemplo n.º 11
0
    def resolveIndirect(self):
        if not self.isIndirect() or locks.LOCKS.isLocked("resolve_indirect"):
            return self

        part = self.parts[0]
        if part is None:
            util.DEBUG("Failed to resolve indirect media: missing valid part")
            return None

        postBody = None
        postUrl = part.postURL
        request = plexrequest.PlexRequest(
            self.getServer(), part.key, postUrl is not None and "POST"
            or "GET")

        if postUrl is not None:
            util.DEBUG(
                "Fetching content for indirect media POST URL: {0}".format(
                    postUrl))
            # Force setting the certificate to handle following https redirects
            postRequest = http.HttpRequest(postUrl, None, True)
            postResponse = postRequest.getToStringWithTimeout(30)
            if len(postResponse) > 0 and type(
                    postRequest.event) == "roUrlEvent":
                util.DEBUG(
                    "Retrieved data from postURL, posting to resolve container"
                )
                crlf = chr(13) + chr(10)
                postBody = ""
                for header in postRequest.event.getResponseHeadersArray():
                    for name in header:
                        postBody = postBody + name + ": " + header[name] + crlf
                postBody = postBody + crlf + postResponse
            else:
                util.DEBUG("Failed to resolve indirect media postUrl")
                self.Set("indirect", "-1")
                return self

            request.addParam("postURL", postUrl)

        response = request.doRequestWithTimeout(30, postBody)

        item = response.items[0]
        if item is None or item.mediaItems[0] is None:
            util.DEBUG("Failed to resolve indirect media: no media items")
            self.indirect = -1
            return self

        media = item.mediaItems[0]

        # Add indirect headers to the media item
        media.indirectHeaders = util.AttributeDict()
        for header in (item.container.httpHeaders or '').split("&"):
            arr = header.split("=")
            if len(arr) == 2:
                media.indirectHeaders[arr[0]] = arr[1]

        # Reset the fallback media id if applicable
        if self.id.asInt() < 0:
            media.id = self.id

        return media.resolveIndirect()
Ejemplo n.º 12
0
 def dispatch_client_requests(self):
     client_socket, addr = self.listener_socket.accept()
     req = http.HttpRequest(client_socket)
     resp = http.HttpResponse(client_socket)
     self.client_request_router(req, resp)
Ejemplo n.º 13
0
    def __init__(self):

        self.req = http.HttpRequest()