diff options
author | Sergio Benitez <sbenitez@mit.edu> | 2015-09-09 13:44:51 -0700 |
---|---|---|
committer | Sergio Benitez <sbenitez@mit.edu> | 2015-09-09 13:44:51 -0700 |
commit | 964d0262ff353db6a50ed5be83ebd22f71aa6e69 (patch) | |
tree | 8cbab6b6a9b4f62cbe9acb2a0b8752b531633362 /models | |
parent | 079a2d68db5c843ef2dbba65aeca46d5887d6b02 (diff) | |
parent | b75d0378cbbf0523963fd9bc749543244be7392b (diff) | |
download | gitea-964d0262ff353db6a50ed5be83ebd22f71aa6e69.tar.gz gitea-964d0262ff353db6a50ed5be83ebd22f71aa6e69.zip |
Merged conflicts.
Diffstat (limited to 'models')
-rw-r--r-- | models/issue.go | 2 | ||||
-rw-r--r-- | models/models.go | 9 | ||||
-rw-r--r-- | models/models_tidb.go | 16 | ||||
-rw-r--r-- | models/org.go | 93 | ||||
-rw-r--r-- | models/repo.go | 23 | ||||
-rw-r--r-- | models/user.go | 178 |
6 files changed, 194 insertions, 127 deletions
diff --git a/models/issue.go b/models/issue.go index dbc63b9574..00db990d8f 100644 --- a/models/issue.go +++ b/models/issue.go @@ -758,7 +758,7 @@ func GetUserIssueStats(repoID, uid int64, repoIDs []int64, filterMode int, isPul queryStr := "SELECT COUNT(*) FROM `issue` " baseCond := " WHERE issue.is_closed=?" - if repoID > 0 { + if repoID > 0 || len(repoIDs) == 0 { baseCond += " AND issue.repo_id=" + com.ToStr(repoID) } else { baseCond += " AND issue.repo_id IN (" + strings.Join(base.Int64sToStrings(repoIDs), ",") + ")" diff --git a/models/models.go b/models/models.go index b446dcde16..be5f335115 100644 --- a/models/models.go +++ b/models/models.go @@ -72,6 +72,7 @@ var ( } EnableSQLite3 bool + EnableTidb bool ) func init() { @@ -143,6 +144,14 @@ func getEngine() (*xorm.Engine, error) { return nil, fmt.Errorf("Fail to create directories: %v", err) } cnnstr = "file:" + DbCfg.Path + "?cache=shared&mode=rwc" + case "tidb": + if !EnableTidb { + return nil, fmt.Errorf("Unknown database type: %s", DbCfg.Type) + } + if err := os.MkdirAll(path.Dir(DbCfg.Path), os.ModePerm); err != nil { + return nil, fmt.Errorf("Fail to create directories: %v", err) + } + cnnstr = "goleveldb://" + DbCfg.Path default: return nil, fmt.Errorf("Unknown database type: %s", DbCfg.Type) } diff --git a/models/models_tidb.go b/models/models_tidb.go new file mode 100644 index 0000000000..d99884e9e8 --- /dev/null +++ b/models/models_tidb.go @@ -0,0 +1,16 @@ +// +build tidb go1.4.2 + +// Copyright 2015 The Gogs Authors. All rights reserved. +// Use of this source code is governed by a MIT-style +// license that can be found in the LICENSE file. + +package models + +import ( + _ "github.com/go-xorm/tidb" + _ "github.com/pingcap/tidb" +) + +func init() { + EnableTidb = true +} diff --git a/models/org.go b/models/org.go index dfd720fade..b45dcafb21 100644 --- a/models/org.go +++ b/models/org.go @@ -10,7 +10,7 @@ import ( "os" "strings" - "github.com/gogits/gogs/modules/base" + "github.com/go-xorm/xorm" ) var ( @@ -93,17 +93,6 @@ func (org *User) RemoveOrgRepo(repoID int64) error { return org.removeOrgRepo(x, repoID) } -// IsOrgEmailUsed returns true if the e-mail has been used in organization account. -func IsOrgEmailUsed(email string) (bool, error) { - if len(email) == 0 { - return false, nil - } - return x.Get(&User{ - Email: email, - Type: ORGANIZATION, - }) -} - // CreateOrganization creates record of a new organization. func CreateOrganization(org, owner *User) (err error) { if err = IsUsableName(org.Name); err != nil { @@ -117,18 +106,9 @@ func CreateOrganization(org, owner *User) (err error) { return ErrUserAlreadyExist{org.Name} } - isExist, err = IsOrgEmailUsed(org.Email) - if err != nil { - return err - } else if isExist { - return ErrEmailAlreadyUsed{org.Email} - } - org.LowerName = strings.ToLower(org.Name) org.FullName = org.Name - org.Avatar = base.EncodeMd5(org.Email) - org.AvatarEmail = org.Email - // No password for organization. + org.UseCustomAvatar = true org.NumTeams = 1 org.NumMembers = 1 @@ -141,6 +121,17 @@ func CreateOrganization(org, owner *User) (err error) { if _, err = sess.Insert(org); err != nil { return fmt.Errorf("insert organization: %v", err) } + org.GenerateRandomAvatar() + + // Add initial creator to organization and owner team. + if _, err = sess.Insert(&OrgUser{ + Uid: owner.Id, + OrgID: org.Id, + IsOwner: true, + NumTeams: 1, + }); err != nil { + return fmt.Errorf("insert org-user relation: %v", err) + } // Create default owner team. t := &Team{ @@ -154,23 +145,11 @@ func CreateOrganization(org, owner *User) (err error) { return fmt.Errorf("insert owner team: %v", err) } - // Add initial creator to organization and owner team. - ou := &OrgUser{ - Uid: owner.Id, - OrgID: org.Id, - IsOwner: true, - NumTeams: 1, - } - if _, err = sess.Insert(ou); err != nil { - return fmt.Errorf("insert org-user relation: %v", err) - } - - tu := &TeamUser{ + if _, err = sess.Insert(&TeamUser{ Uid: owner.Id, OrgID: org.Id, TeamID: t.ID, - } - if _, err = sess.Insert(tu); err != nil { + }); err != nil { return fmt.Errorf("insert team-user relation: %v", err) } @@ -212,7 +191,6 @@ func GetOrganizations(num, offset int) ([]*User, error) { return orgs, err } -// TODO: need some kind of mechanism to record failure. // DeleteOrganization completely and permanently deletes everything of organization. func DeleteOrganization(org *User) (err error) { if err := DeleteUser(org); err != nil { @@ -220,23 +198,23 @@ func DeleteOrganization(org *User) (err error) { } sess := x.NewSession() - defer sess.Close() + defer sessionRelease(sess) if err = sess.Begin(); err != nil { return err } - if _, err = sess.Delete(&Team{OrgID: org.Id}); err != nil { - sess.Rollback() - return err - } - if _, err = sess.Delete(&OrgUser{OrgID: org.Id}); err != nil { - sess.Rollback() - return err + if err = deleteBeans(sess, + &Team{OrgID: org.Id}, + &OrgUser{OrgID: org.Id}, + &TeamUser{OrgID: org.Id}, + ); err != nil { + return fmt.Errorf("deleteBeans: %v", err) } - if _, err = sess.Delete(&TeamUser{OrgID: org.Id}); err != nil { - sess.Rollback() - return err + + if err = deleteUser(sess, org); err != nil { + return fmt.Errorf("deleteUser: %v", err) } + return sess.Commit() } @@ -275,6 +253,25 @@ func IsPublicMembership(orgId, uid int64) bool { return has } +func getOwnedOrgsByUserID(sess *xorm.Session, userID int64) ([]*User, error) { + orgs := make([]*User, 0, 10) + return orgs, sess.Where("`org_user`.uid=?", userID).And("`org_user`.is_owner=?", true). + Join("INNER", "`org_user`", "`org_user`.org_id=`user`.id").Find(&orgs) +} + +// GetOwnedOrgsByUserID returns a list of organizations are owned by given user ID. +func GetOwnedOrgsByUserID(userID int64) ([]*User, error) { + sess := x.NewSession() + return getOwnedOrgsByUserID(sess, userID) +} + +// GetOwnedOrganizationsByUserIDDesc returns a list of organizations are owned by +// given user ID and descring order by given condition. +func GetOwnedOrgsByUserIDDesc(userID int64, desc string) ([]*User, error) { + sess := x.NewSession() + return getOwnedOrgsByUserID(sess.Desc(desc), userID) +} + // GetOrgUsersByUserId returns all organization-user relations by user ID. func GetOrgUsersByUserId(uid int64) ([]*OrgUser, error) { ous := make([]*OrgUser, 0, 10) diff --git a/models/repo.go b/models/repo.go index 9fb5607db7..a22c6e17a7 100644 --- a/models/repo.go +++ b/models/repo.go @@ -272,6 +272,11 @@ func (repo *Repository) IsOwnedBy(userID int64) bool { return repo.OwnerID == userID } +// CanBeForked returns true if repository meets the requirements of being forked. +func (repo *Repository) CanBeForked() bool { + return !repo.IsBare && !repo.IsMirror +} + func (repo *Repository) NextIssueIndex() int64 { return int64(repo.NumIssues+repo.NumPulls) + 1 } @@ -465,6 +470,16 @@ func MigrateRepository(u *User, name, desc string, private, mirror bool, url str return repo, fmt.Errorf("create update hook: %v", err) } + // Check if repository is empty. + _, stderr, err = com.ExecCmdDir(repoPath, "git", "log", "-1") + if err != nil { + if strings.Contains(stderr, "fatal: bad default revision 'HEAD'") { + repo.IsBare = true + } else { + return repo, fmt.Errorf("check bare: %v - %s", err, stderr) + } + } + // Check if repository has master branch, if so set it to default branch. gitRepo, err := git.OpenRepository(repoPath) if err != nil { @@ -615,7 +630,7 @@ func initRepository(e Engine, repoPath string, u *User, repo *Repository, opts C } tmpDir := filepath.Join(os.TempDir(), "gogs-"+repo.Name+"-"+com.ToStr(time.Now().Nanosecond())) - fmt.Println(tmpDir) + // Initialize repository according to user's choice. if opts.AutoInit { os.MkdirAll(tmpDir, os.ModePerm) @@ -1185,9 +1200,13 @@ func GetRecentUpdatedRepositories(page int) (repos []*Repository, err error) { Where("is_private=?", false).Limit(setting.ExplorePagingNum).Desc("updated").Find(&repos) } +func getRepositoryCount(e Engine, u *User) (int64, error) { + return x.Count(&Repository{OwnerID: u.Id}) +} + // GetRepositoryCount returns the total number of repositories of user. func GetRepositoryCount(u *User) (int64, error) { - return x.Count(&Repository{OwnerID: u.Id}) + return getRepositoryCount(x, u) } type SearchOption struct { diff --git a/models/user.go b/models/user.go index 423b30f16e..da2f49a1cc 100644 --- a/models/user.go +++ b/models/user.go @@ -55,12 +55,13 @@ type User struct { Name string `xorm:"UNIQUE NOT NULL"` FullName string // Email is the primary email address (to be used for communication). - Email string `xorm:"UNIQUE(s) NOT NULL"` + Email string `xorm:"NOT NULL"` Passwd string `xorm:"NOT NULL"` LoginType LoginType LoginSource int64 `xorm:"NOT NULL DEFAULT 0"` LoginName string - Type UserType `xorm:"UNIQUE(s)"` + Type UserType + OwnedOrgs []*User `xorm:"-"` Orgs []*User `xorm:"-"` Repos []*Repository `xorm:"-"` Location string @@ -132,42 +133,56 @@ func (u *User) HomeLink() string { return setting.AppSubUrl + "/" + u.Name } +// CustomAvatarPath returns user custom avatar file path. +func (u *User) CustomAvatarPath() string { + return filepath.Join(setting.AvatarUploadPath, com.ToStr(u.Id)) +} + +// GenerateRandomAvatar generates a random avatar for user. +func (u *User) GenerateRandomAvatar() error { + seed := u.Email + if len(seed) == 0 { + seed = u.Name + } + + img, err := avatar.RandomImage([]byte(seed)) + if err != nil { + return fmt.Errorf("RandomImage: %v", err) + } + if err = os.MkdirAll(path.Dir(u.CustomAvatarPath()), os.ModePerm); err != nil { + return fmt.Errorf("MkdirAll: %v", err) + } + fw, err := os.Create(u.CustomAvatarPath()) + if err != nil { + return fmt.Errorf("Create: %v", err) + } + defer fw.Close() + + if err = jpeg.Encode(fw, img, nil); err != nil { + return fmt.Errorf("Encode: %v", err) + } + + log.Info("New random avatar created: %d", u.Id) + return nil +} + func (u *User) RelAvatarLink() string { defaultImgUrl := "/img/avatar_default.jpg" if u.Id == -1 { return defaultImgUrl } - imgPath := path.Join(setting.AvatarUploadPath, com.ToStr(u.Id)) switch { case u.UseCustomAvatar: - if !com.IsExist(imgPath) { + if !com.IsExist(u.CustomAvatarPath()) { return defaultImgUrl } return "/avatars/" + com.ToStr(u.Id) case setting.DisableGravatar, setting.OfflineMode: - if !com.IsExist(imgPath) { - img, err := avatar.RandomImage([]byte(u.Email)) - if err != nil { - log.Error(3, "RandomImage: %v", err) - return defaultImgUrl - } - if err = os.MkdirAll(path.Dir(imgPath), os.ModePerm); err != nil { - log.Error(3, "MkdirAll: %v", err) - return defaultImgUrl - } - fw, err := os.Create(imgPath) - if err != nil { - log.Error(3, "Create: %v", err) - return defaultImgUrl - } - defer fw.Close() - - if err = jpeg.Encode(fw, img, nil); err != nil { - log.Error(3, "Encode: %v", err) - return defaultImgUrl + if !com.IsExist(u.CustomAvatarPath()) { + if err := u.GenerateRandomAvatar(); err != nil { + log.Error(3, "GenerateRandomAvatar: %v", err) } - log.Info("New random avatar created: %d", u.Id) } return "/avatars/" + com.ToStr(u.Id) @@ -208,11 +223,6 @@ func (u *User) ValidatePassword(passwd string) bool { return u.Passwd == newUser.Passwd } -// CustomAvatarPath returns user custom avatar file path. -func (u *User) CustomAvatarPath() string { - return filepath.Join(setting.AvatarUploadPath, com.ToStr(u.Id)) -} - // UploadAvatar saves custom avatar for user. // FIXME: split uploads to different subdirs in case we have massive users. func (u *User) UploadAvatar(data []byte) error { @@ -222,28 +232,27 @@ func (u *User) UploadAvatar(data []byte) error { if err != nil { return err } + m := resize.Resize(234, 234, img, resize.NearestNeighbor) sess := x.NewSession() - defer sess.Close() + defer sessionRelease(sess) if err = sess.Begin(); err != nil { return err } if _, err = sess.Id(u.Id).AllCols().Update(u); err != nil { - sess.Rollback() return err } os.MkdirAll(setting.AvatarUploadPath, os.ModePerm) fw, err := os.Create(u.CustomAvatarPath()) if err != nil { - sess.Rollback() return err } defer fw.Close() + if err = jpeg.Encode(fw, m, nil); err != nil { - sess.Rollback() return err } @@ -284,9 +293,13 @@ func (u *User) IsPublicMember(orgId int64) bool { return IsPublicMembership(orgId, u.Id) } +func (u *User) getOrganizationCount(e Engine) (int64, error) { + return e.Where("uid=?", u.Id).Count(new(OrgUser)) +} + // GetOrganizationCount returns count of membership of organization of user. func (u *User) GetOrganizationCount() (int64, error) { - return x.Where("uid=?", u.Id).Count(new(OrgUser)) + return u.getOrganizationCount(x) } // GetRepositories returns all repositories that user owns, including private repositories. @@ -295,6 +308,12 @@ func (u *User) GetRepositories() (err error) { return err } +// GetOwnedOrganizations returns all organizations that user owns. +func (u *User) GetOwnedOrganizations() (err error) { + u.OwnedOrgs, err = GetOwnedOrgsByUserID(u.Id) + return err +} + // GetOrganizations returns all organizations that user belongs to. func (u *User) GetOrganizations() error { ous, err := GetOrgUsersByUserId(u.Id) @@ -490,12 +509,20 @@ func ChangeUserName(u *User, newUserName string) (err error) { } func updateUser(e Engine, u *User) error { - u.Email = strings.ToLower(u.Email) - has, err := e.Where("id!=?", u.Id).And("type=?", u.Type).And("email=?", u.Email).Get(new(User)) - if err != nil { - return err - } else if has { - return ErrEmailAlreadyUsed{u.Email} + // Organization does not need e-mail. + if !u.IsOrganization() { + u.Email = strings.ToLower(u.Email) + has, err := e.Where("id!=?", u.Id).And("type=?", u.Type).And("email=?", u.Email).Get(new(User)) + if err != nil { + return err + } else if has { + return ErrEmailAlreadyUsed{u.Email} + } + + if len(u.AvatarEmail) == 0 { + u.AvatarEmail = u.Email + } + u.Avatar = avatar.HashEmail(u.AvatarEmail) } u.LowerName = strings.ToLower(u.Name) @@ -510,13 +537,8 @@ func updateUser(e Engine, u *User) error { u.Description = u.Description[:255] } - if u.AvatarEmail == "" { - u.AvatarEmail = u.Email - } - u.Avatar = avatar.HashEmail(u.AvatarEmail) - u.FullName = base.Sanitizer.Sanitize(u.FullName) - _, err = e.Id(u.Id).AllCols().Update(u) + _, err := e.Id(u.Id).AllCols().Update(u) return err } @@ -525,8 +547,8 @@ func UpdateUser(u *User) error { return updateUser(x, u) } -// DeleteBeans deletes all given beans, beans should contain delete conditions. -func DeleteBeans(e Engine, beans ...interface{}) (err error) { +// deleteBeans deletes all given beans, beans should contain delete conditions. +func deleteBeans(e Engine, beans ...interface{}) (err error) { for i := range beans { if _, err = e.Delete(beans[i]); err != nil { return err @@ -536,14 +558,12 @@ func DeleteBeans(e Engine, beans ...interface{}) (err error) { } // FIXME: need some kind of mechanism to record failure. HINT: system notice -// DeleteUser completely and permanently deletes everything of a user, -// but issues/comments/pulls will be kept and shown as someone has been deleted. -func DeleteUser(u *User) error { +func deleteUser(e *xorm.Session, u *User) error { // Note: A user owns any repository or belongs to any organization // cannot perform delete operation. // Check ownership of repository. - count, err := GetRepositoryCount(u) + count, err := getRepositoryCount(e, u) if err != nil { return fmt.Errorf("GetRepositoryCount: %v", err) } else if count > 0 { @@ -551,26 +571,20 @@ func DeleteUser(u *User) error { } // Check membership of organization. - count, err = u.GetOrganizationCount() + count, err = u.getOrganizationCount(e) if err != nil { return fmt.Errorf("GetOrganizationCount: %v", err) } else if count > 0 { return ErrUserHasOrgs{UID: u.Id} } - sess := x.NewSession() - defer sessionRelease(sess) - if err = sess.Begin(); err != nil { - return err - } - // ***** START: Watch ***** watches := make([]*Watch, 0, 10) - if err = x.Find(&watches, &Watch{UserID: u.Id}); err != nil { + if err = e.Find(&watches, &Watch{UserID: u.Id}); err != nil { return fmt.Errorf("get all watches: %v", err) } for i := range watches { - if _, err = sess.Exec("UPDATE `repository` SET num_watches=num_watches-1 WHERE id=?", watches[i].RepoID); err != nil { + if _, err = e.Exec("UPDATE `repository` SET num_watches=num_watches-1 WHERE id=?", watches[i].RepoID); err != nil { return fmt.Errorf("decrease repository watch number[%d]: %v", watches[i].RepoID, err) } } @@ -578,11 +592,11 @@ func DeleteUser(u *User) error { // ***** START: Star ***** stars := make([]*Star, 0, 10) - if err = x.Find(&stars, &Star{UID: u.Id}); err != nil { + if err = e.Find(&stars, &Star{UID: u.Id}); err != nil { return fmt.Errorf("get all stars: %v", err) } for i := range stars { - if _, err = sess.Exec("UPDATE `repository` SET num_stars=num_stars-1 WHERE id=?", stars[i].RepoID); err != nil { + if _, err = e.Exec("UPDATE `repository` SET num_stars=num_stars-1 WHERE id=?", stars[i].RepoID); err != nil { return fmt.Errorf("decrease repository star number[%d]: %v", stars[i].RepoID, err) } } @@ -590,17 +604,17 @@ func DeleteUser(u *User) error { // ***** START: Follow ***** followers := make([]*Follow, 0, 10) - if err = x.Find(&followers, &Follow{UserID: u.Id}); err != nil { + if err = e.Find(&followers, &Follow{UserID: u.Id}); err != nil { return fmt.Errorf("get all followers: %v", err) } for i := range followers { - if _, err = sess.Exec("UPDATE `user` SET num_followers=num_followers-1 WHERE id=?", followers[i].UserID); err != nil { + if _, err = e.Exec("UPDATE `user` SET num_followers=num_followers-1 WHERE id=?", followers[i].UserID); err != nil { return fmt.Errorf("decrease user follower number[%d]: %v", followers[i].UserID, err) } } // ***** END: Follow ***** - if err = DeleteBeans(sess, + if err = deleteBeans(e, &Oauth2{Uid: u.Id}, &AccessToken{UID: u.Id}, &Collaboration{UserID: u.Id}, @@ -612,34 +626,30 @@ func DeleteUser(u *User) error { &IssueUser{UID: u.Id}, &EmailAddress{Uid: u.Id}, ); err != nil { - return fmt.Errorf("DeleteBeans: %v", err) + return fmt.Errorf("deleteUser: %v", err) } // ***** START: PublicKey ***** keys := make([]*PublicKey, 0, 10) - if err = sess.Find(&keys, &PublicKey{OwnerID: u.Id}); err != nil { + if err = e.Find(&keys, &PublicKey{OwnerID: u.Id}); err != nil { return fmt.Errorf("get all public keys: %v", err) } for _, key := range keys { - if err = deletePublicKey(sess, key.ID); err != nil { + if err = deletePublicKey(e, key.ID); err != nil { return fmt.Errorf("deletePublicKey: %v", err) } } // ***** END: PublicKey ***** // Clear assignee. - if _, err = sess.Exec("UPDATE `issue` SET assignee_id=0 WHERE assignee_id=?", u.Id); err != nil { + if _, err = e.Exec("UPDATE `issue` SET assignee_id=0 WHERE assignee_id=?", u.Id); err != nil { return fmt.Errorf("clear assignee: %v", err) } - if _, err = sess.Id(u.Id).Delete(new(User)); err != nil { + if _, err = e.Id(u.Id).Delete(new(User)); err != nil { return fmt.Errorf("Delete: %v", err) } - if err = sess.Commit(); err != nil { - return fmt.Errorf("Commit: %v", err) - } - // FIXME: system notice // Note: There are something just cannot be roll back, // so just keep error logs of those operations. @@ -651,6 +661,22 @@ func DeleteUser(u *User) error { return nil } +// DeleteUser completely and permanently deletes everything of a user, +// but issues/comments/pulls will be kept and shown as someone has been deleted. +func DeleteUser(u *User) (err error) { + sess := x.NewSession() + defer sessionRelease(sess) + if err = sess.Begin(); err != nil { + return err + } + + if err = deleteUser(sess, u); err != nil { + return fmt.Errorf("deleteUser: %v", err) + } + + return sess.Commit() +} + // DeleteInactivateUsers deletes all inactivate users and email addresses. func DeleteInactivateUsers() (err error) { users := make([]*User, 0, 10) |