{"text":"\/\/ Copyright 2014 The Gogs Authors. All rights reserved.\n\/\/ Use of this source code is governed by a MIT-style\n\/\/ license that can be found in the LICENSE file.\n\npackage ssh\n\nimport (\n\t\"fmt\"\n\t\"io\"\n\t\"io\/ioutil\"\n\t\"net\"\n\t\"os\"\n\t\"os\/exec\"\n\t\"path\/filepath\"\n\t\"strings\"\n\n\t\"github.com\/Unknwon\/com\"\n\t\"golang.org\/x\/crypto\/ssh\"\n\tlog \"gopkg.in\/clog.v1\"\n\n\t\"github.com\/gogits\/gogs\/models\"\n\t\"github.com\/gogits\/gogs\/pkg\/setting\"\n)\n\nfunc cleanCommand(cmd string) string {\n\ti := strings.Index(cmd, \"git\")\n\tif i == -1 {\n\t\treturn cmd\n\t}\n\treturn cmd[i:]\n}\n\nfunc handleServerConn(keyID string, chans <-chan ssh.NewChannel) {\n\tfor newChan := range chans {\n\t\tif newChan.ChannelType() != \"session\" {\n\t\t\tnewChan.Reject(ssh.UnknownChannelType, \"unknown channel type\")\n\t\t\tcontinue\n\t\t}\n\n\t\tch, reqs, err := newChan.Accept()\n\t\tif err != nil {\n\t\t\tlog.Error(3, \"Error accepting channel: %v\", err)\n\t\t\tcontinue\n\t\t}\n\n\t\tgo func(in <-chan *ssh.Request) {\n\t\t\tdefer ch.Close()\n\t\t\tfor req := range in {\n\t\t\t\tpayload := cleanCommand(string(req.Payload))\n\t\t\t\tswitch req.Type {\n\t\t\t\tcase \"env\":\n\t\t\t\t\targs := strings.Split(strings.Replace(payload, \"\\x00\", \"\", -1), \"\\v\")\n\t\t\t\t\tif len(args) != 2 {\n\t\t\t\t\t\tlog.Warn(\"SSH: Invalid env arguments: '%#v'\", args)\n\t\t\t\t\t\tcontinue\n\t\t\t\t\t}\n\t\t\t\t\targs[0] = strings.TrimLeft(args[0], \"\\x04\")\n\t\t\t\t\t_, _, err := com.ExecCmdBytes(\"env\", args[0]+\"=\"+args[1])\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\tlog.Error(3, \"env: %v\", err)\n\t\t\t\t\t\treturn\n\t\t\t\t\t}\n\t\t\t\tcase \"exec\":\n\t\t\t\t\tcmdName := strings.TrimLeft(payload, \"'()\")\n\t\t\t\t\tlog.Trace(\"SSH: Payload: %v\", cmdName)\n\n\t\t\t\t\targs := []string{\"serv\", \"key-\" + keyID, \"--config=\" + setting.CustomConf}\n\t\t\t\t\tlog.Trace(\"SSH: Arguments: %v\", args)\n\t\t\t\t\tcmd := exec.Command(setting.AppPath, args...)\n\t\t\t\t\tcmd.Env = append(os.Environ(), \"SSH_ORIGINAL_COMMAND=\"+cmdName)\n\n\t\t\t\t\tstdout, err := cmd.StdoutPipe()\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\tlog.Error(3, \"SSH: StdoutPipe: %v\", err)\n\t\t\t\t\t\treturn\n\t\t\t\t\t}\n\t\t\t\t\tstderr, err := cmd.StderrPipe()\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\tlog.Error(3, \"SSH: StderrPipe: %v\", err)\n\t\t\t\t\t\treturn\n\t\t\t\t\t}\n\t\t\t\t\tinput, err := cmd.StdinPipe()\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\tlog.Error(3, \"SSH: StdinPipe: %v\", err)\n\t\t\t\t\t\treturn\n\t\t\t\t\t}\n\n\t\t\t\t\t\/\/ FIXME: check timeout\n\t\t\t\t\tif err = cmd.Start(); err != nil {\n\t\t\t\t\t\tlog.Error(3, \"SSH: Start: %v\", err)\n\t\t\t\t\t\treturn\n\t\t\t\t\t}\n\n\t\t\t\t\treq.Reply(true, nil)\n\t\t\t\t\tgo io.Copy(input, ch)\n\t\t\t\t\tio.Copy(ch, stdout)\n\t\t\t\t\tio.Copy(ch.Stderr(), stderr)\n\n\t\t\t\t\tif err = cmd.Wait(); err != nil {\n\t\t\t\t\t\tlog.Error(3, \"SSH: Wait: %v\", err)\n\t\t\t\t\t\treturn\n\t\t\t\t\t}\n\n\t\t\t\t\tch.SendRequest(\"exit-status\", false, []byte{0, 0, 0, 0})\n\t\t\t\t\treturn\n\t\t\t\tdefault:\n\t\t\t\t}\n\t\t\t}\n\t\t}(reqs)\n\t}\n}\n\nfunc listen(config *ssh.ServerConfig, host string, port int) {\n\tlistener, err := net.Listen(\"tcp\", host+\":\"+com.ToStr(port))\n\tif err != nil {\n\t\tlog.Fatal(4, \"Fail to start SSH server: %v\", err)\n\t}\n\tfor {\n\t\t\/\/ Once a ServerConfig has been configured, connections can be accepted.\n\t\tconn, err := listener.Accept()\n\t\tif err != nil {\n\t\t\tlog.Error(3, \"SSH: Error accepting incoming connection: %v\", err)\n\t\t\tcontinue\n\t\t}\n\n\t\t\/\/ Before use, a handshake must be performed on the incoming net.Conn.\n\t\t\/\/ It must be handled in a separate goroutine,\n\t\t\/\/ otherwise one user could easily block entire loop.\n\t\t\/\/ For example, user could be asked to trust server key fingerprint and hangs.\n\t\tgo func() {\n\t\t\tlog.Trace(\"SSH: Handshaking for %s\", conn.RemoteAddr())\n\t\t\tsConn, chans, reqs, err := ssh.NewServerConn(conn, config)\n\t\t\tif err != nil {\n\t\t\t\tif err == io.EOF {\n\t\t\t\t\tlog.Warn(\"SSH: Handshaking was terminated: %v\", err)\n\t\t\t\t} else {\n\t\t\t\t\tlog.Error(3, \"SSH: Error on handshaking: %v\", err)\n\t\t\t\t}\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tlog.Trace(\"SSH: Connection from %s (%s)\", sConn.RemoteAddr(), sConn.ClientVersion())\n\t\t\t\/\/ The incoming Request channel must be serviced.\n\t\t\tgo ssh.DiscardRequests(reqs)\n\t\t\tgo handleServerConn(sConn.Permissions.Extensions[\"key-id\"], chans)\n\t\t}()\n\t}\n}\n\n\/\/ Listen starts a SSH server listens on given port.\nfunc Listen(host string, port int, ciphers []string) {\n\tconfig := &ssh.ServerConfig{\n\t\tConfig: ssh.Config{\n\t\t\tCiphers: ciphers,\n\t\t},\n\t\tPublicKeyCallback: func(conn ssh.ConnMetadata, key ssh.PublicKey) (*ssh.Permissions, error) {\n\t\t\tpkey, err := models.SearchPublicKeyByContent(strings.TrimSpace(string(ssh.MarshalAuthorizedKey(key))))\n\t\t\tif err != nil {\n\t\t\t\tlog.Error(3, \"SearchPublicKeyByContent: %v\", err)\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\treturn &ssh.Permissions{Extensions: map[string]string{\"key-id\": com.ToStr(pkey.ID)}}, nil\n\t\t},\n\t}\n\n\tkeyPath := filepath.Join(setting.AppDataPath, \"ssh\/gogs.rsa\")\n\tif !com.IsExist(keyPath) {\n\t\tos.MkdirAll(filepath.Dir(keyPath), os.ModePerm)\n\t\t_, stderr, err := com.ExecCmd(setting.SSH.KeygenPath, \"-f\", keyPath, \"-t\", \"rsa\", \"-N\", \"\")\n\t\tif err != nil {\n\t\t\tpanic(fmt.Sprintf(\"Fail to generate private key: %v - %s\", err, stderr))\n\t\t}\n\t\tlog.Trace(\"SSH: New private key is generateed: %s\", keyPath)\n\t}\n\n\tprivateBytes, err := ioutil.ReadFile(keyPath)\n\tif err != nil {\n\t\tpanic(\"SSH: Fail to load private key\")\n\t}\n\tprivate, err := ssh.ParsePrivateKey(privateBytes)\n\tif err != nil {\n\t\tpanic(\"SSH: Fail to parse private key\")\n\t}\n\tconfig.AddHostKey(private)\n\n\tgo listen(config, host, port)\n}\n[annex] return exit value with go ssh server\/\/ Copyright 2014 The Gogs Authors. All rights reserved.\n\/\/ Use of this source code is governed by a MIT-style\n\/\/ license that can be found in the LICENSE file.\n\npackage ssh\n\nimport (\n\t\"fmt\"\n\t\"io\"\n\t\"io\/ioutil\"\n\t\"net\"\n\t\"os\"\n\t\"os\/exec\"\n\t\"path\/filepath\"\n\t\"strings\"\n\n\t\"github.com\/Unknwon\/com\"\n\t\"golang.org\/x\/crypto\/ssh\"\n\tlog \"gopkg.in\/clog.v1\"\n\n\t\"github.com\/gogits\/gogs\/models\"\n\t\"github.com\/gogits\/gogs\/pkg\/setting\"\n\t\"syscall\"\n)\n\nfunc cleanCommand(cmd string) string {\n\ti := strings.Index(cmd, \"git\")\n\tif i == -1 {\n\t\treturn cmd\n\t}\n\treturn cmd[i:]\n}\n\nfunc handleServerConn(keyID string, chans <-chan ssh.NewChannel) {\n\tfor newChan := range chans {\n\t\tif newChan.ChannelType() != \"session\" {\n\t\t\tnewChan.Reject(ssh.UnknownChannelType, \"unknown channel type\")\n\t\t\tcontinue\n\t\t}\n\n\t\tch, reqs, err := newChan.Accept()\n\t\tif err != nil {\n\t\t\tlog.Error(3, \"Error accepting channel: %v\", err)\n\t\t\tcontinue\n\t\t}\n\n\t\tgo func(in <-chan *ssh.Request) {\n\t\t\tdefer ch.Close()\n\t\t\tfor req := range in {\n\t\t\t\tpayload := cleanCommand(string(req.Payload))\n\t\t\t\tswitch req.Type {\n\t\t\t\tcase \"env\":\n\t\t\t\t\targs := strings.Split(strings.Replace(payload, \"\\x00\", \"\", -1), \"\\v\")\n\t\t\t\t\tif len(args) != 2 {\n\t\t\t\t\t\tlog.Warn(\"SSH: Invalid env arguments: '%#v'\", args)\n\t\t\t\t\t\tcontinue\n\t\t\t\t\t}\n\t\t\t\t\targs[0] = strings.TrimLeft(args[0], \"\\x04\")\n\t\t\t\t\t_, _, err := com.ExecCmdBytes(\"env\", args[0]+\"=\"+args[1])\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\tlog.Error(3, \"env: %v\", err)\n\t\t\t\t\t\treturn\n\t\t\t\t\t}\n\t\t\t\tcase \"exec\":\n\t\t\t\t\tcmdName := strings.TrimLeft(payload, \"'()\")\n\t\t\t\t\tlog.Trace(\"SSH: Payload: %v\", cmdName)\n\n\t\t\t\t\targs := []string{\"serv\", \"key-\" + keyID, \"--config=\" + setting.CustomConf}\n\t\t\t\t\tlog.Trace(\"SSH: Arguments: %v\", args)\n\t\t\t\t\tcmd := exec.Command(setting.AppPath, args...)\n\t\t\t\t\tcmd.Env = append(os.Environ(), \"SSH_ORIGINAL_COMMAND=\"+cmdName)\n\n\t\t\t\t\tstdout, err := cmd.StdoutPipe()\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\tlog.Error(3, \"SSH: StdoutPipe: %v\", err)\n\t\t\t\t\t\treturn\n\t\t\t\t\t}\n\t\t\t\t\tstderr, err := cmd.StderrPipe()\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\tlog.Error(3, \"SSH: StderrPipe: %v\", err)\n\t\t\t\t\t\treturn\n\t\t\t\t\t}\n\t\t\t\t\tinput, err := cmd.StdinPipe()\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\tlog.Error(3, \"SSH: StdinPipe: %v\", err)\n\t\t\t\t\t\treturn\n\t\t\t\t\t}\n\n\t\t\t\t\t\/\/ FIXME: check timeout\n\t\t\t\t\tif err = cmd.Start(); err != nil {\n\t\t\t\t\t\tlog.Error(3, \"SSH: Start: %v\", err)\n\t\t\t\t\t\treturn\n\t\t\t\t\t}\n\n\t\t\t\t\treq.Reply(true, nil)\n\t\t\t\t\tgo io.Copy(input, ch)\n\t\t\t\t\tio.Copy(ch, stdout)\n\t\t\t\t\tio.Copy(ch.Stderr(), stderr)\n\n\t\t\t\t\tif err = cmd.Wait(); err != nil {\n\t\t\t\t\t\tlog.Error(3, \"SSH: Wait: %v\", err)\n\t\t\t\t\t\t\/\/ Fix 255 default return value error\n\t\t\t\t\t\tif t, ok := err.(*exec.ExitError); ok {\n\t\t\t\t\t\t\tlog.Info(\"t:%s\", t)\n\n\t\t\t\t\t\t\tes := t.Sys().(syscall.WaitStatus).ExitStatus()\n\t\t\t\t\t\t\tif es == 1 {\n\t\t\t\t\t\t\t\tch.SendRequest(\"exit-status\", false, []byte{0, 0, 0, 1})\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\treturn\n\t\t\t\t\t}\n\n\t\t\t\t\tch.SendRequest(\"exit-status\", false, []byte{0, 0, 0, 0})\n\t\t\t\t\treturn\n\t\t\t\tdefault:\n\t\t\t\t}\n\t\t\t}\n\t\t}(reqs)\n\t}\n}\n\nfunc listen(config *ssh.ServerConfig, host string, port int) {\n\tlistener, err := net.Listen(\"tcp\", host+\":\"+com.ToStr(port))\n\tif err != nil {\n\t\tlog.Fatal(4, \"Fail to start SSH server: %v\", err)\n\t}\n\tfor {\n\t\t\/\/ Once a ServerConfig has been configured, connections can be accepted.\n\t\tconn, err := listener.Accept()\n\t\tif err != nil {\n\t\t\tlog.Error(3, \"SSH: Error accepting incoming connection: %v\", err)\n\t\t\tcontinue\n\t\t}\n\n\t\t\/\/ Before use, a handshake must be performed on the incoming net.Conn.\n\t\t\/\/ It must be handled in a separate goroutine,\n\t\t\/\/ otherwise one user could easily block entire loop.\n\t\t\/\/ For example, user could be asked to trust server key fingerprint and hangs.\n\t\tgo func() {\n\t\t\tlog.Trace(\"SSH: Handshaking for %s\", conn.RemoteAddr())\n\t\t\tsConn, chans, reqs, err := ssh.NewServerConn(conn, config)\n\t\t\tif err != nil {\n\t\t\t\tif err == io.EOF {\n\t\t\t\t\tlog.Warn(\"SSH: Handshaking was terminated: %v\", err)\n\t\t\t\t} else {\n\t\t\t\t\tlog.Error(3, \"SSH: Error on handshaking: %v\", err)\n\t\t\t\t}\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tlog.Trace(\"SSH: Connection from %s (%s)\", sConn.RemoteAddr(), sConn.ClientVersion())\n\t\t\t\/\/ The incoming Request channel must be serviced.\n\t\t\tgo ssh.DiscardRequests(reqs)\n\t\t\tgo handleServerConn(sConn.Permissions.Extensions[\"key-id\"], chans)\n\t\t}()\n\t}\n}\n\n\/\/ Listen starts a SSH server listens on given port.\nfunc Listen(host string, port int, ciphers []string) {\n\tconfig := &ssh.ServerConfig{\n\t\tConfig: ssh.Config{\n\t\t\tCiphers: ciphers,\n\t\t},\n\t\tPublicKeyCallback: func(conn ssh.ConnMetadata, key ssh.PublicKey) (*ssh.Permissions, error) {\n\t\t\tpkey, err := models.SearchPublicKeyByContent(strings.TrimSpace(string(ssh.MarshalAuthorizedKey(key))))\n\t\t\tif err != nil {\n\t\t\t\tlog.Error(3, \"SearchPublicKeyByContent: %v\", err)\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\treturn &ssh.Permissions{Extensions: map[string]string{\"key-id\": com.ToStr(pkey.ID)}}, nil\n\t\t},\n\t}\n\n\tkeyPath := filepath.Join(setting.AppDataPath, \"ssh\/gogs.rsa\")\n\tif !com.IsExist(keyPath) {\n\t\tos.MkdirAll(filepath.Dir(keyPath), os.ModePerm)\n\t\t_, stderr, err := com.ExecCmd(setting.SSH.KeygenPath, \"-f\", keyPath, \"-t\", \"rsa\", \"-N\", \"\")\n\t\tif err != nil {\n\t\t\tpanic(fmt.Sprintf(\"Fail to generate private key: %v - %s\", err, stderr))\n\t\t}\n\t\tlog.Trace(\"SSH: New private key is generateed: %s\", keyPath)\n\t}\n\n\tprivateBytes, err := ioutil.ReadFile(keyPath)\n\tif err != nil {\n\t\tpanic(\"SSH: Fail to load private key\")\n\t}\n\tprivate, err := ssh.ParsePrivateKey(privateBytes)\n\tif err != nil {\n\t\tpanic(\"SSH: Fail to parse private key\")\n\t}\n\tconfig.AddHostKey(private)\n\n\tgo listen(config, host, port)\n}\n<|endoftext|>"} {"text":"package alertsAPI\n\n\/\/ Author: Joseph Herlant\n\/\/\n\/\/ This File contains all the struct definitions needed for the xml parser for\n\/\/ catchpoint Alert Push API according to the xsd they provide as of 2015-07-06\n\nimport (\n\t\"encoding\/xml\"\n)\n\ntype NodeThreshold struct {\n\tTypeId uint8\n\tNodeCount int64\n\tNodePct float32\n\tOrOperator string\n}\n\ntype InsightDataSource struct {\n\tid int `xml:\"id,attr\"`\n\tName string\n\tDataSourceId uint8\n}\n\ntype TriggerInsight struct {\n\tIndicator InsightDataSource\n\tTracepoint InsightDataSource\n}\n\ntype TriggerZone struct {\n\tid int `xml:\"id,attr\"`\n\tName string\n}\n\ntype Trigger struct {\n\tTypeId uint8\n\tHistoricalInterval uint16\n\tOperatorId uint8\n\tWarning float32\n\tCritical float32\n\tRegexMatch string\n\tInsight TriggerInsight\n\tZone TriggerZone\n\tCompareId uint8\n\tCompareModifier float32\n}\n\ntype Setting struct {\n\tAlertGroupId int\n\tAlertGroupItemId int\n\tAlertTypeId uint8\n\tAlertSubTypeId uint8\n\tAlertGroupItemFilterTypeId uint8\n\tAlertGroupItemFilterTypeValue string\n\tNodeThreshold NodeThreshold\n\tTimeThreshold uint16 \/\/ Unit = minutes\n\tTrigger Trigger\n}\n\ntype TimestampData struct {\n\tLocal, Utc string\n}\n\ntype AlertTimestamp struct {\n\tCreate, ReportInterval TimestampData\n\tProcessingUtc string\n}\n\ntype AlertTestDetail struct {\n\tName string\n\tMonitorTypeId uint8\n\tTypeId uint8\n\tPath string\n\tUrl string\n\tClientName string\n\tDivisionName string\n\tProductName string\n}\n\ntype AlertNodeTriggered struct {\n\tCounter, Max, Min int\n\tMean, Median, Trailing float32\n}\n\ntype AlertNodePageFailure struct {\n\tErrorCode, HttpStatusCode int\n}\n\ntype AlertNodeSuspect struct {\n\tUrl string\n\tObjectResponse, PageResponse int \/\/ Unit = milliseconds\n}\n\ntype AlertNodeHostFailure struct {\n\tHostsFailed uint32\n\tWorstHost, WorstHostDetails string\n}\n\ntype AlertNode struct {\n\tXmlName xml.Name `xml:\"Node\"`\n\tId int `xml:\"id,attr\"`\n\tName, IpAddress, RemoteIpAddress, IsCritical string\n\tTransactionStepIndex uint8\n\tProbableCauseId int8\n\tCounter int\n\tMean float32\n\tTriggered AlertNodeTriggered \/\/ Applies for 'Response', 'ByteLength' and 'Insight (Indicator)' alerts\n\tPageFailure AlertNodePageFailure \/\/ Applies only for 'PageFaliure' alert\n\tSuspect AlertNodeSuspect \/\/ Applies only for 'ResponseTimeTotalPageLoadWithSuspect alert sub-type\n\tHostFailure AlertNodeHostFailure \/\/ Applies only for 'HostFailure' alert\n}\n\ntype ConditionRuns struct {\n\tDetected, Expected int\n}\n\ntype AlertCondition struct {\n\tNodeCount int64\n\tNodePct float32\n\tAverageAcrossNodes float64\n\tAverageAcrossNodesTrailing float64\n\tTransactionStepIndex uint8\n\tRuns ConditionRuns\n\tNodes []AlertNode `xml:\"Nodes>Node\"`\n}\n\ntype PingGroupPacketSent struct {\n\tTotal, Failed int8\n\tRoundTripTimes []int `xml:\"RoundTripTimes>RoundTripTime\"` \/\/ Unit = milliseconds (version since Aug-2011)\n}\n\ntype PingGroup struct {\n\tV uint `xml:\"v,attr\"`\n\tAddress, Host, Asn string\n\tBufferSize, FailureStatus int16\n\tFromDebugPrimaryHost string\n\tDuration int \/\/ Unit = milliseconds\n\tPacketsSent PingGroupPacketSent\n}\n\ntype TraceRouteGroup struct {\n\tV uint `xml:\"v,attr\"`\n\tAddress, Host, Timestamp string\n\tErrorCode int8\n\tFromDebugPrimaryHost string\n\tDuration int \/\/ Unit = milliseconds\n\tHops []PingGroup `xml:\"Hops>Hop\"`\n}\n\ntype DnsServer struct {\n\tAddress, HostName, Name string\n\tPort uint8\n}\n\ntype DnsQuery struct {\n\tXmlName xml.Name `xml:\"Query\"`\n\tV uint `xml:\"v,attr\"`\n\tServer DnsServer\n\tReturnCode uint\n\tResponseTime int\n\tErrorMessage string\n\tPing PingGroup\n\tTraceRoute []TraceRouteGroup `xml:\"TraceRoute>TraceRouteGroup\"`\n}\n\ntype DnsResponse struct {\n\tXmlName xml.Name `xml:\"Response\"`\n\tV uint `xml:\"v,attr\"`\n\tName, Info, Address string\n\tTtl uint\n\tClass uint8\n\tType, InnerResolveTime uint16\n\tInnerResolveErrorCode int8\n}\ntype DnsGroup struct {\n\tXmlName xml.Name `xml:\"Group\"`\n\tQueries []DnsQuery `xml:\"Queries>Query\"`\n\tResponses []DnsResponse `xml:\"Responses>Response\"`\n}\n\ntype DiagnosticDnsTraversalLastLevel struct {\n\t\/\/ For 'QueryType' enumerations see: http:\/\/www.iana.org\/assignments\/dns-parameters\n\tQueryType uint16\n\tV uint `xml:\"v,attr\"`\n\tlevel int8\n\tGroups []DnsGroup `xml:\"Groups>Group\"`\n}\n\ntype AlertDiagnostic struct {\n\tPing PingGroup\n\tTraceRoute TraceRouteGroup\n\tDnsTraversalLastLevel DiagnosticDnsTraversalLastLevel\n}\n\ntype Alert struct {\n\tXmlName xml.Name `xml:\"Alert\"`\n\tVersion uint `xml:\"version,attr\"`\n\tV uint `xml:\"v,attr\"`\n\tTestId uint64 `xml:\"testId,attr\"`\n\tNotificationLevelId uint8 `xml:\"notificationLevelId,attr\"`\n\tDivisionId int `xml:\"divisionId,attr\"`\n\tProductId int `xml:\"productId,attr\"`\n\tSetting Setting\n\tTimestamp AlertTimestamp\n\tTestDetail AlertTestDetail\n\tCondition AlertCondition\n\tDiagnostic AlertDiagnostic\n}\nAdding some code documentationpackage alertsAPI\n\n\/\/ This File contains all the struct definitions needed for the xml parser for\n\/\/ catchpoint Alert Push API according to the xsd they provide as of 2015-07-06\n\nimport (\n\t\"encoding\/xml\"\n)\n\ntype NodeThreshold struct {\n\tTypeId uint8\n\tNodeCount int64\n\tNodePct float32\n\tOrOperator string\n}\n\ntype InsightDataSource struct {\n\tid int `xml:\"id,attr\"`\n\tName string\n\tDataSourceId uint8\n}\n\ntype TriggerInsight struct {\n\tIndicator InsightDataSource\n\tTracepoint InsightDataSource\n}\n\ntype TriggerZone struct {\n\tid int `xml:\"id,attr\"`\n\tName string\n}\n\ntype Trigger struct {\n\tTypeId uint8\n\tHistoricalInterval uint16\n\tOperatorId uint8\n\tWarning float32\n\tCritical float32\n\tRegexMatch string\n\tInsight TriggerInsight\n\tZone TriggerZone\n\tCompareId uint8\n\tCompareModifier float32\n}\n\ntype Setting struct {\n\tAlertGroupId int\n\tAlertGroupItemId int\n\tAlertTypeId uint8\n\tAlertSubTypeId uint8\n\tAlertGroupItemFilterTypeId uint8\n\tAlertGroupItemFilterTypeValue string\n\tNodeThreshold NodeThreshold\n\tTimeThreshold uint16 \/\/ Unit = minutes\n\tTrigger Trigger\n}\n\ntype TimestampData struct {\n\tLocal, Utc string\n}\n\ntype AlertTimestamp struct {\n\tCreate, ReportInterval TimestampData\n\tProcessingUtc string\n}\n\ntype AlertTestDetail struct {\n\tName string\n\tMonitorTypeId uint8\n\tTypeId uint8\n\tPath string\n\tUrl string\n\tClientName string\n\tDivisionName string\n\tProductName string\n}\n\ntype AlertNodeTriggered struct {\n\tCounter, Max, Min int\n\tMean, Median, Trailing float32\n}\n\ntype AlertNodePageFailure struct {\n\tErrorCode, HttpStatusCode int\n}\n\ntype AlertNodeSuspect struct {\n\tUrl string\n\tObjectResponse, PageResponse int \/\/ Unit = milliseconds\n}\n\ntype AlertNodeHostFailure struct {\n\tHostsFailed uint32\n\tWorstHost, WorstHostDetails string\n}\n\ntype AlertNode struct {\n\tXmlName xml.Name `xml:\"Node\"`\n\tId int `xml:\"id,attr\"`\n\tName, IpAddress, RemoteIpAddress, IsCritical string\n\tTransactionStepIndex uint8\n\tProbableCauseId int8\n\tCounter int\n\tMean float32\n\tTriggered AlertNodeTriggered \/\/ Applies for 'Response', 'ByteLength' and 'Insight (Indicator)' alerts\n\tPageFailure AlertNodePageFailure \/\/ Applies only for 'PageFaliure' alert\n\tSuspect AlertNodeSuspect \/\/ Applies only for 'ResponseTimeTotalPageLoadWithSuspect alert sub-type\n\tHostFailure AlertNodeHostFailure \/\/ Applies only for 'HostFailure' alert\n}\n\ntype ConditionRuns struct {\n\tDetected, Expected int\n}\n\ntype AlertCondition struct {\n\tNodeCount int64\n\tNodePct float32\n\tAverageAcrossNodes float64\n\tAverageAcrossNodesTrailing float64\n\tTransactionStepIndex uint8\n\tRuns ConditionRuns\n\tNodes []AlertNode `xml:\"Nodes>Node\"`\n}\n\ntype PingGroupPacketSent struct {\n\tTotal, Failed int8\n\tRoundTripTimes []int `xml:\"RoundTripTimes>RoundTripTime\"` \/\/ Unit = milliseconds (version since Aug-2011)\n}\n\ntype PingGroup struct {\n\tV uint `xml:\"v,attr\"`\n\tAddress, Host, Asn string\n\tBufferSize, FailureStatus int16\n\tFromDebugPrimaryHost string\n\tDuration int \/\/ Unit = milliseconds\n\tPacketsSent PingGroupPacketSent\n}\n\ntype TraceRouteGroup struct {\n\tV uint `xml:\"v,attr\"`\n\tAddress, Host, Timestamp string\n\tErrorCode int8\n\tFromDebugPrimaryHost string\n\tDuration int \/\/ Unit = milliseconds\n\tHops []PingGroup `xml:\"Hops>Hop\"`\n}\n\ntype DnsServer struct {\n\tAddress, HostName, Name string\n\tPort uint8\n}\n\ntype DnsQuery struct {\n\tXmlName xml.Name `xml:\"Query\"`\n\tV uint `xml:\"v,attr\"`\n\tServer DnsServer\n\tReturnCode uint\n\tResponseTime int\n\tErrorMessage string\n\tPing PingGroup\n\tTraceRoute []TraceRouteGroup `xml:\"TraceRoute>TraceRouteGroup\"`\n}\n\ntype DnsResponse struct {\n\tXmlName xml.Name `xml:\"Response\"`\n\tV uint `xml:\"v,attr\"`\n\tName, Info, Address string\n\tTtl uint\n\tClass uint8\n\tType, InnerResolveTime uint16\n\tInnerResolveErrorCode int8\n}\ntype DnsGroup struct {\n\tXmlName xml.Name `xml:\"Group\"`\n\tQueries []DnsQuery `xml:\"Queries>Query\"`\n\tResponses []DnsResponse `xml:\"Responses>Response\"`\n}\n\ntype DiagnosticDnsTraversalLastLevel struct {\n\t\/\/ For 'QueryType' enumerations see: http:\/\/www.iana.org\/assignments\/dns-parameters\n\tQueryType uint16\n\tV uint `xml:\"v,attr\"`\n\tlevel int8\n\tGroups []DnsGroup `xml:\"Groups>Group\"`\n}\n\ntype AlertDiagnostic struct {\n\tPing PingGroup\n\tTraceRoute TraceRouteGroup\n\tDnsTraversalLastLevel DiagnosticDnsTraversalLastLevel\n}\n\ntype Alert struct {\n\tXmlName xml.Name `xml:\"Alert\"`\n\tVersion uint `xml:\"version,attr\"`\n\tV uint `xml:\"v,attr\"`\n\tTestId uint64 `xml:\"testId,attr\"`\n\tNotificationLevelId uint8 `xml:\"notificationLevelId,attr\"`\n\tDivisionId int `xml:\"divisionId,attr\"`\n\tProductId int `xml:\"productId,attr\"`\n\tSetting Setting\n\tTimestamp AlertTimestamp\n\tTestDetail AlertTestDetail\n\tCondition AlertCondition\n\tDiagnostic AlertDiagnostic\n}\n<|endoftext|>"} {"text":"package httpmux\n\nimport (\n\t\"fmt\"\n\t\"net\/http\"\n\t\"path\"\n\t\"regexp\"\n\t\"strings\"\n\n\t\"golang.org\/x\/net\/context\"\n)\n\nvar pathParamContextKey = new(struct{})\n\ntype Mux struct {\n\thandlers []handler\n}\n\nfunc New() *Mux {\n\treturn new(Mux)\n}\n\ntype handler struct {\n\tpath *regexp.Regexp\n\tuserHandler http.Handler\n}\n\nfunc (me *Mux) ServeHTTP(w http.ResponseWriter, r *http.Request) {\n\tmatches := me.matchingHandlers(r)\n\tif len(matches) == 0 {\n\t\thttp.NotFound(w, r)\n\t\treturn\n\t}\n\tm := matches[0]\n\tr = r.WithContext(context.WithValue(r.Context(), pathParamContextKey, &PathParams{m}))\n\tm.handler.userHandler.ServeHTTP(w, r)\n}\n\ntype match struct {\n\thandler handler\n\tsubmatches []string\n}\n\nfunc (me *Mux) matchingHandlers(r *http.Request) (ret []match) {\n\tfor _, h := range me.handlers {\n\t\tsubs := h.path.FindStringSubmatch(r.URL.Path)\n\t\tif subs == nil {\n\t\t\tcontinue\n\t\t}\n\t\tret = append(ret, match{h, subs})\n\t}\n\treturn\n}\n\nfunc (me *Mux) distinctHandlerRegexp(r *regexp.Regexp) bool {\n\tfor _, h := range me.handlers {\n\t\tif h.path.String() == r.String() {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}\n\nfunc (me *Mux) Handle(path string, h http.Handler) {\n\texpr := \"^\" + path\n\tif !strings.HasSuffix(expr, \"$\") {\n\t\texpr += \"$\"\n\t}\n\tre, err := regexp.Compile(expr)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tif !me.distinctHandlerRegexp(re) {\n\t\tpanic(fmt.Sprintf(\"path %q is not distinct\", path))\n\t}\n\tme.handlers = append(me.handlers, handler{re, h})\n}\n\nfunc (me *Mux) HandleFunc(path string, hf func(http.ResponseWriter, *http.Request)) {\n\tme.Handle(path, http.HandlerFunc(hf))\n}\n\nfunc Path(parts ...string) string {\n\treturn path.Join(parts...)\n}\n\ntype PathParams struct {\n\tmatch match\n}\n\nfunc (me *PathParams) ByName(name string) string {\n\tfor i, sn := range me.match.handler.path.SubexpNames()[1:] {\n\t\tif sn == name {\n\t\t\treturn me.match.submatches[i+1]\n\t\t}\n\t}\n\treturn \"\"\n}\n\nfunc RequestPathParams(r *http.Request) *PathParams {\n\tctx := r.Context()\n\treturn ctx.Value(pathParamContextKey).(*PathParams)\n}\n\nfunc PathRegexpParam(name string, re string) string {\n\treturn fmt.Sprintf(\"(?P<%s>%s)\", name, re)\n}\n\nfunc Param(name string) string {\n\treturn fmt.Sprintf(\"(?P<%s>[^\/]+)\", name)\n}\n\nfunc RestParam(name string) string {\n\treturn fmt.Sprintf(\"(?P<%s>.*)$\", name)\n}\n\nfunc NonEmptyRestParam(name string) string {\n\treturn fmt.Sprintf(\"(?P<%s>.+)$\", name)\n}\nhttpmux: Log pattern when handler panicspackage httpmux\n\nimport (\n\t\"fmt\"\n\t\"log\"\n\t\"net\/http\"\n\t\"path\"\n\t\"regexp\"\n\t\"strings\"\n\n\t\"golang.org\/x\/net\/context\"\n)\n\nvar pathParamContextKey = new(struct{})\n\ntype Mux struct {\n\thandlers []handler\n}\n\nfunc New() *Mux {\n\treturn new(Mux)\n}\n\ntype handler struct {\n\tpath *regexp.Regexp\n\tuserHandler http.Handler\n}\n\nfunc (me *Mux) ServeHTTP(w http.ResponseWriter, r *http.Request) {\n\tmatches := me.matchingHandlers(r)\n\tif len(matches) == 0 {\n\t\thttp.NotFound(w, r)\n\t\treturn\n\t}\n\tm := matches[0]\n\tr = r.WithContext(context.WithValue(r.Context(), pathParamContextKey, &PathParams{m}))\n\tdefer func() {\n\t\tr := recover()\n\t\tif r == nil {\n\t\t\treturn\n\t\t}\n\t\tlog.Printf(\"panic while handling %v\", m)\n\t\tpanic(r)\n\t}()\n\tm.handler.userHandler.ServeHTTP(w, r)\n}\n\ntype match struct {\n\thandler handler\n\tsubmatches []string\n}\n\nfunc (me *Mux) matchingHandlers(r *http.Request) (ret []match) {\n\tfor _, h := range me.handlers {\n\t\tsubs := h.path.FindStringSubmatch(r.URL.Path)\n\t\tif subs == nil {\n\t\t\tcontinue\n\t\t}\n\t\tret = append(ret, match{h, subs})\n\t}\n\treturn\n}\n\nfunc (me *Mux) distinctHandlerRegexp(r *regexp.Regexp) bool {\n\tfor _, h := range me.handlers {\n\t\tif h.path.String() == r.String() {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}\n\nfunc (me *Mux) Handle(path string, h http.Handler) {\n\texpr := \"^\" + path\n\tif !strings.HasSuffix(expr, \"$\") {\n\t\texpr += \"$\"\n\t}\n\tre, err := regexp.Compile(expr)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tif !me.distinctHandlerRegexp(re) {\n\t\tpanic(fmt.Sprintf(\"path %q is not distinct\", path))\n\t}\n\tme.handlers = append(me.handlers, handler{re, h})\n}\n\nfunc (me *Mux) HandleFunc(path string, hf func(http.ResponseWriter, *http.Request)) {\n\tme.Handle(path, http.HandlerFunc(hf))\n}\n\nfunc Path(parts ...string) string {\n\treturn path.Join(parts...)\n}\n\ntype PathParams struct {\n\tmatch match\n}\n\nfunc (me *PathParams) ByName(name string) string {\n\tfor i, sn := range me.match.handler.path.SubexpNames()[1:] {\n\t\tif sn == name {\n\t\t\treturn me.match.submatches[i+1]\n\t\t}\n\t}\n\treturn \"\"\n}\n\nfunc RequestPathParams(r *http.Request) *PathParams {\n\tctx := r.Context()\n\treturn ctx.Value(pathParamContextKey).(*PathParams)\n}\n\nfunc PathRegexpParam(name string, re string) string {\n\treturn fmt.Sprintf(\"(?P<%s>%s)\", name, re)\n}\n\nfunc Param(name string) string {\n\treturn fmt.Sprintf(\"(?P<%s>[^\/]+)\", name)\n}\n\nfunc RestParam(name string) string {\n\treturn fmt.Sprintf(\"(?P<%s>.*)$\", name)\n}\n\nfunc NonEmptyRestParam(name string) string {\n\treturn fmt.Sprintf(\"(?P<%s>.+)$\", name)\n}\n<|endoftext|>"} {"text":"\/* Copyright (c) 2015, Daniel Martí *\/\n\/* See LICENSE for licensing information *\/\n\npackage main\n\nimport (\n\t\"archive\/zip\"\n\t\"bytes\"\n\t\"encoding\/xml\"\n\t\"errors\"\n\t\"flag\"\n\t\"fmt\"\n\t\"io\"\n\t\"io\/ioutil\"\n\t\"log\"\n\t\"net\/http\"\n\t\"os\"\n\t\"sort\"\n\t\"strings\"\n)\n\n\/\/ Repo is an F-Droid repository holding apps and apks\ntype Repo struct {\n\tApps []App `xml:\"application\"`\n}\n\ntype CommaList []string\n\nfunc (cl *CommaList) UnmarshalXML(d *xml.Decoder, start xml.StartElement) error {\n\tvar content string\n\tif err := d.DecodeElement(&content, &start); err != nil {\n\t\treturn err\n\t}\n\t*cl = strings.Split(content, \",\")\n\treturn nil\n}\n\n\/\/ App is an Android application\ntype App struct {\n\tID string `xml:\"id\"`\n\tName string `xml:\"name\"`\n\tSummary string `xml:\"summary\"`\n\tDesc string `xml:\"desc\"`\n\tLicense string `xml:\"license\"`\n\tCategs CommaList `xml:\"categories\"`\n\tWebsite string `xml:\"web\"`\n\tSource string `xml:\"source\"`\n\tTracker string `xml:\"tracker\"`\n\tDonate string `xml:\"donate\"`\n\tBitcoin string `xml:\"bitcoin\"`\n\tLitecoin string `xml:\"litecoin\"`\n\tDogecoin string `xml:\"dogecoin\"`\n\tFlattrID string `xml:\"flattr\"`\n\tApks []Apk `xml:\"package\"`\n\tCVName string `xml:\"marketversion\"`\n\tCVCode uint `xml:\"marketvercode\"`\n\tCurApk *Apk\n}\n\n\/\/ Apk is an Android package\ntype Apk struct {\n\tVName string `xml:\"version\"`\n\tVCode uint `xml:\"versioncode\"`\n\tSize int `xml:\"size\"`\n\tMinSdk int `xml:\"sdkver\"`\n\tMaxSdk int `xml:\"maxsdkver\"`\n\tABIs CommaList `xml:\"nativecode\"`\n}\n\nfunc (app *App) calcCurApk() {\n\tfor _, apk := range app.Apks {\n\t\tapp.CurApk = &apk\n\t\tif app.CVCode >= apk.VCode {\n\t\t\tbreak\n\t\t}\n\t}\n}\n\nfunc (app *App) writeTextDesc(w io.Writer) {\n\treader := strings.NewReader(app.Desc)\n\tdecoder := xml.NewDecoder(reader)\n\tfirstParagraph := true\n\tlinePrefix := \"\"\n\tcolsUsed := 0\n\tfor {\n\t\ttoken, err := decoder.Token()\n\t\tif err == io.EOF || token == nil {\n\t\t\tbreak\n\t\t}\n\t\tswitch t := token.(type) {\n\t\tcase xml.StartElement:\n\t\t\tswitch t.Name.Local {\n\t\t\tcase \"p\":\n\t\t\t\tif firstParagraph {\n\t\t\t\t\tfirstParagraph = false\n\t\t\t\t} else {\n\t\t\t\t\tfmt.Fprintln(w)\n\t\t\t\t}\n\t\t\t\tlinePrefix = \"\"\n\t\t\t\tcolsUsed = 0\n\t\t\tcase \"li\":\n\t\t\t\tfmt.Fprint(w, \"\\n *\")\n\t\t\t\tlinePrefix = \" \"\n\t\t\t\tcolsUsed = 0\n\t\t\t}\n\t\tcase xml.EndElement:\n\t\t\tswitch t.Name.Local {\n\t\t\tcase \"p\":\n\t\t\t\tfmt.Fprintln(w)\n\t\t\tcase \"ul\":\n\t\t\t\tfmt.Fprintln(w)\n\t\t\tcase \"ol\":\n\t\t\t\tfmt.Fprintln(w)\n\t\t\t}\n\t\tcase xml.CharData:\n\t\t\tleft := string(t)\n\t\t\tlimit := 80 - len(linePrefix) - colsUsed\n\t\t\tfirstLine := true\n\t\t\tfor len(left) > limit {\n\t\t\t\tlast := 0\n\t\t\t\tfor i, c := range left {\n\t\t\t\t\tif i >= limit {\n\t\t\t\t\t\tbreak\n\t\t\t\t\t}\n\t\t\t\t\tif c == ' ' {\n\t\t\t\t\t\tlast = i\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif firstLine {\n\t\t\t\t\tfirstLine = false\n\t\t\t\t\tlimit += colsUsed\n\t\t\t\t} else {\n\t\t\t\t\tfmt.Fprint(w, linePrefix)\n\t\t\t\t}\n\t\t\t\tfmt.Fprintln(w, left[:last])\n\t\t\t\tleft = left[last+1:]\n\t\t\t\tcolsUsed = 0\n\t\t\t}\n\t\t\tif firstLine {\n\t\t\t\tfirstLine = false\n\t\t\t} else {\n\t\t\t\tfmt.Fprint(w, linePrefix)\n\t\t\t}\n\t\t\tfmt.Fprint(w, left)\n\t\t\tcolsUsed += len(left)\n\t\t}\n\t}\n}\n\nfunc (app *App) prepareData() {\n\tapp.calcCurApk()\n}\n\nfunc (app *App) writeShort(w io.Writer) {\n\tfmt.Fprintf(w, \"%s | %s %s\\n\", app.ID, app.Name, app.CurApk.VName)\n\tfmt.Fprintf(w, \" %s\\n\", app.Summary)\n}\n\nfunc (app *App) writeDetailed(w io.Writer) {\n\tp := func(title string, format string, args ...interface{}) {\n\t\tif format == \"\" {\n\t\t\tfmt.Fprintln(w, title)\n\t\t} else {\n\t\t\tfmt.Fprintf(w, \"%s %s\\n\", title, fmt.Sprintf(format, args...))\n\t\t}\n\t}\n\tp(\"Name :\", \"%s\", app.Name)\n\tp(\"Summary :\", \"%s\", app.Summary)\n\tp(\"Current Version :\", \"%s (%d)\", app.CurApk.VName, app.CurApk.VCode)\n\tp(\"Upstream Version :\", \"%s (%d)\", app.CVName, app.CVCode)\n\tp(\"License :\", \"%s\", app.License)\n\tif app.Categs != nil {\n\t\tp(\"Categories :\", \"%s\", strings.Join(app.Categs, \", \"))\n\t}\n\tif app.Website != \"\" {\n\t\tp(\"Website :\", \"%s\", app.Website)\n\t}\n\tif app.Source != \"\" {\n\t\tp(\"Source :\", \"%s\", app.Source)\n\t}\n\tif app.Tracker != \"\" {\n\t\tp(\"Tracker :\", \"%s\", app.Tracker)\n\t}\n\tif app.Donate != \"\" {\n\t\tp(\"Donate :\", \"%s\", app.Donate)\n\t}\n\tif app.Bitcoin != \"\" {\n\t\tp(\"Bitcoin :\", \"bitcoin:%s\", app.Bitcoin)\n\t}\n\tif app.Litecoin != \"\" {\n\t\tp(\"Litecoin :\", \"litecoin:%s\", app.Litecoin)\n\t}\n\tif app.Dogecoin != \"\" {\n\t\tp(\"Dogecoin :\", \"dogecoin:%s\", app.Dogecoin)\n\t}\n\tif app.FlattrID != \"\" {\n\t\tp(\"Flattr :\", \"https:\/\/flattr.com\/thing\/%s\", app.FlattrID)\n\t}\n\tfmt.Println()\n\tp(\"Description :\", \"\")\n\tfmt.Println()\n\tapp.writeTextDesc(w)\n\tfmt.Println()\n\tp(\"Available Versions :\", \"\")\n\tfor _, apk := range app.Apks {\n\t\tfmt.Println()\n\t\tp(\" Name :\", \"%s (%d)\", apk.VName, apk.VCode)\n\t\tp(\" Size :\", \"%d\", apk.Size)\n\t\tp(\" MinSdk :\", \"%d\", apk.MinSdk)\n\t\tif apk.MaxSdk > 0 {\n\t\t\tp(\" MaxSdk :\", \"%d\", apk.MaxSdk)\n\t\t}\n\t\tif apk.ABIs != nil {\n\t\t\tp(\" ABIs :\", \"%s\", strings.Join(apk.ABIs, \", \"))\n\t\t}\n\t}\n}\n\nvar ErrNotModified = errors.New(\"etag matches, file was not modified\")\n\nfunc downloadEtag(url, path string) error {\n\tclient := &http.Client{}\n\treq, err := http.NewRequest(\"GET\", url, nil)\n\n\tetagPath := path + \"-etag\"\n\tif _, err := os.Stat(path); err == nil {\n\t\tetag, _ := ioutil.ReadFile(etagPath)\n\t\treq.Header.Add(\"If-None-Match\", string(etag))\n\t}\n\n\tresp, err := client.Do(req)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer resp.Body.Close()\n\tif resp.StatusCode == http.StatusNotModified {\n\t\treturn ErrNotModified\n\t}\n\tjar, err := ioutil.ReadAll(resp.Body)\n\tif err != nil {\n\t\treturn err\n\t}\n\terr = ioutil.WriteFile(path, jar, 0644)\n\terr2 := ioutil.WriteFile(etagPath, []byte(resp.Header[\"Etag\"][0]), 0644)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif err2 != nil {\n\t\treturn err2\n\t}\n\treturn nil\n}\n\nconst indexName = \"index.jar\"\n\nfunc updateIndex() {\n\turl := fmt.Sprintf(\"%s\/%s\", *repoURL, indexName)\n\tlog.Printf(\"Downloading %s\", url)\n\terr := downloadEtag(url, indexName)\n\tif err == ErrNotModified {\n\t\tlog.Printf(\"Index is already up to date\")\n\t} else if err != nil {\n\t\tlog.Fatalf(\"Could not update index: %s\", err)\n\t}\n}\n\nfunc loadApps() map[string]App {\n\tr, err := zip.OpenReader(indexName)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tdefer r.Close()\n\tbuf := new(bytes.Buffer)\n\n\tfor _, f := range r.File {\n\t\tif f.Name != \"index.xml\" {\n\t\t\tcontinue\n\t\t}\n\t\trc, err := f.Open()\n\t\tif err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\t\tif _, err = io.Copy(buf, rc); err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\t\trc.Close()\n\t\tbreak\n\t}\n\n\tvar repo Repo\n\tif err := xml.Unmarshal(buf.Bytes(), &repo); err != nil {\n\t\tlog.Fatalf(\"Could not read xml: %s\", err)\n\t}\n\tapps := make(map[string]App)\n\n\tfor i := range repo.Apps {\n\t\tapp := repo.Apps[i]\n\t\tapp.prepareData()\n\t\tapps[app.ID] = app\n\t}\n\treturn apps\n}\n\nfunc appMatches(fields []string, terms []string) bool {\n\tfor _, field := range fields {\n\t\tfor _, term := range terms {\n\t\t\tif !strings.Contains(field, term) {\n\t\t\t\tgoto next\n\t\t\t}\n\t\t}\n\t\treturn true\n\tnext:\n\t}\n\treturn false\n}\n\nfunc filterAppsSearch(apps *map[string]App, terms []string) {\n\tfor _, term := range terms {\n\t\tterm = strings.ToLower(term)\n\t}\n\tfor appID, app := range *apps {\n\t\tfields := []string{\n\t\t\tstrings.ToLower(app.ID),\n\t\t\tstrings.ToLower(app.Name),\n\t\t\tstrings.ToLower(app.Summary),\n\t\t\tstrings.ToLower(app.Desc),\n\t\t}\n\t\tif !appMatches(fields, terms) {\n\t\t\tdelete(*apps, appID)\n\t\t}\n\t}\n}\n\ntype appList []App\n\nfunc (al appList) Len() int { return len(al) }\nfunc (al appList) Swap(i, j int) { al[i], al[j] = al[j], al[i] }\nfunc (al appList) Less(i, j int) bool { return al[i].ID < al[j].ID }\n\nfunc sortedApps(apps map[string]App) []App {\n\tlist := make(appList, 0, len(apps))\n\tfor appID := range apps {\n\t\tlist = append(list, apps[appID])\n\t}\n\tsort.Sort(list)\n\treturn list\n}\n\nvar repoURL = flag.String(\"r\", \"https:\/\/f-droid.org\/repo\", \"repository address\")\n\nfunc init() {\n\tflag.Usage = func() {\n\t\tp := func(args ...interface{}) {\n\t\t\tfmt.Fprintln(os.Stderr, args...)\n\t\t}\n\t\tp(\"Usage: fdroidcl [-h] [-r ] []\")\n\t\tp()\n\t\tp(\"Available commands:\")\n\t\tp(\" update Update the index\")\n\t\tp(\" list List all available apps\")\n\t\tp(\" search Search available apps\")\n\t\tp(\" show Show detailed info of an app\")\n\t}\n}\n\nfunc main() {\n\tflag.Parse()\n\tif flag.NArg() == 0 {\n\t\tflag.Usage()\n\t\tos.Exit(2)\n\t}\n\n\tcmd := flag.Args()[0]\n\targs := flag.Args()[1:]\n\n\tswitch cmd {\n\tcase \"update\":\n\t\tupdateIndex()\n\tcase \"list\":\n\t\tapps := loadApps()\n\t\tfor _, app := range sortedApps(apps) {\n\t\t\tapp.writeShort(os.Stdout)\n\t\t}\n\tcase \"search\":\n\t\tapps := loadApps()\n\t\tfilterAppsSearch(&apps, args)\n\t\tfor _, app := range sortedApps(apps) {\n\t\t\tapp.writeShort(os.Stdout)\n\t\t}\n\tcase \"show\":\n\t\tapps := loadApps()\n\t\tfor _, appID := range args {\n\t\t\tapp, e := apps[appID]\n\t\t\tif !e {\n\t\t\t\tlog.Fatalf(\"Could not find app with ID '%s'\", appID)\n\t\t\t}\n\t\t\tapp.writeDetailed(os.Stdout)\n\t\t}\n\tdefault:\n\t\tfmt.Fprintf(os.Stderr, \"Unrecognised command '%s'\\n\\n\", cmd)\n\t\tflag.Usage()\n\t\tos.Exit(2)\n\t}\n}\nAdd link support to description\/* Copyright (c) 2015, Daniel Martí *\/\n\/* See LICENSE for licensing information *\/\n\npackage main\n\nimport (\n\t\"archive\/zip\"\n\t\"bytes\"\n\t\"encoding\/xml\"\n\t\"errors\"\n\t\"flag\"\n\t\"fmt\"\n\t\"io\"\n\t\"io\/ioutil\"\n\t\"log\"\n\t\"net\/http\"\n\t\"os\"\n\t\"sort\"\n\t\"strings\"\n)\n\n\/\/ Repo is an F-Droid repository holding apps and apks\ntype Repo struct {\n\tApps []App `xml:\"application\"`\n}\n\ntype CommaList []string\n\nfunc (cl *CommaList) UnmarshalXML(d *xml.Decoder, start xml.StartElement) error {\n\tvar content string\n\tif err := d.DecodeElement(&content, &start); err != nil {\n\t\treturn err\n\t}\n\t*cl = strings.Split(content, \",\")\n\treturn nil\n}\n\n\/\/ App is an Android application\ntype App struct {\n\tID string `xml:\"id\"`\n\tName string `xml:\"name\"`\n\tSummary string `xml:\"summary\"`\n\tDesc string `xml:\"desc\"`\n\tLicense string `xml:\"license\"`\n\tCategs CommaList `xml:\"categories\"`\n\tWebsite string `xml:\"web\"`\n\tSource string `xml:\"source\"`\n\tTracker string `xml:\"tracker\"`\n\tDonate string `xml:\"donate\"`\n\tBitcoin string `xml:\"bitcoin\"`\n\tLitecoin string `xml:\"litecoin\"`\n\tDogecoin string `xml:\"dogecoin\"`\n\tFlattrID string `xml:\"flattr\"`\n\tApks []Apk `xml:\"package\"`\n\tCVName string `xml:\"marketversion\"`\n\tCVCode uint `xml:\"marketvercode\"`\n\tCurApk *Apk\n}\n\n\/\/ Apk is an Android package\ntype Apk struct {\n\tVName string `xml:\"version\"`\n\tVCode uint `xml:\"versioncode\"`\n\tSize int `xml:\"size\"`\n\tMinSdk int `xml:\"sdkver\"`\n\tMaxSdk int `xml:\"maxsdkver\"`\n\tABIs CommaList `xml:\"nativecode\"`\n}\n\nfunc (app *App) calcCurApk() {\n\tfor _, apk := range app.Apks {\n\t\tapp.CurApk = &apk\n\t\tif app.CVCode >= apk.VCode {\n\t\t\tbreak\n\t\t}\n\t}\n}\n\nfunc (app *App) writeTextDesc(w io.Writer) {\n\treader := strings.NewReader(app.Desc)\n\tdecoder := xml.NewDecoder(reader)\n\tfirstParagraph := true\n\tlinePrefix := \"\"\n\tcolsUsed := 0\n\tvar links []string\n\tlinked := false\n\tfor {\n\t\ttoken, err := decoder.Token()\n\t\tif err == io.EOF || token == nil {\n\t\t\tbreak\n\t\t}\n\t\tswitch t := token.(type) {\n\t\tcase xml.StartElement:\n\t\t\tswitch t.Name.Local {\n\t\t\tcase \"p\":\n\t\t\t\tif firstParagraph {\n\t\t\t\t\tfirstParagraph = false\n\t\t\t\t} else {\n\t\t\t\t\tfmt.Fprintln(w)\n\t\t\t\t}\n\t\t\t\tlinePrefix = \"\"\n\t\t\t\tcolsUsed = 0\n\t\t\tcase \"li\":\n\t\t\t\tfmt.Fprint(w, \"\\n *\")\n\t\t\t\tlinePrefix = \" \"\n\t\t\t\tcolsUsed = 0\n\t\t\tcase \"a\":\n\t\t\t\tfor _, attr := range t.Attr {\n\t\t\t\t\tif attr.Name.Local == \"href\" {\n\t\t\t\t\t\tlinks = append(links, attr.Value)\n\t\t\t\t\t\tlinked = true\n\t\t\t\t\t\tbreak\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\tcase xml.EndElement:\n\t\t\tswitch t.Name.Local {\n\t\t\tcase \"p\":\n\t\t\t\tfmt.Fprintln(w)\n\t\t\tcase \"ul\":\n\t\t\t\tfmt.Fprintln(w)\n\t\t\tcase \"ol\":\n\t\t\t\tfmt.Fprintln(w)\n\t\t\t}\n\t\tcase xml.CharData:\n\t\t\tleft := string(t)\n\t\t\tif linked {\n\t\t\t\tleft += fmt.Sprintf(\"[%d]\", len(links)-1)\n\t\t\t\tlinked = false\n\t\t\t}\n\t\t\tlimit := 80 - len(linePrefix) - colsUsed\n\t\t\tfirstLine := true\n\t\t\tfor len(left) > limit {\n\t\t\t\tlast := 0\n\t\t\t\tfor i, c := range left {\n\t\t\t\t\tif i >= limit {\n\t\t\t\t\t\tbreak\n\t\t\t\t\t}\n\t\t\t\t\tif c == ' ' {\n\t\t\t\t\t\tlast = i\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif firstLine {\n\t\t\t\t\tfirstLine = false\n\t\t\t\t\tlimit += colsUsed\n\t\t\t\t} else {\n\t\t\t\t\tfmt.Fprint(w, linePrefix)\n\t\t\t\t}\n\t\t\t\tfmt.Fprintln(w, left[:last])\n\t\t\t\tleft = left[last+1:]\n\t\t\t\tcolsUsed = 0\n\t\t\t}\n\t\t\tif firstLine {\n\t\t\t\tfirstLine = false\n\t\t\t} else {\n\t\t\t\tfmt.Fprint(w, linePrefix)\n\t\t\t}\n\t\t\tfmt.Fprint(w, left)\n\t\t\tcolsUsed += len(left)\n\t\t}\n\t}\n\tif len(links) > 0 {\n\t\tfmt.Fprintln(w)\n\t\tfor i, link := range links {\n\t\t\tfmt.Fprintf(w, \"[%d] %s\\n\", i, link)\n\t\t}\n\t}\n}\n\nfunc (app *App) prepareData() {\n\tapp.calcCurApk()\n}\n\nfunc (app *App) writeShort(w io.Writer) {\n\tfmt.Fprintf(w, \"%s | %s %s\\n\", app.ID, app.Name, app.CurApk.VName)\n\tfmt.Fprintf(w, \" %s\\n\", app.Summary)\n}\n\nfunc (app *App) writeDetailed(w io.Writer) {\n\tp := func(title string, format string, args ...interface{}) {\n\t\tif format == \"\" {\n\t\t\tfmt.Fprintln(w, title)\n\t\t} else {\n\t\t\tfmt.Fprintf(w, \"%s %s\\n\", title, fmt.Sprintf(format, args...))\n\t\t}\n\t}\n\tp(\"Name :\", \"%s\", app.Name)\n\tp(\"Summary :\", \"%s\", app.Summary)\n\tp(\"Current Version :\", \"%s (%d)\", app.CurApk.VName, app.CurApk.VCode)\n\tp(\"Upstream Version :\", \"%s (%d)\", app.CVName, app.CVCode)\n\tp(\"License :\", \"%s\", app.License)\n\tif app.Categs != nil {\n\t\tp(\"Categories :\", \"%s\", strings.Join(app.Categs, \", \"))\n\t}\n\tif app.Website != \"\" {\n\t\tp(\"Website :\", \"%s\", app.Website)\n\t}\n\tif app.Source != \"\" {\n\t\tp(\"Source :\", \"%s\", app.Source)\n\t}\n\tif app.Tracker != \"\" {\n\t\tp(\"Tracker :\", \"%s\", app.Tracker)\n\t}\n\tif app.Donate != \"\" {\n\t\tp(\"Donate :\", \"%s\", app.Donate)\n\t}\n\tif app.Bitcoin != \"\" {\n\t\tp(\"Bitcoin :\", \"bitcoin:%s\", app.Bitcoin)\n\t}\n\tif app.Litecoin != \"\" {\n\t\tp(\"Litecoin :\", \"litecoin:%s\", app.Litecoin)\n\t}\n\tif app.Dogecoin != \"\" {\n\t\tp(\"Dogecoin :\", \"dogecoin:%s\", app.Dogecoin)\n\t}\n\tif app.FlattrID != \"\" {\n\t\tp(\"Flattr :\", \"https:\/\/flattr.com\/thing\/%s\", app.FlattrID)\n\t}\n\tfmt.Println()\n\tp(\"Description :\", \"\")\n\tfmt.Println()\n\tapp.writeTextDesc(w)\n\tfmt.Println()\n\tp(\"Available Versions :\", \"\")\n\tfor _, apk := range app.Apks {\n\t\tfmt.Println()\n\t\tp(\" Name :\", \"%s (%d)\", apk.VName, apk.VCode)\n\t\tp(\" Size :\", \"%d\", apk.Size)\n\t\tp(\" MinSdk :\", \"%d\", apk.MinSdk)\n\t\tif apk.MaxSdk > 0 {\n\t\t\tp(\" MaxSdk :\", \"%d\", apk.MaxSdk)\n\t\t}\n\t\tif apk.ABIs != nil {\n\t\t\tp(\" ABIs :\", \"%s\", strings.Join(apk.ABIs, \", \"))\n\t\t}\n\t}\n}\n\nvar ErrNotModified = errors.New(\"etag matches, file was not modified\")\n\nfunc downloadEtag(url, path string) error {\n\tclient := &http.Client{}\n\treq, err := http.NewRequest(\"GET\", url, nil)\n\n\tetagPath := path + \"-etag\"\n\tif _, err := os.Stat(path); err == nil {\n\t\tetag, _ := ioutil.ReadFile(etagPath)\n\t\treq.Header.Add(\"If-None-Match\", string(etag))\n\t}\n\n\tresp, err := client.Do(req)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer resp.Body.Close()\n\tif resp.StatusCode == http.StatusNotModified {\n\t\treturn ErrNotModified\n\t}\n\tjar, err := ioutil.ReadAll(resp.Body)\n\tif err != nil {\n\t\treturn err\n\t}\n\terr = ioutil.WriteFile(path, jar, 0644)\n\terr2 := ioutil.WriteFile(etagPath, []byte(resp.Header[\"Etag\"][0]), 0644)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif err2 != nil {\n\t\treturn err2\n\t}\n\treturn nil\n}\n\nconst indexName = \"index.jar\"\n\nfunc updateIndex() {\n\turl := fmt.Sprintf(\"%s\/%s\", *repoURL, indexName)\n\tlog.Printf(\"Downloading %s\", url)\n\terr := downloadEtag(url, indexName)\n\tif err == ErrNotModified {\n\t\tlog.Printf(\"Index is already up to date\")\n\t} else if err != nil {\n\t\tlog.Fatalf(\"Could not update index: %s\", err)\n\t}\n}\n\nfunc loadApps() map[string]App {\n\tr, err := zip.OpenReader(indexName)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tdefer r.Close()\n\tbuf := new(bytes.Buffer)\n\n\tfor _, f := range r.File {\n\t\tif f.Name != \"index.xml\" {\n\t\t\tcontinue\n\t\t}\n\t\trc, err := f.Open()\n\t\tif err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\t\tif _, err = io.Copy(buf, rc); err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\t\trc.Close()\n\t\tbreak\n\t}\n\n\tvar repo Repo\n\tif err := xml.Unmarshal(buf.Bytes(), &repo); err != nil {\n\t\tlog.Fatalf(\"Could not read xml: %s\", err)\n\t}\n\tapps := make(map[string]App)\n\n\tfor i := range repo.Apps {\n\t\tapp := repo.Apps[i]\n\t\tapp.prepareData()\n\t\tapps[app.ID] = app\n\t}\n\treturn apps\n}\n\nfunc appMatches(fields []string, terms []string) bool {\n\tfor _, field := range fields {\n\t\tfor _, term := range terms {\n\t\t\tif !strings.Contains(field, term) {\n\t\t\t\tgoto next\n\t\t\t}\n\t\t}\n\t\treturn true\n\tnext:\n\t}\n\treturn false\n}\n\nfunc filterAppsSearch(apps *map[string]App, terms []string) {\n\tfor _, term := range terms {\n\t\tterm = strings.ToLower(term)\n\t}\n\tfor appID, app := range *apps {\n\t\tfields := []string{\n\t\t\tstrings.ToLower(app.ID),\n\t\t\tstrings.ToLower(app.Name),\n\t\t\tstrings.ToLower(app.Summary),\n\t\t\tstrings.ToLower(app.Desc),\n\t\t}\n\t\tif !appMatches(fields, terms) {\n\t\t\tdelete(*apps, appID)\n\t\t}\n\t}\n}\n\ntype appList []App\n\nfunc (al appList) Len() int { return len(al) }\nfunc (al appList) Swap(i, j int) { al[i], al[j] = al[j], al[i] }\nfunc (al appList) Less(i, j int) bool { return al[i].ID < al[j].ID }\n\nfunc sortedApps(apps map[string]App) []App {\n\tlist := make(appList, 0, len(apps))\n\tfor appID := range apps {\n\t\tlist = append(list, apps[appID])\n\t}\n\tsort.Sort(list)\n\treturn list\n}\n\nvar repoURL = flag.String(\"r\", \"https:\/\/f-droid.org\/repo\", \"repository address\")\n\nfunc init() {\n\tflag.Usage = func() {\n\t\tp := func(args ...interface{}) {\n\t\t\tfmt.Fprintln(os.Stderr, args...)\n\t\t}\n\t\tp(\"Usage: fdroidcl [-h] [-r ] []\")\n\t\tp()\n\t\tp(\"Available commands:\")\n\t\tp(\" update Update the index\")\n\t\tp(\" list List all available apps\")\n\t\tp(\" search Search available apps\")\n\t\tp(\" show Show detailed info of an app\")\n\t}\n}\n\nfunc main() {\n\tflag.Parse()\n\tif flag.NArg() == 0 {\n\t\tflag.Usage()\n\t\tos.Exit(2)\n\t}\n\n\tcmd := flag.Args()[0]\n\targs := flag.Args()[1:]\n\n\tswitch cmd {\n\tcase \"update\":\n\t\tupdateIndex()\n\tcase \"list\":\n\t\tapps := loadApps()\n\t\tfor _, app := range sortedApps(apps) {\n\t\t\tapp.writeShort(os.Stdout)\n\t\t}\n\tcase \"search\":\n\t\tapps := loadApps()\n\t\tfilterAppsSearch(&apps, args)\n\t\tfor _, app := range sortedApps(apps) {\n\t\t\tapp.writeShort(os.Stdout)\n\t\t}\n\tcase \"show\":\n\t\tapps := loadApps()\n\t\tfor _, appID := range args {\n\t\t\tapp, e := apps[appID]\n\t\t\tif !e {\n\t\t\t\tlog.Fatalf(\"Could not find app with ID '%s'\", appID)\n\t\t\t}\n\t\t\tapp.writeDetailed(os.Stdout)\n\t\t}\n\tdefault:\n\t\tfmt.Fprintf(os.Stderr, \"Unrecognised command '%s'\\n\\n\", cmd)\n\t\tflag.Usage()\n\t\tos.Exit(2)\n\t}\n}\n<|endoftext|>"} {"text":"\/\/ Copyright 2015 The LUCI Authors. All rights reserved.\n\/\/ Use of this source code is governed under the Apache License, Version 2.0\n\/\/ that can be found in the LICENSE file.\n\npackage tumble\n\nimport (\n\t\"fmt\"\n\t\"math\"\n\t\"time\"\n\n\tds \"github.com\/luci\/gae\/service\/datastore\"\n\t\"github.com\/luci\/gae\/service\/info\"\n\ttq \"github.com\/luci\/gae\/service\/taskqueue\"\n\t\"github.com\/luci\/luci-go\/common\/clock\"\n\t\"github.com\/luci\/luci-go\/common\/errors\"\n\t\"github.com\/luci\/luci-go\/common\/logging\"\n\n\t\"golang.org\/x\/net\/context\"\n)\n\ntype timestamp int64\n\nconst minTS timestamp = math.MinInt64\n\n\/\/ TaskNamespace is the namespace used to store and dispatch Tumble task queue\n\/\/ tasks.\nconst TaskNamespace = \"__tumble\"\n\nfunc (t timestamp) Unix() time.Time {\n\treturn time.Unix((int64)(t), 0).UTC()\n}\n\nfunc mkTimestamp(cfg *Config, t time.Time) timestamp {\n\ttrf := time.Duration(cfg.TemporalRoundFactor)\n\teta := t.UTC().Add(time.Duration(cfg.TemporalMinDelay) + trf).Round(trf)\n\treturn timestamp(eta.Unix())\n}\n\ntype taskShard struct {\n\tshard uint64\n\ttime timestamp\n}\n\nfunc fireTasks(c context.Context, cfg *Config, shards map[taskShard]struct{}) bool {\n\tif len(shards) == 0 {\n\t\treturn true\n\t}\n\n\t\/\/ If namespacing is enabled, Tumble will fire tasks into the Tumble task\n\t\/\/ namespace.\n\tif cfg.Namespaced {\n\t\tc = info.MustNamespace(c, TaskNamespace)\n\t}\n\n\tnextSlot := mkTimestamp(cfg, clock.Now(c).UTC())\n\tlogging.Fields{\n\t\t\"slot\": nextSlot,\n\t}.Debugf(c, \"got next slot\")\n\n\ttasks := make([]*tq.Task, 0, len(shards))\n\n\tfor shard := range shards {\n\t\teta := nextSlot\n\t\tif cfg.DelayedMutations && shard.time > eta {\n\t\t\teta = shard.time\n\t\t}\n\t\ttsk := &tq.Task{\n\t\t\tName: fmt.Sprintf(\"%d_%d\", eta, shard.shard),\n\n\t\t\tPath: processURL(eta, shard.shard),\n\n\t\t\tETA: eta.Unix(),\n\n\t\t\t\/\/ TODO(riannucci): Tune RetryOptions?\n\t\t}\n\t\ttasks = append(tasks, tsk)\n\t\tlogging.Infof(c, \"added task %q %s %s\", tsk.Name, tsk.Path, tsk.ETA)\n\t}\n\n\tif err := errors.Filter(tq.Add(ds.WithoutTransaction(c), baseName, tasks...), tq.ErrTaskAlreadyAdded); err != nil {\n\t\tlogging.Warningf(c, \"attempted to fire tasks %v, but failed: %s\", shards, err)\n\t\treturn false\n\t}\n\treturn true\n}\nUse batch add for Tumble task queue tasks.\/\/ Copyright 2015 The LUCI Authors. All rights reserved.\n\/\/ Use of this source code is governed under the Apache License, Version 2.0\n\/\/ that can be found in the LICENSE file.\n\npackage tumble\n\nimport (\n\t\"fmt\"\n\t\"math\"\n\t\"time\"\n\n\tds \"github.com\/luci\/gae\/service\/datastore\"\n\t\"github.com\/luci\/gae\/service\/info\"\n\ttq \"github.com\/luci\/gae\/service\/taskqueue\"\n\t\"github.com\/luci\/luci-go\/common\/clock\"\n\t\"github.com\/luci\/luci-go\/common\/errors\"\n\t\"github.com\/luci\/luci-go\/common\/logging\"\n\n\t\"golang.org\/x\/net\/context\"\n)\n\ntype timestamp int64\n\nconst minTS timestamp = math.MinInt64\n\n\/\/ TaskNamespace is the namespace used to store and dispatch Tumble task queue\n\/\/ tasks.\nconst TaskNamespace = \"__tumble\"\n\nfunc (t timestamp) Unix() time.Time {\n\treturn time.Unix((int64)(t), 0).UTC()\n}\n\nfunc mkTimestamp(cfg *Config, t time.Time) timestamp {\n\ttrf := time.Duration(cfg.TemporalRoundFactor)\n\teta := t.UTC().Add(time.Duration(cfg.TemporalMinDelay) + trf).Round(trf)\n\treturn timestamp(eta.Unix())\n}\n\ntype taskShard struct {\n\tshard uint64\n\ttime timestamp\n}\n\nfunc fireTasks(c context.Context, cfg *Config, shards map[taskShard]struct{}) bool {\n\tif len(shards) == 0 {\n\t\treturn true\n\t}\n\n\t\/\/ If namespacing is enabled, Tumble will fire tasks into the Tumble task\n\t\/\/ namespace.\n\tif cfg.Namespaced {\n\t\tc = info.MustNamespace(c, TaskNamespace)\n\t}\n\n\tnextSlot := mkTimestamp(cfg, clock.Now(c).UTC())\n\tlogging.Fields{\n\t\t\"slot\": nextSlot,\n\t}.Debugf(c, \"got next slot\")\n\n\ttasks := make([]*tq.Task, 0, len(shards))\n\n\tfor shard := range shards {\n\t\teta := nextSlot\n\t\tif cfg.DelayedMutations && shard.time > eta {\n\t\t\teta = shard.time\n\t\t}\n\t\ttsk := &tq.Task{\n\t\t\tName: fmt.Sprintf(\"%d_%d\", eta, shard.shard),\n\n\t\t\tPath: processURL(eta, shard.shard),\n\n\t\t\tETA: eta.Unix(),\n\n\t\t\t\/\/ TODO(riannucci): Tune RetryOptions?\n\t\t}\n\t\ttasks = append(tasks, tsk)\n\t\tlogging.Infof(c, \"added task %q %s %s\", tsk.Name, tsk.Path, tsk.ETA)\n\t}\n\n\tb := tq.Batcher{}\n\tif err := errors.Filter(b.Add(ds.WithoutTransaction(c), baseName, tasks...), tq.ErrTaskAlreadyAdded); err != nil {\n\t\tlogging.Warningf(c, \"attempted to fire tasks %v, but failed: %s\", shards, err)\n\t\treturn false\n\t}\n\treturn true\n}\n<|endoftext|>"} {"text":"package mch\n\nimport (\n\t\"time\"\n\t\"strconv\"\n\t\"fmt\"\n)\n\ntype QueryOrderRequest struct {\n\tTransactionID string \/\/ 微信的订单号,优先使用\n\tOutTradeNo string \/\/ 商户系统内部的订单号,当没提供transaction_id时需要传这个\n}\n\ntype OrderInfo struct {\n\tDeviceInfo string \/\/ 终端设备号\n\tOpenID string \/\/ 用户在商户appid下的唯一标识\n\tIsSubscribe bool \/\/ 用户是否关注公众账号,仅在公众账号类型支付有效\n\tSubOpenID string \/\/ 用户在子商户appid下的唯一标识\n\tSubIsSubscribe bool \/\/ 用户是否关注子公众账号,仅在公众账号类型支付有效\n\n\tTradeType string\n\tBankType string \/\/ 银行类型,采用字符串类型的银行标识\n\n\tTotalFee int \/\/ 订单总金额,单位为分\n\tFeeType string \/\/ 货币类型,符合ISO 4217标准的三位字母代码,默认人民币:CNY\n\tCashFee int \/\/ 订单现金支付金额,单位为分\n\tCashFeeType string \/\/ 货币类型,符合ISO 4217标准的三位字母代码,默认人民币:CNY\n\tSettlementTotalFee int \/\/ 应结订单金额=订单金额-非充值代金券金额,应结订单金额<=订单金额\n\tCouponFee int \/\/ 代金券或立减优惠金额<=订单总金额,订单总金额-代金券或立减优惠金额=现金支付金额\n\tCouponCount int \/\/ 代金券或立减优惠使用数量\n\t\/\/ TODO: coupon list\n\n\tTransactionID string \/\/ 微信支付订单号\n\tOutTradeNo string \/\/ 商户系统内部订单号,要求32个字符内,只能是数字、大小写字母_-|*@ ,且在同一个商户号下唯一\n\tAttach string \/\/ 附加数据,在查询API和支付通知中原样返回,该字段主要用于商户携带订单的自定义数据\n\tTimeEnd time.Time \/\/ 支付完成时间,格式为yyyyMMddHHmmss,如2009年12月25日9点10分10秒表示为20091225091010\n}\n\nfunc getOrderInfo(req map[string]string) (*OrderInfo, error) {\n\ttotalFee, err := strconv.Atoi(req[\"total_fee\"])\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tcashFee, err := strconv.Atoi(req[\"cash_fee\"])\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tsettlementTotalFee, err := strconv.Atoi(req[\"settlement_total_fee\"])\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tcouponFee, err := strconv.Atoi(req[\"coupon_fee\"])\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tcouponCount, err := strconv.Atoi(req[\"coupon_count\"])\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\ttimeEnd, err := ParseTime(req[\"time_end\"])\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &OrderInfo{\n\t\tDeviceInfo: req[\"device_info\"],\n\t\tOpenID: req[\"openid\"],\n\t\tIsSubscribe: req[\"is_subscribe\"] == \"Y\",\n\t\tSubOpenID: req[\"sub_openid\"],\n\t\tSubIsSubscribe: req[\"sub_is_subscribe\"] == \"Y\",\n\t\tTradeType: req[\"trade_type\"],\n\t\tBankType: req[\"bank_type\"],\n\t\tTotalFee: totalFee,\n\t\tFeeType: req[\"fee_type\"],\n\t\tCashFee: cashFee,\n\t\tCashFeeType: req[\"cash_fee_type\"],\n\t\tSettlementTotalFee: settlementTotalFee,\n\t\tCouponFee: couponFee,\n\t\tCouponCount: couponCount,\n\t\tTransactionID: req[\"transaction_id\"],\n\t\tOutTradeNo: req[\"out_trade_no\"],\n\t\tAttach: req[\"attach\"],\n\t\tTimeEnd: timeEnd,\n\t}, nil\n}\n\ntype QueryOrderResponse struct {\n\tTradeState \/\/ 交易状态\n\tTradeStateDesc string \/\/ 对当前查询订单状态的描述和下一步操作的指引\n\n\tOrderInfo\n\n\tDetail string \/\/ TODO: 商品详细列表\n}\n\nfunc (client *Client) QueryOrder(req *QueryOrderRequest) (rep *QueryOrderResponse, err error) {\n\treqMap := make(map[string]string)\n\tif req.TransactionID != \"\" {\n\t\treqMap[\"transaction_id\"] = req.TransactionID\n\t}\n\tif req.OutTradeNo != \"\" {\n\t\treqMap[\"out_trade_no\"] = req.OutTradeNo\n\t}\n\n\trepMap, err := client.PostXML(\"\/pay\/orderquery\", reqMap)\n\n\ttradeState := TradeState(repMap[\"trade_state\"])\n\tif tradeState != TradeStateSUCCESS {\n\t\trep = &QueryOrderResponse{\n\t\t\tTradeState: tradeState,\n\t\t\tTradeStateDesc: repMap[\"trade_state_desc\"],\n\t\t\tOrderInfo: OrderInfo{\n\t\t\t\tOutTradeNo: repMap[\"out_trade_no\"],\n\t\t\t\tAttach: repMap[\"attach\"],\n\t\t\t},\n\t\t}\n\t\treturn rep, nil\n\t}\n\n\torderInfo, err := getOrderInfo(repMap)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\trep = &QueryOrderResponse{\n\t\tTradeState: tradeState,\n\t\tTradeStateDesc: repMap[\"trade_state_desc\"],\n\t\tOrderInfo: *orderInfo,\n\t\tDetail: repMap[\"detail\"],\n\t}\n\n\tif req.TransactionID != \"\" && rep.TransactionID != \"\" && req.TransactionID != rep.TransactionID {\n\t\terr = fmt.Errorf(\"transaction_id mismatch, have: %s, want: %s\", rep.TransactionID, req.TransactionID)\n\t\treturn nil, err\n\t}\n\tif req.OutTradeNo != \"\" && rep.OutTradeNo != \"\" && req.OutTradeNo != rep.OutTradeNo {\n\t\terr = fmt.Errorf(\"out_trade_no mismatch, have: %s, want: %s\", rep.OutTradeNo, req.OutTradeNo)\n\t\treturn nil, err\n\t}\n\n\treturn rep, nil\n}\nUpdate source filespackage mch\n\nimport (\n\t\"time\"\n\t\"strconv\"\n\t\"fmt\"\n)\n\ntype QueryOrderRequest struct {\n\tTransactionID string \/\/ 微信的订单号,优先使用\n\tOutTradeNo string \/\/ 商户系统内部的订单号,当没提供transaction_id时需要传这个\n}\n\ntype OrderInfo struct {\n\tDeviceInfo string \/\/ 终端设备号\n\tOpenID string \/\/ 用户在商户appid下的唯一标识\n\tIsSubscribe bool \/\/ 用户是否关注公众账号,仅在公众账号类型支付有效\n\tSubOpenID string \/\/ 用户在子商户appid下的唯一标识\n\tSubIsSubscribe bool \/\/ 用户是否关注子公众账号,仅在公众账号类型支付有效\n\n\tTradeType string\n\tBankType string \/\/ 银行类型,采用字符串类型的银行标识\n\n\tTotalFee int \/\/ 订单总金额,单位为分\n\tFeeType string \/\/ 货币类型,符合ISO 4217标准的三位字母代码,默认人民币:CNY\n\tCashFee int \/\/ 订单现金支付金额,单位为分\n\tCashFeeType string \/\/ 货币类型,符合ISO 4217标准的三位字母代码,默认人民币:CNY\n\tSettlementTotalFee int \/\/ 应结订单金额=订单金额-非充值代金券金额,应结订单金额<=订单金额\n\tCouponFee int \/\/ 代金券或立减优惠金额<=订单总金额,订单总金额-代金券或立减优惠金额=现金支付金额\n\tCouponCount int \/\/ 代金券或立减优惠使用数量\n\t\/\/ TODO: coupon list\n\n\tTransactionID string \/\/ 微信支付订单号\n\tOutTradeNo string \/\/ 商户系统内部订单号,要求32个字符内,只能是数字、大小写字母_-|*@ ,且在同一个商户号下唯一\n\tAttach string \/\/ 附加数据,在查询API和支付通知中原样返回,该字段主要用于商户携带订单的自定义数据\n\tTimeEnd time.Time \/\/ 支付完成时间,格式为yyyyMMddHHmmss,如2009年12月25日9点10分10秒表示为20091225091010\n}\n\nfunc getOrderInfo(req map[string]string) (*OrderInfo, error) {\n\ttotalFee, err := strconv.Atoi(req[\"total_fee\"])\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tcashFee, err := strconv.Atoi(req[\"cash_fee\"])\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tsettlementTotalFee, err := strconv.Atoi(req[\"settlement_total_fee\"])\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tcouponFee, err := strconv.Atoi(req[\"coupon_fee\"])\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tcouponCount, err := strconv.Atoi(req[\"coupon_count\"])\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\ttimeEnd, err := ParseTime(req[\"time_end\"])\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &OrderInfo{\n\t\tDeviceInfo: req[\"device_info\"],\n\t\tOpenID: req[\"openid\"],\n\t\tIsSubscribe: req[\"is_subscribe\"] == \"Y\",\n\t\tSubOpenID: req[\"sub_openid\"],\n\t\tSubIsSubscribe: req[\"sub_is_subscribe\"] == \"Y\",\n\t\tTradeType: req[\"trade_type\"],\n\t\tBankType: req[\"bank_type\"],\n\t\tTotalFee: totalFee,\n\t\tFeeType: req[\"fee_type\"],\n\t\tCashFee: cashFee,\n\t\tCashFeeType: req[\"cash_fee_type\"],\n\t\tSettlementTotalFee: settlementTotalFee,\n\t\tCouponFee: couponFee,\n\t\tCouponCount: couponCount,\n\t\tTransactionID: req[\"transaction_id\"],\n\t\tOutTradeNo: req[\"out_trade_no\"],\n\t\tAttach: req[\"attach\"],\n\t\tTimeEnd: timeEnd,\n\t}, nil\n}\n\ntype QueryOrderResponse struct {\n\tTradeState \/\/ 交易状态\n\tTradeStateDesc string \/\/ 对当前查询订单状态的描述和下一步操作的指引\n\n\tOrderInfo\n\n\tDetail string \/\/ TODO: 商品详细列表\n}\n\nfunc (client *Client) QueryOrder(req *QueryOrderRequest) (rep *QueryOrderResponse, err error) {\n\treqMap := make(map[string]string)\n\tif req.TransactionID != \"\" {\n\t\treqMap[\"transaction_id\"] = req.TransactionID\n\t}\n\tif req.OutTradeNo != \"\" {\n\t\treqMap[\"out_trade_no\"] = req.OutTradeNo\n\t}\n\n\trepMap, err := client.PostXML(\"\/pay\/orderquery\", reqMap)\n\tfmt.Printf(\"orderquery: %s\", repMap)\n\n\ttradeState := TradeState(repMap[\"trade_state\"])\n\tif tradeState != TradeStateSUCCESS {\n\t\trep = &QueryOrderResponse{\n\t\t\tTradeState: tradeState,\n\t\t\tTradeStateDesc: repMap[\"trade_state_desc\"],\n\t\t\tOrderInfo: OrderInfo{\n\t\t\t\tOutTradeNo: repMap[\"out_trade_no\"],\n\t\t\t\tAttach: repMap[\"attach\"],\n\t\t\t},\n\t\t}\n\t\treturn rep, nil\n\t}\n\n\torderInfo, err := getOrderInfo(repMap)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\trep = &QueryOrderResponse{\n\t\tTradeState: tradeState,\n\t\tTradeStateDesc: repMap[\"trade_state_desc\"],\n\t\tOrderInfo: *orderInfo,\n\t\tDetail: repMap[\"detail\"],\n\t}\n\n\tif req.TransactionID != \"\" && rep.TransactionID != \"\" && req.TransactionID != rep.TransactionID {\n\t\terr = fmt.Errorf(\"transaction_id mismatch, have: %s, want: %s\", rep.TransactionID, req.TransactionID)\n\t\treturn nil, err\n\t}\n\tif req.OutTradeNo != \"\" && rep.OutTradeNo != \"\" && req.OutTradeNo != rep.OutTradeNo {\n\t\terr = fmt.Errorf(\"out_trade_no mismatch, have: %s, want: %s\", rep.OutTradeNo, req.OutTradeNo)\n\t\treturn nil, err\n\t}\n\n\treturn rep, nil\n}\n<|endoftext|>"} {"text":"package crawler\n\nimport (\n\t\"bytes\"\n\t\"net\/url\"\n\t\"testing\"\n\n\t\"golang.org\/x\/net\/html\"\n\n\t. \"github.com\/smartystreets\/goconvey\/convey\"\n)\n\nfunc helperRunDataExtrator(htmlStr string) *HTMLMetadata {\n\tbaseURL, _ := url.Parse(\"http:\/\/testhost1\/test\/\")\n\tnode, err := html.Parse(bytes.NewReader([]byte(htmlStr)))\n\tSo(err, ShouldBeNil)\n\n\tmeta, err := RunDataExtrator(node, baseURL)\n\tSo(err, ShouldBeNil)\n\n\treturn meta\n}\n\nfunc TestURLs(t *testing.T) {\n\tConvey(\"TestURLs\", t, func() {\n\t\tmeta := helperRunDataExtrator(`\n\n\n\n<\/head>\ntext<\/a>\n
text<\/a><\/div>\n
text\n text<\/a>\n text<\/a>\n <\/a>\n\ntext<\/a>\n<\/noindex>\ntext<\/a>\n<\/div>\n<\/body><\/html>`)\n\n\t\texpectedURLs := make(map[string]string)\n\t\texpectedURLs[\"http:\/\/testhost1\/link1\"] = \"testhost1\"\n\t\texpectedURLs[\"http:\/\/testhost1\/test\/link2\"] = \"testhost1\"\n\t\texpectedURLs[\"http:\/\/testhost1\/test\/link3\/link3\"] = \"testhost1\"\n\t\texpectedURLs[\"http:\/\/testhost1\/link4\"] = \"testhost1\"\n\t\texpectedURLs[\"http:\/\/testhost1\/test\/link5\"] = \"testhost1\"\n\t\texpectedURLs[\"http:\/\/testhost2\/link6\"] = \"testhost2\"\n\t\texpectedURLs[\"http:\/\/testhost1\/test\/link7\"] = \"testhost1\"\n\t\tSo(meta.URLs, ShouldResemble, expectedURLs)\n\n\t\texpectedWrongURLs := make(map[string]string)\n\t\texpectedWrongURLs[\"\/wrong%9\"] = `parse \/wrong%9: invalid URL escape \"%9\"`\n\t\tSo(meta.WrongURLs, ShouldResemble, expectedWrongURLs)\n\t})\n\n\tConvey(\"TestFrameURLs\", t, func() {\n\t\tmeta := helperRunDataExtrator(`<\/head>\n \n \n \n <\/frameset>\n <\/frameset>\n<\/html>`)\n\n\t\texpectedURLs := make(map[string]string)\n\t\texpectedURLs[\"http:\/\/testhost1\/test\/link1\"] = \"testhost1\"\n\t\texpectedURLs[\"http:\/\/testhost1\/link2\"] = \"testhost1\"\n\t\tSo(meta.URLs, ShouldResemble, expectedURLs)\n\n\t\tSo(len(meta.WrongURLs), ShouldEqual, 0)\n\t})\n\n\tConvey(\"TestIFrameURLs\", t, func() {\n\t\tmeta := helperRunDataExtrator(`<\/head>\n\n