File size: 7,447 Bytes
b1b3bae
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
using DWSIM.Simulate365.Models;
using DWSIM.UI.Web.Settings;
using Microsoft.Graph;
using Microsoft.IdentityModel.Tokens;
using Newtonsoft.Json;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading.Tasks;

namespace DWSIM.Simulate365.Services
{
    public static class FileUploaderService
    {
        public static event EventHandler<BeforeUploadEventArgs> BeforeUpload;

        public static S365File UploadFile(string fileUniqueIdentifier, string parentUniqueIdentifier, string filePath, string filename, string simulatePath, UploadConflictAction? conflictAction)
        {
            using (var fileStream = System.IO.File.OpenRead(filePath))
                return UploadFile(fileUniqueIdentifier, parentUniqueIdentifier, fileStream, filename, simulatePath, conflictAction);
        }

        public static S365File UploadFile(string fileUniqueIdentifier, string parentUniqueIdentifier, Stream fileStream, string filename, string simulatePath, UploadConflictAction? conflictAction)
        {
            try
            {
                // Invoke event handlers
                var eventArgs = new BeforeUploadEventArgs();
                BeforeUpload?.Invoke(null, eventArgs);
                if (eventArgs.Cancel)
                    throw new Exception("Upload operation was canceled.");

                fileStream.Seek(0, SeekOrigin.Begin);

                var token = UserService.GetInstance().GetUserToken();
                var client = GetDashboardClient(token);

                var file = Task.Run(async () => await UploadDocumentAsync(parentUniqueIdentifier, filename, fileStream, conflictAction)).Result;

                return new S365File(filename)
                {
                    FileUniqueIdentifier = file.FileUniqueIdentifier.ToString(),
                    ParentUniqueIdentifier = parentUniqueIdentifier,
                    Filename = file.Filename,
                    FullPath = file.SimulatePath
                };
            }
            catch (Exception ex)
            {
                throw new Exception("An error occurred while saving file to Simulate 365 Dashboard.", ex);
            }
        }

        public static S365File UploadFileByFilePath(string simulatePath, Stream fileStream, UploadConflictAction? conflictAction)
        {
            try
            {
                // Invoke event handlers
                var eventArgs = new BeforeUploadEventArgs();
                BeforeUpload?.Invoke(null, eventArgs);
                if (eventArgs.Cancel)
                    throw new Exception("Upload operation was canceled.");

                if (simulatePath.StartsWith("//Simulate 365 Dashboard/"))
                    simulatePath = simulatePath.Substring(24);

                var fileWithBreadCrumbs = GetFileByPath(simulatePath);
                if (fileWithBreadCrumbs == null || fileWithBreadCrumbs.File == null)
                    throw new Exception($"File on simulate path '{simulatePath}' not found.");
                var file = fileWithBreadCrumbs.File;

                fileStream.Seek(0, SeekOrigin.Begin);

                var token = UserService.GetInstance().GetUserToken();
                var client = GetDashboardClient(token);
                var parentUniqueIdentifier = fileWithBreadCrumbs.BreadcrumbItems?.LastOrDefault()?.UniqueIdentifier.ToString();

                var filename = Path.GetFileName(simulatePath) ?? string.Empty;

                var fileResp = Task.Run(async () => await UploadDocumentAsync(parentUniqueIdentifier, filename, fileStream, conflictAction)).Result;

                return new S365File(filename)
                {
                    FileUniqueIdentifier = fileResp.FileUniqueIdentifier.ToString(),
                    ParentUniqueIdentifier = parentUniqueIdentifier,
                    Filename = fileResp.Filename,
                    FullPath = fileResp.SimulatePath
                };
            }
            catch (Exception ex)
            {
                throw new Exception("An error occurred while saving file to Simulate 365 Dashboard.", ex);
            }
        }        

        private static async Task<UploadFileResponseModel> UploadDocumentAsync(string parentUniqueIdentifier, string filename, Stream fileStream, UploadConflictAction? conflictAction)
        {
            try
            {
                var token = UserService.GetInstance().GetUserToken();
                var client = GetDashboardClient(token);

                using (var content = new MultipartFormDataContent())
                {
                    // 0= Overwrite file if exists, 1= Keep both
                    if (conflictAction.HasValue)
                        content.Add(new StringContent(conflictAction.ToString()), "ConflictAction");
                    if (!string.IsNullOrWhiteSpace(parentUniqueIdentifier))
                        content.Add(new StringContent(parentUniqueIdentifier), "ParentDirectoryUniqueId");

                    content.Add(new StreamContent(fileStream), "files", filename);

                    // Send request
                    var response = await client.PostAsync("/api/files/upload", content);

                    // Handle response
                    var responseContent = await response.Content.ReadAsStringAsync();
                    var responseModel = JsonConvert.DeserializeObject<List<UploadFileResponseModel>>(responseContent);
                    if (!response.IsSuccessStatusCode)
                    {
                        var errorMessage = await response.Content.ReadAsStringAsync();
                        throw new Exception($"An error occurred while uploading file. Status code: {response.StatusCode}. Error:{errorMessage}");
                    }
                    if (responseModel == null || responseModel.Count == 0)
                        throw new Exception("An error occurred while uploading file. Response is empty.");

                    return responseModel.First();
                }
            }
            catch (Exception ex)
            {
                throw new Exception("An error occurred while trying to upload document.", ex);
            }
        }

        private static FilesWithBreadcrumbsResponseModel GetFileByPath(string simulatePath)
        {
            var token = UserService.GetInstance().GetUserToken();
            var client = GetDashboardClient(token);
            var result = Task.Run(async () => await client.GetAsync($"/api/files/by-path?filePath={simulatePath}&includeBreadcrumbs=true")).Result;
            var resultContent = Task.Run(async () => await result.Content.ReadAsStringAsync()).Result;
            var itemWithBreadcrumbs = JsonConvert.DeserializeObject<FilesWithBreadcrumbsResponseModel>(resultContent);
            return itemWithBreadcrumbs;
        }

        private static HttpClient GetDashboardClient(string token)
        {
            var client = new HttpClient();
            client.BaseAddress = new Uri(DashboardSettings.DashboardServiceUrl);
            client.DefaultRequestHeaders.Add("Authorization", $"Bearer {token}");

            return client;
        }
    }

    public class BeforeUploadEventArgs : EventArgs
    {
        public bool Cancel { get; set; }
    }
}