aboutsummaryrefslogtreecommitdiff
path: root/vnext/src/api/index.js
blob: ef753eaf7b302b6eab8a9b46328aad6201c378b3 (plain) (blame)
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
import axios from 'axios';
import Cookies from 'universal-cookie';

const apiBaseUrl = 'https://juick.com';

/**
 * @typedef {object} Token
 * @property {string} type
 * @property {string} token
 */

/** 
 * @typedef { object } TagStats
 * @property { string } tag
 */
/**
 * @typedef {object} User
 * @property {string=} uname
 * @property {number} uid
 * @property {number=} unreadCount
 * @property {string=} avatar
 * @property {User[]=} read
 * @property {User[]=} readers
 * @property {number=} statsMyBL
 * @property {string=} uri
 */

/**
 * @typedef {object} SecureUserProperties
 * @property {string=} hash
 * @property {Token[]=} tokens
 * @property {string=} telegramName
 * @property {string=} twitterName
 * @property {string[]=} jids
 * @property {string[]=} emails
 * @property {string=} activeEmail
 * @property {{connected: boolean, crosspostEnabled: boolean}=} facebookStatus
 */

/**
 * @typedef {User & SecureUserProperties} SecureUser
 */

/**
 * @typedef {object} ChatProperties
 * @property {number=} unreadCount
 * @property {string=} lastMessageText
 */

/**
 * @typedef {User & ChatProperties} Chat
 */

/**
 * @typedef {object} Message
 * @property {string} body
 * @property {number=} mid
 * @property {number=} rid
 * @property {boolean=} service
 * @property {User} user
 * @property {User=} to
 * @property {string=} replyQuote
 * @property {string[]=} tags
 * @property {number=} likes
 * @property {number=} replies
 * @property {string=} photo
 * @property {string=} attach
 * @property {string=} timestamp
 * @property {boolean=} ReadOnly
 * @property {number=} replyto
 */


const client = axios.create({
    baseURL: apiBaseUrl
});
client.interceptors.request.use(config => {
    if (config.url.startsWith('/')) {
        // only local URLs
        let cookies = new Cookies();
        config.params = Object.assign(config.params || {}, {
            hash: cookies.get('hash')
        });
    }
    return config;
});

/**
 * fetch my info
 * @param {string} username
 * @param {string} password
 * @returns {Promise<SecureUser, Error>} me object
 */
export function me(username = '', password = '') {
    let cookies = new Cookies();
    return new Promise((resolve, reject) => {
        client.get('/api/me', {
            headers: username ? {
                'Authorization': 'Basic ' + window.btoa(unescape(encodeURIComponent(username + ':' + password)))
            } : {}
        }).then(response => {
            let visitor = response.data;
            cookies.set('hash', visitor.hash, { path: '/' });
            resolve(visitor);
        }).catch(reason => {
            cookies.remove('hash', { path: '/' });
            reject(reason);
        });
    });
}

/**
 * @param {string} username
 */
export function info(username) {
    return client.get(`/api/info/${username}`);
}


/**
 *
 */
export function getChats() {
    return client.get('/api/groups_pms');
}

/**
 * @param {string} userName
 */
export function getChat(userName) {
    return client.get('/api/pm', {
        params: {
            'uname': userName
        }
    });
}

/**
 * @param {string} userName
 * @param {string} body
 */
export function pm(userName, body) {
    let form = new FormData();
    form.set('uname', userName);
    form.set('body', body);
    return client.post('/api/pm', form);
}

/**
 * @param {string} path
 * @param {{ mid: any; }} params
 */
export function getMessages(path, params) {
    return client.get(path, {
        params: params
    });
}

/**
 * @param {string} body
 * @param {string} attach
 */
export function post(body, attach) {
    let form = new FormData();
    form.append('attach', attach);
    form.append('body', body);
    return client.post('/api/post', form);
}

/**
 * @param {number} mid
 * @param {number} rid
 * @param {string} body
 * @param {string} attach
 */
export function comment(mid, rid, body, attach) {
    let form = new FormData();
    form.append('mid', mid.toString());
    form.append('rid', rid.toString());
    form.append('body', body);
    form.append('attach', attach);
    return client.post('/api/comment', form);
}
/**
 * Edit message
 * @param {number} mid 
 * @param {number} rid 
 * @param {string?} body
 */
export function update(mid, rid, body) {
    let form = new FormData();
    form.append('mid', mid);
    form.append('rid', rid);
    form.append('body', body);
    return client.post('/api/update', form);
}
/**
 * Update user avatar
 * @param {string} newAvatar
 */
export function updateAvatar(newAvatar) {
    let form = new FormData();
    form.append('avatar', newAvatar);
    return client.post('/api/me/upload', form);
}

/**
 * @param {string} network
 */
function socialLink(network) {
    return `${apiBaseUrl}/api/_${network}login?state=${window.location.protocol}//${window.location.host}${window.location.pathname}`;
}

/**
 *
 */
export function facebookLink() {
    return socialLink('fb');
}

/**
 *
 */
export function vkLink() {
    return socialLink('vk');
}

/**
 *
 */
export function appleLink() {
    return socialLink('apple');
}

/**
 * @param {Message} msg
 * @param {SecureUser} visitor
 */
export function markReadTracker(msg, visitor) {
    return `${apiBaseUrl}/api/thread/mark_read/${msg.mid}-${msg.rid || 0}.gif?hash=${visitor.hash}`;
}

let profileCache = {};

/**
 * Fetch user profile
 * @param {string} profileUrl User profile URL
 */
export function fetchUserUri(profileUrl) {
    return new Promise((resolve, reject) => {
        if (profileCache[profileUrl]) {
            resolve(profileCache[profileUrl]);
        } else {
            client.get(profileUrl, {
                headers: {
                    'Accept': 'application/ld+json'
                }
            }).then(response => {
                profileCache[profileUrl] = response.data;
                resolve(response.data);
            }).catch(reject);
        }
    });
}

/**
 * 
 * @returns { Promise<TagStats[]> } tags
 */
 export const trends = async () => {
    try {
    const response = await client.get('/api/tags');
    return response.data;
    } catch (e) {
        console.error(e);
        return [];
    }
};

/**
 * Fetch Tweet content
 * @param {string} url Tweet URL
 * @returns {Promise<string>} HTML content
 */
 const embeddedTweet = async (url = '') => {
    const response = await axios.get('https://publish.twitter.com/oembed', {
        params: {
            'dnt': true,
            'omit_script': true,
            'url': url
        }
    });
    return response.data;
};

/**
 * Checks if HTTP error code is redirection code
 * @param {number} code HTTP error code
 * @returns {boolean} is HTTP request redirected or not
 */
function isHttpRedirected(code = 200) {
    return [301, 302].includes(code);
}

/**
 * Checks if HTTP error code is successful code
 * @param {number} code HTTP error code
 * @returns {boolean} is HTTP request successful or not
 */
function isHttpSuccessful(code = 200) {
    return code >= 200 && code < 300;
}

/**
 * Resolves shortened url to actual one
 * @param {string} url URL to resolve
 * @returns {Promise<string>} full URL
 */
function expandShortenedLink(url = '') {
    return new Promise((resolve, reject) => {
        axios.head(url, {
            maxRedirects: 0
        }).then(response => {
            if (isHttpSuccessful(response.status)) {
                // URL is not redirected
                resolve(url);
                return;
            }
            if (isHttpRedirected(response.status)) {
                resolve(/** @type { string } */ (response.headers['Location']));
                return;
            }
            // Error case
            reject('Invalid response');
        }).catch(error => {
            reject(error);
        });
    });
}

export {
    embeddedTweet,
    expandShortenedLink
};