Example #1
0
def console():
    username = session.get("username")
    session_token = request.cookies.get("session_token")
    # _xsrf = request.cookies.get('_xsrf')
    if not session_token:
        return redirect(url_for("login"))
    user = Developer()
    user.session_token = session_token
    if request.method == "POST":
        print request.form
        app_name = request.form["appname"]
        result = user.create_new_app(app_name)
        if not result:
            print "error when create new app"

        # remember = request.form['remember']
        # if user.signup(email=email,username=username,password=password):
        #     return redirect(url_for('login',_anchor='signin'))
        # else:
        #     return redirect(url_for('login',_anchor='signup'))
    if user.get_all_application():
        all_application_dict = user.all_application_dict
    else:
        print "no application  exists"
        all_application_dict = {}
    print "all_application_dict is : %s" % (str(all_application_dict))
    return render_template("console.html", username=username, all_application_dict=all_application_dict)
Example #2
0
def login():
    username = session.get("username")
    session_token = session.get("session_token")
    # session_token = request.cookies.get('session_token')
    # 暂时不验证session_token的有效性
    if session_token:
        return redirect(url_for("index"))

    user = Developer()
    error = None
    if request.method == "POST":
        print "got the post request"
        print request.form
        # email=request.form['email']
        username = request.form["username"]
        password = request.form["password"]
        remember = request.form.get("remember")
        result = user.login_with_username(username=username, password=password)
        if result:
            print "redirecting to console"
            session["username"] = username
            session["session_token"] = user.session_token
            resp = make_response(redirect(url_for("console")))
            # resp.set_cookie('expiration',get_expiration())
            expires = get_expiration() if remember == "on" else None
            resp.set_cookie("_xsrf", generate_xsrf_token())
            resp.set_cookie("session_token", user.session_token, expires=expires)
            return resp
        else:
            return redirect(url_for("login"))
    return make_response(render_template("login.html", error=error))
Example #3
0
def upload_system(demand_id):
    """
    The '/bid/<demand_id>/upload-system' route is where the developer can upload the system that
    they have created for a demand they have been chosen for.
    """
    form = SubmitSystemForm()
    demand_info = Demand.get_info(demand_id)
    client = demand_info['client_username']

    if request.method == 'POST':
        if form.validate():
            # will not actually store the file
            # project is now completed
            Developer.submit_system(demand_id, session['username'])
            return redirect(
                url_for('rating', demand_id=demand_id, recipient=client))
        else:
            return render_template("upload_system.html",
                                   demand_id=demand_id,
                                   form=form)

    if request.method == 'GET':
        return render_template("upload_system.html",
                               demand_id=demand_id,
                               form=form)
Example #4
0
def dashboard():
    """
    The '/dashboard' route directs a user to view their dashboard.
    """
    if 'username' in session:
        if not session['type_of_user'] == "user":
            return render_template("access_denied.html")

        info = User.get_user_info(session['username'])
        if (info == None):
            return render_template("dashboard.html", first_name=" ")
        first_name = info['first_name']

        # Get notifications for this user.
        unread = Notification.get_number_of_unread(session['username'])
        notifications = Notification.get_notif_to_recipient(
            session['username'], 5)

        # If the user has no projects in history, they are a new user.
        user_type = User.get_user_info(session['username'])['type_of_user']
        recs = {
            "client_rec_des": "Most Active Clients",
            "dev_rec_des": "Most Active Developers",
            "client_rec": Client.get_most_active_clients(),
            "dev_rec": Developer.get_most_active_developers()
        }

        if user_type == 'client':
            if Client.get_info(
                    session['username'])['num_of_completed_projects'] > 0:
                recs = {
                    "client_rec_des":
                    "Clients with Similar Interests",
                    "dev_rec_des":
                    "Developers with Similar Interests",
                    "client_rec":
                    Client.get_similar_clients(session['username']),
                    "dev_rec":
                    Developer.get_similar_developers(session['username'])
                }
        elif user_type == 'developer':
            if Developer.get_info(
                    session['username'])['num_of_completed_projects'] > 0:
                recs = {
                    "client_rec_des":
                    "Clients with Similar Interests",
                    "dev_rec_des":
                    "Developers with Similar Interests",
                    "client_rec":
                    Client.get_similar_clients(session['username']),
                    "dev_rec":
                    Developer.get_similar_developers(session['username'])
                }
        return render_template("dashboard.html",
                               first_name=first_name,
                               notifications=notifications,
                               recs=recs,
                               unread=unread)
    else:
        return redirect(url_for('login'))
Example #5
0
def user(name):
    """
    The '/user/<name>' route directs a user to the profile page of the user with the username
    of [name].
    """
    # if User.has_user_id(name):
    # get basic info
    info = User.get_user_info(name)

    if info['type_of_user'] == 'client':
        rating = Client.get_info(name)['avg_rating']
        projects = Client.get_projects_posted(name)
    elif info['type_of_user'] == 'developer':
        rating = Developer.get_info(name)['avg_rating']
        projects = Developer.get_past_projects(name)

    projects_info = []

    for demand_id in projects:
        projects_info.append(Demand.get_info(demand_id))

    # round rating to the nearest 0.5
    rating = round(0.5 * round(float(rating) / 0.5), 1)
    has_half_star = rating % 1 == .5

    return render_template("profile.html",
                           info=info,
                           rating=int(rating),
                           half_star=has_half_star,
                           projects=projects_info)
Example #6
0
def delete():
    # username = session.get('username')
    session_token = session.get("session_token")

    if not session_token:
        print "session_token not exists!"
        return None

    # app_name = app_name
    # app_id = request.args.get('app_id')
    # print 'the app_id of the app is: %s' %(str(app_id))

    user = Developer()
    user.session_token = session_token
    # print 'The form is: %s' %(str(request.form))
    # _xsrf = request.form.get('_xsrf')
    app_id = request.form.get("app_id")

    dashboard = Dashboard()
    dashboard.app_id = app_id

    res = user.delete_app(app_id=app_id, kind=None)
    if res == 0:
        response_json = {"delete": "success"}
        return jsonify(response_json)
    else:
        response_json = {"delete": "failed"}
        return jsonify(response_json)
Example #7
0
  def post_developers(jwt):

    error = False
    body = request.get_json()
    #print(body)
    name = body.get('name')
    #print(name)
    proj_participation = body.get('proj_participation')
    #print(proj_participation)

    new_developer = Developer(name=name, proj_participation=proj_participation)

    try:
      new_developer.insert()
      #flash('New Developer ' + str(new_developer.name) + ' was successful listed!')
    except Exception as e:
      error = True
      print(e)
      #flash('An error occurred. New Developer ' + str(new_developer.name) + ' could not be listed.')
    if error:
      abort(400)
    else:
      return jsonify({
        'success': True,
        'name': name,
        'proj_participation': proj_participation
      }), 200
Example #8
0
def dashboard():
    username = session.get("username")
    session_token = session.get("session_token")
    print username
    print "session_token+", session_token

    # if not session_token:
    #    return redirect(url_for('index'))

    # change app_name & app_id as demo for test
    app_name = request.args.get("app_name")
    app_id = request.args.get("app_id")
    app_id = "demo55bc5d8e00b0cb9c40dec37b"
    print "the app_id of the app is: %s" % (str(app_id))

    user = Developer()
    user.session_token = session_token
    if user.get_all_application():
        all_application_dict = user.all_application_dict
    else:
        print "no application  exists"
        all_application_dict = {}
    print "all_application_dict is : %s" % (str(all_application_dict))
    if app_name and app_id:
        del all_application_dict[app_name]
    else:
        app_name = all_application_dict.keys()[0]
        app_id = all_application_dict[app_name]
        del all_application_dict[app_name]
    dashboard = Dashboard()
    dashboard.app_id = app_id

    # 存到session中是为了在dash中使用
    session["app_name"] = app_name
    session["app_id"] = app_id

    if request.method == "POST":
        is_xhr = True
    else:
        is_xhr = False
    dashboard_link = "/dashboard/"

    return render_template(
        "dashboard.html",
        is_xhr=is_xhr,
        dashboard_link=dashboard_link,
        route_link="dashboard",
        # sort according to ['16down', '16to35', '35to55', '55up']
        # discard unknown data
        username=username,
        app_name=app_name,
        app_id=app_id,
        all_application_dict=all_application_dict,
    )
Example #9
0
def index():
    number_of_clients = Client.get_number_of_clients()
    number_of_developers = Developer.get_number_of_developers()
    # clients with the most projects
    top_clients = Client.get_clients_with_most_projects()
    # developers making the most money
    top_devs = Developer.get_top_earners()
    return render_template("index.html",
                           number_of_clients=number_of_clients,
                           number_of_developers=number_of_developers,
                           top_clients=top_clients,
                           top_devs=top_devs)
Example #10
0
def dashboard_applicant():
    """
    The 'dashboard_applicant' route directs an applicant to their dashboard. 
    They can view the status of their application here.
    """
    if session['username']:
        form = BecomeUserForm()
        info = Applicant.get_applicant_info(session['username'])

        if session['type_of_user'] == 'applicant' and request.method == 'GET':
            return render_template("dashboard_applicant.html",
                                   info=info,
                                   form=form)
        if session['type_of_user'] == 'applicant' and request.method == 'POST':
            info = Applicant.get_applicant_info(session['username'])
            if form.use_prev_credentials.data == 'yes':
                User.use_old_credentials(info['user_id'], info['email'])
                session['type_of_user'] = '******'
                session['role'] = info['type_of_user']
                # Create a new client or developer in database depending on type of user
                if info['type_of_user'] == 'client':
                    Client(info['user_id'])
                elif info['type_of_user'] == 'developer':
                    Developer(info['user_id'])
                return redirect(url_for('dashboard'))

            elif form.validate():
                User.set_credentials(form.username.data, form.password.data,
                                     info['email'])
                session['username'] = form.username.data
                session['type_of_user'] = '******'
                session['role'] = info['type_of_user']
                # Create a new client or developer in database depending on type of user
                if info['type_of_user'] == 'client':
                    Client(form.username.data)
                elif info['type_of_user'] == 'developer':
                    Developer(form.username.data)
                return redirect(url_for('dashboard'))
            else:
                flash(
                    'Login credentials are invalid. Please check that all fields are filled correctly.'
                )
                return render_template("dashboard_applicant.html",
                                       info=info,
                                       form=form)
        elif session['type_of_user'] == 'user':
            return redirect(url_for('dashboard'))
        elif session['type_of_user'] == 'superuser':
            return redirect(url_for('dashboard_superuser'))

    else:
        return render_template("index.html")
Example #11
0
    def get(self, this_id=None):
        self.tv["current_page"] =  "DEVELOPER"
        if this_id:
            developer = Developer.get_by_id(normalize_id(this_id))
            self.tv["developer"] = developer
        else:
            developers = Developer.query().fetch(100)
            self.tv["developers"] = []

            for developer in developers:
                self.tv["developers"].append(developer.to_object())

            self.render('frontend/developer.html')
Example #12
0
def add_funds():
    """
    Allows the user to add funds to their account.
    """
    if 'username' not in session:
        return redirect(url_for('login'))
    else:
        if session['type_of_user'] == "user":
            cc = str(User.get_user_info(session['username'])["credit_card"])
            cc = "******" + cc[-4:]

            balance = 0
            if session['type_of_user'] == "developer":
                balance = Developer.get_info(session['username'])["balance"]
            else:
                balance = Client.get_info(session['username'])["balance"]

            form = AddFundsForm()

            if request.method == "GET":
                return render_template("addFunds.html",
                                       cc=cc,
                                       form=form,
                                       balance=balance,
                                       added=False)
            elif request.method == "POST":
                if form.amount.validate(form):
                    if session['type_of_user'] == "developer":
                        Developer.add_earnings(session['username'],
                                               form.amount.data)
                        balance = Developer.get_info(
                            session['username'])["balance"]
                    else:
                        Client.add_to_balance(session['username'],
                                              form.amount.data)
                        balance = Client.get_info(
                            session['username'])["balance"]
                    return render_template("addFunds.html",
                                           cc=cc,
                                           form=form,
                                           balance=balance,
                                           added=True)
                else:
                    return render_template("addFunds.html",
                                           cc=cc,
                                           form=form,
                                           balance=balance,
                                           added=False)
        else:
            return render_template("access_denied.html")
Example #13
0
def track():
    username = session.get("username")
    session_token = session.get("session_token")

    if not session_token:
        return redirect(url_for("login"))
    user = Developer()
    user.session_token = session_token
    if user.get_all_application():
        all_application_dict = user.all_application_dict
    else:
        print "no application  exists"
        all_application_dict = {}
    app_name = request.args.get("app_name")
    app_id = request.args.get("app_id")
    if app_name and app_id:
        del all_application_dict[app_name]
    else:
        app_name = all_application_dict.keys()[0]
        app_id = all_application_dict[app_name]
        del all_application_dict[app_name]

    if request.method == "POST":
        print request.form
        tracker_id = request.form["tracker_id"]
        app_id = request.form["app_id"]

        result = user.connect_new_tracker(tracker_id=tracker_id, app_id=app_id)
        if not result:
            return "error when connect new tracker"
        else:
            return "success"
    else:
        if user.get_all_tracker():
            all_tracker_dict = user.all_tracker_dict
        else:
            print "no application  exists"
            all_tracker_dict = {}
        print "all_tracker_dict is : %s" % (str(all_tracker_dict))
        return render_template(
            "track.html",
            route_link="track",
            username=username,
            all_tracker_dict=all_tracker_dict,
            app_name=app_name,
            app_id=app_id,
            all_application_dict=all_application_dict,
        )
Example #14
0
    def post(self):
        form = ForgotPasswordEmailForm(self.request.POST)
        if form.validate():
            d = Developer.query(Developer.email == form.email.data).get()
            if d:
                d.password_reset_token = base64.urlsafe_b64encode(
                    os.urandom(12))
                d.put()

                message = mail.EmailMessage(sender="FROM_EMAIL",
                                            to=d.email,
                                            subject="Legit Dev Password Reset",
                                            body="""
Someone (hopefully you) has requested a reset of your Legit Developer account password. If it was you, click the link below to
reset your password. If it wasn't you, delete this email and we can forget this whole thing ever happened.\n\n
%s%s?%s
""" % (SITE_DOMAIN, self.uri_for('forgot_password_set'),
                urlencode({
                'email': d.email,
                'token': d.password_reset_token
                })))
                message.send()

                return self.redirect_to("forgot_password_sent")
            else:
                self.session.add_flash(
                    "Couldn't find a developer account with that email.",
                    "local")
        self.render_response("auth/forgot_password_email.html", form=form)
    def get(self):
        self.response.headers.add_header('Access-Control-Allow-Origin', '*')
        self.response.headers['Content-Type'] = 'application/json'

        id_user = self.request.get('user')
        objemp = Usuarios.query(Usuarios.email == id_user).get()

        if objemp is None:
            myList = []
            json_string = json.dumps(myList, default=MyClass)
            self.response.write(json_string)
            return None

        strKey = objemp.key.urlsafe()
        ownerKey = ndb.Key(urlsafe=strKey)

        myEntities = Developer.query(Developer.user_key == ownerKey)

        myList = []
        for i in myEntities:
            myObj = DemoClass()

            myObj.entityKey = i.entityKey
            myObj.nameA = i.nameA
            myObj.location = i.location
            myObj.year = i.year
            myObj.logo = i.logo

            myList.append(myObj)

        json_string = json.dumps(myList, default=MyClass)
        self.response.write(json_string)
Example #16
0
def demo():

    username = session.get("username")
    session_token = session.get("session_token")
    if not session_token:
        return redirect(url_for("index"))

    user = Developer()
    user.session_token = session_token
    if user.get_all_demo_application():
        all_demo_application_dict = user.all_demo_application_dict  # 一旦上一步执行成功,会给user添加一个成员变量 all_demo_application_dict
    else:
        print "no demo application  exists"
        all_demo_application_dict = {}
    print "all_demo_application_dict is : %s" % (str(all_demo_application_dict))
    if DEMO_APP_NAME in all_demo_application_dict.keys():
        app_name = DEMO_APP_NAME
        app_id = all_demo_application_dict[app_name]
    else:
        "Demo not exists"
        app_name = None
        app_id = None
    session["app_name"] = app_name
    session["app_id"] = app_id
    # del all_demo_application_dict[app_name]
    print "app_name is %s and app_id is %s" % (str(app_name), str(app_id))
    dashboard = Dashboard()
    dashboard.app_id = app_id
    # all_app_event = 1
    if request.method == "POST":
        is_xhr = True
    else:
        is_xhr = False
    dashboard_link = "/demo"

    return render_template(
        "demo.html",
        is_xhr=is_xhr,
        dashboard_link=dashboard_link,
        route_link="dashboard",
        # sort according to ['16down', '16to35', '35to55', '55up']
        # discard unknown data
        username=username,
        app_name=app_name,
        app_id=app_id,
        all_application_dict={},
    )
Example #17
0
def ajax_dashboard(param):
    # username = session.get('username')
    session_token = session.get("session_token")

    if not session_token:
        print "session_token not exists!"
        return None

    # app_name = app_name
    # app_id = request.args.get('app_id')
    # print 'the app_id of the app is: %s' %(str(app_id))

    user = Developer()
    user.session_token = session_token
    # print 'The form is: %s' %(str(request.form))
    # print 'Param is: %s' %(str(param))
    # _xsrf = request.form.get('_xsrf')
    app_id = request.form.get("app_id")

    dashboard = Dashboard()
    dashboard.app_id = app_id

    if param == "profile":
        category = request.form.get("category")
        print "before get_profile_option"
        option = dashboard.get_profile_option(category=category, kind=None)
        print "Option is: %s" % (str(option))
        return jsonify(option)
        pass
    elif param == "path":
        category = request.form.get("category")
        option = dashboard.get_path_option(category=category, kind=None)
        return jsonify(option)
        pass
    elif param == "behavior":
        event_name = request.form.get("event")
        category = request.form.get("category")
        option = dashboard.get_event_option(event_name=event_name, category=category, kind=None)
        print "after get_event_option"
        print "Option is: %s" % (str(option))
        return jsonify(option)
        pass
    else:
        return None
        pass
Example #18
0
def generatekey():
    content=request.json
    if 'token' in content:
        token=content['token']
        token=loggedIn(token)
        if token is not None:
            user=token.user[0]
            if len(user.keys)>4:
                return jsonify({"details":"Limit number of keys reached"}),400
            devkey=tokenvalue=''.join(random.SystemRandom().choice(string.ascii_uppercase + string.digits + string.ascii_lowercase) for _ in range(128))
            dev=Developer(devkey)
            dev.user=user
            db_session.add(dev)
            db_session.commit()
            return jsonify({"details":"Key Generated"}),200
        jsonify({"details":"Not authorized"}),401
    
    return jsonify({"details":"Wrong data"}),400
Example #19
0
 def get(self):
     token = self.request.GET.get('token')
     email = self.request.GET.get('email')
     d = Developer.query(ndb.StringProperty('password_reset_token') == token, Developer.email == email).get()
     if not d:
         self.session.add_flash("Invalid password reset link. Please generate a fresh one.", "local")
         return self.redirect_to('forgot_password_email')
     form = ForgotPasswordSetForm(self.request.GET)            
     self.render_response("auth/forgot_password_set.html", form=form)
Example #20
0
 def clean_alias(self):
     alias = self.cleaned_data["alias"].strip()
     
     if re.match("^([\w\d_]+)$", alias) is None:
         raise forms.ValidationError(_("alias not valid, use only letters, numbers or underscores"))
             
     if Developer.all(keys_only=True).filter("alias =", alias).get(): 
         raise forms.ValidationError(_("alias not available"))
     
     return alias
Example #21
0
 def post(self):
     form = ForgotPasswordSetForm(self.request.POST)
     if form.validate():
         d = Developer.query(ndb.StringProperty('password_reset_token') == form.token.data, 
                             Developer.email == form.email.data).get()
         d.password = security.generate_password_hash(form.new_password.data, length=12)
         d.put()
         self.auth.set_session(self.auth.store.user_to_dict(d))
         return self.redirect_to('profile')
     self.render_response("auth/forgot_password_set.html", form=form)    
Example #22
0
def signup():
    username = session.get("username")
    print str(request.form)
    # user_id = session.get('user')
    if username:
        return redirect(url_for("dashboard", username=username))
    user = Developer()
    if request.method == "POST":
        print request.form
        email = request.form["email"]
        username = request.form["username"]
        password = request.form["password"]
        # remember = request.form['remember']
        if user.signup(email=email, username=username, password=password):
            flash("Successfully sign up,please login in!")
            return redirect(url_for("login", _anchor="signin"))
        else:
            flash("Sign up failed,please try again!")
            return redirect(url_for("login", _anchor="signup"))
Example #23
0
    def get(self):
        self.tv["current_page"] = "CREATE LIST"

        self.tv["amenities"] = PROPERTY_AMENITIES
        developers = Developer.query().fetch(100)

        self.tv["developers"] = []
        for developer in developers:
            self.tv["developers"].append(developer.to_object())

        self.render("frontend/createlists.html")
Example #24
0
 def post(self):
     form = ForgotPasswordSetForm(self.request.POST)
     if form.validate():
         d = Developer.query(
             ndb.StringProperty('password_reset_token') == form.token.data,
             Developer.email == form.email.data).get()
         d.password = security.generate_password_hash(
             form.new_password.data, length=12)
         d.put()
         self.auth.set_session(self.auth.store.user_to_dict(d))
         return self.redirect_to('profile')
     self.render_response("auth/forgot_password_set.html", form=form)
Example #25
0
 def get(self):
     token = self.request.GET.get('token')
     email = self.request.GET.get('email')
     d = Developer.query(
         ndb.StringProperty('password_reset_token') == token,
         Developer.email == email).get()
     if not d:
         self.session.add_flash(
             "Invalid password reset link. Please generate a fresh one.",
             "local")
         return self.redirect_to('forgot_password_email')
     form = ForgotPasswordSetForm(self.request.GET)
     self.render_response("auth/forgot_password_set.html", form=form)
Example #26
0
def protest_approval(warning_id):
    """
    The '/protest_approval/<warning_id>' route directs a superuser to approve a protest against a warning
    with the id of [warning_id].
    """
    if session['type_of_user'] == 'user':
        return redirect(url_for('dashboard'))
    if session['type_of_user'] == 'applicant':
        return redirect(url_for('dashboard_applicant'))

    warning_id = int(warning_id)
    info = SystemWarning.get_warning_info(warning_id)
    username = info['warned_user']
    type_of_user = User.get_user_info(username)['type_of_user']
    avg_rating = 0
    if type_of_user == 'client':
        avg_rating = Client.get_info(username)['avg_rating']
    elif type_of_user == 'developer':
        avg_rating = Developer.get_info(username)['avg_rating']

    form = ProtestApprovalForm()

    if request.method == 'GET':
        return render_template("protestApproval.html",
                               warning_id=warning_id,
                               info=info,
                               form=form,
                               avg_rating=avg_rating)
    if request.method == 'POST':
        if form.validate():
            if form.decision.data == 'remove':
                SystemWarning.remove_warning(warning_id)
                Notification(
                    username, session['username'],
                    'Your protest for warning#' + str(warning_id) +
                    ' was approved. Your warning has been deleted.')
            else:
                SystemWarning.keep_warning(warning_id)
                Notification(
                    username, session['username'],
                    'Your protest for warning#' + str(warning_id) +
                    ' was not approved. Your warning remains.')
            return redirect(url_for('dashboard_superuser'))
        else:
            return render_template("protestApproval.html",
                                   warning_id=warning_id,
                                   info=info,
                                   form=form,
                                   avg_rating=avg_rating)
Example #27
0
def choose_developer(demand_id):
    """
    The '/bid/<demand_id>/choose-developer' route directs a client to a page
    where he/she can select the developer he/she wants to hire to implement the
    system that was demanded.
    """
    demand_info = Demand.get_info(demand_id)

    bids = Bid.get_bids_for_demand(demand_id)
    bids_info = []
    bidders_info = {}

    for bid in bids:
        info = Bid.get_info(bid)
        bids_info.append(info)

        if info['developer_username'] not in bidders_info:
            username = info['developer_username']
            bidders_info[username] = User.get_user_info(username)
            bidders_info[username]['lowest_bid'] = info['bid_amount']

            rating = Developer.get_info(username)['avg_rating']
            # round rating to the nearest 0.5
            rating = round(0.5 * round(float(rating) / 0.5), 1)
            bidders_info[username]['full_stars'] = int(rating)
            bidders_info[username]['has_half_star'] = rating % 1 == .5

    if request.method == 'POST':
        chosen_developer = request.form['developer']
        session['chosen_developer'] = request.form['developer']

        # if the chosen developer had the lowest bid,
        # update the demand's chosen developer
        if chosen_developer == bids_info[0]['developer_username']:
            # updates the table, notifies the developer, and also starts the transaction request
            Demand.choose_developer(demand_id, chosen_developer,
                                    session['username'],
                                    bids_info[0]['bid_amount'])
            return render_template("developer_chosen.html")

        # if the chosen developer did not have the lowest bid,
        # the client must provide a reason for choosing this developer
        else:
            return redirect(
                url_for('justify_developer_choice', demand_id=demand_id))
    if request.method == 'GET':
        return render_template("choose_developer.html",
                               demand_id=demand_id,
                               bidders_info=bidders_info)
Example #28
0
 def done(self, request, form_list):
     
     cleaned_data = {}
     [cleaned_data.update(form.cleaned_data) for form in form_list]
     
     import logging
     logging.info(cleaned_data)
     
     form = DeveloperForm(cleaned_data)
     developer = Developer(
       user = request.user,
       alias = cleaned_data['alias'], 
       email_contact = cleaned_data['email_contact'] or None,
       first_name = cleaned_data['first_name'],
       last_name = cleaned_data['last_name'],                                
       location = cleaned_data['location'] or None,
       location_description = cleaned_data['location_description'] or None,
       country = cleaned_data['country'],
       phone = cleaned_data['phone'] or None,
       personal_blog = cleaned_data['personal_blog'] or None,
       personal_page = cleaned_data['personal_page'] or None,
       public_contact_information = True,
       about_me = cleaned_data['about_me'] or None,
       python_sdk = "python" in cleaned_data['sdks'],
       java_sdk = "java" in cleaned_data['sdks'],
       tags = cleaned_data['tags'] or []
     )
     developer.put()
     
     taskqueue.add(url=reverse("users_fusiontable_insert", args=[str(developer.key())]))
     taskqueue.add(url=reverse("country_update_country", kwargs={'country_code': developer.country}))
     
     request.flash['message'] = unicode(_("Welcome!"))
     request.flash['severity'] = "success"
     
     return HttpResponseRedirect(reverse('users_avatar_change'))
Example #29
0
File: tests.py Project: jsphyin/idb
    def test_add_Developer3(self):

        with app.test_request_context():
            developer3 = Developer()
            init_len = len(Developer.query.all())
            db.session.add(developer3)
            db.session.commit()
            changed_len = len(Developer.query.all())
            self.assertEqual(init_len + 1, changed_len)

            init_len = changed_len
            db.session.delete(developer3)
            db.session.commit()
            changed_len = len(Developer.query.all())
            self.assertEqual(init_len - 1, changed_len)
Example #30
0
def get_consumer(key=None, secret=None):
    """
    Look up a developer based on their consumer key/secret.
    """
    if not key and not secret:
        raise ValueError("You must specify at least one consumer property to do a lookup.")

    q = Developer.query()    
    if key:
        q = q.filter(Developer.consumer_key == key)    
    if secret:
        q = q.filter(Developer.consumer_secret == secret)    
    consumer = q.get()

    return consumer
Example #31
0
def get_consumer(key=None, secret=None):
    """
    Look up a developer based on their consumer key/secret.
    """
    if not key and not secret:
        raise ValueError(
            "You must specify at least one consumer property to do a lookup.")

    q = Developer.query()
    if key:
        q = q.filter(Developer.consumer_key == key)
    if secret:
        q = q.filter(Developer.consumer_secret == secret)
    consumer = q.get()

    return consumer
Example #32
0
def my_projects():
    """
    The '/dashboard/projects' route directs a user to view their projects.
    """
    if 'username' in session:
        if not session['type_of_user'] == "user":
            return render_template("access_denied.html")

        user_type = User.get_user_info(session['username'])['type_of_user']
        current = list(
            Demand.get_info(x)
            for x in Demand.get_current_projects(session['username']))
        mid = []
        completed = []
        if user_type == "developer":
            bids_by_username = Bid.get_bids_by_username(session['username'])
            temp = []

            for i in bids_by_username:
                info = Bid.get_info(i)['demand_id']
                if info not in temp:
                    temp.append(info)

            mid = list(Demand.get_info(y) for y in temp)
            completed = list(
                Demand.get_info(x)
                for x in Developer.get_past_projects(session['username']))
        else:
            temp = (Demand.get_info(x) for x in Demand.get_filtered_demands(
                None, None, session['username'], None, None, None, True))
            for demand in temp:
                if demand['chosen_developer_username'] is np.nan:
                    mid.append(demand)
            completed = list(
                Demand.get_info(x)
                for x in Client.get_past_projects(session['username']))

        return render_template("myProjects.html",
                               user_type=user_type,
                               current=current,
                               mid=mid,
                               completed=completed)
    else:
        return redirect(url_for('login'))
Example #33
0
    def post(self, this_id=None):
        self.tv["current_page"] =  "DEVELOPER"
        if this_id:
            developer = Developer.get_by_id(normalize_id(this_id))
        else:
            developer = Developer(id=self.request.get("CODE").strip())

        developer.name = self.request.get("developer_name").strip()
        developer.contacts = self.request.get("developer_contact").strip()

        developer.put()

        self.redirect("/developer?success=successfully added!")
Example #34
0
File: tests.py Project: jsphyin/idb
    def test_add_Developer2(self):

        with app.test_request_context():
            developer2 = Developer(id=1000000,
                                   name="developer2",
                                   image="www.test_image2.com",
                                   desc="This is a test developer 2.",
                                   raw_desc="Test developer 2",
                                   website="www.developer2.com")
            db.session.add(developer2)
            db.session.commit()

            gamequery = db.session.query(Developer).filter_by(
                id="1000000").first()
            self.assertEqual(gamequery.desc, "This is a test developer 2.")
            self.assertEqual(gamequery.raw_desc, "Test developer 2")
            self.assertEqual(gamequery.website, "www.developer2.com")

            db.session.delete(developer2)
            db.session.commit()
Example #35
0
File: tests.py Project: jsphyin/idb
    def test_add_Developer1(self):

        with app.test_request_context():
            developer1 = Developer(id=1000000,
                                   name="developer1",
                                   image="www.test_image.com",
                                   desc="This is a test developer.",
                                   raw_desc="Test developer",
                                   website="www.developer.com")
            db.session.add(developer1)
            db.session.commit()

            gamequery = db.session.query(Developer).filter_by(
                id="1000000").first()
            self.assertEqual(gamequery.id, 1000000)
            self.assertEqual(gamequery.name, "developer1")
            self.assertEqual(gamequery.image, "www.test_image.com")

            db.session.delete(developer1)
            db.session.commit()
Example #36
0
def developer_add(request):
    response = lambda form: render_to_response('developers/add.html', { 'form': form })

    if not request.POST:
        form = DeveloperAddForm()
        return response(form)


    # Validating form and saving developer
    form = DeveloperAddForm(request.POST)
    if form.is_valid():
        developer = Developer()
        developer.set_login(form.cleaned_data['login'])
        developer.set_password(form.cleaned_data['password'])
        developer.save()

        messages.success(request, 'Developer %s was added successfully.' % developer.login())

        return back_to_developers_list()

    # Form is not valid
    return response(form)
Example #37
0
    def post(self):
        form = ForgotPasswordEmailForm(self.request.POST)
        if form.validate():
            d = Developer.query(Developer.email == form.email.data).get()
            if d:
                d.password_reset_token = base64.urlsafe_b64encode(os.urandom(12))
                d.put()
                
                message = mail.EmailMessage(sender="FROM_EMAIL",
                                            to=d.email,
                                            subject="Legit Dev Password Reset",
                                            body="""
Someone (hopefully you) has requested a reset of your Legit Developer account password. If it was you, click the link below to
reset your password. If it wasn't you, delete this email and we can forget this whole thing ever happened.\n\n
%s%s?%s
""" % (SITE_DOMAIN, self.uri_for('forgot_password_set'), urlencode({'email': d.email, 'token': d.password_reset_token})))
                message.send()

                return self.redirect_to("forgot_password_sent")
            else:
                self.session.add_flash("Couldn't find a developer account with that email.", "local")
        self.render_response("auth/forgot_password_email.html", form=form)            
Example #38
0
def view_transactions():
    """
    Transaction history page for user's dashboard.
    """
    if 'username' not in session:
        return redirect(url_for('login'))
    else:
        if not session['type_of_user'] == "user":
            return render_template("access_denied.html")

        balance = 0
        if session['type_of_user'] == "developer":
            balance = Developer.get_info(session['username'])["balance"]
        else:
            balance = Client.get_info(session['username'])["balance"]

        outgoing = Transaction.get_transactions_by_sender(session['username'])
        incoming = Transaction.get_transactions_by_recipient(
            session['username'])
        return render_template("myTransactions.html",
                               balance=balance,
                               outgoing=outgoing,
                               incoming=incoming)
Example #39
0
def developer_password(request, login):
    developer = Developer.get_by_login(login)
    if not developer:
        raise Http404

    response = lambda form, login: render_to_response('developers/password.html',
        { 'form' : form, 'login': login })

    if not request.POST:
        form = DeveloperEditForm(initial={ 'login' : login })
        return response(form, login)

    # Validating form and saving developer
    form = DeveloperEditForm(request.POST)
    if form.is_valid():
        developer.set_password(form.cleaned_data['password'])
        developer.save()

        messages.success(request, 'Password updated for %s.' % login)

        return back_to_developers_list()

    # Form is not valid
    return response(form, login)
Example #40
0
def rating(demand_id, recipient):
    """
    The '/bid/<demand_id>/rating/<recipient>' route is where the user can rate another user 
    for a demand they were involved in.
    """
    if 'username' not in session:
        return redirect(url_for('login'))

    demand_info = Demand.get_info(demand_id)

    # make sure the user is authorized to rate the recipient
    if session['role'] == 'developer':
        # developer rates the client, so client is recipient
        if session['username'] != demand_info['chosen_developer_username']:
            return render_template('access_denied.html')
    elif session['role'] == 'client':
        # client rates the developer, so developer is recipient
        if session['username'] != demand_info['client_username']:
            return render_template('access_denied.html')

    if Rating.check_if_valid_rating_form(int(demand_id), recipient,
                                         session['username']):
        form = RatingForm()

        if request.method == "GET":
            return render_template("rating.html",
                                   form=form,
                                   recipient=recipient,
                                   demand_id=demand_id)
        elif request.method == "POST":
            # low rating
            if form.rating.data <= 2:
                session['rating' + demand_id] = form.rating.data
                return redirect(
                    url_for('ratingMessage',
                            demand_id=demand_id,
                            recipient=recipient))
            elif form.rating.data == None:
                return render_template('rating.html',
                                       form=form,
                                       recipient=recipient,
                                       demand_id=demand_id)
            else:
                # add to form data
                Rating(demand_id, recipient, session['username'],
                       form.rating.data)

                # if the client gave a good rating to a developer (<= 3)
                # the remaining half of the bid amount gets transferred over to the developer
                if session['role'] == 'client':
                    bid_amount = Demand.get_info(
                        demand_id)['chosen_bid_amount']
                    Transaction(recipient, session['username'],
                                round(bid_amount / 2, 2))

                    # update developer's earnings
                    Developer.add_earnings(recipient, bid_amount)

                return render_template('ratingFinished.html',
                                       recipient=recipient)
    return render_template('access_denied.html')
Example #41
0
def edit_game(game_slug):
    game = db.session.query(Game).filter(Game.slug==game_slug).one()
    no_perm = no_permission(game.user_id)
    if no_perm:
        return no_perm
    error = None
    form = GameFormEdit()
    if form.validate_on_submit():
        game.game_title = form.game_title.data
        game.creator_type = form.creator_type.data
        game.description = form.description_.data
        game.age_rating_id = form.age_rating_id.data

        words = form.words.data
        words = words.replace(",", "")
        words = words.replace(".", "")
        try:
            words = int(re.search(r'(0|(-?[1-9][0-9]*))', words).group(0))
        except: # Catch exception if re.search returns None
            words = 0

        if not words:
            words = 0
        game.words = words

        playtime = 0
        if form.playtime.data:
            try:
                playtime = float(form.playtime.data)
            except TypeError:
                try:
                    playtime = int(re.search(r'(0|(-?[1-9][0-9]*))', form.playtime.data).group(0))
                except TypeError: # Catch exception if re.search returns None
                    playtime = 0
            #playtime = float(form.playtime.data)
            if form.playtime_unit.data == 'hours':
                playtime = playtime * 60
                game.playtime = int(math.ceil(playtime))
            else:
                #game.playtime = 0
                #game.playtime = form.playtime.data
                game.playtime = playtime
        if game.words == 0:
            game.words_estimate = playtime*200
        else:
            game.words_estimate = game.words

        #save new creator if it doesn't exists:
        developer_name = form.creator.data
        developer_name = developer_name.replace("'", "")
        developer = Developer.query.filter(Developer.name==developer_name).first()
        if not developer:
            if form.creator_type.data=='person':
                type=1
                person = Person('')
                db.session.add(person)
                db.session.commit()
                developer = Developer (developer_name, type, g.user.id, person_id=person.id)
            if form.creator_type.data=='group':
                type=2
                group = Group('')
                db.session.add(group)
                db.session.commit()
                developer = Developer (developer_name, type, g.user.id, group_id=group.id)
            db.session.add(developer)
        game.developer_id = developer.id

        #save homepage link to link_game table:
        li = LinkGame.query.filter_by(game_id=game.id).first()
        if not li.url==form.homepage_link_url.data:
            db.session.delete(li)
            li = LinkGame(game_id=game.id, url=form.homepage_link_url.data, name = 'Home Page', link_type_id = '1')
            db.session.add(li)
        categories = []
        for category in game.categories:
            if not category.category_id in form.categories.data:
                ca = CategoryGame.query.filter_by(id=category.id).first()
                db.session.delete(ca)
            categories.append(category.category_id)
        for category in form.categories.data:
            if not category in categories:
                db.session.add(CategoryGame(category_id=category, game_id=game.id))
        game.approved = False;
        db.session.commit()

        flash('Release data was saved.')
        return redirect(url_for('game_details', game_slug=game_slug))
    else:
        form.game_title.data = game.game_title
        form.homepage_link_url.data = game.link.url
        form.description_.data = game.description
        form.age_rating_id.data = game.age_rating_id
        form.words.data = game.words
        form.playtime.data = game.playtime
        form.categories.data = []
        for category in game.categories:
            form.categories.data.append(category.category_id)
        dev = db.session.query(Developer).filter(Developer.id==game.developer_id).one()
        if dev.type==1:
            form.creator_type.data = "person"
        else:
            form.creator_type.data = "group"
        form.creator.data = dev.name

    developers = '['
    for developer in Developer.query.filter(Developer.id>0).order_by(Developer.type):
        developer.name = developer.name.replace("'", "")
        developers += '"'+developer.name+'",'
    developers = developers[:-1]
    developers += ']'

    return render_template('add_game.html', navigation=return_navigation(), site_data=site_data(), form=form, developers=developers, edit=True)
Example #42
0
def panel():
    location1_list = [
        "home",
        "dining",
        "scenic_spot",
        "traffic",
        "exhibition",
        "entertainment",
        "healthcare",
        "estate",
        "life_service",
        "hotel",
        "work_office",
        "finance",
        "education",
        "government",
        "infrastructure",
        "auto_related",
        "shopping",
        "sports",
    ]
    location2_list = [
        ["home"],
        [
            "chinese_restaurant",
            "japan_korea_restaurant",
            "japan_restaurant",
            "korea_restaurant",
            "western_restaurant",
            "bbq",
            "chafing_dish",
            "seafood_restaurant",
            "vegetarian_diet",
            "muslim_dish",
            "buffet",
            "dessert",
            "cooler_store",
            "snack_bar",
            "vegetarian_diet",
        ],
        ["scenic_spot"],
        [
            "traffic",
            "bus_stop",
            "subway",
            "highway_service_area",
            "railway_station",
            "airport",
            "coach_station",
            "traffic_place",
            "bus_route",
            "subway_track",
        ],
        ["museum", "exhibition_hall", "science_museum", "library", "gallery", "convention_center"],
        [
            "bath_sauna",
            "ktv",
            "bar",
            "coffee",
            "night_club",
            "cinema",
            "odeum",
            "resort",
            "outdoor",
            "game_room",
            "internet_bar",
            "botanic_garden",
            "music_hall",
            "movie",
            "playground",
            "temple",
            "aquarium",
            "cultural_venues",
            "fishing_garden",
            "picking_garden",
            "cultural_palace",
            "memorial_hall",
            "park",
            "zoo",
            "chess_room",
            "bathing_beach",
            "theater",
        ],
        ["hospital", "clinic", "emergency_center", "drugstore", "special_hospital"],
        ["residence", "business_building", "community_center"],
        [
            "travel_agency",
            "ticket_agent",
            "ticket_agent_plane",
            "ticket_agent_train",
            "post_office",
            "telecom_offices",
            "telecom_offices_unicom",
            "telecom_offices_netcom",
            "newstand",
            "water_supply_office",
            "electricity_office",
            "photographic_studio",
            "laundry",
            "talent_market",
            "lottery_station",
            "housekeeping",
            "housekeeping_lock",
            "housekeeping_hour",
            "housekeeping_water_deliver",
            "intermediary",
            "pet_service",
            "salvage_station",
            "welfare_house",
            "barbershop",
            "laundry",
            "ticket_agent_coach",
            "housekeeping_nanny",
            "housekeeping_house_moving",
            "telecom_offices_tietong",
            "ticket_agent_bus",
            "telecom_offices_mobile",
            "housekeeping_alliance_repair",
            "telecom_offices_telecom",
        ],
        [
            "motel",
            "hotel",
            "economy_hotel",
            "guest_house",
            "hostel",
            "farm_house",
            "villa",
            "dormitory",
            "other_hotel",
            "apartment_hotel",
            "inn",
            "holiday_village",
        ],
        ["work_office"],
        ["bank", "atm", "insurance_company", "security_company"],
        [
            "university",
            "high_school",
            "primary_school",
            "kinder_garten",
            "training_institutions",
            "technical_school",
            "adult_education",
            "scientific_research_institution",
            "driving_school",
        ],
        [
            "agriculture_forestry_and_fishing_base",
            "foreign_institutional",
            "government_agency",
            "minor_institutions",
            "tax_authorities",
        ],
        [
            "public_utilities",
            "toll_station",
            "other_infrastructure",
            "public_phone",
            "factory",
            "city_square",
            "refuge",
            "public_toilet",
            "church",
            "industrial_area",
        ],
        [
            "gas_station",
            "parking_plot",
            "auto_sale",
            "auto_repair",
            "motorcycle",
            "car_maintenance",
            "car_wash",
            "motorcycle_service",
            "motorcycle_repair",
        ],
        [
            "comprehensive_market",
            "convenience_store",
            "supermarket",
            "digital_store",
            "pet_market",
            "furniture_store",
            "farmers_market",
            "commodity_market",
            "flea_market",
            "sports_store",
            "clothing_store",
            "video_store",
            "glass_store",
            "mother_store",
            "jewelry_store",
            "cosmetics_store",
            "gift_store",
            "pawnshop",
            "antique_store",
            "bike_store",
            "cigarette_store",
            "stationer",
            "motorcycle_sell",
            "sports_store",
            "shopping_street",
        ],
        [
            "golf",
            "skiing",
            "sports_venues",
            "football_field",
            "tennis_court",
            "horsemanship",
            "race_course",
            "basketball_court",
        ],
    ]
    motion_dict = {"sitting": 0, "walking": 3, "running": 4, "ridding": 2, "driving": 1, "unknown": -1}
    event_list = [
        "attend_concert",
        "go_outing",
        "dining_in_restaurant",
        "watch_movie",
        "study_in_class",
        "visit_sights",
        "work_in_office",
        "exercise_outdoor",
        "shopping_in_mall",
        "exercise_indoor",
    ]
    status_dict = {
        "unknown": -1,
        "arriving_home": 0,
        "leaving_home": 1,
        "arriving_office": 2,
        "leaving_office": 3,
        "going_home": 4,
        "going_office": 5,
        "user_home_office_not_yet_defined": 6,
    }

    session_token = session.get("session_token")
    if not session_token:
        return redirect(url_for("login"))
    user = Developer()
    user.session_token = session_token

    app_id = request.form.get("app_id")
    dashboard = Dashboard()
    dashboard.app_id = app_id
    app_key = dashboard.get_app_key()
    if not app_key:
        app_key = dashboard.get_demo_app_key()
    if not app_key:
        flash("App not exists")
        return render_template("console.html")

    type = request.form.get("type")
    val = request.form.get("val")
    if type and val:
        if user.get_tracker_of_app(app_id):
            tracker_list = user.tracker_list
        headers = {
            "X-AVOSCloud-Application-Id": "qTFUwcnM3U3us8B3ArenyJbm",
            "X-AVOSCloud-Application-Key": "ksfJtp9tIEriApWmbtOrQs5F",
        }
        payload = {"type": type, "val": val}
        # for tracker in tracker_list:
        requests.post("https://leancloud.cn/1.1/functions/notify_new_details", headers=headers, data=payload)
    return render_template(
        "panel.html",
        location1_list=location1_list,
        location2_list=location2_list,
        motion_dict=motion_dict,
        event_list=event_list,
        status_dict=status_dict,
    )
Example #43
0
def developer_profile(request, login):
    developer = Developer.get_by_login(login)
    if not developer:
        raise Http404

    return render_to_response('developers/profile.html', {'developer': developer})
def register():
    switch = request.form["switch"]
    print(switch)
    is_valid = True
    if switch == "org":
        email = Organization.query.filter_by(email=request.form["email"]).all()
        email2 = Developer.query.filter_by(email=request.form["email"]).all()
        if len(request.form["orgname"]) == 0:
            is_valid = False
            flash("Organization name cannot be blank", "reg")
    elif switch == "dev":
        email = Developer.query.filter_by(email=request.form["email"]).all()
        email2 = Organization.query.filter_by(
            email=request.form["email"]).all()
    if email:
        is_valid = False
        flash("Email in use")
    if email2:
        is_valid = False
        if switch == "dev":
            flash("Email registered as an Organization")
        if switch == "org":
            flash("Email registered as a Developer")
    if not request.form["fname"].isalpha() or not len(
            request.form["fname"]) >= 2:
        is_valid = False
        flash(
            "First name can only contain letters and must be at least 2 characters long",
            "reg")
    if not request.form['lname'].isalpha() or not len(
            request.form['lname']) >= 2:
        is_valid = False
        flash(
            "Last name can only contain letters and must be at least 2 characters long",
            "reg")
    if not EMAIL_REGEX.match(request.form["email"]):
        is_valid = False
        flash("Invalid Email Address")
    if not len(request.form['address']) > 5:
        is_valid = False
        flash("Address must be longer than 5 characters", "reg")
    if not len(request.form['city']) >= 2:
        is_valid = False
        flash("City name must be at least 3 characters long", "reg")
    if not password_reg.match(request.form["password"]):
        is_valid = False
        flash(
            "Password should be at least 5 characters, have one number, one uppercase and one lowercase letter, and one symbol"
        )
    if request.form["password"] != request.form["confirmpass"]:
        is_valid = False
        flash("Passwords do not match", "reg")
    if is_valid:
        pw_hash = bcrypt.generate_password_hash(request.form["password"])
        if switch == "dev":
            user = Developer(fname=request.form["fname"],
                             lname=request.form["lname"],
                             email=request.form["email"],
                             address=request.form["address"],
                             city=request.form["city"],
                             state=request.form["state"],
                             password=pw_hash)
        elif switch == "org":
            user = Organization(orgname=request.form["orgname"],
                                fname=request.form["fname"],
                                lname=request.form["lname"],
                                email=request.form["email"],
                                address=request.form["address"],
                                city=request.form["city"],
                                state=request.form["state"],
                                password=pw_hash)
        db.session.add(user)
        db.session.commit()
        session["user_id"] = {
            "fname": user.fname,
            "lname": user.lname,
            "email": user.email,
            "id": user.id,
            "role": switch
        }
        return redirect("/{}_landing".format(switch))
    return redirect("/#{}_reg".format(switch))
Example #45
0
def developers_list(request):
    developers = Developer.all()
    return render_to_response('developers/list.html',
                              { 'developers': developers },
                              context_instance=RequestContext(request))
Example #46
0
def panel():
    location1_list = ['home','dining','scenic_spot','traffic', 'exhibition',
                      'entertainment','healthcare', 'estate','life_service','hotel',
                      'work_office','finance', 'education','government','infrastructure',
                      'auto_related','shopping','sports']
    location2_list = [
        ['home'],
        ['chinese_restaurant', 'japan_korea_restaurant','japan_restaurant','korea_restaurant', 'western_restaurant', 'bbq', 'chafing_dish', 'seafood_restaurant', 'vegetarian_diet', 'muslim_dish', 'buffet', 'dessert', 'cooler_store', 'snack_bar','vegetarian_diet'],
        ['scenic_spot'],
        ['traffic','bus_stop','subway','highway_service_area','railway_station','airport','coach_station','traffic_place','bus_route','subway_track'],
        ['museum', 'exhibition_hall', 'science_museum', 'library', 'gallery', 'convention_center'],
        ['bath_sauna', 'ktv', 'bar', 'coffee', 'night_club', 'cinema', 'odeum', 'resort', 'outdoor', 'game_room', 'internet_bar','botanic_garden','music_hall','movie','playground','temple','aquarium','cultural_venues','fishing_garden','picking_garden','cultural_palace', 'memorial_hall','park','zoo','chess_room','bathing_beach','theater'],
        ['hospital', 'clinic', 'emergency_center', 'drugstore','special_hospital'],
        ['residence', 'business_building','community_center'],
        ['travel_agency', 'ticket_agent','ticket_agent_plane', 'ticket_agent_train','post_office', 'telecom_offices' ,'telecom_offices_unicom', 'telecom_offices_netcom','newstand', 'water_supply_office', 'electricity_office', 'photographic_studio', 'laundry', 'talent_market', 'lottery_station', 'housekeeping','housekeeping_lock','housekeeping_hour','housekeeping_water_deliver', 'intermediary', 'pet_service', 'salvage_station', 'welfare_house', 'barbershop','laundry','ticket_agent_coach','housekeeping_nanny','housekeeping_house_moving', 'telecom_offices_tietong','ticket_agent_bus','telecom_offices_mobile','housekeeping_alliance_repair','telecom_offices_telecom'],
        ['motel', 'hotel', 'economy_hotel', 'guest_house', 'hostel','farm_house','villa','dormitory','other_hotel','apartment_hotel','inn','holiday_village'],
        ['work_office'],
        ['bank', 'atm', 'insurance_company', 'security_company'],
        ['university', 'high_school', 'primary_school', 'kinder_garten', 'training_institutions', 'technical_school', 'adult_education','scientific_research_institution','driving_school'],
        ['agriculture_forestry_and_fishing_base','foreign_institutional','government_agency','minor_institutions','tax_authorities'],
        ['public_utilities', 'toll_station', 'other_infrastructure','public_phone','factory' ,'city_square','refuge','public_toilet','church','industrial_area'],
        ['gas_station', 'parking_plot', 'auto_sale', 'auto_repair', 'motorcycle', 'car_maintenance', 'car_wash','motorcycle_service','motorcycle_repair'],
        ['comprehensive_market', 'convenience_store', 'supermarket', 'digital_store', 'pet_market', 'furniture_store', 'farmers_market', 'commodity_market', 'flea_market', 'sports_store', 'clothing_store', 'video_store', 'glass_store', 'mother_store', 'jewelry_store', 'cosmetics_store', 'gift_store', 'pawnshop', 'antique_store', 'bike_store', 'cigarette_store', 'stationer','motorcycle_sell','sports_store','shopping_street'],
        ['golf','skiing','sports_venues','football_field','tennis_court','horsemanship','race_course','basketball_court'],
    ]
    motion_dict = {'sitting': 0, 'walking': 3, 'running': 4, 'ridding': 2, 'driving': 1, 'unknown': -1}
    event_list = ['attend_concert', 'go_outing', 'dining_in_restaurant', 'watch_movie',
                  'study_in_class', 'visit_sights', 'work_in_office', 'exercise_outdoor',
                  'shopping_in_mall', 'exercise_indoor']
    status_dict = {"unknown": -1, "arriving_home":0, "leaving_home":1, "arriving_office": 2, "leaving_office": 3, "going_home":4, "going_office":5, "user_home_office_not_yet_defined": 6}

    session_token = session.get('session_token')
    if not session_token:
        return redirect(url_for('login'))
    user = Developer()
    user.session_token = session_token

    app_id = request.form.get('app_id')
    dashboard = Dashboard()
    dashboard.app_id = app_id
    app_key = dashboard.get_app_key()
    if not app_key:
        app_key = dashboard.get_demo_app_key()
    if not app_key:
        flash('App not exists')
        return render_template('console.html')

    type = request.form.get('type')
    val = request.form.get('val')
    if type and val:
        if user.get_tracker_of_app(app_id):
            tracker_list = user.tracker_list
        headers = {"X-AVOSCloud-Application-Id": "qTFUwcnM3U3us8B3ArenyJbm", "X-AVOSCloud-Application-Key": "ksfJtp9tIEriApWmbtOrQs5F"}
        payload = {"type": type, "val": val}
        #for tracker in tracker_list:
        requests.post("https://leancloud.cn/1.1/functions/notify_new_details",  headers = headers, data = payload)
    return render_template('panel.html',
                           location1_list = location1_list,
                           location2_list = location2_list,
                           motion_dict = motion_dict,
                           event_list = event_list,
                           status_dict= status_dict)
Example #47
0
def developers_management():
    existing_developers = Developer.query().fetch(100)

    return render_template("admin/developers.html",
                           developers=existing_developers)
Example #48
0
def developers_management():
    existing_developers = Developer.query().fetch(100)
        
    return render_template("admin/developers.html", developers=existing_developers)
Example #49
0
def dash(param):
    username = session.get("username")
    session_token = session.get("session_token")

    if not session_token:
        return redirect(url_for("index"))
    # app_name = request.args.get('app_name')
    # app_id = request.args.get('app_id')
    app_name = session.get("app_name")
    app_id = session.get("app_id")
    print "the app_name is %s and the app_id  is: %s" % (str(app_name), str(app_id))

    user = Developer()
    user.session_token = session_token
    print "Param is %s" % (str(param))
    if param == "dashboard":
        if user.get_all_application():
            all_application_dict = user.all_application_dict  # 一旦上一步执行成功,会给user添加一个成员变量 all_application_dict
        else:
            print "no application  exists"
            all_application_dict = {}
        print "all_application_dict is : %s" % (str(all_application_dict))
        if app_name and app_id:
            del all_application_dict[app_name]
        else:
            app_name = all_application_dict.keys()[0]
            app_id = all_application_dict[app_name]
            del all_application_dict[app_name]
    elif param == "demo":

        if user.get_all_demo_application():
            all_demo_application_dict = (
                user.all_demo_application_dict
            )  # 一旦上一步执行成功,会给user添加一个成员变量 all_demo_application_dict
        else:
            print "no demo application  exists"
            all_demo_application_dict = {}
        print "all_demo_application_dict is : %s" % (str(all_demo_application_dict))
        all_application_dict = {}
        if DEMO_APP_NAME in all_demo_application_dict.keys():
            app_name = DEMO_APP_NAME
            app_id = all_demo_application_dict[app_name]
        else:
            "Demo not exists"
            app_name = None
            app_id = None
    else:
        print "Param is %s" % (str(param))
        all_application_dict = {}

    session["app_name"] = app_name
    session["app_id"] = app_id
    # del all_demo_application_dict[app_name]
    print "app_name is %s and app_id is %s" % (str(app_name), str(app_id))
    dashboard = Dashboard()
    dashboard.app_id = app_id
    # all_app_event = 1
    if request.method == "POST":
        is_xhr = True
    else:
        is_xhr = False
    print "last all_application_dict is : %s" % (str(all_application_dict))

    default_user_profile_category = "Age&Gender"
    default_path_analysis_category = "Frequently Location"
    default_event_name = "Event1"
    default_behavior_recognition_measure = "Activity"

    user_profile_type = "age"
    path_analysis_type = "location"
    event_name_type = "Event1"
    behavior_recognition_measure_type = "activity"

    user_profile_category_dict = dashboard.get_user_profile_category_dict()  # ['Occupation','Tastes']
    path_analysis_measure_dict = dashboard.get_path_analysis_measure_dict()  # ['Frequently Track']
    behavior_recognition_event_dict = dashboard.get_behavior_recognition_event_dict()  # ['event2']
    behavior_recognition_measure_dict = dashboard.get_behavior_recognition_measure_dict()  # ['Location','Time']

    del user_profile_category_dict[user_profile_type]
    del path_analysis_measure_dict[path_analysis_type]
    del behavior_recognition_event_dict[event_name_type]
    del behavior_recognition_measure_dict[behavior_recognition_measure_type]

    print "log comes out !!!!!"
    return render_template(
        "shared/dash.html",
        is_xhr=is_xhr,
        # dashboard_link = dashboard_link,
        route_link="dashboard",
        # sort according to ['16down', '16to35', '35to55', '55up']
        # discard unknown data
        username=username,
        app_name=app_name,
        app_id=app_id,
        all_application_dict=all_application_dict,
        default_user_profile_category=default_user_profile_category,
        default_path_analysis_category=default_path_analysis_category,
        default_event_name=default_event_name,
        default_behavior_recognition_measure=default_behavior_recognition_measure,
        user_profile_type=user_profile_type,
        path_analysis_type=path_analysis_type,
        event_name_type=event_name_type,
        behavior_recognition_measure_type=behavior_recognition_measure_type,
        user_profile_category_dict=user_profile_category_dict,
        path_analysis_measure_dict=path_analysis_measure_dict,
        behavior_recognition_event_dict=behavior_recognition_event_dict,
        behavior_recognition_measure_dict=behavior_recognition_measure_dict,
    )