def copy_courses()

in microservices/lms/src/routes/classroom_courses.py [0:0]


def copy_courses(course_details: CourseDetails):
  """Copy course  API

  Args:
    course_id (Course): Course_id of a course that needs to copied

  Raises:
    HTTPException: 500 Internal Server Error if something fails

  Returns:
    {"status":"Success","new_course":{}}: Returns new course details,
    {'status': 'Failed'} if the user creation raises an exception
  """
  try:
    input_course_details_dict = {**course_details.dict()}
    course_id = input_course_details_dict["course_id"]
    # Get course by course id
    current_course = classroom_crud.get_course_by_id(course_id)
    if current_course is None:
      return "No course found "
    # Create a new course
    new_course = classroom_crud.create_course(current_course["name"],
                                              current_course["description"],
                                              current_course["section"],
                                              current_course["ownerId"]
                                              )
    target_folder_id = new_course["teacherFolder"]["id"]
    # Get topics of current course
    topics = classroom_crud.get_topics(course_id)
    # If topics are present in course create topics returns a dict
    # with keys a current topicID and new topic id as values
    if topics is not None:
      topic_id_map = classroom_crud.create_topics(new_course["id"], topics)
    # Get coursework of current course and create a new course
    coursework_list = classroom_crud.get_coursework_list(course_id)
    final_coursework =[]
    for coursework in coursework_list:
      try:
        # Check if a coursework is linked to
        #  a topic if yes then
        # replace the old topic id to new
        # topic id using topic_id_map
        if "topicId" in coursework.keys():
          coursework["topicId"] = topic_id_map[coursework["topicId"]]
        # Check if a material is present in coursework
        if "materials" in coursework.keys():
          # Calling function to get edit_url and view url of google
          #  form which returns
          # a dictionary of view_links as keys and edit links as
          # values of google form
          url_mapping = classroom_crud.\
            get_edit_url_and_view_url_mapping_of_form()
          # Loop to check if a material in courssework has
          #  a google form attached to it
          # update the  view link to edit link and attach it as a form
          for material in coursework["materials"]:
            if "driveFile" in  material.keys():
              material = classroom_crud.copy_material(material,target_folder_id)
            if "form" in material.keys():
              if "title" not in material["form"].keys():
                raise ResourceNotFound("Form to be copied is deleted")
              result1 = classroom_crud.drive_copy(
                url_mapping[material["form"]["formUrl"]]["file_id"],
                      target_folder_id,material["form"]["title"])
              material["link"] = {
                  "title": material["form"]["title"],
                  "url": result1["webViewLink"]
              }
              # remove form from  material dict
              material.pop("form")
        final_coursework.append(coursework)
      except Exception as error:
        title = coursework["title"]
        Logger.error(f"Get coursework failed for {title}")
        error=traceback.format_exc().replace("\n", " ")
        Logger.error(error)
        continue

    # Create coursework in new course
    if final_coursework is not None:
      for course_work in final_coursework:
        classroom_crud.create_coursework(new_course["id"], course_work)
    # Get the list of courseworkMaterial
    coursework_material_list = classroom_crud.get_coursework_material_list(
        course_id)
    final_coursework_material=[]
    for coursework_material in coursework_material_list:
      try:
        # Check if a coursework material is linked to a topic if yes then
        # replace the old topic id to new topic id using topic_id_map
        if "topicId" in coursework_material.keys():
          coursework_material["topicId"] = topic_id_map[
              coursework_material["topicId"]]
        # Check if a material is present in coursework
        if "materials" in coursework_material.keys():
          # Calling function to get edit_url and view url of
          # google form which returns
          # a dictionary of view_links as keys and edit
          #  links as values of google form
          url_mapping = classroom_crud.\
            get_edit_url_and_view_url_mapping_of_form()
          # Loop to check if a material in coursework has a google
          # form attached to it
          # update the  view link to edit link and attach it as a form
          for material in coursework_material["materials"]:
            if "driveFile" in  material.keys():
              material = classroom_crud.copy_material(material,target_folder_id)
            if "form" in material.keys():
              if "title" not in material["form"].keys():
                raise ResourceNotFound("Form to be copied is deleted")
              new_copied_file_details = classroom_crud.drive_copy(
                url_mapping[material["form"]["formUrl"]]["file_id"],
                      target_folder_id,material["form"]["title"])
              material["link"] = {
                  "title": material["form"]["title"],
                  "url": new_copied_file_details["webViewLink"]
              }
              # remove form from  material dict
              material.pop("form")
        final_coursework_material.append(coursework_material)
      except Exception as error:
        title = coursework_material["title"]
        error=traceback.format_exc().replace("\n", " ")
        Logger.error(
          f"Get coursework material failed for {title}")
        Logger.error(error)
        continue
    # Create coursework in new course
    if final_coursework_material is not None:
      for course_work_material in final_coursework_material:
        classroom_crud.create_coursework_material(new_course["id"],
                                                course_work_material)
    response={}
    response["new_course"] = new_course
    response["coursework_list"] = final_coursework
    response["coursework_material"]=final_coursework_material
    return {"data":response}
  except HttpError as hte:
    Logger.error(hte)
    raise ClassroomHttpException(status_code=hte.resp.status,
                              message=str(hte)) from hte
  except Exception as e:
    err = traceback.format_exc().replace("\n", " ")
    Logger.error(err)
    raise InternalServerError(str(e)) from e