~ubuntu-branches/ubuntu/oneiric/banshee/oneiric-proposed

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
//
// AudioscrobblerService.cs
//
// Authors:
//   Alexander Hixon <hixon.alexander@mediati.org>
//   Chris Toshok <toshok@ximian.com>
//   Ruben Vermeersch <ruben@savanne.be>
//   Aaron Bockover <aaron@abock.org>
//
// Copyright (C) 2005-2008 Novell, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//

using System;
using System.IO;
using System.Net;
using System.Text;
using System.Security.Cryptography;
using Gtk;
using Mono.Unix;

using Hyena;

using Lastfm;

using Banshee.MediaEngine;
using Banshee.Base;
using Banshee.Configuration;
using Banshee.ServiceStack;
using Banshee.Gui;
using Banshee.Networking;

using Banshee.Collection;

using Browser = Lastfm.Browser;

namespace Banshee.Lastfm.Audioscrobbler
{
    public class AudioscrobblerService : IExtensionService, IDisposable
    {
        private AudioscrobblerConnection connection;
        private ActionGroup actions;
        private uint ui_manager_id;
        private InterfaceActionService action_service;
        private Queue queue;
        private Account account;

        private bool queued; /* if current_track has been queued */
        private bool now_playing_sent = false; /* self-explanatory :) */
        private int iterate_countdown = 4 * 4; /* number of times to wait for iterate event before sending now playing */

        private DateTime song_start_time;
        private TrackInfo last_track;

        public AudioscrobblerService ()
        {
        }

        void IExtensionService.Initialize ()
        {
            account = LastfmCore.Account;

            if (account.UserName == null) {
                account.UserName = LastUserSchema.Get ();
                account.SessionKey = LastSessionKeySchema.Get ();
                account.ScrobbleUrl = LastScrobbleUrlSchema.Get ();
            }

            if (LastfmCore.UserAgent == null) {
                LastfmCore.UserAgent = Banshee.Web.Browser.UserAgent;
            }

            Browser.Open = Banshee.Web.Browser.Open;

            queue = new Queue ();
            LastfmCore.AudioscrobblerQueue = queue;
            connection = LastfmCore.Audioscrobbler;

            // Initialize with a reasonable value in case we miss the first StartOfStream event
            song_start_time = DateTime.Now;

            Network network = ServiceManager.Get<Network> ();
            connection.UpdateNetworkState (network.Connected);
            network.StateChanged += HandleNetworkStateChanged;

            // Update the Visit action menu item if we update our account info
            LastfmCore.Account.Updated += delegate (object o, EventArgs args) {
                actions["AudioscrobblerVisitAction"].Sensitive = String.IsNullOrEmpty (LastfmCore.Account.UserName);
            };

            ServiceManager.PlayerEngine.ConnectEvent (OnPlayerEvent,
                PlayerEvent.StartOfStream |
                PlayerEvent.EndOfStream |
                PlayerEvent.Seek |
                PlayerEvent.Iterate);

            action_service = ServiceManager.Get<InterfaceActionService> ();
            InterfaceInitialize ();
        }

        public void InterfaceInitialize ()
        {
            actions = new ActionGroup ("Audioscrobbler");

            actions.Add (new ActionEntry [] {
                new ActionEntry ("AudioscrobblerAction", null,
                    Catalog.GetString ("_Last.fm"), null,
                    Catalog.GetString ("Configure the Audioscrobbler plugin"), null),

                new ActionEntry ("AudioscrobblerVisitAction", null,
                    Catalog.GetString ("Visit _User Profile Page"), null,
                    Catalog.GetString ("Visit Your Last.fm Profile Page"), OnVisitOwnProfile)
            });

            actions.Add (new ToggleActionEntry [] {
                new ToggleActionEntry ("AudioscrobblerEnableAction", null,
                    Catalog.GetString ("_Enable Song Reporting"), null,
                    Catalog.GetString ("Enable song reporting"), OnToggleEnabled, Enabled)
            });

            action_service.UIManager.InsertActionGroup (actions, 0);
            ui_manager_id = action_service.UIManager.AddUiFromResource ("AudioscrobblerMenu.xml");

            actions["AudioscrobblerVisitAction"].Sensitive = account.UserName != null && account.UserName != String.Empty;
        }


        public void Dispose ()
        {
            // Try and queue the currently playing track just in case it's queueable
            // but the user hasn't hit next yet and quit/disposed the service.
            if (ServiceManager.PlayerEngine.CurrentTrack != null) {
                Queue (ServiceManager.PlayerEngine.CurrentTrack);
            }

            ServiceManager.PlayerEngine.DisconnectEvent (OnPlayerEvent);

            ServiceManager.Get<Network> ().StateChanged -= HandleNetworkStateChanged;

            // When we stop the connection, queue ends up getting saved too, so the
            // track we queued earlier should stay until next session.
            connection.Stop ();

            action_service.UIManager.RemoveUi (ui_manager_id);
            action_service.UIManager.RemoveActionGroup (actions);
            actions = null;
        }

        private void HandleNetworkStateChanged (object o, NetworkStateChangedArgs args)
        {
            connection.UpdateNetworkState (args.Connected);
        }

        // We need to time how long the song has played
        internal class SongTimer
        {
            private long playtime = 0;  // number of msecs played
            public long PlayTime {
                get { return playtime; }
            }

            private long previouspos = 0;

            // number of events to ignore to get sync (since events may be fired in wrong order)
            private int ignorenext = 0;

            public void IncreasePosition ()
            {
                long increase = 0;

                if (ignorenext == 0) {
                    increase = (ServiceManager.PlayerEngine.Position - previouspos);
                    if (increase > 0) {
                        playtime += increase;
                    }
                } else {
                    ignorenext--;
                }

                previouspos = ServiceManager.PlayerEngine.Position;
            }

            public void SkipPosition ()
            {
                // Set newly seeked position
                previouspos = ServiceManager.PlayerEngine.Position;
                ignorenext = 2; // allow 2 iterates to sync
            }

            public void Reset ()
            {
                playtime = 0;
                previouspos = 0;
                ignorenext = 0;
            }
        }

        SongTimer st = new SongTimer ();

        private void Queue (TrackInfo track) {
            if (track == null || st.PlayTime == 0 ||
                !(actions["AudioscrobblerEnableAction"] as ToggleAction).Active) {

                return;
            }

            Log.DebugFormat ("Track {3} had playtime of {0} msec ({4}sec), duration {1} msec, queued: {2}",
                st.PlayTime, track.Duration.TotalMilliseconds, queued, track, st.PlayTime / 1000);

            if (!queued && track.Duration.TotalSeconds > 30 &&
                (track.MediaAttributes & TrackMediaAttributes.Music) != 0 &&
                !String.IsNullOrEmpty (track.ArtistName) && !String.IsNullOrEmpty (track.TrackTitle) &&
                (st.PlayTime > track.Duration.TotalMilliseconds / 2 || st.PlayTime > 240 * 1000)) {
                    if (!connection.Started) {
                        connection.Start ();
                    }

                    queue.Add (track, song_start_time);
                    queued = true;
            }
        }

        private void OnPlayerEvent (PlayerEventArgs args)
        {
            switch (args.Event) {
                case PlayerEvent.StartOfStream:
                    // Queue the previous track in case of a skip
                    Queue (last_track);

                    st.Reset ();
                    song_start_time = DateTime.Now;
                    last_track = ServiceManager.PlayerEngine.CurrentTrack;
                    queued = false;
                    now_playing_sent = false;
                    iterate_countdown = 4 * 4;  /* we get roughly 4 events/sec */

                    break;

                case PlayerEvent.Seek:
                    st.SkipPosition ();
                    break;

                case PlayerEvent.Iterate:
                    // Queue as now playing
                    if (!now_playing_sent && iterate_countdown == 0) {
                        if (last_track != null && last_track.Duration.TotalSeconds > 30 &&
                            (actions["AudioscrobblerEnableAction"] as ToggleAction).Active &&
                            (last_track.MediaAttributes & TrackMediaAttributes.Music) != 0) {

                            connection.NowPlaying (last_track.ArtistName, last_track.TrackTitle,
                                last_track.AlbumTitle, last_track.Duration.TotalSeconds, last_track.TrackNumber);
                        }

                        now_playing_sent = true;
                    } else if (iterate_countdown > 0) {
                        iterate_countdown --;
                    }

                    st.IncreasePosition ();
                    break;

                case PlayerEvent.EndOfStream:
                    Queue (last_track);
                    last_track = null;
                    iterate_countdown = 4 * 4;
                    break;
            }
        }

        private void OnVisitOwnProfile (object o, EventArgs args)
        {
            account.VisitUserProfile (account.UserName);
        }

        private void OnToggleEnabled (object o, EventArgs args)
        {
            Enabled = (o as ToggleAction).Active;
        }

        internal bool Enabled {
            get { return EngineEnabledSchema.Get (); }
            set {
                EngineEnabledSchema.Set (value);
                (actions["AudioscrobblerEnableAction"] as ToggleAction).Active = value;
            }
        }

        public static readonly SchemaEntry<string> LastUserSchema = new SchemaEntry<string> (
            "plugins.lastfm", "username", "", "Last.fm user", "Last.fm username"
        );

        public static readonly SchemaEntry<string> LastSessionKeySchema = new SchemaEntry<string> (
            "plugins.lastfm", "session_key", "", "Last.fm session key", "Last.fm sessions key used in authenticated calls"
        );

        public static readonly SchemaEntry<string> LastScrobbleUrlSchema = new SchemaEntry<string> (
            "plugins.audioscrobbler", "api_url",
            null,
            "AudioScrobbler API URL",
            "URL for the AudioScrobbler API (supports turtle.libre.fm, for instance)"
        );

        public static readonly SchemaEntry<bool> EngineEnabledSchema = new SchemaEntry<bool> (
            "plugins.audioscrobbler", "engine_enabled",
            false,
            "Engine enabled",
            "Audioscrobbler reporting engine enabled"
        );

        string IService.ServiceName {
            get { return "AudioscrobblerService"; }
        }
    }
}