コード例 #1
0
    def __create_application_load_balancer(
            self, target_group: elbv2.ApplicationTargetGroup, vpc: ec2.Vpc):
        sub_nets = ec2.SubnetSelection(one_per_az=True,
                                       subnet_type=ec2.SubnetType.PUBLIC)
        load_balancer = elbv2.ApplicationLoadBalancer(
            self,
            id=common.generate_id("ImagizerLoadBalancer"),
            vpc=vpc,
            internet_facing=True,
            vpc_subnets=sub_nets)

        listener = load_balancer.add_listener(
            common.generate_id("ImagizerHTTPListener"),
            port=variables.PUBLIC_PORT,
            protocol=elbv2.ApplicationProtocol.HTTP)
        listener.add_target_groups(common.generate_id("ImagizerTargetGroup"),
                                   target_groups=[target_group])
        common.add_tags(self, load_balancer, variables.IMAGIZER_CLUSTER_TAGS)

        core.CfnOutput(self,
                       common.generate_id("ImagizerClusterEndpointOutput"),
                       export_name="Endpoint",
                       value="http://" + load_balancer.load_balancer_dns_name)

        return load_balancer
コード例 #2
0
ファイル: base_stack.py プロジェクト: Nventify/imagizer-aws
 def __create_vpc(self):
     vpc = ec2.Vpc(self,
                   common.generate_id("Vpc"),
                   cidr=variables.VPC_CIDR,
                   max_azs=variables.MAX_AVAILABILITY_ZONES,
                   nat_gateways=1)
     common.add_tags(self, vpc, [{
         "name": "Name",
         "value": common.generate_id("Vpc")
     }])
     return vpc
コード例 #3
0
def get_default_list(client, board):
    # XXX also insert in bridge?
    default_list = get_none(client.wekan.lists, {
        "title": "No roadmap [UNMILESTONE]",
        "boardId": board["_id"]
    })

    if default_list:
        print "'No roadmap' list already exists, return it"
        return default_list["_id"]

    all_lists = list(client.wekan.lists.find({"boardId": board["_id"]}))
    if all_lists:
        sort = 1 + max([x.get("sort", 0) for x in all_lists])
    else:
        sort = 0

    print "'No roadmap' didn't exist, create it"
    return client.wekan.lists.insert({
        "_id": generate_id(),
        "title": "No roadmap [UNMILESTONE]",
        "boardId": board["_id"],
        "archived": False,
        "createdAt": datetime.now(),
        "sort": sort
    })
コード例 #4
0
    def __create_asg(self, user_data: str, vpc: ec2.Vpc):
        subnets = ec2.SubnetSelection(one_per_az=True,
                                      subnet_type=ec2.SubnetType.PUBLIC)
        asg = autoscaling.AutoScalingGroup(
            self,
            id=common.generate_id("ImagizerAutoscalingGroup"),
            vpc=vpc,
            vpc_subnets=subnets,
            instance_type=ec2.InstanceType.of(
                instance_class=ec2.InstanceClass[variables.ASG_INSTANCE_TYPE],
                instance_size=ec2.InstanceSize[variables.ASG_INSTANCE_SIZE]),
            machine_image=ec2.GenericLinuxImage(
                ami_map={self.region: variables.IMAGIZER_AMI_ID}),
            user_data=ec2.UserData.custom(user_data),
            update_type=autoscaling.UpdateType.ROLLING_UPDATE,
            health_check=autoscaling.HealthCheck.ec2(
                grace=core.Duration.seconds(
                    variables.ASG_HEALTH_CHECK_GRACE_PERIOD)),
            cooldown=core.Duration.seconds(
                variables.ASG_HEALTH_CHECK_GRACE_PERIOD),
            min_capacity=variables.ASG_MIN_CAPACITY,
            max_capacity=variables.ASG_MAX_CAPACITY,
            rolling_update_configuration=autoscaling.
            RollingUpdateConfiguration(
                min_instances_in_service=variables.ASG_ROLL_OUT_BATCH_SIZE,
                max_batch_size=variables.ASG_ROLL_OUT_BATCH_SIZE,
                wait_on_resource_signals=True,
                pause_time=core.Duration.minutes(
                    variables.ASG_ROLL_OUT_PATCH_MINUTES)))

        common.add_tags(self, asg, variables.IMAGIZER_CLUSTER_TAGS)
        return asg
コード例 #5
0
    def create_user(self, **kwargs):
        """
        创建用户
        :param kwargs
        :return object:
        """
        try:
            database.connect(reuse_if_open=True)
            password = kwargs.get('password', None)
            if password:
                kwargs['password'] = password_utils.shal(password)
            kwargs['create_time'] = common.get_time_now()
            kwargs['update_time'] = common.get_time_now()
            kwargs['uid'] = common.generate_id()

            # 创建用户
            result = User.create(**kwargs)
            database.close()
            if result:
                return result
            else:
                return False
        except Exception as Err:
            logging.critical(Err)
            return False
コード例 #6
0
ファイル: logger.py プロジェクト: yiu31802/ave
def t1():
    pretty = common.get_test_pretty()
    print(pretty)

    b = Broker()
    w = b.get({'type': 'workspace'})
    file_name = 'test.log'

    guid = common.generate_id()

    logger = Logger(w, guid, file_path=file_name)

    result = logger.log_it('i', 'Test')

    flocker_url = '%s/%s' % (logger.parse_flocker_data(result)[0], file_name)

    log_file = urllib2.urlopen(flocker_url)

    lines = []

    for line in log_file:
        lines.append(line)

    exp_data = ['Initiating Test Job Log in flocker', 'Test']

    for i in range(len(exp_data)):
        if exp_data[i] not in lines[i]:
            print(
                'FAIL %s: Unexpected first line in log: %s, expected text "%s" '
                'not found.' % (pretty, lines[i], exp_data[i]))
            return False

    return True
コード例 #7
0
def generate_spell_item(spell_id, lvl, item_name, item_value):
    return {
            "name": "repeating_spell-" + lvl + "_-" + spell_id + "_"+ item_name,
            "current": item_value,
            "max": "",
            "id": "-" + generate_id(19)
        }
コード例 #8
0
 def generate_monster_trait_item(trait_id, item_name, item_value):
     return {
         "name": "repeating_npctrait_-" + trait_id + "_" + item_name,
         "current": item_value,
         "max": "",
         "id": "-" + generate_id(19)
     }
コード例 #9
0
 def generate_monster_action_item(action_id, item_name, item_value):
     return {
         "name": "repeating_npcaction_-" + action_id + "_" + item_name,
         "current": item_value,
         "max": "",
         "id": "-" + generate_id(19)
     }
コード例 #10
0
def interface_api_v1_save():
    data = request.get_json()
    # 参数校验
    url = data.get('url')
    if not url:
        return jsonify({
            'status': 400,
            'message': 'invalid parameter "url".',
            'data': data
        })
    method = data.get('method')
    if not method:
        return jsonify({
            'status': 400,
            'message': 'invalid parameter "method".',
            'data': data
        })
    # 判断是新增还是修改后保存
    if data.get('_id'):
        mongo.update(database='interface',
                     collection='cases',
                     filter_condition={'_id': data['_id']},
                     document=data)
    else:
        # 生成唯一id
        data['_id'] = generate_id()
        print(data)
        # 存储数据
        mongo.insert(database='interface', collection='cases', document=data)
    return jsonify({'status': 0, 'message': 'ok', 'data': data})
コード例 #11
0
 def generate_monster_item(item_name, item_value, item_max=""):
     return {
         "name": item_name,
         "current": item_value,
         "max": item_max,
         "id": "-" + generate_id(19)
     }
コード例 #12
0
ファイル: income_expenses.py プロジェクト: Voytay/Petproject
def add_record(category, data_):
    YEAR_INDEX = 0
    MONTH_INDEX = 1
    DAY_INDEX = 2
    record = [c.generate_id(data_)]

    amount = float(input('Enter the amount [0.0]: '))
    amount = format(amount, '.2f')
    record.append(str(amount))

    display.print_menu(category)
    selected_category = int(input('Chose category number: '))
    record.append(category[selected_category - 1])

    operation_details = input('Enter the operation details: ')
    record.append(operation_details)

    expanse_date = date.today()
    expanse_date = expanse_date.timetuple()
    record.append(str(expanse_date[YEAR_INDEX]))
    record.append(str(expanse_date[MONTH_INDEX]))
    record.append(str(expanse_date[DAY_INDEX]))

    data_.append(record)
    print('Record added correctly. \n')
    return data_
コード例 #13
0
 def keyword_save(self, data):
     if not data.get('mock'):
         return jsonify({
             'status_code': 400,
             'message': 'invalid parameter {mock}',
             'data': data
         })
     mock = {'data': json.loads(data['mock'])}
     snippet = data.get('snippet')
     if not snippet:
         return jsonify({
             'status_code': 400,
             'message': 'invalid parameter {snippet}',
             'data': data
         })
     name = re.findall(r'def\s+(.+?)\(', data['snippet'])
     name = name[0] if name else ""
     func = re.findall(r'def\s+(.+?):', data['snippet'])
     if func:
         snippet += '\n' + 'result=' + func[0]
     keyword = {
         '_id': generate_id(),
         'name': name,
         'mock': mock,
         'snippet': snippet
     }
     self._db.insert("variable", "keywords", keyword)
     return jsonify({
         'status_code': 200,
         'message': 'ok',
     })
コード例 #14
0
def create(companies):
    inputs = ui.get_inputs(["Name: "])

    if common.check_company_name(companies, inputs[0]):
        companies.append(Company(common.generate_id(companies), *inputs))
        ui.print_notification("Company added!")
    else:
        ui.print_notification("Company name already exists!")
コード例 #15
0
def insert_api():
    data = request.get_json()
    db.switch_database_collection('interface', 'api')
    data['_id'] = 'api_' + generate_id()
    db.insert_one(data)
    return jsonify({
        'status_code': 200,
        'message': '保存成功!',
        'data': data['_id']
    })
コード例 #16
0
def hack_one_common():
    user_id = flask.request.cookies['user_id']

    # Ensure a token exists
    with csrf_tokens_mutex:
        csrf_tokens[user_id] = csrf_tokens.get(user_id, generate_id())

    if flask.request.method == 'GET':
        return f'<form method="POST"><input name="user_id"><input type="hidden" name="csrf_token" value="{csrf_tokens[user_id]}"></form>'

    # Remember token before update
    token = csrf_tokens[user_id]
    # If it's not a get request, change token
    with csrf_tokens_mutex:
        csrf_tokens[user_id] = generate_id()

    if token != flask.request.form['csrf_token']:
        return 'CSRF attack'

    if flask.request.headers.get(
            confirmation_header) != get_admin_csrf_token():
        return 'Я подонок, я гнида, мне на все наплевать'
コード例 #17
0
 def __create_application_target_group(self,
                                       asg: autoscaling.AutoScalingGroup,
                                       vpc: ec2.Vpc):
     target_group = elbv2.ApplicationTargetGroup(
         self,
         id=common.generate_id("ImagizerTargetGroup"),
         targets=[asg],
         port=variables.PUBLIC_PORT,
         protocol=elbv2.ApplicationProtocol.HTTP,
         vpc=vpc,
         health_check=elbv2.HealthCheck(path="/health",
                                        healthy_threshold_count=2,
                                        interval=core.Duration.seconds(10)))
     common.add_tags(self, target_group, variables.IMAGIZER_CLUSTER_TAGS)
     return target_group
コード例 #18
0
def generate_spell(input_spell_json):
    spell_id = generate_id(19)

    if input_spell_json['level'] == "0":
        lvl = "cantrip"
    else:
        lvl = input_spell_json['level']

    spellcomp_v = "{{v=1}}"
    spellcomp_s = "{{s=1}}"
    spellcomp_m = "{{m=1}}"

    if input_spell_json.get('components') is not None:
        components = input_spell_json['components']
        if components.find("В") == -1:
            spellcomp_v = "0"
        if components.find("С") == -1:
            spellcomp_s = "0"
        if components.find("M") == -1:
            spellcomp_m = "0"

    if input_spell_json.get('source') is None:
        spellsource = ""
    else:
        spellsource = input_spell_json.get('source')

    name = generate_spell_item(spell_id, lvl, "spellname", input_spell_json['name'].upper())
    school = generate_spell_item(spell_id, lvl, "spellschool", spell_schools[input_spell_json['school']])
    casting_time = generate_spell_item(spell_id, lvl, "spellcastingtime", input_spell_json['castingTime'])
    spell_range = generate_spell_item(spell_id, lvl, "spellrange",  input_spell_json['range'])
    target = generate_spell_item(spell_id, lvl, "spelltarget", "")
    materials = generate_spell_item(spell_id, lvl, "spellcomp_materials", input_spell_json.get('materials'))
    text = generate_spell_item(spell_id, lvl, "spelldescription", input_spell_json['text'])
    duration = generate_spell_item(spell_id, lvl, "spellduration", input_spell_json['duration'])
    comp_v = generate_spell_item(spell_id, lvl, "spellcomp_v", spellcomp_v)
    comp_s = generate_spell_item(spell_id, lvl, "spellcomp_s", spellcomp_s)
    comp_m = generate_spell_item(spell_id, lvl, "spellcomp_m", spellcomp_m)
    source = generate_spell_item(spell_id, lvl, "spellsource", spellsource)
    details_flag = generate_spell_item(spell_id, lvl, "details-flag", "0")

    options_flag = generate_spell_item(spell_id, lvl, "options-flag", "0")

    return [name, school, casting_time, spell_range, target, materials, text, duration, comp_v, comp_s, comp_m, source,
            details_flag, options_flag]
コード例 #19
0
def get_user(client, author):
    bridge_user = get_none(client.wekan.bridge_for_users,
                           {"username": author["login"]})

    if bridge_user:
        print "Found bridge user, return matching user (%s)" % bridge_user[
            "wekan_id"]
        return get_by_id(client.wekan.users, bridge_user["wekan_id"])["_id"]

    user = get_none(client.wekan.users, {"username": author["login"]})

    if user is None:
        # TODO I need to grab the real user to fill the data, I only have the actor edge here
        user = client.wekan.users.insert({
            "_id": generate_id(),
            "createdAt": datetime.now(),
            "services": {
                "password": {},
                "email": {},
                "resume": {}
            },
            "username": author["login"],
            "emails": [],
            "isAdmin": False,
            "profile": {
                # "fullname" : "Testeu",
                # TODO copy file
                # "avatarUrl" : "/cfs/files/avatars/vvwa5nMFBRCbMc6p6/2-punaise-des-bois-pentatomes.jpg"
            }
        })
    else:
        user = user["_id"]

    bridge_user = client.wekan.bridge_for_users.insert({
        "github_id":
        author["login"],
        "wekan_id":
        user
    })

    return user
コード例 #20
0
def create(applications):
    inputs = ui.get_inputs(
        ["Status: ", "Student ID: ", "Position ID: "])

    allowed = True

    try:
        if int(inputs[0]) > 1 or int(inputs[0]) < 0:
            ui.print_notification("Status could be only either 1 or 0!")
            allowed = False
    except ValueError:
        ui.print_notification("Only numbers are allowed!")

    if inputs[1] not in student.get_students_id():
        ui.print_notification("Wrong student ID!")
        allowed = False

    if inputs[2] not in position.get_positions_id():
        ui.print_notification("Wrong position ID!")
        allowed = False

    for application in applications:
        if inputs[2] == application.position_id and inputs[1] == application.student_id:
            ui.print_notification("Student already applied to this position!")
            allowed = False
            #break

    if inputs[0] == "1":    #check if the user can create an application and not exceeded the available seats
        taken_seats = position.get_taken_seats()[0]
        max_seats = position.get_taken_seats()[1]

        for i in range(len(max_seats)):
            if max_seats[i].ID == inputs[2]:
                if taken_seats[i] >= int(max_seats[i].seats):
                    ui.print_notification("Position is full!")
                    allowed = False

    if allowed:
        applications.append(Application(common.generate_id(applications), *inputs))
        ui.print_notification("Application added!")
コード例 #21
0
def add_variable():
    data = request.get_json()
    data['_id'] = 'var_' + generate_id()
    # 根据产品和变量名判断是否已存在变量
    db.switch_database_collection('assist', 'variables')
    variable = db.find_one({
        'variable': data['variable'],
        'product': data['product']
    })
    if variable:
        return jsonify({
            'status': 400,
            'message': '已存在同名变量!',
            'data': variable['_id']
        })
    new_variable = db.insert_one(data)
    if new_variable.inserted_id:
        return jsonify({
            'status': 200,
            'message': 'ok',
            'data': new_variable.inserted_id
        })
コード例 #22
0
def create(positions):
    inputs = ui.get_inputs(["Description: ", "Seats: ", "Company ID: "])

    allowed = True

    if not inputs[0]:
        ui.print_notification("Descriptions cannot be empty!")
        allowed = False

    try:
        if int(inputs[1]) < 1:
            ui.print_notification("Seats must be greater than 0!")
            allowed = False
    except ValueError:
        ui.print_notification("Only numbers are allowed!")

    if inputs[2] not in company.get_company_ids():
        ui.print_notification("Wrong company ID!")
        allowed = False

    if allowed:
        positions.append(Position(common.generate_id(positions), *inputs))
        ui.print_notification("Position added!")
コード例 #23
0
ファイル: student.py プロジェクト: markdioszegi/TW5
def create(students):
    inputs = ui.get_inputs(
        ["Name: ", "Age: ", "Status (1 - activated, 0 - deactivated): "])

    allowed = True

    try:
        if int(inputs[1]) > 100 and int(inputs[1]) < 16:
            ui.print_notification("Wrong age! (16-99)")
            allowed = False
    except ValueError:
        ui.print_notification("Only numbers are allowed!")

    try:
        if int(inputs[2]) > 1 or int(inputs[2]) < 0:
            ui.print_notification("Status could be only either 1 or 0!")
            allowed = False
    except ValueError:
        ui.print_notification("Only numbers are allowed!")

    if allowed:
        ui.print_notification("Student added!")

    students.append(Student(common.generate_id(students), *inputs))
コード例 #24
0
            spellcasting += add_trait(traits)
        else:
            if traits is not None:
                for trait in traits:
                    spellcasting += add_trait(trait)
        is_spell_value = "1" if spellcasting > 0 else "0"
        npcspellcastingflag = generate_monster_item("npcspellcastingflag",
                                                    is_spell_value)
        attributes.append(npcspellcastingflag)

    fiction = "" if monster_json.get(
        'fiction') is None else monster_json['fiction']

    out = {
        "schema_version": 2,
        "oldId": "-" + generate_id(19),
        "name": monster_json['name'],
        "avatar": "https://tentaculus.ru/monsters/img/cute_monsters/" + image,
        "bio": fiction,
        "gmnotes": "",
        "defaulttoken": "",
        "tags": "[]",
        "controlledby": "",
        "inplayerjournals": "",
        "attribs": attributes,
        "abilities": []
    }

    with open('./monsters/' + monster_json['name'].replace("/", ",") + '.json',
              'w',
              encoding='utf-8') as f:
コード例 #25
0
def github():
    # print request
    # print request.json

    # github_hook_secret = open("./secret_for_webhook", "r").read().strip()

    # > HMAC hex digest of the payload, using the hook's secret as the key (if
    # > configured)
    # if request.headers.get("X-Hub-Signature").strip() != github_hook_secret:
    # TODO real exception
    # raise 400

    # stolen and adapted from here
    # https://github.com/carlos-jenkins/python-github-webhooks/blob/d485b31c0291d06b5153198bc1de685d50731536/webhooks.py#L72-L93
    secret = open("./github_webhook_secret", "r").read().strip()

    # Only SHA1 is supported
    header_signature = request.headers.get('X-Hub-Signature')
    if header_signature is None:
        print "no header X-Hub-Signature"
        abort(403)

    sha_name, signature = header_signature.split('=')
    if sha_name != 'sha1':
        print "signing algo isn't sha1, it's '%s'" % sha_name
        abort(501)

    # HMAC requires the key to be bytes, but data is string
    mac = hmac.new(str(secret), msg=request.data, digestmod=hashlib.sha1)

    if not hmac.compare_digest(str(mac.hexdigest()), str(signature)):
        abort(403)

    hook_type = request.headers.get("X-Github-Event")

    print "Hook type:", hook_type

    if hook_type == "pull_request":
        token = open("graphql_token", "r").read().strip()
        query = open("./query-one.graphql", "r").read()

        project = request.json["repository"]["name"]
        number = request.json["pull_request"]["number"]

        pr = requests.post("https://api.github.com/graphql",
                           headers={
                               "Authorization": "bearer %s" % token
                           },
                           json={
                               "query": query % (project, number)
                           }).json()

        print "reimporting pr %s#%s" % (project, number)
        import_pr(client, project, pr["data"]["repository"]["pullRequest"])

    elif hook_type == "milestone":
        # actions: created, closed, opened, edited, deleted

        board = get_board(client)
        project = request.json["repository"]["name"]

        if request.json["action"] == "created":
            # I need to import it here

            # this is badly name but will create list (column) on the fly
            get_list_for_milestone(client, board, project,
                                   request.json["milestone"])

        elif request.json["action"] in ("closed", "deleted"):
            print "Milestone %s#%s as been closed on github" % (
                project, request.json["milestone"]["number"])
            bridge_milestone = get(
                client.wekan.bridge_for_milestones, {
                    "github_id": request.json["milestone"]["number"],
                    "github_project": project
                })

            # if all milestone pointing to this list are closed, archive to
            # column assuming the milestone exist
            print "checking if all other PR are closed"
            all_closed = True
            # get all milestone pointing to this list
            # this sucks because I need to contact github api
            for other_miletone in client.wekan.bridge_for_milestones.find(
                {"wekan_id": bridge_milestone["wekan_id"]}):
                # GET /repos/:owner/:repo/milestones/:number
                other_project = other_miletone["github_project"]
                print "https://api.github.com/repos/yunohost/%s/milestones/%s" % (
                    other_project, other_miletone["github_id"])
                other_miletone = requests.get(
                    "https://api.github.com/repos/yunohost/%s/milestones/%s" %
                    (other_project, other_miletone["github_id"])).json()

                if other_miletone["state"] == "open":
                    print "milestone of '%s' is not closed (and maybe other), stop" % other_project
                    all_closed = False
                    break

            list_ = get_by_id(client.wekan.lists, bridge_milestone["wekan_id"])

            list_is_empty = len(
                list(
                    client.wekan.cards.find({
                        "listId": list_["_id"],
                        "archived": False
                    }))) == 0

            if all_closed and list_is_empty:
                print "all other milestone are closed, closing"
                client.wekan.lists.update({"_id": list_["_id"]},
                                          {"$set": {
                                              "archived": True
                                          }})

            if request.json["action"] == "deleted":
                client.wekan.bridge_for_milestones.remove({
                    "github_id":
                    request.json["milestone"]["number"],
                    "github_project":
                    project
                })

                # move all cards out in "no milestone" list
                print "deleting action, moving all cards "
                list_ = get_default_list(client, board)
                for card in client.wekan.cards.find({"listId": list_["_id"]}):
                    # TODO update title
                    # should I just uses the "import_pr" here?
                    client.wekan.lists.update(
                        {"_id": list_["_id"]},
                        {"$set": {
                            "listId": list_["_id"]
                        }})

        elif request.json["action"] == "opened":
            # set column state to unarchived
            # assuming the milestone exist
            bridge_milestone = get(
                client.wekan.bridge_for_milestones, {
                    "github_id": request.json["milestone"]["number"],
                    "github_project": project
                })
            list_ = get_by_id(client.wekan.lists, bridge_milestone["wekan_id"])
            client.wekan.lists.update({"_id": list_["_id"]},
                                      {"$set": {
                                          "archived": False
                                      }})

        elif request.json["action"] == "edited":
            print request.json["changes"]

            bridge_milestone = get(
                client.wekan.bridge_for_milestones, {
                    "github_id": request.json["milestone"]["number"],
                    "github_project": project
                })

            # only care about title change
            if not request.json["changes"].get("title"):
                return "ok"

            new_title = request.json["milestone"]["title"]
            new_list_title = "%s [MILESTONE]" % new_title
            list_ = get_by_id(client.wekan.lists, bridge_milestone["wekan_id"])

            # if I'm the only milestone on that column rename it
            if len(
                    list(
                        client.wekan.bridge_for_milestones.find(
                            {"wekan_id": bridge_milestone["wekan_id"]}))) == 1:
                print "I'm the only milestone on that column rename it"
                print list(
                    client.wekan.bridge_for_milestones.find(
                        {"wekan_id": bridge_milestone["wekan_id"]}))
                client.wekan.lists.update({"_id": list_["_id"]},
                                          {"$set": {
                                              "title": new_list_title
                                          }})

                # rename card: change milestone titles
                for card in client.wekan.cards.find({"listId": list_["_id"]}):
                    old_milestone_card_title = "{%s}" % request.json[
                        "changes"]["title"]["from"].lower().replace(" ", "-")
                    new_milestone_card_title = "{%s}" % request.json[
                        "milestone"]["title"].lower().replace(" ", "-")
                    title = card["title"].replace(old_milestone_card_title,
                                                  new_milestone_card_title, 1)
                    print "rename card: '%s' -> '%s'" % (card["title"], title)
                    client.wekan.cards.update({"_id": card["_id"]},
                                              {"$set": {
                                                  "title": title
                                              }})

                return "ok"

            # I'm not the only milestone pointing on that column

            target_list = get_none(client.wekan.lists,
                                   {"title": new_list_title})
            print "new_list_title:", new_list_title
            print "target list:", target_list

            board = get_board(client)

            # are they any other column with the same new title?
            if target_list:
                # if so, merge into it
                print "there is one list with the same title, merge into it"
                list_id = target_list["_id"]
            else:
                # else, create new list
                print "no other colum with new title, create a new one", request.json[
                    "milestone"]
                sort = 1 + max([
                    x.get("sort", 0)
                    for x in client.wekan.lists.find({"boardId": board["_id"]})
                ])

                print "create new list '%s'" % new_list_title
                list_id = client.wekan.lists.insert({
                    "_id": generate_id(),
                    "title": new_list_title,
                    "boardId": board["_id"],
                    "archived": False,
                    "createdAt": datetime.now(),
                    "sort": sort
                })

                client.wekan.bridge_for_milestones.update(
                    {
                        "github_project": bridge_milestone["github_project"],
                        "github_id": bridge_milestone["github_id"]
                    }, {"$set": {
                        "wekan_id": list_id
                    }})

            # move all the milestone cards into the new target list
            for bridge_pr in client.wekan.bridge_for_prs.find(
                {"github_project": project}):
                card = get_by_id(client.wekan.cards, bridge_pr["wekan_id"])

                if card["listId"] == bridge_milestone["wekan_id"]:
                    cards_in_column = list(
                        client.wekan.cards.find({
                            "boardId": board["_id"],
                            "listId": list_
                        }))
                    sort = 1 + (max(
                        [x.get("sort", 0)
                         for x in cards_in_column]) if cards_in_column else -1)

                    old_milestone_card_title = "{%s}" % request.json[
                        "changes"]["title"]["from"].lower().replace(" ", "-")
                    new_milestone_card_title = "{%s}" % request.json[
                        "milestone"]["title"].lower().replace(" ", "-")
                    title = card["title"].replace(old_milestone_card_title,
                                                  new_milestone_card_title, 1)

                    print "'%s' (%s): %s -> %s [%s]" % (
                        card["title"], card["_id"],
                        bridge_milestone["wekan_id"], list_id, sort)
                    print "rename card '%s' -> '%s'" % (card["title"], title)
                    client.wekan.cards.update({"_id": card["_id"]}, {
                        "$set": {
                            "listId": list_id,
                            "sort": sort,
                            "title": title
                        }
                    })

        else:
            print "unkown action for milestone webhook: '%s'" % request.json[
                "action"]

    elif hook_type == "label":
        # TODO
        pass

    # XXX really need to do that?
    elif hook_type == "user":
        # TODO
        pass

    else:
        print "unsupported hook type: %s" % hook_type

    return "ok"
コード例 #26
0
    def add_action(action_json):
        if action_json.get('attack') is not None:
            if isinstance(action_json['attack'], list):
                for attack in action_json['attack']:
                    action_id = generate_id(19)
                    action_name = generate_monster_action_item(
                        action_id, "name", action_json['name'] + " (" +
                        attack.split("|")[0] + ")")
                    attributes.append(action_name)
                    if isinstance(action_json['text'], list):
                        action_text = ""
                        for action_text_item in action_json['text']:
                            action_text += action_text_item.replace(
                                "<i>", "\n").replace("</i>", "\n") + "\n\n"

                    else:
                        action_text = action_json['text'].replace(
                            "<i>", "\n").replace("</i>", "\n")

                    action_description = generate_monster_action_item(
                        action_id, "description", action_text)
                    attributes.append(action_description)

                    action_attack_flag = generate_monster_action_item(
                        action_id, "attack_flag", "on")
                    attributes.append(action_attack_flag)
                    attack_tohitrange = generate_monster_action_item(
                        action_id, "attack_tohitrange",
                        "+" + attack.split("|")[1])
                    attributes.append(attack_tohitrange)
                    damage = attack.split("|")[2]
                    attack_onhit = generate_monster_action_item(
                        action_id, "attack_onhit", "")
                    attributes.append(attack_onhit)
                    attack_tohit = generate_monster_action_item(
                        action_id, "attack_tohit",
                        attack.split("|")[1])
                    attributes.append(attack_tohit)
                    action_damage = generate_monster_action_item(
                        action_id, "attack_damage", damage)
                    attributes.append(action_damage)
                    action_damage_flag = generate_monster_action_item(
                        action_id, "damage_flag",
                        "{{damage=1}} {{dmg1flag=1}}")
                    attributes.append(action_damage_flag)
                    attack_rollbase = "@{wtype}&{template:npcaction} {{attack=1}} @{damage_flag} " \
                                      "@{npc_name_flag} {{rname=@{name}}} {{r1=[[@{d20}+(@{attack_tohit})]]}} " \
                                      "@{rtype}+(@{attack_tohit})]]}} {{dmg1=[[@{attack_damage}]]}} " \
                                      "{{dmg1type=@{attack_damagetype}}} {{dmg2=[[@{attack_damage2}+0]]}} " \
                                      "{{dmg2type=@{attack_damagetype2}}} {{crit1=[[@{attack_crit}+0]]}} " \
                                      "{{crit2=[[@{attack_crit2}+0]]}} {{description=@{show_desc}}} @{charname_output}"
                    rollbase = generate_monster_action_item(
                        action_id, "rollbase", attack_rollbase)
                    attributes.append(rollbase)
                    crit1 = generate_monster_action_item(
                        action_id, "attack_crit",
                        attack.split("|")[2])
                    attributes.append(crit1)
                    crit2 = generate_monster_action_item(
                        action_id, "attack_crit2", "")
                    attributes.append(crit2)

            else:
                action_id = generate_id(19)
                action_name = generate_monster_action_item(
                    action_id, "name", action_json['name'])
                attributes.append(action_name)
                if isinstance(action_json['text'], list):
                    action_text = ""
                    for action_text_item in action_json['text']:
                        action_text += action_text_item.replace(
                            "<i>", "\n").replace("</i>", "\n") + "\n\n"

                else:
                    action_text = action_json['text'].replace("<i>",
                                                              "\n").replace(
                                                                  "</i>", "\n")
                action_description = generate_monster_action_item(
                    action_id, "description", action_text)
                attributes.append(action_description)

                action_attack_flag = generate_monster_action_item(
                    action_id, "attack_flag", "on")
                attributes.append(action_attack_flag)
                attack_tohitrange = generate_monster_action_item(
                    action_id, "attack_tohitrange",
                    "+" + action_json['attack'].split("|")[1])
                attributes.append(attack_tohitrange)
                damage = action_json['attack'].split("|")[2]
                attack_onhit = generate_monster_action_item(
                    action_id, "attack_onhit", "")
                attributes.append(attack_onhit)
                attack_tohit = generate_monster_action_item(
                    action_id, "attack_tohit",
                    action_json['attack'].split("|")[1])
                attributes.append(attack_tohit)
                action_damage = generate_monster_action_item(
                    action_id, "attack_damage", damage)
                attributes.append(action_damage)
                action_damage_flag = generate_monster_action_item(
                    action_id, "damage_flag", "{{damage=1}} {{dmg1flag=1}}")
                attributes.append(action_damage_flag)
                attack_rollbase = "@{wtype}&{template:npcaction} {{attack=1}} @{damage_flag} " \
                                  "@{npc_name_flag} {{rname=@{name}}} {{r1=[[@{d20}+(@{attack_tohit})]]}} " \
                                  "@{rtype}+(@{attack_tohit})]]}} {{dmg1=[[@{attack_damage}]]}} " \
                                  "{{dmg1type=@{attack_damagetype}}} {{dmg2=[[@{attack_damage2}+0]]}} " \
                                  "{{dmg2type=@{attack_damagetype2}}} {{crit1=[[@{attack_crit}+0]]}} " \
                                  "{{crit2=[[@{attack_crit2}+0]]}} {{description=@{show_desc}}} @{charname_output}"
                rollbase = generate_monster_action_item(
                    action_id, "rollbase", attack_rollbase)
                attributes.append(rollbase)
                crit1 = generate_monster_action_item(
                    action_id, "attack_crit",
                    action_json['attack'].split("|")[2])
                attributes.append(crit1)
                crit2 = generate_monster_action_item(action_id, "attack_crit2",
                                                     "")
                attributes.append(crit2)
        else:
            action_id = generate_id(19)
            action_name = generate_monster_action_item(action_id, "name",
                                                       action_json['name'])
            attributes.append(action_name)
            action_description = generate_monster_action_item(
                action_id, "description", action_json['text'])
            attributes.append(action_description)
            attack_tohitrange = generate_monster_action_item(
                action_id, "attack_tohitrange", "+0")
            attributes.append(attack_tohitrange)
            attack_onhit = generate_monster_action_item(
                action_id, "attack_onhit", "")
            attributes.append(attack_onhit)
            action_damage_flag = generate_monster_action_item(
                action_id, "damage_flag", "")
            attributes.append(action_damage_flag)

            crit1 = generate_monster_action_item(action_id, "attack_crit", "")
            attributes.append(crit1)
            crit2 = generate_monster_action_item(action_id, "attack_crit2", "")
            attributes.append(crit2)

            attack_rollbase = "@{wtype}&{template:npcaction} @{npc_name_flag} {{rname=@{name}}} " \
                              "{{description=@{show_desc}}} @{charname_output}"

            rollbase = generate_monster_action_item(action_id, "rollbase",
                                                    attack_rollbase)
            attributes.append(rollbase)
コード例 #27
0
    def add_trait(trait_json):
        is_spell = 0
        # if trait_json.get('attack') is not None:
        #     add_action(trait_json)
        # else:
        trait_id = generate_id(19)
        trait_name = generate_monster_trait_item(trait_id, "name",
                                                 trait_json['name'])
        attributes.append(trait_name)
        trait_text = trait_json['text']

        text = ""
        if isinstance(trait_text, list):
            for trait_text_item in trait_text:
                text += trait_text_item.replace("<br>", "\n\n").replace(
                    "<i>", "\n").replace("</i>", "\n") + "\n\n"
                if trait_text_item.find(
                        "<a href='https://tentaculus.ru/spells/#q=") != -1:
                    text = text.replace(
                        "<a href='https://tentaculus.ru/spells/#q=", "")
                    text = text.replace("'>", "")
                    text = text.replace("&view=text", "")
                    text = text.replace("</a>", ": ")
                    is_spell += 1
                    spells_links = trait_text_item.split(
                        "<a href='https://tentaculus.ru/spells/#q=")
                    spells = []
                    spells_links.pop(0)
                    for spell in spells_links:
                        spells.append(
                            spell.split("'>")[0].replace('&view=text',
                                                         "").replace("_", " "))
                        text = text.replace(spell.split("'>")[0] + "'", "")
                    spells_json = generate_spells_out_json(spells)
                    for spell_item in spells_json:
                        attributes.append(spell_item)

        else:
            text += trait_text.replace("<br>", "\n\n").replace("<i>",
                                                               "\n").replace(
                                                                   "</i>", "")
            if trait_text.find(
                    "<a href='https://tentaculus.ru/spells/#q=") != -1:
                text = text.replace(
                    "<a href='https://tentaculus.ru/spells/#q=", "")
                text = text.replace("</a>", "")
                is_spell += 1
                spells_links = trait_text.split(
                    "<a href='https://tentaculus.ru/spells/#q=")
                spells = []
                spells_links.pop(0)
                for spell in spells_links:
                    spells.append(
                        spell.split("'>")[0].replace('&view=text',
                                                     "").replace("_", " "))
                    text = text.replace(spell.split("'>")[0] + "'", "")
                spells_json = generate_spells_out_json(spells)
                for spell_item in spells_json:
                    attributes.append(spell_item)

        trait_desc = generate_monster_trait_item(trait_id, "description", text)
        attributes.append(trait_desc)
        return is_spell
コード例 #28
0
def get_list_for_milestone(client, board, project, milestone):
    def update_list(list_, milestone):
        if list_["title"] != milestone_title:
            print "Updating milestone 'title from '%s' to '%s'" % (
                list_["title"], milestone_title)
            list_["title"] = milestone_title
            client.wekan.lists.update({"_id": list_["_id"]}, {"$set": list_})

        archived = milestone["state"] == "CLOSED"
        if list_["archived"] != archived:
            if archived:
                print "Archiving milestone '%s'" % (list_['title'])
            else:
                print "Briging milestone '%s' back from archives" % (
                    list_['title'])
            list_["archived"] = archived
            client.wekan.lists.update({"_id": list_["_id"]}, {"$set": list_})

    milestone_title = "%s [MILESTONE]" % milestone["title"]

    bridge_milestone = get_none(client.wekan.bridge_for_milestones, {
        "github_id": milestone["number"],
        "github_project": project
    })

    if bridge_milestone:
        print "Found bridge_milestone, return list"
        list_ = get_by_id(client.wekan.lists, bridge_milestone["wekan_id"])
        update_list(list_, milestone)
        return list_["_id"]

    # let's try to find an existing colum with the milestone name
    list_ = get_none(client.wekan.lists, {"title": milestone_title})

    # create it
    if not list_:
        sort = 1 + max([
            x.get("sort", 0)
            for x in client.wekan.lists.find({"boardId": board["_id"]})
        ])

        print "create new list '%s'" % milestone_title
        list_ = client.wekan.lists.insert({
            "_id":
            generate_id(),
            "title":
            milestone_title,
            "boardId":
            board["_id"],
            "archived":
            milestone["state"].upper() == "CLOSED",
            "createdAt":
            datetime.now(),
            "sort":
            sort
        })
    else:
        update_list(list_, milestone)
        list_ = list_["_id"]
        print "List exists for milestone '%s', return it" % milestone["title"]

    print "Create bridge for milestone %s -> %s" % (milestone["number"], list_)
    bridge_milestone = client.wekan.bridge_for_milestones.insert({
        "github_id":
        milestone["number"],
        "github_project":
        project,
        "wekan_id":
        list_
    })

    return list_
コード例 #29
0
 def insert(self, data):
     data['_id'] = generate_id()
     return self._db.insert('variable', 'variables', data)
コード例 #30
0
def import_pr(client, project, pr):
    # TODO create the bord if it doesn't exist
    board = get_board(client)

    print "Working on '%s' (%s)" % (pr["title"], pr["url"])

    bridge_pr = get_none(client.wekan.bridge_for_prs, {
        "github_id": pr["number"],
        "github_project": project
    })

    # get list for milestone
    milestone = pr["milestone"]
    if milestone is None:
        print "No milestone"
        list_ = get_default_list(client, board)
        title = "%s#%s %s" % (project.upper(), pr["number"], pr["title"])
        print "selected default list (%s)" % (list_)
    else:
        print "Has milestone"
        list_ = get_list_for_milestone(client, board, project, milestone)

        # include milestone in card title
        title = "%s#%s {%s} %s" % (project.upper(), pr["number"],
                                   milestone["title"].lower().replace(
                                       " ", "-"), pr["title"])

        print "selected list '%s' (%s)" % (milestone["title"], list_)

    if pr["labels"]["edges"]:
        title += " %s" % " ".join([
            "#" + x["node"]["name"].lower().replace(" ", "-")
            for x in pr["labels"]["edges"]
        ])

    # get user for ticket
    user = get_user(client, pr["author"])
    print "selected user '%s' (%s)" % (pr["author"]["login"], user)

    # we haven't imported this PR yet
    if not bridge_pr:
        cards_in_column = list(
            client.wekan.cards.find({
                "boardId": board["_id"],
                "listId": list_
            }))
        sort = 1 + (max([x.get("sort", 0)
                         for x in cards_in_column]) if cards_in_column else -1)

        card = client.wekan.cards.insert({
            "_id": generate_id(),
            "title": title,
            "description": pr["url"],
            "members": [],
            "labelIds": [],
            "listId": list_,
            "boardId": board["_id"],
            "sort": sort,
            "archived": pr["closed"],
            "createdAt": datetime.now(),  # XXX uses card value?
            "dateLastActivity": datetime.now(),
            "userId": user
        })
        print "create card '%s' (%s)" % (pr["title"], card)

        bridge_pr = client.wekan.bridge_for_prs.insert({
            "github_id":
            pr["number"],
            "github_project":
            project,
            "wekan_id":
            card,
        })
        print "create card bridge %s -> %s" % (pr["number"], card)

    else:
        print "Card already exist, update"
        card = get_by_id(client.wekan.cards, bridge_pr["wekan_id"])

        if card["title"] != title:
            print "change title from '%s' to '%s'" % (card["title"], title)
            card["title"] = title

        if card["listId"] != list_:
            before_list = get_by_id(client.wekan.lists, card["listId"])
            after_list = get_by_id(client.wekan.lists, list_)
            print "move card from '%s' -> '%s'" % (before_list["title"],
                                                   after_list["title"])

        if card["archived"] != pr["closed"]:
            if pr["closed"]:
                print "archiving the card"
            else:
                print "card is re-opened"
            card["archived"] = pr["closed"]

        if card["userId"] != user:
            print "card has change of author for a weird reason, update it"
            card["userId"] = user

        if card.get("description", "") != pr["url"]:
            print "update descript from '%s' to '%s'" % (card.get(
                "description", ""), pr["url"])
            card["description"] = pr["url"]

        client.wekan.cards.update({"_id": card["_id"]}, {"$set": card})