Now the buttons in the buffers are connected to their functions; datetime and languageHandler improvements.

This commit is contained in:
Manuel Cortez 2015-01-05 06:05:31 -06:00
parent 32884d3bf2
commit a84d35c6af
8 changed files with 83 additions and 170 deletions

View File

@ -1,13 +1,14 @@
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
import wx import wx
import widgetUtils import widgetUtils
import datetime import arrow
import webbrowser import webbrowser
import output import output
import config import config
import sound import sound
import messages import messages
from twitter import compose, prettydate, utils import languageHandler
from twitter import compose, utils
from wxUI import buffers, dialogs, commonMessageDialogs from wxUI import buffers, dialogs, commonMessageDialogs
from mysc.thread_utils import call_threaded from mysc.thread_utils import call_threaded
from twython import TwythonError from twython import TwythonError
@ -98,6 +99,17 @@ class bufferController(object):
def destroy_status(self): def destroy_status(self):
pass pass
def post_tweet(self, *args, **kwargs):
title = _(u"Tweet")
caption = _(u"Write the tweet here")
tweet = messages.tweet(self.session, title, caption, "")
if tweet.message.get_response() == widgetUtils.OK:
text = tweet.message.get_text()
if tweet.image == None:
call_threaded(buffer.session.api_call, call_name="update_status", _sound="tweet_send.ogg", status=text)
else:
call_threaded(buffer.session.api_call, call_name="update_status_with_media", _sound="tweet_send.ogg", status=text, media=tweet.image)
class accountPanel(bufferController): class accountPanel(bufferController):
def __init__(self, parent, name, account): def __init__(self, parent, name, account):
super(accountPanel, self).__init__(parent, None, name) super(accountPanel, self).__init__(parent, None, name)
@ -174,6 +186,11 @@ class baseBufferController(bufferController):
def bind_events(self): def bind_events(self):
self.buffer.list.list.Bind(wx.EVT_LIST_ITEM_FOCUSED, self.onFocus) self.buffer.list.list.Bind(wx.EVT_LIST_ITEM_FOCUSED, self.onFocus)
self.buffer.list.list.Bind(wx.EVT_CHAR_HOOK, self.get_event) self.buffer.list.list.Bind(wx.EVT_CHAR_HOOK, self.get_event)
widgetUtils.connect_event(self.buffer, widgetUtils.BUTTON_PRESSED, self.post_tweet, self.buffer.tweet)
# if self.type == "baseBuffer":
widgetUtils.connect_event(self.buffer, widgetUtils.BUTTON_PRESSED, self.retweet, self.buffer.retweet)
widgetUtils.connect_event(self.buffer, widgetUtils.BUTTON_PRESSED, self.direct_message, self.buffer.dm)
widgetUtils.connect_event(self.buffer, widgetUtils.BUTTON_PRESSED, self.reply, self.buffer.reply)
def get_tweet(self): def get_tweet(self):
if self.session.db[self.name][self.buffer.list.get_selected()].has_key("retweeted_status"): if self.session.db[self.name][self.buffer.list.get_selected()].has_key("retweeted_status"):
@ -186,7 +203,7 @@ class baseBufferController(bufferController):
tweet = self.session.db[self.name][self.buffer.list.get_selected()] tweet = self.session.db[self.name][self.buffer.list.get_selected()]
return tweet return tweet
def reply(self): def reply(self, *args, **kwargs):
tweet = self.get_right_tweet() tweet = self.get_right_tweet()
screen_name = tweet["user"]["screen_name"] screen_name = tweet["user"]["screen_name"]
id = tweet["id"] id = tweet["id"]
@ -198,7 +215,7 @@ class baseBufferController(bufferController):
else: else:
call_threaded(self.session.twitter.api_call, call_name="update_status_with_media", _sound="reply_send.ogg", in_reply_to_status_id=id, status=message.message.get_text(), media=message.file) call_threaded(self.session.twitter.api_call, call_name="update_status_with_media", _sound="reply_send.ogg", in_reply_to_status_id=id, status=message.message.get_text(), media=message.file)
def direct_message(self): def direct_message(self, *args, **kwargs):
tweet = self.get_tweet() tweet = self.get_tweet()
if self.type == "dm": if self.type == "dm":
screen_name = tweet["sender"]["screen_name"] screen_name = tweet["sender"]["screen_name"]
@ -213,7 +230,7 @@ class baseBufferController(bufferController):
if dm.message.get_response() == widgetUtils.OK: if dm.message.get_response() == widgetUtils.OK:
call_threaded(self.session.api_call, call_name="send_direct_message", _sound="dm_sent.ogg", text=dm.message.get_text(), screen_name=dm.message.get("cb")) call_threaded(self.session.api_call, call_name="send_direct_message", _sound="dm_sent.ogg", text=dm.message.get_text(), screen_name=dm.message.get("cb"))
def retweet(self): def retweet(self, *args, **kwargs):
tweet = self.get_right_tweet() tweet = self.get_right_tweet()
id = tweet["id"] id = tweet["id"]
answer = commonMessageDialogs.retweet_question(self.buffer) answer = commonMessageDialogs.retweet_question(self.buffer)
@ -230,8 +247,9 @@ class baseBufferController(bufferController):
def onFocus(self, ev): def onFocus(self, ev):
tweet = self.get_tweet() tweet = self.get_tweet()
if self.session.settings["general"]["relative_times"] == True: if self.session.settings["general"]["relative_times"] == True:
original_date = datetime.datetime.strptime(self.session.db[self.name][self.buffer.list.get_selected()]["created_at"], "%a %b %d %H:%M:%S +0000 %Y") # fix this:
ts = prettydate(original_date) original_date = arrow.get(self.session.db[self.name_buffer][self.list.get_selected()]["created_at"], "ddd MMM D H:m:s Z YYYY", locale="en")
ts = original_date.humanize(locale=languageHandler.getLanguage())
self.buffer.list.list.SetStringItem(self.buffer.list.get_selected(), 2, ts) self.buffer.list.list.SetStringItem(self.buffer.list.get_selected(), 2, ts)
if utils.is_audio(tweet): if utils.is_audio(tweet):
sound.player.play("audio.ogg") sound.player.play("audio.ogg")

View File

@ -234,15 +234,7 @@ class Controller(object):
def post_tweet(self, event=None): def post_tweet(self, event=None):
buffer = self.get_best_buffer() buffer = self.get_best_buffer()
title = _(u"Tweet") buffer.post_tweet()
caption = _(u"Write the tweet here")
tweet = messages.tweet(buffer.session, title, caption, "")
if tweet.message.get_response() == widgetUtils.OK:
text = tweet.message.get_text()
if tweet.image == None:
call_threaded(buffer.session.api_call, call_name="update_status", _sound="tweet_send.ogg", status=text)
else:
call_threaded(buffer.session.api_call, call_name="update_status_with_media", _sound="tweet_send.ogg", status=text, media=tweet.image)
def post_reply(self, *args, **kwargs): def post_reply(self, *args, **kwargs):
buffer = self.get_current_buffer() buffer = self.get_current_buffer()

View File

@ -126,23 +126,27 @@ def setLanguage(lang):
elif system == "Darwin": elif system == "Darwin":
import Foundation import Foundation
localeName = Foundation.NSLocale.currentLocale().identifier() localeName = Foundation.NSLocale.currentLocale().identifier()
# trans=gettext.translation('twblue', localedir=paths.locale_path(), languages=[localeName])
# curLang=localeName
else:
localeName=locale.getdefaultlocale()[0]
trans=gettext.translation('twblue', localedir=paths.locale_path(), languages=[localeName]) trans=gettext.translation('twblue', localedir=paths.locale_path(), languages=[localeName])
curLang=localeName curLang=localeName
# else:
# localeName=locale.getdefaultlocale()[0]
# trans=gettext.translation('twblue', localedir=paths.locale_path(), languages=[localeName])
# curLang=localeName
else: else:
trans=gettext.translation("twblue", localedir=paths.locale_path(), languages=[lang]) trans=gettext.translation("twblue", localedir=paths.locale_path(), languages=[lang])
curLang=lang curLang=lang
localeChanged=False localeChanged=False
#Try setting Python's locale to lang #Try setting Python's locale to lang
try: # try:
if system == "Windows":
locale.setlocale(locale.LC_ALL, langToWindowsLocale(lang))
localeChanged=True
else:
locale.setlocale(locale.LC_ALL, lang) locale.setlocale(locale.LC_ALL, lang)
localeChanged=True localeChanged=True
except: # except:
pass # pass
if not localeChanged and '_' in lang: if not localeChanged and '_' in lang:
#Python couldn'tsupport the language_country locale, just try language. #Python couldn'tsupport the language_country locale, just try language.
try: try:
@ -158,7 +162,7 @@ def setLanguage(lang):
curLang="en" curLang="en"
trans.install(unicode=True) trans.install(unicode=True)
# Install our pgettext function. # Install our pgettext function.
__builtin__.__dict__["pgettext"] = makePgettext(trans) # __builtin__.__dict__["pgettext"] = makePgettext(trans)
def getLanguage(): def getLanguage():
return curLang return curLang
@ -178,3 +182,20 @@ def normalizeLanguage(lang):
ld[1]=ld[1].upper() ld[1]=ld[1].upper()
return "_".join(ld) return "_".join(ld)
def langToWindowsLocale(lang):
languages = {"en": "eng",
"ar": "ara",
"ca": "cat",
"es": "esp",
"fi": "fin",
"fr": "fre_FRA",
"gl": "glc",
"eu": "euq",
"hu": "hun",
"it": "ita",
"pl": "plk",
"pt": "ptb",
"ru": "rus",
"tr": "trk"
}
return languages[lang]

View File

@ -1,2 +1 @@
import buffers, utils, compose, twitter import buffers, utils, compose, twitter
from compose import prettydate

View File

@ -2,93 +2,10 @@
import utils import utils
import re import re
import htmlentitydefs import htmlentitydefs
import datetime
import time import time
import output import output
import gettext, paths, locale, gettext_windows import languageHandler
import platform import arrow
system = platform.system()
def prettydate(d):
""" Converts a string to the relative time."""
diff = datetime.datetime.utcnow() - d
s = diff.seconds
if diff.days > 7 and diff.days < 14:
return _(u"About a week ago")
elif diff.days > 14 and diff.days < 31:
return _(u"About {} weeks ago").format(diff.days/7)
elif diff.days > 31 and diff.days <= 62:
return _(u"A month ago")
elif diff.days >62 and diff.days <= 365:
return _(u"About {} months ago").format(diff.days/30)
elif diff.days > 365 and diff.days <= 730:
return _(u"About a year ago")
elif diff.days > 730:
return _(u"About {} years ago").format(diff.days/365)
elif diff.days == 1:
return _(u"About 1 day ago")
elif diff.days > 1:
return _(u"About {} days ago").format(diff.days)
elif s <= 1:
return _(u"just now")
elif s < 60:
return _(u"{} seconds ago").format(s)
elif s < 120:
return _(u"1 minute ago")
elif s < 3600:
return _(u"{} minutes ago").format(s/60)
elif s < 7200:
return _(u"About 1 hour ago")
else:
return _(u"About {} hours ago").format(s/3600)
# Months, days, short_months and short_days are used to translate the string that Twitter gives to us with the date and time.
months = {
"January": _(u"January"),
"February": _(u"February"),
"March": _(u"March"),
"April": _(u"April"),
"May": _(u"May"),
"June": _(u"June"),
"July": _(u"July"),
"August": _(u"August"),
"September": _(u"September"),
"October": _(u"October"),
"November": _(u"November"),
"December": _(u"December"),
}
days = {"Sunday": _(u"Sunday"),
"Monday": _(u"Monday"),
"Tuesday": _(u"Tuesday"),
"Wednesday": _(u"Wednesday"),
"Thursday": _(u"Thursday"),
"Friday": _(u"Friday"),
"Saturday": _(u"Saturday")}
short_days = {
"Sun": _(u"sun"),
"Mon": _(u"mon"),
"Tue": _(u"tue"),
"Wed": _(u"wed"),
"Thu": _(u"thu"),
"Fri": _(u"fri"),
"Sat": _(u"sat")
}
short_months = {
"Jan": _(u"jan"),
"Feb": _(u"feb"),
"Mar": _(u"mar"),
"Apr": _(u"apr"),
"May": _(u"may"),
"Jun": _(u"jun"),
"Jul": _(u"jul"),
"Aug": _(u"aug"),
"Sep": _(u"sep"),
"Oct": _(u"oct"),
"Nov": _(u"nov"),
"Dec": _(u"dec")}
def StripChars(s): def StripChars(s):
"""Converts any html entities in s to their unicode-decoded equivalents and returns a string.""" """Converts any html entities in s to their unicode-decoded equivalents and returns a string."""
@ -103,44 +20,15 @@ def StripChars(s):
return replacement.decode('iso-8859-1') return replacement.decode('iso-8859-1')
return unicode(entity_re.sub(matchFunc, s)) return unicode(entity_re.sub(matchFunc, s))
def translate(string):
""" Changes the days in English for the current language. Needed for Windows."""
if system != "Windows": return string
else:
global months, days
for d in months:
string = string.replace(d, months[d])
for d in days:
string = string.replace(d, days[d])
return string
def translate_short(string):
""" Changes the English date from Twitter to a local date and time. Needed for datetime on Linux."""
if system != "Linux": return string
else:
# if 1 == 1:
global short_months, short_days
for d in short_months:
string = string.replace(d, short_months[d])
for d in short_days:
string = string.replace(d, short_days[d])
return string
chars = "abcdefghijklmnopqrstuvwxyz" chars = "abcdefghijklmnopqrstuvwxyz"
def compose_tweet(tweet, db, relative_times): def compose_tweet(tweet, db, relative_times):
""" It receives a tweet and returns a list with the user, text for the tweet or message, date and the client where user is.""" """ It receives a tweet and returns a list with the user, text for the tweet or message, date and the client where user is."""
# original_date = datetime.datetime.strptime(translate_short(tweet["created_at"]).encode("utf-8"), "%a %b %d %H:%M:%S +0000 %Y") original_date = arrow.get(tweet["created_at"], "ddd MMM D H:m:s Z YYYY", locale="en")
original_date = datetime.datetime.strptime(tweet["created_at"], "%a %b %d %H:%M:%S +0000 %Y")
# else:
# original_date = datetime.datetime.strptime(tweet["created_at"], '%a %b %d %H:%M:%S +0000 %Y')
date = original_date-datetime.timedelta(seconds=-db["utc_offset"])
if relative_times == True: if relative_times == True:
ts = prettydate(original_date) ts = original_date.humanize(locale=languageHandler.getLanguage())
else: else:
# ts = translate(datetime.datetime.strftime(date, _("%A, %B %d, %Y at %I:%M:%S %p".encode("utf-8"))).decode("utf-8")) ts = original_date.replace(seconds=db["utc_offset"]).format(_(u"dddd, MMMM D, YYYY H:m:s"), locale=languageHandler.getLanguage())
ts = translate(datetime.datetime.strftime(date, _("%A, %B %d, %Y at %I:%M:%S %p")))
# ts = tweet["created_at"]
text = StripChars(tweet["text"]) text = StripChars(tweet["text"])
if tweet.has_key("sender"): if tweet.has_key("sender"):
source = "DM" source = "DM"
@ -148,7 +36,7 @@ def compose_tweet(tweet, db, relative_times):
else: user = tweet["sender"]["name"] else: user = tweet["sender"]["name"]
elif tweet.has_key("user"): elif tweet.has_key("user"):
user = tweet["user"]["name"] user = tweet["user"]["name"]
source = re.sub(r"(?s)<.*?>", " ", tweet["source"]) source = re.sub(r"(?s)<.*?>", "", tweet["source"])
try: text = "rt @%s: %s" % (tweet["retweeted_status"]["user"]["screen_name"], StripChars(tweet["retweeted_status"]["text"])) try: text = "rt @%s: %s" % (tweet["retweeted_status"]["user"]["screen_name"], StripChars(tweet["retweeted_status"]["text"]))
except KeyError: text = "%s" % (StripChars(tweet["text"])) except KeyError: text = "%s" % (StripChars(tweet["text"]))
if text[-1] in chars: text=text+"." if text[-1] in chars: text=text+"."
@ -157,26 +45,21 @@ def compose_tweet(tweet, db, relative_times):
try: text = text.replace(urls[url], tweet["entities"]["urls"][url]["expanded_url"]) try: text = text.replace(urls[url], tweet["entities"]["urls"][url]["expanded_url"])
except IndexError: pass except IndexError: pass
tweet["text"] = text tweet["text"] = text
return [user+", ", text, ts+", ", source] return [user+", ", tweet["text"], ts+", ", source]
def compose_followers_list(tweet, db, relative_time=True): def compose_followers_list(tweet, db, relative_times=True):
# original_date = datetime.datetime.strptime(translate_short(tweet["created_at"]).encode("utf-8"), '%a %b %d %H:%M:%S +0000 %Y') original_date = arrow.get(tweet["created_at"], "ddd MMM D H:m:s Z YYYY", locale="en")
original_date = datetime.datetime.strptime(tweet["created_at"], '%a %b %d %H:%M:%S +0000 %Y') if relative_times == True:
date = original_date-datetime.timedelta(seconds=-db["utc_offset"]) ts = original_date.humanize(locale=languageHandler.getLanguage())
if relative_time == True:
ts = prettydate(original_date)
else: else:
ts = translate(datetime.datetime.strftime(date, _(u"%A, %B %d, %Y at %I:%M:%S %p"))) ts = original_date.replace(seconds=db["utc_offset"]).format(_(u"dddd, MMMM D, YYYY H:m:s"), locale=languageHandler.getLanguage())
# ts = tweet["created_at"]
if tweet.has_key("status"): if tweet.has_key("status"):
if len(tweet["status"]) > 4: if len(tweet["status"]) > 4:
# original_date2 = datetime.datetime.strptime(translate_short(tweet["status"]["created_at"]).encode("utf-8"), '%a %b %d %H:%M:%S +0000 %Y') original_date2 = arrow.get(tweet["status"]["created_at"], "ddd MMM D H:m:s Z YYYY", locale="en")
original_date2 = datetime.datetime.strptime(tweet["status"]["created_at"], '%a %b %d %H:%M:%S +0000 %Y') if relative_times:
date2 = original_date2-datetime.timedelta(seconds=-db["utc_offset"]) ts2 = original_date2.humanize(locale=languageHandler.getLanguage())
if relative_time == True:
ts2 = prettydate(original_date2)
else: else:
ts2 = translate(datetime.datetime.strftime(date2, _(u"%A, %B %d, %Y at %I:%M:%S %p"))) ts2 = original_date2.replace(seconds=db["utc_offset"]).format(_(u"dddd, MMMM D, YYYY H:m:s"), locale=languageHandler.getLanguage())
else: else:
ts2 = _("Unavailable") ts2 = _("Unavailable")
return [_(u"%s (@%s). %s followers, %s friends, %s tweets. Last tweet on %s. Joined Twitter on %s") % (tweet["name"], tweet["screen_name"], tweet["followers_count"], tweet["friends_count"], tweet["statuses_count"], ts2, ts)] return [_(u"%s (@%s). %s followers, %s friends, %s tweets. Last tweet on %s. Joined Twitter on %s") % (tweet["name"], tweet["screen_name"], tweet["followers_count"], tweet["friends_count"], tweet["statuses_count"], ts2, ts)]

View File

@ -18,15 +18,15 @@ class basePanel(wx.Panel):
self.type = "baseBuffer" self.type = "baseBuffer"
self.sizer = wx.BoxSizer(wx.VERTICAL) self.sizer = wx.BoxSizer(wx.VERTICAL)
self.create_list() self.create_list()
self.btn = wx.Button(self, -1, _(u"Tweet")) self.tweet = wx.Button(self, -1, _(u"Tweet"))
self.retweetBtn = wx.Button(self, -1, _(u"Retweet")) self.retweet = wx.Button(self, -1, _(u"Retweet"))
self.responseBtn = wx.Button(self, -1, _(u"Reply")) self.reply = wx.Button(self, -1, _(u"Reply"))
self.dmBtn = wx.Button(self, -1, _(u"Direct message")) self.dm = wx.Button(self, -1, _(u"Direct message"))
btnSizer = wx.BoxSizer(wx.HORIZONTAL) btnSizer = wx.BoxSizer(wx.HORIZONTAL)
btnSizer.Add(self.btn, 0, wx.ALL, 5) btnSizer.Add(self.tweet, 0, wx.ALL, 5)
btnSizer.Add(self.retweetBtn, 0, wx.ALL, 5) btnSizer.Add(self.retweet, 0, wx.ALL, 5)
btnSizer.Add(self.responseBtn, 0, wx.ALL, 5) btnSizer.Add(self.reply, 0, wx.ALL, 5)
btnSizer.Add(self.dmBtn, 0, wx.ALL, 5) btnSizer.Add(self.dm, 0, wx.ALL, 5)
self.sizer.Add(btnSizer, 0, wx.ALL, 5) self.sizer.Add(btnSizer, 0, wx.ALL, 5)
self.sizer.Add(self.list.list, 0, wx.ALL, 5) self.sizer.Add(self.list.list, 0, wx.ALL, 5)
self.SetSizer(self.sizer) self.SetSizer(self.sizer)

View File

@ -6,6 +6,6 @@ class dmPanel(basePanel):
def __init__(self, parent, name): def __init__(self, parent, name):
""" Class to DM'S. Reply and retweet buttons are not showed and they have your delete method for dm's.""" """ Class to DM'S. Reply and retweet buttons are not showed and they have your delete method for dm's."""
super(dmPanel, self).__init__(parent, name) super(dmPanel, self).__init__(parent, name)
self.retweetBtn.Disable() self.retweet.Disable()
self.responseBtn.Disable() self.reply.Disable()
self.type = "dm" self.type = "dm"

View File

@ -12,5 +12,5 @@ class peoplePanel(basePanel):
def __init__(self, parent, name): def __init__(self, parent, name):
super(peoplePanel, self).__init__(parent, name) super(peoplePanel, self).__init__(parent, name)
self.type = "people" self.type = "people"
self.responseBtn.SetLabel(_(u"Mention")) self.reply.SetLabel(_(u"Mention"))
self.retweetBtn.Disable() self.retweet.Disable()