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.

356 lines
10 KiB

10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
Feature: Timetracking (#2211) * Added comment's hashtag to url for mail notifications. * Added explanation to return statement + documentation. * Replacing in-line link generation with HTMLURL. (+gofmt) * Replaced action-based model with nil-based model. (+gofmt) * Replaced mailIssueActionToParticipants with mailIssueCommentToParticipants. * Updating comment for mailIssueCommentToParticipants * Added link to comment in "Dashboard" * Deleting feed entry if a comment is going to be deleted * Added migration * Added improved migration to add a CommentID column to action. * Added improved links to comments in feed entries. * Fixes #1956 by filtering for deleted comments that are referenced in actions. * Introducing "IsDeleted" column to action. * Adding design draft (not functional) * Adding database models for stopwatches and trackedtimes * See go-gitea/gitea#967 * Adding design draft (not functional) * Adding translations and improving design * Implementing stopwatch (for timetracking) * Make UI functional * Add hints in timeline for time tracking events * Implementing timetracking feature * Adding "Add time manual" option * Improved stopwatch * Created report of total spent time by user * Only showing total time spent if theire is something to show. * Adding license headers. * Improved error handling for "Add Time Manual" * Adding @sapks 's changes, refactoring * Adding API for feature tracking * Adding unit test * Adding DISABLE/ENABLE option to Repository settings page * Improving translations * Applying @sapk 's changes * Removing repo_unit and using IssuesSetting for disabling/enabling timetracker * Adding DEFAULT_ENABLE_TIMETRACKER to config, installation and admin menu * Improving documentation * Fixing vendor/ folder * Changing timtracking routes by adding subgroups /times and /times/stopwatch (Proposed by @lafriks ) * Restricting write access to timetracking based on the repo settings (Proposed by @lafriks ) * Fixed minor permissions bug. * Adding CanUseTimetracker and IsTimetrackerEnabled in ctx.Repo * Allow assignees and authors to track there time too. * Fixed some build-time-errors + logical errors. * Removing unused Get...ByID functions * Moving IsTimetrackerEnabled from context.Repository to models.Repository * Adding a seperate file for issue related repo functions * Adding license headers * Fixed GetUserByParams return 404 * Moving /users/:username/times to /repos/:username/:reponame/times/:username for security reasons * Adding /repos/:username/times to get all tracked times of the repo * Updating sdk-dependency * Updating swagger.v1.json * Adding warning if user has already a running stopwatch (auto-timetracker) * Replacing GetTrackedTimesBy... with GetTrackedTimes(options FindTrackedTimesOptions) * Changing code.gitea.io/sdk back to code.gitea.io/sdk * Correcting spelling mistake * Updating vendor.json * Changing GET stopwatch/toggle to POST stopwatch/toggle * Changing GET stopwatch/cancel to POST stopwatch/cancel * Added migration for stopwatches/timetracking * Fixed some access bugs for read-only users * Added default allow only contributors to track time value to config * Fixed migration by chaging x.Iterate to x.Find * Resorted imports * Moved Add Time Manually form to repo_form.go * Removed "Seconds" field from Add Time Manually * Resorted imports * Improved permission checking * Fixed some bugs * Added integration test * gofmt * Adding integration test by @lafriks * Added created_unix to comment fixtures * Using last event instead of a fixed event * Adding another integration test by @lafriks * Fixing bug Timetracker enabled causing error 500 at sidebar.tpl * Fixed a refactoring bug that resulted in hiding "HasUserStopwatch" warning. * Returning TrackedTime instead of AddTimeOption at AddTime. * Updating SDK from go-gitea/go-sdk#69 * Resetting Go-SDK back to default repository * Fixing test-vendor by changing ini back to original repository * Adding "tags" to swagger spec * govendor sync * Removed duplicate * Formatting templates * Adding IsTimetrackingEnabled checks to API * Improving translations / english texts * Improving documentation * Updating swagger spec * Fixing integration test caused be translation-changes * Removed encoding issues in local_en-US.ini. * "Added" copyright line * Moved unit.IssuesConfig().EnableTimetracker into a != nil check * Removed some other encoding issues in local_en-US.ini * Improved javascript by checking if data-context exists * Replaced manual comment creation with CreateComment * Removed unnecessary code * Improved error checking * Small cosmetic changes * Replaced int>string>duration parsing with int>duration parsing * Fixed encoding issues * Removed unused imports Signed-off-by: Jonas Franz <info@jonasfranz.software>
7 years ago
9 years ago
10 years ago
10 years ago
10 years ago
10 years ago
8 years ago
10 years ago
10 years ago
10 years ago
9 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
  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. "database/sql"
  7. "errors"
  8. "fmt"
  9. "net/url"
  10. "os"
  11. "path"
  12. "path/filepath"
  13. "strings"
  14. "code.gitea.io/gitea/modules/log"
  15. "code.gitea.io/gitea/modules/setting"
  16. // Needed for the MySQL driver
  17. _ "github.com/go-sql-driver/mysql"
  18. "github.com/go-xorm/core"
  19. "github.com/go-xorm/xorm"
  20. // Needed for the Postgresql driver
  21. _ "github.com/lib/pq"
  22. // Needed for the MSSSQL driver
  23. _ "github.com/denisenkom/go-mssqldb"
  24. )
  25. // Engine represents a xorm engine or session.
  26. type Engine interface {
  27. Table(tableNameOrBean interface{}) *xorm.Session
  28. Count(...interface{}) (int64, error)
  29. Decr(column string, arg ...interface{}) *xorm.Session
  30. Delete(interface{}) (int64, error)
  31. Exec(string, ...interface{}) (sql.Result, error)
  32. Find(interface{}, ...interface{}) error
  33. Get(interface{}) (bool, error)
  34. ID(interface{}) *xorm.Session
  35. In(string, ...interface{}) *xorm.Session
  36. Incr(column string, arg ...interface{}) *xorm.Session
  37. Insert(...interface{}) (int64, error)
  38. InsertOne(interface{}) (int64, error)
  39. Iterate(interface{}, xorm.IterFunc) error
  40. Join(joinOperator string, tablename interface{}, condition string, args ...interface{}) *xorm.Session
  41. SQL(interface{}, ...interface{}) *xorm.Session
  42. Where(interface{}, ...interface{}) *xorm.Session
  43. }
  44. var (
  45. x *xorm.Engine
  46. tables []interface{}
  47. // HasEngine specifies if we have a xorm.Engine
  48. HasEngine bool
  49. // DbCfg holds the database settings
  50. DbCfg struct {
  51. Type, Host, Name, User, Passwd, Path, SSLMode string
  52. Timeout int
  53. }
  54. // EnableSQLite3 use SQLite3
  55. EnableSQLite3 bool
  56. // EnableTiDB enable TiDB
  57. EnableTiDB bool
  58. )
  59. func init() {
  60. tables = append(tables,
  61. new(User),
  62. new(PublicKey),
  63. new(AccessToken),
  64. new(Repository),
  65. new(DeployKey),
  66. new(Collaboration),
  67. new(Access),
  68. new(Upload),
  69. new(Watch),
  70. new(Star),
  71. new(Follow),
  72. new(Action),
  73. new(Issue),
  74. new(PullRequest),
  75. new(Comment),
  76. new(Attachment),
  77. new(Label),
  78. new(IssueLabel),
  79. new(Milestone),
  80. new(Mirror),
  81. new(Release),
  82. new(LoginSource),
  83. new(Webhook),
  84. new(HookTask),
  85. new(Team),
  86. new(OrgUser),
  87. new(TeamUser),
  88. new(TeamRepo),
  89. new(Notice),
  90. new(EmailAddress),
  91. new(Notification),
  92. new(IssueUser),
  93. new(LFSMetaObject),
  94. new(TwoFactor),
  95. new(GPGKey),
  96. new(RepoUnit),
  97. new(RepoRedirect),
  98. new(ExternalLoginUser),
  99. new(ProtectedBranch),
  100. new(UserOpenID),
  101. new(IssueWatch),
  102. new(CommitStatus),
  103. new(Stopwatch),
  104. new(TrackedTime),
  105. new(DeletedBranch),
  106. new(RepoIndexerStatus),
  107. new(LFSLock),
  108. new(Reaction),
  109. new(IssueAssignees),
  110. new(U2FRegistration),
  111. )
  112. gonicNames := []string{"SSL", "UID"}
  113. for _, name := range gonicNames {
  114. core.LintGonicMapper[name] = true
  115. }
  116. }
  117. // LoadConfigs loads the database settings
  118. func LoadConfigs() {
  119. sec := setting.Cfg.Section("database")
  120. DbCfg.Type = sec.Key("DB_TYPE").String()
  121. switch DbCfg.Type {
  122. case "sqlite3":
  123. setting.UseSQLite3 = true
  124. case "mysql":
  125. setting.UseMySQL = true
  126. case "postgres":
  127. setting.UsePostgreSQL = true
  128. case "tidb":
  129. setting.UseTiDB = true
  130. case "mssql":
  131. setting.UseMSSQL = true
  132. }
  133. DbCfg.Host = sec.Key("HOST").String()
  134. DbCfg.Name = sec.Key("NAME").String()
  135. DbCfg.User = sec.Key("USER").String()
  136. if len(DbCfg.Passwd) == 0 {
  137. DbCfg.Passwd = sec.Key("PASSWD").String()
  138. }
  139. DbCfg.SSLMode = sec.Key("SSL_MODE").String()
  140. DbCfg.Path = sec.Key("PATH").MustString("data/gitea.db")
  141. DbCfg.Timeout = sec.Key("SQLITE_TIMEOUT").MustInt(500)
  142. sec = setting.Cfg.Section("indexer")
  143. setting.Indexer.IssuePath = sec.Key("ISSUE_INDEXER_PATH").MustString(path.Join(setting.AppDataPath, "indexers/issues.bleve"))
  144. if !filepath.IsAbs(setting.Indexer.IssuePath) {
  145. setting.Indexer.IssuePath = path.Join(setting.AppWorkPath, setting.Indexer.IssuePath)
  146. }
  147. setting.Indexer.RepoIndexerEnabled = sec.Key("REPO_INDEXER_ENABLED").MustBool(false)
  148. setting.Indexer.RepoPath = sec.Key("REPO_INDEXER_PATH").MustString(path.Join(setting.AppDataPath, "indexers/repos.bleve"))
  149. if !filepath.IsAbs(setting.Indexer.RepoPath) {
  150. setting.Indexer.RepoPath = path.Join(setting.AppWorkPath, setting.Indexer.RepoPath)
  151. }
  152. setting.Indexer.UpdateQueueLength = sec.Key("UPDATE_BUFFER_LEN").MustInt(20)
  153. setting.Indexer.MaxIndexerFileSize = sec.Key("MAX_FILE_SIZE").MustInt64(1024 * 1024)
  154. }
  155. // parsePostgreSQLHostPort parses given input in various forms defined in
  156. // https://www.postgresql.org/docs/current/static/libpq-connect.html#LIBPQ-CONNSTRING
  157. // and returns proper host and port number.
  158. func parsePostgreSQLHostPort(info string) (string, string) {
  159. host, port := "127.0.0.1", "5432"
  160. if strings.Contains(info, ":") && !strings.HasSuffix(info, "]") {
  161. idx := strings.LastIndex(info, ":")
  162. host = info[:idx]
  163. port = info[idx+1:]
  164. } else if len(info) > 0 {
  165. host = info
  166. }
  167. return host, port
  168. }
  169. func parseMSSQLHostPort(info string) (string, string) {
  170. host, port := "127.0.0.1", "1433"
  171. if strings.Contains(info, ":") {
  172. host = strings.Split(info, ":")[0]
  173. port = strings.Split(info, ":")[1]
  174. } else if strings.Contains(info, ",") {
  175. host = strings.Split(info, ",")[0]
  176. port = strings.TrimSpace(strings.Split(info, ",")[1])
  177. } else if len(info) > 0 {
  178. host = info
  179. }
  180. return host, port
  181. }
  182. func getEngine() (*xorm.Engine, error) {
  183. connStr := ""
  184. var Param = "?"
  185. if strings.Contains(DbCfg.Name, Param) {
  186. Param = "&"
  187. }
  188. switch DbCfg.Type {
  189. case "mysql":
  190. if DbCfg.Host[0] == '/' { // looks like a unix socket
  191. connStr = fmt.Sprintf("%s:%s@unix(%s)/%s%scharset=utf8&parseTime=true",
  192. DbCfg.User, DbCfg.Passwd, DbCfg.Host, DbCfg.Name, Param)
  193. } else {
  194. connStr = fmt.Sprintf("%s:%s@tcp(%s)/%s%scharset=utf8&parseTime=true",
  195. DbCfg.User, DbCfg.Passwd, DbCfg.Host, DbCfg.Name, Param)
  196. }
  197. case "postgres":
  198. host, port := parsePostgreSQLHostPort(DbCfg.Host)
  199. if host[0] == '/' { // looks like a unix socket
  200. connStr = fmt.Sprintf("postgres://%s:%s@:%s/%s%ssslmode=%s&host=%s",
  201. url.QueryEscape(DbCfg.User), url.QueryEscape(DbCfg.Passwd), port, DbCfg.Name, Param, DbCfg.SSLMode, host)
  202. } else {
  203. connStr = fmt.Sprintf("postgres://%s:%s@%s:%s/%s%ssslmode=%s",
  204. url.QueryEscape(DbCfg.User), url.QueryEscape(DbCfg.Passwd), host, port, DbCfg.Name, Param, DbCfg.SSLMode)
  205. }
  206. case "mssql":
  207. host, port := parseMSSQLHostPort(DbCfg.Host)
  208. connStr = fmt.Sprintf("server=%s; port=%s; database=%s; user id=%s; password=%s;", host, port, DbCfg.Name, DbCfg.User, DbCfg.Passwd)
  209. case "sqlite3":
  210. if !EnableSQLite3 {
  211. return nil, errors.New("this binary version does not build support for SQLite3")
  212. }
  213. if err := os.MkdirAll(path.Dir(DbCfg.Path), os.ModePerm); err != nil {
  214. return nil, fmt.Errorf("Failed to create directories: %v", err)
  215. }
  216. connStr = fmt.Sprintf("file:%s?cache=shared&mode=rwc&_busy_timeout=%d", DbCfg.Path, DbCfg.Timeout)
  217. case "tidb":
  218. if !EnableTiDB {
  219. return nil, errors.New("this binary version does not build support for TiDB")
  220. }
  221. if err := os.MkdirAll(path.Dir(DbCfg.Path), os.ModePerm); err != nil {
  222. return nil, fmt.Errorf("Failed to create directories: %v", err)
  223. }
  224. connStr = "goleveldb://" + DbCfg.Path
  225. default:
  226. return nil, fmt.Errorf("Unknown database type: %s", DbCfg.Type)
  227. }
  228. return xorm.NewEngine(DbCfg.Type, connStr)
  229. }
  230. // NewTestEngine sets a new test xorm.Engine
  231. func NewTestEngine(x *xorm.Engine) (err error) {
  232. x, err = getEngine()
  233. if err != nil {
  234. return fmt.Errorf("Connect to database: %v", err)
  235. }
  236. x.SetMapper(core.GonicMapper{})
  237. x.SetLogger(log.XORMLogger)
  238. x.ShowSQL(!setting.ProdMode)
  239. return x.StoreEngine("InnoDB").Sync2(tables...)
  240. }
  241. // SetEngine sets the xorm.Engine
  242. func SetEngine() (err error) {
  243. x, err = getEngine()
  244. if err != nil {
  245. return fmt.Errorf("Failed to connect to database: %v", err)
  246. }
  247. x.SetMapper(core.GonicMapper{})
  248. // WARNING: for serv command, MUST remove the output to os.stdout,
  249. // so use log file to instead print to stdout.
  250. x.SetLogger(log.XORMLogger)
  251. x.ShowSQL(setting.LogSQL)
  252. return nil
  253. }
  254. // NewEngine initializes a new xorm.Engine
  255. func NewEngine(migrateFunc func(*xorm.Engine) error) (err error) {
  256. if err = SetEngine(); err != nil {
  257. return err
  258. }
  259. if err = x.Ping(); err != nil {
  260. return err
  261. }
  262. if err = migrateFunc(x); err != nil {
  263. return fmt.Errorf("migrate: %v", err)
  264. }
  265. if err = x.StoreEngine("InnoDB").Sync2(tables...); err != nil {
  266. return fmt.Errorf("sync database struct error: %v", err)
  267. }
  268. return nil
  269. }
  270. // Statistic contains the database statistics
  271. type Statistic struct {
  272. Counter struct {
  273. User, Org, PublicKey,
  274. Repo, Watch, Star, Action, Access,
  275. Issue, Comment, Oauth, Follow,
  276. Mirror, Release, LoginSource, Webhook,
  277. Milestone, Label, HookTask,
  278. Team, UpdateTask, Attachment int64
  279. }
  280. }
  281. // GetStatistic returns the database statistics
  282. func GetStatistic() (stats Statistic) {
  283. stats.Counter.User = CountUsers()
  284. stats.Counter.Org = CountOrganizations()
  285. stats.Counter.PublicKey, _ = x.Count(new(PublicKey))
  286. stats.Counter.Repo = CountRepositories(true)
  287. stats.Counter.Watch, _ = x.Count(new(Watch))
  288. stats.Counter.Star, _ = x.Count(new(Star))
  289. stats.Counter.Action, _ = x.Count(new(Action))
  290. stats.Counter.Access, _ = x.Count(new(Access))
  291. stats.Counter.Issue, _ = x.Count(new(Issue))
  292. stats.Counter.Comment, _ = x.Count(new(Comment))
  293. stats.Counter.Oauth = 0
  294. stats.Counter.Follow, _ = x.Count(new(Follow))
  295. stats.Counter.Mirror, _ = x.Count(new(Mirror))
  296. stats.Counter.Release, _ = x.Count(new(Release))
  297. stats.Counter.LoginSource = CountLoginSources()
  298. stats.Counter.Webhook, _ = x.Count(new(Webhook))
  299. stats.Counter.Milestone, _ = x.Count(new(Milestone))
  300. stats.Counter.Label, _ = x.Count(new(Label))
  301. stats.Counter.HookTask, _ = x.Count(new(HookTask))
  302. stats.Counter.Team, _ = x.Count(new(Team))
  303. stats.Counter.Attachment, _ = x.Count(new(Attachment))
  304. return
  305. }
  306. // Ping tests if database is alive
  307. func Ping() error {
  308. if x != nil {
  309. return x.Ping()
  310. }
  311. return errors.New("database not configured")
  312. }
  313. // DumpDatabase dumps all data from database according the special database SQL syntax to file system.
  314. func DumpDatabase(filePath string, dbType string) error {
  315. var tbs []*core.Table
  316. for _, t := range tables {
  317. tbs = append(tbs, x.TableInfo(t).Table)
  318. }
  319. if len(dbType) > 0 {
  320. return x.DumpTablesToFile(tbs, filePath, core.DbType(dbType))
  321. }
  322. return x.DumpTablesToFile(tbs, filePath)
  323. }