def _do_event(self, event): username = event['username'] reponame = event['reponame'] remote_git_url = event['remote_git_url'] local_user = GsuserManager.get_user_by_name(username) local_repo = RepoManager.get_repo_by_name(username, reponame) if local_user is None or local_repo is None or local_repo.status == 0: return local_repo_path = local_repo.get_abs_repopath() if os.path.exists(local_repo_path): return args = ['/bin/bash', '/opt/bin/git-import-remote-repo.sh'] + [local_repo_path, remote_git_url] try: popen = Popen(args, stdout=PIPE, shell=False, close_fds=True) output = popen.communicate()[0].strip() returncode = popen.returncode if returncode == 0: RepoManager.check_export_ok_file(local_repo) diff_size = long(output) RepoManager.update_user_repo_quote(local_user, local_repo, diff_size) local_repo.status = 0 local_repo.save() else: local_repo.status = 500 local_repo.save() except Exception, e: local_repo.status = 500 local_repo.save() logger.exception(e)
def do_event(event): from_repo_id = event['from_repo_id'] to_repo_id = event['to_repo_id'] from_repo = RepoManager.get_repo_by_id(from_repo_id) to_repo = RepoManager.get_repo_by_id(to_repo_id) copy_from_bare = False if to_repo is None: return if from_repo is None: copy_from_bare = True from_repo_path = GIT_BARE_REPO_PATH if not copy_from_bare: from_repo_path = from_repo.get_abs_repopath() to_repo_path = to_repo.get_abs_repopath() if not os.path.exists(from_repo_path): logger.info('from_repo_path: %s is not exists, clone failed' % from_repo_path) return if chdir(from_repo_path) is False: logger.info('chdir to from_repo_path: %s is False, clone failed' % from_repo_path) return if os.path.exists(to_repo_path): logger.info('to_repo_path: %s already exists, clone failed' % to_repo_path) return args = ['/usr/bin/git', 'gc'] popen = Popen(args, stdout=PIPE, shell=False, close_fds=True) result = popen.communicate()[0].strip() to_repo_dirname = os.path.dirname(to_repo_path) if not os.path.exists(to_repo_dirname): os.makedirs(to_repo_dirname) shutil.copytree(from_repo_path, to_repo_path) update_repo_status(from_repo, to_repo)
def _do_event(self, event): username = event['username'] reponame = event['reponame'] remote_git_url = event['remote_git_url'] local_user = GsuserManager.get_user_by_name(username) local_repo = RepoManager.get_repo_by_name(username, reponame) if local_user is None or local_repo is None or local_repo.status == 0: return local_repo_path = local_repo.get_abs_repopath() if os.path.exists(local_repo_path): return args = ['/bin/bash', '/opt/bin/git-import-remote-repo.sh' ] + [local_repo_path, remote_git_url] try: popen = Popen(args, stdout=PIPE, shell=False, close_fds=True) output = popen.communicate()[0].strip() returncode = popen.returncode if returncode == 0: RepoManager.check_export_ok_file(local_repo) diff_size = long(output) RepoManager.update_user_repo_quote(local_user, local_repo, diff_size) local_repo.status = 0 local_repo.save() else: local_repo.status = 500 local_repo.save() except Exception, e: local_repo.status = 500 local_repo.save() logger.exception(e)
def do_event(event): from_repo_id = event['from_repo_id'] to_repo_id = event['to_repo_id'] from_repo = RepoManager.get_repo_by_id(from_repo_id) to_repo = RepoManager.get_repo_by_id(to_repo_id) copy_from_bare = False if to_repo is None: return if from_repo is None: copy_from_bare = True from_repo_path = GIT_BARE_REPO_PATH if not copy_from_bare: from_repo_path = from_repo.get_abs_repopath() to_repo_path = to_repo.get_abs_repopath() if not os.path.exists(from_repo_path): logger.info('from_repo_path: %s is not exists, clone failed' % from_repo_path) return if chdir(from_repo_path) is False: logger.info('chdir to from_repo_path: %s is False, clone failed' % from_repo_path) return if os.path.exists(to_repo_path): logger.info('to_repo_path: %s already exists, clone failed' % to_repo_path) return args = ['/usr/bin/git', 'gc'] popen = Popen(args, stdout=PIPE, shell=False, close_fds=True) result = popen.communicate()[0].strip() to_repo_dirname = os.path.dirname(to_repo_path) if not os.path.exists(to_repo_dirname): os.makedirs(to_repo_dirname) shutil.copytree(from_repo_path, to_repo_path) update_repo_status(from_repo, to_repo)
def update(request, user_name, repo_name, issue_id, attr): repo = RepoManager.get_repo_by_name(user_name, repo_name) if repo is None: raise Http404 issue = IssueManager.get_issue(repo.id, issue_id) if issue is None: return _json_failed() has_issue_modify_right = _has_issue_modify_right(request, issue, repo) if not has_issue_modify_right: return _json_failed() orgi_issue = copy.copy(issue) (key, value) = attr.split('___', 1) if key == 'assigned': user = GsuserManager.get_user_by_name(value) if user is None: return _json_failed() repoMember = RepoManager.get_repo_member(repo.id, user.id) if repoMember is None: return _json_failed() issue.assigned = repoMember.user_id issue.save() FeedManager.notif_issue_status(request.user, issue, ISSUE_STATUS.ASSIGNED) FeedManager.feed_issue_change(request.user, repo, orgi_issue, issue.id) return _json_ok() value = int(value) if key == 'tracker': issue.tracker = value elif key == 'status': issue.status = value elif key == 'priority': issue.priority = value issue.save() FeedManager.feed_issue_change(request.user, repo, orgi_issue, issue.id) return _json_ok()
def _fillwith_notifMessages(self, notifMessages): repo_ids = [x.repo_id for x in notifMessages] userprofile_ids = [x.user_id for x in notifMessages] repo_dict = dict( (x.id, x) for x in RepoManager.list_repo_by_ids(repo_ids)) userprofile_dict = dict( (x.id, x) for x in GsuserManager.list_userprofile_by_ids(userprofile_ids)) for notifMessage in notifMessages: if notifMessage.repo_id in repo_dict: notifMessage.repo = repo_dict[notifMessage.repo_id] if notifMessage.from_user_id in userprofile_dict: notifMessage.from_userprofile = userprofile_dict[ notifMessage.from_user_id] if notifMessage.is_at_commit(): commitHistory = RepoManager.get_commit_by_id( notifMessage.relative_id) notifMessage.relative_obj = commitHistory elif notifMessage.is_at_issue() or notifMessage.is_issue_cate(): issue = IssueManager.get_issue_by_id(notifMessage.relative_id) notifMessage.relative_obj = issue elif notifMessage.is_at_merge( ) or notifMessage.is_pull_request_cate(): pullRequest = RepoManager.get_pullRequest_by_id( notifMessage.relative_id) notifMessage.relative_obj = pullRequest elif notifMessage.is_at_issue_comment(): issue_comment = IssueManager.get_issue_comment( notifMessage.relative_id) notifMessage.relative_obj = issue_comment return notifMessages
def update(request, user_name, repo_name, issue_id, attr): repo = RepoManager.get_repo_by_name(user_name, repo_name) if repo is None: raise Http404 issue = IssueManager.get_issue(repo.id, issue_id) if issue is None: return _json_failed() has_issue_modify_right = _has_issue_modify_right(request, issue, repo) if not has_issue_modify_right: return _json_failed() orgi_issue = copy.copy(issue) (key, value) = attr.split('___', 1) if key == 'assigned': user = GsuserManager.get_user_by_name(value) if user is None: return _json_failed() repoMember = RepoManager.get_repo_member(repo.id, user.id) if repoMember is None: return _json_failed() issue.assigned = repoMember.user_id issue.save() FeedManager.notif_issue_status(request.user, issue, ISSUE_STATUS.ASSIGNED) FeedManager.feed_issue_change(request.user, repo, orgi_issue, issue.id) return _json_ok() value = int(value) if key == 'tracker': issue.tracker = value elif key == 'status': issue.status = value elif key == 'priority': issue.priority = value issue.save() FeedManager.feed_issue_change(request.user, repo, orgi_issue, issue.id) return _json_ok()
def update_quote(user, userprofile, repo, repopath, parameters): args = ['/opt/bin/diff-tree-blob-size.sh', repopath] args.extend(parameters) popen = Popen(args, stdout=PIPE, shell=False, close_fds=True) result = popen.communicate()[0].strip() diff_size = 0 if popen.returncode == 0: if result.startswith('+') or result.startswith('-'): diff_size = int(result) else: diff_size = int(result) - repo.used_quote RepoManager.update_user_repo_quote(userprofile, repo, diff_size)
def update_quote(user, userprofile, repo, repopath, parameters): args = ['/opt/bin/diff-tree-blob-size.sh', repopath] args.extend(parameters) popen = Popen(args, stdout=PIPE, shell=False, close_fds=True) result = popen.communicate()[0].strip() diff_size = 0 if popen.returncode == 0: if result.startswith('+') or result.startswith('-'): diff_size = int(result) else: diff_size = int(result) - repo.used_quote RepoManager.update_user_repo_quote(userprofile, repo, diff_size)
def start(): users = User.objects.all() for user in users: userprofile = GsuserManager.get_userprofile_by_id(user.id) if not userprofile: continue if not re.match('[a-zA-Z0-9-_]+', user.username): continue userstats = {} userstats['username'] = user.username userstats['email'] = user.email userstats['date_joined'] = user.date_joined.strftime('%Y/%m/%d %H:%M:%S') userstats['last_login'] = user.last_login.strftime('%Y/%m/%d %H:%M:%S') repos = RepoManager.list_repo_by_userId(user.id, 0, 1000) userstats['repo_total_count'] = len(repos) first_time_commit = None; last_time_commit = None; commits = 0; forks = 0; repo_private_count = 0 for repo in repos: commits = commits + repo.commit if repo.auth_type != 0: repo_private_count = repo_private_count + 1 if repo.fork_repo_id != 0: forks = forks + 1 commitHistorys = CommitHistory.objects.filter(visibly=0).filter(repo_id=repo.id).order_by('create_time')[0:1] if len(commitHistorys) > 0: first_time_commitHistory = commitHistorys[0] if first_time_commit is None or first_time_commit > first_time_commitHistory.create_time: first_time_commit = first_time_commitHistory.create_time commitHistorys = CommitHistory.objects.filter(visibly=0).filter(repo_id=repo.id).order_by('-create_time')[0:1] if len(commitHistorys) > 0: last_time_commitHistory = commitHistorys[0] if last_time_commit is None or last_time_commit < last_time_commitHistory.create_time: last_time_commit = last_time_commitHistory.create_time userstats['repo_private_count'] = repo_private_count if first_time_commit: userstats['first_time_commit'] = first_time_commit.strftime('%Y/%m/%d %H:%M:%S') else: userstats['first_time_commit'] = '' if last_time_commit: userstats['last_time_commit'] = last_time_commit.strftime('%Y/%m/%d %H:%M:%S') else: userstats['last_time_commit'] = '' userstats['commits'] = commits userstats['watch_repo'] = userprofile.watchrepo userstats['fork_repo'] = forks pullrequests = RepoManager.list_pullRequest_by_pullUserId(user.id) userstats['pullrequests'] = len(pullrequests) issues = Issue.objects.filter(visibly=0).filter(creator_user_id=user.id)[0:1000] userstats['issues'] = len(issues) userpubkeys = KeyauthManager.list_userpubkey_by_userId(user.id) userstats['ssh_key'] = len(userpubkeys) csv_items = [userstats['username'], userstats['email'], userstats['date_joined'], userstats['last_login'], str(int(userstats['repo_total_count'])), str(int(userstats['repo_private_count'])), userstats['first_time_commit'], userstats['last_time_commit'], str(int(userstats['commits'])), str(int(userstats['watch_repo'])), str(int(userstats['fork_repo'])), str(int(userstats['pullrequests'])), str(int(userstats['issues'])), str(int(userstats['ssh_key']))] print ','.join(csv_items)
def user(request, user_name): title = u'%s / 概括' % user_name gsuser = GsuserManager.get_user_by_name(user_name) if gsuser is None: raise Http404 gsuserprofile = GsuserManager.get_userprofile_by_id(gsuser.id) if gsuserprofile.is_team_account == 1 and TeamManager.is_teamMember( gsuser.id, request.user.id): return HttpResponseRedirect('/%s/-/dashboard/' % user_name) recommendsForm = RecommendsForm() repos = [] if gsuser.id == request.user.id: repos = RepoManager.list_repo_by_userId(gsuser.id, 0, 100) else: repos = RepoManager.list_unprivate_repo_by_userId(gsuser.id, 0, 100) now = datetime.now() last30days = timeutils.getlast30days(now) last30days_commit = get_last30days_commit(gsuser) feedAction = FeedAction() raw_watch_repos = feedAction.get_watch_repos(gsuser.id, 0, 10) watch_repo_ids = [int(x[0]) for x in raw_watch_repos] watch_repos_map = RepoManager.merge_repo_map(watch_repo_ids) watch_repos = [ watch_repos_map[x] for x in watch_repo_ids if x in watch_repos_map ] pri_user_feeds = feedAction.get_pri_user_feeds(gsuser.id, 0, 10) pub_user_feeds = feedAction.get_pub_user_feeds(gsuser.id, 0, 10) feeds_as_json = get_feeds_as_json(request, pri_user_feeds, pub_user_feeds) star_repos = RepoManager.list_star_repo(gsuser.id, 0, 20) response_dictionary = { 'mainnav': 'user', 'title': title, 'recommendsForm': recommendsForm, 'repos': repos, 'watch_repos': watch_repos, 'star_repos': star_repos, 'last30days': last30days, 'last30days_commit': last30days_commit, 'feeds_as_json': feeds_as_json } response_dictionary.update( get_common_user_dict(request, gsuser, gsuserprofile)) return render_to_response('user/user.html', response_dictionary, context_instance=RequestContext(request))
def http_auth(request): try: unauthorized_httpResponse = HttpResponse(status=401) unauthorized_httpResponse[ 'WWW-Authenticate'] = 'Basic realm="%s"' % 'Restricted' if not request.META.has_key('HTTP_X_SET_REQUESTURI'): return unauthorized_httpResponse orgi_request_uri = request.META['HTTP_X_SET_REQUESTURI'].strip() (desc_username, desc_reponame, action) = _get_desc_name(orgi_request_uri) if desc_username == '' or desc_reponame == '': return unauthorized_httpResponse suffix = '.git' if desc_reponame.endswith(suffix): desc_reponame = desc_reponame[0:len(desc_reponame) - len(suffix)] repo = RepoManager.get_repo_by_name(desc_username, desc_reponame) if repo is None: return unauthorized_httpResponse # if deploy key if 'git-receive-pack' not in orgi_request_uri: deploy_key = None username, password = _http_authenticate_name_password(request) if username is not None: deploy_key = username if deploy_key is not None and deploy_key != '' and repo.deploy_url == deploy_key: return HttpResponse(status=200) if repo.auth_type == 0: # if orgi_request_uri.endswith('?service=git-receive-pack') or action == 'git-receive-pack': if 'git-receive-pack' in orgi_request_uri: user = _http_authenticate_user(request) if not RepoManager.is_allowed_access_repo( repo, user, REPO_PERMISSION.WRITE): return unauthorized_httpResponse return HttpResponse(status=200) else: user = _http_authenticate_user(request) if 'git-receive-pack' in orgi_request_uri: if RepoManager.is_allowed_access_repo(repo, user, REPO_PERMISSION.WRITE): return HttpResponse(status=200) else: if RepoManager.is_allowed_access_repo( repo, user, REPO_PERMISSION.READ_ONLY): return HttpResponse(status=200) except Exception, e: print e
def destroy_confirm(request, username): (teamUser, teamUserprofile) = _get_team_user_userprofile(request, username) teamMember = TeamManager.get_teamMember_by_teamUserId_userId(teamUser.id, request.user.id) teamRepos = RepoManager.list_repo_by_userId(teamUser.id, 0, 1000) for teamRepo in teamRepos: RepoManager.delete_repo(teamUser, teamUserprofile, teamRepo) teamMembers = TeamManager.list_teamMember_by_teamUserId(teamUser.id) for teamMember in teamMembers: teamMember.visibly = 1 teamMember.save() teamUser.delete() teamUserprofile.visibly = 1 teamUserprofile.save() return json_success(u'已经删除了团队帐号')
def repo(request, username): (teamUser, teamUserprofile) = _get_team_user_userprofile(request, username) current = 'repo'; title = u'%s / 仓库列表' % (teamUser.username) teamMember = TeamManager.get_teamMember_by_teamUserId_userId(teamUser.id, request.user.id) repos = [] # is team member if teamMember: repos = RepoManager.list_repo_by_userId(teamUser.id, 0, 1000) else: repos = RepoManager.list_unprivate_repo_by_userId(teamUser.id, 0, 1000) response_dictionary = {'current': current, 'title': title, 'repos': repos} response_dictionary.update(_get_common_team_dict(request, teamUser, teamUserprofile)) return render_to_response('team/repo.html', response_dictionary, context_instance=RequestContext(request))
def destroy_confirm(request, username): (teamUser, teamUserprofile) = _get_team_user_userprofile(request, username) teamMember = TeamManager.get_teamMember_by_teamUserId_userId( teamUser.id, request.user.id) teamRepos = RepoManager.list_repo_by_userId(teamUser.id, 0, 1000) for teamRepo in teamRepos: RepoManager.delete_repo(teamUser, teamUserprofile, teamRepo) teamMembers = TeamManager.list_teamMember_by_teamUserId(teamUser.id) for teamMember in teamMembers: teamMember.visibly = 1 teamMember.save() teamUser.delete() teamUserprofile.visibly = 1 teamUserprofile.save() return json_success(u'已经删除了团队帐号')
def do_issue(request): action = request.POST.get('action', '') comment = request.POST.get('comment', '') repo_id = request.POST.get('repo_id', '') issue_id = request.POST.get('issue_id', '') if action == '' or repo_id == '' or issue_id == '': return _json_failed() repo = RepoManager.get_repo_by_id(int(repo_id)) issue = IssueManager.get_issue(int(repo_id), int(issue_id)) if repo is None or issue is None: return _json_failed() if issue.assigned != request.user.id and repo.user_id != request.user.id: return _json_failed() orgi_issue = copy.copy(issue) if action == 'fixed': issue.status = 4 elif action == 'close': issue.status = 5 elif action == 'reject': issue.status = 6 if comment != '': issueComment = IssueComment() issueComment.issue_id = issue.id issueComment.user_id = request.user.id issueComment.content = comment issueComment.save() issue.comment_count = issue.comment_count + 1 issue.save() FeedManager.feed_issue_change(request.user, repo, orgi_issue, issue.id) return _json_ok()
def edit(request, user_name, repo_name, issue_id): refs = 'master'; path = '.'; current = 'issues'; title = u'%s / %s / 编辑问题' % (user_name, repo_name) repo = RepoManager.get_repo_by_name(user_name, repo_name) if repo is None: raise Http404 issue = IssueManager.get_issue(repo.id, issue_id) has_issue_modify = _has_issue_modify_right(request, issue, repo) if issue is None or not has_issue_modify: raise Http404 orgi_issue = copy.copy(issue) issueForm = IssueForm(instance = issue) issueForm.fill_assigned(repo) error = u'' if request.method == 'POST': issueForm = IssueForm(request.POST, instance = issue) issueForm.fill_assigned(repo) if issueForm.is_valid(): newIssue = issueForm.save() nid = newIssue.id FeedManager.notif_issue_at(request.user.id, nid, issueForm.cleaned_data['subject'] + ' ' + issueForm.cleaned_data['content']) FeedManager.notif_issue_status(request.user, newIssue, ISSUE_STATUS.ASSIGNED) FeedManager.feed_issue_change(request.user, repo, orgi_issue, nid) return HttpResponseRedirect('/%s/%s/issues/%s/' % (user_name, repo_name, nid)) else: error = u'issue 内容不能为空' response_dictionary = {'mainnav': 'repo', 'current': current, 'title': title, 'path': path, 'issueForm': issueForm, 'error': error, 'issue_id': issue_id} response_dictionary.update(ISSUE_ATTRS) response_dictionary.update(get_common_repo_dict(request, repo, user_name, repo_name, refs)) return render_to_response('repo/issue_edit.html', response_dictionary, context_instance=RequestContext(request))
def do_issue(request): action = request.POST.get('action', '') comment = request.POST.get('comment', '') repo_id = request.POST.get('repo_id', '') issue_id = request.POST.get('issue_id', '') if action == '' or repo_id == '' or issue_id == '': return _json_failed() repo = RepoManager.get_repo_by_id(int(repo_id)) issue = IssueManager.get_issue(int(repo_id), int(issue_id)) if repo is None or issue is None: return _json_failed() if issue.assigned != request.user.id and repo.user_id != request.user.id: return _json_failed() orgi_issue = copy.copy(issue) if action == 'fixed': issue.status = 4 elif action == 'close': issue.status = 5 elif action == 'reject': issue.status = 6 if comment != '': issueComment = IssueComment() issueComment.issue_id = issue.id issueComment.user_id = request.user.id issueComment.content = comment issueComment.save() issue.comment_count = issue.comment_count + 1 issue.save() FeedManager.feed_issue_change(request.user, repo, orgi_issue, issue.id) return _json_ok()
def do_event(event): etype = event['type'] if etype == 0: abspath = event['abspath'].strip() (username, reponame) = get_username_reponame(abspath) if username == '' or reponame == '': return (user, userprofile, repo, abs_repo_path) = get_attrs(username, reponame) if user is None or userprofile is None or repo is None or abs_repo_path is None or not os.path.exists( abs_repo_path): return gitHandler = GitHandler() webHookURLs = RepoManager.list_webHookURL_by_repoId(repo.id) rev_ref_arr = event['revrefarr'] for rev_ref in rev_ref_arr: if len(rev_ref) < 3: continue oldrev = rev_ref[0] newrev = rev_ref[1] refname = rev_ref[2] for webHookURL in webHookURLs: if webHookURL.status != 0: continue handle_push_webHookURL(gitHandler, abs_repo_path, user, repo, oldrev, newrev, refname, webHookURL)
def list_permissionItem_by_setId(self, set_id, repo_id): if set_id == 0: return [] permissionItems = query(PermissionItem, set_id, 'permissionitem_l_setId', [set_id]) if len(permissionItems) == 0: return [] from gitshell.repo.models import Repo, RepoManager userprofile_dict = dict((x.id, x)for x in RepoManager.list_repo_team_memberUser(repo_id)) teamGroup_dict = {} for x in permissionItems: if x.group_id in teamGroup_dict: continue teamGroup = self.get_teamGroup_by_id(x.group_id) if not teamGroup: continue teamGroup_dict[teamGroup.id] = teamGroup filtered_permissionItems = [] for permissionItem in permissionItems: if permissionItem.user_id not in userprofile_dict and permissionItem.group_id not in teamGroup_dict: permissionItem.visibly = 1 permissionItem.save() continue if permissionItem.user_id in userprofile_dict: permissionItem.userprofile = userprofile_dict[permissionItem.user_id] if permissionItem.group_id in teamGroup_dict: permissionItem.group = teamGroup_dict[permissionItem.group_id] if permissionItem.permission in PERMISSION.VIEW: permissionItem.permission_view = PERMISSION.VIEW[permissionItem.permission] filtered_permissionItems.append(permissionItem) return filtered_permissionItems
def watch_repo(request, user_name): title = u'%s / 关注的仓库' % user_name gsuser = GsuserManager.get_user_by_name(user_name) if gsuser is None: raise Http404 gsuserprofile = GsuserManager.get_userprofile_by_id(gsuser.id) feedAction = FeedAction() raw_watch_repos = feedAction.get_watch_repos(gsuser.id, 0, 100) watch_repo_ids = [int(x[0]) for x in raw_watch_repos] watch_repos_map = RepoManager.merge_repo_map_ignore_visibly(watch_repo_ids) watch_repos = [ watch_repos_map[x] for x in watch_repo_ids if x in watch_repos_map ] response_dictionary = { 'mainnav': 'user', 'title': title, 'watch_repos': watch_repos } # fixed on detect if len(watch_repos) != gsuserprofile.watchrepo: gsuserprofile.watchrepo = len(watch_repos) gsuserprofile.save() response_dictionary.update( get_common_user_dict(request, gsuser, gsuserprofile)) return render_to_response('user/watch_repo.html', response_dictionary, context_instance=RequestContext(request))
def get_common_user_dict(request, gsuser, gsuserprofile): feedAction = FeedAction() raw_watch_users = feedAction.get_watch_users(gsuser.id, 0, 10) raw_bewatch_users = feedAction.get_bewatch_users(gsuser.id, 0, 10) watch_user_ids = [int(x[0]) for x in raw_watch_users] bewatch_user_ids = [int(x[0]) for x in raw_bewatch_users] watch_users_map = GsuserManager.map_users(watch_user_ids) bewatch_users_map = GsuserManager.map_users(bewatch_user_ids) watch_users = [ watch_users_map[x] for x in watch_user_ids if x in watch_users_map ] bewatch_users = [ bewatch_users_map[x] for x in bewatch_user_ids if x in bewatch_users_map ] raw_recommends = GsuserManager.list_recommend_by_userid(gsuser.id, 0, 20) recommends = __conver_to_recommends_vo(raw_recommends) is_watched_user = False if request.user.is_authenticated(): is_watched_user = RepoManager.is_watched_user(request.user.id, gsuser.id) return { 'gsuser': gsuser, 'gsuserprofile': gsuserprofile, 'watch_users': watch_users, 'bewatch_users': bewatch_users, 'recommends': recommends, 'is_watched_user': is_watched_user, 'show_common': True }
def change(request): thirdpartyUser = GsuserManager.get_thirdpartyUser_by_id(request.user.id) user = None is_user_exist = True is_exist_repo = False username = request.POST.get('username') if username is not None and re.match( "^[a-zA-Z0-9_-]+$", username ) and username != request.user.username and username not in MAIN_NAVS and not username.startswith( '-'): repo_count = RepoManager.count_repo_by_userId(request.user.id) if repo_count > 0: return json_httpResponse({'is_exist_repo': True}) user = GsuserManager.get_user_by_name(username) if user is None: request.user.username = username request.userprofile.username = username request.user.save() request.userprofile.save() for repo in RepoManager.list_repo_by_userId( request.user.id, 0, 100): repo.username = username repo.save() is_user_exist = False goto = '' email = request.POST.get('email') if email is not None and email_re.match(email): user = GsuserManager.get_user_by_email(email) if user is None: Mailer().send_change_email(request.user, email) email_suffix = email.split('@')[-1] if email_suffix in COMMON_EMAIL_DOMAIN: goto = COMMON_EMAIL_DOMAIN[email_suffix] is_user_exist = False if thirdpartyUser is not None: thirdpartyUser.init = 1 thirdpartyUser.save() if username == request.user.username: is_user_exist = False response_dictionary = { 'is_exist_repo': is_exist_repo, 'is_user_exist': is_user_exist, 'goto': goto, 'new_username': username, 'new_email': email } return json_httpResponse(response_dictionary)
def _convert_to_commit_dict(request, commit_ids): commit_dict = {} allowed_view_access_repoId_set = Set() commits = RepoManager.list_commits_by_ids(commit_ids) repos = RepoManager.list_repo_by_ids( list(Set([x.repo_id for x in commits]))) for repo in repos: if repo.auth_type == 2: if not request.user.is_authenticated( ) or not RepoManager.is_allowed_view_access_repo( repo, request.user): continue allowed_view_access_repoId_set.add(repo.id) for commit in commits: if commit.repo_id in allowed_view_access_repoId_set: commit_dict[commit.id] = commit return commit_dict
def _fillwith_pull_event(request, feeds): for feed in feeds: if not feed.is_pull_event(): continue pullRequest = RepoManager.get_pullRequest_by_id(feed.relative_id) if pullRequest is None or pullRequest.source_repo is None or pullRequest.desc_repo is None: continue feed.relative_obj = pullRequest
def _fillwith_push_revref(request, feeds): revref_dict = {} for feed in feeds: if not feed.is_push_revref(): continue push_revref = RepoManager.get_pushrevref_by_id(feed.relative_id) if not push_revref: continue repo = RepoManager.get_repo_by_id(push_revref.repo_id) if repo and repo.auth_type == 2: if not request.user.is_authenticated( ) or not RepoManager.is_allowed_view_access_repo( repo, request.user): continue push_revref.commits = RepoManager.list_commit_by_repoId_pushrevrefId( push_revref.repo_id, push_revref.id, 0, 10) feed.relative_obj = push_revref
def wrap(request, *args, **kwargs): if len(args) >= 2: user_name = args[0]; repo_name = args[1] repo = RepoManager.get_repo_by_name(user_name, repo_name) if repo is None: return error_with_reason(request, 'repo_not_found') if repo.auth_type != 0 and not request.user.is_authenticated(): return HttpResponseRedirect('/login/?next=' + urlquote(request.path)) is_allowed_access_repo = RepoManager.is_allowed_access_repo(repo, request.user, REPO_PERMISSION.READ_ONLY) if not is_allowed_access_repo: if request.method == 'POST': return json_failed(403, u'没有管理权限') return error_with_reason(request, 'repo_permission_denied') if request.user.is_authenticated(): feedAction = FeedAction() feedAction.add_recently_view_repo_now(request.user.id, repo.id) return function(request, *args, **kwargs)
def http_auth(request): try: unauthorized_httpResponse = HttpResponse(status=401) unauthorized_httpResponse['WWW-Authenticate'] = 'Basic realm="%s"' % 'Restricted' if not request.META.has_key('HTTP_X_SET_REQUESTURI'): return unauthorized_httpResponse orgi_request_uri = request.META['HTTP_X_SET_REQUESTURI'].strip() (desc_username, desc_reponame, action) = _get_desc_name(orgi_request_uri) if desc_username == '' or desc_reponame == '': return unauthorized_httpResponse suffix = '.git' if desc_reponame.endswith(suffix): desc_reponame = desc_reponame[0:len(desc_reponame)-len(suffix)] repo = RepoManager.get_repo_by_name(desc_username, desc_reponame) if repo is None: return unauthorized_httpResponse # if deploy key if 'git-receive-pack' not in orgi_request_uri: deploy_key = None username, password = _http_authenticate_name_password(request) if username is not None: deploy_key = username if deploy_key is not None and deploy_key != '' and repo.deploy_url == deploy_key: return HttpResponse(status=200) if repo.auth_type == 0: # if orgi_request_uri.endswith('?service=git-receive-pack') or action == 'git-receive-pack': if 'git-receive-pack' in orgi_request_uri: user = _http_authenticate_user(request) if not RepoManager.is_allowed_access_repo(repo, user, REPO_PERMISSION.WRITE): return unauthorized_httpResponse return HttpResponse(status=200) else: user = _http_authenticate_user(request) if 'git-receive-pack' in orgi_request_uri: if RepoManager.is_allowed_access_repo(repo, user, REPO_PERMISSION.WRITE): return HttpResponse(status=200) else: if RepoManager.is_allowed_access_repo(repo, user, REPO_PERMISSION.READ_ONLY): return HttpResponse(status=200) except Exception, e: print e
def unwatch(request, user_name): gsuserprofile = GsuserManager.get_userprofile_by_name(user_name) if gsuserprofile is None: message = u'用户不存在' return json_failed(404, message) if not RepoManager.unwatch_user(request.userprofile, gsuserprofile): message = u'取消关注失败,可能用户未被关注' return json_failed(500, message) return json_success(u'成功取消关注用户 %s' % user_name)
def unwatch(request, user_name): gsuserprofile = GsuserManager.get_userprofile_by_name(user_name) if gsuserprofile is None: message = u'用户不存在' return json_failed(404, message) if not RepoManager.unwatch_user(request.userprofile, gsuserprofile): message = u'取消关注失败,可能用户未被关注' return json_failed(500, message) return json_success(u'成功取消关注用户 %s' % user_name)
def watch(request, user_name): gsuserprofile = GsuserManager.get_userprofile_by_name(user_name) if gsuserprofile is None: message = u'用户不存在' return json_failed(404, message) if not RepoManager.watch_user(request.userprofile, gsuserprofile): message = u'关注失败,关注数量超过限制或者用户不允许关注' return json_failed(500, message) return json_success(u'成功关注用户 %s' % user_name)
def repo(request, username): (teamUser, teamUserprofile) = _get_team_user_userprofile(request, username) current = 'repo' title = u'%s / 仓库列表' % (teamUser.username) teamMember = TeamManager.get_teamMember_by_teamUserId_userId( teamUser.id, request.user.id) repos = [] # is team member if teamMember: repos = RepoManager.list_repo_by_userId(teamUser.id, 0, 1000) else: repos = RepoManager.list_unprivate_repo_by_userId(teamUser.id, 0, 1000) response_dictionary = {'current': current, 'title': title, 'repos': repos} response_dictionary.update( _get_common_team_dict(request, teamUser, teamUserprofile)) return render_to_response('team/repo.html', response_dictionary, context_instance=RequestContext(request))
def watch(request, user_name): gsuserprofile = GsuserManager.get_userprofile_by_name(user_name) if gsuserprofile is None: message = u'用户不存在' return json_failed(404, message) if not RepoManager.watch_user(request.userprofile, gsuserprofile): message = u'关注失败,关注数量超过限制或者用户不允许关注' return json_failed(500, message) return json_success(u'成功关注用户 %s' % user_name)
def show(request, user_name, repo_name, issue_id, page): refs = 'master'; path = '.'; current = 'issues' repo = RepoManager.get_repo_by_name(user_name, repo_name) if repo is None: raise Http404 issue = IssueManager.get_issue(repo.id, issue_id) if issue is None: raise Http404 issueCommentForm = IssueCommentForm() if request.method == 'POST' and request.user.is_authenticated(): issueComment = IssueComment() issueComment.issue_id = issue_id issueComment.user_id = request.user.id issueCommentForm = IssueCommentForm(request.POST, instance = issueComment) if issueCommentForm.is_valid(): cid = issueCommentForm.save().id FeedManager.notif_issue_comment_at(request.user.id, cid, issueCommentForm.cleaned_data['content']) issue.comment_count = issue.comment_count + 1 issue.save() return HttpResponseRedirect('/%s/%s/issues/%s/' % (user_name, repo_name, issue_id)) page_size = 50; total_count = issue.comment_count; total_page = total_count / page_size if total_count != 0 and total_count % page_size == 0: total_page = total_page - 1 if page is None or int(page) > total_page: page = total_page page = int(page) issue_comments = [] if total_count > 0: offset = page*page_size; row_count = page_size issue_comments = IssueManager.list_issue_comments(issue_id, offset, row_count) memberUsers = RepoManager.list_repo_team_memberUser(repo.id) memberUsers = _let_request_user_first(memberUsers, request.user.id) assigneds = [x.username for x in memberUsers] has_issue_modify_right = _has_issue_modify_right(request, issue, repo) title = u'%s / %s / 问题:%s' % (user_name, repo_name, issue.subject) response_dictionary = {'mainnav': 'repo', 'current': current, 'title': title, 'path': path, 'issue': issue, 'issue_comments': issue_comments, 'issueCommentForm': issueCommentForm, 'page': page, 'total_page': range(0, total_page+1), 'assigneds': assigneds, 'assigned': issue.assigned, 'tracker': issue.tracker, 'status': issue.status, 'priority': issue.priority, 'has_issue_modify_right': has_issue_modify_right} response_dictionary.update(ISSUE_ATTRS) response_dictionary.update(get_common_repo_dict(request, repo, user_name, repo_name, refs)) return render_to_response('repo/issue_show.html', response_dictionary, context_instance=RequestContext(request))
def issues_list(request, user_name, repo_name, assigned, tracker, status, priority, orderby, page): refs = 'master'; path = '.'; current = 'issues'; title = u'%s / %s / 问题列表' % (user_name, repo_name) repo = RepoManager.get_repo_by_name(user_name, repo_name) if repo is None: raise Http404 user_id = request.user.id memberUsers = RepoManager.list_repo_team_memberUser(repo.id) memberUsers = _let_request_user_first(memberUsers, user_id) member_ids = [x.id for x in memberUsers] assigneds = [x.username for x in memberUsers] assigneds.insert(0, '0') if assigned is None: assigned = assigneds[0] assigned_id = 0 assigned_user = GsuserManager.get_user_by_name(assigned) if assigned_user is not None and assigned in assigneds: assigned_id = assigned_user.id tracker = int(tracker); status = int(status); priority = int(priority); page = int(page) current_attrs = { 'assigned': str(assigned), 'tracker': tracker, 'status': status, 'priority': priority, 'orderby': str(orderby), 'page': page } issues = [] page_size = 50; offset = page*page_size; row_count = page_size + 1 if assigned_id == 0 and tracker == 0 and status == 0 and priority == 0: issues = IssueManager.list_issues(repo.id, orderby, offset, row_count) else: assigned_ids = member_ids if assigned_id == 0 else [assigned_id] trackeres = TRACKERS_VAL if tracker == 0 else [tracker] statuses = STATUSES_VAL if status == 0 else [status] priorities = PRIORITIES_VAL if priority == 0 else [priority] issues = IssueManager.list_issues_cons(repo.id, assigned_ids, trackeres, statuses, priorities, orderby, offset, row_count) hasPre = False ; hasNext = False if page > 0: hasPre = True if len(issues) > page_size: hasNext = True issues.pop() response_dictionary = {'mainnav': 'repo', 'current': current, 'title': title, 'path': path, 'assigneds': assigneds, 'assigned': assigned, 'tracker': tracker, 'status': status, 'priority': priority, 'orderby': orderby, 'page': page, 'current_attrs': current_attrs, 'issues': issues, 'hasPre': hasPre, 'hasNext': hasNext} response_dictionary.update(ISSUE_ATTRS) response_dictionary.update(get_common_repo_dict(request, repo, user_name, repo_name, refs)) return render_to_response('repo/issues.html', response_dictionary, context_instance=RequestContext(request))
def __list_not_exists_commitHistorys(repo, raw_commitHistorys): commitHistorys = [] commit_ids = [x.commit_id for x in raw_commitHistorys] exists_commitHistorys = RepoManager.list_commits_by_commit_ids(repo.id, commit_ids) exists_commit_ids_set = set([x.commit_id for x in exists_commitHistorys]) commitHistorys = [] for commitHistory in raw_commitHistorys: if commitHistory.commit_id not in exists_commit_ids_set: commitHistorys.append(commitHistory) return commitHistorys
def delete(request, user_name, repo_name, issue_id): repo = RepoManager.get_repo_by_name(user_name, repo_name) if repo is None: raise Http404 issue = IssueManager.get_issue(repo.id, issue_id) if issue is not None: if _has_issue_modify_right(request, issue, repo): issue.visibly = 1 issue.save() return _json_ok()
def delete(request, user_name, repo_name, issue_id): repo = RepoManager.get_repo_by_name(user_name, repo_name) if repo is None: raise Http404 issue = IssueManager.get_issue(repo.id, issue_id) if issue is not None: if _has_issue_modify_right(request, issue, repo): issue.visibly = 1 issue.save() return _json_ok()
def fillwith(self): self.repo = RepoManager.get_repo_by_id(self.repo_id) self.creator_userprofile = GsuserManager.get_userprofile_by_id(self.creator_user_id) self.assigned_userprofile = GsuserManager.get_userprofile_by_id(self.assigned) if self.tracker in ISSUE_ATTRS['REV_TRACKERS']: self.tracker_v = ISSUE_ATTRS['REV_TRACKERS'][self.tracker] if self.status in ISSUE_ATTRS['REV_STATUSES']: self.status_v = ISSUE_ATTRS['REV_STATUSES'][self.status] if self.priority in ISSUE_ATTRS['REV_PRIORITIES']: self.priority_v = ISSUE_ATTRS['REV_PRIORITIES'][self.priority]
def pull_request(request, username): (teamUser, teamUserprofile) = _get_team_user_userprofile(request, username) current = 'pull'; title = u'%s / 我创建的合并请求' % (teamUser.username) feedAction = FeedAction() feedAction.set_user_position(teamUser.id, PositionKey.PULL) pullRequests = RepoManager.list_pullRequest_by_teamUserId_pullUserId(teamUser.id, request.user.id) response_dictionary = {'current': current, 'title': title, 'pullRequests': pullRequests} response_dictionary.update(_get_common_team_dict(request, teamUser, teamUserprofile)) return render_to_response('team/pull_request.html', response_dictionary, context_instance=RequestContext(request))
def __list_not_exists_commitHistorys(repo, raw_commitHistorys): commitHistorys = [] commit_ids = [x.commit_id for x in raw_commitHistorys] exists_commitHistorys = RepoManager.list_commits_by_commit_ids( repo.id, commit_ids) exists_commit_ids_set = set([x.commit_id for x in exists_commitHistorys]) commitHistorys = [] for commitHistory in raw_commitHistorys: if commitHistory.commit_id not in exists_commit_ids_set: commitHistorys.append(commitHistory) return commitHistorys
def wrap(request, *args, **kwargs): if len(args) >= 2: user_name = args[0] repo_name = args[1] repo = RepoManager.get_repo_by_name(user_name, repo_name) if repo is None: return error_with_reason(request, 'repo_not_found') if repo.auth_type != 0 and not request.user.is_authenticated(): return HttpResponseRedirect('/login/?next=' + urlquote(request.path)) is_allowed_access_repo = RepoManager.is_allowed_access_repo( repo, request.user, REPO_PERMISSION.READ_ONLY) if not is_allowed_access_repo: if request.method == 'POST': return json_failed(403, u'没有管理权限') return error_with_reason(request, 'repo_permission_denied') if request.user.is_authenticated(): feedAction = FeedAction() feedAction.add_recently_view_repo_now(request.user.id, repo.id) return function(request, *args, **kwargs)
def star_repo(request, user_name): title = u'%s / 标星的仓库' % user_name gsuser = GsuserManager.get_user_by_name(user_name) if gsuser is None: raise Http404 gsuserprofile = GsuserManager.get_userprofile_by_id(gsuser.id) star_repos = RepoManager.list_star_repo(gsuser.id, 0, 500) response_dictionary = {'mainnav': 'user', 'title': title, 'star_repos': star_repos} response_dictionary.update(get_common_user_dict(request, gsuser, gsuserprofile)) return render_to_response('user/star_repo.html', response_dictionary, context_instance=RequestContext(request))
def get_attrs(username, reponame): user = GsuserManager.get_user_by_name(username) if not user: return_all_none() userprofile = GsuserManager.get_userprofile_by_id(user.id) if not userprofile: return_all_none() repo = RepoManager.get_repo_by_userId_name(user.id, reponame) if not repo: return_all_none() abs_repo_path = repo.get_abs_repopath() return (user, userprofile, repo, abs_repo_path)
def get_attrs(username, reponame): user = GsuserManager.get_user_by_name(username) if not user: return_all_none() userprofile = GsuserManager.get_userprofile_by_id(user.id) if not userprofile: return_all_none() repo = RepoManager.get_repo_by_userId_name(user.id, reponame) if not repo: return_all_none() abs_repo_path = repo.get_abs_repopath() return (user, userprofile, repo, abs_repo_path)
def create(self, notif_cate, notif_type, from_user_id, to_user_id, relative_id): notifMessage = NotifMessage( notif_cate=notif_cate, notif_type=notif_type, from_user_id=from_user_id, to_user_id=to_user_id, relative_id=relative_id, ) if not relative_id: return notifMessage # without AT_MERGE_COMMENT if notifMessage.is_at_commit(): commitHistory = RepoManager.get_commit_by_id(relative_id) if commitHistory: repo = RepoManager.get_repo_by_id(commitHistory.repo_id) if repo: notifMessage.user_id = repo.user_id notifMessage.repo_id = repo.id elif notifMessage.is_at_issue() or notifMessage.is_issue_cate(): issue = IssueManager.get_issue_by_id(relative_id) if issue: notifMessage.user_id = issue.user_id notifMessage.repo_id = issue.repo_id elif notifMessage.is_at_merge() or notifMessage.is_pull_request_cate(): pullRequest = RepoManager.get_pullRequest_by_id(relative_id) if pullRequest: repo = RepoManager.get_repo_by_id(pullRequest.desc_repo_id) if repo: notifMessage.user_id = repo.user_id notifMessage.repo_id = repo.id elif notifMessage.is_at_issue_comment(): issue_comment = IssueManager.get_issue_comment(relative_id) if issue_comment: issue = IssueManager.get_issue_by_id(issue_comment.issue_id) if issue: notifMessage.user_id = issue.user_id notifMessage.repo_id = issue.repo_id return notifMessage
def get_user_repo_attr(username, reponame): nones = (None, None, None, None) user = GsuserManager.get_user_by_name(username) if not user: return nones userprofile = GsuserManager.get_userprofile_by_id(user.id) if not userprofile: return nones repo = RepoManager.get_repo_by_userId_name(user.id, reponame) if not repo: return nones abs_repopath = repo.get_abs_repopath() return (user, userprofile, repo, abs_repopath)
def get_user_repo_attr(username, reponame): nones = (None, None, None, None) user = GsuserManager.get_user_by_name(username) if not user: return nones userprofile = GsuserManager.get_userprofile_by_id(user.id) if not userprofile: return nones repo = RepoManager.get_repo_by_userId_name(user.id, reponame) if not repo: return nones abs_repopath = repo.get_abs_repopath() return (user, userprofile, repo, abs_repopath)
def get_stats_dict(request, user): now = datetime.now() last12hours = timeutils.getlast12hours(now) last7days = timeutils.getlast7days(now) last30days = timeutils.getlast30days(now) last12months = timeutils.getlast12months(now) raw_last12hours_commit = StatsManager.list_user_stats(user.id, 'hour', datetime.fromtimestamp(last12hours[-1]), datetime.fromtimestamp(last12hours[0])) last12hours_commit = dict([(time.mktime(x.date.timetuple()), int(x.count)) for x in raw_last12hours_commit]) raw_last30days_commit = StatsManager.list_user_stats(user.id, 'day', datetime.fromtimestamp(last30days[-1]), datetime.fromtimestamp(last30days[0])) last30days_commit = dict([(time.mktime(x.date.timetuple()), int(x.count)) for x in raw_last30days_commit]) last7days_commit = {} for x in last7days: if x in last30days_commit: last7days_commit[x] = last30days_commit[x] raw_last12months_commit = StatsManager.list_user_stats(user.id, 'month', datetime.fromtimestamp(last12months[-1]), datetime.fromtimestamp(last12months[0])) last12months_commit = dict([(time.mktime(x.date.timetuple()), int(x.count)) for x in raw_last12months_commit]) round_week = timeutils.get_round_week(now) round_month = timeutils.get_round_month(now) round_year = timeutils.get_round_year(now) raw_per_last_week_commits = StatsManager.list_user_repo_stats(user.id, 'week', round_week) raw_per_last_month_commits = StatsManager.list_user_repo_stats(user.id, 'month', round_month) raw_per_last_year_commits = StatsManager.list_user_repo_stats(user.id, 'year', round_year) raw_week_repo_ids = [x.repo_id for x in raw_per_last_week_commits] raw_month_repo_ids = [x.repo_id for x in raw_per_last_month_commits] raw_year_repo_ids = [x.repo_id for x in raw_per_last_year_commits] uniq_repo_ids = list(set(raw_week_repo_ids + raw_month_repo_ids + raw_year_repo_ids)) repo_dict = RepoManager.merge_repo_map(uniq_repo_ids) is_yourself = False if request.user.is_authenticated() and user.id == request.user.id: is_yourself = True per_repo_week_commits = _list_repo_count_dict(raw_per_last_week_commits, repo_dict, is_yourself) per_repo_month_commits = _list_repo_count_dict(raw_per_last_month_commits, repo_dict, is_yourself) per_repo_year_commits = _list_repo_count_dict(raw_per_last_year_commits, repo_dict, is_yourself) round_week_tip = u'%s 以来参与项目' % round_week.strftime('%y/%m/%d') round_month_tip = u'%s 以来参与项目' % round_month.strftime('%y/%m/%d') round_year_tip = u'%s 以来参与项目' % round_year.strftime('%y/%m/%d') per_repo_commits = [] if len(per_repo_week_commits) > 0: per_repo_commits.append({'commits': per_repo_week_commits, 'tip': round_week_tip}) if len(per_repo_month_commits) > 0: per_repo_commits.append({'commits': per_repo_month_commits, 'tip': round_month_tip}) if len(per_repo_year_commits) > 0: per_repo_commits.append({'commits': per_repo_year_commits, 'tip': round_year_tip}) stats_dict = {'last12hours': last12hours, 'last7days': last7days, 'last30days': last30days, 'last12months': last12months, 'last12hours_commit': last12hours_commit, 'last7days_commit': last7days_commit, 'last30days_commit': last30days_commit, 'last12months_commit': last12months_commit, 'per_repo_commits': per_repo_commits} return stats_dict
def create(self, notif_cate, notif_type, from_user_id, to_user_id, relative_id): notifMessage = NotifMessage( notif_cate = notif_cate, notif_type = notif_type, from_user_id = from_user_id, to_user_id = to_user_id, relative_id = relative_id, ) if not relative_id: return notifMessage # without AT_MERGE_COMMENT if notifMessage.is_at_commit(): commitHistory = RepoManager.get_commit_by_id(relative_id) if commitHistory: repo = RepoManager.get_repo_by_id(commitHistory.repo_id) if repo: notifMessage.user_id = repo.user_id notifMessage.repo_id = repo.id elif notifMessage.is_at_issue() or notifMessage.is_issue_cate(): issue = IssueManager.get_issue_by_id(relative_id) if issue: notifMessage.user_id = issue.user_id notifMessage.repo_id = issue.repo_id elif notifMessage.is_at_merge() or notifMessage.is_pull_request_cate(): pullRequest = RepoManager.get_pullRequest_by_id(relative_id) if pullRequest: repo = RepoManager.get_repo_by_id(pullRequest.desc_repo_id) if repo: notifMessage.user_id = repo.user_id notifMessage.repo_id = repo.id elif notifMessage.is_at_issue_comment(): issue_comment = IssueManager.get_issue_comment(relative_id) if issue_comment: issue = IssueManager.get_issue_by_id(issue_comment.issue_id) if issue: notifMessage.user_id = issue.user_id notifMessage.repo_id = issue.repo_id return notifMessage
def pull_request(request): current = 'pull' title = u'%s / 我创建的合并请求' % (request.user.username) feedAction = FeedAction() feedAction.set_user_position(request.user.id, PositionKey.PULL) pullRequests = RepoManager.list_pullRequest_by_pullUserId(request.user.id) response_dictionary = { 'current': current, 'title': title, 'pullRequests': pullRequests } return render_to_response('user/pull_request.html', response_dictionary, context_instance=RequestContext(request))
def user(request, user_name): title = u'%s / 概括' % user_name gsuser = GsuserManager.get_user_by_name(user_name) if gsuser is None: raise Http404 gsuserprofile = GsuserManager.get_userprofile_by_id(gsuser.id) if gsuserprofile.is_team_account == 1 and TeamManager.is_teamMember(gsuser.id, request.user.id): return HttpResponseRedirect('/%s/-/dashboard/' % user_name) recommendsForm = RecommendsForm() repos = [] if gsuser.id == request.user.id: repos = RepoManager.list_repo_by_userId(gsuser.id, 0, 100) else: repos = RepoManager.list_unprivate_repo_by_userId(gsuser.id, 0, 100) now = datetime.now() last30days = timeutils.getlast30days(now) last30days_commit = get_last30days_commit(gsuser) feedAction = FeedAction() raw_watch_repos = feedAction.get_watch_repos(gsuser.id, 0, 10) watch_repo_ids = [int(x[0]) for x in raw_watch_repos] watch_repos_map = RepoManager.merge_repo_map(watch_repo_ids) watch_repos = [watch_repos_map[x] for x in watch_repo_ids if x in watch_repos_map] pri_user_feeds = feedAction.get_pri_user_feeds(gsuser.id, 0, 10) pub_user_feeds = feedAction.get_pub_user_feeds(gsuser.id, 0, 10) feeds_as_json = get_feeds_as_json(request, pri_user_feeds, pub_user_feeds) star_repos = RepoManager.list_star_repo(gsuser.id, 0, 20) response_dictionary = {'mainnav': 'user', 'title': title, 'recommendsForm': recommendsForm, 'repos': repos, 'watch_repos': watch_repos, 'star_repos': star_repos, 'last30days': last30days, 'last30days_commit': last30days_commit, 'feeds_as_json': feeds_as_json} response_dictionary.update(get_common_user_dict(request, gsuser, gsuserprofile)) return render_to_response('user/user.html', response_dictionary, context_instance=RequestContext(request))
def change(request): thirdpartyUser = GsuserManager.get_thirdpartyUser_by_id(request.user.id) user = None is_user_exist = True is_exist_repo = False username = request.POST.get('username') if username is not None and re.match("^[a-zA-Z0-9_-]+$", username) and username != request.user.username and username not in MAIN_NAVS and not username.startswith('-'): repo_count = RepoManager.count_repo_by_userId(request.user.id) if repo_count > 0: return json_httpResponse({'is_exist_repo': True}) user = GsuserManager.get_user_by_name(username) if user is None: request.user.username = username request.userprofile.username = username request.user.save() request.userprofile.save() for repo in RepoManager.list_repo_by_userId(request.user.id, 0, 100): repo.username = username repo.save() is_user_exist = False goto = '' email = request.POST.get('email') if email is not None and email_re.match(email): user = GsuserManager.get_user_by_email(email) if user is None: Mailer().send_change_email(request.user, email) email_suffix = email.split('@')[-1] if email_suffix in COMMON_EMAIL_DOMAIN: goto = COMMON_EMAIL_DOMAIN[email_suffix] is_user_exist = False if thirdpartyUser is not None: thirdpartyUser.init = 1 thirdpartyUser.save() if username == request.user.username: is_user_exist = False response_dictionary = { 'is_exist_repo': is_exist_repo, 'is_user_exist': is_user_exist, 'goto': goto, 'new_username': username, 'new_email': email } return json_httpResponse(response_dictionary)
def comment_delete(request, user_name, repo_name, comment_id): repo = RepoManager.get_repo_by_name(user_name, repo_name) if repo is None: return _json_failed() issue_comment = IssueManager.get_issue_comment(comment_id) if issue_comment is None: return _json_failed() issue = IssueManager.get_issue(repo.id, issue_comment.issue_id) if issue is None or not _has_issue_comment_modify_right(request, issue_comment, repo): return _json_failed() issue_comment.visibly = 1 issue_comment.save() issue.comment_count = issue.comment_count - 1 issue.save() return _json_ok()
def _fillwith_notifMessages(self, notifMessages): repo_ids = [x.repo_id for x in notifMessages] userprofile_ids = [x.user_id for x in notifMessages] repo_dict = dict((x.id, x) for x in RepoManager.list_repo_by_ids(repo_ids)) userprofile_dict = dict((x.id, x) for x in GsuserManager.list_userprofile_by_ids(userprofile_ids)) for notifMessage in notifMessages: if notifMessage.repo_id in repo_dict: notifMessage.repo = repo_dict[notifMessage.repo_id] if notifMessage.from_user_id in userprofile_dict: notifMessage.from_userprofile = userprofile_dict[notifMessage.from_user_id] if notifMessage.is_at_commit(): commitHistory = RepoManager.get_commit_by_id(notifMessage.relative_id) notifMessage.relative_obj = commitHistory elif notifMessage.is_at_issue() or notifMessage.is_issue_cate(): issue = IssueManager.get_issue_by_id(notifMessage.relative_id) notifMessage.relative_obj = issue elif notifMessage.is_at_merge() or notifMessage.is_pull_request_cate(): pullRequest = RepoManager.get_pullRequest_by_id(notifMessage.relative_id) notifMessage.relative_obj = pullRequest elif notifMessage.is_at_issue_comment(): issue_comment = IssueManager.get_issue_comment(notifMessage.relative_id) notifMessage.relative_obj = issue_comment return notifMessages
def comment_delete(request, user_name, repo_name, comment_id): repo = RepoManager.get_repo_by_name(user_name, repo_name) if repo is None: return _json_failed() issue_comment = IssueManager.get_issue_comment(comment_id) if issue_comment is None: return _json_failed() issue = IssueManager.get_issue(repo.id, issue_comment.issue_id) if issue is None or not _has_issue_comment_modify_right( request, issue_comment, repo): return _json_failed() issue_comment.visibly = 1 issue_comment.save() issue.comment_count = issue.comment_count - 1 issue.save() return _json_ok()
def edit(request, user_name, repo_name, issue_id): refs = 'master' path = '.' current = 'issues' title = u'%s / %s / 编辑问题' % (user_name, repo_name) repo = RepoManager.get_repo_by_name(user_name, repo_name) if repo is None: raise Http404 issue = IssueManager.get_issue(repo.id, issue_id) has_issue_modify = _has_issue_modify_right(request, issue, repo) if issue is None or not has_issue_modify: raise Http404 orgi_issue = copy.copy(issue) issueForm = IssueForm(instance=issue) issueForm.fill_assigned(repo) error = u'' if request.method == 'POST': issueForm = IssueForm(request.POST, instance=issue) issueForm.fill_assigned(repo) if issueForm.is_valid(): newIssue = issueForm.save() nid = newIssue.id FeedManager.notif_issue_at( request.user.id, nid, issueForm.cleaned_data['subject'] + ' ' + issueForm.cleaned_data['content']) FeedManager.notif_issue_status(request.user, newIssue, ISSUE_STATUS.ASSIGNED) FeedManager.feed_issue_change(request.user, repo, orgi_issue, nid) return HttpResponseRedirect('/%s/%s/issues/%s/' % (user_name, repo_name, nid)) else: error = u'issue 内容不能为空' response_dictionary = { 'mainnav': 'repo', 'current': current, 'title': title, 'path': path, 'issueForm': issueForm, 'error': error, 'issue_id': issue_id } response_dictionary.update(ISSUE_ATTRS) response_dictionary.update( get_common_repo_dict(request, repo, user_name, repo_name, refs)) return render_to_response('repo/issue_edit.html', response_dictionary, context_instance=RequestContext(request))
def get_common_user_dict(request, gsuser, gsuserprofile): feedAction = FeedAction() raw_watch_users = feedAction.get_watch_users(gsuser.id, 0, 10) raw_bewatch_users = feedAction.get_bewatch_users(gsuser.id, 0, 10) watch_user_ids = [int(x[0]) for x in raw_watch_users] bewatch_user_ids = [int(x[0]) for x in raw_bewatch_users] watch_users_map = GsuserManager.map_users(watch_user_ids) bewatch_users_map = GsuserManager.map_users(bewatch_user_ids) watch_users = [watch_users_map[x] for x in watch_user_ids if x in watch_users_map] bewatch_users = [bewatch_users_map[x] for x in bewatch_user_ids if x in bewatch_users_map] raw_recommends = GsuserManager.list_recommend_by_userid(gsuser.id, 0, 20) recommends = __conver_to_recommends_vo(raw_recommends) is_watched_user = False if request.user.is_authenticated(): is_watched_user = RepoManager.is_watched_user(request.user.id, gsuser.id) return {'gsuser': gsuser, 'gsuserprofile': gsuserprofile, 'watch_users': watch_users, 'bewatch_users': bewatch_users, 'recommends': recommends, 'is_watched_user': is_watched_user, 'show_common': True}