Exemplo n.º 1
0
Arquivo: wan.py Projeto: Keith2/Plinth
    def main(self, message='', **kwargs):
        store = filedict_con(cfg.store_file, 'sys')

        defaults = {'wan_admin': "''",
                    'wan_ssh': "''",
                    'lan_ssh': "''",
                    }
        for k,c in defaults.items():
            if not k in kwargs:
                try:
                    kwargs[k] = store[k]
                except KeyError:
                    exec("if not '%(k)s' in kwargs: store['%(k)s'] = kwargs['%(k)s'] = %(c)s" % {'k':k, 'c':c})

        form = Form(title=_("Accessing the %s" % cfg.box_name), 
                        action="/sys/config/wan", 
                        name="admin_wan_form",
                        message=message )
        form.html(self.help())
        if cfg.users.expert():
            form.checkbox(_("Allow access to Plinth from WAN"), name="wan_admin", checked=kwargs['wan_admin'])
            form.checkbox(_("Allow SSH access from LAN"), name="lan_ssh", checked=kwargs['lan_ssh'])
            form.checkbox(_("Allow SSH access from WAN"), name="wan_ssh", checked=kwargs['wan_ssh'])
        form.submit(_("Submit"))
        return form.render()
Exemplo n.º 2
0
def categories_edit(category_id):
    try:
        category = Category.find_by_id(category_id)
        if category:
            if request.method == 'GET':
                category_dict = category.__dict__
                form = Form(category_dict, form_fields)
                return render_template('category/edit.html', form=form, category_id=category_id, success=True)
            elif request.method == 'POST':
                form = Form(request.form, form_fields)
                if form.validate():
                    values = form.named_values()
                    category.from_dict(values)
                    category.save()
                    miner = miner_cls(category)
                    miners[category_id] = miner
                    miner.start()
                    return redirect(url_for('categories'))
                else:
                    return render_template('category/edit.html', form=form, category_id=category_id, success=True)
            elif request.method == 'DELETE':
                miner = miners[category_id]
                miner.stop()
                del miners[category_id]
                Category.delete(category_id)
                return 'Category {} deleted.'.format(category_id), 200
            else:
                return 'Unsupported request method.', 400
        else:
            return 'Category {} not found.'.format(category_id), 400
    except ValueError, e:
        print e
        return '{} is not a valid category id.'.format(category_id), 400
Exemplo n.º 3
0
def racimos_faltantes():
    form = Form(request.form)
    _populated_select(form)
    if form.type.data =='1':
        cur.execute("SELECT id, peso, item, fecha, orden, cod_empacadora, peso_neto, peso_bruto, cod_item_corto, cod_hacienda, "
                    "ROUND(AVG(peso),2) as promedio, COUNT(orden) as total_cajas, cantidad, ROUND(MIN(peso),2) as minimo, "
                    "ROUND(MAX(peso),2) as maximo, ROUND(AVG(peso_bruto),2) as promedio_bruto FROM caja ")
    if form.type.data =='2':
        cur.execute("SELECT id, peso, item, fecha, orden, cod_empacadora, peso_neto, peso_bruto, cod_item_corto, cod_hacienda, "
                    "ROUND(AVG(peso),2) as promedio, COUNT(orden) as total_cajas, cantidad, ROUND(MIN(peso),2) as minimo, "
                    "ROUND(MAX(peso),2) as maximo, ROUND(AVG(peso_bruto),2) as promedio_bruto "
                    "FROM bandeja WHERE DATE(fecha)='$fecha_consulta' GROUP BY orden, cod_item_corto ORDER BY "
                    "cod_empacadora, orden")
    if form.type.data =='3':
        cur.execute("SELECT r.idracimo, r.idconvoy, r.peso, r.timestamp as fecha_racimo, r.numlote as lote_racimo, "
                    "r.cinta, r.edad, r.cod_empacadora, r.cod_hacienda, r.tara, c.timestamp as fecha_convoy,c.num_racimos, "
                    "c.cuadrilla, COUNT(peso) as cantidad_pesada, ROUND(AVG(tara),2) as prom_tara, "
                    "ROUND(MIN(CAST(peso AS DECIMAL)),2) as minimo, ROUND(MAX(CAST(peso AS DECIMAL)),2) as maximo, "
                    "ROUND(AVG(CAST(peso AS DECIMAL)),2) as peso_promedio from racimo r left join convoy c ON(r.idconvoy=c.idconvoy) "
                    "WHERE DATE(r.timestamp)='"+form.date.data+"' GROUP BY r.idconvoy, r.numlote, r.cinta")
        cur.execute("SELECT r.idracimo, r.idconvoy, r.peso, r.timestamp as fecha_racimo, r.numlote as lote_racimo, "
                    "r.cinta, r.edad, r.cod_empacadora, r.cod_hacienda, r.tara, c.timestamp as fecha_convoy,c.num_racimos, "
                    "c.cuadrilla, COUNT(peso) as cantidad_pesada, ROUND(AVG(tara),2) as prom_tara, "
                    "ROUND(MIN(CAST(peso AS DECIMAL)),2) as minimo, ROUND(MAX(CAST(peso AS DECIMAL)),2) as maximo, "
                    "ROUND(AVG(CAST(peso AS DECIMAL)),2) as peso_promedio from racimo r left join convoy c ON(r.idconvoy=c.idconvoy) "
                    "WHERE DATE(r.timestamp)='"+form.date.data+"' GROUP BY r.cinta")
    if not form.type.data == 'None':
        data= cur.fetchall()
    else:
        data= []
    if not form.validate_on_submit():
        flash('Ingresar bien todos los campos')
    return render_template('racimos_faltantes.html',form=form, data=data)
Exemplo n.º 4
0
def skriv(request):
    data = {}
    if request.method == "POST":
        form = Form(data=request.POST)
        if form.is_valid():
            form.save()
            return HttpResponseRedirect(reverse('gastbok'))
    else:
        form = Form(initial={'spamcheck': 'Sto'})
    data['form'] = form
    return render(request, 'guestbook/skriv.html', data)
Exemplo n.º 5
0
def form(request):
    if request.method == 'POST':
        form = Form(request.POST)
        if form.is_valid():
            return render_to_response('form.html',{'m':'woo hoo'})
    else:
        form = Form()

    return render_to_response('form.html', {
        'form': form,
    })
Exemplo n.º 6
0
    def fill_form_and_submit(self, elm, data={}):
        """
        Fill form with given data, then submit

        :param elm: Form element
        :param data: Dictionary of data for the form. \
                Keys in the dictionary represent name \
                attributes of the form elements
        """
        form = Form(elm)
        form.fill_out_and_submit(data)
Exemplo n.º 7
0
	def on_submit(self):
		Form.on_submit(self)
		localdir = self.content["Local Dir?"].get()
		portnum = self.content["Port Number"].get()
		filename = self.content["File Name"].get()
		servername = self.content["Server Name"].get() 
		if localdir:
			os.chdir(localdir)
		portnum = int(portnum)
		getfile.client(servername, portnum, filename)
		showinfo("getfilegui-3", "Download Complete")
		if self.one_shot: Tk().quit()
Exemplo n.º 8
0
 def main(self, msg=''):
     users = cfg.users.keys()
     add_form = Form(title=_("Edit or Delete User"), action="/sys/users/edit", message=msg)
     add_form.html('<span class="indent"><strong>Delete</strong><br /></span>')
     for uname in sorted(users.keys()):
         add_form.html('<span class="indent">&nbsp;&nbsp;%s&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;' % 
                       add_form.get_checkbox(name=uname) +
                       '<a href="/sys/users/edit?username=%s">%s (%s)</a><br /></span>' % 
                       (uname, users[uname]['name'], uname))
     add_form.submit(label=_("Delete User"), name="delete")
     return add_form.render()
Exemplo n.º 9
0
 def main(self, msg=''):
     users = cfg.users.get_all()
     add_form = Form(title=_("Edit or Delete User"), action=cfg.server_dir + "/sys/users/edit", message=msg)
     add_form.html('<span class="indent"><strong>Delete</strong><br /></span>')
     for uname in users:
         user = User(uname[1])
         add_form.html('<span class="indent">&nbsp;&nbsp;%s&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;' %
                       add_form.get_checkbox(name=user['username']) +
                       '<a href="'+cfg.server_dir+'/sys/users/edit?username=%s">%s (%s)</a><br /></span>' %
                       (user['username'], user['name'], user['username']))
     add_form.submit(label=_("Delete User"), name="delete")
     return add_form.render()
Exemplo n.º 10
0
 def main(self, username='', message=None, *args, **kwargs):
     form = Form(title="Register XMPP Account",
                 action=cfg.server_dir + "/services/xmpp/register/index",
                 name="register_xmpp_form",
                 message=message)
     form.text_input(_("Username"), name="username", value=username)
     form.text_input(_("Password"), name="password", type="password")
     form.submit(label=_("Register XMPP Account"), name="register")
     return form.render()
Exemplo n.º 11
0
    def main(self, xmpp_inband_enable=False, message=None, *args, **kwargs):
        output, error = actions.superuser_run("xmpp-setup", 'status')
        if error:
            raise Exception("something is wrong: " + error)
        if "inband_enable" in output.split():
            xmpp_inband_enable = True

        form = Form(title="Configure XMPP Server",
                    action=cfg.server_dir + "/services/xmpp/configure/index",
                    name="configure_xmpp_form",
                    message=message)
        form.checkbox(_("Allow In-Band Registration"), name="xmpp_inband_enable",
                        id="xmpp_inband_enable", checked=xmpp_inband_enable)
        # hidden field is needed because checkbox doesn't post if not checked
        form.hidden(name="submitted", value="True")
        form.html(_("<p>When enabled, anyone who can reach this server will be allowed to register an account through an XMPP client.</p>"))
        form.submit(_("Update setup"))
        return form.render()
Exemplo n.º 12
0
def diff(request):
    base_result = ''
    new_result = ''
    if request.method == 'POST':
        form = Form(request.POST)
        if form.is_valid():
            base_url = form.cleaned_data['base_url']
            new_url = form.cleaned_data['new_url']
            query = form.cleaned_data['query']
            if base_url != '' and new_url != '' and query != '':
                base_result = urllib2.urlopen("%s%s" % (base_url.encode('utf8'), query.encode('utf8'))).read()
                if base_result != '':
                    base_result = simplejson.loads(base_result)['records']
                new_result = urllib2.urlopen("%s%s" % (new_url.encode('utf8'), query.encode('utf8'))).read()
                if new_result != '':
                    new_result = simplejson.loads(new_result)['records']
                print base_result
    else:
        form = Form()

    return render_to_response('diff.html', {'form': form, 'base_result': base_result, 'new_result': new_result}, context_instance=RequestContext(request))
Exemplo n.º 13
0
 def main(self, expert=None, message='', **kwargs):
     """Note that kwargs contains '':"submit" if this is coming
     from a submitted form.  If kwargs is empty, it's a fresh form
     with no user input, which means it should just reflect the
     state of the stored data."""
     if not kwargs and expert == None:
         expert = cfg.users.expert()
         cfg.log("Expert mode is %s" % expert)
     form = Form(title=_("Expert Mode"), 
                     action="/sys/config/experts", 
                     name="expert_mode_form",
                     message=message )
     form.html(self.help())
     form.checkbox(_("Expert Mode"), name="expert", checked=expert)
     form.submit(_("Submit"))
     return form.render()
Exemplo n.º 14
0
def categories_edit(category_id):
    try:
        category = Category.find_by_id(category_id)
        if category:
            if request.method == "GET":
                category_dict = category.__dict__
                form = Form(category_dict, form_fields)
                return render_template("category/edit.html", form=form, category_id=category_id, success=True)
            elif request.method == "POST":
                form = Form(request.form, form_fields)
                if form.validate():
                    values = form.named_values()
                    category.from_dict(values)
                    category.save()
                    miner = miner_cls(category)
                    miners[category_id] = miner
                    miner.start()
                    return redirect(url_for("categories"))
                else:
                    return render_template("category/edit.html", form=form, category_id=category_id, success=True)
            elif request.method == "DELETE":
                if category_id in miners:
                    miner = miners[category_id]
                    miner.stop()
                    del miners[category_id]
                    Category.delete(category_id)
                    return "Category {} deleted.".format(category_id), 200
                else:
                    return "Category {} not present on miner.".format(category_id), 400
            else:
                return "Unsupported request method.", 400
        else:
            return "Category {} not found.".format(category_id), 400
    except ValueError, e:
        print e
        return "{} is not a valid category id.".format(category_id), 400
Exemplo n.º 15
0
    def __init__(self, name, **kwargs):
        super(BaseCrud, self).__init__()
        self.name=name
        self.pk_type='int'
        self.navigation_hint=name+'.list'
        self.form=[]
        self.label=name.capitalize()
        self.url='/{0}/'.format(name)
        self.parent=None
        self.labels={}
        self.list_columns=[]
        self.form=Form()
        self.collection=None


        if 'pk_type' in kwargs: self.pk_type=kwargs['pk_type'] 
        if 'navigation_hint' in kwargs: self.navigation_hint=kwargs['navigation_hint'] 
        if 'label' in kwargs: self.label=kwargs['label'] 
        if 'url' in kwargs: self.url=kwargs['url'] 
        if 'labels' in kwargs: self.labels=kwargs['labels'] 
        if 'list_columns' in kwargs:
            self.list_columns=create_columns(kwargs['list_columns'])
        if 'form' in kwargs: 
            self.form=create_form(kwargs['form'],self.labels)  
Exemplo n.º 16
0
    def main(self, wan_ip0=0, wan_ip1=0, wan_ip2=0, wan_ip3=0, 
             subnet0=0, subnet1=0, subnet2=0, subnet3=0, 
             gateway0=0, gateway1=0, gateway2=0, gateway3=0, 
             dns10=0, dns11=0, dns12=0, dns13=0, 
             dns20=0, dns21=0, dns22=0, dns23=0, 
             dns30=0, dns31=0, dns32=0, dns33=0, 
             message=None, **kwargs):
        if not cfg.users.expert():
            return ''

        store = filedict_con(cfg.store_file, 'router')
        defaults = {'connect_type': "'DHCP'",
                    }
        for k,c in defaults.items():
            if not k in kwargs:
                try:
                    kwargs[k] = store[k]
                except KeyError:
                    exec("if not '%(k)s' in kwargs: store['%(k)s'] = kwargs['%(k)s'] = %(c)s" % {'k':k, 'c':c})

        form = Form(title="WAN Connection", 
                        action="/router/setup/wan/index", 
                        name="wan_connection_form",
                        message=message)
        form.dropdown('Connection Type', vals=["DHCP", "Static IP"], id="connect_type", onchange="hideshow_static()")
        form.html('<div id="static_ip_form">')
        form.dotted_quad("WAN IP Address", name="wan_ip", quad=[wan_ip0, wan_ip1, wan_ip2, wan_ip3])
        form.dotted_quad("Subnet Mask", name="subnet", quad=[subnet0, subnet1, subnet2, subnet3])
        form.dotted_quad("Gateway", name="gateway", quad=[gateway0, gateway1, gateway2, gateway3])
        form.dotted_quad("Static DNS 1", name="dns1", quad=[dns10, dns11, dns12, dns13])
        form.dotted_quad("Static DNS 2", name="dns2", quad=[dns20, dns21, dns22, dns23])
        form.dotted_quad("Static DNS 3", name="dns3", quad=[dns30, dns31, dns32, dns33])
        form.html('</div>')
        form.html("""  <script LANGUAGE="JavaScript">
    <!--
      hideshow_static();
    // --> 
  </script>""")
        form.submit("Set Wan")
        return form.render()
Exemplo n.º 17
0
 def disproveAccusation(self,message_type,accusation_lines,card_names_to_limit=None):
     card_deck = CardDeck()
     
     accusation_form = Form(False)
     disproving = False
     if len(accusation_lines) > 0:
         disproving = True
         accusation_form.add_object('new_title', Text('Current Suggestion:', label_style=['bold','underline']))
         for k in xrange(len(accusation_lines)):
             accusation_message, accusation_pos,accusation_message_str = accusation_lines[k]
             accusation_form.add_object('accusation_{0}'.format(k), Text('{0}'.format(accusation_message_str), label_style=['bold']))
         accusation_form.add_object('spacer', Text('', label_style=['bold','underline']))
         accusation_form.add_object('disprove_title_{0}'.format(k), Text('Select card(s) to disprove:', label_style=['bold','underline']))
     else:
         
         if message_type == "New Suggestion":
             accusation_form.add_object('suggestion_title', Text('Select card(s) for suggestion:', label_style=['bold','underline']))
         else:
             accusation_form.add_object('suggestion_title', Text('Select card(s) for accusation:', label_style=['bold','underline']))
     
     screen = self.getScreen(message_type,disproving)
     
     
     
     tracker = []
     character_menu = Select(border_width=2, top=50)
     character_list = card_deck.get_cardlist("character")
     char_found = False
     for character_name in character_list:
         if card_names_to_limit and len(card_names_to_limit) > 1 and character_name in card_names_to_limit:
             character_menu.add_option(character_name,character_name)
             tracker.append(character_name)
             char_found = True
         elif card_names_to_limit and len(card_names_to_limit) == 1:
             character_menu.add_option(character_name,character_name)
             tracker.append(character_name)
             char_found = True
         elif not card_names_to_limit:
             character_menu.add_option(character_name,character_name)
             tracker.append(character_name)
             char_found = True
     if char_found:
         accusation_form.add_object('title_character', Text('Select Character:', label_style=['bold']))
         accusation_form.add_object('character', character_menu)
     else:
         accusation_form.add_object('title_character', Text('Select Character:', label_style=['bold']))
         accusation_form.add_object('title_character_1', Text('Sorry, no Character cards', label_style=['bold']))
         accusation_form.add_object('title_character_2', Text('in your deck to select', label_style=['bold']))
     
     
     #if disproving: accusation_form.add_object('weapon_title', Text('with a', label_style=['bold']))
     
     weapon_list = card_deck.get_cardlist("weapon")
     weapon_menu = Select(border_width=2, top=50)
     weapon_found = False
     for weapon_name in weapon_list:
         if card_names_to_limit and len(card_names_to_limit) > 1 and weapon_name in card_names_to_limit:
             weapon_menu.add_option(weapon_name,weapon_name)
             tracker.append(weapon_name)
             weapon_found = True
         elif card_names_to_limit and len(card_names_to_limit) == 1:
             weapon_menu.add_option(weapon_name,weapon_name)
             tracker.append(weapon_name)
             weapon_found = True
         elif not card_names_to_limit:
             weapon_menu.add_option(weapon_name,weapon_name)
             tracker.append(weapon_name)
             weapon_found = True
     
     if weapon_found:
         accusation_form.add_object('title_weapon', Text('Select Weapon:', label_style=['bold']))
         accusation_form.add_object('weapon', weapon_menu)
     else:
         accusation_form.add_object('title_weapon', Text('Select Weapon:', label_style=['bold']))
         accusation_form.add_object('title_weapon_1', Text('Sorry, no Weapon cards', label_style=['bold']))
         accusation_form.add_object('title_weapon_2', Text('in your deck to select', label_style=['bold']))
     
     
     
     #if disproving: accusation_form.add_object('room_title', Text('in the', label_style=['bold']))
     
     room_list = card_deck.get_cardlist("room")
     room_menu = Select(border_width=2, top=50)
     room_found = False
     for room_name in room_list:
         if card_names_to_limit and room_name in card_names_to_limit:
             room_menu.add_option(room_name,room_name)
             tracker.append(room_name)
             room_found = True
         elif not card_names_to_limit:
             room_menu.add_option(room_name,room_name)
             tracker.append(room_name)
             room_found = True
     
     if room_found:
         accusation_form.add_object('title_room', Text('Select Room:', label_style=['bold']))
         accusation_form.add_object('room', room_menu)
     else:
         accusation_form.add_object('title_room', Text('Select Room:', label_style=['bold']))
         accusation_form.add_object('title_room_1', Text('Sorry, no Room cards', label_style=['bold']))
         accusation_form.add_object('title_room_2', Text('in your deck to select', label_style=['bold']))
     
     if disproving:
         accusation_form.add_object('submit', Button('Disprove', accusation_form.submit, ()))
         accusation_form.add_object('skip', Button('Skip', accusation_form.skip, ()))
     else:
         if message_type == "New Suggestion":
             accusation_form.add_object('submit', Button('Make Suggestion', accusation_form.submit, ()))
         else:
             accusation_form.add_object('submit', Button('Make Final Accusation', accusation_form.submit, ()))
         accusation_form.add_object('skip', Button('Skip', accusation_form.skip, ()))
     
     accusation_form.add_object('Clear', Button('Clear', accusation_form.clear, ()))
     
     form_input = accusation_form.run(screen)
     
     if accusation_form._skip:
         return {}
     elif disproving and len(form_input) == 0:
         return None
     elif not disproving and len(form_input) != 3:
         return None
     return form_input
Exemplo n.º 18
0
class BaseCrud(object):
    
    def __init__(self, name, **kwargs):
        super(BaseCrud, self).__init__()
        self.name=name
        self.pk_type='int'
        self.navigation_hint=name+'.list'
        self.form=[]
        self.label=name.capitalize()
        self.url='/{0}/'.format(name)
        self.parent=None
        self.labels={}
        self.list_columns=[]
        self.form=Form()
        self.collection=None


        if 'pk_type' in kwargs: self.pk_type=kwargs['pk_type'] 
        if 'navigation_hint' in kwargs: self.navigation_hint=kwargs['navigation_hint'] 
        if 'label' in kwargs: self.label=kwargs['label'] 
        if 'url' in kwargs: self.url=kwargs['url'] 
        if 'labels' in kwargs: self.labels=kwargs['labels'] 
        if 'list_columns' in kwargs:
            self.list_columns=create_columns(kwargs['list_columns'])
        if 'form' in kwargs: 
            self.form=create_form(kwargs['form'],self.labels)  
        



    def list(self):
        context = self.__get_context()
        context['rows']=self.collection.list()
        return self.render('list', context) 

    def view(self, id):
        obj=self.collection.find(self.pk_prop,id)
        context = self.__get_context()
        context['obj']=obj
        return 'view '+str(id)+' '+str(context)

    def edit(self, id):
        obj=self.collection.find(self.pk_prop,id)
        context = self.__get_context()
        context['obj']=obj
        context['form']=self.form
        context['form_data']=self.form.form_data(obj)
        
        if request.method == 'POST':
            data=self.form.form_data(request.form)
            errors=self.form.validate(data)
            if not errors:
                self.form.set_obj(request.form, obj)
                self.collection.update(obj)
                flash('<strong>{name}</strong> updated!'.format(name=self.get_label(obj)))
                return redirect(url_for('%s.list' % self.name, id=id))
            else:
                context['form_data']=data
                context['form_errors']=errors

        return self.render('edit', context) 

    def delete(self, id):
        obj=self.collection.find(self.pk_prop,id)
        context = self.__get_context()
        context['obj']=obj
        self.collection.delete(obj)
        flash('<strong>{name}</strong> deleted!'.format(name=self.get_label(obj)))
        return redirect(url_for('%s.list' % self.name))

    def new(self):
        obj=self.collection.new_object()
        context = self.__get_context()
        context['obj']=obj
        context['form']=self.form
        context['form_data']=self.form.form_data(obj)

        if request.method == 'POST':
            data=self.form.form_data(request.form)
            errors=self.form.validate(data)
            if not errors:
                self.form.set_obj(request.form, obj)
                self.collection.save(obj)
                flash('<strong>{name}</strong> created!'.format(name=self.get_label(obj)))
                return redirect(url_for('%s.list' % self.name))
            else:
                context['form_data']=data
                context['form_errors']=errors
                            
    
        return self.render('new', context) 

    def __get_context(self):
        ctx= { 'crud_name':self.name, 'crud':self }
        if self.parent:
            ctx['app']=self.parent
        if self.navigation_hint:
            ctx['navigation_hint']=self.navigation_hint
        return ctx    

    def get_tempalte(self,view):
        template='%s/%s/%s/%s.html' % (current_app.root_path,current_app.template_folder, self.name, view)
        if os.path.exists(template):
            return '%s/%s.html' % (self.name, view)
        return'crud/%s.html' % view 

    def render(self, view, context):
        return render_template( self.get_tempalte(view) , **context)  

    def get_label(self, obj):
        return obj

    def get_id(self, obj):
        return obj
    

    def register(self, app):
        id_name='<id>'
        if self.pk_type:
            id_name='<%s:id>' % self.pk_type

        app.add_url_rule('%sl' % self.url, '{0}.list'.format(self.name), self.list)   
        app.add_url_rule('%sv/%s' % (self.url,id_name), '{0}.view'.format(self.name), self.view)   
        app.add_url_rule('%se/%s' % (self.url, id_name), '{0}.edit'.format(self.name), self.edit, methods=['POST', 'GET'])   
        app.add_url_rule('%sd/%s' % (self.url, id_name), '{0}.delete'.format(self.name), self.delete)   
        app.add_url_rule('%sn' % self.url, '{0}.new'.format(self.name), self.new, methods=['POST', 'GET'])   
Exemplo n.º 19
0
 def main(self, username='', name='', email='', message=None, *args, **kwargs):
     form = Form(title="Add User", 
                     action="/sys/users/add/index", 
                     onsubmit="return md5ify('add_user_form', 'password')", 
                     name="add_user_form",
                     message=message)
     form.text = '<script type="text/javascript" src="/static/js/md5.js"></script>\n'+form.text
     form.text_input(_("Username"), name="username", value=username)
     form.text_input(_("Full name"), name="name", value=name)
     form.text_input(_("Email"), name="email", value=email)
     form.text_input(_("Password"), name="password")
     form.text_input(name="md5_password", type="hidden")
     form.submit(label=_("Create User"), name="create")
     return form.render()
Exemplo n.º 20
0
    def __init__(self, mt, title, choices,
                 prompt=None, line_skip=0, margin_top=0, prompt_line=None, addit=None,
                 cancelable=True
                 ):
        """
        Parameters:
            mt (:py:class:`Minitel`): the Minitel instance
            title (str or list of str): the menu title, displayed centered on the screen
            choices (list of str): the options
            prompt (str): the prompt displayed with the input field. Default: "Your choice"
            line_skip (int): vertical space between options. Default (0) places options on consecutive lines
            margin_top (int): vertical space before the menu title. Default: 0
            prompt_line (int): line number on which the input prompt is displayed
            addit (list of tuple): additional prompts as a list of (x, y, text) tuples
            cancelable (bool): if True, the cancel key (SOMMAIRE) can be used, and `get_choice` will exit
            and return None. If False, the cancel key will be treated as an invalid choice.
        """
        if not mt:
            raise ValueError('mt parameter is mandatory')

        if not choices:
            raise ValueError('choices parameter must be an iterable of option labels')

        if len(choices) < 2:
            raise ValueError('choices must contain at least 2 items')

        if isinstance(title, basestring):
            title = [title]

        if not prompt:
            prompt = "Your choice"

        addit = addit or []

        choice_max = len(choices)
        prompt = "%s [1..%d] : " % (prompt, choice_max)
        prompt_text = prompt + ('..' if choice_max > 9 else '.') + " + ENVOI"
        x_prompt = max(0, (40 - len(prompt_text)) / 2)

        form = Form(mt)

        y = margin_top
        for line in title:
            form.add_prompt(0, y, line.center(40))
            y += 1

        choice_lines = ["%2d - %s" % (i + 1, s) for i, s in enumerate(choices)]
        max_len = max(len(s) for s in choice_lines)
        x = max(0, (40 - max_len) / 2)
        y += 1
        y_inc = line_skip + 1
        for line in choice_lines:
            form.add_prompt(x, y, line)
            y += y_inc

        y = prompt_line or y + 1
        form.add_prompt(x_prompt, y, prompt_text)
        form.add_field('choice', x_prompt + len(prompt), y, 1 if choice_max < 10 else 2)

        for addit_prompt in addit:
            form.add_prompt(*addit_prompt)

        self._mt = mt
        self._form = form
        self._choice_max = choice_max
        self._cancelable = cancelable
Exemplo n.º 21
0
def custom_object_decoder(obj):
    if 'py/object' in obj:
        if obj['py/object'] == 'forms.Form':
            return Form.from_json(obj['name'], obj['path'])
    return obj
Exemplo n.º 22
0
    def test_discretize_lobatto(self):
        """Test the discretize method of the 2 - forms."""
        my_mesh = CrazyMesh(2, (2, 2), ((-1, 1), (-1, 1)), curvature=0)
        p_int_0 = 2
        for p in range(3, 8):
            filename = 'discrete_2_form_p' + \
                str(p) + '_p_int' + str(p_int_0) + '.dat'
            directory = os.getcwd() + '/src/tests/test_discrete_2_form/'
            func_space = FunctionSpace(my_mesh, '2-lobatto', p)
            form = Form(func_space)
            form.discretize(paraboloid, ('gauss', p_int_0))
            cochain_ref = np.loadtxt(directory + filename, delimiter=',')
            npt.assert_array_almost_equal(form.cochain_local,
                                          cochain_ref,
                                          decimal=4)
        p = 5
        for p_int in range(2, 6):
            filename = 'discrete_2_form_p' + \
                str(p) + '_p_int' + str(p_int_0) + '.dat'
            directory = os.getcwd() + '/src/tests/test_discrete_2_form/'
            func_space = FunctionSpace(my_mesh, '2-lobatto', p)
            form = Form(func_space)
            form.discretize(paraboloid, ('gauss', p_int_0))
            cochain_ref = np.loadtxt(directory + filename, delimiter=',')
            npt.assert_array_almost_equal(form.cochain_local,
                                          cochain_ref,
                                          decimal=4)

        p = 6
        p_int = 5
        filename_1 = 'discrete_2_form_p' + \
            str(p) + '_p_int' + str(p_int) + '_el_57.dat'
        directory = os.getcwd() + '/src/tests/test_discrete_2_form/'
        mesh_1 = CrazyMesh(2, (5, 7), ((-1, 1), (-1, 1)), curvature=0)
        func_space = FunctionSpace(mesh_1, '2-lobatto', p)
        form = Form(func_space)
        form.discretize(paraboloid, ('gauss', p_int))
        cochain_ref_1 = np.loadtxt(directory + filename_1, delimiter=',')
        npt.assert_array_almost_equal(form.cochain_local, cochain_ref_1)

        mesh_2 = CrazyMesh(2, (5, 7), ((-1, 1), (-1, 1)), curvature=0.2)
        filename_2 = 'discrete_2_form_p' + \
            str(p) + '_p_int' + str(p_int) + '_el_57_cc2.dat'
        directory = os.getcwd() + '/src/tests/test_discrete_2_form/'
        func_space = FunctionSpace(mesh_2, '2-lobatto', p)
        form = Form(func_space)
        form.discretize(paraboloid, ('gauss', p_int))
        cochain_ref_2 = np.loadtxt(directory + filename_2, delimiter=',')
        npt.assert_array_almost_equal(form.cochain_local, cochain_ref_2)
Exemplo n.º 23
0
    def state0(self, message="", hostname="", box_key="", submitted=False, username="", password="", **kwargs):
        """
        In this state, we do time config over HTTP, name the box and
        server key selection.

        All the parameters are form inputs.  They get passed in when
        the form is submitted.  This method checks the inputs and if
        they validate, uses them to take action.  If they do not
        validate, it displays the form to give the user a chance to
        input correct values.  It might display an error message (in
        the message parameter).

        message is an optional string that we can display to the
        user. It's a good place to put error messages.
        """

        # FIXME: reject connection attempt if db["state"] >= 5.

        ## Until LDAP is in place, we'll put the box name and key in the cfg.store_file
        ## Must resist the sick temptation to write an LDAP interface to the sqlite file
        with sqlite_db(cfg.store_file, table="thisbox", autocommit=True) as db:
            db['about'] = "This table is for information about this FreedomBox"
            if hostname:
                if '' == config.valid_hostname(hostname):
                    config.set_hostname(hostname)
                else:
                    message += _("Invalid box name: %s") % config.valid_hostname(hostname)
            else:
                hostname = config.get_hostname()
            if box_key:
                if self.valid_box_key_p(box_key):
                    db['box_key'] = box_key
                else:
                    message += _("Invalid key!")
            elif 'box_key' in db and db['box_key']:
                box_key = _("We already have a key for this box on file.") # TODO: Think this through and handle more gracefully.  Seriously.
            elif submitted and not box_key:
                box_key = self.generate_box_key()
                db['box_key'] = box_key
            if username and password:
                error = add_user(username, password, 'First user - please change', '', True)
                if error:
                    message += _("User account creation failed: %s") % error
                    validuser = False
                else:
                    validuser = True
            else:
                validuser = False

        if hostname and box_key and '' == config.valid_hostname(hostname) and self.valid_box_key_p(box_key) and validuser:
            ## Update state to 1 and head there
            with sqlite_db(cfg.store_file, table="firstboot", autocommit=True) as db:
                db['state']=1
            raise cherrypy.InternalRedirect('state1')

        main = "<p>Welcome.  It looks like this FreedomBox isn't set up yet.  We'll need to ask you a just few questions to get started.</p>"
        form = Form(title="Welcome to Your FreedomBox!",
                        action="", # stay at firstboot
                        name="whats_my_name",
                        message=message)
        form.html("<p>For convenience, your FreedomBox needs a name.  It should be something short that doesn't contain spaces or punctuation.  'Willard' would be a good name.  'Freestyle McFreedomBox!!!' would not.</p>")
        form.text_input('Name your FreedomBox', id="hostname", value=hostname)
        form.html("<p><strong>Initial user and password.</strong> Access to this web interface is protected by knowing a username and password.  Provide one here to register the initial privileged user.  The password can be changed and other users added later.</p>")
        form.text_input('Username:'******'Password:'******'password')
        form.html("<p>%(box_name)s uses cryptographic keys so it can prove its identity when talking to you.  %(box_name)s can make a key for itself, but if one already exists (from a prior FreedomBox, for example), you can paste it below.  This key should not be the same as your key because you are not your FreedomBox!</p>" % {'box_name':cfg.box_name})
        form.text_box("If you want, paste your box's key here.", id="box_key", value=box_key)
        form.hidden(name="submitted", value="True")
        form.submit("Box it up!")

        main += form.render()
        return self.fill_template(
            template="base",
            title=_("First Boot!"),
            main=main,
            sidebar_right=sidebar_right)
Exemplo n.º 24
0
 def main(self, username='', name='', email='', message=None, *args, **kwargs):
     form = Form(title="Add User",
                     action=cfg.server_dir + "/sys/users/add/index",
                     name="add_user_form",
                     message=message)
     form.text_input(_("Username"), name="username", value=username)
     form.text_input(_("Full name"), name="name", value=name)
     form.text_input(_("Email"), name="email", value=email)
     form.text_input(_("Password"), name="password", type="password")
     form.submit(label=_("Create User"), name="create")
     return form.render()
Exemplo n.º 25
0
    async def submitmap(self,
                        ctx,
                        map_code=None,
                        map_name=None,
                        map_type=None,
                        creator=None,
                        *,
                        desc=""):
        """Submit a map to database."""

        await ctx.message.delete()

        def map_code_regex(m):
            if re.match(r"^[a-zA-Z0-9]+$", m):
                return True

        def map_type_check(m):
            m = [convert_short_types(x.upper()) for x in m.split()]
            # Checks map_type(s) exists
            for x in m:
                if x not in constants.TYPES_OF_MAP:
                    return
            return True

        if map_code is None or map_name is None or map_type is None or creator is None:
            warn = None
            if any([map_code, map_name, map_type, creator
                    ]) and not all([map_code, map_name, map_type, creator]):
                warn = await ctx.send(
                    "There was some info missing. Please answer the following questions."
                )
            form = Form(ctx, "Map Submission Wizard", cleanup=True)

            form.add_question("What is the map code?",
                              "map_code",
                              v=map_code_regex)
            form.add_question(
                "What map is it?\nMany variations of map names work such as 'King's Row', 'Kings Row', 'kr', 'kings', 'kingsrow', etc.",
                "map_name",
                v=map_name_converter,
            )
            form.add_question(
                f"What is/are the map type(s)?\n{' | '.join(constants.TYPES_OF_MAP)}",
                "map_type",
                v=map_type_check,
            )
            form.add_question("Who is/are the map creator(s)?", "creator")
            form.add_question("What is the map description?", "desc")
            form.add_cancelkeyword("cancel")
            form.edit_and_delete(True)
            result = await form.start()
            if warn:
                await warn.delete()
            if result is None:
                cancel = await ctx.send("Map submission cancelled.")
                await asyncio.sleep(10)
                await cancel.delete()
                return

            map_code = result.map_code
            map_name = result.map_name
            map_type = [
                convert_short_types(x.upper())
                for x in result.map_type.split()
            ]
            creator = result.creator
            desc = result.desc
        else:
            if not map_code_regex(map_code):
                m = await ctx.send(
                    "Only letters A-Z and numbers 0-9 allowed in <map_code>. Map submission rejected."
                )
                await asyncio.sleep(10)
                await m.delete()
                return

            if not map_name_converter(map_name):
                m = await ctx.send(
                    "<map_name> doesn't exist! Map submission rejected. Use `/maps` for a list of acceptable maps."
                )
                await asyncio.sleep(10)
                await m.delete()
                return

            if not map_type_check(map_type):
                m = await ctx.send(
                    "<map_type> doesn't exist! Map submission rejected. Use `/maptypes` for a list of acceptable map types."
                )
                await asyncio.sleep(10)
                await m.delete()
                return

            map_type = [
                convert_short_types(x.upper()) for x in map_type.split()
            ]

        map_code = map_code.upper()
        count = await MapData.count_documents({"code": map_code})

        # map_code must be unique.
        if count != 0:
            await ctx.send(
                f"{map_code} already exists! Map submission rejected.")
            return

        new_map_name = map_name_converter(map_name)
        submission = MapData(**dict(
            code=map_code,
            creator=creator,
            map_name=new_map_name,
            desc=desc,
            posted_by=ctx.author.id,
            type=map_type,
        ))

        embed = await map_submit_embed(submission,
                                       "Is this submission correct?")

        msg = await ctx.send(embed=embed)
        confirmed = await confirmation.confirm(ctx, msg)

        # User confirmation with reactions
        if confirmed is True:
            await msg.edit(
                content=
                f"{constants.CONFIRM_REACTION_EMOJI} Confirmed! Map submission accepted."
            )
            await submission.commit()
            embed_copy = embed.to_dict()
            embed_copy["title"] = "New Map"
            e = discord.Embed.from_dict(embed_copy)
            new_map_channel = self.bot.get_channel(
                constants_bot.NEW_MAPS_CHANNEL_ID)
            await new_map_channel.send(embed=e)
        elif confirmed is False:
            await msg.edit(
                content=
                f"{constants.CANCEL_REACTION_EMOJI} Map submission rejected.")
        elif confirmed is None:
            await msg.edit(
                content="Submission timed out! Map submission rejected.")

        await asyncio.sleep(10)
        await msg.delete()
Exemplo n.º 26
0
    def state0(self, message="", box_name="", box_key="", submitted=False):
        """
        In this state, we do time config over HTTP, name the box and
        server key selection.

        All the parameters are form inputs.  They get passed in when
        the form is submitted.  This method checks the inputs and if
        they validate, uses them to take action.  If they do not
        validate, it displays the form to give the user a chance to
        input correct values.  It might display an error message (in
        the message parameter).

        message is an optional string that we can display to the
        user. It's a good place to put error messages.
        """

        ## Until LDAP is in place, we'll put the box name and key in the cfg.store_file
        ## Must resist the sick temptation to write an LDAP interface to the sqlite file
        with sqlite_db(cfg.store_file, table="thisbox", autocommit=True) as db:
            db['about'] = "This table is for information about this FreedomBox"
            if box_name:
                if self.valid_box_name_p(box_name): 
                    db['box_name'] = box_name
                else:
                    message += _("Invalid box name.")
            elif 'box_name' in db and db['box_name']:
                box_name = db['box_name']
                #TODO: set /etc/hostname to box name via ex machina

            if box_key: 
                if self.valid_box_key_p(box_key):
                    db['box_key'] = box_key
                else:
                    message += _("Invalid key!")
            elif 'box_key' in db and db['box_key']:
                box_key = _("We already have a key for this box on file.") #TODO: Think this through and handle more gracefully
            elif submitted and not box_key:
                box_key = self.generate_box_key()
                db['box_key'] = box_key


        if box_name and box_key and self.valid_box_name_p(box_name) and self.valid_box_key_p(box_key):
            ## Update state to 1 and head there
            with sqlite_db(cfg.store_file, table="firstboot", autocommit=True) as db:
                db['state']=1
            raise cherrypy.InternalRedirect('/firstboot/state1')

        main = "<p>Welcome.  It looks like this FreedomBox isn't set up yet.  We'll need to ask you a just few questions to get started.</p>"
        form = Form(title="Welcome to Your FreedomBox!", 
                        action="/firstboot", 
                        name="whats_my_name",
                        message=message)
        if not box_name:
            box_name = cfg.box_name
        form.html("<p>For convenience, your FreedomBox needs a name.  It should be something short that doesn't contain spaces or punctuation.  'Willard' would be a good name.  'Freestyle McFreedomBox!!!' would not.</p>")
        form.text_input('Name your FreedomBox', id="box_name", value=box_name)
        form.html("<p>%(box_name)s uses cryptographic keys so it can prove its identity when talking to you.  %(box_name)s can make a key for itself, but if one already exists (from a prior FreedomBox, for example), you can paste it below.  This key should not be the same as your key because you are not your FreedomBox!</p>" % {'box_name':cfg.box_name})
        form.text_box("If you want, paste your box's key here.", id="box_key", value=box_key)
        form.hidden(name="submitted", value="True")
        form.submit("Box it up!")

        main += form.render()
        return self.fill_template(template="base", title=_("First Boot!"), main=main,
        sidebar_right=_("""<strong>Getting Help</strong><p>We've done our best to make your FreedomBox easy to use.  If you have questions during setup, there are a few places to turn for help. TODO: add links to such help.</p>"""))
Exemplo n.º 27
0
	def __init__(self, one_shot=False):
		root = Tk()
		root.title("Getfile GUI")
		labels = ["Server Name", "Port Number", "File Name", "Local Dir?"]
		Form.__init__(self, labels, root)
		self.one_shot = one_shot
Exemplo n.º 28
0
    def main(self, message='', **kwargs):
        sys_store = filedict_con(cfg.store_file, 'sys')
        hostname = cfg.exmachina.augeas.get("/files/etc/hostname/*")
        # this layer of persisting configuration in sys_store could/should be
        # removed -BLN
        defaults = {'time_zone': "slurp('/etc/timezone').rstrip()",
                    'hostname': "hostname",
                    }
        for k,c in defaults.items():
            if not k in kwargs:
                try:
                    kwargs[k] = sys_store[k]
                except KeyError:
                    exec("if not '%(k)s' in kwargs: sys_store['%(k)s'] = kwargs['%(k)s'] = %(c)s" % {'k':k, 'c':c})
        # over-ride the sys_store cached value
        kwargs['hostname'] = hostname

        ## Get the list of supported timezones and the index in that list of the current one
        module_file = __file__
        if module_file.endswith(".pyc"):
            module_file = module_file[:-1]
        time_zones = json.loads(slurp(os.path.join(os.path.dirname(os.path.realpath(module_file)), "time_zones")))
        for i in range(len(time_zones)):
            if kwargs['time_zone'] == time_zones[i]:
                time_zone_id = i
                break

        ## A little sanity checking.  Make sure the current timezone is in the list.
        try:
            cfg.log('kwargs tz: %s, from_table: %s' % (kwargs['time_zone'], time_zones[time_zone_id]))
        except NameError:
            cfg.log.critical("Unknown Time Zone: %s" % kwargs['time_zone'])
            raise cherrypy.HTTPError(500, "Unknown Time Zone: %s" % kwargs['time_zone'])

        ## And now, the form.
        form = Form(title=_("General Config"), 
                        action="/sys/config/general/index", 
                        name="config_general_form",
                        message=message )
        form.html(self.help())
        form.dropdown(_("Time Zone"), name="time_zone", vals=time_zones, select=time_zone_id)
        form.html("<p>Your hostname is the local name by which other machines on your LAN can reach you.</p>")
        form.text_input('Hostname', name='hostname', value=kwargs['hostname'])
        form.submit(_("Submit"))
        return form.render()
Exemplo n.º 29
0
    def main(self, message="", **kwargs):
        sys_store = filedict_con(cfg.store_file, "sys")
        defaults = {"time_zone": "slurp('/etc/timezone').rstrip()", "hostname": "gethostname()"}
        for k, c in defaults.items():
            if not k in kwargs:
                try:
                    kwargs[k] = sys_store[k]
                except KeyError:
                    exec("if not '%(k)s' in kwargs: sys_store['%(k)s'] = kwargs['%(k)s'] = %(c)s" % {"k": k, "c": c})

        ## Get the list of supported timezones and the index in that list of the current one
        module_file = __file__
        if module_file.endswith(".pyc"):
            module_file = module_file[:-1]
        time_zones = json.loads(slurp(os.path.join(os.path.dirname(os.path.realpath(module_file)), "time_zones")))
        for i in range(len(time_zones)):
            if kwargs["time_zone"] == time_zones[i]:
                time_zone_id = i
                break

        ## A little sanity checking.  Make sure the current timezone is in the list.
        try:
            cfg.log("kwargs tz: %s, from_table: %s" % (kwargs["time_zone"], time_zones[time_zone_id]))
        except NameError:
            cfg.log.critical("Unknown Time Zone: %s" % kwargs["time_zone"])
            raise cherrypy.HTTPError(500, "Unknown Time Zone: %s" % kwargs["time_zone"])

        ## And now, the form.
        form = Form(
            title=_("General Config"), action="/sys/config/general/index", name="config_general_form", message=message
        )
        form.html(self.help())
        form.dropdown(_("Time Zone"), name="time_zone", vals=time_zones, select=time_zone_id)
        form.html("<p>Your hostname is the local name by which other machines on your LAN can reach you.</p>")
        form.text_input("Hostname", name="hostname", value=kwargs["hostname"])
        form.submit(_("Submit"))
        return form.render()