def render_params(self): ret = super(ContestHandler, self).render_params() ret["contest"] = self.contest ret["auth_type"] = get_auth_type(self.contest.auth_type) if self.contest_url is not None: ret["contest_url"] = self.contest_url ret["phase"] = self.contest.phase(self.timestamp) ret["printing_enabled"] = (config.printer is not None) ret["questions_enabled"] = self.contest.allow_questions ret["testing_enabled"] = self.contest.allow_user_tests if self.current_user is not None: participation = self.current_user ret["participation"] = participation ret["user"] = participation.user res = compute_actual_phase( self.timestamp, self.contest.start, self.contest.stop, self.contest.analysis_start if self.contest.analysis_enabled else None, self.contest.analysis_stop if self.contest.analysis_enabled else None, self.contest.per_user_time, participation.starting_time, participation.delay_time, participation.extra_time) ret["actual_phase"], ret["current_phase_begin"], \ ret["current_phase_end"], ret["valid_phase_begin"], \ ret["valid_phase_end"] = res if ret["actual_phase"] == 0: ret["phase"] = 0 # set the timezone used to format timestamps ret["timezone"] = get_timezone(participation.user, self.contest) # some information about token configuration ret["tokens_contest"] = self.contest.token_mode t_tokens = set(t.token_mode for t in self.contest.tasks) if len(t_tokens) == 1: ret["tokens_tasks"] = next(iter(t_tokens)) else: ret["tokens_tasks"] = TOKEN_MODE_MIXED return ret
def render_params(self): ret = super().render_params() ret["contest"] = self.contest if self.contest_url is not None: ret["contest_url"] = self.contest_url ret["phase"] = self.contest.phase(self.timestamp) ret["printing_enabled"] = (config.printer is not None) ret["questions_enabled"] = self.contest.allow_questions ret["testing_enabled"] = self.contest.allow_user_tests if self.current_user is not None: participation = self.current_user ret["participation"] = participation ret["user"] = participation.user res = compute_actual_phase( self.timestamp, self.contest.start, self.contest.stop, self.contest.analysis_start if self.contest.analysis_enabled else None, self.contest.analysis_stop if self.contest.analysis_enabled else None, self.contest.per_user_time, participation.starting_time, participation.delay_time, participation.extra_time) ret["actual_phase"], ret["current_phase_begin"], \ ret["current_phase_end"], ret["valid_phase_begin"], \ ret["valid_phase_end"] = res if ret["actual_phase"] == 0: ret["phase"] = 0 # set the timezone used to format timestamps ret["timezone"] = get_timezone(participation.user, self.contest) # some information about token configuration ret["tokens_contest"] = self.contest.token_mode t_tokens = set(t.token_mode for t in self.contest.tasks) if len(t_tokens) == 1: ret["tokens_tasks"] = next(iter(t_tokens)) else: ret["tokens_tasks"] = TOKEN_MODE_MIXED return ret
def render_params(self): ret = super(ContestHandler, self).render_params() ret["contest"] = self.contest if hasattr(self, "contest_url"): ret["contest_url"] = self.contest_url ret["phase"] = self.contest.phase(self.timestamp) ret["printing_enabled"] = (config.printer is not None) ret["questions_enabled"] = self.contest.allow_questions ret["testing_enabled"] = self.contest.allow_user_tests if self.current_user is not None: participation = self.current_user res = compute_actual_phase( self.timestamp, self.contest.start, self.contest.stop, self.contest.analysis_start if self.contest.analysis_enabled else None, self.contest.analysis_stop if self.contest.analysis_enabled else None, self.contest.per_user_time, participation.starting_time, participation.delay_time, participation.extra_time) ret["actual_phase"], ret["current_phase_begin"], \ ret["current_phase_end"], ret["valid_phase_begin"], \ ret["valid_phase_end"] = res if ret["actual_phase"] == 0: ret["phase"] = 0 # set the timezone used to format timestamps ret["timezone"] = get_timezone(participation.user, self.contest) # some information about token configuration ret["tokens_contest"] = self._get_token_status(self.contest) t_tokens = sum(self._get_token_status(t) for t in self.contest.tasks) if t_tokens == 0: ret["tokens_tasks"] = 0 # all disabled elif t_tokens == 2 * len(self.contest.tasks): ret["tokens_tasks"] = 2 # all infinite else: ret["tokens_tasks"] = 1 # all finite or mixed # TODO Now all language names are shown in the active language. # It would be better to show them in the corresponding one. ret["lang_names"] = {} # Get language codes for allowed localizations lang_codes = self.langs.keys() if len(self.contest.allowed_localizations) > 0: lang_codes = filter_language_codes( lang_codes, self.contest.allowed_localizations) for lang_code, trans in self.langs.iteritems(): language_name = None # Filter lang_codes with allowed localizations if lang_code not in lang_codes: continue try: language_name = translate_language_country_code( lang_code, trans) except ValueError: language_name = translate_language_code( lang_code, trans) ret["lang_names"][lang_code.replace("_", "-")] = language_name ret["cookie_lang"] = self.cookie_lang ret["browser_lang"] = self.browser_lang return ret
def execute(self, entry): """Print a print job. This is the core of PrintingService. entry (QueueEntry): the entry containing the operation to perform. """ # TODO: automatically re-enqueue in case of a recoverable # error. printjob_id = entry.item.printjob_id with SessionGen() as session: # Obtain print job. printjob = PrintJob.get_from_id(printjob_id, session) if printjob is None: raise ValueError("Print job %d not found in the database." % printjob_id) user = printjob.participation.user contest = printjob.participation.contest timezone = get_timezone(user, contest) timestr = format_datetime(printjob.timestamp, timezone) filename = printjob.filename # Check if it's ready to be printed. if printjob.done: logger.info("Print job %d was already sent to the printer.", printjob_id) directory = tempfile.mkdtemp(dir=config.temp_dir) logger.info("Preparing print job in directory %s", directory) # Take the base name just to be sure. relname = "source_" + os.path.basename(filename) source = os.path.join(directory, relname) with open(source, "wb") as file_: self.file_cacher.get_file_to_fobj(printjob.digest, file_) if filename.endswith(".pdf") and config.pdf_printing_allowed: source_pdf = source else: # Convert text to ps. source_ps = os.path.join(directory, "source.ps") cmd = ["a2ps", source, "--delegate=no", "--output=" + source_ps, "--medium=%s" % config.paper_size.capitalize(), "--portrait", "--columns=1", "--rows=1", "--pages=1-%d" % (config.max_pages_per_job), "--header=", "--footer=", "--left-footer=", "--right-footer=", "--center-title=" + filename, "--left-title=" + timestr] ret = subprocess.call(cmd, cwd=directory) if ret != 0: raise Exception( "Failed to convert text file to ps with command: %s" "(error %d)" % (pretty_print_cmdline(cmd), ret)) if not os.path.exists(source_ps): logger.warning("Unable to convert from text to ps.") printjob.done = True printjob.status = json.dumps([ N_("Invalid file")]) session.commit() rmtree(directory) return # Convert ps to pdf source_pdf = os.path.join(directory, "source.pdf") cmd = ["ps2pdf", "-sPAPERSIZE=%s" % config.paper_size.lower(), source_ps] ret = subprocess.call(cmd, cwd=directory) if ret != 0: raise Exception( "Failed to convert ps file to pdf with command: %s" "(error %d)" % (pretty_print_cmdline(cmd), ret)) # Find out number of pages with open(source_pdf, "rb") as file_: pdfreader = PdfFileReader(file_) page_count = pdfreader.getNumPages() logger.info("Preparing %d page(s) (plus the title page)", page_count) if page_count > config.max_pages_per_job: logger.info("Too many pages.") printjob.done = True printjob.status = json.dumps([ N_("Print job has too many pages")]) session.commit() rmtree(directory) return # Add the title page title_tex = os.path.join(directory, "title_page.tex") title_pdf = os.path.join(directory, "title_page.pdf") with open(title_tex, "w") as f: f.write(self.template_loader.load("title_page.tex") .generate(user=user, filename=filename, timestr=timestr, page_count=page_count, paper_size=config.paper_size)) cmd = ["pdflatex", "-interaction", "nonstopmode", title_tex] ret = subprocess.call(cmd, cwd=directory) if ret != 0: raise Exception( "Failed to create title page with command: %s" "(error %d)" % (pretty_print_cmdline(cmd), ret)) pdfmerger = PdfFileMerger() with open(title_pdf, "rb") as file_: pdfmerger.append(file_) with open(source_pdf, "rb") as file_: pdfmerger.append(file_) result = os.path.join(directory, "document.pdf") with open(result, "wb") as file_: pdfmerger.write(file_) try: printer_connection = cups.Connection() printer_connection.printFile( config.printer, result, "Printout %d" % printjob_id, {}) except cups.IPPError as error: logger.error("Unable to print: `%s'.", error) else: printjob.done = True printjob.status = json.dumps([N_("Sent to printer")]) session.commit() finally: rmtree(directory)
def render_params(self): """Return the default render params used by almost all handlers. return (dict): default render params """ ret = {} ret["timestamp"] = self.timestamp ret["contest"] = self.contest ret["url_root"] = get_url_root(self.request.path) ret["phase"] = self.contest.phase(self.timestamp) ret["printing_enabled"] = (config.printer is not None) ret["questions_enabled"] = self.contest.allow_questions ret["testing_enabled"] = self.contest.allow_user_tests if self.current_user is not None: participation = self.current_user res = compute_actual_phase(self.timestamp, self.contest.start, self.contest.stop, self.contest.per_user_time, participation.starting_time, participation.delay_time, participation.extra_time) ret["actual_phase"], ret["current_phase_begin"], \ ret["current_phase_end"], ret["valid_phase_begin"], \ ret["valid_phase_end"] = res if ret["actual_phase"] == 0: ret["phase"] = 0 # set the timezone used to format timestamps ret["timezone"] = get_timezone(participation.user, self.contest) # some information about token configuration ret["tokens_contest"] = self._get_token_status(self.contest) t_tokens = sum(self._get_token_status(t) for t in self.contest.tasks) if t_tokens == 0: ret["tokens_tasks"] = 0 # all disabled elif t_tokens == 2 * len(self.contest.tasks): ret["tokens_tasks"] = 2 # all infinite else: ret["tokens_tasks"] = 1 # all finite or mixed # TODO Now all language names are shown in the active language. # It would be better to show them in the corresponding one. ret["lang_names"] = {} # Get language codes for allowed localizations lang_codes = self.langs.keys() if len(self.contest.allowed_localizations) > 0: lang_codes = filter_language_codes( lang_codes, self.contest.allowed_localizations) for lang_code, trans in self.langs.iteritems(): language_name = None # Filter lang_codes with allowed localizations if lang_code not in lang_codes: continue try: language_name = translate_language_country_code( lang_code, trans) except ValueError: language_name = translate_language_code(lang_code, trans) ret["lang_names"][lang_code.replace("_", "-")] = language_name ret["cookie_lang"] = self.cookie_lang ret["browser_lang"] = self.browser_lang if self.current_user is not None: tree_menu = {'childs': {}, 'tasks': []} for t in self.contest.tasks: if not self.contest.restrict_level or self.current_user.user.level == t.level or self.current_user.user.level == "x" or t.level == "x": node = tree_menu if t.category: for subcat in t.category.split('.'): if subcat not in node['childs']: node['childs'][subcat] = { 'childs': {}, 'tasks': [] } node = node['childs'][subcat] node['tasks'].append(t) def make_list(tree, result, ancname="root"): for name in sorted(tree['childs']): fullname = ancname + '.' + name result.append({ 'type': 'startcat', 'name': name, 'fullname': fullname, 'parent': ancname }) make_list(tree['childs'][name], result, fullname) result.append({'type': 'endcat'}) for t in sorted(tree['tasks'], key=lambda t: t.name): result.append({ 'type': 'task', 'task': t, 'parent': ancname }) ret['list_tree_menu'] = [] make_list(tree_menu, ret['list_tree_menu']) return ret
def render_params(self): """Return the default render params used by almost all handlers. return (dict): default render params """ ret = {} ret["timestamp"] = self.timestamp ret["contest"] = self.contest ret["url_root"] = get_url_root(self.request.path) ret["phase"] = self.contest.phase(self.timestamp) ret["printing_enabled"] = (config.printer is not None) if self.current_user is not None: participation = self.current_user res = compute_actual_phase( self.timestamp, self.contest.start, self.contest.stop, self.contest.per_user_time, participation.starting_time, participation.delay_time, participation.extra_time) ret["actual_phase"], ret["current_phase_begin"], \ ret["current_phase_end"], ret["valid_phase_begin"], \ ret["valid_phase_end"] = res if ret["actual_phase"] == 0: ret["phase"] = 0 # set the timezone used to format timestamps ret["timezone"] = get_timezone(participation.user, self.contest) # some information about token configuration ret["tokens_contest"] = self._get_token_status(self.contest) t_tokens = sum(self._get_token_status(t) for t in self.contest.tasks) if t_tokens == 0: ret["tokens_tasks"] = 0 # all disabled elif t_tokens == 2 * len(self.contest.tasks): ret["tokens_tasks"] = 2 # all infinite else: ret["tokens_tasks"] = 1 # all finite or mixed # TODO Now all language names are shown in the active language. # It would be better to show them in the corresponding one. ret["lang_names"] = {} for lang_code, trans in self.langs.iteritems(): language_name = None try: language_name = translate_language_country_code( lang_code, trans) except ValueError: language_name = translate_language_code( lang_code, trans) ret["lang_names"][lang_code.replace("_", "-")] = language_name ret["cookie_lang"] = self.cookie_lang ret["browser_lang"] = self.browser_lang return ret
def render_params(self): """Return the default render params used by almost all handlers. return (dict): default render params """ ret = {} ret["timestamp"] = self.timestamp ret["contest"] = self.contest ret["url_root"] = get_url_root(self.request.path) ret["phase"] = self.contest.phase(self.timestamp) ret["printing_enabled"] = (config.printer is not None) ret["questions_enabled"] = self.contest.allow_questions ret["testing_enabled"] = self.contest.allow_user_tests if self.current_user is not None: participation = self.current_user res = compute_actual_phase( self.timestamp, self.contest.start, self.contest.stop, self.contest.per_user_time, participation.starting_time, participation.delay_time, participation.extra_time) ret["actual_phase"], ret["current_phase_begin"], \ ret["current_phase_end"], ret["valid_phase_begin"], \ ret["valid_phase_end"] = res if ret["actual_phase"] == 0: ret["phase"] = 0 # set the timezone used to format timestamps ret["timezone"] = get_timezone(participation.user, self.contest) # some information about token configuration ret["tokens_contest"] = self._get_token_status(self.contest) t_tokens = sum(self._get_token_status(t) for t in self.contest.tasks) if t_tokens == 0: ret["tokens_tasks"] = 0 # all disabled elif t_tokens == 2 * len(self.contest.tasks): ret["tokens_tasks"] = 2 # all infinite else: ret["tokens_tasks"] = 1 # all finite or mixed # TODO Now all language names are shown in the active language. # It would be better to show them in the corresponding one. ret["lang_names"] = {} # Get language codes for allowed localizations lang_codes = self.langs.keys() if len(self.contest.allowed_localizations) > 0: lang_codes = filter_language_codes( lang_codes, self.contest.allowed_localizations) for lang_code, trans in self.langs.iteritems(): language_name = None # Filter lang_codes with allowed localizations if lang_code not in lang_codes: continue try: language_name = translate_language_country_code( lang_code, trans) except ValueError: language_name = translate_language_code( lang_code, trans) ret["lang_names"][lang_code.replace("_", "-")] = language_name ret["cookie_lang"] = self.cookie_lang ret["browser_lang"] = self.browser_lang if self.current_user is not None: tree_menu = {'childs':{}, 'tasks': []} for t in self.contest.tasks: if not self.contest.restrict_level or self.current_user.user.level == t.level or self.current_user.user.level == "x" or t.level == "x": node = tree_menu if t.category: for subcat in t.category.split('.'): if subcat not in node['childs']: node['childs'][subcat] = {'childs':{}, 'tasks': []} node = node['childs'][subcat] node['tasks'].append(t) def make_list(tree, result, ancname="root"): for name in sorted(tree['childs']): fullname = ancname+'.'+name result.append({'type': 'startcat', 'name' : name, 'fullname' : fullname, 'parent' : ancname}) make_list(tree['childs'][name], result, fullname) result.append({'type': 'endcat'}) for t in sorted(tree['tasks'], key=lambda t: t.name): result.append({'type': 'task', 'task' : t, 'parent' : ancname}) ret['list_tree_menu'] = [] make_list(tree_menu, ret['list_tree_menu']) return ret