|
| 1 | +""" |
| 2 | +Copyright 2022 Google LLC |
| 3 | +
|
| 4 | +Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | +you may not use this file except in compliance with the License. |
| 6 | +You may obtain a copy of the License at |
| 7 | +
|
| 8 | + http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | +
|
| 10 | +Unless required by applicable law or agreed to in writing, software |
| 11 | +distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | +See the License for the specific language governing permissions and |
| 14 | +limitations under the License. |
| 15 | +""" |
| 16 | +# [START drive_touch_file] |
| 17 | + |
| 18 | +from __future__ import print_function |
| 19 | + |
| 20 | +from datetime import datetime |
| 21 | + |
| 22 | +import google.auth |
| 23 | +from googleapiclient.discovery import build |
| 24 | +from googleapiclient.errors import HttpError |
| 25 | + |
| 26 | + |
| 27 | +def touch_file(real_file_id, real_timestamp): |
| 28 | + """Change the file's modification timestamp. |
| 29 | + Args: |
| 30 | + real_file_id: ID of the file to change modified time |
| 31 | + real_timestamp: Timestamp to override Modified date time of the file |
| 32 | + Returns : Modified Date and time. |
| 33 | +
|
| 34 | + Load pre-authorized user credentials from the environment. |
| 35 | + TODO(developer) - See https://developers.google.com/identity |
| 36 | + for guides on implementing OAuth2 for the application. |
| 37 | + """ |
| 38 | + creds, _ = google.auth.default() |
| 39 | + |
| 40 | + try: |
| 41 | + # create gmail api client |
| 42 | + service = build('drive', 'v3', credentials=creds) |
| 43 | + |
| 44 | + file_metadata = { |
| 45 | + 'modifiedTime': datetime.utcnow().isoformat() + 'Z' |
| 46 | + } |
| 47 | + # pylint: disable=maybe-no-member |
| 48 | + file_id = real_file_id |
| 49 | + file_metadata['modifiedTime'] = real_timestamp |
| 50 | + file = service.files().update(fileId=file_id, body=file_metadata, |
| 51 | + fields='id, modifiedTime').execute() |
| 52 | + print(F'Modified time: {file.get("modifiedTime")}') |
| 53 | + |
| 54 | + except HttpError as error: |
| 55 | + print(F'An error occurred: {error}') |
| 56 | + file = None |
| 57 | + |
| 58 | + return file.get('modifiedDate') |
| 59 | + |
| 60 | + |
| 61 | +if __name__ == '__main__': |
| 62 | + touch_file(real_file_id='17EqlSf7FpPU95SS00sICyVzQHpeET1cz', |
| 63 | + real_timestamp='2022-03-02T05:43:27.504Z') |
| 64 | +# [END drive_touch_file] |
0 commit comments