File: UserService.cpp

package info (click to toggle)
audacity 3.7.7%2Bdfsg-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 134,800 kB
  • sloc: cpp: 366,277; ansic: 198,323; lisp: 7,761; sh: 3,414; python: 1,501; xml: 1,385; perl: 854; makefile: 125
file content (261 lines) | stat: -rw-r--r-- 6,223 bytes parent folder | download | duplicates (2)
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
/*  SPDX-License-Identifier: GPL-2.0-or-later */
/*!********************************************************************

  Audacity: A Digital Audio Editor

  UserService.cpp

  Dmitry Vedenko

**********************************************************************/

#include "UserService.h"

#include <memory>
#include <vector>

#include <wx/file.h>

#include <rapidjson/document.h>

#include "ServiceConfig.h"
#include "OAuthService.h"

#include "BasicUI.h"
#include "FileNames.h"
#include "Observer.h"
#include "Prefs.h"

#include "IResponse.h"
#include "NetworkManager.h"
#include "NetworkUtils.h"
#include "Request.h"

#include "CodeConversions.h"

namespace audacity::cloud::audiocom
{
namespace
{
wxString MakeAvatarPath()
{
   const wxFileName avatarFileName(FileNames::ConfigDir(), "avatar");
   return avatarFileName.GetFullPath();
}

StringSetting userId { L"/cloud/audiocom/userId", "" };
StringSetting userName { L"/cloud/audiocom/userName", "" };
StringSetting displayName { L"/cloud/audiocom/displayName", "" };
StringSetting avatarEtag { L"/cloud/audiocom/avatarEtag", "" };

Observer::Subscription authStateChangedSubscription =
   GetOAuthService().Subscribe(
      [](const auto& state)
      {
         if (state.authorised)
            GetUserService().UpdateUserData();
         else
            GetUserService().ClearUserData();
      });

} // namespace

void UserService::UpdateUserData()
{
   auto& oauthService = GetOAuthService();

   if (!oauthService.HasAccessToken())
      return;

   using namespace audacity::network_manager;

   Request request(GetServiceConfig().GetAPIUrl("/me"));

   request.setHeader(
      common_headers::Authorization,
      std::string(oauthService.GetAccessToken()));

   request.setHeader(
      common_headers::Accept, common_content_types::ApplicationJson);

   SetOptionalHeaders(request);

   auto response = NetworkManager::GetInstance().doGet(request);

   response->setRequestFinishedCallback(
      [response, this](auto)
      {
         const auto httpCode = response->getHTTPCode();

         if (httpCode != 200)
            return;

         const auto body = response->readAll<std::string>();

         using namespace rapidjson;

         Document document;
         document.Parse(body.data(), body.size());

         if (!document.IsObject())
            return;

         const auto id = document["id"].GetString();
         const auto username = document["username"].GetString();
         const auto avatar = document["avatar"].GetString();
         const auto profileName = document["profile"]["name"].GetString();

         BasicUI::CallAfter(
            [this,
             id = std::string(id),
             username = std::string(username),
             profileName = std::string(profileName),
             avatar = std::string(avatar)]()
            {
               userId.Write(audacity::ToWXString(id));
               userName.Write(audacity::ToWXString(username));
               displayName.Write(audacity::ToWXString(profileName));

               gPrefs->Flush();

               DownloadAvatar(avatar);

               Publish({});
            });
      });
}

void UserService::ClearUserData()
{
   BasicUI::CallAfter(
      [this]()
      {
         // No valid data was present, do not spam Publish()
         if (GetUserSlug().empty())
            return;

         userId.Write({});
         userName.Write({});
         displayName.Write({});
         avatarEtag.Write({});

         gPrefs->Flush();

         Publish({});
      });
}

UserService& GetUserService()
{
   static UserService userService;
   return userService;
}

void UserService::DownloadAvatar(std::string_view url)
{
   const auto avatarPath = MakeAvatarPath();
   const auto avatarTempPath = avatarPath + ".tmp";

   if (url.empty())
   {
      if (wxFileExists(avatarPath))
         wxRemoveFile(avatarPath);

      return;
   }

   std::shared_ptr<wxFile> avatarFile = std::make_shared<wxFile>();

   if (!avatarFile->Create(avatarTempPath, true))
      return;

   using namespace audacity::network_manager;

   auto request = Request(std::string(url));

   const auto etag = audacity::ToUTF8(avatarEtag.Read());

   // If ETag is present - use it to prevent re-downloading the same file
   if (!etag.empty() && wxFileExists(avatarPath))
      request.setHeader(common_headers::IfNoneMatch, etag);

   auto response = NetworkManager::GetInstance().doGet(request);

   response->setOnDataReceivedCallback(
      [response, avatarFile](auto)
      {
         std::vector<char> buffer(response->getBytesAvailable());

         size_t bytes = response->readData(buffer.data(), buffer.size());

         avatarFile->Write(buffer.data(), buffer.size());
      });

   response->setRequestFinishedCallback(
      [response, avatarFile, avatarPath, avatarTempPath, this](auto)
      {
         avatarFile->Close();

         const auto httpCode = response->getHTTPCode();

         if (httpCode != 200)
         {
            // For any response except 200 just remove the temp file
            wxRemoveFile(avatarTempPath);
            return;
         }

         const auto etag = response->getHeader("ETag");
         const auto oldPath = avatarPath + ".old";

         if (wxFileExists(avatarPath))
            if (!wxRenameFile(avatarPath, oldPath))
               return;

         if (!wxRenameFile(avatarTempPath, avatarPath))
         {
            // Try at least to get it back...
            wxRenameFile(oldPath, avatarPath);
            return;
         }

         if (wxFileExists(oldPath))
            wxRemoveFile(oldPath);

         BasicUI::CallAfter(
            [this, etag]()
            {
               avatarEtag.Write(etag);
               gPrefs->Flush();

               Publish({});
            });
      });
}

wxString UserService::GetUserId() const
{
   return userId.Read();
}

wxString UserService::GetDisplayName() const
{
   return displayName.Read();
}

wxString UserService::GetUserSlug() const
{
   return userName.Read();
}

wxString UserService::GetAvatarPath() const
{
   auto path = MakeAvatarPath();

   if (!wxFileExists(path))
      return {};

   return path;
}

} // namespace audacity::cloud::audiocom