def POST(self, key): i = web.input(v=None, _method="GET") v = i.v and safeint(i.v, None) edition = web.ctx.site.get(key, v) if edition is None: raise web.notfound() if edition.works: work = edition.works[0] else: work = None add = (edition.revision == 1 and work and work.revision == 1 and work.edition_count == 1) try: helper = SaveBookHelper(work, edition) helper.save(web.input()) if add: add_flash_message("info", utils.get_message("flash_book_added")) else: add_flash_message("info", utils.get_message("flash_book_updated")) raise web.seeother(edition.url()) except (ClientException, ValidationException), e: raise add_flash_message('error', str(e)) return self.GET(key)
def test_get_message(self): test_sock_ok = TestSocket(self.test_success_receive) test_sock_err = TestSocket(self.test_error_receive) self.assertEqual(get_message(test_sock_ok, self.CONFIGS), self.test_success_receive) self.assertEqual(get_message(test_sock_err, self.CONFIGS), self.test_error_receive)
def get_data_message(payload, secrets, symmetricAlgorithm): """ Returns the decrypted message of the encrypted data sent by a device. This message contains sensor values from the device. """ message = "" if secrets != None and symmetricAlgorithm != None: key = secrets.get("1", "") if key != "": encriptor = utils.modify_encriptor(key, symmetricAlgorithm) message, trustworthy = utils.get_message(payload, encriptor, HASH_KEY) if message == "": key = secrets.get("0", "") if key != "": encriptor = utils.modify_encriptor(key, symmetricAlgorithm) message, trustworthy = utils.get_message( payload,\ encriptor, HASH_KEY ) if not trustworthy: message = "" return message
def POST(self, key): i = web.input(v=None, _method="GET") if spamcheck.is_spam(): return render_template( "message.html", "Oops", 'Something went wrong. Please try again later.') recap_plugin_active = is_plugin_enabled('recaptcha') #check to see if account is more than two years old old_user = False user = web.ctx.site.get_user() account = user and user.get_account() if account: create_dt = account.creation_time() now_dt = datetime.datetime.utcnow() delta = now_dt - create_dt if delta.days > 365 * 2: old_user = True if recap_plugin_active and not old_user: public_key = config.plugin_recaptcha.public_key private_key = config.plugin_recaptcha.private_key recap = recaptcha.Recaptcha(public_key, private_key) if not recap.validate(): return 'Recaptcha solution was incorrect. Please <a href="javascript:history.back()">go back</a> and try again.' v = i.v and safeint(i.v, None) edition = web.ctx.site.get(key, v) if edition is None: raise web.notfound() if edition.works: work = edition.works[0] else: work = None add = (edition.revision == 1 and work and work.revision == 1 and work.edition_count == 1) try: helper = SaveBookHelper(work, edition) helper.save(web.input()) if add: add_flash_message("info", utils.get_message("flash_book_added")) else: add_flash_message("info", utils.get_message("flash_book_updated")) raise web.seeother(edition.url()) except (ClientException, ValidationException), e: add_flash_message('error', str(e)) return self.GET(key)
def test_get_message(self): """ Тест функции приёма сообщения :return: """ test_sock_ok = TestSocket(self.test_dict_recv_ok) test_sock_err = TestSocket(self.test_dict_recv_err) # тест корректной расшифровки корректного словаря self.assertEqual(get_message(test_sock_ok), self.test_dict_recv_ok) # тест корректной расшифровки ошибочного словаря self.assertEqual(get_message(test_sock_err), self.test_dict_recv_err)
def POST(self, key): i = web.input(v=None, _method="GET") if spamcheck.is_spam(): return render_template("message.html", "Oops", 'Something went wrong. Please try again later.') recap_plugin_active = is_plugin_enabled('recaptcha') #check to see if account is more than two years old old_user = False user = web.ctx.site.get_user() account = user and user.get_account() if account: create_dt = account.creation_time() now_dt = datetime.datetime.utcnow() delta = now_dt - create_dt if delta.days > 365*2: old_user = True if recap_plugin_active and not old_user: public_key = config.plugin_recaptcha.public_key private_key = config.plugin_recaptcha.private_key recap = recaptcha.Recaptcha(public_key, private_key) if not recap.validate(): return 'Recaptcha solution was incorrect. Please <a href="javascript:history.back()">go back</a> and try again.' v = i.v and safeint(i.v, None) edition = web.ctx.site.get(key, v) if edition is None: raise web.notfound() if edition.works: work = edition.works[0] else: work = None add = (edition.revision == 1 and work and work.revision == 1 and work.edition_count == 1) try: helper = SaveBookHelper(work, edition) helper.save(web.input()) if add: add_flash_message("info", utils.get_message("flash_book_added")) else: add_flash_message("info", utils.get_message("flash_book_updated")) raise web.seeother(edition.url()) except (ClientException, ValidationException), e: add_flash_message('error', str(e)) return self.GET(key)
def no_match(self, i): # TODO: Handle add-new-author work = new_doc("/type/work", title=i.title, authors=[{"author": {"key": i.author_key}}] ) comment = utils.get_message("comment_new_work") work._save(comment) edition = self._make_edition(work, i) comment = utils.get_message("comment_new_edition") edition._save(comment) raise web.seeother(edition.url("/edit?mode=add-work"))
def test_register_and_update_badge(client, badge_keys, conference_key): """ Test to successfully register badge, and also update badge information. """ badge = {'name': 'cybaix'} response = post_message(client, badge_keys[1], '/badge/1', badge) assert response.status_code == 200 saved_badge = get_message(client, conference_key, '/badge/1') assert saved_badge == badge # Test 'doh' scenario and ensure attendees can update information badge = {'name': 'mark'} response = post_message(client, badge_keys[1], '/badge/1', badge) assert response.status_code == 200 saved_badge = get_message(client, conference_key, '/badge/1') assert saved_badge == badge
def top_secret(satellites: Satellites): """Top Secret Service: Calculates the position of the sender of the message based on the distance between the satellites and the sender and removes noise from the message.""" satellites = satellites.satellites dirt_message = [] distances = [] satellites_must_have_a_legth_of_three(satellites) for satellite in satellites: find_satellite_by_name(satellite.name) dirt_message.append(satellite.message) distances.append(satellite.distance) x, y = get_location(distances) message = get_message(dirt_message) data = { 'position': { 'x': x, 'y': y, }, 'message': message } return data
def delivery_time_handler(update, context): try: logger.info(f'delivery_time_handler: {update, context}') chat = utils.get_chat(context, update) message = utils.get_message(context, update) chat_id = chat.effective_chat.id context.bot.editMessageReplyMarkup( chat_id=message.chat_id, message_id=message.message_id, reply_markup=InlineKeyboardMarkup( utils.generate_time_suggest_reply_keyb( chat_id, utils.get_delivery_time_from_callback( chat.callback_query.data) )), parse_mode=ParseMode.MARKDOWN ) context.bot.send_message( chat_id=utils.get_user_id_from_callback(chat.callback_query.data), text=f'Ваш заказ будет доставлен в течении ' f'{utils.get_delivery_time_from_callback(chat.callback_query.data)} ' f'минут', reply_markup=utils.get_ok_ko_markup() ) except Exception as ex: logger.warning(f'delivery_time_handler: {ex}')
def POST(self, key): i = web.input(v=None, _method="GET") recap_plugin_active = 'recaptcha' in config.get('plugins') if recap_plugin_active: public_key = config.plugin_recaptcha.public_key private_key = config.plugin_recaptcha.private_key recap = recaptcha.Recaptcha(public_key, private_key) if not recap.validate(): return 'Recaptcha solution was incorrect. Please <a href="javascript:history.back()">go back</a> and try again.' v = i.v and safeint(i.v, None) work = web.ctx.site.get(key, v) if work is None: raise web.notfound() try: helper = SaveBookHelper(work, None) helper.save(web.input()) add_flash_message("info", utils.get_message("flash_work_updated")) raise web.seeother(work.url()) except (ClientException, ValidationException), e: add_flash_message('error', str(e)) return self.GET(key)
def POST(self, key): i = web.input(v=None, _method="GET") if spamcheck.is_spam(): return render_template( "message.html", "Oops", 'Something went wrong. Please try again later.') recap = get_recaptcha() if recap and not recap.validate(): return render_template( "message.html", 'Recaptcha solution was incorrect', 'Please <a href="javascript:history.back()">go back</a> and try again.' ) v = i.v and safeint(i.v, None) work = web.ctx.site.get(key, v) if work is None: raise web.notfound() try: helper = SaveBookHelper(work, None) helper.save(web.input()) add_flash_message("info", utils.get_message("flash_work_updated")) raise web.seeother(work.url()) except (ClientException, ValidationException) as e: add_flash_message('error', str(e)) return self.GET(key)
def read_messages(client): while True: # читаем сообщение print('Ожидание сообщения') message = get_message(client) # там должно быть сообщение всем print(message['message'])
def main(): global CONFIGS CONFIGS = load_configs(is_server=False) try: server_address = sys.argv[1] server_port = int(sys.argv[2]) if not 65535 >= server_port >= 1024: raise ValueError except IndexError: server_address = CONFIGS.get('DEFAULT_IP_ADDRESS') server_port = CONFIGS.get('DEFAULT_PORT') except ValueError: CLIENT_LOGGER.critical( f'The port should be specified in the range of (1024, 65535)') print('The port should be in the range of 1024 and 65535') sys.exit(1) transport = socket.socket(socket.AF_INET, socket.SOCK_STREAM) transport.connect((server_address, server_port)) presence_message = create_presence_message('Guest', CONFIGS) CLIENT_LOGGER.info(f'Sending a message to the server') send_message(transport, presence_message, CONFIGS) try: response = get_message(transport, CONFIGS) handled_response = handle_response(response, CONFIGS) CLIENT_LOGGER.debug(f'The response were handled: {response}') CLIENT_LOGGER.info(f'The response were handled: {handled_response}') print(f'The response from the server: {response}') print(handled_response) except (ValueError, json.JSONDecodeError): CLIENT_LOGGER.critical(f'An error during decoding of server message') print('Error message decoding ')
def POST(self, key): i = web.input(v=None, _method="GET") if spamcheck.is_spam(): return render_template("message.html", "Oops", 'Something went wrong. Please try again later.') recap = get_recaptcha() if recap and not recap.validate(): return render_template("message.html", 'Recaptcha solution was incorrect', 'Please <a href="javascript:history.back()">go back</a> and try again.' ) v = i.v and safeint(i.v, None) work = web.ctx.site.get(key, v) if work is None: raise web.notfound() try: helper = SaveBookHelper(work, None) helper.save(web.input()) add_flash_message("info", utils.get_message("flash_work_updated")) raise web.seeother(work.url()) except (ClientException, ValidationException) as e: add_flash_message('error', str(e)) return self.GET(key)
def main(): global CONFIGS CONFIGS = load_configs(is_server=False) try: server_address = sys.argv[1] server_port = int(sys.argv[2]) if not 65535 >= server_port >= 1024: raise ValueError except IndexError: server_address = CONFIGS.get('DEFAULT_IP_ADDRESS') server_port = CONFIGS.get('DEFAULT_PORT') except ValueError: print('The port should be in the range of 1024 and 65535') sys.exit(1) transport = socket.socket(socket.AF_INET, socket.SOCK_STREAM) transport.connect((server_address, server_port)) presence_message = create_presence_message('Guest') send_message(transport, presence_message, CONFIGS) try: response = get_message(transport, CONFIGS) handled_response = handle_response(response) print(f'The response from the server: {response}') print(handled_response) except (ValueError, json.JSONDecodeError): print('Error message decoding ')
def no_match(self, saveutil, i): """ Action to take when no matches are found. Creates and saves both a Work and Edition. Redirects the user to the work/edition edit page in `add-work` mode. :param DocSaveHelper saveutil: :param web.utils.Storage i: :rtype: None """ # Any new author has been created and added to # saveutil, and author_key added to i work = new_doc("/type/work", title=i.title, authors=[{"author": {"key": i.author_key}}] ) edition = self._make_edition(work, i) saveutil.save(work) saveutil.save(edition) comment = utils.get_message("comment_add_book") saveutil.commit(action="add-book", comment=comment) raise web.seeother(edition.url("/edit?mode=add-work"))
def update_chat(): last_update = time.time() while True: if time.time() - last_update > 1: serv_message = get_message(client) if serv_message: print('{} написал: {}'.format(serv_message['user'], serv_message['message']))
def find_matches(self, saveutil, i): """Tries to find an edition or a work or multiple works that match the given input data. Case#1: No match. None is returned. Case#2: Work match but not editon. Work is returned. Case#3: Work match and edition match. Edition is returned Case#3A: Work match and multiple edition match. List of works is returned Case#4: Multiple work match. List of works is returned. """ i.publish_year = i.publish_date and self.extract_year(i.publish_date) work_key = i.get('work') # work_key is set to none-of-these when user selects none-of-these link. if work_key == 'none-of-these': return None work = work_key and web.ctx.site.get(work_key) if work: edition = self.try_edition_match(work=work, publisher=i.publisher, publish_year=i.publish_year, id_name=i.id_name, id_value=i.id_value) return edition or work if i.author_key == "__new__": a = new_doc("/type/author", name=i.author_name) comment = utils.get_message("comment_new_author") saveutil.save(a) i.author_key = a.key # since new author is created it must be a new record return None edition = self.try_edition_match(title=i.title, author_key=i.author_key, publisher=i.publisher, publish_year=i.publish_year, id_name=i.id_name, id_value=i.id_value) if edition: return edition solr = get_solr() author_key = i.author_key and i.author_key.split("/")[-1] result = solr.select({ 'title': i.title, 'author_key': author_key }, doc_wrapper=make_work, q_op="AND") if result.num_found == 0: return None elif result.num_found == 1: return result.docs[0] else: return result.docs
def POST(self): i = web.input(title="", author_name="", author_key="", publisher="", publish_date="", id_name="", id_value="", _test="false") if spamcheck.is_spam(i): return render_template( "message.html", "Oops", 'Something went wrong. Please try again later.') if not web.ctx.site.get_user(): recap = get_recaptcha() if recap and not recap.validate(): return render_template( 'message.html', 'Recaptcha solution was incorrect', 'Please <a href="javascript:history.back()">go back</a> and try again.' ) match = self.find_matches(i) saveutil = DocSaveHelper() if i.author_key == '__new__': if i._test != 'true': a = new_doc('/type/author', name=i.author_name) comment = utils.get_message('comment_new_author') # Save, but don't commit, new author. # It will be committed when the Edition is created below. saveutil.save(a) i.author_key = a.key # since new author is created it must be a new record match = None if i._test == 'true' and not isinstance(match, list): if match: return 'Matched <a href="%s">%s</a>' % (match.key, match.key) else: return 'No match found' if isinstance(match, list): # multiple matches return render_template('books/check', i, match) elif match and match.key.startswith('/books'): # work match and edition match, match is an Edition return self.work_edition_match(match) elif match and match.key.startswith('/works'): # work match but not edition work = match return self.work_match(saveutil, work, i) else: # no match return self.no_match(saveutil, i)
def work_match(self, saveutil, work, i): edition = self._make_edition(work, i) saveutil.save(edition) comment = utils.get_message("comment_add_book") saveutil.commit(comment=comment, action="add-book") raise web.seeother(edition.url("/edit?mode=add-book"))
def test_process_ans(self): server_address, server_port = DEFAULT_IP_ADDRESS, DEFAULT_PORT self.transport.connect((server_address, server_port)) self.message_to_server = create_presence() send_message(self.transport, self.message_to_server) self.answer = get_message(self.transport) self.assertEqual(self.answer[RESPONSE], 200) self.transport.close()
def POST(self, key): i = web.input(v=None, _method="GET") if spamcheck.is_spam(): return render_template( "message.html", "Oops", 'Something went wrong. Please try again later.') recap = get_recaptcha() if recap and not recap.validate(): return render_template( "message.html", 'Recaptcha solution was incorrect', 'Please <a href="javascript:history.back()">go back</a> and try again.' ) v = i.v and safeint(i.v, None) edition = web.ctx.site.get(key, v) if edition is None: raise web.notfound() if edition.works: work = edition.works[0] else: work = None add = (edition.revision == 1 and work and work.revision == 1 and work.edition_count == 1) try: helper = SaveBookHelper(work, edition) helper.save(web.input()) if add: add_flash_message("info", utils.get_message("flash_book_added")) else: add_flash_message("info", utils.get_message("flash_book_updated")) raise web.seeother(edition.url()) except ClientException as e: add_flash_message('error', e.message or e.json) return self.GET(key) except ValidationException as e: add_flash_message('error', str(e)) return self.GET(key)
def mainloop(): address = ('', 9090) clients = [] server = new_listen_socket(address) while True: try: client, addr = server.accept() msg = get_message(client) responce_200 = { 'responce': 200, 'alert': 'Соединение с сервером установлено успешно. Привет, {}!'.format(msg['user']) } print(msg) send_responce(client, responce_200) except OSError as e: pass else: print('Получен запрос на соединение от {}'.format(addr)) clients.append(client) finally: r = [] w = [] try: r, w, e = select(clients, clients, [], 0) except Exception as e: pass for some_client in r: try: # resp = [] client_msg = get_message(some_client) # resp.append(client_msg) # message = resp[0] print(client_msg) for some_client in w: send_responce(some_client, client_msg) except: print('Клиент {} отключился'.format(client.getpeername())) clients.remove(some_client)
def on_registration(client, userdata, msg): """ Method used for the registration process of a device. """ global connected, connection_failed global msg_1, msg_3, msg_5, msg_7 message, trustworthy = utils.get_message( str( msg.payload.decode( "utf-8" ) ),\ encriptor, HASH_KEY ) if message != "" and trustworthy: topic = message.get("topic", "") if topic == REGISTRATION_TOPIC: error = message.get("error", "") if error != "": # We have received an error message from a device # during registration print("ERROR: ", error) connection_failed = True # Get the id of the device that sent a message. deviceID = message.get("id", PLATFORM_ID) if not connection_failed and deviceID != PLATFORM_ID: # If it is different of the platform id, we treat it. # We do not want to read our own messages. number = int(message.get("msg", 0)) if number == 1: msg_1 = on_receive_message_1(client, userdata, message) if not msg_1: print_error_registration( "Registration request incomplete.") elif msg_1 and number == 3: msg_3 = on_receive_message_3(client, userdata, message) if not msg_3: print_error_registration("Keys does not match.") elif msg_3 and number == 5: msg_5 = on_receive_message_5(client, userdata, message) if not msg_5: print_error_registration("Code does not match.") elif msg_5 and number == 7: msg_7 = on_receive_message_7(client, userdata, message) if not msg_7: print_error_registration("Connection failed.") elif msg_7 and number == 9: # We received a confirmation of the topics reception # from the device. connected.release() if not trustworthy: print_error_registration("Corrupt message received. Closing process.")
def run(self): # Инициализация сокета self.init_socket() # Основной цикл программы сервера while True: # Ждём подключения, если таймаут вышел, будет исключение try: client, client_address = self.sock.accept() except OSError: pass else: logger.info(f'Установлено соедение с ПК {client_address}') print(f'Установлено соедение с ПК {client_address}') self.clients.append(client) recv_data_lst = [] send_data_lst = [] # Проверяем на наличие ждущих клиентов try: if self.clients: recv_data_lst, send_data_lst, err_lst = select.select( self.clients, self.clients, [], 0) except OSError as error: logger.error(f'Ошибка работы с сокетами: {error}') # Принимаем сообщения и если ошибка, исключаем клиента. if recv_data_lst: for client_with_message in recv_data_lst: try: self.process_client_message( get_message(client_with_message), client_with_message) except (OSError): # Ищем клиента в словаре клиентов и удаляем его из него и базы подключённых logger.info( f'Клиент {client_with_message.getpeername()} отключился от сервера.' ) for name in self.names: if self.names[name] == client_with_message: self.database.user_logout(name) del self.names[name] break self.clients.remove(client_with_message) # Если есть сообщения, обрабатываем каждое for message in self.messages: try: self.process_message(message, send_data_lst) except: logger.info( f'Связь с клиентом с именем {message["to"]} была потеряна' ) self.clients.remove(self.names[message['to']]) self.database.user_logout(message['to']) del self.names[message['to']] self.messages.clear()
def _add_post(self): subject = ask_user('Subject:') title = ask_user('Title:') body = ask_user('Body:') try: self._server.add_post(self._user_id, subject, title, body) except Fault as ex: print(get_message(ex))
def _print_posts(self): try: posts = self._server.get_all_posts(self._user_id) except Fault as ex: print(get_message(ex)) return print(format_posts(posts))
def read_messages(client, account_name): """ Клиент читает входящие сообщения в бесконечном цикле :param client: сокет клиента """ while True: # читаем сообщение message = get_message(client) print(message['message'])
def main(): global CONFIGS logger.debug(f'The following configs are set \n. {CONFIGS}') CONFIGS = load_configs(is_server=False) logger.debug(f'For the key "is_server" set to "False" value') try: server_address = sys.argv[1] logger.debug(f'The server_address set to {server_address}') server_port = int(sys.argv[2]) logger.debug(f'The server_port set to {server_port}') if not 65535 >= server_port >= 1024: logger.error( f'The specified server_port out of range (1024, 65535). \n Entered value is {server_port}' f'\n Will be raised {ValueError}') raise ValueError except IndexError: server_address = CONFIGS.get('DEFAULT_IP_ADDRESS') server_port = CONFIGS.get('DEFAULT_PORT') logger.warning( f'A server_address and a server_port are not specified, will be set to default values \n' f' The server_address - {server_address} \n' f' The server_port {server_port}') except ValueError: logger.error( f'The specified server_port out of range (1024, 65535). \n Entered value is {server_port}' f'\n Will be raised {ValueError}') print('The port should be in the range of 1024 and 65535') sys.exit(1) transport = socket.socket(socket.AF_INET, socket.SOCK_STREAM) logger.debug(f'The socket was established for connection') transport.connect((server_address, server_port)) logger.debug( f'The connection with a server were established using {server_address} and {server_port}' ) presence_message = create_presence_message('Guest', CONFIGS) logger.info(f'The presence_message were created: \n' f'{presence_message}') send_message(transport, presence_message, CONFIGS) logger.debug( f'The presence_message were sent to the server with parameters: \n' f'socket - {transport}' f'presence message - {presence_message}' f'CONFIGS - {CONFIGS}') try: response = get_message(transport, CONFIGS) logger.debug(f'The response were received: \n {response}') handled_response = handle_response(response, CONFIGS) logger.info(f'The response were handled: \n {handled_response}') print(f'The response from the server: {response}') print(handled_response) except (ValueError, json.JSONDecodeError): logger.error( f'An error during decoding of server\'s response occurred. \n' f'The response - {response} \n' f'Error message - {ValueError}') print('Error message decoding ')
def run(self): print("Handling client request") option = self.socket_descriptor.recv(4) option = get_message("i", option) print("Option:{}".format(option)) requested_message_size = self.socket_descriptor.recv(8) requested_message_size = get_message("q", requested_message_size) print("Requested message size:{}".format(requested_message_size)) message_block_bytes = get_byte_data("H", MESSAGE_BLOCK) print("Sending to client the message block size.") self.socket_descriptor.send(message_block_bytes) if option == STREAMING_OPTION: self.stream_message(requested_message_size) else: self.stop_and_wait(requested_message_size)
def _create_user(self): user_id = ask_user('User identification:') try: self._server.register_user(user_id) except Fault as ex: print(get_message(ex)) return self._user_id = user_id
def read_requests(r_clients, all_clients): messages = [] for sock in r_clients: try: message = get_message(sock) messages.append(message) except: print('Клиент {} {} отключился'.format(sock.fileno(), sock.getpeername())) all_clients.remove(sock) return messages
def find_matches(self, saveutil, i): """Tries to find an edition or a work or multiple works that match the given input data. Case#1: No match. None is returned. Case#2: Work match but not editon. Work is returned. Case#3: Work match and edition match. Edition is returned Case#3A: Work match and multiple edition match. List of works is returned Case#4: Multiple work match. List of works is returned. """ i.publish_year = i.publish_date and self.extract_year(i.publish_date) work_key = i.get('work') # work_key is set to none-of-these when user selects none-of-these link. if work_key == 'none-of-these': return None work = work_key and web.ctx.site.get(work_key) if work: edition = self.try_edition_match(work=work, publisher=i.publisher, publish_year=i.publish_year, id_name=i.id_name, id_value=i.id_value) return edition or work if i.author_key == "__new__": a = new_doc("/type/author", name=i.author_name) comment = utils.get_message("comment_new_author") saveutil.save(a) i.author_key = a.key # since new author is created it must be a new record return None edition = self.try_edition_match( title=i.title, author_key=i.author_key, publisher=i.publisher, publish_year=i.publish_year, id_name=i.id_name, id_value=i.id_value) if edition: return edition solr = get_works_solr() author_key = i.author_key and i.author_key.split("/")[-1] result = solr.select({'title': i.title, 'author_key': author_key}, doc_wrapper=make_work, q_op="AND") if result.num_found == 0: return None elif result.num_found == 1: return result.docs[0] else: return result.docs
def no_match(self, saveutil, i): # TODO: Handle add-new-author work = new_doc("/type/work", title=i.title, authors=[{"author": {"key": i.author_key}}]) edition = self._make_edition(work, i) saveutil.save(work) saveutil.save(edition) comment = utils.get_message("comment_add_book") saveutil.commit(action="add-book", comment=comment) raise web.seeother(edition.url("/edit?mode=add-work"))
def POST(self, key): i = web.input(v=None, _method="GET") if spamcheck.is_spam(): return render_template("message.html", "Oops", 'Something went wrong. Please try again later.') recap = get_recaptcha() if recap and not recap.validate(): return 'Recaptcha solution was incorrect. Please <a href="javascript:history.back()">go back</a> and try again.' v = i.v and safeint(i.v, None) edition = web.ctx.site.get(key, v) if edition is None: raise web.notfound() if edition.works: work = edition.works[0] else: work = None add = (edition.revision == 1 and work and work.revision == 1 and work.edition_count == 1) try: helper = SaveBookHelper(work, edition) helper.save(web.input()) if add: add_flash_message("info", utils.get_message("flash_book_added")) else: add_flash_message("info", utils.get_message("flash_book_updated")) raise web.seeother(edition.url()) except (ClientException, ValidationException), e: add_flash_message('error', str(e)) return self.GET(key)
def save(self, formdata): """Update work and edition documents according to the specified formdata.""" comment = formdata.pop('_comment', '') user = web.ctx.site.get_user() delete = user and user.is_admin() and formdata.pop('_delete', '') formdata = utils.unflatten(formdata) work_data, edition_data = self.process_input(formdata) self.process_new_fields(formdata) if delete: if self.edition: self.delete(self.edition.key, comment=comment) if self.work and self.work.edition_count == 0: self.delete(self.work.key, comment=comment) return for i, author in enumerate(work_data.get("authors") or []): if author['author']['key'] == "__new__": a = self.new_author(formdata['authors'][i]) a._save(utils.get_message("comment_new_author")) author['author']['key'] = a.key if work_data: if self.work is None: self.work = self.new_work(self.edition) self.edition.works = [{'key': self.work.key}] self.work.update(work_data) self.work._save(comment=comment) if self.edition and edition_data: identifiers = edition_data.pop('identifiers', []) self.edition.set_identifiers(identifiers) classifications = edition_data.pop('classifications', []) self.edition.set_classifications(classifications) self.edition.set_physical_dimensions(edition_data.pop('physical_dimensions', None)) self.edition.set_weight(edition_data.pop('weight', None)) self.edition.set_toc_text(edition_data.pop('table_of_contents', '')) if edition_data.pop('translation', None) != 'yes': edition_data.translation_of = None edition_data.translated_from = None self.edition.update(edition_data) self.edition._save(comment=comment)
def POST(self, key): i = web.input(v=None, _method="GET") v = i.v and safeint(i.v, None) work = web.ctx.site.get(key, v) if work is None: raise web.notfound() try: helper = SaveBookHelper(work, None) helper.save(web.input()) add_flash_message("info", utils.get_message("flash_work_updated")) raise web.seeother(work.url()) except (ClientException, ValidationException), e: add_flash_message('error', str(e)) return self.GET(key)
def make_index_file(date, audio_fname_list, output_fname=None): import datetime import os import schedule import utils from rsab.listenagain import config, ListenAgainConfigError if not config.has_option('DEFAULT', 'output'): raise ListenAgainConfigError('No [DEFAULT]/output config defined') if output_fname is None: output_fname = 'index.html' output_fname = os.path.join(config.get('DEFAULT', 'output'), output_fname) output_file = open(output_fname, 'w') template = Template('player') playlist_items = [] details_for_audio_files = [] show_name_mapping = {} presenter_name_mapping = {} for audio_fname in audio_fname_list: playlist_items.append(str(make_playlist_item(audio_fname))) details_for_audio_files.append(schedule.schedule_from_audio_file_name(audio_fname)) live_schedule = schedule.get_schedule(date + datetime.timedelta(days=1)) for details in details_for_audio_files + live_schedule: if details is None: continue show_name = details['show'] show_title = utils.get_message(show_name, 'show', default=None) if show_title is None: show_title = utils.get_message(show_name, 'presenter', default=show_name) if show_name and show_name not in show_name_mapping: show_name_mapping[show_name] = show_title for presenter in details.get('presenters', []): if not presenter or presenter == show_name: continue if presenter not in presenter_name_mapping: presenter_name_mapping[presenter] = utils.get_message(presenter, 'presenter', default=presenter) template.playlist_items = '\n'.join(filter(None, playlist_items)) hidden_input = '<input type="hidden" disabled="disabled" name="%s" value="%s" />' template.show_name_mapping = '\n'.join([ hidden_input % ('showname', '%s:%s' % pair) for pair in show_name_mapping.items() ]) template.presenter_name_mapping = '\n'.join([ hidden_input % ('presentername', '%s:%s' % pair) for pair in presenter_name_mapping.items() ]) template.live_schedule = '\n'.join([ hidden_input % ( 'live_schedule', '%s:%s' % ( details['start'].strftime('%H:%M'), ','.join([details['show']] + details.get('presenters', [])), ), ) for details in schedule.get_schedule(date + datetime.timedelta(days=1)) ]) output_file.write(str(template)) output_file.close() return output_fname
def work_match(self, work, i): edition = self._make_edition(work, i) comment = utils.get_message("comment_new_edition") edition._save(comment) raise web.seeother(edition.url("/edit?mode=add-book"))