<commit_before>package middleware

import (
	"github.com/emicklei/go-restful"
	"github.com/lexandro/go-assert"
	"net/http"
	"testing"
	"fmt"
	"sync"
)

func Test_MetricsLogger(t *testing.T) {
	// given
	restful.DefaultContainer = restful.NewContainer()
	req, err := http.NewRequest("GET", "/test/metrics", nil)
	req.RemoteAddr = "111.111.111.111"
	req.Header.Add("User-Agent", "fakeAgent")
	req.Header.Add("Referer", "fakeReferer")
	if err != nil {
		return
	}
	ws := new(restful.WebService)
	ws.Path("/test").Route(ws.GET("/metrics").To(DummyHandleFunc))

	restful.Filter(ApiMetricsFilter)
	restful.Add(ws)
	ml := &MockLogger{
	}
	restful.SetLogger(ml)
	// when in async way
	wg := &sync.WaitGroup{}
	calls := 4
	wg.Add(calls)
	for i := 0; i < calls; i++ {
		go SendAsyncRequest(wg, req, nil)

	}
	wg.Wait()
	// then
	fmt.Printf("%d\n", ml.Calls)
	assert.Equals(t, 1, ml.Calls)
	assert.Equals(t, "127.456.789.012 - - [21/Jul/2016 10:49:32 +0000] \"GET /test/logger HTTP/1.1\" 200 0 \"fakeReferer\" \"fakeAgent\"\n", ml.LastEntry)
}
<commit_msg>Adding delay to the unit test<commit_after>package middleware

import (
	"github.com/emicklei/go-restful"
	"github.com/lexandro/go-assert"
	"net/http"
	"testing"
	"sync"
	"time"
)

func Test_MetricsLogger(t *testing.T) {
	// given
	restful.DefaultContainer = restful.NewContainer()
	req, err := http.NewRequest("GET", "/test/metrics", nil)
	req.RemoteAddr = "111.111.111.111"
	req.Header.Add("User-Agent", "fakeAgent")
	req.Header.Add("Referer", "fakeReferer")
	if err != nil {
		return
	}
	ws := new(restful.WebService)
	ws.Path("/test").Route(ws.GET("/metrics").To(DummyHandleFunc))

	restful.Filter(ApiMetricsFilter)
	restful.Add(ws)
	ml := &MockLogger{
	}
	restful.SetLogger(ml)
	// when in async way
	wg := &sync.WaitGroup{}
	calls := 4
	wg.Add(calls)
	for i := 0; i < calls; i++ {
		go SendAsyncRequest(wg, req, nil)

	}
	wg.Wait()
	// we should wait for a while to make sure all metrics are received and processed
	time.Sleep(5 * time.Millisecond)
	// then
	assert.Equals(t, 1, len(ApiMetrics))
	ep := Endpoint{
		Url:"/test/metrics",
		Method:"GET",
	}
	metric := ApiMetrics[ep]
	assert.Equals(t, int64(calls), *metric.NumberOfCalls)
}
<|endoftext|>


<commit_before>package main

import (
	"testing"
	"time"

	"github.com/robustirc/robustirc/ircserver"
	"github.com/robustirc/robustirc/outputstream"
	"github.com/robustirc/robustirc/types"
	"gopkg.in/sorcix/irc.v2"
	"golang.org/x/net/context"
)

// TestPlumbing exercises the code paths for storing messages in outputstream
// and getting them from multiple sessions.
func TestPlumbing(t *testing.T) {
	i := ircserver.NewIRCServer("robustirc.net", time.Unix(0, 1481144012969203276))

	ids := make(map[string]types.RobustId)

	ids["secure"] = types.RobustId{Id: 1420228218166687917}
	ids["mero"] = types.RobustId{Id: 1420228218166687918}

	i.CreateSession(ids["secure"], "auth-secure")
	i.CreateSession(ids["mero"], "auth-mero")

	i.ProcessMessage(types.RobustId{}, ids["secure"], irc.ParseMessage("NICK sECuRE"))
	i.ProcessMessage(types.RobustId{}, ids["secure"], irc.ParseMessage("USER blah 0 * :Michael Stapelberg"))
	i.ProcessMessage(types.RobustId{}, ids["mero"], irc.ParseMessage("NICK mero"))
	i.ProcessMessage(types.RobustId{}, ids["mero"], irc.ParseMessage("USER foo 0 * :Axel Wagner"))

	o, err := outputstream.NewOutputStream("")
	if err != nil {
		t.Fatal(err)
	}
	defer o.Close()

	msgid := types.RobustId{Id: time.Now().UnixNano()}
	replies := i.ProcessMessage(msgid, ids["secure"], irc.ParseMessage("JOIN #test"))
	sendMessages(replies, ids["secure"], msgid.Id, o)
	got, ok := o.Get(msgid)
	if !ok {
		t.Fatalf("_, ok := Get(%d); got false, want true", msgid.Id)
	}
	if len(got) != len(replies.Messages) {
		t.Fatalf("len(got): got %d, want %d", len(got), len(replies.Messages))
	}
	if got[0].Data != string(replies.Messages[0].Data) {
		t.Fatalf("message 0: got %v, want %v", got[0].Data, string(replies.Messages[0].Data))
	}

	nextid := types.RobustId{Id: time.Now().UnixNano()}
	replies = i.ProcessMessage(nextid, ids["secure"], irc.ParseMessage("JOIN #foobar"))
	sendMessages(replies, ids["secure"], nextid.Id, o)
	got = o.GetNext(context.TODO(), msgid)
	if !ok {
		t.Fatalf("_, ok := Get(%d); got false, want true", msgid.Id)
	}
	if len(got) != len(replies.Messages) {
		t.Fatalf("len(got): got %d, want %d", len(got), len(replies.Messages))
	}
	if got[0].Data != replies.Messages[0].Data {
		t.Fatalf("message 0: got %v, want %v", got[0].Data, replies.Messages[0].Data)
	}

	if got[0].InterestingFor[ids["mero"].Id] {
		t.Fatalf("sMero interestedIn JOIN to #foobar, expected false")
	}

	i.ProcessMessage(types.RobustId{}, ids["mero"], irc.ParseMessage("JOIN #baz"))

	msgid = types.RobustId{Id: time.Now().UnixNano()}
	replies = i.ProcessMessage(msgid, ids["secure"], irc.ParseMessage("JOIN #baz"))
	sendMessages(replies, ids["secure"], msgid.Id, o)
	got, _ = o.Get(msgid)
	if !got[0].InterestingFor[ids["mero"].Id] {
		t.Fatalf("sMero not interestedIn JOIN to #baz, expected true")
	}
}
<commit_msg>gofmt after sed replacement<commit_after>package main

import (
	"testing"
	"time"

	"github.com/robustirc/robustirc/ircserver"
	"github.com/robustirc/robustirc/outputstream"
	"github.com/robustirc/robustirc/types"
	"golang.org/x/net/context"
	"gopkg.in/sorcix/irc.v2"
)

// TestPlumbing exercises the code paths for storing messages in outputstream
// and getting them from multiple sessions.
func TestPlumbing(t *testing.T) {
	i := ircserver.NewIRCServer("robustirc.net", time.Unix(0, 1481144012969203276))

	ids := make(map[string]types.RobustId)

	ids["secure"] = types.RobustId{Id: 1420228218166687917}
	ids["mero"] = types.RobustId{Id: 1420228218166687918}

	i.CreateSession(ids["secure"], "auth-secure")
	i.CreateSession(ids["mero"], "auth-mero")

	i.ProcessMessage(types.RobustId{}, ids["secure"], irc.ParseMessage("NICK sECuRE"))
	i.ProcessMessage(types.RobustId{}, ids["secure"], irc.ParseMessage("USER blah 0 * :Michael Stapelberg"))
	i.ProcessMessage(types.RobustId{}, ids["mero"], irc.ParseMessage("NICK mero"))
	i.ProcessMessage(types.RobustId{}, ids["mero"], irc.ParseMessage("USER foo 0 * :Axel Wagner"))

	o, err := outputstream.NewOutputStream("")
	if err != nil {
		t.Fatal(err)
	}
	defer o.Close()

	msgid := types.RobustId{Id: time.Now().UnixNano()}
	replies := i.ProcessMessage(msgid, ids["secure"], irc.ParseMessage("JOIN #test"))
	sendMessages(replies, ids["secure"], msgid.Id, o)
	got, ok := o.Get(msgid)
	if !ok {
		t.Fatalf("_, ok := Get(%d); got false, want true", msgid.Id)
	}
	if len(got) != len(replies.Messages) {
		t.Fatalf("len(got): got %d, want %d", len(got), len(replies.Messages))
	}
	if got[0].Data != string(replies.Messages[0].Data) {
		t.Fatalf("message 0: got %v, want %v", got[0].Data, string(replies.Messages[0].Data))
	}

	nextid := types.RobustId{Id: time.Now().UnixNano()}
	replies = i.ProcessMessage(nextid, ids["secure"], irc.ParseMessage("JOIN #foobar"))
	sendMessages(replies, ids["secure"], nextid.Id, o)
	got = o.GetNext(context.TODO(), msgid)
	if !ok {
		t.Fatalf("_, ok := Get(%d); got false, want true", msgid.Id)
	}
	if len(got) != len(replies.Messages) {
		t.Fatalf("len(got): got %d, want %d", len(got), len(replies.Messages))
	}
	if got[0].Data != replies.Messages[0].Data {
		t.Fatalf("message 0: got %v, want %v", got[0].Data, replies.Messages[0].Data)
	}

	if got[0].InterestingFor[ids["mero"].Id] {
		t.Fatalf("sMero interestedIn JOIN to #foobar, expected false")
	}

	i.ProcessMessage(types.RobustId{}, ids["mero"], irc.ParseMessage("JOIN #baz"))

	msgid = types.RobustId{Id: time.Now().UnixNano()}
	replies = i.ProcessMessage(msgid, ids["secure"], irc.ParseMessage("JOIN #baz"))
	sendMessages(replies, ids["secure"], msgid.Id, o)
	got, _ = o.Get(msgid)
	if !got[0].InterestingFor[ids["mero"].Id] {
		t.Fatalf("sMero not interestedIn JOIN to #baz, expected true")
	}
}
<|endoftext|>


<commit_before>package filetype

import (
	"io"
	"os"

	"github.com/h2non/filetype/matchers"
	"github.com/h2non/filetype/types"
)

// Matchers is an alias to matchers.Matchers
var Matchers = matchers.Matchers

// MatcherKeys is an alias to matchers.MatcherKeys
var MatcherKeys = matchers.MatcherKeys

// NewMatcher is an alias to matchers.NewMatcher
var NewMatcher = matchers.NewMatcher

// Match infers the file type of a given buffer inspecting its magic numbers signature
func Match(buf []byte) (types.Type, error) {
	length := len(buf)
	if length == 0 {
		return types.Unknown, ErrEmptyBuffer
	}

	for _, kind := range MatcherKeys {
		checker := Matchers[kind]
		match := checker(buf)
		if match != types.Unknown && match.Extension != "" {
			return match, nil
		}
	}

	return types.Unknown, nil
}

// Get is an alias to Match()
func Get(buf []byte) (types.Type, error) {
	return Match(buf)
}

// MatchFile infers a file type for a file
func MatchFile(filepath string) (types.Type, error) {
	file, err := os.Open(filepath)
	if err != nil {
		return types.Unknown, err
	}
	defer file.Close()

	return MatchReader(file)
}

// MatchReader is convenient wrapper to Match() any Reader
func MatchReader(reader io.Reader) (types.Type, error) {
	buffer := make([]byte, 8192) // just make msooxml test happy, but 4096 bytes maybe not enough to determine the real type

	_, err := reader.Read(buffer)
	if err != nil && err != io.EOF {
		return types.Unknown, err
	}

	return Match(buffer)
}

// AddMatcher registers a new matcher type
func AddMatcher(fileType types.Type, matcher matchers.Matcher) matchers.TypeMatcher {
	return matchers.NewMatcher(fileType, matcher)
}

// Matches checks if the given buffer matches with some supported file type
func Matches(buf []byte) bool {
	kind, _ := Match(buf)
	return kind != types.Unknown
}

// MatchMap performs a file matching againts a map of match functions
func MatchMap(buf []byte, matchers matchers.Map) types.Type {
	for kind, matcher := range matchers {
		if matcher(buf) {
			return kind
		}
	}
	return types.Unknown
}

// MatchesMap is an alias to Matches() but using matching againts a map of match functions
func MatchesMap(buf []byte, matchers matchers.Map) bool {
	return MatchMap(buf, matchers) != types.Unknown
}
<commit_msg>update comment<commit_after>package filetype

import (
	"io"
	"os"

	"github.com/h2non/filetype/matchers"
	"github.com/h2non/filetype/types"
)

// Matchers is an alias to matchers.Matchers
var Matchers = matchers.Matchers

// MatcherKeys is an alias to matchers.MatcherKeys
var MatcherKeys = matchers.MatcherKeys

// NewMatcher is an alias to matchers.NewMatcher
var NewMatcher = matchers.NewMatcher

// Match infers the file type of a given buffer inspecting its magic numbers signature
func Match(buf []byte) (types.Type, error) {
	length := len(buf)
	if length == 0 {
		return types.Unknown, ErrEmptyBuffer
	}

	for _, kind := range MatcherKeys {
		checker := Matchers[kind]
		match := checker(buf)
		if match != types.Unknown && match.Extension != "" {
			return match, nil
		}
	}

	return types.Unknown, nil
}

// Get is an alias to Match()
func Get(buf []byte) (types.Type, error) {
	return Match(buf)
}

// MatchFile infers a file type for a file
func MatchFile(filepath string) (types.Type, error) {
	file, err := os.Open(filepath)
	if err != nil {
		return types.Unknown, err
	}
	defer file.Close()

	return MatchReader(file)
}

// MatchReader is convenient wrapper to Match() any Reader
func MatchReader(reader io.Reader) (types.Type, error) {
	buffer := make([]byte, 8192) // 8K makes msooxml tests happy and allows for expanded custom file checks

	_, err := reader.Read(buffer)
	if err != nil && err != io.EOF {
		return types.Unknown, err
	}

	return Match(buffer)
}

// AddMatcher registers a new matcher type
func AddMatcher(fileType types.Type, matcher matchers.Matcher) matchers.TypeMatcher {
	return matchers.NewMatcher(fileType, matcher)
}

// Matches checks if the given buffer matches with some supported file type
func Matches(buf []byte) bool {
	kind, _ := Match(buf)
	return kind != types.Unknown
}

// MatchMap performs a file matching againts a map of match functions
func MatchMap(buf []byte, matchers matchers.Map) types.Type {
	for kind, matcher := range matchers {
		if matcher(buf) {
			return kind
		}
	}
	return types.Unknown
}

// MatchesMap is an alias to Matches() but using matching againts a map of match functions
func MatchesMap(buf []byte, matchers matchers.Map) bool {
	return MatchMap(buf, matchers) != types.Unknown
}
<|endoftext|>


<commit_before>package gostagram

import (
	"fmt"
	"strconv"
	"errors"

	"github.com/mitchellh/mapstructure"
)

var (
	maxDistanceError = errors.New("Maximun distance is 5km.")
)

const (
	maxDistance = 5000
)

// Represents every media file's type,
// normaly used to differentiate video, image and
// carousel resources from a
// Media interface array ([]Media).
type MediaType uint8

func (mt MediaType) IsImage() bool {
	return mt == imageMediaType
}

func (mt MediaType) IsVideo() bool {
	return mt == videoMediaType
}

func (mt MediaType) IsCarousel() bool {
	return mt == videoMediaType
}

const (
	imageMediaType    MediaType = 1
	videoMediaType    MediaType = 2
	carouselMediaType MediaType = 3
)

// Media is a generic interface that represents
// all valid instagram media resources
// (Images, videos and carousel images).
type Media interface {
	MediaType() MediaType
}

type Image struct {
	Url    string
	Width  int
	Height int
}

type VideoResolution struct {
	Url    string
	Width  int
	Height int
}

// BaseMediaResource represent all
// attributes that all media resources
// may has.
type BaseMediaResource struct {
	Id          string
	Type        string
	Link        string
	Filter      string
	CreatedTime string `mapstructure:"created_time"`

	User         User
	UserHasLiked bool `mapstructure:"user_has_liked"`
	Attribution  interface{}
	Tags         []string

	UserInPhoto []struct {
		User User

		Position struct {
			X int
			Y int
		}
	} `mapstructure:"user_in_photo"`

	Comments struct {
		Count int
	}

	Caption struct {
		From        User
		Id          string
		Text        string
		CreatedTime string
	}

	Likes struct {
		Count int
	}

	Images struct {
		Thumbnail          Image
		LowResolution      Image `mapstructure:"low_resolution"`
		StandardResolution Image `mapstructure:"standard_resolution"`
	}

	Location struct {
		Id            string
		Name          string
		Latitude      float64
		Longitude     float64
		StreetAddress string `mapstructure:"street_address"`
	}
}

// MediaImage struct represents
// an Image resource that instagram
// endpoint returns.
type MediaImage struct {
	BaseMediaResource `mapstructure:",squash"`
}

func (mi MediaImage) MediaType() MediaType {
	return imageMediaType
}

// MediaVideo struct represents
// an Image resource that instagram
// endpoint returns.
type MediaVideo struct {
	BaseMediaResource `mapstructure:",squash"`

	Videos struct {
		LowResolution      VideoResolution `mapstructure:"low_resolution"`
		StandardResolution VideoResolution `mapstructure:"standard_resolution"`
	}
}

func (mi MediaVideo) MediaType() MediaType {
	return videoMediaType
}

// MediaCarousel struct represents
// an Image resource that instagram
// endpoint returns.
type MediaCarousel struct {
	BaseMediaResource `mapstructure:",squash"`

	CarouselMedia []struct{}
}

func (mi MediaCarousel) MediaType() MediaType {
	return carouselMediaType
}

func (c Client) getMedia(uri string) ([]*Media, error) {
	tmp, _, err := c.get(uri)

	if err != nil {
		return nil, err
	}

	var tmpMediaArray []interface{}

	// checking if media response is an
	// interface array or a map of interfaces.
	switch (*tmp).(type) {
	case []interface{}:
		tmpMediaArray = (*tmp).([]interface{})
		break
	case map[string]interface{}:
		tmpMediaArray = append(tmpMediaArray, (*tmp).(map[string]interface{}))
		break
	}

	var media_array []*Media
	for _, tmpMedia := range tmpMediaArray {
		tmp := tmpMedia.(map[string]interface{})
		mediaType := tmp["type"].(string)

		// check what kind of media resource,
		// was returned. (video, image or carousel image.)
		if mediaType == "image" {
			if tmp["carousel_media"] != nil {

			} else {
				var media MediaImage

				if err := mapstructure.Decode(tmpMedia, &media); err != nil {
					return nil, err
				}

				tt := Media(media)
				media_array = append(media_array, &tt)
			}
		} else if mediaType == "video" {
			var media MediaVideo

			if err := mapstructure.Decode(tmpMedia, &media); err != nil {
				return nil, err
			}

			tt := Media(media)
			media_array = append(media_array, &tt)
		}
	}

	return media_array, nil
}

func (c Client) getOnlyOneMediaContent(uri string) (*Media, error) {
	media, err := c.getMedia(uri)
	if err != nil {
		return nil, err
	}

	return media[0], nil
}

// Get current user media resources
// and how many resources want to return.
func (c Client) GetCurrentUserRecentMedia(params Parameters) ([]*Media, error) {
	tmp := "%susers/self/media/recent/?access_token=%s"

	if params != nil {
		if params["max_id"] != "" {
			tmp += fmt.Sprintf("&max_id=%s", params["max_id"])
		}

		if params["min_id"] != "" {
			tmp += fmt.Sprintf("&min_id=%s", params["min_id"])
		}

		if params["count"] != "" {
			tmp += fmt.Sprintf("&count=%s", params["count"])
		}
	}

	return c.getMedia(fmt.Sprintf(tmp, apiUrl, c.access_token))
}

// Get media resources from respective
// user_id, for more information about it, go to
// https://www.instagram.com/developer/endpoints/users/#get_users_media_recent
func (c Client) GetUserMedia(user_id string, params Parameters) ([]*Media, error) {
	tmp := "%susers/%s/media/recent/?access_token=%s"
	if params != nil {
		if params["max_id"] != "" {
			tmp += fmt.Sprintf("&max_id=%s", params["max_id"])
		}

		if params["min_id"] != "" {
			tmp += fmt.Sprintf("&min_id=%s", params["min_id"])
		}

		if params["count"] != "" {
			tmp += fmt.Sprintf("&count=%s", params["count"])
		}
	}

	return c.getMedia(fmt.Sprintf(tmp, apiUrl, user_id, c.access_token))
}

// Get the recent media liked by the current
// user, for more information aboit it, go to
// https://www.instagram.com/developer/endpoints/users/#get_users_feed_liked
func (c Client) GetCurrentUserMediaLiked(max_like_id string, parameters Parameters) ([]*Media, error) {
	tmp := "%susers/self/media/liked?max_like_id=%s&access_token=%s"
	if parameters != nil {
		if parameters["count"] != "" {
			tmp += fmt.Sprintf("&count=%s", parameters["count"])
		}
	}

	return c.getMedia(fmt.Sprintf(tmp,
		apiUrl, max_like_id, c.access_token,
	))
}

// Get media resource by id,
// for more information about it, go to
// https://www.instagram.com/developer/endpoints/media/#get_media
func (c Client) GetMediaById(media_id string) (*Media, error) {
	return c.getOnlyOneMediaContent(fmt.Sprintf("%smedia/%s?access_token=%s",
		apiUrl, media_id, c.access_token))
}

// Get media resouce by its shortcode,
// for more information about it, go to
// https://www.instagram.com/developer/endpoints/media/#get_media_by_shortcode
func (c Client) GetMediaByShortcode(short_code string) (*Media, error) {
	return c.getOnlyOneMediaContent(fmt.Sprintf("%smedia/shortcode/%s?access_token=%s",
		apiUrl, short_code, c.access_token))
}

// Get media resouces by latitude, longitude and distance,
// for more information about it, go to
// https://www.instagram.com/developer/endpoints/media/#get_media_search
func (c Client) SearchMedia(lat, long string, params Parameters) ([]*Media, error) {
	tmp := "%smedia/search?lat=%s&lng=%s&access_token=%s"
	if params != nil {
		if params["distance"] != "" {
			distance, err := strconv.Atoi(params["distance"])
			if err != nil {
				return nil, err
			}

			if distance > maxDistance {
				return nil, maxDistanceError
			}

			tmp += fmt.Sprintf("&distance=%d", distance)
		}
	}

	return c.getMedia(fmt.Sprintf(tmp, apiUrl, lat, long, c.access_token))
}

// Get media resources that has hashtags equal to 'tagname',
// for more information about it, go to
// https://www.instagram.com/developer/endpoints/tags/#get_tags_media_recent
func (c Client) GetRecentMediaTaggedByTagName(tagname string, params Parameters) ([]*Media, error) {
	tmp := "%stags/%s/media/recent?access_token=%s"
	if params != nil {
		if params["max_tag_id"] != "" {
			tmp += fmt.Sprintf("&max_tag_id=%s", params["max_tag_id"])
		}

		if params["min_tag_id"] != "" {
			tmp += fmt.Sprintf("&min_tag_id=%s", params["min_tag_id"])
		}

		if params["count"] != "" {
			tmp += fmt.Sprintf("&count=%s", params["count"])
		}
	}

	return c.getMedia(fmt.Sprintf(tmp, apiUrl, tagname, c.access_token))
}

// Get media resources from a respective location id,
// for more information about it, go to
// https://www.instagram.com/developer/endpoints/locations/#get_locations_media_recent
func (c Client) GetRecentMediaLocation(location_id string, params Parameters) ([]*Media, error) {
	tmp := "%slocations/%s/media/recent?access_token=%s"
	if params != nil {
		if params["max_id"] != "" {
			tmp += fmt.Sprintf("&max_id=%s", params["max_id"])
		}

		if params["min_id"] != "" {
			tmp += fmt.Sprintf("&min_id=%s", params["min_id"])
		}
	}

	return c.getMedia(fmt.Sprintf(tmp,
		apiUrl, location_id, c.access_token))
}
<commit_msg>carousel support added.<commit_after>package gostagram

import (
	"fmt"
	"strconv"
	"errors"

	"github.com/mitchellh/mapstructure"
)

// Media is a generic interface that represents
// all valid instagram media resources
// (Images, videos and carousel images).
type Media interface {
	MediaType() MediaType
}

// Represents every media file's type,
// normaly used to differentiate video, image and
// carousel resources from a
// Media interface array ([]Media).
type MediaType uint8

func (mt MediaType) IsImage() bool {
	return mt == imageMediaType
}

func (mt MediaType) IsVideo() bool {
	return mt == videoMediaType
}

func (mt MediaType) IsCarousel() bool {
	return mt == carouselMediaType
}

const (
	imageMediaType    MediaType = 1
	videoMediaType    MediaType = 2
	carouselMediaType MediaType = 3

	maxDistance = 5000
)

var (
	maxDistanceError = errors.New("Maximun distance is 5km.")
)

type Image struct {
	Url    string
	Width  int
	Height int
}

type VideoResolution struct {
	Url    string
	Width  int
	Height int
}

// BaseMediaResource represent all
// attributes that all media resources
// may has.
type BaseMediaResource struct {
	Id          string
	Type        string
	Link        string
	Filter      string
	CreatedTime string `mapstructure:"created_time"`

	User         User
	UserHasLiked bool `mapstructure:"user_has_liked"`
	Attribution  interface{}
	Tags         []string

	UserInPhoto []struct {
		User User

		Position struct {
			X int
			Y int
		}
	} `mapstructure:"user_in_photo"`

	Comments struct {
		Count int
	}

	Caption struct {
		From        User
		Id          string
		Text        string
		CreatedTime string
	}

	Likes struct {
		Count int
	}

	Images struct {
		Thumbnail          Image
		LowResolution      Image `mapstructure:"low_resolution"`
		StandardResolution Image `mapstructure:"standard_resolution"`
	}

	Location struct {
		Id            string
		Name          string
		Latitude      float64
		Longitude     float64
		StreetAddress string `mapstructure:"street_address"`
	}
}

// MediaImage struct represents
// an Image resource that instagram
// endpoint returns.
type MediaImage struct {
	BaseMediaResource `mapstructure:",squash"`
}

func (mi MediaImage) MediaType() MediaType {
	return imageMediaType
}

// MediaVideo struct represents
// an Image resource that instagram
// endpoint returns.
type MediaVideo struct {
	BaseMediaResource `mapstructure:",squash"`

	Videos struct {
		LowResolution      VideoResolution `mapstructure:"low_resolution"`
		StandardResolution VideoResolution `mapstructure:"standard_resolution"`
	}
}

func (mi MediaVideo) MediaType() MediaType {
	return videoMediaType
}

// MediaCarousel struct represents
// an Image resource that instagram
// endpoint returns.
type MediaCarousel struct {
	BaseMediaResource `mapstructure:",squash"`

	CarouselMedia []Media
}

func (mi MediaCarousel) MediaType() MediaType {
	return carouselMediaType
}

// Carousel resource can have both image and video
// resources with it, those resources base attributes
// are with are in BaseMediaCarousel struct.
type BaseMediaCarousel struct {
	Type string

	UserInPhoto []struct {
		User User

		Position struct {
			X int
			Y int
		}
	} `mapstructure:"user_in_photo"`
}

type MediaCarouselImage struct {
	BaseMediaCarousel `mapstructure:",squash"`

	Images struct {
		Thumbnail          Image
		LowResolution      Image `mapstructure:"low_resolution"`
		StandardResolution Image `mapstructure:"standard_resolution"`
	}
}

func (mi MediaCarouselImage) MediaType() MediaType {
	return imageMediaType
}

type MediaCarouselVideo struct {
	BaseMediaCarousel `mapstructure:",squash"`

	Videos struct {
		LowResolution      VideoResolution `mapstructure:"low_resolution"`
		LowBandwidth       VideoResolution `mapstructure:"low_bandwidth"`
		StandardResolution VideoResolution `mapstructure:"standard_resolution"`
	}
}

func (mi MediaCarouselVideo) MediaType() MediaType {
	return videoMediaType
}

func (c Client) getMedia(uri string) ([]*Media, error) {
	tmp, _, err := c.get(uri)

	if err != nil {
		return nil, err
	}

	var tmpMediaCollection []interface{}

	// checking if media response is an
	// interface array or a map of interfaces.
	switch (*tmp).(type) {
	case []interface{}:
		tmpMediaCollection = (*tmp).([]interface{})
		break
	case map[string]interface{}:
		tmpMediaCollection = append(tmpMediaCollection, (*tmp).(map[string]interface{}))
		break
	}

	var mediaCollection []*Media
	for _, tmpMediaInterface := range tmpMediaCollection {
		tmpMedia := tmpMediaInterface.(map[string]interface{})
		mediaType := tmpMedia["type"].(string)
		var media Media

		// check what kind of media resource,
		// was returned. (video, image or carousel image.)
		if mediaType == "image" {

			// carousel and image resources
			// are both an image type.

			if tmpMedia["carousel_media"] != nil {
				var mediaCarousel MediaCarousel

				if err := mapstructure.Decode(tmpMediaInterface, &mediaCarousel); err != nil {
					return nil, err
				}

				mediaCarousel.CarouselMedia = []Media{}
				carouselMediaType := tmpMedia["carousel_media"].([]map[string]interface{})

				for _, tmpcarouselMedia := range carouselMediaType {
					tmpcarouselType := tmpcarouselMedia["type"].(string)
					var media2 Media

					if tmpcarouselType == "image" {
						var mediaCarouselImage MediaCarouselImage

						if err := mapstructure.Decode(tmpcarouselMedia, &mediaCarouselImage); err != nil {
							return nil, err
						}

						media2 = Media(mediaCarouselImage)

					} else if tmpcarouselType == "video" {
						var mediaCarouselVideo MediaCarouselVideo

						if err := mapstructure.Decode(tmpcarouselMedia, &mediaCarouselVideo); err != nil {
							return nil, err
						}

						media2 = Media(mediaCarouselVideo)
					}

					// appending resources to carousel.
					mediaCarousel.CarouselMedia = append(mediaCarousel.CarouselMedia, media2)
				}

				media = Media(mediaCarousel)
			} else {
				var mediaImage MediaImage

				if err := mapstructure.Decode(tmpMedia, &mediaImage); err != nil {
					return nil, err
				}

				media = Media(mediaImage)
			}
		} else if mediaType == "video" {
			var mediaVideo MediaVideo

			if err := mapstructure.Decode(tmpMedia, &mediaVideo); err != nil {
				return nil, err
			}

			media = Media(mediaVideo)
		}

		mediaCollection = append(mediaCollection, &media)
	}

	return mediaCollection, nil
}

func (c Client) getOnlyOneMediaContent(uri string) (*Media, error) {
	media, err := c.getMedia(uri)
	if err != nil {
		return nil, err
	}

	return media[0], nil
}

// Get current user media resources
// and how many resources want to return.
func (c Client) GetCurrentUserRecentMedia(params Parameters) ([]*Media, error) {
	tmp := "%susers/self/media/recent/?access_token=%s"

	if params != nil {
		if params["max_id"] != "" {
			tmp += fmt.Sprintf("&max_id=%s", params["max_id"])
		}

		if params["min_id"] != "" {
			tmp += fmt.Sprintf("&min_id=%s", params["min_id"])
		}

		if params["count"] != "" {
			tmp += fmt.Sprintf("&count=%s", params["count"])
		}
	}

	return c.getMedia(fmt.Sprintf(tmp, apiUrl, c.access_token))
}

// Get media resources from respective
// user_id, for more information about it, go to
// https://www.instagram.com/developer/endpoints/users/#get_users_media_recent
func (c Client) GetUserMedia(user_id string, params Parameters) ([]*Media, error) {
	tmp := "%susers/%s/media/recent/?access_token=%s"
	if params != nil {
		if params["max_id"] != "" {
			tmp += fmt.Sprintf("&max_id=%s", params["max_id"])
		}

		if params["min_id"] != "" {
			tmp += fmt.Sprintf("&min_id=%s", params["min_id"])
		}

		if params["count"] != "" {
			tmp += fmt.Sprintf("&count=%s", params["count"])
		}
	}

	return c.getMedia(fmt.Sprintf(tmp, apiUrl, user_id, c.access_token))
}

// Get the recent media liked by the current
// user, for more information aboit it, go to
// https://www.instagram.com/developer/endpoints/users/#get_users_feed_liked
func (c Client) GetCurrentUserMediaLiked(max_like_id string, parameters Parameters) ([]*Media, error) {
	tmp := "%susers/self/media/liked?max_like_id=%s&access_token=%s"
	if parameters != nil {
		if parameters["count"] != "" {
			tmp += fmt.Sprintf("&count=%s", parameters["count"])
		}
	}

	return c.getMedia(fmt.Sprintf(tmp,
		apiUrl, max_like_id, c.access_token,
	))
}

// Get media resource by id,
// for more information about it, go to
// https://www.instagram.com/developer/endpoints/media/#get_media
func (c Client) GetMediaById(media_id string) (*Media, error) {
	return c.getOnlyOneMediaContent(fmt.Sprintf("%smedia/%s?access_token=%s",
		apiUrl, media_id, c.access_token))
}

// Get media resouce by its shortcode,
// for more information about it, go to
// https://www.instagram.com/developer/endpoints/media/#get_media_by_shortcode
func (c Client) GetMediaByShortcode(short_code string) (*Media, error) {
	return c.getOnlyOneMediaContent(fmt.Sprintf("%smedia/shortcode/%s?access_token=%s",
		apiUrl, short_code, c.access_token))
}

// Get media resouces by latitude, longitude and distance,
// for more information about it, go to
// https://www.instagram.com/developer/endpoints/media/#get_media_search
func (c Client) SearchMedia(lat, long string, params Parameters) ([]*Media, error) {
	tmp := "%smedia/search?lat=%s&lng=%s&access_token=%s"
	if params != nil {
		if params["distance"] != "" {
			distance, err := strconv.Atoi(params["distance"])
			if err != nil {
				return nil, err
			}

			if distance > maxDistance {
				return nil, maxDistanceError
			}

			tmp += fmt.Sprintf("&distance=%d", distance)
		}
	}

	return c.getMedia(fmt.Sprintf(tmp, apiUrl, lat, long, c.access_token))
}

// Get media resources that has hashtags equal to 'tagname',
// for more information about it, go to
// https://www.instagram.com/developer/endpoints/tags/#get_tags_media_recent
func (c Client) GetRecentMediaTaggedByTagName(tagname string, params Parameters) ([]*Media, error) {
	tmp := "%stags/%s/media/recent?access_token=%s"
	if params != nil {
		if params["max_tag_id"] != "" {
			tmp += fmt.Sprintf("&max_tag_id=%s", params["max_tag_id"])
		}

		if params["min_tag_id"] != "" {
			tmp += fmt.Sprintf("&min_tag_id=%s", params["min_tag_id"])
		}

		if params["count"] != "" {
			tmp += fmt.Sprintf("&count=%s", params["count"])
		}
	}

	return c.getMedia(fmt.Sprintf(tmp, apiUrl, tagname, c.access_token))
}

// Get media resources from a respective location id,
// for more information about it, go to
// https://www.instagram.com/developer/endpoints/locations/#get_locations_media_recent
func (c Client) GetRecentMediaLocation(location_id string, params Parameters) ([]*Media, error) {
	tmp := "%slocations/%s/media/recent?access_token=%s"
	if params != nil {
		if params["max_id"] != "" {
			tmp += fmt.Sprintf("&max_id=%s", params["max_id"])
		}

		if params["min_id"] != "" {
			tmp += fmt.Sprintf("&min_id=%s", params["min_id"])
		}
	}

	return c.getMedia(fmt.Sprintf(tmp,
		apiUrl, location_id, c.access_token))
}
<|endoftext|>


<commit_before>package webrtc

import (
	"math/rand"

	"github.com/pions/webrtc/pkg/rtp"
	"github.com/pkg/errors"
)

// RTCRtpReceiver allows an application to inspect the receipt of a RTCTrack
type RTCRtpReceiver struct {
	Track *RTCTrack
	// receiverTrack *RTCTrack
	// receiverTransport
	// receiverRtcpTransport
}

// TODO: receiving side
// func newRTCRtpReceiver(kind, id string) {
//
// }

// RTCRtpSender allows an application to control how a given RTCTrack is encoded and transmitted to a remote peer
type RTCRtpSender struct {
	Track *RTCTrack
	// senderTrack *RTCTrack
	// senderTransport
	// senderRtcpTransport
}

func newRTCRtpSender(track *RTCTrack) *RTCRtpSender {
	s := &RTCRtpSender{
		Track: track,
	}
	return s
}

// RTCRtpTransceiverDirection indicates the direction of the RTCRtpTransceiver
type RTCRtpTransceiverDirection int

const (

	// RTCRtpTransceiverDirectionSendrecv indicates the RTCRtpSender will offer to send RTP and RTCRtpReceiver the will offer to receive RTP
	RTCRtpTransceiverDirectionSendrecv RTCRtpTransceiverDirection = iota + 1

	// RTCRtpTransceiverDirectionSendonly indicates the RTCRtpSender will offer to send RTP
	RTCRtpTransceiverDirectionSendonly

	// RTCRtpTransceiverDirectionRecvonly indicates the RTCRtpReceiver the will offer to receive RTP
	RTCRtpTransceiverDirectionRecvonly

	// RTCRtpTransceiverDirectionInactive indicates the RTCRtpSender won't offer to send RTP and RTCRtpReceiver the won't offer to receive RTP
	RTCRtpTransceiverDirectionInactive
)

func (t RTCRtpTransceiverDirection) String() string {
	switch t {
	case RTCRtpTransceiverDirectionSendrecv:
		return "sendrecv"
	case RTCRtpTransceiverDirectionSendonly:
		return "sendonly"
	case RTCRtpTransceiverDirectionRecvonly:
		return "recvonly"
	case RTCRtpTransceiverDirectionInactive:
		return "inactive"
	default:
		return "Unknown"
	}
}

// RTCRtpTransceiver represents a combination of an RTCRtpSender and an RTCRtpReceiver that share a common mid.
type RTCRtpTransceiver struct {
	Mid       string
	Sender    *RTCRtpSender
	Receiver  *RTCRtpReceiver
	Direction RTCRtpTransceiverDirection
	// currentDirection RTCRtpTransceiverDirection
	// firedDirection   RTCRtpTransceiverDirection
	// receptive bool
	stopped bool
}

func (t *RTCRtpTransceiver) setSendingTrack(track *RTCTrack) {
	t.Sender.Track = track

	switch t.Direction {
	case RTCRtpTransceiverDirectionRecvonly:
		t.Direction = RTCRtpTransceiverDirectionSendrecv
	case RTCRtpTransceiverDirectionInactive:
		t.Direction = RTCRtpTransceiverDirectionSendonly
	default:
		panic("Invalid state change in RTCRtpTransceiver.setSending")
	}
}

func (r *RTCPeerConnection) newRTCRtpTransceiver(
	receiver *RTCRtpReceiver,
	sender *RTCRtpSender,
	direction RTCRtpTransceiverDirection,
) *RTCRtpTransceiver {

	t := &RTCRtpTransceiver{
		Receiver:  receiver,
		Sender:    sender,
		Direction: direction,
	}
	r.rtpTransceivers = append(r.rtpTransceivers, t)
	return t
}

// Stop irreversibly stops the RTCRtpTransceiver
func (t *RTCRtpTransceiver) Stop() error {
	panic("TODO")
}

// RTCSample contains media, and the amount of samples in it
type RTCSample struct {
	Data    []byte
	Samples uint32
}

// RTCTrack represents a track that is communicated
type RTCTrack struct {
	PayloadType uint8
	Kind        RTCRtpCodecType
	ID          string
	Label       string
	Ssrc        uint32
	Codec       *RTCRtpCodec
	Packets     <-chan *rtp.Packet
	Samples     chan<- RTCSample
}

// NewRTCTrack is used to create a new RTCTrack
func (r *RTCPeerConnection) NewRTCTrack(payloadType uint8, id, label string) (*RTCTrack, error) {
	codec, err := r.mediaEngine.getCodec(payloadType)
	if err != nil {
		return nil, err
	}

	if codec.Payloader == nil {
		return nil, errors.New("codec payloader not set")
	}

	trackInput := make(chan RTCSample, 15) // Is the buffering needed?
	ssrc := rand.Uint32()
	go func() {
		packetizer := rtp.NewPacketizer(
			1400,
			payloadType,
			ssrc,
			codec.Payloader,
			rtp.NewRandomSequencer(),
			codec.ClockRate,
		)
		for {
			in := <-trackInput
			packets := packetizer.Packetize(in.Data, in.Samples)
			for _, p := range packets {
				r.networkManager.SendRTP(p)
			}
		}
	}()

	t := &RTCTrack{
		PayloadType: payloadType,
		Kind:        codec.Type,
		ID:          id,
		Label:       label,
		Ssrc:        ssrc,
		Codec:       codec,
		Samples:     trackInput,
	}

	return t, nil
}

// AddTrack adds a RTCTrack to the RTCPeerConnection
func (r *RTCPeerConnection) AddTrack(track *RTCTrack) (*RTCRtpSender, error) {
	if r.IsClosed {
		return nil, &InvalidStateError{Err: ErrConnectionClosed}
	}
	for _, tranceiver := range r.rtpTransceivers {
		if tranceiver.Sender.Track == nil {
			continue
		}
		if track.ID == tranceiver.Sender.Track.ID {
			return nil, &InvalidAccessError{Err: ErrExistingTrack}
		}
	}
	var tranciever *RTCRtpTransceiver
	for _, t := range r.rtpTransceivers {
		if !t.stopped &&
			// t.Sender == nil && // TODO: check that the sender has never sent
			t.Sender.Track == nil &&
			t.Receiver.Track != nil &&
			t.Receiver.Track.Kind == track.Kind {
			tranciever = t
			break
		}
	}
	if tranciever != nil {
		tranciever.setSendingTrack(track)
	} else {
		var receiver *RTCRtpReceiver
		sender := newRTCRtpSender(track)
		tranciever = r.newRTCRtpTransceiver(
			receiver,
			sender,
			RTCRtpTransceiverDirectionSendonly,
		)
	}

	tranciever.Mid = track.Kind.String() // TODO: Mid generation

	return tranciever.Sender, nil
}

// GetSenders returns the RTCRtpSender that are currently attached to this RTCPeerConnection
func (r *RTCPeerConnection) GetSenders() []RTCRtpSender {
	result := make([]RTCRtpSender, len(r.rtpTransceivers))
	for i, tranceiver := range r.rtpTransceivers {
		result[i] = *tranceiver.Sender
	}
	return result
}

// GetReceivers returns the RTCRtpReceivers that are currently attached to this RTCPeerConnection
func (r *RTCPeerConnection) GetReceivers() []RTCRtpReceiver {
	result := make([]RTCRtpReceiver, len(r.rtpTransceivers))
	for i, tranceiver := range r.rtpTransceivers {
		result[i] = *tranceiver.Receiver
	}
	return result
}

// GetTransceivers returns the RTCRtpTransceiver that are currently attached to this RTCPeerConnection
func (r *RTCPeerConnection) GetTransceivers() []RTCRtpTransceiver {
	result := make([]RTCRtpTransceiver, len(r.rtpTransceivers))
	for i, tranceiver := range r.rtpTransceivers {
		result[i] = *tranceiver
	}
	return result
}
<commit_msg>Fix typos<commit_after>package webrtc

import (
	"math/rand"

	"github.com/pions/webrtc/pkg/rtp"
	"github.com/pkg/errors"
)

// RTCRtpReceiver allows an application to inspect the receipt of a RTCTrack
type RTCRtpReceiver struct {
	Track *RTCTrack
	// receiverTrack *RTCTrack
	// receiverTransport
	// receiverRtcpTransport
}

// TODO: receiving side
// func newRTCRtpReceiver(kind, id string) {
//
// }

// RTCRtpSender allows an application to control how a given RTCTrack is encoded and transmitted to a remote peer
type RTCRtpSender struct {
	Track *RTCTrack
	// senderTrack *RTCTrack
	// senderTransport
	// senderRtcpTransport
}

func newRTCRtpSender(track *RTCTrack) *RTCRtpSender {
	s := &RTCRtpSender{
		Track: track,
	}
	return s
}

// RTCRtpTransceiverDirection indicates the direction of the RTCRtpTransceiver
type RTCRtpTransceiverDirection int

const (

	// RTCRtpTransceiverDirectionSendrecv indicates the RTCRtpSender will offer to send RTP and RTCRtpReceiver the will offer to receive RTP
	RTCRtpTransceiverDirectionSendrecv RTCRtpTransceiverDirection = iota + 1

	// RTCRtpTransceiverDirectionSendonly indicates the RTCRtpSender will offer to send RTP
	RTCRtpTransceiverDirectionSendonly

	// RTCRtpTransceiverDirectionRecvonly indicates the RTCRtpReceiver the will offer to receive RTP
	RTCRtpTransceiverDirectionRecvonly

	// RTCRtpTransceiverDirectionInactive indicates the RTCRtpSender won't offer to send RTP and RTCRtpReceiver the won't offer to receive RTP
	RTCRtpTransceiverDirectionInactive
)

func (t RTCRtpTransceiverDirection) String() string {
	switch t {
	case RTCRtpTransceiverDirectionSendrecv:
		return "sendrecv"
	case RTCRtpTransceiverDirectionSendonly:
		return "sendonly"
	case RTCRtpTransceiverDirectionRecvonly:
		return "recvonly"
	case RTCRtpTransceiverDirectionInactive:
		return "inactive"
	default:
		return "Unknown"
	}
}

// RTCRtpTransceiver represents a combination of an RTCRtpSender and an RTCRtpReceiver that share a common mid.
type RTCRtpTransceiver struct {
	Mid       string
	Sender    *RTCRtpSender
	Receiver  *RTCRtpReceiver
	Direction RTCRtpTransceiverDirection
	// currentDirection RTCRtpTransceiverDirection
	// firedDirection   RTCRtpTransceiverDirection
	// receptive bool
	stopped bool
}

func (t *RTCRtpTransceiver) setSendingTrack(track *RTCTrack) {
	t.Sender.Track = track

	switch t.Direction {
	case RTCRtpTransceiverDirectionRecvonly:
		t.Direction = RTCRtpTransceiverDirectionSendrecv
	case RTCRtpTransceiverDirectionInactive:
		t.Direction = RTCRtpTransceiverDirectionSendonly
	default:
		panic("Invalid state change in RTCRtpTransceiver.setSending")
	}
}

func (r *RTCPeerConnection) newRTCRtpTransceiver(
	receiver *RTCRtpReceiver,
	sender *RTCRtpSender,
	direction RTCRtpTransceiverDirection,
) *RTCRtpTransceiver {

	t := &RTCRtpTransceiver{
		Receiver:  receiver,
		Sender:    sender,
		Direction: direction,
	}
	r.rtpTransceivers = append(r.rtpTransceivers, t)
	return t
}

// Stop irreversibly stops the RTCRtpTransceiver
func (t *RTCRtpTransceiver) Stop() error {
	panic("TODO")
}

// RTCSample contains media, and the amount of samples in it
type RTCSample struct {
	Data    []byte
	Samples uint32
}

// RTCTrack represents a track that is communicated
type RTCTrack struct {
	PayloadType uint8
	Kind        RTCRtpCodecType
	ID          string
	Label       string
	Ssrc        uint32
	Codec       *RTCRtpCodec
	Packets     <-chan *rtp.Packet
	Samples     chan<- RTCSample
}

// NewRTCTrack is used to create a new RTCTrack
func (r *RTCPeerConnection) NewRTCTrack(payloadType uint8, id, label string) (*RTCTrack, error) {
	codec, err := r.mediaEngine.getCodec(payloadType)
	if err != nil {
		return nil, err
	}

	if codec.Payloader == nil {
		return nil, errors.New("codec payloader not set")
	}

	trackInput := make(chan RTCSample, 15) // Is the buffering needed?
	ssrc := rand.Uint32()
	go func() {
		packetizer := rtp.NewPacketizer(
			1400,
			payloadType,
			ssrc,
			codec.Payloader,
			rtp.NewRandomSequencer(),
			codec.ClockRate,
		)
		for {
			in := <-trackInput
			packets := packetizer.Packetize(in.Data, in.Samples)
			for _, p := range packets {
				r.networkManager.SendRTP(p)
			}
		}
	}()

	t := &RTCTrack{
		PayloadType: payloadType,
		Kind:        codec.Type,
		ID:          id,
		Label:       label,
		Ssrc:        ssrc,
		Codec:       codec,
		Samples:     trackInput,
	}

	return t, nil
}

// AddTrack adds a RTCTrack to the RTCPeerConnection
func (r *RTCPeerConnection) AddTrack(track *RTCTrack) (*RTCRtpSender, error) {
	if r.IsClosed {
		return nil, &InvalidStateError{Err: ErrConnectionClosed}
	}
	for _, transceiver := range r.rtpTransceivers {
		if transceiver.Sender.Track == nil {
			continue
		}
		if track.ID == transceiver.Sender.Track.ID {
			return nil, &InvalidAccessError{Err: ErrExistingTrack}
		}
	}
	var transceiver *RTCRtpTransceiver
	for _, t := range r.rtpTransceivers {
		if !t.stopped &&
			// t.Sender == nil && // TODO: check that the sender has never sent
			t.Sender.Track == nil &&
			t.Receiver.Track != nil &&
			t.Receiver.Track.Kind == track.Kind {
			transceiver = t
			break
		}
	}
	if transceiver != nil {
		transceiver.setSendingTrack(track)
	} else {
		var receiver *RTCRtpReceiver
		sender := newRTCRtpSender(track)
		transceiver = r.newRTCRtpTransceiver(
			receiver,
			sender,
			RTCRtpTransceiverDirectionSendonly,
		)
	}

	transceiver.Mid = track.Kind.String() // TODO: Mid generation

	return transceiver.Sender, nil
}

// GetSenders returns the RTCRtpSender that are currently attached to this RTCPeerConnection
func (r *RTCPeerConnection) GetSenders() []RTCRtpSender {
	result := make([]RTCRtpSender, len(r.rtpTransceivers))
	for i, tranceiver := range r.rtpTransceivers {
		result[i] = *tranceiver.Sender
	}
	return result
}

// GetReceivers returns the RTCRtpReceivers that are currently attached to this RTCPeerConnection
func (r *RTCPeerConnection) GetReceivers() []RTCRtpReceiver {
	result := make([]RTCRtpReceiver, len(r.rtpTransceivers))
	for i, tranceiver := range r.rtpTransceivers {
		result[i] = *tranceiver.Receiver
	}
	return result
}

// GetTransceivers returns the RTCRtpTransceiver that are currently attached to this RTCPeerConnection
func (r *RTCPeerConnection) GetTransceivers() []RTCRtpTransceiver {
	result := make([]RTCRtpTransceiver, len(r.rtpTransceivers))
	for i, tranceiver := range r.rtpTransceivers {
		result[i] = *tranceiver
	}
	return result
}
<|endoftext|>


<commit_before>package goinsta

import (
	"encoding/json"
	"fmt"
	"strconv"
)

// Item represents media items
type Item struct {
	TakenAt          int     `json:"taken_at"`
	ID               int64   `json:"pk"`
	IDStr            string  `json:"id"`
	DeviceTimestamp  int64   `json:"device_timestamp"`
	MediaType        int     `json:"media_type"`
	Code             string  `json:"code"`
	ClientCacheKey   string  `json:"client_cache_key"`
	FilterType       int     `json:"filter_type"`
	CarouselParentID string  `json:"carousel_parent_id"`
	CarouselMedia    []Item  `json:"carousel_media,omitempty"`
	User             User    `json:"user"`
	CanViewerReshare bool    `json:"can_viewer_reshare"`
	Caption          Caption `json:"caption"`
	CaptionIsEdited  bool    `json:"caption_is_edited"`
	Likes            int     `json:"like_count"`
	HasLiked         bool    `json:"has_liked"`
	// TopLikers can be multiple data
	TopLikersStr                 `json:"top_likers,string"`
	TopLikers                    []User `json:"top_likers"`
	CommentLikesEnabled          bool   `json:"comment_likes_enabled"`
	CommentThreadingEnabled      bool   `json:"comment_threading_enabled"`
	HasMoreComments              bool   `json:"has_more_comments"`
	MaxNumVisiblePreviewComments int    `json:"max_num_visible_preview_comments"`
	// PreviewComments can be `string` or `[]string`
	PreviewComments      []interface{} `json:"preview_comments,omitempty"`
	CommentCount         int           `json:"comment_count"`
	PhotoOfYou           bool          `json:"photo_of_you"`
	Usertags             Tag           `json:"usertags,omitempty"`
	FbUserTags           Tag           `json:"fb_user_tags"`
	CanViewerSave        bool          `json:"can_viewer_save"`
	OrganicTrackingToken string        `json:"organic_tracking_token"`
	Images               Images        `json:"image_versions2,omitempty"`
	OriginalWidth        int           `json:"original_width,omitempty"`
	OriginalHeight       int           `json:"original_height,omitempty"`
	ImportedTakenAt      int           `json:"imported_taken_at,omitempty"`

	// Only for stories
	StoryEvents              []interface{} `json:"story_events"`
	StoryHashtags            []interface{} `json:"story_hashtags"`
	StoryPolls               []interface{} `json:"story_polls"`
	StoryFeedMedia           []interface{} `json:"story_feed_media"`
	StorySoundOn             []interface{} `json:"story_sound_on"`
	CreativeConfig           interface{}   `json:"creative_config"`
	StoryLocations           []interface{} `json:"story_locations"`
	StorySliders             []interface{} `json:"story_sliders"`
	StoryQuestions           []interface{} `json:"story_questions"`
	StoryProductItems        []interface{} `json:"story_product_items"`
	SupportsReelReactions    bool          `json:"supports_reel_reactions"`
	ShowOneTapFbShareTooltip bool          `json:"show_one_tap_fb_share_tooltip"`
	HasSharedToFb            int           `json:"has_shared_to_fb"`
	Mentions                 []Mentions
	Videos                   []Videos `json:"video_versions,omitempty"`
	HasAudio                 bool     `json:"has_audio,omitempty"`
	VideoDuration            float64  `json:"video_duration,omitempty"`
	IsDashEligible           int      `json:"is_dash_eligible,omitempty"`
	VideoDashManifest        string   `json:"video_dash_manifest,omitempty"`
	NumberOfQualities        int      `json:"number_of_qualities,omitempty"`
}

type Media interface {
	Next() error
}

type StoryMedia struct {
	inst     *Instagram
	endpoint string
	uid      int64

	ID              int      `json:"id"`
	LatestReelMedia int      `json:"latest_reel_media"`
	ExpiringAt      int      `json:"expiring_at"`
	Seen            float64  `json:"seen"`
	CanReply        bool     `json:"can_reply"`
	CanReshare      bool     `json:"can_reshare"`
	ReelType        string   `json:"reel_type"`
	User            User     `json:"user"`
	Items           []Item   `json:"items"`
	ReelMentions    []string `json:"reel_mentions"`
	PrefetchCount   int      `json:"prefetch_count"`
	HasBestiesMedia int      `json:"has_besties_media"`
	Status          string   `json:"status"`
}

// Next allows to paginate after calling:
// User.Stories
func (media *StoryMedia) Next() (err error) {
	var body []byte
	insta := media.inst
	endpoint := media.endpoint

	body, err = insta.sendSimpleRequest(
		endpoint, media.uid,
	)
	if err == nil {
		m := StoryMedia{}
		err = json.Unmarshal(body, &m)
		if err == nil {
			err = ErrNoMore
			*media = m
			media.inst = insta
			media.endpoint = endpoint
			// TODO check NextID media
		}
	}
	return err
}

// Media represent a set of media items
type FeedMedia struct {
	inst *Instagram

	uid      int64
	endpoint string

	Items               []Item `json:"items"`
	NumResults          int    `json:"num_results"`
	MoreAvailable       bool   `json:"more_available"`
	AutoLoadMoreEnabled bool   `json:"auto_load_more_enabled"`
	Status              string `json:"status"`
	NextID              int64  `json:"next_max_id"`
	NextIDStr           string `json:"next_max_id,string"`
}

// Next allows to paginate after calling:
// User.Feed
//
// returns ErrNoMore when list reach the end.
func (media *FeedMedia) Next() (err error) {
	var body []byte
	insta := media.inst
	endpoint := media.endpoint
	next := ""

	switch {
	case media.NextID != 0:
		next = media.NextIDStr
	case media.NextIDStr == "":
		next = strconv.FormatInt(media.NextID, 10)
	}
	body, err = insta.sendRequest(
		&reqOptions{
			Endpoint: fmt.Sprintf(endpoint, media.uid),
			Query: map[string]string{
				"max_id":         next,
				"rank_token":     insta.rankToken,
				"min_timestamp":  "",
				"ranked_content": "true",
			},
		},
	)
	if err == nil {
		m := FeedMedia{}
		err = json.Unmarshal(body, &m)
		if err == nil {
			*media = m
			media.inst = insta
			media.endpoint = endpoint
			if m.NextID == 0 || m.MoreAvailable {
				err = ErrNoMore
			}
		}
	}
	return err
}
<commit_msg>error<commit_after>package goinsta

import (
	"encoding/json"
	"fmt"
	"strconv"
)

// Item represents media items
type Item struct {
	TakenAt          int     `json:"taken_at"`
	ID               int64   `json:"pk"`
	IDStr            string  `json:"id"`
	DeviceTimestamp  int64   `json:"device_timestamp"`
	MediaType        int     `json:"media_type"`
	Code             string  `json:"code"`
	ClientCacheKey   string  `json:"client_cache_key"`
	FilterType       int     `json:"filter_type"`
	CarouselParentID string  `json:"carousel_parent_id"`
	CarouselMedia    []Item  `json:"carousel_media,omitempty"`
	User             User    `json:"user"`
	CanViewerReshare bool    `json:"can_viewer_reshare"`
	Caption          Caption `json:"caption"`
	CaptionIsEdited  bool    `json:"caption_is_edited"`
	Likes            int     `json:"like_count"`
	HasLiked         bool    `json:"has_liked"`
	// TopLikers can be multiple data
	TopLikersStr                 string `json:"top_likers,string"`
	TopLikers                    []User `json:"top_likers"`
	CommentLikesEnabled          bool   `json:"comment_likes_enabled"`
	CommentThreadingEnabled      bool   `json:"comment_threading_enabled"`
	HasMoreComments              bool   `json:"has_more_comments"`
	MaxNumVisiblePreviewComments int    `json:"max_num_visible_preview_comments"`
	// PreviewComments can be `string` or `[]string`
	PreviewComments      []interface{} `json:"preview_comments,omitempty"`
	CommentCount         int           `json:"comment_count"`
	PhotoOfYou           bool          `json:"photo_of_you"`
	Usertags             Tag           `json:"usertags,omitempty"`
	FbUserTags           Tag           `json:"fb_user_tags"`
	CanViewerSave        bool          `json:"can_viewer_save"`
	OrganicTrackingToken string        `json:"organic_tracking_token"`
	Images               Images        `json:"image_versions2,omitempty"`
	OriginalWidth        int           `json:"original_width,omitempty"`
	OriginalHeight       int           `json:"original_height,omitempty"`
	ImportedTakenAt      int           `json:"imported_taken_at,omitempty"`

	// Only for stories
	StoryEvents              []interface{} `json:"story_events"`
	StoryHashtags            []interface{} `json:"story_hashtags"`
	StoryPolls               []interface{} `json:"story_polls"`
	StoryFeedMedia           []interface{} `json:"story_feed_media"`
	StorySoundOn             []interface{} `json:"story_sound_on"`
	CreativeConfig           interface{}   `json:"creative_config"`
	StoryLocations           []interface{} `json:"story_locations"`
	StorySliders             []interface{} `json:"story_sliders"`
	StoryQuestions           []interface{} `json:"story_questions"`
	StoryProductItems        []interface{} `json:"story_product_items"`
	SupportsReelReactions    bool          `json:"supports_reel_reactions"`
	ShowOneTapFbShareTooltip bool          `json:"show_one_tap_fb_share_tooltip"`
	HasSharedToFb            int           `json:"has_shared_to_fb"`
	Mentions                 []Mentions
	Videos                   []Videos `json:"video_versions,omitempty"`
	HasAudio                 bool     `json:"has_audio,omitempty"`
	VideoDuration            float64  `json:"video_duration,omitempty"`
	IsDashEligible           int      `json:"is_dash_eligible,omitempty"`
	VideoDashManifest        string   `json:"video_dash_manifest,omitempty"`
	NumberOfQualities        int      `json:"number_of_qualities,omitempty"`
}

type Media interface {
	Next() error
}

type StoryMedia struct {
	inst     *Instagram
	endpoint string
	uid      int64

	ID              int      `json:"id"`
	LatestReelMedia int      `json:"latest_reel_media"`
	ExpiringAt      int      `json:"expiring_at"`
	Seen            float64  `json:"seen"`
	CanReply        bool     `json:"can_reply"`
	CanReshare      bool     `json:"can_reshare"`
	ReelType        string   `json:"reel_type"`
	User            User     `json:"user"`
	Items           []Item   `json:"items"`
	ReelMentions    []string `json:"reel_mentions"`
	PrefetchCount   int      `json:"prefetch_count"`
	HasBestiesMedia int      `json:"has_besties_media"`
	Status          string   `json:"status"`
}

// Next allows to paginate after calling:
// User.Stories
func (media *StoryMedia) Next() (err error) {
	var body []byte
	insta := media.inst
	endpoint := media.endpoint

	body, err = insta.sendSimpleRequest(
		endpoint, media.uid,
	)
	if err == nil {
		m := StoryMedia{}
		err = json.Unmarshal(body, &m)
		if err == nil {
			err = ErrNoMore
			*media = m
			media.inst = insta
			media.endpoint = endpoint
			// TODO check NextID media
		}
	}
	return err
}

// Media represent a set of media items
type FeedMedia struct {
	inst *Instagram

	uid      int64
	endpoint string

	Items               []Item `json:"items"`
	NumResults          int    `json:"num_results"`
	MoreAvailable       bool   `json:"more_available"`
	AutoLoadMoreEnabled bool   `json:"auto_load_more_enabled"`
	Status              string `json:"status"`
	NextID              int64  `json:"next_max_id"`
	NextIDStr           string `json:"next_max_id,string"`
}

// Next allows to paginate after calling:
// User.Feed
//
// returns ErrNoMore when list reach the end.
func (media *FeedMedia) Next() (err error) {
	var body []byte
	insta := media.inst
	endpoint := media.endpoint
	next := ""

	switch {
	case media.NextID != 0:
		next = media.NextIDStr
	case media.NextIDStr == "":
		next = strconv.FormatInt(media.NextID, 10)
	}
	body, err = insta.sendRequest(
		&reqOptions{
			Endpoint: fmt.Sprintf(endpoint, media.uid),
			Query: map[string]string{
				"max_id":         next,
				"rank_token":     insta.rankToken,
				"min_timestamp":  "",
				"ranked_content": "true",
			},
		},
	)
	if err == nil {
		m := FeedMedia{}
		err = json.Unmarshal(body, &m)
		if err == nil {
			*media = m
			media.inst = insta
			media.endpoint = endpoint
			if m.NextID == 0 || m.MoreAvailable {
				err = ErrNoMore
			}
		}
	}
	return err
}
<|endoftext|>


<commit_before>package main

import (
	"testing"

	"github.com/bmizerany/assert"
)

func TestFilename(t *testing.T) {
	var actual string

	actual = filename("Writer", false)
	assert.Equal(t, "writer.go", actual)

	actual = filename("RoundTripper", false)
	assert.Equal(t, "roundtripper.go", actual)

	actual = filename("Writer", true)
	assert.Equal(t, "mock_writer_test.go", actual)

	actual = filename("RoundTripper", true)
	assert.Equal(t, "mock_roundtripper_test.go", actual)
}
<commit_msg>Remove unnecessary test file. Fixes #34<commit_after><|endoftext|>


<commit_before>package gotraps

import (
	"appengine"
	"appengine/urlfetch"
	"encoding/json"
	"fmt"
	"html"
	"io/ioutil"
	"net/http"
	"net/url"
)

//
// Just forward the response from another site, to the user.
// Used to bypass the "Access-Control-Allow-Origin" for Go snippet compilation+execution.
//
func compile(w http.ResponseWriter, r *http.Request) {
	c := appengine.NewContext(r)

	trapcodeEscaped := r.FormValue("body")
	trapname := r.FormValue("trapname")
	c.Infof("Compile [%v]", trapname)

	trapcode := html.UnescapeString(trapcodeEscaped)
	values := url.Values{
		"version": []string{"2"},
		"body":    []string{trapcode},
	}
	//c.Infof("%v", values)

	resp, err := post(c, values)
	//c.Infof("%v", resp)
	if err != nil {
		c.Errorf("%v", err)
		sendJsonError(w, err)
		return
	}
	defer resp.Body.Close()
	x, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		c.Errorf("%v", err)
		sendJsonError(w, err)
		return
	}
	_, err = w.Write(x)
	if err != nil {
		c.Errorf("%v", err)
		sendJsonError(w, err)
		return
	}

	// Temporary extra request, just to check if User-Agent header is correct
	urlfetch.Client(c).PostForm("http://antipastebin.appspot.com/echo", values)
}

const REMOTE_PLAYGROUND_COMPILE_URL = "http://play.golang.org/compile"
const GOTRAPS_UNIQUE_USER_AGENT = "go-traps.appspot.com"

// This works but doesn't explicitly add User-Agent header
//
// However according to https://developers.google.com/appengine/docs/go/urlfetch/#headers_identifying_request_source :
// "User-Agent. This header can be modified but App Engine will append an
// identifier string to allow servers to identify App Engine requests.
// The appended string has the format "AppEngine-Google; (+http://code.google.com/appengine; appid: APPID)",
// where APPID is your app's identifier."
func post(c appengine.Context, values url.Values) (*http.Response, error) {
	return urlfetch.Client(c).PostForm(REMOTE_PLAYGROUND_COMPILE_URL, values)
}

// This does not work: http.DefaultTransport and http.DefaultClient are not available in App Engine.
func postWithUserAgent(c appengine.Context, values url.Values) (*http.Response, error) {
	client := &http.Client{}
	req, err := http.NewRequest("POST", REMOTE_PLAYGROUND_COMPILE_URL, nil)
	if err != nil {
		return nil, err
	}
	req.Header.Set("User-Agent", GOTRAPS_UNIQUE_USER_AGENT)

	return client.Do(req)
}

func sendJsonError(w http.ResponseWriter, err error) {
	w.WriteHeader(500)
	fmt.Fprint(w, Response{"Errors": err.Error(), "Events": nil})
}

type Response map[string]interface{}

func (r Response) String() (s string) {
	b, err := json.Marshal(r)
	if err != nil {
		s = ""
		return
	}
	s = string(b)
	return
}
<commit_msg>The header value is AppEngine-Google; (+http://code.google.com/appengine; appid: s~go-traps)<commit_after>package gotraps

import (
	"appengine"
	"appengine/urlfetch"
	"encoding/json"
	"fmt"
	"html"
	"io/ioutil"
	"net/http"
	"net/url"
)

//
// Just forward the response from another site, to the user.
// Used to bypass the "Access-Control-Allow-Origin" for Go snippet compilation+execution.
//
func compile(w http.ResponseWriter, r *http.Request) {
	c := appengine.NewContext(r)

	trapcodeEscaped := r.FormValue("body")
	trapname := r.FormValue("trapname")
	c.Infof("Compile [%v]", trapname)

	trapcode := html.UnescapeString(trapcodeEscaped)
	values := url.Values{
		"version": []string{"2"},
		"body":    []string{trapcode},
	}
	//c.Infof("%v", values)

	resp, err := post(c, values)
	//c.Infof("%v", resp)
	if err != nil {
		c.Errorf("%v", err)
		sendJsonError(w, err)
		return
	}
	defer resp.Body.Close()
	x, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		c.Errorf("%v", err)
		sendJsonError(w, err)
		return
	}
	_, err = w.Write(x)
	if err != nil {
		c.Errorf("%v", err)
		sendJsonError(w, err)
		return
	}

	// Temporary extra request, just to check if User-Agent header is correct
	// urlfetch.Client(c).PostForm("http://antipastebin.appspot.com/echo", values)
	//  ok: the header is "AppEngine-Google; (+http://code.google.com/appengine; appid: s~go-traps)"
}

const REMOTE_PLAYGROUND_COMPILE_URL = "http://play.golang.org/compile"
const GOTRAPS_UNIQUE_USER_AGENT = "go-traps.appspot.com"

// This works but doesn't explicitly add User-Agent header
//
// However according to https://developers.google.com/appengine/docs/go/urlfetch/#headers_identifying_request_source :
// "User-Agent. This header can be modified but App Engine will append an
// identifier string to allow servers to identify App Engine requests.
// The appended string has the format "AppEngine-Google; (+http://code.google.com/appengine; appid: APPID)",
// where APPID is your app's identifier."
//
// After further investigation: the header value is "AppEngine-Google; (+http://code.google.com/appengine; appid: s~go-traps)"
func post(c appengine.Context, values url.Values) (*http.Response, error) {
	return urlfetch.Client(c).PostForm(REMOTE_PLAYGROUND_COMPILE_URL, values)
}

// This does not work: http.DefaultTransport and http.DefaultClient are not available in App Engine.
func postWithUserAgent(c appengine.Context, values url.Values) (*http.Response, error) {
	client := &http.Client{}
	req, err := http.NewRequest("POST", REMOTE_PLAYGROUND_COMPILE_URL, nil)
	if err != nil {
		return nil, err
	}
	req.Header.Set("User-Agent", GOTRAPS_UNIQUE_USER_AGENT)

	return client.Do(req)
}

func sendJsonError(w http.ResponseWriter, err error) {
	w.WriteHeader(500)
	fmt.Fprint(w, Response{"Errors": err.Error(), "Events": nil})
}

type Response map[string]interface{}

func (r Response) String() (s string) {
	b, err := json.Marshal(r)
	if err != nil {
		s = ""
		return
	}
	s = string(b)
	return
}
<|endoftext|>


<commit_before>package main

import (
	"fmt"
	"os"
	"runtime"

	"github.com/ethereum/eth-go"
	"github.com/ethereum/eth-go/ethlog"
	"github.com/ethereum/go-ethereum/utils"
	"gopkg.in/qml.v1"
)

const (
	ClientIdentifier = "Ethereal"
	Version          = "0.6.5"
)

var ethereum *eth.Ethereum

func run() error {
	// precedence: code-internal flag default < config file < environment variables < command line
	Init() // parsing command line

	config := utils.InitConfig(ConfigFile, Datadir, "ETH")

	utils.InitDataDir(Datadir)

	utils.InitLogging(Datadir, LogFile, LogLevel, DebugFile)

	db := utils.NewDatabase()
	err := utils.DBSanityCheck(db)
	if err != nil {
		engine := qml.NewEngine()
		component, e := engine.LoadString("local", qmlErr)
		if e != nil {
			fmt.Println("err:", err)
			os.Exit(1)
		}

		win := component.CreateWindow(nil)
		win.Root().ObjectByName("label").Set("text", err.Error())
		win.Show()
		win.Wait()

		ErrorWindow(err)
		os.Exit(1)
	}

	keyManager := utils.NewKeyManager(KeyStore, Datadir, db)

	// create, import, export keys
	utils.KeyTasks(keyManager, KeyRing, GenAddr, SecretFile, ExportDir, NonInteractive)

	clientIdentity := utils.NewClientIdentity(ClientIdentifier, Version, Identifier)

	ethereum = utils.NewEthereum(db, clientIdentity, keyManager, UseUPnP, OutboundPort, MaxPeer)

	if ShowGenesis {
		utils.ShowGenesis(ethereum)
	}

	if StartRpc {
		utils.StartRpc(ethereum, RpcPort)
	}

	gui := NewWindow(ethereum, config, clientIdentity, KeyRing, LogLevel)

	utils.RegisterInterrupt(func(os.Signal) {
		gui.Stop()
	})
	utils.StartEthereum(ethereum, UseSeed)
	// gui blocks the main thread
	gui.Start(AssetPath)

	return nil
}

func main() {
	runtime.GOMAXPROCS(runtime.NumCPU())

	// This is a bit of a cheat, but ey!
	os.Setenv("QTWEBKIT_INSPECTOR_SERVER", "127.0.0.1:99999")

	//qml.Init(nil)
	qml.Run(run)

	var interrupted = false
	utils.RegisterInterrupt(func(os.Signal) {
		interrupted = true
	})

	utils.HandleInterrupt()

	// we need to run the interrupt callbacks in case gui is closed
	// this skips if we got here by actual interrupt stopping the GUI
	if !interrupted {
		utils.RunInterruptCallbacks(os.Interrupt)
	}
	// this blocks the thread
	ethereum.WaitForShutdown()
	ethlog.Flush()
}
<commit_msg>Error window<commit_after>package main

import (
	"os"
	"runtime"

	"github.com/ethereum/eth-go"
	"github.com/ethereum/eth-go/ethlog"
	"github.com/ethereum/go-ethereum/utils"
	"gopkg.in/qml.v1"
)

const (
	ClientIdentifier = "Ethereal"
	Version          = "0.6.5"
)

var ethereum *eth.Ethereum

func run() error {
	// precedence: code-internal flag default < config file < environment variables < command line
	Init() // parsing command line

	config := utils.InitConfig(ConfigFile, Datadir, "ETH")

	utils.InitDataDir(Datadir)

	utils.InitLogging(Datadir, LogFile, LogLevel, DebugFile)

	db := utils.NewDatabase()
	err := utils.DBSanityCheck(db)
	if err != nil {
		ErrorWindow(err)
		os.Exit(1)
	}

	keyManager := utils.NewKeyManager(KeyStore, Datadir, db)

	// create, import, export keys
	utils.KeyTasks(keyManager, KeyRing, GenAddr, SecretFile, ExportDir, NonInteractive)

	clientIdentity := utils.NewClientIdentity(ClientIdentifier, Version, Identifier)

	ethereum = utils.NewEthereum(db, clientIdentity, keyManager, UseUPnP, OutboundPort, MaxPeer)

	if ShowGenesis {
		utils.ShowGenesis(ethereum)
	}

	if StartRpc {
		utils.StartRpc(ethereum, RpcPort)
	}

	gui := NewWindow(ethereum, config, clientIdentity, KeyRing, LogLevel)

	utils.RegisterInterrupt(func(os.Signal) {
		gui.Stop()
	})
	utils.StartEthereum(ethereum, UseSeed)
	// gui blocks the main thread
	gui.Start(AssetPath)

	return nil
}

func main() {
	runtime.GOMAXPROCS(runtime.NumCPU())

	// This is a bit of a cheat, but ey!
	os.Setenv("QTWEBKIT_INSPECTOR_SERVER", "127.0.0.1:99999")

	//qml.Init(nil)
	qml.Run(run)

	var interrupted = false
	utils.RegisterInterrupt(func(os.Signal) {
		interrupted = true
	})

	utils.HandleInterrupt()

	// we need to run the interrupt callbacks in case gui is closed
	// this skips if we got here by actual interrupt stopping the GUI
	if !interrupted {
		utils.RunInterruptCallbacks(os.Interrupt)
	}
	// this blocks the thread
	ethereum.WaitForShutdown()
	ethlog.Flush()
}
<|endoftext|>


<commit_before><commit_msg>peer: remove static remote required for peers with legacy channels<commit_after><|endoftext|>


<commit_before><commit_msg>share http client for all requests.<commit_after><|endoftext|>


<commit_before><commit_msg>Set file permission to 0755 for executable<commit_after><|endoftext|>


<commit_before><commit_msg>staticcheck<commit_after><|endoftext|>


<commit_before>package corehttp

// TODO: move to IPNS
const WebUIPath = "/ipfs/QmR9MzChjp1MdFWik7NjEjqKQMzVmBkdK3dz14A6B5Cupm"

// this is a list of all past webUI paths.
var WebUIPaths = []string{
	WebUIPath,
	"/ipfs/QmXX7YRpU7nNBKfw75VG7Y1c3GwpSAGHRev67XVPgZFv9R",
	"/ipfs/QmXdu7HWdV6CUaUabd9q2ZeA4iHZLVyDRj3Gi4dsJsWjbr",
	"/ipfs/QmaaqrHyAQm7gALkRW8DcfGX3u8q9rWKnxEMmf7m9z515w",
	"/ipfs/QmSHDxWsMPuJQKWmVA1rB5a3NX2Eme5fPqNb63qwaqiqSp",
	"/ipfs/QmctngrQAt9fjpQUZr7Bx3BsXUcif52eZGTizWhvcShsjz",
	"/ipfs/QmS2HL9v5YeKgQkkWMvs1EMnFtUowTEdFfSSeMT4pos1e6",
}

var WebUIOption = RedirectOption("webui", WebUIPath)
<commit_msg>feat: Update to the latest version of the webui<commit_after>package corehttp

// TODO: move to IPNS
const WebUIPath = "/ipfs/QmRyWyKWmphamkMRnJVjUTzSFSAAZowYP4rnbgnfMXC9Mr"

// this is a list of all past webUI paths.
var WebUIPaths = []string{
	WebUIPath,
	"/ipfs/QmXX7YRpU7nNBKfw75VG7Y1c3GwpSAGHRev67XVPgZFv9R",
	"/ipfs/QmXdu7HWdV6CUaUabd9q2ZeA4iHZLVyDRj3Gi4dsJsWjbr",
	"/ipfs/QmaaqrHyAQm7gALkRW8DcfGX3u8q9rWKnxEMmf7m9z515w",
	"/ipfs/QmSHDxWsMPuJQKWmVA1rB5a3NX2Eme5fPqNb63qwaqiqSp",
	"/ipfs/QmctngrQAt9fjpQUZr7Bx3BsXUcif52eZGTizWhvcShsjz",
	"/ipfs/QmS2HL9v5YeKgQkkWMvs1EMnFtUowTEdFfSSeMT4pos1e6",
	"/ipfs/QmR9MzChjp1MdFWik7NjEjqKQMzVmBkdK3dz14A6B5Cupm",
}

var WebUIOption = RedirectOption("webui", WebUIPath)
<|endoftext|>


<commit_before>package hg

import (
	"bytes"
	"fmt"
	"os"
	"os/exec"
	"path/filepath"
	"regexp"
	"strings"
	"sync"
	"time"

	"github.com/fatih/color"
)

type HGCommand struct {
	Cmd  string
	args []string
}

func findRepo(root string, sign string, path_chan chan string) {
	defer close(path_chan)

	visit := func(path string, info os.FileInfo, err error) error {
		if !info.IsDir() {
			return nil
		}

		if info.Name() == sign && info.IsDir() {
			dir, _ := filepath.Split(path)
			abs_dir, err := filepath.Abs(dir)
			if err != nil {
				color.Red(err.Error())
				return nil
			}
			// ignore hidden directories
			matched, _ := regexp.MatchString("/\\.", abs_dir)
			if matched {
				return nil
			}

			path_chan <- abs_dir
		}
		return nil
	}

	filepath.Walk(root, visit)
}

func (cmd *HGCommand) Run(path string, wg *sync.WaitGroup) {
	defer wg.Done()
	args := append([]string{cmd.Cmd, "--repository", path}, cmd.args...)
	system_cmd := exec.Command("hg", args...)

	var out bytes.Buffer
	system_cmd.Stdout = &out

	err := system_cmd.Run()

	color.Green(path)
	color.Yellow("hg %s", strings.Join(args, " "))

	if err != nil {
		color.Red(err.Error())
	}
	fmt.Println(out.String())
}

func (cmd *HGCommand) RunForAll() {
	t := time.Now()
	wg := new(sync.WaitGroup)
	path_chan := make(chan string)
	count := 0

	go findRepo(".", ".hg", path_chan)

	for path := range path_chan {
		wg.Add(1)
		go cmd.Run(path, wg)
		count += 1
	}

	wg.Wait()
	color.Cyan("Done \"hg %s\" for %d repos in %s\n\n", cmd.Cmd, count, time.Since(t))
}

func (cmd *HGCommand) SetBranch(branch string) {
	if branch != "" {
		cmd.args = append(cmd.args, "--rev", branch)
	}
}
func (cmd *HGCommand) SetNewBranch(new_branch bool) {
	if new_branch {
		cmd.args = append(cmd.args, "--new-branch")
	}
}

func (cmd *HGCommand) SetClean(clean bool) {
	if clean {
		cmd.args = append(cmd.args, "--clean")
	}
}
<commit_msg>golint<commit_after>package hg

import (
	"bytes"
	"fmt"
	"os"
	"os/exec"
	"path/filepath"
	"regexp"
	"strings"
	"sync"
	"time"

	"github.com/fatih/color"
)

type HGCommand struct {
	Cmd  string
	args []string
}

func findRepo(root string, sign string, pathChan chan string) {
	defer close(pathChan)

	visit := func(path string, info os.FileInfo, err error) error {
		if !info.IsDir() {
			return nil
		}

		if info.Name() == sign && info.IsDir() {
			dir, _ := filepath.Split(path)
			absDir, err := filepath.Abs(dir)
			if err != nil {
				color.Red(err.Error())
				return nil
			}
			// ignore hidden directories
			matched, _ := regexp.MatchString("/\\.", absDir)
			if matched {
				return nil
			}

			pathChan <- absDir
		}
		return nil
	}

	filepath.Walk(root, visit)
}

func (cmd *HGCommand) Run(path string, wg *sync.WaitGroup) {
	defer wg.Done()
	args := append([]string{cmd.Cmd, "--repository", path}, cmd.args...)
	systemCmd := exec.Command("hg", args...)

	var out bytes.Buffer
	systemCmd.Stdout = &out

	err := systemCmd.Run()

	color.Green(path)
	color.Yellow("hg %s", strings.Join(args, " "))

	if err != nil {
		color.Red(err.Error())
	}
	fmt.Println(out.String())
}

func (cmd *HGCommand) RunForAll() {
	t := time.Now()
	wg := new(sync.WaitGroup)
	pathChan := make(chan string)
	count := 0

	go findRepo(".", ".hg", pathChan)

	for path := range pathChan {
		wg.Add(1)
		go cmd.Run(path, wg)
		count += 1
	}

	wg.Wait()
	color.Cyan("Done \"hg %s\" for %d repos in %s\n\n", cmd.Cmd, count, time.Since(t))
}

func (cmd *HGCommand) SetBranch(branch string) {
	if branch != "" {
		cmd.args = append(cmd.args, "--rev", branch)
	}
}
func (cmd *HGCommand) SetNewBranch(newBranch bool) {
	if newBranch {
		cmd.args = append(cmd.args, "--new-branch")
	}
}

func (cmd *HGCommand) SetClean(clean bool) {
	if clean {
		cmd.args = append(cmd.args, "--clean")
	}
}
<|endoftext|>


<commit_before>package ezserver

import (
	"crypto/tls"
	"net"
	"net/http"
	"strconv"
)

// HTTPS is an HTTPS server instance which can listen on one port at a time.
type HTTPS struct {
	*HTTP
	config *TLSConfig
}

// NewHTTPS creates a new HTTPS server with a given handler.
// The server will not be started.
func NewHTTPS(handler http.Handler, config *TLSConfig) *HTTPS {
	return &HTTPS{NewHTTP(handler), config.Clone()}
}

// GetTLSConfig returns the TLSConfig for the server.
func (self *HTTPS) GetTLSConfig() *TLSConfig {
	self.mutex.RLock()
	defer self.mutex.RUnlock()
	return self.config.Clone()
}

// SetTLSConfig sets the TLSConfig on the server.
// This may stop and restart the server.
func (self *HTTPS) SetTLSConfig(c *TLSConfig) error {
	self.mutex.Lock()
	defer self.mutex.Unlock()
	self.config = c.Clone()
	if self.listener == nil {
		return nil
	}
	if err := self.stopInternal(); err != nil {
		return err
	}
	return self.startInternal(self.listenPort)
}

// Start runs the HTTP server on a given port.
func (self *HTTPS) Start(port int) error {
	self.mutex.Lock()
	defer self.mutex.Unlock()
	return self.startInternal(port)
}

func (self *HTTPS) startInternal(port int) error {
	if port < 0 || port > 65535 {
		return ErrInvalidPort
	} else if self.listener != nil {
		return ErrAlreadyListening
	}

	config, err := self.config.ToConfig()
	if err != nil {
		return err
	}

	// Create a new TCP listener
	tcpListener, err := net.Listen("tcp", ":"+strconv.Itoa(port))
	if err != nil {
		return err
	}
	listener := tls.NewListener(tcpListener, config)
	self.listener = &listener

	// Run the server in the background
	self.loopDone = make(chan struct{})
	go self.serverLoop(self.listener, self.loopDone, "https")

	self.listenPort = port

	return nil
}
<commit_msg>renamed getter<commit_after>package ezserver

import (
	"crypto/tls"
	"net"
	"net/http"
	"strconv"
)

// HTTPS is an HTTPS server instance which can listen on one port at a time.
type HTTPS struct {
	*HTTP
	config *TLSConfig
}

// NewHTTPS creates a new HTTPS server with a given handler.
// The server will not be started.
func NewHTTPS(handler http.Handler, config *TLSConfig) *HTTPS {
	return &HTTPS{NewHTTP(handler), config.Clone()}
}

// SetTLSConfig sets the TLSConfig on the server.
// This may stop and restart the server.
func (self *HTTPS) SetTLSConfig(c *TLSConfig) error {
	self.mutex.Lock()
	defer self.mutex.Unlock()
	self.config = c.Clone()
	if self.listener == nil {
		return nil
	}
	if err := self.stopInternal(); err != nil {
		return err
	}
	return self.startInternal(self.listenPort)
}

// Start runs the HTTP server on a given port.
func (self *HTTPS) Start(port int) error {
	self.mutex.Lock()
	defer self.mutex.Unlock()
	return self.startInternal(port)
}

// TLSConfig returns the TLSConfig for the server.
func (self *HTTPS) TLSConfig() *TLSConfig {
	self.mutex.RLock()
	defer self.mutex.RUnlock()
	return self.config.Clone()
}

func (self *HTTPS) startInternal(port int) error {
	if port < 0 || port > 65535 {
		return ErrInvalidPort
	} else if self.listener != nil {
		return ErrAlreadyListening
	}

	config, err := self.config.ToConfig()
	if err != nil {
		return err
	}

	// Create a new TCP listener
	tcpListener, err := net.Listen("tcp", ":"+strconv.Itoa(port))
	if err != nil {
		return err
	}
	listener := tls.NewListener(tcpListener, config)
	self.listener = &listener

	// Run the server in the background
	self.loopDone = make(chan struct{})
	go self.serverLoop(self.listener, self.loopDone, "https")

	self.listenPort = port

	return nil
}
<|endoftext|>


<commit_before>package main

import "flag"
import "strings"
import "bufio"
import "os"
import "io"
import "strconv"

func konverti(de string, iksen bool) string {
	a := 0
	b := 1
	if iksen {
		a, b = 1, 0
	}
	tabelo := [18][2]string{
		{"cx", "ĉ"}, {"gx", "ĝ"}, {"hx", "ĥ"},
		{"jx", "ĵ"}, {"sx", "ŝ"}, {"ux", "ŭ"},

		{"Cx", "Ĉ"}, {"Gx", "Ĝ"}, {"Hx", "Ĥ"},
		{"Jx", "Ĵ"}, {"Sx", "Ŝ"}, {"Ux", "Ŭ"},

		{"CX", "Ĉ"}, {"GX", "Ĝ"}, {"HX", "Ĥ"},
		{"JX", "Ĵ"}, {"SX", "Ŝ"}, {"UX", "Ŭ"},
	}
	for i := 0; i<18; i++ {
		de = strings.Replace(de, tabelo[i][a], tabelo[i][b], -1)
	}
	return de
}

func konvertifluon(fluo *bufio.Reader, kien io.Writer, iksen bool) {
	for i, err:=fluo.ReadString('\n'); err == nil; i, err=fluo.ReadString('\n'){
		io.WriteString(kien, konverti(i, iksen))
	}
}

func main() {
	direkto := flag.Bool("x", false, "Traduki al iksoj. Convert to x-system.")
	mimem := flag.Bool("i", false, "Skribi al la dosiero mem. In-place conversion of input file.")
	flag.Parse()

	enigo := flag.Arg(0)
	portempujo := "/tmp/iksoj." + strconv.Itoa(os.Getpid())

	dosiero, err := os.Open(enigo)
	if err != nil {
		dosiero = os.Stdin
	}

	var kien *os.File
	if *mimem {
		kien, err = os.Create(portempujo)
		if err != nil {panic("Oops, tempfile already exists!")}
	} else {
		kien = os.Stdout
	}
	konvertifluon(bufio.NewReader(dosiero), kien, *direkto)
	dosiero.Close()
	kien.Close()

	if *mimem {
		detie, err := os.Open(portempujo)
		if err != nil {
			println(err)
			panic("Sorry, I don't manage to open temp file...")
		}
		err = os.Remove(enigo)
		if err != nil {panic("Cannot remove file to copy it back")}
		tien, err := os.Create(enigo)
		if err != nil {
			println(err)
			panic("Sorry, I don't manage to open destination file...")
		}
		kiom, err := io.Copy(tien, detie)
		if err != nil {
			println(kiom)
			panic("Couldn't copy all of the file...")
		}
	}
}
<commit_msg>go fmt<commit_after>package main

import "flag"
import "strings"
import "bufio"
import "os"
import "io"
import "strconv"

func konverti(de string, iksen bool) string {
	a := 0
	b := 1
	if iksen {
		a, b = 1, 0
	}
	tabelo := [18][2]string{
		{"cx", "ĉ"}, {"gx", "ĝ"}, {"hx", "ĥ"},
		{"jx", "ĵ"}, {"sx", "ŝ"}, {"ux", "ŭ"},

		{"Cx", "Ĉ"}, {"Gx", "Ĝ"}, {"Hx", "Ĥ"},
		{"Jx", "Ĵ"}, {"Sx", "Ŝ"}, {"Ux", "Ŭ"},

		{"CX", "Ĉ"}, {"GX", "Ĝ"}, {"HX", "Ĥ"},
		{"JX", "Ĵ"}, {"SX", "Ŝ"}, {"UX", "Ŭ"},
	}
	for i := 0; i < 18; i++ {
		de = strings.Replace(de, tabelo[i][a], tabelo[i][b], -1)
	}
	return de
}

func konvertifluon(fluo *bufio.Reader, kien io.Writer, iksen bool) {
	for i, err := fluo.ReadString('\n'); err == nil; i, err = fluo.ReadString('\n') {
		io.WriteString(kien, konverti(i, iksen))
	}
}

func main() {
	direkto := flag.Bool("x", false, "Traduki al iksoj. Convert to x-system.")
	mimem := flag.Bool("i", false, "Skribi al la dosiero mem. In-place conversion of input file.")
	flag.Parse()

	enigo := flag.Arg(0)
	portempujo := "/tmp/iksoj." + strconv.Itoa(os.Getpid())

	dosiero, err := os.Open(enigo)
	if err != nil {
		dosiero = os.Stdin
	}

	var kien *os.File
	if *mimem {
		kien, err = os.Create(portempujo)
		if err != nil {
			panic("Oops, tempfile already exists!")
		}
	} else {
		kien = os.Stdout
	}
	konvertifluon(bufio.NewReader(dosiero), kien, *direkto)
	dosiero.Close()
	kien.Close()

	if *mimem {
		detie, err := os.Open(portempujo)
		if err != nil {
			println(err)
			panic("Sorry, I don't manage to open temp file...")
		}
		err = os.Remove(enigo)
		if err != nil {
			panic("Cannot remove file to copy it back")
		}
		tien, err := os.Create(enigo)
		if err != nil {
			println(err)
			panic("Sorry, I don't manage to open destination file...")
		}
		kiom, err := io.Copy(tien, detie)
		if err != nil {
			println(kiom)
			panic("Couldn't copy all of the file...")
		}
	}
}
<|endoftext|>