diff --git a/.bra.toml b/.bra.toml index e009a2b7c..3216404d1 100755 --- a/.bra.toml +++ b/.bra.toml @@ -1,5 +1,6 @@ [run] init_cmds = [ # Commands run in start + ["go", "mod", "vendor"], ["make", "backend"], ["./opendata"] ] @@ -14,6 +15,7 @@ watch_dirs = [ "$WORKDIR/public", "$WORKDIR/custom", "$WORKDIR/web_src", + "$WORKDIR/vendor", ] # Directories to watch watch_exts = [".go", ".ini", ".less"] # Extensions to watch env_files = [] # Load env vars from files @@ -24,6 +26,7 @@ build_delay = 3000 # Minimal interval to Trigger build event interrupt_timout = 15 # Time to wait until force kill graceful_kill = false # Wait for exit and before directly kill cmds = [ # Commands to run + ["go", "mod", "vendor"], ["make", "backend"], ["./opendata"] ] diff --git a/docs/开源社区平台与区块链平台对接方案.docx b/docs/开源社区平台与区块链平台对接方案.docx index 365a26540..f4223c354 100755 Binary files a/docs/开源社区平台与区块链平台对接方案.docx and b/docs/开源社区平台与区块链平台对接方案.docx differ diff --git a/models/action.go b/models/action.go index a29ed343d..ab7d576e8 100755 --- a/models/action.go +++ b/models/action.go @@ -55,21 +55,21 @@ const ( // repository. It implemented interface base.Actioner so that can be // used in template render. type Action struct { - ID int64 `xorm:"pk autoincr"` - UserID int64 `xorm:"INDEX"` // Receiver user id. - OpType ActionType - ActUserID int64 `xorm:"INDEX"` // Action user id. - ActUser *User `xorm:"-"` - RepoID int64 `xorm:"INDEX"` - Repo *Repository `xorm:"-"` - CommentID int64 `xorm:"INDEX"` - Comment *Comment `xorm:"-"` - IsDeleted bool `xorm:"INDEX NOT NULL DEFAULT false"` - RefName string - IsPrivate bool `xorm:"INDEX NOT NULL DEFAULT false"` - IsTransformed bool `xorm:"INDEX NOT NULL DEFAULT false"` - Content string `xorm:"TEXT"` - CreatedUnix timeutil.TimeStamp `xorm:"INDEX created"` + ID int64 `xorm:"pk autoincr"` + UserID int64 `xorm:"INDEX"` // Receiver user id. + OpType ActionType + ActUserID int64 `xorm:"INDEX"` // Action user id. + ActUser *User `xorm:"-"` + RepoID int64 `xorm:"INDEX"` + Repo *Repository `xorm:"-"` + CommentID int64 `xorm:"INDEX"` + Comment *Comment `xorm:"-"` + IsDeleted bool `xorm:"INDEX NOT NULL DEFAULT false"` + RefName string + IsPrivate bool `xorm:"INDEX NOT NULL DEFAULT false"` + IsTransformed bool `xorm:"INDEX NOT NULL DEFAULT false"` + Content string `xorm:"TEXT"` + CreatedUnix timeutil.TimeStamp `xorm:"INDEX created"` } // GetOpType gets the ActionType of this action. diff --git a/models/attachment.go b/models/attachment.go index 063230e57..f08063b83 100755 --- a/models/attachment.go +++ b/models/attachment.go @@ -46,7 +46,7 @@ type Attachment struct { type AttachmentUsername struct { Attachment `xorm:"extends"` - Name string + Name string } func (a *Attachment) AfterUpdate() { @@ -359,7 +359,7 @@ func GetAllPublicAttachments() ([]*AttachmentUsername, error) { func getAllPublicAttachments(e Engine) ([]*AttachmentUsername, error) { attachments := make([]*AttachmentUsername, 0, 10) - if err := e.Table("attachment").Join("LEFT", "`user`", "attachment.uploader_id " + + if err := e.Table("attachment").Join("LEFT", "`user`", "attachment.uploader_id "+ "= `user`.id").Where("decompress_state= ? and is_private= ?", DecompressStateDone, false).Find(&attachments); err != nil { return nil, err } @@ -377,7 +377,7 @@ func GetPrivateAttachments(username string) ([]*AttachmentUsername, error) { func getPrivateAttachments(e Engine, userID int64) ([]*AttachmentUsername, error) { attachments := make([]*AttachmentUsername, 0, 10) - if err := e.Table("attachment").Join("LEFT", "`user`", "attachment.uploader_id " + + if err := e.Table("attachment").Join("LEFT", "`user`", "attachment.uploader_id "+ "= `user`.id").Where("decompress_state= ? and uploader_id= ?", DecompressStateDone, userID).Find(&attachments); err != nil { return nil, err } @@ -401,11 +401,11 @@ func GetAllUserAttachments(userID int64) ([]*AttachmentUsername, error) { return append(attachsPub, attachsPri...), nil } - */ +*/ func getAllUserAttachments(e Engine, userID int64) ([]*AttachmentUsername, error) { attachments := make([]*AttachmentUsername, 0, 10) - if err := e.Table("attachment").Join("LEFT", "`user`", "attachment.uploader_id " + + if err := e.Table("attachment").Join("LEFT", "`user`", "attachment.uploader_id "+ "= `user`.id").Where("decompress_state= ? and (uploader_id= ? or is_private = ?)", DecompressStateDone, userID, false).Find(&attachments); err != nil { return nil, err } diff --git a/models/blockchain.go b/models/blockchain.go index a5b335184..ed13908d7 100755 --- a/models/blockchain.go +++ b/models/blockchain.go @@ -7,11 +7,13 @@ import ( ) type BlockChainCommitStatus int + const ( BlockChainCommitInit BlockChainCommitStatus = iota BlockChainCommitSuccess BlockChainCommitFailed ) + type BlockChain struct { ID int64 `xorm:"pk autoincr"` PrID int64 `xorm:"INDEX NOT NULL unique"` diff --git a/models/cloudbrain.go b/models/cloudbrain.go index 7244bc3ab..182a13a61 100755 --- a/models/cloudbrain.go +++ b/models/cloudbrain.go @@ -22,25 +22,25 @@ const ( JobFailed CloudbrainStatus = "FAILED" JobRunning CloudbrainStatus = "RUNNING" - JobTypeDebug JobType = "DEBUG" - JobTypeBenchmark JobType = "BENCHMARK" + JobTypeDebug JobType = "DEBUG" + JobTypeBenchmark JobType = "BENCHMARK" ) type Cloudbrain struct { ID int64 `xorm:"pk autoincr"` JobID string `xorm:"INDEX NOT NULL"` - JobType string `xorm:"INDEX NOT NULL DEFAULT 'DEBUG'"` - JobName string `xorm:"INDEX"` - Status string `xorm:"INDEX"` - UserID int64 `xorm:"INDEX"` - RepoID int64 `xorm:"INDEX"` - SubTaskName string `xorm:"INDEX"` + JobType string `xorm:"INDEX NOT NULL DEFAULT 'DEBUG'"` + JobName string `xorm:"INDEX"` + Status string `xorm:"INDEX"` + UserID int64 `xorm:"INDEX"` + RepoID int64 `xorm:"INDEX"` + SubTaskName string `xorm:"INDEX"` ContainerID string ContainerIp string CreatedUnix timeutil.TimeStamp `xorm:"INDEX created"` UpdatedUnix timeutil.TimeStamp `xorm:"INDEX updated"` - DeletedAt time.Time `xorm:"deleted"` - CanDebug bool `xorm:"-"` + DeletedAt time.Time `xorm:"deleted"` + CanDebug bool `xorm:"-"` User *User `xorm:"-"` Repo *Repository `xorm:"-"` @@ -64,17 +64,17 @@ type TaskRole struct { Command string `json:"command"` NeedIBDevice bool `json:"needIBDevice"` IsMainRole bool `json:"isMainRole"` - UseNNI bool `json:"useNNI"` + UseNNI bool `json:"useNNI"` } type StHostPath struct { - Path string `json:"path"` - MountPath string `json:"mountPath"` - ReadOnly bool `json:"readOnly"` + Path string `json:"path"` + MountPath string `json:"mountPath"` + ReadOnly bool `json:"readOnly"` } type Volume struct { - HostPath StHostPath `json:"hostPath"` + HostPath StHostPath `json:"hostPath"` } type CreateJobParams struct { @@ -87,9 +87,9 @@ type CreateJobParams struct { } type CreateJobResult struct { - Code string `json:"code"` - Msg string `json:"msg"` - Payload map[string]interface{} `json:"payload"` + Code string `json:"code"` + Msg string `json:"msg"` + Payload map[string]interface{} `json:"payload"` } type GetJobResult struct { @@ -99,8 +99,8 @@ type GetJobResult struct { } type GetImagesResult struct { - Code string `json:"code"` - Msg string `json:"msg"` + Code string `json:"code"` + Msg string `json:"msg"` Payload map[string]*ImageInfo `json:"payload"` } @@ -131,24 +131,23 @@ type TaskPod struct { ExitCode int `json:"exitCode"` ExitDiagnostics string `json:"exitDiagnostics"` RetriedCount int `json:"retriedCount"` - StartTime string - FinishedTime string + StartTime string + FinishedTime string } `json:"taskStatuses"` } - type TaskInfo struct { - Username string `json:"username"` - TaskName string `json:"task_name"` - CodeName string `json:"code_name"` + Username string `json:"username"` + TaskName string `json:"task_name"` + CodeName string `json:"code_name"` } func ConvertToTaskPod(input map[string]interface{}) (TaskPod, error) { data, _ := json.Marshal(input) var taskPod TaskPod err := json.Unmarshal(data, &taskPod) - taskPod.TaskStatuses[0].StartTime = time.Unix(taskPod.TaskStatuses[0].StartAt.Unix() + 8*3600, 0).UTC().Format("2006-01-02 15:04:05") - taskPod.TaskStatuses[0].FinishedTime = time.Unix(taskPod.TaskStatuses[0].FinishedAt.Unix() + 8*3600, 0).UTC().Format("2006-01-02 15:04:05") + taskPod.TaskStatuses[0].StartTime = time.Unix(taskPod.TaskStatuses[0].StartAt.Unix()+8*3600, 0).UTC().Format("2006-01-02 15:04:05") + taskPod.TaskStatuses[0].FinishedTime = time.Unix(taskPod.TaskStatuses[0].FinishedAt.Unix()+8*3600, 0).UTC().Format("2006-01-02 15:04:05") return taskPod, err } @@ -173,8 +172,8 @@ type JobResultPayload struct { AppExitDiagnostics string `json:"appExitDiagnostics"` AppExitType interface{} `json:"appExitType"` VirtualCluster string `json:"virtualCluster"` - StartTime string - EndTime string + StartTime string + EndTime string } `json:"jobStatus"` TaskRoles map[string]interface{} `json:"taskRoles"` Resource struct { @@ -220,42 +219,42 @@ func ConvertToJobResultPayload(input map[string]interface{}) (JobResultPayload, type ImagesResultPayload struct { Images []struct { - ID int `json:"id"` - Name string `json:"name"` - Place string `json:"place"` - Description string `json:"description"` - Provider string `json:"provider"` - Createtime string `json:"createtime"` - Remark string `json:"remark"` + ID int `json:"id"` + Name string `json:"name"` + Place string `json:"place"` + Description string `json:"description"` + Provider string `json:"provider"` + Createtime string `json:"createtime"` + Remark string `json:"remark"` } `json:"taskStatuses"` } type ImageInfo struct { - ID int `json:"id"` - Name string `json:"name"` - Place string `json:"place"` - Description string `json:"description"` - Provider string `json:"provider"` - Createtime string `json:"createtime"` - Remark string `json:"remark"` - PlaceView string + ID int `json:"id"` + Name string `json:"name"` + Place string `json:"place"` + Description string `json:"description"` + Provider string `json:"provider"` + Createtime string `json:"createtime"` + Remark string `json:"remark"` + PlaceView string } type CommitImageParams struct { - Ip string `json:"ip"` - TaskContainerId string `json:"taskContainerId"` - ImageTag string `json:"imageTag"` - ImageDescription string `json:"imageDescription"` + Ip string `json:"ip"` + TaskContainerId string `json:"taskContainerId"` + ImageTag string `json:"imageTag"` + ImageDescription string `json:"imageDescription"` } type CommitImageResult struct { - Code string `json:"code"` - Msg string `json:"msg"` - Payload map[string]interface{} `json:"payload"` + Code string `json:"code"` + Msg string `json:"msg"` + Payload map[string]interface{} `json:"payload"` } type StopJobResult struct { - Code string `json:"code"` - Msg string `json:"msg"` + Code string `json:"code"` + Msg string `json:"msg"` } func Cloudbrains(opts *CloudbrainsOptions) ([]*Cloudbrain, int64, error) { diff --git a/models/issue.go b/models/issue.go index 6e766bdf1..7bed58843 100755 --- a/models/issue.go +++ b/models/issue.go @@ -68,7 +68,7 @@ type Issue struct { IsLocked bool `xorm:"NOT NULL DEFAULT false"` //block_chain - Amount int + Amount int64 IsTransformed bool `xorm:"INDEX NOT NULL DEFAULT false"` } diff --git a/models/login_source.go b/models/login_source.go index 7153606a9..ca2aa5a4d 100755 --- a/models/login_source.go +++ b/models/login_source.go @@ -32,25 +32,25 @@ type LoginType int // Note: new type must append to the end of list to maintain compatibility. const ( - LoginNoType LoginType = iota - LoginPlain // 1 - LoginLDAP // 2 - LoginSMTP // 3 - LoginPAM // 4 - LoginDLDAP // 5 - LoginOAuth2 // 6 - LoginSSPI // 7 - LoginCloudBrain // 8 + LoginNoType LoginType = iota + LoginPlain // 1 + LoginLDAP // 2 + LoginSMTP // 3 + LoginPAM // 4 + LoginDLDAP // 5 + LoginOAuth2 // 6 + LoginSSPI // 7 + LoginCloudBrain // 8 ) // LoginNames contains the name of LoginType values. var LoginNames = map[LoginType]string{ - LoginLDAP: "LDAP (via BindDN)", - LoginDLDAP: "LDAP (simple auth)", // Via direct bind - LoginSMTP: "SMTP", - LoginPAM: "PAM", - LoginOAuth2: "OAuth2", - LoginSSPI: "SPNEGO with SSPI", + LoginLDAP: "LDAP (via BindDN)", + LoginDLDAP: "LDAP (simple auth)", // Via direct bind + LoginSMTP: "SMTP", + LoginPAM: "PAM", + LoginOAuth2: "OAuth2", + LoginSSPI: "SPNEGO with SSPI", LoginCloudBrain: "Cloud Brain", } @@ -849,14 +849,14 @@ func LoginViaCloudBrain(user *User, login, password string, source *LoginSource) } user = &User{ - LowerName: strings.ToLower(login), - Name: login, - Email: cloudBrainUser.Email, - LoginType: source.Type, - LoginSource: source.ID, - LoginName: login, - IsActive: true, - Token: token, + LowerName: strings.ToLower(login), + Name: login, + Email: cloudBrainUser.Email, + LoginType: source.Type, + LoginSource: source.ID, + LoginName: login, + IsActive: true, + Token: token, } err = CreateUser(user) diff --git a/models/repo.go b/models/repo.go index bef634941..1228a79ba 100755 --- a/models/repo.go +++ b/models/repo.go @@ -6,12 +6,14 @@ package models import ( - "code.gitea.io/gitea/modules/blockchain" "context" "crypto/md5" "errors" "fmt" "html/template" + "sync" + + "code.gitea.io/gitea/modules/blockchain" // Needed for jpeg support _ "image/jpeg" @@ -144,7 +146,7 @@ const ( ) const ( - RepoBlockChainInit RepoBlockChainStatus = iota + RepoBlockChainInit RepoBlockChainStatus = iota RepoBlockChainSuccess RepoBlockChainFailed ) @@ -208,6 +210,9 @@ type Repository struct { Balance string `xorm:"NOT NULL DEFAULT '0'"` BlockChainStatus RepoBlockChainStatus `xorm:"NOT NULL DEFAULT 0"` + // git clone total count + CloneCnt int64 `xorm:"NOT NULL DEFAULT 0"` + CreatedUnix timeutil.TimeStamp `xorm:"INDEX created"` UpdatedUnix timeutil.TimeStamp `xorm:"INDEX updated"` } @@ -1408,7 +1413,7 @@ func updateRepository(e Engine, repo *Repository, visibilityChanged bool) (err e repo.Description = repo.Description[:255] } - */ + */ if len(repo.Website) > 255 { repo.Website = repo.Website[:255] } @@ -2397,6 +2402,15 @@ func (repo *Repository) GetTreePathLock(treePath string) (*LFSLock, error) { return nil, nil } +var lck sync.Mutex + +func (repo *Repository) IncreaseCloneCnt() { + lck.Lock() + defer lck.Unlock() + repo.CloneCnt++ + _ = UpdateRepositoryCols(repo, "clone_cnt") +} + func updateRepositoryCols(e Engine, repo *Repository, cols ...string) error { _, err := e.ID(repo.ID).Cols(cols...).Update(repo) return err diff --git a/models/user.go b/models/user.go index 709fc2fd2..4d282f477 100755 --- a/models/user.go +++ b/models/user.go @@ -171,7 +171,7 @@ type User struct { Theme string `xorm:"NOT NULL DEFAULT ''"` //CloudBrain - Token string `xorm:"VARCHAR(1024)"` + Token string `xorm:"VARCHAR(1024)"` //BlockChain PublicKey string `xorm:"INDEX"` diff --git a/modules/auth/cloudbrain.go b/modules/auth/cloudbrain.go index ce2733afb..2b150cf75 100755 --- a/modules/auth/cloudbrain.go +++ b/modules/auth/cloudbrain.go @@ -7,16 +7,16 @@ import ( // CreateDatasetForm form for dataset page type CreateCloudBrainForm struct { - JobName string `form:"job_name" binding:"Required"` - Image string `form:"image" binding:"Required"` - Command string `form:"command" binding:"Required"` + JobName string `form:"job_name" binding:"Required"` + Image string `form:"image" binding:"Required"` + Command string `form:"command" binding:"Required"` Attachment string `form:"attachment" binding:"Required"` - JobType string `form:"job_type" binding:"Required"` + JobType string `form:"job_type" binding:"Required"` } type CommitImageCloudBrainForm struct { Description string `form:"description" binding:"Required"` - Tag string `form:"tag" binding:"Required"` + Tag string `form:"tag" binding:"Required"` } func (f *CreateCloudBrainForm) Validate(ctx *macaron.Context, errs binding.Errors) binding.Errors { diff --git a/modules/auth/cloudbrain/cloudbrain.go b/modules/auth/cloudbrain/cloudbrain.go index 4020faa5f..acab326b7 100755 --- a/modules/auth/cloudbrain/cloudbrain.go +++ b/modules/auth/cloudbrain/cloudbrain.go @@ -12,7 +12,7 @@ import ( ) const ( - UrlToken = "/rest-server/api/v1/token/" + UrlToken = "/rest-server/api/v1/token/" UrlGetUserInfo = "/rest-server/api/v1/user/" TokenTypeBear = "Bearer " @@ -21,29 +21,29 @@ const ( ) type RespAuth struct { - AccessToken string `json:"access_token"` - RefreshToken string `json:"refresh_token"` - TokenType string `json:"token_type"` - ExpiresIn int `json:"expires_in"` - Error string `json:"error"` + AccessToken string `json:"access_token"` + RefreshToken string `json:"refresh_token"` + TokenType string `json:"token_type"` + ExpiresIn int `json:"expires_in"` + Error string `json:"error"` ErrorDescription string `json:"error_description"` } type RespToken struct { - Code string `json:"code"` - Message string `json:"msg"` + Code string `json:"code"` + Message string `json:"msg"` Payload PayloadToken `json:"payload"` } type PayloadToken struct { Username string `json:"username"` - Token string `json:"token"` - IsAdmin bool `json:"admin"` + Token string `json:"token"` + IsAdmin bool `json:"admin"` } type RespUserInfo struct { - Code string `json:"code"` - Message string `json:"msg"` + Code string `json:"code"` + Message string `json:"msg"` Payload PayloadUserInfo `json:"payload"` } @@ -57,13 +57,13 @@ type StUserInfo struct { type CloudBrainUser struct { UserName string `json:"username"` - Email string `json:"email"` + Email string `json:"email"` } func UserValidate(username string, password string) (string, error) { values := map[string]string{"username": username, "password": password} jsonValue, _ := json.Marshal(values) - resp, err := http.Post(setting.RestServerHost + UrlToken, + resp, err := http.Post(setting.RestServerHost+UrlToken, "application/json", bytes.NewBuffer(jsonValue)) if err != nil { @@ -73,7 +73,7 @@ func UserValidate(username string, password string) (string, error) { defer resp.Body.Close() - body,err := ioutil.ReadAll(resp.Body) + body, err := ioutil.ReadAll(resp.Body) if err != nil { log.Error("read resp body failed:" + err.Error()) return "", err @@ -98,14 +98,14 @@ func GetUserInfo(username string, token string) (*CloudBrainUser, error) { user := &CloudBrainUser{} client := &http.Client{} - reqHttp,err := http.NewRequest("GET", setting.RestServerHost + UrlGetUserInfo + username, strings.NewReader("")) + reqHttp, err := http.NewRequest("GET", setting.RestServerHost+UrlGetUserInfo+username, strings.NewReader("")) if err != nil { log.Error("new req failed:", err.Error()) return nil, err } - reqHttp.Header.Set("Authorization", TokenTypeBear + token) - resp,err := client.Do(reqHttp) + reqHttp.Header.Set("Authorization", TokenTypeBear+token) + resp, err := client.Do(reqHttp) if err != nil { log.Error("req rest-server failed:", err.Error()) return nil, err @@ -113,7 +113,7 @@ func GetUserInfo(username string, token string) (*CloudBrainUser, error) { defer resp.Body.Close() - body,err := ioutil.ReadAll(resp.Body) + body, err := ioutil.ReadAll(resp.Body) if err != nil { log.Error("read resp body failed:", err.Error()) return nil, err diff --git a/modules/auth/repo_form.go b/modules/auth/repo_form.go index 7d0e9b439..e34da18fa 100755 --- a/modules/auth/repo_form.go +++ b/modules/auth/repo_form.go @@ -369,6 +369,7 @@ type CreateIssueForm struct { AssigneeID int64 Content string Files []string + Rewards int64 } // Validate validates the fields diff --git a/modules/blockchain/blockchain.go b/modules/blockchain/blockchain.go index 6ebf701da..00aeb8808 100755 --- a/modules/blockchain/blockchain.go +++ b/modules/blockchain/blockchain.go @@ -1,14 +1,12 @@ package blockchain const ( - Command = `pip3 install jupyterlab==2.2.5 -i https://pypi.tuna.tsinghua.edu.cn/simple;service ssh stop;jupyter lab --no-browser --ip=0.0.0.0 --allow-root --notebook-dir="/code" --port=80 --LabApp.token="" --LabApp.allow_origin="self https://cloudbrain.pcl.ac.cn"` - CodeMountPath = "/code" - DataSetMountPath = "/dataset" - ModelMountPath = "/model" + Command = `pip3 install jupyterlab==2.2.5 -i https://pypi.tuna.tsinghua.edu.cn/simple;service ssh stop;jupyter lab --no-browser --ip=0.0.0.0 --allow-root --notebook-dir="/code" --port=80 --LabApp.token="" --LabApp.allow_origin="self https://cloudbrain.pcl.ac.cn"` + CodeMountPath = "/code" + DataSetMountPath = "/dataset" + ModelMountPath = "/model" BenchMarkMountPath = "/benchmark" - TaskInfoName = "/taskInfo" + TaskInfoName = "/taskInfo" SubTaskName = "task1" - - ) diff --git a/modules/blockchain/resty.go b/modules/blockchain/resty.go index 09178181a..4b5de68f3 100755 --- a/modules/blockchain/resty.go +++ b/modules/blockchain/resty.go @@ -23,20 +23,20 @@ const ( ) type CreateAccountResult struct { - Code int `json:"code"` - Msg string `json:"message"` - Payload map[string]interface{} `json:"data"` + Code int `json:"code"` + Msg string `json:"message"` + Payload map[string]interface{} `json:"data"` } type GetBalanceResult struct { - Code int `json:"code"` - Msg string `json:"message"` - Payload map[string]interface{} `json:"data"` + Code int `json:"code"` + Msg string `json:"message"` + Data string `json:"data"` } type NewRepoResult struct { - Code int `json:"code"` - Msg string `json:"message"` + Code int `json:"code"` + Msg string `json:"message"` //Data string `json:"data"` } @@ -49,7 +49,7 @@ type ContributeResult struct { type SetIssueResult struct { Code int `json:"code"` Msg string `json:"message"` - //Payload map[string]interface{} `json:"data"` + //Data string `json:"data"` } func getRestyClient() *resty.Client { @@ -86,9 +86,9 @@ func NewRepo(repoID, publicKey, repoName string) (*NewRepoResult, error) { res, err := client.R(). SetHeader("Accept", "application/json"). SetQueryParams(map[string]string{ - "repoId" : repoID, - "creator" : publicKey, - "repoName" : repoName, + "repoId": repoID, + "creator": publicKey, + "repoName": repoName, }). SetResult(&result). Get(setting.BlockChainHost + UrlNewRepo) @@ -111,8 +111,8 @@ func GetBalance(contractAddress, contributor string) (*GetBalanceResult, error) res, err := client.R(). SetHeader("Accept", "application/json"). SetQueryParams(map[string]string{ - "contractAddress" : contractAddress, - "contributor" : contributor, + "contractAddress": contractAddress, + "contributor": contributor, }). SetResult(&result). Get(setting.BlockChainHost + UrlGetBalance) diff --git a/modules/cloudbrain/cloudbrain.go b/modules/cloudbrain/cloudbrain.go index dccbee5c6..dedfb55f6 100755 --- a/modules/cloudbrain/cloudbrain.go +++ b/modules/cloudbrain/cloudbrain.go @@ -10,12 +10,12 @@ import ( ) const ( - Command = `pip3 install jupyterlab==2.2.5 -i https://pypi.tuna.tsinghua.edu.cn/simple;service ssh stop;jupyter lab --no-browser --ip=0.0.0.0 --allow-root --notebook-dir="/code" --port=80 --LabApp.token="" --LabApp.allow_origin="self https://cloudbrain.pcl.ac.cn"` - CodeMountPath = "/code" - DataSetMountPath = "/dataset" - ModelMountPath = "/model" + Command = `pip3 install jupyterlab==2.2.5 -i https://pypi.tuna.tsinghua.edu.cn/simple;service ssh stop;jupyter lab --no-browser --ip=0.0.0.0 --allow-root --notebook-dir="/code" --port=80 --LabApp.token="" --LabApp.allow_origin="self https://cloudbrain.pcl.ac.cn"` + CodeMountPath = "/code" + DataSetMountPath = "/dataset" + ModelMountPath = "/model" BenchMarkMountPath = "/benchmark" - TaskInfoName = "/taskInfo" + TaskInfoName = "/taskInfo" SubTaskName = "task1" @@ -46,36 +46,36 @@ func GenerateTask(ctx *context.Context, jobName, image, command, uuid, codePath, Command: command, NeedIBDevice: false, IsMainRole: false, - UseNNI: false, + UseNNI: false, }, }, Volumes: []models.Volume{ { HostPath: models.StHostPath{ - Path: codePath, - MountPath: CodeMountPath, - ReadOnly: false, + Path: codePath, + MountPath: CodeMountPath, + ReadOnly: false, }, }, { HostPath: models.StHostPath{ - Path: dataActualPath, - MountPath: DataSetMountPath, - ReadOnly: true, + Path: dataActualPath, + MountPath: DataSetMountPath, + ReadOnly: true, }, }, { HostPath: models.StHostPath{ - Path: modelPath, - MountPath: ModelMountPath, - ReadOnly: false, + Path: modelPath, + MountPath: ModelMountPath, + ReadOnly: false, }, }, { HostPath: models.StHostPath{ - Path: benchmarkPath, - MountPath: BenchMarkMountPath, - ReadOnly: true, + Path: benchmarkPath, + MountPath: BenchMarkMountPath, + ReadOnly: true, }, }, }, @@ -91,13 +91,13 @@ func GenerateTask(ctx *context.Context, jobName, image, command, uuid, codePath, var jobID = jobResult.Payload["jobId"].(string) err = models.CreateCloudbrain(&models.Cloudbrain{ - Status: string(models.JobWaiting), - UserID: ctx.User.ID, - RepoID: ctx.Repo.Repository.ID, - JobID: jobID, - JobName: jobName, + Status: string(models.JobWaiting), + UserID: ctx.User.ID, + RepoID: ctx.Repo.Repository.ID, + JobID: jobID, + JobName: jobName, SubTaskName: SubTaskName, - JobType: jobType, + JobType: jobType, }) if err != nil { diff --git a/modules/context/auth.go b/modules/context/auth.go index 34b74523d..6aee002b5 100755 --- a/modules/context/auth.go +++ b/modules/context/auth.go @@ -21,10 +21,10 @@ import ( // ToggleOptions contains required or check options type ToggleOptions struct { - SignInRequired bool - SignOutRequired bool - AdminRequired bool - DisableCSRF bool + SignInRequired bool + SignOutRequired bool + AdminRequired bool + DisableCSRF bool BasicAuthRequired bool } @@ -149,7 +149,7 @@ func basicAuth(ctx *Context) bool { var siteAuth = base64.StdEncoding.EncodeToString([]byte(setting.CBAuthUser + ":" + setting.CBAuthPassword)) auth := ctx.Req.Header.Get("Authorization") - if !marc_auth.SecureCompare(auth, "Basic " + siteAuth) { + if !marc_auth.SecureCompare(auth, "Basic "+siteAuth) { return false } @@ -158,6 +158,6 @@ func basicAuth(ctx *Context) bool { } func basicUnauthorized(res http.ResponseWriter) { - res.Header().Set("WWW-Authenticate", "Basic realm=\"" + marc_auth.BasicRealm + "\"") + res.Header().Set("WWW-Authenticate", "Basic realm=\""+marc_auth.BasicRealm+"\"") http.Error(res, "Not Authorized", http.StatusUnauthorized) } diff --git a/modules/minio_ext/api-error-response.go b/modules/minio_ext/api-error-response.go index b515c829c..5dee08500 100755 --- a/modules/minio_ext/api-error-response.go +++ b/modules/minio_ext/api-error-response.go @@ -27,9 +27,11 @@ type ErrorResponse struct { func (e ErrorResponse) Error() string { return e.Message } + const ( reportIssue = "Please report this issue at https://github.com/minio/minio/issues." ) + // httpRespToErrorResponse returns a new encoded ErrorResponse // structure as error. func httpRespToErrorResponse(resp *http.Response, bucketName, objectName string) error { @@ -122,6 +124,7 @@ func ToErrorResponse(err error) ErrorResponse { return ErrorResponse{} } } + // ErrInvalidArgument - Invalid argument response. func ErrInvalidArgument(message string) error { return ErrorResponse{ diff --git a/modules/minio_ext/api-list.go b/modules/minio_ext/api-list.go index 5904431e7..b9dc27cb5 100755 --- a/modules/minio_ext/api-list.go +++ b/modules/minio_ext/api-list.go @@ -38,7 +38,6 @@ func (c Client) ListObjectParts(bucketName, objectName, uploadID string) (partsI return partsInfo, nil } - // listObjectPartsQuery (List Parts query) // - lists some or all (up to 1000) parts that have been uploaded // for a specific multipart upload diff --git a/modules/minio_ext/api-s3-datatypes.go b/modules/minio_ext/api-s3-datatypes.go index df13ca380..37412dbbb 100755 --- a/modules/minio_ext/api-s3-datatypes.go +++ b/modules/minio_ext/api-s3-datatypes.go @@ -68,4 +68,4 @@ type ListObjectPartsResult struct { ObjectParts []ObjectPart `xml:"Part"` EncodingType string -} \ No newline at end of file +} diff --git a/modules/minio_ext/api.go b/modules/minio_ext/api.go index d3d7272e5..79583b99b 100755 --- a/modules/minio_ext/api.go +++ b/modules/minio_ext/api.go @@ -142,7 +142,6 @@ func (r *lockedRandSource) Seed(seed int64) { r.lk.Unlock() } - // Different types of url lookup supported by the server.Initialized to BucketLookupAuto const ( BucketLookupAuto BucketLookupType = iota @@ -904,8 +903,7 @@ func (c Client) newRequest(method string, metadata requestMetadata) (req *http.R return req, nil } - -func (c Client) GenUploadPartSignedUrl(uploadID string, bucketName string, objectName string, partNumber int, size int64, expires time.Duration, bucketLocation string) (string, error){ +func (c Client) GenUploadPartSignedUrl(uploadID string, bucketName string, objectName string, partNumber int, size int64, expires time.Duration, bucketLocation string) (string, error) { signedUrl := "" // Input validation. @@ -939,17 +937,17 @@ func (c Client) GenUploadPartSignedUrl(uploadID string, bucketName string, objec customHeader := make(http.Header) reqMetadata := requestMetadata{ - presignURL: true, - bucketName: bucketName, - objectName: objectName, - queryValues: urlValues, - customHeader: customHeader, + presignURL: true, + bucketName: bucketName, + objectName: objectName, + queryValues: urlValues, + customHeader: customHeader, //contentBody: reader, - contentLength: size, + contentLength: size, //contentMD5Base64: md5Base64, //contentSHA256Hex: sha256Hex, - expires: int64(expires/time.Second), - bucketLocation: bucketLocation, + expires: int64(expires / time.Second), + bucketLocation: bucketLocation, } req, err := c.newRequest("PUT", reqMetadata) @@ -959,10 +957,9 @@ func (c Client) GenUploadPartSignedUrl(uploadID string, bucketName string, objec } signedUrl = req.URL.String() - return signedUrl,nil + return signedUrl, nil } - // executeMethod - instantiates a given method, and retries the // request upon any error up to maxRetries attempts in a binomially // delayed manner using a standard back off algorithm. diff --git a/modules/minio_ext/object.go b/modules/minio_ext/object.go index 3a075e457..12fed7d5c 100755 --- a/modules/minio_ext/object.go +++ b/modules/minio_ext/object.go @@ -8,10 +8,12 @@ import ( // StringMap represents map with custom UnmarshalXML type StringMap map[string]string + // CommonPrefix container for prefix response. type CommonPrefix struct { Prefix string } + // ObjectInfo container for object metadata. type ObjectInfo struct { // An ETag is optionally set to md5sum of an object. In case of multipart objects, @@ -44,6 +46,7 @@ type ObjectInfo struct { // Error Err error `json:"-"` } + // ListBucketResult container for listObjects response. type ListBucketResult struct { // A response can contain CommonPrefixes only if you have diff --git a/modules/setting/setting.go b/modules/setting/setting.go index f3888b9e7..c11c70ccc 100755 --- a/modules/setting/setting.go +++ b/modules/setting/setting.go @@ -427,26 +427,26 @@ var ( ResultBackend string //decompress config - DecompressAddress string - AuthUser string - AuthPassword string + DecompressAddress string + AuthUser string + AuthPassword string //cloudbrain config - CBAuthUser string - CBAuthPassword string - RestServerHost string - JobPath string - JobType string - DebugServerHost string + CBAuthUser string + CBAuthPassword string + RestServerHost string + JobPath string + JobType string + DebugServerHost string //benchmark config - IsBenchmarkEnabled bool - BenchmarkCode string - BenchmarkServerHost string + IsBenchmarkEnabled bool + BenchmarkCode string + BenchmarkServerHost string //blockchain config - BlockChainHost string - CommitValidDate string + BlockChainHost string + CommitValidDate string ) // DateLang transforms standard language locale name to corresponding value in datetime plugin. diff --git a/modules/storage/minio_ext.go b/modules/storage/minio_ext.go index e110138f7..2f738ebad 100755 --- a/modules/storage/minio_ext.go +++ b/modules/storage/minio_ext.go @@ -150,7 +150,7 @@ func CompleteMultiPartUpload(uuid string, uploadID string) (string, error) { for _, partInfo := range partInfos { complMultipartUpload.Parts = append(complMultipartUpload.Parts, miniov6.CompletePart{ PartNumber: partInfo.PartNumber, - ETag: partInfo.ETag, + ETag: partInfo.ETag, }) } diff --git a/modules/timer/timer.go b/modules/timer/timer.go index 176f84423..58cc13084 100755 --- a/modules/timer/timer.go +++ b/modules/timer/timer.go @@ -15,7 +15,7 @@ func init() { specCheckBlockChainUserSuccess := "*/10 * * * *" c.AddFunc(specCheckBlockChainUserSuccess, repo.HandleBlockChainUnSuccessUsers) - specCheckRepoBlockChainSuccess := "*/5 * * * *" + specCheckRepoBlockChainSuccess := "*/1 * * * *" c.AddFunc(specCheckRepoBlockChainSuccess, repo.HandleBlockChainUnSuccessRepos) specCheckUnTransformedPRs := "*/1 * * * *" diff --git a/options/locale/locale_en-US.ini b/options/locale/locale_en-US.ini index edb3b2ce0..16a739406 100644 --- a/options/locale/locale_en-US.ini +++ b/options/locale/locale_en-US.ini @@ -747,6 +747,7 @@ cloudbrain=cloudbrain cloudbrain.new=New cloudbrain cloudbrain.desc=cloudbrain cloudbrain.cancel=Cancel +clone_cnt=download template.items = Template Items template.git_content = Git Content (Default Branch) diff --git a/options/locale/locale_zh-CN.ini b/options/locale/locale_zh-CN.ini index 0398d5655..c2f37b976 100755 --- a/options/locale/locale_zh-CN.ini +++ b/options/locale/locale_zh-CN.ini @@ -753,6 +753,7 @@ cloudbrain.new=新建任务 cloudbrain.desc=云脑功能 cloudbrain.cancel=取消 cloudbrain.commit_image=提交 +clone_cnt=次下载 template.items=模板选项 template.git_content=Git数据(默认分支) diff --git a/routers/private/serv.go b/routers/private/serv.go index d5b5fcc8f..f405d1d75 100644 --- a/routers/private/serv.go +++ b/routers/private/serv.go @@ -126,6 +126,12 @@ func ServCommand(ctx *macaron.Context) { } } + for _, verb := range ctx.QueryStrings("verb") { // clone_cnt + if verb == "git-upload-pack" { + go repo.IncreaseCloneCnt() + } + } + if repoExist { repo.OwnerName = ownerName results.RepoID = repo.ID diff --git a/routers/repo/attachment.go b/routers/repo/attachment.go index f474f88d6..0258a5373 100755 --- a/routers/repo/attachment.go +++ b/routers/repo/attachment.go @@ -30,10 +30,10 @@ const ( ) type CloudBrainDataset struct { - UUID string `json:"id"` - Name string `json:"name"` - Path string `json:"place"` - UserName string `json:"provider"` + UUID string `json:"id"` + Name string `json:"name"` + Path string `json:"place"` + UserName string `json:"provider"` CreateTime string `json:"created_at"` } @@ -402,13 +402,13 @@ func GetSuccessChunks(ctx *context.Context) { if attach == nil { ctx.JSON(200, map[string]string{ - "uuid": fileChunk.UUID, - "uploaded": strconv.Itoa(fileChunk.IsUploaded), - "uploadID": fileChunk.UploadID, - "chunks": string(chunks), - "attachID": "0", - "datasetID": "0", - "fileName": "", + "uuid": fileChunk.UUID, + "uploaded": strconv.Itoa(fileChunk.IsUploaded), + "uploadID": fileChunk.UploadID, + "chunks": string(chunks), + "attachID": "0", + "datasetID": "0", + "fileName": "", "datasetName": "", }) return @@ -421,13 +421,13 @@ func GetSuccessChunks(ctx *context.Context) { } ctx.JSON(200, map[string]string{ - "uuid": fileChunk.UUID, - "uploaded": strconv.Itoa(fileChunk.IsUploaded), - "uploadID": fileChunk.UploadID, - "chunks": string(chunks), - "attachID": strconv.Itoa(int(attachID)), - "datasetID": strconv.Itoa(int(attach.DatasetID)), - "fileName": attach.Name, + "uuid": fileChunk.UUID, + "uploaded": strconv.Itoa(fileChunk.IsUploaded), + "uploadID": fileChunk.UploadID, + "chunks": string(chunks), + "attachID": strconv.Itoa(int(attachID)), + "datasetID": strconv.Itoa(int(attach.DatasetID)), + "fileName": attach.Name, "datasetName": dataset.Title, }) @@ -624,13 +624,13 @@ func HandleUnDecompressAttachment() { return } -func QueryAllPublicDataset(ctx *context.Context){ +func QueryAllPublicDataset(ctx *context.Context) { attachs, err := models.GetAllPublicAttachments() if err != nil { ctx.JSON(200, map[string]string{ "result_code": "-1", - "error_msg": err.Error(), - "data": "", + "error_msg": err.Error(), + "data": "", }) return } @@ -638,14 +638,14 @@ func QueryAllPublicDataset(ctx *context.Context){ queryDatasets(ctx, attachs) } -func QueryPrivateDataset(ctx *context.Context){ +func QueryPrivateDataset(ctx *context.Context) { username := ctx.Params(":username") attachs, err := models.GetPrivateAttachments(username) if err != nil { ctx.JSON(200, map[string]string{ "result_code": "-1", - "error_msg": err.Error(), - "data": "", + "error_msg": err.Error(), + "data": "", }) return } @@ -663,14 +663,14 @@ func queryDatasets(ctx *context.Context, attachs []*models.AttachmentUsername) { log.Info("dataset is null") ctx.JSON(200, map[string]string{ "result_code": "0", - "error_msg": "", - "data": "", + "error_msg": "", + "data": "", }) return } for _, attch := range attachs { - has,err := storage.Attachments.HasObject(models.AttachmentRelativePath(attch.UUID)) + has, err := storage.Attachments.HasObject(models.AttachmentRelativePath(attch.UUID)) if err != nil || !has { continue } @@ -686,21 +686,21 @@ func queryDatasets(ctx *context.Context, attachs []*models.AttachmentUsername) { attch.CreatedUnix.Format("2006-01-02 03:04:05 PM")}) } - data,err := json.Marshal(datasets) + data, err := json.Marshal(datasets) if err != nil { log.Error("json.Marshal failed:", err.Error()) ctx.JSON(200, map[string]string{ "result_code": "-1", - "error_msg": err.Error(), - "data": "", + "error_msg": err.Error(), + "data": "", }) return } ctx.JSON(200, map[string]string{ "result_code": "0", - "error_msg": "", - "data": string(data), + "error_msg": "", + "data": string(data), }) return } diff --git a/routers/repo/blockchain.go b/routers/repo/blockchain.go index 72bd2a0de..cd9fdd550 100755 --- a/routers/repo/blockchain.go +++ b/routers/repo/blockchain.go @@ -11,13 +11,13 @@ import ( ) type BlockChainInitNotify struct { - RepoId int64 `json:"repoId"` - ContractAddress string `json:"contractAddress"` + RepoId int64 `json:"repoId"` + ContractAddress string `json:"contractAddress"` } type BlockChainCommitNotify struct { - CommitID string `json:"commitId"` - TransactionHash string `json:"txHash"` + CommitID string `json:"commitId"` + TransactionHash string `json:"txHash"` } func HandleBlockChainInitNotify(ctx *context.Context) { @@ -29,8 +29,8 @@ func HandleBlockChainInitNotify(ctx *context.Context) { if err != nil { log.Error("GetRepositoryByID failed:", err.Error()) ctx.JSON(200, map[string]string{ - "code" : "-1", - "message" : "internal error", + "code": "-1", + "message": "internal error", }) return } @@ -38,8 +38,8 @@ func HandleBlockChainInitNotify(ctx *context.Context) { if repo.BlockChainStatus == models.RepoBlockChainSuccess && len(repo.ContractAddress) != 0 { log.Error("the repo has been RepoBlockChainSuccess:", req.RepoId) ctx.JSON(200, map[string]string{ - "code" : "-1", - "message" : "the repo has been RepoBlockChainSuccess", + "code": "-1", + "message": "the repo has been RepoBlockChainSuccess", }) return } @@ -50,14 +50,14 @@ func HandleBlockChainInitNotify(ctx *context.Context) { if err = models.UpdateRepositoryCols(repo, "block_chain_status", "contract_address"); err != nil { log.Error("UpdateRepositoryCols failed:", err.Error()) ctx.JSON(200, map[string]string{ - "code" : "-1", - "message" : "internal error", + "code": "-1", + "message": "internal error", }) return } ctx.JSON(200, map[string]string{ - "code": "0", + "code": "0", "message": "", }) } @@ -68,8 +68,8 @@ func HandleBlockChainCommitNotify(ctx *context.Context) { if err := json.Unmarshal(data, &req); err != nil { log.Error("json.Unmarshal failed:", err.Error()) ctx.JSON(200, map[string]string{ - "code" : "-1", - "message" : "response data error", + "code": "-1", + "message": "response data error", }) return } @@ -78,8 +78,8 @@ func HandleBlockChainCommitNotify(ctx *context.Context) { if err != nil { log.Error("GetRepositoryByID failed:", err.Error()) ctx.JSON(200, map[string]string{ - "code" : "-1", - "message" : "internal error", + "code": "-1", + "message": "internal error", }) return } @@ -87,8 +87,8 @@ func HandleBlockChainCommitNotify(ctx *context.Context) { if blockChain.Status == models.BlockChainCommitSuccess { log.Error("the commit has been BlockChainCommitReady:", blockChain.RepoID) ctx.JSON(200, map[string]string{ - "code" : "-1", - "message" : "the commit has been BlockChainCommitReady", + "code": "-1", + "message": "the commit has been BlockChainCommitReady", }) return } @@ -99,14 +99,14 @@ func HandleBlockChainCommitNotify(ctx *context.Context) { if err = models.UpdateBlockChainCols(blockChain, "status", "transaction_hash"); err != nil { log.Error("UpdateBlockChainCols failed:", err.Error()) ctx.JSON(200, map[string]string{ - "code" : "-1", - "message" : "internal error", + "code": "-1", + "message": "internal error", }) return } ctx.JSON(200, map[string]string{ - "code": "0", + "code": "0", "message": "", }) } diff --git a/routers/repo/cloudbrain.go b/routers/repo/cloudbrain.go index d22d44ced..5b19166be 100755 --- a/routers/repo/cloudbrain.go +++ b/routers/repo/cloudbrain.go @@ -55,7 +55,7 @@ func CloudBrainIndex(ctx *context.Context) { timestamp := time.Now().Unix() for i, task := range ciTasks { - if task.Status == string(models.JobRunning) && (timestamp - int64(task.CreatedUnix) > 30){ + if task.Status == string(models.JobRunning) && (timestamp-int64(task.CreatedUnix) > 30) { ciTasks[i].CanDebug = true } else { ciTasks[i].CanDebug = false @@ -90,9 +90,9 @@ func CloudBrainNew(ctx *context.Context) { ctx.Data["error"] = err.Error() } - for i,payload := range result.Payload { - if strings.HasPrefix(result.Payload[i].Place,"192.168") { - result.Payload[i].PlaceView = payload.Place[strings.Index(payload.Place, "/"): len(payload.Place)] + for i, payload := range result.Payload { + if strings.HasPrefix(result.Payload[i].Place, "192.168") { + result.Payload[i].PlaceView = payload.Place[strings.Index(payload.Place, "/"):len(payload.Place)] } else { result.Payload[i].PlaceView = payload.Place } @@ -205,29 +205,29 @@ func CloudBrainCommitImage(ctx *context.Context, form auth.CommitImageCloudBrain if err != nil { ctx.JSON(200, map[string]string{ "result_code": "-1", - "error_msg": "GetCloudbrainByJobID failed", + "error_msg": "GetCloudbrainByJobID failed", }) return } err = cloudbrain.CommitImage(jobID, models.CommitImageParams{ - Ip: task.ContainerIp, - TaskContainerId: task.ContainerID, - ImageDescription: form.Description, - ImageTag: form.Tag, + Ip: task.ContainerIp, + TaskContainerId: task.ContainerID, + ImageDescription: form.Description, + ImageTag: form.Tag, }) if err != nil { log.Error("CommitImage(%s) failed:", task.JobName, err.Error()) ctx.JSON(200, map[string]string{ "result_code": "-1", - "error_msg": "CommitImage failed", + "error_msg": "CommitImage failed", }) return } ctx.JSON(200, map[string]string{ "result_code": "0", - "error_msg": "", + "error_msg": "", }) } diff --git a/routers/repo/dir.go b/routers/repo/dir.go index a44227c66..388af34ec 100755 --- a/routers/repo/dir.go +++ b/routers/repo/dir.go @@ -21,15 +21,15 @@ const ( type FileInfo struct { FileName string `json:"FileName"` ModTime string `json:"ModTime"` - IsDir bool `json:"IsDir"` - Size int64 `json:"Size"` + IsDir bool `json:"IsDir"` + Size int64 `json:"Size"` ParenDir string `json:"ParenDir"` UUID string `json:"UUID"` } type RespGetDirs struct { ResultCode string `json:"resultCode"` - FileInfos string `json:"fileInfos"` + FileInfos string `json:"fileInfos"` } func DirIndex(ctx *context.Context) { @@ -80,7 +80,7 @@ func DirIndex(ctx *context.Context) { ctx.HTML(200, tplDirIndex) } -func getDirs(uuid string, parentDir string) (string,error) { +func getDirs(uuid string, parentDir string) (string, error) { var dirs string var req string if parentDir == "" { diff --git a/routers/repo/http.go b/routers/repo/http.go index 650642a58..ed6276466 100644 --- a/routers/repo/http.go +++ b/routers/repo/http.go @@ -313,6 +313,10 @@ func HTTP(ctx *context.Context) { environ = append(environ, models.ProtectedBranchRepoID+fmt.Sprintf("=%d", repo.ID)) + if service == "git-upload-pack" { // clone_cnt + go repo.IncreaseCloneCnt() + } + w := ctx.Resp r := ctx.Req.Request cfg := &serviceConfig{ diff --git a/routers/repo/issue.go b/routers/repo/issue.go old mode 100644 new mode 100755 index 1e8f1d81a..e23d10b92 --- a/routers/repo/issue.go +++ b/routers/repo/issue.go @@ -7,6 +7,7 @@ package repo import ( "bytes" + "code.gitea.io/gitea/modules/blockchain" "errors" "fmt" "io/ioutil" @@ -509,6 +510,21 @@ func NewIssue(ctx *context.Context) { ctx.Data["HasIssuesOrPullsWritePermission"] = ctx.Repo.CanWrite(models.UnitTypeIssues) + if ctx.Repo.Repository.ContractAddress == "" || ctx.User.PublicKey == ""{ + log.Error("the repo(%d) or the user(%d) has not been initialized in block_chain", ctx.Repo.Repository.ID, ctx.User.ID) + ctx.HTML(http.StatusInternalServerError, tplIssueNew) + return + } + + res, err := blockchain.GetBalance(ctx.Repo.Repository.ContractAddress, ctx.User.PublicKey) + if err != nil { + log.Error("GetBalance(%s) failed:%v", ctx.User.PublicKey, err) + ctx.HTML(http.StatusInternalServerError, tplIssueNew) + return + } + + ctx.Data["balance"] = res.Data + ctx.HTML(200, tplIssueNew) } @@ -637,6 +653,33 @@ func NewIssuePost(ctx *context.Context, form auth.CreateIssueForm) { Ref: form.Ref, } + if repo.ContractAddress == "" || ctx.User.PublicKey == ""{ + log.Error("the repo(%d) or the user(%d) has not been initialized in block_chain", issue.RepoID, ctx.User.ID) + ctx.HTML(http.StatusInternalServerError, tplIssueNew) + return + } + + res, err := blockchain.GetBalance(repo.ContractAddress, ctx.User.PublicKey) + if err != nil { + log.Error("GetBalance(%s) failed:%v", ctx.User.PublicKey, err) + ctx.HTML(http.StatusInternalServerError, tplIssueNew) + return + } + + balance, err := com.StrTo(res.Data).Int64() + if err != nil { + log.Error("balance(%s) convert failed:%v", res.Data, err) + ctx.HTML(http.StatusInternalServerError, tplIssueNew) + return + } + + if form.Rewards < 0 || form.Rewards > balance { + ctx.RenderWithErr(ctx.Tr("repo.issues.new.rewards_error"), tplIssueNew, form) + return + } + + issue.Amount = form.Rewards + if err := issue_service.NewIssue(repo, issue, labelIDs, attachments, assigneeIDs); err != nil { if models.IsErrUserDoesNotHaveAccessToRepo(err) { ctx.Error(400, "UserDoesNotHaveAccessToRepo", err.Error()) diff --git a/routers/routes/routes.go b/routers/routes/routes.go index 3d797a1e7..cfb730490 100755 --- a/routers/routes/routes.go +++ b/routers/routes/routes.go @@ -245,7 +245,7 @@ func RegisterRoutes(m *macaron.Macaron) { ignSignIn := context.Toggle(&context.ToggleOptions{SignInRequired: setting.Service.RequireSignInView}) ignSignInAndCsrf := context.Toggle(&context.ToggleOptions{DisableCSRF: true}) reqSignOut := context.Toggle(&context.ToggleOptions{SignOutRequired: true}) - reqBasicAuth := context.Toggle(&context.ToggleOptions{BasicAuthRequired:true}) + reqBasicAuth := context.Toggle(&context.ToggleOptions{BasicAuthRequired: true}) bindIgnErr := binding.BindIgnErr validation.AddBindingRules() diff --git a/templates/repo/sub_menu.tmpl b/templates/repo/sub_menu.tmpl index cd000d474..d1b73a9b0 100644 --- a/templates/repo/sub_menu.tmpl +++ b/templates/repo/sub_menu.tmpl @@ -13,6 +13,9 @@
+ {{end}}