Skip to content
This repository
Fetching contributors…

Cannot retrieve contributors at this time

executable file 507 lines (369 sloc) 16.879 kb
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 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507
// SparkleShare, a collaboration and sharing tool.
// Copyright (C) 2010 Hylke Bons <hylkebons@gmail.com>
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.


using System;
using System.Collections.Generic;
using System.IO;
using System.Threading;

using Timers = System.Timers;

namespace SparkleLib {

    public enum SyncStatus {
        Idle,
        SyncUp,
        SyncDown,
        Error
    }


    public abstract class SparkleRepoBase {

        public static bool UseCustomWatcher = false;

        public abstract string CurrentRevision { get; }
        public abstract double Size { get; }
        public abstract double HistorySize { get; }
        public abstract List<string> ExcludePaths { get; }
        public abstract bool HasUnsyncedChanges { get; set; }
        public abstract bool HasLocalChanges { get; }
        public abstract bool HasRemoteChanges { get; }
        public abstract bool SyncUp ();
        public abstract bool SyncDown ();
        public abstract List<SparkleChangeSet> GetChangeSets (int count);
        public abstract List<SparkleChangeSet> GetChangeSets (string path, int count);
        public abstract void RevertFile (string path, string revision);

        public event SyncStatusChangedEventHandler SyncStatusChanged = delegate { };
        public delegate void SyncStatusChangedEventHandler (SyncStatus new_status);

        public event ProgressChangedEventHandler ProgressChanged = delegate { };
        public delegate void ProgressChangedEventHandler (double percentage, string speed);

        public event NewChangeSetEventHandler NewChangeSet = delegate { };
        public delegate void NewChangeSetEventHandler (SparkleChangeSet change_set);

        public event Action ConflictResolved = delegate { };
        public event Action ChangesDetected = delegate { };


        public readonly string LocalPath;
        public readonly string Name;
        public readonly Uri RemoteUrl;
        public List<SparkleChangeSet> ChangeSets { get; protected set; }
        public SyncStatus Status { get; private set; }
        public bool ServerOnline { get; private set; }
        public bool IsBuffering { get; private set; }
        public double ProgressPercentage { get; private set; }
        public string ProgressSpeed { get; private set; }

        public string Identifier {
            get {
                if (this.identifier != null)
                    return this.identifier;

                string id_path = Path.Combine (LocalPath, ".sparkleshare");

                if (File.Exists (id_path))
                    this.identifier = File.ReadAllText (id_path).Trim ();

                if (!string.IsNullOrEmpty (this.identifier)) {
                    return this.identifier;

                } else {
                    string config_identifier = this.local_config.GetIdentifierForFolder (Name);

                    if (!string.IsNullOrEmpty (config_identifier))
                        this.identifier = config_identifier;
                    else
                        this.identifier = SparkleFetcherBase.CreateIdentifier ();

                    File.WriteAllText (id_path, this.identifier);
                    File.SetAttributes (id_path, FileAttributes.Hidden);

                    SparkleLogger.LogInfo ("Local", Name + " | Assigned identifier: " + this.identifier);

                    return this.identifier;
                }
            }
        }

        public virtual string [] UnsyncedFilePaths {
            get {
                return new string [0];
            }
        }


        protected SparkleConfig local_config;


        private string identifier;
        private SparkleListenerBase listener;
        private SparkleWatcher watcher;
        private TimeSpan poll_interval = PollInterval.Short;
        private DateTime last_poll = DateTime.Now;
        private DateTime progress_last_change = DateTime.Now;
        private TimeSpan progress_change_interval = new TimeSpan (0, 0, 0, 1);
        private Timers.Timer remote_timer = new Timers.Timer () { Interval = 5000 };

        private bool is_syncing {
            get {
                return (Status == SyncStatus.SyncUp || Status == SyncStatus.SyncDown || IsBuffering);
            }
        }

        private static class PollInterval {
            public static readonly TimeSpan Short = new TimeSpan (0, 0, 5, 0);
            public static readonly TimeSpan Long = new TimeSpan (0, 0, 15, 0);
        }


        public SparkleRepoBase (string path, SparkleConfig config)
        {
            this.local_config = config;
            LocalPath = path;
            Name = Path.GetFileName (LocalPath);
            RemoteUrl = new Uri (this.local_config.GetUrlForFolder (Name));
            IsBuffering = false;
            ServerOnline = true;
            this.identifier = Identifier;
            ChangeSets = GetChangeSets ();

            SyncStatusChanged += delegate (SyncStatus status) {
                Status = status;
            };

            if (!UseCustomWatcher)
                this.watcher = new SparkleWatcher (LocalPath);

            new Thread (() => CreateListener ()).Start ();

            this.remote_timer.Elapsed += delegate {
                if (this.is_syncing || IsBuffering)
                    return;

                int time_comparison = DateTime.Compare (this.last_poll, DateTime.Now.Subtract (this.poll_interval));
                bool time_to_poll = (time_comparison < 0);

                if (time_to_poll && !is_syncing) {
                    this.last_poll = DateTime.Now;

                    if (HasRemoteChanges)
                        SyncDownBase ();
                }

                // In the unlikely case that we haven't synced up our
                // changes or the server was down, sync up again
                if (HasUnsyncedChanges && !is_syncing && ServerOnline)
                    SyncUpBase ();
            };
        }


        public void Initialize ()
        {
            if (!UseCustomWatcher)
                this.watcher.ChangeEvent += OnFileActivity;

            // Sync up everything that changed
            // since we've been offline
            if (HasLocalChanges) {
                SyncUpBase ();

                while (HasUnsyncedChanges)
                    SyncUpBase ();
            }

            this.remote_timer.Start ();
        }


        public List<SparkleChangeSet> GetChangeSets () {
            return GetChangeSets (30);
        }


        public void OnFileActivity (FileSystemEventArgs args)
        {
            if (IsBuffering)
                return;

            ChangesDetected ();
            string relative_path = args.FullPath.Replace (LocalPath, "");

            foreach (string exclude_path in ExcludePaths) {
                if (relative_path.Contains (exclude_path))
                    return;
            }

            if (IsBuffering || !HasLocalChanges)
                return;

            IsBuffering = true;

            if (!UseCustomWatcher)
                this.watcher.Disable ();

            SparkleLogger.LogInfo ("Local", Name + " | Activity detected, waiting for it to settle...");

            List<double> size_buffer = new List<double> ();

            do {
                if (size_buffer.Count >= 4)
                    size_buffer.RemoveAt (0);

                DirectoryInfo info = new DirectoryInfo (LocalPath);
                size_buffer.Add (CalculateSize (info));

                if (size_buffer.Count >= 4 &&
                    size_buffer [0].Equals (size_buffer [1]) &&
                    size_buffer [1].Equals (size_buffer [2]) &&
                    size_buffer [2].Equals (size_buffer [3])) {

                    SparkleLogger.LogInfo ("Local", Name + " | Activity has settled");
                    IsBuffering = false;

                    if (HasLocalChanges) {
                        do {
                            SyncUpBase ();

                        } while (HasLocalChanges);

                    } else {
                        SyncStatusChanged (SyncStatus.Idle);
                    }

                } else {
                    Thread.Sleep (500);
                }

            } while (IsBuffering);

            if (!UseCustomWatcher)
                this.watcher.Enable ();
        }


        protected void OnConflictResolved ()
        {
            ConflictResolved ();
        }


        protected void OnProgressChanged (double progress_percentage, string progress_speed)
        {
            // Only trigger the ProgressChanged event once per second
            if (DateTime.Compare (this.progress_last_change, DateTime.Now.Subtract (this.progress_change_interval)) >= 0)
                return;

            if (progress_percentage == 100.0)
                progress_percentage = 99.0;

            ProgressPercentage = progress_percentage;
            ProgressSpeed = progress_speed;
            this.progress_last_change = DateTime.Now;

            ProgressChanged (progress_percentage, progress_speed);
        }


        private void SyncUpBase ()
        {
            if (!UseCustomWatcher)
                this.watcher.Disable ();

            SparkleLogger.LogInfo ("SyncUp", Name + " | Initiated");
            HasUnsyncedChanges = true;

            SyncStatusChanged (SyncStatus.SyncUp);

            if (SyncUp ()) {
                SparkleLogger.LogInfo ("SyncUp", Name + " | Done");
                ChangeSets = GetChangeSets ();

                HasUnsyncedChanges = false;

                SyncStatusChanged (SyncStatus.Idle);
                this.listener.Announce (new SparkleAnnouncement (Identifier, CurrentRevision));

            } else {
                SparkleLogger.LogInfo ("SyncUp", Name + " | Error");
                SyncDownBase ();

                if (!UseCustomWatcher)
                    this.watcher.Disable ();

                if (ServerOnline && SyncUp ()) {
                    HasUnsyncedChanges = false;

                    SyncStatusChanged (SyncStatus.Idle);
                    this.listener.Announce (new SparkleAnnouncement (Identifier, CurrentRevision));

                } else {
                    ServerOnline = false;
                    SyncStatusChanged (SyncStatus.Error);
                }
            }

            ProgressPercentage = 0.0;
            ProgressSpeed = "";

            if (!UseCustomWatcher)
                this.watcher.Enable ();
        }


        private void SyncDownBase ()
        {
            if (!UseCustomWatcher)
                this.watcher.Disable ();

            SparkleLogger.LogInfo ("SyncDown", Name + " | Initiated");

            SyncStatusChanged (SyncStatus.SyncDown);
            string pre_sync_revision = CurrentRevision;

            if (SyncDown ()) {
                SparkleLogger.LogInfo ("SyncDown", Name + " | Done");
                ServerOnline = true;

                ChangeSets = GetChangeSets ();

                if (!pre_sync_revision.Equals (CurrentRevision) && ChangeSets != null && ChangeSets.Count > 0) {
                    bool emit_change_event = true;

                    foreach (SparkleChange change in ChangeSets [0].Changes) {
                        if (change.Path.EndsWith (".sparkleshare")) {
                            emit_change_event = false;
                            break;
                        }
                    }
                    
                    if (emit_change_event)
                        NewChangeSet (ChangeSets [0]);
                }

                // There could be changes from a resolved
                // conflict. Tries only once, then lets
                // the timer try again periodically
                if (HasUnsyncedChanges) {
                    SyncStatusChanged (SyncStatus.SyncUp);
                    
                    SyncUp ();
                    HasUnsyncedChanges = false;
                }

                SyncStatusChanged (SyncStatus.Idle);

            } else {
                SparkleLogger.LogInfo ("SyncDown", Name + " | Error");
                ServerOnline = false;

                ChangeSets = GetChangeSets ();

                SyncStatusChanged (SyncStatus.Error);
            }

            ProgressPercentage = 0.0;
            ProgressSpeed = "";

            if (!UseCustomWatcher)
                this.watcher.Enable ();

            SyncStatusChanged (SyncStatus.Idle);
        }


        private void CreateListener ()
        {
            this.listener = SparkleListenerFactory.CreateListener (Name, Identifier);

            if (this.listener.IsConnected) {
                this.poll_interval = PollInterval.Long;

                new Thread (() => {
                    if (!is_syncing && !HasLocalChanges && HasRemoteChanges)
                        SyncDownBase ();

                }).Start ();
            }

            this.listener.Connected += ListenerConnectedDelegate;
            this.listener.Disconnected += ListenerDisconnectedDelegate;
            this.listener.AnnouncementReceived += ListenerAnnouncementReceivedDelegate;

            // Start listening
            if (!this.listener.IsConnected && !this.listener.IsConnecting)
                this.listener.Connect ();
        }


        // Stop polling when the connection to the irc channel is succesful
        private void ListenerConnectedDelegate ()
        {
            this.poll_interval = PollInterval.Long;
            this.last_poll = DateTime.Now;

            if (!is_syncing) {
                // Check for changes manually one more time
                if (HasRemoteChanges)
                    SyncDownBase ();

                // Push changes that were made since the last disconnect
                if (HasUnsyncedChanges)
                    SyncUpBase ();
            }
        }


        // Start polling when the connection to the channel is lost
        private void ListenerDisconnectedDelegate ()
        {
            this.poll_interval = PollInterval.Short;
            SparkleLogger.LogInfo (Name, "Falling back to polling");
        }


        // Fetch changes when there is an announcement
        private void ListenerAnnouncementReceivedDelegate (SparkleAnnouncement announcement)
        {
            string identifier = Identifier;

            if (announcement.FolderIdentifier.Equals (identifier) &&
                !announcement.Message.Equals (CurrentRevision)) {

                while (this.is_syncing)
                    Thread.Sleep (100);

                SparkleLogger.LogInfo (Name, "Syncing due to announcement");
                SyncDownBase ();

            } else {
                if (announcement.FolderIdentifier.Equals (identifier))
                    SparkleLogger.LogInfo (Name, "Not syncing, message is for current revision");
            }
        }


        // Recursively gets a folder's size in bytes
        private double CalculateSize (DirectoryInfo parent)
        {
            if (!Directory.Exists (parent.ToString ()))
                return 0;

            double size = 0;

            if (ExcludePaths.Contains (parent.Name))
                return 0;

            try {
                foreach (FileInfo file in parent.GetFiles ()) {
                    if (!file.Exists)
                        return 0;

                    size += file.Length;
                }

                foreach (DirectoryInfo directory in parent.GetDirectories ())
                    size += CalculateSize (directory);

            } catch (Exception) {
                return 0;
            }

            return size;
        }


        public void Dispose ()
        {
            this.remote_timer.Stop ();
            this.remote_timer.Dispose ();

            this.listener.Connected -= ListenerConnectedDelegate;
            this.listener.Disconnected -= ListenerDisconnectedDelegate;
            this.listener.AnnouncementReceived -= ListenerAnnouncementReceivedDelegate;

            if (!UseCustomWatcher)
                this.watcher.Dispose ();
        }
    }
}
Something went wrong with that request. Please try again.