Skip to content

Commit e552fe4

Browse files
committed
WIP: Support displaying of images in msg in the default viewer.
1 parent 360192a commit e552fe4

File tree

3 files changed

+50
-2
lines changed

3 files changed

+50
-2
lines changed

zulipterminal/config/keys.py

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -136,6 +136,10 @@
136136
'keys': {'ctrl c'},
137137
'help_text': 'Quit',
138138
}),
139+
('OPEN_MEDIA', {
140+
'keys': {'o'},
141+
'help_text': 'Open Media in the current highlighted message',
142+
}),
139143
]) # type: OrderedDict[str, KeyBinding]
140144

141145

zulipterminal/helper.py

Lines changed: 37 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,8 +6,11 @@
66
Any, Dict, List, Set, Tuple, Optional, DefaultDict, FrozenSet, Union
77
)
88
from mypy_extensions import TypedDict
9-
109
import os
10+
import requests
11+
import tempfile
12+
import subprocess
13+
import sys
1114

1215
Message = Dict[str, Any]
1316

@@ -347,3 +350,36 @@ def match_user(user: Any, text: str) -> bool:
347350
if keyword.startswith(text.lower()):
348351
return True
349352
return False
353+
354+
355+
# Plan to open all the images/gifs in a msg
356+
# A message contains n images/gifs
357+
# download all the images/gifs first in /tmp/MSGID folder
358+
# Open the first image in the default viewer of the os.
359+
# user can click next in the viewer for viewing rest of the media
360+
def open_media(urls: List[str], msg_id: int, server_url: str):
361+
first_media = None
362+
for url in urls:
363+
if url.startswith('user_uploads'):
364+
url = server_url + url
365+
if url.startswith('/user_uploads'):
366+
url = server_url + url[1:]
367+
img_name = url.split("/")[-1]
368+
img_dir_path = os.path.join(tempfile.gettempdir(), str(msg_id))
369+
img_path = os.path.join(img_dir_path, img_name)
370+
if not first_media:
371+
first_media = img_path
372+
try:
373+
os.mkdir(img_dir_path)
374+
except FileExistsError:
375+
pass
376+
with requests.get(url, stream=True) as r:
377+
r.raise_for_status()
378+
with open(img_path, 'wb') as f:
379+
for chunk in r.iter_content(chunk_size=8192):
380+
if chunk: # filter out keep-alive new chunks
381+
f.write(chunk)
382+
imageViewerFromCommandLine = {'linux': 'xdg-open',
383+
'win32': 'explorer',
384+
'darwin': 'open'}[sys.platform]
385+
subprocess.run([imageViewerFromCommandLine, img_path])

zulipterminal/ui_tools/boxes.py

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@
1111
from bs4.element import NavigableString, Tag
1212

1313
from zulipterminal.config.keys import is_command_key
14+
from zulipterminal.helper import open_media
1415

1516

1617
class WriteBox(urwid.Pile):
@@ -127,6 +128,8 @@ def __init__(self, message: Dict[str, Any], model: Any,
127128
self.email = ''
128129
self.user_id = None # type: Union[int, None]
129130
self.last_message = last_message
131+
# collect all the media links with their name in one place.
132+
self.media = list() # type: List[str]
130133
# if this is the first message
131134
if self.last_message is None:
132135
self.last_message = defaultdict(dict)
@@ -302,6 +305,9 @@ def soup2markup(self, soup: Any) -> List[Any]:
302305
elif element.name == 'a':
303306
# LINKS
304307
link = element.attrs['href']
308+
if element.img:
309+
self.media.append(element.img['src'])
310+
self.media.append(link)
305311
text = element.img['src'] if element.img else element.text
306312
if link == text:
307313
# If the link and text are same
@@ -312,7 +318,7 @@ def soup2markup(self, soup: Any) -> List[Any]:
312318
if link.startswith('/user_uploads/'):
313319
# Append org url to before user_uploads to convert it
314320
# into a link.
315-
link = self.model.server_url + link
321+
link = self.model.server_url + link[1:]
316322
markup.append(
317323
('link', '[' + text + ']' + '(' + link + ')'))
318324
elif element.name == 'blockquote':
@@ -529,6 +535,8 @@ def keypress(self, size: Tuple[int, int], key: str) -> str:
529535
self.model.controller.view.write_box.msg_write_box.set_edit_pos(
530536
len(quote))
531537
self.model.controller.view.middle_column.set_focus('footer')
538+
elif is_command_key('OPEN_MEDIA', key) and len(self.media):
539+
open_media(self.media, self.message['id'], self.model.server_url)
532540
return key
533541

534542

0 commit comments

Comments
 (0)