You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

778 lines
19 KiB

10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
8 years ago
9 years ago
9 years ago
9 years ago
Better logging (#6038) (#6095) * Panic don't fatal on create new logger Fixes #5854 Signed-off-by: Andrew Thornton <art27@cantab.net> * partial broken * Update the logging infrastrcture Signed-off-by: Andrew Thornton <art27@cantab.net> * Reset the skip levels for Fatal and Error Signed-off-by: Andrew Thornton <art27@cantab.net> * broken ncsa * More log.Error fixes Signed-off-by: Andrew Thornton <art27@cantab.net> * Remove nal * set log-levels to lowercase * Make console_test test all levels * switch to lowercased levels * OK now working * Fix vetting issues * Fix lint * Fix tests * change default logging to match current gitea * Improve log testing Signed-off-by: Andrew Thornton <art27@cantab.net> * reset error skip levels to 0 * Update documentation and access logger configuration * Redirect the router log back to gitea if redirect macaron log but also allow setting the log level - i.e. TRACE * Fix broken level caching * Refactor the router log * Add Router logger * Add colorizing options * Adjust router colors * Only create logger if they will be used * update app.ini.sample * rename Attribute ColorAttribute * Change from white to green for function * Set fatal/error levels * Restore initial trace logger * Fix Trace arguments in modules/auth/auth.go * Properly handle XORMLogger * Improve admin/config page * fix fmt * Add auto-compression of old logs * Update error log levels * Remove the unnecessary skip argument from Error, Fatal and Critical * Add stacktrace support * Fix tests * Remove x/sync from vendors? * Add stderr option to console logger * Use filepath.ToSlash to protect against Windows in tests * Remove prefixed underscores from names in colors.go * Remove not implemented database logger This was removed from Gogs on 4 Mar 2016 but left in the configuration since then. * Ensure that log paths are relative to ROOT_PATH * use path.Join * rename jsonConfig to logConfig * Rename "config" to "jsonConfig" to make it clearer * Requested changes * Requested changes: XormLogger * Try to color the windows terminal If successful default to colorizing the console logs * fixup * Colorize initially too * update vendor * Colorize logs on default and remove if this is not a colorizing logger * Fix documentation * fix test * Use go-isatty to detect if on windows we are on msys or cygwin * Fix spelling mistake * Add missing vendors * More changes * Rationalise the ANSI writer protection * Adjust colors on advice from @0x5c * Make Flags a comma separated list * Move to use the windows constant for ENABLE_VIRTUAL_TERMINAL_PROCESSING * Ensure matching is done on the non-colored message - to simpify EXPRESSION
5 years ago
10 years ago
10 years ago
10 years ago
8 years ago
  1. // Copyright 2014 The Gogs Authors. All rights reserved.
  2. // Copyright 2019 The Gitea Authors. All rights reserved.
  3. // Use of this source code is governed by a MIT-style
  4. // license that can be found in the LICENSE file.
  5. package models
  6. import (
  7. "errors"
  8. "fmt"
  9. "os"
  10. "strings"
  11. "code.gitea.io/gitea/modules/log"
  12. "code.gitea.io/gitea/modules/structs"
  13. "github.com/Unknwon/com"
  14. "github.com/go-xorm/builder"
  15. "github.com/go-xorm/xorm"
  16. )
  17. var (
  18. // ErrTeamNotExist team does not exist
  19. ErrTeamNotExist = errors.New("Team does not exist")
  20. )
  21. // IsOwnedBy returns true if given user is in the owner team.
  22. func (org *User) IsOwnedBy(uid int64) (bool, error) {
  23. return IsOrganizationOwner(org.ID, uid)
  24. }
  25. // IsOrgMember returns true if given user is member of organization.
  26. func (org *User) IsOrgMember(uid int64) (bool, error) {
  27. return IsOrganizationMember(org.ID, uid)
  28. }
  29. func (org *User) getTeam(e Engine, name string) (*Team, error) {
  30. return getTeam(e, org.ID, name)
  31. }
  32. // GetTeam returns named team of organization.
  33. func (org *User) GetTeam(name string) (*Team, error) {
  34. return org.getTeam(x, name)
  35. }
  36. func (org *User) getOwnerTeam(e Engine) (*Team, error) {
  37. return org.getTeam(e, ownerTeamName)
  38. }
  39. // GetOwnerTeam returns owner team of organization.
  40. func (org *User) GetOwnerTeam() (*Team, error) {
  41. return org.getOwnerTeam(x)
  42. }
  43. func (org *User) getTeams(e Engine) error {
  44. return e.
  45. Where("org_id=?", org.ID).
  46. OrderBy("CASE WHEN name LIKE '" + ownerTeamName + "' THEN '' ELSE name END").
  47. Find(&org.Teams)
  48. }
  49. // GetTeams returns all teams that belong to organization.
  50. func (org *User) GetTeams() error {
  51. return org.getTeams(x)
  52. }
  53. // GetMembers returns all members of organization.
  54. func (org *User) GetMembers() error {
  55. ous, err := GetOrgUsersByOrgID(org.ID)
  56. if err != nil {
  57. return err
  58. }
  59. var ids = make([]int64, len(ous))
  60. for i, ou := range ous {
  61. ids[i] = ou.UID
  62. }
  63. org.Members, err = GetUsersByIDs(ids)
  64. return err
  65. }
  66. // AddMember adds new member to organization.
  67. func (org *User) AddMember(uid int64) error {
  68. return AddOrgUser(org.ID, uid)
  69. }
  70. // RemoveMember removes member from organization.
  71. func (org *User) RemoveMember(uid int64) error {
  72. return RemoveOrgUser(org.ID, uid)
  73. }
  74. func (org *User) removeOrgRepo(e Engine, repoID int64) error {
  75. return removeOrgRepo(e, org.ID, repoID)
  76. }
  77. // RemoveOrgRepo removes all team-repository relations of organization.
  78. func (org *User) RemoveOrgRepo(repoID int64) error {
  79. return org.removeOrgRepo(x, repoID)
  80. }
  81. // CreateOrganization creates record of a new organization.
  82. func CreateOrganization(org, owner *User) (err error) {
  83. if !owner.CanCreateOrganization() {
  84. return ErrUserNotAllowedCreateOrg{}
  85. }
  86. if err = IsUsableUsername(org.Name); err != nil {
  87. return err
  88. }
  89. isExist, err := IsUserExist(0, org.Name)
  90. if err != nil {
  91. return err
  92. } else if isExist {
  93. return ErrUserAlreadyExist{org.Name}
  94. }
  95. org.LowerName = strings.ToLower(org.Name)
  96. if org.Rands, err = GetUserSalt(); err != nil {
  97. return err
  98. }
  99. if org.Salt, err = GetUserSalt(); err != nil {
  100. return err
  101. }
  102. org.UseCustomAvatar = true
  103. org.MaxRepoCreation = -1
  104. org.NumTeams = 1
  105. org.NumMembers = 1
  106. org.Type = UserTypeOrganization
  107. sess := x.NewSession()
  108. defer sess.Close()
  109. if err = sess.Begin(); err != nil {
  110. return err
  111. }
  112. if _, err = sess.Insert(org); err != nil {
  113. return fmt.Errorf("insert organization: %v", err)
  114. }
  115. if err = org.generateRandomAvatar(sess); err != nil {
  116. return fmt.Errorf("generate random avatar: %v", err)
  117. }
  118. // Add initial creator to organization and owner team.
  119. if _, err = sess.Insert(&OrgUser{
  120. UID: owner.ID,
  121. OrgID: org.ID,
  122. }); err != nil {
  123. return fmt.Errorf("insert org-user relation: %v", err)
  124. }
  125. // Create default owner team.
  126. t := &Team{
  127. OrgID: org.ID,
  128. LowerName: strings.ToLower(ownerTeamName),
  129. Name: ownerTeamName,
  130. Authorize: AccessModeOwner,
  131. NumMembers: 1,
  132. }
  133. if _, err = sess.Insert(t); err != nil {
  134. return fmt.Errorf("insert owner team: %v", err)
  135. }
  136. // insert units for team
  137. var units = make([]TeamUnit, 0, len(allRepUnitTypes))
  138. for _, tp := range allRepUnitTypes {
  139. units = append(units, TeamUnit{
  140. OrgID: org.ID,
  141. TeamID: t.ID,
  142. Type: tp,
  143. })
  144. }
  145. if _, err = sess.Insert(&units); err != nil {
  146. sess.Rollback()
  147. return err
  148. }
  149. if _, err = sess.Insert(&TeamUser{
  150. UID: owner.ID,
  151. OrgID: org.ID,
  152. TeamID: t.ID,
  153. }); err != nil {
  154. return fmt.Errorf("insert team-user relation: %v", err)
  155. }
  156. return sess.Commit()
  157. }
  158. // GetOrgByName returns organization by given name.
  159. func GetOrgByName(name string) (*User, error) {
  160. if len(name) == 0 {
  161. return nil, ErrOrgNotExist{0, name}
  162. }
  163. u := &User{
  164. LowerName: strings.ToLower(name),
  165. Type: UserTypeOrganization,
  166. }
  167. has, err := x.Get(u)
  168. if err != nil {
  169. return nil, err
  170. } else if !has {
  171. return nil, ErrOrgNotExist{0, name}
  172. }
  173. return u, nil
  174. }
  175. // CountOrganizations returns number of organizations.
  176. func CountOrganizations() int64 {
  177. count, _ := x.
  178. Where("type=1").
  179. Count(new(User))
  180. return count
  181. }
  182. // DeleteOrganization completely and permanently deletes everything of organization.
  183. func DeleteOrganization(org *User) (err error) {
  184. sess := x.NewSession()
  185. defer sess.Close()
  186. if err = sess.Begin(); err != nil {
  187. return err
  188. }
  189. if err = deleteOrg(sess, org); err != nil {
  190. if IsErrUserOwnRepos(err) {
  191. return err
  192. } else if err != nil {
  193. return fmt.Errorf("deleteOrg: %v", err)
  194. }
  195. }
  196. return sess.Commit()
  197. }
  198. func deleteOrg(e *xorm.Session, u *User) error {
  199. if !u.IsOrganization() {
  200. return fmt.Errorf("You can't delete none organization user: %s", u.Name)
  201. }
  202. // Check ownership of repository.
  203. count, err := getRepositoryCount(e, u)
  204. if err != nil {
  205. return fmt.Errorf("GetRepositoryCount: %v", err)
  206. } else if count > 0 {
  207. return ErrUserOwnRepos{UID: u.ID}
  208. }
  209. if err := deleteBeans(e,
  210. &Team{OrgID: u.ID},
  211. &OrgUser{OrgID: u.ID},
  212. &TeamUser{OrgID: u.ID},
  213. &TeamUnit{OrgID: u.ID},
  214. ); err != nil {
  215. return fmt.Errorf("deleteBeans: %v", err)
  216. }
  217. if _, err = e.ID(u.ID).Delete(new(User)); err != nil {
  218. return fmt.Errorf("Delete: %v", err)
  219. }
  220. // FIXME: system notice
  221. // Note: There are something just cannot be roll back,
  222. // so just keep error logs of those operations.
  223. path := UserPath(u.Name)
  224. if err := os.RemoveAll(path); err != nil {
  225. return fmt.Errorf("Failed to RemoveAll %s: %v", path, err)
  226. }
  227. if len(u.Avatar) > 0 {
  228. avatarPath := u.CustomAvatarPath()
  229. if com.IsExist(avatarPath) {
  230. if err := os.Remove(avatarPath); err != nil {
  231. return fmt.Errorf("Failed to remove %s: %v", avatarPath, err)
  232. }
  233. }
  234. }
  235. return nil
  236. }
  237. // ________ ____ ___
  238. // \_____ \_______ ____ | | \______ ___________
  239. // / | \_ __ \/ ___\| | / ___// __ \_ __ \
  240. // / | \ | \/ /_/ > | /\___ \\ ___/| | \/
  241. // \_______ /__| \___ /|______//____ >\___ >__|
  242. // \/ /_____/ \/ \/
  243. // OrgUser represents an organization-user relation.
  244. type OrgUser struct {
  245. ID int64 `xorm:"pk autoincr"`
  246. UID int64 `xorm:"INDEX UNIQUE(s)"`
  247. OrgID int64 `xorm:"INDEX UNIQUE(s)"`
  248. IsPublic bool `xorm:"INDEX"`
  249. }
  250. func isOrganizationOwner(e Engine, orgID, uid int64) (bool, error) {
  251. ownerTeam := &Team{
  252. OrgID: orgID,
  253. Name: ownerTeamName,
  254. }
  255. if has, err := e.Get(ownerTeam); err != nil {
  256. return false, err
  257. } else if !has {
  258. log.Error("Organization does not have owner team: %d", orgID)
  259. return false, nil
  260. }
  261. return isTeamMember(e, orgID, ownerTeam.ID, uid)
  262. }
  263. // IsOrganizationOwner returns true if given user is in the owner team.
  264. func IsOrganizationOwner(orgID, uid int64) (bool, error) {
  265. return isOrganizationOwner(x, orgID, uid)
  266. }
  267. // IsOrganizationMember returns true if given user is member of organization.
  268. func IsOrganizationMember(orgID, uid int64) (bool, error) {
  269. return isOrganizationMember(x, orgID, uid)
  270. }
  271. func isOrganizationMember(e Engine, orgID, uid int64) (bool, error) {
  272. return e.
  273. Where("uid=?", uid).
  274. And("org_id=?", orgID).
  275. Table("org_user").
  276. Exist()
  277. }
  278. // IsPublicMembership returns true if given user public his/her membership.
  279. func IsPublicMembership(orgID, uid int64) (bool, error) {
  280. return x.
  281. Where("uid=?", uid).
  282. And("org_id=?", orgID).
  283. And("is_public=?", true).
  284. Table("org_user").
  285. Exist()
  286. }
  287. func getOrgsByUserID(sess *xorm.Session, userID int64, showAll bool) ([]*User, error) {
  288. orgs := make([]*User, 0, 10)
  289. if !showAll {
  290. sess.And("`org_user`.is_public=?", true)
  291. }
  292. return orgs, sess.
  293. And("`org_user`.uid=?", userID).
  294. Join("INNER", "`org_user`", "`org_user`.org_id=`user`.id").
  295. Asc("`user`.name").
  296. Find(&orgs)
  297. }
  298. // GetOrgsByUserID returns a list of organizations that the given user ID
  299. // has joined.
  300. func GetOrgsByUserID(userID int64, showAll bool) ([]*User, error) {
  301. sess := x.NewSession()
  302. defer sess.Close()
  303. return getOrgsByUserID(sess, userID, showAll)
  304. }
  305. func getOwnedOrgsByUserID(sess *xorm.Session, userID int64) ([]*User, error) {
  306. orgs := make([]*User, 0, 10)
  307. return orgs, sess.
  308. Join("INNER", "`team_user`", "`team_user`.org_id=`user`.id").
  309. Join("INNER", "`team`", "`team`.id=`team_user`.team_id").
  310. Where("`team_user`.uid=?", userID).
  311. And("`team`.authorize=?", AccessModeOwner).
  312. Asc("`user`.name").
  313. Find(&orgs)
  314. }
  315. // HasOrgVisible tells if the given user can see the given org
  316. func HasOrgVisible(org *User, user *User) bool {
  317. // Not SignedUser
  318. if user == nil {
  319. if org.Visibility == structs.VisibleTypePublic {
  320. return true
  321. }
  322. return false
  323. }
  324. if user.IsAdmin {
  325. return true
  326. }
  327. if org.Visibility == structs.VisibleTypePrivate && !org.IsUserPartOfOrg(user.ID) {
  328. return false
  329. }
  330. return true
  331. }
  332. // HasOrgsVisible tells if the given user can see at least one of the orgs provided
  333. func HasOrgsVisible(orgs []*User, user *User) bool {
  334. if len(orgs) == 0 {
  335. return false
  336. }
  337. for _, org := range orgs {
  338. if HasOrgVisible(org, user) {
  339. return true
  340. }
  341. }
  342. return false
  343. }
  344. // GetOwnedOrgsByUserID returns a list of organizations are owned by given user ID.
  345. func GetOwnedOrgsByUserID(userID int64) ([]*User, error) {
  346. sess := x.NewSession()
  347. defer sess.Close()
  348. return getOwnedOrgsByUserID(sess, userID)
  349. }
  350. // GetOwnedOrgsByUserIDDesc returns a list of organizations are owned by
  351. // given user ID, ordered descending by the given condition.
  352. func GetOwnedOrgsByUserIDDesc(userID int64, desc string) ([]*User, error) {
  353. return getOwnedOrgsByUserID(x.Desc(desc), userID)
  354. }
  355. // GetOrgUsersByUserID returns all organization-user relations by user ID.
  356. func GetOrgUsersByUserID(uid int64, all bool) ([]*OrgUser, error) {
  357. ous := make([]*OrgUser, 0, 10)
  358. sess := x.
  359. Join("LEFT", "`user`", "`org_user`.org_id=`user`.id").
  360. Where("`org_user`.uid=?", uid)
  361. if !all {
  362. // Only show public organizations
  363. sess.And("is_public=?", true)
  364. }
  365. err := sess.
  366. Asc("`user`.name").
  367. Find(&ous)
  368. return ous, err
  369. }
  370. // GetOrgUsersByOrgID returns all organization-user relations by organization ID.
  371. func GetOrgUsersByOrgID(orgID int64) ([]*OrgUser, error) {
  372. return getOrgUsersByOrgID(x, orgID)
  373. }
  374. func getOrgUsersByOrgID(e Engine, orgID int64) ([]*OrgUser, error) {
  375. ous := make([]*OrgUser, 0, 10)
  376. err := e.
  377. Where("org_id=?", orgID).
  378. Find(&ous)
  379. return ous, err
  380. }
  381. // ChangeOrgUserStatus changes public or private membership status.
  382. func ChangeOrgUserStatus(orgID, uid int64, public bool) error {
  383. ou := new(OrgUser)
  384. has, err := x.
  385. Where("uid=?", uid).
  386. And("org_id=?", orgID).
  387. Get(ou)
  388. if err != nil {
  389. return err
  390. } else if !has {
  391. return nil
  392. }
  393. ou.IsPublic = public
  394. _, err = x.ID(ou.ID).Cols("is_public").Update(ou)
  395. return err
  396. }
  397. // AddOrgUser adds new user to given organization.
  398. func AddOrgUser(orgID, uid int64) error {
  399. isAlreadyMember, err := IsOrganizationMember(orgID, uid)
  400. if err != nil || isAlreadyMember {
  401. return err
  402. }
  403. sess := x.NewSession()
  404. defer sess.Close()
  405. if err := sess.Begin(); err != nil {
  406. return err
  407. }
  408. ou := &OrgUser{
  409. UID: uid,
  410. OrgID: orgID,
  411. }
  412. if _, err := sess.Insert(ou); err != nil {
  413. sess.Rollback()
  414. return err
  415. } else if _, err = sess.Exec("UPDATE `user` SET num_members = num_members + 1 WHERE id = ?", orgID); err != nil {
  416. sess.Rollback()
  417. return err
  418. }
  419. return sess.Commit()
  420. }
  421. func removeOrgUser(sess *xorm.Session, orgID, userID int64) error {
  422. ou := new(OrgUser)
  423. has, err := sess.
  424. Where("uid=?", userID).
  425. And("org_id=?", orgID).
  426. Get(ou)
  427. if err != nil {
  428. return fmt.Errorf("get org-user: %v", err)
  429. } else if !has {
  430. return nil
  431. }
  432. org, err := getUserByID(sess, orgID)
  433. if err != nil {
  434. return fmt.Errorf("GetUserByID [%d]: %v", orgID, err)
  435. }
  436. // Check if the user to delete is the last member in owner team.
  437. if isOwner, err := isOrganizationOwner(sess, orgID, userID); err != nil {
  438. return err
  439. } else if isOwner {
  440. t, err := org.getOwnerTeam(sess)
  441. if err != nil {
  442. return err
  443. }
  444. if t.NumMembers == 1 {
  445. if err := t.getMembers(sess); err != nil {
  446. return err
  447. }
  448. if t.Members[0].ID == userID {
  449. return ErrLastOrgOwner{UID: userID}
  450. }
  451. }
  452. }
  453. if _, err := sess.ID(ou.ID).Delete(ou); err != nil {
  454. return err
  455. } else if _, err = sess.Exec("UPDATE `user` SET num_members=num_members-1 WHERE id=?", orgID); err != nil {
  456. return err
  457. }
  458. // Delete all repository accesses and unwatch them.
  459. env, err := org.accessibleReposEnv(sess, userID)
  460. if err != nil {
  461. return fmt.Errorf("AccessibleReposEnv: %v", err)
  462. }
  463. repoIDs, err := env.RepoIDs(1, org.NumRepos)
  464. if err != nil {
  465. return fmt.Errorf("GetUserRepositories [%d]: %v", userID, err)
  466. }
  467. for _, repoID := range repoIDs {
  468. if err = watchRepo(sess, userID, repoID, false); err != nil {
  469. return err
  470. }
  471. }
  472. if len(repoIDs) > 0 {
  473. if _, err = sess.
  474. Where("user_id = ?", userID).
  475. In("repo_id", repoIDs).
  476. Delete(new(Access)); err != nil {
  477. return err
  478. }
  479. }
  480. // Delete member in his/her teams.
  481. teams, err := getUserOrgTeams(sess, org.ID, userID)
  482. if err != nil {
  483. return err
  484. }
  485. for _, t := range teams {
  486. if err = removeTeamMember(sess, t, userID); err != nil {
  487. return err
  488. }
  489. }
  490. return nil
  491. }
  492. // RemoveOrgUser removes user from given organization.
  493. func RemoveOrgUser(orgID, userID int64) error {
  494. sess := x.NewSession()
  495. defer sess.Close()
  496. if err := sess.Begin(); err != nil {
  497. return err
  498. }
  499. if err := removeOrgUser(sess, orgID, userID); err != nil {
  500. return err
  501. }
  502. return sess.Commit()
  503. }
  504. func removeOrgRepo(e Engine, orgID, repoID int64) error {
  505. teamRepos := make([]*TeamRepo, 0, 10)
  506. if err := e.Find(&teamRepos, &TeamRepo{OrgID: orgID, RepoID: repoID}); err != nil {
  507. return err
  508. }
  509. if len(teamRepos) == 0 {
  510. return nil
  511. }
  512. if _, err := e.Delete(&TeamRepo{
  513. OrgID: orgID,
  514. RepoID: repoID,
  515. }); err != nil {
  516. return err
  517. }
  518. teamIDs := make([]int64, len(teamRepos))
  519. for i, teamRepo := range teamRepos {
  520. teamIDs[i] = teamRepo.TeamID
  521. }
  522. _, err := e.Decr("num_repos").In("id", teamIDs).Update(new(Team))
  523. return err
  524. }
  525. func (org *User) getUserTeams(e Engine, userID int64, cols ...string) ([]*Team, error) {
  526. teams := make([]*Team, 0, org.NumTeams)
  527. return teams, e.
  528. Where("`team_user`.org_id = ?", org.ID).
  529. Join("INNER", "team_user", "`team_user`.team_id = team.id").
  530. Join("INNER", "`user`", "`user`.id=team_user.uid").
  531. And("`team_user`.uid = ?", userID).
  532. Asc("`user`.name").
  533. Cols(cols...).
  534. Find(&teams)
  535. }
  536. func (org *User) getUserTeamIDs(e Engine, userID int64) ([]int64, error) {
  537. teamIDs := make([]int64, 0, org.NumTeams)
  538. return teamIDs, e.
  539. Table("team").
  540. Cols("team.id").
  541. Where("`team_user`.org_id = ?", org.ID).
  542. Join("INNER", "team_user", "`team_user`.team_id = team.id").
  543. And("`team_user`.uid = ?", userID).
  544. Find(&teamIDs)
  545. }
  546. // TeamsWithAccessToRepo returns all teamsthat have given access level to the repository.
  547. func (org *User) TeamsWithAccessToRepo(repoID int64, mode AccessMode) ([]*Team, error) {
  548. return GetTeamsWithAccessToRepo(org.ID, repoID, mode)
  549. }
  550. // GetUserTeamIDs returns of all team IDs of the organization that user is member of.
  551. func (org *User) GetUserTeamIDs(userID int64) ([]int64, error) {
  552. return org.getUserTeamIDs(x, userID)
  553. }
  554. // GetUserTeams returns all teams that belong to user,
  555. // and that the user has joined.
  556. func (org *User) GetUserTeams(userID int64) ([]*Team, error) {
  557. return org.getUserTeams(x, userID)
  558. }
  559. // AccessibleReposEnvironment operations involving the repositories that are
  560. // accessible to a particular user
  561. type AccessibleReposEnvironment interface {
  562. CountRepos() (int64, error)
  563. RepoIDs(page, pageSize int) ([]int64, error)
  564. Repos(page, pageSize int) ([]*Repository, error)
  565. MirrorRepos() ([]*Repository, error)
  566. AddKeyword(keyword string)
  567. }
  568. type accessibleReposEnv struct {
  569. org *User
  570. userID int64
  571. teamIDs []int64
  572. e Engine
  573. keyword string
  574. }
  575. // AccessibleReposEnv an AccessibleReposEnvironment for the repositories in `org`
  576. // that are accessible to the specified user.
  577. func (org *User) AccessibleReposEnv(userID int64) (AccessibleReposEnvironment, error) {
  578. return org.accessibleReposEnv(x, userID)
  579. }
  580. func (org *User) accessibleReposEnv(e Engine, userID int64) (AccessibleReposEnvironment, error) {
  581. teamIDs, err := org.getUserTeamIDs(e, userID)
  582. if err != nil {
  583. return nil, err
  584. }
  585. return &accessibleReposEnv{
  586. org: org,
  587. userID: userID,
  588. teamIDs: teamIDs,
  589. e: e,
  590. }, nil
  591. }
  592. func (env *accessibleReposEnv) cond() builder.Cond {
  593. var cond builder.Cond = builder.Eq{
  594. "`repository`.owner_id": env.org.ID,
  595. "`repository`.is_private": false,
  596. }
  597. if len(env.teamIDs) > 0 {
  598. cond = cond.Or(builder.In("team_repo.team_id", env.teamIDs))
  599. }
  600. if env.keyword != "" {
  601. cond = cond.And(builder.Like{"`repository`.lower_name", strings.ToLower(env.keyword)})
  602. }
  603. return cond
  604. }
  605. func (env *accessibleReposEnv) CountRepos() (int64, error) {
  606. repoCount, err := env.e.
  607. Join("INNER", "team_repo", "`team_repo`.repo_id=`repository`.id").
  608. Where(env.cond()).
  609. Distinct("`repository`.id").
  610. Count(&Repository{})
  611. if err != nil {
  612. return 0, fmt.Errorf("count user repositories in organization: %v", err)
  613. }
  614. return repoCount, nil
  615. }
  616. func (env *accessibleReposEnv) RepoIDs(page, pageSize int) ([]int64, error) {
  617. if page <= 0 {
  618. page = 1
  619. }
  620. repoIDs := make([]int64, 0, pageSize)
  621. return repoIDs, env.e.
  622. Table("repository").
  623. Join("INNER", "team_repo", "`team_repo`.repo_id=`repository`.id").
  624. Where(env.cond()).
  625. GroupBy("`repository`.id,`repository`.updated_unix").
  626. OrderBy("updated_unix DESC").
  627. Limit(pageSize, (page-1)*pageSize).
  628. Cols("`repository`.id").
  629. Find(&repoIDs)
  630. }
  631. func (env *accessibleReposEnv) Repos(page, pageSize int) ([]*Repository, error) {
  632. repoIDs, err := env.RepoIDs(page, pageSize)
  633. if err != nil {
  634. return nil, fmt.Errorf("GetUserRepositoryIDs: %v", err)
  635. }
  636. repos := make([]*Repository, 0, len(repoIDs))
  637. if len(repoIDs) == 0 {
  638. return repos, nil
  639. }
  640. return repos, env.e.
  641. In("`repository`.id", repoIDs).
  642. Find(&repos)
  643. }
  644. func (env *accessibleReposEnv) MirrorRepoIDs() ([]int64, error) {
  645. repoIDs := make([]int64, 0, 10)
  646. return repoIDs, env.e.
  647. Table("repository").
  648. Join("INNER", "team_repo", "`team_repo`.repo_id=`repository`.id AND `repository`.is_mirror=?", true).
  649. Where(env.cond()).
  650. GroupBy("`repository`.id, `repository`.updated_unix").
  651. OrderBy("updated_unix DESC").
  652. Cols("`repository`.id").
  653. Find(&repoIDs)
  654. }
  655. func (env *accessibleReposEnv) MirrorRepos() ([]*Repository, error) {
  656. repoIDs, err := env.MirrorRepoIDs()
  657. if err != nil {
  658. return nil, fmt.Errorf("MirrorRepoIDs: %v", err)
  659. }
  660. repos := make([]*Repository, 0, len(repoIDs))
  661. if len(repoIDs) == 0 {
  662. return repos, nil
  663. }
  664. return repos, env.e.
  665. In("`repository`.id", repoIDs).
  666. Find(&repos)
  667. }
  668. func (env *accessibleReposEnv) AddKeyword(keyword string) {
  669. env.keyword = keyword
  670. }