Esempio n. 1
0
def remove_issue(user, id):
    """Deletes issue from the db"""
    Issue.delete_issue(id)
    response = Response("Issue deleted",
                        status=200,
                        mimetype="application/json")
    return response
Esempio n. 2
0
    def get_digest(self):
        """
        builds a DigestData instance filled with the digest
        """
        issue_list = list(self.get_issues())

        digest = DigestData()
        digest.user = self._user
        digest.repo = self._repository_name

        for github_issue in issue_list:
            if github_issue.state == IssueStates.OPEN:
                digest.total_opened += 1
            elif github_issue.state == IssueStates.CLOSED:
                digest.total_closed += 1

            digest.total_issues += 1

            issue = Issue()
            issue.url = github_issue.html_url
            issue.label = '{}/{}#{}'.format(self._user, self._repository_name, github_issue.number)
            issue.title = github_issue.title
            issue.state = github_issue.state
            github_user = github_issue.user

            display_name = github_user.name or github_user.login
            if display_name not in digest.users:
                user = User()
                user.name = display_name
                user.gravatar = github_user.avatar_url
                digest.users[display_name] = user

            digest.issues.setdefault(display_name, []).append(issue)

        return digest
Esempio n. 3
0
def create_issue(customer_id, body):
    issue_schema = IssueSchema()
    issue_data = issue_schema.load(body).data

    new_issue = Issue(**issue_data)

    if customers.get(customer_id):
        new_issue.customer_id = customer_id
    else:
        response = {
            'message': 'Customer with id {id} not exists'.format(id=customer_id)
        }
        return response, 409

    db.session.add(new_issue)
    db.session.commit()

    issue_history = IssueHistory(
        issue_id=new_issue.id,
        status_id=1,
    )

    db.session.add(issue_history)
    db.session.commit()

    issue_data = issue_schema.dump(new_issue).data

    return issue_data, 201
Esempio n. 4
0
def add_issue():
    """ Create an issue """
    data = request.get_json()
    if 'title' in data and 'description' in data and data['title'].strip():
        issue = Issue(data['title'].strip(), data['description'].strip(), current_user.id)
        db.session.add(issue)
        db.session.commit()
        return jsonify(issue.to_dict()), 201
    return 'Invalid title or description', 422
Esempio n. 5
0
    def get(self, slug):

        output = get_cache("project_%s_rss" % slug)
        if output is None:

            project = Project.all().filter('slug =', slug).fetch(1)[0]

            # allow query string arguments to specify filters
            if self.request.get("open"):
                status_filter = True
                fixed = False
            elif self.request.get("closed"):
                status_filter = True
                fixed = True
            else:
                status_filter = None

            # if we have a filter then filter the results set
            if status_filter:
                issues = Issue.all().filter('project =', project).filter(
                    'fixed =', fixed).order('fixed').order('created_date')
            else:
                issues = Issue.all().filter(
                    'project =', project).order('fixed').order('created_date')

            # create the RSS feed
            rss = RSS2(title="Issues for %s on GitBug" % project.name,
                       link="%s/%s/" % (settings.SYSTEM_URL, project.slug),
                       description="",
                       lastBuildDate=datetime.now())

            # add an item for each issue
            for issue in issues:
                if issue.fixed:
                    pubDate = issue.fixed_date
                    title = "%s (%s)" % (issue.name, "Fixed")
                else:
                    pubDate = issue.created_date
                    title = issue.name

                rss.items.append(
                    RSSItem(title=title,
                            link="%s/projects%s" %
                            (settings.SYSTEM_URL, issue.internal_url),
                            description=issue.html,
                            pubDate=pubDate))

            # get the xml
            output = rss.to_xml()

            memcache.add("project_%s_rss" % slug, output, 3600)
        # send the correct headers
        self.response.headers[
            "Content-Type"] = "application/rss+xml; charset=utf8"
        self.response.out.write(output)
	def setUp(self):
		self.client = app.test_client()
		db.drop_all()
		db.create_all()

		c1 = Category(
        category_id=0,
        category_label="Technical Issue"
    )

		p1 = Priority(
        priority_id=1,
        priority_label="Medium"
    )

		s1 = Status(
        status_id=0,
        status_label="Submitted"
    )

		ro1 = Role(
        role_id=0,
        role_label="user"
    )

		ro2 = Role(
        role_id=1,
        role_label="assignee"
    )

		ro3 = Role(
        role_id=2,
        role_label="admin"
    )

		db.session.add_all([c1,p1,s1,ro1,ro2,ro3])
		db.session.commit()

		User.query.delete()
		Issue.query.delete()

		user1 = User.register(**TEST_USER1)
		user2 = User.register(**TEST_USER2)
		user1.role = 2
		db.session.add_all([user1,user2])
		db.session.commit()

		issue1 = Issue(title="Test Issue 1", text="Issue 1 description", reporter=user1.id)
		issue2 = Issue(title="Test Issue 2", text="Issue 2 description", reporter=user2.id)
		db.session.add_all([issue1,issue2])
		db.session.commit()

		comment1 = Comment(comment_text="This is a comment", comment_user=2, comment_issue=2)
		db.session.add(comment1)
		db.session.commit()
Esempio n. 7
0
File: views.py Progetto: sjhest/Ti
def save_issue(request):
    requester = models.Ti_user.objects.get(id=request.user.id)
    title = request.POST.get('title')
    description = request.POST.get('description')
    severity = request.POST.get('severity')
    department = models.Department.objects.get(department_name=request.POST.get('department'))
    issue = Issue(title = title, description = description, requester = requester, assigned_group = department, Severity = severity)
    issue.save()
    print issue.id
    comments = models.Comment.objects.filter(issue_id=issue.id).order_by('-created_time')
    return HttpResponseRedirect('/issue/%s' %issue.id)
Esempio n. 8
0
 def test_issue(self):
     issue = Issue(user=self.user,
                   project=self.project,
                   id=42,
                   title="Wrong encoding",
                   action="opened",
                   url="http://bugtracker.example.com/issue/42")
     self.assertEqual(
         issue.render_simple(),
         "[My Project] Mrs Foobar opened issue #42: Wrong encoding. "
         "(http://bugtracker.example.com/issue/42)")
Esempio n. 9
0
    def test_issue_creation(self):
        c = Category.objects.all()[0]

        i = Issue(summary="Test",
                  description="Test",
                  reporter_name="User",
                  reporter_email="*****@*****.**",
                  urgent=True,
                  category=c)
        i.save()
        iid = i.id
        i = Issue.objects.get(id=iid)
        self.failUnlessEqual(i.summary, "Test")
Esempio n. 10
0
def put_issue(user, id):
    """Edits issue in the db"""
    request_data = request.get_json(force=True)
    Issue.update_issue(
        id,
        request_data["title"],
        request_data["details"],
        request_data["status"],
        request_data["priority"],
    )
    response = Response("Issue updated",
                        status=200,
                        mimetype="application/json")
    return response
Esempio n. 11
0
 def test_issue(self):
     issue = Issue(
         user=self.user,
         project=self.project,
         id=42,
         title="Wrong encoding",
         action="opened",
         url="http://bugtracker.example.com/issue/42"
     )
     self.assertEqual(
         issue.render_simple(),
         "[My Project] Mrs Foobar opened issue #42: Wrong encoding. "
         "(http://bugtracker.example.com/issue/42)"
     )
Esempio n. 12
0
def add_issue(current_user, id):
    """Adds new issue to db"""
    request_data = request.get_json(force=True)  # getting data from client
    # project = current_user.projects.filter_by(id=id).first()
    project = Project.query.get(id)
    Issue.add_issue(
        request_data["title"],
        request_data["details"],
        request_data["status"],
        request_data["priority"],
        project,
    )
    response = Response("Issue added", 201, mimetype="application/json")
    return response
Esempio n. 13
0
def save_issues(issues, project, fetch_index):
    for issue in issues:
        Issue.create(
            fetch_index=fetch_index,
            github_id=issue['id'],
            project=project,
            number=issue['number'],
            created_at=issue['created_at'],
            updated_at=issue['updated_at'],
            closed_at=issue['closed_at'],
            state=issue['state'],
            body=issue['body'],
            comments=issue['comments'],
            user_id=issue['user']['id'],
        )
Esempio n. 14
0
def index(request):
    if request.POST:
        issue = Issue()
        form = IssueForm(request.POST, instance=issue)
        if (form.is_valid()):
            #send issue to GitHub
            title = form.cleaned_data.get('title')
            body = form.cleaned_data.get('body')
            url = 'https://api.github.com/repos/mcdermott-scholars/mcdermott/issues'
            auth = (settings.GITHUB_USERNAME, settings.GITHUB_PASSWORD)
            data = {'title': title, 'body': body}
            r = requests.post(url, auth=auth, data=json.dumps(data))
            messages.add_message(
                request,
                messages.SUCCESS if r.status_code == 201 else messages.ERROR,
                'Issue submitted'
                if r.status_code == 201 else 'Error submitting issue',
            )
            return redirect(reverse('issues:index'))
        else:
            form = IssueForm(request.POST, instance=issue)
    else:
        form = IssueForm()
    context = {
        'form': form,
    }
    return render(request, 'issues/index.html', context)
Esempio n. 15
0
    def create_issue(self, data):
        session = self.session_maker()

        try:
            pollution_category_id = session.query(PollutionCategory).filter(
                PollutionCategory.category == data.get(
                    'pollution_category')).one_or_none().id
            data['pollution_category'] = pollution_category_id
            unapproved_issue_id = session.query(IssueState).filter(
                IssueState.state == 'new').one_or_none().id
            data['state_id'] = unapproved_issue_id

            new_issue = Issue(data)
            session.add(new_issue)
            session.commit()

            issue_fields = [
                'id', 'title', 'description', 'location', 'date',
                'pollution_rating', 'pollution_category', 'creator'
            ]
            result = to_dict(new_issue, [i for i in issue_fields])
            point = wkb.loads(bytes(new_issue.location.data))
            result['location'] = {'x': point.x, 'y': point.y}
            result[
                'pollution_category'] = new_issue.pollution_category.category
            result['creator'] = new_issue.creator.username

            return (result, True)
        except Exception as e:
            return (e.args, False)
Esempio n. 16
0
def new_issue():
    """New issue form and handler."""

    categories = Category.query.all()
    categories_list = [(c.category_id, c.category_label) for c in categories]
    priorities = Priority.query.all()
    priorities_list = [(p.priority_id, p.priority_label) for p in priorities]

    # import pdb; pdb.set_trace()

    form = NewIssueForm(category=0, priority=1)
    form.category.choices = categories_list
    form.priority.choices = priorities_list

    if form.validate_on_submit():
        title = form.title.data
        text = form.text.data
        category = form.category.data
        priority = form.priority.data

        issue = Issue(title=title,
                      text=text,
                      category=category,
                      priority=priority,
                      reporter=current_user.id)
        db.session.add(issue)
        db.session.commit()
        flash("Issue submitted", "success")
        return redirect("/")

    return render_template('issues/new.html', form=form)
Esempio n. 17
0
    def get(self, project_slug, issue_slug):

        if self.request.path[-1] != "/":
            self.redirect("%s/" % self.request.path, True)
            return

        # if we don't have a user then throw
        # an unauthorised error
        user = users.get_current_user()
        if not user:
            self.render_403()
            return

        issue = Issue.all().filter('internal_url =', "/%s/%s/" %
                                   (project_slug, issue_slug)).fetch(1)[0]

        if issue.project.user == user or users.is_current_user_admin():
            context = {
                'issue': issue,
                'owner': True,
            }
            output = self.render("issue_delete.html", context)
            self.response.out.write(output)
        else:
            self.render_403()
            return
Esempio n. 18
0
    def __load(self):
        try:
            handle = open(os.path.join(self.__base, "namespaces.txt"), mode='r', encoding='utf-8')
            content = handle.read()
            handle.close()

            self.__ns = []
            self.__data = {}
            namespaces = content.split("\n")
            for namespace in namespaces:
                ns = Namespace.fromstr(namespace)
                if ns is not None:
                    self.__ns.append(ns)
                    self.__data[ns.key] = []

            for namespace in self.__ns:
                key = namespace.key
                handle = open(os.path.join(self.__base, key), 'rb')
                entries = struct.unpack('>h', handle.read(2))[0]
                issues = []
                for entry in range(0, entries):
                    issue_no = struct.unpack('>h', handle.read(2))[0]
                    desc_len = struct.unpack('>h', handle.read(2))[0]
                    desc = handle.read(desc_len).decode('utf-8')
                    issues.append(Issue(issue_no, desc))
                self.__data[key] = issues

            return True
        except Exception as e:
            print(e)
            return False
Esempio n. 19
0
    def post(self, slug):
        project = Project.all().filter('slug =', slug).fetch(1)[0]

        key = self.request.get("key")

        if key == project.key():
            try:
                payload = self.request.get("payload")
                representation = simplejson.loads(payload)
                commits = representation['commits']
                for commit in commits:
                    message = commit['message']
                    search = GITBUG.search(message)
                    if search:
                        identifier = search.group()[7:]
                        issue = Issue.all().filter(
                            'project =',
                            project).filter('identifier =',
                                            int(identifier)).fetch(1)[0]
                        issue.fixed = True
                        issue.put()
                        logging.info("issue updated via webhook: %s in %s" %
                                     (issue.name, issue.project.name))
            except Exception, e:
                logging.error("webhook error: %s" % e)
Esempio n. 20
0
def parse_issue(ctxt, hook):
    attrs = hook["object_attributes"]
    return Issue(user=ctxt.user,
                 project=ctxt.project,
                 id=attrs["iid"],
                 title=attrs["title"],
                 action=_preterit(attrs["action"]),
                 url=attrs["url"])
Esempio n. 21
0
def parse_issue(ctxt, hook):
    issue = hook["issue"]
    return Issue(user=ctxt.user,
                 project=ctxt.project,
                 id=issue["id"],
                 title=issue["title"],
                 action=hook["action"],
                 url=issue["url"])
Esempio n. 22
0
    def get(self, project_slug, issue_slug):
        if self.request.path[-1] != "/":
            self.redirect("%s/" % self.request.path, True)
            return

        user = users.get_current_user()

        output = None
        if not user:
            output = get_cache("/%s/%s/" % (project_slug, issue_slug))

        if output is None:
            try:
                issue = Issue.all().filter(
                    'internal_url =',
                    "/%s/%s/" % (project_slug, issue_slug)).fetch(1)[0]
                issues = Issue.all().filter('project =', issue.project).filter(
                    'fixed =', False).fetch(10)
            except IndexError:
                self.render_404()
                return

            on_list = False
            try:
                if user.email() in issue.project.other_users:
                    on_list = True
            except:
                pass

            if issue.project.user == user or users.is_current_user_admin(
            ) or on_list:
                owner = True
            else:
                owner = False
            context = {
                'issue': issue,
                'issues': issues,
                'owner': owner,
            }
            # calculate the template path
            output = self.render("issue.html", context)

        if not user:
            memcache.add("/%s/%s/" % (project_slug, issue_slug), output, 60)

        self.response.out.write(output)
Esempio n. 23
0
    def get(self, slug):
        output = get_cache("project_%s_json" % slug)
        if output is None:
            project = Project.all().filter('slug =', slug).fetch(1)[0]
            issues = Issue.all().filter(
                'project =', project).order('fixed').order('created_date')

            issues_data = {}
            for issue in issues:
                # friendlier display of information
                if issue.fixed:
                    status = "Fixed"
                else:
                    status = "Open"

                # set structure of inner json
                data = {
                    'internal_url':
                    "%s/projects%s" %
                    (settings.SYSTEM_URL, issue.internal_url),
                    'created_date':
                    str(project.created_date)[0:19],
                    'description':
                    issue.html,
                    'status':
                    status,
                    'identifier':
                    "#gitbug%s" % issue.identifier,
                }
                if issue.fixed and issue.fixed_description:
                    data['fixed_description'] = issue.fixed_description
                issues_data[issue.name] = data

            # set structure of outer json
            json = {
                'date':
                str(datetime.now())[0:19],
                'name':
                project.name,
                'internal_url':
                "%s/projects/%s/" % (settings.SYSTEM_URL, project.slug),
                'created_date':
                str(project.created_date)[0:19],
                'issues':
                issues_data,
            }

            if project.url:
                json['external_url'] = project.url

            # create the json
            output = simplejson.dumps(json)
            # cache it
            memcache.add("project_%s_json" % slug, output, 3600)
        # send the correct headers
        self.response.headers[
            "Content-Type"] = "application/javascript; charset=utf8"
        self.response.out.write(output)
Esempio n. 24
0
def paynow(request):
    languages = []
    for lang in Issue.LANGUAGES:
        languages.append(lang[0])
    issuetracker = request.POST.get('issuetracker')
    issueurl = request.POST.get('issueUrl')
    issuetitle = request.POST.get('title')
    issuesummary = request.POST.get('summary')
    language = request.POST.get('language')
    bounty = request.POST.get('bounty')
    message = ''
    if not bounty:
        message = "Bounty is required."
    if not issuesummary:
        message = "Summary is required."
    if not issuetitle:
        message = "Title is required."
    if not issueurl:
        message = "Issue URL is required."
    if not message:
        userprofile = UserProfile()
        issuesaver = Issue()
        issuesaver.title = issuetitle
        issuesaver.content = issuesummary
        issuesaver.language = language
        issuesaver.notified_user = False
        issuesaver.status = "open"
        issuesaver.user = request.user
        issuesaver.save()

        bountysaver = Bounty()
        bountysaver.price = bounty
        bountysaver.issue = issuesaver
        bountysaver.user = request.user
        bountysaver.save()

        return render(request, 'post.html', {
            'languages': languages,
            'message': 'Successfully registered on DB.'
        })
    else:
        return render(request, 'post.html', {
            'languages': languages,
            'message': message
        })
Esempio n. 25
0
def read_issues(file_name):
    items = []
    with gzip.open(f'{file_name}.gz', 'rb') as f:
        reader = Reader(f)
        # with jsonlines.open(file_name) as reader:
        for obj in reader:
            pr = create_obj(obj, Issue())
            items.append(pr)
    return items
Esempio n. 26
0
def update_comment(issue_id, comment):
    with get_session() as s:
        issue = Issue.get_by_id(issue_id)
        if issue:
            issue.content = comment
            s.add(issue)
            return "mapped with url: " + issue.id

        return "not found"
Esempio n. 27
0
def save_comment(comment):
    with get_session() as s:
        issue = Issue.get_latest_one(s)
        if issue:
            issue.content = comment
            s.add(issue)
            return "{}: {}#{}".format(comment, config.SHARE_BOT_URL, issue.id)

        return "not found"
Esempio n. 28
0
def add_issue_to_database(request):

    issue = request.session.get('issue', False)
    service = Service.objects.get(name=issue['service'])

    try:
        db_issue = Issue.objects.get(service=service,
                                     number=issue['number'],
                                     project=issue['project'])
        if db_issue.status == "paid":
            error = "I see that issue has been closed and paid already."
            messages.error(request, error)
            return False
    except:

        db_issue = Issue(service=service,
                         number=issue['number'],
                         project=issue['project'],
                         user=issue.has_key('user') and issue['user'] or '',
                         title=issue['title'],
                         content=issue['content'][:350],
                         status=issue['status'])
        filename, file = get_image_for_issue(service, issue)
        if filename:
            db_issue.image.save(filename, file)
        db_issue.save()
        if not settings.DEBUG:
            create_comment(db_issue)

    ends = issue['limit']
    hour_day = ends[-1]
    number = ends.rstrip(hour_day)
    if hour_day == "h":
        limit = datetime.timedelta(hours=int(number))
    else:
        limit = datetime.timedelta(days=int(number))
    bounty = Bounty(user=request.user,
                    issue=db_issue,
                    price=issue['bounty'],
                    ends=datetime.datetime.now() + limit)
    bounty.save()
    alert_watchers_increase(db_issue, int(request.GET.get('bounty', 0)))
    del request.session['issue']
    return True
Esempio n. 29
0
	def get(self):
		user = users.get_current_user()
		if user:
			logout_url = users.create_logout_url('/')
		else:
			login_url = users.create_login_url('/')
		issues = Issue.all().order('creation_date').fetch(30)
		success_type = self.request.get('success')
		success_msg = None
		if success_type == 'vote':
			success_msg = 'Your vote was successfully cast!'
		if success_type == 'updated':
			success_msg = 'Your vote was successfully updated!'
		created_by = Issue.issues_created_by(member=user,limit=20)
		voted_on = Issue.issues_voted_on(member=user,limit=20)
		#recent_results = [issue for issue in voted_on if issue.has_results]
		recent_voted = [issue for issue in voted_on if issue.is_active()]
		recent_results = Issue.recent_results(limit=20)
		self.response.out.write(template.render('templates/overview.html', locals()))
Esempio n. 30
0
def create_issue():
    data = json.loads(request.data)
    issue = Issue(data["description"], data["lat"], data["lng"], data["kind"])
    db.session.add(issue)
    db.session.commit()
    fh = open("issue_pics/{}.png".format(issue.id), "wb")
    fh.write(data["image"].decode('base64'))
    fh.close()

    return json.dumps({"result": True})
Esempio n. 31
0
	def get(self,id):
		user = users.get_current_user()
		if user:
			logout_url = users.create_logout_url('/')
		else:
			self.redirect(users.create_login_url(self.request.uri))
			return
		issue = Issue.get_by_id(int(id))
		choices = issue.choices
		self.response.out.write(template.render('templates/edit.html', locals()))
Esempio n. 32
0
 def get(self, id):
     user = users.get_current_user()
     if user:
         logout_url = users.create_logout_url('/')
     else:
         self.redirect(users.create_login_url(self.request.uri))
         return
     issue = Issue.get_by_id(int(id))
     choices = issue.choices
     self.response.out.write(
         template.render('templates/edit.html', locals()))
Esempio n. 33
0
 def get(self):
     user = users.get_current_user()
     if user:
         logout_url = users.create_logout_url('/')
     else:
         login_url = users.create_login_url('/')
     issues = Issue.all().order('creation_date').fetch(30)
     success_type = self.request.get('success')
     success_msg = None
     if success_type == 'vote':
         success_msg = 'Your vote was successfully cast!'
     if success_type == 'updated':
         success_msg = 'Your vote was successfully updated!'
     created_by = Issue.issues_created_by(member=user, limit=20)
     voted_on = Issue.issues_voted_on(member=user, limit=20)
     #recent_results = [issue for issue in voted_on if issue.has_results]
     recent_voted = [issue for issue in voted_on if issue.is_active()]
     recent_results = Issue.recent_results(limit=20)
     self.response.out.write(
         template.render('templates/overview.html', locals()))
Esempio n. 34
0
def add_issue_to_database(request):


    issue = request.session.get('issue', False)
    service = Service.objects.get(name=issue['service'])

    try:
        db_issue = Issue.objects.get(service=service, number=issue['number'], project=issue['project'])
        if db_issue.status == "paid":
            error = "I see that issue has been closed and paid already."
            messages.error(request, error)
            return False
    except:

        db_issue = Issue(
        service=service,
        number=issue['number'],
        project=issue['project'],
        user=issue.has_key('user') and issue['user'] or '',
        title=issue['title'],
        content=issue['content'][:350],
        status = issue['status'])
        filename, file = get_image_for_issue(service, issue)
        if filename:
            db_issue.image.save(filename, file)
        db_issue.save()
        if not settings.DEBUG:
            create_comment(db_issue)

    ends = issue['limit']
    hour_day = ends[-1]
    number = ends.rstrip(hour_day)
    if hour_day == "h":
        limit = datetime.timedelta(hours=int(number))
    else:
        limit = datetime.timedelta(days=int(number))
    bounty = Bounty(user=request.user, issue=db_issue, price=issue['bounty'], ends=datetime.datetime.now()+limit )
    bounty.save()
    alert_watchers_increase(db_issue, int(request.GET.get('bounty', 0)))
    del request.session['issue']
    return True
Esempio n. 35
0
def project_issue_new(slug):
	form = IssueForm()
	project = Project.query.filter_by(slug=slug).first_or_404()
	if form.validate_on_submit():
		issue = Issue(project, current_user, form.urgency.data,
						form.title.data, form.text.data)
		db.session.add(issue)
		db.session.commit()
		flash("Created issue <a href=\"%s\">#%s</a>" %
				(url_for('project_issue', slug=project.slug, iid=issue.id), issue.id))
		return redirect(url_for('project_issue_new', slug=slug))
	return render_template('issue_new.html', project=project, form=form)
Esempio n. 36
0
async def api_upload(*, name, crashDoc, appDetail):
    crash = await Crash.find(name)
    if crash:
        raise APIValueError('upload', '重复导入:%s' % name)

    jsonCrashDoc = json.loads(crashDoc)
    crashMap = jsonCrashDoc.get('crashMap', None)
    if not crashMap:
        raise APIValueError('upload', '找不到crashMap:%s' % name)

    version = crashMap.get('productVersion', None)
    if not version:
        raise APIValueError('upload', '找不到productVersion:%s' % name)

    content = crashMap.get('expMessage', None)
    if not content:
        raise APIValueError('upload', '找不到expMessage:%s' % name)

    content = content.replace('\\"', '\"')
    content = content.replace('\\n', '\n')
    content = content.replace('\\t', '\t')
    content_md5 = hashlib.md5(content.encode('utf-8')).hexdigest()
    length = content.find('\n')
    if length >= 0:
        title = content[:length]
    else:
        title = content[:]

    issues = await Issue.findAll(
        where=r"`content_md5` = '%s' AND `version` = '%s'" %
        (content_md5, version))
    if (len(issues) == 1):
        issue_id = issues[0].id
    elif (len(issues) == 0):
        issue_id = await Issue.findNumber('count(id)') + 1
        issue = Issue(id=issue_id,
                      title=title,
                      content=content,
                      content_md5=content_md5,
                      version=version,
                      user_id=None,
                      status=0)
        await issue.save()
    else:
        raise APIValueError('upload', '数据库存储错误%s' % name)

    crash = Crash(id=name,
                  issue_id=issue_id,
                  crash_doc=crashDoc,
                  app_detail=appDetail)
    await crash.save()

    return "success"
Esempio n. 37
0
    def post(self, slug):
        "Create an issue against this project"
        project = Project.all().filter('slug =', slug).fetch(1)[0]
        # get details from the form
        name = self.request.get("name")
        description = self.request.get("description")
        email = self.request.get("email")

        try:
            if Issue.all().filter('name =', name).filter('project =',
                                                         project).count() == 0:
                issue = Issue(
                    name=name,
                    description=description,
                    project=project,
                )
                if email:
                    issue.email = email
                issue.put()
                mail.send_mail(
                    sender="*****@*****.**",
                    to=project.user.email(),
                    subject="[GitBug] New bug added to %s" % project.name,
                    body=
                    """You requested to be emailed when a bug on GitBug was added:

Issue name: %s
Description: %s

Thanks for using GitBug <http://gitbug.appspot.com>. A very simple issue tracker.
    """ % (issue.name, issue.description))
                logging.info("issue created: %s in %s" % (name, project.name))
        except Exception, e:
            logging.error("error adding issue: %s" % e)
Esempio n. 38
0
def create(env, data, nxt):
    data.form = form = IssueForm(env)
    db = env.db
    if env.request.method == 'POST':
        if form.accept(env.request.POST):
            deadline = form.python_data['deadline']
            text = form.python_data['issue']
            title, body = text, ''
            chunks = text.split('\r\n\r\n', 1)
            if len(chunks) > 1:
                title, body = chunks
            issue = Issue(title=title, proj=data.project, 
                          author=env.user, deadline=deadline)
            issue.executor = form.python_data['executor']
            db.add(issue)
            if body:
                comment = Comment(issue=issue, raw=body, html=body, author=env.user)
                db.add(comment)
            db.commit()
            return env.redirect_to('issue', issue=issue.id)
    data.env = env
    return env.template.render_to_response('create-issue', data.as_dict())
Esempio n. 39
0
def add_issue_by_form():
    data = request.json
    video_url = (data["video_url"]).replace("watch?v=", "embed/")
    subcategory = Subcategory.query.filter(
        Subcategory.name == data["subcategory"]).first()
    new_issue = Issue(name=data["name"].title(),
                      video_url=video_url,
                      subcategory_id=subcategory.id,
                      num_hours=data["num_hours"],
                      difficulty=data["difficulty"])
    db.session.add(new_issue)
    db.session.commit()
    return data
def get_issue_events(show_progress):

    # Retrieve the list of all projects for which issue events should be fetched.
    github_projects = (
        GitHubProject
        .select(GitHubProject.owner, GitHubProject.repo)
        .group_by(GitHubProject.owner, GitHubProject.repo)
    )

    if show_progress:
        progress_bar = ProgressBar(maxval=github_projects.count(), widgets=[
            'Progress: ', Percentage(),
            ' ', Bar(marker=RotatingMarker()),
            ' ', ETA(),
            ' Processing project ', Counter(), ' / ' + str(github_projects.count()) + '.'
        ])
        progress_bar.start()

    # Create a new fetch index
    last_fetch_index = IssueEvent.select(fn.Max(IssueEvent.fetch_index)).scalar() or 0
    fetch_index = last_fetch_index + 1
    issue_fetch_index = Issue.select(fn.Max(Issue.fetch_index)).scalar() or 0

    for project_index, project in enumerate(github_projects, start=1):

        # Wrap a callback that will save fetched events
        save_events_callback = functools.partial(
            save_events,
            project=project,
            fetch_index=fetch_index,
            issue_fetch_index=issue_fetch_index,
        )

        # Fetch all events for all issues for the project
        github_get(
            start_url=(
                GITHUB_API_URL + '/repos/' + project.owner + '/' +
                project.repo + '/issues/events'
            ),
            results_callback=save_events_callback,
        )

        if show_progress:
            progress_bar.update(project_index)

    if show_progress:
        progress_bar.finish()

    # Make sure that all records from the batch inserter have been written out
    batch_inserter.flush()
Esempio n. 41
0
	def get(self,id):
		user = users.get_current_user()
		if user:
			logout_url = users.create_logout_url('/')
		else:
			self.redirect(users.create_login_url(self.request.uri))
			return
		
		issue = Issue.get_by_id(int(id))
		issue.update_status()
		
		vote = issue.vote_for_member(user)

		issueUrl = self.request.uri
		self.response.out.write(template.render('templates/Issue.html', locals()))
Esempio n. 42
0
def later_results(k):
    issue = Issue.get(k)
    issue.update_status()
    yes = 0
    no = 0
    for choice in issue.choices:
      if "Yes" in choice.name:
        yes = choice.vote_count()
      if "No" in choice.name:
        no = choice.vote_count()

    passed = "Not approved"
    if yes > no:
      passed = "Purchase Approved"

    notify_results(passed,yes,no,issue)
Esempio n. 43
0
	def post(self,id):
		user = users.get_current_user()
		if not user: #don't want someone who is not authenticated to be able to vote
			self.redirect(users.create_login_url(self.request.uri))
			return
		
		issue = Issue.get_by_id(int(id))
		#vote = issue.vote_for_member()
		
		new_choice = Choice.get_by_id(int(self.request.get('choice')))
		was_updated = issue.register_vote(new_choice)
		
		if was_updated:
			self.redirect('/?success=updated')
		else:
			self.redirect('/?success=vote')
Esempio n. 44
0
 def post(self,urlcode):
   user = users.get_current_user()
   if user:
     logout_url = users.create_logout_url('/')
   else:
     self.redirect(users.create_login_url(self.request.uri))
   
   issue = Issue.get_issue_by_urlcode(urlcode)
   #vote = issue.vote_for_member()
   
   new_choice = Choice.get_by_id(int(self.request.get('choice')))
   was_updated = issue.register_vote(new_choice)
   self.response.out.write(template.render('templates/issue.html', locals()))
   if was_updated:
     self.redirect('/redirect/%s?success=updated' % issue.urlcode)
   else:
     self.redirect('/redirect/%s?success=voted' % issue.urlcode)
Esempio n. 45
0
	def post(self,urlcode):
                user = users.get_current_user()
		if user:
			logout_url = users.create_logout_url('/')
		else:
			self.redirect(users.create_login_url(self.request.uri))
		
                issue = Issue.get_issue_by_urlcode(urlcode)
		#vote = issue.vote_for_member()
		
		new_choice = Choice.get_by_id(int(self.request.get('choice')))
		was_updated = issue.register_vote(new_choice)
		
		if was_updated:
			self.redirect('/?success=updated')
		else:
			self.redirect('/?success=vote')
Esempio n. 46
0
 def get(self, slug):
     # we want canonocal urls so redirect to add a trailing slash if needed
     if self.request.path[-1] != "/":
         self.redirect("%s/" % self.request.path, True)
         return
     
     user = users.get_current_user()
     output = None
     
     # if not logged in then use a cached version
     if not user:
         output = get_cache("project_%s" % slug)
     
     # if we don't have a cached version or are logged in
     if output is None:
         try:
             project = Project.all().filter('slug =', slug).fetch(1)[0]        
             issues = Issue.all().filter('project =', project)
             files = DatastoreFile.all().filter('project =', project)
         except IndexError:
             self.render_404()
             return 
             
         logging.info("Files in this project: %d" % files.count())
         # check to see if we have admin rights over this project
         if project.user == user or users.is_current_user_admin():
             owner = True
         else:
             owner = False            
         
         context = {
             'project': project,
             'issues': issues,
             'owner': owner,
             'files': files,
         }
         output = self.render("project.html", context)
     if not user:
         # only save a cached version if we're not logged in
         # so as to avoid revelaving user details
         memcache.add("project_%s" % slug, output, 3600)
     self.response.out.write(output)
Esempio n. 47
0
 def post(self, project_slug, issue_slug):
     
     # if we don't have a user then throw
     # an unauthorised error
     user = users.get_current_user()
     if not user:
         self.render_403()
         return
     
     issue = Issue.all().filter('internal_url =', "/%s/%s/" % (project_slug, issue_slug)).fetch(1)[0]
     
     user = users.get_current_user()
     
     if issue.project.user == user:
     
         try:
             name = self.request.get("name")
             description = self.request.get("description")
             email = self.request.get("email")
             fixed = self.request.get("fixed")
             priority = self.request.get("priority")
             fixed_description = self.request.get("fixed_description")
     
             issue.name = name
             issue.description = description
             issue.priority = priority
             if email:
                 issue.email = email
             else:
                 issue.email = None
             issue.fixed = bool(fixed)
             if fixed:
                 issue.fixed_description = fixed_description
             else:
                 issue.fixed_description = None
 
             issue.put()
             logging.info("issue edited: %s in %s" % (issue.name, issue.project.name))
             
         except Exception, e:
             logging.info("error editing issue: %s" % e)
Esempio n. 48
0
  def post(self,urlcode):
    user = users.get_current_user()
    if user:
      logout_url = users.create_logout_url('/')
    else:
      self.redirect(users.create_login_url(self.request.uri))
      return
    issue = Issue.get_issue_by_urlcode(urlcode)

    if self.request.get('extend'):#if extending vote
      choices = issue.choices
      extend_amount = int(self.request.get('extend_amount')) * int(self.request.get('extend_multiplier'))
      issue.extend_duration(extend_amount)
      self.redirect('/redirect/%s?success=extended' % issue.urlcode)
      
    else:#otherwise we are saving changes
      if issue.vote_count():
        raise Exception('Unable to change issue text once votes have been cast')

      duration_amount = int(self.request.get('duration_amount'))
      multiplier = int(self.request.get('duration_multiplier'))
      issue.duration = duration_amount * multiplier
      if self.request.get('title'):
        issue.title = cgi.escape(self.request.get('title'))
      if self.request.get('description'):
        issue.description = cgi.escape(self.request.get('description'))
      if self.request.get('option1') and self.request.get('option2'):
        choices = issue.choices
        db.delete(choices)
        issue.add_choice(cgi.escape(self.request.get('option1')))
        issue.add_choice(cgi.escape(self.request.get('option2')))
        if self.request.get('option3'):
          issue.add_choice(cgi.escape(self.request.get('option3')))
        if self.request.get('option4'):
          issue.add_choice(cgi.escape(self.request.get('option4')))
        if self.request.get('option5'):
          issue.add_choice(cgi.escape(self.request.get('option5')))
      issue.put()
      #choices = issue.choices
      self.redirect('/redirect/%s' % issue.urlcode)
Esempio n. 49
0
def reconcile_db_with_gh(*args, **kwargs):
    ghc = GitHubConnector()
    issues = ghc.get_all_issues()
    repos = ghc.get_all_repos()

    for repo in repos:
        r = Repo(github_id=repo.id, name=repo.name)
        r.save()

    for issue in issues:
        i = Issue(github_id=issue.id)
        i.title = issue.title
        i.number = issue.number
        i.repo = Repo.objects.get(name=issue.repository[1])
        i.save()

    print "Not only did your task run successfully, but you're damned good looking too."
Esempio n. 50
0
	def post(self,id):
		user = users.get_current_user()
		if user:
			logout_url = users.create_logout_url('/')
		else:
			self.redirect(users.create_login_url(self.request.uri))
			return
		issue = Issue.get_by_id(int(id))
		
		
		if self.request.get('extend'):#if extending vote
			choices = issue.choices
			extend_amount = int(self.request.get('extend_amount')) * int(self.request.get('extend_multiplier'))
			issue.extend_duration(extend_amount)
			self.response.out.write(template.render('templates/edit.html', locals()))
			
		else:#otherwise we are saving changes
			duration_amount = int(self.request.get('duration_amount'))
			multiplier = int(self.request.get('duration_multiplier'))
			issue.duration = duration_amount * multiplier
			if self.request.get('title'):
				issue.title = cgi.escape(self.request.get('title'))
			if self.request.get('description'):
				issue.description = cgi.escape(self.request.get('description'))
			if self.request.get('option1') and self.request.get('option2'):
				choices = issue.choices
				db.delete(choices)
				issue.add_choice(cgi.escape(self.request.get('option1')))
				issue.add_choice(cgi.escape(self.request.get('option2')))
				if self.request.get('option3'):
					issue.add_choice(cgi.escape(self.request.get('option3')))
				if self.request.get('option4'):
					issue.add_choice(cgi.escape(self.request.get('option4')))
				if self.request.get('option5'):
					issue.add_choice(cgi.escape(self.request.get('option5')))
			issue.put()
			#choices = issue.choices
			self.redirect('/issue/%s' % (id))
Esempio n. 51
0
    def test_m2m_and_m2o(self):
        r = User.objects.create(username="******")
        g = User.objects.create(username="******")

        i1 = Issue(num=1)
        i1.client = r
        i1.save()

        i2 = Issue(num=2)
        i2.client = r
        i2.save()
        i2.cc.add(r)

        i3 = Issue(num=3)
        i3.client = g
        i3.save()
        i3.cc.add(r)

        self.assertQuerysetEqual(
            Issue.objects.filter(client=r.id), [
                1,
                2,
            ],
            lambda i: i.num
        )
        self.assertQuerysetEqual(
            Issue.objects.filter(client=g.id), [
                3,
            ],
            lambda i: i.num
        )
        self.assertQuerysetEqual(
            Issue.objects.filter(cc__id__exact=g.id), []
        )
        self.assertQuerysetEqual(
            Issue.objects.filter(cc__id__exact=r.id), [
                2,
                3,
            ],
            lambda i: i.num
        )

        # These queries combine results from the m2m and the m2o relationships.
        # They're three ways of saying the same thing.
        self.assertQuerysetEqual(
            Issue.objects.filter(Q(cc__id__exact = r.id) | Q(client=r.id)), [
                1,
                2,
                3,
            ],
            lambda i: i.num
        )
        self.assertQuerysetEqual(
            Issue.objects.filter(cc__id__exact=r.id) | Issue.objects.filter(client=r.id), [
                1,
                2,
                3,
            ],
            lambda i: i.num
        )
        self.assertQuerysetEqual(
            Issue.objects.filter(Q(client=r.id) | Q(cc__id__exact=r.id)), [
                1,
                2,
                3,
            ],
            lambda i: i.num
        )