// HandleGetCharacteristics handles a get characteristic request like `/characteristics?id=1.4,1.5` func (ctr *CharacteristicController) HandleGetCharacteristics(form url.Values) (io.Reader, error) { var b bytes.Buffer var chs []data.Characteristic // id=1.4,1.5 paths := strings.Split(form.Get("id"), ",") for _, p := range paths { if ids := strings.Split(p, "."); len(ids) == 2 { aid := to.Int64(ids[0]) // accessory id iid := to.Int64(ids[1]) // instance id (= characteristic id) c := data.Characteristic{AccessoryID: aid, CharacteristicID: iid} if ch := ctr.GetCharacteristic(aid, iid); ch != nil { c.Value = ch.Value } else { c.Status = hap.StatusServiceCommunicationFailure } chs = append(chs, c) } } result, err := json.Marshal(&data.Characteristics{chs}) if err != nil { log.Info.Panic(err) } b.Write(result) return &b, err }
func (db *database) DNSWithName(name string) DNS { config, err := db.storage.Get(configurationKeyForDNSName(name)) state, err := db.storage.Get(stateKeyForDNSName(name)) if len(config) > 0 && err == nil && len(state) > 0 { return NewDNS(name, to.Int64(string(config)), to.Int64(string(state))) } return nil }
// ParseAccessoryAndCharacterID returns the accessory and characteristic id encoded in the argument string. // The string must be in format "<accessory id>.<characteristic id>" func ParseAccessoryAndCharacterID(str string) (accessoryID int64, characteristicID int64, err error) { ids := strings.Split(str, ".") if len(ids) != 2 { err = fmt.Errorf("Could not parse uid %s", str) } else { accessoryID = to.Int64(ids[0]) characteristicID = to.Int64(ids[1]) } return accessoryID, characteristicID, err }
func (s *MDNSService) txtRecords() []string { return []string{ fmt.Sprintf("pv=%s", s.protocol), fmt.Sprintf("id=%s", s.id), fmt.Sprintf("c#=%d", s.configuration), fmt.Sprintf("s#=%d", s.state), fmt.Sprintf("sf=%d", to.Int64(s.reachable)), fmt.Sprintf("ff=%d", to.Int64(s.mfiCompliant)), fmt.Sprintf("md=%s", s.name), fmt.Sprintf("ci=%d", s.categoryIdentifier), } }
// txtRecords returns the config formatted as mDNS txt records func (cfg Config) txtRecords() []string { return []string{ fmt.Sprintf("pv=%s", cfg.protocol), fmt.Sprintf("id=%s", cfg.id), fmt.Sprintf("c#=%d", cfg.version), fmt.Sprintf("s#=%d", cfg.state), fmt.Sprintf("sf=%d", to.Int64(cfg.discoverable)), fmt.Sprintf("ff=%d", to.Int64(cfg.mfiCompliant)), fmt.Sprintf("md=%s", cfg.name), fmt.Sprintf("ci=%d", cfg.categoryId), } }
func newContext(server *Server, writer http.ResponseWriter, request *http.Request) *Context { context := &Context{} switch request.Method { case "GET": context.GET = true case "POST": context.POST = true case "DELETE": context.DELETE = true case "PUT": context.PUT = true } context.cookieMap = make(map[string]*http.Cookie) context.Server = server context.Request = request context.Writer = writer maxSize := to.Int64(config.Get("server/request_max_size")) request.ParseMultipartForm(maxSize) context.Params = context.getParams() context.Cookies = context.getCookies() context.Files = context.getFiles() server.Context = context return context }
func (t *ipTransport) Start() { // Create server which handles incoming tcp connections config := http.Config{ Port: t.config.Port, Context: t.context, Database: t.database, Container: t.container, Device: t.device, Mutex: t.mutex, Emitter: t.emitter, } s := http.NewServer(config) t.server = s // Publish server port which might be different then `t.config.Port` t.config.servePort = int(to.Int64(s.Port())) mdns := NewMDNSService(t.config) t.mdns = mdns mdns.Publish() // Publish accessory ip log.Info.Println("Accessory IP is", t.config.IP) // Send keep alive notifications to all connected clients every 10 minutes t.keepAlive = hap.NewKeepAlive(10*time.Minute, t.context) go t.keepAlive.Start() // Listen until server.Stop() is called s.ListenAndServe() }
// options: // url - url to generate codes from // notmog - turn off grabbing transmogged items from armory func (g *Generator) Generate(options map[string]interface{}, w io.Writer) error { url := to.String(options["url"]) var tmorphItems TMorphItems var err error switch { case strings.Contains(url, "wowhead.com"): tmorphItems, err = wowhead(options) case strings.Contains(url, "battle.net/wow"): tmorphItems, err = wowarmory(options) case strings.Contains(url, "http"): tmorphItems, err = generic(options) default: return errors.New("Do not recognize the URL.") } if err != nil { return err } g.lastTmorphItems = tmorphItems bonus := int(to.Int64(options["bonus"])) g.Bonus(bonus) g.Output(w) return nil }
func (t *ipTransport) Start() { config := server.Config{ Port: t.config.Port, Context: t.context, Database: t.database, Container: t.container, Device: t.device, Mutex: t.mutex, Emitter: t.emitter, } s := server.NewServer(config) t.server = s port := to.Int64(s.Port()) mdns := NewMDNSService(t.name, t.device.Name(), int(port)) t.mdns = mdns // Paired accessories must not be reachable for other clients since iOS 9 if t.isPaired() { mdns.SetReachable(false) } mdns.Publish() // Listen until server.Stop() is called s.ListenAndServe() }
// Init read yaml config func (sender *Sender) Init(senderSettings map[string]string, logger *logging.Logger) error { sender.SetLogger(logger) sender.From = senderSettings["mail_from"] sender.SMTPhost = senderSettings["mail_smtp_host"] sender.SMTPport = int(to.Int64(senderSettings["mail_smtp_port"])) sender.InsecureTLS = to.Bool(senderSettings["mail_insecure_tls"]) sender.FrontURI = senderSettings["front_uri"] return nil }
func (b *Base) getUser(c *gin.Context) { if userId := to.Int64(c.Params.ByName("user_id")); userId != 0 { var user User err := b.Db.SelectOne(&user, "SELECT * FROM users WHERE id = ? LIMIT 1", userId) checkErr(err) if err == nil { c.JSON(200, user) return } } c.JSON(404, "Not found") }
func (t *ipTransport) Start() { s := server.NewServer(t.context, t.database, t.container, t.device, t.mutex) t.server = s port := to.Int64(s.Port()) mdns := NewMDNSService(t.name, t.device.Name(), int(port)) t.mdns = mdns mdns.Publish() // Listen until server.Stop() is called s.ListenAndServe() }
// loads load the id, version and config hash func (cfg *Config) load(storage util.Storage) { if b, err := storage.Get("uuid"); err == nil { cfg.id = string(b) } if b, err := storage.Get("version"); err == nil { cfg.version = to.Int64(string(b)) } if b, err := storage.Get("configHash"); err == nil { cfg.configHash = b } }
func (b *Base) deleteUser(c *gin.Context) { if userId := to.Int64(c.Params.ByName("user_id")); userId != 0 { var user User err := b.Db.SelectOne(&user, "SELECT * FROM users WHERE id = ? LIMIT 1", userId) checkErr(err) if err == nil { _, err = b.Db.Delete(&user) checkErr(err) c.Writer.WriteHeader(204) return } } c.JSON(400, "Bad request") }
func (b *Base) editUser(c *gin.Context) { var jsonForm UserJSON if err := c.BindJSON(&jsonForm); err != nil { c.JSON(400, "Bad request") return } if userId := to.Int64(c.Params.ByName("user_id")); userId != 0 { user := User{Id: userId, Name: jsonForm.Name, Email: jsonForm.Email} _, err := b.Db.Update(&user) checkErr(err) c.JSON(200, user) return } c.JSON(404, "Not found") }
func readConfig(configFileName *string) error { file, err := yaml.Open(*configFileName) if err != nil { return fmt.Errorf("Can't read config file %s: %s", *configFileName, err.Error()) } pidFileName = to.String(file.Get("cache", "pid")) logFileName = to.String(file.Get("cache", "log_file")) listen = to.String(file.Get("cache", "listen")) retentionConfigFileName = to.String(file.Get("cache", "retention-config")) redisURI = fmt.Sprintf("%s:%s", to.String(file.Get("redis", "host")), to.String(file.Get("redis", "port"))) graphiteURI = to.String(file.Get("graphite", "uri")) graphitePrefix = to.String(file.Get("graphite", "prefix")) graphiteInterval = to.Int64(file.Get("graphite", "interval")) return nil }
func (t *ipTransport) Start() { s := server.NewServer(t.context, t.database, t.container, t.device, t.mutex) t.server = s port := to.Int64(s.Port()) mdns := NewMDNSService(t.name, t.device.Name(), int(port)) t.mdns = mdns dns := t.database.DNSWithName(t.name) if dns == nil { dns = db.NewDNS(t.name, 1, 1) t.database.SaveDNS(dns) } mdns.Publish() // Listen until server.Stop() is called s.ListenAndServe() }
// InitMetrics inits graphite metrics and starts graphite flush cycle func InitMetrics() { graphiteURI := config.Get("graphite", "uri") graphitePrefix := config.Get("graphite", "prefix") graphiteInterval := to.Int64(config.Get("graphite", "interval")) if graphiteURI != "" { graphiteAddr, err := net.ResolveTCPAddr("tcp", graphiteURI) if err != nil { log.Errorf("Can not resolve graphiteURI %s: %s", graphiteURI, err) return } hostname, err := os.Hostname() if err != nil { log.Errorf("Can not get OS hostname: %s", err) return } shortname := strings.Split(hostname, ".")[0] go graphite.Graphite(metrics.DefaultRegistry, time.Duration(graphiteInterval)*time.Second, fmt.Sprintf("%s.notifier.%s", graphitePrefix, shortname), graphiteAddr) } }
func TestEventCharacteristicFromJSON(t *testing.T) { var b = []byte(`{"characteristics":[{"aid":2,"iid":13,"status":1,"ev":true}]}`) var cs Characteristics if err := json.Unmarshal(b, &cs); err != nil { t.Fatal(err) } if x := len(cs.Characteristics); x != 1 { t.Fatal(x) } c := cs.Characteristics[0] if x := c.AccessoryID; x != 2 { t.Fatal(x) } if x := c.CharacteristicID; x != 13 { t.Fatal(x) } if x, ok := c.Events.(bool); ok { if !x { t.Fatalf("want=true is=%v", x) } } else { t.Fatalf("invalid events type %v", reflect.TypeOf(x)) } if x := to.Int64(c.Status); x != 1 { t.Fatal(x) } if c.Value != nil { t.Fatalf("want=nil is=%v", c.Value) } }
func startImport(name string, dest string) { defer func() { ok <- 1 }() tags, err := getExifData(name) if err == nil { hash := checksum.File(name, crypto.SHA1) rename := "" switch tags["File Type"] { case "MP3": rename = strings.Join( []string{ dest, normalize(pick(tags["Artist"], "Unknown Artist")), normalize(pick(tags["Album"], "Unknown Album")), fmt.Sprintf("%s%s", normalize(tags["Track"], fmt.Sprintf("%s-%s", pick(tags["Title"], "Unknown Title"), hash[0:4])), pick(strings.ToLower(path.Ext(name)), ".mp3")), }, Ps, ) default: var taken string dateTimeFields := []string{ "Date and Time (Original)", "Date/Time Original", "Media Create Date", "Track Create Date", "Create Date", } for _, field := range dateTimeFields { if tags[field] != "" { taken = tags[field] break } } if taken == "" { stats.unknown++ return } all := reDateTime.FindAllStringSubmatch(taken, -1) timeTaken := time.Date( int(to.Int64(all[0][1])), time.Month(int(to.Int64(all[0][2]))), int(to.Int64(all[0][3])), int(to.Int64(all[0][4])), int(to.Int64(all[0][5])), int(to.Int64(all[0][6])), 0, time.UTC, ) rename = strings.Join( []string{ dest, to.String(timeTaken.Year()), fmt.Sprintf("%02d-%s", timeTaken.Month(), timeTaken.Month()), fmt.Sprintf("%02d-%s", timeTaken.Day(), timeTaken.Weekday()), fmt.Sprintf("%02d%02d%02d-%s%s", timeTaken.Hour(), timeTaken.Minute(), timeTaken.Second(), strings.ToUpper(hash[0:4]), strings.ToLower(path.Ext(name))), }, Ps, ) } if rename != "" { _, err := os.Stat(rename) if err != nil { if *flagDryRun == false { err = os.MkdirAll(path.Dir(rename), os.ModeDir|0750) if err != nil { panic(err) } } err = nil if *flagMove == true { log.Printf("Moving file: %s -> %s\n", name, rename) if *flagDryRun == false { err = fileMove(name, rename) stats.moved++ } } else { log.Printf("Copying file: %s -> %s\n", name, rename) if *flagDryRun == false { err = copyFile(name, rename) stats.copied++ } } if err != nil { panic(err) } } else { rehash := checksum.File(rename, crypto.SHA1) if hash == rehash { log.Printf("Destination already exists: %s, removing original: %s (same file).\n", rename, name) os.Remove(name) stats.deleted++ } else { log.Printf("Destination already exists: %s, skipping original: %s (files differ).\n", rename, name) stats.skipped++ } } } else { stats.unknown++ } } else { stats.unknown++ } }
func TestApi(t *testing.T) { var err error client := New(&oauth.Credentials{ to.String(conf.Get("twitter/app/key")), to.String(conf.Get("twitter/app/secret")), }) client.SetAuth(&oauth.Credentials{ to.String(conf.Get("twitter/user/token")), to.String(conf.Get("twitter/user/secret")), }) _, err = client.VerifyCredentials(nil) if err != nil { t.Errorf("Test failed: %s\n", err.Error()) } _, err = client.HomeTimeline(nil) if err != nil { t.Errorf("Test failed: %s\n", err.Error()) } _, err = client.MentionsTimeline(nil) if err != nil { t.Errorf("Test failed: %s\n", err.Error()) } _, err = client.UserTimeline(nil) if err != nil { t.Errorf("Test failed: %s\n", err.Error()) } _, err = client.RetweetsOfMe(nil) if err != nil { t.Errorf("Test failed: %s\n", err.Error()) } _, err = client.Retweets(int64(21947795900469248), nil) if err != nil { t.Errorf("Test failed: %s\n", err.Error()) } var status *sugar.Map status, err = client.Update(fmt.Sprintf("Test message @ %s", time.Now()), nil) if err != nil { t.Errorf("Test failed: %s\n", err.Error()) } tweetId := to.Int64(status.Get("id_str")) _, err = client.Destroy(tweetId, nil) if err != nil { t.Errorf("Test failed: %s\n", err.Error()) } tweetId = to.Int64(status.Get("id_str")) files := []string{ "_resources/test.jpg", } _, err = client.UpdateWithMedia("Hello", nil, files) if err != nil { t.Errorf("Test failed: %s\n", err.Error()) } _, err = client.Retweet(int64(21947795900469248), nil) if err != nil { t.Errorf("Test failed: %s\n", err.Error()) } }
// Get detailed codes from a character's armory page. func wowarmory(options map[string]interface{}) (TMorphItems, error) { u, err := neturl.Parse(to.String(options["url"])) if err != nil { return nil, merry.Wrap(err) } parts := strings.Split(u.Path, "/") loc := -1 for x := 0; x < len(parts); x++ { if parts[x] == "character" { loc = x + 1 break } } if loc == -1 { return nil, errors.New("Could not parse battle.net URL") } // FIXME: this isn't exactly correct, because you can be in the US and want // to get the tmorph codes of a person in EU/China. So we need to probably // have settings to where the user of TMorphGen is. hostParts := strings.Split(u.Host, ".") if hostParts[0] == "cn" { } else if len(hostParts) == 2 { u.Host = "us.api." + strings.Join(hostParts, ".") } else { u.Host = hostParts[0] + ".api." + strings.Join(hostParts[1:], ".") } u.Scheme = "https" u.Path = fmt.Sprintf("/wow/character/%s/%s", parts[loc], parts[loc+1]) u.RawQuery = "fields=items,appearance&locale=en_US" resp, err := apicall(u) if err != nil { return nil, merry.Wrap(err) } data, err := ioutil.ReadAll(resp.Body) if err != nil { return nil, merry.Wrap(err) } resp.Body.Close() var tmorphItems TMorphItems var datam map[string]interface{} err = json.Unmarshal(data, &datam) if err != nil { return nil, merry.Wrap(err) } // get all armor, weapons, and enchants items := Map(datam["items"]) for k, v := range items { if v, ok := v.(map[string]interface{}); ok { if canDisplayName(k) { id := to.Int64(v["id"]) tooltipParams := Map(v["tooltipParams"]) if !to.Bool(options["notmog"]) { transmogItem := tooltipParams["transmogItem"] if transmogItem != nil { id = to.Int64(transmogItem) } } tmorphItems = append(tmorphItems, &TMorphItem{ Type: "item", Args: []int{nameSlotMap[k], int(id)}, }) // get enchants off the weapons if k == "mainHand" || k == "offHand" { if tooltipParams["enchant"] != nil { which := 1 if k == "offHand" { which = 2 } tmorphItems = append(tmorphItems, &TMorphItem{ Type: "enchant", Args: []int{which, int(to.Int64(tooltipParams["enchant"]))}, }) } } } } } // set offhand to 0 if there is none. // TODO: maybe there should be defaults? if items["offHand"] == nil { tmorphItems = append(tmorphItems, &TMorphItem{ Type: "item", Args: []int{nameSlotMap["offHand"], 0}, }) } // appearance stuff appearance := Map(datam["appearance"]) for k, v := range appearance { if typ, ok := appearanceMap[k]; ok { tmorphItems = append(tmorphItems, &TMorphItem{ Type: typ, Args: []int{int(to.Int64(v))}, }) } } tmorphItems = append(tmorphItems, &TMorphItem{ Type: "race", Args: []int{int(to.Int64(datam["race"]))}, }, &TMorphItem{ Type: "gender", Args: []int{int(to.Int64(datam["gender"]))}, }) return tmorphItems, nil }
// Get the codes for the list of ids via the wow api. func wowapi(ids []string) (TMorphItems, error) { var tmorphItems TMorphItems idslen := len(ids) errChan := make(chan error) doneChan := make(chan bool, idslen) for _, id := range ids { go func(id string) { defer func() { doneChan <- true }() contextUrl := "" REDO: // FIXME: using US api, ignoring user's location u, err := neturl.Parse("https://us.api.battle.net/wow/item/" + id + contextUrl) if err != nil { errChan <- err return } resp, err := apicall(u) if err != nil { errChan <- err return } data, err := ioutil.ReadAll(resp.Body) if err != nil { errChan <- err return } resp.Body.Close() var datam map[string]interface{} err = json.Unmarshal(data, &datam) if err != nil { errChan <- err return } if _, ok := datam["inventoryType"]; !ok { if contexts, ok := datam["availableContexts"]; ok { ctxs := contexts.([]interface{}) contextUrl = "/" + ctxs[0].(string) goto REDO } } slot := int(to.Int64(datam["inventoryType"])) if v, ok := slotMap[slot]; ok { slot = v } if canDisplaySlot(slot) { tmorphItems = append(tmorphItems, &TMorphItem{ Type: "item", Args: []int{slot, int(to.Int64(id))}, }) } }(id) } count := 0 for count < idslen { select { case err := <-errChan: return nil, merry.Wrap(err) case <-doneChan: count++ if count >= idslen { return tmorphItems, nil } } } return nil, nil }