Skip to content

Commit aa0617a

Browse files
committed
Refactor Python Adaptive Cards
1 parent 613d499 commit aa0617a

13 files changed

+600
-559
lines changed

webexteamssdk/__init__.py

Lines changed: 5 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,7 @@
3232

3333
import logging
3434

35+
import webexteamssdk.models.cards as cards
3536
from ._metadata import *
3637
from ._version import get_versions
3738
from .api import WebexTeamsAPI
@@ -41,11 +42,11 @@
4142
)
4243
from .models.dictionary import dict_data_factory
4344
from .models.immutable import (
44-
AccessToken, AttachmentAction, Event, License, Membership, Message,
45-
Organization, Person, Role, Room, Team, TeamMembership, Webhook,
46-
WebhookEvent, immutable_data_factory,
45+
AccessToken, AttachmentAction, Event, immutable_data_factory, License,
46+
Membership, Message, Organization, Person, Role, Room, Team,
47+
TeamMembership, Webhook, WebhookEvent,
4748
)
48-
from .models.simple import SimpleDataModel, simple_data_factory
49+
from .models.simple import simple_data_factory, SimpleDataModel
4950
from .utils import WebexTeamsDateTime
5051

5152

@@ -56,7 +57,3 @@
5657
# Initialize Package Logging
5758
logger = logging.getLogger(__name__)
5859
logger.addHandler(logging.NullHandler())
59-
60-
from ._version import get_versions
61-
__version__ = get_versions()['version']
62-
del get_versions

webexteamssdk/api/messages.py

Lines changed: 8 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -35,11 +35,12 @@
3535
from past.builtins import basestring
3636
from requests_toolbelt import MultipartEncoder
3737

38+
from webexteamssdk.models.cards import AdaptiveCard
3839
from ..generator_containers import generator_container
3940
from ..restsession import RestSession
4041
from ..utils import (
4142
check_type, dict_from_items_with_values, is_local_file, is_web_url,
42-
make_card_attachment, open_local_file,
43+
make_attachment, open_local_file,
4344
)
4445

4546

@@ -191,11 +192,13 @@ def create(self, roomId=None, toPersonId=None, toPersonEmail=None,
191192
else:
192193
files = None
193194

195+
# Process and serialize attachments
194196
if attachments:
195-
for attachment in attachments:
196-
check_type(attachment, dict)
197-
else:
198-
attachments = None
197+
for item, attachment in enumerate(attachments):
198+
check_type(attachment, (dict, AdaptiveCard))
199+
200+
if isinstance(attachments, AdaptiveCard):
201+
attachments[item] = make_attachment(attachment)
199202

200203
post_data = dict_from_items_with_values(
201204
request_parameters,
@@ -208,17 +211,6 @@ def create(self, roomId=None, toPersonId=None, toPersonEmail=None,
208211
attachments=attachments,
209212
)
210213

211-
# Add cards
212-
if cards is not None:
213-
cards_list = []
214-
215-
if isinstance(cards, list):
216-
cards_list = [make_card_attachment(c) for c in cards]
217-
else:
218-
cards_list = [make_card_attachment(cards)]
219-
220-
post_data['attachments'] = cards_list
221-
222214
# API request
223215
if not files or is_web_url(files[0]):
224216
# Standard JSON post
Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
# -*- coding: utf-8 -*-
2+
"""Webex Teams Adaptive Cards data models.
3+
4+
Copyright (c) 2016-2019 Cisco and/or its affiliates.
5+
6+
Permission is hereby granted, free of charge, to any person obtaining a copy
7+
of this software and associated documentation files (the "Software"), to deal
8+
in the Software without restriction, including without limitation the rights
9+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10+
copies of the Software, and to permit persons to whom the Software is
11+
furnished to do so, subject to the following conditions:
12+
13+
The above copyright notice and this permission notice shall be included in all
14+
copies or substantial portions of the Software.
15+
16+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
22+
SOFTWARE.
23+
"""
24+
25+
from .adaptive_card_component import AdaptiveCardComponent
26+
from .card import AdaptiveCard
27+
from .components import (
28+
Choice, Column, Fact, Image, Media, MediaSource,
29+
TextBlock,
30+
)
31+
from .container import ColumnSet, Container, FactSet, ImageSet
32+
from .inputs import Choices, Date, Number, Text, Time, Toggle
33+
from .options import (
34+
BlockElementHeight, ChoiceInputStyle, Colors,
35+
ContainerStyle, FontSize, FontWeight, HorizontalAlignment, ImageSize,
36+
ImageStyle, Spacing, TextInputStyle, VerticalContentAlignment,
37+
)

webexteamssdk/models/cards/abstract_components.py

Lines changed: 0 additions & 111 deletions
This file was deleted.

webexteamssdk/models/cards/actions.py

Lines changed: 32 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
# -*- coding: utf-8 -*-
2-
"""Webex Teams Access-Tokens API wrapper.
2+
"""Webex Teams Adaptive Card actions.
33
44
Copyright (c) 2016-2019 Cisco and/or its affiliates.
55
@@ -22,39 +22,48 @@
2222
SOFTWARE.
2323
"""
2424

25-
from .abstract_components import Serializable
25+
from .adaptive_card_component import AdaptiveCardComponent
2626

27-
class OpenUrl(Serializable):
28-
def __init__(self, url, title=None,
29-
iconURL=None):
30-
self.type = "Action.OpenUrl"
27+
28+
class OpenUrl(AdaptiveCardComponent):
29+
"""Open URL Action."""
30+
type = "Action.OpenUrl"
31+
32+
def __init__(self, url, title=None, iconURL=None):
3133
self.title = title
3234
self.iconURL = iconURL
3335

34-
super().__init__(serializable_properties=[],
35-
simple_properties=['type', 'title', 'iconURL'])
36+
super().__init__(
37+
serializable_properties=[],
38+
simple_properties=['type', 'title', 'iconURL'],
39+
)
40+
3641

37-
class Submit(Serializable):
38-
def __init__(self, data=None,
39-
title=None,
40-
iconURL=None,
41-
):
42-
self.type = "Action.Submit"
42+
class Submit(AdaptiveCardComponent):
43+
"""Submit Action."""
44+
type = "Action.Submit"
45+
46+
def __init__(self, data=None, title=None, iconURL=None):
4347
self.data = data
4448
self.title = title
4549
self.iconURL = iconURL
4650

47-
super().__init__(serializable_properties=['data'],
48-
simple_properties=['title', 'iconURL', 'type'])
51+
super().__init__(
52+
serializable_properties=['data'],
53+
simple_properties=['title', 'iconURL', 'type'],
54+
)
55+
56+
57+
class ShowCard(AdaptiveCardComponent):
58+
"""Show Card Action."""
59+
type = "Action.ShowCard"
4960

50-
class ShowCard(Serializable):
51-
def __init__(self, card=None,
52-
title=None,
53-
iconURL=None):
54-
self.type = "Action.ShowCard"
61+
def __init__(self, card=None, title=None, iconURL=None):
5562
self.card = card
5663
self.title = title
5764
self.iconURL = iconURL
5865

59-
super().__init__(serializable_properties=['card'],
60-
simple_properties=['title', 'type', 'iconURL'])
66+
super().__init__(
67+
serializable_properties=['card'],
68+
simple_properties=['title', 'type', 'iconURL'],
69+
)
Lines changed: 88 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,88 @@
1+
# -*- coding: utf-8 -*-
2+
"""Webex Teams Adaptive Card Component base class.
3+
4+
Copyright (c) 2016-2019 Cisco and/or its affiliates.
5+
6+
Permission is hereby granted, free of charge, to any person obtaining a copy
7+
of this software and associated documentation files (the "Software"), to deal
8+
in the Software without restriction, including without limitation the rights
9+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10+
copies of the Software, and to permit persons to whom the Software is
11+
furnished to do so, subject to the following conditions:
12+
13+
The above copyright notice and this permission notice shall be included in all
14+
copies or substantial portions of the Software.
15+
16+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
22+
SOFTWARE.
23+
"""
24+
25+
import json
26+
27+
28+
class AdaptiveCardComponent:
29+
"""Base class for all Adaptive Card components.
30+
31+
Each component should inherit from this class and specify which of its
32+
properties fall into the following two categories:
33+
34+
* Simple properties are basic types (int, float, str, etc.).
35+
36+
* Serializable properties are properties that can themselves be serialized.
37+
This includes lists of items (i.e. the 'body' field of the adaptive card)
38+
or single objects that also inherit from Serializable
39+
"""
40+
def __init__(self, serializable_properties, simple_properties):
41+
"""Initialize a serializable object.
42+
43+
Args:
44+
serializable_properties(list): List of all serializable properties
45+
simple_properties(list): List of all simple properties.
46+
"""
47+
self.serializable_properties = serializable_properties
48+
self.simple_properties = simple_properties
49+
50+
def to_dict(self):
51+
"""Serialize the component into a Python dictionary.
52+
53+
The to_dict() method recursively serializes the object's data into
54+
a Python dictionary.
55+
56+
Returns:
57+
dict: Dictionary representation of this component.
58+
"""
59+
serialized_data = {}
60+
61+
# Serialize simple properties
62+
for property_name in self.simple_properties:
63+
property_value = getattr(self, property_name, None)
64+
65+
if property_value is not None:
66+
serialized_data[property_name] = str(property_value)
67+
68+
# Recursively serialize sub-components
69+
for property_name in self.serializable_properties:
70+
property_value = getattr(self, property_name, None)
71+
72+
if property_value is not None:
73+
if isinstance(property_value, list):
74+
serialized_data[property_name] = [
75+
item.to_dict() for item in property_value
76+
]
77+
else:
78+
serialized_data[property_name] = property_value.to_dict()
79+
80+
return serialized_data
81+
82+
def to_json(self, **kwargs):
83+
"""Serialize the component into JSON text.
84+
85+
Any keyword arguments provided are passed through the Python JSON
86+
encoder.
87+
"""
88+
return json.dumps(self.to_dict(), **kwargs)

0 commit comments

Comments
 (0)