diff --git a/build/api.py b/build/api.py index ea8e08b..5a93100 100644 --- a/build/api.py +++ b/build/api.py @@ -6,6 +6,7 @@ """ import os from pathlib import Path +from urllib.parse import urljoin import frontmatter from frappeclient import FrappeClient @@ -73,6 +74,19 @@ def save_document(self, doctype, name, doc): print(doctype, name, "saving...") return self.invoke_method("mon_school.api.save_document", data=data) + def add_attachment(self, filename, doctype, docname, fieldname): + files = {"file": open(filename, "rb")} + data = { + "is_private": 0, + "doctype": doctype, + "docname": docname, + "fieldname": fieldname, + "folder": "Home" + } + url = urljoin(self.frappe.url, "/api/method/upload_file") + r = self.frappe.session.post(url, files=files, data=data) + return r.json()['message']['file_url'] + def trim_tables(self, doc): def trim(d): ignore = "name owner creation modified modified_by parent parentfield parenttype idx docstatus doctype".split() @@ -117,6 +131,8 @@ def update_course(self, course: Course): for chapter in course.chapters: self.update_chapter(chapter) + self.update_course_preview_image(course) + def update_chapter(self, chapter: Chapter): doc = chapter.get_doc() self.ensure_doc("Course Chapter", doc['name'], course=doc['course']) @@ -149,3 +165,13 @@ def ensure_doc(self, doctype, name, **fields): if not self.exists(doctype, name): doc = dict(DEFAULTS[doctype], **fields) self.save_document(doctype, name, doc) + + def update_course_preview_image(self, course: Course): + if course.preview_image: + path = str(course.root / course.preview_image) + print("upload preview_image", path) + file_url = self.add_attachment(path, + doctype="LMS Course", + docname=course.name, + fieldname="image") + self.save_document("LMS Course", course.name, {"image": file_url}) diff --git a/build/workspace.py b/build/workspace.py index b6dd1b5..ad55b47 100644 --- a/build/workspace.py +++ b/build/workspace.py @@ -38,6 +38,7 @@ def read_course(self, name: str) -> Course: description=data['description'], instructor=data['instructor'], draft=data.get('draft', False), + preview_image=data.get("preview_image", None), is_published=data['is_published'], upcoming=data['upcoming'], tags=data['tags'], @@ -81,6 +82,7 @@ class Course: video_link: str chapters: List[Chapter] draft: bool = False + preview_image: str = None def get_doc(self) -> dict: doc = CourseDoc( diff --git a/tests/test_workspace.py b/tests/test_workspace.py index 99e9295..a913852 100644 --- a/tests/test_workspace.py +++ b/tests/test_workspace.py @@ -11,6 +11,7 @@ draft: false, is_published: true upcoming: true +preview_image: null tags: - python - beginner