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

user.go 19 kB

12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
11 years ago
11 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
11 years ago
11 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
11 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
11 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
11 years ago
12 years ago
11 years ago
12 years ago
12 years ago
12 years ago
11 years ago
11 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745
  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 models
  5. import (
  6. "bytes"
  7. "container/list"
  8. "crypto/sha256"
  9. "encoding/hex"
  10. "errors"
  11. "fmt"
  12. "image"
  13. "image/jpeg"
  14. "os"
  15. "path/filepath"
  16. "strings"
  17. "time"
  18. "github.com/Unknwon/com"
  19. "github.com/nfnt/resize"
  20. "github.com/gogits/gogs/modules/base"
  21. "github.com/gogits/gogs/modules/git"
  22. "github.com/gogits/gogs/modules/log"
  23. "github.com/gogits/gogs/modules/setting"
  24. )
  25. type UserType int
  26. const (
  27. INDIVIDUAL UserType = iota // Historic reason to make it starts at 0.
  28. ORGANIZATION
  29. )
  30. var (
  31. ErrUserOwnRepos = errors.New("User still have ownership of repositories")
  32. ErrUserHasOrgs = errors.New("User still have membership of organization")
  33. ErrUserAlreadyExist = errors.New("User already exist")
  34. ErrUserNotExist = errors.New("User does not exist")
  35. ErrUserNotKeyOwner = errors.New("User does not the owner of public key")
  36. ErrEmailAlreadyUsed = errors.New("E-mail already used")
  37. ErrUserNameIllegal = errors.New("User name contains illegal characters")
  38. ErrLoginSourceNotExist = errors.New("Login source does not exist")
  39. ErrLoginSourceNotActived = errors.New("Login source is not actived")
  40. ErrUnsupportedLoginType = errors.New("Login source is unknown")
  41. )
  42. // User represents the object of individual and member of organization.
  43. type User struct {
  44. Id int64
  45. LowerName string `xorm:"UNIQUE NOT NULL"`
  46. Name string `xorm:"UNIQUE NOT NULL"`
  47. FullName string
  48. Email string `xorm:"UNIQUE(s) NOT NULL"`
  49. Passwd string `xorm:"NOT NULL"`
  50. LoginType LoginType
  51. LoginSource int64 `xorm:"NOT NULL DEFAULT 0"`
  52. LoginName string
  53. Type UserType `xorm:"UNIQUE(s)"`
  54. Orgs []*User `xorm:"-"`
  55. Repos []*Repository `xorm:"-"`
  56. Location string
  57. Website string
  58. Rands string `xorm:"VARCHAR(10)"`
  59. Salt string `xorm:"VARCHAR(10)"`
  60. Created time.Time `xorm:"CREATED"`
  61. Updated time.Time `xorm:"UPDATED"`
  62. // Permissions.
  63. IsActive bool
  64. IsAdmin bool
  65. AllowGitHook bool
  66. // Avatar.
  67. Avatar string `xorm:"VARCHAR(2048) NOT NULL"`
  68. AvatarEmail string `xorm:"NOT NULL"`
  69. UseCustomAvatar bool
  70. // Counters.
  71. NumFollowers int
  72. NumFollowings int
  73. NumStars int
  74. NumRepos int
  75. // For organization.
  76. Description string
  77. NumTeams int
  78. NumMembers int
  79. Teams []*Team `xorm:"-"`
  80. Members []*User `xorm:"-"`
  81. }
  82. // DashboardLink returns the user dashboard page link.
  83. func (u *User) DashboardLink() string {
  84. if u.IsOrganization() {
  85. return setting.AppSubUrl + "/org/" + u.Name + "/dashboard/"
  86. }
  87. return setting.AppSubUrl + "/"
  88. }
  89. // HomeLink returns the user home page link.
  90. func (u *User) HomeLink() string {
  91. return setting.AppSubUrl + "/" + u.Name
  92. }
  93. // AvatarLink returns user gravatar link.
  94. func (u *User) AvatarLink() string {
  95. switch {
  96. case u.UseCustomAvatar:
  97. return setting.AppSubUrl + "/avatars/" + com.ToStr(u.Id)
  98. case setting.DisableGravatar:
  99. return setting.AppSubUrl + "/img/avatar_default.jpg"
  100. case setting.Service.EnableCacheAvatar:
  101. return setting.AppSubUrl + "/avatar/" + u.Avatar
  102. }
  103. return setting.GravatarSource + u.Avatar
  104. }
  105. // NewGitSig generates and returns the signature of given user.
  106. func (u *User) NewGitSig() *git.Signature {
  107. return &git.Signature{
  108. Name: u.Name,
  109. Email: u.Email,
  110. When: time.Now(),
  111. }
  112. }
  113. // EncodePasswd encodes password to safe format.
  114. func (u *User) EncodePasswd() {
  115. newPasswd := base.PBKDF2([]byte(u.Passwd), []byte(u.Salt), 10000, 50, sha256.New)
  116. u.Passwd = fmt.Sprintf("%x", newPasswd)
  117. }
  118. // ValidtePassword checks if given password matches the one belongs to the user.
  119. func (u *User) ValidtePassword(passwd string) bool {
  120. newUser := &User{Passwd: passwd, Salt: u.Salt}
  121. newUser.EncodePasswd()
  122. return u.Passwd == newUser.Passwd
  123. }
  124. // CustomAvatarPath returns user custom avatar file path.
  125. func (u *User) CustomAvatarPath() string {
  126. return filepath.Join(setting.AvatarUploadPath, com.ToStr(u.Id))
  127. }
  128. // UploadAvatar saves custom avatar for user.
  129. // FIXME: splite uploads to different subdirs in case we have massive users.
  130. func (u *User) UploadAvatar(data []byte) error {
  131. u.UseCustomAvatar = true
  132. img, _, err := image.Decode(bytes.NewReader(data))
  133. if err != nil {
  134. return err
  135. }
  136. m := resize.Resize(200, 200, img, resize.NearestNeighbor)
  137. sess := x.NewSession()
  138. defer sess.Close()
  139. if err = sess.Begin(); err != nil {
  140. return err
  141. }
  142. if _, err = sess.Id(u.Id).AllCols().Update(u); err != nil {
  143. sess.Rollback()
  144. return err
  145. }
  146. os.MkdirAll(setting.AvatarUploadPath, os.ModePerm)
  147. fw, err := os.Create(u.CustomAvatarPath())
  148. if err != nil {
  149. sess.Rollback()
  150. return err
  151. }
  152. defer fw.Close()
  153. if err = jpeg.Encode(fw, m, nil); err != nil {
  154. sess.Rollback()
  155. return err
  156. }
  157. return sess.Commit()
  158. }
  159. // IsOrganization returns true if user is actually a organization.
  160. func (u *User) IsOrganization() bool {
  161. return u.Type == ORGANIZATION
  162. }
  163. // IsUserOrgOwner returns true if user is in the owner team of given organization.
  164. func (u *User) IsUserOrgOwner(orgId int64) bool {
  165. return IsOrganizationOwner(orgId, u.Id)
  166. }
  167. // IsPublicMember returns true if user public his/her membership in give organization.
  168. func (u *User) IsPublicMember(orgId int64) bool {
  169. return IsPublicMembership(orgId, u.Id)
  170. }
  171. // GetOrganizationCount returns count of membership of organization of user.
  172. func (u *User) GetOrganizationCount() (int64, error) {
  173. return x.Where("uid=?", u.Id).Count(new(OrgUser))
  174. }
  175. // GetRepositories returns all repositories that user owns, including private repositories.
  176. func (u *User) GetRepositories() (err error) {
  177. u.Repos, err = GetRepositories(u.Id, true)
  178. return err
  179. }
  180. // GetOrganizations returns all organizations that user belongs to.
  181. func (u *User) GetOrganizations() error {
  182. ous, err := GetOrgUsersByUserId(u.Id)
  183. if err != nil {
  184. return err
  185. }
  186. u.Orgs = make([]*User, len(ous))
  187. for i, ou := range ous {
  188. u.Orgs[i], err = GetUserById(ou.OrgId)
  189. if err != nil {
  190. return err
  191. }
  192. }
  193. return nil
  194. }
  195. // GetFullNameFallback returns Full Name if set, otherwise username
  196. func (u *User) GetFullNameFallback() string {
  197. if u.FullName == "" {
  198. return u.Name
  199. }
  200. return u.FullName
  201. }
  202. // IsUserExist checks if given user name exist,
  203. // the user name should be noncased unique.
  204. func IsUserExist(name string) (bool, error) {
  205. if len(name) == 0 {
  206. return false, nil
  207. }
  208. return x.Get(&User{LowerName: strings.ToLower(name)})
  209. }
  210. // IsEmailUsed returns true if the e-mail has been used.
  211. func IsEmailUsed(email string) (bool, error) {
  212. if len(email) == 0 {
  213. return false, nil
  214. }
  215. return x.Get(&User{Email: email})
  216. }
  217. // GetUserSalt returns a ramdom user salt token.
  218. func GetUserSalt() string {
  219. return base.GetRandomString(10)
  220. }
  221. // CreateUser creates record of a new user.
  222. func CreateUser(u *User) error {
  223. if !IsLegalName(u.Name) {
  224. return ErrUserNameIllegal
  225. }
  226. isExist, err := IsUserExist(u.Name)
  227. if err != nil {
  228. return err
  229. } else if isExist {
  230. return ErrUserAlreadyExist
  231. }
  232. isExist, err = IsEmailUsed(u.Email)
  233. if err != nil {
  234. return err
  235. } else if isExist {
  236. return ErrEmailAlreadyUsed
  237. }
  238. u.LowerName = strings.ToLower(u.Name)
  239. u.Avatar = base.EncodeMd5(u.Email)
  240. u.AvatarEmail = u.Email
  241. u.Rands = GetUserSalt()
  242. u.Salt = GetUserSalt()
  243. u.EncodePasswd()
  244. sess := x.NewSession()
  245. defer sess.Close()
  246. if err = sess.Begin(); err != nil {
  247. return err
  248. }
  249. if _, err = sess.Insert(u); err != nil {
  250. sess.Rollback()
  251. return err
  252. } else if err = os.MkdirAll(UserPath(u.Name), os.ModePerm); err != nil {
  253. sess.Rollback()
  254. return err
  255. } else if err = sess.Commit(); err != nil {
  256. return err
  257. }
  258. // Auto-set admin for user whose ID is 1.
  259. if u.Id == 1 {
  260. u.IsAdmin = true
  261. u.IsActive = true
  262. _, err = x.Id(u.Id).UseBool().Update(u)
  263. }
  264. return err
  265. }
  266. // CountUsers returns number of users.
  267. func CountUsers() int64 {
  268. count, _ := x.Where("type=0").Count(new(User))
  269. return count
  270. }
  271. // GetUsers returns given number of user objects with offset.
  272. func GetUsers(num, offset int) ([]*User, error) {
  273. users := make([]*User, 0, num)
  274. err := x.Limit(num, offset).Where("type=0").Asc("id").Find(&users)
  275. return users, err
  276. }
  277. // get user by erify code
  278. func getVerifyUser(code string) (user *User) {
  279. if len(code) <= base.TimeLimitCodeLength {
  280. return nil
  281. }
  282. // use tail hex username query user
  283. hexStr := code[base.TimeLimitCodeLength:]
  284. if b, err := hex.DecodeString(hexStr); err == nil {
  285. if user, err = GetUserByName(string(b)); user != nil {
  286. return user
  287. }
  288. log.Error(4, "user.getVerifyUser: %v", err)
  289. }
  290. return nil
  291. }
  292. // verify active code when active account
  293. func VerifyUserActiveCode(code string) (user *User) {
  294. minutes := setting.Service.ActiveCodeLives
  295. if user = getVerifyUser(code); user != nil {
  296. // time limit code
  297. prefix := code[:base.TimeLimitCodeLength]
  298. data := com.ToStr(user.Id) + user.Email + user.LowerName + user.Passwd + user.Rands
  299. if base.VerifyTimeLimitCode(data, minutes, prefix) {
  300. return user
  301. }
  302. }
  303. return nil
  304. }
  305. // ChangeUserName changes all corresponding setting from old user name to new one.
  306. func ChangeUserName(u *User, newUserName string) (err error) {
  307. if !IsLegalName(newUserName) {
  308. return ErrUserNameIllegal
  309. }
  310. newUserName = strings.ToLower(newUserName)
  311. // Update accesses of user.
  312. accesses := make([]Access, 0, 10)
  313. if err = x.Find(&accesses, &Access{UserName: u.LowerName}); err != nil {
  314. return err
  315. }
  316. sess := x.NewSession()
  317. defer sess.Close()
  318. if err = sess.Begin(); err != nil {
  319. return err
  320. }
  321. for i := range accesses {
  322. accesses[i].UserName = newUserName
  323. if strings.HasPrefix(accesses[i].RepoName, u.LowerName+"/") {
  324. accesses[i].RepoName = strings.Replace(accesses[i].RepoName, u.LowerName, newUserName, 1)
  325. }
  326. if err = UpdateAccessWithSession(sess, &accesses[i]); err != nil {
  327. return err
  328. }
  329. }
  330. repos, err := GetRepositories(u.Id, true)
  331. if err != nil {
  332. return err
  333. }
  334. for i := range repos {
  335. accesses = make([]Access, 0, 10)
  336. // Update accesses of user repository.
  337. if err = x.Find(&accesses, &Access{RepoName: u.LowerName + "/" + repos[i].LowerName}); err != nil {
  338. return err
  339. }
  340. for j := range accesses {
  341. // if the access is not the user's access (already updated above)
  342. if accesses[j].UserName != u.LowerName {
  343. accesses[j].RepoName = newUserName + "/" + repos[i].LowerName
  344. if err = UpdateAccessWithSession(sess, &accesses[j]); err != nil {
  345. return err
  346. }
  347. }
  348. }
  349. }
  350. // Change user directory name.
  351. if err = os.Rename(UserPath(u.LowerName), UserPath(newUserName)); err != nil {
  352. sess.Rollback()
  353. return err
  354. }
  355. return sess.Commit()
  356. }
  357. // UpdateUser updates user's information.
  358. func UpdateUser(u *User) error {
  359. has, err := x.Where("id != ?", u.Id).And("email = ?", u.Email).Get(new(User))
  360. if err != nil {
  361. return err
  362. } else if has {
  363. return ErrEmailAlreadyUsed
  364. }
  365. u.LowerName = strings.ToLower(u.Name)
  366. if len(u.Location) > 255 {
  367. u.Location = u.Location[:255]
  368. }
  369. if len(u.Website) > 255 {
  370. u.Website = u.Website[:255]
  371. }
  372. if len(u.Description) > 255 {
  373. u.Description = u.Description[:255]
  374. }
  375. _, err = x.Id(u.Id).AllCols().Update(u)
  376. return err
  377. }
  378. // FIXME: need some kind of mechanism to record failure. HINT: system notice
  379. // DeleteUser completely and permanently deletes everything of user.
  380. func DeleteUser(u *User) error {
  381. // Check ownership of repository.
  382. count, err := GetRepositoryCount(u)
  383. if err != nil {
  384. return errors.New("GetRepositoryCount: " + err.Error())
  385. } else if count > 0 {
  386. return ErrUserOwnRepos
  387. }
  388. // Check membership of organization.
  389. count, err = u.GetOrganizationCount()
  390. if err != nil {
  391. return errors.New("GetOrganizationCount: " + err.Error())
  392. } else if count > 0 {
  393. return ErrUserHasOrgs
  394. }
  395. // FIXME: check issues, other repos' commits
  396. // FIXME: roll backable in some point.
  397. // Delete all followers.
  398. if _, err = x.Delete(&Follow{FollowId: u.Id}); err != nil {
  399. return err
  400. }
  401. // Delete oauth2.
  402. if _, err = x.Delete(&Oauth2{Uid: u.Id}); err != nil {
  403. return err
  404. }
  405. // Delete all feeds.
  406. if _, err = x.Delete(&Action{UserId: u.Id}); err != nil {
  407. return err
  408. }
  409. // Delete all watches.
  410. if _, err = x.Delete(&Watch{UserId: u.Id}); err != nil {
  411. return err
  412. }
  413. // Delete all accesses.
  414. if _, err = x.Delete(&Access{UserName: u.LowerName}); err != nil {
  415. return err
  416. }
  417. // Delete all SSH keys.
  418. keys := make([]*PublicKey, 0, 10)
  419. if err = x.Find(&keys, &PublicKey{OwnerId: u.Id}); err != nil {
  420. return err
  421. }
  422. for _, key := range keys {
  423. if err = DeletePublicKey(key); err != nil {
  424. return err
  425. }
  426. }
  427. // Delete user directory.
  428. if err = os.RemoveAll(UserPath(u.Name)); err != nil {
  429. return err
  430. }
  431. _, err = x.Delete(u)
  432. return err
  433. }
  434. // DeleteInactivateUsers deletes all inactivate users.
  435. func DeleteInactivateUsers() error {
  436. _, err := x.Where("is_active=?", false).Delete(new(User))
  437. return err
  438. }
  439. // UserPath returns the path absolute path of user repositories.
  440. func UserPath(userName string) string {
  441. return filepath.Join(setting.RepoRootPath, strings.ToLower(userName))
  442. }
  443. func GetUserByKeyId(keyId int64) (*User, error) {
  444. user := new(User)
  445. rawSql := "SELECT a.* FROM `user` AS a, public_key AS b WHERE a.id = b.owner_id AND b.id=?"
  446. has, err := x.Sql(rawSql, keyId).Get(user)
  447. if err != nil {
  448. return nil, err
  449. } else if !has {
  450. return nil, ErrUserNotKeyOwner
  451. }
  452. return user, nil
  453. }
  454. // GetUserById returns the user object by given ID if exists.
  455. func GetUserById(id int64) (*User, error) {
  456. u := new(User)
  457. has, err := x.Id(id).Get(u)
  458. if err != nil {
  459. return nil, err
  460. } else if !has {
  461. return nil, ErrUserNotExist
  462. }
  463. return u, nil
  464. }
  465. // GetUserByName returns user by given name.
  466. func GetUserByName(name string) (*User, error) {
  467. if len(name) == 0 {
  468. return nil, ErrUserNotExist
  469. }
  470. u := &User{LowerName: strings.ToLower(name)}
  471. has, err := x.Get(u)
  472. if err != nil {
  473. return nil, err
  474. } else if !has {
  475. return nil, ErrUserNotExist
  476. }
  477. return u, nil
  478. }
  479. // GetUserEmailsByNames returns a list of e-mails corresponds to names.
  480. func GetUserEmailsByNames(names []string) []string {
  481. mails := make([]string, 0, len(names))
  482. for _, name := range names {
  483. u, err := GetUserByName(name)
  484. if err != nil {
  485. continue
  486. }
  487. mails = append(mails, u.Email)
  488. }
  489. return mails
  490. }
  491. // GetUserIdsByNames returns a slice of ids corresponds to names.
  492. func GetUserIdsByNames(names []string) []int64 {
  493. ids := make([]int64, 0, len(names))
  494. for _, name := range names {
  495. u, err := GetUserByName(name)
  496. if err != nil {
  497. continue
  498. }
  499. ids = append(ids, u.Id)
  500. }
  501. return ids
  502. }
  503. // UserCommit represtns a commit with validation of user.
  504. type UserCommit struct {
  505. User *User
  506. *git.Commit
  507. }
  508. // ValidateCommitWithEmail chceck if author's e-mail of commit is corresponsind to a user.
  509. func ValidateCommitWithEmail(c *git.Commit) *User {
  510. u, err := GetUserByEmail(c.Author.Email)
  511. if err != nil {
  512. return nil
  513. }
  514. return u
  515. }
  516. // ValidateCommitsWithEmails checks if authors' e-mails of commits are corresponding to users.
  517. func ValidateCommitsWithEmails(oldCommits *list.List) *list.List {
  518. emails := map[string]*User{}
  519. newCommits := list.New()
  520. e := oldCommits.Front()
  521. for e != nil {
  522. c := e.Value.(*git.Commit)
  523. var u *User
  524. if v, ok := emails[c.Author.Email]; !ok {
  525. u, _ = GetUserByEmail(c.Author.Email)
  526. emails[c.Author.Email] = u
  527. } else {
  528. u = v
  529. }
  530. newCommits.PushBack(UserCommit{
  531. User: u,
  532. Commit: c,
  533. })
  534. e = e.Next()
  535. }
  536. return newCommits
  537. }
  538. // GetUserByEmail returns the user object by given e-mail if exists.
  539. func GetUserByEmail(email string) (*User, error) {
  540. if len(email) == 0 {
  541. return nil, ErrUserNotExist
  542. }
  543. user := &User{Email: strings.ToLower(email)}
  544. has, err := x.Get(user)
  545. if err != nil {
  546. return nil, err
  547. } else if !has {
  548. return nil, ErrUserNotExist
  549. }
  550. return user, nil
  551. }
  552. // SearchUserByName returns given number of users whose name contains keyword.
  553. func SearchUserByName(opt SearchOption) (us []*User, err error) {
  554. if len(opt.Keyword) == 0 {
  555. return us, nil
  556. }
  557. opt.Keyword = strings.ToLower(opt.Keyword)
  558. us = make([]*User, 0, opt.Limit)
  559. err = x.Limit(opt.Limit).Where("type=0").And("lower_name like ?", "%"+opt.Keyword+"%").Find(&us)
  560. return us, err
  561. }
  562. // Follow is connection request for receiving user notifycation.
  563. type Follow struct {
  564. Id int64
  565. UserId int64 `xorm:"unique(follow)"`
  566. FollowId int64 `xorm:"unique(follow)"`
  567. }
  568. // FollowUser marks someone be another's follower.
  569. func FollowUser(userId int64, followId int64) (err error) {
  570. sess := x.NewSession()
  571. defer sess.Close()
  572. sess.Begin()
  573. if _, err = sess.Insert(&Follow{UserId: userId, FollowId: followId}); err != nil {
  574. sess.Rollback()
  575. return err
  576. }
  577. rawSql := "UPDATE `user` SET num_followers = num_followers + 1 WHERE id = ?"
  578. if _, err = sess.Exec(rawSql, followId); err != nil {
  579. sess.Rollback()
  580. return err
  581. }
  582. rawSql = "UPDATE `user` SET num_followings = num_followings + 1 WHERE id = ?"
  583. if _, err = sess.Exec(rawSql, userId); err != nil {
  584. sess.Rollback()
  585. return err
  586. }
  587. return sess.Commit()
  588. }
  589. // UnFollowUser unmarks someone be another's follower.
  590. func UnFollowUser(userId int64, unFollowId int64) (err error) {
  591. session := x.NewSession()
  592. defer session.Close()
  593. session.Begin()
  594. if _, err = session.Delete(&Follow{UserId: userId, FollowId: unFollowId}); err != nil {
  595. session.Rollback()
  596. return err
  597. }
  598. rawSql := "UPDATE `user` SET num_followers = num_followers - 1 WHERE id = ?"
  599. if _, err = session.Exec(rawSql, unFollowId); err != nil {
  600. session.Rollback()
  601. return err
  602. }
  603. rawSql = "UPDATE `user` SET num_followings = num_followings - 1 WHERE id = ?"
  604. if _, err = session.Exec(rawSql, userId); err != nil {
  605. session.Rollback()
  606. return err
  607. }
  608. return session.Commit()
  609. }
  610. func UpdateMentions(userNames []string, issueId int64) error {
  611. users := make([]*User, 0, len(userNames))
  612. if err := x.Where("name IN (?)", strings.Join(userNames, "\",\"")).OrderBy("name ASC").Find(&users); err != nil {
  613. return err
  614. }
  615. ids := make([]int64, 0, len(userNames))
  616. for _, user := range users {
  617. ids = append(ids, user.Id)
  618. if user.Type == INDIVIDUAL {
  619. continue
  620. }
  621. if user.NumMembers == 0 {
  622. continue
  623. }
  624. tempIds := make([]int64, 0, user.NumMembers)
  625. orgUsers, err := GetOrgUsersByOrgId(user.Id)
  626. if err != nil {
  627. return err
  628. }
  629. for _, orgUser := range orgUsers {
  630. tempIds = append(tempIds, orgUser.Id)
  631. }
  632. ids = append(ids, tempIds...)
  633. }
  634. if err := UpdateIssueUserPairsByMentions(ids, issueId); err != nil {
  635. return err
  636. }
  637. return nil
  638. }