Ejemplo n.º 1
0
func NewWatcher(session *sharesession.Session, watchedDir string) (w *Watcher, err error) {
	w = &Watcher{
		session:        session,
		watchedDir:     watchedDir,
		PingNewTorrent: make(chan string),
	}

	go w.watch()

	// Initialization, only if there is something in the dir
	if _, err := os.Stat(watchedDir); err != nil {
		return nil, err
	}

	st, err := os.Stat(watchedDir)
	if err != nil {
		return nil, err
	}
	if !st.IsDir() {
		return nil, errInvalidDir
	}

	go func() {
		w.PingNewTorrent <- session.GetCurrentInfohash()
	}()

	return
}
Ejemplo n.º 2
0
func NewControlSession(shareid id.Id, listenPort int, session *sharesession.Session, trackers []string) (*ControlSession, error) {
	sid := "-tt" + strconv.Itoa(os.Getpid()) + "_" + strconv.FormatInt(rand.Int63(), 10)

	// TODO: UPnP UDP port mapping.
	cfg := dht.NewConfig()
	cfg.Port = listenPort
	cfg.NumTargetPeers = TARGET_NUM_PEERS

	dhtNode, err := dht.New(cfg)
	if err != nil {
		log.Fatal("DHT node creation error", err)
	}

	current := session.GetCurrentIHMessage()
	var currentIhMessage IHMessage
	err = bencode.NewDecoder(strings.NewReader(current)).Decode(&currentIhMessage)
	if err != nil {
		log.Printf("Couldn't decode current message, starting from scratch: %s\n", err)
	}

	rev := "0-"
	if currentIhMessage.Info.Rev != "" {
		parts := strings.Split(currentIhMessage.Info.Rev, "-")
		if len(parts) == 2 {
			if _, err := strconv.Atoi(parts[0]); err == nil {
				rev = currentIhMessage.Info.Rev
			}
		}
	}

	cs := &ControlSession{
		Port:            listenPort,
		PeerID:          sid[:20],
		ID:              shareid,
		Torrents:        make(chan Announce),
		NewPeers:        make(chan string),
		dht:             dhtNode,
		peerMessageChan: make(chan peerMessage),
		quit:            make(chan struct{}),
		ourExtensions: map[int]string{
			1: "ut_pex",
			2: "bs_metadata",
		},
		peers: newPeers(),

		currentIH: currentIhMessage.Info.InfoHash,
		rev:       rev,

		trackers: trackers,

		session: session,
	}
	go cs.dht.Run()
	cs.dht.PeersRequest(string(cs.ID.Infohash), true)

	go cs.Run()

	return cs, nil
}