forked from akhoury/nodebb-plugin-ubbmigrator
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ubbmigrator.js
1392 lines (1170 loc) · 46.5 KB
/
ubbmigrator.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
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
'use strict';
var Group, Meta, User, Topics, Posts, Categories, RDB;
// activated or not, still works IF it's in NodeBB/node_modules/nodebb-plugin-ubbmigrator
try {
Group = module.parent.require('./groups.js');
Meta = module.parent.require('./meta.js');
User = module.parent.require('./user.js');
Topics = module.parent.require('./topics.js');
Posts = module.parent.require('./posts.js');
Categories = module.parent.require('./categories.js');
RDB = module.parent.require('./redis.js');
} catch (e) {
console.log('HA!');
Group = require('../../src/groups.js');
Meta = require('../../src/meta.js');
User = require('../../src/user.js');
Topics = require('../../src/topics.js');
Posts = require('../../src/posts.js');
Categories = require('../../src/categories.js');
RDB = require('../../src/redis.js');
}
var
// nodebb utils, useful
utils = require('../../public/src/utils.js'),
// some useful modules
// mysql to talk to ubb db
mysql = require('mysql'),
// exactly what it means, ubb uses html for some posts, nbb uses markdown, right?
// todo: too fucking slow ! and a memory hog !!
htmlToMarkdown = require('html-md'),
// I'm lazy
$ = require('jquery'),
async = require('async'),
fs = require('fs-extra'),
path = require('path'),
http = require('http'),
argv = require('optimist').argv,
storage = require('node-persist'),
glob = require('glob'),
// a quick logger
Logger = require('./logger.js'),
// later to be initialized with config in init()
logger, m;
m = {
common: {
migrate: function(config) {
async.series([
function(next){
console.log("common.init()");
m.common.init(config, next);
},
function(next){
logger.debug('common.setup()');
m.common.setup(next);
},
function(next) {
if (m.nbb.config.resetup && m.nbb.config.resetup.flush) {
logger.debug('nbb.resetup()');
m.nbb.resetup(next);
} else {
next();
}
},
function (next) {
logger.debug('ubb.getUsers()');
m.ubb.getUsers(next);
},
function (next) {
logger.debug('ubb.getForums()');
m.ubb.getForums(next);
},
function (next) {
logger.debug('ubb.getTopics()');
m.ubb.getTopics(next);
},
function (next) {
logger.debug('ubb.getPosts()');
m.ubb.getPosts(next);
},
function (next) {
logger.debug('ubb.disconnect()');
m.ubb.disconnect();
next();
},
function(next) {
// ubb.forums ===> nbb.categories
logger.debug('nbb.setForums()');
m.nbb.setForums(next);
},
function(next) {
logger.debug('nbb.setUsers()');
m.nbb.setUsers(next);
},
function(next) {
logger.debug('nbb.setTopics()');
m.nbb.setTopics(next);
},
function(next) {
logger.debug('nbb.setPosts()');
m.nbb.setPosts(next);
},
function(next) {
logger.debug('nbb.restoreConfigs()');
m.nbb.restoreConfig(next);
},
function(next) {
logger.debug('common.report()');
m.common.report(next);
},
function(){
logger.debug('common.exit()');
m.common.exit();
}
]);
},
init: function(config, next){
config = config || {};
m.common.config = $.extend({},
{
log: 'info,warn,error,debug',
// generate passwords for the users, yea
passwordGen: {
// chars selection menu
chars: '{}.-_=+qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM1234567890',
// password length
len: 13
},
nginx: {
// ONLY replace the 'MY_UBB_PATH' and 'MY_NBB_PATH' and leave the ${FROM} and ${TO} as they will be replaced appropriately
// or i guess if you know what you're doing then modify at will
// example: rewrite ^/MY_UBB_PATH/users/123(.*)$ /MY_NBB_PATH/user/elvis/$1 last;
// this will be stdout as [info] per each record and also added to the report map.
// I am not an nginx expert, but this should be enough for you if you are.
rule: '[nginx] rewrite ^/MY_UBB_PATH/${FROM}(.*)$ /MY_NBB_PATH/${TO}$1 permanent;'
},
storageDir: path.join(__dirname, './storage'),
markdown: false,
// generate ubbRedictorMap ?
// to work with this https://github.com/akhoury/ubb-redirector
genUbbRedirectorMap: null
}
, config.common);
m.ubb.config = $.extend({},
{
// ubb mysql db access configs
db: {
host: "localhost",
user: "ubb_user",
password: "password",
database: "ubb_test"
},
// ubb default, I think
tablePrefix: 'ubbt_',
// Limit ubb queries to certain time frames
// timestamp in SECONDS
// this is potentially problematic,
// since you can't migrate a topic or post that was created by a user who you wish not to migrate
// I wouldn't use that, maybe for testing .. such as limiting your migration to pre 2004 or something to test it out quick, like I do
timeMachine: {
// using 'after' is very problematic, since dependencies may not exsits, such as a parent topic to a post, a user to a topic, or even a forum to a topic
users: {
after: null,
before: null
},
forums: {
after: null,
before: null
},
topics: {
after: null,
before: null
},
posts: {
after: null,
before: null
}
}
}
, config.ubb);
m.nbb.config = $.extend({},
{
resetup: {
run: false,
setupVal: {
'admin:username': 'admin',
'admin:password': 'password',
'admin:password:confirm': 'password',
'admin:email': 'you@example.com',
'base_url': 'http://localhost',
'port': '4567',
'use_port': 'y',
'redis:host': '127.0.0.1',
'redis:port': 6379,
'redis:password': '',
'redis:database': 0,
'bind_address': '0.0.0.0',
'secret': ''
}
},
// to be randomly selected from migrating the ubb.forums
categoriesTextColors: ['#FFFFFF'],
categoriesBgColors: ['#ab1290','#004c66','#0059b2'],
categoriesIcons: ['fa-comment'],
// this will set the nodebb 'email:*:confirm' records to true
// and will del all the 'confirm:*KEYS*:emails' too
// if you want to auto confirm the user's accounts..
autoConfirmEmails: true,
userReputationMultiplier: 5,
// async.eachLimit
forumsBatchSize: 10000,
usersBatchSize: 10000,
topicsBatchSize: 10000,
postsBatchSize: 10000
}, config.nbb);
// you can override the log by using something like --log="debug"
m.common.config.log = argv.l || argv.log || m.common.config.log;
logger = Logger.init(m.common.config.log);
logger.debug('init()');
m.common.config.storageDir = path.normalize(argv.s || argv.storage || m.common.config.storageDir);
logger.debug("Storage directory is: " + m.common.config.storageDir);
// dev purposes, must be valid JSON
// brotip: i use it like dis
// node ubbmigrator.js --flush --storage="$HOME/Desktop/storage" --log="debug,useful" --ubbredirector --time="{\"users\":{\"before\":1004537600},\"forums\":{\"before\":1004537600},\"topics\":{\"before\":1004537600},\"posts\":{\"before\":1004537600}}"
try {
m.ubb.config.timeMachine = JSON.parse(argv.t || argv.time || JSON.stringify(m.ubb.config.timeMachine));
} catch (e) {
logger.debug("couldn't parse the --time flag value");
}
if (m.nbb.config.resetup.flush) {
logger.info("Clearing out the storage from previous run, please be patient...");
storage.clear();
} else {
logger.info("Attempting to reload memory from storage, please be patient...");
}
storage.initSync({
dir: m.common.config.storageDir
});
if (typeof next == 'function')
next();
},
setup: function(next){
// temp memory
m.mem = {};
m.mem.startTime = new Date().getTime();
if (!m.ubb.config.db) throw new Error('config.ubb.db needs to be passed in to common.migrate()');
// mysql connection to ubb database
m.ubb.connection = mysql.createConnection(m.ubb.config.db);
m.ubb.connection.connect();
m.common.config.genUbbRedirectorMap = argv["ubbredirector"] || m.common.config.genUbbRedirectorMap ? true : null;
if (m.common.config.genUbbRedirectorMap) {
m.mem.ubbRedirectorMap = {
_comment: "see https://github.com/akhoury/ubb-redirector",
newSiteRootUrl: "forums.example.com",
newRootPath: "",
hard: {
newPrefix: "",
map: {
"An_Example_Of_UBB_Old_Hardcoded_Path": "to_New_Harcoded_Path--see _comment key for readme"
}
},
forums: {
prefix: "You Need To Set That -- see _comment key for readme",
// map will be filled automatically
map: {}
},
topics: {
prefix: "You Need To Set That -- see _comment key for readme",
// map will be filled automatically
map: {}
},
users: {
prefix: "You Need To Set That -- see _comment key for readme",
// map will be filled automatically
map: {}
}
// why isn't there any posts? because they each belong in a topic and they cannot be redirected easily, see readme
// but still each OLD post URL will be redirected correctly to its parent Topic, which is not a bad deal
}
}
if (argv.flush || argv.f)
m.nbb.config.resetup.flush = true;
if (m.nbb.config.resetup.flush)
storage.clear();
next();
},
// helpers
report: function(next) {
logger.log('\n\n==== REMEMBER TO:\n'
+ '\n\t*-) Email all your users their new passwords, find them in the map file reported few lines up.'
+ '\n\t*-) Go through all users in the saved users map, each who has user.customPicture == true, test the image url if 200 or not, also filter the ones pointing to your old forum avatar dir, or keep that dir ([YOUR_UBB_PATH]/images/avatars/*) path working, your call'
+ (m.common.config.markdown ? '' : '\n\t*-) All of the posts and topics content are still in HTML, you sould either go through all the html content and Markdown it on your own or use this: https://github.com/akhoury/nodebb-plugin-sanitizehtml')
+ '\n\t*-) Create a nodebb-theme that works with your site'
+ '\n\t*-) I may write a NodeBB plugin to enforce one time use of temp passwords, if you beat me to it, let me know');
logger.log('\n\nFind a gazillion file (for your redirection maps and user\'s new passwords) in: ' + m.common.config.storageDir + '\n');
logger.log('These files have a pattern u.[_ouid], f.[_ofid], t.[_otid], p.[_opid], \'cat\' one of each to view the structure.\n');
logger.log('----> Or if you saved these stdout logs, look for [user-json] or [user-csv] to find all the users mapping.\n');
logger.log('----> And if you used the --ubbredirector flag, you can find a mapping for your redirects in: ' + m.common.config.storageDir + '/ubbRedirectorMap.json' + '\n');
logger.info('DONE, Took ' + (((new Date()).getTime() - m.mem.startTime) / 1000 / 60).toFixed(2) + ' minutes.');
next();
},
redirectRule: function(from, to) {
var res = m.common.config.nginx.rule.replace('${FROM}', from).replace('${TO}', to);
logger.useful(res);
return res;
},
setUbbRedirectorKey: function(key, oid, nIdSlug) {
if (m.common.config.genUbbRedirectorMap)
m.mem.ubbRedirectorMap[key].map[oid] = nIdSlug;
},
exit: function(code, msg){
code = m.common.isNumber(code) ? code : 0;
logger.info('Exiting ... code: ' + code + ( msg ? ' msg: ' + msg : '') );
process.exit(code);
},
maybeMarkdown: function(str){
if (!m.common.config.markdown) return str || '';
return htmlToMarkdown(str || '');
},
// which of the values is falsy
whichIsFalsy: function(arr){
for (var i = 0; i < arr.length; i++) {
if (!arr[i])
return i;
}
return null;
},
// writing json to file slowly, prop by prop to avoid Out of memory errors
slowWriteJSONtoFile: function(file, json, callback) {
fs.writeFileSync(file, '{');
var first = true;
for(var prop in json) {
if(json.hasOwnProperty(prop)) {
if(first)
first = false;
else
fs.appendFileSync(file, ',\n');
fs.appendFileSync(file, JSON.stringify(prop, null, 4) + ':' + JSON.stringify(json[prop], null, 4));
}
}
fs.appendFileSync(file, '}\n');
callback();
},
// yea, for faster lookup
// fn is optional which will take item and apply something to it
convertListToMap: function(list, key, fn){
var map = {};
fn = typeof fn == 'function' ? fn : function(itm){ return itm;};
list.forEach(function(item) {
item = fn(item);
map[item[key]] = item;
});
return map;
},
// check if valid url
isValidUrlSimple: function(url){
// no ftp allowed and length must be > 10 .. whatever.
return url && url.indexOf('http') == 0 && url.length > 10 && url.length <= 2083;
},
// a helper method to generate temporary passwords
genRandPwd: function(len, chars) {
var index = (Math.random() * (chars.length - 1)).toFixed(0);
return len > 0 ? chars[index] + m.common.genRandPwd(len - 1, chars) : '';
},
truncateStr : function (str, len) {
if (typeof str != 'string') return str;
len = m.common.isNumber(len) && len > 3 ? len : 20;
return str.length <= len ? str : str.substr(0, len - 3) + '...';
},
isNumber : function (n) {
return !isNaN(parseFloat(n)) && isFinite(n);
},
// todo: i think I got that right?
cleanUsername: function(str) {
str = str.replace(/[^\u00BF-\u1FFF\u2C00-\uD7FF\-.*\w\s]/gi, '');
// todo: i don't know what I'm doing HALP
return str.replace(/ /g,'').replace(/\*/g, '').replace(/æ/g, '').replace(/ø/g, '').replace(/å/g, '');
},
// todo: holy fuck clean this shit
makeValidNbbUsername: function(_username, _userDisplayName) {
var _userslug = utils.slugify(_username || '');
if (utils.isUserNameValid(_username) && _userslug) {
return {username: _username, userslug: _userslug, validUsername: true, _username: _username, _userDisplayName: _userDisplayName};
} else {
logger.warn(_username + ' [_username] is invalid, attempting to clean.');
var username = m.common.cleanUsername(_username);
var userslug = utils.slugify(username);
if (utils.isUserNameValid(username) && userslug) {
return {username: username, userslug: userslug, validUsername: true, _username: _username, _userDisplayName: _userDisplayName};
} else {
logger.warn(username + ' [username.cleaned] is still invalid, attempting to use the userDisplayName.');
var _userDisplaySlug = utils.slugify(_userDisplayName);
if (utils.isUserNameValid(_userDisplayName) && _userDisplaySlug) {
return {username: _userDisplayName, userslug: _userDisplaySlug, validUsername: true, _username: _username, _userDisplayName: _userDisplayName};
} else {
logger.warn(_userDisplayName + ' [_userDisplayName] is invalid, attempting to clean.');
var userDisplayName = m.common.cleanUsername(_userDisplayName);
var userDisplaySlug = utils.slugify(userDisplayName);
if (utils.isUserNameValid(userDisplayName) && userDisplaySlug) {
return {username: userDisplayName, userslug: userDisplaySlug, validUsername: true, _username: _username, _userDisplayName: _userDisplayName};
} else {
logger.warn(userDisplayName + ' [_userDisplayName.cleaned] is still invalid. sorry. no luck');
return {username: userDisplayName, userslug: userDisplaySlug, validUsername: false, _username: _username, _userDisplayName: _userDisplayName};
}
}
}
}
},
// todo: remove unused functions
hazHtml: function(str){
return !!str.match(/<[a-z][\s\S]*>/i);
},
hasNumber : function (n) {
return !isNaN(parseFloat(n));
},
monthWord : function (i) {
return (function(){return {0: 'Jan', 1: 'Feb', 2: 'Mar', 3: 'Apr', 4: 'May', 5: 'Jun',
6: 'Jul', 7: 'Aug', 8: 'Sep', 9: 'Oct', 10: 'Nov', 11: 'Dec' }})()[i];
},
checkUrlResponse: function(url, callback) {
http.get(url, function(res) {
res.on('data', function(c){
callback(true);
});
res.on('end', function() {
});
res.on('error', function() {
callback(false)
});
});
},
// check if valid url
isValidUrl: function(url){
return url && url.length < 2083 && url.match(/^(?!mailto:)(?:(?:https?|ftp):\/\/)?(?:\S+(?::\S*)?@)?(?:(?:(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z\u00a1-\uffff0-9]+-?)*[a-z\u00a1-\uffff0-9]+)(?:\.(?:[a-z\u00a1-\uffff0-9]+-?)*[a-z\u00a1-\uffff0-9]+)*(?:\.(?:[a-z\u00a1-\uffff]{2,})))|localhost)(?::\d{2,5})?(?:\/[^\s]*)?$/i);
},
// writing json to file prop by prop to avoid Out of memory errors
writeJSONtoFile: function(file, json, callback) {
fs.writeFile(file, JSON.stringify(json, null, 4), callback);
},
// dont ask
saveMap: function(file, nbbid, ubbid) {
}
},
ubb: {
// get ubb users
getUsers: function(next) {
var prefix = m.ubb.config.tablePrefix
, query = 'SELECT '
+ prefix + 'USERS.USER_ID as _ouid, '
+ prefix + 'USERS.USER_LOGIN_NAME as _username, '
+ prefix + 'USERS.USER_DISPLAY_NAME as _userDisplayName, '
+ prefix + 'USERS.USER_REGISTRATION_EMAIL as _email, '
+ prefix + 'USERS.USER_MEMBERSHIP_LEVEL as _level, '
+ prefix + 'USERS.USER_REGISTERED_ON as _joindate, '
+ prefix + 'USERS.USER_IS_APPROVED as _approved, '
+ prefix + 'USERS.USER_IS_banned as _banned, '
+ prefix + 'USER_PROFILE.USER_SIGNATURE as _signature, '
+ prefix + 'USER_PROFILE.USER_HOMEPAGE as _website, '
+ prefix + 'USER_PROFILE.USER_OCCUPATION as _occupation, '
+ prefix + 'USER_PROFILE.USER_LOCATION as _location, '
+ prefix + 'USER_PROFILE.USER_AVATAR as _avatar, '
+ prefix + 'USER_PROFILE.USER_TITLE as _title, '
+ prefix + 'USER_PROFILE.USER_POSTS_PER_TOPIC as _postsPerTopic, '
+ prefix + 'USER_PROFILE.USER_TEMPORARY_PASSWORD as _tempPassword, '
+ prefix + 'USER_PROFILE.USER_TOTAL_POSTS as _totalPosts, '
+ prefix + 'USER_PROFILE.USER_RATING as _rating, '
+ prefix + 'USER_PROFILE.USER_TOTAL_RATES as _totalRates, '
+ prefix + 'USER_PROFILE.USER_BIRTHDAY as _birthday, '
+ prefix + 'USER_PROFILE.USER_UNVERIFIED_EMAIL as _unverifiedEmail '
+ 'FROM ' + prefix + 'USERS, ' + prefix + 'USER_PROFILE '
+ 'WHERE ' + prefix + 'USERS.USER_ID = ' + prefix + 'USER_PROFILE.USER_ID '
+ (m.ubb.config.timeMachine.users.before ?
'AND ' + prefix + 'USERS.USER_REGISTERED_ON < ' + m.ubb.config.timeMachine.users.before : ' ')
+ (m.ubb.config.timeMachine.users.after ?
'AND ' + prefix + 'USERS.USER_REGISTERED_ON >= ' + m.ubb.config.timeMachine.users.after : ' ');
m.ubb.query(query, function(err, rows) {
if (err) throw err;
logger.info('Users query came back with ' + rows.length + ' records, now preparing, please be patient.');
m.mem._ouids = m.ubb._normalizeUsers(rows);
next();
});
},
_normalizeUsers: function(users) {
var kept = 0, _ouids = [];
users.forEach(function(user, ui) {
var stored = storage.getItem('u.' + user._ouid);
if (stored && (stored.normalized || stored.skipped)) {
logger.debug('[c:' + ui + '] user: ' + user._ouid + ' already normalized');
_ouids.push(user._ouid);
return;
}
var userData = {};
if (user._username && user._joindate && user._email) {
user = $.extend({}, user, m.common.makeValidNbbUsername(user._username, user._userDisplayName, user._ouid));
if (user.validUsername) {
// maybe markdown
user.signature = m.common.maybeMarkdown (
// nbb forces signatures to be less than 150 chars
m.common.truncateStr(user._signature || '', 150)
);
// from unix timestamp (s) to JS timestamp (ms)
user._joindate = user._joindate * 1000;
// lower case the email as well
user.email = user._email.toLowerCase();
// I don't know about you about I noticed a lot my users have incomplete urls
// user.avatar = m._isValidUrl(user._avatar) ? user._avatar : '';
// user.website = m._isValidUrl(user._website) ? user._website : '';
// this is a little faster, and less agressive
user.avatar = m.common.isValidUrlSimple(user._avatar) ? user._avatar : '';
user.website = m.common.isValidUrlSimple(user._website) ? user._website : '';
// generate a temp password, don't worry i'll add the clear text to the map so you can email it to the user
user.password = m.common.genRandPwd(m.common.config.passwordGen.len, m.common.config.passwordGen.chars);
kept++;
userData.normalized = user;
_ouids.push(user._ouid);
if (ui % 1000 == 0)
logger.info('Prepared ' + ui + ' users so far.');
} else {
userData.skipped = user;
users.slice(ui, 1);
logger.warn('[!username] skipping user ' + user._username + ':' + user._email + ' _ouid: ' + user._ouid);
}
} else {
logger.warn('[!_username | !_joindate | !_email] skipping user ' + user._username + ':' + user._email + ' _ouid: ' + user._ouid);
userData.skipped = user;
users.slice(ui, 1);
}
storage.setItem('u.' + user._ouid, userData);
});
logger.info('Preparing users done. normalized ' + kept + '/' + users.length);
storage.setItem('u.1', {normalized: {_ouid: 1, uid: 1}});
return _ouids;
},
// get ubb forums
getForums: function(next) {
var prefix = m.ubb.config.tablePrefix
, query = 'SELECT '
+ prefix + 'FORUMS.FORUM_ID as _ofid, '
+ prefix + 'FORUMS.FORUM_TITLE as _name, '
+ prefix + 'FORUMS.FORUM_DESCRIPTION as _description, '
+ prefix + 'FORUMS.CATEGORY_ID as _categoryId, '
+ prefix + 'FORUMS.FORUM_CREATED_ON as _datetime '
+ 'FROM ' + prefix + 'FORUMS '
+ 'WHERE 1 = 1 '
+ (m.ubb.config.timeMachine.forums.before ?
'AND ' + prefix + 'FORUMS.FORUM_CREATED_ON < ' + m.ubb.config.timeMachine.forums.before : ' ')
+ (m.ubb.config.timeMachine.forums.after ?
'AND ' + prefix + 'FORUMS.FORUM_CREATED_ON >= ' + m.ubb.config.timeMachine.forums.after : ' ');
m.ubb.query(query,
function(err, rows){
if (err) throw err;
logger.info('Forums query came back with ' + rows.length + ' records, now preparing, please be patient.');
m.mem._ofids = m.ubb._normalizeForums(rows);
next();
});
},
// ubb.forums == nbb.categories
_normalizeForums: function(forums) {
var kept = 0, _ofids = [];
forums.forEach(function(forum, fi) {
var stored = storage.getItem('f.' + forum._ofid);
if (stored && (stored.normalized || stored.skipped)) {
logger.debug('[c:' + fi + '] forum: ' + forum._ofid + ' already normalized');
_ofids.push(forum._ofid);
return;
}
var forumData = {};
if (forum._name && forum._description) {
// set some defaults since i don't have them
forum.icon = m.nbb.config.categoriesIcons[Math.floor(Math.random() * m.nbb.config.categoriesIcons.length)];
forum.bgColor = m.nbb.config.categoriesBgColors[Math.floor(Math.random() * m.nbb.config.categoriesBgColors.length)];
forum.color = m.nbb.config.categoriesTextColors[Math.floor(Math.random() * m.nbb.config.categoriesTextColors.length)];
// order based on index i guess
forum.order = fi + 1;
forum.name = forum._name;
forum.description = forum._description;
kept++;
forumData.normalized = forum;
_ofids.push(forum._ofid);
if (fi % 1000 == 0)
logger.info('Prepared ' + fi + ' forums so far.');
} else {
logger.warn('skipping forum ' + forum._name + ':' + forum._description + ' _ofid: ' + forum._ofid);
forumData.skipped = forum;
forums.slice(fi, 1);
}
storage.setItem('f.' + forum._ofid, forumData);
});
logger.info('Preparing forums done. normalized ' + kept + '/' + forums.length);
return _ofids;
},
// get ubb topics
getTopics: function(next) {
var prefix = m.ubb.config.tablePrefix
, query =
'SELECT '
+ prefix + 'TOPICS.TOPIC_ID as _otid, '
+ prefix + 'TOPICS.FORUM_ID as _forumId, '
+ prefix + 'TOPICS.POST_ID as _postId, '
+ prefix + 'TOPICS.USER_ID as _userId, '
+ prefix + 'TOPICS.TOPIC_VIEWS as _views, '
+ prefix + 'TOPICS.TOPIC_SUBJECT as _title, '
+ prefix + 'TOPICS.TOPIC_REPLIES as _replies, '
+ prefix + 'TOPICS.TOPIC_TOTAL_RATES as _totalRates,'
+ prefix + 'TOPICS.TOPIC_RATING as _rating, '
+ prefix + 'TOPICS.TOPIC_CREATED_TIME as _datetime, '
+ prefix + 'TOPICS.TOPIC_IS_APPROVED as _approved, '
+ prefix + 'TOPICS.TOPIC_STATUS as _status, '
+ prefix + 'TOPICS.TOPIC_IS_STICKY as _pinned, '
+ prefix + 'POSTS.POST_PARENT_ID as _postParent, '
+ prefix + 'POSTS.TOPIC_ID as _postTopicId, '
+ prefix + 'POSTS.POST_BODY as _firstPostBody '
+ 'FROM ' + prefix + 'TOPICS, ' + prefix + 'POSTS '
+ 'WHERE ' + prefix + 'TOPICS.TOPIC_ID=' + prefix + 'POSTS.TOPIC_ID '
+ 'AND ' + prefix + 'POSTS.POST_PARENT_ID=0 '
+ (m.ubb.config.timeMachine.topics.before ?
'AND ' + prefix + 'TOPICS.TOPIC_CREATED_TIME < ' + m.ubb.config.timeMachine.topics.before : ' ')
+ (m.ubb.config.timeMachine.topics.after ?
'AND ' + prefix + 'TOPICS.TOPIC_CREATED_TIME >= ' + m.ubb.config.timeMachine.topics.after : ' ');
m.ubb.query(query,
function(err, rows) {
if (err) throw err;
logger.info('Topics query came back with ' + rows.length + ' records, now preparing, please be patient.');
m.mem._otids = m.ubb._normalizeTopics(rows);
next();
});
},
// ubb.forums == nbb.categories
_normalizeTopics: function(topics) {
var kept = 0, _otids = [];
topics.forEach(function(topic, ti) {
var stored = storage.getItem('t.' + topic._otid);
if (stored && (stored.normalized || stored.skipped)) {
logger.debug('[c:' + ti + '] topic: ' + topic._otid + ' already normalized');
_otids.push(topic._otid);
return;
}
var topicData = {};
var forumData = storage.getItem('f.' + topic._forumId);
var userData = storage.getItem('u.' + topic._userId);
var forum = (forumData || {}).normalized;
var user = (userData || {}).normalized;
if (user && forum) {
// from s to ms
var time = topic._datetime * 1000;
// maybe markdown
topic.content = m.common.maybeMarkdown(topic._firstPostBody);
topic.title = topic._title ? topic._title[0].toUpperCase() + topic._title.substr(1) : 'Untitled';
topic.timestamp = time;
topic.teaser_timestamp = time;
topic.relativeTime = new Date(time).toISOString();
topic.viewcount = topic._views || 0;
topic.pinned = topic._pinned || 0;
kept++;
topicData.normalized = topic;
_otids.push(topic._otid);
if (ti % 1000 == 0)
logger.info('Prepared ' + ti + ' topics so far.');
} else {
var requiredValues = [forum, user];
var requiredKeys = ['forum','user'];
var falsyIndex = m.common.whichIsFalsy(requiredValues);
logger.warn('Skipping topic: ' + topic._otid + ' titled: ' + topic._title + ' because ' + requiredKeys[falsyIndex] + ' is falsy. Value: ' + requiredValues[falsyIndex]);
topicData.skipped = topic;
topics.slice(ti, 1);
}
storage.setItem('t.' + topic._otid, topicData);
});
logger.info('Preparing topics done. normalized ' + kept + '/' + topics.length);
return _otids;
},
// get ubb forums
getPosts: function(next) {
var prefix = m.ubb.config.tablePrefix
, query =
'SELECT POST_ID as _opid, POST_PARENT_ID as _parent, POST_PARENT_USER_ID as _parentUserId, TOPIC_ID as _topicId, '
+ 'POST_POSTED_TIME as _datetime, POST_SUBJECT as _subject, '
+ 'POST_BODY as _body, USER_ID as _userId, '
+ 'POST_MARKUP_TYPE as _markup, POST_IS_APPROVED as _approved '
+ 'FROM ' + prefix + 'POSTS '
+ 'WHERE POST_PARENT_ID > 0 '
+ (m.ubb.config.timeMachine.posts.before ?
'AND POST_POSTED_TIME < ' + m.ubb.config.timeMachine.posts.before : ' ')
+ (m.ubb.config.timeMachine.posts.after ?
'AND POST_POSTED_TIME >= ' + m.ubb.config.timeMachine.posts.after : ' ');
m.ubb.query(query, function(err, rows) {
if (err) throw err;
logger.info('Posts query came back with ' + rows.length + ' records, now preparing, please be patient.');
m.mem._opids = m.ubb._ubbNormalizePosts(rows);
next();
});
},
_ubbNormalizePosts: function(posts) {
var kept = 0, _opids = [];
posts.forEach(function(post, pi) {
var stored = storage.getItem('p.' + post._opid);
if (stored && (stored.normalized || stored.skipped)) {
logger.debug('[c:' + pi + '] post: ' + post._opid + ' already normalized');
_opids.push(post._opid);
return;
}
var postData = {};
var topicData = storage.getItem('t.' + post._topicId);
var userData = storage.getItem('u.' + post._userId);
var topic = (topicData || {}).normalized;
var user = (userData || {}).normalized;
if (topic && user) {
// from s to ms
var time = post._datetime * 1000;
post.content = m.common.maybeMarkdown(post._body);
post.timestamp = time;
post.relativeTime = new Date(time).toISOString();
postData.normalized = post;
_opids.push(post._opid);
kept++;
if (pi % 1000 == 0)
logger.info('Prepared ' + pi + ' posts so far.');
} else {
var requiredValues = [topic, user];
var requiredKeys = ['topic', 'user'];
var falsyIndex = m.common.whichIsFalsy(requiredValues);
logger.warn('Skipping post: ' + post._opid + ' because ' + requiredKeys[falsyIndex] + ' is falsy. Value: ' + requiredValues[falsyIndex]);
postData.skipped = post;
posts.slice(pi, 1);
}
storage.setItem('p.' + post._opid, postData);
});
logger.info('Preparing posts done. normalized ' + kept + '/' + posts.length + '\n\n\n');
return _opids;
},
// disconnect from the ubb mysql database
disconnect: function(){
m.ubb.connection.end();
},
// query ubb mysql database
query: function(q, callback){
m.ubb.connection.query(q, callback);
}
},
nbb: {
resetup: function(next){
var execSync = require('exec-sync')
, setupVal = JSON.stringify(m.nbb.config.resetup.setupVal).replace(/"/g, '\\"')
, node, result, command;
var setup = function(){
logger.debug('stating nodebb setup');
try {
// todo: won't work on windows
// todo: do i even need this?
node = execSync('which node', true).stdout;
logger.debug('node lives here: ' + node);
// assuming we're in nodebb/node_modules/nodebb-plugin-ubbmigrator
command = node + ' ' + __dirname + '/../../app.js --setup="' + setupVal + '"';
logger.info('Calling this command on your behalf: \n' + command + '\n\n');
result = execSync(command, true);
} catch (e){
logger.error(e);
logger.info('COMMAND');
logger.info(result);
m.exit(1);
}
if (result.stdout.indexOf('NodeBB Setup Completed') > -1) {
logger.info('\n\nNodeBB re-setup completed.');
m.nbb.clearDefaultCategories(next);
} else {
logger.error(JSON.stringify(result));
throw new Error('NodeBB automated setup didn\'t go too well. ');
}
};
RDB.flushdb(function(err, res){
if (err) throw err;
logger.info('flushdb done. ' + res);
setup();
});
},
clearDefaultCategories: function(next) {
// deleting the first 12 default categories by nbb
RDB.keys('category:*', function(err, arr) {
arr.forEach(function(k){
RDB.del(k);
});
RDB.del('categories:cid', function(){
m.nbb.setupGroups(next);
});
});
},
setupGroups: function(next){
Group.getGidFromName('Administrators', function(err, gid) {
// save it
storage.setItem('nbb.groups.administrators.gid', gid);
m.nbb.backupConfig(next);
});
},
backupConfig: function(next){
RDB.hgetall('config', function(err, data) {
if (err) throw err;
m.nbb.config.backedConfig = data || {};
storage.setItem('nbb.config', m.nbb.config);
m.nbb.setTmpConfig(next);
});
},
setTmpConfig: function(next){
// clone the configs
var config = $.extend(true, {}, m.nbb.config.backedConfig);
// get the nbb backedConfigs, change them, then set them back to the db
// just to make the transition a little less flexible
// yea.. i dont know .. i have a bad feeling about this
config.postDelay = 0;
config.minimumPostLength = 1;
config.minimumTitleLength = 1;
config.maximumUsernameLength = 50;
config.maximumProfileImageSize = 1024;
// if you want to auto confirm email, set the host to null, if there is any
// this will prevent User.sendConfirmationEmail from setting expiration time on the email address
// per https://github.com/designcreateplay/NodeBB/blob/master/src/user.js#L458'ish
if (m.nbb.config.autoConfirmEmails)
config['email:smtp:host'] = 'this.host.is.set.by.ubbmigrator.to.disable.email.confirmation@i.hope.this.wont.work';
RDB.hmset('config', config, function(err){
if (err) throw err;
next();
});
},
// aka forums
makeModeratorOnAllCategories: function(uid){
m.mem._ofids.forEach(function(_ofid) {
var forum = storage.getItem('f.' + _ofid);
if (forum && forum.migrated) {