Separated rendering functions from the rest of the code

This commit is contained in:
Manuel Cortez 2018-12-06 15:37:16 -06:00
parent 3aa5a27268
commit 49530b8d0c
6 changed files with 200 additions and 158 deletions

View File

@ -16,7 +16,7 @@ import attach
from pubsub import pub from pubsub import pub
from vk.exceptions import VkAPIError from vk.exceptions import VkAPIError
from wxUI.tabs import home from wxUI.tabs import home
from sessionmanager import session from sessionmanager import session, renderers
from mysc.thread_utils import call_threaded from mysc.thread_utils import call_threaded
from mysc import upload from mysc import upload
from wxUI import commonMessages, menus from wxUI import commonMessages, menus
@ -68,7 +68,7 @@ class baseBuffer(object):
def insert(self, item, reversed=False): def insert(self, item, reversed=False):
""" Add a new item to the list. Uses session.composefunc for parsing the dictionary and create a valid result for putting it in the list.""" """ Add a new item to the list. Uses session.composefunc for parsing the dictionary and create a valid result for putting it in the list."""
item_ = getattr(session, self.compose_function)(item, self.session) item_ = getattr(renderers, self.compose_function)(item, self.session)
self.tab.list.insert_item(reversed, *item_) self.tab.list.insert_item(reversed, *item_)
def get_items(self, show_nextpage=False): def get_items(self, show_nextpage=False):
@ -615,7 +615,7 @@ class chatBuffer(baseBuffer):
def insert(self, item, reversed=False): def insert(self, item, reversed=False):
""" Add a new item to the list. Uses session.composefunc for parsing the dictionary and create a valid result for putting it in the list.""" """ Add a new item to the list. Uses session.composefunc for parsing the dictionary and create a valid result for putting it in the list."""
item_ = getattr(session, self.compose_function)(item, self.session) item_ = getattr(renderers, self.compose_function)(item, self.session)
# the self.chat dictionary will have (first_line, last_line) as keys and message ID as a value for looking into it when needed. # the self.chat dictionary will have (first_line, last_line) as keys and message ID as a value for looking into it when needed.
# Here we will get first and last line of a chat message appended to the history. # Here we will get first and last line of a chat message appended to the history.
values = self.tab.add_message(item_[0]) values = self.tab.add_message(item_[0])

View File

@ -62,7 +62,7 @@ class Controller(object):
self.buffers.append(posts_) self.buffers.append(posts_)
# Translators: Name for the posts tab in the tree view. # Translators: Name for the posts tab in the tree view.
self.window.add_buffer(posts_.tab, _(u"Posts")) self.window.add_buffer(posts_.tab, _(u"Posts"))
home = buffers.baseBuffer(parent=self.window.tb, name="home_timeline", session=self.session, composefunc="compose_new", endpoint="newsfeed", count=self.session.settings["buffers"]["count_for_wall_buffers"]) home = buffers.baseBuffer(parent=self.window.tb, name="home_timeline", session=self.session, composefunc="render_newsfeed_item", endpoint="newsfeed", count=self.session.settings["buffers"]["count_for_wall_buffers"])
self.buffers.append(home) self.buffers.append(home)
# Translators: Newsfeed's name in the tree view. # Translators: Newsfeed's name in the tree view.
self.window.insert_buffer(home.tab, _(u"Home"), self.window.search("posts")) self.window.insert_buffer(home.tab, _(u"Home"), self.window.search("posts"))
@ -70,7 +70,7 @@ class Controller(object):
self.repeatedUpdate.start() self.repeatedUpdate.start()
self.readMarker = RepeatingTimer(120, self.mark_as_read) self.readMarker = RepeatingTimer(120, self.mark_as_read)
self.readMarker.start() self.readMarker.start()
feed = buffers.feedBuffer(parent=self.window.tb, name="me_feed", composefunc="compose_status", session=self.session, endpoint="get", parent_endpoint="wall", extended=1, count=self.session.settings["buffers"]["count_for_wall_buffers"]) feed = buffers.feedBuffer(parent=self.window.tb, name="me_feed", composefunc="render_status", session=self.session, endpoint="get", parent_endpoint="wall", extended=1, count=self.session.settings["buffers"]["count_for_wall_buffers"])
self.buffers.append(feed) self.buffers.append(feed)
# Translators: Own user's wall name in the tree view. # Translators: Own user's wall name in the tree view.
self.window.insert_buffer(feed.tab, _(u"My wall"), self.window.search("posts")) self.window.insert_buffer(feed.tab, _(u"My wall"), self.window.search("posts"))
@ -80,13 +80,13 @@ class Controller(object):
# Translators: name for the music category in the tree view. # Translators: name for the music category in the tree view.
# self.window.add_buffer(audios.tab, _(u"Music")) # self.window.add_buffer(audios.tab, _(u"Music"))
# audio = buffers.audioBuffer(parent=self.window.tb, name="me_audio", composefunc="compose_audio", session=self.session, endpoint="get", parent_endpoint="audio", full_list=True, count=self.session.settings["buffers"]["count_for_audio_buffers"]) # audio = buffers.audioBuffer(parent=self.window.tb, name="me_audio", composefunc="render_audio", session=self.session, endpoint="get", parent_endpoint="audio", full_list=True, count=self.session.settings["buffers"]["count_for_audio_buffers"])
# self.buffers.append(audio) # self.buffers.append(audio)
# self.window.insert_buffer(audio.tab, _(u"My audios"), self.window.search("audios")) # self.window.insert_buffer(audio.tab, _(u"My audios"), self.window.search("audios"))
# p_audio = buffers.audioBuffer(parent=self.window.tb, name="popular_audio", composefunc="compose_audio", session=self.session, endpoint="getPopular", parent_endpoint="audio", full_list=True, count=self.session.settings["buffers"]["count_for_audio_buffers"]) # p_audio = buffers.audioBuffer(parent=self.window.tb, name="popular_audio", composefunc="render_audio", session=self.session, endpoint="getPopular", parent_endpoint="audio", full_list=True, count=self.session.settings["buffers"]["count_for_audio_buffers"])
# self.buffers.append(p_audio) # self.buffers.append(p_audio)
# self.window.insert_buffer(p_audio.tab, _(u"Populars"), self.window.search("audios")) # self.window.insert_buffer(p_audio.tab, _(u"Populars"), self.window.search("audios"))
# r_audio = buffers.audioBuffer(parent=self.window.tb, name="recommended_audio", composefunc="compose_audio", session=self.session, endpoint="getRecommendations", parent_endpoint="audio", full_list=True, count=self.session.settings["buffers"]["count_for_audio_buffers"]) # r_audio = buffers.audioBuffer(parent=self.window.tb, name="recommended_audio", composefunc="render_audio", session=self.session, endpoint="getRecommendations", parent_endpoint="audio", full_list=True, count=self.session.settings["buffers"]["count_for_audio_buffers"])
# self.buffers.append(r_audio) # self.buffers.append(r_audio)
# self.window.insert_buffer(r_audio.tab, _(u"Recommendations"), self.window.search("audios")) # self.window.insert_buffer(r_audio.tab, _(u"Recommendations"), self.window.search("audios"))
# albums = buffers.empty(parent=self.window.tb, name="albums") # albums = buffers.empty(parent=self.window.tb, name="albums")
@ -96,7 +96,7 @@ class Controller(object):
self.buffers.append(videos) self.buffers.append(videos)
# Translators: name for the videos category in the tree view. # Translators: name for the videos category in the tree view.
self.window.add_buffer(videos.tab, _(u"Video")) self.window.add_buffer(videos.tab, _(u"Video"))
my_videos = buffers.videoBuffer(parent=self.window.tb, name="me_video", composefunc="compose_video", session=self.session, endpoint="get", parent_endpoint="video", count=self.session.settings["buffers"]["count_for_video_buffers"]) my_videos = buffers.videoBuffer(parent=self.window.tb, name="me_video", composefunc="render_video", session=self.session, endpoint="get", parent_endpoint="video", count=self.session.settings["buffers"]["count_for_video_buffers"])
self.buffers.append(my_videos) self.buffers.append(my_videos)
self.window.insert_buffer(my_videos.tab, _(u"My videos"), self.window.search("videos")) self.window.insert_buffer(my_videos.tab, _(u"My videos"), self.window.search("videos"))
video_albums = buffers.empty(parent=self.window.tb, name="video_albums") video_albums = buffers.empty(parent=self.window.tb, name="video_albums")
@ -105,16 +105,16 @@ class Controller(object):
people = buffers.empty(parent=self.window.tb, name="people") people = buffers.empty(parent=self.window.tb, name="people")
self.buffers.append(people) self.buffers.append(people)
self.window.add_buffer(people.tab, _(u"People")) self.window.add_buffer(people.tab, _(u"People"))
friends = buffers.peopleBuffer(parent=self.window.tb, name="friends_", composefunc="compose_person", session=self.session, endpoint="get", parent_endpoint="friends", count=5000, fields="uid, first_name, last_name, last_seen") friends = buffers.peopleBuffer(parent=self.window.tb, name="friends_", composefunc="render_person", session=self.session, endpoint="get", parent_endpoint="friends", count=5000, fields="uid, first_name, last_name, last_seen")
self.buffers.append(friends) self.buffers.append(friends)
self.window.insert_buffer(friends.tab, _(u"Friends"), self.window.search("people")) self.window.insert_buffer(friends.tab, _(u"Friends"), self.window.search("people"))
requests_ = buffers.empty(parent=self.window.tb, name="requests") requests_ = buffers.empty(parent=self.window.tb, name="requests")
self.buffers.append(requests_) self.buffers.append(requests_)
self.window.insert_buffer(requests_.tab, _(u"Friendship requests"), self.window.search("people")) self.window.insert_buffer(requests_.tab, _(u"Friendship requests"), self.window.search("people"))
incoming_requests = buffers.requestsBuffer(parent=self.window.tb, name="friend_requests", composefunc="compose_person", session=self.session, count=1000) incoming_requests = buffers.requestsBuffer(parent=self.window.tb, name="friend_requests", composefunc="render_person", session=self.session, count=1000)
self.buffers.append(incoming_requests) self.buffers.append(incoming_requests)
self.window.insert_buffer(incoming_requests.tab, _(u"Pending requests"), self.window.search("requests")) self.window.insert_buffer(incoming_requests.tab, _(u"Pending requests"), self.window.search("requests"))
outgoing_requests = buffers.requestsBuffer(parent=self.window.tb, name="friend_requests_sent", composefunc="compose_person", session=self.session, count=1000, out=1) outgoing_requests = buffers.requestsBuffer(parent=self.window.tb, name="friend_requests_sent", composefunc="render_person", session=self.session, count=1000, out=1)
self.buffers.append(outgoing_requests) self.buffers.append(outgoing_requests)
self.window.insert_buffer(outgoing_requests.tab, _(u"I follow"), self.window.search("requests")) self.window.insert_buffer(outgoing_requests.tab, _(u"I follow"), self.window.search("requests"))
chats = buffers.empty(parent=self.window.tb, name="chats") chats = buffers.empty(parent=self.window.tb, name="chats")
@ -252,7 +252,7 @@ class Controller(object):
lyrics = dlg.get_checkable("lyrics") lyrics = dlg.get_checkable("lyrics")
performer_only = dlg.get_checkable("artist_only") performer_only = dlg.get_checkable("artist_only")
sort = dlg.get_sort_order() sort = dlg.get_sort_order()
newbuff = buffers.audioBuffer(parent=self.window.tb, name=u"{0}_audiosearch".format(q.decode("utf-8"),), session=self.session, composefunc="compose_audio", parent_endpoint="audio", endpoint="search", q=q, count=count, auto_complete=auto_complete, lyrics=lyrics, performer_only=performer_only, sort=sort) newbuff = buffers.audioBuffer(parent=self.window.tb, name=u"{0}_audiosearch".format(q.decode("utf-8"),), session=self.session, composefunc="render_audio", parent_endpoint="audio", endpoint="search", q=q, count=count, auto_complete=auto_complete, lyrics=lyrics, performer_only=performer_only, sort=sort)
self.buffers.append(newbuff) self.buffers.append(newbuff)
call_threaded(newbuff.get_items) call_threaded(newbuff.get_items)
# Translators: {0} will be replaced with the search term. # Translators: {0} will be replaced with the search term.
@ -270,7 +270,7 @@ class Controller(object):
params["adult"] = dlg.get_checkable("safe_search") params["adult"] = dlg.get_checkable("safe_search")
params["sort"] = dlg.get_sort_order() params["sort"] = dlg.get_sort_order()
params["filters"] = "youtube, vimeo, short, long" params["filters"] = "youtube, vimeo, short, long"
newbuff = buffers.videoBuffer(parent=self.window.tb, name=u"{0}_videosearch".format(params["q"].decode("utf-8"),), session=self.session, composefunc="compose_video", parent_endpoint="video", endpoint="search", **params) newbuff = buffers.videoBuffer(parent=self.window.tb, name=u"{0}_videosearch".format(params["q"].decode("utf-8"),), session=self.session, composefunc="render_video", parent_endpoint="video", endpoint="search", **params)
self.buffers.append(newbuff) self.buffers.append(newbuff)
call_threaded(newbuff.get_items) call_threaded(newbuff.get_items)
# Translators: {0} will be replaced with the search term. # Translators: {0} will be replaced with the search term.
@ -321,15 +321,15 @@ class Controller(object):
commonMessages.no_user_exist() commonMessages.no_user_exist()
return return
if buffertype == "audio": if buffertype == "audio":
buffer = buffers.audioBuffer(parent=self.window.tb, name="{0}_audio".format(user_id,), composefunc="compose_audio", session=self.session, endpoint="get", parent_endpoint="audio", full_list=True, count=self.session.settings["buffers"]["count_for_audio_buffers"], owner_id=user_id) buffer = buffers.audioBuffer(parent=self.window.tb, name="{0}_audio".format(user_id,), composefunc="render_audio", session=self.session, endpoint="get", parent_endpoint="audio", full_list=True, count=self.session.settings["buffers"]["count_for_audio_buffers"], owner_id=user_id)
# Translators: {0} will be replaced with an user. # Translators: {0} will be replaced with an user.
name_ = _(u"{0}'s audios").format(self.session.get_user_name(user_id, "gen"),) name_ = _(u"{0}'s audios").format(self.session.get_user_name(user_id, "gen"),)
elif buffertype == "wall": elif buffertype == "wall":
buffer = buffers.feedBuffer(parent=self.window.tb, name="{0}_feed".format(user_id,), composefunc="compose_status", session=self.session, endpoint="get", parent_endpoint="wall", extended=1, count=self.session.settings["buffers"]["count_for_wall_buffers"], owner_id=user_id) buffer = buffers.feedBuffer(parent=self.window.tb, name="{0}_feed".format(user_id,), composefunc="render_status", session=self.session, endpoint="get", parent_endpoint="wall", extended=1, count=self.session.settings["buffers"]["count_for_wall_buffers"], owner_id=user_id)
# Translators: {0} will be replaced with an user. # Translators: {0} will be replaced with an user.
name_ = _(u"{0}'s wall posts").format(self.session.get_user_name(user_id, "gen"),) name_ = _(u"{0}'s wall posts").format(self.session.get_user_name(user_id, "gen"),)
elif buffertype == "friends": elif buffertype == "friends":
buffer = buffers.peopleBuffer(parent=self.window.tb, name="friends_{0}".format(user_id,), composefunc="compose_person", session=self.session, endpoint="get", parent_endpoint="friends", count=5000, fields="uid, first_name, last_name, last_seen", user_id=user_id) buffer = buffers.peopleBuffer(parent=self.window.tb, name="friends_{0}".format(user_id,), composefunc="render_person", session=self.session, endpoint="get", parent_endpoint="friends", count=5000, fields="uid, first_name, last_name, last_seen", user_id=user_id)
# Translators: {0} will be replaced with an user. # Translators: {0} will be replaced with an user.
name_ = _(u"{0}'s friends").format(self.session.get_user_name(user_id, "friends"),) name_ = _(u"{0}'s friends").format(self.session.get_user_name(user_id, "friends"),)
self.buffers.append(buffer) self.buffers.append(buffer)
@ -358,7 +358,7 @@ class Controller(object):
self.window.change_buffer(pos) self.window.change_buffer(pos)
return b.tab.text.SetFocus() return b.tab.text.SetFocus()
return return
buffer = buffers.chatBuffer(parent=self.window.tb, name="{0}_messages".format(user_id,), composefunc="compose_message", session=self.session, count=200, user_id=user_id, rev=0) buffer = buffers.chatBuffer(parent=self.window.tb, name="{0}_messages".format(user_id,), composefunc="render_message", session=self.session, count=200, user_id=user_id, rev=0)
self.buffers.append(buffer) self.buffers.append(buffer)
# Translators: {0} will be replaced with an user. # Translators: {0} will be replaced with an user.
self.window.insert_buffer(buffer.tab, _(u"Chat with {0}").format(self.session.get_user_name(user_id, "ins")), self.window.search("chats")) self.window.insert_buffer(buffer.tab, _(u"Chat with {0}").format(self.session.get_user_name(user_id, "ins")), self.window.search("chats"))
@ -441,7 +441,7 @@ class Controller(object):
return return
self.session.audio_albums = albums["items"] self.session.audio_albums = albums["items"]
for i in albums["items"]: for i in albums["items"]:
buffer = buffers.audioAlbum(parent=self.window.tb, name="{0}_audio_album".format(i["id"],), composefunc="compose_audio", session=self.session, endpoint="get", parent_endpoint="audio", full_list=True, count=self.session.settings["buffers"]["count_for_audio_buffers"], user_id=user_id, album_id=i["id"]) buffer = buffers.audioAlbum(parent=self.window.tb, name="{0}_audio_album".format(i["id"],), composefunc="render_audio", session=self.session, endpoint="get", parent_endpoint="audio", full_list=True, count=self.session.settings["buffers"]["count_for_audio_buffers"], user_id=user_id, album_id=i["id"])
buffer.can_get_items = False buffer.can_get_items = False
# Translators: {0} Will be replaced with an audio album's title. # Translators: {0} Will be replaced with an audio album's title.
name_ = _(u"Album: {0}").format(i["title"],) name_ = _(u"Album: {0}").format(i["title"],)
@ -462,7 +462,7 @@ class Controller(object):
return self.get_audio_albums(user_id=user_id) return self.get_audio_albums(user_id=user_id)
self.session.video_albums = albums["items"] self.session.video_albums = albums["items"]
for i in albums["items"]: for i in albums["items"]:
buffer = buffers.videoAlbum(parent=self.window.tb, name="{0}_video_album".format(i["id"],), composefunc="compose_video", session=self.session, endpoint="get", parent_endpoint="video", count=self.session.settings["buffers"]["count_for_video_buffers"], user_id=user_id, album_id=i["id"]) buffer = buffers.videoAlbum(parent=self.window.tb, name="{0}_video_album".format(i["id"],), composefunc="render_video", session=self.session, endpoint="get", parent_endpoint="video", count=self.session.settings["buffers"]["count_for_video_buffers"], user_id=user_id, album_id=i["id"])
buffer.can_get_items = False buffer.can_get_items = False
# Translators: {0} Will be replaced with a video album's title. # Translators: {0} Will be replaced with a video album's title.
name_ = _(u"Album: {0}").format(i["title"],) name_ = _(u"Album: {0}").format(i["title"],)
@ -478,7 +478,7 @@ class Controller(object):
response = self.session.vk.client.audio.addAlbum(title=d.get("title")) response = self.session.vk.client.audio.addAlbum(title=d.get("title"))
if response.has_key("album_id") == False: return if response.has_key("album_id") == False: return
album_id = response["album_id"] album_id = response["album_id"]
buffer = buffers.audioAlbum(parent=self.window.tb, name="{0}_audio_album".format(album_id,), composefunc="compose_audio", session=self.session, endpoint="get", parent_endpoint="audio", full_list=True, count=self.session.settings["buffers"]["count_for_audio_buffers"], user_id=self.session.user_id, album_id=album_id) buffer = buffers.audioAlbum(parent=self.window.tb, name="{0}_audio_album".format(album_id,), composefunc="render_audio", session=self.session, endpoint="get", parent_endpoint="audio", full_list=True, count=self.session.settings["buffers"]["count_for_audio_buffers"], user_id=self.session.user_id, album_id=album_id)
buffer.can_get_items = False buffer.can_get_items = False
# Translators: {0} will be replaced with an audio album's title. # Translators: {0} will be replaced with an audio album's title.
name_ = _(u"Album: {0}").format(d.get("title"),) name_ = _(u"Album: {0}").format(d.get("title"),)
@ -507,7 +507,7 @@ class Controller(object):
response = self.session.vk.client.video.addAlbum(title=d.get("title")) response = self.session.vk.client.video.addAlbum(title=d.get("title"))
if response.has_key("album_id") == False: return if response.has_key("album_id") == False: return
album_id = response["album_id"] album_id = response["album_id"]
buffer = buffers.videoAlbum(parent=self.window.tb, name="{0}_video_album".format(album_id,), composefunc="compose_video", session=self.session, endpoint="get", parent_endpoint="video", count=self.session.settings["buffers"]["count_for_video_buffers"], user_id=self.session.user_id, album_id=album_id) buffer = buffers.videoAlbum(parent=self.window.tb, name="{0}_video_album".format(album_id,), composefunc="render_video", session=self.session, endpoint="get", parent_endpoint="video", count=self.session.settings["buffers"]["count_for_video_buffers"], user_id=self.session.user_id, album_id=album_id)
buffer.can_get_items = False buffer.can_get_items = False
# Translators: {0} will be replaced with a video album's title. # Translators: {0} will be replaced with a video album's title.
name_ = _(u"Album: {0}").format(d.get("title"),) name_ = _(u"Album: {0}").format(d.get("title"),)

View File

@ -14,7 +14,7 @@ import webbrowser
import utils import utils
import logging import logging
from sessionmanager import session # We'll use some functions from there from sessionmanager import session # We'll use some functions from there
from sessionmanager.session import utils from sessionmanager import utils
from pubsub import pub from pubsub import pub
from wxUI.dialogs import postDialogs, urlList, profiles from wxUI.dialogs import postDialogs, urlList, profiles
from extra import SpellChecker, translator from extra import SpellChecker, translator

View File

@ -0,0 +1,176 @@
# -*- coding: utf-8 -*-
""" this module contains everything used to render different kind of posts (posts in the home buffer,
Chat messages, audios, videos, photos, comments in posts, etc)"""
import arrow
import languageHandler
import logging
import utils
log = logging.getLogger(__file__)
### Some util funtions
def extract_attachment(attachment):
""" Adds information about attachment files in posts. It only adds the text, I mean, no attachment file is added here.
This will produce a result like:
'website: http://url.com'.
'photo: A forest'."""
msg = u""
if attachment["type"] == "link":
msg = u"{0}: {1}".format(attachment["link"]["title"], attachment["link"]["url"])
elif attachment["type"] == "photo":
msg = attachment["photo"]["text"]
if msg == "":
return _(u"photo with no description available")
elif attachment["type"] == "video":
msg = _(u"video: {0}").format(attachment["video"]["title"],)
return msg
def short_text(status):
""" This shorts the text to 140 characters for displaying it in the list control of buffers."""
message = ""
# copy_story indicates that the post is a shared repost.
if status.has_key("copy_history"):
txt = status["copy_history"][0]["text"]
else:
txt = status["text"]
if len(txt) < 140:
message = utils.clean_text(txt)
else:
message = utils.clean_text(txt[:139])
return message
def clean_audio(audio):
""" Remove unavailable songs due to different reasons. This is used to clean the audio list when people adds audios and need to be displayed in the buffer."""
for i in audio["items"][:]:
if type(i) == bool:
audio["items"].remove(i)
audio["count"] = audio["count"] -1
return audio
### Render functions
def render_person(status, session):
""" Render users in people buffers such as everything related to friendships or buffers created with only people.
Example result: ["John Doe", "An hour ago"]
Reference: https://vk.com/dev/fields"""
if status.has_key("last_seen"):
original_date = arrow.get(status["last_seen"]["time"])
# Translators: This is the date of last seen
last_seen = _(u"{0}").format(original_date.humanize(locale=languageHandler.getLanguage()),)
# Account suspended or deleted.
elif status.has_key("last_seen") == False and status.has_key("deactivated"):
last_seen = _(u"Account deactivated")
return [u"{0} {1}".format(status["first_name"], status["last_name"]), last_seen]
def render_newsfeed_item(status, session):
""" This me☻thod is used to render an item of the news feed.
References:
https://vk.com/dev/newsfeed.get
https://vk.com/dev/post_source
https://vk.com/dev/post
"""
user = session.get_user_name(status["source_id"], case_name="nom")
# See if this is a post or repost.
if status.has_key("copy_history"):
user = _(u"{0} has shared the {1}'s post").format(user, session.get_user_name(status["copy_history"][0]["owner_id"]))
message = ""
original_date = arrow.get(status["date"])
created_at = original_date.humanize(locale=languageHandler.getLanguage())
# handle status updates.
if status["type"] == "post":
message += short_text(status)
if status.has_key("attachment") and len(status["attachment"]) > 0:
message += extract_attachment(status["attachment"])
# If there is no message after adding text, it's because a pphoto with no description has been found.
# so let's manually add the "no description" tag here.
if message == "":
message = "no description available"
# Handle audio rendering.
elif status["type"] == "audio":
# removes deleted audios.
status["audio"] = clean_audio(status["audio"])
if status["audio"]["count"] == 1:
message = _(u"{0} has added an audio: {1}").format(user, u", ".join(render_audio(status["audio"]["items"][0], session)),)
else:
prem = ""
for i in xrange(0, status["audio"]["count"]):
composed_audio = render_audio(status["audio"]["items"][i], session)
prem += u"{0} - {1}, ".format(composed_audio[0], composed_audio[1])
message = _(u"{0} has added {1} audios: {2}").format(user, status["audio"]["count"], prem)
# handle new friends for people in the news buffer.
elif status["type"] == "friend":
msg_users = u""
if status.has_key("friends"):
for i in status["friends"]["items"]:
msg_users = msg_users + u"{0}, ".format(session.get_user_name(i["user_id"], "nom"))
else:
print status.keys()
message = _(u"{0} hadded friends: {1}").format(user, msg_users)
elif status["type"] == "video":
if status["video"]["count"] == 1:
message = _(u"{0} has added a video: {1}").format(user, u", ".join(render_video(status["video"]["items"][0], session)),)
else:
prem = ""
for i in xrange(0, status["video"]["count"]):
composed_video = render_video(status["video"]["items"][i], session)
prem += u"{0} - {1}, ".format(composed_video[0], composed_video[1])
message = _(u"{0} has added {1} videos: {2}").format(user, status["video"]["count"], prem)
else:
if status["type"] != "post": print status
return [user, message, created_at]
def render_message(message, session):
""" Render a message posted in a private conversation.
Reference: https://vk.com/dev/message"""
user = session.get_user_name(message["from_id"], "nom")
original_date = arrow.get(message["date"])
now = arrow.now()
original_date = original_date.to(now.tzinfo)
# Format the date here differently depending in if this is the same day for both dates or not.
if original_date.day == now.day:
created_at = original_date.format(_(u"H:mm."), locale=languageHandler.getLanguage())
else:
created_at = original_date.format(_(u"H:mm. dddd, MMMM D, YYYY"), locale=languageHandler.getLanguage())
# No idea why some messages send "text" instead "body"
if message.has_key("body"):
body = message["body"]
else:
body = message["text"]
return [u"{2}, {0} {1}".format(body, created_at, user)]
def render_status(status, session):
""" Render a wall post (shown in user's wall, not in newsfeed).
Reference: https://vk.com/dev/post"""
user = session.get_user_name(status["from_id"], "nom")
if status.has_key("copy_history"):
user = _(u"{0} has shared the {1}'s post").format(user, session.get_user_name(status["copy_history"][0]["owner_id"]))
message = ""
original_date = arrow.get(status["date"])
created_at = original_date.humanize(locale=languageHandler.getLanguage())
if status.has_key("copy_owner_id"):
user = _(u"{0} has shared the {1}'s post").format(user, session.get_user_name(status["copy_owner_id"]))
if status["post_type"] == "post" or status["post_type"] == "copy":
message += short_text(status)
if status.has_key("attachment") and len(status["attachment"]) > 0:
message += extract_attachment(status["attachment"])
if message == "":
message = "no description available"
return [user, message, created_at]
def render_audio(audio, session=None):
""" Render audio files added to VK.
Example result:
["Song title", "Artist", "03:15"]
reference: https://vk.com/dev/audio_object"""
if audio == False: return [_(u"Audio removed from library"), "", ""]
return [audio["title"], audio["artist"], utils.seconds_to_string(audio["duration"])]
def render_video(video, session=None):
""" Render a video file from VK.
Example result:
["Video title", "Video description", "01:30:28"]
Reference: https://vk.com/dev/video_object"""
if video == False:
return [_(u"Video not available"), "", ""]
return [video["title"], video["description"], utils.seconds_to_string(video["duration"])]

View File

@ -1,11 +1,8 @@
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
import time import logging
import arrow
import languageHandler import languageHandler
import paths import paths
import vkSessionHandler import vkSessionHandler
import logging
import utils
import sound import sound
from config_utils import Configuration, ConfigurationResetException from config_utils import Configuration, ConfigurationResetException
from pubsub import pub from pubsub import pub
@ -37,137 +34,6 @@ def find_item(list, item):
return True return True
return False return False
def add_attachment(attachment):
""" Adds information about attachment files in posts. It only adds the text, I mean, no attachment file is added here.
This will produce a result like 'Title of a web page: http://url.xxx', etc."""
msg = u""
if attachment["type"] == "link":
msg = u"{0}: {1}".format(attachment["link"]["title"], attachment["link"]["url"])
elif attachment["type"] == "photo":
msg = attachment["photo"]["text"]
if msg == "":
return _(u"photo with no description available")
elif attachment["type"] == "video":
msg = _(u"video: {0}").format(attachment["video"]["title"],)
return msg
def add_text(status):
""" This shorts the text to 140 characters for displaying it in the list control."""
message = ""
if status.has_key("copy_history"):
txt = status["copy_history"][0]["text"]
else:
txt = status["text"]
if len(txt) < 140:
message = utils.clean_text(txt)
else:
message = utils.clean_text(txt[:139])
return message
def compose_person(status, session):
if status.has_key("last_seen"):
original_date = arrow.get(status["last_seen"]["time"])
# Translators: This is the date of last seen
last_seen = _(u"{0}").format(original_date.humanize(locale=languageHandler.getLanguage()),)
elif status.has_key("last_seen") == False and status.has_key("deactivated"):
last_seen = _(u"Account deactivated")
return [u"{0} {1}".format(status["first_name"], status["last_name"]), last_seen]
def compose_new(status, session):
""" This method is used to compose an item of the news feed."""
user = session.get_user_name(status["source_id"], case_name="nom")
if status.has_key("copy_history"):
user = _(u"{0} has shared the {1}'s post").format(user, session.get_user_name(status["copy_history"][0]["owner_id"]))
message = ""
original_date = arrow.get(status["date"])
created_at = original_date.humanize(locale=languageHandler.getLanguage())
if status["type"] == "post":
message += add_text(status)
if status.has_key("attachment") and len(status["attachment"]) > 0:
message += add_attachment(status["attachment"])
if message == "":
message = "no description available"
elif status["type"] == "audio":
# removes deleted audios.
status["audio"] = clean_audio(status["audio"])
if status["audio"]["count"] == 1:
message = _(u"{0} has added an audio: {1}").format(user, u", ".join(compose_audio(status["audio"]["items"][0], session)),)
else:
prem = ""
for i in xrange(0, status["audio"]["count"]):
composed_audio = compose_audio(status["audio"]["items"][i], session)
prem += u"{0} - {1}, ".format(composed_audio[0], composed_audio[1])
message = _(u"{0} has added {1} audios: {2}").format(user, status["audio"]["count"], prem)
elif status["type"] == "friend":
msg_users = u""
if status.has_key("friends"):
for i in status["friends"]["items"]:
msg_users = msg_users + u"{0}, ".format(session.get_user_name(i["user_id"], "nom"))
else:
print status.keys()
message = _(u"{0} hadded friends: {1}").format(user, msg_users)
elif status["type"] == "video":
if status["video"]["count"] == 1:
message = _(u"{0} has added a video: {1}").format(user, u", ".join(compose_video(status["video"]["items"][0], session)),)
else:
prem = ""
for i in xrange(0, status["video"]["count"]):
composed_video = compose_video(status["video"]["items"][i], session)
prem += u"{0} - {1}, ".format(composed_video[0], composed_video[1])
message = _(u"{0} has added {1} videos: {2}").format(user, status["video"]["count"], prem)
else:
if status["type"] != "post": print status
return [user, message, created_at]
def clean_audio(audio):
for i in audio["items"][:]:
if type(i) == bool:
audio["items"].remove(i)
audio["count"] = audio["count"] -1
return audio
def compose_message(message, session):
user = session.get_user_name(message["from_id"], "nom")
original_date = arrow.get(message["date"])
now = arrow.now()
original_date = original_date.to(now.tzinfo)
# Format the date here differently depending in if this is the same day for both dates or not.
if original_date.day == now.day:
created_at = original_date.format(_(u"H:mm."), locale=languageHandler.getLanguage())
else:
created_at = original_date.format(_(u"H:mm. dddd, MMMM D, YYYY"), locale=languageHandler.getLanguage())
# No idea why some messages send "text" instead "body"
if message.has_key("body"):
body = message["body"]
else:
body = message["text"]
return [u"{2}, {0} {1}".format(body, created_at, user)]
def compose_status(status, session):
user = session.get_user_name(status["from_id"], "nom")
if status.has_key("copy_history"):
user = _(u"{0} has shared the {1}'s post").format(user, session.get_user_name(status["copy_history"][0]["owner_id"]))
message = ""
original_date = arrow.get(status["date"])
created_at = original_date.humanize(locale=languageHandler.getLanguage())
if status.has_key("copy_owner_id"):
user = _(u"{0} has shared the {1}'s post").format(user, session.get_user_name(status["copy_owner_id"]))
if status["post_type"] == "post" or status["post_type"] == "copy":
message += add_text(status)
if status.has_key("attachment") and len(status["attachment"]) > 0:
message += add_attachment(status["attachment"])
if message == "":
message = "no description available"
return [user, message, created_at]
def compose_audio(audio, session=None):
if audio == False: return [_(u"Audio removed from library"), "", ""]
return [audio["title"], audio["artist"], utils.seconds_to_string(audio["duration"])]
def compose_video(video, session=None):
if video == False: return [_(u"Audio removed from library"), "", ""]
return [video["title"], video["description"], utils.seconds_to_string(video["duration"])]
class vkSession(object): class vkSession(object):
def order_buffer(self, name, data, show_nextpage): def order_buffer(self, name, data, show_nextpage):