From 49530b8d0c84b3398a3ad8afe08879fc999555e0 Mon Sep 17 00:00:00 2001 From: Manuel Cortez Date: Thu, 6 Dec 2018 15:37:16 -0600 Subject: [PATCH] Separated rendering functions from the rest of the code --- src/controller/buffers.py | 6 +- src/controller/mainController.py | 38 +++---- src/controller/posts.py | 2 +- src/sessionmanager/renderers.py | 176 ++++++++++++++++++++++++++++++ src/sessionmanager/session.py | 136 +---------------------- src/{ => sessionmanager}/utils.py | 0 6 files changed, 200 insertions(+), 158 deletions(-) create mode 100644 src/sessionmanager/renderers.py rename src/{ => sessionmanager}/utils.py (100%) diff --git a/src/controller/buffers.py b/src/controller/buffers.py index 3985066..5ff42a0 100644 --- a/src/controller/buffers.py +++ b/src/controller/buffers.py @@ -16,7 +16,7 @@ import attach from pubsub import pub from vk.exceptions import VkAPIError from wxUI.tabs import home -from sessionmanager import session +from sessionmanager import session, renderers from mysc.thread_utils import call_threaded from mysc import upload from wxUI import commonMessages, menus @@ -68,7 +68,7 @@ class baseBuffer(object): 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.""" - 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_) def get_items(self, show_nextpage=False): @@ -615,7 +615,7 @@ class chatBuffer(baseBuffer): 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.""" - 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. # Here we will get first and last line of a chat message appended to the history. values = self.tab.add_message(item_[0]) diff --git a/src/controller/mainController.py b/src/controller/mainController.py index 62f3dd8..cf68966 100644 --- a/src/controller/mainController.py +++ b/src/controller/mainController.py @@ -62,7 +62,7 @@ class Controller(object): self.buffers.append(posts_) # Translators: Name for the posts tab in the tree view. 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) # Translators: Newsfeed's name in the tree view. self.window.insert_buffer(home.tab, _(u"Home"), self.window.search("posts")) @@ -70,7 +70,7 @@ class Controller(object): self.repeatedUpdate.start() self.readMarker = RepeatingTimer(120, self.mark_as_read) 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) # Translators: Own user's wall name in the tree view. 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. # 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.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.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.window.insert_buffer(r_audio.tab, _(u"Recommendations"), self.window.search("audios")) # albums = buffers.empty(parent=self.window.tb, name="albums") @@ -96,7 +96,7 @@ class Controller(object): self.buffers.append(videos) # Translators: name for the videos category in the tree view. 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.window.insert_buffer(my_videos.tab, _(u"My videos"), self.window.search("videos")) 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") self.buffers.append(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.window.insert_buffer(friends.tab, _(u"Friends"), self.window.search("people")) requests_ = buffers.empty(parent=self.window.tb, name="requests") self.buffers.append(requests_) 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.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.window.insert_buffer(outgoing_requests.tab, _(u"I follow"), self.window.search("requests")) chats = buffers.empty(parent=self.window.tb, name="chats") @@ -252,7 +252,7 @@ class Controller(object): lyrics = dlg.get_checkable("lyrics") performer_only = dlg.get_checkable("artist_only") 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) call_threaded(newbuff.get_items) # Translators: {0} will be replaced with the search term. @@ -270,7 +270,7 @@ class Controller(object): params["adult"] = dlg.get_checkable("safe_search") params["sort"] = dlg.get_sort_order() 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) call_threaded(newbuff.get_items) # Translators: {0} will be replaced with the search term. @@ -321,15 +321,15 @@ class Controller(object): commonMessages.no_user_exist() return 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. name_ = _(u"{0}'s audios").format(self.session.get_user_name(user_id, "gen"),) 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. name_ = _(u"{0}'s wall posts").format(self.session.get_user_name(user_id, "gen"),) 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. name_ = _(u"{0}'s friends").format(self.session.get_user_name(user_id, "friends"),) self.buffers.append(buffer) @@ -358,7 +358,7 @@ class Controller(object): self.window.change_buffer(pos) return b.tab.text.SetFocus() 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) # 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")) @@ -441,7 +441,7 @@ class Controller(object): return self.session.audio_albums = 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 # Translators: {0} Will be replaced with an audio album's title. name_ = _(u"Album: {0}").format(i["title"],) @@ -462,7 +462,7 @@ class Controller(object): return self.get_audio_albums(user_id=user_id) self.session.video_albums = 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 # Translators: {0} Will be replaced with a video album's 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")) if response.has_key("album_id") == False: return 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 # Translators: {0} will be replaced with an audio album's 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")) if response.has_key("album_id") == False: return 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 # Translators: {0} will be replaced with a video album's title. name_ = _(u"Album: {0}").format(d.get("title"),) diff --git a/src/controller/posts.py b/src/controller/posts.py index 737a81d..f4f01d1 100644 --- a/src/controller/posts.py +++ b/src/controller/posts.py @@ -14,7 +14,7 @@ import webbrowser import utils import logging 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 wxUI.dialogs import postDialogs, urlList, profiles from extra import SpellChecker, translator diff --git a/src/sessionmanager/renderers.py b/src/sessionmanager/renderers.py new file mode 100644 index 0000000..02d3de4 --- /dev/null +++ b/src/sessionmanager/renderers.py @@ -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"])] \ No newline at end of file diff --git a/src/sessionmanager/session.py b/src/sessionmanager/session.py index 7748441..fd0c611 100644 --- a/src/sessionmanager/session.py +++ b/src/sessionmanager/session.py @@ -1,11 +1,8 @@ # -*- coding: utf-8 -*- -import time -import arrow +import logging import languageHandler import paths import vkSessionHandler -import logging -import utils import sound from config_utils import Configuration, ConfigurationResetException from pubsub import pub @@ -37,137 +34,6 @@ def find_item(list, item): return True 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): def order_buffer(self, name, data, show_nextpage): diff --git a/src/utils.py b/src/sessionmanager/utils.py similarity index 100% rename from src/utils.py rename to src/sessionmanager/utils.py