def setUp(self):
     self.api_key = u("123456")
     self.api_secret = u("1234567890abcdef1234567890abcdef1234567890")
     self.session_id = u(
         "1_MX4xMjM0NTZ-flNhdCBNYXIgMTUgMTQ6NDI6MjMgUERUIDIwMTR-MC40OTAxMzAyNX4"
     )
     self.opentok = Client(self.api_key, self.api_secret)
Exemplo n.º 2
0
 def setUp(self):
     self.api_key = u("123456")
     self.api_secret = u("1234567890abcdef1234567890abcdef1234567890")
     self.opentok = Client(self.api_key, self.api_secret)
     self.session_id = u("2_MX4xMDBfjE0Mzc2NzY1NDgwMTJ-TjMzfn4")
Exemplo n.º 3
0
class OpenTokBroadcastTest(unittest.TestCase):
    def setUp(self):
        self.api_key = u("123456")
        self.api_secret = u("1234567890abcdef1234567890abcdef1234567890")
        self.opentok = Client(self.api_key, self.api_secret)
        self.session_id = u("2_MX4xMDBfjE0Mzc2NzY1NDgwMTJ-TjMzfn4")

    @httpretty.activate
    def test_start_broadcast(self):
        """
        Test start_broadcast() method
        """
        httpretty.register_uri(
            httpretty.POST,
            u("https://api.opentok.com/v2/project/{0}/broadcast").format(
                self.api_key),
            body=textwrap.dedent(
                u("""\
                        {
                            "id": "1748b7070a81464c9759c46ad10d3734",
                            "sessionId": "2_MX4xMDBfjE0Mzc2NzY1NDgwMTJ-TjMzfn4",
                            "projectId": 100,
                            "createdAt": 1437676551000,
                            "updatedAt": 1437676551000,
                            "resolution": "640x480",
                            "status": "started",
                            "broadcastUrls": {
                                "hls" : "http://server/fakepath/playlist.m3u8",
                                "rtmp": {
                                    "foo": {
                                        "serverUrl": "rtmp://myfooserver/myfooapp",
                                        "streamName": "myfoostream"
                                    },
                                    "bar": {
                                        "serverUrl": "rtmp://mybarserver/mybarapp",
                                        "streamName": "mybarstream"
                                    }
                                }
                            }
                        }
                    """)),
            status=200,
            content_type=u("application/json"),
        )

        options = {
            "layout": {
                "type":
                "custom",
                "stylesheet":
                "the layout stylesheet (only used with type == custom)",
            },
            "maxDuration": 5400,
            "outputs": {
                "hls": {},
                "rtmp": [
                    {
                        "id": "foo",
                        "serverUrl": "rtmp://myfooserver/myfooapp",
                        "streamName": "myfoostream",
                    },
                    {
                        "id": "bar",
                        "serverUrl": "rtmp://mybarserver/mybarapp",
                        "streamName": "mybarstream",
                    },
                ],
            },
            "resolution": "640x480",
        }

        broadcast = self.opentok.start_broadcast(self.session_id, options)
        validate_jwt_header(
            self,
            httpretty.last_request().headers[u("x-opentok-auth")])
        expect(httpretty.last_request().headers[u("user-agent")]).to(
            contain(u("OpenTok-Python-SDK/") + __version__))
        expect(httpretty.last_request().headers[u("content-type")]).to(
            equal(u("application/json")))
        # non-deterministic json encoding. have to decode to test it properly
        if PY2:
            body = json.loads(httpretty.last_request().body)
        if PY3:
            body = json.loads(httpretty.last_request().body.decode("utf-8"))

        expect(body).to(have_key(u("layout")))
        expect(broadcast).to(be_an(Broadcast))
        expect(broadcast).to(
            have_property(u("id"), u("1748b7070a81464c9759c46ad10d3734")))
        expect(broadcast).to(
            have_property(u("sessionId"),
                          u("2_MX4xMDBfjE0Mzc2NzY1NDgwMTJ-TjMzfn4")))
        expect(broadcast).to(have_property(u("projectId"), 100))
        expect(broadcast).to(have_property(u("createdAt"), 1437676551000))
        expect(broadcast).to(have_property(u("updatedAt"), 1437676551000))
        expect(broadcast).to(have_property(u("resolution"), u("640x480")))
        expect(broadcast).to(have_property(u("status"), u("started")))
        expect(list(broadcast.broadcastUrls)).to(have_length(2))
        expect(list(broadcast.broadcastUrls["rtmp"])).to(have_length(2))

    @httpretty.activate
    def test_start_broadcast_only_one_rtmp(self):
        """
        Test start_broadcast() method with only one rtmp
        """
        httpretty.register_uri(
            httpretty.POST,
            u("https://api.opentok.com/v2/project/{0}/broadcast").format(
                self.api_key),
            body=textwrap.dedent(
                u("""\
                        {
                            "id": "1748b7070a81464c9759c46ad10d3734",
                            "sessionId": "2_MX4xMDBfjE0Mzc2NzY1NDgwMTJ-TjMzfn4",
                            "projectId": 100,
                            "createdAt": 1437676551000,
                            "updatedAt": 1437676551000,
                            "resolution": "640x480",
                            "status": "started",
                            "broadcastUrls": {
                                "hls" : "http://server/fakepath/playlist.m3u8",
                                "rtmp": {
                                    "foo": {
                                        "serverUrl": "rtmp://myfooserver/myfooapp",
                                        "streamName": "myfoostream"
                                    },
                                    "bar": {
                                        "serverUrl": "rtmp://mybarserver/mybarapp",
                                        "streamName": "mybarstream"
                                    }
                                }
                            }
                        }
                    """)),
            status=200,
            content_type=u("application/json"),
        )

        options = {
            "sessionId": "2_MX4xMDBfjE0Mzc2NzY1NDgwMTJ",
            "layout": {
                "type":
                "custom",
                "stylesheet":
                "the layout stylesheet (only used with type == custom)",
            },
            "maxDuration": 5400,
            "outputs": {
                "rtmp": {
                    "id": "my-id",
                    "serverUrl": "rtmp://myserver/myapp",
                    "streamName": "my-stream-name",
                }
            },
            "resolution": "640x480",
        }

        broadcast = self.opentok.start_broadcast(self.session_id, options)
        validate_jwt_header(
            self,
            httpretty.last_request().headers[u("x-opentok-auth")])
        expect(httpretty.last_request().headers[u("user-agent")]).to(
            contain(u("OpenTok-Python-SDK/") + __version__))
        expect(httpretty.last_request().headers[u("content-type")]).to(
            equal(u("application/json")))
        expect(broadcast).to(be_an(Broadcast))
        expect(broadcast).to(
            have_property(u("id"), u("1748b7070a81464c9759c46ad10d3734")))
        expect(broadcast).to(
            have_property(u("sessionId"),
                          u("2_MX4xMDBfjE0Mzc2NzY1NDgwMTJ-TjMzfn4")))
        expect(broadcast).to(have_property(u("projectId"), 100))
        expect(broadcast).to(have_property(u("createdAt"), 1437676551000))
        expect(broadcast).to(have_property(u("updatedAt"), 1437676551000))
        expect(broadcast).to(have_property(u("resolution"), u("640x480")))
        expect(broadcast).to(have_property(u("status"), u("started")))
        expect(list(broadcast.broadcastUrls)).to(have_length(2))
        expect(list(broadcast.broadcastUrls["rtmp"])).to(have_length(2))

    @httpretty.activate
    def test_start_broadcast_with_screenshare_type(self):
        """
        Test start_broadcast() method
        """
        httpretty.register_uri(
            httpretty.POST,
            u("https://api.opentok.com/v2/project/{0}/broadcast").format(
                self.api_key),
            body=textwrap.dedent(
                u("""\
                        {
                            "id": "1748b7070a81464c9759c46ad10d3734",
                            "sessionId": "2_MX4xMDBfjE0Mzc2NzY1NDgwMTJ-TjMzfn4",
                            "projectId": 100,
                            "createdAt": 1437676551000,
                            "updatedAt": 1437676551000,
                            "resolution": "640x480",
                            "status": "started",
                            "broadcastUrls": {
                                "hls" : "http://server/fakepath/playlist.m3u8",
                                "rtmp": {
                                    "foo": {
                                        "serverUrl": "rtmp://myfooserver/myfooapp",
                                        "streamName": "myfoostream"
                                    },
                                    "bar": {
                                        "serverUrl": "rtmp://mybarserver/mybarapp",
                                        "streamName": "mybarstream"
                                    }
                                }
                            }
                        }
                    """)),
            status=200,
            content_type=u("application/json"),
        )

        options = {
            "layout": {
                "screenshareType": "verticalPresentation"
            },
            "maxDuration": 5400,
            "outputs": {
                "hls": {},
                "rtmp": [
                    {
                        "id": "foo",
                        "serverUrl": "rtmp://myfooserver/myfooapp",
                        "streamName": "myfoostream",
                    },
                    {
                        "id": "bar",
                        "serverUrl": "rtmp://mybarserver/mybarapp",
                        "streamName": "mybarstream",
                    },
                ],
            },
            "resolution": "640x480",
        }

        broadcast = self.opentok.start_broadcast(self.session_id, options)
        validate_jwt_header(
            self,
            httpretty.last_request().headers[u("x-opentok-auth")])
        expect(httpretty.last_request().headers[u("user-agent")]).to(
            contain(u("OpenTok-Python-SDK/") + __version__))
        expect(httpretty.last_request().headers[u("content-type")]).to(
            equal(u("application/json")))
        # non-deterministic json encoding. have to decode to test it properly
        if PY2:
            body = json.loads(httpretty.last_request().body)
        if PY3:
            body = json.loads(httpretty.last_request().body.decode("utf-8"))

        expect(body).to(have_key("sessionId", self.session_id))
        expect(body).to(have_key("layout"))
        expect(body["layout"]).to(have_key("screenshareType"))
        expect(body["layout"]["screenshareType"]).to(
            equal("verticalPresentation"))
        expect(broadcast).to(be_an(Broadcast))
        expect(broadcast).to(
            have_property(u("id"), u("1748b7070a81464c9759c46ad10d3734")))
        expect(broadcast).to(
            have_property(u("sessionId"),
                          u("2_MX4xMDBfjE0Mzc2NzY1NDgwMTJ-TjMzfn4")))
        expect(broadcast).to(have_property(u("projectId"), 100))
        expect(broadcast).to(have_property(u("createdAt"), 1437676551000))
        expect(broadcast).to(have_property(u("updatedAt"), 1437676551000))
        expect(broadcast).to(have_property(u("resolution"), u("640x480")))
        expect(broadcast).to(have_property(u("status"), u("started")))
        expect(list(broadcast.broadcastUrls)).to(have_length(2))
        expect(list(broadcast.broadcastUrls["rtmp"])).to(have_length(2))

    @httpretty.activate
    def test_stop_broadcast(self):
        """
        Test stop_broadcast() method
        """
        broadcast_id = u("1748b7070a81464c9759c46ad10d3734")

        httpretty.register_uri(
            httpretty.POST,
            u("https://api.opentok.com/v2/project/{0}/broadcast/{1}/stop").
            format(self.api_key, broadcast_id),
            body=textwrap.dedent(
                u("""\
                        {
                            "id": "1748b7070a81464c9759c46ad10d3734",
                            "sessionId": "2_MX4xMDBfjE0Mzc2NzY1NDgwMTJ-TjMzfn4",
                            "projectId": 100,
                            "createdAt": 1437676551000,
                            "updatedAt": 1437676551000,
                            "resolution": "640x480",
                            "broadcastUrls": null
                        }
                    """)),
            status=200,
            content_type=u("application/json"),
        )

        broadcast = self.opentok.stop_broadcast(broadcast_id)
        validate_jwt_header(
            self,
            httpretty.last_request().headers[u("x-opentok-auth")])
        expect(httpretty.last_request().headers[u("user-agent")]).to(
            contain(u("OpenTok-Python-SDK/") + __version__))
        expect(httpretty.last_request().headers[u("content-type")]).to(
            equal(u("application/json")))
        expect(broadcast).to(be_an(Broadcast))
        expect(broadcast).to(
            have_property(u("id"), u("1748b7070a81464c9759c46ad10d3734")))
        expect(broadcast).to(
            have_property(u("sessionId"),
                          u("2_MX4xMDBfjE0Mzc2NzY1NDgwMTJ-TjMzfn4")))
        expect(broadcast).to(have_property(u("projectId"), 100))
        expect(broadcast).to(have_property(u("createdAt"), 1437676551000))
        expect(broadcast).to(have_property(u("updatedAt"), 1437676551000))
        expect(broadcast).to(have_property(u("resolution"), u("640x480")))

    @httpretty.activate
    def test_get_broadcast(self):
        """
        Test get_broadcast() method
        """
        broadcast_id = u("1748b707-0a81-464c-9759-c46ad10d3734")

        httpretty.register_uri(
            httpretty.GET,
            u("https://api.opentok.com/v2/project/{0}/broadcast/{1}").format(
                self.api_key, broadcast_id),
            body=textwrap.dedent(
                u("""\
                        {
                            "id": "1748b707-0a81-464c-9759-c46ad10d3734",
                            "sessionId": "2_MX4xMDBfjE0Mzc2NzY1NDgwMTJ-TjMzfn4",
                            "projectId": 100,
                            "createdAt": 1437676551000,
                            "updatedAt": 1437676551000,
                            "resolution": "640x480",
                            "broadcastUrls": {
                                "hls" : "http://server/fakepath/playlist.m3u8",
                                "rtmp": {
                                    "foo": {
                                        "serverUrl": "rtmp://myfooserver/myfooapp",
                                        "streamName": "myfoostream",
                                        "status": "live"
                                    },
                                    "bar": {
                                        "serverUrl": "rtmp://mybarserver/mybarapp",
                                        "streamName": "mybarstream",
                                        "status": "live"
                                    }
                                }
                            },
                            "status": "started"
                        }
                    """)),
            status=200,
            content_type=u("application/json"),
        )

        broadcast = self.opentok.get_broadcast(broadcast_id)
        validate_jwt_header(
            self,
            httpretty.last_request().headers[u("x-opentok-auth")])
        expect(httpretty.last_request().headers[u("user-agent")]).to(
            contain(u("OpenTok-Python-SDK/") + __version__))
        expect(httpretty.last_request().headers[u("content-type")]).to(
            equal(u("application/json")))
        expect(broadcast).to(be_an(Broadcast))
        expect(broadcast).to(have_property(u("id"), broadcast_id))
        expect(broadcast).to(
            have_property(u("sessionId"),
                          u("2_MX4xMDBfjE0Mzc2NzY1NDgwMTJ-TjMzfn4")))
        expect(broadcast).to(have_property(u("projectId"), 100))
        expect(broadcast).to(have_property(u("createdAt"), 1437676551000))
        expect(broadcast).to(have_property(u("updatedAt"), 1437676551000))
        expect(broadcast).to(have_property(u("resolution"), u("640x480")))
        expect(broadcast).to(have_property(u("status"), u("started")))
        expect(list(broadcast.broadcastUrls)).to(have_length(2))
        expect(list(broadcast.broadcastUrls["rtmp"])).to(have_length(2))

    @httpretty.activate
    def test_set_broadcast_layout(self):
        """ Test set_broadcast_layout() functionality """
        broadcast_id = u("1748b707-0a81-464c-9759-c46ad10d3734")

        httpretty.register_uri(
            httpretty.PUT,
            u("https://api.opentok.com/v2/project/{0}/broadcast/{1}/layout").
            format(self.api_key, broadcast_id),
            status=200,
            content_type=u("application/json"),
        )

        self.opentok.set_broadcast_layout(broadcast_id,
                                          "horizontalPresentation")

        validate_jwt_header(
            self,
            httpretty.last_request().headers[u("x-opentok-auth")])
        expect(httpretty.last_request().headers[u("user-agent")]).to(
            contain(u("OpenTok-Python-SDK/") + __version__))
        expect(httpretty.last_request().headers[u("content-type")]).to(
            equal(u("application/json")))

    @httpretty.activate
    def test_set_broadcast_layout_with_screenshare_type(self):
        """ Test set_broadcast_layout() functionality """
        broadcast_id = u("1748b707-0a81-464c-9759-c46ad10d3734")

        httpretty.register_uri(
            httpretty.PUT,
            u("https://api.opentok.com/v2/project/{0}/broadcast/{1}/layout").
            format(self.api_key, broadcast_id),
            status=200,
            content_type=u("application/json"),
        )

        self.opentok.set_broadcast_layout(
            broadcast_id, "bestFit", screenshare_type="horizontalPresentation")

        validate_jwt_header(
            self,
            httpretty.last_request().headers[u("x-opentok-auth")])
        expect(httpretty.last_request().headers[u("user-agent")]).to(
            contain(u("OpenTok-Python-SDK/") + __version__))
        expect(httpretty.last_request().headers[u("content-type")]).to(
            equal(u("application/json")))
        if PY2:
            body = json.loads(httpretty.last_request().body)
        if PY3:
            body = json.loads(httpretty.last_request().body.decode("utf-8"))

        expect(body).to(have_key(u("type"), u("bestFit")))
        expect(body).to_not(have_key(u("stylesheet")))
        expect(body).to(
            have_key(u("screenshareType"), u("horizontalPresentation")))

    @httpretty.activate
    def test_set_custom_broadcast_layout(self):
        """ Test set a custom broadcast layout specifying the 'stylesheet' parameter """
        broadcast_id = u("1748b707-0a81-464c-9759-c46ad10d3734")

        httpretty.register_uri(
            httpretty.PUT,
            u("https://api.opentok.com/v2/project/{0}/broadcast/{1}/layout").
            format(self.api_key, broadcast_id),
            status=200,
            content_type=u("application/json"),
        )

        self.opentok.set_broadcast_layout(
            broadcast_id,
            "custom",
            "stream.instructor {position: absolute; width: 100%;  height:50%;}",
        )

        validate_jwt_header(
            self,
            httpretty.last_request().headers[u("x-opentok-auth")])
        expect(httpretty.last_request().headers[u("user-agent")]).to(
            contain(u("OpenTok-Python-SDK/") + __version__))
        expect(httpretty.last_request().headers[u("content-type")]).to(
            equal(u("application/json")))

    @httpretty.activate
    def test_set_broadcast_layout_throws_exception(self):
        """ Test invalid request in set broadcast layout """
        broadcast_id = u("1748b707-0a81-464c-9759-c46ad10d3734")

        httpretty.register_uri(
            httpretty.PUT,
            u("https://api.opentok.com/v2/project/{0}/broadcast/{1}/layout").
            format(self.api_key, broadcast_id),
            status=400,
            content_type=u("application/json"),
        )

        self.assertRaises(
            BroadcastError,
            self.opentok.set_broadcast_layout,
            broadcast_id,
            "horizontalPresentation",
        )
Exemplo n.º 4
0
 def test_initialization_with_timeout(self):
     opentok = Client(self.api_key, self.api_secret, timeout=5)
     assert isinstance(opentok, Client)
Exemplo n.º 5
0
 def test_initialization_with_numeric_api_key(self):
     opentok = Client(123456, self.api_secret)
     assert isinstance(opentok, Client)
Exemplo n.º 6
0
 def test_initialization_with_api_url(self):
     opentok = Client(self.api_key, self.api_secret, self.api_url)
     assert isinstance(opentok, Client)
Exemplo n.º 7
0
 def test_initialization_without_required_params(self):
     opentok = Client()
Exemplo n.º 8
0
class OpenTokSignalTest(unittest.TestCase):
    def setUp(self):
        self.api_key = u("123456")
        self.api_secret = u("1234567890abcdef1234567890abcdef1234567890")
        self.opentok = Client(self.api_key, self.api_secret)
        self.session_id = u("SESSIONID")

    @httpretty.activate
    def test_signal(self):
        data = {u("type"): u("type test"), u("data"): u("test data")}

        httpretty.register_uri(
            httpretty.POST,
            u("https://api.opentok.com/v2/project/{0}/session/{1}/signal").
            format(self.api_key, self.session_id),
            body=textwrap.dedent(
                u("""\
                        {
                            "type": "type test",
                            "data": "test data"
                        }
                    """)),
            status=204,
            content_type=u("application/json"),
        )

        self.opentok.send_signal(self.session_id, data)

        validate_jwt_header(
            self,
            httpretty.last_request().headers[u("x-opentok-auth")])
        expect(httpretty.last_request().headers[u("user-agent")]).to(
            contain(u("OpenTok-Python-SDK/") + __version__))
        expect(httpretty.last_request().headers[u("content-type")]).to(
            equal(u("application/json")))
        # non-deterministic json encoding. have to decode to test it properly
        if PY2:
            body = json.loads(httpretty.last_request().body)
        if PY3:
            body = json.loads(httpretty.last_request().body.decode("utf-8"))
        expect(body).to(have_key(u("type"), u("type test")))
        expect(body).to(have_key(u("data"), u("test data")))

    @httpretty.activate
    def test_signal_with_connection_id(self):
        data = {u("type"): u("type test"), u("data"): u("test data")}

        connection_id = u("da9cb410-e29b-4c2d-ab9e-fe65bf83fcaf")

        httpretty.register_uri(
            httpretty.POST,
            u("https://api.opentok.com/v2/project/{0}/session/{1}/connection/{2}/signal"
              ).format(self.api_key, self.session_id, connection_id),
            body=textwrap.dedent(
                u("""\
                        {
                            "type": "type test",
                            "data": "test data"
                        }
                    """)),
            status=204,
            content_type=u("application/json"),
        )

        self.opentok.send_signal(self.session_id, data, connection_id)

        validate_jwt_header(
            self,
            httpretty.last_request().headers[u("x-opentok-auth")])
        expect(httpretty.last_request().headers[u("user-agent")]).to(
            contain(u("OpenTok-Python-SDK/") + __version__))
        expect(httpretty.last_request().headers[u("content-type")]).to(
            equal(u("application/json")))
        # non-deterministic json encoding. have to decode to test it properly
        if PY2:
            body = json.loads(httpretty.last_request().body)
        if PY3:
            body = json.loads(httpretty.last_request().body.decode("utf-8"))
        expect(body).to(have_key(u("type"), u("type test")))
        expect(body).to(have_key(u("data"), u("test data")))
Exemplo n.º 9
0
 def test_intialization(self):
     opentok = Client(self.api_key, self.api_secret)
     assert isinstance(opentok, Client)
     self.assertEquals(opentok.proxies, None)
Exemplo n.º 10
0
 def setUp(self):
     self.api_key = u("123456")
     self.api_secret = u("1234567890abcdef1234567890abcdef1234567890")
     self.opentok = Client(self.api_key, self.api_secret)
class OpenTokTokenGenerationTest(unittest.TestCase):
    def setUp(self):
        self.api_key = u("123456")
        self.api_secret = u("1234567890abcdef1234567890abcdef1234567890")
        self.session_id = u(
            "1_MX4xMjM0NTZ-flNhdCBNYXIgMTUgMTQ6NDI6MjMgUERUIDIwMTR-MC40OTAxMzAyNX4"
        )
        self.opentok = Client(self.api_key, self.api_secret)

    def test_generate_plain_token(self):
        token = self.opentok.generate_token(self.session_id)
        assert isinstance(token, text_type)
        assert token_decoder(token)[u("session_id")] == self.session_id
        assert token_signature_validator(token, self.api_secret)

    def test_generate_role_token(self):
        token = self.opentok.generate_token(self.session_id, Roles.moderator)
        assert isinstance(token, text_type)
        assert token_decoder(token)[u("role")] == Roles.moderator.value
        assert token_signature_validator(token, self.api_secret)
        token = self.opentok.generate_token(self.session_id,
                                            role=Roles.moderator)
        assert isinstance(token, text_type)
        assert token_decoder(token)[u("role")] == Roles.moderator.value
        assert token_signature_validator(token, self.api_secret)

    def test_generate_expires_token(self):
        # an integer is a valid argument
        expire_time = int(time.time()) + 100
        token = self.opentok.generate_token(self.session_id,
                                            expire_time=expire_time)
        assert isinstance(token, text_type)
        assert token_decoder(token)[u("expire_time")] == text_type(expire_time)
        assert token_signature_validator(token, self.api_secret)
        # anything that can be coerced into an integer is also valid
        expire_time = text_type(int(time.time()) + 100)
        token = self.opentok.generate_token(self.session_id,
                                            expire_time=expire_time)
        assert isinstance(token, text_type)
        assert token_decoder(token)[u("expire_time")] == expire_time
        assert token_signature_validator(token, self.api_secret)
        # a datetime object is also valid
        if PY2:
            expire_time = datetime.datetime.fromtimestamp(
                time.time(), pytz.UTC) + datetime.timedelta(days=1)
        if PY3:
            expire_time = datetime.datetime.fromtimestamp(
                time.time(),
                datetime.timezone.utc) + datetime.timedelta(days=1)
        token = self.opentok.generate_token(self.session_id,
                                            expire_time=expire_time)
        assert isinstance(token, text_type)
        assert token_decoder(token)[u("expire_time")] == text_type(
            calendar.timegm(expire_time.utctimetuple()))
        assert token_signature_validator(token, self.api_secret)

    def test_generate_data_token(self):
        data = u("name=Johnny")
        token = self.opentok.generate_token(self.session_id, data=data)
        assert isinstance(token, text_type)
        assert token_decoder(token)[u("connection_data")] == data
        assert token_signature_validator(token, self.api_secret)

    def test_generate_initial_layout_class_list(self):
        initial_layout_class_list = [u("focus"), u("small")]
        token = self.opentok.generate_token(
            self.session_id,
            initial_layout_class_list=initial_layout_class_list)
        assert isinstance(token, text_type)
        assert sorted(
            token_decoder(token)[u("initial_layout_class_list")].split(
                u(" "))) == sorted(initial_layout_class_list)
        assert token_signature_validator(token, self.api_secret)

    def test_generate_no_data_token(self):
        token = self.opentok.generate_token(self.session_id)
        assert isinstance(token, text_type)
        assert u("connection_data") not in token_decoder(token)
        assert token_signature_validator(token, self.api_secret)

    @raises(TypeError)
    def test_does_not_generate_token_without_params(self):
        token = self.opentok.generate_token()

    @raises(TypeError)
    def test_does_not_generate_token_without_session(self):
        token = self.opentok.generate_token(role=Roles.subscriber)

    @raises(OpenTokException)
    def test_does_not_generate_token_invalid_session(self):
        token = self.opentok.generate_token(u("NOT A REAL SESSIONID"))

    @raises(OpenTokException)
    def test_does_not_generate_token_without_api_key_match(self):
        # this session_id has the wrong api_key
        session_id = u(
            "1_MX42NTQzMjF-flNhdCBNYXIgMTUgMTQ6NDI6MjMgUERUIDIwMTR-MC40OTAxMzAyNX4"
        )
        token = self.opentok.generate_token(session_id)
Exemplo n.º 12
0
from flask import Flask, render_template, request, redirect, url_for
from opentok import Client, MediaModes, OutputModes
from email.utils import formatdate
import os, time

try:
    api_key = os.environ["API_KEY"]
    api_secret = os.environ["API_SECRET"]
except Exception:
    raise Exception(
        "You must define API_KEY and API_SECRET environment variables")

app = Flask(__name__)
opentok = Client(api_key, api_secret)
session = opentok.create_session(media_mode=MediaModes.routed)


@app.template_filter("datefmt")
def datefmt(dt):
    return formatdate(time.mktime(dt.timetuple()))


@app.route("/")
def index():
    return render_template("index.html")


@app.route("/host")
def host():
    key = api_key
    session_id = session.session_id
class OpenTokSessionCreationTest(unittest.TestCase):
    def setUp(self):
        self.api_key = u("123456")
        self.api_secret = u("1234567890abcdef1234567890abcdef1234567890")
        self.opentok = Client(self.api_key, self.api_secret)

    @httpretty.activate
    def test_create_default_session(self):
        httpretty.register_uri(
            httpretty.POST,
            u("https://api.opentok.com/session/create"),
            body=
            u('<?xml version="1.0" encoding="UTF-8" standalone="yes"?><sessions><Session><session_id>1_MX4xMjM0NTZ-fk1vbiBNYXIgMTcgMDA6NDE6MzEgUERUIDIwMTR-MC42ODM3ODk1MzQ0OTQyODA4fg</session_id><partner_id>123456</partner_id><create_dt>Mon Mar 17 00:41:31 PDT 2014</create_dt></Session></sessions>'
              ),
            status=200,
            content_type=u("text/xml"),
        )

        session = self.opentok.create_session()

        validate_jwt_header(
            self,
            httpretty.last_request().headers[u("x-opentok-auth")])
        expect(httpretty.last_request().headers[u("user-agent")]).to(
            contain(u("OpenTok-Python-SDK/") + __version__))
        body = parse_qs(httpretty.last_request().body)
        expect(body).to(have_key(b("p2p.preference"), [b("enabled")]))
        expect(body).to(have_key(b("archiveMode"), [b("manual")]))
        expect(session).to(be_a(Session))
        expect(session).to(
            have_property(
                u("session_id"),
                u("1_MX4xMjM0NTZ-fk1vbiBNYXIgMTcgMDA6NDE6MzEgUERUIDIwMTR-MC42ODM3ODk1MzQ0OTQyODA4fg"
                  ),
            ))
        expect(session).to(have_property(u("media_mode"), MediaModes.relayed))
        expect(session).to(have_property(u("location"), None))

    @httpretty.activate
    def test_create_routed_session(self):
        httpretty.register_uri(
            httpretty.POST,
            u("https://api.opentok.com/session/create"),
            body=
            u('<?xml version="1.0" encoding="UTF-8" standalone="yes"?><sessions><Session><session_id>1_MX4xMjM0NTZ-fk1vbiBNYXIgMTcgMDA6NDE6MzEgUERUIDIwMTR-MC42ODM3ODk1MzQ0OTQyODA4fg</session_id><partner_id>123456</partner_id><create_dt>Mon Mar 17 00:41:31 PDT 2014</create_dt></Session></sessions>'
              ),
            status=200,
            content_type=u("text/xml"),
        )

        session = self.opentok.create_session(media_mode=MediaModes.routed)

        validate_jwt_header(
            self,
            httpretty.last_request().headers[u("x-opentok-auth")])
        expect(httpretty.last_request().headers[u("user-agent")]).to(
            contain(u("OpenTok-Python-SDK/") + __version__))
        body = parse_qs(httpretty.last_request().body)
        expect(body).to(have_key(b("p2p.preference"), [b("disabled")]))
        expect(body).to(have_key(b("archiveMode"), [b("manual")]))
        expect(session).to(be_a(Session))
        expect(session).to(
            have_property(
                u("session_id"),
                u("1_MX4xMjM0NTZ-fk1vbiBNYXIgMTcgMDA6NDE6MzEgUERUIDIwMTR-MC42ODM3ODk1MzQ0OTQyODA4fg"
                  ),
            ))
        expect(session).to(have_property(u("media_mode"), MediaModes.routed))
        expect(session).to(have_property(u("location"), None))

    @httpretty.activate
    def test_failure_create_routed_session(self):
        # Session creation fails when server doesn't returns a XML
        httpretty.register_uri(
            httpretty.POST,
            u("https://api.opentok.com/session/create"),
            body=
            u('<html><head><meta charset="UTF-8"></head><body>Page not found</body></html>'
              ),
            status=200,
            content_type=u("text/xml"),
        )

        self.assertRaises(OpenTokException,
                          self.opentok.create_session,
                          media_mode=MediaModes.routed)

    @httpretty.activate
    def test_create_session_with_location_hint(self):
        httpretty.register_uri(
            httpretty.POST,
            u("https://api.opentok.com/session/create"),
            body=
            u('<?xml version="1.0" encoding="UTF-8" standalone="yes"?><sessions><Session><session_id>1_MX4xMjM0NTZ-fk1vbiBNYXIgMTcgMDA6NDE6MzEgUERUIDIwMTR-MC42ODM3ODk1MzQ0OTQyODA4fg</session_id><partner_id>123456</partner_id><create_dt>Mon Mar 17 00:41:31 PDT 2014</create_dt></Session></sessions>'
              ),
            status=200,
            content_type=u("text/xml"),
        )

        session = self.opentok.create_session(location="12.34.56.78")

        validate_jwt_header(
            self,
            httpretty.last_request().headers[u("x-opentok-auth")])
        expect(httpretty.last_request().headers[u("user-agent")]).to(
            contain(u("OpenTok-Python-SDK/") + __version__))
        # ordering of keys is non-deterministic, must parse the body to see if it is correct
        body = parse_qs(httpretty.last_request().body)
        expect(body).to(have_key(b("location"), [b("12.34.56.78")]))
        expect(body).to(have_key(b("p2p.preference"), [b("enabled")]))
        expect(session).to(be_a(Session))
        expect(session).to(
            have_property(
                u("session_id"),
                u("1_MX4xMjM0NTZ-fk1vbiBNYXIgMTcgMDA6NDE6MzEgUERUIDIwMTR-MC42ODM3ODk1MzQ0OTQyODA4fg"
                  ),
            ))
        expect(session).to(have_property(u("media_mode"), MediaModes.relayed))
        expect(session).to(have_property(u("location"), u("12.34.56.78")))

    @httpretty.activate
    def test_create_routed_session_with_location_hint(self):
        httpretty.register_uri(
            httpretty.POST,
            u("https://api.opentok.com/session/create"),
            body=
            u('<?xml version="1.0" encoding="UTF-8" standalone="yes"?><sessions><Session><session_id>1_MX4xMjM0NTZ-fk1vbiBNYXIgMTcgMDA6NDE6MzEgUERUIDIwMTR-MC42ODM3ODk1MzQ0OTQyODA4fg</session_id><partner_id>123456</partner_id><create_dt>Mon Mar 17 00:41:31 PDT 2014</create_dt></Session></sessions>'
              ),
            status=200,
            content_type=u("text/xml"),
        )

        session = self.opentok.create_session(location="12.34.56.78",
                                              media_mode=MediaModes.routed)

        validate_jwt_header(
            self,
            httpretty.last_request().headers[u("x-opentok-auth")])
        expect(httpretty.last_request().headers[u("user-agent")]).to(
            contain(u("OpenTok-Python-SDK/") + __version__))
        # ordering of keys is non-deterministic, must parse the body to see if it is correct
        body = parse_qs(httpretty.last_request().body)
        expect(body).to(have_key(b("location"), [b("12.34.56.78")]))
        expect(body).to(have_key(b("p2p.preference"), [b("disabled")]))
        expect(session).to(be_a(Session))
        expect(session).to(
            have_property(
                u("session_id"),
                u("1_MX4xMjM0NTZ-fk1vbiBNYXIgMTcgMDA6NDE6MzEgUERUIDIwMTR-MC42ODM3ODk1MzQ0OTQyODA4fg"
                  ),
            ))
        expect(session).to(have_property(u("media_mode"), MediaModes.routed))
        expect(session).to(have_property(u("location"), u("12.34.56.78")))

    @httpretty.activate
    def test_create_manual_archive_mode_session(self):
        httpretty.register_uri(
            httpretty.POST,
            u("https://api.opentok.com/session/create"),
            body=
            u('<?xml version="1.0" encoding="UTF-8" standalone="yes"?><sessions><Session><session_id>1_MX4xMjM0NTZ-fk1vbiBNYXIgMTcgMDA6NDE6MzEgUERUIDIwMTR-MC42ODM3ODk1MzQ0OTQyODA4fg</session_id><partner_id>123456</partner_id><create_dt>Mon Mar 17 00:41:31 PDT 2014</create_dt></Session></sessions>'
              ),
            status=200,
            content_type=u("text/xml"),
        )

        session = self.opentok.create_session(media_mode=MediaModes.routed,
                                              archive_mode=ArchiveModes.manual)

        validate_jwt_header(
            self,
            httpretty.last_request().headers[u("x-opentok-auth")])
        expect(httpretty.last_request().headers[u("user-agent")]).to(
            contain(u("OpenTok-Python-SDK/") + __version__))
        body = parse_qs(httpretty.last_request().body)
        expect(body).to(have_key(b("p2p.preference"), [b("disabled")]))
        expect(body).to(have_key(b("archiveMode"), [b("manual")]))
        expect(session).to(be_a(Session))
        expect(session).to(
            have_property(
                u("session_id"),
                u("1_MX4xMjM0NTZ-fk1vbiBNYXIgMTcgMDA6NDE6MzEgUERUIDIwMTR-MC42ODM3ODk1MzQ0OTQyODA4fg"
                  ),
            ))
        expect(session).to(have_property(u("media_mode"), MediaModes.routed))
        expect(session).to(
            have_property(u("archive_mode"), ArchiveModes.manual))

    @httpretty.activate
    def test_create_always_archive_mode_session(self):
        httpretty.register_uri(
            httpretty.POST,
            u("https://api.opentok.com/session/create"),
            body=
            u('<?xml version="1.0" encoding="UTF-8" standalone="yes"?><sessions><Session><session_id>1_MX4xMjM0NTZ-fk1vbiBNYXIgMTcgMDA6NDE6MzEgUERUIDIwMTR-MC42ODM3ODk1MzQ0OTQyODA4fg</session_id><partner_id>123456</partner_id><create_dt>Mon Mar 17 00:41:31 PDT 2014</create_dt></Session></sessions>'
              ),
            status=200,
            content_type=u("text/xml"),
        )

        session = self.opentok.create_session(media_mode=MediaModes.routed,
                                              archive_mode=ArchiveModes.always)

        validate_jwt_header(
            self,
            httpretty.last_request().headers[u("x-opentok-auth")])
        expect(httpretty.last_request().headers[u("user-agent")]).to(
            contain(u("OpenTok-Python-SDK/") + __version__))
        body = parse_qs(httpretty.last_request().body)
        expect(body).to(have_key(b("p2p.preference"), [b("disabled")]))
        expect(body).to(have_key(b("archiveMode"), [b("always")]))
        expect(session).to(be_a(Session))
        expect(session).to(
            have_property(
                u("session_id"),
                u("1_MX4xMjM0NTZ-fk1vbiBNYXIgMTcgMDA6NDE6MzEgUERUIDIwMTR-MC42ODM3ODk1MzQ0OTQyODA4fg"
                  ),
            ))
        expect(session).to(have_property(u("media_mode"), MediaModes.routed))
        expect(session).to(
            have_property(u("archive_mode"), ArchiveModes.always))

    @httpretty.activate
    def test_complains_about_always_archive_mode_and_relayed_session(self):
        httpretty.register_uri(
            httpretty.POST,
            u("https://api.opentok.com/session/create"),
            body=
            u('<?xml version="1.0" encoding="UTF-8" standalone="yes"?><sessions><Session><session_id>1_MX4xMjM0NTZ-fk1vbiBNYXIgMTcgMDA6NDE6MzEgUERUIDIwMTR-MC42ODM3ODk1MzQ0OTQyODA4fg</session_id><partner_id>123456</partner_id><create_dt>Mon Mar 17 00:41:31 PDT 2014</create_dt></Session></sessions>'
              ),
            status=200,
            content_type=u("text/xml"),
        )
        self.assertRaises(
            OpenTokException,
            self.opentok.create_session,
            media_mode=MediaModes.relayed,
            archive_mode=ArchiveModes.always,
        )
Exemplo n.º 14
0
from flask import Flask, render_template
from opentok import Client
import os

try:
    api_key = os.environ["API_KEY"]
    api_secret = os.environ["API_SECRET"]
except Exception:
    raise Exception(
        "You must define API_KEY and API_SECRET environment variables")

app = Flask(__name__)
opentok = Client(api_key, api_secret)
session = opentok.create_session()


@app.route("/")
def hello():
    key = api_key
    session_id = session.session_id
    token = opentok.generate_token(session_id)
    return render_template("index.html",
                           api_key=key,
                           session_id=session_id,
                           token=token)


if __name__ == "__main__":
    app.debug = True
    app.run()
 def setUp(self):
     self.api_key = u("123456")
     self.api_secret = u("1234567890abcdef1234567890abcdef1234567890")
     self.opentok = Client(self.api_key, self.api_secret)
     self.session_id = u("SESSIONID")
     self.connection_id = u("CONNECTIONID")
Exemplo n.º 16
0
 def test_set_proxies(self):
     opentok = Client(self.api_key, self.api_secret)
     opentok.proxies = {"https": "https://foo.bar"}
     self.assertEquals(opentok.proxies, {"https": "https://foo.bar"})
class OpenTokForceDisconnectTest(unittest.TestCase):
    """" Class that contains test for force disconnect functionality """
    def setUp(self):
        self.api_key = u("123456")
        self.api_secret = u("1234567890abcdef1234567890abcdef1234567890")
        self.opentok = Client(self.api_key, self.api_secret)
        self.session_id = u("SESSIONID")
        self.connection_id = u("CONNECTIONID")

    @httpretty.activate
    def test_force_disconnect(self):
        """ Method to test force disconnect functionality using an Client instance """

        httpretty.register_uri(
            httpretty.DELETE,
            u("https://api.opentok.com/v2/project/{0}/session/{1}/connection/{2}"
              ).format(self.api_key, self.session_id, self.connection_id),
            status=204,
            content_type=u("application/json"),
        )

        self.opentok.force_disconnect(self.session_id, self.connection_id)

        validate_jwt_header(
            self,
            httpretty.last_request().headers[u("x-opentok-auth")])
        expect(httpretty.last_request().headers[u("user-agent")]).to(
            contain(u("OpenTok-Python-SDK/") + __version__))
        expect(httpretty.last_request().headers[u("content-type")]).to(
            equal(u("application/json")))

    @httpretty.activate
    def test_throws_force_disconnect_exception(self):
        """ This method should throw a ForceDisconnectError """

        httpretty.register_uri(
            httpretty.DELETE,
            u("https://api.opentok.com/v2/project/{0}/session/{1}/connection/{2}"
              ).format(self.api_key, self.session_id, self.connection_id),
            status=400,
            content_type=u("application/json"),
        )

        self.assertRaises(
            ForceDisconnectError,
            self.opentok.force_disconnect,
            self.session_id,
            self.connection_id,
        )

    @httpretty.activate
    def test_throws_auth_exception(self):
        """ This method should throw an AuthError """

        httpretty.register_uri(
            httpretty.DELETE,
            u("https://api.opentok.com/v2/project/{0}/session/{1}/connection/{2}"
              ).format(self.api_key, self.session_id, self.connection_id),
            status=403,
            content_type=u("application/json"),
        )

        self.assertRaises(
            AuthError,
            self.opentok.force_disconnect,
            self.session_id,
            self.connection_id,
        )
 def test_timeout(self):
     opentok = Client(self.api_key, self.api_secret, timeout=1)
     opentok.create_session()