repo.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435
  1. // Copyright 2014 The Gogs Authors. All rights reserved.
  2. // Use of this source code is governed by a MIT-style
  3. // license that can be found in the LICENSE file.
  4. package repo
  5. import (
  6. "net/http"
  7. "path"
  8. api "github.com/gogs/go-gogs-client"
  9. "github.com/pkg/errors"
  10. log "unknwon.dev/clog/v2"
  11. "github.com/G-Node/gogs/internal/conf"
  12. "github.com/G-Node/gogs/internal/context"
  13. "github.com/G-Node/gogs/internal/db"
  14. "github.com/G-Node/gogs/internal/form"
  15. "github.com/G-Node/gogs/internal/route/api/v1/convert"
  16. )
  17. func Search(c *context.APIContext) {
  18. opts := &db.SearchRepoOptions{
  19. Keyword: path.Base(c.Query("q")),
  20. OwnerID: c.QueryInt64("uid"),
  21. PageSize: convert.ToCorrectPageSize(c.QueryInt("limit")),
  22. Page: c.QueryInt("page"),
  23. }
  24. // workaround for the all query with logged users
  25. if opts.Keyword == "." {
  26. opts.Keyword = ""
  27. }
  28. // Check visibility.
  29. if c.IsLogged && opts.OwnerID > 0 {
  30. if c.User.ID == opts.OwnerID {
  31. opts.Private = true
  32. } else {
  33. u, err := db.GetUserByID(opts.OwnerID)
  34. if err != nil {
  35. c.JSON(http.StatusInternalServerError, map[string]interface{}{
  36. "ok": false,
  37. "error": err.Error(),
  38. })
  39. return
  40. }
  41. if u.IsOrganization() && u.IsOwnedBy(c.User.ID) {
  42. opts.Private = true
  43. }
  44. // FIXME: how about collaborators?
  45. }
  46. }
  47. repos, count, err := db.SearchRepositoryByName(opts)
  48. if err != nil {
  49. c.JSON(http.StatusInternalServerError, map[string]interface{}{
  50. "ok": false,
  51. "error": err.Error(),
  52. })
  53. return
  54. }
  55. if err = db.RepositoryList(repos).LoadAttributes(); err != nil {
  56. c.JSON(http.StatusInternalServerError, map[string]interface{}{
  57. "ok": false,
  58. "error": err.Error(),
  59. })
  60. return
  61. }
  62. results := make([]*api.Repository, 0, len(repos))
  63. for i := range repos {
  64. if !repos[i].Unlisted {
  65. rep := repos[i].APIFormat(nil)
  66. rep.Owner.Email = ""
  67. results = append(results, rep)
  68. }
  69. }
  70. c.SetLinkHeader(int(count), opts.PageSize)
  71. c.JSONSuccess(map[string]interface{}{
  72. "ok": true,
  73. "data": results,
  74. })
  75. }
  76. func listUserRepositories(c *context.APIContext, username string) {
  77. user, err := db.GetUserByName(username)
  78. if err != nil {
  79. c.NotFoundOrError(err, "get user by name")
  80. return
  81. }
  82. // Only list public repositories if user requests someone else's repository list,
  83. // or an organization isn't a member of.
  84. var ownRepos []*db.Repository
  85. if user.IsOrganization() {
  86. ownRepos, _, err = user.GetUserRepositories(c.User.ID, 1, user.NumRepos)
  87. } else {
  88. ownRepos, err = db.GetUserRepositories(&db.UserRepoOptions{
  89. UserID: user.ID,
  90. Private: c.User.ID == user.ID,
  91. Page: 1,
  92. PageSize: user.NumRepos,
  93. })
  94. }
  95. if err != nil {
  96. c.Error(err, "get user repositories")
  97. return
  98. }
  99. if err = db.RepositoryList(ownRepos).LoadAttributes(); err != nil {
  100. c.Error(err, "load attributes")
  101. return
  102. }
  103. // Early return for querying other user's repositories
  104. if c.User.ID != user.ID {
  105. repos := make([]*api.Repository, len(ownRepos))
  106. for i := range ownRepos {
  107. repos[i] = ownRepos[i].APIFormat(&api.Permission{Admin: true, Push: true, Pull: true})
  108. }
  109. c.JSONSuccess(&repos)
  110. return
  111. }
  112. accessibleRepos, err := user.GetRepositoryAccesses()
  113. if err != nil {
  114. c.Error(err, "get repositories accesses")
  115. return
  116. }
  117. numOwnRepos := len(ownRepos)
  118. repos := make([]*api.Repository, numOwnRepos+len(accessibleRepos))
  119. for i := range ownRepos {
  120. repos[i] = ownRepos[i].APIFormat(&api.Permission{Admin: true, Push: true, Pull: true})
  121. }
  122. i := numOwnRepos
  123. for repo, access := range accessibleRepos {
  124. repos[i] = repo.APIFormat(&api.Permission{
  125. Admin: access >= db.AccessModeAdmin,
  126. Push: access >= db.AccessModeWrite,
  127. Pull: true,
  128. })
  129. i++
  130. }
  131. c.JSONSuccess(&repos)
  132. }
  133. func ListMyRepos(c *context.APIContext) {
  134. listUserRepositories(c, c.User.Name)
  135. }
  136. func ListUserRepositories(c *context.APIContext) {
  137. listUserRepositories(c, c.Params(":username"))
  138. }
  139. func ListOrgRepositories(c *context.APIContext) {
  140. listUserRepositories(c, c.Params(":org"))
  141. }
  142. func CreateUserRepo(c *context.APIContext, owner *db.User, opt api.CreateRepoOption) {
  143. repo, err := db.CreateRepository(c.User, owner, db.CreateRepoOptions{
  144. Name: opt.Name,
  145. Description: opt.Description,
  146. Gitignores: opt.Gitignores,
  147. License: opt.License,
  148. Readme: opt.Readme,
  149. IsPrivate: opt.Private,
  150. AutoInit: opt.AutoInit,
  151. })
  152. if err != nil {
  153. if db.IsErrRepoAlreadyExist(err) ||
  154. db.IsErrNameNotAllowed(err) {
  155. c.ErrorStatus(http.StatusUnprocessableEntity, err)
  156. } else {
  157. if repo != nil {
  158. if err = db.DeleteRepository(c.User.ID, repo.ID); err != nil {
  159. log.Error("Failed to delete repository: %v", err)
  160. }
  161. }
  162. c.Error(err, "create repository")
  163. }
  164. return
  165. }
  166. c.JSON(201, repo.APIFormat(&api.Permission{Admin: true, Push: true, Pull: true}))
  167. }
  168. func Create(c *context.APIContext, opt api.CreateRepoOption) {
  169. // Shouldn't reach this condition, but just in case.
  170. if c.User.IsOrganization() {
  171. c.ErrorStatus(http.StatusUnprocessableEntity, errors.New("Not allowed to create repository for organization."))
  172. return
  173. }
  174. CreateUserRepo(c, c.User, opt)
  175. }
  176. func CreateOrgRepo(c *context.APIContext, opt api.CreateRepoOption) {
  177. org, err := db.GetOrgByName(c.Params(":org"))
  178. if err != nil {
  179. c.NotFoundOrError(err, "get organization by name")
  180. return
  181. }
  182. if !org.IsOwnedBy(c.User.ID) {
  183. c.ErrorStatus(http.StatusForbidden, errors.New("Given user is not owner of organization."))
  184. return
  185. }
  186. CreateUserRepo(c, org, opt)
  187. }
  188. func Migrate(c *context.APIContext, f form.MigrateRepo) {
  189. ctxUser := c.User
  190. // Not equal means context user is an organization,
  191. // or is another user/organization if current user is admin.
  192. if f.Uid != ctxUser.ID {
  193. org, err := db.GetUserByID(f.Uid)
  194. if err != nil {
  195. if db.IsErrUserNotExist(err) {
  196. c.ErrorStatus(http.StatusUnprocessableEntity, err)
  197. } else {
  198. c.Error(err, "get user by ID")
  199. }
  200. return
  201. } else if !org.IsOrganization() && !c.User.IsAdmin {
  202. c.ErrorStatus(http.StatusForbidden, errors.New("Given user is not an organization."))
  203. return
  204. }
  205. ctxUser = org
  206. }
  207. if c.HasError() {
  208. c.ErrorStatus(http.StatusUnprocessableEntity, errors.New(c.GetErrMsg()))
  209. return
  210. }
  211. if ctxUser.IsOrganization() && !c.User.IsAdmin {
  212. // Check ownership of organization.
  213. if !ctxUser.IsOwnedBy(c.User.ID) {
  214. c.ErrorStatus(http.StatusForbidden, errors.New("Given user is not owner of organization."))
  215. return
  216. }
  217. }
  218. remoteAddr, err := f.ParseRemoteAddr(c.User)
  219. if err != nil {
  220. if db.IsErrInvalidCloneAddr(err) {
  221. addrErr := err.(db.ErrInvalidCloneAddr)
  222. switch {
  223. case addrErr.IsURLError:
  224. c.ErrorStatus(http.StatusUnprocessableEntity, err)
  225. case addrErr.IsPermissionDenied:
  226. c.ErrorStatus(http.StatusUnprocessableEntity, errors.New("You are not allowed to import local repositories."))
  227. case addrErr.IsInvalidPath:
  228. c.ErrorStatus(http.StatusUnprocessableEntity, errors.New("Invalid local path, it does not exist or not a directory."))
  229. default:
  230. c.Error(err, "unexpected error")
  231. }
  232. } else {
  233. c.Error(err, "parse remote address")
  234. }
  235. return
  236. }
  237. repo, err := db.MigrateRepository(c.User, ctxUser, db.MigrateRepoOptions{
  238. Name: f.RepoName,
  239. Description: f.Description,
  240. IsPrivate: f.Private || conf.Repository.ForcePrivate,
  241. IsMirror: f.Mirror,
  242. RemoteAddr: remoteAddr,
  243. })
  244. if err != nil {
  245. if repo != nil {
  246. if errDelete := db.DeleteRepository(ctxUser.ID, repo.ID); errDelete != nil {
  247. log.Error("DeleteRepository: %v", errDelete)
  248. }
  249. }
  250. if db.IsErrReachLimitOfRepo(err) {
  251. c.ErrorStatus(http.StatusUnprocessableEntity, err)
  252. } else {
  253. c.Error(errors.New(db.HandleMirrorCredentials(err.Error(), true)), "migrate repository")
  254. }
  255. return
  256. }
  257. log.Trace("Repository migrated: %s/%s", ctxUser.Name, f.RepoName)
  258. c.JSON(201, repo.APIFormat(&api.Permission{Admin: true, Push: true, Pull: true}))
  259. }
  260. // FIXME: inject in the handler chain
  261. func parseOwnerAndRepo(c *context.APIContext) (*db.User, *db.Repository) {
  262. owner, err := db.GetUserByName(c.Params(":username"))
  263. if err != nil {
  264. if db.IsErrUserNotExist(err) {
  265. c.ErrorStatus(http.StatusUnprocessableEntity, err)
  266. } else {
  267. c.Error(err, "get user by name")
  268. }
  269. return nil, nil
  270. }
  271. repo, err := db.GetRepositoryByName(owner.ID, c.Params(":reponame"))
  272. if err != nil {
  273. c.NotFoundOrError(err, "get repository by name")
  274. return nil, nil
  275. }
  276. return owner, repo
  277. }
  278. func Get(c *context.APIContext) {
  279. _, repo := parseOwnerAndRepo(c)
  280. if c.Written() {
  281. return
  282. }
  283. c.JSONSuccess(repo.APIFormat(&api.Permission{
  284. Admin: c.Repo.IsAdmin(),
  285. Push: c.Repo.IsWriter(),
  286. Pull: true,
  287. }))
  288. }
  289. func Delete(c *context.APIContext) {
  290. owner, repo := parseOwnerAndRepo(c)
  291. if c.Written() {
  292. return
  293. }
  294. if owner.IsOrganization() && !owner.IsOwnedBy(c.User.ID) {
  295. c.ErrorStatus(http.StatusForbidden, errors.New("Given user is not owner of organization."))
  296. return
  297. }
  298. if err := db.DeleteRepository(owner.ID, repo.ID); err != nil {
  299. c.Error(err, "delete repository")
  300. return
  301. }
  302. log.Trace("Repository deleted: %s/%s", owner.Name, repo.Name)
  303. c.NoContent()
  304. }
  305. func ListForks(c *context.APIContext) {
  306. forks, err := c.Repo.Repository.GetForks()
  307. if err != nil {
  308. c.Error(err, "get forks")
  309. return
  310. }
  311. apiForks := make([]*api.Repository, len(forks))
  312. for i := range forks {
  313. if err := forks[i].GetOwner(); err != nil {
  314. c.Error(err, "get owner")
  315. return
  316. }
  317. apiForks[i] = forks[i].APIFormat(&api.Permission{
  318. Admin: c.User.IsAdminOfRepo(forks[i]),
  319. Push: c.User.IsWriterOfRepo(forks[i]),
  320. Pull: true,
  321. })
  322. }
  323. c.JSONSuccess(&apiForks)
  324. }
  325. func IssueTracker(c *context.APIContext, form api.EditIssueTrackerOption) {
  326. _, repo := parseOwnerAndRepo(c)
  327. if c.Written() {
  328. return
  329. }
  330. if form.EnableIssues != nil {
  331. repo.EnableIssues = *form.EnableIssues
  332. }
  333. if form.EnableExternalTracker != nil {
  334. repo.EnableExternalTracker = *form.EnableExternalTracker
  335. }
  336. if form.ExternalTrackerURL != nil {
  337. repo.ExternalTrackerURL = *form.ExternalTrackerURL
  338. }
  339. if form.TrackerURLFormat != nil {
  340. repo.ExternalTrackerFormat = *form.TrackerURLFormat
  341. }
  342. if form.TrackerIssueStyle != nil {
  343. repo.ExternalTrackerStyle = *form.TrackerIssueStyle
  344. }
  345. if err := db.UpdateRepository(repo, false); err != nil {
  346. c.Error(err, "update repository")
  347. return
  348. }
  349. c.NoContent()
  350. }
  351. func MirrorSync(c *context.APIContext) {
  352. _, repo := parseOwnerAndRepo(c)
  353. if c.Written() {
  354. return
  355. } else if !repo.IsMirror {
  356. c.NotFound()
  357. return
  358. }
  359. go db.MirrorQueue.Add(repo.ID)
  360. c.Status(http.StatusAccepted)
  361. }
  362. func Releases(c *context.APIContext) {
  363. _, repo := parseOwnerAndRepo(c)
  364. releases, err := db.GetReleasesByRepoID(repo.ID)
  365. if err != nil {
  366. c.Error(err, "get releases by repository ID")
  367. return
  368. }
  369. apiReleases := make([]*api.Release, 0, len(releases))
  370. for _, r := range releases {
  371. publisher, err := db.GetUserByID(r.PublisherID)
  372. if err != nil {
  373. c.Error(err, "get release publisher")
  374. return
  375. }
  376. r.Publisher = publisher
  377. }
  378. for _, r := range releases {
  379. apiReleases = append(apiReleases, r.APIFormat())
  380. }
  381. c.JSONSuccess(&apiReleases)
  382. }