Coverage for slidge/slixfix/link_preview/stanza.py: 98%

61 statements  

« prev     ^ index     » next       coverage.py v7.6.1, created at 2024-11-07 05:11 +0000

1# Slixmpp: The Slick XMPP Library 

2# Copyright (C) 2012 Nathanael C. Fritz, Lance J.T. Stout 

3# This file is part of Slixmpp. 

4# See the file LICENSE for copying permission. 

5from typing import Optional, Type 

6 

7from slixmpp.stanza.message import Message 

8from slixmpp.xmlstream import ElementBase, register_stanza_plugin 

9 

10 

11class LinkPreview(ElementBase): 

12 name = "Description" 

13 namespace = "http://www.w3.org/1999/02/22-rdf-syntax-ns#" 

14 plugin_attrib = "link_preview" 

15 plugin_multi_attrib = "link_previews" 

16 interfaces = {"about", "title", "description", "url", "image", "type", "site_name"} 

17 

18 def _set_og(self, el: ElementBase, value: str) -> None: 

19 el.xml.text = value 

20 self.xml.append(el.xml) 

21 

22 def _get_og(self, el: Type[ElementBase]) -> Optional[str]: 

23 child = self.xml.find(f"{{{el.namespace}}}{el.name}") 

24 if child is None: 

25 return None 

26 return child.text 

27 

28 def set_title(self, v: str) -> None: 

29 self._set_og(Title(), v) 

30 

31 def get_title(self) -> Optional[str]: 

32 return self._get_og(Title) 

33 

34 def set_description(self, v: str) -> None: 

35 self._set_og(Description(), v) 

36 

37 def get_description(self) -> Optional[str]: 

38 return self._get_og(Description) 

39 

40 def set_url(self, v: str) -> None: 

41 self._set_og(Url(), v) 

42 

43 def get_url(self) -> Optional[str]: 

44 return self._get_og(Url) 

45 

46 def set_image(self, v: str) -> None: 

47 self._set_og(Image(), v) 

48 

49 def get_image(self) -> Optional[str]: 

50 return self._get_og(Image) 

51 

52 def set_type(self, v: str) -> None: 

53 self._set_og(Type_(), v) 

54 

55 def get_type(self) -> Optional[str]: 

56 return self._get_og(Type_) 

57 

58 def set_site_name(self, v: str) -> None: 

59 self._set_og(SiteName(), v) 

60 

61 def get_site_name(self) -> Optional[str]: 

62 return self._get_og(SiteName) 

63 

64 def get_about(self) -> Optional[str]: 

65 return self.xml.attrib.get(f"{{{self.namespace}}}about") 

66 

67 

68class OpenGraphMixin(ElementBase): 

69 namespace = "https://ogp.me/ns#" 

70 

71 

72class Title(OpenGraphMixin): 

73 name = plugin_attrib = "title" 

74 

75 

76class Description(OpenGraphMixin): 

77 name = plugin_attrib = "description" 

78 

79 

80class Url(OpenGraphMixin): 

81 name = plugin_attrib = "url" 

82 

83 

84class Image(OpenGraphMixin): 

85 name = plugin_attrib = "image" 

86 

87 

88class Type_(OpenGraphMixin): 

89 name = plugin_attrib = "type" 

90 

91 

92class SiteName(OpenGraphMixin): 

93 name = plugin_attrib = "site_name" 

94 

95 

96def register_plugin(): 

97 for plugin in Title, Description, Url, Image, Type_, SiteName: 

98 register_stanza_plugin(plugin, Title) 

99 register_stanza_plugin(Message, LinkPreview, iterable=True)