Added onboarding progress tracking & landing page
This commit is contained in:
0
backend/services/integrations/README
Normal file
0
backend/services/integrations/README
Normal file
5
backend/services/integrations/wix/__init__.py
Normal file
5
backend/services/integrations/wix/__init__.py
Normal file
@@ -0,0 +1,5 @@
|
||||
"""
|
||||
Wix integration modular services package.
|
||||
"""
|
||||
|
||||
|
||||
82
backend/services/integrations/wix/auth.py
Normal file
82
backend/services/integrations/wix/auth.py
Normal file
@@ -0,0 +1,82 @@
|
||||
from typing import Any, Dict, Optional, Tuple
|
||||
import requests
|
||||
from loguru import logger
|
||||
import base64
|
||||
import hashlib
|
||||
import secrets
|
||||
|
||||
|
||||
class WixAuthService:
|
||||
def __init__(self, client_id: Optional[str], redirect_uri: str, base_url: str):
|
||||
self.client_id = client_id
|
||||
self.redirect_uri = redirect_uri
|
||||
self.base_url = base_url
|
||||
|
||||
def generate_authorization_url(self, state: Optional[str] = None) -> Tuple[str, str]:
|
||||
if not self.client_id:
|
||||
raise ValueError("Wix client ID not configured")
|
||||
code_verifier = base64.urlsafe_b64encode(secrets.token_bytes(32)).decode('utf-8').rstrip('=')
|
||||
code_challenge = base64.urlsafe_b64encode(
|
||||
hashlib.sha256(code_verifier.encode('utf-8')).digest()
|
||||
).decode('utf-8').rstrip('=')
|
||||
oauth_url = 'https://www.wix.com/oauth/authorize'
|
||||
from urllib.parse import urlencode
|
||||
params = {
|
||||
'client_id': self.client_id,
|
||||
'redirect_uri': self.redirect_uri,
|
||||
'response_type': 'code',
|
||||
'scope': 'BLOG.CREATE-DRAFT,BLOG.PUBLISH,MEDIA.MANAGE',
|
||||
'code_challenge': code_challenge,
|
||||
'code_challenge_method': 'S256'
|
||||
}
|
||||
if state:
|
||||
params['state'] = state
|
||||
return f"{oauth_url}?{urlencode(params)}", code_verifier
|
||||
|
||||
def exchange_code_for_tokens(self, code: str, code_verifier: str) -> Dict[str, Any]:
|
||||
headers = {'Content-Type': 'application/x-www-form-urlencoded'}
|
||||
data = {
|
||||
'grant_type': 'authorization_code',
|
||||
'code': code,
|
||||
'redirect_uri': self.redirect_uri,
|
||||
'client_id': self.client_id,
|
||||
'code_verifier': code_verifier,
|
||||
}
|
||||
token_url = f'{self.base_url}/oauth2/token'
|
||||
response = requests.post(token_url, headers=headers, data=data)
|
||||
response.raise_for_status()
|
||||
return response.json()
|
||||
|
||||
def refresh_access_token(self, refresh_token: str) -> Dict[str, Any]:
|
||||
headers = {'Content-Type': 'application/x-www-form-urlencoded'}
|
||||
data = {
|
||||
'grant_type': 'refresh_token',
|
||||
'refresh_token': refresh_token,
|
||||
'client_id': self.client_id,
|
||||
}
|
||||
token_url = f'{self.base_url}/oauth2/token'
|
||||
response = requests.post(token_url, headers=headers, data=data)
|
||||
response.raise_for_status()
|
||||
return response.json()
|
||||
|
||||
def get_site_info(self, access_token: str) -> Dict[str, Any]:
|
||||
headers = {
|
||||
'Authorization': f'Bearer {access_token}',
|
||||
'Content-Type': 'application/json'
|
||||
}
|
||||
response = requests.get(f"{self.base_url}/sites/v1/site", headers=headers)
|
||||
response.raise_for_status()
|
||||
return response.json()
|
||||
|
||||
def get_current_member(self, access_token: str, client_id: Optional[str]) -> Dict[str, Any]:
|
||||
headers = {
|
||||
'Authorization': f'Bearer {access_token}',
|
||||
'Content-Type': 'application/json'
|
||||
}
|
||||
if client_id:
|
||||
headers['wix-client-id'] = client_id
|
||||
response = requests.get(f"{self.base_url}/members/v1/members/my", headers=headers)
|
||||
response.raise_for_status()
|
||||
return response.json()
|
||||
|
||||
|
||||
60
backend/services/integrations/wix/blog.py
Normal file
60
backend/services/integrations/wix/blog.py
Normal file
@@ -0,0 +1,60 @@
|
||||
from typing import Any, Dict, List, Optional
|
||||
import requests
|
||||
from loguru import logger
|
||||
|
||||
|
||||
class WixBlogService:
|
||||
def __init__(self, base_url: str, client_id: Optional[str]):
|
||||
self.base_url = base_url
|
||||
self.client_id = client_id
|
||||
|
||||
def headers(self, access_token: str, extra: Optional[Dict[str, str]] = None) -> Dict[str, str]:
|
||||
h: Dict[str, str] = {
|
||||
'Authorization': f'Bearer {access_token}',
|
||||
'Content-Type': 'application/json',
|
||||
}
|
||||
if self.client_id:
|
||||
h['wix-client-id'] = self.client_id
|
||||
if extra:
|
||||
h.update(extra)
|
||||
return h
|
||||
|
||||
def create_draft_post(self, access_token: str, payload: Dict[str, Any], extra_headers: Optional[Dict[str, str]] = None) -> Dict[str, Any]:
|
||||
response = requests.post(f"{self.base_url}/blog/v3/draft-posts", headers=self.headers(access_token, extra_headers), json=payload)
|
||||
response.raise_for_status()
|
||||
return response.json()
|
||||
|
||||
def publish_draft(self, access_token: str, draft_post_id: str, extra_headers: Optional[Dict[str, str]] = None) -> Dict[str, Any]:
|
||||
response = requests.post(f"{self.base_url}/blog/v3/draft-posts/{draft_post_id}/publish", headers=self.headers(access_token, extra_headers))
|
||||
response.raise_for_status()
|
||||
return response.json()
|
||||
|
||||
def list_categories(self, access_token: str, extra_headers: Optional[Dict[str, str]] = None) -> List[Dict[str, Any]]:
|
||||
response = requests.get(f"{self.base_url}/blog/v3/categories", headers=self.headers(access_token, extra_headers))
|
||||
response.raise_for_status()
|
||||
return response.json().get('categories', [])
|
||||
|
||||
def create_category(self, access_token: str, label: str, description: Optional[str] = None, language: Optional[str] = None, extra_headers: Optional[Dict[str, str]] = None) -> Dict[str, Any]:
|
||||
payload: Dict[str, Any] = {'category': {'label': label}, 'fieldsets': ['URL']}
|
||||
if description:
|
||||
payload['category']['description'] = description
|
||||
if language:
|
||||
payload['category']['language'] = language
|
||||
response = requests.post(f"{self.base_url}/blog/v3/categories", headers=self.headers(access_token, extra_headers), json=payload)
|
||||
response.raise_for_status()
|
||||
return response.json()
|
||||
|
||||
def list_tags(self, access_token: str, extra_headers: Optional[Dict[str, str]] = None) -> List[Dict[str, Any]]:
|
||||
response = requests.get(f"{self.base_url}/blog/v3/tags", headers=self.headers(access_token, extra_headers))
|
||||
response.raise_for_status()
|
||||
return response.json().get('tags', [])
|
||||
|
||||
def create_tag(self, access_token: str, label: str, language: Optional[str] = None, extra_headers: Optional[Dict[str, str]] = None) -> Dict[str, Any]:
|
||||
payload: Dict[str, Any] = {'label': label, 'fieldsets': ['URL']}
|
||||
if language:
|
||||
payload['language'] = language
|
||||
response = requests.post(f"{self.base_url}/blog/v3/tags", headers=self.headers(access_token, extra_headers), json=payload)
|
||||
response.raise_for_status()
|
||||
return response.json()
|
||||
|
||||
|
||||
59
backend/services/integrations/wix/content.py
Normal file
59
backend/services/integrations/wix/content.py
Normal file
@@ -0,0 +1,59 @@
|
||||
from typing import Any, Dict, List
|
||||
|
||||
|
||||
def convert_content_to_ricos(content: str, images: List[str] = None) -> Dict[str, Any]:
|
||||
"""
|
||||
Convert simple markdown-like text into minimal valid Ricos JSON.
|
||||
"""
|
||||
paragraphs = content.split('\n\n')
|
||||
nodes = []
|
||||
|
||||
import uuid
|
||||
|
||||
for paragraph in paragraphs:
|
||||
text = paragraph.strip()
|
||||
if not text:
|
||||
continue
|
||||
node_id = str(uuid.uuid4())
|
||||
text_node_id = str(uuid.uuid4())
|
||||
|
||||
if text.startswith('#'):
|
||||
level = len(text) - len(text.lstrip('#'))
|
||||
heading_text = text.lstrip('# ').strip()
|
||||
nodes.append({
|
||||
'id': node_id,
|
||||
'type': 'HEADING',
|
||||
'nodes': [{
|
||||
'id': text_node_id,
|
||||
'type': 'TEXT',
|
||||
'textData': {
|
||||
'text': heading_text,
|
||||
'decorations': []
|
||||
}
|
||||
}],
|
||||
'headingData': { 'level': min(level, 6) }
|
||||
})
|
||||
else:
|
||||
nodes.append({
|
||||
'id': node_id,
|
||||
'type': 'PARAGRAPH',
|
||||
'nodes': [{
|
||||
'id': text_node_id,
|
||||
'type': 'TEXT',
|
||||
'textData': {
|
||||
'text': text,
|
||||
'decorations': []
|
||||
}
|
||||
}],
|
||||
'paragraphData': {}
|
||||
})
|
||||
|
||||
return {
|
||||
'nodes': nodes,
|
||||
'metadata': { 'version': 1, 'id': str(uuid.uuid4()) },
|
||||
'documentStyle': {
|
||||
'paragraph': { 'decorations': [], 'nodeStyle': {}, 'lineHeight': '1.5' }
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
23
backend/services/integrations/wix/media.py
Normal file
23
backend/services/integrations/wix/media.py
Normal file
@@ -0,0 +1,23 @@
|
||||
from typing import Any, Dict
|
||||
import requests
|
||||
|
||||
|
||||
class WixMediaService:
|
||||
def __init__(self, base_url: str):
|
||||
self.base_url = base_url
|
||||
|
||||
def import_image(self, access_token: str, image_url: str, display_name: str) -> Dict[str, Any]:
|
||||
headers = {
|
||||
'Authorization': f'Bearer {access_token}',
|
||||
'Content-Type': 'application/json',
|
||||
}
|
||||
payload = {
|
||||
'url': image_url,
|
||||
'mediaType': 'IMAGE',
|
||||
'displayName': display_name,
|
||||
}
|
||||
response = requests.post(f"{self.base_url}/media/v1/files/import", headers=headers, json=payload)
|
||||
response.raise_for_status()
|
||||
return response.json()
|
||||
|
||||
|
||||
109
backend/services/integrations/wix/utils.py
Normal file
109
backend/services/integrations/wix/utils.py
Normal file
@@ -0,0 +1,109 @@
|
||||
from typing import Any, Dict, Optional
|
||||
import jwt
|
||||
import json
|
||||
|
||||
|
||||
def normalize_token_string(access_token: Any) -> Optional[str]:
|
||||
try:
|
||||
if isinstance(access_token, str):
|
||||
return access_token
|
||||
if isinstance(access_token, dict):
|
||||
token_str = access_token.get('access_token') or access_token.get('value')
|
||||
if token_str:
|
||||
return token_str
|
||||
at = access_token.get('accessToken')
|
||||
if isinstance(at, dict):
|
||||
return at.get('value')
|
||||
if isinstance(at, str):
|
||||
return at
|
||||
return None
|
||||
except Exception:
|
||||
return None
|
||||
|
||||
|
||||
def extract_member_id_from_access_token(access_token: Any) -> Optional[str]:
|
||||
try:
|
||||
token_str: Optional[str] = None
|
||||
if isinstance(access_token, str):
|
||||
token_str = access_token
|
||||
elif isinstance(access_token, dict):
|
||||
token_str = access_token.get('access_token') or access_token.get('value')
|
||||
if not token_str:
|
||||
at = access_token.get('accessToken')
|
||||
if isinstance(at, dict):
|
||||
token_str = at.get('value')
|
||||
elif isinstance(at, str):
|
||||
token_str = at
|
||||
if not token_str:
|
||||
return None
|
||||
|
||||
if token_str.startswith('OauthNG.JWS.'):
|
||||
jwt_part = token_str[12:]
|
||||
data = jwt.decode(jwt_part, options={"verify_signature": False, "verify_aud": False})
|
||||
else:
|
||||
data = jwt.decode(token_str, options={"verify_signature": False, "verify_aud": False})
|
||||
|
||||
data_payload = data.get('data')
|
||||
if isinstance(data_payload, str):
|
||||
try:
|
||||
data_payload = json.loads(data_payload)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
if isinstance(data_payload, dict):
|
||||
instance = data_payload.get('instance', {})
|
||||
if isinstance(instance, dict):
|
||||
site_member_id = instance.get('siteMemberId')
|
||||
if isinstance(site_member_id, str) and site_member_id:
|
||||
return site_member_id
|
||||
for key in ['memberId', 'sub', 'authorizedSubject', 'id', 'siteMemberId']:
|
||||
val = data_payload.get(key)
|
||||
if isinstance(val, str) and val:
|
||||
return val
|
||||
member = data_payload.get('member') or {}
|
||||
if isinstance(member, dict):
|
||||
val = member.get('id')
|
||||
if isinstance(val, str) and val:
|
||||
return val
|
||||
|
||||
for key in ['memberId', 'sub', 'authorizedSubject']:
|
||||
val = data.get(key)
|
||||
if isinstance(val, str) and val:
|
||||
return val
|
||||
member = data.get('member') or {}
|
||||
if isinstance(member, dict):
|
||||
val = member.get('id')
|
||||
if isinstance(val, str) and val:
|
||||
return val
|
||||
return None
|
||||
except Exception:
|
||||
return None
|
||||
|
||||
|
||||
def decode_wix_token(access_token: str) -> Dict[str, Any]:
|
||||
token_str = str(access_token)
|
||||
if token_str.startswith('OauthNG.JWS.'):
|
||||
jwt_part = token_str[12:]
|
||||
return jwt.decode(jwt_part, options={"verify_signature": False, "verify_aud": False})
|
||||
return jwt.decode(token_str, options={"verify_signature": False, "verify_aud": False})
|
||||
|
||||
|
||||
def extract_meta_from_token(access_token: str) -> Dict[str, Optional[str]]:
|
||||
try:
|
||||
payload = decode_wix_token(access_token)
|
||||
data_payload = payload.get('data', {})
|
||||
if isinstance(data_payload, str):
|
||||
try:
|
||||
data_payload = json.loads(data_payload)
|
||||
except Exception:
|
||||
pass
|
||||
instance = (data_payload or {}).get('instance', {})
|
||||
return {
|
||||
'siteMemberId': instance.get('siteMemberId'),
|
||||
'metaSiteId': instance.get('metaSiteId'),
|
||||
'permissions': instance.get('permissions'),
|
||||
}
|
||||
except Exception:
|
||||
return {'siteMemberId': None, 'metaSiteId': None, 'permissions': None}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user