示例#1
0
 def __init__(self):
     config = ConfigParser()
     config.read('config.ini')
     opentok_api_key = config.get('tokens', 'opentok_api_key')
     opentok_api_secret = config.get('tokens', 'opentok_api_secret')
     self.opentok = OpenTok(opentok_api_key, opentok_api_secret)
     self.session = None
示例#2
0
    def post(self):
        caller = self.request.get('caller')
        callee = self.request.get('callee')

        registrations = Registration.query(
            Registration.uid == callee).order(-Registration.date).fetch(5)

        opentok = OpenTok(api_key, secret)
        session = opentok.create_session()
        token = session.generate_token()

        call = {
            'caller': caller,
            'callee': callee,
            'apiKey': api_key,
            'sessionId': session.session_id,
            'token': token
        }
        if not registrations:
            self.abort(404)
            return

        logging.info(str(registrations))
        for registration in registrations:
            self.signal(registration.session_id, call)

        self.response.write(json.dumps(call))
示例#3
0
def create():
    if request.method == 'POST':
        content = request.get_json(silent=True)
        fullName = cgi.escape(content['username'])
        className = cgi.escape(content['classname'])

        hashids = Hashids(salt=settings.HASHID_SALT,min_length=6)
        increment()
        count = get_count()
        hashid = hashids.encode(count)

        courseId = DEFAULT_COURSE_PREFIX + hashid
        userId = request.cookies.get('remote_userid') if 'remote_userid' in request.cookies else generate_user_id()
        userColor = request.cookies.get('remote_usercolor') if 'remote_usercolor' in request.cookies else generate_color()

        host = app.config.get('host')
        resp = make_response(hashid)

        # Add course to database
        key = courseId
        course = Course.get_or_insert(key, courseId=courseId, teacherName=fullName)
        course.put()

        # Add teacher to course

        # Create OpenTok session
        opentok_sdk = OpenTok(OPENTOK_API_KEY, OPENTOK_API_SECRET)
        # use tokbox server to route media streams;
        # if you want to use p2p - change media_mode to MediaModes.relayed
        opentok_session = opentok_sdk.create_session(media_mode = MediaModes.routed)
        opentok_token = opentok_sdk.generate_token(opentok_session.session_id)
        
        key = courseId + userId
        user = Student.get_or_insert(key, 
            courseId = courseId,
            studentId = userId,
            fullName = fullName,
            color = userColor,
            role = 'TEACHER',
            opentokSessionId = opentok_session.session_id,
            opentokToken = opentok_token
        )
        user.put()

        # Set user cookies (teacher role)
        auth = json.loads(request.cookies.get('remote_auth')) if 'remote_auth' in request.cookies else {}
        auth[hashid] = {
            'role': 'Instructor',
            'opentok_api_key': OPENTOK_API_KEY,
            'opentok_session_id': user.opentokSessionId,
            'opentok_token': user.opentokToken
        }
        resp.set_cookie('remote_userfullname', fullName)
        resp.set_cookie('remote_auth', json.dumps(auth))
        resp.set_cookie('remote_userid', userId)
        resp.set_cookie('remote_usercolor', userColor)
        #resp.set_cookie('remote_userinitials', userInitials)

        return resp
    return redirect('/main#/create')
示例#4
0
 def create_interview_session():
     if settings.ENVIRONMENT != "TEST":
         opentok = OpenTok(settings.OPENTOK_API_KEY,
                           settings.OPENTOK_SECRET)
         session = opentok.create_session(media_mode=MediaModes.relayed)
         return session.session_id
     return "UNKNOWN"
示例#5
0
def create_session(request):

    tbox = TokBox.objects.get(pk=1)
    opentok = OpenTok(tbox.api_key, tbox.api_secret)
    session = opentok.create_session(media_mode=MediaModes.routed)
    session_id = session.session_id
    return HttpResponse(session_id)
示例#6
0
def get_opentok_details(opentok_session_id, chat_time=0):
    optok = Opentok.objects.filter(mode='development').first()
    opentok = OpenTok(optok.api_key, optok.api_secret)
    token = opentok.generate_token(opentok_session_id)
    api_key = Opentok.get_api_key()
    session_id = opentok_session_id
    return token, api_key, session_id
示例#7
0
    def get_context_data(self, **kwargs):

        #room = "333"
        api_key = '47058394'
        api_secret = '6a0bd6f70f9be22bde0678e0ae81f8d608e5aea1'

        #print(self.request.GET.get('room',))
        context = super(OpenRoom, self).get_context_data(**kwargs)

        opentok = OpenTok(api_key, api_secret)

        if context['room'] == 3:
            session_id = Event.objects.get_sala(2)
            token = opentok.generate_token(session_id[0].token,
                                           role=Roles.publisher)
        else:
            session_id = Event.objects.get_sala(context['room'])
            token = opentok.generate_token(session_id[0].token)

        print(token)
        #context=super(OpenRoom,self).get_context_data(**kwargs)

        context['api_key'] = '47058394'
        context['session_id'] = session_id[0].token
        context['token'] = token

        return context
示例#8
0
    def post(self):
        caller = self.request.get('caller')
        callee = self.request.get('callee')

        registrations = Registration.query(Registration.uid == callee).order(-Registration.date).fetch(5)

        opentok = OpenTok(api_key, secret)
        session = opentok.create_session()
        token = session.generate_token()

        call = {
            'caller': caller,
            'callee': callee,
            'apiKey': api_key,
            'sessionId': session.session_id,
            'token': token
        }
        if not registrations:
            self.abort(404)
            return

        logging.info(str(registrations))
        for registration in registrations:
            self.signal(registration.session_id, call)

        self.response.write(json.dumps(call))
示例#9
0
 def setUp(self):
     self.api_key = u("123456")
     self.api_secret = u("1234567890abcdef1234567890abcdef1234567890")
     self.session_id = u(
         "1_MX4xMjM0NTZ-flNhdCBNYXIgMTUgMTQ6NDI6MjMgUERUIDIwMTR-MC40OTAxMzAyNX4"
     )
     self.opentok = OpenTok(self.api_key, self.api_secret)
示例#10
0
def index(request):
    key = "45351832"
    secret = "29d4d704b3a28373202c230946bfe91e3e74c4fb"
    opentok = OpenTok(key, secret)
    if request.method == "POST":
        name = request.POST.get('name', '')
        role = request.POST.get('role', '')
        if role == "": role = "Publisher"
        ses_id = request.POST.get('session', '')
        try:
            if ses_id is "":
                ses = "New Session"
                session = opentok.create_session()
                session_id = session.session_id
                token = opentok.generate_token(session_id,role=Roles.publisher)
            else:
                ses = "Existing Session"
                session_id = ses_id
                if role == "moderator":
                    token = opentok.generate_token(session_id,role=Roles.moderator)
                elif role == "subscriber":
                    token = opentok.generate_token(session_id,role=Roles.subscriber)
                else:
                    token = "Wrong Role requested for existing session id"
            data = {"user": name, "Session": ses, "role":role, "session:": {"Authentication": token, "Session ID": session_id}}
        except Exception as e:
            data = {"Exception": e.message, "Type": type(e)}
        return JsonResponse(data)
示例#11
0
def create_session(request):

    tbox = TokBox.objects.get(pk=1)
    opentok = OpenTok(tbox.api_key, tbox.api_secret)
    session = opentok.create_session(media_mode=MediaModes.routed)
    session_id = session.session_id
    return HttpResponse(session_id)
    def save(self, *args, **kwargs):

        opentok = OpenTok('46764812',
                          'c6376c5a1c8c5c7c40d97235d852d6d50698e1a3')
        session = opentok.create_session()
        self.token = session.generate_token()
        self.session = session.session_id
        super(Room, self).save(*args, **kwargs)
示例#13
0
    def setUp(self):
        self.api_key = u('123456')
        self.api_secret = u('1234567890abcdef1234567890abcdef1234567890')
        self.opentok = OpenTok(self.api_key, self.api_secret)

        self.session_id = u('SESSIONID')
        self.token = u('TOKEN')
        self.sip_uri = u('sip:[email protected];transport=tls')
示例#14
0
def gen_token(request, session_pk=None):
    # make curl to create session
    # 	requrl = request.build_absolute_uri(reverse("tbox:create_session"))
    # 	req = urllib2.Request(requrl)
    # 	res = urllib2.urlopen(req)
    # 	session_id = res.read()
    # GET has to pass the session_pk or passed from room view
    if request.method == "GET" or session_pk:
        res = {}
        if request.GET or session_pk:
            if request.GET:
                session = Session.objects.get(pk=request.GET["session_pk"])
            else:
                session = Session.objects.get(pk=session_pk)

            session_id = session.session_id
            print "token request for session and session id:"
            print session, session_id
            tbox = TokBox.objects.get(pk=1)
            opentok = OpenTok(tbox.api_key, tbox.api_secret)

            #set token parameters: role and data
            print "request by user:"******"role": None, "data": "name=" + request.user.username}

            if userprofile.function == "Mod":
                params["role"] = Roles.moderator
            elif userprofile.function == "Pub":
                params["role"] = Roles.publisher
            elif userprofile.function == "Sub":
                params["role"] = Roles.subscriber

            token = opentok.generate_token(session_id, **params)
            print token
            res["token"] = token
            res["success"] = {
                "status": True,
                "error": None,
            }
            if request.GET:
                return HttpResponse(json.dumps(res))
            else:
                return json.dumps(res)
        else:
            res["success"] = {
                "status": False,
                "error": "no GET data",
            }
            return HttpResponse(json.dumps(res))

    elif request.method == "POST":
        # need to update session table with connection count
        # need to update connection table with connection id and data
        # will be done through ajax post/tokbox js on room view
        pass
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 = OpenTok(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 OpenTok 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)
示例#16
0
文件: __init__.py 项目: Alesh/wrtc
 def __init__(self, *args, **kwargs):
     super().__init__(*args, **kwargs)
     try:
         api_key = os.environ['API_KEY']
         api_secret = os.environ['API_SECRET']
     except Exception:
         raise RuntimeError('You must define API_KEY and API_SECRET environment variables')
     self.opentok = OpenTok(api_key, api_secret)
     self.sessions = dict()
     self.users = dict()
示例#17
0
def add_ot_session(api_key, api_session):
    from opentok import OpenTok
    opentok = OpenTok(api_key, api_session)
    otsession = opentok.create_session()

    otsessiondb.insert_one({
        "_id": otsession.session_id,
        "timestamp": time.time(),
        "status": "open"
    })
    return 200
示例#18
0
def game(sid):
    opentok = OpenTok(api_key, api_secret)
    session_id = unicode(sid)
    token = opentok.generate_token(session_id)
    session = Session.query.filter_by(s_id=sid).first()
    if session.player1 == None:
        session.player1 = token
    else:
        session.player2 = token
    db.session.commit()  #db session, don't confuse with tb session
    return render_template('game.html', token=token, sid=session_id)
    def setUp(self):
        self.api_key = os.environ.get('API_KEY') or u('123456')
        self.api_secret = (os.environ.get('API_SECRET') or
            u('1234567890abcdef1234567890abcdef1234567890'))
        self.api_url = os.environ.get('API_URL')
        self.mock = not (os.environ.get('API_MOCK') == 'FALSE')

        if self.mock or self.api_url is None:
            self.opentok = OpenTok(self.api_key, self.api_secret)
        else:
            self.opentok = OpenTok(self.api_key, self.api_secret, api_url = self.api_url)
示例#20
0
 def get(self, request, *args, **kwargs):
     opentok = OpenTok('46640082',
                       '27254ec0aeb2fb70021007f55c9dfb26078b727d')
     session = opentok.create_session()
     session_id = session.session_id
     token = session.generate_token()
     return JsonResponse({
         "ar_session_id": session_id,
         "ar_token": token
     },
                         safe=False)
示例#21
0
 def get(self, request, *args, **kwargs):
     opentok = OpenTok(
         settings.API_KEY,
         settings.API_SECRET)
     session_id = kwargs.get('session_id')
     response = {
         'api_key': settings.API_KEY,
         'token': opentok.generate_token(session_id)
     }
     return JsonResponse(
         response, content_type="application/json", safe=False)
示例#22
0
def video(classId):
    if "userId" in session:
        if request.method == "POST":
            api_key = '46838544'
            api_secret = 'c727ac0672a3ae6c1490b68e4032d8e982531450'
            opentok = OpenTok(api_key, api_secret)
            session_id = classdb.find_one({"_id": ObjectId(classId)}, {"session_id": 1})["session_id"]
            Tk = opentok.generate_token(session_id)
            # Sending Video API credentials
            return jsonify({'apiKey': api_key, 'sessionId': session_id, 'token': Tk})

        return render_template('class.html')
示例#23
0
    def generate_session_id():
        opentok = OpenTok(api_key, api_secret)

        # Create a session that attempts to send streams directly between clients (falling back
        # to use the OpenTok TURN server to relay streams if the clients cannot connect):
        session = opentok.create_session()

        # Store this session ID in the database
        session_id = session.session_id

        # print("generate session:" + session_id)

        return session_id
示例#24
0
def gen_token(request, session_pk=None):
    # make curl to create session
    # 	requrl = request.build_absolute_uri(reverse("tbox:create_session"))
    # 	req = urllib2.Request(requrl)
    # 	res = urllib2.urlopen(req)
    # 	session_id = res.read()
    # GET has to pass the session_pk or passed from room view
    if request.method == "GET" or session_pk:
        res = {}
        if request.GET or session_pk:
            if request.GET:
                session = Session.objects.get(pk=request.GET["session_pk"])
            else:
                session = Session.objects.get(pk=session_pk)

            session_id = session.session_id
            print "token request for session and session id:"
            print session, session_id
            tbox = TokBox.objects.get(pk=1)
            opentok = OpenTok(tbox.api_key, tbox.api_secret)

            # set token parameters: role and data
            print "request by user:"******"role": None, "data": "name=" + request.user.username}

            if userprofile.function == "Mod":
                params["role"] = Roles.moderator
            elif userprofile.function == "Pub":
                params["role"] = Roles.publisher
            elif userprofile.function == "Sub":
                params["role"] = Roles.subscriber

            token = opentok.generate_token(session_id, **params)
            print token
            res["token"] = token
            res["success"] = {"status": True, "error": None}
            if request.GET:
                return HttpResponse(json.dumps(res))
            else:
                return json.dumps(res)
        else:
            res["success"] = {"status": False, "error": "no GET data"}
            return HttpResponse(json.dumps(res))

    elif request.method == "POST":
        # need to update session table with connection count
        # need to update connection table with connection id and data
        # will be done through ajax post/tokbox js on room view
        pass
示例#25
0
 def get(self, request, *args, **kwargs):
     opentok = OpenTok(
         settings.API_KEY,
         settings.API_SECRET)
     session = opentok.create_session(
         media_mode=MediaModes.routed,
         archive_mode=ArchiveModes.always)
     response = {
         'session_id': session.session_id,
         'api_key': settings.API_KEY,
         'token': opentok.generate_token(session.session_id)
     }
     return JsonResponse(
         response, content_type="application/json", safe=False)
示例#26
0
    def post(self, request, *args, **kwargs):

        api_key = '47058394'
        api_secret = '6a0bd6f70f9be22bde0678e0ae81f8d608e5aea1'

        opentok = OpenTok(api_key, api_secret)
        session = opentok.create_session()
        session_id = session.session_id
        token = opentok.generate_token(session_id)

        Event.objects.create_token(request.POST['id'], session_id)

        #logout(request)
        return HttpResponseRedirect(reverse('induccion_app:entry-lista'))
示例#27
0
def join():
    content = request.get_json(silent=True)
    hashid = cgi.escape(content['hashid'])
    fullName = cgi.escape(content['username'])
    userId = request.cookies.get('remote_userid') if 'remote_userid' in request.cookies else generate_user_id()
    userColor = request.cookies.get('remote_usercolor') if 'remote_usercolor' in request.cookies else generate_color()

    resp = make_response(hashid)

    # Ensure course exists
    courseId = DEFAULT_COURSE_PREFIX + hashid
    course = ndb.Key('Course', courseId).get()

    # Add user to course
    key = courseId + userId
    user = Student.get_or_insert(key, courseId=courseId, studentId=userId, fullName=fullName, color=userColor)
    userInitials = user.initials
    user.put()

    if not user.opentokSessionId:
        opentok_sdk = OpenTok(OPENTOK_API_KEY, OPENTOK_API_SECRET)
        # use tokbox server to route media streams;
        # if you want to use p2p - change media_mode to MediaModes.relayed
        opentok_session = opentok_sdk.create_session(media_mode = MediaModes.routed)
        opentok_token = opentok_sdk.generate_token(opentok_session.session_id)

        user.opentokSessionId = opentok_session.session_id
        user.opentokToken = opentok_token
        user.put()

    teacher = Student.get_teacher_by_course(courseId)

    # Set user cookies (student role)
    auth = json.loads(request.cookies.get('remote_auth')) if 'remote_auth' in request.cookies else {}
    auth[hashid] = {
        'role': 'Student',
        'opentok_api_key': OPENTOK_API_KEY,
        'opentok_session_id': user.opentokSessionId,
        'opentok_token': user.opentokToken,
        'teacher_session_id': teacher.opentokSessionId,
        'teacher_token': teacher.opentokToken
    }
    resp.set_cookie('remote_userfullname', fullName)
    resp.set_cookie('remote_auth', json.dumps(auth))
    resp.set_cookie('remote_userid', userId)
    resp.set_cookie('remote_usercolor', userColor)
    resp.set_cookie('remote_userinitials', userInitials)

    configChanged(courseId, 'config', 'users')
    return resp
示例#28
0
    def get_token_id(self, username, role=ROLE_STUDENT):
        opentok = OpenTok(api_key, api_secret)
        session_id = self.session_id

        if not session_id:
            return None

        # Generate a Token from just a session_id (fetched from a database)
        connectionMetadata = '{"role":"' + role + '", "username":"******"}'

        if role == self.ROLE_TUTOR:
            token_id = opentok.generate_token(session_id, Roles.moderator, None, connectionMetadata)
        else:
            token_id = opentok.generate_token(session_id, Roles.publisher, None, connectionMetadata)
        return token_id
示例#29
0
def index():
    sid = ''
    sessions = Session.query.all()
    for s in sessions:
        if (s.player1 == None or s.player2 == None):
            sid = s.s_id
    if sid == '':
        opentok = OpenTok(api_key, api_secret)
        session = opentok.create_session()
        sid = session.session_id
        unicodedata.normalize('NFKD', sid).encode('ascii', 'ignore')
        s = Session(s_id=sid, player1=None, player2=None)
        db.session.add(s)
        db.session.commit()
    return redirect('/game/' + sid)
示例#30
0
文件: views.py 项目: giuse88/seevcam
 def get_context_data(self, **kwargs):
     InterviewRoomViewExperiment.test = not InterviewRoomViewExperiment.test
     context = super(InterviewRoomViewExperimentEE,
                     self).get_context_data(**kwargs)
     opentok = OpenTok(settings.OPENTOK_API_KEY, settings.OPENTOK_SECRET)
     context['test'] = self.test
     context['is_interview_open'] = True
     context['api_key'] = settings.OPENTOK_API_KEY
     context[
         'session_id'] = "1_MX40NTExOTk3Mn5-MTQyMDI3NzYxMzI1NH5zek80L1owVkRadGVRMS9peUZQR2dKa0l-UH4"
     context['role'] = "interviewee"
     context['token'] = opentok.generate_token(
         session_id=context['session_id'],
         data="test=" + str(InterviewRoomViewExperiment.test),
         role=Roles.publisher)
     return context
示例#31
0
def admin_class():
    if profiledb.find_one({"_id": ObjectId(session["userId"])})["role"] == "admin":
        query = request.form
        api_key = '46838544'
        api_secret = 'c727ac0672a3ae6c1490b68e4032d8e982531450'
        opentok = OpenTok(api_key, api_secret)
        video_session = opentok.create_session()

        classdb.insert_one({
            "title": query["title"],
            "body": query["body"],
            "session_id": video_session.session_id
        })
        return redirect(url_for('profile', id=profiledb.find_one({"role": "admin"})["_id"]))



    """Only one endpoint for long polling"""
示例#32
0
 def get(self, request, *args, **kwargs):
     opentok = OpenTok(
         settings.API_KEY,
         settings.API_SECRET)
     response = opentok.get_archive(kwargs.get('archive_id'))
     millis = int(response.duration)
     seconds = (millis / 1000) % 60
     seconds = int(seconds)
     minutes = (millis / (1000 * 60)) % 60
     minutes = int(minutes)
     hours = (millis / (1000 * 60 * 60)) % 24
     response = {
         "url": response.url,
         "status": response.status,
         "api_key": settings.API_KEY,
         "length": str(hours) + " : " + str(minutes) + " : " + str(seconds)}
     return JsonResponse(
         response, content_type="application/json", safe=False)
    def setUp(self):
        self.api_key = os.environ.get('API_KEY') or u('123456')
        self.api_secret = (os.environ.get('API_SECRET') or
            u('1234567890abcdef1234567890abcdef1234567890'))
        self.api_url = os.environ.get('API_URL')
        # self.mock = not (os.environ.get('API_MOCK') == 'FALSE')

        self.opentok = OpenTok(self.api_key, self.api_secret)
        self.session_id = u('SESSIONID')
示例#34
0
class Tokbox(object):
    opentok = OpenTok(OPENTOK_API_KEY, OPENTOK_API_SECRET)

    def create_session(self, *args, **kwargs):
        return self.opentok.create_session()

    def get_token(self, session):
        return session.generate_token(
            role=Roles.moderator,
            expire_time=int(time.time()) + 10,
            data=u'name=Johnny',
            initial_layout_class_list=[u'focus'])
示例#35
0
    def get(self):
        template = JINJA_ENVIRONMENT.get_template('index.html')
        uid = self.request.get('uid')
        if uid:
            opentok = OpenTok(api_key, secret)
            session = opentok.create_session()

            registration = Registration(parent=ndb.Key('Registration', 'poc'))
            registration.uid = uid
            registration.session_id = str(session.session_id)
            registration.put()

            logging.info('Register uid: ' + uid + ' sessionId: ' + session.session_id)

            self.response.write(template.render({
                'uid': uid,
                'apiKey': api_key,
                'sessionId': session.session_id,
                'token': session.generate_token()
            }))
        else:
            self.response.write(template.render({}))
示例#36
0
def add_meeting(request):

    api_key = "47084204"  # Replace with your OpenTok API key.
    api_secret = "3e487ed7f77e32f86f561244ee1571618a485458"  # Replace with your OpenTok API secret.

    data = request.data

    opentok = OpenTok(api_key, api_secret)
    session = opentok.create_session()
    session_id = session.session_id
    token = opentok.generate_token(session_id)

    meeting = Meeting(name=data['name'],
                      session_id=session_id,
                      token=token,
                      start_date=data['start_date'],
                      end_date=data['end_date'],
                      colour=data['colour'],
                      summary=data['summary'],
                      fullday=data['fullday'])
    meeting.save()
    return Response(meeting.values())
示例#37
0
    def get(self):
        template = JINJA_ENVIRONMENT.get_template('index.html')
        uid = self.request.get('uid')
        if uid:
            opentok = OpenTok(api_key, secret)
            session = opentok.create_session()

            registration = Registration(parent=ndb.Key('Registration', 'poc'))
            registration.uid = uid
            registration.session_id = str(session.session_id)
            registration.put()

            logging.info('Register uid: ' + uid + ' sessionId: ' +
                         session.session_id)

            self.response.write(
                template.render({
                    'uid': uid,
                    'apiKey': api_key,
                    'sessionId': session.session_id,
                    'token': session.generate_token()
                }))
        else:
            self.response.write(template.render({}))
示例#38
0
class OpenTokServer:
    """ OpenTok wrapper. For now only supports a single session """
    def __init__(self):
        config = ConfigParser()
        config.read('config.ini')
        opentok_api_key = config.get('tokens', 'opentok_api_key')
        opentok_api_secret = config.get('tokens', 'opentok_api_secret')
        self.opentok = OpenTok(opentok_api_key, opentok_api_secret)
        self.session = None

    def create_session(self):
        """
        Create an OpenTok session, get session ID and (moderator) token

        Returns:
            str, Session ID or None on error
        """

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

    def get_session_id(self):
        """
        Query session ID if session is active

        Returns:    
            str, Session ID or None if no session is active
        """

        return self.session.session_id

    def generate_token(self, username):
        """
        Generate a token for session if active (username stored in metadata)

        Returns:
            str, Token or None if no active session
        """

        if self.session is not None:
            return self.session.generate_token(role=Roles.publisher,
                                               data=f"username={username}")
        else:
            return None
示例#39
0
def create_app(env):
    init_config(env)
    app = _initialize_flask_app()
    app.wsgi_app = RequestLoggerMiddleware(app.wsgi_app)
    app = _configure_logging(app)
    app.config.from_object(Ivysaur.Config)
    app = _register_blueprints(app)
    app = _register_version_and_log(app)

    db = SQLAlchemy(app, session_options={"autoflush": False})
    reg = get_registry()
    reg['DB'] = db

    mail = Mail(app)
    reg['MAIL'] = mail

    reg['TOKBOX'] = OpenTok(
        Ivysaur.Config.TOKBOX_API_KEY, Ivysaur.Config.TOKBOX_API_SECRET
    )

    from lib.models.user import User
    from lib.models.role import Role

    user_datastore = SQLAlchemyUserDatastore(db, User, Role)
    Security(app, user_datastore)

    from lib.repo.user_repo import UserRepo
    from lib.repo.device_repo import DeviceRepo
    from lib.repo.deck_repo import DeckRepo
    from lib.repo.notification_repo import NotificationRepo
    from lib.repo.ask_repo import AskRepo

    # see comment for this method
    _initialize_models()

    reg['USER_DATASTORE'] = user_datastore
    reg['USER_REPO'] = UserRepo()
    reg['DEVICE_REPO'] = DeviceRepo()
    reg['DECK_REPO'] = DeckRepo()
    reg['NOTIFICATION_REPO'] = NotificationRepo()
    reg['ASK_REPO'] = AskRepo()

    app = _initialize_managers(app)
    app.json_encoder = AppJSONEncoder
    return app
 def test_set_proxies(self):
     opentok = OpenTok(self.api_key, self.api_secret)
     opentok.proxies = {'https': 'https://foo.bar'}
     self.assertEquals(opentok.proxies, {'https': 'https://foo.bar'})
 def test_timeout(self):
     with self.assertRaises(RequestError):
         opentok = OpenTok(self.api_key, self.api_secret, timeout=5)
         opentok.create_session()
 def setUp(self):
     self.api_key = u('123456')
     self.api_secret = u('1234567890abcdef1234567890abcdef1234567890')
     self.opentok = OpenTok(self.api_key, self.api_secret)
class OpenTokSessionCreationTest(unittest.TestCase):
    def setUp(self):
        self.api_key = u('123456')
        self.api_secret = u('1234567890abcdef1234567890abcdef1234567890')
        self.opentok = OpenTok(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()

        expect(httpretty.last_request().headers[u('x-tb-partner-auth')]).to.equal(self.api_key+u(':')+self.api_secret)
        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')).being.equal([b('enabled')])
        expect(body).to.have.key(b('archiveMode')).being.equal([b('manual')])
        expect(session).to.be.a(Session)
        expect(session).to.have.property(u('session_id')).being.equal(u('1_MX4xMjM0NTZ-fk1vbiBNYXIgMTcgMDA6NDE6MzEgUERUIDIwMTR-MC42ODM3ODk1MzQ0OTQyODA4fg'))
        expect(session).to.have.property(u('media_mode')).being.equal(MediaModes.relayed)
        expect(session).to.have.property(u('location')).being.equal(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)

        expect(httpretty.last_request().headers[u('x-tb-partner-auth')]).to.equal(self.api_key+u(':')+self.api_secret)
        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')).being.equal([b('disabled')])
        expect(body).to.have.key(b('archiveMode')).being.equal([b('manual')])
        expect(session).to.be.a(Session)
        expect(session).to.have.property(u('session_id')).being.equal(u('1_MX4xMjM0NTZ-fk1vbiBNYXIgMTcgMDA6NDE6MzEgUERUIDIwMTR-MC42ODM3ODk1MzQ0OTQyODA4fg'))
        expect(session).to.have.property(u('media_mode')).being.equal(MediaModes.routed)
        expect(session).to.have.property(u('location')).being.equal(None)

    @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')

        expect(httpretty.last_request().headers[u('x-tb-partner-auth')]).to.equal(self.api_key+u(':')+self.api_secret)
        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')).being.equal([b('12.34.56.78')])
        expect(body).to.have.key(b('p2p.preference')).being.equal([b('enabled')])
        expect(session).to.be.a(Session)
        expect(session).to.have.property(u('session_id')).being.equal(u('1_MX4xMjM0NTZ-fk1vbiBNYXIgMTcgMDA6NDE6MzEgUERUIDIwMTR-MC42ODM3ODk1MzQ0OTQyODA4fg'))
        expect(session).to.have.property(u('media_mode')).being.equal(MediaModes.relayed)
        expect(session).to.have.property(u('location')).being.equal(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)

        expect(httpretty.last_request().headers[u('x-tb-partner-auth')]).to.equal(self.api_key+u(':')+self.api_secret)
        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')).being.equal([b('12.34.56.78')])
        expect(body).to.have.key(b('p2p.preference')).being.equal([b('disabled')])
        expect(session).to.be.a(Session)
        expect(session).to.have.property(u('session_id')).being.equal(u('1_MX4xMjM0NTZ-fk1vbiBNYXIgMTcgMDA6NDE6MzEgUERUIDIwMTR-MC42ODM3ODk1MzQ0OTQyODA4fg'))
        expect(session).to.have.property(u('media_mode')).being.equal(MediaModes.routed)
        expect(session).to.have.property(u('location')).being.equal(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)

        expect(httpretty.last_request().headers[u('x-tb-partner-auth')]).to.equal(self.api_key+u(':')+self.api_secret)
        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')).being.equal([b('disabled')])
        expect(body).to.have.key(b('archiveMode')).being.equal([b('manual')])
        expect(session).to.be.a(Session)
        expect(session).to.have.property(u('session_id')).being.equal(u('1_MX4xMjM0NTZ-fk1vbiBNYXIgMTcgMDA6NDE6MzEgUERUIDIwMTR-MC42ODM3ODk1MzQ0OTQyODA4fg'))
        expect(session).to.have.property(u('media_mode')).being.equal(MediaModes.routed)
        expect(session).to.have.property(u('archive_mode')).being.equal(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)

        expect(httpretty.last_request().headers[u('x-tb-partner-auth')]).to.equal(self.api_key+u(':')+self.api_secret)
        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')).being.equal([b('disabled')])
        expect(body).to.have.key(b('archiveMode')).being.equal([b('always')])
        expect(session).to.be.a(Session)
        expect(session).to.have.property(u('session_id')).being.equal(u('1_MX4xMjM0NTZ-fk1vbiBNYXIgMTcgMDA6NDE6MzEgUERUIDIwMTR-MC42ODM3ODk1MzQ0OTQyODA4fg'))
        expect(session).to.have.property(u('media_mode')).being.equal(MediaModes.routed)
        expect(session).to.have.property(u('archive_mode')).being.equal(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)
class OpenTokSessionCreationTest(unittest.TestCase):
    def setUp(self):
        self.api_key = os.environ.get('API_KEY') or u('123456')
        self.api_secret = (os.environ.get('API_SECRET') or
            u('1234567890abcdef1234567890abcdef1234567890'))
        self.api_url = os.environ.get('API_URL')
        self.mock = not (os.environ.get('API_MOCK') == 'FALSE')

        if self.mock or self.api_url is None:
            self.opentok = OpenTok(self.api_key, self.api_secret)
        else:
            self.opentok = OpenTok(self.api_key, self.api_secret, api_url = self.api_url)

    def httpretty_enable(self):
        if self.mock:
            httpretty.enable()

    def httpretty_disable(self):
        if self.mock:
            httpretty.disable()

    def test_create_default_session(self):
        self.httpretty_enable()
        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()
        if self.mock:
            expect(httpretty.last_request().headers[u('x-tb-partner-auth')]).to.equal(self.api_key+u(':')+self.api_secret)
            expect(httpretty.last_request().headers[u('user-agent')]).to.contain(u('OpenTok-Python-SDK/')+__version__)
            expect(httpretty.last_request().body).to.equal(b('p2p.preference=enabled'))

        expect(session).to.be.a(Session)
        if self.mock:
            expect(session).to.have.property(u('session_id')).being.equal(u('1_MX4xMjM0NTZ-fk1vbiBNYXIgMTcgMDA6NDE6MzEgUERUIDIwMTR-MC42ODM3ODk1MzQ0OTQyODA4fg'))
        expect(session).to.have.property(u('media_mode')).being.equal(MediaModes.relayed)
        expect(session).to.have.property(u('location')).being.equal(None)
        self.httpretty_disable()

    def test_create_routed_session(self):
        self.httpretty_enable()
        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)

        if self.mock:
            expect(httpretty.last_request().headers[u('x-tb-partner-auth')]).to.equal(self.api_key+u(':')+self.api_secret)
            expect(httpretty.last_request().headers[u('user-agent')]).to.contain(u('OpenTok-Python-SDK/')+__version__)
            expect(httpretty.last_request().body).to.equal(b('p2p.preference=disabled'))

        expect(session).to.be.a(Session)
        if self.mock:
            expect(session).to.have.property(u('session_id')).being.equal(u('1_MX4xMjM0NTZ-fk1vbiBNYXIgMTcgMDA6NDE6MzEgUERUIDIwMTR-MC42ODM3ODk1MzQ0OTQyODA4fg'))
        expect(session).to.have.property(u('media_mode')).being.equal(MediaModes.routed)
        expect(session).to.have.property(u('location')).being.equal(None)
        self.httpretty_disable()

    def test_create_session_with_location_hint(self):
        self.httpretty_enable()
        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')

        if self.mock:
            expect(httpretty.last_request().headers[u('x-tb-partner-auth')]).to.equal(self.api_key+u(':')+self.api_secret)
            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')).being.equal([b('12.34.56.78')])
            expect(body).to.have.key(b('p2p.preference')).being.equal([b('enabled')])

        expect(session).to.be.a(Session)
        if self.mock:
            expect(session).to.have.property(u('session_id')).being.equal(u('1_MX4xMjM0NTZ-fk1vbiBNYXIgMTcgMDA6NDE6MzEgUERUIDIwMTR-MC42ODM3ODk1MzQ0OTQyODA4fg'))
        expect(session).to.have.property(u('media_mode')).being.equal(MediaModes.relayed)
        expect(session).to.have.property(u('location')).being.equal(u('12.34.56.78'))
        self.httpretty_disable()

    def test_create_routed_session_with_location_hint(self):
        self.httpretty_enable()
        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)

        if self.mock:
            expect(httpretty.last_request().headers[u('x-tb-partner-auth')]).to.equal(self.api_key+u(':')+self.api_secret)
            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')).being.equal([b('12.34.56.78')])
            expect(body).to.have.key(b('p2p.preference')).being.equal([b('disabled')])

        expect(session).to.be.a(Session)
        if self.mock:
            expect(session).to.have.property(u('session_id')).being.equal(u('1_MX4xMjM0NTZ-fk1vbiBNYXIgMTcgMDA6NDE6MzEgUERUIDIwMTR-MC42ODM3ODk1MzQ0OTQyODA4fg'))
        expect(session).to.have.property(u('media_mode')).being.equal(MediaModes.routed)
        expect(session).to.have.property(u('location')).being.equal(u('12.34.56.78'))
        self.httpretty_disable()
class OpenTokSessionCreationTest(unittest.TestCase):
    def setUp(self):
        self.api_key = u("123456")
        self.api_secret = u("1234567890abcdef1234567890abcdef1234567890")
        self.opentok = OpenTok(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_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,
        )
 def setUp(self):
     self.api_key = u('123456')
     self.api_secret = u('1234567890abcdef1234567890abcdef1234567890')
     self.session_id = u('1_MX4xMjM0NTZ-flNhdCBNYXIgMTUgMTQ6NDI6MjMgUERUIDIwMTR-MC40OTAxMzAyNX4')
     self.opentok = OpenTok(self.api_key, self.api_secret)
示例#47
0
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')

monkey.patch_all()
app = Flask(__name__)
app.debug=True
app.config['SECRET_KEY']='secret!'
socketio=SocketIO(app)
thread=None

opentok = OpenTok(api_key, api_secret)
toksession = opentok.create_session()
rooms = {}

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


@app.route("/login", methods=['POST'])
def login():
    """check if user in db, add to session and redirect to profile
    if not in db, redirect to index page"""

    email = request.form.get("email")
    password = request.form.get("password")
class OpenTokBroadcastTest(unittest.TestCase):
    def setUp(self):
        self.api_key = u('123456')
        self.api_secret = u('1234567890abcdef1234567890abcdef1234567890')
        self.opentok = OpenTok(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')))
        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_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_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'
        )
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 = OpenTok(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 OpenTok 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 setUp(self):
     self.api_key = u('123456')
     self.api_secret = u('1234567890abcdef1234567890abcdef1234567890')
     self.session_id = u('SESSIONID')
     self.opentok = OpenTok(self.api_key, self.api_secret)
示例#51
0
文件: hello.py 项目: NAVEENMN/mbideo
from opentok import OpenTok
opentok = OpenTok(45391562, ad29bbb303526b268937e661ae51dfdaf88a8307)
# Create a session that attempts to send streams directly between clients (falling back
# to use the OpenTok TURN server to relay streams if the clients cannot connect):
session = opentok.create_session()

from opentok import MediaModes
# A session that uses the OpenTok Media Router:
session = opentok.create_session(media_mode=MediaModes.routed)

# A session with a location hint
session = opentok.create_session(location=u'12.34.56.78')

# An automatically archived session:
session = opentok.create_session(media_mode=MediaModes.routed, archive_mode=ArchiveModes.always)

# Store this session ID in the database
session_id = session.session_id

# Generate a Token from just a session_id (fetched from a database)
token = opentok.generate_token(session_id)
# Generate a Token by calling the method on the Session (returned from create_session)
token = session.generate_token()

from opentok import Roles
# Set some options in a token
token = session.generate_token(role=Roles.moderator,
                               expire_time=int(time.time()) + 10,
                               data=u'name=Johnny')
示例#52
0
class OpenTokArchiveTest(unittest.TestCase):

    def setUp(self):
        self.api_key = os.environ.get('API_KEY') or u('123456')
        self.api_secret = (os.environ.get('API_SECRET') or
            u('1234567890abcdef1234567890abcdef1234567890'))
        self.api_url = os.environ.get('API_URL')
        self.mock = not (os.environ.get('API_MOCK') == 'FALSE')

        if self.mock or self.api_url is None:
            self.opentok = OpenTok(self.api_key, self.api_secret)
        else:
            self.opentok = OpenTok(self.api_key, self.api_secret, api_url = self.api_url)

        self.session_id = u('SESSIONID')
        self.archive_id = u('ARCHIVEID')

    def httpretty_enable(self):
        if self.mock:
            httpretty.enable()

    def httpretty_disable(self):
        if self.mock:
            httpretty.disable()

    def test_start_archive(self):
        self.httpretty_enable()

        if self.mock:
            httpretty.register_uri(httpretty.POST, u('https://api.opentok.com/v2/partner/{0}/archive').format(self.api_key),
                                   status=404,
                                   content_type=u('application/json'))
        expect(self.opentok.start_archive).when.called_with(self.session_id).to.throw(OpenTokException)
        self.httpretty_disable()

    def test_stop_archive(self):
        self.httpretty_enable()

        if self.mock:
            httpretty.register_uri(httpretty.POST, u('https://api.opentok.com/v2/partner/{0}/archive/{1}/stop').format(self.api_key, self.archive_id),
                               status=404,
                               content_type=u('application/json'))

        expect(self.opentok.stop_archive).when.called_with(self.archive_id).to.throw(OpenTokException)
        expect(self.opentok.stop_archive).when.called_with(self.archive_id).to.throw('Archive not found')
        self.httpretty_disable()

    def test_delete_archive(self):
        self.httpretty_enable()

        if self.mock:
            httpretty.register_uri(httpretty.DELETE, u('https://api.opentok.com/v2/partner/{0}/archive/{1}').format(self.api_key, self.archive_id),
                               body=u(''),
                               status=404)

        expect(self.opentok.delete_archive).when.called_with(self.archive_id).to.throw(OpenTokException)
        expect(self.opentok.delete_archive).when.called_with(self.archive_id).to.throw('Archive not found')
        self.httpretty_disable()

    def test_get_archives(self):
        self.httpretty_enable()

        if self.mock:
            httpretty.register_uri(httpretty.GET, u('https://api.opentok.com/v2/partner/{0}/archive').format(self.api_key),
                               body=textwrap.dedent(u("""\
                                       {
                                          "count" : 6,
                                          "items" : [ {
                                            "createdAt" : 1395187930000,
                                            "duration" : 22,
                                            "id" : "ef546c5a-4fd7-4e59-ab3d-f1cfb4148d1d",
                                            "name" : "",
                                            "partnerId" : 123456,
                                            "reason" : "",
                                            "sessionId" : "SESSIONID",
                                            "size" : 2909274,
                                            "status" : "available",
                                            "url" : "http://tokbox.com.archive2.s3.amazonaws.com/123456%2Fef546c5a-4fd7-4e59-ab3d-f1cfb4148d1d%2Farchive.mp4?Expires=1395188695&AWSAccessKeyId=AKIAI6LQCPIXYVWCQV6Q&Signature=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
                                          }, {
                                            "createdAt" : 1395187910000,
                                            "duration" : 14,
                                            "id" : "5350f06f-0166-402e-bc27-09ba54948512",
                                            "name" : "",
                                            "partnerId" : 123456,
                                            "reason" : "",
                                            "sessionId" : "SESSIONID",
                                            "size" : 1952651,
                                            "status" : "available",
                                            "url" : "http://tokbox.com.archive2.s3.amazonaws.com/123456%2F5350f06f-0166-402e-bc27-09ba54948512%2Farchive.mp4?Expires=1395188695&AWSAccessKeyId=AKIAI6LQCPIXYVWCQV6Q&Signature=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
                                          }, {
                                            "createdAt" : 1395187836000,
                                            "duration" : 62,
                                            "id" : "f6e7ee58-d6cf-4a59-896b-6d56b158ec71",
                                            "name" : "",
                                            "partnerId" : 123456,
                                            "reason" : "",
                                            "sessionId" : "SESSIONID",
                                            "size" : 8347554,
                                            "status" : "available",
                                            "url" : "http://tokbox.com.archive2.s3.amazonaws.com/123456%2Ff6e7ee58-d6cf-4a59-896b-6d56b158ec71%2Farchive.mp4?Expires=1395188695&AWSAccessKeyId=AKIAI6LQCPIXYVWCQV6Q&Signature=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
                                          }, {
                                            "createdAt" : 1395183243000,
                                            "duration" : 544,
                                            "id" : "30b3ebf1-ba36-4f5b-8def-6f70d9986fe9",
                                            "name" : "",
                                            "partnerId" : 123456,
                                            "reason" : "",
                                            "sessionId" : "SESSIONID",
                                            "size" : 78499758,
                                            "status" : "available",
                                            "url" : "http://tokbox.com.archive2.s3.amazonaws.com/123456%2F30b3ebf1-ba36-4f5b-8def-6f70d9986fe9%2Farchive.mp4?Expires=1395188695&AWSAccessKeyId=AKIAI6LQCPIXYVWCQV6Q&Signature=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
                                          }, {
                                            "createdAt" : 1394396753000,
                                            "duration" : 24,
                                            "id" : "b8f64de1-e218-4091-9544-4cbf369fc238",
                                            "name" : "showtime again",
                                            "partnerId" : 123456,
                                            "reason" : "",
                                            "sessionId" : "SESSIONID",
                                            "size" : 2227849,
                                            "status" : "available",
                                            "url" : "http://tokbox.com.archive2.s3.amazonaws.com/123456%2Fb8f64de1-e218-4091-9544-4cbf369fc238%2Farchive.mp4?Expires=1395188695&AWSAccessKeyId=AKIAI6LQCPIXYVWCQV6Q&Signature=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
                                          }, {
                                            "createdAt" : 1394321113000,
                                            "duration" : 1294,
                                            "id" : "832641bf-5dbf-41a1-ad94-fea213e59a92",
                                            "name" : "showtime",
                                            "partnerId" : 123456,
                                            "reason" : "",
                                            "sessionId" : "SESSIONID",
                                            "size" : 42165242,
                                            "status" : "available",
                                            "url" : "http://tokbox.com.archive2.s3.amazonaws.com/123456%2F832641bf-5dbf-41a1-ad94-fea213e59a92%2Farchive.mp4?Expires=1395188695&AWSAccessKeyId=AKIAI6LQCPIXYVWCQV6Q&Signature=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
                                          } ]
                                        }""")),
                               status=200,
                               content_type=u('application/json'))

        archive_list = self.opentok.get_archives()
        expect(archive_list).to.be.an(ArchiveList)
        expect(archive_list).to.have.property(u('count')).to.be.greater_than(1)
        assert expect(archive_list).to_not.have.length_of(0)
        self.httpretty_disable()

    def test_get_archives_with_count(self):
        self.httpretty_enable()

        if self.mock:
            httpretty.register_uri(httpretty.GET, u('https://api.opentok.com/v2/partner/{0}/archive').format(self.api_key),
                               body=textwrap.dedent(u("""\
                                       {
                                          "count" : 2,
                                          "items" : [ {
                                            "createdAt" : 1395187930000,
                                            "duration" : 22,
                                            "id" : "ef546c5a-4fd7-4e59-ab3d-f1cfb4148d1d",
                                            "name" : "",
                                            "partnerId" : 123456,
                                            "reason" : "",
                                            "sessionId" : "SESSIONID",
                                            "size" : 2909274,
                                            "status" : "available",
                                            "url" : "http://tokbox.com.archive2.s3.amazonaws.com/123456%2Fef546c5a-4fd7-4e59-ab3d-f1cfb4148d1d%2Farchive.mp4?Expires=1395188695&AWSAccessKeyId=AKIAI6LQCPIXYVWCQV6Q&Signature=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
                                          }, {
                                            "createdAt" : 1395187910000,
                                            "duration" : 14,
                                            "id" : "5350f06f-0166-402e-bc27-09ba54948512",
                                            "name" : "",
                                            "partnerId" : 123456,
                                            "reason" : "",
                                            "sessionId" : "SESSIONID",
                                            "size" : 1952651,
                                            "status" : "available",
                                            "url" : "http://tokbox.com.archive2.s3.amazonaws.com/123456%2F5350f06f-0166-402e-bc27-09ba54948512%2Farchive.mp4?Expires=1395188695&AWSAccessKeyId=AKIAI6LQCPIXYVWCQV6Q&Signature=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
                                          } ]
                                        }""")),
                               status=200,
                               content_type=u('application/json'))

        archive_list = self.opentok.get_archives(count=2)
        expect(archive_list).to.be.an(ArchiveList)
        expect(archive_list).to.have.property(u('count')).to.be.greater_than(1)
        assert expect(archive_list).to.have.length_of(2)
        self.httpretty_disable()

    def test_find_archives_with_offset_and_count(self):
        self.httpretty_enable()

        if self.mock:
            httpretty.register_uri(httpretty.GET, u('https://api.opentok.com/v2/partner/{0}/archive').format(self.api_key),
                               body=textwrap.dedent(u("""\
                                       {
                                          "count" : 6,
                                          "items" : [ {
                                            "createdAt" : 1395187836000,
                                            "duration" : 62,
                                            "id" : "f6e7ee58-d6cf-4a59-896b-6d56b158ec71",
                                            "name" : "",
                                            "partnerId" : 123456,
                                            "reason" : "",
                                            "sessionId" : "SESSIONID",
                                            "size" : 8347554,
                                            "status" : "available",
                                            "url" : "http://tokbox.com.archive2.s3.amazonaws.com/123456%2Ff6e7ee58-d6cf-4a59-896b-6d56b158ec71%2Farchive.mp4?Expires=1395188695&AWSAccessKeyId=AKIAI6LQCPIXYVWCQV6Q&Signature=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
                                          }, {
                                            "createdAt" : 1395183243000,
                                            "duration" : 544,
                                            "id" : "30b3ebf1-ba36-4f5b-8def-6f70d9986fe9",
                                            "name" : "",
                                            "partnerId" : 123456,
                                            "reason" : "",
                                            "sessionId" : "SESSIONID",
                                            "size" : 78499758,
                                            "status" : "available",
                                            "url" : "http://tokbox.com.archive2.s3.amazonaws.com/123456%2F30b3ebf1-ba36-4f5b-8def-6f70d9986fe9%2Farchive.mp4?Expires=1395188695&AWSAccessKeyId=AKIAI6LQCPIXYVWCQV6Q&Signature=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
                                          }, {
                                            "createdAt" : 1394396753000,
                                            "duration" : 24,
                                            "id" : "b8f64de1-e218-4091-9544-4cbf369fc238",
                                            "name" : "showtime again",
                                            "partnerId" : 123456,
                                            "reason" : "",
                                            "sessionId" : "SESSIONID",
                                            "size" : 2227849,
                                            "status" : "available",
                                            "url" : "http://tokbox.com.archive2.s3.amazonaws.com/123456%2Fb8f64de1-e218-4091-9544-4cbf369fc238%2Farchive.mp4?Expires=1395188695&AWSAccessKeyId=AKIAI6LQCPIXYVWCQV6Q&Signature=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
                                          }, {
                                            "createdAt" : 1394321113000,
                                            "duration" : 1294,
                                            "id" : "832641bf-5dbf-41a1-ad94-fea213e59a92",
                                            "name" : "showtime",
                                            "partnerId" : 123456,
                                            "reason" : "",
                                            "sessionId" : "SESSIONID",
                                            "size" : 42165242,
                                            "status" : "available",
                                            "url" : "http://tokbox.com.archive2.s3.amazonaws.com/123456%2F832641bf-5dbf-41a1-ad94-fea213e59a92%2Farchive.mp4?Expires=1395188695&AWSAccessKeyId=AKIAI6LQCPIXYVWCQV6Q&Signature=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
                                          } ]
                                        }""")),
                               status=200,
                               content_type=u('application/json'))
        archive_list = self.opentok.get_archives(count=4, offset=2)
        expect(archive_list).to.be.an(ArchiveList)
        expect(archive_list).to.have.property(u('count')).to.be.greater_than(5)
        expect(list(archive_list.items)).to.have.length_of(4)
        self.httpretty_disable()
示例#53
0
class OpenTokSignalTest(unittest.TestCase):
    def setUp(self):
        self.api_key = u('123456')
        self.api_secret = u('1234567890abcdef1234567890abcdef1234567890')
        self.opentok = OpenTok(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.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.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')))
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 = OpenTok(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)
class OpenTokArchiveApiTest(unittest.TestCase):
    def setUp(self):
        self.api_key = u('123456')
        self.api_secret = u('1234567890abcdef1234567890abcdef1234567890')
        self.session_id = u('SESSIONID')
        self.opentok = OpenTok(self.api_key, self.api_secret)

    @httpretty.activate
    def test_start_archive(self):
        httpretty.register_uri(httpretty.POST, u('https://api.opentok.com/v2/partner/{0}/archive').format(self.api_key),
                               body=textwrap.dedent(u("""\
                                       {
                                          "createdAt" : 1395183243556,
                                          "duration" : 0,
                                          "id" : "30b3ebf1-ba36-4f5b-8def-6f70d9986fe9",
                                          "name" : "",
                                          "partnerId" : 123456,
                                          "reason" : "",
                                          "sessionId" : "SESSIONID",
                                          "size" : 0,
                                          "status" : "started",
                                          "hasAudio": true,
                                          "hasVideo": true,
                                          "outputMode": "composed",
                                          "url" : null
                                        }""")),
                               status=200,
                               content_type=u('application/json'))

        archive = self.opentok.start_archive(self.session_id)

        expect(httpretty.last_request().headers[u('x-tb-partner-auth')]).to.equal(self.api_key+u(':')+self.api_secret)
        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('name')).being.equal(None)
        expect(body).to.have.key(u('sessionId')).being.equal(u('SESSIONID'))
        expect(archive).to.be.an(Archive)
        expect(archive).to.have.property(u('id')).being.equal(u('30b3ebf1-ba36-4f5b-8def-6f70d9986fe9'))
        expect(archive).to.have.property(u('name')).being.equal(u(''))
        expect(archive).to.have.property(u('status')).being.equal(u('started'))
        expect(archive).to.have.property(u('session_id')).being.equal(u('SESSIONID'))
        expect(archive).to.have.property(u('partner_id')).being.equal(123456)
        if PY2:
            created_at = datetime.datetime.fromtimestamp(1395183243, pytz.UTC)
        if PY3:
            created_at = datetime.datetime.fromtimestamp(1395183243, datetime.timezone.utc)
        expect(archive).to.have.property(u('created_at')).being.equal(created_at)
        expect(archive).to.have.property(u('size')).being.equal(0)
        expect(archive).to.have.property(u('duration')).being.equal(0)
        expect(archive).to.have.property(u('has_audio')).being.equal(True)
        expect(archive).to.have.property(u('has_video')).being.equal(True)
        expect(archive).to.have.property(u('url')).being.equal(None)

    @httpretty.activate
    def test_start_archive_with_name(self):
        httpretty.register_uri(httpretty.POST, u('https://api.opentok.com/v2/partner/{0}/archive').format(self.api_key),
                               body=textwrap.dedent(u("""\
                                       {
                                          "createdAt" : 1395183243556,
                                          "duration" : 0,
                                          "id" : "30b3ebf1-ba36-4f5b-8def-6f70d9986fe9",
                                          "name" : "ARCHIVE NAME",
                                          "partnerId" : 123456,
                                          "reason" : "",
                                          "sessionId" : "SESSIONID",
                                          "size" : 0,
                                          "status" : "started",
                                          "hasAudio": true,
                                          "hasVideo": true,
                                          "outputMode": "composed",
                                          "url" : null
                                        }""")),
                               status=200,
                               content_type=u('application/json'))

        archive = self.opentok.start_archive(self.session_id, name=u('ARCHIVE NAME'))

        expect(httpretty.last_request().headers[u('x-tb-partner-auth')]).to.equal(self.api_key+u(':')+self.api_secret)
        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('sessionId')).being.equal(u('SESSIONID'))
        expect(body).to.have.key(u('name')).being.equal(u('ARCHIVE NAME'))
        expect(archive).to.be.an(Archive)
        expect(archive).to.have.property(u('id')).being.equal(u('30b3ebf1-ba36-4f5b-8def-6f70d9986fe9'))
        expect(archive).to.have.property(u('name')).being.equal(u('ARCHIVE NAME'))
        expect(archive).to.have.property(u('status')).being.equal(u('started'))
        expect(archive).to.have.property(u('session_id')).being.equal(u('SESSIONID'))
        expect(archive).to.have.property(u('partner_id')).being.equal(123456)
        if PY2:
            created_at = datetime.datetime.fromtimestamp(1395183243, pytz.UTC)
        if PY3:
            created_at = datetime.datetime.fromtimestamp(1395183243, datetime.timezone.utc)
        expect(archive).to.have.property(u('created_at')).being.equal(created_at)
        expect(archive).to.have.property(u('size')).being.equal(0)
        expect(archive).to.have.property(u('duration')).being.equal(0)
        expect(archive).to.have.property(u('url')).being.equal(None)

    @httpretty.activate
    def test_start_voice_archive(self):
        httpretty.register_uri(httpretty.POST, u('https://api.opentok.com/v2/partner/{0}/archive').format(self.api_key),
                               body=textwrap.dedent(u("""\
                                       {
                                          "createdAt" : 1395183243556,
                                          "duration" : 0,
                                          "id" : "30b3ebf1-ba36-4f5b-8def-6f70d9986fe9",
                                          "name" : "ARCHIVE NAME",
                                          "partnerId" : 123456,
                                          "reason" : "",
                                          "sessionId" : "SESSIONID",
                                          "size" : 0,
                                          "status" : "started",
                                          "hasAudio": true,
                                          "hasVideo": false,
                                          "outputMode": "composed",
                                          "url" : null
                                        }""")),
                               status=200,
                               content_type=u('application/json'))

        archive = self.opentok.start_archive(self.session_id, name=u('ARCHIVE NAME'), has_video=False)

        expect(httpretty.last_request().headers[u('x-tb-partner-auth')]).to.equal(self.api_key+u(':')+self.api_secret)
        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('sessionId')).being.equal(u('SESSIONID'))
        expect(body).to.have.key(u('name')).being.equal(u('ARCHIVE NAME'))
        expect(archive).to.be.an(Archive)
        expect(archive).to.have.property(u('id')).being.equal(u('30b3ebf1-ba36-4f5b-8def-6f70d9986fe9'))
        expect(archive).to.have.property(u('name')).being.equal(u('ARCHIVE NAME'))
        expect(archive).to.have.property(u('status')).being.equal(u('started'))
        expect(archive).to.have.property(u('session_id')).being.equal(u('SESSIONID'))
        expect(archive).to.have.property(u('partner_id')).being.equal(123456)
        if PY2:
            created_at = datetime.datetime.fromtimestamp(1395183243, pytz.UTC)
        if PY3:
            created_at = datetime.datetime.fromtimestamp(1395183243, datetime.timezone.utc)
        expect(archive).to.have.property(u('created_at')).being.equal(created_at)
        expect(archive).to.have.property(u('size')).being.equal(0)
        expect(archive).to.have.property(u('duration')).being.equal(0)
        expect(archive).to.have.property(u('has_audio')).being.equal(True)
        expect(archive).to.have.property(u('has_video')).being.equal(False)
        expect(archive).to.have.property(u('url')).being.equal(None)

    @httpretty.activate
    def test_start_individual_archive(self):
        httpretty.register_uri(httpretty.POST, u('https://api.opentok.com/v2/partner/{0}/archive').format(self.api_key),
                               body=textwrap.dedent(u("""\
                                       {
                                          "createdAt" : 1395183243556,
                                          "duration" : 0,
                                          "id" : "30b3ebf1-ba36-4f5b-8def-6f70d9986fe9",
                                          "name" : "ARCHIVE NAME",
                                          "partnerId" : 123456,
                                          "reason" : "",
                                          "sessionId" : "SESSIONID",
                                          "size" : 0,
                                          "status" : "started",
                                          "hasAudio": true,
                                          "hasVideo": true,
                                          "outputMode": "individual",
                                          "url" : null
                                        }""")),
                               status=200,
                               content_type=u('application/json'))

        archive = self.opentok.start_archive(self.session_id, name=u('ARCHIVE NAME'), output_mode=OutputModes.individual)

        expect(httpretty.last_request().headers[u('x-tb-partner-auth')]).to.equal(self.api_key+u(':')+self.api_secret)
        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('sessionId')).being.equal(u('SESSIONID'))
        expect(body).to.have.key(u('name')).being.equal(u('ARCHIVE NAME'))
        expect(archive).to.be.an(Archive)
        expect(archive).to.have.property(u('id')).being.equal(u('30b3ebf1-ba36-4f5b-8def-6f70d9986fe9'))
        expect(archive).to.have.property(u('name')).being.equal(u('ARCHIVE NAME'))
        expect(archive).to.have.property(u('status')).being.equal(u('started'))
        expect(archive).to.have.property(u('session_id')).being.equal(u('SESSIONID'))
        expect(archive).to.have.property(u('partner_id')).being.equal(123456)
        if PY2:
            created_at = datetime.datetime.fromtimestamp(1395183243, pytz.UTC)
        if PY3:
            created_at = datetime.datetime.fromtimestamp(1395183243, datetime.timezone.utc)
        expect(archive).to.have.property(u('created_at')).being.equal(created_at)
        expect(archive).to.have.property(u('size')).being.equal(0)
        expect(archive).to.have.property(u('duration')).being.equal(0)
        expect(archive).to.have.property(u('has_audio')).being.equal(True)
        expect(archive).to.have.property(u('has_video')).being.equal(True)
        expect(archive).to.have.property(u('output_mode')).being.equal(OutputModes.individual)
        expect(archive).to.have.property(u('url')).being.equal(None)

    @httpretty.activate
    def test_start_composed_archive(self):
        httpretty.register_uri(httpretty.POST, u('https://api.opentok.com/v2/partner/{0}/archive').format(self.api_key),
                               body=textwrap.dedent(u("""\
                                       {
                                          "createdAt" : 1395183243556,
                                          "duration" : 0,
                                          "id" : "30b3ebf1-ba36-4f5b-8def-6f70d9986fe9",
                                          "name" : "ARCHIVE NAME",
                                          "partnerId" : 123456,
                                          "reason" : "",
                                          "sessionId" : "SESSIONID",
                                          "size" : 0,
                                          "status" : "started",
                                          "hasAudio": true,
                                          "hasVideo": true,
                                          "outputMode": "composed",
                                          "url" : null
                                        }""")),
                               status=200,
                               content_type=u('application/json'))

        archive = self.opentok.start_archive(self.session_id, name=u('ARCHIVE NAME'), output_mode=OutputModes.composed)

        expect(httpretty.last_request().headers[u('x-tb-partner-auth')]).to.equal(self.api_key+u(':')+self.api_secret)
        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('sessionId')).being.equal(u('SESSIONID'))
        expect(body).to.have.key(u('name')).being.equal(u('ARCHIVE NAME'))
        expect(archive).to.be.an(Archive)
        expect(archive).to.have.property(u('id')).being.equal(u('30b3ebf1-ba36-4f5b-8def-6f70d9986fe9'))
        expect(archive).to.have.property(u('name')).being.equal(u('ARCHIVE NAME'))
        expect(archive).to.have.property(u('status')).being.equal(u('started'))
        expect(archive).to.have.property(u('session_id')).being.equal(u('SESSIONID'))
        expect(archive).to.have.property(u('partner_id')).being.equal(123456)
        if PY2:
            created_at = datetime.datetime.fromtimestamp(1395183243, pytz.UTC)
        if PY3:
            created_at = datetime.datetime.fromtimestamp(1395183243, datetime.timezone.utc)
        expect(archive).to.have.property(u('created_at')).being.equal(created_at)
        expect(archive).to.have.property(u('size')).being.equal(0)
        expect(archive).to.have.property(u('duration')).being.equal(0)
        expect(archive).to.have.property(u('has_audio')).being.equal(True)
        expect(archive).to.have.property(u('has_video')).being.equal(True)
        expect(archive).to.have.property(u('output_mode')).being.equal(OutputModes.composed)
        expect(archive).to.have.property(u('url')).being.equal(None)

    @httpretty.activate
    def test_stop_archive(self):
        archive_id = u('30b3ebf1-ba36-4f5b-8def-6f70d9986fe9')
        httpretty.register_uri(httpretty.POST, u('https://api.opentok.com/v2/partner/{0}/archive/{1}/stop').format(self.api_key, archive_id),
                               body=textwrap.dedent(u("""\
                                       {
                                          "createdAt" : 1395183243000,
                                          "duration" : 0,
                                          "id" : "30b3ebf1-ba36-4f5b-8def-6f70d9986fe9",
                                          "name" : "",
                                          "partnerId" : 123456,
                                          "reason" : "",
                                          "sessionId" : "SESSIONID",
                                          "size" : 0,
                                          "status" : "stopped",
                                          "hasAudio": true,
                                          "hasVideo": true,
                                          "outputMode": "composed",
                                          "url" : null
                                        }""")),
                               status=200,
                               content_type=u('application/json'))

        archive = self.opentok.stop_archive(archive_id)

        expect(httpretty.last_request().headers[u('x-tb-partner-auth')]).to.equal(self.api_key+u(':')+self.api_secret)
        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(archive).to.be.an(Archive)
        expect(archive).to.have.property(u('id')).being.equal(archive_id)
        expect(archive).to.have.property(u('name')).being.equal(u(''))
        expect(archive).to.have.property(u('status')).being.equal(u('stopped'))
        expect(archive).to.have.property(u('session_id')).being.equal(u('SESSIONID'))
        expect(archive).to.have.property(u('partner_id')).being.equal(123456)
        if PY2:
            created_at = datetime.datetime.fromtimestamp(1395183243, pytz.UTC)
        if PY3:
            created_at = datetime.datetime.fromtimestamp(1395183243, datetime.timezone.utc)
        expect(archive).to.have.property(u('created_at')).being.equal(created_at)
        expect(archive).to.have.property(u('size')).being.equal(0)
        expect(archive).to.have.property(u('duration')).being.equal(0)
        expect(archive).to.have.property(u('url')).being.equal(None)

    @httpretty.activate
    def test_delete_archive(self):
        archive_id = u('30b3ebf1-ba36-4f5b-8def-6f70d9986fe9')
        httpretty.register_uri(httpretty.DELETE, u('https://api.opentok.com/v2/partner/{0}/archive/{1}').format(self.api_key, archive_id),
                               body=u(''),
                               status=204)

        self.opentok.delete_archive(archive_id)

        expect(httpretty.last_request().headers[u('x-tb-partner-auth')]).to.equal(self.api_key+u(':')+self.api_secret)
        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_find_archive(self):
        archive_id = u('f6e7ee58-d6cf-4a59-896b-6d56b158ec71')
        httpretty.register_uri(httpretty.GET, u('https://api.opentok.com/v2/partner/{0}/archive/{1}').format(self.api_key, archive_id),
                               body=textwrap.dedent(u("""\
                                       {
                                          "createdAt" : 1395187836000,
                                          "duration" : 62,
                                          "id" : "f6e7ee58-d6cf-4a59-896b-6d56b158ec71",
                                          "name" : "",
                                          "partnerId" : 123456,
                                          "reason" : "",
                                          "sessionId" : "SESSIONID",
                                          "size" : 8347554,
                                          "status" : "available",
                                          "hasAudio": true,
                                          "hasVideo": true,
                                          "outputMode": "composed",
                                          "url" : "http://tokbox.com.archive2.s3.amazonaws.com/123456%2Ff6e7ee58-d6cf-4a59-896b-6d56b158ec71%2Farchive.mp4?Expires=1395194362&AWSAccessKeyId=AKIAI6LQCPIXYVWCQV6Q&Signature=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
                                        }""")),
                               status=200,
                               content_type=u('application/json'))

        archive = self.opentok.get_archive(archive_id)

        expect(httpretty.last_request().headers[u('x-tb-partner-auth')]).to.equal(self.api_key+u(':')+self.api_secret)
        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(archive).to.be.an(Archive)
        expect(archive).to.have.property(u('id')).being.equal(archive_id)
        expect(archive).to.have.property(u('name')).being.equal(u(''))
        expect(archive).to.have.property(u('status')).being.equal(u('available'))
        expect(archive).to.have.property(u('session_id')).being.equal(u('SESSIONID'))
        expect(archive).to.have.property(u('partner_id')).being.equal(123456)
        if PY2:
            created_at = datetime.datetime.fromtimestamp(1395187836, pytz.UTC)
        if PY3:
            created_at = datetime.datetime.fromtimestamp(1395187836, datetime.timezone.utc)
        expect(archive).to.have.property(u('created_at')).being.equal(created_at)
        expect(archive).to.have.property(u('size')).being.equal(8347554)
        expect(archive).to.have.property(u('duration')).being.equal(62)
        expect(archive).to.have.property(u('url')).being.equal(u('http://tokbox.com.archive2.s3.amazonaws.com/123456%2Ff6e7ee58-d6cf-4a59-896b-6d56b158ec71%2Farchive.mp4?Expires=1395194362&AWSAccessKeyId=AKIAI6LQCPIXYVWCQV6Q&Signature=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'))

    @httpretty.activate
    def test_find_archives(self):
        httpretty.register_uri(httpretty.GET, u('https://api.opentok.com/v2/partner/{0}/archive').format(self.api_key),
                               body=textwrap.dedent(u("""\
                                       {
                                          "count" : 6,
                                          "items" : [ {
                                            "createdAt" : 1395187930000,
                                            "duration" : 22,
                                            "id" : "ef546c5a-4fd7-4e59-ab3d-f1cfb4148d1d",
                                            "name" : "",
                                            "partnerId" : 123456,
                                            "reason" : "",
                                            "sessionId" : "SESSIONID",
                                            "size" : 2909274,
                                            "status" : "available",
                                            "hasAudio": true,
                                            "hasVideo": true,
                                            "outputMode": "composed",
                                            "url" : "http://tokbox.com.archive2.s3.amazonaws.com/123456%2Fef546c5a-4fd7-4e59-ab3d-f1cfb4148d1d%2Farchive.mp4?Expires=1395188695&AWSAccessKeyId=AKIAI6LQCPIXYVWCQV6Q&Signature=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
                                          }, {
                                            "createdAt" : 1395187910000,
                                            "duration" : 14,
                                            "id" : "5350f06f-0166-402e-bc27-09ba54948512",
                                            "name" : "",
                                            "partnerId" : 123456,
                                            "reason" : "",
                                            "sessionId" : "SESSIONID",
                                            "size" : 1952651,
                                            "status" : "available",
                                            "hasAudio": true,
                                            "hasVideo": true,
                                            "outputMode": "composed",
                                            "url" : "http://tokbox.com.archive2.s3.amazonaws.com/123456%2F5350f06f-0166-402e-bc27-09ba54948512%2Farchive.mp4?Expires=1395188695&AWSAccessKeyId=AKIAI6LQCPIXYVWCQV6Q&Signature=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
                                          }, {
                                            "createdAt" : 1395187836000,
                                            "duration" : 62,
                                            "id" : "f6e7ee58-d6cf-4a59-896b-6d56b158ec71",
                                            "name" : "",
                                            "partnerId" : 123456,
                                            "reason" : "",
                                            "sessionId" : "SESSIONID",
                                            "size" : 8347554,
                                            "status" : "available",
                                            "hasAudio": true,
                                            "hasVideo": true,
                                            "outputMode": "composed",
                                            "url" : "http://tokbox.com.archive2.s3.amazonaws.com/123456%2Ff6e7ee58-d6cf-4a59-896b-6d56b158ec71%2Farchive.mp4?Expires=1395188695&AWSAccessKeyId=AKIAI6LQCPIXYVWCQV6Q&Signature=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
                                          }, {
                                            "createdAt" : 1395183243000,
                                            "duration" : 544,
                                            "id" : "30b3ebf1-ba36-4f5b-8def-6f70d9986fe9",
                                            "name" : "",
                                            "partnerId" : 123456,
                                            "reason" : "",
                                            "sessionId" : "SESSIONID",
                                            "size" : 78499758,
                                            "status" : "available",
                                            "hasAudio": true,
                                            "hasVideo": true,
                                            "outputMode": "composed",
                                            "url" : "http://tokbox.com.archive2.s3.amazonaws.com/123456%2F30b3ebf1-ba36-4f5b-8def-6f70d9986fe9%2Farchive.mp4?Expires=1395188695&AWSAccessKeyId=AKIAI6LQCPIXYVWCQV6Q&Signature=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
                                          }, {
                                            "createdAt" : 1394396753000,
                                            "duration" : 24,
                                            "id" : "b8f64de1-e218-4091-9544-4cbf369fc238",
                                            "name" : "showtime again",
                                            "partnerId" : 123456,
                                            "reason" : "",
                                            "sessionId" : "SESSIONID",
                                            "size" : 2227849,
                                            "status" : "available",
                                            "hasAudio": true,
                                            "hasVideo": true,
                                            "outputMode": "composed",
                                            "url" : "http://tokbox.com.archive2.s3.amazonaws.com/123456%2Fb8f64de1-e218-4091-9544-4cbf369fc238%2Farchive.mp4?Expires=1395188695&AWSAccessKeyId=AKIAI6LQCPIXYVWCQV6Q&Signature=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
                                          }, {
                                            "createdAt" : 1394321113000,
                                            "duration" : 1294,
                                            "id" : "832641bf-5dbf-41a1-ad94-fea213e59a92",
                                            "name" : "showtime",
                                            "partnerId" : 123456,
                                            "reason" : "",
                                            "sessionId" : "SESSIONID",
                                            "size" : 42165242,
                                            "status" : "available",
                                            "hasAudio": true,
                                            "hasVideo": true,
                                            "outputMode": "composed",
                                            "url" : "http://tokbox.com.archive2.s3.amazonaws.com/123456%2F832641bf-5dbf-41a1-ad94-fea213e59a92%2Farchive.mp4?Expires=1395188695&AWSAccessKeyId=AKIAI6LQCPIXYVWCQV6Q&Signature=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
                                          } ]
                                        }""")),
                               status=200,
                               content_type=u('application/json'))

        archive_list = self.opentok.get_archives()

        expect(httpretty.last_request().headers[u('x-tb-partner-auth')]).to.equal(self.api_key+u(':')+self.api_secret)
        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(archive_list).to.be.an(ArchiveList)
        expect(archive_list).to.have.property(u('count')).being.equal(6)
        expect(list(archive_list.items)).to.have.length_of(6)
        # TODO: we could inspect each item in the list

    @httpretty.activate
    def test_find_archives_with_offset(self):
        httpretty.register_uri(httpretty.GET, u('https://api.opentok.com/v2/partner/{0}/archive').format(self.api_key),
                               body=textwrap.dedent(u("""\
                                       {
                                          "count" : 6,
                                          "items" : [ {
                                            "createdAt" : 1395183243000,
                                            "duration" : 544,
                                            "id" : "30b3ebf1-ba36-4f5b-8def-6f70d9986fe9",
                                            "name" : "",
                                            "partnerId" : 123456,
                                            "reason" : "",
                                            "sessionId" : "SESSIONID",
                                            "size" : 78499758,
                                            "status" : "available",
                                            "hasAudio": true,
                                            "hasVideo": true,
                                            "url" : "http://tokbox.com.archive2.s3.amazonaws.com/123456%2F30b3ebf1-ba36-4f5b-8def-6f70d9986fe9%2Farchive.mp4?Expires=1395188695&AWSAccessKeyId=AKIAI6LQCPIXYVWCQV6Q&Signature=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
                                          }, {
                                            "createdAt" : 1394396753000,
                                            "duration" : 24,
                                            "id" : "b8f64de1-e218-4091-9544-4cbf369fc238",
                                            "name" : "showtime again",
                                            "partnerId" : 123456,
                                            "reason" : "",
                                            "sessionId" : "SESSIONID",
                                            "size" : 2227849,
                                            "status" : "available",
                                            "hasAudio": true,
                                            "hasVideo": true,
                                            "url" : "http://tokbox.com.archive2.s3.amazonaws.com/123456%2Fb8f64de1-e218-4091-9544-4cbf369fc238%2Farchive.mp4?Expires=1395188695&AWSAccessKeyId=AKIAI6LQCPIXYVWCQV6Q&Signature=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
                                          }, {
                                            "createdAt" : 1394321113000,
                                            "duration" : 1294,
                                            "id" : "832641bf-5dbf-41a1-ad94-fea213e59a92",
                                            "name" : "showtime",
                                            "partnerId" : 123456,
                                            "reason" : "",
                                            "sessionId" : "SESSIONID",
                                            "size" : 42165242,
                                            "status" : "available",
                                            "hasAudio": true,
                                            "hasVideo": true,
                                            "url" : "http://tokbox.com.archive2.s3.amazonaws.com/123456%2F832641bf-5dbf-41a1-ad94-fea213e59a92%2Farchive.mp4?Expires=1395188695&AWSAccessKeyId=AKIAI6LQCPIXYVWCQV6Q&Signature=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
                                          } ]
                                        }""")),
                               status=200,
                               content_type=u('application/json'))

        archive_list = self.opentok.get_archives(offset=3)

        expect(httpretty.last_request().headers[u('x-tb-partner-auth')]).to.equal(self.api_key+u(':')+self.api_secret)
        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(httpretty.last_request()).to.have.property("querystring").being.equal({
            u('offset'): [u('3')]
        })
        expect(archive_list).to.be.an(ArchiveList)
        expect(archive_list).to.have.property(u('count')).being.equal(6)
        expect(list(archive_list.items)).to.have.length_of(3)
        # TODO: we could inspect each item in the list

    @httpretty.activate
    def test_find_archives_with_count(self):
        httpretty.register_uri(httpretty.GET, u('https://api.opentok.com/v2/partner/{0}/archive').format(self.api_key),
                               body=textwrap.dedent(u("""\
                                       {
                                          "count" : 6,
                                          "items" : [ {
                                            "createdAt" : 1395187930000,
                                            "duration" : 22,
                                            "id" : "ef546c5a-4fd7-4e59-ab3d-f1cfb4148d1d",
                                            "name" : "",
                                            "partnerId" : 123456,
                                            "reason" : "",
                                            "sessionId" : "SESSIONID",
                                            "size" : 2909274,
                                            "status" : "available",
                                            "hasAudio": true,
                                            "hasVideo": true,
                                            "url" : "http://tokbox.com.archive2.s3.amazonaws.com/123456%2Fef546c5a-4fd7-4e59-ab3d-f1cfb4148d1d%2Farchive.mp4?Expires=1395188695&AWSAccessKeyId=AKIAI6LQCPIXYVWCQV6Q&Signature=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
                                          }, {
                                            "createdAt" : 1395187910000,
                                            "duration" : 14,
                                            "id" : "5350f06f-0166-402e-bc27-09ba54948512",
                                            "name" : "",
                                            "partnerId" : 123456,
                                            "reason" : "",
                                            "sessionId" : "SESSIONID",
                                            "size" : 1952651,
                                            "status" : "available",
                                            "hasAudio": true,
                                            "hasVideo": true,
                                            "url" : "http://tokbox.com.archive2.s3.amazonaws.com/123456%2F5350f06f-0166-402e-bc27-09ba54948512%2Farchive.mp4?Expires=1395188695&AWSAccessKeyId=AKIAI6LQCPIXYVWCQV6Q&Signature=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
                                          } ]
                                        }""")),
                               status=200,
                               content_type=u('application/json'))

        archive_list = self.opentok.get_archives(count=2)

        expect(httpretty.last_request().headers[u('x-tb-partner-auth')]).to.equal(self.api_key+u(':')+self.api_secret)
        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(httpretty.last_request()).to.have.property("querystring").being.equal({
            u('count'): [u('2')]
        })
        expect(archive_list).to.be.an(ArchiveList)
        expect(archive_list).to.have.property(u('count')).being.equal(6)
        expect(list(archive_list.items)).to.have.length_of(2)
        # TODO: we could inspect each item in the list

    @httpretty.activate
    def test_find_archives_with_offset_and_count(self):
        httpretty.register_uri(httpretty.GET, u('https://api.opentok.com/v2/partner/{0}/archive').format(self.api_key),
                               body=textwrap.dedent(u("""\
                                       {
                                          "count" : 6,
                                          "items" : [ {
                                            "createdAt" : 1395187836000,
                                            "duration" : 62,
                                            "id" : "f6e7ee58-d6cf-4a59-896b-6d56b158ec71",
                                            "name" : "",
                                            "partnerId" : 123456,
                                            "reason" : "",
                                            "sessionId" : "SESSIONID",
                                            "size" : 8347554,
                                            "status" : "available",
                                            "hasAudio": true,
                                            "hasVideo": true,
                                            "url" : "http://tokbox.com.archive2.s3.amazonaws.com/123456%2Ff6e7ee58-d6cf-4a59-896b-6d56b158ec71%2Farchive.mp4?Expires=1395188695&AWSAccessKeyId=AKIAI6LQCPIXYVWCQV6Q&Signature=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
                                          }, {
                                            "createdAt" : 1395183243000,
                                            "duration" : 544,
                                            "id" : "30b3ebf1-ba36-4f5b-8def-6f70d9986fe9",
                                            "name" : "",
                                            "partnerId" : 123456,
                                            "reason" : "",
                                            "sessionId" : "SESSIONID",
                                            "size" : 78499758,
                                            "status" : "available",
                                            "hasAudio": true,
                                            "hasVideo": true,
                                            "url" : "http://tokbox.com.archive2.s3.amazonaws.com/123456%2F30b3ebf1-ba36-4f5b-8def-6f70d9986fe9%2Farchive.mp4?Expires=1395188695&AWSAccessKeyId=AKIAI6LQCPIXYVWCQV6Q&Signature=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
                                          }, {
                                            "createdAt" : 1394396753000,
                                            "duration" : 24,
                                            "id" : "b8f64de1-e218-4091-9544-4cbf369fc238",
                                            "name" : "showtime again",
                                            "partnerId" : 123456,
                                            "reason" : "",
                                            "sessionId" : "SESSIONID",
                                            "size" : 2227849,
                                            "status" : "available",
                                            "hasAudio": true,
                                            "hasVideo": true,
                                            "url" : "http://tokbox.com.archive2.s3.amazonaws.com/123456%2Fb8f64de1-e218-4091-9544-4cbf369fc238%2Farchive.mp4?Expires=1395188695&AWSAccessKeyId=AKIAI6LQCPIXYVWCQV6Q&Signature=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
                                          }, {
                                            "createdAt" : 1394321113000,
                                            "duration" : 1294,
                                            "id" : "832641bf-5dbf-41a1-ad94-fea213e59a92",
                                            "name" : "showtime",
                                            "partnerId" : 123456,
                                            "reason" : "",
                                            "sessionId" : "SESSIONID",
                                            "size" : 42165242,
                                            "status" : "available",
                                            "hasAudio": true,
                                            "hasVideo": true,
                                            "url" : "http://tokbox.com.archive2.s3.amazonaws.com/123456%2F832641bf-5dbf-41a1-ad94-fea213e59a92%2Farchive.mp4?Expires=1395188695&AWSAccessKeyId=AKIAI6LQCPIXYVWCQV6Q&Signature=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
                                          } ]
                                        }""")),
                               status=200,
                               content_type=u('application/json'))

        archive_list = self.opentok.get_archives(count=4, offset=2)

        expect(httpretty.last_request().headers[u('x-tb-partner-auth')]).to.equal(self.api_key+u(':')+self.api_secret)
        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(httpretty.last_request()).to.have.property("querystring").being.equal({
            u('offset'): [u('2')],
            u('count'): [u('4')]
        })
        expect(archive_list).to.be.an(ArchiveList)
        expect(archive_list).to.have.property(u('count')).being.equal(6)
        expect(list(archive_list.items)).to.have.length_of(4)
        # TODO: we could inspect each item in the list

    @httpretty.activate
    def test_find_paused_archive(self):
        archive_id = u('f6e7ee58-d6cf-4a59-896b-6d56b158ec71')
        httpretty.register_uri(httpretty.GET, u('https://api.opentok.com/v2/partner/{0}/archive/{1}').format(self.api_key, archive_id),
                               body=textwrap.dedent(u("""\
                                       {
                                          "createdAt" : 1395187836000,
                                          "duration" : 62,
                                          "id" : "f6e7ee58-d6cf-4a59-896b-6d56b158ec71",
                                          "name" : "",
                                          "partnerId" : 123456,
                                          "reason" : "",
                                          "sessionId" : "SESSIONID",
                                          "size" : 8347554,
                                          "status" : "paused",
                                          "hasAudio": true,
                                          "hasVideo": true,
                                          "url" : null
                                        }""")),
                               status=200,
                               content_type=u('application/json'))

        archive = self.opentok.get_archive(archive_id)

        expect(archive).to.be.an(Archive)
        expect(archive).to.have.property(u('status')).being.equal(u('paused'))

    @httpretty.activate
    def test_find_expired_archive(self):
        archive_id = u('f6e7ee58-d6cf-4a59-896b-6d56b158ec71')
        httpretty.register_uri(httpretty.GET, u('https://api.opentok.com/v2/partner/{0}/archive/{1}').format(self.api_key, archive_id),
                               body=textwrap.dedent(u("""\
                                       {
                                          "createdAt" : 1395187836000,
                                          "duration" : 62,
                                          "id" : "f6e7ee58-d6cf-4a59-896b-6d56b158ec71",
                                          "name" : "",
                                          "partnerId" : 123456,
                                          "reason" : "",
                                          "sessionId" : "SESSIONID",
                                          "size" : 8347554,
                                          "status" : "expired",
                                          "hasAudio": true,
                                          "hasVideo": true,
                                          "url" : null
                                        }""")),
                               status=200,
                               content_type=u('application/json'))

        archive = self.opentok.get_archive(archive_id)

        expect(archive).to.be.an(Archive)
        expect(archive).to.have.property(u('status')).being.equal(u('expired'))

    @httpretty.activate
    def test_find_archive_with_unknown_properties(self):
        archive_id = u('f6e7ee58-d6cf-4a59-896b-6d56b158ec71')
        httpretty.register_uri(httpretty.GET, u('https://api.opentok.com/v2/partner/{0}/archive/{1}').format(self.api_key, archive_id),
                               body=textwrap.dedent(u("""\
                                       {
                                          "createdAt" : 1395187836000,
                                          "duration" : 62,
                                          "id" : "f6e7ee58-d6cf-4a59-896b-6d56b158ec71",
                                          "name" : "",
                                          "partnerId" : 123456,
                                          "reason" : "",
                                          "sessionId" : "SESSIONID",
                                          "size" : 8347554,
                                          "status" : "expired",
                                          "url" : null,
                                          "hasAudio": true,
                                          "hasVideo": true,
                                          "notarealproperty" : "not a real value"
                                        }""")),
                               status=200,
                               content_type=u('application/json'))

        archive = self.opentok.get_archive(archive_id)

        expect(archive).to.be.an(Archive)
示例#56
0
from flask import Flask, render_template, request, redirect, url_for
from opentok import OpenTok, 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 = OpenTok(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
    token = opentok.generate_token(session_id)
    return render_template('host.html', api_key=key, session_id=session_id, token=token)

@app.route("/participant")
 def setUp(self):
     self.api_key = u('123456')
     self.api_secret = u('1234567890abcdef1234567890abcdef1234567890')
     self.opentok = OpenTok(self.api_key, self.api_secret)
     self.session_id = u('2_MX4xMDBfjE0Mzc2NzY1NDgwMTJ-TjMzfn4')
 def test_timeout(self):
     opentok = OpenTok(self.api_key, self.api_secret, timeout=1)
     opentok.create_session()