aboutsummaryrefslogtreecommitdiff
path: root/Timeline/ClientApp/src/app/data/timeline.ts
blob: 19bb3d45a524e9c85d5543fd3a446fe1dd9f1af6 (plain)
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
import axios from 'axios';
import XRegExp from 'xregexp';

import { base64 } from './base64';
import { apiBaseUrl } from '../config';
import { User, UserAuthInfo, getCurrentUser, UserWithToken } from './user';
import { UiLogicError } from '../common';

export const kTimelineVisibilities = ['Public', 'Register', 'Private'] as const;

export type TimelineVisibility = typeof kTimelineVisibilities[number];

export const timelineVisibilityTooltipTranslationMap: Record<
  TimelineVisibility,
  string
> = {
  Public: 'timeline.visibilityTooltip.public',
  Register: 'timeline.visibilityTooltip.register',
  Private: 'timeline.visibilityTooltip.private',
};

export interface TimelineInfo {
  name: string;
  description: string;
  owner: User;
  visibility: TimelineVisibility;
  members: User[];
  _links: {
    posts: string;
  };
}

export interface TimelinePostTextContent {
  type: 'text';
  text: string;
}

export interface TimelinePostImageContent {
  type: 'image';
  url: string;
}

export type TimelinePostContent =
  | TimelinePostTextContent
  | TimelinePostImageContent;

export interface TimelinePostInfo {
  id: number;
  content: TimelinePostContent;
  time: Date;
  author: User;
}

export interface CreatePostRequestTextContent {
  type: 'text';
  text: string;
}

export interface CreatePostRequestImageContent {
  type: 'image';
  data: Blob;
}

export type CreatePostRequestContent =
  | CreatePostRequestTextContent
  | CreatePostRequestImageContent;

export interface CreatePostRequest {
  content: CreatePostRequestContent;
  time?: Date;
}

// TODO: Remove in the future
export interface TimelineChangePropertyRequest {
  visibility?: TimelineVisibility;
  description?: string;
}

export interface PersonalTimelineChangePropertyRequest {
  visibility?: TimelineVisibility;
  description?: string;
}

export interface OrdinaryTimelineChangePropertyRequest {
  // not supported by server now
  // name?: string;
  visibility?: TimelineVisibility;
  description?: string;
}

//-------------------- begin: internal model --------------------

interface RawTimelinePostTextContent {
  type: 'text';
  text: string;
}

interface RawTimelinePostImageContent {
  type: 'image';
  url: string;
}

type RawTimelinePostContent =
  | RawTimelinePostTextContent
  | RawTimelinePostImageContent;

interface RawTimelinePostInfo {
  id: number;
  content: RawTimelinePostContent;
  time: string;
  author: User;
}

interface RawCreatePostRequestTextContent {
  type: 'text';
  text: string;
}

interface RawCreatePostRequestImageContent {
  type: 'text';
  data: string;
}

type RawCreatePostRequestContent =
  | RawCreatePostRequestTextContent
  | RawCreatePostRequestImageContent;

interface RawCreatePostRequest {
  content: RawCreatePostRequestContent;
  time?: string;
}

//-------------------- end: internal model --------------------

function processRawTimelinePostInfo(
  raw: RawTimelinePostInfo,
  token?: string
): TimelinePostInfo {
  return {
    ...raw,
    content: (() => {
      if (raw.content.type === 'image' && token != null) {
        return {
          ...raw.content,
          url: raw.content.url + '?token=' + token,
        };
      }
      return raw.content;
    })(),
    time: new Date(raw.time),
  };
}

type TimelineUrlResolver = (name: string) => string;

export class TimelineServiceTemplate<
  TTimeline extends TimelineInfo,
  TChangePropertyRequest
> {
  private checkUser(): UserWithToken {
    const user = getCurrentUser();
    if (user == null) {
      throw new UiLogicError('You must login to perform the operation.');
    }
    return user;
  }

  constructor(private urlResolver: TimelineUrlResolver) {}

  changeProperty(
    name: string,
    req: TChangePropertyRequest
  ): Promise<TTimeline> {
    const user = this.checkUser();

    return axios
      .patch<TTimeline>(`${this.urlResolver(name)}?token=${user.token}`, req)
      .then((res) => res.data);
  }

  fetch(name: string): Promise<TTimeline> {
    return axios
      .get<TTimeline>(`${this.urlResolver(name)}`)
      .then((res) => res.data);
  }

  fetchPosts(name: string): Promise<TimelinePostInfo[]> {
    const token = getCurrentUser()?.token;
    return axios
      .get<RawTimelinePostInfo[]>(
        token == null
          ? `${this.urlResolver(name)}/posts`
          : `${this.urlResolver(name)}/posts?token=${token}`
      )
      .then((res) => res.data.map((p) => processRawTimelinePostInfo(p, token)));
  }

  createPost(
    name: string,
    request: CreatePostRequest
  ): Promise<TimelinePostInfo> {
    const user = this.checkUser();

    const rawReq: Promise<RawCreatePostRequest> = new Promise<
      RawCreatePostRequestContent
    >((resolve) => {
      if (request.content.type === 'image') {
        void base64(request.content.data).then((d) =>
          resolve({
            ...request.content,
            data: d,
          } as RawCreatePostRequestImageContent)
        );
      } else {
        resolve(request.content);
      }
    }).then((content) => {
      const rawReq: RawCreatePostRequest = {
        content,
      };
      if (request.time != null) {
        rawReq.time = request.time.toISOString();
      }
      return rawReq;
    });

    return rawReq
      .then((req) =>
        axios.post<RawTimelinePostInfo>(
          `${this.urlResolver(name)}/posts?token=${user.token}`,
          req
        )
      )
      .then((res) => processRawTimelinePostInfo(res.data, user.token));
  }

  deletePost(name: string, id: number): Promise<void> {
    const user = this.checkUser();

    return axios.delete(
      `${this.urlResolver(name)}/posts/${id}?token=${user.token}`
    );
  }

  addMember(name: string, username: string): Promise<void> {
    const user = this.checkUser();

    return axios.put(
      `${this.urlResolver(name)}/members/${username}?token=${user.token}`
    );
  }

  removeMember(name: string, username: string): Promise<void> {
    const user = this.checkUser();

    return axios.delete(
      `${this.urlResolver(name)}/members/${username}?token=${user.token}`
    );
  }

  isMemberOf(username: string, timeline: TTimeline): boolean {
    return timeline.members.findIndex((m) => m.username == username) >= 0;
  }

  hasReadPermission(
    user: UserAuthInfo | null | undefined,
    timeline: TTimeline
  ): boolean {
    if (user != null && user.administrator) return true;

    const { visibility } = timeline;
    if (visibility === 'Public') {
      return true;
    } else if (visibility === 'Register') {
      if (user != null) return true;
    } else if (visibility === 'Private') {
      if (user != null && this.isMemberOf(user.username, timeline)) {
        return true;
      }
    }
    return false;
  }

  hasPostPermission(
    user: UserAuthInfo | null | undefined,
    timeline: TTimeline
  ): boolean {
    if (user != null && user.administrator) return true;

    return (
      user != null &&
      (timeline.owner.username === user.username ||
        this.isMemberOf(user.username, timeline))
    );
  }

  hasManagePermission(
    user: UserAuthInfo | null | undefined,
    timeline: TTimeline
  ): boolean {
    if (user != null && user.administrator) return true;

    return user != null && user.username == timeline.owner.username;
  }

  hasModifyPostPermission(
    user: UserAuthInfo | null | undefined,
    timeline: TTimeline,
    post: TimelinePostInfo
  ): boolean {
    if (user != null && user.administrator) return true;

    return (
      user != null &&
      (user.username === timeline.owner.username ||
        user.username === post.author.username)
    );
  }
}

export type PersonalTimelineService = TimelineServiceTemplate<
  TimelineInfo,
  PersonalTimelineChangePropertyRequest
>;

export const personalTimelineService: PersonalTimelineService = new TimelineServiceTemplate<
  TimelineInfo,
  PersonalTimelineChangePropertyRequest
>((name) => `${apiBaseUrl}/timelines/@${name}`);

export type OrdinaryTimelineService = TimelineServiceTemplate<
  TimelineInfo,
  OrdinaryTimelineChangePropertyRequest
>;

export const ordinaryTimelineService: OrdinaryTimelineService = new TimelineServiceTemplate<
  TimelineInfo,
  TimelineChangePropertyRequest
>((name) => `${apiBaseUrl}/timelines/${name}`);

const timelineNameReg = XRegExp('^[-_\\p{L}]*$', 'u');

export function validateTimelineName(name: string): boolean {
  return timelineNameReg.test(name);
}