1
0
mirror of https://github.com/fazo96/telecommander.git synced 2025-01-10 11:34:20 +01:00

separated program into multiple files

This commit is contained in:
Enrico Fasoli 2015-08-31 12:04:32 +00:00
parent d573978f7e
commit 5be530cb17
3 changed files with 393 additions and 320 deletions

217
lib/ui.js Normal file
View File

@ -0,0 +1,217 @@
var blessed = require('blessed')
module.exports = function(data){
data.statusWindow = "Status"
data.selectedWindow = data.statusWindow // the currently selected window
// Get msgBox for given group/user NAME, create if not exists
data.getMsgBox = function(chat,switchto){
if(chat === undefined){
log('ERROR: asked for box for "undefined"!!')
return data.msgBox[statusWindow]
}
if(!data.msgBox[chat]){
//log('Generating window: "'+chat+'"')
data.msgBox[chat] = data.mkBox(chat)
data.screen.append(data.msgBox[chat])
data.getMessages(chat,data.msgBox[chat])
} // else log('Getting window','"'+chat+'"')
if(switchto === true){
data.switchToBox(chat)
}
return data.msgBox[chat]
}
data.switchToBox= function(boxname){
if(data.selectedWindow && data.msgBox[data.selectedWindow])
data.msgBox[data.selectedWindow].hide()
data.selectedWindow = boxname;
if(data.selectedWindow != data.statusWindow)
data.cmdline.setLabel('to '+data.selectedWindow)
else
data.cmdline.setLabel('Command for Telecommander')
var newb = data.getMsgBox(data.selectedWindow)
newb.show()
}
data.screen = blessed.screen({
smartCSR: true,
dockBorders: true
})
data.screen.title = "Telecommander"
data.defaultStyle = {
fg: 'white',
border: { fg: 'grey' },
scrollbar: {
ch: '*'
}
}
// Contact list window
data.chats = blessed.list({
keys: true,
label: 'Conversations',
left: 0,
top:0,
height: data.screen.height-3,
width: '20%',
border: { type: 'line' },
mouse: true,
invertSelected: true,
style: data.defaultStyle,
})
data.chats.style.selected = { bold: true }
// Function to create a log box
data.mkBox = function(label){
var box = blessed.log({
keys: true,
right: 0,
label: label,
width: '80%',
height: data.screen.height - data.cmdline.height,
border: { type: 'line' },
scrollable: true,
//draggable: true,
style: data.defaultStyle
})
box.hide()
return box
}
// Command line prompt
data.cmdline = blessed.textbox({
keys: true,
label: 'Command for Telecommander',
inputOnFocus: true,
bottom: 0,
left: 'center',
width: '100%',
height: 3,
border: { type: 'line' },
style: data.defaultStyle
})
// mgsBox holds the chat boxes for every list entry
data.msgBox = { }
data.msgBox[data.statusWindow] = data.mkBox(data.statusWindow)
// Add stuff to the screen
data.screen.append(data.chats);
data.screen.append(data.msgBox[data.statusWindow]);
data.screen.append(data.cmdline);
data.chats.addItem(data.msgBox[data.statusWindow])
data.switchToBox(data.statusWindow)
data.screen.on('resize',function(){
for(i in data.msgBox){
item = data.msgBox[i]
item.height = screen.height - data.cmdline.height
}
data.chats.height = data.screen.height - data.cmdline.height
data.screen.render()
})
data.screen.key('tab',function(){
data.screen.focusPush(data.chats)
})
data.command = function(cmd){
cmdl = cmd.split(' ')
cmdname = cmdl[0]
if(cmdname === 'phone'){ // So the user can provide his phone numbah
if(data.connected){
return log("Silly user, you're already connected! We don't need that phone number")
}
data.user.phone = cmd.split(' ')[1]
var mindate = moment()
log('Checking your phone number with Telegram...')
data.client.auth.sendCode(user.phone,5,'en',function(result){
if(result.err_code){
return log('Errors:',result.error_code,result.error_message)
}
//log('Res:',JSON.stringify(result))
data.user.registered = result.phone_registered
data.user.phoneCodeHash = result.phone_code_hash
function gmd(){
var m = moment()
m = m.subtract(m.diff(mindate))
return 'Please use a telegram code not older than '+m.fromNow(true)
}
if(!data.user.registered){
data.log("Your number is not registered. Telecommander will register your account with the Telegram service")
data.log(gmd())
data.log('Ready for phone code, use command: "code <code> <name> <lastname>" to register')
data.log("If you don't want to sign up, just don't enter the code and press ESC to exit. No data was saved to the file system")
} else {
data.log("Your number is already assigned to a Telegram account. Telecommander will log you in.")
data.log(gmd())
data.log("If you don't want to sign in, just don't enter the code and press ESC to exit. No data was saved to the file system")
}
})
} else if(cmdname === 'code'){ // So the user can provide his phone code
if(data.connected){
return log("Silly user, you're already connected! We don't need that phone code")
}
code = cmdl[1]
name = cmdl[2]
lastname = cmdl[3]
if(((!name || !lastname) && !data.user.registered) || !code)
return log('insufficient arguments:',cmd)
cb = function(result){
data.user.id = ''+result.user.id
data.user.phone = result.user.phone
data.user.phoneCodeHash = result.phone_code_hash
data.user.username = result.user.username
data.user.first_name = result.user.first_name
data.user.last_name = result.user.last_name
// Done, write user data and key to disk
log('Writing Log In token and user data to',cfgDir)
fs.writeFile(cfgDir+'key',authKey,function(err){
if(err) log('FATAL: Could not write key to disk:',err)
})
fs.writeFile(cfgDir+'user_data.json',JSON.stringify(user),function(err){
if(err) log("FATAL: couldn't write user_data.json:",err)
})
whenReady()
}
// Log in finally
if(user.registered) client.auth.signIn(user.phone,user.phoneCodeHash,code,cb)
else client.auth.signUp(user.phone,user.phoneCodeHash,code,name,lastname,cb)
} else {
data.log('Command not found.')
}
}
// What happens when a different window is selected
data.chats.on('select',function(selected){
data.log('SELECT:',selected.content)
data.switchToBox(selected.content)
data.screen.focusPush(data.cmdline)
data.screen.render()
})
// Catch ctrl-c or escape event and close program
data.screen.key(['escape','C-c'], function(ch,key){
data.quit()
});
// What happens when the user submits a command in the prompt
data.cmdline.on('submit',function(value){
data.getMsgBox(data.statusWindow).add('< '+value)
if(data.selectedWindow === data.statusWindow || data.nameToObj(data.selectedWindow) === undefined){
//log('Window:',selectedWindow,'Eval cmd:',value)
data.command(value)
} else if(value.indexOf('//') === 0){
data.sendMsg(selectedWindow,value.substring(1))
} else if(value.indexOf('/') === 0){
data.command(value.substring(1))
} else {
data.sendMsg(data.selectedWindow,value)
}
data.cmdline.clearValue()
data.cmdline.focus()
})
}

85
lib/util.js Normal file
View File

@ -0,0 +1,85 @@
module.exports = function(data){
// Contacts holds all the contacts data
data.contacts = { }
// Groups hold all the data about groups
data.groups = { }
// unameToUid is used to match a name to its user id
data.unameToUid = { }
// same thing for group name -> group object
data.gnameToGid = { }
data.user = { } // holds data about current user
data.state = { } // keeps track of the telegram update state
data.addUser = function(u){
if(!data.user || !data.user.id) return log("Can't add invalid user object to contacts",u)
data.contacts[u.id] = { user: u, id: u.id}
var name = data.getName(u.id,'user')
data.unameToUid[name] = u.id
if(!data.chats.getItem(name)) data.chats.addItem(name)
}
data.addGroup = function(group){
if(data.groups[group.id]) return;
if(group.left === true) return;
if(group.title === undefined){
return data.log('Undefined group title in group ',group)
}
data.groups[group.id] = { id: group.id, title: group.title }
data.gnameToGid[group.title] = group.id
if(!data.chats.getItem(group.title)) data.chats.addItem(group.title)
}
// Updates the current state
data.updateState = function(newstate){
data.state.pts = newstate.pts
data.state.qts = newstate.qts
data.state.date = newstate.date
data.state.sqp = newstate.seq
data.state.unreadCount = newstate.unread_count
}
// process an update
data.onUpdate = function(upd){
data.log('Got Update:',upd.toPrintable())
}
data.nameForUser = function(u){
return u.first_name + ' ' + u.last_name + (u.username?' (@'+u.username+')':'')
}
data.getName = function(id,type){
if(id === data.user.id) return data.nameForUser(data.user)
else if(type === undefined) throw new Error('no type')
else if(type === 'group' && data.groups[id])
return data.groups[id].title
else if(type === 'user' && data.contacts[id])
return data.nameForUser(data.contacts[id].user)
else data.log('Failed to find name for',type,id)
}
data.nameToObj = function(name){
var id = data.gnameToGid[name]
if(data.groups[id] && data.groups[id].title === name)
return data.groups[id]
else {
id = data.unameToUid[name]
return data.contacts[id]
}
}
data.idToPeer = function(uid,type){
if(type === 'user')
return new data.telegramLink.type.InputPeerContact({ props: { user_id: ''+uid } })
else if(type === 'group')
return new data.telegramLink.type.InputPeerChat({ props: { chat_id: ''+uid } })
}
data.quit = function(){
if(data.connected || data.client != undefined){
data.log('Closing communications and shutting down...')
data.client.end(function(){
process.exit(0)
})
} else process.exit(0);
}
}

View File

@ -1,20 +1,25 @@
#!/usr/bin/env node #!/usr/bin/env node
var path = require('path')
var cfgDir = path.join(process.env.XDG_CONFIG_HOME || (path.join(process.env.HOME || process.env.USERPROFILE, '/.config/')), 'telecommander/')
process.env.LOGGER_FILE = cfgDir+'log'
var os = require('os') var os = require('os')
var fs = require('fs') var fs = require('fs')
var moment = require('moment') var moment = require('moment')
var blessed = require('blessed') var blessed = require('blessed')
var data = {} // Hold all global data
require('./lib/util.js')(data) // Load utils
require('./lib/ui.js')(data) // Load ui
var path = require('path')
data.cfgDir = path.join(process.env.XDG_CONFIG_HOME || (path.join(process.env.HOME || process.env.USERPROFILE, '/.config/')), 'telecommander/')
process.env.LOGGER_FILE = data.cfgDir+'log'
/* IF YOU FORK THE APP PLEASE CHANGE THE ID /* IF YOU FORK THE APP PLEASE CHANGE THE ID
* AND HASH IN THE APP OBJECT! THEY IDENTIFY * AND HASH IN THE APP OBJECT! THEY IDENTIFY
* THE APPLICATION CREATOR AND YOU CAN * THE APPLICATION CREATOR AND YOU CAN
* OBTAIN YOURS FROM http://my.telegram.org * OBTAIN YOURS FROM http://my.telegram.org
*/ */
var app = { data.app = {
id: '42419', id: '42419',
hash: '90a3c2cdbf9b391d9ed72c0639dc0786', hash: '90a3c2cdbf9b391d9ed72c0639dc0786',
version: require('./package.json').version, version: require('./package.json').version,
@ -25,124 +30,24 @@ var app = {
try { fs.makeDirSync(cfgDir,'0770') } catch (e) { } try { fs.makeDirSync(cfgDir,'0770') } catch (e) { }
// Logger
var getLogger = require('get-log') var getLogger = require('get-log')
getLogger.PROJECT_NAME = 'telecommander' getLogger.PROJECT_NAME = 'telecommander'
var logger = getLogger('main') data.logger = getLogger('main')
var telegramLink = require('telegram.link')() data.telegramLink = require('telegram.link')()
data.authKey // our authorization key to access telegram
// Prepare blessed UI data.connected = false // keep track of wether we are good to go and logged in
var screen = blessed.screen({
smartCSR: true,
dockBorders: true
})
screen.title = "Telecommander"
var defaultStyle = {
fg: 'white',
border: { fg: 'grey' },
scrollbar: {
ch: '*'
}
}
// Contact list window
var chats = blessed.list({
keys: true,
label: 'Conversations',
left: 0,
top:0,
height: screen.height-3,
width: '20%',
border: { type: 'line' },
mouse: true,
invertSelected: true,
style: defaultStyle,
})
chats.style.selected = { bold: true }
chats.focus()
// Function to create a log box
function mkBox(label){
var box = blessed.log({
keys: true,
right: 0,
label: label,
width: '80%',
height: screen.height - cmdline.height,
border: { type: 'line' },
scrollable: true,
//draggable: true,
style: defaultStyle
})
box.hide()
return box
}
// Command line prompt
var cmdline = blessed.textbox({
keys: true,
label: 'Command for Telecommander',
inputOnFocus: true,
bottom: 0,
left: 'center',
width: '100%',
height: 3,
border: { type: 'line' },
style: defaultStyle
})
var statusWindow = "Status"
// mgsBox holds the chat boxes for every list entry
var msgBox = { }
msgBox[statusWindow] = mkBox(statusWindow)
// Add stuff to the screen
screen.append(chats);
screen.append(cmdline);
screen.append(msgBox[statusWindow]);
chats.addItem(msgBox[statusWindow])
switchToBox(statusWindow)
screen.on('resize',function(){
for(i in msgBox){
item = msgBox[i]
item.height = screen.height - cmdline.height
}
chats.height = screen.height - cmdline.height
screen.render()
})
screen.key('tab',function(){
screen.focusPush(chats)
})
screen.render()
// Contacts holds all the contacts data
var contacts = { }
// Groups hold all the data about groups
var groups = { }
// unameToUid is used to match a name to its user id
var unameToUid = { }
// same thing for group name -> group object
var gnameToGid = { }
var state = { } // keeps track of the telegram update state
var client // used to talk with telegram
var user = { } // holds data about current user
var authKey // our authorization key to access telegram
var connected = false // keep track of wether we are good to go and logged in
var selectedWindow = statusWindow // the currently selected window
// Write something in the Status box // Write something in the Status box
function log(){ data.log = function(){
args = Array.prototype.slice.call(arguments) args = Array.prototype.slice.call(arguments)
var msg = args.join(' ') var msg = args.join(' ')
msgBox[statusWindow].add(msg) data.getMsgBox(data.statusWindow).add(msg)
logger.info(msg) data.logger.info(msg)
} }
function command(cmd){ data.command = function(cmd){
cmdl = cmd.split(' ') cmdl = cmd.split(' ')
cmdname = cmdl[0] cmdname = cmdl[0]
@ -211,241 +116,107 @@ function command(cmd){
} }
} }
// What happens when a different window is selected
chats.on('select',function(selected){
log('SELECT:',selected.content)
switchToBox(selected.content)
screen.focusPush(cmdline)
screen.render()
})
function switchToBox(boxname){
if(selectedWindow && msgBox[selectedWindow])
msgBox[selectedWindow].hide()
selectedWindow = boxname;
if(selectedWindow != statusWindow)
cmdline.setLabel('to '+selectedWindow)
else
cmdline.setLabel('Command for Telecommander')
var newb = getMsgBox(selectedWindow)
newb.show()
}
// Get msgBox for given group/user NAME, create if not exists
function getMsgBox(chat,switchto){
if(chat === undefined){
log('ERROR: asked for box for "undefined"!!')
return msgBox[statusWindow]
}
if(!msgBox[chat]){
//log('Generating window: "'+chat+'"')
msgBox[chat] = mkBox(chat)
screen.append(msgBox[chat])
getMessages(chat,msgBox[chat])
} // else log('Getting window','"'+chat+'"')
if(switchto === true){
switchToBox(chat)
}
return msgBox[chat]
}
// What happens when the user submits a command in the prompt
cmdline.on('submit',function(value){
msgBox[statusWindow].add('< '+value)
if(selectedWindow === statusWindow || nameToObj(selectedWindow) === undefined){
//log('Window:',selectedWindow,'Eval cmd:',value)
command(value)
} else if(value.indexOf('//') === 0){
sendMsg(selectedWindow,value.substring(1))
} else if(value.indexOf('/') === 0){
command(value.substring(1))
} else {
sendMsg(selectedWindow,value)
}
cmdline.clearValue()
cmdline.focus()
})
//cmdline.focus() // make sure prompt is focused
function quit(){
if(connected || client != undefined){
log('Closing communications and shutting down...')
client.end(function(){
process.exit(0)
})
} else process.exit(0);
}
// Catch ctrl-c or escape event and close program
screen.key(['escape','C-c'], function(ch,key){
quit()
});
function nameToObj(name){
var id = gnameToGid[name]
if(groups[id] && groups[id].title === name)
return groups[id]
else {
id = unameToUid[name]
return contacts[id]
}
}
function idToPeer(uid,type){
if(type === 'user')
return new telegramLink.type.InputPeerContact({ props: { user_id: ''+uid } })
else if(type === 'group')
return new telegramLink.type.InputPeerChat({ props: { chat_id: ''+uid } })
}
// Send a message // Send a message
function sendMsg(name,str){ data.sendMsg = function(name,str){
if(!connected){ if(!data.connected){
return log('Error: not ready to send messages') return log('Error: not ready to send messages')
} }
var peer = idToPeer(nameToObj(name).id,nameToObj(name).title?'group':'user') var obj = data.nameToObj(name)
var peer = data.idToPeer(obj.id,obj.title?'group':'user')
var randid = parseInt(Math.random() * 1000000000) var randid = parseInt(Math.random() * 1000000000)
//log('Sending Message to:',peer.toPrintable()) //log('Sending Message to:',peer.toPrintable())
client.messages.sendMessage(peer,str,randid,function(sent){ data.client.messages.sendMessage(peer,str,randid,function(sent){
//log('Sent message:','"'+str+'"','to:',selectedWindow+':',sent.toPrintable()) //log('Sent message:','"'+str+'"','to:',selectedWindow+':',sent.toPrintable())
}) })
} }
// Connects to telegram // Connects to telegram
function connect(){ data.connect = function(){
client = telegramLink.createClient(app, telegramLink.PROD_PRIMARY_DC, function(){ data.client = data.telegramLink.createClient(data.app, data.telegramLink.PROD_PRIMARY_DC, function(){
if(!app.authKey){ if(!data.app.authKey){
log('Downloading Authorization Key...') log('Downloading Authorization Key...')
client.createAuthKey(function(auth){ data.client.createAuthKey(function(auth){
authKey = auth.key.encrypt('password') // I know sorry, but I'm testing. Will add security later, I promise data.app.authKey = auth.key.encrypt('password') // Will add security later, I promise
// Writes the new encrypted key to disk // Writes the new encrypted key to disk
log('Ready for phone number, use command: phone <number>') data.log('Ready for phone number, use command: phone <number>')
}) })
} else { } else {
whenReady() data.whenReady()
} }
}) })
client.once('dataCenter',function(dcs){ data.client.once('dataCenter',function(dcs){
log('Datacenters:',dcs.toPrintable()) data.log('Datacenters:',dcs.toPrintable())
}) })
} }
// Executed when connected and logged in // Executed when connected and logged in
function whenReady(){ data.whenReady = function(){
log('READY!') data.log('READY!')
connected = true data.connected = true
downloadData() data.downloadData()
} }
// Downloads stuff // Downloads stuff
function downloadData(){ data.downloadData = function(){
log('Downloading data...') data.log('Downloading data...')
client.contacts.getContacts('',function(cont){ data.client.contacts.getContacts('',function(cont){
chats.clearItems() data.chats.clearItems()
chats.add(statusWindow) data.chats.add(data.statusWindow)
cont.users.list.forEach(addUser) cont.users.list.forEach(data.addUser)
}) })
client.messages.getDialogs(0,0,10,function(dialogs){ data.client.messages.getDialogs(0,0,10,function(dialogs){
if(dialogs && dialogs.chats && dialogs.chats.list) if(dialogs && dialogs.chats && dialogs.chats.list)
dialogs.chats.list.forEach(addGroup) dialogs.chats.list.forEach(data.addGroup)
}) })
client.updates.getState(function(astate){ data.client.updates.getState(function(astate){
updateState(astate) data.updateState(astate)
log(state.unreadCount,'unread messages') data.log(data.state.unreadCount,'unread messages')
log('Started receiving updates') data.log('Started receiving updates')
// Can't use registerOnUpdates because it's apparently broken // Can't use registerOnUpdates because it's apparently broken
//client.registerOnUpdates(onUpdate) //client.registerOnUpdates(onUpdate)
setTimeout(downloadUpdates,1000) setTimeout(data.downloadUpdates,1000)
}) })
} }
function addUser(u){ data.downloadUpdates = function(){
if(!user || !user.id) return log("Can't add invalid user object to contacts",u) data.client.updates.getDifference(data.state.pts,data.state.date,data.state.qts,function(res){
contacts[u.id] = { user: u, id: u.id}
var name = getName(u.id,'user')
unameToUid[name] = u.id
if(!chats.getItem(name)) chats.addItem(name)
}
function addGroup(group){
if(groups[group.id]) return;
if(group.left === true) return;
if(group.title === undefined){
return log('Undefined group title in group ',group)
}
groups[group.id] = { id: group.id, title: group.title }
gnameToGid[group.title] = group.id
if(!chats.getItem(group.title)) chats.addItem(group.title)
}
// Updates the current state
function updateState(newstate){
state.pts = newstate.pts
state.qts = newstate.qts
state.date = newstate.date
state.sqp = newstate.seq
state.unreadCount = newstate.unread_count
}
// process an update
function onUpdate(upd){
log('Got Update:',upd.toPrintable())
}
function downloadUpdates(){
client.updates.getDifference(state.pts,state.date,state.qts,function(res){
if(!res.instanceOf('api.type.updates.DifferenceEmpty')){ if(!res.instanceOf('api.type.updates.DifferenceEmpty')){
//log('Got Diff: ',res.toPrintable()) //log('Got Diff: ',res.toPrintable())
if(res.state){ if(res.state){
updateState(res.state) data.updateState(res.state)
} }
if(res.chats) if(res.chats)
for(c in res.chats.list) addGroup(c) for(c in res.chats.list) data.addGroup(c)
if(res.users) if(res.users)
for(c in res.users.list) addUser(c) for(c in res.users.list) data.addUser(c)
if(res.new_messages){ if(res.new_messages){
res.new_messages.list.forEach(function(msg){ res.new_messages.list.forEach(function(msg){
appendMsg(msg,undefined,false,true) data.appendMsg(msg,undefined,false,true)
}) })
} }
} }
setTimeout(downloadUpdates,1000) setTimeout(data.downloadUpdates,1000)
}) })
} }
function nameForUser(u){
return u.first_name + ' ' + u.last_name + (u.username?' (@'+u.username+')':'')
}
function getName(id,type){
if(id === user.id) return nameForUser(user)
else if(type === undefined) throw new Error('no type')
else if(type === 'group' && groups[id])
return groups[id].title
else if(type === 'user' && contacts[id])
return nameForUser(contacts[id].user)
else log('Failed to find name for',type,id)
}
// Get message history with given name in the given box // Get message history with given name in the given box
function getMessages(name,box){ data.getMessages = function(name,box){
if(!connected){ if(!data.connected){
return log('Uh cant get messages cuz not connected.....') return log('Uh cant get messages cuz not connected.....')
} }
//log('Name to obj:',name) //log('Name to obj:',name)
var obj = nameToObj(name) var obj = data.nameToObj(name)
if(!obj || !obj.id){ if(!obj || !obj.id){
return log("Can't get messages",obj,obj.id,obj.title) return data.log("Can't get messages",obj,obj.id,obj.title)
} }
var type = obj.title?'group':'user' var type = obj.title?'group':'user'
var peer = idToPeer(obj.id,type) var peer = data.idToPeer(obj.id,type)
box.add('Downloading message history for '+name) box.add('Downloading message history for '+name)
if(!peer) return log('Could not find peer:',name) if(!peer) return log('Could not find peer:',name)
client.messages.getHistory(peer,0,-1,20,function(res){ data.client.messages.getHistory(peer,0,-1,20,function(res){
//log(res.toPrintable()) //log(res.toPrintable())
//log('Got history for: '+getName(peer.user_id||peer.chat_id,peer.chat_id?'group':'user')) //log('Got history for: '+getName(peer.user_id||peer.chat_id,peer.chat_id?'group':'user'))
if(!res.messages){ if(!res.messages){
@ -455,62 +226,62 @@ function getMessages(name,box){
return msg1.date - msg2.date return msg1.date - msg2.date
}) })
if(res.messages.list.length === 0) if(res.messages.list.length === 0)
return appendToUserBox('No messages.',res) return data.appendToUserBox('No messages.',res)
res.messages.list.forEach(function(msg){ res.messages.list.forEach(function(msg){
//if(!msg.message) return log('Empty message!',msg.toPrintable()) //if(!msg.message) return log('Empty message!',msg.toPrintable())
//log('Scheduling message: '+msg.toPrintable()) //log('Scheduling message: '+msg.toPrintable())
appendMsg(msg) data.appendMsg(msg)
}) })
}) })
} }
function appendToUserBox(msg,context){ data.appendToUserBox = function(msg,context){
var goesto var goesto
if(context.messages.list.length > 0){ if(context.messages.list.length > 0){
if(context.messages.list[0].to_id.chat_id){ if(context.messages.list[0].to_id.chat_id){
// Group message // Group message
log('Chose',getName(context.messages.list[0].to_id.chat_id,'group')) data.log('Chose',data.getName(context.messages.list[0].to_id.chat_id,'group'))
goesto = getMsgBox(getName(context.messages.list[0].to_id.chat_id)) goesto = data.getMsgBox(data.getName(context.messages.list[0].to_id.chat_id))
} }
} }
if(goesto === undefined){ if(goesto === undefined){
if(context.users.list[0].user_id == user.id){ if(context.users.list[0].user_id == user.id){
goesto = getMsgBox(getName(context.users.list[1].id,'user')) goesto = data.getMsgBox(getName(context.users.list[1].id,'user'))
} else{ } else{
goesto = getMsgBox(getName(context.users.list[0].id,'user')) goesto = data.getMsgBox(getName(context.users.list[0].id,'user'))
} }
} }
appendMsg(msg,goesto,true) data.appendMsg(msg,goesto,true)
} }
// Writes given telegram.link "message" object to given boxId // Writes given telegram.link "message" object to given boxId
function appendMsg(msg,toBoxId,bare,smartmode){ data.appendMsg = function(msg,toBoxId,bare,smartmode){
var box,param var box,param
if(toBoxId != undefined){ if(toBoxId != undefined){
box = toBoxId box = toBoxId
} else { } else {
if(msg.to_id.chat_id != undefined){ if(msg.to_id.chat_id != undefined){
// Is a group // Is a group
param = getName(msg.to_id.chat_id,'group') param = data.getName(msg.to_id.chat_id,'group')
} else if(msg.from_id === msg.to_id.user_id || msg.from_id != user.id){ } else if(msg.from_id === msg.to_id.user_id || msg.from_id != user.id){
param = getName(msg.from_id,'user') param = data.getName(msg.from_id,'user')
} else if(msg.to_id.user_id != undefined && msg.to_id.user_id != user.id) { } else if(msg.to_id.user_id != undefined && msg.to_id.user_id != user.id) {
// don't forget dat .user_id! don't need it in from_id... // don't forget dat .user_id! don't need it in from_id...
param = getName(msg.to_id.user_id,'user') param = data.getName(msg.to_id.user_id,'user')
} }
if(smartmode && !bare){ if(smartmode && !bare){
// Smart mode doesn't append the message to the box if it doesn't exist // Smart mode doesn't append the message to the box if it doesn't exist
// because when created, the box will download message history // because when created, the box will download message history
if(msgBox[param] === undefined) return; if(data.msgBox[param] === undefined) return;
} }
box = getMsgBox(param) box = data.getMsgBox(param)
} }
if(bare) if(bare)
box.add(msg) box.add(msg)
else { else {
var from = msg.from_id var from = msg.from_id
var date = moment.unix(msg.date).fromNow() var date = moment.unix(msg.date).fromNow()
name = getName(from,'user') name = data.getName(from,'user')
var txt var txt
if(msg.media){ if(msg.media){
if(msg.media.photo) if(msg.media.photo)
@ -527,34 +298,34 @@ function appendMsg(msg,toBoxId,bare,smartmode){
// - Entry Point - // - Entry Point -
// Load authKey and userdata from disk, then act depending on outcome // Load authKey and userdata from disk, then act depending on outcome
var keyPath = cfgDir+'key' data.screen.render()
log('Loading files...') var keyPath = data.cfgDir+'key'
data.log('Loading files...')
fs.exists(keyPath,function(exists){ fs.exists(keyPath,function(exists){
if(exists){ if(exists){
//log('Authorization Key found') //log('Authorization Key found')
fs.readFile(keyPath,function(err,content){ fs.readFile(keyPath,function(err,content){
if(err) if(err)
log('Error while reading key:',err) data.log('Error while reading key:',err)
else { else {
authKey = telegramLink.retrieveAuthKey(content,'password') // yeah sorry just testing data.app.authKey = data.telegramLink.retrieveAuthKey(content,'password') // yeah sorry just testing
app.authKey = authKey data.log('Authorization Key found')
log('Authorization Key found') fs.readFile(data.cfgDir+'user_data.json',function(err,res){
fs.readFile(cfgDir+'user_data.json',function(err,data){
if(err) if(err)
log("FATAL: couldn't read user_data.json") data.log("FATAL: couldn't read user_data.json")
else { else {
try { try {
user = JSON.parse(data) data.user = JSON.parse(res)
log('Welcome',getName(user.id,'user')) data.log('Welcome',data.getName(data.user.id,'user'))
connect()
} catch (e) { } catch (e) {
log("FATAL: user data corrupted:",e) data.log("FATAL: user data corrupted:",e)
} }
data.connect()
} }
}) })
} }
}) })
} else { } else {
connect() data.connect()
} }
}) })