-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathkaling.js
492 lines (447 loc) · 19.7 KB
/
kaling.js
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
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
/*
카카오링크 자동 전송 모듈
© 2021-2022 Dark Tornado, All rights reserved.
Based on Delta's kaling.js
*/
(function() {
const cryptoModule = require('./crypto');
const CryptoJS = cryptoModule.CryptoJS;
const UserAgent = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.130 Safari/537.36';
const VERSION = '2022.11.16.dev';
/* Main */
function Kakao() {
this.key = null;
this.isInitialized = false;
this.ka = null;
this.referer = null;
this.cookies = new java.util.HashMap();
this.id = null;
this.pw = null;
};
Kakao.prototype = {};
Kakao.prototype.init = function(key, domain) {
if (typeof key != 'string') throw new TypeError('Api key must be string.');
if (key.length != 32) throw new TypeError('Invalid api key: ' + key + '.');
if (typeof domain != 'string') throw new TypeError('Domain must be string.');
this.key = key;
this.ka = 'sdk/2.0.1 os/javascript sdk_type/javascript lang/en-US device/Win32 origin/' + encodeURIComponent(domain);
this.isInitialized = true;
};
Kakao.prototype.login = function(id, pw, save) {
if (!this.isInitialized) throw new TypeError('Cannot call login method before initialization.');
if (typeof id != 'string') throw new TypeError('Invalid id type ' + typeof id);
if (typeof pw != 'string') throw new TypeError('Invalid password type ' + typeof pw);
var login = new LoginManager(this);
login.applyData();
login.authenticate(id, pw);
if (save) {
this.id = id;
this.pw = pw;
}
};
Kakao.prototype.send = function(room, data, type, retry) {
if (type === undefined) type = 'default';
if (data.hasOwnProperty('link_ver')) data.link_ver = '4.0';
var sender = new TemplateSender(this);
var applied = sender.prepareData(type, data);
if (!applied) {
if (!retry) throw new Error('Failed to send KakaoLink. Please login again and retry it.');
if (this.id == null) throw new Error('Cannot execute auto login. Data is not enough(id, password).');
this.login(this.id, this.pw);
sender = new TemplateSender(this);
var applied = sender.prepareData(type, data);
if (!applied) throw new Error('Failed to send KakaoLink although auto login was executed.');
}
sender.findRoom(room);
sender.send();
};
Kakao.prototype.getVersion = function() {
return VERSION;
};
Kakao.prototype.applyDownloader = function(ctx) {
createModuleDownloader(ctx);
};
Kakao.prototype.getRoomInfo = function(room) {
var obj = {"link_ver":"4.0","template_object":{"object_type":"feed","button_title":"","content":{"title":"","image_url":"","link":{},"description":""},"buttons":[{"title":"","link":{}}]}};
var sender = new TemplateSender(this);
var applied = sender.prepareData('default', obj);
if (!applied) throw new Error('Cannot use this method before login');
var rooms = sender.roomList;
for (var n = 0; n < rooms.length; n++) {
if (rooms[n].title.replace(/\u200b/g, '') == room) {
return {
count: rooms[n].member_count,
isOpenChat: rooms[n].id.length == 97
}
}
}
};
/* Kakao Web Login */
function LoginManager(kakao) {
this.kakao = kakao;
this.res = null;
this.cryptoKey = null;
this.loginURL = 'https://accounts.kakao.com/login/';
this.tiaraURL = 'https://stat.tiara.kakao.com/track/';
this.authenticateURL = 'https://accounts.kakao.com/api/v2/login/authenticate.json';
this.authenticateURLLegacy = 'https://accounts.kakao.com/weblogin/authenticate.json';
this.isNextJS;
};
LoginManager.prototype = {};
LoginManager.prototype.applyData = function() {
var res = org.jsoup.Jsoup.connect(this.loginURL)
.header('User-Agent', UserAgent)
.header('referer', 'https://accounts.kakao.com/')
.header('Upgrade-Insecure-Requests', '1')
.data('app_type', 'web')
.data('continue', 'https://accounts.kakao.com/weblogin/account/info')
.ignoreHttpErrors(true)
.method(org.jsoup.Connection.Method.GET)
.execute();
if (res.statusCode() == 401) throw new ReferenceError('Invalid api key: ' + key);
if (res.statusCode() != 200) throw new Error('Unexpected error on method login' + res.statusCode());
this.kakao.referer = res.url().toString();
var docs = res.parse();
var next = docs.getElementById('__NEXT_DATA__');
this.isNextJS = !!next;
if (this.isNextJS) { //새로 바뀐 방식
var data = JSON.parse(next.data());
data = data.props.pageProps.pageContext.commonContext;
this.cryptoKey = data.p;
this.csrfToken = data._csrf;
} else { //기존 방식
this.cryptoKey = docs.select('input[name=p]').attr('value');
this.csrfToken = docs.select('meta[name=csrf-token]').attr('content');
}
var cookies = res.cookies();
var keys = cookies.keySet().toArray();
for (var n = 0; n < keys.length; n++) {
this.kakao.cookies.put(keys[n], cookies.get(keys[n]));
}
//tiara
res = org.jsoup.Jsoup.connect(this.tiaraURL)
.header('User-Agent', UserAgent)
.header('referer', 'https://accounts.kakao.com/')
//.header('Upgrade-Insecure-Requests', '1')
.data('d', '{"sdk":{"type":"WEB","version":"1.1.22"}}')
.ignoreContentType(true)
.ignoreHttpErrors(true)
.method(org.jsoup.Connection.Method.GET)
.execute();
cookies = res.cookies();
var keys = cookies.keySet().toArray();
for (var n = 0; n < keys.length; n++) {
this.kakao.cookies.put(keys[n], cookies.get(keys[n]));
}
};
LoginManager.prototype.authenticate = function(id, pw) {
if (!this.isNextJS) return this.authenticateLegacy(id, pw);
var res = org.jsoup.Jsoup.connect(this.authenticateURL)
.header('User-Agent', UserAgent)
.header('Referer', this.kakao.referer)
.header('Host', 'accounts.kakao.com')
.header('Content-Type', 'application/json')
.cookies(this.kakao.cookies)
.requestBody(JSON.stringify({
'_csrf': this.csrfToken,
'activeSso': true,
'loginKey': id,
'loginUrl': this.kakao.referer,
'password': CryptoJS.AES.encrypt(pw, this.cryptoKey).toString(),
'staySignedIn': false
}))
.ignoreContentType(true)
.ignoreHttpErrors(true)
.method(org.jsoup.Connection.Method.POST)
.execute();
var result = JSON.parse(res.body());
if (result.status == -450) throw new ReferenceError('Invalid id or password');
if (result.status != 0) throw new Error('Unexpected error on method login' + result.status);
var cookies = res.cookies();
var keys = cookies.keySet().toArray();
for (var n = 0; n < keys.length; n++) {
this.kakao.cookies.put(keys[n], cookies.get(keys[n]));
}
};
LoginManager.prototype.authenticateLegacy = function(id, pw) {
var res = org.jsoup.Jsoup.connect(this.authenticateURLLegacy)
.header('User-Agent', UserAgent)
.header('Referer', this.kakao.referer)
.cookies(this.kakao.cookies)
.data('os', 'web')
.data('webview_v', '2')
.data('email', CryptoJS.AES.encrypt(id, this.cryptoKey).toString())
.data('password', CryptoJS.AES.encrypt(pw, this.cryptoKey).toString())
.data('continue', decodeURIComponent(this.kakao.referer.split('continue=')[1]))
.data('third', 'false')
.data('sdk', 'false')
.data('authenticity_token', this.csrfToken)
.data('k', 'true')
.ignoreContentType(true)
.method(org.jsoup.Connection.Method.POST)
.execute();
var result = JSON.parse(res.body());
if (result.status == -450) throw new ReferenceError('Invalid id or password');
if (result.status != 0) throw new Error('Unexpected error on method login' + result.status);
var cookies = res.cookies();
var keys = cookies.keySet().toArray();
for (var n = 0; n < keys.length; n++) {
this.kakao.cookies.put(keys[n], cookies.get(keys[n]));
}
};
/* KakaoLink Sender */
function TemplateSender(kakao) {
this.kakao = kakao;
this.id = null;
this.shortKey = null;
this.checksum = null;
this.csrf = null;
this.template = null;
this.roomList = null;
this.channelData = null;
this.pickerURL = 'https://sharer.kakao.com/picker/link';
this.senderURL = 'https://sharer.kakao.com/picker/send';
};
TemplateSender.prototype = {};
TemplateSender.prototype.prepareData = function(type, data) {
var res = org.jsoup.Jsoup.connect(this.pickerURL)
.header('User-Agent', UserAgent)
.header('Upgrade-Insecure-Requests', '1')
.cookies(this.kakao.cookies)
.data('app_key', this.kakao.key)
.data('ka', this.kakao.ka)
.data('validation_action', type)
.data('validation_params', JSON.stringify(data))
.ignoreHttpErrors(true)
.method(org.jsoup.Connection.Method.POST)
.execute();
var base64 = res.body().match(/serverData = "(.*)"/);
if (base64 == null) return false;
else base64 = base64[1];
var decoded = new java.lang.String(android.util.Base64.decode(base64, android.util.Base64.URL_SAFE)) + '';
var json = JSON.parse(decoded).data;
this.shortKey = json.shortKey;
this.csrf = json.csrfToken;
this.checksum = json.checksum;
this.roomList = json.chats;
var cookies = res.cookies();
var keys = cookies.keySet().toArray();
for (var n = 0; n < keys.length; n++) {
this.kakao.cookies.put(keys[n], cookies.get(keys[n]));
}
return true;
};
TemplateSender.prototype.findRoom = function(room) {
var rooms = this.roomList;
for (var n = 0; n < rooms.length; n++) {
if (rooms[n].title.replace(/\u200b/g, '') == room) {
this.channelData = rooms[n];
return;
}
}
throw new Error('Invalid room name ' + room);
};
TemplateSender.prototype.send = function() {
var str = new java.lang.String(JSON.stringify(this.channelData));
var receiver = android.util.Base64.encodeToString(str.getBytes(), android.util.Base64.NO_WRAP) + '';
var res = org.jsoup.Jsoup.connect(this.senderURL)
.header('User-Agent', UserAgent)
.header('origin', 'https://sharer.kakao.com')
.header('Referer', this.pickerURL + '?app_key=' + this.kakao.key + '&short_key=' + this.shortKey)
.header('Content-Type', 'application/x-www-form-urlencoded')
.header('Upgrade-Insecure-Requests', '1')
.cookies(this.kakao.cookies)
.data('app_key', this.kakao.key)
.data('short_key', this.shortKey)
.data('_csrf', this.csrf)
.data('checksum', this.checksum)
.data('receiver', receiver)
.ignoreContentType(true)
.ignoreHttpErrors(true)
.method(org.jsoup.Connection.Method.POST)
.execute();
};
/* Module Downloader */
const GithubURL = 'https://raw.githubusercontent.com/DarkTornado/KakaoLink.js/main/';
var ctx;
function createModuleDownloader(_ctx) {
ctx = _ctx;
createUI();
}
function createUI() {
var layout0 = new android.widget.LinearLayout(ctx);
layout0.setOrientation(1);
var title = new android.widget.Toolbar(ctx);
title.setTitle('kaling.js 모듈 적용기');
title.setTitleTextColor(android.graphics.Color.WHITE);
title.setBackgroundColor(android.graphics.Color.BLACK);
var margin = new android.widget.LinearLayout.LayoutParams(-1, -2);
margin.setMargins(0, 0, 0, dip2px(ctx, 10));
title.setLayoutParams(margin);
title.setElevation(dip2px(ctx, 3));
layout0.addView(title);
var layout = new android.widget.LinearLayout(ctx);
layout.setOrientation(1);
var txt = new android.widget.TextView(ctx);
txt.setText(' 개발자의 깃허브에서 카카오링크를 다운로드 받아서 자동으로 적용하는 기능입니다.\n' +
' "채팅 자동응답 봇"에서 사용시 모듈이 바로 적용되고, "메신저봇"에서 사용시 "/내장메모리/Download/" 폴더에 저장됩니다.\n\n' +
'현재 사용중인 카링 모듈 버전 : ' + VERSION);
txt.setTextSize(18);
layout.addView(txt);
var check = new android.widget.Button(ctx);
check.setText('최신 버전 확인');
check.setOnClickListener(new android.view.View.OnClickListener() {
onClick: function(v) {
var version = getNewestVersion();
if (version == null) toast('최신버전 확인 실패');
else showDialog('버전 정보', '현재 버전 : ' + VERSION + '\n최신 버전 : ' + version);
}
});
layout.addView(check);
var kaling = new android.widget.Button(ctx);
kaling.setText('kaling.js 다운로드');
kaling.setTransformationMethod(null);
kaling.setOnClickListener(new android.view.View.OnClickListener() {
onClick: function(v) {
checkBotType('kaling');
}
});
layout.addView(kaling);
var crypto = new android.widget.Button(ctx);
crypto.setText('crypto.js 다운로드');
crypto.setTransformationMethod(null);
crypto.setOnClickListener(new android.view.View.OnClickListener() {
onClick: function(v) {
checkBotType('crypto');
}
});
layout.addView(crypto);
var maker = new android.widget.TextView(ctx);
maker.setText('\n© 2021-2022 Dark Tornado, All rights reserved.\n');
maker.setTextSize(12);
maker.setGravity(android.view.Gravity.CENTER);
layout.addView(maker);
var pad = dip2px(ctx, 16);
layout.setPadding(pad, pad, pad, pad);
var scroll = new android.widget.ScrollView(ctx);
scroll.addView(layout);
layout0.addView(scroll);
ctx.setContentView(layout0);
android.os.StrictMode.enableDefaults();
}
function getNewestVersion() {
var url = GithubURL + 'version.txt';
var data = getWebText(url);
if (data == '') return null;
return data;
}
function checkBotType(fileName) {
var type = getBotType();
if (type == '채팅 자동응답 봇') {
prepareDownload(fileName, 'ChatBot/module');
} else if (type == '메신저봇') {
prepareDownload(fileName, 'Download');
} else {
showDialog('기능 사용 불가능', '현재 사용중이신 봇 구동 앱이 무엇인지 식별하지 못했어요.');
}
}
function prepareDownload(fileName, dir) {
var sdcard = android.os.Environment.getExternalStorageDirectory().getAbsolutePath();
var file = new java.io.File(sdcard + '/' + dir + '/' + fileName + '.js');
if (file.exists()) {
alertFileExists(fileName, file);
} else {
download(fileName, file);
}
}
function alertFileExists(fileName, file) {
var dialog = new android.app.AlertDialog.Builder(ctx);
dialog.setTitle('파일이 이미 있습니다');
dialog.setMessage('기존에 있던 모듈 파일을 덮어씌우시겠습니까?');
dialog.setNegativeButton('아니요', null);
dialog.setPositiveButton('네', new android.content.DialogInterface.OnClickListener({
onClick: function(v) {
download(fileName, file);
}
}));
dialog.show();
}
function download(fileName, file) {
var downloaded = copyFromWeb(GithubURL + 'release/' + fileName + '.js', file);
if (downloaded) showDialog('모듈 다운로드 완료', '모듈 파일을 다운로드했어요\n위치: ' + file);
else showDialog('모듈 다운로드 실패', '모듈 파일을 다운로드하지 못했어요 :(');
}
function getWebText(url) {
try {
var url = new java.net.URL(url);
var con = url.openConnection();
if (con != null) {
con.setConnectTimeout(5000);
con.setUseCaches(false);
var isr = new java.io.InputStreamReader(con.getInputStream());
var br = new java.io.BufferedReader(isr);
var str = br.readLine();
var line = '';
while ((line = br.readLine()) != null) {
str += '\n' + line;
}
isr.close();
br.close();
con.disconnect();
}
return str + '';
} catch (e) {
Log.e(e, true);
}
return '';
}
function copyFromWeb(url, file) {
try {
var url = new java.net.URL(url);
var con = url.openConnection();
if (con != null) {
con.setConnectTimeout(5000);
con.setUseCaches(false);
var bis = new java.io.BufferedInputStream(con.getInputStream());
var fos = new java.io.FileOutputStream(file);
var bos = new java.io.BufferedOutputStream(fos);
var buf;
while ((buf = bis.read()) != -1) {
bos.write(buf);
}
bis.close();
bos.close();
con.disconnect();
fos.close();
}
return true;
} catch (e) {
Log.e(e, true);
}
return false;
}
function showDialog(title, msg) {
var dialog = new android.app.AlertDialog.Builder(ctx);
dialog.setTitle(title);
dialog.setMessage(msg);
dialog.setNegativeButton('닫기', null);
dialog.show();
}
function toast(msg) {
android.widget.Toast.makeText(ctx, msg, android.widget.Toast.LENGTH_LONG).show();
}
function dip2px(ctx, dips) {
return Math.ceil(dips * ctx.getResources().getDisplayMetrics().density);
}
function getBotType() {
if (typeof com.darktornado.chatbot.BuildConfig == 'function') return '채팅 자동응답 봇';
if (typeof com.xfl.msgbot.BuildConfig == 'function') return '메신저봇';
return '알 수 없음';
}
/* Legacy Module Compatible */
Kakao.Kakao = function() {
return Kakao;
};
/* Export */
module.exports = Kakao;
})();