@@ -8,7 +8,7 @@ const attachUdpService = require('./services/attachUdp')
88const attachWSService = require ( './services/attachWS' )
99const setupStatsRoute = require ( './services/statsRoute' )
1010const common = require ( './lib/common' )
11- const Swarm = require ( './lib/server/ swarm' )
11+ const Swarm = require ( './swarm' )
1212
1313/**
1414 * BitTorrent tracker server.
@@ -163,6 +163,22 @@ class Server extends EventEmitter {
163163 } )
164164 }
165165
166+ // Get existing swarm, or create one if one does not exist
167+ getOrCreateSwarm ( params ) {
168+ const gotOrCreatedSwarm = resolve => {
169+ this . getSwarm ( params . info_hash , ( err , swarm ) => {
170+ if ( err ) return resolve ( err )
171+ if ( swarm ) return resolve ( swarm )
172+ this . createSwarm ( params . info_hash , ( err , swarm ) => {
173+ if ( err ) return resolve ( err )
174+ resolve ( swarm )
175+ } )
176+ } )
177+ }
178+
179+ return new Promise ( gotOrCreatedSwarm )
180+ }
181+
166182 _onRequest ( params , cb ) {
167183 if ( params && params . action === common . ACTIONS . CONNECT ) {
168184 cb ( null , { action : common . ACTIONS . CONNECT } )
@@ -179,37 +195,24 @@ class Server extends EventEmitter {
179195 const self = this
180196
181197 if ( this . _filter ) {
182- this . _filter ( params . info_hash , params , err => {
198+ const onFiltered = err => {
183199 // Presence of `err` means that this announce request is disallowed
184200 if ( err ) return cb ( err )
185201
186- getOrCreateSwarm ( ( err , swarm ) => {
187- if ( err ) return cb ( err )
188- announce ( swarm )
189- } )
190- } )
191- } else {
192- getOrCreateSwarm ( ( err , swarm ) => {
193- if ( err ) return cb ( err )
194- announce ( swarm )
195- } )
196- }
202+ this . getOrCreateSwarm ( params )
203+ . then ( announce )
204+ }
197205
198- // Get existing swarm, or create one if one does not exist
199- function getOrCreateSwarm ( cb ) {
200- self . getSwarm ( params . info_hash , ( err , swarm ) => {
201- if ( err ) return cb ( err )
202- if ( swarm ) return cb ( null , swarm )
203- self . createSwarm ( params . info_hash , ( err , swarm ) => {
204- if ( err ) return cb ( err )
205- cb ( null , swarm )
206- } )
207- } )
206+ this . _filter ( params . info_hash , params , onFiltered )
207+ } else {
208+ this . getOrCreateSwarm ( params )
209+ . then ( announce )
208210 }
209211
210212 function announce ( swarm ) {
211213 if ( ! params . event || params . event === 'empty' ) params . event = 'update'
212- swarm . announce ( params , ( err , response ) => {
214+
215+ const _onAnnounce = ( err , response ) => {
213216 if ( err ) return cb ( err )
214217
215218 if ( ! response . action ) response . action = common . ACTIONS . ANNOUNCE
@@ -242,7 +245,9 @@ class Server extends EventEmitter {
242245 } // else, return full peer objects (used for websocket responses)
243246
244247 cb ( null , response )
245- } )
248+ }
249+
250+ swarm . announce ( params , _onAnnounce )
246251 }
247252 }
248253
0 commit comments