public MainWindowViewModel()
        {
            Mapper.CreateMap <Task, TaskViewModel>();
            NameValueCollection appSettings = ConfigurationManager.AppSettings;

            DownloadStation = new DownloadStation(new Uri(appSettings["host"]), appSettings["username"], appSettings["password"], CreateProxy(appSettings["proxy"]));

            if (DownloadStation.Login())
            {
                var listResult = DownloadStation.List(String.Join(",", new [] { "detail", "transfer", "file", "tracker" }));
                if (listResult.Success)
                {
                    var taskList = (from task in listResult.Data.Tasks orderby task.Additional.Detail.CreateTime select Mapper.Map <TaskViewModel>(task)).ToList();
                    _allTasks = new ObservableCollection <TaskViewModel>(taskList);
                    var statusList = (new List <TaskStatusViewModel>()
                    {
                        new TaskStatusViewModel("all")
                    }).Concat(
                        taskList.Select(t => t.Status).Distinct().OrderBy(s => s).Select(s => new TaskStatusViewModel(s)));
                    _statuses      = new ObservableCollection <TaskStatusViewModel>(statusList);
                    _tasksByStatus = new Dictionary <string, ObservableCollection <TaskViewModel> >();
                    foreach (var taskStatus in _statuses)
                    {
                        if (taskStatus.Title == "all")
                        {
                            _tasksByStatus.Add(taskStatus.Title, _allTasks);
                            continue;
                        }
                        var tasks = new ObservableCollection <TaskViewModel>(_allTasks.Where(t => t.Status == taskStatus.Title).OrderBy(t => t.Additional.Detail.CreateTime));
                        _tasksByStatus.Add(taskStatus.Title, tasks);
                    }
                }
                OnPropertyChanged("CurrentTasks");
                OnPropertyChanged("Statuses");

                DownloadStation.Logout();
            }
        }
Beispiel #2
0
 public TaskListTests()
 {
     station = new DownloadStation(TestConfig.HttpGateway());
 }
        /// <summary>
        /// Adds a file to Download Station
        /// </summary>
        /// <param name="path">Path of file</param>
        /// <returns>Success?</returns>
        public static bool AddFileToDownloadStation(string path)
        {
            DownloadStation ds = null;
            string name = string.Empty;
            string extention = string.Empty;
            FileStream file = null;

            try
            {
                UriBuilder uriBuilder = new UriBuilder(Properties.Settings.Default.Address)
                {
                    Scheme = Uri.UriSchemeHttp
                };

                ds = new DownloadStation(uriBuilder.Uri, Properties.Settings.Default.Username, Encoding.UTF8.GetString(Convert.FromBase64String(Properties.Settings.Default.Password)));

                if (File.Exists(path))
                {
                    name = Path.GetFileName(path);

                    
                        Adapter.ShowBalloonTip("Adding " + name , ToolTipIcon.Info, 30000);

                        // Register file for download
                        string fileDownload = RegisterFileDownload(path);

                        // Login to Download Station
                        if (ds.Login())
                        {
                            // Add file to Download Station
                            SynologyRestDAL.TResult<object> result = ds.CreateTask(fileDownload);

                            if (!result.Success)
                            {
                                if (result.Error.Code == 406)
                                {
                                    throw new Exception("Couldn't add link(s). You have to choose a download folder for your Download Station.");
                                }
                                else
                                {
                                    throw new Exception("While adding " + name + " error code " + result.Error.Code + " occurred");
                                }
                            }

                            Adapter.ShowBalloonTip("Added " + name, ToolTipIcon.Info);

                            return true;
                        }
                        else
                        {
                            throw new Exception("Couldn't login to Download Station");
                        }                    
                }
                else
                {
                    Adapter.ShowBalloonTip("Couldn't find file '" + path + "'", ToolTipIcon.Error);
                    return false;
                }
            }
            catch (Exception ex)
            {
                Adapter.ShowBalloonTip(ex.Message, ToolTipIcon.Error);
                return false;
            }
            finally
            {
                if (ds != null)
                {
                    ds.Logout();
                }

                if (file != null)
                {
                    file.Close();
                }
            }
        }
        /// <summary>
        /// Add links to Download Station
        /// </summary>
        /// <param name="links">Links to Download</param>
        /// <returns>Success?</returns>
        public static bool AddLinksToDownloadStation(List<string> links)
        {
            DownloadStation ds = null;
                                    
            try
            {
                UriBuilder uriBuilder = new UriBuilder(Properties.Settings.Default.Address);
                                
                ds = new DownloadStation(uriBuilder.Uri, Properties.Settings.Default.Username, Encoding.UTF8.GetString(Convert.FromBase64String(Properties.Settings.Default.Password)));
                         
                links.RemoveAll(str => String.IsNullOrEmpty(str.Trim()));

                Dictionary<string, List<string>> validHostLinks = new Dictionary<string, List<string>>();
                List<string> corruptedLinks = new List<string>();   
                Uri currentLink = null;
                int validHostLinkCount = 0;
                int totalLinkCount = 0;
                string balloonMsg;

                foreach (string link in links)
                {
                    try
                    {
                        currentLink = new Uri(link);
                           
                        if (!validHostLinks.ContainsKey(currentLink.Host))
                        {
                            validHostLinks.Add(currentLink.Host, new List<string>());
                        }
                            
                        validHostLinks[currentLink.Host].Add(link);
                    }
                    catch
                    {
                        corruptedLinks.Add(link);
                    }                        
                }

                if (validHostLinks.Keys.Count > 1)
                {                        
                    frmSettings.Instance.Invoke((MethodInvoker)(() =>
                    {
                        // Run on UI thread
                        frmSelectHoster.Instance.SelectHoster(validHostLinks);
                    }
                    ));
                }

                // Get total link count
                foreach (var validHostLink in validHostLinks)
                {
                    totalLinkCount += validHostLink.Value.Count;
                }


                if (validHostLinks.Count > 0)
                {
                    balloonMsg = "Adding " + totalLinkCount + " links(s) (" + (validHostLinks.Count > 1 ? validHostLinks.Count + " Hosts)" : validHostLinks.First().Key + ")");

                    Adapter.ShowBalloonTip(balloonMsg, ToolTipIcon.Info, 30000);

                    // Login to Download Station
                    if (ds.Login())
                    {

                        foreach (var validHostLink in validHostLinks)
                        {
                            validHostLinkCount += validHostLink.Value.Count;

                            List<List<string>> portions = CreateLinkPortions(validHostLink.Value);

                            foreach (List<string> partionLinks in portions)
                            {
                                // Add links to Download Station
                                SynologyRestDAL.TResult<object> result = ds.CreateTask(string.Join(",", partionLinks.ToArray()));

                                if (!result.Success)
                                {
                                    if (result.Error.Code == 406)
                                    {
                                        throw new Exception("Couldn't add link(s). You have to choose a download folder for your Download Station.");
                                    }
                                    else
                                    {
                                        throw new Exception("While adding link(s) the error code " + result.Error.Code + " occurred");
                                    }
                                }
                            }
                        }

                        balloonMsg = totalLinkCount + " link(s) added (" + (validHostLinks.Count > 1 ? validHostLinks.Count + " Hosts)" : validHostLinks.First().Key + ")");

                        if (corruptedLinks.Count > 0)
                        {
                            balloonMsg += "\r\n" + corruptedLinks.Count + " links(s) were corrupted";
                        }

                        Adapter.ShowBalloonTip(balloonMsg, ToolTipIcon.Info);
                        return true;

                    }
                    else
                    {
                        throw new Exception("Couldn't login to Download Station");
                    }
                }
                else
                {
                    return false;
                }
            }
            catch (Exception ex)
            {
                Adapter.ShowBalloonTip(ex.Message, ToolTipIcon.Error);
                return false;
            }
            finally
            {
                if (ds != null)
                {
                    try
                    {
                        ds.Logout();
                    }
                    catch
                    {
                        // Ignore error on logout
                    }                    
                }
            }
        }
Beispiel #5
0
        static void Main(string[] args)
        {
            string invokedVerb         = "";
            object invokedVerbInstance = null;
            var    options             = new Options();

            if (!Parser.Default.ParseArguments(args, options,
                                               (verb, subOptions) =>
            {
                invokedVerb = verb;
                invokedVerbInstance = subOptions;
            }))
            {
                Console.ReadLine();
                Environment.Exit(Parser.DefaultExitCodeFail);
            }

            NameValueCollection appSettings = ConfigurationManager.AppSettings;
            var ds = new DownloadStation(new Uri(appSettings["host"]), appSettings["username"], appSettings["password"], CreateProxy(appSettings["proxy"]));

            // todo: this is ugly, needs refactoring
            switch (invokedVerb)
            {
            case ("list"):
                var listOptions = (ListOptions)invokedVerbInstance;
                if (ds.Login())
                {
                    var listResult = ds.List(String.Join(",", listOptions.Details));
                    if (listResult.Success)
                    {
                        var taskList = from task in listResult.Data.Tasks select task;
                        if (listOptions.Status.Any())
                        {
                            var statusesToList = new List <string>(listOptions.Status);
                            taskList = from task in taskList where statusesToList.Contains(task.Status) select task;
                        }
                        foreach (var task in taskList)
                        {
                            Console.WriteLine(ObjectUtils.HumanReadable(task));
                            Console.WriteLine();
                        }
                    }
                    ds.Logout();
                }
                break;

            case ("task"):
                var taskOptions = (TaskOptions)invokedVerbInstance;
                if (ds.Login())
                {
                    var taskResult = ds.GetTasks(taskOptions.Id, taskOptions.Details);
                    if (taskResult.Success)
                    {
                        foreach (var task in taskResult.Data.Tasks)
                        {
                            Console.WriteLine(ObjectUtils.HumanReadable(task));
                            Console.WriteLine();
                        }
                    }
                    ds.Logout();
                }
                break;

            case ("new"):
                var newOptions = (NewOptions)invokedVerbInstance;
                if (ds.Login())
                {
                    TResult <Object> taskResult = null;
                    var fileName  = Path.GetFileName(newOptions.Filename);
                    var msgResult = String.Empty;
                    if (!String.IsNullOrWhiteSpace(newOptions.Filename))
                    {
                        using (var taskFile = new FileStream(newOptions.Filename, FileMode.Open, FileAccess.Read, FileShare.Read))
                        {
                            taskResult = ds.CreateTask(fileName, taskFile);
                        }
                        msgResult = String.Format("{0} upload", fileName);
                    }
                    if (!String.IsNullOrWhiteSpace(newOptions.Uri))
                    {
                        taskResult = ds.CreateTask(newOptions.Uri);
                        msgResult  = String.Format("Create task to download {0}", newOptions.Uri);
                    }
                    Console.WriteLine("{0}: {1}", msgResult, taskResult != null && taskResult.Success ? "Ok" : "Failed ");
                    ds.Logout();
                }
                break;

            case ("delete"):
                var deleteOptions = (TaskDeleteOptions)invokedVerbInstance;
                if (ds.Login())
                {
                    if (deleteOptions.Id.Any())
                    {
                        var taskResult = ds.DeleteTasks(deleteOptions.Id, deleteOptions.Force);
                        if (taskResult.Success)
                        {
                            foreach (var taskError in taskResult.Data)
                            {
                                Console.WriteLine(ObjectUtils.HumanReadable(taskError));
                                Console.WriteLine();
                            }
                        }
                    }
                    ds.Logout();
                }
                break;

            case ("pause"):
                var pauseOptions = (TaskPauseOptions)invokedVerbInstance;
                if (ds.Login())
                {
                    if (pauseOptions.Id.Any())
                    {
                        var taskResult = ds.PauseTasks(pauseOptions.Id);
                        if (taskResult.Success)
                        {
                            foreach (var taskError in taskResult.Data)
                            {
                                Console.WriteLine(ObjectUtils.HumanReadable(taskError));
                                Console.WriteLine();
                            }
                        }
                    }
                    ds.Logout();
                }
                break;

            case ("resume"):
                var resumeOptions = (TaskResumeOptions)invokedVerbInstance;
                if (ds.Login())
                {
                    if (resumeOptions.Id.Any())
                    {
                        var taskResult = ds.ResumeTasks(resumeOptions.Id);
                        if (taskResult.Success)
                        {
                            foreach (var taskError in taskResult.Data)
                            {
                                Console.WriteLine(ObjectUtils.HumanReadable(taskError));
                                Console.WriteLine();
                            }
                        }
                    }
                    ds.Logout();
                }
                break;

            default:
                break;
            }
            // Console.ReadLine();
        }