Beispiel #1
0
def offer_delete(request, id):
    user = get_user(request)
    user_info = get_user_info(user)
    instance = get_object_or_404(Offer, id=id, employer=user_info)
    instance.delete()
    redirect_to = resolve_url('/partime/manage/')
    return HttpResponseRedirect(redirect_to)
Beispiel #2
0
def edit_animal(animal_name):
    """Edit a particular animal"""
    animal = session.query(CategoryItem).filter_by(
        name=animal_name).one_or_none()
    creator = get_user_info(session, animal.user_id)
    if 'username' not in login_session:
        return redirect('/login')
    if creator.id != login_session['user_id']:
        return render_template('unauthorized.html', categories=categories)
    if request.method == 'POST':
        if request.form['name'] == '':
            flash("Edit failed: Name is empty")
            return redirect(url_for(
                'show_category_items', animal_type=request.form['category']
            ))
        animal.name = request.form['name']
        animal.picture = request.form['picture']
        animal.description = request.form['description']
        animal.category = session.query(Category).filter_by(
            name=request.form['category']).one_or_none()
        session.add(animal)
        session.commit()
        flash("Edited!")
        return redirect(url_for(
            'show_category_items', animal_type=request.form['category']
        ))
    return render_template(
        'edit_animal.html',
        categories=categories,
        animal=animal
    )
Beispiel #3
0
    def _eval_attributes(self, properties):
        # response struct
        _response = {
            'computer': {
                'hostname': self.migas_computer_name,
                'ip': network.get_network_info()['ip'],
                'version': self.migas_version,
                'platform': platform.system(),  # new for server 3.0
                'pms': str(self.pms),  # new for server 3.0
                'user': self._graphic_user,
                'user_fullname': utils.get_user_info(
                    self._graphic_user
                )['fullname']
            },
            'attributes': {}
        }

        # properties converted in attributes
        self._send_message(_('Evaluating attributes...'))
        for _item in properties:
            _response['attributes'][_item['name']] = \
                self._eval_code(_item['language'], _item['code'])
            _info = '%s: %s' % (
                _item['name'],
                _response['attributes'][_item['name']]
            )
            if _response['attributes'][_item['name']].strip() != '':
                _operation_ok(_info)
            else:
                _operation_failed(_info)
                self._write_error(
                    'Error: property %s without value\n' % _item['name']
                )

        return _response
Beispiel #4
0
 def assign_sp_to_ticket(self, sp_num=0):
     """Assign an SP to a ticket.
     """
     self.check_starting_location("ticket view",
                                  sys._getframe().f_code.co_name)
     driver = self.driver
     sp_info = get_user_info("SP", user_num=sp_num)
     buttons = driver.find_elements_by_tag_name('button')
     for button in buttons:
         if button.text == "Assign a Provider":
             button.click()
             break
     self.wait_for_page("sp ticket filter modal", delay=10)
     form_groups = driver.find_elements_by_class_name('form__group')
     for form in form_groups:
         label = form.find_element_by_tag_name('label').text
         if label == "Service Provider":
             select = Select(form.find_element_by_tag_name('select'))
             select.select_by_visible_text(sp_info['text_input']["Name"])
             break
     buttons = driver.find_elements_by_tag_name('button')
     for button in buttons:
         if button.text == "Assign Provider":
             button.click()
             break
     self.wait_for_page("sp assigned to ticket", delay=10)
Beispiel #5
0
def user_info(user_name):
    """
        User's information
        name & photo
    """
    user_info = get_user_info(user_name)
    return jsonify(user_info)
Beispiel #6
0
def submit():
    if request.method == "POST":
        username = request.form["username"].lower()
        num_posts = request.form["numPosts"]

        # handles all the errors and formats
        if not username:
            flash("Username was not entered.")
            return redirect(url_for('index'))

        if not num_posts:
            flash("Number of posts was not entered.")
            return redirect(url_for('index'))
        elif "." in num_posts:
            num_posts = int(float(num_posts))
        else:
            num_posts = int(num_posts)

        if "@" in username:
            username.strip("@")

        allowed_str = "abcdefghijklmnopqrstuvwxyz1234567890_."
        for c in username:
            if c not in allowed_str:
                flash(
                    "Usernames must contain only letters, numbers, periods, and underscores."
                )
                return redirect(url_for('index'))

        if len(username) > 30:
            flash("Usernames can not be over 30 characters.")
            return redirect(url_for('index'))

        profile = utils.get_user_info(username)
        if profile["error"]:
            if profile["code"] == 1:
                flash(profile["response"])
                return redirect(url_for('index'))
            elif profile["code"] == 2:
                flash(profile["response"])

        elif profile["is_private"]:
            flash(
                "We can't analyze private accounts. Try again with a public account."
            )
            return redirect(url_for('index'))

        response = utils.scrape(username, num_posts)
        if response["error"]:
            flash(response["response"])
            return redirect(url_for('index'))
        else:
            data = response["response"]

        session['data'] = data
        session['username'] = username
        session['num_posts'] = num_posts
        session['profile'] = profile

        return redirect(url_for('top_posts'))
Beispiel #7
0
def ajax_history_delete():
    date = request.args.get('date', '') # '2013-09-01'
    date = str(date).replace('-', '')
    search_all  = request.args.get('show_all', '') # return all
    uid_list = []
    if not search_all:
        temp = r.hget('delete_user', date)
        if temp:
            results = get_user_info(json.loads(temp))
            return json.dumps(results)
    else:
        all_temp = r.hgetall('delete_user')
        if all_temp:
            temp_list = all_temp.values()
            for item in temp_list:
                uid_list.extend(json.loads(item))
            results = get_user_info(uid_list)
            return json.dumps(results)
    return '0'
Beispiel #8
0
def get_write_user_info_view(request):
    data = {}
    work_id = request.GET.get("work_id", "")
    data["work_id"] = work_id
    data["q"] = request.GET.get("q", "")
    data["flag"] = public.WRITE_FLAG
    data["page_current"] = request.GET.get("page_current")
    data["user"] = utils.get_user_info(data)
    data["auth"] = utils.check_auth(request)
    return render(request, 'set_write.html', {"data": data})
def ajax_history_delete():
    date = request.args.get("date", "")  # '2013-09-01'
    date = str(date).replace("-", "")
    search_all = request.args.get("show_all", "")  # return all
    uid_list = []
    if not search_all:
        temp = r.hget("delete_user", date)
        if temp:
            results = get_user_info(json.loads(temp))
            return json.dumps(results)
    else:
        all_temp = r.hgetall("delete_user")
        if all_temp:
            temp_list = all_temp.values()
            for item in temp_list:
                uid_list.extend(json.loads(item))
            results = get_user_info(uid_list)
            return json.dumps(results)
    return "0"
Beispiel #10
0
def get_write_user_info_view(request):
    data = {}
    work_id = request.GET.get("work_id", "")
    data["work_id"] = work_id
    data["q"] = request.GET.get("q", "")
    data["flag"] = public.WRITE_FLAG
    data["page_current"] = request.GET.get("page_current")
    data["user"] = utils.get_user_info(data)
    data["auth"] = utils.check_auth(request)
    return render(request, 'set_write.html', {"data": data})
Beispiel #11
0
def get_user_view(request):
    data = {}
    work_id = int(request.GET.get("work_id")) if request.GET.get("work_id") else 0
    data["work_id"] = work_id
    data["q"] = request.GET.get("q", "")
    data["flag"] = request.GET.get("flag", "")
    data["page_current"] = request.GET.get("page_current", 1)
    ret = data
    ret["user"] = utils.get_user_info(data)
    ret["auth"] = utils.check_auth(public.get_user_mail(request), work_id)
    return render(request, 'user_info.html', {'data': ret})
Beispiel #12
0
def show_animal(animal_type, animal_name):
    """Show the individual animal"""
    animal = session.query(CategoryItem).filter_by(
        name=animal_name, category_name=animal_type).one()
    creator = get_user_info(session, animal.user_id)
    print creator
    if 'username' not in login_session or \
            creator.id != login_session['user_id']:
        return render_template(
            'animal.html', categories=categories, animal=animal, public=True)
    return render_template('animal.html', categories=categories, animal=animal)
Beispiel #13
0
def manage(request):
    user = get_user(request)
    user_info = get_user_info(user)
    if isinstance(user_info, Employer):
        offer_list = Offer.objects.filter(employer=user_info)
        context = {"offers": offer_list}
        template = 'partime/offer/offer_list.html'
    else:
        request_list = Request.objects.filter(employee=user_info)
        context = {"requests": request_list}
        template = 'partime/request/request_list.html'
    return render(request, template, context)
Beispiel #14
0
def get_user_view(request):
    data = {}
    work_id = int(
        request.GET.get("work_id")) if request.GET.get("work_id") else 0
    data["work_id"] = work_id
    data["q"] = request.GET.get("q", "")
    data["flag"] = request.GET.get("flag", "")
    data["page_current"] = request.GET.get("page_current", 1)
    ret = data
    ret["user"] = utils.get_user_info(data)
    ret["auth"] = utils.check_auth(public.get_user_mail(request), work_id)
    return render(request, 'user_info.html', {'data': ret})
Beispiel #15
0
def match_reject(request, id):
    user = get_user(request)
    user_info = get_user_info(user)
    match = get_object_or_404(RequestOfferMatch, id=id)
    if match.request.employee == user_info:
        match.req_status = 'R'
    elif match.offer.employer == user_info:
        match.offer_status = 'R'
    else:
        raise PermissionDenied("You have no permission for this operation!")
    match.save()
    redirect_to = resolve_url('/partime/match/')
    return HttpResponseRedirect(redirect_to)
Beispiel #16
0
 def __init__(self, auth_url=None, login=None, password=None,
              tenant_name=None, region_name=None, hostname_prefix=None):
     auth_url = auth_url or os.environ.get('OS_AUTH_URL')
     login = login or os.environ.get('OS_USERNAME')
     self.password = password or os.environ.get('OS_PASSWORD')
     region_name = region_name or os.environ.get('OS_REGION_NAME')
     tenant_name = tenant_name or os.environ.get('OS_TENANT_NAME')
     self.hostname_prefix = hostname_prefix or os.environ.get('OS_HOSTNAME_PREFIX')
     user_info = utils.get_user_info(auth_url, login, self.password, tenant_name)
     # Collect authorization token
     self.token_id = user_info['access']['token']['id']
     # Collect services' endpoints
     self.service_catalog = utils.get_service_catalog(user_info['access']['serviceCatalog'],
                                                      region_name)
Beispiel #17
0
def offer_update(request, id):
    user = get_user(request)
    user_info = get_user_info(user)
    instance = get_object_or_404(Offer, id=id, employer=user_info)
    if request.method == "POST":
        form = OfferForm(request.POST, instance=instance)

        if form.is_valid():
            redirect_to = resolve_url('/partime/manage/')
            form.save()
            return HttpResponseRedirect(redirect_to)
    else:
        form = OfferForm(instance=instance)
    return render(request, 'partime/offer/offer_post.html', {'form': form, 'url': 'partime:offer_update', 'id': id})
Beispiel #18
0
def main(urgentLevel):
    # 需要返回的数据
    statusCode = -1
    subject = ''
    emailMsgArr = []
    emailMsgIndent = ''
    emailMsgInline = ''
    isSendEmail = False
    sec, timeStr = utils.init_time(time.localtime())

    print 'sec=%3d timeStr=%s urgentLevel=%d' % (sec, timeStr, urgentLevel)

    utils.append_log('\n' + timeStr + ' ')

    userInfoOld = utils.get_user_info_old()
    userInfo = utils.get_user_info()
    utils.dump_obj_to_file(userInfo, 'temp/temp_uer_info.json')

    if userInfo == {} or userInfoOld == {}:
        statusCode = 1
    if userInfo == userInfoOld:
        statusCode = 0
    else:
        # user_info有变动
        # 1. user_info不完整
        if userInfo.get('id') == None:
            statusCode = 2
            sec = 300
            print "sec=%3d" % sec
        # 2. user_info完整,需要更新log
        else:
            statusCode = 10
            # 保存new_dict
            utils.write_user_info_to_json(userInfo, timeStr)
            emailMsgArr, subjectArr, isOnlyToolbar = diffUserInfo(
                userInfo, userInfoOld, timeStr)
            subject = " ".join(subjectArr)
            emailMsgIndent = json.dumps(emailMsgArr, indent=4)
            emailMsgInline = json.dumps(emailMsgArr)
            if not isOnlyToolbar:
                isSendEmail = True

            # 提升ul
            urgentLevel = MAX_URGENT_LEVEL
            print "urgentLevel=%d" % (urgentLevel)
    return (statusCode, sec, urgentLevel, subject, emailMsgArr, emailMsgIndent,
            emailMsgInline, isSendEmail, timeStr)
Beispiel #19
0
 def complete_ticket(self,
                     ticket_info,
                     ip_num=0,
                     skip=[],
                     ticket_uuid=None):
     """Fills out ticket information
     """
     self.check_starting_location("create ticket",
                                  sys._getframe().f_code.co_name)
     driver = self.driver
     self.start_ticket()
     form_groups = driver.find_elements(By.CLASS_NAME, "form__group")
     # Radios
     for key, val in ticket_info.get("radio", {}).items():
         if key in skip:
             continue
         self.form_radio(form_groups, key, val)
     # IP Name
     ip_name = get_user_info("IP", ip_num)["text_input"]["Name"]
     self.form_select_visible(form_groups, "Implementing Partner", ip_name)
     # Text input
     for key, val in ticket_info.get("text_input", {}).items():
         if key in skip:
             continue
         self.form_text_input(form_groups, key, val)
     # text area
     for key, val in ticket_info.get("text_area", {}).items():
         if key in skip:
             continue
         self.form_text_area(form_groups, key, val)
     # Checkboxes
     for key, options in ticket_info.get("checkbox", {}).items():
         # print(key, options)
         if key in skip:
             continue
         self.form_checkbox(form_groups, key, options)
     # Date
     for key, val in ticket_info.get("date", {}).items():
         if key in skip:
             continue
         self.form_date(form_groups, key, val)
     # Add ticket UUID if requested
     if ticket_uuid is not None:
         team_member_input = driver.find_element_by_id(
             "form-ticket_ip_name")
         team_member_input.clear()
         team_member_input.send_keys(ticket_uuid)
Beispiel #20
0
def history(request):
    user = get_user(request)
    user_info = get_user_info(user)
    if isinstance(user_info, Employer):
        offer_list = Offer.objects.filter(employer=user_info, status='E')
        favor_list = []
        favors = FavorList.objects.filter(employer=user_info)
        favor_index = 0
        for favor in favors:
            favor_index = favor_index + 1
            employee = favor.employee
            favor_dict = model_to_dict(employee, exclude=['id', 'user', 'skills', 'gender', 'type'])
            gender = get_enum_desc_from_value(GENDER, employee.gender)
            type = get_enum_desc_from_value(EMPLOYEE_TYPE, employee.type)
            favor_dict['index'] = favor_index
            favor_dict['id'] = favor.id
            favor_dict['gender'] = gender
            favor_dict['type'] = type
            favor_dict['contact'] = ''
            favor_dict['post_ref'] = ''
            favor_list.append(favor_dict)

        black_list = []
        blackList = Blacklist.objects.filter(employer=user_info)
        black_list_index = 0
        for black_list_emp in blackList:
            black_list_index = black_list_index + 1
            employee = black_list_emp.employee
            black_list_dict = model_to_dict(employee, exclude=['id', 'user', 'skills', 'gender', 'type'])
            gender = get_enum_desc_from_value(GENDER, employee.gender)
            type = get_enum_desc_from_value(EMPLOYEE_TYPE, employee.type)
            black_list_dict['index'] = black_list_index
            black_list_dict['id'] = black_list_emp.id
            black_list_dict['gender'] = gender
            black_list_dict['type'] = type
            black_list_dict['contact'] = ''
            black_list_dict['post_ref'] = ''
            black_list.append(black_list_dict)
        context = {"expired": offer_list, "favor_list": favor_list, "black_list": black_list}
        template = 'partime/offer/offer_history.html'
    else:
        request_list = Request.objects.filter(employee=user_info, status='E')
        context = {"expired": request_list}
        template = 'partime/request/request_history.html'
    return render(request, template, context)
def user_handler(msg):
    chat_id = msg.chat.id
    username = msg.text.split()[-1]
    if username[0] == "/":
        username = utils.get_default_username(chat_id)
        if username is None:
            bot.send_message(chat_id, f"Invalid username")
            return
    user_info, user_extras = utils.get_user_info(username)
    if user_info is None:
        bot.send_message(chat_id, f"Invalid username")
        return

    command = msg.text.split()[0]
    if command == '/user':
        country_flag = convert_to_flag(user_info["country_code"])
        user_profile_url = f"http://osu.ppy.sh/u/{user_info['id']}"
        statistics = user_info["statistics"]
        is_supporter = "(osu! supporter ♥)" if user_info["is_supporter"] else ""
        bot.send_message(chat_id, f"<b>osu! standard</b>\n"
                                  f'<a href="{user_profile_url}">{user_info["username"]}</a> {is_supporter}\n\n'
                                  f'<b>rank:</b> #{statistics["rank"]["global"]} (#{statistics["rank"]["country"]}{country_flag})\n'
                                  f'<b>pp:</b> {round(statistics["pp"], 2)}\n'
                                  f'<b>accuracy:</b> {round(statistics["hit_accuracy"], 2)}%\n\n'
                                  f'<b>play count:</b> {statistics["play_count"]}\n'
                                  f'<b>play time:</b> {utils.format_time(statistics["play_time"])}', parse_mode='HTML',
                         disable_web_page_preview=True)
    if command == '/user_icon':
        bot.send_photo(chat_id, user_info["avatar_url"])
    if command == '/set_default':
        utils.set_default_username(chat_id, username)
        bot.send_message(chat_id, "Success")
    if command == "/user_best":
        res = ""
        for score in user_extras["scoresBest"]:
            beatmap_info = score["beatmap"]
            beatmap_url = f"https://osu.ppy.sh/b/{beatmap_info['id']}"
            beatmapset = score["beatmapset"]
            res += f'<a href="{beatmap_url}">{beatmapset["artist"] + " - " + beatmapset["title"]} [{beatmap_info["version"]}]</a>\n' \
                   f'mapped by <i>{beatmapset["creator"]}</i>\n' \
                   f'<b>star rating:</b> {beatmap_info["difficulty_rating"]} ⭐\n' \
                   f'<b>mods:</b> {" ".join(score["mods"]) if len(score["mods"]) > 0 else "NM"}\n' \
                   f'<b>accuracy:</b> {round(score["accuracy"] * 100, 2)}%\n' \
                   f'<b>pp:</b> {round(score["pp"], 2)}\n\n'
        bot.send_message(chat_id, res, parse_mode='HTML', disable_web_page_preview=True)
Beispiel #22
0
def get_progress(username=''):
    fancy_progress = {}
    user_progress = Global.progress[username]

    for func_desc in Global.data_dict.keys():
        if func_desc in user_progress:
            fancy_progress[func_desc] = 'completed' if user_progress[
                func_desc] else 'attempted'
        else:
            fancy_progress[func_desc] = 'not attempted'

    user_data = utils.get_user_info(username)
    data = {
        'name': user_data['name'],
        'mail': user_data['mail'],
        'progress': fancy_progress
    }
    return jsonify(data)
Beispiel #23
0
    def fill_out_profile(self, user_type, user_num=0, skip=[]):
        """ Fills out an IP or SP inital profile. (Does not submit profile)

        Args:
            user_type: The type of user (IP/SP)
            user_num: The user number to use from the user config file and constants
            skip (array): Names of fields not to complete
        """
        driver = self.driver
        user_info = get_user_info(user_type, user_num)
        # Text Fields
        form_groups = driver.find_elements(By.CLASS_NAME, "form__group")
        for key, val in user_info.get("text_input", {}).items():
            if key in skip:
                continue
            self.form_text_input(form_groups, key, val)
        # Text Areas
        for key, val in user_info.get("text_area", {}).items():
            if key in skip:
                continue
            self.form_text_area(form_groups, key, val)
        # Select Fields
        # Add checkbox elements for notification preferences
        checkbox_elements = driver.find_elements(By.CLASS_NAME,
                                                 "checkboxes-light")
        for i in checkbox_elements:
            if i not in form_groups:
                form_groups.append(i)
        for key, options in user_info.get("checkbox", {}).items():
            # print(key, options)
            if key in skip:
                continue
            self.form_checkbox(form_groups, key, options)
        for key, option in user_info.get("select", {}).items():
            # print(key, options)
            if key in skip:
                continue
            self.form_select(form_groups, key, option)
        for key, options in user_info.get("radio", {}).items():
            # print(key, options)
            if key in skip:
                continue
            self.form_radio(form_groups, key, options)
Beispiel #24
0
 def get_test_user_href(self, user_type, user_num=0):
     driver = self.driver
     user_info = get_user_info(user_type, user_num=user_num)
     user_name = user_info.get("text_input").get("Name")
     self.login("Admin")
     button_target = self.get_page_targets("header",
                                           "{0} list".format(user_type))
     user_list_button = driver.find_element(button_target[0],
                                            button_target[1])
     user_list_button.click()
     self.wait_for_page("{0} list".format(user_type), "Admin", 10)
     card_target = self.get_page_targets("{0}s".format(user_type), "card")
     # print(card_target)
     cards = driver.find_elements(card_target[0], card_target[1])
     users = get_usernames(user_type)
     for card in cards:
         title = card.find_element_by_tag_name("h1").text
         if title == user_name:
             content = card.find_element_by_class_name('card__content')
             return content.get_attribute('href')
Beispiel #25
0
def delete_animal(animal_name):
    """Delete a particular animal"""
    animal = session.query(CategoryItem).filter_by(
        name=animal_name).one_or_none()
    creator = get_user_info(session, animal.user_id)
    if 'username' not in login_session:
        return redirect('/login')
    if creator.id != login_session['user_id']:
        return render_template('unauthorized.html', categories=categories)
    if request.method == 'POST':
        session.delete(animal)
        session.commit()
        flash("%s from %s has been deleted!" %
              (animal.name, animal.category.name))
        return redirect(
            url_for('show_category_items', animal_type=animal.category.name)
        )
    return render_template(
        'delete_animal.html',
        categories=categories,
        animal_name=animal_name
    )
Beispiel #26
0
    def user_exists(self, user_type, user_num=0):
        """ Check if a user exists.

        Requires Admin user to be logged in
        """
        user_info = {
            "IP": {
                "admin_button": 'a[title="Partners"][href="#/partners"]',
                "list_identifier": "IP list"
            },
            "SP": {
                "admin_button":
                'a[title="Service Providers"][href="#/service-providers"]',
                "list_identifier": "SP list"
            }
        }
        info = user_info.get(user_type)
        exists = False
        driver = self.driver
        driver.get(self.civicdr_url)
        name = get_user_info(user_type, user_num)["text_input"]["Name"]
        creds = get_user_creds(user_type)
        # Go to user list page
        button = driver.find_element_by_css_selector(info.get('admin_button'))
        button.click()
        self.wait_for_page(info.get('list_identifier'), "Admin", 10)
        #  Find all  user elements
        users = driver.find_elements_by_tag_name('h1')
        for i in users:
            if i.text == name:
                a_obj = i.find_element_by_xpath('../..')
                a_obj.click()
                self.wait_for_page("profile", "Admin", 10)
                openid = driver.find_element_by_id('form-openid')
                val = openid.get_attribute('value')
                if val == "auth0|{0}".format(creds.uuid):
                    exists = True
                break
        return exists
Beispiel #27
0
def get_new_ts(inotify_handle):
    cache = get_cache()
    for event in inotify_handle.event_gen():
        if event is not None:
            (header, type_names, watch_path, filename) = event
            if filename.endswith('.ts') and 'IN_MOVED_TO' == type_names[0]:
                container = time.strftime("{0}%Y%m%d".format(CONTAINER_PREFIX),
                                          time.localtime())
                ts_file = "%s/%s" % (watch_path.decode('utf-8'),
                                     filename.decode('utf-8'))
                channel = ts_file.split('/')[-2]
                ts_name = ts_file.split('/')[-1].split("-")[0]
                user_info = get_user_info()
                # 获取Ts文件的播放时长
                result = get_ts_time_len(ts_file)
                if not result:
                    print "get ts time len error. ts: <{0}>".format(ts_file)
                    continue
                # 获取频道的最后一个值,用来确定序号
                channel_last = cache.lrange(channel, -1, -1)
                # ts文件的序号
                ts_order_no = 0
                if channel_last:
                    ts_obj = ConvertTsFileName(channel_last[0])
                    ts_order_no = ts_obj.ts_order_no
                    ts_order_no += 1
                new_tsname = "{0}_{1}_{2}_01ws{3}.ts".format(
                    ts_name,
                    result.split(".")[0],
                    result.split(".")[1],
                    str(ts_order_no).zfill(6))
                obj_file = channel + "/" + new_tsname
                cache.rpush(channel, new_tsname)
                upload_ts2oss(user_info=user_info,
                              container=container,
                              obj_file=obj_file,
                              ts_file=ts_file)
Beispiel #28
0
    def _eval_attributes(self, properties):
        # response struct
        _response = {
            'computer': {
                'hostname':
                self.migas_computer_name,
                'ip':
                network.get_network_info()['ip'],
                'version':
                self.migas_version,
                'platform':
                platform.system(),  # new for server 3.0
                'pms':
                str(self.pms),  # new for server 3.0
                'user':
                self._graphic_user,
                'user_fullname':
                utils.get_user_info(self._graphic_user)['fullname']
            },
            'attributes': {}
        }

        # properties converted in attributes
        self._send_message(_('Evaluating attributes...'))
        for _item in properties:
            _response['attributes'][_item['name']] = \
                self._eval_code(_item['language'], _item['code'])
            _info = '%s: %s' % (_item['name'],
                                _response['attributes'][_item['name']])
            if _response['attributes'][_item['name']].strip() != '':
                _operation_ok(_info)
            else:
                _operation_failed(_info)
                self._write_error('Error: property %s without value\n' %
                                  _item['name'])

        return _response
Beispiel #29
0
def receive_json():
    if request.method == 'POST':
        received_json = request.get_json()
        name = ''
        for array_of_something in received_json:
            for received_measure in received_json[array_of_something]:
                try:
                    name = received_measure['subject']['display']
                    if name == 'default':
                        auth = request.headers.get('Authorization', None)
                        name = utils.get_user_info(auth)['email']
                        received_measure['subject']['display'] = name
                    received_wrapper = measure_wrapper.measure_wrapper(
                        received_measure)
                    if not received_wrapper:
                        print('failed a', array_of_something)
                        raise KeyError
                    else:
                        db_inserts.insert_measure(received_wrapper)
                except KeyError:
                    return json.dumps({'status': 'failure'})
        print('received json from:', name, "at:", datetime.now())
        user_queue.put(name)
    return json.dumps({'status': 'success'})
Beispiel #30
0
def get_user_credetials():
    auth = request.headers.get('Authorization', None)
    response = make_response(json.dumps(utils.get_user_info(auth)))
    response.headers['Content-Type'] = 'application/json; charset=utf-8'
    return response
Beispiel #31
0
import json
import codecs
import time
import os
import utils
import config
import logging

URL = config.MAIN_URL
HEADER = config.HEADER



time_str = utils.init_time(time.localtime())[2]
user_info_old = utils.get_user_info_old()
user_info = utils.get_user_info()

if user_info == {} or user_info_old == {}:
    print 'get_user_info failed'
    os._exit(-1)

# 1. user_info不完整
if user_info.get('id') == None:
    print 'json not completed,'
    os._exit(-1)

# 2. user_info完整

os.system('md weibo')
os.system('md following')
os.system('md fans')
Beispiel #32
0
    def handle_response(self, msg):
        # Process replies from Internet servers to clients
        # ------------------------------------------------

        # First see if we need to show the HTTPS user agreement/certificate download
        client_ip = msg.flow.client_conn.address.address[0]
        router_ip = global_config["router_IPs"]["swap"]
        if generate_trust(msg, client_ip, router_ip):
            return
        

        # Only worry about HTML for now
        if msg.code != 200:
            return

        content_type = " ".join(msg.headers["content-type"])

        content_headers = [x.strip() for x in content_type.split(";")]
        charset = "utf-8"
        for head in content_headers:
            if head.startswith("charset="):
                charset = head[8:].lower()
        
        req = msg.flow.request
        url = "{}://{}{}".format(req.get_scheme(), "".join(req.headers["host"]), req.path)

        if content_type is not None and "text/html" in content_type:
            # Decode contents (if gzip'ed)
            contents = msg.get_decoded_content()

            client_ip = msg.flow.client_conn.address.address[0]
            hostname, mac = get_user_info(client_ip, global_config["router_IPs"]["swap"]) or client_ip
            user = {"mac": mac, "ip": client_ip, "hostname": hostname}
            
            t1 = time.time()
            replacements = load_replacements(mac, url, hostname)
            t2 = time.time()
            #print "Loaded replacements in {}ms".format((t2-t1)*1000)

            msg.content = process_as_html(user, url, contents, charset, replacements)
            
            
            # Force uncompressed response
            msg.headers["content-encoding"] = [""]

            # Force unicode
            msg.content = msg.content.encode("utf-8")
            msg.headers["content-type"] = ["{}; charset=utf-8".format(msg.headers["content-type"][0])]

        if content_type is not None and ("image/jpeg" in content_type or "image/webp" in content_type or "image/png" in content_type):
            
            filetype = "jpeg" if "jpeg" in content_type else "webp" if "webp" in content_type else "png"

            client_ip = msg.flow.client_conn.address.address[0]
            hostname, mac = get_user_info(client_ip, global_config["router_IPs"]["swap"]) or client_ip
            user = {"mac": mac, "ip": client_ip, "hostname": hostname}

            contents = msg.get_decoded_content()
            if len(contents) < 10:
                return
            msg.content = process_image(user, url, contents, filetype)
            
            msg.headers["content-encoding"] = [""]



        # Handle JSON
        if "https://twitter.com" in url and content_type is not None and ("json" in content_type or "javascript" in content_type):
            try:
                j = json.loads(msg.get_decoded_content(),  encoding = charset)
            except ValueError:
                # Not really JSON
                #print "this is not json1!!"
                return

            client_ip = msg.flow.client_conn.address.address[0]
            hostname, mac = get_user_info(client_ip, global_config["router_IPs"]["swap"]) or client_ip
            user = {"mac": mac, "ip": client_ip, "hostname": hostname}
            
            replacements = load_replacements(mac, url, hostname)
            process_html_in_json(user, url, j, charset, replacements)

            msg.content = json.dumps(j, sort_keys=True, indent=4, separators=(',', ': '), encoding="utf-8")

            # Force uncompressed response
            msg.headers["content-encoding"] = [""]

            # Force unicode
            msg.content = msg.content.encode("utf-8")
            #msg.headers["content-type"] = ["{}; charset=utf-8".format(msg.headers["content-type"][0])]
            msg.headers["content-type"] = ["text/html; charset=utf-8"]

        # Never cache response
        msg.headers["Pragma"] = ["no-cache"]
        msg.headers["Cache-Control"] = ["no-cache, no-store"]
Beispiel #33
0
                        obj_file_name = obj.get("name")
                        OSSOperate.delete_container_objs(
                            token, project_id, container_name, obj_file_name)
                    # 删除容器
                    OSSOperate.delete_container(token, project_id,
                                                container_name)

    @staticmethod
    def multi_process_del_obj_file(token, project_id, container):
        obj_files = OSSOperate.list_container_objs(token=token,
                                                   project_id=project_id,
                                                   container=container)
        for obj_file in obj_files:
            obj_file_name = obj_file.get("name")
            OSSOperate.delete_container_objs(token=token,
                                             project_id=project_id,
                                             container=container,
                                             obj_file=obj_file_name)


if __name__ == "__main__":
    user_info = get_user_info()
    # 创建新的容器,当天创建明天的容器
    tomorrow_date = int(time.time()) + 86400
    container_name = CONTAINER_PREFIX + get_date(tomorrow_date)
    OSSOperate.create_container(user_info["token"], user_info["project_id"],
                                container_name)
    # 删除n天之前的容器
    OSSOperate.delete_container_ndays_ago(user_info["token"],
                                          user_info["project_id"])
Beispiel #34
0
def match(request):
    user = get_user(request)
    user_info = get_user_info(user)
    results = []
    index = 0
    if isinstance(user_info, Employer):
        offer_list = Offer.objects.filter(employer=user_info)
        for offer in offer_list:
            index = index + 1
            offer_dict = model_to_dict(offer, fields=['id', 'post_name'])
            matches = []
            matchedRequests = RequestOfferMatch.objects.filter(offer=offer)
            match_index = 0
            for match in matchedRequests:
                match_index = match_index + 1
                employee = match.request.employee
                match_dict = model_to_dict(employee, exclude=['id', 'user', 'skills', 'gender', 'type'])
                gender = get_enum_desc_from_value(GENDER, employee.gender)
                type = get_enum_desc_from_value(EMPLOYEE_TYPE, employee.type)
                skills = ','.join([skill.name for skill in employee.skills.all()])
                match_dict['index'] = match_index
                match_dict['id'] = match.id
                match_dict['gender'] = gender
                match_dict['type'] = type
                match_dict['skills'] = skills
                match_dict['show_approve'] = match.show_approve(True)
                match_dict['show_reject'] = match.show_reject(True)
                match_dict['status_msg'] = match.get_status_msg()
                matches.append(match_dict)
            offer_dict['index'] = index
            offer_dict['matches'] = matches
            results.append(offer_dict)
        context = {"offers": results}
        template = 'partime/offer/offer_match.html'
    else:
        request_list = Request.objects.filter(employee=user_info)
        for req in request_list:
            index = index + 1
            request_dict = model_to_dict(req, fields=['id', 'date_from', 'date_to'])
            matches = []
            matchedOffers = RequestOfferMatch.objects.filter(request=req)
            match_index = 0
            for match in matchedOffers:
                match_index = match_index + 1
                offer = match.offer
                employer = offer.employer
                match_dict = model_to_dict(employer, exclude=['id', 'user', 'favor_list', 'black_list', 'gender', 'type'])
                gender = get_enum_desc_from_value(GENDER, employer.gender)
                type = get_enum_desc_from_value(EMPLOYER_TYPE, employer.type)
                match_dict['index'] = match_index
                match_dict['id'] = match.id
                match_dict['gender'] = gender
                match_dict['type'] = type
                match_dict['post_category'] = offer.post_category.name
                match_dict['duration'] = str(offer.duration) + ' ' + get_enum_desc_from_value(YTD, offer.duration_unit)
                match_dict['home_base'] = offer.home_base
                match_dict['pay_rate'] = str(offer.pay_rate) + ' ' + get_enum_desc_from_value(PAY_RATE, offer.pay_rate_unit)
                match_dict['show_approve'] = match.show_approve(False)
                match_dict['show_reject'] = match.show_reject(False)
                match_dict['status_msg'] = match.get_status_msg()
                matches.append(match_dict)
            request_dict['index'] = index
            request_dict['matches'] = matches
            results.append(request_dict)
        context = {"requests": results}
        template = 'partime/request/request_match.html'
    return render(request, template, context)