db - offline messaging, refactoring

This commit is contained in:
ingvar1995 2016-06-14 00:32:45 +03:00
parent f6affc14ef
commit 7e63d9634a
5 changed files with 174 additions and 132 deletions

View file

@ -114,8 +114,19 @@ class History(object):
finally: finally:
db.close() db.close()
def update_messages(self, tox_id, count): def update_messages(self, tox_id, unsent_time):
# TODO: mark all unsent messages to friend with specified public key :tox_id (except last :count) as sent chdir(settings.ProfileHelper.get_path())
db = connect(self._name + '.hstr')
try:
cursor = db.cursor()
cursor.execute('UPDATE id' + tox_id + ' SET owner = 0 '
'WHERE unix_time < ' + str(unsent_time) + ' AND owner = 2;')
db.commit()
except:
db.rollback()
raise
finally:
db.close()
pass pass
def delete_messages(self, tox_id): def delete_messages(self, tox_id):

View file

@ -3,65 +3,9 @@
from menu import * from menu import *
from profile import * from profile import *
from list_items import * from list_items import *
from widgets import QRightClickButton, RubberBand, create_menu, MultilineEdit from widgets import QRightClickButton, RubberBand, MultilineEdit
import plugin_support import plugin_support
from mainscreen_widgets import *
class MessageArea(QtGui.QPlainTextEdit):
"""User enters messages here"""
def __init__(self, parent, form):
super(MessageArea, self).__init__(parent)
self.parent = form
self.setAcceptDrops(True)
self.timer = QtCore.QTimer(self)
self.timer.timeout.connect(lambda: self.parent.profile.send_typing(False))
def keyPressEvent(self, event):
if event.matches(QtGui.QKeySequence.Paste):
self.pasteEvent()
elif event.key() in (QtCore.Qt.Key_Return, QtCore.Qt.Key_Enter):
modifiers = event.modifiers()
if modifiers & QtCore.Qt.ControlModifier or modifiers & QtCore.Qt.ShiftModifier:
self.insertPlainText('\n')
else:
if self.timer.isActive():
self.timer.stop()
self.parent.profile.send_typing(False)
self.parent.send_message()
elif event.key() == QtCore.Qt.Key_Up and not self.toPlainText():
self.appendPlainText(Profile.get_instance().get_last_message())
else:
self.parent.profile.send_typing(True)
if self.timer.isActive():
self.timer.stop()
self.timer.start(5000)
super(MessageArea, self).keyPressEvent(event)
def contextMenuEvent(self, event):
menu = create_menu(self.createStandardContextMenu())
menu.exec_(event.globalPos())
del menu
def dragEnterEvent(self, e):
e.accept()
def dragMoveEvent(self, e):
e.accept()
def dropEvent(self, e):
if e.mimeData().hasFormat('text/plain'):
e.accept()
self.pasteEvent(e.mimeData().text())
else:
e.ignore()
def pasteEvent(self, text=None):
text = text or QtGui.QApplication.clipboard().text()
if text.startswith('file://'):
self.parent.profile.send_file(text[7:])
else:
self.insertPlainText(text)
class MainWindow(QtGui.QMainWindow): class MainWindow(QtGui.QMainWindow):
@ -542,7 +486,10 @@ class MainWindow(QtGui.QMainWindow):
user = u'{} {}'.format(user, friend.name) user = u'{} {}'.format(user, friend.name)
def save_note(text): def save_note(text):
s['notes'][friend.tox_id] = text if friend.tox_id in s['notes']:
del s['notes'][friend.tox_id]
if text:
s['notes'][friend.tox_id] = text
s.save() s.save()
self.note = MultilineEdit(user, note, save_note) self.note = MultilineEdit(user, note, save_note)
self.note.show() self.note.show()
@ -589,61 +536,3 @@ class MainWindow(QtGui.QMainWindow):
def filtering(self): def filtering(self):
self.profile.filtration(self.online_contacts.currentIndex() == 1, self.contact_name.text()) self.profile.filtration(self.online_contacts.currentIndex() == 1, self.contact_name.text())
class ScreenShotWindow(QtGui.QWidget):
def __init__(self, parent):
super(ScreenShotWindow, self).__init__()
self.parent = parent
self.setMouseTracking(True)
self.setWindowFlags(self.windowFlags() | QtCore.Qt.FramelessWindowHint | QtCore.Qt.WindowStaysOnTopHint)
self.showFullScreen()
self.setWindowOpacity(0.5)
self.rubberband = RubberBand()
def closeEvent(self, *args):
if self.parent.isHidden():
self.parent.show()
def mousePressEvent(self, event):
self.origin = event.pos()
self.rubberband.setGeometry(QtCore.QRect(self.origin, QtCore.QSize()))
self.rubberband.show()
QtGui.QWidget.mousePressEvent(self, event)
def mouseMoveEvent(self, event):
if self.rubberband.isVisible():
self.rubberband.setGeometry(QtCore.QRect(self.origin, event.pos()).normalized())
left = QtGui.QRegion(QtCore.QRect(0, 0, self.rubberband.x(), self.height()))
right = QtGui.QRegion(QtCore.QRect(self.rubberband.x() + self.rubberband.width(), 0, self.width(), self.height()))
top = QtGui.QRegion(0, 0, self.width(), self.rubberband.y())
bottom = QtGui.QRegion(0, self.rubberband.y() + self.rubberband.height(), self.width(), self.height())
self.setMask(left + right + top + bottom)
def mouseReleaseEvent(self, event):
if self.rubberband.isVisible():
self.rubberband.hide()
rect = self.rubberband.geometry()
print rect
if rect.width() and rect.height():
p = QtGui.QPixmap.grabWindow(QtGui.QApplication.desktop().winId(),
rect.x() + 4,
rect.y() + 4,
rect.width() - 8,
rect.height() - 8)
byte_array = QtCore.QByteArray()
buffer = QtCore.QBuffer(byte_array)
buffer.open(QtCore.QIODevice.WriteOnly)
p.save(buffer, 'PNG')
Profile.get_instance().send_screenshot(str(byte_array.data()))
self.close()
def keyPressEvent(self, event):
if event.key() == QtCore.Qt.Key_Escape:
self.rubberband.setHidden(True)
self.close()
else:
super(ScreenShotWindow, self).keyPressEvent(event)

119
src/mainscreen_widgets.py Normal file
View file

@ -0,0 +1,119 @@
try:
from PySide import QtCore, QtGui
except ImportError:
from PyQt4 import QtCore, QtGui
from widgets import RubberBand, create_menu
from profile import Profile
class MessageArea(QtGui.QPlainTextEdit):
"""User enters messages here"""
def __init__(self, parent, form):
super(MessageArea, self).__init__(parent)
self.parent = form
self.setAcceptDrops(True)
self.timer = QtCore.QTimer(self)
self.timer.timeout.connect(lambda: self.parent.profile.send_typing(False))
def keyPressEvent(self, event):
if event.matches(QtGui.QKeySequence.Paste):
self.pasteEvent()
elif event.key() in (QtCore.Qt.Key_Return, QtCore.Qt.Key_Enter):
modifiers = event.modifiers()
if modifiers & QtCore.Qt.ControlModifier or modifiers & QtCore.Qt.ShiftModifier:
self.insertPlainText('\n')
else:
if self.timer.isActive():
self.timer.stop()
self.parent.profile.send_typing(False)
self.parent.send_message()
elif event.key() == QtCore.Qt.Key_Up and not self.toPlainText():
self.appendPlainText(Profile.get_instance().get_last_message())
else:
self.parent.profile.send_typing(True)
if self.timer.isActive():
self.timer.stop()
self.timer.start(5000)
super(MessageArea, self).keyPressEvent(event)
def contextMenuEvent(self, event):
menu = create_menu(self.createStandardContextMenu())
menu.exec_(event.globalPos())
del menu
def dragEnterEvent(self, e):
e.accept()
def dragMoveEvent(self, e):
e.accept()
def dropEvent(self, e):
if e.mimeData().hasFormat('text/plain'):
e.accept()
self.pasteEvent(e.mimeData().text())
else:
e.ignore()
def pasteEvent(self, text=None):
text = text or QtGui.QApplication.clipboard().text()
if text.startswith('file://'):
self.parent.profile.send_file(text[7:])
else:
self.insertPlainText(text)
class ScreenShotWindow(QtGui.QWidget):
def __init__(self, parent):
super(ScreenShotWindow, self).__init__()
self.parent = parent
self.setMouseTracking(True)
self.setWindowFlags(self.windowFlags() | QtCore.Qt.FramelessWindowHint | QtCore.Qt.WindowStaysOnTopHint)
self.showFullScreen()
self.setWindowOpacity(0.5)
self.rubberband = RubberBand()
def closeEvent(self, *args):
if self.parent.isHidden():
self.parent.show()
def mousePressEvent(self, event):
self.origin = event.pos()
self.rubberband.setGeometry(QtCore.QRect(self.origin, QtCore.QSize()))
self.rubberband.show()
QtGui.QWidget.mousePressEvent(self, event)
def mouseMoveEvent(self, event):
if self.rubberband.isVisible():
self.rubberband.setGeometry(QtCore.QRect(self.origin, event.pos()).normalized())
left = QtGui.QRegion(QtCore.QRect(0, 0, self.rubberband.x(), self.height()))
right = QtGui.QRegion(QtCore.QRect(self.rubberband.x() + self.rubberband.width(), 0, self.width(), self.height()))
top = QtGui.QRegion(0, 0, self.width(), self.rubberband.y())
bottom = QtGui.QRegion(0, self.rubberband.y() + self.rubberband.height(), self.width(), self.height())
self.setMask(left + right + top + bottom)
def mouseReleaseEvent(self, event):
if self.rubberband.isVisible():
self.rubberband.hide()
rect = self.rubberband.geometry()
print rect
if rect.width() and rect.height():
p = QtGui.QPixmap.grabWindow(QtGui.QApplication.desktop().winId(),
rect.x() + 4,
rect.y() + 4,
rect.width() - 8,
rect.height() - 8)
byte_array = QtCore.QByteArray()
buffer = QtCore.QBuffer(byte_array)
buffer.open(QtCore.QIODevice.WriteOnly)
p.save(buffer, 'PNG')
Profile.get_instance().send_screenshot(str(byte_array.data()))
self.close()
def keyPressEvent(self, event):
if event.key() == QtCore.Qt.Key_Escape:
self.rubberband.setHidden(True)
self.close()
else:
super(ScreenShotWindow, self).keyPressEvent(event)

View file

@ -382,8 +382,9 @@ class Profile(contact.Contact, Singleton):
if not self._history.friend_exists_in_db(friend.tox_id): if not self._history.friend_exists_in_db(friend.tox_id):
self._history.add_friend_to_db(friend.tox_id) self._history.add_friend_to_db(friend.tox_id)
self._history.save_messages_to_db(friend.tox_id, messages) self._history.save_messages_to_db(friend.tox_id, messages)
unsent_count = len(friend.unsent_messages()) unsent_messages = friend.unsent_messages()
self._history.update_messages(friend.tox_id, unsent_count) unsent_time = unsent_messages[0].get_data()[2] if len(unsent_messages) else time.time() + 1
self._history.update_messages(friend.tox_id, unsent_time)
self._history.save() self._history.save()
del self._history del self._history

View file

@ -13,28 +13,35 @@ class SmileyLoader(util.Singleton):
""" """
def __init__(self, settings): def __init__(self, settings):
self.settings = settings self._settings = settings
self.curr_pack = None # current pack name self._curr_pack = None # current pack name
self.smileys = {} # smileys dict. key - smiley (str), value - path to image (str) self._smileys = {} # smileys dict. key - smiley (str), value - path to image (str)
self._set = {} # smileys dict without duplicates
self.load_pack() self.load_pack()
def load_pack(self): def load_pack(self):
""" """
Loads smiley pack Loads smiley pack
""" """
pack_name = self.settings['smiley_pack'] pack_name = self._settings['smiley_pack']
if self.settings['smileys'] and self.curr_pack != pack_name: if self._settings['smileys'] and self._curr_pack != pack_name:
self.curr_pack = pack_name self._curr_pack = pack_name
path = self.get_smileys_path() + 'config.json' path = self.get_smileys_path() + 'config.json'
try: try:
with open(path) as fl: with open(path) as fl:
self.smileys = json.loads(fl.read()) self._smileys = json.loads(fl.read())
print 'Smiley pack', pack_name, 'loaded' print 'Smiley pack', pack_name, 'loaded'
self._set = {}
for key, value in self._smileys.items():
if value not in self._set.values():
self._set[key] = value
except: except:
self._smileys = {}
self._set = {}
print 'Smiley pack', pack_name, 'was not loaded' print 'Smiley pack', pack_name, 'was not loaded'
def get_smileys_path(self): def get_smileys_path(self):
return util.curr_directory() + '/smileys/' + self.curr_pack + '/' return util.curr_directory() + '/smileys/' + self._curr_pack + '/'
def get_packs_list(self): def get_packs_list(self):
d = util.curr_directory() + '/smileys/' d = util.curr_directory() + '/smileys/'
@ -47,13 +54,28 @@ class SmileyLoader(util.Singleton):
:param edit: MessageEdit instance :param edit: MessageEdit instance
:return text with smileys :return text with smileys
""" """
if not self.settings['smileys']: if not self._settings['smileys']:
return text return text
arr = text.split(' ') arr = text.split(' ')
for i in range(len(arr)): for i in range(len(arr)):
if arr[i] in self.smileys: if arr[i] in self._smileys:
file_name = self.smileys[arr[i]] # image name file_name = self._smileys[arr[i]] # image name
arr[i] = u'<img title=\"{}\" src=\"{}\" />'.format(arr[i], file_name) arr[i] = u'<img title=\"{}\" src=\"{}\" />'.format(arr[i], file_name)
if file_name.endswith('.gif'): # animated smiley if file_name.endswith('.gif'): # animated smiley
edit.addAnimation(QtCore.QUrl(file_name), self.get_smileys_path() + file_name) edit.addAnimation(QtCore.QUrl(file_name), self.get_smileys_path() + file_name)
return ' '.join(arr) return ' '.join(arr)
def sticker_loader():
"""
:return dict of stickers
"""
result = {}
d = util.curr_directory() + '/stickers/'
keys = [x[1] for x in os.walk(d)][0]
for key in keys:
path = d + key
files = [f for f in os.listdir(path)]
if files:
result[key] = files
return result