def update_coursework_material()

in microservices/lms/src/services/section_service.py [0:0]


def update_coursework_material(materials,
                               target_folder_id,
                               error_flag,
                               lti_assignment_details=None,
                               logs=None):
  """Takes the material attached to any type of cursework and copy it in the
    target folder Id also removes duplicates from material list
  Args:
    materials (list of dictionary): Coursework materials list which is obtained
      from list coursework method
    url_mapping (dict):Dict of view url as key and edit url, fileid as values
    target_folder_id(str):Drive folder Id of section
  Returns:
    updated_material : (list of dict) returns a updated
  """
  drive_ids = []
  youtube_ids = []
  link_urls = []
  updated_material = []
  lti_assignment_ids = []
  # Loop to check the different types of material attached to coursework
  # 1.If a material is driveFile call called copy_material function which
  #  copies is drivefile in target_folder_id and updates the driveFile
  #  dict with new file id for section drive folder
  # 2.If a material is YoutubeVideo or link check for duplicate youtube
  #   video and link
  # 3.If a material is form use url_mapping dictionary to get the file_id
  # of form which is used to copy form in target_folder_id of section and
  # attach form as link in coursework since attaching forms via api is not
  # supported by classroom

  for material in materials:
    if "driveFile" in material.keys():
      if material["driveFile"]["driveFile"]["id"] not in drive_ids:
        classroom_crud.copy_material(material, target_folder_id)
        drive_ids.append(material["driveFile"]["driveFile"]["id"])
        updated_material.append({"driveFile": material["driveFile"]})

    if "youtubeVideo" in material.keys():
      if material["youtubeVideo"]["id"] not in youtube_ids:
        youtube_ids.append(material["youtubeVideo"]["id"])
        updated_material.append({"youtubeVideo": material["youtubeVideo"]})
    if "link" in material.keys():
      if material["link"]["url"] not in link_urls:
        link = material["link"]

        # Update lti assignment with the course work/course work material details
        if "/classroom-shim/api/v1/launch?lti_assignment_id=" in link["url"]:
          split_url = link["url"].split(
              "/classroom-shim/api/v1/launch?lti_assignment_id=")
          lti_assignment_id = split_url[-1]
          coursework_title = lti_assignment_details.get("coursework_title")
          logs["info"].append(
              f"LTI Course copy started for assignment - {lti_assignment_id}, coursework title - '{coursework_title}'")
          Logger.info(
              f"LTI Course copy started for assignment - {lti_assignment_id}, coursework title - '{coursework_title}'")
          copy_assignment = requests.post(
              "http://classroom-shim/classroom-shim/api/v1/lti-assignment/copy",
              headers={
                  "Authorization": f"Bearer {auth_client.get_id_token()}"
              },
              json={
                  "lti_assignment_id": lti_assignment_id,
                  "context_id": lti_assignment_details.get("section_id"),
                  "source_context_id": lti_assignment_details.get("source_context_id"),
                  "start_date": lti_assignment_details.get("start_date"),
                  "end_date": lti_assignment_details.get("end_date"),
                  "due_date": lti_assignment_details.get("due_date")
              },
              timeout=60)

          if copy_assignment.status_code == 200:
            new_lti_assignment_id = copy_assignment.json().get("data").get(
                "id")
            updated_material_link_url = link["url"].replace(
                lti_assignment_id, new_lti_assignment_id)
            lti_assignment_ids.append(new_lti_assignment_id)

            updated_material.append(
                {"link": {
                    "url": updated_material_link_url
                }})
            Logger.info(
                f"LTI Course copy completed for assignment - {lti_assignment_id}, coursework title - '{coursework_title}', new assignment id - {new_lti_assignment_id}"
            )
            logs["info"].append(
                f"LTI Course copy completed for assignment - {lti_assignment_id}, coursework title - '{coursework_title}', new assignment id - {new_lti_assignment_id}"
            )
          else:
            logs["info"].append(
                f"LTI Course copy failed for assignment - {lti_assignment_id}, coursework title - '{coursework_title}'"
            )
            error_msg = f"Copying an LTI Assignment failed for {lti_assignment_id}, coursework title - '{coursework_title}'\
                          in the new section {lti_assignment_details.get('section_id')} with status code: \
                          {copy_assignment.status_code} and error msg: {copy_assignment.text}"

            logs["errors"].append(error_msg)
            Logger.error(error_msg)
            error_flag = True
        else:
          updated_material.append({"link": material["link"]})

        link_urls.append(material["link"]["url"])

    if "form" in material.keys():
      if "title" not in material["form"].keys():
        raise ResourceNotFound("Form to be copied is deleted")
      # check_form = url_mapping.get(material["form"]["formUrl"])
      # if not check_form:
      #   raise ResourceNotFound("Google form attachment not found.\
      #   Please verify if form is present classroom template drive folder")
      form_url = material["form"]["formUrl"]
      form_l = form_url.split("/")
      form_id = form_l[-2]
      Logger.info(f"This is form ID {form_id}")
      result1 = classroom_crud.drive_copy(
          form_id, target_folder_id,
          material["form"]["title"])
      material["link"] = {
          "title": material["form"]["title"],
          "url": result1["webViewLink"]
      }
      updated_material.append({"link": material["link"]})
      material.pop("form")

  return {
      "material": updated_material,
      "error_flag": error_flag,
      "lti_assignment_ids": lti_assignment_ids
  }