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
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)
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
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')
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
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
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)
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 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')
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
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'))
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
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)
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
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())
class Application(web.Application): 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() def user_enter(self, user_id): if user_id not in self.users: self.users[user_id] = [None, False] rv = {'state': self.users[user_id]} if user_id.lower().startswith('dr.'): rv['patients'] = dict((user_id, state) for user_id, state in self.users.items() if not user_id.lower().startswith('dr.')) return rv def _exit_from_session(self, user_id): session_id = self.users[user_id][0] self.users[user_id] = [None, False] if session_id is not None: if user_id in self.sessions[session_id]: self.sessions[session_id][1].pop(user_id) def user_exit(self, user_id): if user_id in self.users: self._exit_from_session(user_id) self.users.pop(user_id) def create_session(self, user_id): if user_id not in self.users: raise web.HTTPNotFound(reason='user_id not found') if not user_id.lower().startswith('dr.'): raise web.HTTPForbidden(reason='patient vcannot create session') self._exit_from_session(user_id) session = self.opentok.create_session() session_id = session.session_id token = self.opentok.generate_token(session_id) self.sessions[session_id] = [session, {}] self.sessions[session_id][1][user_id] = token self.users[user_id] = [session_id, True] return {'api_key': self.opentok.api_key, 'session_id': session_id, 'token': token} def join_to_session(self, user_id, session_id): if user_id not in self.users: raise web.HTTPNotFound(reason='user_id not found') if session_id not in self.sessions: raise web.HTTPNotFound(reason='session_id not found') if not user_id.lower().startswith('dr.'): if session_id != self.users[user_id][0]: raise web.HTTPForbidden(reason='patient cannot join to arbitrary session') self._exit_from_session(user_id) token = self.opentok.generate_token(session_id) self.sessions[session_id][1][user_id] = token self.users[user_id] = [session_id, True] return {'api_key': self.opentok.api_key, 'session_id': session_id, 'token': token} def call_from_session(self, user_id, session_id, addressee): if user_id not in self.users: raise web.HTTPNotFound(reason='user_id not found') if not user_id.lower().startswith('dr.'): raise web.HTTPForbidden(reason='patient cannot call from session') if addressee not in self.users: raise web.HTTPNotFound(reason='addressee not found') self.users[addressee] = [session_id, False]
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) @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)
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')
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)
def generate_opentok_token(self, session_id): opentok = OpenTok(settings.OPENTOK_API_KEY, settings.OPENTOK_SECRET) return opentok.generate_token(session_id=session_id, data="role=" + self.get_role(), role=Roles.publisher)
# OpenTok Server SDK from opentok import OpenTok from opentok import MediaModes from opentok import ArchiveModes api_key = "API_KEY" api_secret = "API_SECRET" opentok = OpenTok(api_key, api_secret) # create session session = opentok.create_session(media_mode=MediaModes.routed) session_id = session.session_id # generate token token = opentok.generate_token(session_id) # archive ID for this session archive_id = "" app = Flask(__name__) @app.route("/session") def session_get(): obj = {} obj['apiKey'] = api_key obj['sessionId'] = session_id obj['token'] = token j = json.dumps(obj) return (j)