Advertisement
Aluf

Chatango Derplib.py [ch_pm.js]

Feb 1st, 2015
481
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 12.58 KB | None | 0 0
  1. 'use strict';
  2. //Chatango Derplib.py//
  3. // Bay Aluf //
  4. ///////////////////
  5. // Base requires //
  6. var util = require('util'),
  7. events = require('events'),
  8. url = require('url'),
  9. http = require('http'),
  10. querystring = require('querystring'),
  11. _ = require('underscore'),
  12. colors = require('colors');
  13.  
  14. var MM = module.parent,
  15. socket = MM.libary.load('socket'),
  16. weights = MM.libary.load('weights'),
  17. utils = MM.libary.load('utils'),
  18. frame = MM.libary.load('frame'),
  19. request = MM.libary.load('request'),
  20. eventModule = MM.libary.load('eventModule');
  21.  
  22. /////////////////
  23. // Chatango PM //
  24.  
  25. function PM(options) {
  26. events.EventEmitter.call(this);
  27.  
  28. options = options || {};
  29.  
  30. this.ispm = true;
  31. this.contacts = {};
  32. this.blocklist = [];
  33. this._account = options.account || false;
  34. this._accountLC = this._account ? this._account.toLowerCase() : false;
  35. this._password = options.password || false;
  36. this.name = this._accountLC;
  37. this._loggedIn = false;
  38. this._authid = false;
  39. this._writeLock = false;
  40. this._consoleFilter = ['premium', 'msg'];
  41. this._messages = [];
  42. this._sock = false;
  43. this._autoReconnect = options.reconnect || true;
  44. this._settings = {
  45. useBackground: true,
  46. useMedia: false,
  47. nameColor: 'CFF',
  48. textSize: '13',
  49. textColor: 'f00',
  50. textFont: '9',
  51. };
  52.  
  53. var self = this;
  54.  
  55. eventModule.emit("event", "newRoom", this, function(){
  56. // May not be changed
  57. self._settings.type = 'pm';
  58. self._settings.active = true;
  59.  
  60. self.login();
  61. });
  62.  
  63. }
  64.  
  65. util.inherits(PM, events.EventEmitter);
  66.  
  67. PM.prototype.login = function(){
  68.  
  69. var self = this;
  70.  
  71. this.authenticate(function(result){
  72. if(result){
  73. console.log('[PM]['+self._account+'] Session is authenticated');
  74. self._authid = result;
  75. self._sock = new socket.Instance('c1.chatango.com', 5222);
  76. self._onAuth();
  77. eventModule.emit("_PMLoggedIn");
  78. } else {
  79. console.log('[PM]['+self._account+'] Session failed to authenticate');
  80. eventModule.emit("_PMLoginFail");
  81. }
  82. });
  83.  
  84. }
  85.  
  86. PM.prototype.authenticate = function(callback){
  87. console.log('[PM]['+this._account+'] Logging in..');
  88. var auth_re = /auth\.chatango\.com ?= ?([^;]*)/;
  89. var data = querystring.stringify({user_id: this._account, password: this._password, storecookie: 'on', checkerrors: 'yes'});
  90. var options = {host: 'chatango.com', port: 80, path: '/login', method: 'POST', headers: {'Content-Type': 'application/x-www-form-urlencoded', 'Content-Length': data.length}};
  91. var self = this;
  92. var req = http.request(options, function(res) {
  93. if (res.headers['set-cookie'][2]) {
  94. var m = auth_re.exec(res.headers['set-cookie'][2]);
  95. if (m) return callback(m[1]);
  96. }
  97. callback(false);
  98. }).on('error', function(e) {
  99. callback(false);
  100. });
  101. req.write(data);
  102. req.end();
  103. }
  104.  
  105. PM.prototype._onAuth = function(){
  106.  
  107. var self = this;
  108.  
  109. /////////////////////
  110. // Socket Handlers //
  111.  
  112. this._sock.on('onconnect', function() {
  113.  
  114. self.write(['tlogin', self._authid, '2']);
  115.  
  116. self._writeLock = true;
  117.  
  118. eventModule.emit("_PMConnected");
  119. });
  120.  
  121. this._sock.on('error', function(exception) {
  122. console.log(('[PM]['+self._account+'] Socket ERROR:').bold.red, exception);
  123. if(exception.errno == 'ECONNREFUSED'){
  124. if(self._sock._port == 5222){
  125. self._sock._port = 443;
  126. }else if(self._sock._port == 443){
  127. self._sock._port = 5222;
  128. }
  129. }
  130. });
  131.  
  132. this._sock.on('timeout', function(exception) {
  133. console.log(('[PM]['+self._account+'] Socket TIMEOUT:').bold.red, exception);
  134. });
  135.  
  136. this._sock.on('close', function() {
  137. if(self._autoReconnect){
  138. console.log(('[PM]['+self._account+'] Socket closed, reconnecting').bold.red);
  139. self._sock.connect();
  140. }else{
  141. console.log(('[PM]['+self._account+'] Socket closed, reconnect is off').bold.red);
  142. }
  143. });
  144.  
  145. this._sock.on('data', function(data) {
  146.  
  147. data = data.replace(/[\r\n\0]+$/, "");
  148.  
  149. var args = data.split(':');
  150.  
  151. if(self._consoleFilter.indexOf(args[0]) == -1 && self._consoleFilter.indexOf('all') == -1)
  152. console.log('[PM]['+self._account+']', data);
  153.  
  154. var _frame = frame.parseFramePM(data);
  155.  
  156. if(_frame && self.listeners('frame_'+_frame.type).length > 0){
  157. try {
  158. self.emit('frame_'+_frame.type, _frame);
  159. }
  160. catch(e){
  161. console.log('[PM]['+self._account+'] Error: ', e.stack);
  162. //console.log(e.stack.split('\n').slice(0,4).join(''));
  163. }
  164. }
  165.  
  166. });
  167.  
  168. this._sock.on('write', function(data){
  169. //if(data) console.log('[PM]['+self._account+'][WRITE]', data);
  170. });
  171.  
  172. ///////////////////////
  173. // Chatango handlers //
  174.  
  175. this.on('frame_ok', function(_frame){
  176. self._writeLock = false;
  177.  
  178. self._sock.write(['wl']);
  179. self._sock.write(['settings']);
  180. self._sock.write(['getpremium']);
  181.  
  182. /*var idle = true;
  183. setInterval(function(){
  184. idle = !idle;
  185. self.idle(idle);
  186. },1000);*/
  187.  
  188. eventModule.emit('event', 'PmInitialised');
  189. });
  190.  
  191. this.on('frame_msg', function(_frame){
  192. // Parse Room
  193. var req = new request.make(self);
  194. // Parse Message
  195. req.parsePMMessage(_frame);
  196.  
  197. eventModule.emit('event', 'request', req);
  198. });
  199.  
  200. this.on('frame_msgoff', function(_frame){
  201.  
  202. eventModule.emit('event', 'PmOfflineRequest', _frame);
  203. });
  204.  
  205. this.on('frame_wl', function(_frame) {
  206. _.each(_frame.contacts, function(contact){
  207. self.contacts[contact.name] = utils.parseContact(contact.state, (contact.state == 'off' ? contact.time : contact.idle));
  208. });
  209. eventModule.emit('event', 'PmFriendList', _frame.contacts);
  210. });
  211.  
  212. this.on('frame_settings', function(_frame) {
  213. });
  214.  
  215. this.on('frame_idleupdate', function(_frame) {
  216. if(_frame.state == 'on')
  217. self.contacts[_frame.name] = utils.parseContact('on', 1);
  218. else
  219. self.contacts[_frame.name] = utils.parseContact('on', 0);
  220.  
  221. eventModule.emit('event', 'PmIdleupdate', _frame);
  222. });
  223.  
  224. this.on('frame_wloffline', function(_frame){
  225. self.contacts[_frame.name] = utils.parseContact('off', _frame.time);
  226. eventModule.emit('event', 'PmContactOffline', _frame);
  227. });
  228.  
  229. this.on('frame_wlonline', function(_frame){
  230. self.contacts[_frame.name] = utils.parseContact('on', 0);
  231. eventModule.emit('event', 'PmContactOnline', _frame);
  232. });
  233.  
  234. this.on('frame_reload_profile', function(_frame){
  235. eventModule.emit('PmReloadProfile', _frame);
  236. });
  237.  
  238. this.on('frame_wladd', function(_frame){
  239. var contact = utils.parseContact(_frame.state, _frame.time);
  240. self.contacts[_frame.name] = contact;
  241. eventModule.emit('PmFriendAdded', _.extend({name: _frame.name}, contact));
  242. eventModule.emit('PmFriendAdded-'+_frame.name, _.extend({name: _frame.name}, contact));
  243. });
  244.  
  245. this.on('frame_connect', function(_frame){
  246. var contact = utils.parseContact(_frame.state, _frame.time);
  247. _frame.time = contact.time;
  248. _frame.state = contact.state;
  249. eventModule.emit('PmChatOpen', _frame);
  250. });
  251.  
  252. this.on('frame_show_fw', function(_frame){
  253. this._writeLock = true;
  254. setTimeout(function(){
  255. self._writeLock = false;
  256. },10 * 1000);
  257. });
  258.  
  259. this.on('frame_premium', function(_frame) {
  260. if(_frame.time > +new Date/1000){
  261. if(self._settings.useBackground)
  262. self.write(['msgbg', '1']);
  263. if(self._settings.useMedia)
  264. self.write(['msgmedia', '1']);
  265. }
  266. eventModule.emit('PmPremium', _frame);
  267. });
  268.  
  269. }
  270.  
  271. PM.prototype.idle = function(type){
  272. if(type === true)
  273. this._sock.write(['idle', '0']);
  274. else if(type === false)
  275. this._sock.write(['idle', '1']);
  276. }
  277.  
  278. PM.prototype.connectChat = function(name) {
  279. this.write(['connect', name]);
  280. }
  281.  
  282. PM.prototype.disconnectChat = function(name) {
  283. this.write(['disconnect', name]);
  284. }
  285.  
  286. PM.prototype.disconnect = function() {
  287. this._sock.disconnect();
  288. }
  289.  
  290. PM.prototype.reconnect = function(){
  291. this._sock.disconnect();
  292. }
  293.  
  294. PM.prototype.write = function(args) {
  295. if(!this._writeLock){
  296. this._sock.write(_.isArray(args) ? args : _.toArray(arguments));
  297. }
  298. }
  299.  
  300. PM.prototype.message = function(name, body) {
  301.  
  302. if(this._writeLock || !name || !body) return;
  303.  
  304. if(_.isArray(body)){
  305. var output = '';
  306. for(var i=0; i<body.length; i++){
  307. output += '<P>'+this.font()+body[i]+'</g></P>';
  308. }
  309. this.write(['msg', name, '<n'+this._settings.nameColor+'/><m v="1">'+output+'</m>']);
  310. console.log('[PM]['+this._account+'][WRITE]['+name+'] '+body.join('\n'));
  311. }else{
  312. this.write(['msg', name, '<n'+this._settings.nameColor+'/><m v="1">'+this.font()+body+'</g></m>']);
  313. console.log('[PM]['+this._account+'][WRITE]['+name+'] '+body);
  314. }
  315. };
  316.  
  317. PM.prototype.font = function(size, color, face) {
  318. size = size || this._settings.textSize;
  319. color = color || this._settings.textColor;
  320. face = face || this._settings.textFont;
  321. return '<g x'+size+'s'+color+'="'+face+'">';
  322. }
  323.  
  324. PM.prototype.addFriend = function(name){
  325. this.write('wladd', name);
  326. }
  327.  
  328. PM.prototype.userTime = function(user, cb){
  329. user = String(user).toLowerCase();
  330. if( this._accountLC == user){
  331. return utils.parseContact('online',0);
  332. }
  333. this.addFriend(user);
  334. var test = eventModule.once('PmFriendAdded-'+user, function(frame){
  335. // Remove friend if it wasn't before.
  336. cb(frame);
  337. });
  338. }
  339.  
  340. PM.prototype.updateProfile = function(fields){
  341.  
  342. return; // Experimental
  343.  
  344. fields = fields || {};
  345.  
  346. var data = querystring.stringify({
  347. dir: "checked",
  348. checkerrors: "yes",
  349. uns: "1",
  350. //full_profile: " ",
  351. line: fields.mini || "Hi.",
  352. email: '',
  353. location: '',
  354. gender: '',
  355. age: '',
  356. });
  357. var options = {hostname: this._account+'.chatango.com', path: '/updateprofile?flash&d&pic&s='+this._authid, method: 'POST', headers: {'Content-Type': 'application/x-www-form-urlencoded', 'Content-Length': data.length}};
  358. var req = http.request(options, function(res) {
  359. res.setEncoding('utf8');
  360. var result = "";
  361. res.on('data', function(chunk){ result += chunk; });
  362. res.on('end', function(){
  363. console.log("result")
  364. console.log(result);
  365. });
  366. }).on('error', function(e) {
  367. console.log(e);
  368. });
  369. req.write(data);
  370. req.end();
  371. }
  372.  
  373. //
  374. // Exports
  375. //
  376. exports.PM = PM;
  377.  
  378.  
  379. /*
  380. ch_room.js
  381. Room.prototype.parseFont = function(string) {
  382. var self = this;
  383. var all = string.split(string.match(/<font/i));
  384. all.shift();
  385. _.each(all, function(text){
  386. var color = text.match(/color="#(.*?)"/);
  387. color = color != undefined ? color[1] :self._settings.textColor;
  388. var size = text.match(/size="(.*?)"/);
  389. size = size != undefined ? size[1] :self._settings.textSize;
  390. var face = text.match(/face="(.*?)"/);
  391. face = face != undefined ? face[1] :self._settings.textFont;
  392. string = string.replace(/<font(.*?)>/, '<f x'+size+color+'="'+face+'">');
  393. string = string.replace(/<\/font>/g, '</f>');
  394. });
  395. return string;
  396. }
  397. Room.prototype.message = function(body) {
  398.  
  399. if(this._writeLock || !body) return;
  400.  
  401. var self = this;
  402.  
  403. if(_.isArray(body)){
  404. //Multi-line message
  405. var output = _.reduce(body, function(output, msg, i){
  406. return output += self.font() + String(msg) + '</f></p>' + (i == body.length-1 ? '' : '<p>');
  407. }, '');
  408.  
  409. output = output.replace(/(\n\r|\r\n|\n|\r|\0)/g, '<br/>');
  410. _.each(output.match(/.{1,2950}/gm), function(msg){
  411. self.write('bmsg', 'l33t', '<n'+self._settings.nameColor+'/>'+self.parseFont(msg));
  412. });
  413. }
  414. else{
  415. body = String(body).replace(/(\n\r|\r\n|\n|\r|\0)/g, '<br/>');
  416. _.each(body.match(/.{1,2950}/gm), function(msg){
  417. self.write('bmsg', 'l33t', '<n'+self._settings.nameColor+'/>' + self.font() + self.parseFont(msg));
  418. });
  419. }
  420. };
  421. ch_pm.js
  422. PM.prototype.message = function(name, body) {
  423. var self = this;
  424. if(this._writeLock || !name || !body) return;
  425.  
  426. if(_.isArray(body)){
  427. var output = '';
  428. for(var i=0; i<body.length; i++){
  429. output += '<P>'+this.font()+body[i]+'</g></P>';
  430. }
  431. this.write(['msg', name, '<n'+this._settings.nameColor+'/><m v="1">'+self.parseFont(output)+'</m>']);
  432. console.log('[PM][WRITE]['+name+'] '+body.join('\n'));
  433. }else{
  434. this.write(['msg', name, '<n'+this._settings.nameColor+'/><m v="1">'+this.font()+self.parseFont(body)+'</g></m>']);
  435. console.log('[PM][WRITE]['+name+'] '+body);
  436. }
  437. };
  438. PM.prototype.parseFont = function(string) {
  439. var self = this;
  440. var all = string.split(string.match(/<font/i));
  441. all.shift();
  442. _.each(all, function(text){
  443. var color = text.match(/color="#(.*?)"/);
  444. color = color != undefined ? color[1] :self._settings.textColor;
  445. var size = text.match(/size="(.*?)"/);
  446. size = size != undefined ? size[1] :self._settings.textSize;
  447. var face = text.match(/face="(.*?)"/);
  448. face = face != undefined ? face[1] :self._settings.textFont;
  449. string = string.replace(/<font(.*?)>/, '<g x'+size+'s'+color+'="'+face+'">');
  450. string = string.replace(/<\/font>/g, '</g>');
  451. });
  452. return string;
  453. }
  454. */
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement