def _process(self): if self._target.isClosed(): return json.dumps({'status': 'error'}, textarea=True) else: if self._tempFilePath is not None: if self._conf.getPosterTemplateManager().hasTemplate(self.__templateId): # Save backgroundId = self._conf.getPosterTemplateManager().getTemplateById(self.__templateId).addTempBackgroundFilePath(self._tempFilePath,self._bgPosition) else: # New key = "tempBackground-%s-%s" % (self._conf.id, self.__templateId) value = session.get(key) if value is None: # First background tempFilePathList = PersistentList() tempFilePathList.append((self._tempFilePath,self._bgPosition)) session[key] = tempFilePathList backgroundId = 0 else: # We have more value.append((self._tempFilePath, self._bgPosition)) backgroundId = len(value) - 1 session.modified = True return json.dumps({ 'status': 'OK', 'id': backgroundId, 'url': str(urlHandlers.UHConfModifPosterGetBackground.getURL(self._conf, self.__templateId, backgroundId)), 'pos': self._bgPosition }, textarea=True)
def _process(self): if self._target.isClosed(): return json.dumps({'status': 'error'}, textarea=True) else: if self._tempFilePath is not None: if self._conf.getBadgeTemplateManager().hasTemplate(self.__templateId): backgroundId = self._conf.getBadgeTemplateManager().getTemplateById(self.__templateId).addTempBackgroundFilePath(self._tempFilePath) else: key = "tempBackground-%s-%s" % (self._conf.id, self.__templateId) value = session.get(key) if value is None: tempFilePathList = PersistentList() tempFilePathList.append(self._tempFilePath) session[key] = tempFilePathList backgroundId = 0 else: value.append(self._tempFilePath) backgroundId = len(value) - 1 session.modified = True return json.dumps({ 'status': 'OK', 'id': backgroundId, 'url': str(urlHandlers.UHConfModifBadgeGetBackground.getURL(self._conf, self.__templateId, backgroundId)) }, textarea=True)
def test_connect_room_force_fail(caplog, httpretty, room_name, service_type, connected, data): RavemPlugin.settings.set("api_endpoint", RAVEM_TEST_API_ENDPOINT) RavemPlugin.settings.set("polling_limit", 3) RavemPlugin.settings.set("polling_interval", 100) different_vc_room = "different_vc_room" httpretty.register_uri( httpretty.GET, RAVEM_TEST_API_ENDPOINT + "rooms/details", status=200, content_type="application/json", body=json.dumps({ "roomName": room_name, "deviceType": service_type, "services": [{ "status": connected, "eventName": different_vc_room, "name": "videoconference", }], }), ) httpretty.register_uri( httpretty.POST, RAVEM_TEST_API_ENDPOINT + service_type + "/disconnect", status=200, content_type="application/json", body=json.dumps({"result": "OK"}), ) vc_room = MagicMock() vc_room.type = service_type vc_room.data = data with pytest.raises(RavemException) as excinfo: connect_room(room_name, vc_room, force=True) assert ( str(excinfo.value) == f"Failed to disconnect the room {room_name} from the videoconference room {different_vc_room} " "with an unknown error") log = extract_logs(caplog, one=True, name="indico.plugin.ravem") assert ( log.message == f"Failed to disconnect the room {room_name} from the videoconference room {different_vc_room} " "with an unknown error") assert len(httpretty.httpretty.latest_requests ) == 2 + RavemPlugin.settings.get("polling_limit") request = httpretty.httpretty.latest_requests[1] assert request.path.startswith(RAVEM_TEST_PATH + service_type + "/disconnect") assert request.parsed_body == {"roomName": room_name}
def test_connect_room(httpretty, room_name, service_type, connected, data): RavemPlugin.settings.set("api_endpoint", RAVEM_TEST_API_ENDPOINT) service_api = get_api(service_type) vc_room_id = service_api.get_room_id(data) httpretty.register_uri( httpretty.GET, RAVEM_TEST_API_ENDPOINT + "rooms/details", status=200, content_type="application/json", body=json.dumps({ "roomName": room_name, "deviceType": service_type, "services": [{ "status": connected, "eventName": None, "name": "videoconference", }], }), ) httpretty.register_uri( httpretty.POST, RAVEM_TEST_API_ENDPOINT + service_type + "/connect", status=200, content_type="application/json", body=json.dumps({"result": "OK"}), ) vc_room = MagicMock() vc_room.data = data vc_room.type = service_type connect_room(room_name, vc_room) assert len(httpretty.httpretty.latest_requests) == 2 status_request = httpretty.httpretty.latest_requests[0] request = httpretty.last_request() assert request.path.startswith(RAVEM_TEST_PATH + service_type + "/connect") assert request.parsed_body == { "meetingId": vc_room_id, "roomName": room_name } assert status_request.path.startswith(RAVEM_TEST_PATH + "rooms/details") assert status_request.querystring == { "where": ["room_name"], "value": [room_name] }
def getVars( self ): vars=wcomponents.WTemplated.getVars(self) tz = self._session.getTimezone() vars["timezone"]= tz vars['ttdata'] = json.dumps(schedule.ScheduleToJson.process(self._session.getSchedule(), tz, None, days = None, mgmtMode = True)) eventInfo = fossilize(self._session.getConference(), IConferenceEventInfoFossil, tz=tz) eventInfo['timetableSession'] = fossilize(self._session, ISessionFossil, tz=tz) eventInfo['isCFAEnabled'] = self._session.getConference().getAbstractMgr().isActive() vars['eventInfo'] = json.dumps(eventInfo) return vars
def test_connect_room_connected_other(httpretty, room_name, service_type, connected): RavemPlugin.settings.set("api_endpoint", RAVEM_TEST_API_ENDPOINT) different_vc_room = 123 httpretty.register_uri( httpretty.GET, RAVEM_TEST_API_ENDPOINT + "rooms/details", status=200, content_type="application/json", body=json.dumps({ "roomName": room_name, "deviceType": service_type, "services": [{ "status": connected, "eventName": different_vc_room, "name": "videoconference", }], }), ) vc_room = MagicMock() vc_room.type = service_type with pytest.raises(RavemException) as excinfo: connect_room(room_name, vc_room) assert str(excinfo.value) == \ f"The room {room_name} is connected to another videoconference room: {different_vc_room}" assert excinfo.value.reason == "connected-other"
def _process_POST(self): if self._type in ["all", "2priorities"]: self._section.setType(self._type) else: raise MaKaCError(_("Unknown type")) self._setItems() return json.dumps(self._section.fossilize())
def _process_POST(self): self._section.setArrivalOffsetDates( [int(-d) for d in self._arrivalOffsetDates]) self._section.setDepartureOffsetDates( [int(d) for d in self._departureOffsetDates]) self._setItems() return json.dumps(self._section.fossilize())
def _processOAuthError(self, e): res = json.dumps(e.fossilize()) header = oauth.build_authenticate_header(realm=Config.getInstance().getBaseSecureURL()) self._responseUtil.headers.extend(header) self._responseUtil.content_type = 'application/json' self._responseUtil.status = e.code return res
def process(): responseBody = { 'version': '1.1', 'error': None, 'result': None } requestBody = None try: # init/clear fossil cache clearCache() # read request try: requestBody = request.get_json() Logger.get('rpc').info('json rpc request. request: {0}'.format(requestBody)) except BadRequest: raise RequestError('ERR-R1', 'Invalid mime-type.') if not requestBody: raise RequestError('ERR-R2', 'Empty request.') if 'id' in requestBody: responseBody['id'] = requestBody['id'] # run request responseBody['result'] = ServiceRunner().invokeMethod(str(requestBody['method']), requestBody.get('params', [])) except CausedError as e: try: errorInfo = fossilize(e) except NonFossilizableException as e2: # catch Exceptions that are not registered as Fossils # and log them errorInfo = {'code': '', 'message': str(e2)} Logger.get('dev').exception('Exception not registered as fossil') # NoReport errors (i.e. not logged in) shouldn't be logged if not isinstance(e, NoReportError): Logger.get('rpc').exception('Service request failed. ' 'Request text:\r\n{0}\r\n\r\n'.format(requestBody)) if requestBody: params = requestBody.get('params', []) Sanitization._escapeHTML(params) errorInfo["requestInfo"] = { 'method': str(requestBody['method']), 'params': params, 'origin': str(requestBody.get('origin', 'unknown')) } Logger.get('rpc').debug('Arguments: {0}'.format(errorInfo['requestInfo'])) responseBody['error'] = errorInfo try: jsonResponse = dumps(responseBody, ensure_ascii=True) except UnicodeError: Logger.get('rpc').exception('Problem encoding JSON response') # This is to avoid exceptions due to old data encodings (based on iso-8859-1) responseBody['result'] = fix_broken_obj(responseBody['result']) jsonResponse = encode(responseBody) return app.response_class(jsonResponse, mimetype='application/json')
def _process_POST(self): pos = next((i for i, f in enumerate(self._regForm.getSortedForms()) if not f.isEnabled()), None) section = GeneralSectionForm(self._regForm, data=self._sectionHeader) self._regForm.addGeneralSectionForm(section, preserveTitle=True, pos=pos) return json.dumps(section.fossilize())
def _processOAuthError(self, e): res = json.dumps(e.fossilize()) header = oauth.build_authenticate_header( realm=Config.getInstance().getBaseSecureURL()) self._responseUtil.headers.extend(header) self._responseUtil.content_type = 'application/json' self._responseUtil.status = e.code return res
def _process_POST(self): if not self._field.isLocked('disable'): # Move field to the end of the list self._section.addToSortedFields(self._field) self._field.setDisabled(True) else: raise MaKaCError(_("Action couldn't be perform")) return json.dumps(self._field.fossilize())
def _process_POST(self): # If general section if self._section.getId().isdigit(): # Enable field if moved out side of the disabled fields if (self._sectionEndPos == 0 or not self._section.getSortedFields()[self._sectionEndPos].isDisabled()): self._field.setDisabled(False) else: if self._field.isLocked('disable'): return json.dumps(self._section.fossilize()) #w = Warning(_('Warning'), _('This field can\'t be disabled')) #return ResultWithWarning(self._section.fossilize(), w).fossilize() else: self._field.setDisabled(True) self._section.addToSortedFields(self._field, self._sectionEndPos) else: raise MaKaCError(_("Section id: " + self._section.getId() + " doesn't support field move")) return json.dumps(self._section.fossilize())
def _process(self): if self._target.isClosed(): return json.dumps({'status': 'error'}, textarea=True) else: if self._tempFilePath is not None: if self._conf.getPosterTemplateManager().hasTemplate( self.__templateId): # Save backgroundId = self._conf.getPosterTemplateManager( ).getTemplateById( self.__templateId).addTempBackgroundFilePath( self._tempFilePath, self._bgPosition) else: # New key = "tempBackground-%s-%s" % (self._conf.id, self.__templateId) value = session.get(key) if value is None: # First background tempFilePathList = PersistentList() tempFilePathList.append( (self._tempFilePath, self._bgPosition)) session[key] = tempFilePathList backgroundId = 0 else: # We have more value.append((self._tempFilePath, self._bgPosition)) backgroundId = len(value) - 1 session.modified = True return json.dumps( { 'status': 'OK', 'id': backgroundId, 'url': str( urlHandlers.UHConfModifPosterGetBackground.getURL( self._conf, self.__templateId, backgroundId)), 'pos': self._bgPosition }, textarea=True)
def test_connect_room_force_error(caplog, httpretty, room_name, service_type, connected, data): RavemPlugin.settings.set("api_endpoint", RAVEM_TEST_API_ENDPOINT) error_message = "Some internal error" different_vc_room = "different_vc_room" httpretty.register_uri( httpretty.GET, RAVEM_TEST_API_ENDPOINT + "rooms/details", status=200, content_type="application/json", body=json.dumps({ "roomName": room_name, "deviceType": service_type, "services": [{ "status": connected, "eventName": different_vc_room, "name": "videoconference", }], }), ) httpretty.register_uri( httpretty.POST, RAVEM_TEST_API_ENDPOINT + service_type + "/disconnect", status=200, content_type="application/json", body=json.dumps({"error": error_message}), ) vc_room = MagicMock() vc_room.type = service_type vc_room.data = data with pytest.raises(RavemException) as excinfo: connect_room(room_name, vc_room, force=True) assert ( str(excinfo.value) == f"Failed to disconnect the room {room_name} from the videoconference room " f"{different_vc_room} with error: {error_message}") log = extract_logs(caplog, one=True, name="indico.plugin.ravem") assert log.message == str(excinfo.value)
def _process(self): if self.spkUniqueId and self.file: self.uploadProcess() return json.dumps({'status': 'OK'}, textarea=True) if self._cannotViewTab: raise MaKaCError(_("That Video Services tab doesn't exist"), _("Video Services")) else: p = WPElectronicAgreement(self, self._conf) return p.display(sortCriteria = self.sortCriteria, order = self.order)
def _process(self): # We will need to pickle the data back into JSON user = self.getAW().getUser() if not self._loggedIn: return json.dumps( { "status": "ERROR", "info": { "type": "noReport", "title": "", "explanation": _("You are currently not authenticated. Please log in again."), }, }, textarea=True, ) try: owner = self._target title = owner.getTitle() if type(owner) == Conference: ownerType = "event" elif type(owner) == Session: ownerType = "session" elif type(owner) == Contribution: ownerType = "contribution" elif type(owner) == SubContribution: ownerType = "subcontribution" else: ownerType = "" text = " in %s %s" % (ownerType, title) except: owner = None text = "" try: if len(self._errorList) > 0: raise Exception("Operation aborted") else: mat, status, info = self._addMaterialType(text, user) if status == "OK": for entry in info: entry["material"] = mat.getId() except Exception, e: status = "ERROR" if "file" in self._params: del self._params["file"] info = { "message": self._errorList or " %s: %s" % (e.__class__.__name__, str(e)), "code": "0", "requestInfo": self._params, } Logger.get("requestHandler").exception("Error uploading file")
def process(): responseBody = {"version": "1.1", "error": None, "result": None} requestBody = None try: # init/clear fossil cache clearCache() # read request try: requestBody = request.get_json() Logger.get("rpc").info("json rpc request. request: {0}".format(requestBody)) except BadRequest: raise RequestError("ERR-R1", "Invalid mime-type.") if not requestBody: raise RequestError("ERR-R2", "Empty request.") if "id" in requestBody: responseBody["id"] = requestBody["id"] # run request responseBody["result"] = ServiceRunner().invokeMethod(str(requestBody["method"]), requestBody.get("params", [])) except CausedError as e: try: errorInfo = fossilize(e) except NonFossilizableException as e2: # catch Exceptions that are not registered as Fossils # and log them errorInfo = {"code": "", "message": str(e2)} Logger.get("dev").exception("Exception not registered as fossil") # NoReport errors (i.e. not logged in) shouldn't be logged if not isinstance(e, NoReportError): Logger.get("rpc").exception("Service request failed. " "Request text:\r\n{0}\r\n\r\n".format(requestBody)) if requestBody: params = requestBody.get("params", []) Sanitization._escapeHTML(params) errorInfo["requestInfo"] = { "method": str(requestBody["method"]), "params": params, "origin": str(requestBody.get("origin", "unknown")), } Logger.get("rpc").debug("Arguments: {0}".format(errorInfo["requestInfo"])) responseBody["error"] = errorInfo try: jsonResponse = dumps(responseBody, ensure_ascii=True) except UnicodeError: Logger.get("rpc").exception("Problem encoding JSON response") # This is to avoid exceptions due to old data encodings (based on iso-8859-1) responseBody["result"] = fix_broken_obj(responseBody["result"]) jsonResponse = encode(responseBody) return app.response_class(jsonResponse, mimetype="application/json")
def _process(self): user = self._aw.getUser() reg_data = {} if user is not None: if user.isRegisteredInConf(self._conf): registrant = user.getRegistrantById(self._conf.getId()) reg_data = registrant.fossilize() else: personalData = self._regForm.getPersonalData() reg_data['avatar'] = personalData.getFormValuesFromAvatar(user) return json.dumps(reg_data)
def _process(self): if self.spkUniqueId and self.file: self.uploadProcess() return json.dumps({'status': 'OK'}, textarea=True) if self._cannotViewTab: raise MaKaCError(_("That Video Services tab doesn't exist"), _("Video Services")) else: p = WPElectronicAgreement(self, self._conf) return p.display(sortCriteria=self.sortCriteria, order=self.order)
def test_connect_room_already_connected(httpretty, room_name, service_type, connected, data): RavemPlugin.settings.set("api_endpoint", RAVEM_TEST_API_ENDPOINT) service_api = get_api(service_type) vc_room_id = service_api.get_room_id(data) httpretty.register_uri( httpretty.GET, RAVEM_TEST_API_ENDPOINT + "rooms/details", status=200, content_type="application/json", body=json.dumps({ "roomName": room_name, "deviceType": service_type, "services": [{ "status": connected, "eventName": vc_room_id, "name": "videoconference", }], }), ) httpretty.register_uri( httpretty.POST, RAVEM_TEST_API_ENDPOINT + service_type + "/connect", status=200, content_type="application/json", body=json.dumps({"error": "Call already disconnected"}), ) vc_room = MagicMock() vc_room.type = service_type vc_room.data = data with pytest.raises(RavemException) as excinfo: connect_room(room_name, vc_room) assert str( excinfo.value ) == f"The room {room_name} is already connected to the videoconference room {vc_room_id}" assert excinfo.value.reason == "already-connected"
def _process_POST(self): if 'radioitems' in self._fieldData: radioitems = self._fieldData['radioitems'] radioitems = [item for item in radioitems if not 'remove' in item] self._fieldData['radioitems'] = map(self.parseJsonItem, radioitems) # For compatibility reason the client side uses yesno if (self._fieldData['input'] == 'yesno'): self._fieldData['input'] = 'yes/no' field = GeneralField(self._section, data=self._fieldData) pos = next((i for i, f in enumerate(self._section.getSortedFields()) if f.isDisabled()), None) self._section.addToSortedFields(field, i=pos) return json.dumps(field.fossilize())
def _process(self): #print "PROCESSING..." htdocsDir = Config.getInstance().getHtdocsDir() logoDir = "/css/ICTP/images/sponsor-logo/" #try: if 1: # lets UPLOAD the file and SAVE it in a custom FOLDER fileEntry = self._reqParams['file'] fileName = fileEntry.filename filePath = htdocsDir + logoDir + fileName fileData = fileEntry.read() if os.path.isfile(filePath): return json.dumps({'status': 'KO','info': 'ERROR: File EXIST, delete it first.'}) file = open(filePath, "wb") file.write(fileData) file.close() #except: # return json.dumps({'status': 'KO','info': 'ERROR: File NOT uploaded'}) return json.dumps({'status': 'OK','info': fileName})
def _process_POST(self): # If general section if self._section.getId().isdigit(): # Enable field if moved out side of the disabled fields if (self._sectionEndPos == 0 or not self._section.getSortedFields()[ self._sectionEndPos].isDisabled()): self._field.setDisabled(False) else: if self._field.isLocked('disable'): return json.dumps(self._section.fossilize()) #w = Warning(_('Warning'), _('This field can\'t be disabled')) #return ResultWithWarning(self._section.fossilize(), w).fossilize() else: self._field.setDisabled(True) self._section.addToSortedFields(self._field, self._sectionEndPos) else: raise MaKaCError( _("Section id: " + self._section.getId() + " doesn't support field move")) return json.dumps(self._section.fossilize())
def _getAnswer(self): ch = conference.ConferenceHolder() conf = ch.getById(self._confId) pValue = -1 # Public if self._action == 'restrict': pValue = 1 if self._action == 'inherit': pValue = 0 if self._action == 'noAction': return json.dumps({'status': 'KO', 'info': 'No action taken'}) # set ALL sessions for session in conf.getSessionList(): session.setProtection(pValue) for contribution in session.getContributionList(): contribution.setProtection(pValue) contribution.notifyModification() # set all Contributions for contribution in conf.getContributionList(): contribution.setProtection(pValue) contribution.notifyModification() # note: Breaks do not have protection level return json.dumps({'status': 'OK', 'info': 'ok'})
def _process(self): # We will need to pickle the data back into JSON user = self.getAW().getUser() if not self._loggedIn: return json.dumps({ 'status': 'ERROR', 'info': { 'type': 'noReport', 'title': '', 'explanation': _('You are currently not authenticated. Please log in again.') } }, textarea=True) try: owner = self._target title = owner.getTitle() if type(owner) == Conference: ownerType = "event" elif type(owner) == Session: ownerType = "session" elif type(owner) == Contribution: ownerType = "contribution" elif type(owner) == SubContribution: ownerType = "subcontribution" else: ownerType = "" text = " in %s %s" % (ownerType,title) except: owner = None text = "" try: if len(self._errorList) > 0: raise Exception('Operation aborted') else: mat, status, info = self._addMaterialType(text, user) if status == "OK": for entry in info: entry['material'] = mat.getId() except Exception, e: status = "ERROR" if 'file' in self._params: del self._params['file'] info = {'message': self._errorList or " %s: %s" % (e.__class__.__name__, str(e)), 'code': '0', 'requestInfo': self._params} Logger.get('requestHandler').exception('Error uploading file')
def getVars(self): vars = wcomponents.WTemplated.getVars(self) tz = self._session.getTimezone() vars["timezone"] = tz vars['ttdata'] = json.dumps( schedule.ScheduleToJson.process(self._session.getSchedule(), tz, None, days=None, mgmtMode=True)) eventInfo = fossilize(self._session.getConference(), IConferenceEventInfoFossil, tz=tz) eventInfo['timetableSession'] = fossilize(self._session, ISessionFossil, tz=tz) eventInfo['isCFAEnabled'] = self._session.getConference( ).getAbstractMgr().isActive() vars['eventInfo'] = json.dumps(eventInfo) return vars
def _process(self): user = self._aw.getUser() reg_data = {} if user is not None: if user.isRegisteredInConf(self._conf): registrant = user.getRegistrantById(self._conf.getId()) reg_data = registrant.fossilize() else: personalData = self._regForm.getPersonalData() reg_data["avatar"] = personalData.getFormValuesFromAvatar(user) reg_data["avatar"].setdefault("sessionList", [{}, {}]) else: reg_data["avatar"] = {"sessionList": [{}, {}]} return json.dumps(reg_data)
def _process(self): if self._target.isClosed(): return json.dumps({'status': 'error'}, textarea=True) else: if self._tempFilePath is not None: if self._conf.getBadgeTemplateManager().hasTemplate( self.__templateId): backgroundId = self._conf.getBadgeTemplateManager( ).getTemplateById( self.__templateId).addTempBackgroundFilePath( self._tempFilePath) else: key = "tempBackground-%s-%s" % (self._conf.id, self.__templateId) value = session.get(key) if value is None: tempFilePathList = PersistentList() tempFilePathList.append(self._tempFilePath) session[key] = tempFilePathList backgroundId = 0 else: value.append(self._tempFilePath) backgroundId = len(value) - 1 session.modified = True return json.dumps( { 'status': 'OK', 'id': backgroundId, 'url': str( urlHandlers.UHConfModifBadgeGetBackground.getURL( self._conf, self.__templateId, backgroundId)) }, textarea=True)
def _process( self ): import random self._id = str(random.random()*random.randint(1,32768)) if self._templatefd == None: return {'status': 'ERROR'} else: self._conf.getConfPaperReview().setTemplate(self._name, self._description, self._format, self._templatefd, self._id, self._ext) #self._redirect( urlHandlers.UHConfModifReviewingPaperSetup.getURL( self._conf ) ) return json.dumps({ 'status': 'OK', 'info': { 'name': self._name, 'description': self._description, 'format': self._format, 'id': self._id } }, textarea=True)
def _getAnswer(self): ch = conference.ConferenceHolder() conf = ch.getById(self._confId) # remove ALL sessions for session in conf.getSessionList(): conf.removeSession(session, deleteContributions=True) # remove all Contributions for contribution in conf.getContributionList(): conf.removeContribution(contribution) # remove all Breaks for b in conf.getBreakList(): b.delete() return json.dumps({'status': 'OK', 'info': 'ok'})
def _getAnswer(self): consumers = dict((consumer.getName(), consumer) for consumer in ConsumerHolder().getList()) if "indico-checkin" not in consumers: raise NoReportError( _("There is no indico-checkin consumer key for OAuth")) # QRCode (Version 6 with error correction L can contain up to 106 bytes) qr = QRCode(version=6, error_correction=constants.ERROR_CORRECT_M, box_size=4, border=1) oauth_checkin = consumers["indico-checkin"] config = Config.getInstance() baseURL = config.getBaseSecureURL() if config.getBaseSecureURL( ) else config.getBaseURL() qr_data = { "event_id": self._conf.getId(), "title": self._conf.getTitle(), "date": format_date(self._conf.getAdjustedStartDate()), "server": { "baseUrl": baseURL, "consumerKey": oauth_checkin.getId(), "consumerSecret": oauth_checkin.getSecret(), } } json_qr_data = json.dumps(qr_data) qr.add_data(json_qr_data) qr.make(fit=True) qr_img = qr.make_image() output = StringIO() qr_img._img.save(output, format="png") im_data = output.getvalue() return 'data:image/png;base64,{0}'.format(base64.b64encode(im_data))
def _getAnswer(self): config = Config.getInstance() checkin_app_client_id = config.getCheckinAppClientId() if checkin_app_client_id is None: raise NoReportError(_("indico-checkin client_id is not defined in the Indico configuration")) checkin_app = OAuthApplication.find_first(client_id=checkin_app_client_id) if checkin_app is None: raise NoReportError( _("indico-checkin is not registered as an OAuth application with client_id {}").format( checkin_app_client_id ) ) # QRCode (Version 6 with error correction L can contain up to 106 bytes) qr = QRCode(version=6, error_correction=constants.ERROR_CORRECT_M, box_size=4, border=1) baseURL = config.getBaseSecureURL() if config.getBaseSecureURL() else config.getBaseURL() qr_data = { "event_id": self._conf.getId(), "title": self._conf.getTitle(), "date": format_date(self._conf.getAdjustedStartDate()), "server": { "baseUrl": baseURL, "consumerKey": checkin_app.client_id, "auth_url": url_for("oauth.oauth_authorize", _external=True), "token_url": url_for("oauth.oauth_token", _external=True), }, } json_qr_data = json.dumps(qr_data) qr.add_data(json_qr_data) qr.make(fit=True) qr_img = qr.make_image() output = StringIO() qr_img._img.save(output, format="png") im_data = output.getvalue() return "data:image/png;base64,{0}".format(base64.b64encode(im_data))
def _getAnswer(self): consumers = dict((consumer.getName(), consumer) for consumer in ConsumerHolder().getList()) if "indico-checkin" not in consumers: raise NoReportError(_("There is no indico-checkin consumer key for OAuth")) # QRCode (Version 6 with error correction L can contain up to 106 bytes) qr = QRCode( version=6, error_correction=constants.ERROR_CORRECT_M, box_size=4, border=1 ) oauth_checkin = consumers["indico-checkin"] config = Config.getInstance() baseURL = config.getBaseSecureURL() if config.getBaseSecureURL() else config.getBaseURL() qr_data = {"event_id": self._conf.getId(), "title": self._conf.getTitle(), "date": format_date(self._conf.getAdjustedStartDate()), "server": {"baseUrl": baseURL, "consumerKey": oauth_checkin.getId(), "consumerSecret": oauth_checkin.getSecret(), } } json_qr_data = json.dumps(qr_data) qr.add_data(json_qr_data) qr.make(fit=True) qr_img = qr.make_image() output = StringIO() qr_img._img.save(output, format="png") im_data = output.getvalue() return 'data:image/png;base64,{0}'.format(base64.b64encode(im_data))
def test_connect_room_force(httpretty, room_name, service_type, connected, data): RavemPlugin.settings.set("api_endpoint", RAVEM_TEST_API_ENDPOINT) RavemPlugin.settings.set("polling_limit", 3) RavemPlugin.settings.set("polling_interval", 100) service_api = get_api(service_type) vc_room_id = service_api.get_room_id(data) different_vc_room = "different_vc_room" httpretty.register_uri( httpretty.GET, RAVEM_TEST_API_ENDPOINT + "rooms/details", status=200, content_type="application/json", responses=[ httpretty.Response(status=200, content_type='application/json', body=json.dumps({ "roomName": room_name, "deviceType": service_type, "services": [{ "status": connected, "eventName": different_vc_room, "name": "videoconference", }], })) ] * RavemPlugin.settings.get("polling_limit") + [ httpretty.Response(status=200, content_type='application/json', body=json.dumps({ "roomName": room_name, "deviceType": service_type, "services": [{ "status": False, "eventName": None, "name": "videoconference", }], })) ]) httpretty.register_uri( httpretty.POST, RAVEM_TEST_API_ENDPOINT + service_type + "/disconnect", status=200, content_type="application/json", body=json.dumps({"result": "OK"}), ) httpretty.register_uri( httpretty.POST, RAVEM_TEST_API_ENDPOINT + service_type + "/connect", status=200, content_type="application/json", body=json.dumps({"result": "OK"}), ) vc_room = MagicMock() vc_room.type = service_type vc_room.data = data connect_room(room_name, vc_room, force=True) # status, disconnect, polling attempts and connect number_of_requests = 2 + RavemPlugin.settings.get("polling_limit") + 1 assert len(httpretty.httpretty.latest_requests) == number_of_requests disconnect_request = httpretty.httpretty.latest_requests[1] assert disconnect_request.path.startswith(RAVEM_TEST_PATH + service_type + "/disconnect") assert disconnect_request.parsed_body == {"roomName": room_name} request = httpretty.last_request() assert request.path.startswith(RAVEM_TEST_PATH + service_type + "/connect") assert request.parsed_body == { "roomName": room_name, "meetingId": vc_room_id }
def encode(obj): return dumps(obj, ensure_ascii=True)
def getJSONForm(self): """Returns the current locator data as a JSON string. """ return dumps(self.data)
def _process(self): if self.spkUniqueId and self.file: self.uploadProcess() return json.dumps({'status': 'OK'}, textarea=True)
def _process_POST(self): # Move field to the first position self._section.addToSortedFields(self._field) self._field.setDisabled(False) return json.dumps(self._field.fossilize())
class RHSubmitMaterialBase(object): def __init__(self): self._tempFiles = {} self._repositoryIds = None self._errorList = [] self._cfg = Config.getInstance() def _getNewTempFile(self): cfg = Config.getInstance() tempPath = cfg.getUploadedFilesTempDir() tempFileName = tempfile.mkstemp(suffix="Indico.tmp", dir=tempPath)[1] return tempFileName #XXX: improve routine to avoid saving in temporary file def _saveFileToTemp(self, fs): if fs not in self._tempFiles: fileName = self._getNewTempFile() fs.save(fileName) self._tempFiles[fs] = fileName self._tempFilesToDelete.append(fileName) return self._tempFiles[fs] def _checkProtection(self): self._loggedIn = True if self._getUser() == None and ( isinstance(self._target, Category) or not self._target.getConference().canKeyModify(self._aw)): self._loggedIn = False elif self._getUser() and isinstance( self._target, Conference) and self._target.getAccessController( ).canUserSubmit(self._getUser()): self._loggedIn = True else: super(RHSubmitMaterialBase, self)._checkProtection() def _checkParams(self, params): self._params = params self._action = "" self._overwrite = False #if request has already been handled (DB conflict), then we keep the existing files list self._files = [] self._links = [] self._topdf = "topdf" in params self._displayName = params.get("displayName", "").strip() self._uploadType = params.get("uploadType", "") self._materialId = params.get("materialId", "") self._description = params.get("description", "") self._statusSelection = int(params.get("statusSelection", 1)) self._visibility = int(params.get("visibility", 0)) self._password = params.get("password", "") self._doNotSanitizeFields.append("password") self._userList = json.loads(params.get("userList", "[]")) maxUploadFilesTotalSize = float(self._cfg.getMaxUploadFilesTotalSize()) if self._uploadType == "file": if isinstance(params["file"], list): files = params["file"] self._displayName = "" self._description = "" else: files = [params["file"]] for fileUpload in files: if type(fileUpload) != str and fileUpload.filename.strip( ) != "": fDict = {} fDict["fileName"] = fileUpload.filename.encode("utf-8") estimSize = request.content_length if maxUploadFilesTotalSize and estimSize > ( maxUploadFilesTotalSize * BYTES_1MB): # if file is too big, do not save it in disk fDict["filePath"] = '' fDict["size"] = estimSize else: fDict["filePath"] = self._saveFileToTemp(fileUpload) fDict["size"] = os.path.getsize(fDict["filePath"]) self._setErrorList(fDict) self._files.append(fDict) elif self._uploadType == "link": if isinstance(params["url"], list): urls = params["url"] self._displayName = "" self._description = "" else: urls = [params["url"]] matType = params.get("materialType", "") for url in urls: if not url.strip(): continue link = {} link["url"] = url link["matType"] = matType self._links.append(link) def _setErrorList(self, fileEntry): maxUploadFilesTotalSize = float(self._cfg.getMaxUploadFilesTotalSize()) if self._uploadType == "file": if "filePath" in fileEntry and not fileEntry["filePath"].strip(): self._errorList.append( _("""A valid file to be submitted must be specified. """)) if "size" in fileEntry: if fileEntry["size"] < 10: self._errorList.append( _("""The file %s seems to be empty """) % fileEntry["fileName"]) elif maxUploadFilesTotalSize and fileEntry["size"] > ( maxUploadFilesTotalSize * 1024 * 1024): self._errorList.append( _("The file size of %s exceeds the upload limit (%s Mb)" ) % (fileEntry["fileName"], maxUploadFilesTotalSize)) elif self._uploadType == "link": if not self._links[0]["url"].strip(): self._errorList.append(_("""A valid URL must be specified.""")) if self._materialId == "": self._errorList.append(_("""A material ID must be selected.""")) def _getMaterial(self, forceCreate=True): """ Returns the Material object to which the resource is being added """ registry = self._target.getMaterialRegistry() material = self._target.getMaterialById(self._materialId) if material: return material, False # there's a defined id (not new type) elif self._materialId: # get a material factory for it mf = registry.getById(self._materialId) # get a material from the material factory material = mf.get(self._target) # if the factory returns an empty material (doesn't exist) if material == None and forceCreate: # create one material = mf.create(self._target) newlyCreated = True else: newlyCreated = False return material, newlyCreated else: # else, something has gone wrong raise Exception("""A material ID must be specified.""") def _addMaterialType(self, text, user): from MaKaC.common.fossilize import fossilize from MaKaC.fossils.conference import ILocalFileExtendedFossil, ILinkFossil Logger.get('requestHandler').debug('Adding %s - request %s' % (self._uploadType, request)) mat, newlyCreated = self._getMaterial() # if the material still doesn't exist, create it if newlyCreated: protectedAtResourceLevel = False else: protectedAtResourceLevel = True resources = [] if self._uploadType in ['file', 'link']: if self._uploadType == "file": for fileEntry in self._files: resource = LocalFile() resource.setFileName(fileEntry["fileName"]) resource.setFilePath(fileEntry["filePath"]) resource.setDescription(self._description) if self._displayName == "": resource.setName(resource.getFileName()) else: resource.setName(self._displayName) if not type(self._target) is Category: log_info = { "subject": "Added file %s%s" % (fileEntry["fileName"], text) } self._target.getConference().getLogHandler().logAction( log_info, log.ModuleNames.MATERIAL) resources.append(resource) # in case of db conflict we do not want to send the file to conversion again, nor re-store the file elif self._uploadType == "link": for link in self._links: resource = Link() resource.setURL(link["url"]) resource.setDescription(self._description) if self._displayName == "": resource.setName(resource.getURL()) else: resource.setName(self._displayName) if not type(self._target) is Category: log_info = { "subject": "Added link %s%s" % (resource.getURL(), text) } self._target.getConference().getLogHandler().logAction( log_info, log.ModuleNames.MATERIAL) resources.append(resource) status = "OK" info = resources else: status = "ERROR" info = "Unknown upload type" return mat, status, info # forcedFileId - in case there is a conflict, use the file that is # already stored repoIDs = [] for i, resource in enumerate(resources): if self._repositoryIds: mat.addResource(resource, forcedFileId=self._repositoryIds[i]) else: mat.addResource(resource, forcedFileId=None) #apply conversion if self._topdf and not isinstance(resource, Link): file_ext = os.path.splitext( resource.getFileName())[1].strip().lower() if fileConverter.CDSConvFileConverter.hasAvailableConversionsFor( file_ext): # Logger.get('conv').debug('Queueing %s for conversion' % resource.getFilePath()) fileConverter.CDSConvFileConverter.convert( resource.getFilePath(), 'pdf', mat) resource.setPDFConversionRequestDate(nowutc()) # store the repo id, for files if isinstance(resource, LocalFile) and self._repositoryIds is None: repoIDs.append(resource.getRepositoryId()) if protectedAtResourceLevel: protectedObject = resource else: protectedObject = mat mat.setHidden(self._visibility) mat.setAccessKey(self._password) protectedObject.setProtection(self._statusSelection) for userElement in self._userList: if 'isGroup' in userElement and userElement['isGroup']: avatar = GroupHolder().getById(userElement['id']) else: avatar = AvatarHolder().getById(userElement['id']) protectedObject.grantAccess(avatar) self._topdf = False if self._repositoryIds is None: self._repositoryIds = repoIDs return mat, status, fossilize( info, { "MaKaC.conference.Link": ILinkFossil, "MaKaC.conference.LocalFile": ILocalFileExtendedFossil }) def _process(self): # We will need to pickle the data back into JSON user = self.getAW().getUser() if not self._loggedIn: return json.dumps( { 'status': 'ERROR', 'info': { 'type': 'noReport', 'title': '', 'explanation': _('You are currently not authenticated. Please log in again.' ) } }, textarea=True) try: owner = self._target title = owner.getTitle() if type(owner) == Conference: ownerType = "event" elif type(owner) == Session: ownerType = "session" elif type(owner) == Contribution: ownerType = "contribution" elif type(owner) == SubContribution: ownerType = "subcontribution" else: ownerType = "" text = " in %s %s" % (ownerType, title) except: owner = None text = "" try: if len(self._errorList) > 0: raise Exception('Operation aborted') else: mat, status, info = self._addMaterialType(text, user) if status == "OK": for entry in info: entry['material'] = mat.getId() except Exception, e: status = "ERROR" if 'file' in self._params: del self._params['file'] info = { 'message': self._errorList or " %s: %s" % (e.__class__.__name__, str(e)), 'code': '0', 'requestInfo': self._params } Logger.get('requestHandler').exception('Error uploading file') return json.dumps({'status': status, 'info': info}, textarea=True)
except HtmlForbiddenTag,e: res = self._processRestrictedHTML(e) DBMgr.getInstance().endRequest(False) except MaKaCError, e: res = self._processGeneralError( e ) DBMgr.getInstance().endRequest(False) if Config.getInstance().getPropagateAllExceptions(): raise except ValueError, e: res = self._processGeneralError( e ) DBMgr.getInstance().endRequest(False) if Config.getInstance().getPropagateAllExceptions(): raise except OAuthError, e: from indico.util import json res = json.dumps(e.fossilize()) header = oauth.build_authenticate_header(realm=Config.getInstance().getBaseSecureURL()) self._responseUtil.headers.extend(header) self._responseUtil.content_type = 'application/json' self._responseUtil.status = e.code DBMgr.getInstance().endRequest(False) except Exception, e: res = self._processUnexpectedError(e) self._endRequestSpecific2RH(False) DBMgr.getInstance().endRequest(False) if Config.getInstance().getEmbeddedWebserver() or Config.getInstance().getPropagateAllExceptions(): # Re-raise to get the nice werkzeug exception view raise #cancels any redirection
def getJSONForm( self ): """Returns the current locator data as a JSON string. """ return dumps(self.data)
class RHSubmitMaterialBase(object): def __init__(self): self._tempFiles = {} self._repositoryIds = None self._errorList = [] self._cfg = Config.getInstance() def _getNewTempFile(self): cfg = Config.getInstance() tempPath = cfg.getUploadedFilesTempDir() tempFileName = tempfile.mkstemp(suffix="Indico.tmp", dir=tempPath)[1] return tempFileName #XXX: improve routine to avoid saving in temporary file def _saveFileToTemp(self, fs): if fs not in self._tempFiles: fileName = self._getNewTempFile() fs.save(fileName) self._tempFiles[fs] = fileName self._tempFilesToDelete.append(fileName) return self._tempFiles[fs] def _checkProtection(self): self._loggedIn = True if (self._getUser() is None and (isinstance(self._target, Category) or not self._target.getConference().canKeyModify())): self._loggedIn = False elif (self._getUser() and isinstance(self._target, Conference) and self._target.as_event.can_manage(session.user, 'submit')): self._loggedIn = True else: super(RHSubmitMaterialBase, self)._checkProtection() def _checkParams(self, params): self._params = params self._action = "" self._overwrite = False #if request has already been handled (DB conflict), then we keep the existing files list self._files = [] self._links = [] self._displayName = params.get("displayName", "").strip() self._uploadType = params.get("uploadType", "") self._materialId = params.get("materialId", "") assert self._materialId == 'reviewing' self._description = params.get("description", "") self._statusSelection = int(params.get("statusSelection", 1)) self._visibility = int(params.get("visibility", 0)) self._password = params.get("password", "") self._doNotSanitizeFields.append("password") self._userList = json.loads(params.get("userList", "[]")) maxUploadFilesTotalSize = float(self._cfg.getMaxUploadFilesTotalSize()) if self._uploadType == "file": if isinstance(params["file"], list): files = params["file"] self._displayName = "" self._description = "" else: files = [params["file"]] for fileUpload in files: if type(fileUpload) != str and fileUpload.filename.strip( ) != "": fDict = {} fDict["fileName"] = fileUpload.filename.encode("utf-8") estimSize = request.content_length if maxUploadFilesTotalSize and estimSize > ( maxUploadFilesTotalSize * BYTES_1MB): # if file is too big, do not save it in disk fDict["filePath"] = '' fDict["size"] = estimSize else: fDict["filePath"] = self._saveFileToTemp(fileUpload) fDict["size"] = os.path.getsize(fDict["filePath"]) self._setErrorList(fDict) self._files.append(fDict) elif self._uploadType == "link": if isinstance(params["url"], list): urls = params["url"] self._displayName = "" self._description = "" else: urls = [params["url"]] matType = params.get("materialType", "") for url in urls: if not url.strip(): continue link = {} link["url"] = url link["matType"] = matType self._links.append(link) def _setErrorList(self, fileEntry): maxUploadFilesTotalSize = float(self._cfg.getMaxUploadFilesTotalSize()) if self._uploadType == "file": if "filePath" in fileEntry and not fileEntry["filePath"].strip(): self._errorList.append( _("""A valid file to be submitted must be specified. """)) if "size" in fileEntry: if fileEntry["size"] < 10: self._errorList.append( _("""The file %s seems to be empty """) % fileEntry["fileName"]) elif maxUploadFilesTotalSize and fileEntry["size"] > ( maxUploadFilesTotalSize * 1024 * 1024): self._errorList.append( _("The file size of %s exceeds the upload limit (%s Mb)" ) % (fileEntry["fileName"], maxUploadFilesTotalSize)) elif self._uploadType == "link": if not self._links[0]["url"].strip(): self._errorList.append(_("""A valid URL must be specified.""")) if self._materialId == "": self._errorList.append(_("""A material ID must be selected.""")) def _getMaterial(self, forceCreate=True): """ Returns the Material object to which the resource is being added """ assert self._materialId == 'reviewing' # only reviewing still uses this... material = reviewing_factory_get(self._target) if material is None and forceCreate: material = reviewing_factory_create(self._target) newlyCreated = True else: newlyCreated = False return material, newlyCreated def _addMaterialType(self, text, user): from MaKaC.common.fossilize import fossilize from MaKaC.fossils.conference import ILocalFileExtendedFossil, ILinkFossil Logger.get('requestHandler').debug('Adding %s - request %s' % (self._uploadType, request)) mat, newlyCreated = self._getMaterial() # if the material still doesn't exist, create it if newlyCreated: protectedAtResourceLevel = False else: protectedAtResourceLevel = True resources = [] assert self._uploadType == "file" for fileEntry in self._files: resource = LocalFile() resource.setFileName(fileEntry["fileName"]) resource.setFilePath(fileEntry["filePath"]) resource.setDescription(self._description) if self._displayName == "": resource.setName(resource.getFileName()) else: resource.setName(self._displayName) resources.append(resource) status = "OK" info = resources # forcedFileId - in case there is a conflict, use the file that is # already stored repoIDs = [] for i, resource in enumerate(resources): if self._repositoryIds: mat.addResource(resource, forcedFileId=self._repositoryIds[i]) else: mat.addResource(resource, forcedFileId=None) # store the repo id, for files if isinstance(resource, LocalFile) and self._repositoryIds is None: repoIDs.append(resource.getRepositoryId()) if protectedAtResourceLevel: protectedObject = resource else: protectedObject = mat mat.setHidden(self._visibility) mat.setAccessKey(self._password) protectedObject.setProtection(self._statusSelection) for principal in map(principal_from_fossil, self._userList): protectedObject.grantAccess(principal) if self._repositoryIds is None: self._repositoryIds = repoIDs return mat, status, fossilize( info, { "MaKaC.conference.Link": ILinkFossil, "MaKaC.conference.LocalFile": ILocalFileExtendedFossil }) def _process(self): # We will need to pickle the data back into JSON user = self.getAW().getUser() if not self._loggedIn: return json.dumps( { 'status': 'ERROR', 'info': { 'type': 'noReport', 'title': '', 'explanation': _('You are currently not authenticated. Please log in again.' ) } }, textarea=True) try: owner = self._target title = owner.getTitle() if type(owner) == Conference: ownerType = "event" elif type(owner) == Session: ownerType = "session" elif type(owner) == Contribution: ownerType = "contribution" elif type(owner) == SubContribution: ownerType = "subcontribution" else: ownerType = "" text = " in %s %s" % (ownerType, title) except: owner = None text = "" try: if len(self._errorList) > 0: raise Exception('Operation aborted') else: mat, status, info = self._addMaterialType(text, user) if status == "OK": for entry in info: entry['material'] = mat.getId() except Exception, e: status = "ERROR" if 'file' in self._params: del self._params['file'] info = { 'message': self._errorList or " %s: %s" % (e.__class__.__name__, str(e)), 'code': '0', 'requestInfo': self._params } Logger.get('requestHandler').exception('Error uploading file') return json.dumps({'status': status, 'info': info}, textarea=True)
def _process_POST(self): self._field.setValues(self._updateFieldData) return json.dumps(self._field.fossilize())
def _process_DELETE(self): if self._field.isLocked('delete'): raise MaKaCError(_("Deleted action couldn't be perform")) self._section.removeField(self._field) return json.dumps(self._section.fossilize())
def offlineRequest(rh, method, params = {}): return dumps(processRequest(method, params, rh._req))
def _execute(self, fossil): return json.dumps(fossil, pretty=self.pretty)
def offlineRequest(rh, method, params = {}): return dumps(processRequest(method, params, rh._req, True))
def _process(self): # We will need to pickle the data back into JSON user = self.getAW().getUser() if not self._loggedIn: return json.dumps( { 'status': 'ERROR', 'info': { 'type': 'noReport', 'title': '', 'explanation': _('You are currently not authenticated. Please log in again.' ) } }, textarea=True) try: owner = self._target title = owner.getTitle() if type(owner) == Conference: ownerType = "event" elif type(owner) == Session: ownerType = "session" elif type(owner) == Contribution: ownerType = "contribution" elif type(owner) == SubContribution: ownerType = "subcontribution" else: ownerType = "" text = " in %s %s" % (ownerType, title) except: owner = None text = "" try: if len(self._errorList) > 0: raise Exception('Operation aborted') else: mat, status, info = self._addMaterialType(text, user) if status == "OK": for entry in info: entry['material'] = mat.getId() except Exception, e: status = "ERROR" if 'file' in self._params: del self._params['file'] info = { 'message': self._errorList or " %s: %s" % (e.__class__.__name__, str(e)), 'code': '0', 'requestInfo': self._params } Logger.get('requestHandler').exception('Error uploading file')
def __call__(self, fossil): return json.dumps(fossil, pretty=self.pretty)