{{.Org.Description}}
{{end}} +diff --git a/models/repo.go b/models/repo.go index 027ced6ff..5f90f97fc 100755 --- a/models/repo.go +++ b/models/repo.go @@ -140,6 +140,7 @@ func NewRepoContext() { // RepositoryStatus defines the status of repository type RepositoryStatus int type RepoBlockChainStatus int +type RepoType int // all kinds of RepositoryStatus const ( @@ -153,6 +154,11 @@ const ( RepoBlockChainFailed ) +const ( + RepoNormal RepoType = iota + RepoCourse +) + // Repository represents a git repository. type Repository struct { ID int64 `xorm:"pk autoincr"` @@ -166,7 +172,8 @@ type Repository struct { OriginalServiceType api.GitServiceType `xorm:"index"` OriginalURL string `xorm:"VARCHAR(2048)"` DefaultBranch string - + CreatorID int64 `xorm:"INDEX NOT NULL DEFAULT 0"` + Creator *User `xorm:"-"` NumWatches int NumStars int NumForks int @@ -175,11 +182,12 @@ type Repository struct { NumOpenIssues int `xorm:"-"` NumPulls int NumClosedPulls int - NumOpenPulls int `xorm:"-"` - NumMilestones int `xorm:"NOT NULL DEFAULT 0"` - NumClosedMilestones int `xorm:"NOT NULL DEFAULT 0"` - NumOpenMilestones int `xorm:"-"` - NumCommit int64 `xorm:"NOT NULL DEFAULT 0"` + NumOpenPulls int `xorm:"-"` + NumMilestones int `xorm:"NOT NULL DEFAULT 0"` + NumClosedMilestones int `xorm:"NOT NULL DEFAULT 0"` + NumOpenMilestones int `xorm:"-"` + NumCommit int64 `xorm:"NOT NULL DEFAULT 0"` + RepoType RepoType `xorm:"NOT NULL DEFAULT 0"` IsPrivate bool `xorm:"INDEX"` IsEmpty bool `xorm:"INDEX"` @@ -566,6 +574,19 @@ func (repo *Repository) GetOwner() error { return repo.getOwner(x) } +func (repo *Repository) getCreator(e Engine) (err error) { + if repo.CreatorID == 0 { + return nil + } + + repo.Creator, err = getUserByID(e, repo.CreatorID) + return err +} + +func (repo *Repository) GetCreator() error { + return repo.getCreator(x) +} + func (repo *Repository) mustOwner(e Engine) *User { if err := repo.getOwner(e); err != nil { return &User{ @@ -1064,6 +1085,8 @@ type CreateRepoOptions struct { IsMirror bool AutoInit bool Status RepositoryStatus + IsCourse bool + Topics []string } // GetRepoInitFile returns repository init files @@ -1109,7 +1132,7 @@ func IsUsableRepoAlias(name string) error { } // CreateRepository creates a repository for the user/organization. -func CreateRepository(ctx DBContext, doer, u *User, repo *Repository) (err error) { +func CreateRepository(ctx DBContext, doer, u *User, repo *Repository, opts ...CreateRepoOptions) (err error) { repo.LowerAlias = strings.ToLower(repo.Alias) if err = IsUsableRepoName(repo.Name); err != nil { return err @@ -1124,7 +1147,10 @@ func CreateRepository(ctx DBContext, doer, u *User, repo *Repository) (err error } else if has { return ErrRepoAlreadyExist{u.Name, repo.Name} } - + isCourse := isCourse(opts) + if isCourse { + repo.CreatorID = doer.ID + } if _, err = ctx.e.Insert(repo); err != nil { return err } @@ -1158,17 +1184,23 @@ func CreateRepository(ctx DBContext, doer, u *User, repo *Repository) (err error Config: &PullRequestsConfig{AllowMerge: true, AllowRebase: true, AllowRebaseMerge: true, AllowSquash: true}, }) } else if tp == UnitTypeDatasets { - units = append(units, RepoUnit{ - RepoID: repo.ID, - Type: tp, - Config: &DatasetConfig{EnableDataset: true}, - }) + if !isCourse { + units = append(units, RepoUnit{ + RepoID: repo.ID, + Type: tp, + Config: &DatasetConfig{EnableDataset: true}, + }) + } + } else if tp == UnitTypeCloudBrain { - units = append(units, RepoUnit{ - RepoID: repo.ID, - Type: tp, - Config: &CloudBrainConfig{EnableCloudBrain: true}, - }) + if !isCourse { + units = append(units, RepoUnit{ + RepoID: repo.ID, + Type: tp, + Config: &CloudBrainConfig{EnableCloudBrain: true}, + }) + } + } else if tp == UnitTypeBlockChain { units = append(units, RepoUnit{ RepoID: repo.ID, @@ -1176,11 +1208,13 @@ func CreateRepository(ctx DBContext, doer, u *User, repo *Repository) (err error Config: &BlockChainConfig{EnableBlockChain: true}, }) } else if tp == UnitTypeModelManage { - units = append(units, RepoUnit{ - RepoID: repo.ID, - Type: tp, - Config: &ModelManageConfig{EnableModelManage: true}, - }) + if !isCourse { + units = append(units, RepoUnit{ + RepoID: repo.ID, + Type: tp, + Config: &ModelManageConfig{EnableModelManage: true}, + }) + } } else { units = append(units, RepoUnit{ RepoID: repo.ID, @@ -1250,6 +1284,14 @@ func CreateRepository(ctx DBContext, doer, u *User, repo *Repository) (err error return nil } +func isCourse(opts []CreateRepoOptions) bool { + var isCourse = false + if len(opts) > 0 { + isCourse = opts[0].IsCourse + } + return isCourse +} + func countRepositories(userID int64, private bool) int64 { sess := x.Where("id > 0") diff --git a/models/repo_list.go b/models/repo_list.go index e41b0f49d..6fb9380de 100755 --- a/models/repo_list.go +++ b/models/repo_list.go @@ -48,9 +48,12 @@ func (repos RepositoryList) loadAttributes(e Engine) error { set := make(map[int64]struct{}) repoIDs := make([]int64, len(repos)) + setCreator := make(map[int64]struct{}) for i := range repos { set[repos[i].OwnerID] = struct{}{} repoIDs[i] = repos[i].ID + setCreator[repos[i].CreatorID] = struct{}{} + } // Load owners. @@ -61,8 +64,18 @@ func (repos RepositoryList) loadAttributes(e Engine) error { Find(&users); err != nil { return fmt.Errorf("find users: %v", err) } + //Load creator + creators := make(map[int64]*User, len(set)) + if err := e. + Where("id > 0"). + In("id", keysInt64(setCreator)). + Find(&creators); err != nil { + return fmt.Errorf("find create repo users: %v", err) + } + for i := range repos { repos[i].Owner = users[repos[i].OwnerID] + repos[i].Creator = creators[repos[i].CreatorID] } // Load primary language. @@ -174,6 +187,10 @@ type SearchRepoOptions struct { // True -> include just has milestones // False -> include just has no milestone HasMilestones util.OptionalBool + // None -> include all repos + // True -> include just courses + // False -> include just no courses + Course util.OptionalBool } //SearchOrderBy is used to sort the result @@ -351,6 +368,10 @@ func SearchRepositoryCondition(opts *SearchRepoOptions) builder.Cond { cond = cond.And(builder.Eq{"is_mirror": opts.Mirror == util.OptionalBoolTrue}) } + if opts.Course == util.OptionalBoolTrue { + cond = cond.And(builder.Eq{"repo_type": RepoCourse}) + } + if opts.Actor != nil && opts.Actor.IsRestricted { cond = cond.And(accessibleRepositoryCondition(opts.Actor)) } diff --git a/models/repo_tag.go b/models/repo_tag.go index 984f9e2db..730eb3f2a 100644 --- a/models/repo_tag.go +++ b/models/repo_tag.go @@ -42,7 +42,7 @@ type TagsDetail struct { TagId int64 TagName string TagLimit int - RepoList []Repository + RepoList []*Repository } func GetTagByID(id int64) (*OfficialTag, error) { @@ -146,8 +146,8 @@ func GetAllOfficialTagRepos(orgID int64, isOwner bool) ([]TagsDetail, error) { return result, nil } -func GetOfficialTagDetail(orgID, tagId int64) ([]Repository, error) { - t := make([]Repository, 0) +func GetOfficialTagDetail(orgID, tagId int64) ([]*Repository, error) { + t := make([]*Repository, 0) const SQLCmd = "select t2.* from official_tag_repos t1 inner join repository t2 on t1.repo_id = t2.id where t1.org_id = ? and t1.tag_id=? order by t2.updated_unix desc" if err := x.SQL(SQLCmd, orgID, tagId).Find(&t); err != nil { diff --git a/modules/auth/repo_form.go b/modules/auth/repo_form.go index 32890a5c1..c113aa890 100755 --- a/modules/auth/repo_form.go +++ b/modules/auth/repo_form.go @@ -728,3 +728,15 @@ type DeadlineForm struct { func (f *DeadlineForm) Validate(ctx *macaron.Context, errs binding.Errors) binding.Errors { return validate(errs, ctx.Data, f, ctx.Locale) } + +type CreateCourseForm struct { + RepoName string `binding:"Required;AlphaDashDot;MaxSize(100)"` + Alias string `binding:"Required;MaxSize(100);AlphaDashDotChinese"` + Topics string + Description string `binding:"MaxSize(1024)"` +} + +// Validate validates the fields +func (f *CreateCourseForm) Validate(ctx *macaron.Context, errs binding.Errors) binding.Errors { + return validate(errs, ctx.Data, f, ctx.Locale) +} diff --git a/modules/context/context.go b/modules/context/context.go index 25897d068..65f4b3f5d 100755 --- a/modules/context/context.go +++ b/modules/context/context.go @@ -328,7 +328,7 @@ func Contexter() macaron.Handler { } } - ctx.Resp.Header().Set(`X-Frame-Options`, `SAMEORIGIN`) + //ctx.Resp.Header().Set(`X-Frame-Options`, `SAMEORIGIN`) ctx.Data["CsrfToken"] = html.EscapeString(x.GetToken()) ctx.Data["CsrfTokenHtml"] = template.HTML(``) diff --git a/modules/context/org.go b/modules/context/org.go index 9b87fba9f..9b3f720c9 100644 --- a/modules/context/org.go +++ b/modules/context/org.go @@ -63,6 +63,8 @@ func HandleOrgAssignment(ctx *Context, args ...bool) { org := ctx.Org.Organization ctx.Data["Org"] = org + ctx.Data["IsCourse"] = ctx.Org.Organization.Name == setting.Course.OrgName + // Force redirection when username is actually a user. if !org.IsOrganization() { ctx.Redirect(setting.AppSubURL + "/" + org.Name) diff --git a/modules/context/repo.go b/modules/context/repo.go index 4da6e9a16..64f02c921 100755 --- a/modules/context/repo.go +++ b/modules/context/repo.go @@ -402,6 +402,7 @@ func RepoAssignment() macaron.Handler { } ctx.Repo.Owner = owner ctx.Data["Username"] = ctx.Repo.Owner.Name + ctx.Data["IsCourse"] = owner.Name == setting.Course.OrgName // Get repository. repo, err := models.GetRepositoryByName(owner.ID, repoName) diff --git a/modules/repository/create.go b/modules/repository/create.go index f5dfa63d6..0844c43c3 100644 --- a/modules/repository/create.go +++ b/modules/repository/create.go @@ -22,6 +22,10 @@ func CreateRepository(doer, u *models.User, opts models.CreateRepoOptions) (_ *m Limit: u.MaxRepoCreation, } } + var RepoType = models.RepoNormal + if opts.IsCourse { + RepoType = models.RepoCourse + } repo := &models.Repository{ OwnerID: u.ID, @@ -38,10 +42,15 @@ func CreateRepository(doer, u *models.User, opts models.CreateRepoOptions) (_ *m CloseIssuesViaCommitInAnyBranch: setting.Repository.DefaultCloseIssuesViaCommitsInAnyBranch, Status: opts.Status, IsEmpty: !opts.AutoInit, + RepoType: RepoType, + Topics: opts.Topics, } err = models.WithTx(func(ctx models.DBContext) error { - if err = models.CreateRepository(ctx, doer, u, repo); err != nil { + if err = models.CreateRepository(ctx, doer, u, repo, opts); err != nil { + return err + } + if err = models.SaveTopics(repo.ID, opts.Topics...); err != nil { return err } diff --git a/modules/setting/setting.go b/modules/setting/setting.go index 92ed32ef2..d22cdb5de 100755 --- a/modules/setting/setting.go +++ b/modules/setting/setting.go @@ -572,6 +572,11 @@ var ( }{} Warn_Notify_Mails []string + + Course = struct { + OrgName string + TeamName string + }{} ) // DateLang transforms standard language locale name to corresponding value in datetime plugin. @@ -1339,6 +1344,11 @@ func NewContext() { sec = Cfg.Section("warn_mail") Warn_Notify_Mails = strings.Split(sec.Key("mails").MustString(""), ",") + + sec = Cfg.Section("course") + Course.OrgName = sec.Key("org_name").MustString("") + Course.TeamName = sec.Key("team_name").MustString("") + } func SetRadarMapConfig() { diff --git a/modules/templates/helper.go b/modules/templates/helper.go index da278ba32..3d31b611c 100755 --- a/modules/templates/helper.go +++ b/modules/templates/helper.go @@ -93,6 +93,7 @@ func NewFuncMap() []template.FuncMap { "TimeSince": timeutil.TimeSince, "TimeSinceUnix": timeutil.TimeSinceUnix, "TimeSinceUnix1": timeutil.TimeSinceUnix1, + "TimeSinceUnixShort": timeutil.TimeSinceUnixShort, "RawTimeSince": timeutil.RawTimeSince, "FileSize": base.FileSize, "PrettyNumber": base.PrettyNumber, @@ -342,6 +343,7 @@ func NewTextFuncMap() []texttmpl.FuncMap { "TimeSince": timeutil.TimeSince, "TimeSinceUnix": timeutil.TimeSinceUnix, "TimeSinceUnix1": timeutil.TimeSinceUnix1, + "TimeSinceUnixShort": timeutil.TimeSinceUnixShort, "RawTimeSince": timeutil.RawTimeSince, "DateFmtLong": func(t time.Time) string { return t.Format(time.RFC1123Z) diff --git a/modules/timeutil/since.go b/modules/timeutil/since.go index a7854ed91..b19cc6401 100755 --- a/modules/timeutil/since.go +++ b/modules/timeutil/since.go @@ -165,5 +165,8 @@ func htmlTimeSinceUnix(then, now TimeStamp, lang string) template.HTML { func TimeSinceUnix1(then TimeStamp) string { format := time.Unix(int64(then), 0).Format("2006-01-02 15:04:05") return format - +} +func TimeSinceUnixShort(then TimeStamp) string { + format := time.Unix(int64(then), 0).Format("2006-01-02") + return format } diff --git a/options/locale/locale_en-US.ini b/options/locale/locale_en-US.ini index a2f61a914..b3ede3b06 100755 --- a/options/locale/locale_en-US.ini +++ b/options/locale/locale_en-US.ini @@ -50,6 +50,8 @@ repository = Repository organization = Organization mirror = Mirror new_repo = New Repository +new_course=Publish Course +course_desc = Course Description new_migrate = New Migration new_dataset = New Dataset edit_dataset = Edit Dataset @@ -219,6 +221,7 @@ show_only_public = Showing only public issues.in_your_repos = In your repositories contributors = Contributors +contributor = Contributor page_title=Explore Better AI page_small_title=OpenI AI Development Cooperation Platform @@ -268,8 +271,8 @@ org_no_results = No matching organizations found. code_no_results = No source code matching your search term found. code_search_results = Search results for '%s' code_last_indexed_at = Last indexed %s -save=save -cancel=cancel +save=Save +cancel=Cancel [auth] create_new_account = Register Account @@ -349,8 +352,11 @@ modify = Update [form] UserName = Username Alias = Repository name +courseAlias = Course Name +courseAdress = Course Path RepoPath = Repository path RepoAdress = Repository Adress +course_Adress = Course Address Email = Email address Password = Password Retype = Re-Type Password @@ -392,6 +398,7 @@ lang_select_error = Select a language from the list. username_been_taken = The username is already taken. repo_name_been_taken = The repository name or path is already used. +course_name_been_taken=The course name or path is already used. visit_rate_limit = Remote visit addressed rate limitation. 2fa_auth_required = Remote visit required two factors authentication. org_name_been_taken = The organization name is already taken. @@ -796,6 +803,7 @@ generate_from = Generate From repo_desc = Description repo_lang = Language repo_gitignore_helper = Select .gitignore templates. +repo_label_helpe = Press Enter to complete issue_labels = Issue Labels issue_labels_helper = Select an issue label set. license = License @@ -804,6 +812,8 @@ readme = README readme_helper = Select a README file template. auto_init = Initialize Repository (Adds .gitignore, License and README) create_repo = Create Repository +create_course = Publish Course +failed_to_create_course=Fail to publish course, please try again later. default_branch = Default Branch mirror_prune = Prune mirror_prune_desc = Remove obsolete remote-tracking references @@ -867,6 +877,11 @@ get_repo_info_error=Can not get the information of the repository. generate_statistic_file_error=Fail to generate file. repo_stat_inspect=ProjectAnalysis all=All + +computing.all = All +computing.Introduction=Introduction +computing.success=Join Success + modelarts.status=Status modelarts.createtime=CreateTime modelarts.version_nums = Version Nums @@ -988,8 +1003,12 @@ archive.issue.nocomment = This repo is archived. You cannot comment on issues. archive.pull.nocomment = This repo is archived. You cannot comment on pull requests. form.reach_limit_of_creation = You have already reached your limit of %d repositories. +form.reach_limit_of_course_creation=You have already reached your limit of %d courses or repositories. form.name_reserved = The repository name '%s' is reserved. +form.course_name_reserved=The course name '%s' is reserved. form.name_pattern_not_allowed = The pattern '%s' is not allowed in a repository name. +form.course_name_pattern_not_allowed=The pattern '%s' is not allowed in a course name. +add_course_org_fail=Fail to add organization, please try again later. need_auth = Clone Authorization migrate_type = Migration Type @@ -2034,6 +2053,7 @@ org_full_name_holder = Organization Full Name org_name_helper = Organization names should be short and memorable. create_org = Create Organization repo_updated = Updated +repo_released = Post home = Home people = People teams = Teams @@ -2050,6 +2070,14 @@ team_access_desc = Repository access team_permission_desc = Permission team_unit_desc = Allow Access to Repository Sections team_unit_disabled = (Disabled) +selected_couse=Selected Courses +release_course = Publish Course +all_keywords=All keywords +max_selectedPro= Select up to 9 public projects +custom_select_courses = Customize selected courses +recommend_remain_pro = Remain +save_fail_tips = The upper limit is exceeded +select_again = Select more than 9, please select again! form.name_reserved = The organization name '%s' is reserved. form.name_pattern_not_allowed = The pattern '%s' is not allowed in an organization name. @@ -2093,6 +2121,8 @@ members.remove = Remove members.leave = Leave members.invite_desc = Add a new member to %s: members.invite_now = Invite Now +course_members.remove = Remove +course_members.leave = Leave teams.join = Join teams.leave = Leave @@ -2135,6 +2165,7 @@ teams.all_repositories_helper = Team has access to all repositories. Selecting t teams.all_repositories_read_permission_desc = This team grants Read access to all repositories: members can view and clone repositories. teams.all_repositories_write_permission_desc = This team grants Write access to all repositories: members can read from and push to repositories. teams.all_repositories_admin_permission_desc = This team grants Admin access to all repositories: members can read from, push to and add collaborators to repositories. +teams.join_teams=Join in [admin] dashboard = Dashboard diff --git a/options/locale/locale_zh-CN.ini b/options/locale/locale_zh-CN.ini index d0f862d0d..86e88184c 100755 --- a/options/locale/locale_zh-CN.ini +++ b/options/locale/locale_zh-CN.ini @@ -50,6 +50,8 @@ repository=项目 organization=组织 mirror=镜像 new_repo=创建项目 +new_course=发布课程 +course_desc=课程描述 new_dataset=创建数据集 new_migrate=迁移外部项目 edit_dataset = Edit Dataset @@ -221,6 +223,7 @@ show_only_public=只显示公开的 issues.in_your_repos=属于该用户项目的 contributors=贡献者 +contributor=贡献者 page_title=探索更好的AI page_small_title=启智AI开发协作平台 @@ -352,8 +355,11 @@ modify=更新 UserName=用户名 RepoName=项目路径 Alias=项目名称 +courseAlias=课程名称 +courseAdress=课程路径 RepoPath=项目路径 RepoAdress=项目地址 +course_Adress = 课程地址 Email=邮箱地址 Password=密码 Retype=重新输入密码 @@ -395,6 +401,7 @@ lang_select_error=从列表中选出语言 username_been_taken=用户名已被使用。 repo_name_been_taken=项目名称或项目路径已被使用。 +course_name_been_taken=课程名称或地址已被使用。 visit_rate_limit=远程访问达到速度限制。 2fa_auth_required=远程访问需要双重验证。 org_name_been_taken=组织名称已被使用。 @@ -800,6 +807,7 @@ generate_from=生成自 repo_desc=项目描述 repo_lang=项目语言 repo_gitignore_helper=选择 .gitignore 模板。 +repo_label_helpe=输入完成后回车键完成标签确定。 issue_labels=任务标签 issue_labels_helper=选择一个任务标签集 license=授权许可 @@ -808,6 +816,8 @@ readme=自述 readme_helper=选择自述文件模板。 auto_init=初始化存储库 (添加. gitignore、许可证和自述文件) create_repo=创建项目 +create_course=发布课程 +failed_to_create_course=发布课程失败,请稍后再试。 default_branch=默认分支 mirror_prune=修剪 mirror_prune_desc=删除过时的远程跟踪引用 @@ -873,6 +883,10 @@ generate_statistic_file_error=生成文件失败。 repo_stat_inspect=项目分析 all=所有 +computing.all=全部 +computing.Introduction=简介 +computing.success=加入成功 + modelarts.status=状态 modelarts.createtime=创建时间 modelarts.version_nums=版本数 @@ -999,8 +1013,12 @@ archive.issue.nocomment=此项目已存档,您不能在此任务添加评论 archive.pull.nocomment=此项目已存档,您不能在此合并请求添加评论。 form.reach_limit_of_creation=你已经达到了您的 %d 项目的限制。 +form.reach_limit_of_course_creation=你已经达到了您的 %d 课程的限制。 form.name_reserved=项目名称 '%s' 是被保留的。 +form.course_name_reserved=课程名称 '%s' 是被保留的。 form.name_pattern_not_allowed=项目名称中不允许使用模式 "%s"。 +form.course_name_pattern_not_allowed=课程名称中不允许使用模式 "%s"。 +add_course_org_fail=加入组织失败,请稍后重试。 need_auth=需要授权验证 migrate_type=迁移类型 @@ -2045,6 +2063,7 @@ org_full_name_holder=组织全名 org_name_helper=组织名字应该简单明了。 create_org=创建组织 repo_updated=最后更新于 +repo_released=发布于 home=组织主页 people=组织成员 teams=组织团队 @@ -2061,6 +2080,14 @@ team_access_desc=项目权限 team_permission_desc=权限 team_unit_desc=允许访问项目单元 team_unit_disabled=(已禁用) +selected_couse=精选课程 +release_course = 发布课程 +all_keywords=全部关键字 +max_selectedPro= 最多可选9个公开项目 +custom_select_courses = 自定义精选课程 +recommend_remain_pro = 还能推荐 +save_fail_tips = 最多可选9个,保存失败 +select_again = 选择超过9个,请重新选择! form.name_reserved=组织名称 '%s' 是被保留的。 form.name_pattern_not_allowed=组织名称中不允许使用 "%s"。 @@ -2104,6 +2131,8 @@ members.remove=移除成员 members.leave=离开组织 members.invite_desc=邀请新的用户加入 %s: members.invite_now=立即邀请 +course_members.remove=移除 +course_members.leave=离开 teams.join=加入团队 teams.leave=离开团队 @@ -2147,6 +2176,10 @@ teams.all_repositories_read_permission_desc=此团队授予读取修改所有项目的访问权限: 成员可以查看和推送至项目。 teams.all_repositories_admin_permission_desc=该团队拥有 管理 所有项目的权限:团队成员可以读取、克隆、推送以及添加其它项目协作者。 +teams.join_teams=加入该组织 + + + [admin] dashboard=管理面板 users=帐户管理 diff --git a/routers/home.go b/routers/home.go index 399e11997..397e1990d 100755 --- a/routers/home.go +++ b/routers/home.go @@ -7,11 +7,11 @@ package routers import ( "bytes" - "fmt" - "io/ioutil" "net/http" "strings" + "code.gitea.io/gitea/services/repository" + "code.gitea.io/gitea/models" "code.gitea.io/gitea/modules/base" "code.gitea.io/gitea/modules/context" @@ -133,6 +133,7 @@ type RepoSearchOptions struct { Restricted bool PageSize int TplName base.TplName + Course util.OptionalBool } var ( @@ -211,6 +212,7 @@ func RenderRepoSearch(ctx *context.Context, opts *RepoSearchOptions) { AllLimited: true, TopicName: topic, IncludeDescription: setting.UI.SearchRepoDescription, + Course: opts.Course, }) if err != nil { ctx.ServerError("SearchRepository", err) @@ -559,7 +561,7 @@ func NotFound(ctx *context.Context) { func RecommendOrgFromPromote(ctx *context.Context) { url := setting.RecommentRepoAddr + "organizations" - result, err := recommendFromPromote(url) + result, err := repository.RecommendFromPromote(url) if err != nil { ctx.ServerError("500", err) return @@ -586,63 +588,11 @@ func RecommendOrgFromPromote(ctx *context.Context) { ctx.JSON(200, resultOrg) } -func recommendFromPromote(url string) ([]string, error) { - resp, err := http.Get(url) - if err != nil || resp.StatusCode != 200 { - log.Info("Get organizations url error=" + err.Error()) - return nil, err - } - bytes, err := ioutil.ReadAll(resp.Body) - resp.Body.Close() - if err != nil { - log.Info("Get organizations url error=" + err.Error()) - return nil, err - } - - allLineStr := string(bytes) - lines := strings.Split(allLineStr, "\n") - result := make([]string, len(lines)) - for i, line := range lines { - log.Info("i=" + fmt.Sprint(i) + " line=" + line) - result[i] = strings.Trim(line, " ") - } - return result, nil -} - func RecommendRepoFromPromote(ctx *context.Context) { - url := setting.RecommentRepoAddr + "projects" - result, err := recommendFromPromote(url) + result, err := repository.GetRecommendRepoFromPromote("projects") if err != nil { ctx.ServerError("500", err) - return - } - resultRepo := make([]map[string]interface{}, 0) - //resultRepo := make([]*models.Repository, 0) - for _, repoName := range result { - tmpIndex := strings.Index(repoName, "/") - if tmpIndex == -1 { - log.Info("error repo name format.") - } else { - ownerName := strings.Trim(repoName[0:tmpIndex], " ") - repoName := strings.Trim(repoName[tmpIndex+1:], " ") - repo, err := models.GetRepositoryByOwnerAndAlias(ownerName, repoName) - if err == nil { - repoMap := make(map[string]interface{}) - repoMap["ID"] = fmt.Sprint(repo.ID) - repoMap["Name"] = repo.Name - repoMap["Alias"] = repo.Alias - repoMap["OwnerName"] = repo.OwnerName - repoMap["NumStars"] = repo.NumStars - repoMap["NumForks"] = repo.NumForks - repoMap["Description"] = repo.Description - repoMap["NumWatchs"] = repo.NumWatches - repoMap["Topics"] = repo.Topics - repoMap["Avatar"] = repo.RelAvatarLink() - resultRepo = append(resultRepo, repoMap) - } else { - log.Info("query repo error," + err.Error()) - } - } + } else { + ctx.JSON(200, result) } - ctx.JSON(200, resultRepo) } diff --git a/routers/org/home.go b/routers/org/home.go index df600d96d..c9769f559 100755 --- a/routers/org/home.go +++ b/routers/org/home.go @@ -7,6 +7,10 @@ package org import ( "strings" + "code.gitea.io/gitea/services/repository" + + "code.gitea.io/gitea/modules/util" + "code.gitea.io/gitea/models" "code.gitea.io/gitea/modules/base" "code.gitea.io/gitea/modules/context" @@ -14,7 +18,8 @@ import ( ) const ( - tplOrgHome base.TplName = "org/home" + tplOrgHome base.TplName = "org/home" + tplOrgCourseHome base.TplName = "org/home_courses" ) // Home show organization home page @@ -59,10 +64,16 @@ func Home(ctx *context.Context) { case "fewestforks": orderBy = models.SearchOrderByForks default: - ctx.Data["SortType"] = "recentupdate" - orderBy = models.SearchOrderByRecentUpdated - } + if setting.Course.OrgName == org.Name { + ctx.Data["SortType"] = "newest" + orderBy = models.SearchOrderByNewest + } else { + ctx.Data["SortType"] = "recentupdate" + orderBy = models.SearchOrderByRecentUpdated + } + } + orderBy = orderBy + ",id" keyword := strings.Trim(ctx.Query("q"), " ") ctx.Data["Keyword"] = keyword @@ -76,9 +87,18 @@ func Home(ctx *context.Context) { count int64 err error ) + pageSize := setting.UI.User.RepoPagingNum + var CourseOptional util.OptionalBool = util.OptionalBoolNone + if setting.Course.OrgName == org.Name { + pageSize = 15 + recommendCourseKeyWords, _ := repository.GetRecommendCourseKeyWords() + ctx.Data["CoursesKeywords"] = recommendCourseKeyWords + + } + repos, count, err = models.SearchRepository(&models.SearchRepoOptions{ ListOptions: models.ListOptions{ - PageSize: setting.UI.User.RepoPagingNum, + PageSize: pageSize, Page: page, }, Keyword: keyword, @@ -87,6 +107,7 @@ func Home(ctx *context.Context) { Private: ctx.IsSigned, Actor: ctx.User, IncludeDescription: setting.UI.SearchRepoDescription, + Course: CourseOptional, }) if err != nil { ctx.ServerError("SearchRepository", err) @@ -132,11 +153,27 @@ func Home(ctx *context.Context) { //find org tag info tags, err := models.GetAllOfficialTagRepos(org.ID, ctx.Org.IsOwner) + + if setting.Course.OrgName == org.Name { + for _, tag := range tags { + for _, repo := range tag.RepoList { + repo.GetCreator() + repo.GetOwner() + } + } + + } + if err != nil { ctx.ServerError("GetAllOfficialTagRepos", err) return } ctx.Data["tags"] = tags - ctx.HTML(200, tplOrgHome) + if setting.Course.OrgName == org.Name { + ctx.HTML(200, tplOrgCourseHome) + } else { + ctx.HTML(200, tplOrgHome) + } + } diff --git a/routers/org/members.go b/routers/org/members.go index 9f13d1be3..39df692d2 100755 --- a/routers/org/members.go +++ b/routers/org/members.go @@ -17,7 +17,8 @@ import ( const ( // tplMembers template for organization members page - tplMembers base.TplName = "org/member/members" + tplMembers base.TplName = "org/member/members" + tplCourseMembers base.TplName = "org/member/course_members" ) // Members render organization users page @@ -64,8 +65,11 @@ func Members(ctx *context.Context) { ctx.Data["MembersIsPublicMember"] = membersIsPublic ctx.Data["MembersIsUserOrgOwner"] = members.IsUserOrgOwner(org.ID) ctx.Data["MembersTwoFaStatus"] = members.GetTwoFaStatus() - - ctx.HTML(200, tplMembers) + if setting.Course.OrgName == org.Name { + ctx.HTML(200, tplCourseMembers) + } else { + ctx.HTML(200, tplMembers) + } } // MembersAction response for operation to a member of organization diff --git a/routers/org/teams.go b/routers/org/teams.go index 5fc0edbdd..17c424578 100644 --- a/routers/org/teams.go +++ b/routers/org/teams.go @@ -10,6 +10,8 @@ import ( "path" "strings" + "code.gitea.io/gitea/modules/setting" + "code.gitea.io/gitea/models" "code.gitea.io/gitea/modules/auth" "code.gitea.io/gitea/modules/base" @@ -22,7 +24,8 @@ import ( const ( // tplTeams template path for teams list page - tplTeams base.TplName = "org/team/teams" + tplTeams base.TplName = "org/team/teams" + tplCourseTeams base.TplName = "org/team/courseTeams" // tplTeamNew template path for create new team page tplTeamNew base.TplName = "org/team/new" // tplTeamMembers template path for showing team members page @@ -44,8 +47,12 @@ func Teams(ctx *context.Context) { } } ctx.Data["Teams"] = org.Teams + if setting.Course.OrgName == org.Name { + ctx.HTML(200, tplCourseTeams) + } else { + ctx.HTML(200, tplTeams) + } - ctx.HTML(200, tplTeams) } // TeamsAction response for join, leave, remove, add operations to team diff --git a/routers/repo/course.go b/routers/repo/course.go new file mode 100644 index 000000000..44acdfcc0 --- /dev/null +++ b/routers/repo/course.go @@ -0,0 +1,196 @@ +package repo + +import ( + "net/http" + "strings" + + "code.gitea.io/gitea/models" + "code.gitea.io/gitea/modules/auth" + "code.gitea.io/gitea/modules/base" + "code.gitea.io/gitea/modules/context" + "code.gitea.io/gitea/modules/log" + "code.gitea.io/gitea/modules/setting" + repo_service "code.gitea.io/gitea/services/repository" +) + +const ( + tplCreateCourse base.TplName = "repo/createCourse" +) + +func CreateCourse(ctx *context.Context) { + ctx.Data["Title"] = ctx.Tr("new_course") + org, _ := models.GetUserByName(setting.Course.OrgName) + + ctx.Data["Owner"] = org + ctx.Data["IsCourse"] = true + + ctx.HTML(200, tplCreateCourse) + +} + +func CreateCoursePost(ctx *context.Context, form auth.CreateCourseForm) { + ctx.Data["Title"] = ctx.Tr("new_course") + + if ctx.Written() { + return + } + + org, _ := models.GetUserByName(setting.Course.OrgName) + + ctx.Data["Owner"] = org + ctx.Data["IsCourse"] = true + + var topics = make([]string, 0) + var topicsStr = strings.TrimSpace(form.Topics) + if len(topicsStr) > 0 { + topics = strings.Split(topicsStr, ",") + } + + validTopics, invalidTopics := models.SanitizeAndValidateTopics(topics) + + if len(validTopics) > 25 { + ctx.RenderWithErr(ctx.Tr("repo.topic.count_prompt"), tplCreateCourse, form) + return + } + + if len(invalidTopics) > 0 { + ctx.RenderWithErr(ctx.Tr("repo.topic.format_prompt"), tplCreateCourse, form) + return + } + + var repo *models.Repository + var err error + + if setting.Course.OrgName == "" || setting.Course.TeamName == "" { + log.Error("then organization name or team name of course is empty.") + ctx.RenderWithErr(ctx.Tr("repo.failed_to_create_course"), tplCreateCourse, form) + return + } + + org, team, err := getOrgAndTeam() + + if err != nil { + log.Error("Failed to get team from db.", err) + ctx.RenderWithErr(ctx.Tr("repo.failed_to_create_course"), tplCreateCourse, form) + return + } + isInTeam, err := models.IsUserInTeams(ctx.User.ID, []int64{team.ID}) + if err != nil { + log.Error("Failed to get user in team from db.") + ctx.RenderWithErr(ctx.Tr("repo.failed_to_create_course"), tplCreateCourse, form) + return + } + + if !isInTeam { + err = models.AddTeamMember(team, ctx.User.ID) + if err != nil { + log.Error("Failed to add user to team.") + ctx.RenderWithErr(ctx.Tr("repo.failed_to_create_course"), tplCreateCourse, form) + return + } + } + + if ctx.HasError() { + ctx.HTML(200, tplCreateCourse) + return + } + + repo, err = repo_service.CreateRepository(ctx.User, org, models.CreateRepoOptions{ + Name: form.RepoName, + Alias: form.Alias, + Description: form.Description, + Gitignores: "", + IssueLabels: "", + License: "", + Readme: "Default", + IsPrivate: false, + DefaultBranch: "master", + AutoInit: true, + IsCourse: true, + Topics: validTopics, + }) + if err == nil { + log.Trace("Repository created [%d]: %s/%s", repo.ID, org.Name, repo.Name) + ctx.Redirect(setting.AppSubURL + "/" + org.Name + "/" + repo.Name) + return + } + + handleCreateCourseError(ctx, org, err, "CreateCoursePost", tplCreateCourse, &form) +} + +func AddCourseOrg(ctx *context.Context) { + + _, team, err := getOrgAndTeam() + + if err != nil { + log.Error("Failed to get team from db.", err) + ctx.JSON(http.StatusOK, map[string]interface{}{ + "code": 1, + "message": ctx.Tr("repo.addCourseOrgFail"), + }) + return + } + isInTeam, err := models.IsUserInTeams(ctx.User.ID, []int64{team.ID}) + if err != nil { + log.Error("Failed to get user in team from db.", err) + ctx.JSON(http.StatusOK, map[string]interface{}{ + "code": 1, + "message": ctx.Tr("repo.add_course_org_fail"), + }) + return + } + + if !isInTeam { + err = models.AddTeamMember(team, ctx.User.ID) + if err != nil { + log.Error("Failed to add user to team.", err) + ctx.JSON(http.StatusOK, map[string]interface{}{ + "code": 1, + "message": ctx.Tr("repo.add_course_org_fail"), + }) + return + } + } + + ctx.JSON(http.StatusOK, map[string]interface{}{ + "code": 0, + "message": "", + }) + +} + +func getOrgAndTeam() (*models.User, *models.Team, error) { + org, err := models.GetUserByName(setting.Course.OrgName) + + if err != nil { + log.Error("Failed to get organization from db.", err) + return nil, nil, err + } + + team, err := models.GetTeam(org.ID, setting.Course.TeamName) + + if err != nil { + log.Error("Failed to get team from db.", err) + + return nil, nil, err + } + return org, team, nil +} + +func handleCreateCourseError(ctx *context.Context, owner *models.User, err error, name string, tpl base.TplName, form interface{}) { + switch { + case models.IsErrReachLimitOfRepo(err): + ctx.RenderWithErr(ctx.Tr("repo.form.reach_limit_of_course_creation", owner.MaxCreationLimit()), tpl, form) + case models.IsErrRepoAlreadyExist(err): + ctx.Data["Err_RepoName"] = true + ctx.RenderWithErr(ctx.Tr("form.course_name_been_taken"), tpl, form) + case models.IsErrNameReserved(err): + ctx.Data["Err_RepoName"] = true + ctx.RenderWithErr(ctx.Tr("repo.form.course_name_reserved", err.(models.ErrNameReserved).Name), tpl, form) + case models.IsErrNamePatternNotAllowed(err): + ctx.Data["Err_RepoName"] = true + ctx.RenderWithErr(ctx.Tr("repo.form.course_name_pattern_not_allowed", err.(models.ErrNamePatternNotAllowed).Pattern), tpl, form) + default: + ctx.ServerError(name, err) + } +} diff --git a/routers/repo/view.go b/routers/repo/view.go index b08243240..320102ba4 100755 --- a/routers/repo/view.go +++ b/routers/repo/view.go @@ -35,6 +35,7 @@ import ( const ( tplRepoEMPTY base.TplName = "repo/empty" tplRepoHome base.TplName = "repo/home" + tplCourseHome base.TplName = "repo/courseHome" tplWatchers base.TplName = "repo/watchers" tplForks base.TplName = "repo/forks" tplMigrating base.TplName = "repo/migrating" @@ -855,7 +856,12 @@ func renderCode(ctx *context.Context) { ctx.Data["TreeLink"] = treeLink ctx.Data["TreeNames"] = treeNames ctx.Data["BranchLink"] = branchLink - ctx.HTML(200, tplRepoHome) + if ctx.Repo.Repository.RepoType == models.RepoCourse { + ctx.HTML(200, tplCourseHome) + } else { + ctx.HTML(200, tplRepoHome) + } + } // RenderUserCards render a page show users according the input templaet diff --git a/routers/routes/routes.go b/routers/routes/routes.go index 2af1b7edc..9690c115d 100755 --- a/routers/routes/routes.go +++ b/routers/routes/routes.go @@ -708,6 +708,13 @@ func RegisterRoutes(m *macaron.Macaron) { }, reqSignIn) // ***** END: Organization ***** + m.Group("/course", func() { + m.Get("/create", repo.CreateCourse) + m.Post("/create", bindIgnErr(auth.CreateCourseForm{}), repo.CreateCoursePost) + m.Get("/addOrg", repo.AddCourseOrg) + + }, reqSignIn) + // ***** START: Repository ***** m.Group("/repo", func() { m.Get("/create", repo.Create) diff --git a/services/repository/repository.go b/services/repository/repository.go index dffa1ba11..cea16516a 100644 --- a/services/repository/repository.go +++ b/services/repository/repository.go @@ -5,12 +5,17 @@ package repository import ( + "fmt" + "io/ioutil" + "net/http" + "strings" + "code.gitea.io/gitea/models" "code.gitea.io/gitea/modules/log" "code.gitea.io/gitea/modules/notification" repo_module "code.gitea.io/gitea/modules/repository" + "code.gitea.io/gitea/modules/setting" pull_service "code.gitea.io/gitea/services/pull" - "fmt" ) // CreateRepository creates a repository for the user/organization. @@ -86,3 +91,84 @@ func PushCreateRepo(authUser, owner *models.User, repoName string) (*models.Repo return repo, nil } + +func GetRecommendCourseKeyWords() ([]string, error) { + + url := setting.RecommentRepoAddr + "course_keywords" + result, err := RecommendFromPromote(url) + + if err != nil { + return []string{}, err + } + return result, err + +} + +func GetRecommendRepoFromPromote(filename string) ([]map[string]interface{}, error) { + resultRepo := make([]map[string]interface{}, 0) + url := setting.RecommentRepoAddr + filename + result, err := RecommendFromPromote(url) + + if err != nil { + + return resultRepo, err + } + + //resultRepo := make([]*models.Repository, 0) + for _, repoName := range result { + tmpIndex := strings.Index(repoName, "/") + if tmpIndex == -1 { + log.Info("error repo name format.") + } else { + ownerName := strings.Trim(repoName[0:tmpIndex], " ") + repoName := strings.Trim(repoName[tmpIndex+1:], " ") + repo, err := models.GetRepositoryByOwnerAndAlias(ownerName, repoName) + if err == nil { + repoMap := make(map[string]interface{}) + repoMap["ID"] = fmt.Sprint(repo.ID) + repoMap["Name"] = repo.Name + repoMap["Alias"] = repo.Alias + if repo.RepoType == models.RepoCourse { + //Load creator + repo.GetCreator() + repoMap["Creator"] = repo.Creator + } + + repoMap["OwnerName"] = repo.OwnerName + repoMap["NumStars"] = repo.NumStars + repoMap["NumForks"] = repo.NumForks + repoMap["Description"] = repo.Description + repoMap["NumWatchs"] = repo.NumWatches + repoMap["Topics"] = repo.Topics + repoMap["Avatar"] = repo.RelAvatarLink() + resultRepo = append(resultRepo, repoMap) + } else { + log.Info("query repo error," + err.Error()) + } + } + } + return resultRepo, nil +} + +func RecommendFromPromote(url string) ([]string, error) { + resp, err := http.Get(url) + if err != nil || resp.StatusCode != 200 { + log.Info("Get organizations url error=" + err.Error()) + return nil, err + } + bytes, err := ioutil.ReadAll(resp.Body) + resp.Body.Close() + if err != nil { + log.Info("Get organizations url error=" + err.Error()) + return nil, err + } + + allLineStr := string(bytes) + lines := strings.Split(allLineStr, "\n") + result := make([]string, len(lines)) + for i, line := range lines { + log.Info("i=" + fmt.Sprint(i) + " line=" + line) + result[i] = strings.Trim(line, " ") + } + return result, nil +} diff --git a/templates/base/head.tmpl b/templates/base/head.tmpl index 75496aed5..859cacb62 100755 --- a/templates/base/head.tmpl +++ b/templates/base/head.tmpl @@ -200,14 +200,16 @@ var _hmt = _hmt || [];
-{{.Org.Description}}
{{end}} ++ {{if ne .CreatorID 0}} + {{$.i18n.Tr "home.contributor"}} : {{.Creator.Name}} + {{else}} + {{$.i18n.Tr "home.contributor"}}:{{.Owner.Name}} + {{end}} +
+{{.i18n.Tr "org.max_selectedPro"}}
+|
+ {{if .LatestCommitUser}}
+ |
+
+ ||
|---|---|---|
| {{svg "octicon-mail-reply" 16}}.. | +||
| + + {{svg "octicon-inbox" 16}} + {{$refURL := $commit.RefURL AppUrl $.Repository.FullName}} + {{if $refURL}} + {{$entry.Name}} @ {{ShortSha $commit.RefID}} + {{else}} + {{$entry.Name}} @ {{ShortSha $commit.RefID}} + {{end}} + + | + {{else}} ++ + {{if $entry.IsDir}} + {{$subJumpablePathName := $entry.GetSubJumpablePathName}} + {{$subJumpablePath := SubJumpablePath $subJumpablePathName}} + {{svg "octicon-file-directory" 16}} + + {{if eq (len $subJumpablePath) 2}} + {{index $subJumpablePath 0}}{{index $subJumpablePath 1}} + {{else}} + {{index $subJumpablePath 0}} + {{end}} + + {{else}} + + + {{$entry.Name}} + {{end}} + + | + {{end}} +{{TimeSince $commit.Committer.When $.Lang}} | +