~kelemeng/banshee/bug743928

« back to all changes in this revision

Viewing changes to src/Dap/Banshee.Dap.Ipod/Banshee.Dap.Ipod/IpodSource.cs

  • Committer: Bazaar Package Importer
  • Author(s): Chow Loong Jin
  • Date: 2011-05-14 22:25:36 UTC
  • mfrom: (6.3.15 experimental)
  • Revision ID: james.westby@ubuntu.com-20110514222536-u1x7ikxdqkmfvyuz
Tags: 2.1.0-1ubuntu1
* [2396c18] Merge from Debian Unstable, remaining changes:
  + Enable SoundMenu and Disable NotificationArea by default
  + Disable boo and karma extensions
  + Enable and recommnd u1ms and soundmenu extensions
  + Move desktop file for Meego UI to /usr/share/une/applications
  + Change the url for the Amazon store redirector
  + Create the U1MS widget earlier and bump libu1 requirement
* [9d7c600] Drop upstreamed u1ms-initialize-earlier patch

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
//
2
 
// IpodSource.cs
3
 
//
4
 
// Author:
5
 
//   Aaron Bockover <abockover@novell.com>
6
 
//
7
 
// Copyright (C) 2005-2008 Novell, Inc.
8
 
//
9
 
// Permission is hereby granted, free of charge, to any person obtaining
10
 
// a copy of this software and associated documentation files (the
11
 
// "Software"), to deal in the Software without restriction, including
12
 
// without limitation the rights to use, copy, modify, merge, publish,
13
 
// distribute, sublicense, and/or sell copies of the Software, and to
14
 
// permit persons to whom the Software is furnished to do so, subject to
15
 
// the following conditions:
16
 
//
17
 
// The above copyright notice and this permission notice shall be
18
 
// included in all copies or substantial portions of the Software.
19
 
//
20
 
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
21
 
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
22
 
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
23
 
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
24
 
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
25
 
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
26
 
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
27
 
//
28
 
 
29
 
using System;
30
 
using System.IO;
31
 
using System.Threading;
32
 
using System.Collections.Generic;
33
 
using Mono.Unix;
34
 
 
35
 
using IPod;
36
 
 
37
 
using Hyena;
38
 
using Hyena.Query;
39
 
using Banshee.Base;
40
 
using Banshee.ServiceStack;
41
 
using Banshee.Sources;
42
 
using Banshee.Dap;
43
 
using Banshee.Hardware;
44
 
using Banshee.Collection.Database;
45
 
using Banshee.Library;
46
 
using Banshee.Playlist;
47
 
 
48
 
using Banshee.Dap.Gui;
49
 
 
50
 
namespace Banshee.Dap.Ipod
51
 
{
52
 
    public class IpodSource : DapSource
53
 
    {
54
 
        private PodSleuthDevice ipod_device;
55
 
        internal PodSleuthDevice IpodDevice {
56
 
            get { return ipod_device; }
57
 
        }
58
 
 
59
 
        private Dictionary<int, IpodTrackInfo> tracks_map = new Dictionary<int, IpodTrackInfo> (); // FIXME: EPIC FAIL
60
 
        private bool database_loaded;
61
 
 
62
 
        private string name_path;
63
 
        internal string NamePath {
64
 
            get { return name_path; }
65
 
        }
66
 
 
67
 
        private string music_path;
68
 
 
69
 
        private bool database_supported;
70
 
        internal bool DatabaseSupported {
71
 
            get { return database_supported; }
72
 
        }
73
 
 
74
 
        private UnsupportedDatabaseView unsupported_view;
75
 
 
76
 
#region Device Setup/Dispose
77
 
 
78
 
        public override void DeviceInitialize (IDevice device)
79
 
        {
80
 
            base.DeviceInitialize (device);
81
 
 
82
 
            ipod_device = device as PodSleuthDevice;
83
 
            if (ipod_device == null) {
84
 
                throw new InvalidDeviceException ();
85
 
            }
86
 
 
87
 
            name_path = Path.Combine (Path.GetDirectoryName (ipod_device.TrackDatabasePath), "BansheeIPodName");
88
 
            music_path = Path.Combine (ipod_device.ControlPath, "Music");
89
 
            Name = GetDeviceName ();
90
 
 
91
 
            SupportsPlaylists = ipod_device.ModelInfo.DeviceClass != "shuffle";
92
 
 
93
 
            // TODO disable this later, but right now it won't disable it in Sync, so might as well
94
 
            // leave it enabled
95
 
            SupportsPodcasts = ipod_device.ModelInfo.HasCapability ("podcast");
96
 
            SupportsVideo = ipod_device.ModelInfo.DeviceClass == "video" ||
97
 
                            ipod_device.ModelInfo.DeviceClass == "classic" ||
98
 
                            (ipod_device.ModelInfo.DeviceClass == "nano" && ipod_device.ModelInfo.Generation >= 3);
99
 
 
100
 
            Initialize ();
101
 
 
102
 
            AddDapProperty (Catalog.GetString ("Device"), ipod_device.ModelInfo.DeviceClass);
103
 
            AddDapProperty (Catalog.GetString ("Color"), ipod_device.ModelInfo.ShellColor);
104
 
            AddDapProperty (Catalog.GetString ("Generation"), ipod_device.ModelInfo.Generation.ToString ());
105
 
            AddDapProperty (Catalog.GetString ("Capacity"), ipod_device.ModelInfo.AdvertisedCapacity);
106
 
            AddDapProperty (Catalog.GetString ("Serial number"), ipod_device.Serial);
107
 
            AddDapProperty (Catalog.GetString ("Produced on"), ipod_device.ProductionInfo.DisplayDate);
108
 
            AddDapProperty (Catalog.GetString ("Firmware"), ipod_device.FirmwareVersion);
109
 
 
110
 
            string [] capabilities = new string [ipod_device.ModelInfo.Capabilities.Count];
111
 
            ipod_device.ModelInfo.Capabilities.CopyTo (capabilities, 0);
112
 
            AddDapProperty (Catalog.GetString ("Capabilities"), String.Join (", ", capabilities));
113
 
            AddYesNoDapProperty (Catalog.GetString ("Supports cover art"), ipod_device.ModelInfo.AlbumArtSupported);
114
 
            AddYesNoDapProperty (Catalog.GetString ("Supports photos"), ipod_device.ModelInfo.PhotosSupported);
115
 
        }
116
 
 
117
 
        public override void Dispose ()
118
 
        {
119
 
            ThreadAssist.ProxyToMain (DestroyUnsupportedView);
120
 
            CancelSyncThread ();
121
 
            base.Dispose ();
122
 
        }
123
 
 
124
 
        // WARNING: This will be called from a thread!
125
 
        protected override void Eject ()
126
 
        {
127
 
            base.Eject ();
128
 
            CancelSyncThread ();
129
 
            if (ipod_device.CanUnmount) {
130
 
                ipod_device.Unmount ();
131
 
            }
132
 
 
133
 
            if (ipod_device.CanEject) {
134
 
                ipod_device.Eject ();
135
 
            }
136
 
 
137
 
            Dispose ();
138
 
        }
139
 
 
140
 
        protected override bool CanHandleDeviceCommand (DeviceCommand command)
141
 
        {
142
 
            try {
143
 
                SafeUri uri = new SafeUri (command.DeviceId);
144
 
                return IpodDevice.MountPoint.StartsWith (uri.LocalPath);
145
 
            } catch {
146
 
                return false;
147
 
            }
148
 
        }
149
 
 
150
 
        protected override IDeviceMediaCapabilities MediaCapabilities {
151
 
            get { return ipod_device.Parent.MediaCapabilities ?? base.MediaCapabilities; }
152
 
        }
153
 
 
154
 
#endregion
155
 
 
156
 
#region Database Loading
157
 
 
158
 
        // WARNING: This will be called from a thread!
159
 
        protected override void LoadFromDevice ()
160
 
        {
161
 
            LoadIpod ();
162
 
            LoadFromDevice (false);
163
 
            OnTracksAdded ();
164
 
        }
165
 
 
166
 
        private void LoadIpod ()
167
 
        {
168
 
            database_supported = false;
169
 
 
170
 
            try {
171
 
                if (File.Exists (ipod_device.TrackDatabasePath)) {
172
 
                    ipod_device.LoadTrackDatabase (false);
173
 
                } else {
174
 
                    int count = CountMusicFiles ();
175
 
                    Log.DebugFormat ("Found {0} files in /iPod_Control/Music", count);
176
 
                    if (CountMusicFiles () > 5) {
177
 
                        throw new DatabaseReadException ("No database, but found a lot of music files");
178
 
                    }
179
 
                }
180
 
                database_supported = true;
181
 
                ThreadAssist.ProxyToMain (DestroyUnsupportedView);
182
 
            } catch (DatabaseReadException e) {
183
 
                Log.Exception ("Could not read iPod database", e);
184
 
                ipod_device.LoadTrackDatabase (true);
185
 
 
186
 
                ThreadAssist.ProxyToMain (delegate {
187
 
                    DestroyUnsupportedView ();
188
 
                    unsupported_view = new UnsupportedDatabaseView (this);
189
 
                    unsupported_view.Refresh += OnRebuildDatabaseRefresh;
190
 
                    Properties.Set<Banshee.Sources.Gui.ISourceContents> ("Nereid.SourceContents", unsupported_view);
191
 
                });
192
 
            } catch (Exception e) {
193
 
                Log.Exception (e);
194
 
            }
195
 
 
196
 
            database_loaded = true;
197
 
 
198
 
            Name = GetDeviceName ();
199
 
        }
200
 
 
201
 
        private int CountMusicFiles ()
202
 
        {
203
 
            try {
204
 
                int file_count = 0;
205
 
 
206
 
                DirectoryInfo m_dir = new DirectoryInfo (music_path);
207
 
                foreach (DirectoryInfo f_dir in m_dir.GetDirectories ()) {
208
 
                    file_count += f_dir.GetFiles().Length;
209
 
                }
210
 
 
211
 
                return file_count;
212
 
            } catch {
213
 
                return 0;
214
 
            }
215
 
        }
216
 
 
217
 
        private void LoadFromDevice (bool refresh)
218
 
        {
219
 
            // bool previous_database_supported = database_supported;
220
 
 
221
 
            if (refresh) {
222
 
                ipod_device.TrackDatabase.Reload ();
223
 
            }
224
 
 
225
 
            tracks_map.Clear ();
226
 
 
227
 
            if (database_supported || (ipod_device.HasTrackDatabase &&
228
 
                ipod_device.ModelInfo.DeviceClass == "shuffle")) {
229
 
                foreach (Track ipod_track in ipod_device.TrackDatabase.Tracks) {
230
 
                    try {
231
 
                        IpodTrackInfo track = new IpodTrackInfo (ipod_track);
232
 
                        track.PrimarySource = this;
233
 
                        track.Save (false);
234
 
                        tracks_map.Add (track.TrackId, track);
235
 
                    } catch (Exception e) {
236
 
                        Log.Exception (e);
237
 
                    }
238
 
                }
239
 
 
240
 
                Hyena.Data.Sqlite.HyenaSqliteCommand insert_cmd = new Hyena.Data.Sqlite.HyenaSqliteCommand (
241
 
                    @"INSERT INTO CorePlaylistEntries (PlaylistID, TrackID)
242
 
                        SELECT ?, TrackID FROM CoreTracks WHERE PrimarySourceID = ? AND ExternalID = ?");
243
 
                foreach (IPod.Playlist playlist in ipod_device.TrackDatabase.Playlists) {
244
 
                    if (playlist.IsOnTheGo) { // || playlist.IsPodcast) {
245
 
                        continue;
246
 
                    }
247
 
                    PlaylistSource pl_src = new PlaylistSource (playlist.Name, this);
248
 
                    pl_src.Save ();
249
 
                    // We use the IPod.Track.Id here b/c we just shoved it into ExternalID above when we loaded
250
 
                    // the tracks, however when we sync, the Track.Id values may/will change.
251
 
                    foreach (IPod.Track track in playlist.Tracks) {
252
 
                        ServiceManager.DbConnection.Execute (insert_cmd, pl_src.DbId, this.DbId, track.Id);
253
 
                    }
254
 
                    pl_src.UpdateCounts ();
255
 
                    AddChildSource (pl_src);
256
 
                }
257
 
            }
258
 
 
259
 
            /*else {
260
 
                BuildDatabaseUnsupportedWidget ();
261
 
            }*/
262
 
 
263
 
            /*if(previous_database_supported != database_supported) {
264
 
                OnPropertiesChanged();
265
 
            }*/
266
 
        }
267
 
 
268
 
        private void OnRebuildDatabaseRefresh (object o, EventArgs args)
269
 
        {
270
 
            ServiceManager.SourceManager.SetActiveSource (MusicGroupSource);
271
 
            base.LoadDeviceContents ();
272
 
        }
273
 
 
274
 
        private void DestroyUnsupportedView ()
275
 
        {
276
 
            if (unsupported_view != null) {
277
 
                unsupported_view.Refresh -= OnRebuildDatabaseRefresh;
278
 
                unsupported_view.Destroy ();
279
 
                unsupported_view = null;
280
 
            }
281
 
        }
282
 
 
283
 
#endregion
284
 
 
285
 
#region Source Cosmetics
286
 
 
287
 
        internal string [] _GetIconNames ()
288
 
        {
289
 
            return GetIconNames ();
290
 
        }
291
 
 
292
 
        protected override string [] GetIconNames ()
293
 
        {
294
 
            string [] names = new string[4];
295
 
            string prefix = "multimedia-player-";
296
 
            string shell_color = ipod_device.ModelInfo.ShellColor;
297
 
 
298
 
            names[0] = ipod_device.ModelInfo.IconName;
299
 
            names[2] = "ipod-standard-color";
300
 
            names[3] = "multimedia-player";
301
 
 
302
 
            switch (ipod_device.ModelInfo.DeviceClass) {
303
 
                case "grayscale":
304
 
                    names[1] = "ipod-standard-monochrome";
305
 
                    break;
306
 
                case "color":
307
 
                    names[1] = "ipod-standard-color";
308
 
                    break;
309
 
                case "mini":
310
 
                    names[1] = String.Format ("ipod-mini-{0}", shell_color);
311
 
                    names[2] = "ipod-mini-silver";
312
 
                    break;
313
 
                case "shuffle":
314
 
                    names[1] = String.Format ("ipod-shuffle-{0}", shell_color);
315
 
                    names[2] = "ipod-shuffle";
316
 
                    break;
317
 
                case "nano":
318
 
                case "nano3":
319
 
                    names[1] = String.Format ("ipod-nano-{0}", shell_color);
320
 
                    names[2] = "ipod-nano-white";
321
 
                    break;
322
 
                case "video":
323
 
                    names[1] = String.Format ("ipod-video-{0}", shell_color);
324
 
                    names[2] = "ipod-video-white";
325
 
                    break;
326
 
                case "classic":
327
 
                case "touch":
328
 
                case "phone":
329
 
                default:
330
 
                    break;
331
 
            }
332
 
 
333
 
            names[1] = names[1] ?? names[2];
334
 
            names[1] = prefix + names[1];
335
 
            names[2] = prefix + names[2];
336
 
 
337
 
            return names;
338
 
        }
339
 
 
340
 
        public override void Rename (string name)
341
 
        {
342
 
            if (!CanRename) {
343
 
                return;
344
 
            }
345
 
 
346
 
            try {
347
 
                if (name_path != null) {
348
 
                    Directory.CreateDirectory (Path.GetDirectoryName (name_path));
349
 
 
350
 
                    using (StreamWriter writer = new StreamWriter (File.Open (name_path, FileMode.Create),
351
 
                        System.Text.Encoding.Unicode)) {
352
 
                        writer.Write (name);
353
 
                    }
354
 
                }
355
 
            } catch (Exception e) {
356
 
                Log.Exception (e);
357
 
            }
358
 
 
359
 
            ipod_device.Name = name;
360
 
            base.Rename (name);
361
 
        }
362
 
 
363
 
        private string GetDeviceName ()
364
 
        {
365
 
            string name = null;
366
 
            if (File.Exists (name_path)) {
367
 
                using (StreamReader reader = new StreamReader (name_path, System.Text.Encoding.Unicode)) {
368
 
                    name = reader.ReadLine ();
369
 
                }
370
 
            }
371
 
 
372
 
            if (String.IsNullOrEmpty (name) && database_loaded && database_supported) {
373
 
                name = ipod_device.Name;
374
 
            }
375
 
 
376
 
            if (!String.IsNullOrEmpty (name)) {
377
 
                return name;
378
 
            } else if (ipod_device.PropertyExists ("volume.label")) {
379
 
                name = ipod_device.GetPropertyString ("volume.label");
380
 
            } else if (ipod_device.PropertyExists ("info.product")) {
381
 
                name = ipod_device.GetPropertyString ("info.product");
382
 
            } else {
383
 
                name = ((IDevice)ipod_device).Name ?? "iPod";
384
 
            }
385
 
 
386
 
            return name;
387
 
        }
388
 
 
389
 
        public override bool CanRename {
390
 
            get { return !(IsAdding || IsDeleting || IsReadOnly); }
391
 
        }
392
 
 
393
 
        public override long BytesUsed {
394
 
            get { return (long)ipod_device.VolumeInfo.SpaceUsed; }
395
 
        }
396
 
 
397
 
        public override long BytesCapacity {
398
 
            get { return (long)ipod_device.VolumeInfo.Size; }
399
 
        }
400
 
 
401
 
#endregion
402
 
 
403
 
#region Syncing
404
 
 
405
 
        public override void UpdateMetadata (DatabaseTrackInfo track)
406
 
        {
407
 
            lock (sync_mutex) {
408
 
                IpodTrackInfo ipod_track;
409
 
                if (!tracks_map.TryGetValue (track.TrackId, out ipod_track)) {
410
 
                    return;
411
 
                }
412
 
 
413
 
                ipod_track.UpdateInfo (track);
414
 
                tracks_to_update.Enqueue (ipod_track);
415
 
            }
416
 
        }
417
 
 
418
 
        protected override void OnTracksChanged (params QueryField[] fields)
419
 
        {
420
 
            if (tracks_to_update.Count > 0 && !Sync.Syncing) {
421
 
                QueueSync ();
422
 
            }
423
 
            base.OnTracksChanged (fields);
424
 
        }
425
 
 
426
 
        protected override void OnTracksAdded ()
427
 
        {
428
 
            if (!IsAdding && tracks_to_add.Count > 0 && !Sync.Syncing) {
429
 
                QueueSync ();
430
 
            }
431
 
            base.OnTracksAdded ();
432
 
        }
433
 
 
434
 
        protected override void OnTracksDeleted ()
435
 
        {
436
 
            if (!IsDeleting && tracks_to_remove.Count > 0 && !Sync.Syncing) {
437
 
                QueueSync ();
438
 
            }
439
 
            base.OnTracksDeleted ();
440
 
        }
441
 
 
442
 
        private Queue<IpodTrackInfo> tracks_to_add = new Queue<IpodTrackInfo> ();
443
 
        private Queue<IpodTrackInfo> tracks_to_update = new Queue<IpodTrackInfo> ();
444
 
        private Queue<IpodTrackInfo> tracks_to_remove = new Queue<IpodTrackInfo> ();
445
 
 
446
 
        private uint sync_timeout_id = 0;
447
 
        private object sync_timeout_mutex = new object ();
448
 
        private object sync_mutex = new object ();
449
 
        private Thread sync_thread;
450
 
        private AutoResetEvent sync_thread_wait;
451
 
        private bool sync_thread_dispose = false;
452
 
 
453
 
        public override bool IsReadOnly {
454
 
            get { return ipod_device.IsReadOnly || !database_supported; }
455
 
        }
456
 
 
457
 
        public override void Import ()
458
 
        {
459
 
            Banshee.ServiceStack.ServiceManager.Get<LibraryImportManager> ().Enqueue (music_path);
460
 
        }
461
 
 
462
 
        /*public override void CopyTrackTo (DatabaseTrackInfo track, SafeUri uri, BatchUserJob job)
463
 
        {
464
 
            throw new Exception ("Copy to Library is not implemented for iPods yet");
465
 
        }*/
466
 
 
467
 
        protected override bool DeleteTrack (DatabaseTrackInfo track)
468
 
        {
469
 
            lock (sync_mutex) {
470
 
                if (!tracks_map.ContainsKey (track.TrackId)) {
471
 
                    return true;
472
 
                }
473
 
 
474
 
                IpodTrackInfo ipod_track = tracks_map[track.TrackId];
475
 
                if (ipod_track != null) {
476
 
                    tracks_to_remove.Enqueue (ipod_track);
477
 
                }
478
 
 
479
 
                return true;
480
 
            }
481
 
        }
482
 
 
483
 
        protected override void AddTrackToDevice (DatabaseTrackInfo track, SafeUri fromUri)
484
 
        {
485
 
            lock (sync_mutex) {
486
 
                if (track.PrimarySourceId == DbId) {
487
 
                    return;
488
 
                }
489
 
 
490
 
                if (track.Duration.Equals (TimeSpan.Zero)) {
491
 
                    throw new Exception (Catalog.GetString ("Track duration is zero"));
492
 
                }
493
 
 
494
 
                var ipod_track = new IpodTrackInfo (track) {
495
 
                    Uri = fromUri,
496
 
                    PrimarySource = this,
497
 
                };
498
 
 
499
 
                tracks_to_add.Enqueue (ipod_track);
500
 
            }
501
 
        }
502
 
 
503
 
        public override void SyncPlaylists ()
504
 
        {
505
 
            if (!IsReadOnly && Monitor.TryEnter (sync_mutex)) {
506
 
                PerformSync ();
507
 
                Monitor.Exit (sync_mutex);
508
 
            }
509
 
        }
510
 
 
511
 
        private void QueueSync ()
512
 
        {
513
 
            lock (sync_timeout_mutex) {
514
 
                if (sync_timeout_id > 0) {
515
 
                    Application.IdleTimeoutRemove (sync_timeout_id);
516
 
                }
517
 
 
518
 
                sync_timeout_id = Application.RunTimeout (150, PerformSync);
519
 
            }
520
 
        }
521
 
 
522
 
        private void CancelSyncThread ()
523
 
        {
524
 
            Thread thread = sync_thread;
525
 
            lock (sync_mutex) {
526
 
                if (sync_thread != null && sync_thread_wait != null) {
527
 
                    sync_thread_dispose = true;
528
 
                    sync_thread_wait.Set ();
529
 
                }
530
 
            }
531
 
 
532
 
            if (thread != null) {
533
 
                thread.Join ();
534
 
            }
535
 
        }
536
 
 
537
 
        private bool PerformSync ()
538
 
        {
539
 
            lock (sync_mutex) {
540
 
                if (sync_thread == null) {
541
 
                    sync_thread_wait = new AutoResetEvent (false);
542
 
 
543
 
                    sync_thread = new Thread (new ThreadStart (PerformSyncThread));
544
 
                    sync_thread.Name = "iPod Sync Thread";
545
 
                    sync_thread.IsBackground = false;
546
 
                    sync_thread.Priority = ThreadPriority.Lowest;
547
 
                    sync_thread.Start ();
548
 
                }
549
 
 
550
 
                sync_thread_wait.Set ();
551
 
 
552
 
                lock (sync_timeout_mutex) {
553
 
                    sync_timeout_id = 0;
554
 
                }
555
 
 
556
 
                return false;
557
 
            }
558
 
        }
559
 
 
560
 
        private void PerformSyncThread ()
561
 
        {
562
 
            try {
563
 
                while (true) {
564
 
                    sync_thread_wait.WaitOne ();
565
 
                    if (sync_thread_dispose) {
566
 
                        break;
567
 
                    }
568
 
 
569
 
                    PerformSyncThreadCycle ();
570
 
                }
571
 
 
572
 
                lock (sync_mutex) {
573
 
                    sync_thread_dispose = false;
574
 
                    sync_thread_wait.Close ();
575
 
                    sync_thread_wait = null;
576
 
                    sync_thread = null;
577
 
                }
578
 
            } catch (Exception e) {
579
 
                Log.Exception (e);
580
 
            }
581
 
        }
582
 
 
583
 
        private void PerformSyncThreadCycle ()
584
 
        {
585
 
            Hyena.Log.Debug ("Starting iPod sync thread cycle");
586
 
 
587
 
            CreateNewSyncUserJob ();
588
 
            var i = 0;
589
 
            var total = tracks_to_add.Count;
590
 
            while (tracks_to_add.Count > 0) {
591
 
                IpodTrackInfo track = null;
592
 
                lock (sync_mutex) {
593
 
                    total = tracks_to_add.Count + i;
594
 
                    track = tracks_to_add.Dequeue ();
595
 
                }
596
 
 
597
 
                ChangeSyncProgress (track.ArtistName, track.TrackTitle, ++i / total);
598
 
 
599
 
                try {
600
 
                    track.CommitToIpod (ipod_device);
601
 
                    tracks_map[track.TrackId] = track;
602
 
                    track.Save (false);
603
 
                } catch (Exception e) {
604
 
                    Log.Exception ("Cannot save track to iPod", e);
605
 
                }
606
 
            }
607
 
            if (total > 0) {
608
 
                OnTracksAdded ();
609
 
                OnUserNotifyUpdated ();
610
 
            }
611
 
 
612
 
            while (tracks_to_update.Count > 0) {
613
 
                IpodTrackInfo track = null;
614
 
                lock (sync_mutex) {
615
 
                    track = tracks_to_update.Dequeue ();
616
 
                }
617
 
 
618
 
                try {
619
 
                    track.CommitToIpod (ipod_device);
620
 
                } catch (Exception e) {
621
 
                    Log.Exception ("Cannot save track to iPod", e);
622
 
                }
623
 
            }
624
 
 
625
 
            while (tracks_to_remove.Count > 0) {
626
 
                IpodTrackInfo track = null;
627
 
                lock (sync_mutex) {
628
 
                    track = tracks_to_remove.Dequeue ();
629
 
                }
630
 
 
631
 
                if (tracks_map.ContainsKey (track.TrackId)) {
632
 
                    tracks_map.Remove (track.TrackId);
633
 
                }
634
 
 
635
 
                try {
636
 
                    if (track.IpodTrack != null) {
637
 
                        ipod_device.TrackDatabase.RemoveTrack (track.IpodTrack);
638
 
                    }
639
 
                } catch (Exception e) {
640
 
                    Log.Exception ("Cannot remove track from iPod", e);
641
 
                }
642
 
            }
643
 
 
644
 
            // Remove playlists on the device
645
 
            List<IPod.Playlist> device_playlists = new List<IPod.Playlist> (ipod_device.TrackDatabase.Playlists);
646
 
            foreach (IPod.Playlist playlist in device_playlists) {
647
 
                if (!playlist.IsOnTheGo) {
648
 
                    ipod_device.TrackDatabase.RemovePlaylist (playlist);
649
 
                }
650
 
            }
651
 
            device_playlists.Clear ();
652
 
 
653
 
            if (SupportsPlaylists) {
654
 
                // Add playlists from Banshee to the device
655
 
                List<Source> children = null;
656
 
                lock (Children) {
657
 
                    children = new List<Source> (Children);
658
 
                }
659
 
                foreach (Source child in children) {
660
 
                    PlaylistSource from = child as PlaylistSource;
661
 
                    if (from != null && from.Count > 0) {
662
 
                        IPod.Playlist playlist = ipod_device.TrackDatabase.CreatePlaylist (from.Name);
663
 
                        foreach (int track_id in ServiceManager.DbConnection.QueryEnumerable<int> (String.Format (
664
 
                            "SELECT CoreTracks.TrackID FROM {0} WHERE {1}",
665
 
                            from.DatabaseTrackModel.ConditionFromFragment, from.DatabaseTrackModel.Condition)))
666
 
                        {
667
 
                            if (tracks_map.ContainsKey (track_id)) {
668
 
                                playlist.AddTrack (tracks_map[track_id].IpodTrack);
669
 
                            }
670
 
                        }
671
 
                    }
672
 
                }
673
 
            }
674
 
 
675
 
            try {
676
 
                ipod_device.TrackDatabase.SaveEnded += OnIpodDatabaseSaveEnded;
677
 
                ipod_device.TrackDatabase.SaveProgressChanged += OnIpodDatabaseSaveProgressChanged;
678
 
                ipod_device.Save ();
679
 
            } catch (InsufficientSpaceException) {
680
 
                ErrorSource.AddMessage (Catalog.GetString ("Out of space on device"), Catalog.GetString ("Please manually remove some songs"));
681
 
            } catch (Exception e) {
682
 
                Log.Exception ("Failed to save iPod database", e);
683
 
            } finally {
684
 
                ipod_device.TrackDatabase.SaveEnded -= OnIpodDatabaseSaveEnded;
685
 
                ipod_device.TrackDatabase.SaveProgressChanged -= OnIpodDatabaseSaveProgressChanged;
686
 
                Hyena.Log.Debug ("Ending iPod sync thread cycle");
687
 
            }
688
 
        }
689
 
 
690
 
        private UserJob sync_user_job;
691
 
 
692
 
        private void CreateNewSyncUserJob ()
693
 
        {
694
 
            sync_user_job = new UserJob (Catalog.GetString ("Syncing iPod"),
695
 
                Catalog.GetString ("Preparing to synchronize..."), GetIconNames ());
696
 
            sync_user_job.Register ();
697
 
        }
698
 
 
699
 
        private void OnIpodDatabaseSaveEnded (object o, EventArgs args)
700
 
        {
701
 
            DisposeSyncUserJob ();
702
 
        }
703
 
 
704
 
        private void DisposeSyncUserJob ()
705
 
        {
706
 
            if (sync_user_job != null) {
707
 
                sync_user_job.Finish ();
708
 
                sync_user_job = null;
709
 
            }
710
 
        }
711
 
 
712
 
        private void OnIpodDatabaseSaveProgressChanged (object o, IPod.TrackSaveProgressArgs args)
713
 
        {
714
 
            if (args.CurrentTrack == null) {
715
 
                ChangeSyncProgress (null, null, 0.0);
716
 
            } else {
717
 
                ChangeSyncProgress (args.CurrentTrack.Artist, args.CurrentTrack.Title, args.TotalProgress);
718
 
            }
719
 
        }
720
 
 
721
 
        private void ChangeSyncProgress (string artist, string title, double progress)
722
 
        {
723
 
            string message = (artist == null && title == null)
724
 
                    ? Catalog.GetString ("Updating...")
725
 
                    : String.Format ("{0} - {1}", artist, title);
726
 
 
727
 
            if (progress >= 0.99) {
728
 
                sync_user_job.Status = Catalog.GetString ("Flushing to disk...");
729
 
                sync_user_job.Progress = 0;
730
 
            } else {
731
 
                sync_user_job.Status = message;
732
 
                sync_user_job.Progress = progress;
733
 
            }
734
 
        }
735
 
 
736
 
        public bool SyncNeeded {
737
 
            get {
738
 
                lock (sync_mutex) {
739
 
                    return tracks_to_add.Count > 0 ||
740
 
                        tracks_to_update.Count > 0 ||
741
 
                        tracks_to_remove.Count > 0;
742
 
 
743
 
                }
744
 
            }
745
 
        }
746
 
 
747
 
        public override bool HasEditableTrackProperties {
748
 
            get {
749
 
                // we want child sources to be able to edit metadata and the
750
 
                // savetrackmetadataservice to take in account this source
751
 
                return true;
752
 
            }
753
 
        }
754
 
 
755
 
#endregion
756
 
 
757
 
    }
758
 
}