1+ /**
2+ *
3+ * @returns {downloaderConstructor }
4+ */
5+ var downloader = function downloaderConstructor ( ) {
6+
7+ } ;
8+
9+ /**
10+ *
11+ * fetches a track from jamendo.com and writes it into the temporary folder
12+ * on disc
13+ *
14+ * @param {type } trackId
15+ * @param {type } temporaryTracksDirecotry
16+ * @param {type } format
17+ * @returns {undefined }
18+ */
19+ downloader . prototype . writeTrackToDisc = function ( trackId , temporaryTracksDirecotry , format ) {
20+
21+ if ( temporaryTracksDirecotry === undefined ) {
22+
23+ temporaryTracksDirecotry = '' ;
24+
25+ }
26+
27+ if ( format === undefined ) {
28+
29+ format = 'ogg' ;
30+
31+ }
32+
33+ var formatCode ;
34+
35+ switch ( format ) {
36+ case 'mp3' :
37+ formatCode = 'mp31' ;
38+ break ;
39+ case 'ogg' :
40+ formatCode = 'ogg1' ;
41+ break ;
42+ default :
43+ throw 'unsupported track format' ;
44+ }
45+
46+ var trackPath = temporaryTracksDirecotry + '/' + trackId + '.' + format ;
47+
48+ //
49+ var options = {
50+ hostname : 'storage-new.newjamendo.com' ,
51+ port : 80 ,
52+ path : '/download/track/' + trackId + '/' + formatCode ,
53+ method : 'GET'
54+ } ;
55+
56+ var writeStream = fs . createWriteStream ( trackPath ) ;
57+
58+ writeStream . on ( 'open' , function ( ) {
59+
60+ var httpRequest = http . request ( options , function ( httpResponse ) {
61+
62+ console . log ( 'writeTrackToDisc httpRequest STATUS: ' + httpResponse . statusCode ) ;
63+ console . log ( 'writeTrackToDisc httpRequest HEADERS: ' + JSON . stringify ( httpResponse . headers ) ) ;
64+
65+ httpResponse . on ( 'data' , function ( chunk ) {
66+
67+ writeStream . write ( chunk ) ;
68+
69+ } ) ;
70+
71+ httpResponse . on ( 'end' , function ( ) {
72+
73+ console . log ( 'file ' + trackFileName + ' got downloaded into ' + trackPath ) ;
74+
75+ writeStream . end ( ) ;
76+
77+ moveTrack ( ) ;
78+
79+ } ) ;
80+
81+ } ) ;
82+
83+ httpRequest . on ( 'error' , function ( error ) {
84+
85+ console . log ( 'writeTrackToDisc, http request error: ' + error . message ) ;
86+
87+ writeStream . end ( ) ;
88+
89+ } ) ;
90+
91+ httpRequest . end ( ) ;
92+
93+ } ) ;
94+
95+ writeStream . on ( 'error' , function ( error ) {
96+
97+ console . log ( 'writeTrackToDisc writeStream, error: ' + error ) ;
98+
99+ writeStream . end ( ) ;
100+
101+ } ) ;
102+
103+ } ;
104+
105+ module . exports . downloader = downloader ;
0 commit comments