This commit is contained in:
ingvar1995 2016-04-26 20:42:20 +03:00
parent 822b25fcdb
commit 6a82b7d285
5 changed files with 47 additions and 33 deletions

View File

@ -46,6 +46,8 @@ size <file_name> - get size of file (get access)
get <file_name> - get file with specified filename (get access) get <file_name> - get file with specified filename (get access)
get --all - get all files (get access)
stats - show statistics (write access) stats - show statistics (write access)
del <file_name> - remove file with specified filename (delete access) del <file_name> - remove file with specified filename (delete access)

62
bot.py
View File

@ -17,7 +17,7 @@ class Bot(Singleton):
super(Bot, self).__init__() super(Bot, self).__init__()
self._tox = tox self._tox = tox
self._file_transfers = {} # dict of file transfers. key - tuple (friend_number, file_number) self._file_transfers = {} # dict of file transfers. key - tuple (friend_number, file_number)
self._downloads = defaultdict(int) self._downloads = defaultdict(int) # defaultdict of downloads count
# ----------------------------------------------------------------------------------------------------------------- # -----------------------------------------------------------------------------------------------------------------
# Edit current user's data # Edit current user's data
@ -35,10 +35,10 @@ class Bot(Singleton):
def send_message(self, number, message, message_type=TOX_MESSAGE_TYPE['NORMAL']): def send_message(self, number, message, message_type=TOX_MESSAGE_TYPE['NORMAL']):
""" """
Message splitting Send message with message splitting
:param number: friend's number :param number: friend's number
:param message_type: type of message
:param message: message text :param message: message text
:param message_type: type of message
""" """
while len(message) > TOX_MAX_MESSAGE_LENGTH: while len(message) > TOX_MAX_MESSAGE_LENGTH:
size = TOX_MAX_MESSAGE_LENGTH * 4 / 5 size = TOX_MAX_MESSAGE_LENGTH * 4 / 5
@ -65,7 +65,8 @@ class Bot(Singleton):
id = self._tox.friend_get_public_key(friend_num) id = self._tox.friend_get_public_key(friend_num)
settings = Settings.get_instance() settings = Settings.get_instance()
message = message.strip() message = message.strip()
if message == 'files': # message parsing
if message == 'files': # get file list
if id in settings['read']: if id in settings['read']:
s = '' s = ''
for f in os.listdir(settings['folder']): for f in os.listdir(settings['folder']):
@ -77,17 +78,23 @@ class Bot(Singleton):
self.send_message(friend_num, s.encode('utf-8'), TOX_MESSAGE_TYPE['NORMAL']) self.send_message(friend_num, s.encode('utf-8'), TOX_MESSAGE_TYPE['NORMAL'])
else: else:
self.send_message(friend_num, 'Not enough rights'.encode('utf-8')) self.send_message(friend_num, 'Not enough rights'.encode('utf-8'))
elif message.startswith('get '): elif message.startswith('get '): # download file or all files
if id in settings['read']: if id in settings['read']:
path = settings['folder'] + '/' + unicode(message[4:]) if '--all' not in message:
if os.path.exists(unicode(path)): path = settings['folder'] + '/' + unicode(message[4:])
self.send_file(unicode(path), friend_num) if os.path.exists(unicode(path)):
self.send_file(unicode(path), friend_num)
else:
self.send_message(friend_num, 'Wrong file name'.encode('utf-8'))
else: else:
self.send_message(friend_num, 'Wrong file name'.encode('utf-8')) for f in os.listdir(settings['folder']):
if os.path.isfile(os.path.join(settings['folder'], f)):
self.send_file(unicode(os.path.join(settings['folder'], f)), friend_num)
else: else:
self.send_message(friend_num, 'Not enough rights'.encode('utf-8')) self.send_message(friend_num, 'Not enough rights'.encode('utf-8'))
elif message == 'help': elif message == 'help': # help
self.send_message(friend_num, """help - list of commands\n self.send_message(friend_num, """
help - list of commands\n
rights - get access rights\n rights - get access rights\n
files - show list of files (get access)\n files - show list of files (get access)\n
id - get bot's id (get access)\n id - get bot's id (get access)\n
@ -95,6 +102,7 @@ class Bot(Singleton):
share --all <file_name> - send file to all friends (get access)\n share --all <file_name> - send file to all friends (get access)\n
size <file_name> - get size of file (get access)\n size <file_name> - get size of file (get access)\n
get <file_name> - get file with specified filename (get access)\n get <file_name> - get file with specified filename (get access)\n
get --all - get all files (get access)\n
stats - show statistics (write access)\n stats - show statistics (write access)\n
del <file_name> - remove file with specified filename (delete access)\n del <file_name> - remove file with specified filename (delete access)\n
rename <file_name> --new <new_file_name> - rename file (delete access)\n rename <file_name> --new <new_file_name> - rename file (delete access)\n
@ -106,13 +114,13 @@ class Bot(Singleton):
stop - stop bot (masters only)\n stop - stop bot (masters only)\n
Users with write access can send files to bot. Users with write access can send files to bot.
""".encode('utf-8')) """.encode('utf-8'))
elif message == 'rights': elif message == 'rights': # get rights
self.send_message(friend_num, 'Read: {}\nWrite: {}\nDelete: {}\nMaster: {}' self.send_message(friend_num, 'Read: {}\nWrite: {}\nDelete: {}\nMaster: {}'
.format('Yes' if id in settings['read'] else 'No', .format('Yes' if id in settings['read'] else 'No, sorry',
'Yes' if id in settings['write'] else 'No', 'Yes' if id in settings['write'] else 'No',
'Yes' if id in settings['delete'] else 'No', 'Yes' if id in settings['delete'] else 'No',
'Yes, sir!' if id in settings['master'] else 'No')) 'Yes, sir!' if id in settings['master'] else 'No'))
elif message.startswith('del '): elif message.startswith('del '): # delete file
if id in settings['delete']: if id in settings['delete']:
path = settings['folder'] + '/' + message[4:] path = settings['folder'] + '/' + message[4:]
if os.path.exists(path): if os.path.exists(path):
@ -122,7 +130,7 @@ class Bot(Singleton):
self.send_message(friend_num, 'Wrong file name'.encode('utf-8')) self.send_message(friend_num, 'Wrong file name'.encode('utf-8'))
else: else:
self.send_message(friend_num, 'Not enough rights'.encode('utf-8')) self.send_message(friend_num, 'Not enough rights'.encode('utf-8'))
elif message.startswith('user '): elif message.startswith('user '): # new rights for user
if id not in settings['master']: if id not in settings['master']:
self.send_message(friend_num, 'Not enough rights'.encode('utf-8')) self.send_message(friend_num, 'Not enough rights'.encode('utf-8'))
return return
@ -149,17 +157,17 @@ class Bot(Singleton):
settings.save() settings.save()
self.send_message(friend_num, 'Updated'.encode('utf-8')) self.send_message(friend_num, 'Updated'.encode('utf-8'))
elif message.startswith('status '): elif message.startswith('status '): # new status
if id not in settings['master']: if id not in settings['master']:
self.send_message(friend_num, 'Not enough rights'.encode('utf-8')) self.send_message(friend_num, 'Not enough rights'.encode('utf-8'))
else: else:
self.set_status_message(message[7:]) self.set_status_message(message[7:])
elif message.startswith('name '): elif message.startswith('name '): # new name
if id not in settings['master']: if id not in settings['master']:
self.send_message(friend_num, 'Not enough rights'.encode('utf-8')) self.send_message(friend_num, 'Not enough rights'.encode('utf-8'))
else: else:
self.set_name(message[5:]) self.set_name(message[5:])
elif message.startswith('share '): elif message.startswith('share '): # send file to friend (all friends)
if id in settings['read']: if id in settings['read']:
if '--all' not in message: if '--all' not in message:
fl = ' '.join(message.split(' ')[2:]) fl = ' '.join(message.split(' ')[2:])
@ -177,7 +185,7 @@ class Bot(Singleton):
self.send_file(settings['folder'] + '/' + fl, num) self.send_file(settings['folder'] + '/' + fl, num)
else: else:
self.send_message(friend_num, 'Not enough rights'.encode('utf-8')) self.send_message(friend_num, 'Not enough rights'.encode('utf-8'))
elif message.startswith('rename '): elif message.startswith('rename '): # rename existing file
ind = message.index(' --new ') ind = message.index(' --new ')
old = message[7:ind] old = message[7:ind]
new = message[ind + 7:] new = message[ind + 7:]
@ -189,13 +197,13 @@ class Bot(Singleton):
self.send_message(friend_num, 'File not found'.encode('utf-8')) self.send_message(friend_num, 'File not found'.encode('utf-8'))
else: else:
self.send_message(friend_num, 'Not enough rights'.encode('utf-8')) self.send_message(friend_num, 'Not enough rights'.encode('utf-8'))
elif message == 'id': elif message == 'id': # get TOX ID
if id in settings['read']: if id in settings['read']:
tox_id = self._tox.self_get_address() tox_id = self._tox.self_get_address()
self.send_message(friend_num, tox_id.encode('utf-8')) self.send_message(friend_num, tox_id.encode('utf-8'))
else: else:
self.send_message(friend_num, 'Not enough rights'.encode('utf-8')) self.send_message(friend_num, 'Not enough rights'.encode('utf-8'))
elif message.startswith('size '): elif message.startswith('size '): # get file size
path = unicode(settings['folder'] + '/' + message[5:]) path = unicode(settings['folder'] + '/' + message[5:])
if id not in settings['read']: if id not in settings['read']:
self.send_message(friend_num, 'Not enough rights'.encode('utf-8')) self.send_message(friend_num, 'Not enough rights'.encode('utf-8'))
@ -209,9 +217,9 @@ class Bot(Singleton):
size = u'{} KB'.format(bytes_size / 1024) size = u'{} KB'.format(bytes_size / 1024)
else: else:
size = u'{} MB'.format(bytes_size / 1024 * 1024) size = u'{} MB'.format(bytes_size / 1024 * 1024)
s = u'size: {} ({} bytes)'.format(size, bytes_size) s = u'Size: {} ({} bytes)'.format(size, bytes_size)
self.send_message(friend_num, s.encode('utf-8')) self.send_message(friend_num, s.encode('utf-8'))
elif message.startswith('message '): elif message.startswith('message '): # send message to friend (all friends)
if id not in settings['master']: if id not in settings['master']:
self.send_message(friend_num, 'Not enough rights'.encode('utf-8')) self.send_message(friend_num, 'Not enough rights'.encode('utf-8'))
elif '--all' not in message: elif '--all' not in message:
@ -227,7 +235,7 @@ class Bot(Singleton):
for num in self._tox.self_get_friend_list(): for num in self._tox.self_get_friend_list():
if self._tox.friend_get_connection_status(num): if self._tox.friend_get_connection_status(num):
self.send_message(num, s.encode('utf-8')) self.send_message(num, s.encode('utf-8'))
elif message == 'stats': elif message == 'stats': # get stats
if id not in settings['write']: if id not in settings['write']:
self.send_message(friend_num, 'Not enough rights'.encode('utf-8')) self.send_message(friend_num, 'Not enough rights'.encode('utf-8'))
else: else:
@ -247,7 +255,7 @@ class Bot(Singleton):
count += 1 count += 1
s = 'Friends: {}\nOnline friends: {}\nFiles:\n'.format(self._tox.self_get_friend_list_size(), count) + s s = 'Friends: {}\nOnline friends: {}\nFiles:\n'.format(self._tox.self_get_friend_list_size(), count) + s
self.send_message(friend_num, s.encode('utf-8'), TOX_MESSAGE_TYPE['NORMAL']) self.send_message(friend_num, s.encode('utf-8'), TOX_MESSAGE_TYPE['NORMAL'])
elif message == 'stop': elif message == 'stop': # stop bot
if id in settings['master']: if id in settings['master']:
settings.save() settings.save()
data = self._tox.get_savedata() data = self._tox.get_savedata()
@ -269,8 +277,9 @@ class Bot(Singleton):
:param tox_id: tox id of contact :param tox_id: tox id of contact
:param message: message :param message: message
""" """
self._tox.friend_add_norequest(tox_id) # num - friend number self._tox.friend_add_norequest(tox_id)
settings = Settings.get_instance() settings = Settings.get_instance()
# give friend default rights
if 'r' in settings['auto_rights'] and tox_id not in settings['read']: if 'r' in settings['auto_rights'] and tox_id not in settings['read']:
settings['read'].append(tox_id) settings['read'].append(tox_id)
if 'w' in settings['auto_rights'] and tox_id not in settings['write']: if 'w' in settings['auto_rights'] and tox_id not in settings['write']:
@ -341,6 +350,7 @@ class Bot(Singleton):
""" """
Send file to current active friend Send file to current active friend
:param path: file path :param path: file path
:param friend_number: friend_number
""" """
self._downloads[path] += 1 self._downloads[path] += 1
st = SendTransfer(path, self._tox, friend_number) st = SendTransfer(path, self._tox, friend_number)

10
main.py
View File

@ -13,6 +13,7 @@ class FileBot(object):
self.stop = False self.stop = False
self.profile = None self.profile = None
self.path = path self.path = path
print 'FileBot v0.1'
def main(self): def main(self):
self.tox = tox_factory(ProfileHelper.open_profile(self.path)) self.tox = tox_factory(ProfileHelper.open_profile(self.path))
@ -28,11 +29,10 @@ class FileBot(object):
self.tox.iterate() self.tox.iterate()
time.sleep(self.tox.iteration_interval() / 1000.0) time.sleep(self.tox.iteration_interval() / 1000.0)
except KeyboardInterrupt: except KeyboardInterrupt:
print '' settings.save()
settings.save() data = self.tox.get_savedata()
data = self.tox.get_savedata() ProfileHelper.save_profile(data)
ProfileHelper.save_profile(data) del self.tox
del self.tox
if __name__ == '__main__': if __name__ == '__main__':

View File

@ -1 +1 @@
{"write": ["56A1ADE4B65B86BCD51CC73E2CD4E542179F47959FE3E0E21B4B0ACDADE51855D34D34D37CB5"], "auto_rights": "r", "master": [], "read": ["56A1ADE4B65B86BCD51CC73E2CD4E542179F47959FE3E0E21B4B0ACDADE51855D34D34D37CB5"], "folder": "/home/tox_user/tox/shared", "delete": ["56A1ADE4B65B86BCD51CC73E2CD4E542179F47959FE3E0E21B4B0ACDADE51855D34D34D37CB5"]} {"write": ["56A1ADE4B65B86BCD51CC73E2CD4E542179F47959FE3E0E21B4B0ACDADE51855"], "auto_rights": "r", "master": [], "read": ["56A1ADE4B65B86BCD51CC73E2CD4E542179F47959FE3E0E21B4B0ACDADE51855"], "folder": "/home/tox_user/tox/shared", "delete": ["56A1ADE4B65B86BCD51CC73E2CD4E542179F47959FE3E0E21B4B0ACDADE51855"]}

View File

@ -16,11 +16,13 @@ class Settings(Singleton, dict):
super(self.__class__, self).__init__(json.loads(data)) super(self.__class__, self).__init__(json.loads(data))
else: else:
super(self.__class__, self).__init__(Settings.get_default_settings()) super(self.__class__, self).__init__(Settings.get_default_settings())
self.save()
self['read'] = map(lambda x: x[:TOX_PUBLIC_KEY_SIZE * 2], set(self['read'])) self['read'] = map(lambda x: x[:TOX_PUBLIC_KEY_SIZE * 2], set(self['read']))
self['write'] = map(lambda x: x[:TOX_PUBLIC_KEY_SIZE * 2], set(self['write'])) self['write'] = map(lambda x: x[:TOX_PUBLIC_KEY_SIZE * 2], set(self['write']))
self['delete'] = map(lambda x: x[:TOX_PUBLIC_KEY_SIZE * 2], set(self['delete'])) self['delete'] = map(lambda x: x[:TOX_PUBLIC_KEY_SIZE * 2], set(self['delete']))
self['master'] = map(lambda x: x[:TOX_PUBLIC_KEY_SIZE * 2], set(self['master'])) self['master'] = map(lambda x: x[:TOX_PUBLIC_KEY_SIZE * 2], set(self['master']))
if self['folder'][-1] == '/' or self['folder'][-1] == '\\':
self['folder'] = self['folder'][:-1]
self.save()
@staticmethod @staticmethod
def get_default_settings(): def get_default_settings():