From 3e93e5314e6ceaa3a6159ccbec4f7d14f3515c6c Mon Sep 17 00:00:00 2001 From: Jeremy Bicha Date: Wed, 30 Sep 2020 00:26:01 +0100 Subject: [PATCH 1/1] Import libgdata_0.17.13.orig.tar.xz [dgit import orig libgdata_0.17.13.orig.tar.xz] --- AUTHORS | 1 + COPYING | 504 ++ HACKING | 216 + NEWS | 1684 ++++++ README | 64 + demos/calendar/calendar-cli.c | 553 ++ demos/docs-list/docs-list.c | 120 + demos/docs-property/docs-property.c | 258 + demos/meson.build | 32 + demos/scrapbook/scrapbook.c | 721 +++ demos/scrapbook/scrapbook.h | 188 + demos/tasks/tasks-cli.c | 350 ++ demos/youtube/youtube-cli.c | 585 ++ docs/reference/cancellation.dia | Bin 0 -> 1273 bytes docs/reference/cancellation.png | Bin 0 -> 7849 bytes docs/reference/data-flow.dia | Bin 0 -> 1657 bytes docs/reference/data-flow.png | Bin 0 -> 24681 bytes docs/reference/gdata-docs.xml | 318 ++ docs/reference/gdata-overrides.txt | 0 docs/reference/gdata-overview.xml | 244 + docs/reference/gdata-running.xml | 84 + docs/reference/gdata-sections.txt.in | 2911 ++++++++++ docs/reference/meson.build | 78 + docs/reference/structure.dia | Bin 0 -> 1803 bytes docs/reference/structure.png | Bin 0 -> 22102 bytes docs/reference/xml/gtkdocentities.ent.in | 7 + docs/reference/xml/meson.build | 15 + gdata/GData-0.0.metadata | 12 + gdata/app/gdata-app-categories.c | 255 + gdata/app/gdata-app-categories.h | 77 + gdata/app/meson.build | 10 + gdata/atom/gdata-author.c | 377 ++ gdata/atom/gdata-author.h | 81 + gdata/atom/gdata-category.c | 377 ++ gdata/atom/gdata-category.h | 121 + gdata/atom/gdata-generator.c | 264 + gdata/atom/gdata-generator.h | 74 + gdata/atom/gdata-link.c | 625 ++ gdata/atom/gdata-link.h | 190 + gdata/atom/meson.build | 20 + gdata/exif/gdata-exif-tags.c | 343 ++ gdata/exif/gdata-exif-tags.h | 83 + gdata/exif/meson.build | 1 + gdata/gcontact/gdata-gcontact-calendar.c | 478 ++ gdata/gcontact/gdata-gcontact-calendar.h | 123 + gdata/gcontact/gdata-gcontact-event.c | 446 ++ gdata/gcontact/gdata-gcontact-event.h | 108 + gdata/gcontact/gdata-gcontact-external-id.c | 406 ++ gdata/gcontact/gdata-gcontact-external-id.h | 132 + gdata/gcontact/gdata-gcontact-jot.c | 308 + gdata/gcontact/gdata-gcontact-jot.h | 140 + gdata/gcontact/gdata-gcontact-language.c | 327 ++ gdata/gcontact/gdata-gcontact-language.h | 80 + gdata/gcontact/gdata-gcontact-relation.c | 406 ++ gdata/gcontact/gdata-gcontact-relation.h | 252 + gdata/gcontact/gdata-gcontact-website.c | 481 ++ gdata/gcontact/gdata-gcontact-website.h | 171 + gdata/gcontact/meson.build | 26 + gdata/gd/gdata-gd-email-address.c | 520 ++ gdata/gd/gdata-gd-email-address.h | 117 + gdata/gd/gdata-gd-feed-link.c | 447 ++ gdata/gd/gdata-gd-feed-link.h | 84 + gdata/gd/gdata-gd-im-address.c | 526 ++ gdata/gd/gdata-gd-im-address.h | 198 + gdata/gd/gdata-gd-name.c | 589 ++ gdata/gd/gdata-gd-name.h | 92 + gdata/gd/gdata-gd-organization.c | 826 +++ gdata/gd/gdata-gd-organization.h | 121 + gdata/gd/gdata-gd-phone-number.c | 562 ++ gdata/gd/gdata-gd-phone-number.h | 270 + gdata/gd/gdata-gd-postal-address.c | 1342 +++++ gdata/gd/gdata-gd-postal-address.h | 205 + gdata/gd/gdata-gd-reminder.c | 467 ++ gdata/gd/gdata-gd-reminder.h | 111 + gdata/gd/gdata-gd-when.c | 593 ++ gdata/gd/gdata-gd-when.h | 172 + gdata/gd/gdata-gd-where.c | 407 ++ gdata/gd/gdata-gd-where.h | 110 + gdata/gd/gdata-gd-who.c | 414 ++ gdata/gd/gdata-gd-who.h | 122 + gdata/gd/meson.build | 33 + gdata/gdata-access-handler.c | 251 + gdata/gdata-access-handler.h | 109 + gdata/gdata-access-rule.c | 661 +++ gdata/gdata-access-rule.h | 118 + gdata/gdata-authorization-domain.c | 197 + gdata/gdata-authorization-domain.h | 78 + gdata/gdata-authorizer.c | 312 + gdata/gdata-authorizer.h | 92 + gdata/gdata-batch-feed.c | 170 + gdata/gdata-batch-feed.h | 73 + gdata/gdata-batch-operation.c | 825 +++ gdata/gdata-batch-operation.h | 150 + gdata/gdata-batch-private.h | 44 + gdata/gdata-batchable.c | 81 + gdata/gdata-batchable.h | 76 + gdata/gdata-buffer.c | 351 ++ gdata/gdata-buffer.h | 59 + gdata/gdata-client-login-authorizer.c | 1344 +++++ gdata/gdata-client-login-authorizer.h | 141 + gdata/gdata-comment.c | 54 + gdata/gdata-comment.h | 72 + gdata/gdata-commentable.c | 598 ++ gdata/gdata-commentable.h | 103 + gdata/gdata-comparable.c | 95 + gdata/gdata-comparable.h | 66 + gdata/gdata-core.symbols | 1128 ++++ gdata/gdata-download-stream.c | 1100 ++++ gdata/gdata-download-stream.h | 87 + gdata/gdata-entry.c | 1300 +++++ gdata/gdata-entry.h | 111 + gdata/gdata-feed.c | 1175 ++++ gdata/gdata-feed.h | 98 + gdata/gdata-goa-authorizer.c | 401 ++ gdata/gdata-goa-authorizer.h | 79 + gdata/gdata-goa.symbols | 3 + gdata/gdata-marshal.list | 2 + gdata/gdata-oauth1-authorizer.c | 1498 +++++ gdata/gdata-oauth1-authorizer.h | 108 + gdata/gdata-oauth2-authorizer.c | 1592 ++++++ gdata/gdata-oauth2-authorizer.h | 137 + gdata/gdata-parsable.c | 781 +++ gdata/gdata-parsable.h | 135 + gdata/gdata-parser.c | 1295 +++++ gdata/gdata-parser.h | 124 + gdata/gdata-private.h | 174 + gdata/gdata-query.c | 1222 ++++ gdata/gdata-query.h | 102 + gdata/gdata-service.c | 2499 ++++++++ gdata/gdata-service.h | 247 + gdata/gdata-types.c | 134 + gdata/gdata-types.h | 50 + gdata/gdata-upload-stream.c | 1660 ++++++ gdata/gdata-upload-stream.h | 124 + gdata/gdata-version.h.in | 80 + gdata/gdata.h | 162 + gdata/georss/gdata-georss-where.c | 223 + gdata/georss/gdata-georss-where.h | 77 + gdata/georss/meson.build | 1 + gdata/media/gdata-media-category.c | 388 ++ gdata/media/gdata-media-category.h | 81 + gdata/media/gdata-media-content.c | 573 ++ gdata/media/gdata-media-content.h | 121 + gdata/media/gdata-media-credit.c | 268 + gdata/media/gdata-media-credit.h | 74 + gdata/media/gdata-media-group.c | 667 +++ gdata/media/gdata-media-group.h | 93 + gdata/media/gdata-media-thumbnail.c | 434 ++ gdata/media/gdata-media-thumbnail.h | 80 + gdata/media/meson.build | 53 + gdata/meson.build | 205 + .../calendar/gdata-calendar-access-rule.c | 277 + .../calendar/gdata-calendar-access-rule.h | 125 + .../calendar/gdata-calendar-calendar.c | 805 +++ .../calendar/gdata-calendar-calendar.h | 86 + .../services/calendar/gdata-calendar-event.c | 1815 ++++++ .../services/calendar/gdata-calendar-event.h | 105 + gdata/services/calendar/gdata-calendar-feed.c | 158 + gdata/services/calendar/gdata-calendar-feed.h | 78 + .../services/calendar/gdata-calendar-query.c | 974 ++++ .../services/calendar/gdata-calendar-query.h | 99 + .../calendar/gdata-calendar-service.c | 918 +++ .../calendar/gdata-calendar-service.h | 129 + gdata/services/calendar/meson.build | 24 + .../contacts/gdata-contacts-contact.c | 3487 ++++++++++++ .../contacts/gdata-contacts-contact.h | 305 + .../services/contacts/gdata-contacts-group.c | 601 ++ .../services/contacts/gdata-contacts-group.h | 118 + .../services/contacts/gdata-contacts-query.c | 488 ++ .../services/contacts/gdata-contacts-query.h | 85 + .../contacts/gdata-contacts-service.c | 568 ++ .../contacts/gdata-contacts-service.h | 110 + gdata/services/contacts/meson.build | 20 + .../documents/gdata-documents-access-rule.c | 230 + .../documents/gdata-documents-access-rule.h | 75 + .../documents/gdata-documents-document.c | 556 ++ .../documents/gdata-documents-document.h | 84 + .../documents/gdata-documents-drawing.c | 88 + .../documents/gdata-documents-drawing.h | 130 + .../documents/gdata-documents-entry-private.h | 33 + .../documents/gdata-documents-entry.c | 1421 +++++ .../documents/gdata-documents-entry.h | 130 + .../services/documents/gdata-documents-feed.c | 185 + .../services/documents/gdata-documents-feed.h | 73 + .../documents/gdata-documents-folder.c | 157 + .../documents/gdata-documents-folder.h | 76 + .../documents/gdata-documents-metadata.c | 230 + .../documents/gdata-documents-metadata.h | 77 + .../services/documents/gdata-documents-pdf.c | 88 + .../services/documents/gdata-documents-pdf.h | 77 + .../documents/gdata-documents-presentation.c | 87 + .../documents/gdata-documents-presentation.h | 147 + .../documents/gdata-documents-property.c | 472 ++ .../documents/gdata-documents-property.h | 106 + .../documents/gdata-documents-query.c | 709 +++ .../documents/gdata-documents-query.h | 93 + .../documents/gdata-documents-service.c | 1628 ++++++ .../documents/gdata-documents-service.h | 163 + .../documents/gdata-documents-spreadsheet.c | 189 + .../documents/gdata-documents-spreadsheet.h | 159 + .../services/documents/gdata-documents-text.c | 87 + .../services/documents/gdata-documents-text.h | 192 + .../documents/gdata-documents-upload-query.c | 423 ++ .../documents/gdata-documents-upload-query.h | 84 + .../documents/gdata-documents-utils.c | 154 + .../documents/gdata-documents-utils.h | 43 + gdata/services/documents/meson.build | 75 + .../services/freebase/gdata-freebase-query.c | 259 + .../services/freebase/gdata-freebase-query.h | 81 + .../services/freebase/gdata-freebase-result.c | 205 + .../services/freebase/gdata-freebase-result.h | 81 + .../freebase/gdata-freebase-search-query.c | 626 +++ .../freebase/gdata-freebase-search-query.h | 106 + .../freebase/gdata-freebase-search-result.c | 432 ++ .../freebase/gdata-freebase-search-result.h | 104 + .../freebase/gdata-freebase-service.c | 509 ++ .../freebase/gdata-freebase-service.h | 111 + .../freebase/gdata-freebase-topic-query.c | 351 ++ .../freebase/gdata-freebase-topic-query.h | 84 + .../freebase/gdata-freebase-topic-result.c | 1047 ++++ .../freebase/gdata-freebase-topic-result.h | 135 + gdata/services/freebase/meson.build | 58 + gdata/services/meson.build | 7 + .../picasaweb/gdata-picasaweb-album.c | 1268 +++++ .../picasaweb/gdata-picasaweb-album.h | 114 + .../picasaweb/gdata-picasaweb-comment.c | 114 + .../picasaweb/gdata-picasaweb-comment.h | 75 + .../services/picasaweb/gdata-picasaweb-feed.c | 91 + .../services/picasaweb/gdata-picasaweb-feed.h | 73 + .../services/picasaweb/gdata-picasaweb-file.c | 1801 ++++++ .../services/picasaweb/gdata-picasaweb-file.h | 154 + .../picasaweb/gdata-picasaweb-query.c | 608 ++ .../picasaweb/gdata-picasaweb-query.h | 92 + .../picasaweb/gdata-picasaweb-service.c | 741 +++ .../picasaweb/gdata-picasaweb-service.h | 120 + .../services/picasaweb/gdata-picasaweb-user.c | 376 ++ .../services/picasaweb/gdata-picasaweb-user.h | 82 + gdata/services/picasaweb/meson.build | 58 + gdata/services/tasks/gdata-tasks-query.c | 659 +++ gdata/services/tasks/gdata-tasks-query.h | 90 + gdata/services/tasks/gdata-tasks-service.c | 872 +++ gdata/services/tasks/gdata-tasks-service.h | 115 + gdata/services/tasks/gdata-tasks-task.c | 697 +++ gdata/services/tasks/gdata-tasks-task.h | 118 + gdata/services/tasks/gdata-tasks-tasklist.c | 84 + gdata/services/tasks/gdata-tasks-tasklist.h | 73 + gdata/services/tasks/meson.build | 20 + .../services/youtube/gdata-youtube-category.c | 242 + .../services/youtube/gdata-youtube-category.h | 77 + .../services/youtube/gdata-youtube-comment.c | 576 ++ .../services/youtube/gdata-youtube-comment.h | 77 + .../services/youtube/gdata-youtube-content.c | 157 + .../services/youtube/gdata-youtube-content.h | 108 + gdata/services/youtube/gdata-youtube-credit.c | 179 + gdata/services/youtube/gdata-youtube-credit.h | 97 + gdata/services/youtube/gdata-youtube-feed.c | 102 + gdata/services/youtube/gdata-youtube-feed.h | 74 + gdata/services/youtube/gdata-youtube-query.c | 1127 ++++ gdata/services/youtube/gdata-youtube-query.h | 197 + .../services/youtube/gdata-youtube-service.c | 1229 ++++ .../services/youtube/gdata-youtube-service.h | 201 + gdata/services/youtube/gdata-youtube-state.c | 285 + gdata/services/youtube/gdata-youtube-state.h | 75 + gdata/services/youtube/gdata-youtube-video.c | 2476 ++++++++ gdata/services/youtube/gdata-youtube-video.h | 238 + gdata/services/youtube/meson.build | 62 + gdata/symbol.map | 1147 ++++ gdata/tests/authorization.c | 793 +++ gdata/tests/buffer.c | 165 + gdata/tests/calendar.c | 1595 ++++++ gdata/tests/cert.pem | 23 + gdata/tests/common.c | 1050 ++++ gdata/tests/common.h | 344 ++ gdata/tests/contacts.c | 2703 +++++++++ gdata/tests/documents.c | 2284 ++++++++ gdata/tests/gdata-dummy-authorizer.c | 222 + gdata/tests/gdata-dummy-authorizer.h | 77 + gdata/tests/general.c | 5005 +++++++++++++++++ gdata/tests/key.pem | 28 + gdata/tests/meson.build | 103 + gdata/tests/oauth1-authorizer.c | 1139 ++++ gdata/tests/oauth2-authorizer.c | 1033 ++++ gdata/tests/perf.c | 118 + gdata/tests/photo.jpg | Bin 0 -> 17659 bytes gdata/tests/picasaweb.c | 2239 ++++++++ gdata/tests/sample.ogg | Bin 0 -> 96839 bytes gdata/tests/streams.c | 1105 ++++ gdata/tests/tasks.c | 1443 +++++ gdata/tests/template.test.in | 4 + gdata/tests/test.doc | Bin 0 -> 7680 bytes gdata/tests/test.ods | Bin 0 -> 7564 bytes gdata/tests/test.odt | Bin 0 -> 8033 bytes gdata/tests/test.ppt | Bin 0 -> 71168 bytes gdata/tests/test.xls | Bin 0 -> 7680 bytes gdata/tests/test_updated.odt | Bin 0 -> 8649 bytes gdata/tests/test_updated_file.ppt | Bin 0 -> 72192 bytes .../tests/traces/calendar/access-rule-delete | 23 + gdata/tests/traces/calendar/access-rule-get | 65 + .../tests/traces/calendar/access-rule-insert | 43 + .../tests/traces/calendar/access-rule-update | 43 + gdata/tests/traces/calendar/authentication | 35 + .../traces/calendar/authentication-async | 27 + .../authentication-async-cancellation | 27 + gdata/tests/traces/calendar/event-insert | 76 + .../tests/traces/calendar/event_insert-async | 76 + .../calendar/event_insert-async-cancellation | 76 + .../traces/calendar/global-authentication | 35 + .../tests/traces/calendar/query-all-calendars | 145 + ...query-all-calendars-async-progress-closure | 145 + gdata/tests/traces/calendar/query-events | 140 + .../query-events-async-progress-closure | 140 + .../tests/traces/calendar/query-own-calendars | 117 + ...query-own-calendars-async-progress-closure | 117 + .../traces/calendar/query_all_calendars-async | 145 + .../query_all_calendars-async-cancellation | 145 + .../tests/traces/calendar/query_events-async | 140 + .../calendar/query_events-async-cancellation | 140 + .../traces/calendar/query_own_calendars-async | 117 + .../query_own_calendars-async-cancellation | 117 + .../traces/calendar/setup-query-calendars | 78 + .../tests/traces/calendar/setup-query-events | 199 + .../tests/traces/calendar/setup-temp-calendar | 39 + .../traces/calendar/setup-temp-calendar-acls | 43 + .../traces/calendar/teardown-insert-event | 24 + .../traces/calendar/teardown-query-calendars | 48 + .../traces/calendar/teardown-query-events | 72 + .../traces/calendar/teardown-temp-calendar | 24 + .../calendar/teardown-temp-calendar-acls | 23 + gdata/tests/traces/contacts/authentication | 35 + .../traces/contacts/authentication-async | 27 + .../authentication-async-cancellation | 27 + gdata/tests/traces/contacts/batch | 242 + gdata/tests/traces/contacts/batch-async | 57 + .../traces/contacts/batch-async-cancellation | 0 gdata/tests/traces/contacts/contact-insert | 90 + gdata/tests/traces/contacts/contact-update | 63 + .../traces/contacts/global-authentication | 35 + gdata/tests/traces/contacts/group-insert | 45 + .../tests/traces/contacts/group_insert-async | 45 + .../contacts/group_insert-async-cancellation | 45 + gdata/tests/traces/contacts/photo-add | 33 + gdata/tests/traces/contacts/photo-delete | 27 + gdata/tests/traces/contacts/photo-get | 29 + gdata/tests/traces/contacts/photo_add-async | 33 + .../contacts/photo_add-async-cancellation | 31 + .../tests/traces/contacts/photo_delete-async | 27 + .../contacts/photo_delete-async-cancellation | 34 + gdata/tests/traces/contacts/photo_get-async | 29 + .../contacts/photo_get-async-cancellation | 29 + .../tests/traces/contacts/query-all-contacts | 373 ++ .../query-all-contacts-async-progress-closure | 373 ++ gdata/tests/traces/contacts/query-all-groups | 166 + .../query-all-groups-async-progress-closure | 166 + .../traces/contacts/query_all_contacts-async | 373 ++ .../query_all_contacts-async-cancellation | 373 ++ .../traces/contacts/query_all_groups-async | 166 + .../query_all_groups-async-cancellation | 166 + gdata/tests/traces/contacts/setup-batch-async | 49 + .../traces/contacts/setup-query-all-contacts | 135 + .../traces/contacts/setup-query-all-groups | 132 + .../tests/traces/contacts/setup-temp-contact | 45 + .../contacts/setup-temp-contact-with-photo | 75 + .../traces/contacts/teardown-batch-async | 30 + gdata/tests/traces/contacts/teardown-insert | 30 + .../traces/contacts/teardown-insert-group | 30 + .../contacts/teardown-query-all-contacts | 90 + .../traces/contacts/teardown-query-all-groups | 90 + .../traces/contacts/teardown-temp-contact | 72 + .../tests/traces/documents/access-rule-insert | 32 + gdata/tests/traces/documents/authentication | 81 + .../traces/documents/authentication-async | 81 + .../authentication-async-cancellation | 135 + gdata/tests/traces/documents/batch | 196 + gdata/tests/traces/documents/batch-async | 28 + .../traces/documents/batch-async-cancellation | 0 gdata/tests/traces/documents/copy-document | 32 + gdata/tests/traces/documents/delete-document | 53 + gdata/tests/traces/documents/delete-folder | 53 + .../tests/traces/documents/download-document | 112 + .../traces/documents/folders-add-to-folder | 32 + .../documents/folders-remove-from-folder | 53 + .../documents/folders_add_to_folder-async | 32 + .../folders_add_to_folder-async-cancellation | 32 + .../folders_remove_from_folder-async | 53 + ...ders_remove_from_folder-async-cancellation | 53 + .../folders_remove_from_folder-async-epilogue | 56 + .../traces/documents/global-authentication | 81 + .../traces/documents/query-all-documents | 28 + ...query-all-documents-async-progress-closure | 28 + .../documents/query-all-documents-with-folder | 28 + .../documents/query_all_documents-async | 28 + .../query_all_documents-async-cancellation | 112 + .../tests/traces/documents/setup-batch-async | 33 + .../documents/setup-folders-add-to-folder | 93 + .../setup-folders-remove-from-folder | 93 + .../documents/setup-temp-document-spreadsheet | 80 + .../traces/documents/setup-temp-documents | 179 + .../tests/traces/documents/setup-temp-folder | 33 + ...ocument_content-and-metadata-non-resumable | 80 + ...te-document_content-and-metadata-resumable | 80 + ...update-document_content-only-non-resumable | 80 + ...tup-update-document_content-only-resumable | 80 + ...pdate-document_metadata-only-non-resumable | 80 + ...tadata-in-folder-non-resumable-odt-convert | 33 + ...etadata-in-folder-resumable-bin-no-convert | 33 + ...d-metadata-in-folder-resumable-odt-convert | 33 + ...etadata-in-folder-resumable-odt-no-convert | 33 + ...data-root-folder-non-resumable-odt-convert | 0 ...adata-root-folder-resumable-bin-no-convert | 0 ...metadata-root-folder-resumable-odt-convert | 0 ...adata-root-folder-resumable-odt-no-convert | 0 ...t-only-in-folder-non-resumable-odt-convert | 33 + ...nt-only-in-folder-resumable-bin-no-convert | 33 + ...ntent-only-in-folder-resumable-odt-convert | 33 + ...nt-only-in-folder-resumable-odt-no-convert | 33 + ...only-root-folder-non-resumable-odt-convert | 0 ...-only-root-folder-resumable-bin-no-convert | 0 ...ent-only-root-folder-resumable-odt-convert | 0 ...-only-root-folder-resumable-odt-no-convert | 0 ...a-only-in-folder-non-resumable-odt-convert | 33 + ...only-root-folder-non-resumable-odt-convert | 0 .../traces/documents/teardown-batch-async | 53 + .../traces/documents/teardown-copy-document | 53 + .../documents/teardown-folders-add-to-folder | 106 + .../traces/documents/teardown-temp-document | 53 + .../traces/documents/teardown-temp-documents | 212 + .../traces/documents/teardown-temp-folder | 53 + ...ocument_content-and-metadata-non-resumable | 53 + ...te-document_content-and-metadata-resumable | 53 + ...update-document_content-only-non-resumable | 53 + ...own-update-document_content-only-resumable | 53 + ...pdate-document_metadata-only-non-resumable | 53 + ...tadata-in-folder-non-resumable-odt-convert | 106 + ...etadata-in-folder-resumable-bin-no-convert | 106 + ...d-metadata-in-folder-resumable-odt-convert | 106 + ...etadata-in-folder-resumable-odt-no-convert | 106 + ...data-root-folder-non-resumable-odt-convert | 53 + ...adata-root-folder-resumable-bin-no-convert | 53 + ...metadata-root-folder-resumable-odt-convert | 53 + ...adata-root-folder-resumable-odt-no-convert | 53 + ...t-only-in-folder-non-resumable-odt-convert | 106 + ...nt-only-in-folder-resumable-bin-no-convert | 106 + ...ntent-only-in-folder-resumable-odt-convert | 106 + ...nt-only-in-folder-resumable-odt-no-convert | 106 + ...only-root-folder-non-resumable-odt-convert | 53 + ...-only-root-folder-resumable-bin-no-convert | 53 + ...ent-only-root-folder-resumable-odt-convert | 53 + ...-only-root-folder-resumable-odt-no-convert | 53 + ...a-only-in-folder-non-resumable-odt-convert | 106 + ...only-root-folder-non-resumable-odt-convert | 53 + .../update_content-and-metadata-non-resumable | 30 + .../update_content-and-metadata-resumable | 48 + .../update_content-only-non-resumable | 30 + .../documents/update_content-only-resumable | 48 + .../update_metadata-only-non-resumable | 30 + ...tadata-in-folder-non-resumable-odt-convert | 32 + ...etadata-in-folder-resumable-bin-no-convert | 52 + ...d-metadata-in-folder-resumable-odt-convert | 52 + ...etadata-in-folder-resumable-odt-no-convert | 52 + ...data-root-folder-non-resumable-odt-convert | 32 + ...adata-root-folder-resumable-bin-no-convert | 52 + ...metadata-root-folder-resumable-odt-convert | 52 + ...adata-root-folder-resumable-odt-no-convert | 52 + ...t-only-in-folder-non-resumable-odt-convert | 32 + ...nt-only-in-folder-resumable-bin-no-convert | 52 + ...ntent-only-in-folder-resumable-odt-convert | 52 + ...nt-only-in-folder-resumable-odt-no-convert | 52 + ...only-root-folder-non-resumable-odt-convert | 32 + ...-only-root-folder-resumable-bin-no-convert | 52 + ...ent-only-root-folder-resumable-odt-convert | 52 + ...-only-root-folder-resumable-odt-no-convert | 52 + ...a-only-in-folder-non-resumable-odt-convert | 33 + ...only-root-folder-non-resumable-odt-convert | 33 + ...uthorizer-interactive-data-bad-credentials | 25 + .../oauth1-authorizer-refresh-authorization | 0 ...uthorizer-request-authentication-uri-async | 25 + ...uest-authentication-uri-async-cancellation | 0 ...authorizer-request-authentication-uri-sync | 25 + ...quest-authentication-uri-sync-cancellation | 0 ...th1-authorizer-request-authorization-async | 25 + ...equest-authorization-async-bad-credentials | 26 + ...r-request-authorization-async-cancellation | 0 ...uth1-authorizer-request-authorization-sync | 25 + ...request-authorization-sync-bad-credentials | 26 + ...er-request-authorization-sync-cancellation | 0 ...setup-oauth1-authorizer-data-authenticated | 50 + .../setup-oauth1-authorizer-interactive-data | 25 + ...uthorizer-refresh-authorization-authorized | 34 + ...horizer-refresh-authorization-unauthorized | 0 ...th2-authorizer-request-authorization-async | 35 + ...equest-authorization-async-bad-credentials | 31 + ...r-request-authorization-async-cancellation | 0 ...uth2-authorizer-request-authorization-sync | 35 + ...request-authorization-sync-bad-credentials | 31 + ...er-request-authorization-sync-cancellation | 0 ...setup-oauth2-authorizer-data-authenticated | 35 + gdata/tests/traces/picasaweb/authentication | 35 + .../traces/picasaweb/authentication-async | 27 + .../authentication-async-cancellation | 41 + gdata/tests/traces/picasaweb/comment-delete | 26 + gdata/tests/traces/picasaweb/comment-insert | 34 + gdata/tests/traces/picasaweb/comment-query | 30 + .../comment-query-async-progress-closure | 30 + .../traces/picasaweb/comment_delete-async | 26 + .../comment_delete-async-cancellation | 26 + .../traces/picasaweb/comment_insert-async | 34 + .../comment_insert-async-cancellation | 34 + .../traces/picasaweb/comment_query-async | 30 + .../comment_query-async-cancellation | 30 + gdata/tests/traces/picasaweb/download-photo | 25 + .../traces/picasaweb/download-thumbnails | 101 + .../traces/picasaweb/global-authentication | 35 + gdata/tests/traces/picasaweb/insert-album | 64 + .../tests/traces/picasaweb/insert_album-async | 34 + .../picasaweb/insert_album-async-cancellation | 50 + gdata/tests/traces/picasaweb/query-all-albums | 30 + .../query-all-albums-async-progress-closure | 30 + .../picasaweb/query-all-albums-with-limits | 90 + gdata/tests/traces/picasaweb/query-files | 30 + .../query-files-async-progress-closure | 30 + .../tests/traces/picasaweb/query-files-single | 30 + gdata/tests/traces/picasaweb/query-user | 30 + .../traces/picasaweb/query_all_albums-async | 30 + .../query_all_albums-async-cancellation | 98 + .../tests/traces/picasaweb/query_files-async | 30 + .../picasaweb/query_files-async-cancellation | 30 + gdata/tests/traces/picasaweb/query_user-async | 30 + .../picasaweb/query_user-async-cancellation | 90 + .../picasaweb/query_user_by_username-async | 30 + .../query_user_by_username-async-cancellation | 120 + .../traces/picasaweb/setup-query-all-albums | 136 + .../traces/picasaweb/setup-query-comments | 102 + .../tests/traces/picasaweb/setup-query-files | 170 + gdata/tests/traces/picasaweb/setup-upload | 0 .../traces/picasaweb/teardown-insert-album | 27 + .../traces/picasaweb/teardown-insert-comment | 26 + .../picasaweb/teardown-query-all-albums | 108 + .../traces/picasaweb/teardown-query-comments | 78 + .../traces/picasaweb/teardown-query-files | 57 + gdata/tests/traces/picasaweb/teardown-upload | 27 + .../traces/picasaweb/upload-default-album | 34 + .../picasaweb/upload_default_album-async | 34 + .../upload_default_album-async-cancellation | 34 + gdata/tests/traces/tasks/authentication | 35 + .../tests/traces/tasks/global-authentication | 35 + gdata/tests/traces/tasks/setup-delete-task | 84 + .../tests/traces/tasks/setup-delete-tasklist | 41 + gdata/tests/traces/tasks/setup-insert-task | 41 + gdata/tests/traces/tasks/setup-list-task | 170 + gdata/tests/traces/tasks/setup-list-tasklist | 123 + gdata/tests/traces/tasks/setup-update-task | 84 + .../tests/traces/tasks/setup-update-tasklist | 41 + gdata/tests/traces/tasks/task-delete | 25 + gdata/tests/traces/tasks/task-insert | 43 + gdata/tests/traces/tasks/task-list | 65 + gdata/tests/traces/tasks/task-update | 44 + gdata/tests/traces/tasks/tasklist-delete | 25 + gdata/tests/traces/tasks/tasklist-insert | 41 + .../traces/tasks/tasklist-insert-unauthorised | 46 + gdata/tests/traces/tasks/tasklist-list | 91 + gdata/tests/traces/tasks/tasklist-update | 42 + gdata/tests/traces/tasks/teardown-delete-task | 25 + gdata/tests/traces/tasks/teardown-insert-task | 50 + .../traces/tasks/teardown-insert-tasklist | 25 + gdata/tests/traces/tasks/teardown-list-task | 100 + .../tests/traces/tasks/teardown-list-tasklist | 75 + gdata/tests/traces/tasks/teardown-update-task | 50 + .../traces/tasks/teardown-update-tasklist | 25 + gdata/tests/traces/youtube/authentication | 35 + .../tests/traces/youtube/authentication-async | 27 + .../youtube/authentication-async-cancellation | 27 + gdata/tests/traces/youtube/batch | 0 gdata/tests/traces/youtube/batch-async | 0 .../traces/youtube/batch-async-cancellation | 0 gdata/tests/traces/youtube/categories | 701 +++ gdata/tests/traces/youtube/categories-async | 355 ++ .../youtube/categories-async-cancellation | 355 ++ gdata/tests/traces/youtube/comment-delete | 0 gdata/tests/traces/youtube/comment-insert | 68 + gdata/tests/traces/youtube/comment-query | 703 +++ .../comment-query-async-progress-closure | 705 +++ .../tests/traces/youtube/comment_delete-async | 0 .../youtube/comment_delete-async-cancellation | 0 .../tests/traces/youtube/comment_insert-async | 68 + .../youtube/comment_insert-async-cancellation | 68 + .../tests/traces/youtube/comment_query-async | 705 +++ .../youtube/comment_query-async-cancellation | 705 +++ .../traces/youtube/global-authentication | 35 + gdata/tests/traces/youtube/query-related | 175 + .../query-related-async-progress-closure | 175 + gdata/tests/traces/youtube/query-single | 103 + .../tests/traces/youtube/query-standard-feed | 325 ++ ...query-standard-feed-async-progress-closure | 325 ++ .../youtube/query-standard-feed-with-query | 325 ++ .../tests/traces/youtube/query-standard-feeds | 3250 +++++++++++ .../tests/traces/youtube/query_related-async | 175 + .../youtube/query_related-async-cancellation | 175 + gdata/tests/traces/youtube/query_single-async | 103 + .../youtube/query_single-async-cancellation | 103 + .../traces/youtube/query_standard_feed-async | 325 ++ .../query_standard_feed-async-cancellation | 325 ++ gdata/tests/traces/youtube/setup-batch | 190 + gdata/tests/traces/youtube/setup-comment | 95 + .../tests/traces/youtube/setup-insert-comment | 0 .../traces/youtube/teardown-insert-comment | 0 gdata/tests/traces/youtube/teardown-upload | 25 + gdata/tests/traces/youtube/upload-async | 77 + .../traces/youtube/upload-async-cancellation | 76 + gdata/tests/traces/youtube/upload-simple | 77 + gdata/tests/youtube.c | 2499 ++++++++ libgdata.doap | 18 + meson.build | 189 + meson_options.txt | 49 + po/LINGUAS | 63 + po/POTFILES.in | 29 + po/ar.po | 494 ++ po/as.po | 563 ++ po/be.po | 626 +++ po/bg.po | 582 ++ po/bn_IN.po | 444 ++ po/bs.po | 570 ++ po/ca.po | 630 +++ po/ca@valencia.po | 626 +++ po/cs.po | 608 ++ po/da.po | 612 ++ po/de.po | 639 +++ po/el.po | 663 +++ po/en_GB.po | 634 +++ po/eo.po | 582 ++ po/es.po | 643 +++ po/et.po | 450 ++ po/eu.po | 610 ++ po/fi.po | 633 +++ po/fr.po | 614 ++ po/fur.po | 608 ++ po/gl.po | 612 ++ po/gu.po | 551 ++ po/he.po | 595 ++ po/hi.po | 496 ++ po/hr.po | 602 ++ po/hu.po | 606 ++ po/id.po | 609 ++ po/it.po | 616 ++ po/ja.po | 624 ++ po/kn.po | 469 ++ po/ko.po | 601 ++ po/lt.po | 626 +++ po/lv.po | 610 ++ po/meson.build | 1 + po/ml.po | 478 ++ po/mr.po | 482 ++ po/ms.po | 606 ++ po/nb.po | 585 ++ po/ne.po | 589 ++ po/nl.po | 632 +++ po/oc.po | 640 +++ po/or.po | 494 ++ po/pa.po | 563 ++ po/pl.po | 604 ++ po/pt.po | 624 ++ po/pt_BR.po | 636 +++ po/ro.po | 626 +++ po/ru.po | 625 ++ po/sk.po | 625 ++ po/sl.po | 671 +++ po/sr.po | 629 +++ po/sr@latin.po | 615 ++ po/sv.po | 629 +++ po/ta.po | 485 ++ po/te.po | 498 ++ po/tg.po | 483 ++ po/th.po | 589 ++ po/tr.po | 632 +++ po/ug.po | 476 ++ po/uk.po | 625 ++ po/vi.po | 601 ++ po/zh_CN.po | 618 ++ po/zh_HK.po | 545 ++ po/zh_TW.po | 612 ++ 679 files changed, 181311 insertions(+) create mode 100644 AUTHORS create mode 100644 COPYING create mode 100644 HACKING create mode 100644 NEWS create mode 100644 README create mode 100644 demos/calendar/calendar-cli.c create mode 100644 demos/docs-list/docs-list.c create mode 100644 demos/docs-property/docs-property.c create mode 100644 demos/meson.build create mode 100644 demos/scrapbook/scrapbook.c create mode 100644 demos/scrapbook/scrapbook.h create mode 100644 demos/tasks/tasks-cli.c create mode 100644 demos/youtube/youtube-cli.c create mode 100644 docs/reference/cancellation.dia create mode 100644 docs/reference/cancellation.png create mode 100644 docs/reference/data-flow.dia create mode 100644 docs/reference/data-flow.png create mode 100644 docs/reference/gdata-docs.xml create mode 100644 docs/reference/gdata-overrides.txt create mode 100644 docs/reference/gdata-overview.xml create mode 100644 docs/reference/gdata-running.xml create mode 100644 docs/reference/gdata-sections.txt.in create mode 100644 docs/reference/meson.build create mode 100644 docs/reference/structure.dia create mode 100644 docs/reference/structure.png create mode 100644 docs/reference/xml/gtkdocentities.ent.in create mode 100644 docs/reference/xml/meson.build create mode 100644 gdata/GData-0.0.metadata create mode 100644 gdata/app/gdata-app-categories.c create mode 100644 gdata/app/gdata-app-categories.h create mode 100644 gdata/app/meson.build create mode 100644 gdata/atom/gdata-author.c create mode 100644 gdata/atom/gdata-author.h create mode 100644 gdata/atom/gdata-category.c create mode 100644 gdata/atom/gdata-category.h create mode 100644 gdata/atom/gdata-generator.c create mode 100644 gdata/atom/gdata-generator.h create mode 100644 gdata/atom/gdata-link.c create mode 100644 gdata/atom/gdata-link.h create mode 100644 gdata/atom/meson.build create mode 100644 gdata/exif/gdata-exif-tags.c create mode 100644 gdata/exif/gdata-exif-tags.h create mode 100644 gdata/exif/meson.build create mode 100644 gdata/gcontact/gdata-gcontact-calendar.c create mode 100644 gdata/gcontact/gdata-gcontact-calendar.h create mode 100644 gdata/gcontact/gdata-gcontact-event.c create mode 100644 gdata/gcontact/gdata-gcontact-event.h create mode 100644 gdata/gcontact/gdata-gcontact-external-id.c create mode 100644 gdata/gcontact/gdata-gcontact-external-id.h create mode 100644 gdata/gcontact/gdata-gcontact-jot.c create mode 100644 gdata/gcontact/gdata-gcontact-jot.h create mode 100644 gdata/gcontact/gdata-gcontact-language.c create mode 100644 gdata/gcontact/gdata-gcontact-language.h create mode 100644 gdata/gcontact/gdata-gcontact-relation.c create mode 100644 gdata/gcontact/gdata-gcontact-relation.h create mode 100644 gdata/gcontact/gdata-gcontact-website.c create mode 100644 gdata/gcontact/gdata-gcontact-website.h create mode 100644 gdata/gcontact/meson.build create mode 100644 gdata/gd/gdata-gd-email-address.c create mode 100644 gdata/gd/gdata-gd-email-address.h create mode 100644 gdata/gd/gdata-gd-feed-link.c create mode 100644 gdata/gd/gdata-gd-feed-link.h create mode 100644 gdata/gd/gdata-gd-im-address.c create mode 100644 gdata/gd/gdata-gd-im-address.h create mode 100644 gdata/gd/gdata-gd-name.c create mode 100644 gdata/gd/gdata-gd-name.h create mode 100644 gdata/gd/gdata-gd-organization.c create mode 100644 gdata/gd/gdata-gd-organization.h create mode 100644 gdata/gd/gdata-gd-phone-number.c create mode 100644 gdata/gd/gdata-gd-phone-number.h create mode 100644 gdata/gd/gdata-gd-postal-address.c create mode 100644 gdata/gd/gdata-gd-postal-address.h create mode 100644 gdata/gd/gdata-gd-reminder.c create mode 100644 gdata/gd/gdata-gd-reminder.h create mode 100644 gdata/gd/gdata-gd-when.c create mode 100644 gdata/gd/gdata-gd-when.h create mode 100644 gdata/gd/gdata-gd-where.c create mode 100644 gdata/gd/gdata-gd-where.h create mode 100644 gdata/gd/gdata-gd-who.c create mode 100644 gdata/gd/gdata-gd-who.h create mode 100644 gdata/gd/meson.build create mode 100644 gdata/gdata-access-handler.c create mode 100644 gdata/gdata-access-handler.h create mode 100644 gdata/gdata-access-rule.c create mode 100644 gdata/gdata-access-rule.h create mode 100644 gdata/gdata-authorization-domain.c create mode 100644 gdata/gdata-authorization-domain.h create mode 100644 gdata/gdata-authorizer.c create mode 100644 gdata/gdata-authorizer.h create mode 100644 gdata/gdata-batch-feed.c create mode 100644 gdata/gdata-batch-feed.h create mode 100644 gdata/gdata-batch-operation.c create mode 100644 gdata/gdata-batch-operation.h create mode 100644 gdata/gdata-batch-private.h create mode 100644 gdata/gdata-batchable.c create mode 100644 gdata/gdata-batchable.h create mode 100644 gdata/gdata-buffer.c create mode 100644 gdata/gdata-buffer.h create mode 100644 gdata/gdata-client-login-authorizer.c create mode 100644 gdata/gdata-client-login-authorizer.h create mode 100644 gdata/gdata-comment.c create mode 100644 gdata/gdata-comment.h create mode 100644 gdata/gdata-commentable.c create mode 100644 gdata/gdata-commentable.h create mode 100644 gdata/gdata-comparable.c create mode 100644 gdata/gdata-comparable.h create mode 100644 gdata/gdata-core.symbols create mode 100644 gdata/gdata-download-stream.c create mode 100644 gdata/gdata-download-stream.h create mode 100644 gdata/gdata-entry.c create mode 100644 gdata/gdata-entry.h create mode 100644 gdata/gdata-feed.c create mode 100644 gdata/gdata-feed.h create mode 100644 gdata/gdata-goa-authorizer.c create mode 100644 gdata/gdata-goa-authorizer.h create mode 100644 gdata/gdata-goa.symbols create mode 100644 gdata/gdata-marshal.list create mode 100644 gdata/gdata-oauth1-authorizer.c create mode 100644 gdata/gdata-oauth1-authorizer.h create mode 100644 gdata/gdata-oauth2-authorizer.c create mode 100644 gdata/gdata-oauth2-authorizer.h create mode 100644 gdata/gdata-parsable.c create mode 100644 gdata/gdata-parsable.h create mode 100644 gdata/gdata-parser.c create mode 100644 gdata/gdata-parser.h create mode 100644 gdata/gdata-private.h create mode 100644 gdata/gdata-query.c create mode 100644 gdata/gdata-query.h create mode 100644 gdata/gdata-service.c create mode 100644 gdata/gdata-service.h create mode 100644 gdata/gdata-types.c create mode 100644 gdata/gdata-types.h create mode 100644 gdata/gdata-upload-stream.c create mode 100644 gdata/gdata-upload-stream.h create mode 100644 gdata/gdata-version.h.in create mode 100644 gdata/gdata.h create mode 100644 gdata/georss/gdata-georss-where.c create mode 100644 gdata/georss/gdata-georss-where.h create mode 100644 gdata/georss/meson.build create mode 100644 gdata/media/gdata-media-category.c create mode 100644 gdata/media/gdata-media-category.h create mode 100644 gdata/media/gdata-media-content.c create mode 100644 gdata/media/gdata-media-content.h create mode 100644 gdata/media/gdata-media-credit.c create mode 100644 gdata/media/gdata-media-credit.h create mode 100644 gdata/media/gdata-media-group.c create mode 100644 gdata/media/gdata-media-group.h create mode 100644 gdata/media/gdata-media-thumbnail.c create mode 100644 gdata/media/gdata-media-thumbnail.h create mode 100644 gdata/media/meson.build create mode 100644 gdata/meson.build create mode 100644 gdata/services/calendar/gdata-calendar-access-rule.c create mode 100644 gdata/services/calendar/gdata-calendar-access-rule.h create mode 100644 gdata/services/calendar/gdata-calendar-calendar.c create mode 100644 gdata/services/calendar/gdata-calendar-calendar.h create mode 100644 gdata/services/calendar/gdata-calendar-event.c create mode 100644 gdata/services/calendar/gdata-calendar-event.h create mode 100644 gdata/services/calendar/gdata-calendar-feed.c create mode 100644 gdata/services/calendar/gdata-calendar-feed.h create mode 100644 gdata/services/calendar/gdata-calendar-query.c create mode 100644 gdata/services/calendar/gdata-calendar-query.h create mode 100644 gdata/services/calendar/gdata-calendar-service.c create mode 100644 gdata/services/calendar/gdata-calendar-service.h create mode 100644 gdata/services/calendar/meson.build create mode 100644 gdata/services/contacts/gdata-contacts-contact.c create mode 100644 gdata/services/contacts/gdata-contacts-contact.h create mode 100644 gdata/services/contacts/gdata-contacts-group.c create mode 100644 gdata/services/contacts/gdata-contacts-group.h create mode 100644 gdata/services/contacts/gdata-contacts-query.c create mode 100644 gdata/services/contacts/gdata-contacts-query.h create mode 100644 gdata/services/contacts/gdata-contacts-service.c create mode 100644 gdata/services/contacts/gdata-contacts-service.h create mode 100644 gdata/services/contacts/meson.build create mode 100644 gdata/services/documents/gdata-documents-access-rule.c create mode 100644 gdata/services/documents/gdata-documents-access-rule.h create mode 100644 gdata/services/documents/gdata-documents-document.c create mode 100644 gdata/services/documents/gdata-documents-document.h create mode 100644 gdata/services/documents/gdata-documents-drawing.c create mode 100644 gdata/services/documents/gdata-documents-drawing.h create mode 100644 gdata/services/documents/gdata-documents-entry-private.h create mode 100644 gdata/services/documents/gdata-documents-entry.c create mode 100644 gdata/services/documents/gdata-documents-entry.h create mode 100644 gdata/services/documents/gdata-documents-feed.c create mode 100644 gdata/services/documents/gdata-documents-feed.h create mode 100644 gdata/services/documents/gdata-documents-folder.c create mode 100644 gdata/services/documents/gdata-documents-folder.h create mode 100644 gdata/services/documents/gdata-documents-metadata.c create mode 100644 gdata/services/documents/gdata-documents-metadata.h create mode 100644 gdata/services/documents/gdata-documents-pdf.c create mode 100644 gdata/services/documents/gdata-documents-pdf.h create mode 100644 gdata/services/documents/gdata-documents-presentation.c create mode 100644 gdata/services/documents/gdata-documents-presentation.h create mode 100644 gdata/services/documents/gdata-documents-property.c create mode 100644 gdata/services/documents/gdata-documents-property.h create mode 100644 gdata/services/documents/gdata-documents-query.c create mode 100644 gdata/services/documents/gdata-documents-query.h create mode 100644 gdata/services/documents/gdata-documents-service.c create mode 100644 gdata/services/documents/gdata-documents-service.h create mode 100644 gdata/services/documents/gdata-documents-spreadsheet.c create mode 100644 gdata/services/documents/gdata-documents-spreadsheet.h create mode 100644 gdata/services/documents/gdata-documents-text.c create mode 100644 gdata/services/documents/gdata-documents-text.h create mode 100644 gdata/services/documents/gdata-documents-upload-query.c create mode 100644 gdata/services/documents/gdata-documents-upload-query.h create mode 100644 gdata/services/documents/gdata-documents-utils.c create mode 100644 gdata/services/documents/gdata-documents-utils.h create mode 100644 gdata/services/documents/meson.build create mode 100644 gdata/services/freebase/gdata-freebase-query.c create mode 100644 gdata/services/freebase/gdata-freebase-query.h create mode 100644 gdata/services/freebase/gdata-freebase-result.c create mode 100644 gdata/services/freebase/gdata-freebase-result.h create mode 100644 gdata/services/freebase/gdata-freebase-search-query.c create mode 100644 gdata/services/freebase/gdata-freebase-search-query.h create mode 100644 gdata/services/freebase/gdata-freebase-search-result.c create mode 100644 gdata/services/freebase/gdata-freebase-search-result.h create mode 100644 gdata/services/freebase/gdata-freebase-service.c create mode 100644 gdata/services/freebase/gdata-freebase-service.h create mode 100644 gdata/services/freebase/gdata-freebase-topic-query.c create mode 100644 gdata/services/freebase/gdata-freebase-topic-query.h create mode 100644 gdata/services/freebase/gdata-freebase-topic-result.c create mode 100644 gdata/services/freebase/gdata-freebase-topic-result.h create mode 100644 gdata/services/freebase/meson.build create mode 100644 gdata/services/meson.build create mode 100644 gdata/services/picasaweb/gdata-picasaweb-album.c create mode 100644 gdata/services/picasaweb/gdata-picasaweb-album.h create mode 100644 gdata/services/picasaweb/gdata-picasaweb-comment.c create mode 100644 gdata/services/picasaweb/gdata-picasaweb-comment.h create mode 100644 gdata/services/picasaweb/gdata-picasaweb-feed.c create mode 100644 gdata/services/picasaweb/gdata-picasaweb-feed.h create mode 100644 gdata/services/picasaweb/gdata-picasaweb-file.c create mode 100644 gdata/services/picasaweb/gdata-picasaweb-file.h create mode 100644 gdata/services/picasaweb/gdata-picasaweb-query.c create mode 100644 gdata/services/picasaweb/gdata-picasaweb-query.h create mode 100644 gdata/services/picasaweb/gdata-picasaweb-service.c create mode 100644 gdata/services/picasaweb/gdata-picasaweb-service.h create mode 100644 gdata/services/picasaweb/gdata-picasaweb-user.c create mode 100644 gdata/services/picasaweb/gdata-picasaweb-user.h create mode 100644 gdata/services/picasaweb/meson.build create mode 100644 gdata/services/tasks/gdata-tasks-query.c create mode 100644 gdata/services/tasks/gdata-tasks-query.h create mode 100644 gdata/services/tasks/gdata-tasks-service.c create mode 100644 gdata/services/tasks/gdata-tasks-service.h create mode 100644 gdata/services/tasks/gdata-tasks-task.c create mode 100644 gdata/services/tasks/gdata-tasks-task.h create mode 100644 gdata/services/tasks/gdata-tasks-tasklist.c create mode 100644 gdata/services/tasks/gdata-tasks-tasklist.h create mode 100644 gdata/services/tasks/meson.build create mode 100644 gdata/services/youtube/gdata-youtube-category.c create mode 100644 gdata/services/youtube/gdata-youtube-category.h create mode 100644 gdata/services/youtube/gdata-youtube-comment.c create mode 100644 gdata/services/youtube/gdata-youtube-comment.h create mode 100644 gdata/services/youtube/gdata-youtube-content.c create mode 100644 gdata/services/youtube/gdata-youtube-content.h create mode 100644 gdata/services/youtube/gdata-youtube-credit.c create mode 100644 gdata/services/youtube/gdata-youtube-credit.h create mode 100644 gdata/services/youtube/gdata-youtube-feed.c create mode 100644 gdata/services/youtube/gdata-youtube-feed.h create mode 100644 gdata/services/youtube/gdata-youtube-query.c create mode 100644 gdata/services/youtube/gdata-youtube-query.h create mode 100644 gdata/services/youtube/gdata-youtube-service.c create mode 100644 gdata/services/youtube/gdata-youtube-service.h create mode 100644 gdata/services/youtube/gdata-youtube-state.c create mode 100644 gdata/services/youtube/gdata-youtube-state.h create mode 100644 gdata/services/youtube/gdata-youtube-video.c create mode 100644 gdata/services/youtube/gdata-youtube-video.h create mode 100644 gdata/services/youtube/meson.build create mode 100644 gdata/symbol.map create mode 100644 gdata/tests/authorization.c create mode 100644 gdata/tests/buffer.c create mode 100644 gdata/tests/calendar.c create mode 100644 gdata/tests/cert.pem create mode 100644 gdata/tests/common.c create mode 100644 gdata/tests/common.h create mode 100644 gdata/tests/contacts.c create mode 100644 gdata/tests/documents.c create mode 100644 gdata/tests/gdata-dummy-authorizer.c create mode 100644 gdata/tests/gdata-dummy-authorizer.h create mode 100644 gdata/tests/general.c create mode 100644 gdata/tests/key.pem create mode 100644 gdata/tests/meson.build create mode 100644 gdata/tests/oauth1-authorizer.c create mode 100644 gdata/tests/oauth2-authorizer.c create mode 100644 gdata/tests/perf.c create mode 100644 gdata/tests/photo.jpg create mode 100644 gdata/tests/picasaweb.c create mode 100644 gdata/tests/sample.ogg create mode 100644 gdata/tests/streams.c create mode 100644 gdata/tests/tasks.c create mode 100644 gdata/tests/template.test.in create mode 100644 gdata/tests/test.doc create mode 100644 gdata/tests/test.ods create mode 100644 gdata/tests/test.odt create mode 100644 gdata/tests/test.ppt create mode 100644 gdata/tests/test.xls create mode 100644 gdata/tests/test_updated.odt create mode 100644 gdata/tests/test_updated_file.ppt create mode 100644 gdata/tests/traces/calendar/access-rule-delete create mode 100644 gdata/tests/traces/calendar/access-rule-get create mode 100644 gdata/tests/traces/calendar/access-rule-insert create mode 100644 gdata/tests/traces/calendar/access-rule-update create mode 100644 gdata/tests/traces/calendar/authentication create mode 100644 gdata/tests/traces/calendar/authentication-async create mode 100644 gdata/tests/traces/calendar/authentication-async-cancellation create mode 100644 gdata/tests/traces/calendar/event-insert create mode 100644 gdata/tests/traces/calendar/event_insert-async create mode 100644 gdata/tests/traces/calendar/event_insert-async-cancellation create mode 100644 gdata/tests/traces/calendar/global-authentication create mode 100644 gdata/tests/traces/calendar/query-all-calendars create mode 100644 gdata/tests/traces/calendar/query-all-calendars-async-progress-closure create mode 100644 gdata/tests/traces/calendar/query-events create mode 100644 gdata/tests/traces/calendar/query-events-async-progress-closure create mode 100644 gdata/tests/traces/calendar/query-own-calendars create mode 100644 gdata/tests/traces/calendar/query-own-calendars-async-progress-closure create mode 100644 gdata/tests/traces/calendar/query_all_calendars-async create mode 100644 gdata/tests/traces/calendar/query_all_calendars-async-cancellation create mode 100644 gdata/tests/traces/calendar/query_events-async create mode 100644 gdata/tests/traces/calendar/query_events-async-cancellation create mode 100644 gdata/tests/traces/calendar/query_own_calendars-async create mode 100644 gdata/tests/traces/calendar/query_own_calendars-async-cancellation create mode 100644 gdata/tests/traces/calendar/setup-query-calendars create mode 100644 gdata/tests/traces/calendar/setup-query-events create mode 100644 gdata/tests/traces/calendar/setup-temp-calendar create mode 100644 gdata/tests/traces/calendar/setup-temp-calendar-acls create mode 100644 gdata/tests/traces/calendar/teardown-insert-event create mode 100644 gdata/tests/traces/calendar/teardown-query-calendars create mode 100644 gdata/tests/traces/calendar/teardown-query-events create mode 100644 gdata/tests/traces/calendar/teardown-temp-calendar create mode 100644 gdata/tests/traces/calendar/teardown-temp-calendar-acls create mode 100644 gdata/tests/traces/contacts/authentication create mode 100644 gdata/tests/traces/contacts/authentication-async create mode 100644 gdata/tests/traces/contacts/authentication-async-cancellation create mode 100644 gdata/tests/traces/contacts/batch create mode 100644 gdata/tests/traces/contacts/batch-async create mode 100644 gdata/tests/traces/contacts/batch-async-cancellation create mode 100644 gdata/tests/traces/contacts/contact-insert create mode 100644 gdata/tests/traces/contacts/contact-update create mode 100644 gdata/tests/traces/contacts/global-authentication create mode 100644 gdata/tests/traces/contacts/group-insert create mode 100644 gdata/tests/traces/contacts/group_insert-async create mode 100644 gdata/tests/traces/contacts/group_insert-async-cancellation create mode 100644 gdata/tests/traces/contacts/photo-add create mode 100644 gdata/tests/traces/contacts/photo-delete create mode 100644 gdata/tests/traces/contacts/photo-get create mode 100644 gdata/tests/traces/contacts/photo_add-async create mode 100644 gdata/tests/traces/contacts/photo_add-async-cancellation create mode 100644 gdata/tests/traces/contacts/photo_delete-async create mode 100644 gdata/tests/traces/contacts/photo_delete-async-cancellation create mode 100644 gdata/tests/traces/contacts/photo_get-async create mode 100644 gdata/tests/traces/contacts/photo_get-async-cancellation create mode 100644 gdata/tests/traces/contacts/query-all-contacts create mode 100644 gdata/tests/traces/contacts/query-all-contacts-async-progress-closure create mode 100644 gdata/tests/traces/contacts/query-all-groups create mode 100644 gdata/tests/traces/contacts/query-all-groups-async-progress-closure create mode 100644 gdata/tests/traces/contacts/query_all_contacts-async create mode 100644 gdata/tests/traces/contacts/query_all_contacts-async-cancellation create mode 100644 gdata/tests/traces/contacts/query_all_groups-async create mode 100644 gdata/tests/traces/contacts/query_all_groups-async-cancellation create mode 100644 gdata/tests/traces/contacts/setup-batch-async create mode 100644 gdata/tests/traces/contacts/setup-query-all-contacts create mode 100644 gdata/tests/traces/contacts/setup-query-all-groups create mode 100644 gdata/tests/traces/contacts/setup-temp-contact create mode 100644 gdata/tests/traces/contacts/setup-temp-contact-with-photo create mode 100644 gdata/tests/traces/contacts/teardown-batch-async create mode 100644 gdata/tests/traces/contacts/teardown-insert create mode 100644 gdata/tests/traces/contacts/teardown-insert-group create mode 100644 gdata/tests/traces/contacts/teardown-query-all-contacts create mode 100644 gdata/tests/traces/contacts/teardown-query-all-groups create mode 100644 gdata/tests/traces/contacts/teardown-temp-contact create mode 100644 gdata/tests/traces/documents/access-rule-insert create mode 100644 gdata/tests/traces/documents/authentication create mode 100644 gdata/tests/traces/documents/authentication-async create mode 100644 gdata/tests/traces/documents/authentication-async-cancellation create mode 100644 gdata/tests/traces/documents/batch create mode 100644 gdata/tests/traces/documents/batch-async create mode 100644 gdata/tests/traces/documents/batch-async-cancellation create mode 100644 gdata/tests/traces/documents/copy-document create mode 100644 gdata/tests/traces/documents/delete-document create mode 100644 gdata/tests/traces/documents/delete-folder create mode 100644 gdata/tests/traces/documents/download-document create mode 100644 gdata/tests/traces/documents/folders-add-to-folder create mode 100644 gdata/tests/traces/documents/folders-remove-from-folder create mode 100644 gdata/tests/traces/documents/folders_add_to_folder-async create mode 100644 gdata/tests/traces/documents/folders_add_to_folder-async-cancellation create mode 100644 gdata/tests/traces/documents/folders_remove_from_folder-async create mode 100644 gdata/tests/traces/documents/folders_remove_from_folder-async-cancellation create mode 100644 gdata/tests/traces/documents/folders_remove_from_folder-async-epilogue create mode 100644 gdata/tests/traces/documents/global-authentication create mode 100644 gdata/tests/traces/documents/query-all-documents create mode 100644 gdata/tests/traces/documents/query-all-documents-async-progress-closure create mode 100644 gdata/tests/traces/documents/query-all-documents-with-folder create mode 100644 gdata/tests/traces/documents/query_all_documents-async create mode 100644 gdata/tests/traces/documents/query_all_documents-async-cancellation create mode 100644 gdata/tests/traces/documents/setup-batch-async create mode 100644 gdata/tests/traces/documents/setup-folders-add-to-folder create mode 100644 gdata/tests/traces/documents/setup-folders-remove-from-folder create mode 100644 gdata/tests/traces/documents/setup-temp-document-spreadsheet create mode 100644 gdata/tests/traces/documents/setup-temp-documents create mode 100644 gdata/tests/traces/documents/setup-temp-folder create mode 100644 gdata/tests/traces/documents/setup-update-document_content-and-metadata-non-resumable create mode 100644 gdata/tests/traces/documents/setup-update-document_content-and-metadata-resumable create mode 100644 gdata/tests/traces/documents/setup-update-document_content-only-non-resumable create mode 100644 gdata/tests/traces/documents/setup-update-document_content-only-resumable create mode 100644 gdata/tests/traces/documents/setup-update-document_metadata-only-non-resumable create mode 100644 gdata/tests/traces/documents/setup-upload-document_content-and-metadata-in-folder-non-resumable-odt-convert create mode 100644 gdata/tests/traces/documents/setup-upload-document_content-and-metadata-in-folder-resumable-bin-no-convert create mode 100644 gdata/tests/traces/documents/setup-upload-document_content-and-metadata-in-folder-resumable-odt-convert create mode 100644 gdata/tests/traces/documents/setup-upload-document_content-and-metadata-in-folder-resumable-odt-no-convert create mode 100644 gdata/tests/traces/documents/setup-upload-document_content-and-metadata-root-folder-non-resumable-odt-convert create mode 100644 gdata/tests/traces/documents/setup-upload-document_content-and-metadata-root-folder-resumable-bin-no-convert create mode 100644 gdata/tests/traces/documents/setup-upload-document_content-and-metadata-root-folder-resumable-odt-convert create mode 100644 gdata/tests/traces/documents/setup-upload-document_content-and-metadata-root-folder-resumable-odt-no-convert create mode 100644 gdata/tests/traces/documents/setup-upload-document_content-only-in-folder-non-resumable-odt-convert create mode 100644 gdata/tests/traces/documents/setup-upload-document_content-only-in-folder-resumable-bin-no-convert create mode 100644 gdata/tests/traces/documents/setup-upload-document_content-only-in-folder-resumable-odt-convert create mode 100644 gdata/tests/traces/documents/setup-upload-document_content-only-in-folder-resumable-odt-no-convert create mode 100644 gdata/tests/traces/documents/setup-upload-document_content-only-root-folder-non-resumable-odt-convert create mode 100644 gdata/tests/traces/documents/setup-upload-document_content-only-root-folder-resumable-bin-no-convert create mode 100644 gdata/tests/traces/documents/setup-upload-document_content-only-root-folder-resumable-odt-convert create mode 100644 gdata/tests/traces/documents/setup-upload-document_content-only-root-folder-resumable-odt-no-convert create mode 100644 gdata/tests/traces/documents/setup-upload-document_metadata-only-in-folder-non-resumable-odt-convert create mode 100644 gdata/tests/traces/documents/setup-upload-document_metadata-only-root-folder-non-resumable-odt-convert create mode 100644 gdata/tests/traces/documents/teardown-batch-async create mode 100644 gdata/tests/traces/documents/teardown-copy-document create mode 100644 gdata/tests/traces/documents/teardown-folders-add-to-folder create mode 100644 gdata/tests/traces/documents/teardown-temp-document create mode 100644 gdata/tests/traces/documents/teardown-temp-documents create mode 100644 gdata/tests/traces/documents/teardown-temp-folder create mode 100644 gdata/tests/traces/documents/teardown-update-document_content-and-metadata-non-resumable create mode 100644 gdata/tests/traces/documents/teardown-update-document_content-and-metadata-resumable create mode 100644 gdata/tests/traces/documents/teardown-update-document_content-only-non-resumable create mode 100644 gdata/tests/traces/documents/teardown-update-document_content-only-resumable create mode 100644 gdata/tests/traces/documents/teardown-update-document_metadata-only-non-resumable create mode 100644 gdata/tests/traces/documents/teardown-upload-document_content-and-metadata-in-folder-non-resumable-odt-convert create mode 100644 gdata/tests/traces/documents/teardown-upload-document_content-and-metadata-in-folder-resumable-bin-no-convert create mode 100644 gdata/tests/traces/documents/teardown-upload-document_content-and-metadata-in-folder-resumable-odt-convert create mode 100644 gdata/tests/traces/documents/teardown-upload-document_content-and-metadata-in-folder-resumable-odt-no-convert create mode 100644 gdata/tests/traces/documents/teardown-upload-document_content-and-metadata-root-folder-non-resumable-odt-convert create mode 100644 gdata/tests/traces/documents/teardown-upload-document_content-and-metadata-root-folder-resumable-bin-no-convert create mode 100644 gdata/tests/traces/documents/teardown-upload-document_content-and-metadata-root-folder-resumable-odt-convert create mode 100644 gdata/tests/traces/documents/teardown-upload-document_content-and-metadata-root-folder-resumable-odt-no-convert create mode 100644 gdata/tests/traces/documents/teardown-upload-document_content-only-in-folder-non-resumable-odt-convert create mode 100644 gdata/tests/traces/documents/teardown-upload-document_content-only-in-folder-resumable-bin-no-convert create mode 100644 gdata/tests/traces/documents/teardown-upload-document_content-only-in-folder-resumable-odt-convert create mode 100644 gdata/tests/traces/documents/teardown-upload-document_content-only-in-folder-resumable-odt-no-convert create mode 100644 gdata/tests/traces/documents/teardown-upload-document_content-only-root-folder-non-resumable-odt-convert create mode 100644 gdata/tests/traces/documents/teardown-upload-document_content-only-root-folder-resumable-bin-no-convert create mode 100644 gdata/tests/traces/documents/teardown-upload-document_content-only-root-folder-resumable-odt-convert create mode 100644 gdata/tests/traces/documents/teardown-upload-document_content-only-root-folder-resumable-odt-no-convert create mode 100644 gdata/tests/traces/documents/teardown-upload-document_metadata-only-in-folder-non-resumable-odt-convert create mode 100644 gdata/tests/traces/documents/teardown-upload-document_metadata-only-root-folder-non-resumable-odt-convert create mode 100644 gdata/tests/traces/documents/update_content-and-metadata-non-resumable create mode 100644 gdata/tests/traces/documents/update_content-and-metadata-resumable create mode 100644 gdata/tests/traces/documents/update_content-only-non-resumable create mode 100644 gdata/tests/traces/documents/update_content-only-resumable create mode 100644 gdata/tests/traces/documents/update_metadata-only-non-resumable create mode 100644 gdata/tests/traces/documents/upload_content-and-metadata-in-folder-non-resumable-odt-convert create mode 100644 gdata/tests/traces/documents/upload_content-and-metadata-in-folder-resumable-bin-no-convert create mode 100644 gdata/tests/traces/documents/upload_content-and-metadata-in-folder-resumable-odt-convert create mode 100644 gdata/tests/traces/documents/upload_content-and-metadata-in-folder-resumable-odt-no-convert create mode 100644 gdata/tests/traces/documents/upload_content-and-metadata-root-folder-non-resumable-odt-convert create mode 100644 gdata/tests/traces/documents/upload_content-and-metadata-root-folder-resumable-bin-no-convert create mode 100644 gdata/tests/traces/documents/upload_content-and-metadata-root-folder-resumable-odt-convert create mode 100644 gdata/tests/traces/documents/upload_content-and-metadata-root-folder-resumable-odt-no-convert create mode 100644 gdata/tests/traces/documents/upload_content-only-in-folder-non-resumable-odt-convert create mode 100644 gdata/tests/traces/documents/upload_content-only-in-folder-resumable-bin-no-convert create mode 100644 gdata/tests/traces/documents/upload_content-only-in-folder-resumable-odt-convert create mode 100644 gdata/tests/traces/documents/upload_content-only-in-folder-resumable-odt-no-convert create mode 100644 gdata/tests/traces/documents/upload_content-only-root-folder-non-resumable-odt-convert create mode 100644 gdata/tests/traces/documents/upload_content-only-root-folder-resumable-bin-no-convert create mode 100644 gdata/tests/traces/documents/upload_content-only-root-folder-resumable-odt-convert create mode 100644 gdata/tests/traces/documents/upload_content-only-root-folder-resumable-odt-no-convert create mode 100644 gdata/tests/traces/documents/upload_metadata-only-in-folder-non-resumable-odt-convert create mode 100644 gdata/tests/traces/documents/upload_metadata-only-root-folder-non-resumable-odt-convert create mode 100644 gdata/tests/traces/oauth1-authorizer/oauth1-authorizer-interactive-data-bad-credentials create mode 100644 gdata/tests/traces/oauth1-authorizer/oauth1-authorizer-refresh-authorization create mode 100644 gdata/tests/traces/oauth1-authorizer/oauth1-authorizer-request-authentication-uri-async create mode 100644 gdata/tests/traces/oauth1-authorizer/oauth1-authorizer-request-authentication-uri-async-cancellation create mode 100644 gdata/tests/traces/oauth1-authorizer/oauth1-authorizer-request-authentication-uri-sync create mode 100644 gdata/tests/traces/oauth1-authorizer/oauth1-authorizer-request-authentication-uri-sync-cancellation create mode 100644 gdata/tests/traces/oauth1-authorizer/oauth1-authorizer-request-authorization-async create mode 100644 gdata/tests/traces/oauth1-authorizer/oauth1-authorizer-request-authorization-async-bad-credentials create mode 100644 gdata/tests/traces/oauth1-authorizer/oauth1-authorizer-request-authorization-async-cancellation create mode 100644 gdata/tests/traces/oauth1-authorizer/oauth1-authorizer-request-authorization-sync create mode 100644 gdata/tests/traces/oauth1-authorizer/oauth1-authorizer-request-authorization-sync-bad-credentials create mode 100644 gdata/tests/traces/oauth1-authorizer/oauth1-authorizer-request-authorization-sync-cancellation create mode 100644 gdata/tests/traces/oauth1-authorizer/setup-oauth1-authorizer-data-authenticated create mode 100644 gdata/tests/traces/oauth1-authorizer/setup-oauth1-authorizer-interactive-data create mode 100644 gdata/tests/traces/oauth2-authorizer/oauth2-authorizer-refresh-authorization-authorized create mode 100644 gdata/tests/traces/oauth2-authorizer/oauth2-authorizer-refresh-authorization-unauthorized create mode 100644 gdata/tests/traces/oauth2-authorizer/oauth2-authorizer-request-authorization-async create mode 100644 gdata/tests/traces/oauth2-authorizer/oauth2-authorizer-request-authorization-async-bad-credentials create mode 100644 gdata/tests/traces/oauth2-authorizer/oauth2-authorizer-request-authorization-async-cancellation create mode 100644 gdata/tests/traces/oauth2-authorizer/oauth2-authorizer-request-authorization-sync create mode 100644 gdata/tests/traces/oauth2-authorizer/oauth2-authorizer-request-authorization-sync-bad-credentials create mode 100644 gdata/tests/traces/oauth2-authorizer/oauth2-authorizer-request-authorization-sync-cancellation create mode 100644 gdata/tests/traces/oauth2-authorizer/setup-oauth2-authorizer-data-authenticated create mode 100644 gdata/tests/traces/picasaweb/authentication create mode 100644 gdata/tests/traces/picasaweb/authentication-async create mode 100644 gdata/tests/traces/picasaweb/authentication-async-cancellation create mode 100644 gdata/tests/traces/picasaweb/comment-delete create mode 100644 gdata/tests/traces/picasaweb/comment-insert create mode 100644 gdata/tests/traces/picasaweb/comment-query create mode 100644 gdata/tests/traces/picasaweb/comment-query-async-progress-closure create mode 100644 gdata/tests/traces/picasaweb/comment_delete-async create mode 100644 gdata/tests/traces/picasaweb/comment_delete-async-cancellation create mode 100644 gdata/tests/traces/picasaweb/comment_insert-async create mode 100644 gdata/tests/traces/picasaweb/comment_insert-async-cancellation create mode 100644 gdata/tests/traces/picasaweb/comment_query-async create mode 100644 gdata/tests/traces/picasaweb/comment_query-async-cancellation create mode 100644 gdata/tests/traces/picasaweb/download-photo create mode 100644 gdata/tests/traces/picasaweb/download-thumbnails create mode 100644 gdata/tests/traces/picasaweb/global-authentication create mode 100644 gdata/tests/traces/picasaweb/insert-album create mode 100644 gdata/tests/traces/picasaweb/insert_album-async create mode 100644 gdata/tests/traces/picasaweb/insert_album-async-cancellation create mode 100644 gdata/tests/traces/picasaweb/query-all-albums create mode 100644 gdata/tests/traces/picasaweb/query-all-albums-async-progress-closure create mode 100644 gdata/tests/traces/picasaweb/query-all-albums-with-limits create mode 100644 gdata/tests/traces/picasaweb/query-files create mode 100644 gdata/tests/traces/picasaweb/query-files-async-progress-closure create mode 100644 gdata/tests/traces/picasaweb/query-files-single create mode 100644 gdata/tests/traces/picasaweb/query-user create mode 100644 gdata/tests/traces/picasaweb/query_all_albums-async create mode 100644 gdata/tests/traces/picasaweb/query_all_albums-async-cancellation create mode 100644 gdata/tests/traces/picasaweb/query_files-async create mode 100644 gdata/tests/traces/picasaweb/query_files-async-cancellation create mode 100644 gdata/tests/traces/picasaweb/query_user-async create mode 100644 gdata/tests/traces/picasaweb/query_user-async-cancellation create mode 100644 gdata/tests/traces/picasaweb/query_user_by_username-async create mode 100644 gdata/tests/traces/picasaweb/query_user_by_username-async-cancellation create mode 100644 gdata/tests/traces/picasaweb/setup-query-all-albums create mode 100644 gdata/tests/traces/picasaweb/setup-query-comments create mode 100644 gdata/tests/traces/picasaweb/setup-query-files create mode 100644 gdata/tests/traces/picasaweb/setup-upload create mode 100644 gdata/tests/traces/picasaweb/teardown-insert-album create mode 100644 gdata/tests/traces/picasaweb/teardown-insert-comment create mode 100644 gdata/tests/traces/picasaweb/teardown-query-all-albums create mode 100644 gdata/tests/traces/picasaweb/teardown-query-comments create mode 100644 gdata/tests/traces/picasaweb/teardown-query-files create mode 100644 gdata/tests/traces/picasaweb/teardown-upload create mode 100644 gdata/tests/traces/picasaweb/upload-default-album create mode 100644 gdata/tests/traces/picasaweb/upload_default_album-async create mode 100644 gdata/tests/traces/picasaweb/upload_default_album-async-cancellation create mode 100644 gdata/tests/traces/tasks/authentication create mode 100644 gdata/tests/traces/tasks/global-authentication create mode 100644 gdata/tests/traces/tasks/setup-delete-task create mode 100644 gdata/tests/traces/tasks/setup-delete-tasklist create mode 100644 gdata/tests/traces/tasks/setup-insert-task create mode 100644 gdata/tests/traces/tasks/setup-list-task create mode 100644 gdata/tests/traces/tasks/setup-list-tasklist create mode 100644 gdata/tests/traces/tasks/setup-update-task create mode 100644 gdata/tests/traces/tasks/setup-update-tasklist create mode 100644 gdata/tests/traces/tasks/task-delete create mode 100644 gdata/tests/traces/tasks/task-insert create mode 100644 gdata/tests/traces/tasks/task-list create mode 100644 gdata/tests/traces/tasks/task-update create mode 100644 gdata/tests/traces/tasks/tasklist-delete create mode 100644 gdata/tests/traces/tasks/tasklist-insert create mode 100644 gdata/tests/traces/tasks/tasklist-insert-unauthorised create mode 100644 gdata/tests/traces/tasks/tasklist-list create mode 100644 gdata/tests/traces/tasks/tasklist-update create mode 100644 gdata/tests/traces/tasks/teardown-delete-task create mode 100644 gdata/tests/traces/tasks/teardown-insert-task create mode 100644 gdata/tests/traces/tasks/teardown-insert-tasklist create mode 100644 gdata/tests/traces/tasks/teardown-list-task create mode 100644 gdata/tests/traces/tasks/teardown-list-tasklist create mode 100644 gdata/tests/traces/tasks/teardown-update-task create mode 100644 gdata/tests/traces/tasks/teardown-update-tasklist create mode 100644 gdata/tests/traces/youtube/authentication create mode 100644 gdata/tests/traces/youtube/authentication-async create mode 100644 gdata/tests/traces/youtube/authentication-async-cancellation create mode 100644 gdata/tests/traces/youtube/batch create mode 100644 gdata/tests/traces/youtube/batch-async create mode 100644 gdata/tests/traces/youtube/batch-async-cancellation create mode 100644 gdata/tests/traces/youtube/categories create mode 100644 gdata/tests/traces/youtube/categories-async create mode 100644 gdata/tests/traces/youtube/categories-async-cancellation create mode 100644 gdata/tests/traces/youtube/comment-delete create mode 100644 gdata/tests/traces/youtube/comment-insert create mode 100644 gdata/tests/traces/youtube/comment-query create mode 100644 gdata/tests/traces/youtube/comment-query-async-progress-closure create mode 100644 gdata/tests/traces/youtube/comment_delete-async create mode 100644 gdata/tests/traces/youtube/comment_delete-async-cancellation create mode 100644 gdata/tests/traces/youtube/comment_insert-async create mode 100644 gdata/tests/traces/youtube/comment_insert-async-cancellation create mode 100644 gdata/tests/traces/youtube/comment_query-async create mode 100644 gdata/tests/traces/youtube/comment_query-async-cancellation create mode 100644 gdata/tests/traces/youtube/global-authentication create mode 100644 gdata/tests/traces/youtube/query-related create mode 100644 gdata/tests/traces/youtube/query-related-async-progress-closure create mode 100644 gdata/tests/traces/youtube/query-single create mode 100644 gdata/tests/traces/youtube/query-standard-feed create mode 100644 gdata/tests/traces/youtube/query-standard-feed-async-progress-closure create mode 100644 gdata/tests/traces/youtube/query-standard-feed-with-query create mode 100644 gdata/tests/traces/youtube/query-standard-feeds create mode 100644 gdata/tests/traces/youtube/query_related-async create mode 100644 gdata/tests/traces/youtube/query_related-async-cancellation create mode 100644 gdata/tests/traces/youtube/query_single-async create mode 100644 gdata/tests/traces/youtube/query_single-async-cancellation create mode 100644 gdata/tests/traces/youtube/query_standard_feed-async create mode 100644 gdata/tests/traces/youtube/query_standard_feed-async-cancellation create mode 100644 gdata/tests/traces/youtube/setup-batch create mode 100644 gdata/tests/traces/youtube/setup-comment create mode 100644 gdata/tests/traces/youtube/setup-insert-comment create mode 100644 gdata/tests/traces/youtube/teardown-insert-comment create mode 100644 gdata/tests/traces/youtube/teardown-upload create mode 100644 gdata/tests/traces/youtube/upload-async create mode 100644 gdata/tests/traces/youtube/upload-async-cancellation create mode 100644 gdata/tests/traces/youtube/upload-simple create mode 100644 gdata/tests/youtube.c create mode 100644 libgdata.doap create mode 100644 meson.build create mode 100644 meson_options.txt create mode 100644 po/LINGUAS create mode 100644 po/POTFILES.in create mode 100644 po/ar.po create mode 100644 po/as.po create mode 100644 po/be.po create mode 100644 po/bg.po create mode 100644 po/bn_IN.po create mode 100644 po/bs.po create mode 100644 po/ca.po create mode 100644 po/ca@valencia.po create mode 100644 po/cs.po create mode 100644 po/da.po create mode 100644 po/de.po create mode 100644 po/el.po create mode 100644 po/en_GB.po create mode 100644 po/eo.po create mode 100644 po/es.po create mode 100644 po/et.po create mode 100644 po/eu.po create mode 100644 po/fi.po create mode 100644 po/fr.po create mode 100644 po/fur.po create mode 100644 po/gl.po create mode 100644 po/gu.po create mode 100644 po/he.po create mode 100644 po/hi.po create mode 100644 po/hr.po create mode 100644 po/hu.po create mode 100644 po/id.po create mode 100644 po/it.po create mode 100644 po/ja.po create mode 100644 po/kn.po create mode 100644 po/ko.po create mode 100644 po/lt.po create mode 100644 po/lv.po create mode 100644 po/meson.build create mode 100644 po/ml.po create mode 100644 po/mr.po create mode 100644 po/ms.po create mode 100644 po/nb.po create mode 100644 po/ne.po create mode 100644 po/nl.po create mode 100644 po/oc.po create mode 100644 po/or.po create mode 100644 po/pa.po create mode 100644 po/pl.po create mode 100644 po/pt.po create mode 100644 po/pt_BR.po create mode 100644 po/ro.po create mode 100644 po/ru.po create mode 100644 po/sk.po create mode 100644 po/sl.po create mode 100644 po/sr.po create mode 100644 po/sr@latin.po create mode 100644 po/sv.po create mode 100644 po/ta.po create mode 100644 po/te.po create mode 100644 po/tg.po create mode 100644 po/th.po create mode 100644 po/tr.po create mode 100644 po/ug.po create mode 100644 po/uk.po create mode 100644 po/vi.po create mode 100644 po/zh_CN.po create mode 100644 po/zh_HK.po create mode 100644 po/zh_TW.po diff --git a/AUTHORS b/AUTHORS new file mode 100644 index 0000000..426a183 --- /dev/null +++ b/AUTHORS @@ -0,0 +1 @@ +Philip Withnall diff --git a/COPYING b/COPYING new file mode 100644 index 0000000..5ab7695 --- /dev/null +++ b/COPYING @@ -0,0 +1,504 @@ + GNU LESSER GENERAL PUBLIC LICENSE + Version 2.1, February 1999 + + Copyright (C) 1991, 1999 Free Software Foundation, Inc. + 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + +[This is the first released version of the Lesser GPL. It also counts + as the successor of the GNU Library Public License, version 2, hence + the version number 2.1.] + + Preamble + + The licenses for most software are designed to take away your +freedom to share and change it. By contrast, the GNU General Public +Licenses are intended to guarantee your freedom to share and change +free software--to make sure the software is free for all its users. + + This license, the Lesser General Public License, applies to some +specially designated software packages--typically libraries--of the +Free Software Foundation and other authors who decide to use it. You +can use it too, but we suggest you first think carefully about whether +this license or the ordinary General Public License is the better +strategy to use in any particular case, based on the explanations below. + + When we speak of free software, we are referring to freedom of use, +not price. Our General Public Licenses are designed to make sure that +you have the freedom to distribute copies of free software (and charge +for this service if you wish); that you receive source code or can get +it if you want it; that you can change the software and use pieces of +it in new free programs; and that you are informed that you can do +these things. + + To protect your rights, we need to make restrictions that forbid +distributors to deny you these rights or to ask you to surrender these +rights. These restrictions translate to certain responsibilities for +you if you distribute copies of the library or if you modify it. + + For example, if you distribute copies of the library, whether gratis +or for a fee, you must give the recipients all the rights that we gave +you. You must make sure that they, too, receive or can get the source +code. If you link other code with the library, you must provide +complete object files to the recipients, so that they can relink them +with the library after making changes to the library and recompiling +it. And you must show them these terms so they know their rights. + + We protect your rights with a two-step method: (1) we copyright the +library, and (2) we offer you this license, which gives you legal +permission to copy, distribute and/or modify the library. + + To protect each distributor, we want to make it very clear that +there is no warranty for the free library. Also, if the library is +modified by someone else and passed on, the recipients should know +that what they have is not the original version, so that the original +author's reputation will not be affected by problems that might be +introduced by others. + + Finally, software patents pose a constant threat to the existence of +any free program. We wish to make sure that a company cannot +effectively restrict the users of a free program by obtaining a +restrictive license from a patent holder. Therefore, we insist that +any patent license obtained for a version of the library must be +consistent with the full freedom of use specified in this license. + + Most GNU software, including some libraries, is covered by the +ordinary GNU General Public License. This license, the GNU Lesser +General Public License, applies to certain designated libraries, and +is quite different from the ordinary General Public License. We use +this license for certain libraries in order to permit linking those +libraries into non-free programs. + + When a program is linked with a library, whether statically or using +a shared library, the combination of the two is legally speaking a +combined work, a derivative of the original library. The ordinary +General Public License therefore permits such linking only if the +entire combination fits its criteria of freedom. The Lesser General +Public License permits more lax criteria for linking other code with +the library. + + We call this license the "Lesser" General Public License because it +does Less to protect the user's freedom than the ordinary General +Public License. It also provides other free software developers Less +of an advantage over competing non-free programs. These disadvantages +are the reason we use the ordinary General Public License for many +libraries. However, the Lesser license provides advantages in certain +special circumstances. + + For example, on rare occasions, there may be a special need to +encourage the widest possible use of a certain library, so that it becomes +a de-facto standard. To achieve this, non-free programs must be +allowed to use the library. A more frequent case is that a free +library does the same job as widely used non-free libraries. In this +case, there is little to gain by limiting the free library to free +software only, so we use the Lesser General Public License. + + In other cases, permission to use a particular library in non-free +programs enables a greater number of people to use a large body of +free software. For example, permission to use the GNU C Library in +non-free programs enables many more people to use the whole GNU +operating system, as well as its variant, the GNU/Linux operating +system. + + Although the Lesser General Public License is Less protective of the +users' freedom, it does ensure that the user of a program that is +linked with the Library has the freedom and the wherewithal to run +that program using a modified version of the Library. + + The precise terms and conditions for copying, distribution and +modification follow. Pay close attention to the difference between a +"work based on the library" and a "work that uses the library". The +former contains code derived from the library, whereas the latter must +be combined with the library in order to run. + + GNU LESSER GENERAL PUBLIC LICENSE + TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION + + 0. This License Agreement applies to any software library or other +program which contains a notice placed by the copyright holder or +other authorized party saying it may be distributed under the terms of +this Lesser General Public License (also called "this License"). +Each licensee is addressed as "you". + + A "library" means a collection of software functions and/or data +prepared so as to be conveniently linked with application programs +(which use some of those functions and data) to form executables. + + The "Library", below, refers to any such software library or work +which has been distributed under these terms. A "work based on the +Library" means either the Library or any derivative work under +copyright law: that is to say, a work containing the Library or a +portion of it, either verbatim or with modifications and/or translated +straightforwardly into another language. (Hereinafter, translation is +included without limitation in the term "modification".) + + "Source code" for a work means the preferred form of the work for +making modifications to it. For a library, complete source code means +all the source code for all modules it contains, plus any associated +interface definition files, plus the scripts used to control compilation +and installation of the library. + + Activities other than copying, distribution and modification are not +covered by this License; they are outside its scope. The act of +running a program using the Library is not restricted, and output from +such a program is covered only if its contents constitute a work based +on the Library (independent of the use of the Library in a tool for +writing it). Whether that is true depends on what the Library does +and what the program that uses the Library does. + + 1. You may copy and distribute verbatim copies of the Library's +complete source code as you receive it, in any medium, provided that +you conspicuously and appropriately publish on each copy an +appropriate copyright notice and disclaimer of warranty; keep intact +all the notices that refer to this License and to the absence of any +warranty; and distribute a copy of this License along with the +Library. + + You may charge a fee for the physical act of transferring a copy, +and you may at your option offer warranty protection in exchange for a +fee. + + 2. You may modify your copy or copies of the Library or any portion +of it, thus forming a work based on the Library, and copy and +distribute such modifications or work under the terms of Section 1 +above, provided that you also meet all of these conditions: + + a) The modified work must itself be a software library. + + b) You must cause the files modified to carry prominent notices + stating that you changed the files and the date of any change. + + c) You must cause the whole of the work to be licensed at no + charge to all third parties under the terms of this License. + + d) If a facility in the modified Library refers to a function or a + table of data to be supplied by an application program that uses + the facility, other than as an argument passed when the facility + is invoked, then you must make a good faith effort to ensure that, + in the event an application does not supply such function or + table, the facility still operates, and performs whatever part of + its purpose remains meaningful. + + (For example, a function in a library to compute square roots has + a purpose that is entirely well-defined independent of the + application. Therefore, Subsection 2d requires that any + application-supplied function or table used by this function must + be optional: if the application does not supply it, the square + root function must still compute square roots.) + +These requirements apply to the modified work as a whole. If +identifiable sections of that work are not derived from the Library, +and can be reasonably considered independent and separate works in +themselves, then this License, and its terms, do not apply to those +sections when you distribute them as separate works. But when you +distribute the same sections as part of a whole which is a work based +on the Library, the distribution of the whole must be on the terms of +this License, whose permissions for other licensees extend to the +entire whole, and thus to each and every part regardless of who wrote +it. + +Thus, it is not the intent of this section to claim rights or contest +your rights to work written entirely by you; rather, the intent is to +exercise the right to control the distribution of derivative or +collective works based on the Library. + +In addition, mere aggregation of another work not based on the Library +with the Library (or with a work based on the Library) on a volume of +a storage or distribution medium does not bring the other work under +the scope of this License. + + 3. You may opt to apply the terms of the ordinary GNU General Public +License instead of this License to a given copy of the Library. To do +this, you must alter all the notices that refer to this License, so +that they refer to the ordinary GNU General Public License, version 2, +instead of to this License. (If a newer version than version 2 of the +ordinary GNU General Public License has appeared, then you can specify +that version instead if you wish.) Do not make any other change in +these notices. + + Once this change is made in a given copy, it is irreversible for +that copy, so the ordinary GNU General Public License applies to all +subsequent copies and derivative works made from that copy. + + This option is useful when you wish to copy part of the code of +the Library into a program that is not a library. + + 4. You may copy and distribute the Library (or a portion or +derivative of it, under Section 2) in object code or executable form +under the terms of Sections 1 and 2 above provided that you accompany +it with the complete corresponding machine-readable source code, which +must be distributed under the terms of Sections 1 and 2 above on a +medium customarily used for software interchange. + + If distribution of object code is made by offering access to copy +from a designated place, then offering equivalent access to copy the +source code from the same place satisfies the requirement to +distribute the source code, even though third parties are not +compelled to copy the source along with the object code. + + 5. A program that contains no derivative of any portion of the +Library, but is designed to work with the Library by being compiled or +linked with it, is called a "work that uses the Library". Such a +work, in isolation, is not a derivative work of the Library, and +therefore falls outside the scope of this License. + + However, linking a "work that uses the Library" with the Library +creates an executable that is a derivative of the Library (because it +contains portions of the Library), rather than a "work that uses the +library". The executable is therefore covered by this License. +Section 6 states terms for distribution of such executables. + + When a "work that uses the Library" uses material from a header file +that is part of the Library, the object code for the work may be a +derivative work of the Library even though the source code is not. +Whether this is true is especially significant if the work can be +linked without the Library, or if the work is itself a library. The +threshold for this to be true is not precisely defined by law. + + If such an object file uses only numerical parameters, data +structure layouts and accessors, and small macros and small inline +functions (ten lines or less in length), then the use of the object +file is unrestricted, regardless of whether it is legally a derivative +work. (Executables containing this object code plus portions of the +Library will still fall under Section 6.) + + Otherwise, if the work is a derivative of the Library, you may +distribute the object code for the work under the terms of Section 6. +Any executables containing that work also fall under Section 6, +whether or not they are linked directly with the Library itself. + + 6. As an exception to the Sections above, you may also combine or +link a "work that uses the Library" with the Library to produce a +work containing portions of the Library, and distribute that work +under terms of your choice, provided that the terms permit +modification of the work for the customer's own use and reverse +engineering for debugging such modifications. + + You must give prominent notice with each copy of the work that the +Library is used in it and that the Library and its use are covered by +this License. You must supply a copy of this License. If the work +during execution displays copyright notices, you must include the +copyright notice for the Library among them, as well as a reference +directing the user to the copy of this License. Also, you must do one +of these things: + + a) Accompany the work with the complete corresponding + machine-readable source code for the Library including whatever + changes were used in the work (which must be distributed under + Sections 1 and 2 above); and, if the work is an executable linked + with the Library, with the complete machine-readable "work that + uses the Library", as object code and/or source code, so that the + user can modify the Library and then relink to produce a modified + executable containing the modified Library. (It is understood + that the user who changes the contents of definitions files in the + Library will not necessarily be able to recompile the application + to use the modified definitions.) + + b) Use a suitable shared library mechanism for linking with the + Library. A suitable mechanism is one that (1) uses at run time a + copy of the library already present on the user's computer system, + rather than copying library functions into the executable, and (2) + will operate properly with a modified version of the library, if + the user installs one, as long as the modified version is + interface-compatible with the version that the work was made with. + + c) Accompany the work with a written offer, valid for at + least three years, to give the same user the materials + specified in Subsection 6a, above, for a charge no more + than the cost of performing this distribution. + + d) If distribution of the work is made by offering access to copy + from a designated place, offer equivalent access to copy the above + specified materials from the same place. + + e) Verify that the user has already received a copy of these + materials or that you have already sent this user a copy. + + For an executable, the required form of the "work that uses the +Library" must include any data and utility programs needed for +reproducing the executable from it. However, as a special exception, +the materials to be distributed need not include anything that is +normally distributed (in either source or binary form) with the major +components (compiler, kernel, and so on) of the operating system on +which the executable runs, unless that component itself accompanies +the executable. + + It may happen that this requirement contradicts the license +restrictions of other proprietary libraries that do not normally +accompany the operating system. Such a contradiction means you cannot +use both them and the Library together in an executable that you +distribute. + + 7. You may place library facilities that are a work based on the +Library side-by-side in a single library together with other library +facilities not covered by this License, and distribute such a combined +library, provided that the separate distribution of the work based on +the Library and of the other library facilities is otherwise +permitted, and provided that you do these two things: + + a) Accompany the combined library with a copy of the same work + based on the Library, uncombined with any other library + facilities. This must be distributed under the terms of the + Sections above. + + b) Give prominent notice with the combined library of the fact + that part of it is a work based on the Library, and explaining + where to find the accompanying uncombined form of the same work. + + 8. You may not copy, modify, sublicense, link with, or distribute +the Library except as expressly provided under this License. Any +attempt otherwise to copy, modify, sublicense, link with, or +distribute the Library is void, and will automatically terminate your +rights under this License. However, parties who have received copies, +or rights, from you under this License will not have their licenses +terminated so long as such parties remain in full compliance. + + 9. You are not required to accept this License, since you have not +signed it. However, nothing else grants you permission to modify or +distribute the Library or its derivative works. These actions are +prohibited by law if you do not accept this License. Therefore, by +modifying or distributing the Library (or any work based on the +Library), you indicate your acceptance of this License to do so, and +all its terms and conditions for copying, distributing or modifying +the Library or works based on it. + + 10. Each time you redistribute the Library (or any work based on the +Library), the recipient automatically receives a license from the +original licensor to copy, distribute, link with or modify the Library +subject to these terms and conditions. You may not impose any further +restrictions on the recipients' exercise of the rights granted herein. +You are not responsible for enforcing compliance by third parties with +this License. + + 11. If, as a consequence of a court judgment or allegation of patent +infringement or for any other reason (not limited to patent issues), +conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot +distribute so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you +may not distribute the Library at all. For example, if a patent +license would not permit royalty-free redistribution of the Library by +all those who receive copies directly or indirectly through you, then +the only way you could satisfy both it and this License would be to +refrain entirely from distribution of the Library. + +If any portion of this section is held invalid or unenforceable under any +particular circumstance, the balance of the section is intended to apply, +and the section as a whole is intended to apply in other circumstances. + +It is not the purpose of this section to induce you to infringe any +patents or other property right claims or to contest validity of any +such claims; this section has the sole purpose of protecting the +integrity of the free software distribution system which is +implemented by public license practices. Many people have made +generous contributions to the wide range of software distributed +through that system in reliance on consistent application of that +system; it is up to the author/donor to decide if he or she is willing +to distribute software through any other system and a licensee cannot +impose that choice. + +This section is intended to make thoroughly clear what is believed to +be a consequence of the rest of this License. + + 12. If the distribution and/or use of the Library is restricted in +certain countries either by patents or by copyrighted interfaces, the +original copyright holder who places the Library under this License may add +an explicit geographical distribution limitation excluding those countries, +so that distribution is permitted only in or among countries not thus +excluded. In such case, this License incorporates the limitation as if +written in the body of this License. + + 13. The Free Software Foundation may publish revised and/or new +versions of the Lesser General Public License from time to time. +Such new versions will be similar in spirit to the present version, +but may differ in detail to address new problems or concerns. + +Each version is given a distinguishing version number. If the Library +specifies a version number of this License which applies to it and +"any later version", you have the option of following the terms and +conditions either of that version or of any later version published by +the Free Software Foundation. If the Library does not specify a +license version number, you may choose any version ever published by +the Free Software Foundation. + + 14. If you wish to incorporate parts of the Library into other free +programs whose distribution conditions are incompatible with these, +write to the author to ask for permission. For software which is +copyrighted by the Free Software Foundation, write to the Free +Software Foundation; we sometimes make exceptions for this. Our +decision will be guided by the two goals of preserving the free status +of all derivatives of our free software and of promoting the sharing +and reuse of software generally. + + NO WARRANTY + + 15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO +WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW. +EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR +OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY +KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE +LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME +THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN +WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY +AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU +FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR +CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE +LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING +RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A +FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF +SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH +DAMAGES. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Libraries + + If you develop a new library, and you want it to be of the greatest +possible use to the public, we recommend making it free software that +everyone can redistribute and change. You can do so by permitting +redistribution under these terms (or, alternatively, under the terms of the +ordinary General Public License). + + To apply these terms, attach the following notices to the library. It is +safest to attach them to the start of each source file to most effectively +convey the exclusion of warranty; and each file should have at least the +"copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + +Also add information on how to contact you by electronic and paper mail. + +You should also get your employer (if you work as a programmer) or your +school, if any, to sign a "copyright disclaimer" for the library, if +necessary. Here is a sample; alter the names: + + Yoyodyne, Inc., hereby disclaims all copyright interest in the + library `Frob' (a library for tweaking knobs) written by James Random Hacker. + + , 1 April 1990 + Ty Coon, President of Vice + +That's all there is to it! + + diff --git a/HACKING b/HACKING new file mode 100644 index 0000000..32917c7 --- /dev/null +++ b/HACKING @@ -0,0 +1,216 @@ +Formatting +========== + +All code should follow the same formatting standards which are broadly based on the GNU style (http://www.gnu.org/prep/standards.html) with some +additions. Briefly: + + - Tab indents are used and braces for blocks go on the same line as the block statement: + + if (x < foo (y, z)) { + haha = bar[4] + 5; + } else { + while (z) { + haha += foo (z, z); + z--; + } + return abc (haha); + } + + Braces should be omitted for single-line blocks, but included for all blocks in a multi-part if statement which has blocks containing more than + one line (as above). + + - Spaces should be present between function name and argument block, and after commas: + + foo (z, z) + + - In pointer types, the '*' is grouped with the variable name, not with the base type. + + int *a; + + Not: + + int* a; + + In cases where there is no variable name, for instance, return values, there should be a single space between the base type and the '*'. + + Type casts should have no space between the type and '*', but a space before the variable being cast: + + (gchar*) foobar; + (gchar**) &foobar; + + - Function and variable names are lower_case_with_underscores, type names are CamelCase and macro names are UPPER_CASE_WITH_UNDERSCORES. + + - Comparisons to NULL, TRUE and FALSE should always be made explicit, for clarity. + + - Code should be wrapped at the 150th column, such that it doesn't require horizontal scrolling on a decent-sized display. + Don't wrap at the 80th column. + +Documentation comments +====================== + +All public API functions should have inline documentation headers in the gtk-doc style. For more information about gtk-doc comments, see the gtk-doc +manual (http://library.gnome.org/devel/gtk-doc-manual/stable/). There are a few conventions above and beyond the standard gtk-doc formatting which +libgdata employs: + + - For API which returns allocated memory, the relevant free/unref function must be mentioned in the "Return value" part of the documentation: + + * Return value: a new #GDataEntry; unref with g_object_unref() + + If the function can also return NULL (on error, for example) or some other "default" value (-1, 0, etc.), format it as follows: + + * Return value: a new #GDataGDFeedLink, or %NULL; free with gdata_gd_feed_link_free() + + Note that if a function returns NULL as a result of a precondition or assertion failure, this should not be listed in the documentation. The + precondition itself may be listed in the function documentation prose, but if it's the only reason for a function to return NULL, the "or %NULL" + clause should be omitted. + + - When adding API, make sure to add a "Since" clause: + + * Since: 0.2.0 + + - For object methods, the "self" parameter should be documented simply as "a #GObjectType": + + * @self: a #GDataQuery + + - For function parameters which can legitimately be set to NULL (or some other default value), list that as follows: + + * @updated_max: the new maximum update time, or %NULL + + - If numbers, such as -1, are mentioned in documentation as values to be passed around in code, they should be wrapped in a DocBook "code" tag + (e.g. "-1"), so that they appear similarly to NULL in the documentation. + + - The documentation explaining the purpose of a property, its limitations, interpretation, etc., should be given in the gtk-doc comment for the + GObject property itself, not in the documentation for its getter or setter. The documentation for the getter and setter should be stubs which + refer to the property's documentation. The getter and setter documentation should, however, still include full details about whether NULL values + are permissible for the function parameters, or are possible as the return value, for example. + +Adding public API +================= + + - Ensure it has proper guards against bad parameters: + + g_return_if_fail (GDATA_IS_QUERY (self)); + g_return_if_fail (foobar != NULL); + + - All public API must have a gtk-doc comment, and be added to the docs/reference/gdata-sections.txt file, to include it in the documentation. + The documentation comment must have a "Since" clause (see "Documentation comments" section). + + - All public API must be listed in gdata/gdata-*.symbols. + + - Non-trivial API should have a test case added in the relevant test suite file in gdata/tests. Note that the "general" test suite file cannot make + network requests in the course of running its test cases. + + - All GObject properties must have getter/setter functions. + + - All API which returns allocated memory must be tagged with G_GNUC_WARN_UNUSED_RESULT after its declaration, to safeguard against consumers of the + API forgetting to use (and consequently free) the memory. This is unlikely, but adding the macro costs little and acts as a reminder in the API + documentation to free the result. + + - All GObject *_get_type function declarations must be tagged with the G_GNUC_CONST macro, as well as any other applicable functions + (see the gcc documentation: http://gcc.gnu.org/onlinedocs/gcc/Function-Attributes.html#index-g_t_0040code_007bconst_007d-function-attribute-2207). + + - All properties which could be considered to use an enumerated value should almost definitely use a string instead. See the documentation section + on "Enumerable Properties" in the "GData Overview" section. Where appropriate, the values for these string properties should be made available + as #defines. + + - New services should be implemented in libgdata itself, not by applications which use libgdata. See the documentation section on "New Services" in + the "GData Overview" section. + + - New API must never be added in a stable micro release. API additions can only be made in a major or minor release; this is to prevent the LT version + of one minor version's micro releases exceeding the LT version of the next minor version as almost happened between versions 0.6.3 and 0.7.0. + See http://www.gnu.org/software/libtool/manual/html_node/Libtool-versioning.html for information about libtool's versioning system. See also the + “Versioning” section below. + + - Any async function which uses non-async-scope callbacks as well as the async ready callback should provide GDestroyNotify callbacks for destroying + the user data for those callbacks. See https://bugzilla.gnome.org/show_bug.cgi?id=649728 for details. + + - Any new class’ class structure (e.g. GDataServiceClass) must have reserved slots to allow future API additions of virtual functions without + breaking ABI. + +Choosing function names +======================= + +In general, use common sense. However, there are some specific cases where a standard is enforced: + + - For boolean getters (e.g. for FooBar:is-baz) use foo_bar_is_baz, rather than foo_bar_get_is_baz. Note that the property name should be "is-baz", + rather than just "baz". + + - For boolean setters use foo_bar_set_is_baz, rather than foo_bar_set_baz. + + - In general, try to keep API named similarly to the actual GData API constructs. In certain cases, however, it might make more sense to rename pieces + of API to be less cryptic (e.g. "timezone" instead of "ctz"). + +Deprecating public API +====================== + +As libgdata moves towards API stability, old API should be deprecated rather than broken or removed entirely. The following should be ensured when +deprecating API: + + - G_GNUC_DEPRECATED_FOR is added to the API in the public header file. + + - A “Deprecated:” line is added to the gtk-doc comment for the API. This should mention what API replaces it, give a brief explanation of why the + API has been deprecated, and finish with “(Since: [version].)” to list the version the API was deprecated. + + - “#ifndef LIBGDATA_DISABLE_DEPRECATED” should be wrapped around the API in the public header file. + + - All references to the API/uses of the API in libgdata code (including demos and the test suite) should be ported to use the replacement API instead. + If this isn't possible, the deprecated function should be split into a static function which contains all the code, and the public symbol should + become a simple wrapper of this static function. This allows the static function to be used inside libgdata without causing deprecation warnings. + + - Don't remove deprecated symbols from gdata-*.symbols. + + - Don't forget to also deprecate related symbols, such as the getter/setter for a property (or vice-versa). + +Commit messages +=============== + +libgdata does not use a ChangeLog; it is auto-generated from the git log when packaging a release. Commit messages should follow the GNOME commit +message guidelines (https://wiki.gnome.org/Git/CommitMessages), with the exception that when a commit closes a bug, the short explanation of the commit +should simply be the bug's title, as copied from Bugzilla (e.g. "Bug 579885 – Add code examples to documentation"). The long explanation should then +be used to give details of the changes. If the bug's title is not relevant, it should be changed before committing the changes. + +Unless the short explanation of a commit is a bug title, it should always be prefixed by a tag to describe the part of the library it touches, using +the following format "tag: Short explanation". The following tags are valid: + + - core: for the core code in the gdata directory, such as GDataEntry. + + - atom: for the Atom-namespaced code in the gdata/atom directory. + + - gcontact: for the gContact-namespaced code in the gdata/gcontact directory. + + - gd: for the GData-namespaced code in the gdata/gd directory. + + - media: for the Media RSS-namespaced code in the gdata/media directory. + + - build: for build changes and releases. + + - docs: for documentation changes which are not specific to a service, such as updates to the docs directory, NEWS, README, this file, etc. + + - tests: for changes to the test code in gdata/tests which are not specific to a service or namespace. + + - demos: for changes to the demo applications in the demos directory. + + - introspection: for introspection annotations and build changes. + + - calendar: for the Google Calendar code in gdata/services/calendar. + + - contacts: for the Google Contacts code in gdata/services/contacts. + + - documents: for the Google Documents code in gdata/services/documents. + + - picasaweb: for the PicasaWeb code in gdata/services/picasaweb. + + - youtube: for the YouTube code in gdata/services/youtube. + +The only commits which should not have a tag are translation commits, touching only the po directory. + +Versioning +========== + +Starting with version 0.9.0, libgdata has adopted an even–odd/stable–unstable versioning policy, where odd minor version numbers are unstable releases, +released periodically (with increasing micro version numbers) and leading to a stable release with the next even minor version number. API breaks of +new API are allowed in micro releases with an odd minor version number, but not in micro releases with an even minor version number. + +ABI and API backwards compatibility must be preserved unless the major version number is changed. libgdata is now ABI-stable. + +It is encouraged to make a new micro release of an odd minor series after each large API addition or break. diff --git a/NEWS b/NEWS new file mode 100644 index 0000000..a903924 --- /dev/null +++ b/NEWS @@ -0,0 +1,1684 @@ +Overview of changes from libgdata 0.17.12 to libgdata 0.17.13 +============================================================= + +* Default to not installing installed-tests (see !24) + +* Default to not building documentation (see !23) (thanks Debarshi Ray) + +* Bugs fixed: + - !23 build: Disable the gtk-doc documentation by default + - !24 Various minor fixes to meson_options.txt + - !25 all: Fix various typos and incorrect terminology + - !26 core: Add g_autoptr() support for GDataUploadStream + +* Translation updates: + - Chinese (China) + - English (United Kingdom) + - Latvian + - Ukrainian + + +Overview of changes from libgdata 0.17.11 to libgdata 0.17.12 +============================================================= + +* Make OAuth 1 support optional and disabled by default; this makes the `oauth` + dependency optional on `-Doauth1=enabled` (#1) + +* Bugs fixed: + - #1 Consider loosening the liboauth dependency + - #23 Authentication errors with Google Drive + - #36 Clarify license in meson.build + +* Translation updates: + - Basque + - Catalan + - Chinese (Taiwan) + - Croatian + - Czech + - Danish + - Dutch + - Finnish + - French + - Friulian + - Galician + - German + - Hungarian + - Indonesian + - Italian + - Japanese + - Korean + - Latvian + - Lithuanian + - Malay + - Polish + - Portuguese (Brazil) + - Romanian + - Serbian + - Slovenian + - Spanish + - Swedish + - Turkish + + +Overview of changes from libgdata 0.17.10 to libgdata 0.17.11 +============================================================= + +* Various fixes to the Meson port, including a soversion fix (#30, #32, #35, !9, !10) + +* Add support for user-specified properties of documents in Drive (!7) + +* Bugs fixed: + - #30 meson: debug messages of libgdata don't come from correct log domain - "libgdata" + - #31 gdata_entry_get_id should not free current value if not changed + - #32 Build failure on Continuous + - #33 en_GBism in a string + - #35 Installed tests fails with an assert in gdata_oauth2_authorizer_request_authorization + - !7 Drive v2 Properties API + - !9 Meson fixes + - !10 meson minor fixes + - !13 docs: Drop use of `` to delimit plurals + - !16 Minor revision of italian translation (after >2ys) + +* Translation updates: + - Basque + - Czech + - English (United Kingdom) + - German + - Indonesian + - Italian + - Lithuanian + - Polish + - Portuguese (Brazil) + - Romanian + - Spanish + - Swedish + + +Overview of changes from libgdata 0.17.9 to libgdata 0.17.10 +============================================================ + +* Port to Meson and drop autotools support (#27) + +* Migrate from intltool to gettext (bug #787252) + +* Bugs fixed: + - #26 Support deleting shared Google Drive files + - #27 Port to Meson + - !1 Remove use of foreach with wrong function prototype and use g_list_free_full + - !3 core: Move the header guards before including other headers + - !4 tasks: Turn 'position' and 'parent' into writable properties + - Bug 787252 — [Patch] Migrate from intltool to gettext + +* Translation updates: + - Catalan + - Chinese (Taiwan) + - Croatian + - Danish + - Dutch + - English (United Kingdom) + - Esperanto + - French + - Indonesian + - Nepali + - Romanian + - Turkish + + +Overview of changes from libgdata 0.17.8 to libgdata 0.17.9 +=========================================================== + +Major changes: + • Support reporting quotas for Drive usage (thanks to Michael Terry) + • Bump GLib dependency to 2.44 for g_autoptr() support + • Add g_autoptr() support for some core classes + • Port from GSimpleAsyncResult to GTask + • More porting to the Google Drive v2 API + (ongoing thanks to Debarshi Ray for working on and maintaining this) + +API changes: + • Add GDataDocumentsMetadata + • Add gdata_documents_service_get_metadata(), + gdata_documents_service_get_metadata_async(), + gdata_documents_service_get_metadata_finish() + • Initial g_autoptr() support for core classes + +Bugs fixed: + • Bug 783046 — Invalid URIs are generated when q and q_internal properties are set + • GitHub PR #1 — added initial .travis.yml + • Bug 785885 — Expose information about quota usage + • Bug 684920 — Port to Google Drive API v2 + + +Overview of changes from libgdata 0.17.7 to libgdata 0.17.8 +=========================================================== + +Major changes: + • Bump GLib dependency to 2.38.0 for G_TEST_DIST + • Bump libsoup dependency for tests to 2.55.90; the dependency if building + libgdata without tests is still 2.42.0 + • Fix use of deprecated GTK+ API in the demos + +Bugs fixed: + • Bug 779641 — test_query_properties broken on i686 + • Bug 780067 — Unable to sync Google Contacts + • Bug 780081 — libgdata 0.17.7 fails streams tests (unable to set up SSL cert) + +Updated translations: + • be (Yuras Shumovich) + • da (Alan Mortensen) + • el (Tom Tryfonidis) + • fi (Jiri Grönroos) + • gl (Fran Dieguez) + • oc (Cédric Valmary) + • ru (Yuri Myasoedov) + + +Overview of changes from libgdata 0.17.6 to libgdata 0.17.7 +=========================================================== + +Major changes: + • Fix licensing in OAuth2 files (they were mistakenly declared as GPLv3+; they’re actually LGPLv2.1+) + • More Google Drive fixes and tests + • Documentation improvements (including bumping the gtk-doc dependency to 1.25) + • Google Calendar parsing fixes + • Pagination fixes for more modern APIs (Calendar, Documents, Tasks, YouTube) + • Pagination support in demo programs + • Add a demo program for Google Tasks + • Fix Google Calendar query parameters for v3 of the API + • Disable PicasaWeb tests as PicasaWeb server is now mostly read-only + • Deprecate Freebase service as Freebase server is now shutdown + +API changes: + • Add GDataDocumentsEntry:file-size + • Add gdata_parsable_get_content_type() + • Add GDataFeed:next-page-token + • Deprecate GDataCalendarQuery:recurrence-expansion-start + • Deprecate GDataCalendarQuery:recurrence-expansion-end + • Deprecate GDataCalendarQuery:sort-order + • Deprecate everything to do with GDataFreebase* + +Bugs fixed: + • Bug 684920 — Port to Google Drive API v2 + • Bug 772756 — Take advantage of Unicode + • Bug 773057 — Provide document file size + • Bug 774179 — Fails to build VAPI file with GOA enabled + • Bug 777980 — Add a public wrapper for GDataParsable:get_content_type + • Bug 775813 — GTasks pagination doesn't work + +Updated translations: + • cs (Marek Černocký) + • da (Ask Hjorth Larsen) + • de (Mario Blättermann) + • es (Daniel Mustieles) + • eu (Inaki Larranaga Murgoitio) + • fi (Jiri Grönroos) + • fr (Claude Paroz) + • fur (Fabio Tomat) + • hu (Gábor Kelemen) + • id (Kukuh Syafaat) + • it (Gianvito Cavasoli) + • ko (Changwoo Ryu) + • lt (Aurimas Černius) + • lv (Rūdolfs Mazurs) + • nb (Kjartan Maraas) + • pl (Piotr Drąg) + • pt (Tiago Santos) + • pt_BR (Rafael Fontenelle) + • sk (Dušan Kazik) + • sl (Matej Urbančič) + • sr (Марко М. Костић) + • sv (Anders Jonsson) + • zh_CN (Qizhi Zhou) + • zh_TW (Chao-Hsiung Liao) + + +Overview of changes from libgdata 0.17.5 to libgdata 0.17.6 +=========================================================== + +Major changes: + • Minor test case fixes + • Fix a download crash on zero-length files (thanks Ondrej Holy) + +Bugs fixed: + • Bug 768278 — release tarball 0.17.5 contains empty ChangeLog + • Bug 768363 — dev-libs/libgdata-0.17.5 fails tests (on the alpha architecture, possibly elsewhere) + • Bug 768282 — test-suite failure: ERROR: general - too few tests run (expected 98, got 2) + • Bug 769727 — Crashes on zero-length files + +Updated translations: + • en_GB (David King) + • he (Yosef Or Boczko) + • pl (Piotr Drąg) + • th (Akom Chotiphantawanon) + + +Overview of changes from libgdata 0.17.4 to libgdata 0.17.5 +=========================================================== + +Major changes: + • Google Drive documentation and test fixes + • Minor memory leak fixes + • Update autogen.sh to latest GNOME recommendations, fixing builddir ≠ srcdir + +Bugs fixed: + • Bug 684920 — Port to Google Drive API v2 + • Bug 759180 — Can't open PDF file shared in Google Drive + • Bug 767784 — picasaweb: Clarify how to handle authentication failures during upload + • Bug 767785 — Mention that GDataGoaAuthorizer uses OAuth 2.0 + +Updated translations: + • cs (Marek Černocký) + • da (Ask Hjorth Larsen) + • de (Mario Blättermann) + • el (Tom Tryfonidis) + • es (Daniel Mustieles) + • eu (Inaki Larranaga Murgoitio) + • fr (Alexandre Franke) + • fur (Fabio Tomat) + • gl (Fran Dieguez) + • id (Andika Triwidada) + • it (Milo Casagrande) + • ko (Changwoo Ryu) + • lt (Aurimas Černius) + • lv (Rūdolfs Mazurs) + • hu (Balázs Meskó) + • nb (Kjartan Maraas) + • oc (Cédric Valmary) + • pl (Piotr Drąg) + • pt (Sérgio Cardeira) + • pt_BR (Enrico Nicoletto, Rafael Fontenelle) + • ru (Stas Solovey) + • sk (Dušan Kazik) + • sl (Matej Urbančič) + • sr (Мирослав Николић) + • sv (Anders Jonsson) + • th (Akom Chotiphantawanon) + • vi (Trần Ngọc Quân) + • zh_CN (Jeff Bai) + • zh_TW (Chao-Hsiung Liao) + +Overview of changes from libgdata 0.17.3 to libgdata 0.17.4 +=========================================================== + +Major changes: + • Download stream data corruption fixes and fixes to content length + calculation + • Fix symbol exporting on OS X + • Fix copying and deleting documents in Google Drive + • Fix folder creation in Google Drive + • Fix metadata-only uploads in Google Drive + • Fix searching by title in Google Drive + +API changes: + • Remove a couple of incorrect GIR annotations + +Bugs fixed: + • Bug 755976 — Seeking with GDataDownloadStream can be broken if a range was + set in the HTTP request + • Bug 754821 — Compilation issues on Mac OS X + • Bug 758119 — make check fails in git master (3.19.x) + • Bug 684920 — Port to Google Drive API v2 + • Bug 758524 — Cannot search documents by title + +Updated translations: + • cs (Marek Černocký) + • da (Ask Hjorth Larsen) + • de (Wolfgang Stöggl) + • es (Daniel Mustieles) + • eu (Iñaki Larrañaga Murgoitio) + • hu (Balázs Meskó) + • lt (Aurimas Černius) + • lv (Rūdolfs Mazurs) + • pl (Piotr Drąg) + • pt (Pedro Albuquerque) + • pt_BR (Enrico Nicoletto) + • ru (Stas Solovey) + • sk (Dušan Kazik) + • sr (Марко Костић, Милош Поповић) + • tr (Muhammet Kara) + +Overview of changes from libgdata 0.17.2 to libgdata 0.17.3 +=========================================================== + +Major changes: + • More Google Drive improvements + • A few memory leak fixes and improvements in the unit tests + +API changes: + • Soft API break for gdata_service_insert_entry() when creating Google Drive + folders — you must now use gdata_documents_service_add_entry_to_folder() due + to changes on the server API + (see https://bugzilla.gnome.org/show_bug.cgi?id=684920) + • Remove two unused symbols from the export list; these were never intended + to be public API: gdata_freebase_result_error_get_type, + gdata_freebase_result_error_quark + +Bugs fixed: + • Bug 684920 — Port to Google Drive API v2 + • Bug 754821 — Compilation issues on Mac OS X + +Updated translations: + • cs (Marek Černocký) + • de (Paul Seyfert) + • el (Tom Tryfonidis) + • es (Daniel Mustieles) + • fr (Bruno Brouard) + • gl (Fran Dieguez) + • hu (Balázs Úr) + • id (Andika Triwidada) + • it (Claudio Arseni) + • ko (Changwoo Ryu) + • lt (Aurimas Černius) + • nb (Kjartan Maraas) + • pl (Piotr Drąg) + • pt (Pedro Albuquerque) + • sk (Dušan Kazik) + • sl (Matej Urbančič) + • sv (Anders Jonsson, Mattias Eriksson) + • th (Akom Chotiphantawanon) + • zh_TW (Chao-Hsiung Liao) + +Overview of changes from libgdata 0.17.1 to libgdata 0.17.2 +=========================================================== + +Major changes: + • More Google Drive API porting + • Port from v2 to v3 of the Calendar API + • Update and re-enable a lot of unit tests + (streams, youtube, freebase, calendar). + • Add calendar-cli demo + • Port to use installed-tests; this adds --enable-always-build-tests and + --enable-installed-tests configure options + • Port to autoconf-archive macros and add an implicit build-time dependency + on autoconf-archive + • Allow applications to store and restore the refresh token for a + GDataOAuth2Authorizer to avoid re-authenticating on each startup + • Bump libuhttpmock dependency to 0.5.0 + +API changes: + • Add gdata_calendar_service_insert_calendar_event(), + gdata_calendar_service_insert_calendar_event_async() + • Deprecate GDataCalendarCalendar:times-cleaned, + gdata_calendar_calendar_get_times_cleaned(), GDataCalendarCalendar:edited, + gdata_calendar_calendar_get_edited() + • Deprecate GDataCalendarFeed:timezone, gdata_calendar_feed_get_timezone(), + GDataCalendarFeed:times-cleaned, gdata_calendar_feed_get_times_cleaned() + • Add GDataAccessHandlerIface.get_rules as a virtual method backing + gdata_access_handler_get_rules() + • Add GDataCalendarAccessRule + • Add GDataDocumentsAccessRule + • Add gdata_oauth2_authorizer_dup_refresh_token(), + gdata_oauth2_authorizer_set_refresh_token() + • Add GDataBatchable.is_supported virtual function + +Bugs fixed: + • Bug 684920 — Port to Google Drive API v2 + • Bug 664353 — Upgrade to Calendar API version 3 + • Bug 750335 — Silence a bunch of warnings + • Bug 750480 — Fix -Werror build for clang + • Bug 750395 — Fix the GDataAccessRule example + • Bug 750746 — Cold start OAuth2 authorization + • Bug 751782 — Enable Drive authorization domains if a GOA account has "files" enabled + • Bug 750914 — Build fails because -Werror=unused-function + +Updated translations: + • oc (Cédric Valmary (Tot en òc)) + • pl (Piotr Drąg) + • pt (Pedro Albuquerque) + • th (Akom Chotiphantawanon) + +Overview of changes from libgdata 0.17.0 to libgdata 0.17.1 +=========================================================== + +Major changes: + • Correctly increment LT version; this release should always be used instead + of 0.17.0 + +Overview of changes from libgdata 0.16.0 to libgdata 0.17.0 +=========================================================== + +Major changes: + • Port from v2 to v3 of the YouTube API — your client’s developer key may stop + working due to never being conigured for v3; refresh it here: + https://developers.google.com/youtube/registering_an_application + • Port from the Google Docs API to the Google Drive API (v2) — the same + libgdata APIs should continue to work unchanged + • Both the YouTube and Drive API ports are not thoroughly tested, and a number + of unit tests have been disabled temporarily; code quality will be ramped up + again in subsequent releases + • Add support for OAuth 2.0 authorisation + • Commit to API and ABI stability + • Add --disable-tests configure flag to skip building tests + • Various improvements to the unit tests + • Fix pagination handling in Google Docs + • Add demo applications for Google Docs and YouTube + • Various Freebase fixes, including a huge number of new tests and + authentication fixes + • Various JSON parser fixes + • Note that the Calendar v2 API has now been withdrawn; there has not been + enough time to port libgdata to version 3 (ongoing: + https://bugzilla.gnome.org/show_bug.cgi?id=664353), but clients can (and + should, regardless) use the CalDAV API provided by Google Calendar + +API changes: + • Add GDATA_OAUTH2_REDIRECT_URI_OOB + • Add GDATA_OAUTH2_REDIRECT_URI_OOB_AUTO + • Add GDataOAuth2Authorizer + • Add API padding and commit to API stability + • Add GDataServiceClass.parse_feed + • Add gdata_freebase_search_result_item_get_type(), + GDATA_TYPE_FREEBASE_SEARCH_RESULT_ITEM + • Add GDATA_CATEGORY_SCHEMA_LABELS_SHARED + • Add GDATA_CATEGORY_SCHEMA_LABELS_VIEWED + • Add GDataYouTubeFeed + • Deprecate GDataYouTubeQuery:format, gdata_youtube_query_get_format(), + gdata_youtube_query_set_format() + • Deprecate GDataYouTubeQuery:has-location + • Deprecate GDataYouTubeQuery:language, gdata_youtube_query_get_language(), + gdata_youtube_query_set_language() + • Deprecate GDataYouTubeQuery:sort-order, gdata_youtube_query_get_sort_order(), + gdata_youtube_query_set_sort_order() + • Deprecate GDataYouTubeQuery:uploader, gdata_youtube_query_get_uploader(), + gdata_youtube_query_set_uploader() + • Deprecate GDataYouTubeSortOrder + • Deprecate GDataYouTubeUploader + • Deprecate GDataYouTubeContent + • Deprecate GDataYouTubeFormat + • Deprecate GDataYouTubeVideo:video-id, gdata_youtube_video_get_video_id() + • Deprecate gdata_youtube_video_look_up_content() + (use gdata_youtube_video_get_player_uri() instead) + • Deprecate GDATA_YOUTUBE_RATING_TYPE_SIMPLE + • Deprecate GDataYouTubeCredit, GDATA_YOUTUBE_CREDIT_ENTITY_PARTNER + • Deprecate GDataYouTubeVideo:credit, gdata_youtube_video_get_credit() + • Deprecate GDataYouTubeVideo:is-draft, gdata_youtube_video_is_draft(), + gdata_youtube_video_set_is_draft() + • Deprecate GDATA_YOUTUBE_*_FEED except GDATA_YOUTUBE_MOST_POPULAR_FEED (all + others have been deprecated online and will transparently return the + most popular videos from the past 24 hours) + • GDataYouTubeQuery:restriction no longer accepts IP addresses + • All GDataCommentable functionality on GDataYouTubeVideo is disabled + at runtime until the v3 YouTube API for comments is finished online + • Not all properties of a GDataYouTubeVideo may be retrieved when doing + searches, retrieving related videos, or listing standard feeds — to + guarantee getting all properties, use gdata_service_query_single_entry() for + the video in question; common properties such as title, description, player + URI and thumbnails will always be retrieved + • Deprecate GDataDocumentsEntry:edited + +Bugs fixed: + • Bug 646285 — Add OAuth 2 support + • Bug 657539 — Add support for Google Tasks + • Bug 739395 — Add an option to build without uhttpmock + • Bug 737799 — Error while updating google address book + • Bug 739956 — libgdata-0.16.1: tests fail + • Bug 741345 — Paging does not work + • Bug 737539 — Freebase: topic results are shallower than expected + • Bug 737936 — Freebase: Add GType for GDataFreebaseSearchResultItem + • Bug 737540 — Freebase: async topic queries use the wrong result gtype + • Bug 737541 — freebase: search query buglets + • Bug 742472 — Freebase: Pass API key on all service requests + • Bug 742473 — Small freebase oauth2 access bugs + • Bug 687597 — Update to YouTube API v3 + • Bug 684920 — Port to Google Drive API v2 + +Updated translations: + • bg (Alexander Shopov) + • bs (Samir Ribić) + • da (Aputsiaq Niels Janussen) + • de (Bernd Homuth) + • et (Mattias Põldaru) + • pa (A S Alam) + • sk (Dušan Kazik) + • sr (Мирослав Николић) + • sv (Mattias Eriksson) + • tr (Muhammet Kara) + • zh_CN (Iris Gou) + +Overview of changes from libgdata 0.15.2 to libgdata 0.16.0 +=========================================================== + +Major changes: + • Update date parsing to handle recent changes in Google’s servers + • Support ACLs with keys (e.g. for link-only sharing of documents) + • Add gzip encoding support for network packet compression + • Support for libsoup ≥ 2.47.3 (but the dependency has not been bumped) + • Basic test suite for the Google Tasks service + • Fix mutex warnings with new GLib versions + +API changes: + • Add GDataAccessRule:key + • Add gdata_access_rule_get_key() + • Add GDATA_TASKS_STATUS_NEEDS_ACTION + • Add GDATA_TASKS_STATUS_COMPLETED + • Deprecate the ‘q’ parameter of gdata_tasks_query_new() + • Add GDATA_SERVICE_ERROR_API_QUOTA_EXCEEDED + +Bugs fixed: + • Bug 732809 — evolution-3.12.3: cannot edit google contact due to invalid + format of timestamp + • Bug 734863 — Google contacts without email address block search/autocomplete + • Bug 690628 — element Not Handled by libgdata + • Bug 703192 — The global log handler interferes with other application + • Bug 666623 — Add gzip encoding support + +Updated translations: + • as (Nilamdyuti Goswami) + • ca (Gil Forcada) + • cs (Marek Černocký) + • fr (Bruno Brouard) + • gu (Sweta Kothari) + • he (Yosef Or Boczko) + • hu (Balázs Úr) + • id (Andika Triwidada) + • it (Claudio Arseni) + • ko (Changwoo Ryu) + • lv (Rūdolfs Mazurs) + • nb (Kjartan Maraas) + • ru (Yuri Myasoedov) + • sl (Matej Urbančič) + • zh_HK (Chao-Hsiung Liao) + • zh_TW (Chao-Hsiung Liao) + +Overview of changes from libgdata 0.15.1 to libgdata 0.15.2 +=========================================================== + +Major changes: + • Support PicasaWeb in the GOA authoriser (thanks to Saurav Agarwalla) + • Fix a data corruption bug in the downloads/uploads code + +Bugs fixed: + • Bug 731269 — Wrong scope information in authorization domain + • Bug 731949 — Memory leak from gdata_parser_int64_to_iso8601() + • Bug 731946 — Removing a task result in error, but succeeds + • Bug 732890 — Refresh authoriser on receiving SOUP_STATUS_NOT_FOUND + +Updated translations: + • el (Tom Tryfonidis) + • en_GB (Philip Withnall) + • es (Daniel Mustieles) + • eu (Iñaki Larrañaga Murgoitio) + • gl (Fran Dieguez) + • lt (Aurimas Černius) + • pt_BR (Enrico Nicoletto) + • sv (Anders Jonsson) + +Overview of changes from libgdata 0.15.0 to libgdata 0.15.1 +=========================================================== + +Major changes: + • Add a Freebase service and demo (thanks to Carlos Garnacho) + • Various minor fixes to make libgdata compile without Coverity errors + +API changes: + • Add GDATA_LINK_PARENT + • Add GDataFreebase* + +Bugs fixed: + • Bug 707477 — Fill in GDataCategory::label for GDataDocumentsDocument + instances + • Bug 725827 — Define GDATA_LINK_PARENT + • Bug 726486 — Add support for the Freebase service + +Updated translations: + • ca (Gil Forcada) + • da (Aputsiaq Niels Janussen) + • de (Benjamin Steinwender) + • eu (Iñaki Larrañaga Murgoitio) + • fr (Bruno Brouard) + • he (Yosef Or Boczko) + • ko (Changwoo Ryu) + • lv (Rūdolfs Mazurs) + • nb (Kjartan Maraas) + • pl (Piotr Drąg, Aviary.pl) + • pt (Tiago S.) + • ru (Yuri Myasoedov) + • zh_HK (Chao-Hsiung Liao) + • zh_TW (Chao-Hsiung Liao) + +Overview of changes from libgdata 0.14.0 to libgdata 0.15.0 +=========================================================== + +Major changes: + • Add JSON support and a Google Tasks service (thanks to Pēteris Krišjānis) + - This adds a dependency on json-glib ≥ 0.15 and breaks ABI (but not API) + • Add support for GProxyResolver proxies (thanks to Matthew Barnes) + • Fix build with recent gnome-common versions + • Fix build and installed header files for C++ + • Remove deprecated function calls + • Fix compilation with -fstrict-aliasing + • Port local tests to use libuhttpmock (which is a new dependency) + +API changes: + • Add gdata_parsable_new_from_json() + • Add gdata_parsable_get_json() + • Add GDataParsable->get_content_type + • Add GDataService:proxy-resolver, gdata_service_get_proxy_resolver(), + gdata_service_set_proxy_resolver() + • Add GDataClientLoginAuthorizer:proxy-resolver, + gdata_client_login_authorizer_get_proxy_resolver(), + gdata_client_login_authorizer_set_proxy_resolver() + • Add GDataOAuth1Authorizer:proxy-resolver, + gdata_oauth1_authorizer_get_proxy_resolver(), + gdata_oauth1_authorizer_set_proxy_resolver() + • Add Google Tasks service: GDataTasksService, GDataTasksQuery, + GDataTasksTasklist, GDataTasksTask + +Bugs fixed: + • Bug 712565 — Fix compilation's warnings + • Bug 719647 — gdata-goa-authorizer.h broken for C++ + +Updated translations: + • as (Nilamdyuti Goswami) + • be (Ihar Hrachyshka) + • ca (Gil Forcada) + • cs (Marek Černocký) + • da (Aputsiaq Niels Janussen) + • de (Christian Kirbach) + • el (Dimitris Spingos, Efstathios Iosifidis) + • es (Daniel Mustieles) + • et (Mattias Põldaru) + • fi (Jiri Grönroos) + • fr (Bruno Brouard) + • gl (Fran Dieguez) + • hu (Gabor Kelemen) + • id (Andika Triwidada) + • it (Claudio Arseni, Milo Casagrande) + • ja (Jiro Matsuzawa) + • ko (Changwoo Ryu) + • lt (Aurimas Černius) + • lv (Rūdolfs Mazurs) + • nb (Kjartan Maraas) + • pa (A S Alam) + • pl (Piotr Drąg) + • pt (António Lima) + • pt_BR (Enrico Nicoletto) + • ru (Yuri Myasoedov) + • sk (Ján Kyselica) + • sl (Matej Urbančič) + • sr (Мирослав Николић) + • th (Akom Chotiphantawanon) + • zh_CN (甘露) + • zh_HK (Chao-Hsiung Liao) + • zh_TW (Chao-Hsiung Liao) + +Overview of changes from libgdata 0.13.4 to libgdata 0.14.0 +=========================================================== + +Updated translations: + • ca (Gil Forcada) + • cs (Marek Černocký) + • de (Christian Kirbach) + • el (Dimitris Spingos) + • es (Daniel Mustieles) + • fr (Alexandre Franke) + • he (Yaron Shahrabani) + • it (Claudio Arseni) + • lt (Aurimas Černius) + • nb (Kjartan Maraas) + • nl (Reinout van Schouwen) + • pt_BR (Rafael Ferreira) + • sl (Matej Urbančič) + • th (Akom Chotiphantawanon) + • zh_HK (Chao-Hsiung Liao) + • zh_TW (Chao-Hsiung Liao) + +Overview of changes from libgdata 0.13.3 to libgdata 0.13.4 +=========================================================== + +Major changes: + • Fixes to request cancellation and progress notification + • Fix tests to be more reliable in the face of distributed system + non-synchronisation + • Add support for running tests offline using stored HTTP request traces + +API changes: + • Added GDATA_YOUTUBE_SERVICE_ERROR_CHANNEL_REQUIRED + +Bugs fixed: + • Bug 627895 — Pretty-print XML in test output + • Bug 703192 — The global log handler interferes with other application + • Bug 705266 — make check fails + +Updated translations: + • eu (Iñaki Larrañaga Murgoitio) + • gl (Fran Diéguez) + • pl (Piotr Drąg) + • pt (António Lima) + • tg (Victor Ibragimov) + +Overview of changes from libgdata 0.13.2 to libgdata 0.13.3 +=========================================================== + +Major changes: + • Fix dependencies in pkg-config file + • Add OAuth 2.0 support to the GOA authoriser + • Fix some licencing inconsistencies (libgdata is entirely licenced under + LGPLv2.1+) + • Add support for PDF documents in Google Documents + • Add in-tree Vala bindings (they were previously in Vala’s tree) + +Bugs fixed: + • Bug 685464 — [PATCH] Package config file depends on too much + • Bug 685289 — GOA now uses OAuth 2.0 for Calendar, Contacts and Documents + • Bug 690281 — do not add unused gnome dependencies to libgdata.pc when + configured with --disable-gnome + • Bug 690225 — [patch] Make GOA optional + • Bug 690656 — unhandled XML warnings from totem youtube plugin + • Bug 693855 — Port introspection fixes from Vala bindings + • Bug 693958 — Add PDF support + • Bug 693865 — Add Vala bindings + • Bug 694415 — Don't require introspection.m4 to be installed system-wide + +Updated translations: + • et (Mattias Põldaru) + • sk (Ján Kyselica) + • ug (Gheyret Kenji) + +Overview of changes from libgdata 0.13.1 to libgdata 0.13.2 +=========================================================== + +Major changes: + • Expand the documentation and add more examples + • Explicitly check for libxml2 in configure + • Port code coverage support to use gnome-common + +Bugs fixed: + • Bug 683209 — Port to gnome-common code coverage macros + +Updated translations: + • as (Nilamdyuti Goswami) + • bg (Alexander Shopov) + • ca (Joan Duran) + • cs (Marek Černocký) + • da (Ask H. Larsen) + • de (Mario Blättermann) + • el (Tom Tryfonidis) + • es (Daniel Mustieles) + • fr (Alexandre Franke) + • gl (Fran Dieguez, Leandro Regueiro) + • hi (Rajesh Ranjan) + • hu (Gabor Kelemen) + • it (Milo Casagrande) + • ko (Changwoo Ryu) + • lt (Aurimas Černius) + • lv (Rūdolfs Mazurs) + • ml (Anish A) + • pa (A S Alam) + • pl (Piotr Drąg) + • pt (António Lima) + • pt_BR (Rafael Ferreira) + • ru (Yuri Kozlov) + • te (Krishnababu Krothapalli) + • th (Akom Chotiphantawanon) + • tr (Muhammet Kara) + • vi (Nguyễn Thái Ngọc Duy) + • zh_HK (Chao-Hsiung Liao) + • zh_TW (Chao-Hsiung Liao) + +Overview of changes from libgdata 0.13.0 to libgdata 0.13.1 +=========================================================== + +Major changes: + • Add support for Google Drawings + • Fix some of the test suite + • Add support for copying Google documents + • Moved GOA authoriser from EDS/GNOME Documents into libgdata (adding a GOA dependency) + • Remove libgnome-keyring dependency in favour of libgcr-base + +API changes: + • Added GDataDocumentsDrawing + • Added gdata_documents_service_copy_document(), gdata_documents_service_copy_document_async(), gdata_documents_service_copy_document_finish() + • Added GDataGoaAuthorizer + • Added gdata_documents_document_get_download_uri() + +Bugs fixed: + • Bug 633548 — Add Google Drawings support + • Bug 679072 — Tests for all Google services fail + • Bug 607270 — Support copying documents + • Bug 656976 — Merge eds and GNOME Documents GOA authorisers + • Bug 679867 — Use libgcr-base instead of libgnome-keyring for secure memory + • Bug 656970 — Add thumbnail support + +Updated translations: + • be (Ihar Hrachyshka) + • bg (Alexander Shopov) + • el (Γιώργος Στεφανάκης, Tom Tryfonidis) + • en_GB (Philip Withnall) + • es (Daniel Mustieles) + • gl (Fran Dieguez) + • he (Yaron Shahrabani) + • id (Andika Triwidada) + • nb (Kjartan Maraas) + • nl (Willem Heppe, Wouter Bolsterlee) + • sl (Matej Urbančič) + • sr (Мирослав Николић) + • te (Sasi Bhushan Boddepalli) + • zh_HK (Chao-Hsiung Liao) + • zh_TW (Chao-Hsiung Liao) + +Overview of changes from libgdata 0.12.0 to libgdata 0.13.0 +=========================================================== + +Major changes: + • Bump GLib dependency to 2.31.0 in order to use its new threading primitives + • Add basic support for resumable uploads to GDataUploadStream (bug #607272) + • Update support for Google Documents to v3 of the API + • Add support for arbitrary file uploads to Google Documents (using GDataDocumentsDocuemtn), + and document conversion on upload (using GDataDocumentsUploadQuery) + +API changes: + • Added gdata_upload_stream_new_resumable() + • Added GDataUploadStream:content-length, gdata_upload_stream_get_content_length() + • Added gdata_documents_service_upload_document_resumable() + • Added gdata_documents_service_update_document_resumable() + • Added GDataDocumentsUploadQuery + • Made GDataDocumentsDocument instantiable (this isn’t a real API break, though) + • Added GDATA_DOCUMENTS_TEXT_JPEG + • GDataDocumentsEntry:quota-used, gdata_documents_entry_get_quota_used() + +Bugs fixed: + • Bug 593537 — Upgrade Documents service to version 3.0 + • Bug 607616 — Permit the uploading of documents of any type + • Bug 656971 — Deprecate GDataDocumentsDocument subclasses + • Bug 588714 — handling in GDataDocumentsEntry + +Updated translations: + • ca (Jordi Serratosa) + • en_GB (Philip Withnall) + • es (Daniel Mustieles) + • he (Yaron Shahrabani) + • sv (Daniel Nylander) + +Overview of changes from libgdata 0.11.0 to libgdata 0.11.1 +=========================================================== + +Major changes: +* Bump libsoup dependency to 2.37.91 in order to ensure it checks the validity of TLS certificates before accepting them + (Note that this was implemented in 0.10.2 using a --with-ca-certs configure argument. This argument isn't necessary with 0.11.1, since the newer + libsoup version which 0.11.1 requires already knows where the system CA cert file is.) + +Bugs fixed: +* Bug 667577 — fix introspection for srcdir != builddir builds +* Bug 668365 — libgdata 0.10.x link error because of exported symbols that don't exist +* Bug 671535 — Security issue in libgdata + +Updated translations: +* be (Kasia Bondarava) +* te (Praveen Illa) +* uk (Korostil Daniel) + +Overview of changes from libgdata 0.10.0 to libgdata 0.11.0 +=========================================================== + +Major changes: +* Added version checking macros (thanks to Holger Berndt) +* Ported scrapbook demo to GtkGrid; this sets our GTK+ dependency to 2.91.2 +* Added a LIBGDATA_DISABLE_DEPRECATED macro for disabling deprecated API in headers +* Sensitive details (passwords, auth. tokens, etc.) are now redacted from logs unless LIBGDATA_DEBUG=4 is set (which is a new logging level) +* Sensitive details are also now stored in non-pageable memory as much as possible to reduce the risk of them being leaked + NOTE: This has not been formally certified or reviewed, and is a precaution rather than a guarantee of security + This adds a dependency on libgnome-keyring when libgdata is configured with --enable-gnome (and is disabled otherwise) +* Use GHmac instead of liboauth's HMAC; this bumps our GLib dependency to 2.30.0 +* Use the new GLib threading API iff compiled with GLib ≥ 2.31.0 (this doesn't bump the hard dependency, though) + +API changes: +* Added GDATA_MAJOR_VERSION, GDATA_MINOR_VERSION, GDATA_MICRO_VERSION, GDATA_CHECK_VERSION +* Added GDataDocumentsEntry:resource-id, gdata_documents_entry_get_resource_id() +* Deprecated GDataDocumentsEntry:document-id, gdata_documents_entry_get_document_id() +* Added GDataYouTubeQuery:license, gdata_youtube_query_get_license(), gdata_youtube_query_set_license() +* Deprecated GDATA_DOCUMENTS_PRESENTATION_SWF +* Added GDATA_CATEGORY_SCHEMA_LABELS, GDATA_CATEGORY_SCHEMA_LABELS_STARRED +* Added GDataContactsContact:file-as, gdata_contacts_contact_get_file_as(), gdata_contacts_contact_set_file_as() + +Bugs fixed: +* Bug 659016 — @rel not mandatory in website references +* Bug 660038 — Add preprocessor macro for version checking +* Bug 656972 — Tidy up document IDs +* Bug 658865 — Add support for the license query parameter +* Bug 660174 — Deprecate SWF export of presentations +* Bug 659148 — Add search-term query example to documentation +* Bug 656973 — Add an example of starring a document +* Bug 656783 — Review security of memory storing authentication details +* Bug 662290 — Can't update contact that has no full name + +Updated translations: +* as (Nilamdyuti Goswami) +* da (Aputsiaq Niels Janussen) +* eu (Iñaki Larrañaga Murgoitio) +* fi (Tommi Vainikainen) +* hu (Gabor Kelemen) +* it (Claudio Arseni) +* ja (Jiro Matsuzawa) +* kn (Shankar Prasad) +* ko (Changwoo Ryu) +* lt (Žygimantas Beručka) +* lv (Rūdofls Mazurs) +* or (Manoj Kumar Giri) +* pa (A S Alam) +* pl (Piotr Drąg) +* pt (António Lima) +* pt_BR (Flamarion Jorge) +* sr (Мирослав Николић) +* ta (I Felix) +* vi (Nguyễn Thái Ngọc Duy) +* zh_CN (YunQiang Su) +* zh_HK (Chao-Hsiung Liao) +* zh_TW (Chao-Hsiung Liao) + +Overview of changes from libgdata 0.9.1 to libgdata 0.10.0 +========================================================== + +Major changes: +* Added support for comments to YouTube and PicasaWeb (thanks to Richard Schwarting) +* Added a “scrapbook” demo application (thanks to Joe Cortes) +* Added lots of cancellation tests + +API changes: +* Added GDataCommentable +* Added GDataComment, GDataYouTubeComment, GDataPicasaWebComment +* Added gdata_entry_remove_link() +* Added gdata_youtube_video_get_media_rating(), GDATA_YOUTUBE_RATING_TYPE_SIMPLE, GDATA_YOUTUBE_RATING_TYPE_MPAA, GDATA_YOUTUBE_RATING_TYPE_V_CHIP + +Bugs fixed: +* Bug 618587 — Implement GDataGDFeedLink +* Bug 598752 — Support comments +* Bug 647882 — Support rating schemes +* Bug 628069 — Add some demo applications +* Bug 656529 — undefined references trying to compile/build libgdata +* Bug 633364 — Add cancellation tests + +Updated translations: +* bg (Alexander Shopov) +* ca, ca@valencia (Gil Forcada) +* cs (Andre Klapper) +* de (Mario Blättermann) +* eo (Kristjan SCHMIDT) +* es (Jorge González) +* fr (Bruno Brouard) +* gl (Fran Diéguez) +* he (Yaron Shahrabani) +* id (Andika Triwidada) +* lt (Aurimas Černius) +* lv (Rūdofls Mazurs) +* nb (Kjartan Maraas) +* ru (Yuri Kozlov) +* sl (Matej Urbančič) +* sv (Daniel Nylander) +* th (Akom Chotiphantawanon) +* ug (Gheyret Kenji) + +Overview of changes from libgdata 0.9.0 to libgdata 0.9.1 +========================================================= + +Major changes: +* Added GDestroyNotify parameters to query-type methods so that they're properly introspectable, breaking API (see below) +* Fixed seeking in GDataDownloadStream +* Made the tests individually idempotent, so the test suites should be less of a tangled mess now +* Fixed uploading to non-default PicasaWeb albums +* Fixed GDataAuthorizer to re-process requests after refreshing, involving a slight change to the semantics of GDataAuthorizer (see bgo#653535) +* Ensure that Google Contacts uses HTTPS for everything +* Fixed the IDs used for Google Documents so that deleting documents now consistently works, even when they're in folders + +API changes: +* Changed the following methods, adding GDestroyNotify parameters for their progress user data parameters: + - gdata_access_handler_get_rules_async() + - gdata_service_query_async() + - gdata_calendar_service_query_all_calendars_async() + - gdata_calendar_service_query_own_calendars_async() + - gdata_calendar_service_query_events_async() + - gdata_contacts_service_query_contacts_async() + - gdata_contacts_service_query_groups_async() + - gdata_documents_service_query_documents_async() + - gdata_picasaweb_service_query_all_albums_async() + - gdata_picasaweb_service_query_files_async() + - gdata_youtube_service_query_standard_feed_async() + - gdata_youtube_service_query_videos_async() + - gdata_youtube_service_query_related_async() +* Added GDataCalendarQuery:max-attendees, gdata_calendar_query_get_max_attendees(), gdata_calendar_query_set_max_attendees() +* Added GDataCalendarQuery:show-deleted, gdata_calendar_query_show_deleted(), gdata_calendar_query_set_show_deleted() +* Added gdata_picasaweb_service_get_user_async(), gdata_picasaweb_service_get_user_finish() + +Bugs fixed: +* Bug 649728 — Add introspection annotations for documents_service_query(_async) +* Bug 639405 — Add max-attendees query parameter +* Bug 637664 — Fix GSeekable interface implementation in GDataDownloadStream +* Bug 633359 — Make tests individually idempotent +* Bug 653535 — Let GDataAuthorizer re-process request after refreshing +* Bug 653530 — Bogus run-time warnings +* Bug 653224 — Add gdata_picasaweb_service_get_user_async() + +Updated translations: +* ca, ca@valencia (Joan Duran) +* cs (Andre Klapper) +* de (Mario Blättermann) +* es (Daniel Mustieles) +* fi (Tommi Vainikainen) +* gl (Fran Diéguez) +* he (Yaron Shahrabani) +* lt (Aurimas Černius) +* ru (Yuri Kozlov) +* sl (Matej Urbančič) +* sr (Мирослав Николић) +* sv (Daniel Nylander) +* tr (Muhammet Kara) + +Overview of changes from libgdata 0.8.0 to libgdata 0.9.0 +========================================================= + +Major changes: +* Switched to even–odd/stable–unstable versioning (so 0.9.0 is an *unstable* release) +* Use HTTPS for all requests +* Some minor parsing fixes +* Fixed some nasty threading/cancellation problems +* Removed the old authentication API in favour of a more extensible, flexible one based on a GDataAuthorizer interface: + - ClientLogin is now handled by GDataClientLoginAuthorizer + - OAuth 1.0 support has been added with GDataOAuth1Authorizer +* Added a dependency on liboauth ≥ 0.9.4 +* Introspection annotation improvements by Philip Chimento +* Removed some outdated contact photo API + +API changes: +* Added GDATA_AUTHENTICATION_ERROR_INVALID_SECOND_FACTOR (later renamed to GDATA_CLIENT_LOGIN_AUTHORIZER_ERROR_INVALID_SECOND_FACTOR as below). +* Rename GDataAuthenticationError to GDataClientLoginAuthorizerError +* Rename GDATA_AUTHENTICATION_ERROR and gdata_authentication_error_quark() similarly. +* Remove gdata_service_authenticate() in favour of using GDataClientLoginAuthorizer with GDataService::authorizer: + - Remove gdata_service_authenticate(), gdata_service_authenticate_async() and gdata_service_authenticate_finish(). + - Replace gdata_service_is_authenticated() by gdata_service_is_authorized() with much the same functionality. + - Add GDataService::authorizer, gdata_service_get_authorizer(), gdata_service_set_authorizer() and gdata_service_get_authorization_domains(). + - Remove gdata_service_get_client_id() in favour of GDataClientLoginAuthorizer::client-id. + - Remove gdata_service_get_username() in favour of GDataClientLoginAuthorizer::username. + - Remove gdata_service_get_password() in favour of GDataClientLoginAuthorizer::password. + - Remove GDataServiceClass->service_name in favour of GDataAuthorizationDomain::service-name. + - Remove GDataServiceClass->authentication_uri and GDataServiceClass->parse_authentication_response in favour of different GDataAuthorizer + implementations. + - Add GDataAuthorizer parameters to and remove client_id parameters from: gdata_calendar_service_new(), gdata_contacts_service_new(), + gdata_documents_service_new(), gdata_picasaweb_service_new() and gdata_youtube_service_new(). +* Add GDataAuthorizationDomain. + - Add GDataServiceClass->get_authorization_domains and gdata_service_get_authorization_domains(). + - Add auth. domain getters to various GDataService subclasses: gdata_youtube_service_get_primary_authorization_domain(), + gdata_contacts_service_get_primary_authorization_domain(), gdata_calendar_service_get_primary_authorization_domain(), + gdata_picasaweb_service_get_primary_authorization_domain(), gdata_documents_service_get_primary_authorization_domain() and + gdata_documents_service_get_spreadsheet_authorization_domain(). + - Add auth. domain properties to various standalone request objects: GDataDownloadStream::authorization-domain with + gdata_download_stream_get_authorization_domain(), GDataUploadStream::authorization-domain with gdata_upload_stream_get_authorization_domain() and + GDataBatchOperation::authorization-domain with gdata_batch_operation_get_authorization_domain(). + - Add GDataAccessHandlerIface->get_authorization_domain. This doesn't have to be implemented by existing GDataAccessHandlers, but it's + highly recommended. + - Add a GDataAuthorizationDomain parameter to GDataServiceClass->append_query_headers, gdata_service_query(), gdata_service_query_async(), + gdata_service_query_single_entry(), gdata_service_query_single_entry_async(), gdata_service_insert_entry(), gdata_service_insert_entry_async(), + gdata_service_update_entry(), gdata_service_update_entry_async(), gdata_service_delete_entry(), gdata_service_delete_entry_async(), + gdata_batchable_create_operation(), gdata_download_stream_new() and gdata_upload_stream_new(). +* Add GDataAuthorizer as described above, implemented by GDataClientLoginAuthorizer. +* Add GDataOAuth1Authorizer and all its properties and methods. +* Remove gdata_contacts_contact_has_photo() and GDataContactsContact:has-photo (use gdata_contacts_contact_get_photo_etag() instead). + +Bugs fixed: +* Bug 642983 — libgdata-0.8.0: test fail with --enable-gtk-doc +* Bug 644940 — Use HTTPS only +* Bug 644946 — Support two-factor authentication +* Bug 639610 — Allow access to a contact's photo ETag +* Bug 648058 — Doesn't allow empty names for user defined fields +* Bug 650835 — [abrt] evolution-data-server-3.0.1-1.fc15: Process /usr/libexec/e-addressbook-factory was killed by signal 6 (SIGABRT) + +Updated translations: +* as (Nilamdyuti Goswami) +* da (Kris Thomsen) +* de (Wolfgang Stöggl) +* bg (Ivaylo Valkov) +* bn_IN (Runa Bhattacharjee) +* ca (Joan Duran) +* cs (Marek Černocký) +* de (Mario Blättermann) +* el (Γιώργος Στεφανάκης, Michael Kotsarinis) +* en_GB (Bruce Cowan) +* eo (Kristjan SCHMIDT) +* es (Daniel Mustieles, Jorge González) +* eu (Iñaki Larrañaga Murgoitio) +* fr (Bruno Brouard) +* gl (Leandro Regueiro, Fran Diéguez) +* gu (Sweta Kothari) +* he (Yaron Shahrabani) +* hi (Rajesh Ranjan) +* hu (Gabor Kelemen) +* id (Andika Triwidada) +* it (Claudio Arseni) +* kn (Shankar Prasad) +* ko (Changwoo Ryu) +* lv (Rudolfs) +* mr (Sandeep Shedmake) +* nb (Kjartan Maraas) +* or (Manoj Kumar Giri) +* pa (A S Alam) +* pl (Piotr Drąg) +* pt (António Lima) +* pt_BR (Rodrigo Padula de Oliveira) +* ro (Lucian Adrian Grijincu) +* ru (Yuri Kozlov) +* sl (Matej Urbančič) +* sr, sr@latin (Мирослав Николић) +* sv (Daniel Nylander) +* th (Akom Chotiphantawanon) +* tr (Senol Korkmaz) +* ug (Gheyret Kenji) +* uk (Korostil Daniel) +* zh_CN (ben) +* zh_HK (Chao-Hsiung Liao) +* zh_TW (Chao-Hsiung Liao) + +Overview of changes from libgdata 0.7.0 to libgdata 0.8.0 +========================================================= + +Major changes: +* Added async counterparts to all remaining blocking methods +* Added various cancellation tests to the test suite +* Many fixes and improvements for cancellation of various operations +* Fixed many race conditions in authentication and cancellation of operations +* Removed the separate youtube-user property for YouTube authentication +* Fixed attribute escaping across all of libgdata +* Removed some deprecated PicasaWeb properties (file clients and positions) +* Switched to stream-based downloading for all download operations +* Tidied up (i.e. broke) the Documents service API a lot +* Tidied up a few test cases and made them idempotent +* Fixed several minor and major memory leaks +* Ensured that batch operations' callbacks are always called, even if the entire batch operation errors out +* Bumped our gdk-pixbuf dependency to 2.14 +* Fixed all the XML comparison tests in light of an invalid assumption we made about hash table ordering being broken +* Added GeoRSS support to YouTube videos +* Overhauled download and upload streams, fixing many race conditions and deadlocks and adding some test cases +* Added support for flushing GDataUploadStream instances +* Added many code examples to the documentation and expanded a few other bits of the documentation + +API changes: +* Added gdata_picasaweb_service_insert_album_async() +* Added gdata_picasaweb_service_query_files_async() +* Removed GDataYouTubeService:youtube-user, gdata_youtube_service_get_youtube_user() +* Removed GDataPicasaWebFile:client, gdata_picasaweb_file_get_client(), gdata_picasaweb_file_set_client() +* Removed GDataPicasaWebFile:position, gdata_picasaweb_file_get_position(), gdata_picasaweb_file_set_position() +* Changed gdata_documents_document_download() to be stream-based +* Changed gdata_documents_service_upload_document(), gdata_documents_service_update_document() to be stream-based +* Added gdata_documents_service_finish_upload() +* Renamed gdata_documents_service_move_document_to_folder() to gdata_documents_service_add_entry_to_folder() +* Renamed gdata_documents_service_remove_document_from_folder() to gdata_documents_service_remove_entry_from_folder() +* Added gdata_documents_service_add_entry_to_folder_async(), gdata_documents_service_add_entry_to_folder_finish() +* Added gdata_documents_service_from_entry_from_folder_async(), gdata_documents_service_from_entry_from_folder_finish() +* Changed GDataDownloadStream::content-length, GDataDownloadStream::content-type to be emitted in the download thread rather than the main thread +* Changed gdata_picasaweb_service_upload_file() to be stream-based +* Removed gdata_picasaweb_service_upload_file_async(), gdata_picasaweb_service_upload_file_finish() +* Added gdata_picasaweb_service_finish_file_upload() +* Changed gdata_media_content_download() to be stream-based +* Changed gdata_media_thumbnail_download() to be stream-based +* Changed gdata_youtube_service_upload_video() to be stream-based +* Added gdata_youtube_service_finish_video_upload() +* Added gdata_calendar_service_query_events_async() +* Added gdata_calendar_service_insert_event_async() +* Changed gdata_contacts_contact_get_photo(), gdata_contacts_contact_set_photo() to use guint8 instead of gchar for image data +* Added gdata_contacts_contact_get_photo_async(), gdata_contacts_contact_get_photo_finish() +* Changed gdata_contacts_contact_set_photo() to require a content type to be passed in +* Added gdata_contacts_contact_set_photo_async(), gdata_contacts_contact_set_photo_finish() +* Added GDataYouTubeVideo:latitude, GDataYouTubeVideo:longitude, gdata_youtube_video_get_coordinates(), gdata_youtube_video_set_coordinates() +* Changed gdata_upload_stream_new() to take a GCancellable +* Added GDataUploadStream:cancellable, gdata_upload_stream_get_cancellable() +* Changed gdata_download_stream_new() to take a GCancellable +* Added GDataDownloadStream:cancellable, gdata_download_stream_get_cancellable() + +Bugs fixed: +* Bug 607620 — Cancelled uploads appear partially complete in PicasaWeb +* Bug 635959 — Proper cancellation support for GDataUploadStream +* Bug 635736 — Asynchronous authentication tests broken +* Bug 634033 — Use standard login URI for YouTube +* Bug 635335 — GIR missing exported packages information +* Bug 631033 — Fix escaping and add tests +* Bug 633363 — Add missing *_async() methods +* Bug 594814 — Handle GeoRSS for YouTube videos +* Bug 637036 — Overhaul cancellation support +* Bug 579885 — Add code examples to documentation + +Updated translations: +* ca@valencia (Joan Duran) +* cs (Marek Černocký) +* da (Kris Thomsen) +* de (Mario Blättermann) +* en_GB (Philip Withnall) +* es (Jorge González) +* eu (Iñaki Larrañaga Murgoitio) +* fr (Bruno Brouard) +* hu (Gabor Kelemen) +* sl (Matej Urbančič) +* sv (Daniel Nylander) +* zh_CN (Eleanor Chen) + +Overview of changes from libgdata 0.6.0 to libgdata 0.7.0 +========================================================= + +Major changes: +* Improved and updated introspection support and annotations for gobject-introspection >= 0.9.7 (which we now depend on) +* Added more code examples to documentation +* Added support for service localisation using gdata_service_set_locale() +* Added support for listing video categories from YouTube +* Tidied up object comparison using a new GDataComparable interface instead of lots of *_compare() methods +* Added batch operation support and implemented it for the Contacts, YouTube, Calendar and Documents services +* Fixed ID projection issues with Contact entries +* Added support for alerting the user of account migration with GDATA_AUTHENTICATION_ERROR_ACCOUNT_MIGRATED +* Added support for a --no-internet option to the tests, so that more of the test suite can be run automatically without an internet connection +* Split handling of entries with inline content from external content (using the new gdata_entry_get_content_uri()) +* Rearranged Documents classes so that instantiable entries are now subclasses of a new GDataDocumentsDocument, which handles downloading of document + files +* Use gtk-doc's no-tmpl flavour, bumping our gtk-doc requirement to 1.14 +* Tightened up URI escaping +* Switched to depending on only gdk-pixbuf instead of the whole of GDK, since we only (optionally) use GdkPixbuf for the test suite +* Tightened up attribute escaping +* Switched from GTimeVal to gint64 for representing UNIX timestamps +* Switched to using upstream gettext instead of glib-gettext +* Added support for manipulating Contact groups + +API changes: +* Added gdata_entry_get_authors +* Added gdata_service_get_locale, gdata_service_set_locale +* Added GDataYouTubeCategory, GDataAPPCategories +* Added gdata_youtube_service_get_categories, gdata_youtube_service_get_categories_async, gdata_youtube_service_get_categories_finish +* Added GDataComparable +* Removed *_compare() functions in favour of implementing the GDataComparable interface +* Added GDataEntryClass->kind_term +* Added GDataBatchable, GDataBatchOperation +* Added GDATA_AUTHENTICATION_ERROR_ACCOUNT_MIGRATED +* Added GDATA_DOCUMENTS_PRESENTATION_PDF, GDATA_DOCUMENTS_PRESENTATION_PNG, GDATA_DOCUMENTS_PRESENTATION_PPT, GDATA_DOCUMENTS_PRESENTATION_SWF + GDATA_DOCUMENTS_PRESENTATION_TXT, GDATA_DOCUMENTS_SPREADSHEET_CSV, GDATA_DOCUMENTS_SPREADSHEET_HTML, GDATA_DOCUMENTS_SPREADSHEET_ODS, + GDATA_DOCUMENTS_SPREADSHEET_PDF, GDATA_DOCUMENTS_SPREADSHEET_TSV, GDATA_DOCUMENTS_SPREADSHEET_XLS, GDATA_DOCUMENTS_TEXT_DOC, + GDATA_DOCUMENTS_TEXT_HTML, GDATA_DOCUMENTS_TEXT_ODT, GDATA_DOCUMENTS_TEXT_PDF, GDATA_DOCUMENTS_TEXT_PNG, GDATA_DOCUMENTS_TEXT_RTF, + GDATA_DOCUMENTS_TEXT_TXT, GDATA_DOCUMENTS_TEXT_ZIP +* Removed GDataDocumentsPresentationFormat, GDataDocumentsSpreadsheetFormat, GDataDocumentsTextFormat and made the appropriate changes to the relevant + Documents functions which took them +* Added gdata_entry_get_content_uri, gdata_entry_set_content_uri and changed the behaviour of gdata_entry_get_content as appropriate +* Added GDataDocumentsDocument as a subclass of GDataDocumentsEntry and the parent of GDataDocumentsPresentation, GDataDocumentsSpreadsheet and + GDataDocumentsText +* Added gdata_documents_document_download, gdata_documents_document_get_download_uri +* Removed gdata_documents_presentation_download_document, gdata_documents_presentation_get_download_uri, + gdata_documents_spreadsheet_download_document, gdata_documents_text_download_document, gdata_documents_text_get_download_uri (moved to + GDataDocumentsDocument) +* Made GDataDocumentsEntry abstract +* Removed gdata_contacts_service_update_contact (use gdata_service_update_entry instead) +* Removed GDataTimeVal (boxed type) +* Removed GTimeVal from the public API, in favour of gint64 +* Added GDATA_LINK_ACCESS_CONTROL_LIST +* Removed gdata_access_handler_insert_rule (use gdata_service_insert_entry instead), gdata_access_handler_update_rule (use gdata_service_update_entry + instead), gdata_access_handler_delete_rule (use gdata_service_delete_entry instead) +* Added gdata_access_handler_get_rules_async +* Added gdata_contacts_service_insert_contact_async +* Added GDataContactsGroup +* Added gdata_contacts_service_query_groups, gdata_contacts_service_query_groups_async, gdata_contacts_service_insert_group, + gdata_contacts_service_insert_group_async + +Bugs fixed: +* Bug 616222 — libgdata fails to build from a remote directory +* Bug 579885 — Add code examples to documentation +* Bug 618584 — Implement gdata_entry_get_authors() +* Bug 615721 — Support listing video categories +* Bug 618586 — gdata_service_query_single_entry() encounters NULL type class +* Bug 579169 — Add batch processing support +* Bug 624142 — Add batch operation support to Calendar service +* Bug 624141 — Add batch operation support to Documents service +* Bug 630350 — Email address cannot contain name + +Updated translations: +* ca (Gil Forcada) +* cs (Marek Cernocky) +* da (Kris Thomsen) +* de (Mario Blättermann, Christian Kirbach) +* en_GB (Philip Withnall) +* es (Jorge González) +* fr (Claude Paroz) +* gl (Fran Diéguez) +* hu (Gabor Kelemen) +* id (Andika Triwidada) +* it (Milo Casagrande) +* lt (Aurimas Černius) +* pl (Piotr Drąg) +* pt (António Lima) +* pt_BR (Djavan Fagundes) +* ro (Daniel Șerbănescu, Lucian Adrian Grijincu) +* sl (Matej Urbančič) +* sv (Daniel Nylander) +* zh_CN (Yinghua Wang, Eleanor Chen, YunQiang Su) + +Overview of changes from libgdata 0.5.0 to libgdata 0.6.0 +========================================================= + +Major changes: +* Added feed icon support +* Added support for querying for user information on the PicasaWeb service +* Added some code examples to the documentation +* Ensured UTF-8 is supported correctly everywhere +* Added GObject introspection support (GData-0.0.gir) +* Added a download API for PicasaWeb images and thumbnails +* Added an asynchronous PicasaWeb upload API +* Reorganised the build system to use non-recursive automake +* Added gcov support and consequently improved test coverage somewhat +* Ensured HTTPS requests are used wherever possible, unless the LIBGDATA_FORCE_HTTP environment variable is set +* Modified memory management to consistently use the GLib memory manager, eliminating 53 calls to g_strdup() on an average test run +* Consolidated generic API errors to GDATA_SERVICE_ERROR_PROTOCOL_ERROR + +API changes: +* Added gdata_picasaweb_query_new_with_limits +* Added gdata_feed_get_icon +* Added GDataPicasaWebUser, gdata_picasaweb_service_get_user +* Removed gdata_picasaweb_album_get_name, gdata_picasaweb_album_get_description, gdata_picasaweb_album_set_description and corresponding properties +* Added GDataPicasaWebFeed +* Removed gdata_youtube_video_get_title, gdata_youtube_video_set_title +* Added gdata_media_content_download, gdata_media_thumbnail_download +* Added gdata_picasaweb_service_insert_album +* Added gdata_picasaweb_service_upload_file_async, gdata_picasaweb_service_upload_file_finish +* Added gdata_gd_organization_get_location, gdata_gd_organization_set_location, + gdata_gd_email_address_get_display_name, gdata_gd_email_address_set_display_name +* Added GDataOperationType +* Removed GDATA_SERVICE_ERROR_WITH_*; GDATA_SERVICE_ERROR_PROTOCOL_ERROR is now returned instead + +Bugs fixed: +* Bug 597248 — Add gdata_picasaweb_query_new_with_limits +* Bug 598746 — gdata_picasaweb_query_set_image_size documentation fix +* Bug 598910 — Timestamp bug +* Bug 598912 — Test data was changed by my mucking around with comments +* Bug 598893 — gdata_picasaweb_album_new doesn't set a valid visibility +* Bug 599140 — Have albums initialise date to now by default +* Bug 589858 — Handle gphoto XML elements found in 'GDataFeed' +* Bug 598913 — Add gdata_picasaweb_service_insert_album() +* Bug 602156 — GDataUploadStream should close GOutputStream on dispose +* Bug 598649 — Download API for PicasaWeb images and thumbnails +* Bug 600262 — Add async PicasaWeb upload API +* Bug 604313 — Test failures in 0.5.1 +* Bug 601919 — Expand a comment, organise some media tests +* Bug 598748 — *_download_document prevents non-overwriting saving into directories +* Bug 607607 — Undefined symbol with introspection + +Updated translations: +* cs (Marek Cernocky, Petr Kovar) +* de (Mario Blättermann) +* es (Jorge González) +* fr (Claude Paroz, Julien Hardelin) +* gl (Fran Dieguez) +* hu (Gabor Kelemen) +* it (Rita Bandiera) +* ja (Takeshi AIHANA) +* pt (António Lima) +* pt_BR (Djavan Fagundes, Og Maciel) +* sl (Matej Urbančič) +* sv (Daniel Nylander) +* zh_CN (Aron Xu) + +Overview of changes from libgdata 0.4.0 to libgdata 0.5.0 +========================================================= + +Major changes: +* Added Exif support for PicasaWeb files +* Added the ability to query single Google Documents files +* Errors are now logged in the "libgdata" domain +* Added GeoRSS support for PicasaWeb files and albums +* Optimisation to the XML output functions +* Added streaming download and upload support using GDataDownloadStream and GDataUploadStream +* Added support for silent building with AM_SILENT_RULES +* Updated the GData namespace to version 3, improving name and address support + +API changes: +* Changed gdata_documents_*_download_document to accept a destination file, rather than a directory +* Added gdata_picasaweb_file_get_distance, gdata_picasaweb_file_get_exposure, gdata_picasaweb_file_get_flash, gdata_picasaweb_file_get_focal_length + gdata_picasaweb_file_get_fstop, gdata_picasaweb_file_get_image_unique_id, gdata_picasaweb_file_get_iso, gdata_picasaweb_file_get_make + gdata_picasaweb_file_get_model and corresponding properties +* Added GDataExifTags +* Added gdata_documents_entry_is_deleted +* Added GDataEntry:rights, gdata_entry_get_rights, gdata_entry_set_rights +* Added gdata_documents_service_query_single_document +* Added GDataPicasaWebAlbum:latitude, GDataPicasaWebAlbum:longitude, gdata_picasaweb_album_get_coordinates, gdata_picasaweb_album_set_coordinates, + GDataPicasaWebFile:latitude, GDataPicasaWebFile:longitude, gdata_picasaweb_file_get_coordinates, gdata_picasaweb_file_set_coordinates +* Added GDataGeoRSSWhere +* Added GDataDownloadStream +* Added GDATA_SERVICE_ERROR_WITH_DOWNLOAD, GDATA_SERVICE_ERROR_WITH_UPLOAD service errors +* Added gdata_documents_*_get_download_uri +* Added GDataUploadStream +* Added GDataGDName +* Added GDataGDOrganization:department, gdata_gd_organization_get_department, gdata_gd_organization_set_department, GDataGDOrganization:job-description, + gdata_gd_organization_get_job_description, gdata_gd_organization_set_job_description, GDataGDOrganization:symbol, gdata_gd_organization_get_symbol, + gdata_gd_organization_set_symbol +* Added GDATA_GD_MAIL_CLASS_*, GDATA_GD_ADDRESS_USAGE_* +* Removed the address parameter from gdata_gd_postal_address_new +* Added GDataGDPostalAddress:mail-class, gdata_gd_postal_address_get_mail_class, gdata_gd_postal_address_set_mail_class, GDataGDPostalAddress:usage, + gdata_gd_postal_address_get_usage, gdata_gd_postal_address_set_usage, GDataGDPostalAddress:agent, gdata_gd_postal_address_get_agent, + gdata_gd_postal_address_set_agent, GDataGDPostalAddress:house-name, gdata_gd_postal_address_get_house_name, gdata_gd_postal_address_set_house_name, + GDataGDPostalAddress:street, gdata_gd_postal_address_get_street, gdata_gd_postal_address_set_street, GDataGDPostalAddress:po-box, + gdata_gd_postal_address_get_po_box, gdata_gd_postal_address_set_po_box, GDataGDPostalAddress:neighborhood, gdata_gd_postal_address_get_neighborhood, + gdata_gd_postal_address_set_neighborhood, GDataGDPostalAddress:city, gdata_gd_postal_address_get_city, gdata_gd_postal_address_set_city, + GDataGDPostalAddress:subregion, gdata_gd_postal_address_get_subregion, gdata_gd_postal_address_set_subregion, GDataGDPostalAddress:region, + gdata_gd_postal_address_get_region, gdata_gd_postal_address_set_region, GDataGDPostalAddress:postcode, gdata_gd_postal_address_get_postcode, + gdata_gd_postal_address_set_postcode, GDataGDPostalAddress:country, GDataGDPostalAddress:country-code, gdata_gd_postal_address_get_country, + gdata_gd_postal_address_get_country_code, gdata_gd_postal_address_set_country +* Added GDataContactsContact:name, gdata_contacts_contact_get_name +* Added gdata_documents_service_get_upload_uri + +Bugs fixed: +* Bug 589265 – Crash on query error +* Bug 589545 – *_download_document(): let the client decide where to download +* Bug 589201 – Add EXIF support for PicasaWeb image files +* Bug 589850 – gdata_picasaweb_album_get_timestamp() returns date in 1970! +* Bug 590345 – handling in GDataDocumentsEntry +* Bug 589855 – Obsolete not handled in GDataPicasaWebAlbum parse_xml() +* Bug 590341 – Allow querying of single documents +* Bug 590132 – Unhandled XML for georss +* Bug 590568 – Crash on querying inside a folder +* Bug 591966 — Can't query single spreadsheets +* Bug 591974 — remove_document_from_folder moves documents to the trash +* Bug 591691 — Getting a feed containing PDF documents returns NULL +* Bug 592124 — G_LOG_DOMAIN not set for subdirectories +* Bug 592845 — Undefined symbol: gdata_picasaweb_query_new_with_limits +* Bug 593239 — Use GDataUploadStream for uploading files +* Bug 593336 — Query parameter "q=..." isn't valid for album kinds + +Updated translations: +* de (Mario Blättermann) +* en_GB (Philip Withnall) +* es (Jorge González) +* eu (Iñaki Larrañaga Murgoitio) +* fr (Nicolas Repentin) +* gl (Fran Dieguez) +* hu (Gabor Kelemen) +* nb (Kjartan Maraas) +* po (Piotr Drąg) +* pt (António Lima) +* pt_BR (Flamarion Jorge) +* sv (Daniel Nylander) +* zh_HK (Chao-Hsiung Liao) +* zh_TW (Chao-Hsiung Liao) + +Overview of changes from libgdata 0.3.0 to libgdata 0.4.0 +========================================================= + +Major changes: +* Added comparison functions for all small XML elements (such as GDataLink and friends) +* Added GDataContactsContact photo support +* Translatable strings are now even clearer, and all have translator comments +* Fixed a number of locale-dependent bugs +* Converted small XML element structs to full GObjects +* Added a PicasaWeb service by Richard Schwarting +* Fixed more licencing issues (libgdata is licenced under LGPLv2.1+) +* Required link relation types to be full URIs +* Added a Google Documents service by Thibault Saunier + +API changes: +* Added gdata_contacts_contact_get_extended_properties +* Added *_compare +* Added GDataContactsContact:has-photo, gdata_contacts_contact_has_photo, gdata_contacts_contact_get_photo, gdata_contacts_contact_set_photo +* Converted GDataAuthor, GDataCategory, GDataLink, GDataGenerator to GObjects (removed *_free functions and added mandatory field accessors) +* Converted GDataGDEmailAddress, GDataGDFeedLink, GDataGDIMAddress, GDataGDOrganization, GDataGDPhoneNumber, GDataGDPostalAddress, GDataGDRating, + GDataGDWhen, GDataGDReminder, GDataGDWhere, GDataGDWho to GObjects (removed *_free functions and added mandatory field accessors) +* Converted GDataMediaCategory, GDataMediaContent, GDataMediaCredit, GDataMediaRating, GDataMediaRestriction, GDataMediaThumbnail to GObjects + (removed *_free functions and added mandatory field accessors) +* Removed gdata_media_thumbnail_parse_time, gdata_media_thumbnail_build_time +* Converted GDataYouTubeState to GObject (removed gdata_youtube_state_free and added mandatory field accessors) +* Added GDataYouTubeControl +* Added PicasaWeb service API +* Removed gdata_entry_new_from_xml, other *_new_from_xml functions, gdata_entry_get_xml +* Added gdata_parsable_new_from_xml, gdata_parsable_get_xml +* Removed GDATA_PARSER_ERROR_UNHANDLED_XML_ELEMENT parser error +* Added GDataParsableClass->element_name, GDataParsableClass->element_namespace +* Added GDATA_LINK_ALTERNATE, GDATA_LINK_EDIT, GDATA_LINK_EDIT_MEDIA, GDATA_LINK_ENCLOSURE, GDATA_LINK_RELATED, GDATA_LINK_SELF, GDATA_LINK_VIA + for use with gdata_entry_look_up_link +* Added gdata_contacts_service_update_contact +* Added gdata_youtube_service_query_single_video, gdata_youtube_service_query_single_video_async, gdata_youtube_service_query_single_video_finish +* Added gdata_youtube_video_get_video_id_from_uri +* Added GDataYouTubeAspectRatio, gdata_youtube_video_get_aspect_ratio, gdata_youtube_video_set_aspect_ratio +* Added Google Documents service API +* Added gdata_contacts_contact_remove_all_email_addresses, gdata_contacts_contact_remove_all_im_addresses, + gdata_contacts_contact_remove_all_postal_addresses, gdata_contacts_contact_remove_all_phone_numbers, gdata_contacts_contact_remove_all_organizations + +Bugs fixed: +* Bug 584417 – Strings are not properly formed for localisation +* Bug 584737 – String parsing is locale-sensitive +* Bug 579170 – Eliminate gdata_parser_error_unhandled_element +* Bug 587277 – Some files are GPLv3 but license is LGPLv2.1? +* Bug 588052 – Parse the yt:aspectratio tag +* Bug 587073 – Add Google Documents service +* Bug 588995 – float radix character depends on LC_NUMERIC, but Google wants "." + +Updated translations: +* ca (Joan Duran) +* de (Mario Blättermann) +* en_GB (Philip Withnall) +* es (Jorge González) +* nb (Kjartan Maraas) +* pa (A S Alam) +* sv (Daniel Nylander) +* uk (Maxim Dziumanenko) + +Overview of changes from libgdata 0.2.0 to libgdata 0.3.0 +========================================================= + +Major changes: +* Empty (but present) entry titles are now set to an empty string, rather than NULL +* GDataCalendarEvent has basic recurrence support +* Optional GNOME support has been added for automagic proxy configuration (depends on libsoup-gnome-2.4) +* Deprecated libsoup API has been removed, bumping the requirement to 2.26.1 +* Translation comments and some translatable strings have been made clearer +* Default error handling has been improved +* More async versions of functions have been added +* The XML output of GDataCalendarCalendar has been completed +* GDataYouTubeVideo now has support for recorded times and comment feed links +* Added a GDataYouTubeQuery class +* Access control list (ACL) support, implemented on GDataCalendarCalendar +* Abstract XML parsing into GDataParsable to allow GDataFeed to be overridden +* Added a GDataCalendarFeed class to deal with calendar-specific properties + +API changes: +* Added GDataCalendarEvent:recurrence, gdata_calendar_event_get_recurrence, gdata_calendar_event_set_recurrence +* Added GDataCalendarEvent:original-event-id, GDataCalendarEvent:original-event-uri, gdata_calendar_event_get_original_event_details +* Added gdata_calendar_event_is_exception +* Added GDATA_SERVICE_ERROR_NOT_FOUND, GDATA_SERVICE_ERROR_CONFLICT +* Changed GDataServiceClass->parse_error_response +* Added gdata_service_insert_entry_async, gdata_service_insert_entry_finish +* Added gdata_service_update_entry_async, gdata_service_update_entry_finish +* Added gdata_service_delete_entry_async, gdata_service_delete_entry_finish +* Added gdata_color_to_hexadecimal +* Added GDataYouTubeVideo:comments-feed-link, gdata_youtube_video_get_comments_feed_link +* Added GDataYouTubeVideo:recorded, gdata_youtube_video_get_recorded, gdata_youtube_video_set_recorded +* Added read_only parameter to gdata_gd_feed_link_new and member to GDataGDFeedLink +* Added GDataYouTubeQuery +* Added GDataAccessHandler, GDataAccessRule +* Added GDATA_SERVICE_ERROR_FORBIDDEN +* Added GDataParsable +* Changed GDataEntry to extend GDataParsable, rather than GObject +* Removed GDataEntry->parse_xml +* Changed GDataFeed to extend GDataParsable, rather than GObject +* Added GDataCalendarFeed +* Added GDataServiceClass->feed_type + +Bugs fixed: +* Bug 582026 – Access Control List functionality +* Bug 578367 – Add support for YouTube-specific query parameters +* Bug 581706 – translation issues +* Bug 580330 – Rejects empty entry titles + +Updated translations: +* de (Mario Blättermann) +* el (Giannis Katsampirhs) +* en_GB (Philip Withnall) +* es (Jorge González) +* gl (Fran Diéguez, Antón Méixome) + +Overview of changes from libgdata 0.1.0 to libgdata 0.2.0 +========================================================= + +Major changes: +* The updated entry is now returned when inserting an entry +* Entries can be updated with gdata_service_update_entry +* Entries can be deleted with gdata_service_delete_entry +* GDataService has proxy support with the proxy-uri property +* Redirects from the server are now handled correctly +* API documentation is now complete +* Unknown XML elements are stored and returned when building the XML for an entry +* ETag support for entries and feeds +* Added a Google Contacts service + +API changes: +* Added GDataEntry:etag, gdata_entry_get_etag +* Added gdata_entry_get_categories +* Added GDataFeed:etag, gdata_feed_get_etag +* Added gdata_feed_look_up_entry +* Added GDataGDWhen, gdata_gd_when_new, gdata_gd_when_free +* Added GDataGDEmailAddress, gdata_gd_email_address_new, gdata_gd_email_address_free +* Added GDataGDIMAddress, gdata_gd_im_address_new, gdata_gd_im_address_free +* Added GDataGDPhoneNumber, gdata_gd_phone_number_new, gdata_gd_phone_number_free +* Added GDataGDPostalAddress, gdata_gd_postal_address_new, gdata_gd_postal_address_free +* Added GDataGDOrganization, gdata_gd_organization_new, gdata_gd_organization_free +* Added GDataGDReminder, gdata_gd_reminder_new, gdata_gd_reminder_free +* Renamed GDataQuery:strict to GDataQuery:is-strict, gdata_query_get_strict to gdata_query_is_strict, gdata_query_set_strict to gdata_query_set_is_strict +* Added GDataQuery:etag, gdata_query_get_etag, gdata_query_set_etag +* Added GDataService:proxy-uri, gdata_service_get_proxy_uri, gdata_service_set_proxy_uri +* Added gdata_service_update_entry +* Added gdata_service_update_entry +* Removed gdata_service_get_session +* Renamed GDataCalendarCalendar:hidden to GDataCalendarCalendar:is-hidden, gdata_calendar_calendar_get_hidden to gdata_calendar_calendar_is_hidden, + gdata_calendar_calendar_set_hidden to gdata_calendar_calendar_set_is_hidden +* Renamed GDataCalendarCalendar:selected to GDataCalendarCalendar:is-selected, + gdata_calendar_calendar_get_selected to gdata_calendar_calendar_is_selected, + gdata_calendar_calendar_set_selected to gdata_calendar_calendar_set_is_selected +* Renamed GDataCalendarEvent:event-status to GDataCalendarEvent:status, gdata_calendar_event_get_event_status to gdata_calendar_event_get_status, + gdata_calendar_event_set_event_status to gdata_calendar_event_set_status +* Added gdata_calendar_event_get_people +* Added gdata_calendar_event_get_places +* Added gdata_calendar_event_add_time, gdata_calendar_event_get_times, gdata_calendar_event_get_primary_time +* Removed gdata_calendar_event_set_edited +* Made GDataCalendarEvent:edited read-only +* Removed gdata_calendar_event_get_start_time, gdata_calendar_event_set_start_time, gdata_calendar_event_get_end_time, gdata_calendar_event_set_end_time, + gdata_calendar_event_get_when_value, gdata_calendar_event_set_when_value +* Renamed GDataCalendarQuery:ctz to GDataCalendarQuery:timezone, gdata_calendar_query_get_ctz to gdata_calendar_query_get_timezone, + gdata_calendar_query_set_ctz to gdata_calendar_query_set_timezone +* Added gdata_calendar_service_insert_event +* Renamed g_time_val_get_type to gdata_g_time_val_get_type +* Added Google Contacts service API + +Bugs fixed: +* Bug 579631 – Add G_GNUC_WARN_UNUSED_RESULT to functions +* Bug 578661 – ETag support +* Bug 578662 – Support unknown XML elements +* Bug 578653 – self-test fails to build on glib-2.18.x +* Bug 578652 – Build failure: missing symbol: gdata_query_param_get_type + +Updated translations: +* de (Mario Blättermann) +* en_GB (Philip Withnall) +* sv (Daniel Nylander) + +Overview of changes from libgdata 0.1.0 to libgdata 0.1.1 +========================================================= + +Major changes: +* Fixed licencing issues +* Changed website to http://live.gnome.org/libgdata + +API changes: +* Renamed gdata_entry_lookup_link to gdata_entry_look_up_link +* Renamed gdata_feed_lookup_link to gdata_feed_look_up_link + +Initial release of libgdata 0.1.0 +================================= + +Major changes: +* Create project +* Add mostly-complete support for YouTube queries and video uploads +* Add basic and incomplete support for Google Calendar queries diff --git a/README b/README new file mode 100644 index 0000000..b0f38c3 --- /dev/null +++ b/README @@ -0,0 +1,64 @@ +libgdata +======== + +libgdata is a GLib-based library for accessing online service APIs using the +GData protocol --- most notably, Google's services. It provides APIs to access +the common Google services, and has full asynchronous support. + +See the test programs in gdata/tests/ for simple examples of how to use the +code. + +libgdata is API and ABI stable. + +Dependencies +============ + + • glib-2.0 ≥ 2.44.0 + • libxml-2.0 + • gio-2.0 ≥ 2.44.0 + • libsoup-2.4 ≥ 2.42.0 + • liboauth ≥ 0.9.4 + • json-glib ≥ 0.15.0 + +If compiling with --enable-gnome (for GNOME support): + • gcr-base-3 + • goa-1.0 ≥ 3.8 + +If compiling the demos: + • gtk+-3.0 ≥ 2.91.2 + +Environment variables +===================== + +If the environment variable LIBGDATA_DEBUG is set to one of the following +values, libgdata will give debug output (at various levels): + 0: Output no debug messages or network logs + 1: Output debug messages, but not network logs + 2: Output debug messages and network traffic headers + 3: Output debug messages and full network traffic logs, redacting usernames, + passwords and auth. tokens + 4: Output debug messages and full network traffic logs, and don't redact + usernames, passwords and auth. tokens +If LIBGDATA_DEBUG is unset, no debug output will be produced. + +So, to debug a program which uses libgdata, run it from a terminal with the +following command: + +$ LIBGDATA_DEBUG=3 ./my-program-name &> libgdata.log + +Deprecation guards +================== + +If LIBGDATA_DISABLE_DEPRECATED is defined when compiling against libgdata, all +deprecated API will be removed from included headers. + +Licensing +========= + +libgdata is licensed under the LGPL; see COPYING for more details. + +Contact +======= + +Philip Withnall +https://wiki.gnome.org/Projects/libgdata diff --git a/demos/calendar/calendar-cli.c b/demos/calendar/calendar-cli.c new file mode 100644 index 0000000..a1d84f6 --- /dev/null +++ b/demos/calendar/calendar-cli.c @@ -0,0 +1,553 @@ +/* -*- Mode: C; indent-tabs-mode: t; c-basic-offset: 8; tab-width: 8 -*- */ +/* + * GData Client + * Copyright (C) 2015 Philip Withnall + * + * GData Client is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * GData Client is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with GData Client. If not, see . + */ + +#include +#include +#include + +#define CLIENT_ID "1074795795536-necvslvs0pchk65nf6ju4i6mniogg8fr.apps.googleusercontent.com" +#define CLIENT_SECRET "8totRi50eo2Zfr3SD2DeNAzo" +#define REDIRECT_URI "urn:ietf:wg:oauth:2.0:oob" + +static int +print_usage (char *argv[]) +{ + g_printerr ("%s: Usage — %s \n" + "Subcommands:\n" + " calendars [--all|--own]\n" + " events [query string]\n" + " insert-event <start time> " + "<end time> <attendee 1> [attendee 2 …]\n", + argv[0], argv[0]); + return -1; +} + +/* Convert a GTimeVal to an ISO 8601 date string (without a time component). */ +static gchar * +tv_to_iso8601_date (GTimeVal *tv) +{ + struct tm *tm; + + tm = gmtime (&tv->tv_sec); + + return g_strdup_printf ("%04d-%02d-%02d", + tm->tm_year + 1900, + tm->tm_mon + 1, + tm->tm_mday); +} + +static void +print_calendar (GDataCalendarCalendar *calendar) +{ + const gchar *id, *title, *time_zone, *access_level, *description; + gboolean is_hidden, is_selected; + + id = gdata_entry_get_id (GDATA_ENTRY (calendar)); + title = gdata_entry_get_title (GDATA_ENTRY (calendar)); + time_zone = gdata_calendar_calendar_get_timezone (calendar); + is_hidden = gdata_calendar_calendar_is_hidden (calendar); + is_selected = gdata_calendar_calendar_is_selected (calendar); + access_level = gdata_calendar_calendar_get_access_level (calendar); + description = gdata_entry_get_summary (GDATA_ENTRY (calendar)); + + g_print ("%s — %s\n", id, title); + g_print (" Timezone: %s\n", time_zone); + g_print (" Access level: %s\n", access_level); + g_print (" Hidden? %s\n", is_hidden ? "Yes" : "No"); + g_print (" Selected? %s\n", is_selected ? "Yes" : "No"); + g_print (" Description:\n %s\n", description); + + g_print ("\n"); +} + +static void +print_event (GDataCalendarEvent *event) +{ + const gchar *title, *id, *description, *status, *visibility; + const gchar *transparency, *uid; + GTimeVal date_published_tv = { 0, }; + GTimeVal date_edited_tv = { 0, }; + gchar *date_published = NULL; /* owned */ + gchar *date_edited = NULL; /* owned */ + guint sequence; + gboolean guests_can_modify, guests_can_invite_others; + gboolean guests_can_see_guests, anyone_can_add_self; + GList/*<unowned GDataGDWho>*/ *people; /* unowned */ + GList/*<unowned GDataGDWhere>*/ *places; /* unowned */ + GList/*<unowned GDataGDWhen>*/ *times; /* unowned */ + + title = gdata_entry_get_title (GDATA_ENTRY (event)); + id = gdata_entry_get_id (GDATA_ENTRY (event)); + description = gdata_entry_get_content (GDATA_ENTRY (event)); + date_published_tv.tv_sec = gdata_entry_get_published (GDATA_ENTRY (event)); + date_published = g_time_val_to_iso8601 (&date_published_tv); + date_edited_tv.tv_sec = gdata_calendar_event_get_edited (event); + date_edited = g_time_val_to_iso8601 (&date_edited_tv); + status = gdata_calendar_event_get_status (event); + visibility = gdata_calendar_event_get_visibility (event); + transparency = gdata_calendar_event_get_transparency (event); + uid = gdata_calendar_event_get_uid (event); + sequence = gdata_calendar_event_get_sequence (event); + guests_can_modify = gdata_calendar_event_get_guests_can_modify (event); + guests_can_invite_others = gdata_calendar_event_get_guests_can_invite_others (event); + guests_can_see_guests = gdata_calendar_event_get_guests_can_see_guests (event); + anyone_can_add_self = gdata_calendar_event_get_anyone_can_add_self (event); + people = gdata_calendar_event_get_people (event); + places = gdata_calendar_event_get_places (event); + times = gdata_calendar_event_get_times (event); + + g_print ("%s — %s\n", id, title); + g_print (" UID: %s\n", uid); + g_print (" Sequence: %u\n", sequence); + g_print (" Published: %s\n", date_published); + g_print (" Edited: %s\n", date_edited); + g_print (" Status: %s\n", status); + g_print (" Visibility: %s\n", visibility); + g_print (" Transparency: %s\n", transparency); + g_print (" Guests can modify event? %s\n", + guests_can_modify ? "Yes" : "No"); + g_print (" Guests can invite others? %s\n", + guests_can_invite_others ? "Yes" : "No"); + g_print (" Guests can see guest list? %s\n", + guests_can_see_guests ? "Yes" : "No"); + g_print (" Anyone can add themselves? %s\n", + anyone_can_add_self ? "Yes" : "No"); + g_print (" Description:\n %s\n", description); + + g_print (" Guests:\n"); + + for (; people != NULL; people = people->next) { + GDataGDWho *who; + + who = GDATA_GD_WHO (people->data); + g_print (" • %s — %s (%s)\n", + gdata_gd_who_get_value_string (who), + gdata_gd_who_get_email_address (who), + gdata_gd_who_get_relation_type (who)); + } + + g_print (" Locations:\n"); + + for (; places != NULL; places = places->next) { + GDataGDWhere *where; + + where = GDATA_GD_WHERE (places->data); + g_print (" • %s\n", gdata_gd_where_get_value_string (where)); + } + + g_print (" Times:\n"); + + for (; times != NULL; times = times->next) { + GDataGDWhen *when; + GTimeVal start_time = { 0, }, end_time = { 0, }; + gchar *start = NULL, *end = NULL; /* owned */ + + when = GDATA_GD_WHEN (times->data); + + start_time.tv_sec = gdata_gd_when_get_start_time (when); + end_time.tv_sec = gdata_gd_when_get_end_time (when); + + if (gdata_gd_when_is_date (when)) { + start = tv_to_iso8601_date (&start_time); + end = tv_to_iso8601_date (&end_time); + } else { + start = g_time_val_to_iso8601 (&start_time); + end = g_time_val_to_iso8601 (&end_time); + } + + g_print (" • %s to %s (%s)\n", + start, end, gdata_gd_when_get_value_string (when)); + + /* TODO: Reminders are not supported yet. */ + } + + g_print ("\n"); + + g_free (date_published); +} + +static GDataAuthorizer * +create_authorizer (GError **error) +{ + GDataOAuth2Authorizer *authorizer = NULL; /* owned */ + gchar *uri = NULL; + gchar code[100]; + GError *child_error = NULL; + + /* Go through the interactive OAuth dance. */ + authorizer = gdata_oauth2_authorizer_new (CLIENT_ID, CLIENT_SECRET, + REDIRECT_URI, + GDATA_TYPE_CALENDAR_SERVICE); + + /* Get an authentication URI */ + uri = gdata_oauth2_authorizer_build_authentication_uri (authorizer, + NULL, FALSE); + + /* Wait for the user to retrieve and enter the verifier. */ + g_print ("Please navigate to the following URI and grant access:\n" + " %s\n", uri); + g_print ("Enter verifier (EOF to abort): "); + + g_free (uri); + + if (scanf ("%100s", code) != 1) { + /* User chose to abort. */ + g_print ("\n"); + g_clear_object (&authorizer); + return NULL; + } + + /* Authorise the token. */ + gdata_oauth2_authorizer_request_authorization (authorizer, code, NULL, + &child_error); + + if (child_error != NULL) { + g_propagate_error (error, child_error); + g_clear_object (&authorizer); + return NULL; + } + + return GDATA_AUTHORIZER (authorizer); +} + +/* List all the user’s calendars. */ +static int +command_calendars (int argc, char *argv[]) +{ + GDataCalendarService *service = NULL; + GDataCalendarQuery *query = NULL; + GDataFeed *feed = NULL; + GList/*<unowned GDataCalendarCalendar>*/ *entries; + GError *error = NULL; + gint retval = 0; + gboolean only_own; /* only query for calendars the user owns */ + GDataAuthorizer *authorizer = NULL; + + if (argc < 2) { + return print_usage (argv); + } else if (argc == 2) { + only_own = FALSE; + } else if (g_strcmp0 (argv[2], "--all") == 0 || + g_strcmp0 (argv[2], "--own") == 0) { + only_own = (g_strcmp0 (argv[2], "--own") == 0); + } else { + only_own = FALSE; + } + + /* Authenticate and create a service. */ + authorizer = create_authorizer (&error); + + if (error != NULL) { + g_printerr ("%s: Error authenticating: %s\n", + argv[0], error->message); + g_error_free (error); + retval = 1; + goto done; + } else if (authorizer == NULL) { + g_printerr ("%s: User chose to abort authentication.\n", + argv[0]); + retval = 1; + goto done; + } + + service = gdata_calendar_service_new (authorizer); + query = gdata_calendar_query_new (NULL); + + if (only_own) { + feed = gdata_calendar_service_query_own_calendars (service, + GDATA_QUERY (query), + NULL, NULL, + NULL, + &error); + } else { + feed = gdata_calendar_service_query_all_calendars (service, + GDATA_QUERY (query), + NULL, NULL, + NULL, + &error); + } + + if (error != NULL) { + g_printerr ("%s: Error querying calendars: %s\n", + argv[0], error->message); + g_error_free (error); + retval = 1; + goto done; + } + + /* Print results. */ + for (entries = gdata_feed_get_entries (feed); entries != NULL; + entries = entries->next) { + GDataCalendarCalendar *calendar; + + calendar = GDATA_CALENDAR_CALENDAR (entries->data); + print_calendar (calendar); + } + + g_print ("Total of %u results.\n", + g_list_length (gdata_feed_get_entries (feed))); + +done: + g_clear_object (&feed); + g_clear_object (&query); + g_clear_object (&authorizer); + g_clear_object (&service); + + return retval; +} + +/* Query the events in a calendar. */ +static int +command_events (int argc, char *argv[]) +{ + GDataCalendarService *service = NULL; + GDataCalendarCalendar *calendar = NULL; + GDataCalendarQuery *query = NULL; + GError *error = NULL; + gint retval = 0; + const gchar *query_string, *calendar_id; + GDataAuthorizer *authorizer = NULL; + guint n_results; + + if (argc < 3) { + return print_usage (argv); + } + + calendar_id = argv[2]; + query_string = (argc > 3) ? argv[3] : NULL; + + /* Authenticate and create a service. */ + authorizer = create_authorizer (&error); + + if (error != NULL) { + g_printerr ("%s: Error authenticating: %s\n", + argv[0], error->message); + g_error_free (error); + retval = 1; + goto done; + } else if (authorizer == NULL) { + g_printerr ("%s: User chose to abort authentication.\n", + argv[0]); + retval = 1; + goto done; + } + + service = gdata_calendar_service_new (authorizer); + query = gdata_calendar_query_new (query_string); + gdata_query_set_max_results (GDATA_QUERY (query), 10); + calendar = gdata_calendar_calendar_new (calendar_id); + n_results = 0; + + while (TRUE) { + GList/*<unowned GDataCalendarEvent>*/ *entries, *l; + GDataFeed *feed = NULL; + + feed = gdata_calendar_service_query_events (service, calendar, + GDATA_QUERY (query), NULL, + NULL, NULL, &error); + + if (error != NULL) { + g_printerr ("%s: Error querying events: %s\n", + argv[0], error->message); + g_error_free (error); + retval = 1; + goto done; + } + + /* Print results. */ + entries = gdata_feed_get_entries (feed); + + if (entries == NULL) { + retval = 0; + g_object_unref (feed); + goto done; + } + + for (l = entries; l != NULL; l = l->next) { + GDataCalendarEvent *event; + + event = GDATA_CALENDAR_EVENT (l->data); + print_event (event); + n_results++; + } + + gdata_query_next_page (GDATA_QUERY (query)); + g_object_unref (feed); + } + + g_print ("Total of %u results.\n", n_results); + +done: + g_clear_object (&query); + g_clear_object (&authorizer); + g_clear_object (&calendar); + g_clear_object (&service); + + return retval; +} + +/* Insert a new event into a calendar. */ +static int +command_insert_event (int argc, char *argv[]) +{ + GDataCalendarService *service = NULL; + GDataCalendarCalendar *calendar = NULL; + GDataCalendarEvent *event = NULL; + GDataCalendarEvent *inserted_event = NULL; + GError *error = NULL; + gint retval = 0; + const gchar *calendar_id, *title, *start, *end; + GDataAuthorizer *authorizer = NULL; + GDataGDWhen *when = NULL; + gboolean is_date; + gchar *start_with_time = NULL, *end_with_time = NULL; + GTimeVal start_tv = { 0, }, end_tv = { 0, }; + gint i; + + if (argc < 7) { + return print_usage (argv); + } + + calendar_id = argv[2]; + title = argv[3]; + start = argv[4]; + end = argv[5]; + /* subsequent arguments are e-mail addresses of attendees, + * with at least one required. */ + + /* Authenticate and create a service. */ + authorizer = create_authorizer (&error); + + if (error != NULL) { + g_printerr ("%s: Error authenticating: %s\n", + argv[0], error->message); + g_error_free (error); + retval = 1; + goto done; + } else if (authorizer == NULL) { + g_printerr ("%s: User chose to abort authentication.\n", + argv[0]); + retval = 1; + goto done; + } + + service = gdata_calendar_service_new (authorizer); + calendar = gdata_calendar_calendar_new (calendar_id); + + /* Create the event to insert. */ + event = gdata_calendar_event_new (NULL); + gdata_entry_set_title (GDATA_ENTRY (event), title); + + start_with_time = g_strconcat (start, "T00:00:00Z", NULL); + end_with_time = g_strconcat (end, "T00:00:00Z", NULL); + + if (g_time_val_from_iso8601 (start, &start_tv) && + g_time_val_from_iso8601 (end, &end_tv)) { + /* Includes time. */ + is_date = FALSE; + } else if (g_time_val_from_iso8601 (start_with_time, &start_tv) && + g_time_val_from_iso8601 (end_with_time, &end_tv)) { + /* Does not include time. */ + is_date = TRUE; + } else { + g_printerr ("%s: Could not parse start time ‘%s’ and end time " + "‘%s’ as ISO 8601.\n", argv[0], start, end); + retval = 1; + goto done; + } + + when = gdata_gd_when_new (start_tv.tv_sec, end_tv.tv_sec, is_date); + gdata_calendar_event_add_time (event, when); + g_object_unref (when); + + for (i = 6; i < argc; i++) { + GDataGDWho *who = NULL; + const gchar *relation_type, *email_address; + + relation_type = GDATA_GD_WHO_EVENT_ATTENDEE; + email_address = argv[i]; + + who = gdata_gd_who_new (relation_type, NULL, email_address); + gdata_calendar_event_add_person (event, who); + g_object_unref (who); + } + + /* Insert the event. */ + inserted_event = gdata_calendar_service_insert_calendar_event (service, + calendar, + event, + NULL, + &error); + + if (error != NULL) { + g_printerr ("%s: Error inserting event: %s\n", + argv[0], error->message); + g_error_free (error); + retval = 1; + goto done; + } + + /* Print results. */ + print_event (inserted_event); + +done: + g_free (start_with_time); + g_free (end_with_time); + g_clear_object (&inserted_event); + g_clear_object (&event); + g_clear_object (&authorizer); + g_clear_object (&calendar); + g_clear_object (&service); + + return retval; +} + +static const struct { + const gchar *command; + int (*handler_fn) (int argc, char **argv); +} command_handlers[] = { + { "calendars", command_calendars }, + { "events", command_events }, + { "insert-event", command_insert_event }, +}; + +int +main (int argc, char *argv[]) +{ + guint i; + gint retval = -1; + + setlocale (LC_ALL, ""); + + if (argc < 2) { + return print_usage (argv); + } + + for (i = 0; i < G_N_ELEMENTS (command_handlers); i++) { + if (strcmp (argv[1], command_handlers[i].command) == 0) { + retval = command_handlers[i].handler_fn (argc, argv); + } + } + + if (retval == -1) { + retval = print_usage (argv); + } + + return retval; +} diff --git a/demos/docs-list/docs-list.c b/demos/docs-list/docs-list.c new file mode 100644 index 0000000..85e0e1e --- /dev/null +++ b/demos/docs-list/docs-list.c @@ -0,0 +1,120 @@ +/* -*- Mode: C; indent-tabs-mode: t; c-basic-offset: 8; tab-width: 8 -*- */ +/* + * GData Client + * Copyright (C) 2014 Debarshi Ray <rishi.is@lostca.se> + * + * GData Client is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * GData Client is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with GData Client. If not, see <http://www.gnu.org/licenses/>. + */ + +/* + * Simple example program to list all documents in the user’s Google Documents + * account, retrieving the account information from GOA. + */ + +#include <gio/gio.h> +#include <glib.h> +#include <locale.h> + +#define GOA_API_IS_SUBJECT_TO_CHANGE +#include <gdata/gdata.h> +#include <goa/goa.h> + +gint +main (void) +{ + GDataDocumentsFeed *feed = NULL; + GDataDocumentsQuery *query = NULL; + GDataDocumentsService *service = NULL; + GError *error = NULL; + GList *accounts = NULL; + GList *entries; + GList *l; + GoaClient *client = NULL; + gint retval; + + setlocale (LC_ALL, ""); + + client = goa_client_new_sync (NULL, &error); + if (error != NULL) { + g_warning ("%s", error->message); + g_error_free (error); + retval = 1; + goto out; + } + + accounts = goa_client_get_accounts (client); + for (l = accounts; l != NULL; l = l->next) { + GoaAccount *account; + GoaObject *object = GOA_OBJECT (l->data); + const gchar *provider_type; + + account = goa_object_peek_account (object); + provider_type = goa_account_get_provider_type (account); + + if (g_strcmp0 (provider_type, "google") == 0) { + GDataGoaAuthorizer *authorizer; + + authorizer = gdata_goa_authorizer_new (object); + service = gdata_documents_service_new (GDATA_AUTHORIZER (authorizer)); + g_object_unref (authorizer); + } + } + + if (service == NULL) { + g_warning ("Account not found"); + retval = 1; + goto out; + } + + query = gdata_documents_query_new_with_limits (NULL, 1, 10); + gdata_documents_query_set_show_folders (query, TRUE); + + while (TRUE) { + feed = gdata_documents_service_query_documents (service, query, NULL, NULL, NULL, &error); + if (error != NULL) { + g_warning ("%s", error->message); + g_error_free (error); + retval = 1; + goto out; + } + + entries = gdata_feed_get_entries (GDATA_FEED (feed)); + if (entries == NULL) { + retval = 0; + goto out; + } + + for (l = entries; l != NULL; l = l->next) { + GDataEntry *entry = GDATA_ENTRY (l->data); + const gchar *title; + + title = gdata_entry_get_title (entry); + g_message ("%s", title); + } + + gdata_query_next_page (GDATA_QUERY (query)); + g_object_unref (feed); + } + + retval = 0; + +out: + g_clear_object (&feed); + g_clear_object (&query); + g_clear_object (&service); + g_clear_object (&client); + g_list_free_full (accounts, g_object_unref); + + return retval; +} diff --git a/demos/docs-property/docs-property.c b/demos/docs-property/docs-property.c new file mode 100644 index 0000000..d4b8f30 --- /dev/null +++ b/demos/docs-property/docs-property.c @@ -0,0 +1,258 @@ +/* -*- Mode: C; indent-tabs-mode: t; c-basic-offset: 8; tab-width: 8 -*- */ +/* + * GData Client + * Copyright (C) 2019 Mayank Sharma <mayank8019@gmail.com> + * + * GData Client is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * GData Client is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with GData Client. If not, see <http://www.gnu.org/licenses/>. + */ + +/* + * Simple example program to fetch a list of all the files from a user's Google Drive, + * then set the documents property and finally remove those set properties. + * + * This program is just meant to show how to set/get/remove GDataDocumentsProperty + * , i.e. the Property Resource on a file. + */ + +#include <gio/gio.h> +#include <glib.h> +#include <locale.h> + +#define GOA_API_IS_SUBJECT_TO_CHANGE +#include <gdata/gdata.h> +#include <goa/goa.h> + +#define SET_DUMMY_PROPERTIES TRUE + +static void print_documents_properties (GDataDocumentsEntry *entry); +static void set_dummy_properties (GDataDocumentsEntry *entry); +static void unset_dummy_properties (GDataDocumentsEntry *entry); +static gboolean is_owner (GDataService *service, GDataEntry *entry); + +static void test_dummy_properties (GDataDocumentsService *service, gboolean set, GCancellable *cancellable, GError **error); + +/* FIXME: Work around https://gitlab.gnome.org/GNOME/gnome-online-accounts/issues/73 */ +typedef GoaObject AutoGoaObject; +G_DEFINE_AUTOPTR_CLEANUP_FUNC(AutoGoaObject, g_object_unref) + +gint +main (void) +{ + g_autoptr(GDataDocumentsService) service = NULL; + g_autoptr(GError) error = NULL; + g_autolist(AutoGoaObject) accounts = NULL; + GList *l = NULL; + g_autoptr(GoaClient) client = NULL; + gint retval = 0; + + setlocale (LC_ALL, ""); + + client = goa_client_new_sync (NULL, &error); + if (error != NULL) { + g_warning ("%s", error->message); + return 1; + } + + accounts = goa_client_get_accounts (client); + for (l = accounts; l != NULL; l = l->next) { + GoaAccount *account; + GoaObject *object = GOA_OBJECT (l->data); + const gchar *provider_type, *account_identity; + + account = goa_object_peek_account (object); + provider_type = goa_account_get_provider_type (account); + account_identity = goa_account_get_identity (account); + + if (g_strcmp0 (provider_type, "google") == 0) { + g_autoptr(GDataGoaAuthorizer) authorizer = NULL; + + authorizer = gdata_goa_authorizer_new (object); + service = gdata_documents_service_new (GDATA_AUTHORIZER (authorizer)); + + if (service == NULL) { + g_warning ("Account not found"); + retval = 1; + continue; + } + + g_message ("Setting dummy properties on the files owned by user - %s", account_identity); + test_dummy_properties (service, SET_DUMMY_PROPERTIES, NULL, &error); + if (error != NULL) { + g_warning ("Error: %s", error->message); + retval = 1; + continue; + } + + g_message ("Removing dummy properties from the files owned by user - %s", account_identity); + test_dummy_properties (service, !SET_DUMMY_PROPERTIES, NULL, &error); + if (error != NULL) { + g_warning ("Error: %s", error->message); + retval = 1; + continue; + } + } + } + + return retval; +} + +static void +test_dummy_properties (GDataDocumentsService *service, gboolean set, GCancellable *cancellable, GError **error) +{ + g_autoptr(GDataDocumentsQuery) query = NULL; + g_autoptr(GDataDocumentsFeed) feed = NULL; + g_autoptr(GError) child_error = NULL; + GList *entries; + GList *l; + + query = gdata_documents_query_new_with_limits (NULL, 1, 10); + gdata_documents_query_set_show_folders (query, TRUE); + + /* Since our query supports fetching 10 results in one go, we just + * perform fetch a single page of query. You can use pagination here + * and call gdata_query_next_page (GDATA_QUERY (query)) inside a while + * loop to set/unset properties on all the files. + * */ + feed = gdata_documents_service_query_documents (service, query, NULL, NULL, NULL, &child_error); + if (child_error != NULL) { + g_propagate_error (error, g_steal_pointer (&child_error)); + return; + } + + entries = gdata_feed_get_entries (GDATA_FEED (feed)); + if (entries == NULL) { + return; + } + + for (l = entries; l != NULL; l = l->next) { + const gchar *title; + g_autoptr(GDataEntry) new_entry = NULL; + GDataEntry *entry = GDATA_ENTRY (l->data); + + title = gdata_entry_get_title (entry); + g_message ("File = %s, id = %s", title, gdata_entry_get_id (GDATA_ENTRY (entry))); + + if (!is_owner (GDATA_SERVICE (service), entry)) { + g_message ("\t**NOT OWNED**"); + continue; + } + + if (set) { + set_dummy_properties (GDATA_DOCUMENTS_ENTRY (entry)); + } else { + unset_dummy_properties (GDATA_DOCUMENTS_ENTRY (entry)); + } + + new_entry = gdata_service_update_entry (GDATA_SERVICE (service), + gdata_documents_service_get_primary_authorization_domain(), + entry, + NULL, + &child_error); + + if (child_error != NULL) { + g_propagate_error (error, g_steal_pointer (&child_error)); + return; + } + + print_documents_properties (GDATA_DOCUMENTS_ENTRY (new_entry)); + } +} + +static gboolean +is_owner (GDataService *service, GDataEntry *entry) { + GList *l; + GDataGoaAuthorizer *goa_authorizer; + GoaAccount *account; + const gchar *account_identity; + + goa_authorizer = GDATA_GOA_AUTHORIZER (gdata_service_get_authorizer (service)); + account = goa_object_peek_account (gdata_goa_authorizer_get_goa_object (goa_authorizer)); + account_identity = goa_account_get_identity (account); + + for (l = gdata_entry_get_authors (entry); l != NULL; l = l->next) { + GDataAuthor *author = GDATA_AUTHOR (l->data); + + if (g_strcmp0 (gdata_author_get_email_address (author), account_identity) == 0) { + return TRUE; + } + } + + return FALSE; +} + +static void +print_documents_properties (GDataDocumentsEntry *entry) +{ + GList *l, *properties; + + g_return_if_fail (GDATA_IS_DOCUMENTS_ENTRY (entry)); + + properties = gdata_documents_entry_get_document_properties (GDATA_DOCUMENTS_ENTRY (entry)); + for (l = properties; l != NULL; l = l->next) { + GDataDocumentsProperty *property = GDATA_DOCUMENTS_PROPERTY (l->data); + + g_message ("\tkey = %s, value = %s, %s", + gdata_documents_property_get_key (GDATA_DOCUMENTS_PROPERTY (property)), + gdata_documents_property_get_value (GDATA_DOCUMENTS_PROPERTY (property)), + gdata_documents_property_get_visibility (GDATA_DOCUMENTS_PROPERTY (property)) + ); + } + +} + +static void +set_dummy_properties (GDataDocumentsEntry *entry) +{ + g_autoptr(GDataDocumentsProperty) p1 = NULL, p2 = NULL, p3 = NULL, p4 = NULL; + + p1 = gdata_documents_property_new ("1"); + gdata_documents_property_set_visibility (p1, GDATA_DOCUMENTS_PROPERTY_VISIBILITY_PUBLIC); + gdata_documents_property_set_value (p1, "ONE"); + gdata_documents_entry_add_documents_property (entry, p1); + + p2 = gdata_documents_property_new ("2"); + gdata_documents_property_set_visibility (p2, GDATA_DOCUMENTS_PROPERTY_VISIBILITY_PRIVATE); + gdata_documents_property_set_value (p2, "TWO"); + gdata_documents_entry_add_documents_property (entry, p2); + + p3 = gdata_documents_property_new ("3"); + gdata_documents_property_set_visibility (p3, GDATA_DOCUMENTS_PROPERTY_VISIBILITY_PUBLIC); + gdata_documents_entry_add_documents_property (entry, p3); + + p4 = gdata_documents_property_new ("4"); + gdata_documents_property_set_visibility (p4, GDATA_DOCUMENTS_PROPERTY_VISIBILITY_PRIVATE); + gdata_documents_entry_add_documents_property (entry, p4); +} + +static void +unset_dummy_properties (GDataDocumentsEntry *entry) +{ + g_autoptr(GDataDocumentsProperty) p1 = NULL, p2 = NULL, p3 = NULL, p4 = NULL; + + p1 = gdata_documents_property_new ("1"); + gdata_documents_property_set_visibility (p1, GDATA_DOCUMENTS_PROPERTY_VISIBILITY_PUBLIC); + gdata_documents_entry_remove_documents_property (entry, p1); + + p2 = gdata_documents_property_new ("2"); + gdata_documents_property_set_visibility (p2, GDATA_DOCUMENTS_PROPERTY_VISIBILITY_PRIVATE); + gdata_documents_entry_remove_documents_property (entry, p2); + + p3 = gdata_documents_property_new ("3"); + gdata_documents_property_set_visibility (p3, GDATA_DOCUMENTS_PROPERTY_VISIBILITY_PUBLIC); + gdata_documents_entry_remove_documents_property (entry, p3); + + p4 = gdata_documents_property_new ("4"); + gdata_documents_property_set_visibility (p4, GDATA_DOCUMENTS_PROPERTY_VISIBILITY_PRIVATE); + gdata_documents_entry_remove_documents_property (entry, p4); +} diff --git a/demos/meson.build b/demos/meson.build new file mode 100644 index 0000000..2d5944e --- /dev/null +++ b/demos/meson.build @@ -0,0 +1,32 @@ +demos_c_args = [ + '-DLIBGDATA_DISABLE_DEPRECATED', +] + +# demos = [subdir, executable name, custom objects (for sources)] +demos = [ + ['calendar', 'calendar-cli', {'sources': 'calendar/calendar-cli.c'}], + ['tasks', 'task-cli', {'sources': 'tasks/tasks-cli.c'}], + ['youtube', 'youtube-cli', {'sources': 'youtube/youtube-cli.c'}], +] + +if enable_goa + demos += [ + ['docs-list', 'docs-list', {'sources': 'docs-list/docs-list.c'}], + ['docs-property', 'docs-property', {'sources': 'docs-property/docs-property.c'}] + ] +endif + +if gtk_dep.found() + demos += [['scrapbook', 'scrapbook', {'sources': 'scrapbook/scrapbook.c', 'dependencies': [gtk_dep]}]] +endif + +foreach demo: demos + kwargs = demo[2] + {'dependencies': [libgdata_dep] + demo[2].get('dependencies', [])} + + executable( + demo[1], + c_args: demos_c_args + common_c_args + ['-DG_LOG_DOMAIN="@0@"'.format(demo[1])], + include_directories: top_inc_dir, + kwargs: kwargs, + ) +endforeach diff --git a/demos/scrapbook/scrapbook.c b/demos/scrapbook/scrapbook.c new file mode 100644 index 0000000..d909ab0 --- /dev/null +++ b/demos/scrapbook/scrapbook.c @@ -0,0 +1,721 @@ +/* -*- Mode: C; indent-tabs-mode: t; c-basic-offset: 8; tab-width: 8 -*- */ +/* + * GData Client + * Copyright (C) Joe Cortes 2010 <escozzia@gmail.com> + * + * GData Client is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * GData Client is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with GData Client. If not, see <http://www.gnu.org/licenses/>. + */ + +/* + * This is an extremely simple example program to query youtube videos + * and picasa pictures and add them to a grid. + * It was coded as part of the 2010 Google Code-In. + * Click on Properties to change the window's title, or authenticate + * yourself (it's assumed that your google and picasa ids are the same) + * It's also possible to upload files to picasa. + * Since this is only an example, intended to serve as documentation, + * it's probably full of bugs and a couple of awful programming practices. + * The program itself is of no practical use, but it does what it is + * meant to do and doesn't segfault randomly (I hope so :p). + */ + +#include "scrapbook.h" + +static void +open_in_web_browser (GtkWidget *widget, gchar *uri) /* quicky wrapper for gtk_show_uri */ +{ + gtk_show_uri_on_window (GTK_WINDOW (gtk_widget_get_toplevel (widget)), uri, GDK_CURRENT_TIME, NULL); +} + +static void +picture_selected (GtkTreeView *tree, GtkTreePath *path, GtkTreeViewColumn *column, ScrapPicSearch *self) +{ + GtkTreeModel *model; + GtkTreeIter iter; + GDataEntry *pic; + GdkPixbuf *thumbnail; + GtkWidget *button; + GtkWidget *image; + + pic = g_slice_new (GDataEntry); + model = gtk_tree_view_get_model (tree); + gtk_tree_model_get_iter (model, &iter, path); + gtk_tree_model_get (model, &iter, COL_PIXBUF, &(thumbnail), P_COL_PIC, &(pic), -1); + gtk_widget_destroy (self->search_data->window); + gtk_list_store_append (self->main_data->lStore, &iter); + gtk_list_store_set (self->main_data->lStore, &iter, + ORIG_COL_PIXBUF, thumbnail, + ORIG_COL_TITLE, gdata_entry_get_title (pic), + ORIG_COL_ENTRY, pic, -1); + if (self->main_data->currentRow[self->main_data->currentCol] > self->main_data->max_rows) { + self->main_data->currentCol++; + self->main_data->currentRow[self->main_data->currentCol] = 0; + } + image = gtk_image_new_from_pixbuf (thumbnail); + button = gtk_button_new (); + self->file = GDATA_PICASAWEB_FILE (pic); + gtk_widget_show (image); + gtk_container_add (GTK_CONTAINER (button), image); + /*g_signal_connect (button, "clicked", G_CALLBACK (open_in_web_browser), gdata_entry_get_id (pic)); + * commented out, I can't seem to find anything that will give me a picture's URI */ + + gtk_grid_attach (GTK_GRID (self->main_data->grid), button, + self->main_data->currentCol, + self->main_data->currentRow[self->main_data->currentCol], + 1, 1); + + gtk_widget_show (button); + self->main_data->currentRow[self->main_data->currentCol]++; +} + + + +static void +video_selected (GtkTreeView *tree, GtkTreePath *path, GtkTreeViewColumn *column, ScrapYTSearch *self) +{ + GtkTreeModel *model; + GtkTreeIter iter; + GDataEntry *video; + GdkPixbuf *thumbnail; + GtkWidget *button; + GtkWidget *image; + video = g_slice_new (GDataEntry); + model = gtk_tree_view_get_model (tree); + gtk_tree_model_get_iter (model, &iter, path); + gtk_tree_model_get (model, &iter, COL_PIXBUF, &(thumbnail), COL_VIDEO, &(video), -1); + gtk_widget_destroy (self->window); + gtk_list_store_append (self->main_data->lStore, &iter); + gtk_list_store_set (self->main_data->lStore, &iter, + ORIG_COL_PIXBUF, thumbnail, + ORIG_COL_TITLE, gdata_entry_get_title (video), + ORIG_COL_ENTRY, video, -1); + if (self->main_data->currentRow[self->main_data->currentCol] > self->main_data->max_rows) { + self->main_data->currentCol++; + self->main_data->currentRow[self->main_data->currentCol] = 0; + } + image = gtk_image_new_from_pixbuf (thumbnail); + button = gtk_button_new (); + gtk_widget_show (image); + gtk_container_add (GTK_CONTAINER (button), image); + g_signal_connect (button, "clicked", G_CALLBACK (open_in_web_browser), + (gpointer) gdata_youtube_video_get_player_uri (GDATA_YOUTUBE_VIDEO (video))); + + gtk_grid_attach (GTK_GRID (self->main_data->grid), button, + self->main_data->currentCol, + self->main_data->currentRow[self->main_data->currentCol], + 1, 1); + + gtk_widget_show (button); + self->main_data->currentRow[self->main_data->currentCol]++; +} + +static void +p_display_tree (ScrapPicSearch *self) +{ + GtkCellRenderer *renderer; + GtkWidget *scrollWin; + scrollWin = gtk_scrolled_window_new (NULL, NULL); + gtk_scrolled_window_set_policy (GTK_SCROLLED_WINDOW(scrollWin), GTK_POLICY_AUTOMATIC, GTK_POLICY_ALWAYS); + + renderer = gtk_cell_renderer_pixbuf_new (); + gtk_tree_view_insert_column_with_attributes (GTK_TREE_VIEW (self->tView), -1, + "", renderer, "pixbuf", + P_COL_PIXBUF, NULL); + + renderer = gtk_cell_renderer_text_new (); + gtk_tree_view_insert_column_with_attributes (GTK_TREE_VIEW (self->tView), -1, + "", renderer, "text", + P_COL_USER, NULL); + + renderer = gtk_cell_renderer_text_new (); + gtk_tree_view_insert_column_with_attributes (GTK_TREE_VIEW (self->tView), -1, + "", renderer, "text", + P_COL_TITLE, NULL); + + gtk_tree_view_set_model (GTK_TREE_VIEW (self->tView), GTK_TREE_MODEL (self->lStore)); + gtk_container_add (GTK_CONTAINER (scrollWin), self->tView); + + g_signal_connect (self->tView, "row-activated", G_CALLBACK (picture_selected), self); + + gtk_widget_show (self->tView); + gtk_widget_show (scrollWin); + gtk_box_pack_start (GTK_BOX(self->search_data->box1), scrollWin, TRUE, TRUE, 2); +} + + +static void +yt_display_tree (ScrapYTSearch *self) +{ + GtkCellRenderer *renderer; + GtkWidget *scrollWin; + scrollWin = gtk_scrolled_window_new (NULL, NULL); + gtk_scrolled_window_set_policy (GTK_SCROLLED_WINDOW(scrollWin), GTK_POLICY_AUTOMATIC, GTK_POLICY_ALWAYS); + renderer = gtk_cell_renderer_pixbuf_new (); + gtk_tree_view_insert_column_with_attributes (GTK_TREE_VIEW (self->tView), -1, + "", renderer, "pixbuf", + COL_PIXBUF, NULL); + renderer = gtk_cell_renderer_text_new (); + gtk_tree_view_insert_column_with_attributes (GTK_TREE_VIEW (self->tView), -1, + "", renderer, "text", + COL_TITLE, NULL); + gtk_tree_view_set_model (GTK_TREE_VIEW (self->tView), GTK_TREE_MODEL (self->lStore)); + gtk_container_add (GTK_CONTAINER (scrollWin), self->tView); + g_signal_connect (self->tView, "row-activated", G_CALLBACK (video_selected), self); + gtk_widget_show (self->tView); + gtk_widget_show (scrollWin); + gtk_box_pack_start (GTK_BOX(self->box1), scrollWin, TRUE, TRUE, 2); +} + +GDataMediaThumbnail * +choose_best_thumbnail (GList *thumbnails, gint ideal_size) +{ + gint delta = G_MININT; + GDataMediaThumbnail *thumbnail = NULL; + for (; thumbnails != NULL; thumbnails = thumbnails->next) { + gint new_delta; + GDataMediaThumbnail *current = (GDataMediaThumbnail *) thumbnails->data; + new_delta = gdata_media_thumbnail_get_width (current) - ideal_size; + if (delta == 0) { + break; + } else if ((delta == G_MININT) + || (delta < 0 && new_delta > delta) + || (delta > 0 && new_delta < delta)) { + delta = new_delta; + thumbnail = current; + } + } + return thumbnail; +} + +static void +find_pictures (GDataEntry *entry, guint entry_key, guint entry_count, ScrapPicSearch *self) +{ + GtkTreeIter iter; + GList *thumbnails; + GDataMediaThumbnail *thumbnail; + GFileInputStream *input_stream; + + gtk_list_store_append (self->lStore, &iter); + gtk_list_store_set (self->lStore, &iter, + P_COL_PIXBUF, NULL, + P_COL_TITLE, self->title, + P_COL_USER, self->user, + P_COL_PIC, entry, -1); + thumbnails = gdata_picasaweb_file_get_thumbnails (GDATA_PICASAWEB_FILE (entry)); + thumbnail = choose_best_thumbnail (thumbnails, THUMBNAIL_WIDTH); + if (thumbnail != NULL) { + GFile *thumbnail_file; + thumbnail_file = g_file_new_for_uri (gdata_media_thumbnail_get_uri (thumbnail)); + input_stream = g_file_read (thumbnail_file, NULL, NULL); + self->thumbnail = gdk_pixbuf_new_from_stream_at_scale (G_INPUT_STREAM (input_stream), THUMBNAIL_WIDTH, -1, + TRUE, NULL, NULL); + gtk_list_store_set (self->lStore, &iter, P_COL_PIXBUF, self->thumbnail, -1); /* we can now set the thumbnail ;) */ + g_object_unref (thumbnail_file); + } + gdata_query_set_q (self->query, NULL); +} + + +static void +p_query_element (GDataEntry *entry, guint entry_key, guint entry_count, ScrapPSearch *self) +{ + GError *error=NULL; + ScrapPicSearch *picture; + GDataFeed *feed; + + picture = self->pic; + picture->title = gdata_entry_get_title (entry); + picture->query = picture->search_data->query; + picture->user = self->user; + gdata_query_set_q (picture->query, picture->title); + feed = gdata_picasaweb_service_query_files (self->main_data->picasaweb_service, GDATA_PICASAWEB_ALBUM (entry), picture->query, NULL, + (GDataQueryProgressCallback) find_pictures, picture, &error); + + if (error != NULL) { + g_print ("whoops, somebody raised an error!\n%s", error->message); + g_error_free (error); + } + + if (feed != NULL) { + g_object_unref (feed); + } +} + +static void +p_text_callback (GtkWidget *widget, ScrapPSearch *self) +{ + GError *error = NULL; + GDataFeed *feed; + + self->user = gtk_entry_get_text (GTK_ENTRY (self->user_entry)); + self->pic->tView = gtk_tree_view_new (); + feed = gdata_picasaweb_service_query_all_albums (self->main_data->picasaweb_service, self->query, self->user, NULL, + (GDataQueryProgressCallback) p_query_element, self, &error); + if (error != NULL) { + g_print ("someone raised an error\n%s\n",error->message); + g_error_free (error); + } + + if (feed != NULL) { + g_object_unref (feed); + } + + p_display_tree (self->pic); +} + + +/* ran as a callback for each individual element queried + * it takes the video found, a unique entry_key and entry_count and the data structure as arguments + * parts of this function were inspired (or simply taken) from the totem youtube plugin */ +static void +yt_query_element (GDataEntry *entry, guint entry_key, guint entry_count, ScrapYTSearch *self) +{ + GtkTreeIter iter; + GList *thumbnails; + GDataMediaThumbnail *thumbnail; + const gchar *title; /* the video's title */ + const gchar *uri; /* the video's URI */ + GFileInputStream *input_stream; /* this will be used to make a pixbuf to store the thumbnail */ + + title = gdata_entry_get_title (entry); /* self-explanatory, I hope */ + uri = gdata_youtube_video_get_player_uri (GDATA_YOUTUBE_VIDEO (entry)); /* ditto */ + g_print ("%s %s", title, uri); + gtk_list_store_append (self->lStore, &iter); /* make a new entry for this vid */ + gtk_list_store_set (self->lStore, &iter, + COL_PIXBUF, NULL, /* this will be set in a few moments */ + COL_TITLE, title, + COL_VIDEO, entry, + -1); + /* get a GList of thumbnails for the vid */ + thumbnails = gdata_youtube_video_get_thumbnails (GDATA_YOUTUBE_VIDEO (entry)); + thumbnail = choose_best_thumbnail (thumbnails, THUMBNAIL_WIDTH); + if (thumbnail != NULL) { + GFile *thumbnail_file; + thumbnail_file = g_file_new_for_uri (gdata_media_thumbnail_get_uri (thumbnail)); + input_stream = g_file_read (thumbnail_file, NULL, NULL); + self->thumbnail = gdk_pixbuf_new_from_stream_at_scale (G_INPUT_STREAM (input_stream), THUMBNAIL_WIDTH, -1, + TRUE, NULL, NULL); + gtk_list_store_set (self->lStore, &iter, COL_PIXBUF, self->thumbnail, -1); /* we can now set the thumbnail ;) */ + g_object_unref (thumbnail_file); + } +} + + +static void +yt_text_callback (GtkWidget *widget, ScrapYTSearch *self) +{ + GDataFeed *feed; + + self->txt = gtk_entry_get_text (GTK_ENTRY (self->txt_entry)); + gdata_query_set_q (self->query, self->txt); /* set the string we'll be searching for in youtube */ + + /* do the actual query, running yt_query_element for each object found */ + feed = gdata_youtube_service_query_videos (self->main_data->youtube_service, self->query, NULL, (GDataQueryProgressCallback) yt_query_element, + self, NULL); + if (feed != NULL) { + g_object_unref (feed); + } + + yt_display_tree (self); /* run yt_display_tree to show the results */ +} + + +static void +start_new_picasa_search (GtkWidget *widget, ScrapData *first) +{ + ScrapPSearch *self; + ScrapPicSearch *picture; + GtkWidget *button, *box2; + + self = first->p_search; + picture = first->pic_search; + picture->search_data = self; + picture->search_data->pic = picture; + picture->main_data = self->main_data; + g_assert (GDATA_IS_PICASAWEB_SERVICE (first->picasaweb_service)); + gtk_list_store_clear (self->pic->lStore); + + self->window = gtk_window_new (GTK_WINDOW_TOPLEVEL); + gtk_window_resize (GTK_WINDOW (self->window), 400, 400); + g_signal_connect (self->window, "destroy", G_CALLBACK (gtk_widget_destroy), NULL); + g_signal_connect_swapped (self->window, "delete-event", G_CALLBACK (gtk_widget_destroy), NULL); + + /* our two boxes */ + + self->box1 = gtk_box_new (GTK_ORIENTATION_VERTICAL, 10); /* this box contains everything in our window */ + gtk_container_add (GTK_CONTAINER (self->window), self->box1); + box2 = gtk_box_new (GTK_ORIENTATION_HORIZONTAL, 2); + + /* search bar */ + + self->user_entry = gtk_entry_new (); + gtk_entry_set_text (GTK_ENTRY (self->user_entry), "User to search for"); + g_signal_connect (self->user_entry, "activate", (GCallback) p_text_callback, self); + gtk_box_pack_start (GTK_BOX(box2), self->user_entry, TRUE, TRUE, 0); + gtk_widget_show (self->user_entry); + + /* Search button */ + button = gtk_button_new_with_mnemonic ("_Search"); + g_signal_connect (button, "clicked", (GCallback) p_text_callback, self); + gtk_box_pack_start (GTK_BOX (box2), button, FALSE, FALSE, 0); + gtk_widget_show (button); + + gtk_box_pack_end (GTK_BOX (self->box1), box2, FALSE, FALSE, 0); /* pack the box with the button and search bar */ + gtk_widget_show (box2); + + gtk_widget_show (self->box1); + gtk_widget_show (self->window); +} + + + +static void +start_new_youtube_search (GtkWidget *widget, ScrapData *first) /* *first is a pointer we use to talk to the main window */ +{ + ScrapYTSearch *self; /* this struct will be used for all the data in the search, if there's time I'll make it into a GObject */ + GtkWidget *button, *box2; + + self = first->yt_search; + + gtk_list_store_clear (self->lStore); /* clear it out */ + self->tView = gtk_tree_view_new (); + /* window stuff */ + self->window = gtk_window_new (GTK_WINDOW_TOPLEVEL); + gtk_window_resize (GTK_WINDOW (self->window), 400, 400); + g_signal_connect (self->window, "destroy", G_CALLBACK (gtk_widget_destroy), NULL); + g_signal_connect_swapped (self->window, "delete-event", G_CALLBACK (gtk_widget_destroy), NULL); + + /* our two boxes */ + + self->box1 = gtk_box_new (GTK_ORIENTATION_VERTICAL, 10); /* this box contains everything in our window */ + gtk_container_add (GTK_CONTAINER (self->window), self->box1); + box2 = gtk_box_new (GTK_ORIENTATION_HORIZONTAL, 2); + + /* search bar */ + + self->txt_entry = gtk_entry_new (); + g_signal_connect (self->txt_entry, "activate", G_CALLBACK (yt_text_callback), self); + gtk_box_pack_start (GTK_BOX (box2), self->txt_entry, TRUE, TRUE, 0); + gtk_widget_show (self->txt_entry); + + /* Search button */ + button = gtk_button_new_with_mnemonic ("_Search"); + g_signal_connect (button, "clicked", (GCallback) yt_text_callback, self); + gtk_box_pack_start (GTK_BOX (box2), button, TRUE, TRUE, 0); + gtk_widget_show (button); + + gtk_box_pack_end (GTK_BOX (self->box1), box2, FALSE, FALSE, 0); /* pack the box with the button and search bar */ + + gtk_widget_show (box2); + gtk_widget_show (self->box1); + gtk_widget_show (self->window); + + + /* everything else is implemented somewhere else */ +} + + +static void +properties_set (GtkWidget *widget, ScrapProps *self) +{ + GDataClientLoginAuthorizer *authorizer; + GList *domains = NULL; /* list of GDataAuthorizationDomains */ + GError *error = NULL; + + /* Get the username and password to use */ + self->main_data->username = g_strdup (gtk_entry_get_text (GTK_ENTRY (self->username_entry))); + self->main_data->password = g_strdup (gtk_entry_get_text (GTK_ENTRY (self->password_entry))); + + /* Domains we need to be authorised for */ + domains = g_list_prepend (domains, gdata_youtube_service_get_primary_authorization_domain ()); + domains = g_list_prepend (domains, gdata_picasaweb_service_get_primary_authorization_domain ()); + + /* Authenticate */ + authorizer = gdata_client_login_authorizer_new_for_authorization_domains (CLIENT_ID, domains); + + gdata_client_login_authorizer_authenticate (authorizer, self->main_data->username, self->main_data->password, NULL, &error); + + if (error != NULL) { /* we show this to the user in case they mistyped their password */ + GtkWidget *label; + + label = gtk_label_new (error->message); + gtk_widget_show (label); + gtk_box_pack_end (GTK_BOX (self->box1), label, FALSE, FALSE, 0); + + g_print ("error\n%s\n", error->message); + + g_error_free (error); + } + + gdata_service_set_authorizer (GDATA_SERVICE (self->main_data->youtube_service), GDATA_AUTHORIZER (authorizer)); + gdata_service_set_authorizer (GDATA_SERVICE (self->main_data->picasaweb_service), GDATA_AUTHORIZER (authorizer)); + + gtk_widget_destroy (self->window); + g_object_unref (authorizer); +} + +static void +properties_show (GtkWidget *widget, ScrapData *first) +{ + ScrapProps *self; + GtkWidget *label, *button, *box2; + + self = g_slice_new (struct _ScrapProps); + self->main_data = first; + self->window = gtk_window_new (GTK_WINDOW_TOPLEVEL); + g_signal_connect (self->window, "destroy", G_CALLBACK (gtk_widget_destroy), NULL); + g_signal_connect (self->window, "delete-event", G_CALLBACK (gtk_widget_destroy), NULL); + + self->box1 = gtk_box_new (GTK_ORIENTATION_VERTICAL, 3); + + /* Username/Password labels box */ + box2 = gtk_box_new (GTK_ORIENTATION_HORIZONTAL, 10); + + label = gtk_label_new ("Username"); + gtk_widget_show (label); + gtk_box_pack_start (GTK_BOX (box2), label, TRUE, TRUE, 0); + + label = gtk_label_new ("Password"); + gtk_widget_show (label); + gtk_box_pack_start (GTK_BOX (box2), label, TRUE, TRUE, 0); + + gtk_widget_show (box2); + gtk_box_pack_start (GTK_BOX (self->box1), box2, FALSE, FALSE, 0); + + /* Username/Password entries box */ + box2 = gtk_box_new (GTK_ORIENTATION_HORIZONTAL, 10); + self->username_entry = gtk_entry_new (); + + if (self->main_data->username != NULL) + gtk_entry_set_text (GTK_ENTRY(self->username_entry), self->main_data->username); + + gtk_widget_show (self->username_entry); + gtk_box_pack_start (GTK_BOX (box2), self->username_entry, TRUE, TRUE, 0); + + self->password_entry = gtk_entry_new (); + gtk_entry_set_visibility (GTK_ENTRY (self->password_entry), FALSE); + + if (self->main_data->password != NULL) + gtk_entry_set_text (GTK_ENTRY(self->password_entry), self->main_data->password); + + gtk_widget_show (self->password_entry); + gtk_box_pack_start (GTK_BOX (box2), self->password_entry, TRUE, TRUE, 0); + + gtk_box_pack_start (GTK_BOX (self->box1), box2, FALSE, FALSE, 0); + gtk_widget_show (box2); + + /* OK button */ + button = gtk_button_new_with_label ("_OK"); + g_signal_connect (button, "clicked", (GCallback) properties_set, self); + gtk_widget_show (button); + gtk_box_pack_start (GTK_BOX (self->box1), button, FALSE, FALSE, 0); + + gtk_widget_show (self->box1); + gtk_container_add (GTK_CONTAINER (self->window), self->box1); + gtk_widget_show (self->window); +} + +static void +select_file (ScrapPUpload *self, GtkFileChooser *file_chooser) +{ + GFile *file; + GError *error = NULL; + GFileInfo *file_info; + GDataUploadStream *upload_stream; + GFileInputStream *file_stream; + + file = gtk_file_chooser_get_file (file_chooser); + + file_info = g_file_query_info (file, G_FILE_ATTRIBUTE_STANDARD_DISPLAY_NAME "," G_FILE_ATTRIBUTE_STANDARD_CONTENT_TYPE, + G_FILE_QUERY_INFO_NONE, NULL, NULL); + + /* upload our file, using the service we've set up, and metadata + * set up in upload () + * no album is specified, but that should be easy to add */ + upload_stream = gdata_picasaweb_service_upload_file (self->main_data->picasaweb_service, NULL /* for now uploading to drop box */, + self->file, g_file_info_get_display_name (file_info), + g_file_info_get_content_type (file_info), NULL, &error); + + g_object_unref (file_info); + g_object_unref (self->file); + self->file = NULL; + + if (error != NULL) { + g_print ("Error: %s\n", error->message); + g_error_free (error); + + g_object_unref (file); + + return; + } + + file_stream = g_file_read (file, NULL, NULL); + g_object_unref (file); + + g_output_stream_splice (G_OUTPUT_STREAM (upload_stream), G_INPUT_STREAM (file_stream), + G_OUTPUT_STREAM_SPLICE_CLOSE_SOURCE | G_OUTPUT_STREAM_SPLICE_CLOSE_TARGET, NULL, NULL); + + self->file = gdata_picasaweb_service_finish_file_upload (self->main_data->picasaweb_service, upload_stream, NULL); + + g_object_unref (file_stream); + g_object_unref (upload_stream); +} + +static void +got_name (GtkWidget *widget, ScrapData *scrap_data) +{ + ScrapPUpload *self; + GtkWidget *file_dialog; + + self = scrap_data->p_upload; + + gdata_entry_set_title (GDATA_ENTRY (self->file), + gtk_entry_get_text (GTK_ENTRY (self->name))); + gdata_entry_set_summary (GDATA_ENTRY (self->file), + gtk_entry_get_text (GTK_ENTRY (self->description))); + gtk_widget_destroy (self->dialog); + + file_dialog = gtk_file_chooser_dialog_new ("Upload Photo", GTK_WINDOW (scrap_data->window), GTK_FILE_CHOOSER_ACTION_SAVE, + "_Cancel", GTK_RESPONSE_CANCEL, + "_Open", GTK_RESPONSE_ACCEPT, + NULL); + + if (gtk_dialog_run (GTK_DIALOG (file_dialog)) == GTK_RESPONSE_ACCEPT) { + select_file (self, GTK_FILE_CHOOSER (file_dialog)); + } + + /* since the upload blocks, it's safe to assume the widget won't + * be destroyed until we're done */ + gtk_widget_destroy (file_dialog); +} + +static void +upload (GtkWidget *widget, ScrapData *first) +{ + ScrapPUpload *self; + GtkWidget *label, *content_area; + label = gtk_label_new ("Enter photo name and description"); + self = first->p_upload; + + /* we make a new file, without an id (it will be assigned automatically later on) */ + self->file = gdata_picasaweb_file_new (NULL); + /* dialog to get the file's name and description */ + self->dialog = gtk_dialog_new(); + content_area = gtk_dialog_get_content_area (GTK_DIALOG (self->dialog)); + + gtk_widget_show (label); + gtk_box_pack_start (GTK_BOX (content_area), label, FALSE, FALSE, 0); + + self->name = gtk_entry_new (); + g_signal_connect (self->name, "activate", G_CALLBACK (got_name), self); + gtk_widget_show (self->name); + gtk_box_pack_start (GTK_BOX (content_area), self->name, TRUE, TRUE, 0); + + self->description = gtk_entry_new (); + g_signal_connect (self->description, "activate", G_CALLBACK (got_name), first); + gtk_widget_show (self->description); + gtk_box_pack_start (GTK_BOX (content_area), self->description, TRUE, TRUE, 0); + + gtk_widget_show (self->dialog); +} + +int +main(int argc, char **argv) +{ + ScrapData *scrapbook; + ScrapPSearch *picasaSearch; + ScrapYTSearch *youtubeSearch; + ScrapPicSearch *photoSearch; + ScrapPUpload *fUpload; + GtkWidget *button; + GtkWidget *vbox; + + scrapbook = g_slice_new (struct _ScrapData); + scrapbook->max_rows = 5; + + gtk_init (&argc, &argv); + + scrapbook->currentCol = 0; + scrapbook->currentRow[scrapbook->currentCol] = 0; + + scrapbook->lStore = gtk_list_store_new (ORIG_N_COLS, GDK_TYPE_PIXBUF, G_TYPE_STRING, GDATA_TYPE_ENTRY); + scrapbook->window = gtk_window_new (GTK_WINDOW_TOPLEVEL); + gtk_window_set_title (GTK_WINDOW (scrapbook->window), "Scrapbook"); + g_signal_connect (scrapbook->window, "destroy", G_CALLBACK (gtk_main_quit), NULL); + g_signal_connect (scrapbook->window, "delete-event", G_CALLBACK (gtk_main_quit), NULL); + + youtubeSearch = g_slice_new (struct _ScrapYTSearch); /* get some memory for the structure */ + youtubeSearch->txt = NULL; + scrapbook->yt_search = youtubeSearch; + youtubeSearch->main_data = scrapbook; + /* create a new query, without any search text, starting at 0, and search only MAX_RESULTS results */ + youtubeSearch->query = gdata_query_new_with_limits (NULL, 0, MAX_RESULTS); + /* create a new youtube service, giving it our developer key; google no longer uses client ids so we send in an empty string (NULL gives an error) */ + scrapbook->youtube_service = gdata_youtube_service_new (DEVELOPER_KEY, NULL); + /* create a new list store and tree to show the user the results + * it has three columns (two of which are displayed): a pixbuf for the thumbnail, the title, and the video data itself (as a gdata generic entry) */ + youtubeSearch->lStore = gtk_list_store_new (N_COLS, GDK_TYPE_PIXBUF, G_TYPE_STRING, GDATA_TYPE_ENTRY); + + picasaSearch = g_slice_new (struct _ScrapPSearch); + scrapbook->p_search = picasaSearch; + picasaSearch->main_data = scrapbook; + picasaSearch->query = gdata_query_new_with_limits (NULL, 0, MAX_RESULTS); + scrapbook->picasaweb_service = gdata_picasaweb_service_new (NULL); + + photoSearch = g_slice_new (struct _ScrapPicSearch); + scrapbook->p_search->pic = photoSearch; + scrapbook->pic_search = photoSearch; + photoSearch->lStore = gtk_list_store_new (P_N_COLS, GDK_TYPE_PIXBUF, G_TYPE_STRING, G_TYPE_STRING, GDATA_TYPE_ENTRY); + + fUpload = g_slice_new (struct _ScrapPUpload); + scrapbook->p_upload = fUpload; + fUpload->main_data = scrapbook; + + scrapbook->box1 = gtk_box_new (GTK_ORIENTATION_HORIZONTAL, 0); + scrapbook->grid = gtk_grid_new (); + + vbox = gtk_box_new (GTK_ORIENTATION_VERTICAL, 2); + + /* Add buttons to the main window */ + button = gtk_button_new_with_mnemonic ("Add YouTube _Video"); + g_signal_connect (button, "clicked", (GCallback) start_new_youtube_search, scrapbook); + gtk_box_pack_start (GTK_BOX (vbox), button, FALSE, FALSE, 0); + gtk_widget_show (button); + + button = gtk_button_new_with_mnemonic ("Add PicasaWeb _Photo"); + g_signal_connect (button, "clicked", (GCallback) start_new_picasa_search, scrapbook); + gtk_box_pack_start (GTK_BOX (vbox), button, FALSE, FALSE, 0); + gtk_widget_show (button); + + button = gtk_button_new_with_mnemonic ("P_roperties"); + g_signal_connect (button, "clicked", (GCallback) properties_show, scrapbook); + gtk_box_pack_start (GTK_BOX (vbox), button, FALSE, FALSE, 0); + gtk_widget_show (button); + + button = gtk_button_new_with_mnemonic ("_Upload Photo to PicasaWeb"); + g_signal_connect (button, "clicked", (GCallback) upload, scrapbook); + gtk_box_pack_start (GTK_BOX (vbox), button, FALSE, FALSE, 0); + gtk_widget_show (button); + + gtk_widget_show (vbox); + gtk_box_pack_start (GTK_BOX (scrapbook->box1), vbox, FALSE, FALSE, 5); + + gtk_box_pack_start (GTK_BOX (scrapbook->box1), scrapbook->grid, TRUE, TRUE, 0); + gtk_widget_show (scrapbook->grid); + gtk_widget_show (scrapbook->box1); + gtk_container_add (GTK_CONTAINER (scrapbook->window), scrapbook->box1); + gtk_widget_show (scrapbook->window); + gtk_main (); + return 0; +} diff --git a/demos/scrapbook/scrapbook.h b/demos/scrapbook/scrapbook.h new file mode 100644 index 0000000..802e736 --- /dev/null +++ b/demos/scrapbook/scrapbook.h @@ -0,0 +1,188 @@ +/* -*- Mode: C; indent-tabs-mode: t; c-basic-offset: 8; tab-width: 8 -*- */ +/* + * GData Client + * Copyright (C) Joe Cortes 2010 <escozzia@gmail.com> + * + * GData Client is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * GData Client is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with GData Client. If not, see <http://www.gnu.org/licenses/>. + */ + +#include <stdio.h> +#include <stdlib.h> +#include <gtk/gtk.h> +#include <gdata/gdata.h> +#include <glib.h> +#include <glib-object.h> +#define DEVELOPER_KEY "AI39si5MkSF-0bzTmP5WETk1D-Z7inHaQJzX13PeG_5Uzeu8mz3vo40cFoqnxjejB-UqzYFrqzOSlsqJvHuPNEGqdycqnPo30A" +#define CLIENT_ID "ytapi-GNOME-libgdata-444fubtt-0" +#define THUMBNAIL_WIDTH 180 +#define MAX_RESULTS 10 + +/* how this works is that there's a struct for every window opened + * they contain that individual window's data + * and every one of them (except for scrap data, which is for the main window) + * has a pointer to the one for the main window called main_data */ + +enum { + COL_PIXBUF, + COL_TITLE, + COL_VIDEO, + N_COLS +}; + +enum { + P_COL_PIXBUF, + P_COL_TITLE, + P_COL_USER, + P_COL_PIC, + P_N_COLS +}; + + +enum { + ORIG_COL_PIXBUF, + ORIG_COL_TITLE, + ORIG_COL_ENTRY, + ORIG_N_COLS +}; + +typedef struct _ScrapYTSearch ScrapYTSearch; +typedef struct _ScrapPSearch ScrapPSearch; +typedef struct _ScrapPUpload ScrapPUpload; +typedef struct _ScrapPicSearch ScrapPicSearch; + +typedef struct _ScrapData { + GtkWidget *window; + gint currentCol; + gint currentRow[5]; + GtkWidget *box1; + GtkWidget *grid; + GtkWidget *scrollWindow; + ScrapYTSearch *yt_search; + ScrapPSearch *p_search; + ScrapPicSearch *pic_search; + ScrapPUpload *p_upload; + gint max_rows; + gchar *username; + gchar *password; + GtkListStore *lStore; + + GDataYouTubeService *youtube_service; + GDataPicasaWebService *picasaweb_service; +} ScrapData; +struct _ScrapPUpload { + ScrapData *main_data; + GDataPicasaWebFile *file; + GtkWidget *dialog; + GtkWidget *name; + GtkWidget *description; +}; + +struct _ScrapPicSearch { /* for finding pictures */ + const gchar *title; + gchar *uri; + const gchar *user; + GdkPixbuf *thumbnail; + ScrapData *main_data; + ScrapPSearch *search_data; + GDataQuery *query; + GDataPicasaWebFile *file; + GtkListStore *lStore; + GtkWidget *tView; +}; + +struct _ScrapYTSearch { /* youtube search data */ + GtkWidget *txt_entry; + const gchar *txt; + GtkWidget *window; + GDataQuery *query; + gchar *title; + gchar *uri; + GdkPixbuf *thumbnail; + GtkWidget *box1; + ScrapData *main_data; /* <- points to a structure containing main vars */ + GtkListStore *lStore; + GtkWidget *tView; +}; + +struct _ScrapPSearch { /* for finding albums */ + GtkWidget *window; + GDataQuery *query; + gchar *title; + gchar *uri; + GdkPixbuf *thumbnail; + GtkWidget *box1; + ScrapData *main_data; + GtkWidget *user_entry; + const gchar *user; + ScrapPicSearch *pic; +}; + +typedef struct _ScrapProps { + GtkWidget *window; + GtkWidget *box1; + GtkWidget *username_entry, *password_entry; + ScrapData *main_data; +} ScrapProps; + + +static void +open_in_web_browser (GtkWidget *widget, gchar *uri); + +static void +picture_selected (GtkTreeView *tree, GtkTreePath *path, GtkTreeViewColumn *column, ScrapPicSearch *self); + +static void +video_selected (GtkTreeView *tree, GtkTreePath *path, GtkTreeViewColumn *column, ScrapYTSearch *self); + +static void +p_display_tree (ScrapPicSearch *self); + +static void +yt_display_tree (ScrapYTSearch *self); + +GDataMediaThumbnail * +choose_best_thumbnail (GList *thumbnails, gint ideal_size); + +static void +find_pictures (GDataEntry *entry, guint entry_key, guint entry_count, ScrapPicSearch *self); + +static void +p_query_element (GDataEntry *entry, guint entry_key, guint entry_count, ScrapPSearch *self); + +static void +p_text_callback (GtkWidget *widget, ScrapPSearch *self); + +static void +yt_query_element (GDataEntry *entry, guint entry_key, guint entry_count, ScrapYTSearch *self); + +static void +yt_text_callback (GtkWidget *widget, ScrapYTSearch *self); + +static void +start_new_picasa_search (GtkWidget *widget, ScrapData *first); + +static void +start_new_youtube_search (GtkWidget *widget, ScrapData *first); + +static void +properties_set (GtkWidget *widget, ScrapProps *self); + +static void +properties_show (GtkWidget *widget, ScrapData *first); + +static void +upload (GtkWidget *widget, ScrapData *first); + + + diff --git a/demos/tasks/tasks-cli.c b/demos/tasks/tasks-cli.c new file mode 100644 index 0000000..c795761 --- /dev/null +++ b/demos/tasks/tasks-cli.c @@ -0,0 +1,350 @@ +/* -*- Mode: C; indent-tabs-mode: t; c-basic-offset: 8; tab-width: 8 -*- */ +/* + * GData Client + * Copyright © 2017 Philip Withnall <philip@tecnocode.co.uk> + * + * GData Client is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * GData Client is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with GData Client. If not, see <http://www.gnu.org/licenses/>. + */ + +#include <gdata/gdata.h> +#include <locale.h> +#include <string.h> + +#define CLIENT_ID "1074795795536-necvslvs0pchk65nf6ju4i6mniogg8fr.apps.googleusercontent.com" +#define CLIENT_SECRET "8totRi50eo2Zfr3SD2DeNAzo" +#define REDIRECT_URI "urn:ietf:wg:oauth:2.0:oob" + +static int +print_usage (char *argv[]) +{ + g_printerr ("%s: Usage — %s <subcommand>\n" + "Subcommands:\n" + " tasklists\n" + " tasks <tasklist ID> [query string]\n", + argv[0], argv[0]); + return -1; +} + +static void +print_tasklist (GDataTasksTasklist *tasklist) +{ + const gchar *id, *title, *description; + + id = gdata_entry_get_id (GDATA_ENTRY (tasklist)); + title = gdata_entry_get_title (GDATA_ENTRY (tasklist)); + description = gdata_entry_get_summary (GDATA_ENTRY (tasklist)); + + g_print ("%s — %s\n", id, title); + g_print (" Description:\n %s\n", description); + + g_print ("\n"); +} + +static const gchar * +format_status (const gchar *status) +{ + if (g_strcmp0 (status, GDATA_TASKS_STATUS_NEEDS_ACTION) == 0) + return "needs action"; + else if (g_strcmp0 (status, GDATA_TASKS_STATUS_COMPLETED) == 0) + return "completed"; + else + return status; +} + +static void +print_task (GDataTasksTask *task) +{ + const gchar *title, *id, *description, *parent_id, *position, *notes; + const gchar *status; + GTimeVal date_published_tv = { 0, }; + gchar *date_published = NULL; /* owned */ + GTimeVal due_tv = { 0, }; + gchar *due = NULL; /* owned */ + GTimeVal completed_tv = { 0, }; + gchar *completed = NULL; /* owned */ + gboolean is_deleted, is_hidden; + + title = gdata_entry_get_title (GDATA_ENTRY (task)); + id = gdata_entry_get_id (GDATA_ENTRY (task)); + description = gdata_entry_get_content (GDATA_ENTRY (task)); + date_published_tv.tv_sec = gdata_entry_get_published (GDATA_ENTRY (task)); + date_published = g_time_val_to_iso8601 (&date_published_tv); + parent_id = gdata_tasks_task_get_parent (task); + position = gdata_tasks_task_get_position (task); + notes = gdata_tasks_task_get_notes (task); + status = gdata_tasks_task_get_status (task); + due_tv.tv_sec = gdata_tasks_task_get_due (task); + due = g_time_val_to_iso8601 (&due_tv); + completed_tv.tv_sec = gdata_tasks_task_get_completed (task); + completed = g_time_val_to_iso8601 (&completed_tv); + is_deleted = gdata_tasks_task_is_deleted (task); + is_hidden = gdata_tasks_task_is_hidden (task); + + g_print ("%s — %s\n", id, title); + g_print (" Published: %s\n", date_published_tv.tv_sec != 0 ? date_published : "unknown"); + g_print (" Status: %s\n", format_status (status)); + g_print (" Due: %s\n", due_tv.tv_sec != 0 ? due : "not set"); + g_print (" Completed: %s\n", completed_tv.tv_sec != 0 ? completed : "not yet"); + g_print (" Deleted? %s\n", is_deleted ? "Yes" : "No"); + g_print (" Hidden? %s\n", is_hidden ? "Yes" : "No"); + g_print (" Position: %s\n", position); + g_print (" Parent ID: %s\n", parent_id); + g_print (" Description:\n %s\n", description); + g_print (" Notes:\n %s\n", notes); + + g_print ("\n"); + + g_free (completed); + g_free (due); + g_free (date_published); +} + +/* FIXME: Factor all this code out of all the demos */ +static GDataAuthorizer * +create_authorizer (GError **error) +{ + GDataOAuth2Authorizer *authorizer = NULL; /* owned */ + gchar *uri = NULL; + gchar code[100]; + GError *child_error = NULL; + + /* Go through the interactive OAuth dance. */ + authorizer = gdata_oauth2_authorizer_new (CLIENT_ID, CLIENT_SECRET, + REDIRECT_URI, + GDATA_TYPE_TASKS_SERVICE); + + /* Get an authentication URI */ + uri = gdata_oauth2_authorizer_build_authentication_uri (authorizer, + NULL, FALSE); + + /* Wait for the user to retrieve and enter the verifier. */ + g_print ("Please navigate to the following URI and grant access:\n" + " %s\n", uri); + g_print ("Enter verifier (EOF to abort): "); + + g_free (uri); + + if (scanf ("%100s", code) != 1) { + /* User chose to abort. */ + g_print ("\n"); + g_clear_object (&authorizer); + return NULL; + } + + /* Authorise the token. */ + gdata_oauth2_authorizer_request_authorization (authorizer, code, NULL, + &child_error); + + if (child_error != NULL) { + g_propagate_error (error, child_error); + g_clear_object (&authorizer); + return NULL; + } + + return GDATA_AUTHORIZER (authorizer); +} + +/* List all the user’s task-lists. */ +static int +command_tasklists (int argc, char *argv[]) +{ + GDataTasksService *service = NULL; + GDataTasksQuery *query = NULL; + GDataFeed *feed = NULL; + GList/*<unowned GDataTasksTasklist>*/ *entries; + GError *error = NULL; + gint retval = 0; + GDataAuthorizer *authorizer = NULL; + + if (argc != 2) { + return print_usage (argv); + } + + /* Authenticate and create a service. */ + authorizer = create_authorizer (&error); + + if (error != NULL) { + g_printerr ("%s: Error authenticating: %s\n", + argv[0], error->message); + g_error_free (error); + retval = 1; + goto done; + } else if (authorizer == NULL) { + g_printerr ("%s: User chose to abort authentication.\n", + argv[0]); + retval = 1; + goto done; + } + + service = gdata_tasks_service_new (authorizer); + query = gdata_tasks_query_new (NULL); + + feed = gdata_tasks_service_query_all_tasklists (service, + GDATA_QUERY (query), + NULL, NULL, + NULL, + &error); + + if (error != NULL) { + g_printerr ("%s: Error querying tasklists: %s\n", + argv[0], error->message); + g_error_free (error); + retval = 1; + goto done; + } + + /* Print results. */ + for (entries = gdata_feed_get_entries (feed); entries != NULL; + entries = entries->next) { + GDataTasksTasklist *tasklist; + + tasklist = GDATA_TASKS_TASKLIST (entries->data); + print_tasklist (tasklist); + } + + g_print ("Total of %u results.\n", + g_list_length (gdata_feed_get_entries (feed))); + +done: + g_clear_object (&feed); + g_clear_object (&query); + g_clear_object (&authorizer); + g_clear_object (&service); + + return retval; +} + +/* Query the tasks in a tasklist. */ +static int +command_tasks (int argc, char *argv[]) +{ + GDataTasksService *service = NULL; + GDataTasksTasklist *tasklist = NULL; + GDataTasksQuery *query = NULL; + GError *error = NULL; + gint retval = 0; + const gchar *query_string, *tasklist_id; + GDataAuthorizer *authorizer = NULL; + guint n_results; + + if (argc < 3) { + return print_usage (argv); + } + + tasklist_id = argv[2]; + query_string = (argc > 3) ? argv[3] : NULL; + + /* Authenticate and create a service. */ + authorizer = create_authorizer (&error); + + if (error != NULL) { + g_printerr ("%s: Error authenticating: %s\n", + argv[0], error->message); + g_error_free (error); + retval = 1; + goto done; + } else if (authorizer == NULL) { + g_printerr ("%s: User chose to abort authentication.\n", + argv[0]); + retval = 1; + goto done; + } + + service = gdata_tasks_service_new (authorizer); + query = gdata_tasks_query_new (query_string); + gdata_query_set_max_results (GDATA_QUERY (query), 10); + tasklist = gdata_tasks_tasklist_new (tasklist_id); + n_results = 0; + + while (TRUE) { + GList/*<unowned GDataTasksTask>*/ *entries, *l; + GDataFeed *feed = NULL; + + feed = gdata_tasks_service_query_tasks (service, tasklist, + GDATA_QUERY (query), + NULL, NULL, NULL, + &error); + + if (error != NULL) { + g_printerr ("%s: Error querying tasks: %s\n", + argv[0], error->message); + g_error_free (error); + retval = 1; + goto done; + } + + /* Print results. */ + entries = gdata_feed_get_entries (feed); + + if (entries == NULL) { + retval = 0; + g_object_unref (feed); + break; + } + + for (l = entries; l != NULL; l = l->next) { + GDataTasksTask *task; + + task = GDATA_TASKS_TASK (l->data); + print_task (task); + n_results++; + } + + gdata_query_next_page (GDATA_QUERY (query)); + g_object_unref (feed); + } + + g_print ("Total of %u results.\n", n_results); + +done: + g_clear_object (&query); + g_clear_object (&authorizer); + g_clear_object (&tasklist); + g_clear_object (&service); + + return retval; +} + +static const struct { + const gchar *command; + int (*handler_fn) (int argc, char **argv); +} command_handlers[] = { + { "tasklists", command_tasklists }, + { "tasks", command_tasks }, +}; + +int +main (int argc, char *argv[]) +{ + guint i; + gint retval = -1; + + setlocale (LC_ALL, ""); + + if (argc < 2) { + return print_usage (argv); + } + + for (i = 0; i < G_N_ELEMENTS (command_handlers); i++) { + if (strcmp (argv[1], command_handlers[i].command) == 0) { + retval = command_handlers[i].handler_fn (argc, argv); + } + } + + if (retval == -1) { + retval = print_usage (argv); + } + + return retval; +} diff --git a/demos/youtube/youtube-cli.c b/demos/youtube/youtube-cli.c new file mode 100644 index 0000000..37ff4af --- /dev/null +++ b/demos/youtube/youtube-cli.c @@ -0,0 +1,585 @@ +/* -*- Mode: C; indent-tabs-mode: t; c-basic-offset: 8; tab-width: 8 -*- */ +/* + * GData Client + * Copyright (C) 2015 Philip Withnall <philip@tecnocode.co.uk> + * + * GData Client is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * GData Client is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with GData Client. If not, see <http://www.gnu.org/licenses/>. + */ + +#include <gdata/gdata.h> +#include <locale.h> +#include <string.h> + +#define CLIENT_ID "1074795795536-necvslvs0pchk65nf6ju4i6mniogg8fr.apps.googleusercontent.com" +#define CLIENT_SECRET "8totRi50eo2Zfr3SD2DeNAzo" +#define REDIRECT_URI "urn:ietf:wg:oauth:2.0:oob" +#define DEVELOPER_KEY "AIzaSyCENhl8yDxDZbyhTF6p-ok-RefK07xdXUg" + +static int +print_usage (char *argv[]) +{ + g_printerr ("%s: Usage — %s <subcommand>\n" + "Subcommands:\n" + " search <query string>\n" + " info <video ID>\n" + " standard-feed <feed name>\n" + " categories\n" + " related <video ID>\n" + " upload <filename> <title> [description]\n", + argv[0], argv[0]); + return -1; +} + +static void +print_video (GDataYouTubeVideo *video) +{ + const gchar *title, *player_uri, *id, *description; + GList/*<unowned GDataMediaThumbnail>*/ *thumbnails; + GTimeVal date_published_tv = { 0, }; + gchar *date_published = NULL; /* owned */ + guint duration; /* seconds */ + guint rating_min = 0, rating_max = 0, rating_count = 0; + gdouble rating_average = 0.0; + + title = gdata_entry_get_title (GDATA_ENTRY (video)); + player_uri = gdata_youtube_video_get_player_uri (video); + id = gdata_entry_get_id (GDATA_ENTRY (video)); + description = gdata_youtube_video_get_description (video); + thumbnails = gdata_youtube_video_get_thumbnails (video); + date_published_tv.tv_sec = gdata_entry_get_published (GDATA_ENTRY (video)); + date_published = g_time_val_to_iso8601 (&date_published_tv); + duration = gdata_youtube_video_get_duration (video); + gdata_youtube_video_get_rating (video, &rating_min, &rating_max, + &rating_count, &rating_average); + + g_print ("%s — %s\n", player_uri, title); + g_print (" ID: %s\n", id); + g_print (" Published: %s\n", date_published); + g_print (" Duration: %us\n", duration); + g_print (" Rating: %.2f (min: %u, max: %u, count: %u)\n", + rating_average, rating_min, rating_max, rating_count); + g_print (" Description:\n %s\n", description); + g_print (" Thumbnails:\n"); + + for (; thumbnails != NULL; thumbnails = thumbnails->next) { + GDataMediaThumbnail *thumbnail; + + thumbnail = GDATA_MEDIA_THUMBNAIL (thumbnails->data); + g_print (" • %s\n", + gdata_media_thumbnail_get_uri (thumbnail)); + } + + g_print ("\n"); + + g_free (date_published); +} + +static void +print_category (GDataCategory *category) +{ + const gchar *term, *label; + + term = gdata_category_get_term (category); + label = gdata_category_get_label (category); + + g_print ("%s — %s\n", term, label); +} + +static GDataAuthorizer * +create_authorizer (GError **error) +{ + GDataOAuth2Authorizer *authorizer = NULL; /* owned */ + gchar *uri = NULL; + gchar code[100]; + GError *child_error = NULL; + + /* Go through the interactive OAuth dance. */ + authorizer = gdata_oauth2_authorizer_new (CLIENT_ID, CLIENT_SECRET, + REDIRECT_URI, + GDATA_TYPE_YOUTUBE_SERVICE); + + /* Get an authentication URI */ + uri = gdata_oauth2_authorizer_build_authentication_uri (authorizer, + NULL, FALSE); + + /* Wait for the user to retrieve and enter the verifier. */ + g_print ("Please navigate to the following URI and grant access:\n" + " %s\n", uri); + g_print ("Enter verifier (EOF to abort): "); + + g_free (uri); + + if (scanf ("%100s", code) != 1) { + /* User chose to abort. */ + g_print ("\n"); + g_clear_object (&authorizer); + return NULL; + } + + /* Authorise the token. */ + gdata_oauth2_authorizer_request_authorization (authorizer, code, NULL, + &child_error); + + if (child_error != NULL) { + g_propagate_error (error, child_error); + g_clear_object (&authorizer); + return NULL; + } + + return GDATA_AUTHORIZER (authorizer); +} + +/* Search for videos given a simple query string. */ +static int +command_search (int argc, char *argv[]) +{ + GDataYouTubeService *service = NULL; + GDataYouTubeQuery *query = NULL; + GDataFeed *feed = NULL; + GList/*<unowned GDataYouTubeVideo>*/ *entries; + GError *error = NULL; + gint retval = 0; + const gchar *query_string; + + if (argc < 3) { + return print_usage (argv); + } + + query_string = argv[2]; + + service = gdata_youtube_service_new (DEVELOPER_KEY, NULL); + query = gdata_youtube_query_new (query_string); + feed = gdata_youtube_service_query_videos (service, GDATA_QUERY (query), + NULL, NULL, NULL, &error); + + if (error != NULL) { + g_printerr ("%s: Error querying YouTube: %s\n", + argv[0], error->message); + g_error_free (error); + retval = 1; + goto done; + } + + /* Print results. */ + for (entries = gdata_feed_get_entries (feed); entries != NULL; + entries = entries->next) { + GDataYouTubeVideo *video; + + video = GDATA_YOUTUBE_VIDEO (entries->data); + print_video (video); + } + + g_print ("Total of %u results.\n", gdata_feed_get_total_results (feed)); + +done: + g_clear_object (&feed); + g_clear_object (&query); + g_clear_object (&service); + + return retval; +} + +/* Display information about a single video. */ +static int +command_info (int argc, char *argv[]) +{ + GDataYouTubeService *service = NULL; + GDataEntry *result = NULL; + GDataYouTubeVideo *video; /* unowned */ + GError *error = NULL; + gint retval = 0; + const gchar *entry_id; + + if (argc < 3) { + return print_usage (argv); + } + + entry_id = argv[2]; + + service = gdata_youtube_service_new (DEVELOPER_KEY, NULL); + result = gdata_service_query_single_entry (GDATA_SERVICE (service), + NULL, entry_id, NULL, + GDATA_TYPE_YOUTUBE_VIDEO, + NULL, &error); + + if (error != NULL) { + g_printerr ("%s: Error querying YouTube: %s\n", + argv[0], error->message); + g_error_free (error); + retval = 1; + goto done; + } + + /* Print results. */ + video = GDATA_YOUTUBE_VIDEO (result); + print_video (video); + +done: + g_clear_object (&result); + g_clear_object (&service); + + return retval; +} + +static gboolean +standard_feed_type_from_name (const gchar *name, + GDataYouTubeStandardFeedType *out) +{ + /* Indexed by GDataYouTubeStandardFeedType. */ + const gchar *feed_type_names[] = { + "top-rated", + "top-favorites", + "most-viewed", + "most-popular", + "most-recent", + "most-discussed", + "most-linked", + "most-responded", + "recently-featured", + "watch-on-mobile", + }; + guint i; + + G_STATIC_ASSERT (G_N_ELEMENTS (feed_type_names) == + GDATA_YOUTUBE_WATCH_ON_MOBILE_FEED + 1); + + for (i = 0; i < G_N_ELEMENTS (feed_type_names); i++) { + if (g_strcmp0 (feed_type_names[i], name) == 0) { + *out = (GDataYouTubeStandardFeedType) i; + return TRUE; + } + } + + return FALSE; +} + +/* List all videos in a standard feed. */ +static int +command_standard_feed (int argc, char *argv[]) +{ + GDataYouTubeService *service = NULL; + GDataFeed *feed = NULL; + GList/*<unowned GDataYouTubeVideo>*/ *entries; + GError *error = NULL; + gint retval = 0; + GDataYouTubeStandardFeedType feed_type; + + if (argc < 3) { + return print_usage (argv); + } + + if (!standard_feed_type_from_name (argv[2], &feed_type)) { + g_printerr ("%s: Invalid feed type ‘%s’.\n", argv[0], argv[2]); + retval = 1; + goto done; + } + + service = gdata_youtube_service_new (DEVELOPER_KEY, NULL); + feed = gdata_youtube_service_query_standard_feed (service, feed_type, + NULL, NULL, NULL, + NULL, &error); + + if (error != NULL) { + g_printerr ("%s: Error querying YouTube: %s\n", + argv[0], error->message); + g_error_free (error); + retval = 1; + goto done; + } + + /* Print results. */ + for (entries = gdata_feed_get_entries (feed); entries != NULL; + entries = entries->next) { + GDataYouTubeVideo *video; + + video = GDATA_YOUTUBE_VIDEO (entries->data); + print_video (video); + } + + g_print ("Total of %u results.\n", gdata_feed_get_total_results (feed)); + +done: + g_clear_object (&feed); + g_clear_object (&service); + + return retval; +} + +/* List videos related to a given one. */ +static int +command_related (int argc, char *argv[]) +{ + GDataYouTubeService *service = NULL; + GDataFeed *feed = NULL; + GList/*<unowned GDataYouTubeVideo>*/ *entries; + GError *error = NULL; + gint retval = 0; + const gchar *entry_id; + GDataYouTubeVideo *query_video = NULL; + + if (argc < 3) { + return print_usage (argv); + } + + entry_id = argv[2]; + query_video = gdata_youtube_video_new (entry_id); + + service = gdata_youtube_service_new (DEVELOPER_KEY, NULL); + feed = gdata_youtube_service_query_related (service, query_video, NULL, + NULL, NULL, NULL, &error); + + if (error != NULL) { + g_printerr ("%s: Error querying YouTube: %s\n", + argv[0], error->message); + g_error_free (error); + retval = 1; + goto done; + } + + /* Print results. */ + for (entries = gdata_feed_get_entries (feed); entries != NULL; + entries = entries->next) { + GDataYouTubeVideo *video; + + video = GDATA_YOUTUBE_VIDEO (entries->data); + print_video (video); + } + + g_print ("Total of %u results.\n", gdata_feed_get_total_results (feed)); + +done: + g_clear_object (&query_video); + g_clear_object (&feed); + g_clear_object (&service); + + return retval; +} + +/* List all available video categories. */ +static int +command_categories (int argc, char *argv[]) +{ + GDataYouTubeService *service = NULL; + GDataAPPCategories *app_categories = NULL; + GList/*<unowned GDataCategory>*/ *categories; + GError *error = NULL; + gint retval = 0; + + service = gdata_youtube_service_new (DEVELOPER_KEY, NULL); + app_categories = gdata_youtube_service_get_categories (service, NULL, + &error); + + if (error != NULL) { + g_printerr ("%s: Error querying YouTube: %s\n", + argv[0], error->message); + g_error_free (error); + retval = 1; + goto done; + } + + /* Print results. */ + for (categories = gdata_app_categories_get_categories (app_categories); + categories != NULL; + categories = categories->next) { + GDataCategory *category; + + category = GDATA_CATEGORY (categories->data); + print_category (category); + } + + g_print ("Total of %u results.\n", + g_list_length (gdata_app_categories_get_categories (app_categories))); + +done: + g_clear_object (&app_categories); + g_clear_object (&service); + + return retval; +} + +/* Upload a video. */ +static int +command_upload (int argc, char *argv[]) +{ + GDataYouTubeService *service = NULL; + GDataUploadStream *upload_stream = NULL; + GError *error = NULL; + gint retval = 0; + const gchar *filename; + GFile *video_file = NULL; + GFileInputStream *video_file_stream = NULL; + GFileInfo *video_file_info = NULL; + GDataYouTubeVideo *video = NULL; + GDataYouTubeVideo *uploaded_video = NULL; + gssize transfer_size; + const gchar *content_type, *slug; + GDataAuthorizer *authorizer = NULL; + const gchar *title, *description; + + if (argc < 3) { + return print_usage (argv); + } + + filename = argv[2]; + title = (argc > 3) ? argv[3] : NULL; + description = (argc > 4) ? argv[4] : NULL; + + /* Load the file and query its details. */ + video_file = g_file_new_for_commandline_arg (filename); + + video_file_info = g_file_query_info (video_file, + G_FILE_ATTRIBUTE_STANDARD_CONTENT_TYPE "," + G_FILE_ATTRIBUTE_STANDARD_DISPLAY_NAME, + G_FILE_QUERY_INFO_NONE, NULL, + &error); + + if (error != NULL) { + g_printerr ("%s: Error loading video information ‘%s’: %s\n", + argv[0], filename, error->message); + g_error_free (error); + retval = 1; + goto done; + } + + content_type = g_file_info_get_content_type (video_file_info); + slug = g_file_info_get_display_name (video_file_info); + + video_file_stream = g_file_read (video_file, NULL, &error); + + if (error != NULL) { + g_printerr ("%s: Error loading video ‘%s’: %s\n", + argv[0], filename, error->message); + g_error_free (error); + retval = 1; + goto done; + } + + /* Build the video. */ + video = gdata_youtube_video_new (NULL); + gdata_entry_set_title (GDATA_ENTRY (video), title); + gdata_entry_set_summary (GDATA_ENTRY (video), description); + + /* Authenticate and create a service. */ + authorizer = create_authorizer (&error); + + if (error != NULL) { + g_printerr ("%s: Error authenticating: %s\n", + argv[0], error->message); + g_error_free (error); + retval = 1; + goto done; + } else if (authorizer == NULL) { + g_printerr ("%s: User chose to abort authentication.\n", + argv[0]); + retval = 1; + goto done; + } + + service = gdata_youtube_service_new (DEVELOPER_KEY, + GDATA_AUTHORIZER (authorizer)); + + /* Start the upload. */ + upload_stream = gdata_youtube_service_upload_video (service, video, + slug, content_type, + NULL, &error); + + if (error != NULL) { + g_printerr ("%s: Error initializing upload with YouTube: %s\n", + argv[0], error->message); + g_error_free (error); + retval = 1; + goto done; + } + + /* Upload the video */ + transfer_size = g_output_stream_splice (G_OUTPUT_STREAM (upload_stream), + G_INPUT_STREAM (video_file_stream), + G_OUTPUT_STREAM_SPLICE_CLOSE_SOURCE | + G_OUTPUT_STREAM_SPLICE_CLOSE_TARGET, + NULL, &error); + + if (error != NULL) { + g_printerr ("%s: Error transferring file: %s\n", + argv[0], error->message); + g_error_free (error); + retval = 1; + goto done; + } + + /* Finish off the upload */ + uploaded_video = gdata_youtube_service_finish_video_upload (service, + upload_stream, + &error); + + if (error != NULL) { + g_printerr ("%s: Error finishing upload with YouTube: %s\n", + argv[0], error->message); + g_error_free (error); + retval = 1; + goto done; + } + + /* Print the uploaded video as confirmation. */ + g_print ("Uploaded %" G_GSSIZE_FORMAT " bytes.\n", transfer_size); + print_video (uploaded_video); + +done: + g_clear_object (&authorizer); + g_clear_object (&uploaded_video); + g_clear_object (&video); + g_clear_object (&video_file_info); + g_clear_object (&video_file_stream); + g_clear_object (&video_file); + g_clear_object (&upload_stream); + g_clear_object (&service); + + return retval; +} + +static const struct { + const gchar *command; + int (*handler_fn) (int argc, char **argv); +} command_handlers[] = { + { "search", command_search }, + { "info", command_info }, + { "standard-feed", command_standard_feed }, + { "categories", command_categories }, + { "related", command_related }, + { "upload", command_upload }, +}; + +int +main (int argc, char *argv[]) +{ + guint i; + gint retval = -1; + + setlocale (LC_ALL, ""); + + if (argc < 2) { + return print_usage (argv); + } + + for (i = 0; i < G_N_ELEMENTS (command_handlers); i++) { + if (strcmp (argv[1], command_handlers[i].command) == 0) { + retval = command_handlers[i].handler_fn (argc, argv); + } + } + + if (retval == -1) { + retval = print_usage (argv); + } + + return retval; +} diff --git a/docs/reference/cancellation.dia b/docs/reference/cancellation.dia new file mode 100644 index 0000000000000000000000000000000000000000..3595787616fab51beb6ef884c3b7d13fd803b289 GIT binary patch literal 1273 zcmV<V1P1#biwFP!000021MON%lj1fIzVj<wo+~RX8H2sE%+_wIQaPlOLpEnh*up4l zBuW-AT=Lt~elP<z=4DJRS$k@rklSDD)t|m@`1JX89vLg9VlKtV#K<xYCVUxi5su8i zzy12bH9x;}J_Ve9g#S>{xdBgzIQcX(XId{l_Im5}8bzC!YN=4fmndeve`yra9vJn^ zmyTiV0t8gkq%CiyS}Q(TYGw#JXCre${qLcYOA(lvRc`0YNGfARqmlVEO)s;T!}RuW zj$kin$R>)>@72&2T%LCg^n$4(?0g|(4kmiDD4A5?B(FO*xm65CB7AxJ(tpajlsCL% z9qMSM6FsLY<f7~c<|fJ}f*_X=0+Zo*u4fJVL%f}n%iT@x>n^&lJ9S@oJRUEk(u#6j zb~%wUVpL>awOX?4{lq?vV2d3aR*g|ixz_ST|EDyH&ly10{1$DOMsBEha6EALEGkge zJkYc8YeUnOp>G;OU-6hvB6g_vT<Dv@Z*Bu$T%DA?-yg5J8#1)Y;~{XF!<@^Hhj7UQ z7N6K=`!*Fwv)rtAYSxQ(=T1!4R5+|t7ZKesmBW91Kc<a*fpf+&sIU2I`)OxR<m4ab z>wK_(X(|G$0^@`6I~VZOn+O33!h@0dr?o#@#qj|e5MgP$7V>RRd0mW)!!MIZ74~FO zgjUddD#D0m@GkP4F1FBM;NfTDA&jvL9+7QZ-gRz$Da4qGARWW`BP-u0*AHDR=l-JT z`cRl&0t#aqQ>Em(2+Y9UZIH(i6QQ1!*KEs=7INykNLjd!hpaJ+gEIo-t9(5W7r1U* zU>mk=gMoob5*Z%6JQEvP5F`X%ubljd&Bwk}qO6>6GosYNiG{6&J!3qa>1uFt9ri@3 zfT`145?k4Y`<{jI0AJ}Yp27Y<keZ#=owo>tZ|qg?L;}tufz*x!x7i~CJIHpkLxK$K zX9DloNzaI(?Ox|sCsT1k5fyBzmNZQv_v{MU<{wP2rTU&7=v;3qa?c}ztxEk%p$|Du z+Knll^JoM8qarqqSZ@+#0pyoG`WuT@Omm;^o`0A3pcIt{gU7Y@uYNtJ`<t<HLn1=3 zUC-0Liak>5u&jEHAV&<voE=`ygQxp(fqzJ&UKSv$v`f`O<4gifv={_4@J(Ebw(T8b z1`L(&PA$`;*?7MT3b8D{3!oSBV1-h)>nmliS)okeuj``05Z<3Lh=QRt1chJ|Yls`y z%HA=l4AQ~-fs}HrsnVykGI45yHz${Oozxc0*XI+&X%mWb`J;b>jKXU;p&*|9Mj+&_ z1hPN41Ic#FAT5LZ<P74}Wf0OVgODPFc=u!wa*9E`mO)wu`AHb0qLwqL%OEatnl0wo z$n&s`lWGq3T=JYbM6QJ&pp^3^-UxrDq>#(FBNt53Bnxc|I!zaJ(oF(>G4}pn6&><8 z6`k7<)UbAvgu8CDRTkGBI$Z}19O9%!77VG&18~zXRQN24Qby{4hxE&21J<L%0|qWN zY{r(U8ZSNL?f{Yg&}l2r4e=Dd3s1Q>_)@G%p2B@JNQh~G`Uy`FjBM9+AC0GsEl+g- z!Vpp$Emz(3YqBA-TCRF@uJUS^jRuW!6@i=&gQnVYm5VHwI1i_(W;6zhGT3wq!)w{8 jX?B85*|O6Q#ZKAh^yjNDoxR_;zI6Tr(VtJ&12X^snYC&D literal 0 HcmV?d00001 diff --git a/docs/reference/cancellation.png b/docs/reference/cancellation.png new file mode 100644 index 0000000000000000000000000000000000000000..62b8d44344a4994889f99ea6be0e7276d4e2b04b GIT binary patch literal 7849 zcma)h2UwF`w`Bmuh|(l<5dunYB7%yv&^yw5mEL>rp$iBKktTvbKm-J&H<hL!y(rQI z3?)G55c(Xy|IW<++?o5_`#z9BlK144z1LoA?RZUf1yT|Q5(orBs-!5Z1%VJ8fWO0_ zgy1nv+D`*K5qTk$bf8e^)V#)T@b6W3MMEzL<jT<BUxLQO<va-Fma3Ahw2pty#!Qe7 zmHs(oi;>cBhb5IFey6&KH$_elX0y#%U0`6Yqxqghj?&nC1xLf<DBgzRs}2m#Rn|xp zz;f$#)%N+yMI<EXro?GIRG{#c7Hm;sk!C?2oq0^1dZv97yoyB5pB(XIPB-r6Hlp0V zJY8a>k*0uxDN!W}`hh2i>Se8#A|8Hz+bRQbadD%RRZcFhdCx}f^xl^Qgb-fZLjNf7 zkYiyXA+6gtJRan1FZQ_2wlr2%4Nps-A=bn#z96r9Hct2U_O?7BfP4poS>k4zX>Z)P z!N6ej<Vn6JCkY9O|Kr)W3Mt>2Xd#g2;V`#X{n?^n=SR!gA}-Z6H8Rk~rY3d{4grG? z5ctcCjHQi@{>AM}grC#ys9@LDhAWxNYO1SST3aWbeWj$N92~fC%K4hkzdn8&9!~AU z9OLmYYHB$0*VNSF;v&<{o8ZoOx@C_ZJ=&8iXnvTkeBb4lF!H$+%Wu!d%*;$9W-KEE z11lTbQE*#SRL4?(c5`zx*B2s)Af(WrXza%iT3T8G^R}ElT@DU3qp0i0`g#-!)rZ+3 zWfUnfZwlPUMqME{GB$2)X_+WDj-~DH>PpYZprNMzhS>ohfAHV|3vyv`(b&j{n}^5A z(GiQq`mX=X7oeNzH#9V)rlDa)7HXB6@Lz0okk{(P$H!MySEni77BFjR2)j6cEgr=A zcP<13_9sWnd6WpZxweg(I}#Bx6rH1J4N639ZLR;&OtYVhvokc(-qjVH8n|`Hq^zhY zy2~mZg<3>EeE86+itg}@4)=KLd=D&JTXZNmp<R%Zho?ipw9&I`a?;S;9|EzZb7&Jq z<zERKa&>n0_V5@E*+1T2<Kp51tJf*jX>D!wY&1C=d3D!%i-;dJH9j6q0p@v0x}mw* z>0oQApD~h!kdSaoJCfz4a#5QFr-;J4iV8CLA1pQ@uc@(d{!ZaM0pt~d`WW4(;bD)3 z&Uh5R=}1Uvem<O=oBQtFC#<PopH{E0J7X)llbQOgs=%wlv<Y2SG>N);dhF@SMOvk* z?4y4CW^+phyfkuK(0nY`@$_R;lMyeC_LZv;IxI^U;}U**G3;#3TqF0<`0Q*l#k<nd z$yz6UUteE4J39@Hl-%6hq$D*pwf?q{laiCF`udcFgkRM*iL$KHP+c7z9ew?4(O=@? z;>wNd>+0%Qk>Ipk=i1bon%erWMkA1#Ha0~#Zq`)$gZ0T~-wo`_ioLzPqPlu=ax$(b z6#}_V@O**vo^|)LmX?;BoE*Q|fY?5adY*(S`-{uO#7#|2#l^+l-Q7F>E#NzB`ZD$> zbpr#NVq;_T@|aP5q~zpoj*bXuu6R&Jzim)pAo$$x-@nt+ZjAWsy9`WDK7_+9v16r# z5x;jZeMU|;PoH}G_{4Wvxw&nA`t(U+E*1ijVM+{VxDSDR(%j;@1%c3A(|Qbn2+|aS z1GeB*+y-wLJYOJygjcb2WoOzd`GsJ9lk!o`G5Z@weSp_kxNnE}_-6<vzKWo)0jZlw zx|@d63=Vr^;O|dFXq!mM(nVAgv2YSD@rqAg$c_3V{1UCrW3Q!W+1ZS!zNEy&we|H* zf$<+d6l7(8PEKBp{(?jzD=PR~PJdQe4-5=|Jq248OUA@%T41cG<wup}^6S^HiT8$V zFp{I-P-o}&i2Nba{jpMQGcz+2e$?Qyg1r31_;{&Uqwhu*$h-3LjX&RBjQjB4xuIlW zK$qQru)X~d1k;=Tgm@~B;=;n`ZBJMDzhZWh7)6um@5OY?`v(O{2J9eN#Pp7PeX*_; zXmroS1P#1%-u=PNfg%;u$9Mi%vPW|Mj<A}zj~bEA1JC(&VioLYQg7u%&}mUI#MIbG zNhP4Kk$(ewj`0i#32AL_zo>JW+EVda`fk|dU5dyrDJ$DOJe+F_5tF8<G;f!OVlWuW zOYn5%Jn^97W+aQsc2o9{GZi&;t^c-Frs~A(>@6CaI-5S48BMq8hKNLBQDI?ZbhMnT zY>8NWa<Z$7%f|Zpv*hI05+O~tr~YrXi&g1!U@2=Rdb+x)ZH_DavT}0KNaWbq7{#S0 zW@gFF<KlY9=k{D83PzckER5a>TVtHIln!}?UNM2J!<ll0SI}XL4n`ebb=RSa+url= z;dk}wE2SOk6tXfhQMI)`Mn+kx>>UED{P3?@Ew1`lk;2QE(hgjWXRGUJ)Qg2!yX}w= znfH|%BM)W7Q;&1xj>**Xh%Dv*8SnwE8{JIc+A;P+qHF<=e#KK;+hj&jeooGkH*ci; zuJ)^ylwRw-c8M@T>Vx;HR;Ft4RLB0>kEqDV^^J|A;Pca?U5_WKs`bJxuBY-$bWx>= zn=jfNhxj#V=g<;*A+E_flHipJ#a|q&Ir;Ze!McRDej7y2KQ=zT3Tlh+TKOW$I?U&1 zM@Pr*&Q4Z#HZ89~c%n3xKfmVc{YRHEq~#`+jFP#FLt!0_c!^btwY3-C1A7nu8R*Y% zgSh`a&;f2{YIu0~=g(I;IW3+T<-&HdAYENub#--peN=7j{p|j_>go|wgcp^gH%Tv} zQKQ+tbCAk1v1Ifi?$_@-gGrLz{b$PuWD8!&#m&lA3wQX|?V-2^&IQvZqDjj1%C++7 zUn<^a4&EY2>8Yu&pKI`7YYWeBX?ZLt_`GLv^4Bl*EaBCGT(Kq<Xtmehm}x4oooVu6 zO^xfr1p52meCR1F3JzUIK|z5Z#YjQ%JR>7UA#=|J9%^E2EEaUI{<*y%h9!<e<2A2Y zivcIh^TAC~(Rz@A-QDtRzWJ@KA!o<?WMpJF$$ENv6he}a6ICOAzUkgxm!xmszP)u6 zERmO&nOR!vGb4?LY9v|Fq#h_evMb@Zk!vU$=uYhWRL!!XKZAf^e_@rIpa0<SP@g-U zP2mgqEFs%xUc#vB>SKUESW72dfk3(=ss5sn!GA)bs3$s+w!T$9FRH&gE**C>5C;w! zEOidm1|7Oe<fUwWQBzW)B#AcRuP-d@oc54T5Y55pM0OwViVEtShkBD*{DGMoju{+! zp<;0c#%%yiLGh)bp%J-%|Guc`=5*sdNl9~ll*TK;h)@o82A02oHzd%|nS@4jAW8uG z)YtzQ92^8pr5ARneK#8y;#Al*v7eqN;e&no_U+rmL=|c2&w$eOJfpt{%Jk`JaQV3d zP4N#t9knWl@`bU&wXAFX+{<__pFgnl28UZx<rP~KtK=U8y9jQsB`1?TA}V(~<a2ya zinyCqXtQutociEoU2U#X!k$(9cfIS($m2R}kA#H8u^!ypaY8b1@2f1)C9YYE!t^&j ziREiNlDRKmj*X7icrB{~y0I};zu5DFU2O!L7it+eBZNK{DL2kBGLIkotWeY2cr4+T z@b%>Vv$<u0F)T^DY}lJ|9<p_VQF{A?nfjb65oniv+Jp-SU$F*Sbfhs~&O9|_M(avQ zMS*e6?7zNtEd9;)iq^}#?pjr5iQqU2M|=BEDGEspMdOlZU-pddMOlqDb(Qih5587U z_xkc2rhyicSY`Ka*5XblCIyR*U~+myq*is3ac_b+-%#Jwv_ALatI)jG)ojKr&V=<f zm2I%laznQQf=C4YSwZE`rlwQjP-P0FR%vI-wjb`Td=dg0FUxugNQ7~j-Es74t)_Dz zMS}LBc3zMIb8atwPt>wgij6Ae{(doE7}(Y(u^*M@8cIq5M>|EzMc9pv^ghhW536H^ zlv`@5syTv|2xVnucX#)^*8Pj{7bEo~4*h{t5tYU#a^_Y0=RX#U&0m?VVa20FTpaYz zS8=sTNu-Dsu+RPg*u_IFWd8`0v-JCHM-gzfsC&IXxi|E6r@JYSv$u2fNSBz;Te*qx z?!^CD6Kqc4IHCNo{g&w8-HLuk`b$_Y)v0D^#>vm`aQLl4*bxTBo&K(_?%?<5sD>iS z)X~S`Ar)dDh}4>X6y_h;y>Y-TQ500ViuIe@3?a~k&6L*VZqy<7*HW(%L$!j#a>e{A zii+fJ-vD6W+1Xiw0`=tIn1O|iTjZ;IcF8FzgUy?5Yin!GVHcq-f^2MW%gR)EX@Y`+ zt`HM1IDlG`^ZdD>4^}5a%Kd1^CQ78dxguZ{w_oz)t&osV+xfARm{>C)Bn=G@rbimS zf~eMFXRse>WhbqbBvK0#jV007{{e94=TC!MDYTT7`R5-ibh!OCXOsHc%p2V27rGLK z#ct;^8a<<P3Mnf@ql5hY@kd7<jni9OTgAofRHPIy;WZC5wSw{CRm8=_dH+E`hyYl8 zj%WDGOz<#r2;|x2|BkZ!z2iUN<-fi`o)!8fF3-J2^^!Co>)Q3H-=0QMUAKsl;CQCP z&6J}^_iVuYPNBawXL@f*NlElIS|OIcG94fh^!jtf>dVX3%(MGY0zd^w2IJiYiHKzM z&CF)SHd}T($R$^thQ`K(LE#6AMW)F3t+@Zzr<s|v-gKU^en3CpmX?-&_#h}L8CGH! zkgiNkON&ZPeWImRaPDGdDtWpk<K?wG-RK4Hi;@5ofzRk;Np0;ukPXMbboBHx($jMv z2YB{n@IA*QZGnh6oC|AjY&?>@IMQHNyK3<=A%O&l5#$i_1zsT<VTp5pHat4IJFLJA zN8*FeH6+huXKq{=Ippzu7DQ!d_u1A^B7mX-IZ|XFaB|=>Ed+;0G~F4}GBB{Wvx}uj zNJ`Qz)fr2IcQLvt+65dRna<p*e*8vWvfUa?z(O;W14<aWUuq6?iwpu`)*iaCx=PQ$ z@JJ{0X(mft&>;@Uz?Xx|b1eb)K>Zpp;!bzm$Bxg1p75diawWss40uI+ax9==OO6iP zFJ>ku8y!ZAsW{X>81O!F!YnPt#K!u0d#h#&-Qnc?Iwno#1Fp%*Ns?$*5s`!MnfKV_ zhaQZ&?uarKH@nYAt}0CE9BfS44GjS5P7}6H7!J!D+{EET?6uA?0%3Rk#$>K%_v6;r z3j_S;wS(JXG&BR*qLt<4E`X~i(h3wGee1e$ieF5b3pt$mn#%T9U;#ezs0@(B%hzaN zFxUezv9O(Q9Dsq2Nk_s90d3{uE3c~Z02Jj%g=tMyResIH>L^<B9B&=TqE}(^5a>wl zD-Xv&<v|w}wFd0kE`84g3%E&!-t@U1*nT++H`kt`kx*{dnl+$wSEUAICvpgUb^8gf zS%R^?zW&OUD{RQ_6y}S$i}N3Q!x8!Dj~`)qZP}7x61gdvtE;PQ^3N=)40@887?E4A z@&W%CAE$<c@KbFxnY9a2+?Hp+9x=Vm#K7B$vR3Q@zHZ9j<Lr}35S3R`O9E6`b8wSx zU`J0+Pfkwm_!qB91I3Qm8>L)~wUyOgZDY_Oe_~hUsjIM0201x7+Vv{etm0Iii?vi} z&%x$gyYr+FkX)70mX`TIo&52W(spntt*qRvu^ZgG?|*Wz0hk-S{ZPTi27|mxb=(q3 z-{yMX%*{=pJTW6CQsOXLN$eUi!S@nrsbxCEzbJv<lmAzR{Et%l|H_t_Znvb!&wIOr zk{s;pSz;ugq|8J1$ARkWXX@G_<ho`5Lb(VC-lb$h!RIFYqJGd0vO<3;S0FcI$(cp` zVBv6(Zim=$9xsKvHvyFV0q($i!<z3*mo1?DC?_063>UtM`u{JSY!$b=y1IC2%Ft-L zEm2Ykq@(u&jR$%6vdapjbLL$DWe}nj6l`vM+y_JrIMu_s;N7GEqA$PiNkAZba{^ov zzyug8c>*Zf_ugJd7Z=_3;8VN@NNbU7KAJ>rZS53h$@5srQ|U9u&`@AV$oTn*N*t!8 zr(=K%Vp~H*NT{r$;=ve=sB#!(|Az;zEiP*7=pa#H7iWh?Ngf=_gLz?_t%u!7jIn>~ zdEB#Se|C=m>B|;%!{KmxqHHr6u0iE55O}WDip+H=5hQ%_G;N{%{CEx1htkNC2wDGG zMNd!fZwXX#-uWJScX<$`X-n{tCvLj&?%lhCuf?^|W59gq>Fj*QaGyl7^?%@jXbQ_i zXF%dk*4X_ckh(fM4GayHZl}=-m`%5bg@Hk_wuNQdAAb}yJDo|Sfj9|(M*8n#sS~>b zPw{u9Da8D6d%L@A&`6fJm>6Owr?rnCg)>#<PaQG6>A*F)B>nZNkg@R;SUuIH?Y&iP zq^64tpR3m)&Xkc6SQ9`P81ha49DtG@Gb~~*PUbGQb^t9#Y8o2ShX!JLsewU|Fs?MU z*bSTpuhC;)QVUSw<e;GRz7nJObQ1uVEHwS)%U5F0E$uELR<hmNwzsx`qbCKGQ&5l$ zJ3j>l9|})Z^ad09{{6ehV)y0Cm#JYe7UV>Q>B&a@+`-<SNsIrsU;D`nNSLur8sHOr zCT}ot)z_y*D6*zfT$;z>Do!Q}rs%vpJ-?6x?|}kQQBi>}1?t+Yz|9AHV5H~=!j8^X zRzqVDY-L$lS(jCn0dKdB(wKP@z|&<62A~lz&MYRYZJ_zjpHtjQLFML#0ARx7{jswE zN&e-mJd682JWL7KF*QxfTY!?fxLI3AQ3ReG@R=Eyn^(G4Hame6s7k&i?$}A4!q#?i zezLT*)RV$Ydx7nYrvlE67AFj-BamsPrlu1U6V4)2y}cyxPOB>5b%A|51K>c-qo;Z3 z>gL7_bT81l@v@N=?@CHE(Z40)WedRUH-FWZ0nQB!ATZ3MN56&+KzssQ@O-CFK$lw= zh~UprS3ImoOo`rTu(y`IEi6R#VczL*zh#6J|Mhj+LV|$%;_m*zGCp*+B>;%GtYz0n zVq$>1zj*x`7znrM=)Nv)JG;1WsAYLC4=_zjv8Fz|`A~?RUA{G;O?&nqegML8_Vee6 zj(I#D|2SYr*4(-r<1h2?8qM0yj$^-0aq42t{KC`E&#q<?=y4?tjh>|a4F(q89h1km zFyZ0hv$JOXcL2G5m`f~}7J;2unN|JhS4_0LaH5p2dGnFC;_VyrE#lzJr>9LG@o1f; zu8hvixVX9Hp-^_6O`moQofG`r-5&%UykAO_(5L@&JFYnr=5|wYn+U;=Vg~o0sol<% zbyFpX+S~J1Q0M`N%QkWOlRZG<sYWj}C|gFez*t~r-u(TWg#xNqZZtkToUc_{td<=^ zaRYh@py9p0m)FjpZw(>A!KZGayV(N+>d2u|ZS<EfU$#6$4t4Ek%ko#zd7+-3p2t0s z=lQjd`S|*$rm}k$uU?A0qmoh5PB7A>@CPU)Bk6a8giPXr!knCnGxLC{A`$tIUW1}p zPQ5?#VWhHyl$SiV<7mBR5by_&f_9+r^3bl=&y^_1Vy)fW!sfqR-WQkc=(NiV@dcz5 zz%iY$fO|Ek(~pWXY*}R+ej$<Q3Yk5BN=gb)ncxDo(4hM1w`3+U@S|s7u(G)+kglwd zd^7$ZnES^z0rT;8b*-qW**!Zsl#u~+%L_buNCMajmM~{c1$=N2;2=O7=1@HRc;Ae4 zI^`GOSA)Qj08Cc;FjgDbcCOP6^Yin-3ZSE+s<G^d0aJn_7Zw&67#R~262J${S_AJp zj&YW=Bqk<$kOR+Sy3WPe&~VZ%?8F#3)abRW_ue4Cji9TySJ|m6BO{}*uyABVi<z0Z z(5oW>1HE>wrmhauqU)B{)@&3|;7q$0<lVLIo^1_M3hlOYKX11Pzwb2h%KB!1H=)KD z;He;F0Jgn*$Gsn)1<Yk&i2~Qhc<IldxGt;6b)6VcmdDHV&07Njt?~ubkx9&V@8ICC z11^T(#Fc5zmF43OfCb0T&kxqVc5f##lJHiFg61q+!G70`&?fugf<eiP92RIa;`8G6 zE%Cs@Nh!ZgMK^=0n|N7LI`^AoS0w4c-g<fpofB$Noqk|81?6<&c<ZZ9$}RDPxHv&S z*dN>eEMRA6y!?A1Q7r+xF)Ywv{VRw#7HE-{Qj@E_J!hM$i16QQZ!qlK%fkb}I#9QW zmxsC~o8y`)>gwl!pPikaDvEjoqXG<r5-@+K^A2RzY4#ZGFz&e#s5Kxu1Al*tc>kUk zuxl>uV$FJUV8td-^MH`KHp8gLt6*mK8jVIbzO{%1le{Gnj6Xj+A&EwC!q~wDd=CG| zGa27ix9{A!BP}g0l<5qqjDbOcL1pnKu;wY2l`3O(Gwh<dveM1nT`-iJCee^r&(JXQ zSd3HkP<8>3g|xJ^tgNgr9UY(=gFZ)fbu|Kkkbg!OA&e^nibpDBCN?!MPtp%(B9Yhb zv!+*$Vqjn>C@A0ul+%8gm60(!GBPsro*ipaknC0?EJXSppGm{k3k`{*?H=Yqpg|nR zxy$u^^o3VqsJ$rTWt+?$AW?vzu20pI=LMtHaqV<_7e7_4zM5KCeB(VxVA#ilg)JPy zPeE5^=WU9Fqk{t+ieOEhZt_WFftoC>fXa?l2W^J*bZUtyb&Af&%h%S|*VSJ?E_D?I zwh?fmxnK#$$H(7ZaB$qYvpT@Dp9U5NvYh#WyA;nD2t4EvP&^*j@zb244xqN==jY?+ zlJzUiKoM}bTw2=*Os0okO9sZqi@L&$D>x=;im;QZxzp2A0Kb4n4#)nI{hg3?-t4uU ze5})~$*HQY?h1;yS9$)+1umfng?NIeM_gvy=?mA8+oQm!@mZSyz5qXJZGPV4&sWNp z$3VLbF7F<le*do8@)Vfhz(m1sr?M$fAc~5Lu;nYW`qHTjS0hU*DnbGK@!j}UMD60} z$ld15&cedN$49!_t{}^!Sl%xldP)c1J3rZc;cDu)>HRmvpD&!078es=tjS9@TC=Ne z@9*zZQc{AR0U}=z4$m(uOT_ymzkcY|-QS<ohXD<q(spKhCnw_?+ayg+K(4B)sz7+n zoC9SCDj0C<SmLzN>Hz@(9*rOZnCa;afqotxwRUn!q*ws9GuiS;kxEwBRhXqovu}T2 zU*E)pF92nuxhPUQnpX=1Oc}u)B!&2MfG!{>Km`@G=c79Rz%1u52f(Y%e;dS7K|_Q8 zA#TRsGB`L`MMcHN#s+jXOigD1HjZuF=efSfGXl~djE(U;iXmm(y8jdkFV*2j^=(JH zdVd+xAEFD-hq@YA)&U~7`Limj55rKG6+i1<qC&97k8ayj+kJOm4a+mKXBup4FJ~q7 z360N>@3$2b6Ek+^BE!Sn_=}qgVwyfy;yke`bHbHIY^|*Q4T5{r!o(I|hg(-^A%#b~ z(?p3)un$X~(^?^`**e^yha;5v{_R_tdgEX@BP*){SyrIUfnxG+Y)c%xUaoi@bRVtW z!8A-s{5NM?nV6W8l9IlC`vw4377BU^|LV&um?xK)l{JT))VbD!b`I!Kf|C*v`D+1! zQrOWKjesLcfK+-T2m#bq74PFDFE0-~Tm#;Ng9Ebb*LBd=$f2BvUSQ*9Lk>;N&F4U^ zSd6wCd~H)R`TF(i$F~F?JZLB^l&#nJ&$b5_xt-lIh;&deNiGqVD+|Fa0pqW!f=1GP z-vDC&<m7}WUAeqK{gdZ(v!7e{GkQ22espxSlzdqb+1?)J;o+gA6kl0c*=S8~ri%aT zc7zA~%g<m~uek##=FLCaGN51M{2Bdk4I6jEYb-yerml&qMn;TGP5mQM6t}}oq@^Q1 xUrvEQXo$5Q55<Iuc1%Bk5Hox-w<HoiW0s%as}#+uWCIg~D9NeIRv;`Q{};b4Q-%Nl literal 0 HcmV?d00001 diff --git a/docs/reference/data-flow.dia b/docs/reference/data-flow.dia new file mode 100644 index 0000000000000000000000000000000000000000..9b1155bcf7144927c7e791a21c5035e3f6b3fe6e GIT binary patch literal 1657 zcmV-<28Q_`iwFP!000021MOVha+^35zRy!I^wyD)#BW`v)9!9}?{;?Ez4pjPw%KCv zfSklPoqd{puzix1fYvq!I|k&GRGtY5M4Tgu^BsNXL&=-BkE>9-r%4*b(O8GT&@~#( zVn2u$WBspBA8uX!?cL2AKOnF9*CHV+jo%Ta;%uxh8C$;|4j&#KK)6i_ixUtA8<5iB z7ZQeK$QupyyBkg0H{cUS#I@ooVJr!z8%DK=tms&ulG*1)5^o}3&s!DkW^ouN+C2%! z`m1^N(T9bZ;enkKw%24qrwJvW>rET{<9SU?uW3>?yIRL-z?-n``lv~b9dX=iQ?yEX zqiAvW>Ye#2?^1DLXRE5CwNBWIB#R(A_QU5U%qIc?7a_za!}46ua7+h&os-MmO|R=N zyso?Cy6%E>vW^p$kboV#oW^lTNtAnK$%Z!flg>!UL+sSBT8v^IFczQb|D1&BQwES< z{)V<ok-JC&|1@w9TGUv12z<7jJW86b-1=6M_4^<VrXj8BeGswE%x}9fUw%4S_TJsz zG8%GgwabI=Qj1!bFAs}N;M4R>m>ssMv9v6j4bRPbx!qGICcji#tTPuO+0vvi|9-bj zYsCXDGS1#C#M8g&j1|NC$VlXq#Mf@M_wl2?V;!7x1pZk6-8h_{@_@K8p81aEXB~eF zB4iDm@_3K4MV;;Gv}`)zohQ*Eq=k7Cc-Fw?hmmOj!x|uQZ03-LbTyg9Np#EzIvG%A zKg$}&gZh>++Vp)%gT<1aFpirU4<bG#lS33%;Lt(dd^T_9B3;H0lM0%7eht0EOa5>t z3GstXdSaf=SkEu!Kx&LE*cMq353odJK_rkR4x<cH9At8V)qFfp0hS{XS8`!Ry{Tu@ zmjEjO9n17gY#D-jyN*R~vD+=yKG8?E2R2xM4YdZF4Xl9)ESZ3_fMp`##lR!z0Ml~B ziPtc4nV5+)G_BO8E{L+a_Mly<1pY`9KIJuK@Coi%SBS(Bt8yo<Yjd&+!Y%I=iBerl z*;bGoo>cQ&f1}|&Wx<T>bFs^NaD@1Za5jKz9DdApP7fpSR1`YMYUiq)bZTW6!)WJ- z*Q<+YMXR4DjW(-_QsY#yQN@=p!^M5pr7|*hT|rNS+brhUd&YQ{NsmDG^*7p*=cOV% zS)8r;+U~bw-90V@N=7?j8n^?dfuMY<VeGgDr}fgwM$;iFwxQU@X|`c@!Zr|+O*d>S z^ODmIY-T5Ypc_Ah0bfxR-M9+f5MikJMnCxmmdrQaC9?{?VRgYb<R(8?5Dt@<SR;sw z7`K|PMo~1Ok)L({qCr(QX<TB?HoOFz_(95tIivN<;;q?`nneDDBuV^mB9c){)02=! zi&M19XgWJP7iWmulRb2SM|>0v75BpG+5vZs<r*$yw*|8|fTlzwbMqKLYziPl&vdyr z;M(^0PhvFfj}1+>&&XojV;Xb&J`R2PTm}N{9e!j}84-m5!u<l^CGZ%dKRl)rDZ^>~ zI&uJ!%%V#03Mh^vSLhhL$dddvvhjGHB4gOSl`)9#%!#XHj5bTZ+ZJq=Ses?ic(LRQ z9|j)Tz=h(+KIj*}{!AEo?$!SX(J=BDR02jn1q|m|1Pre=%P?fWEA~L4Uu17et|DNR z2UXdkxo)Ebj2;LWB@x2BM8Lqc_evEoVEZkMrd$aFI>0fluR4YRH1hhRWBf_eHGgDO z)0C8P6)7VN#}}w&pdU=jfUS3cB3rJSfvlaJfzfsJ3|k2r)%!B$$U~kIG+I%C*4sdl zCtK1$4!|zNg{pxKU_;mKm9X)FQeWvB(pi9~gpEG$1bv>Zps@8`P>ctzOhq@_3hHEx z!^;>4l*~Aq59nnR4wq1bO+`3b5sub7L9spX<i0{N0XC4uy$HJD0NZoKNpIN3FA-C( zQRLH&JPsAx=qcO4&%-vX4%miNg(IgMg~H)oMd4^MBt<wB;W!OAy9>bC@&RY<0nWPu z;A{mr1vn`T-|2wi%ibkbQ2attEI59jBt=E?uSN2err2YaZ%JnPbve-OA_qEhb71BH zj>LBt;O{^0scd(RZ07(={XvMNREK4zI{TSYou^WrN_8sLsZ{skQynsTkm@Yp7-D;j zlU24hK%Uq-<Mg7k{qLWDRpz@==2InYPfOa?$uB?8{!8-R&B4D>zPtG!a2<HeYGD8X DeaR^h literal 0 HcmV?d00001 diff --git a/docs/reference/data-flow.png b/docs/reference/data-flow.png new file mode 100644 index 0000000000000000000000000000000000000000..d1ff178e41fdda781d5a714e6d87e8b7eaba2f39 GIT binary patch literal 24681 zcmd43^;?u(+Xgy-h>C!Opdg}yq=Yom!U%{GDxC__(hML-7zju`w19+kH_{=9bV+yT z(B157{J!rv_8+i+*mFGZf$z*c>%P}o*ShLF&+$=GkRiH4eFcF)5IvDay+9yv4-p8Q zluNkqj_KOf|KJavo#YecOP4N<Oes#n|GjK2t6_&g5OiVxhg0Ue5QjkAK|Db{Qg-^j zGUljFzJE@z;dt@dowpaBhY}%~zq(9PK4#C!Q1LB9_m-Pw7yi^M?*FN2oZVk8(^tMM zovv)7dOsk6nf2qRyEK<^xZT{pr<`0Py}L0LFt9yEH&v>wd#~)EWo%&$rI{U$$Os-P zG<H8;Ey;Q*@nmhh3bVA-EQF7cNcZkS$IC_X7<VK*_C+E4A5ONHcKUt$cEi!pv0np$ z7*}W!LP&5K1-=zEReIUa67Q5PZQ**r`w4vo;qjNOkQk<hQ2Nk?hCdQb|G)T?l!b@b zXpS`BB;@}d=oV`B_MXM0Wywh)2iiQUkQg6<V0biu!<_B+c5Wj#knPq)j-E{J`!Gi2 zR=#Q`dpoU)nZNQ@$B0s^11AE(j2oAPNWOl|7UC^-b&D_Prh1G2IH9$pZQh*(nah!Q zMz^h3w+qj`qW5B|GovRGCx%sA&X$B;tF7M7Wa1P}jy^kU!>dpjf7e5c-lsm>4U#+E zMj$R+(IJR05?R)~c~dTxUEFo;D1@r)a1>Q6Eo{H`<EQ`f?-jZd^XKbj=AC~;6b8oT zrb2eQ`aW@3-g20(tH%xd;{Af#Hg{ZMvHMT<XJOm@;ru(LTj$aU#1wXB>}B~=-E(-# zX1htrsg+0P+?Ja@Fua;26LTnjh`0$Wsjmn|vu2?GbT(OiOh<ZukK7lPQ_PO(<vqt} zijdL<c$+Th4UG2YVaL|rmcd0_BL0IxRN^_xWM1znC+kl9+%~00r%`^oE*<N@5?LlM z$#26mdp*r-ccZV}%Hnm~*kaH4c3{mK+G6dbG4k7#D9yF!FP41;#-2N37ggMz)}z4M zA#ZW4V`e$#a}K-q_gico+2?t)hb|@i>iHPC_xk<q$ITzub-dHQgqfPIsT)3)k*TPt zC{(~fY&Z;h;j2hKdh`p-)~GYK%4SBoUt@gnSBM{<ORngX4h|*Lgxe{%4lufSjurD_ z#MJ&qV`ojcVVa43<K9mKo;JNdtwyi3i!N&_>QMHVMHZ&#<B*1J1*j<LR!4bXB);Xe zGRXDM_=!i*9?1kGw?BXR_ww>GHZ~>?DlX>3C|SL+G;=z&{M+f0n`|_%sdZ!D3?qiN z=1E6YVxq+g-HtHF*%1x;Tj<Qq(<Ft4@hU}^PR@bYu?<6#wZ^{_`59c?q1T>UT3Y7n zR{gY^5PQ>ft=|WMkVCT0U6w@bFbE3^i-?Hu^6tzwhwQIUaBhtR&<cO?^6I?V=lnN5 z<=ONvtzzop-KieGAbJ_g;i4yOlrWO>$-!op6b_=2^e0Bbu*<ACC@6?YG4?7EQI++S zq??;te&LhkzZZ$9KYMwp*@`fK0<Um<aPTZn>@-ACthu!{n%nRS28BR0NDX{w$$L9g zVAvWi`fe*}cF1{mnIWR}J`-8!M3HF^8#}xB*}+Wu%hZ(A)bn-sbAy;mi1-^fqOXQc z6?TgG1_qLlkkAR)r{!<bkfhxfb+$K5`M5<R>bwKfNP4k!a=6{-Ptzzw49*2SP_Q>D zftXh4?L_tIQcr58YIcTRja$%7vw<913X0$NXhIt&e|-wP^-$l$q||b(yi@G>suThz zKI0KQrIDdwU#^~bv8K+OqoyEw2C~Z`vPueL<>-+TtGJ+`ZkWQK0NPf#Rqgqw9K100 zyLW#WGzK`Xk7ujp##$z*v)$%1qo`L_QmAs?6|$c6c*dwz<0krt1y3UEBV5nQ!jf*c z(6PTZw!Oa}=;v2dSU8j7xZK;^(BNso&zu?`e<x=xOFbVKO@PQCwx>-Kxq0&@t&n}G z-GV}*w7)`(5JN~aE*@T)p6gDx%-g~by7ueiF(Z-1`VC)U`3nQ^5E7r^K8*DAiEy9p z?rt$LF;Y^}(Zis!90POnkyJ&xew;_*&O3`Xi(Plqm5)|SCOFjdJkYlg2)G@^yLazC zeE2YsqqDuWb+p|nj%Mn<eDx}Y4~ow1;73pp>B#4J8Mr{$aV=CXd3(NHtNQ&zj37d3 z><31|v$eGq)0a6Ac3<uL_wPs~a%FWDT~km}V%3{Q>hS7vrw0z+-pUX?nUC1<N@2!( zQ8h#wF>IK=Y4Pv}Jc2Kto(}~DPYxI2_{@5lx$D*RT<2zH>hIAgr&YTi=V%toW%jwj ztdI9r4QOF`IN^CEG_xJrzHxaG(-!>vDTZDSjgB6{Z11d%Rcw8FH23Yn>pFpn_lbRG zaDnsDj%mLQB0frT;KLPO$F)&C_tU=K-krtn#6hQ*qV2JwF3Y{?F#ku79>M(o-GUx& z!JMg<t6O9e^x?y=^_uhX0>h{MHXf15Pb2nLM+C&hYh(g%lhBF1!9Ec!Tz>6%e?5-d z@T=^-;bL>D99xxkA5_9vg`*>;pPhw;<<6Zu3=E!VBqB|>3oUV;qf^0ezo=BKS!L3l z;C6bHAAq-V^Tv&pv5Jx>A&i}|qJ+f69qsLga3C^B?P<FTVRRTtK3$oZPVD`BTV&RZ zgv#BB*1+4M%PTAIH>Vp~qGyYmz-Ao}pji5Ej8f4~G~<mBYwMDxELtQ8_wX5ZV} zYYd<*EGQVRaX<IF$)nzg<FSmZL$LFO<~=nzc~9Q!dQq1>*?VODKJhJ^dwXIIE8mn^ zbqd}zAMIi^;9@fzxY!65-niqtjlI2y+evADJ{Lw%>2dMfp<wfeGk^RENl1)gO+J&r zl?F?HleK=n<>KQLg~?`X7OOXYV72(|O<HKw{?~*Tmi6rPcpnBve2^Nz5fyYhIe@1^ zA-k<=PWwx33}C?tC^@tTQx)Tiii+TDzcDf@08^Lzl7lz5yD?QyB6c8=t=btUeqOad z4m)@7h>g-}qIzs#U>{t7AR8fqm7<(D^r@<<Dl9`mLBY|^5|87WHVmxzOkN)L@2$DH z%WPB7yX|?{0>noKLt2E>v&=qXYTm_;7-4XB-~a|@f_n-=^E>nO62G!4Em_d`6&7xT z*}!?EV%O}ge78M0`O203CPIQhhoHr>JK-^t!uLF|OIV)t^mN^DQv(A7Q^w<W>&0>V z(?UTiYP2qPczAeKY#HD~o`$nUavRFY$~MilM!+#jjcC9{EP5AdvSY5+KAoDH(kZvU zn*bN0VgCc4o^3YLfthAD;(r{E5kj{#H$Mp^yd`9hecY<bO3TsG*Kgh=H8S8K;xQ5$ zutS3r6XFaEhQB`I-$=omi-?F=SYLOCvjl55Su){<wf777It1eyFj;t;Q>VNaEWh51 z1e^*kDOd$~>a46Rl}uIFqovfW8H9)Rq#&D<F^^GOsr^zgEJZlGmbx*{)W*ifV5v=_ z?7b*{i{ZXZHSE4l)jH5R3BV~_?nw<)XRCgHXdA*P4|ewh=G^l2`h9I3om`y?qt~y0 zfp5KpQ%+p@31ZE`!ND6tLw2y8mQa?g84twV!a|9~$X-j>eK@6H!`P?(j5yAVFX}bh z1-D)nLZA>U5{bTbjZsRf9*$k>n}V6fz!}L!L_F1^kdh`LC7Yn*+V{l78F*S0k`yC& zN1cO%BU-?UF#%2-d?OHC;iTwF{l^y%-Ot`jNO-8Toq;2S{qGbazBB=+Nx*V+FztEb z(+G|!KVgK@?ZF&8tBA0$>ttjJeP(bXd=l`&4CY$GVq;?ma`obPjEOO9h*~S`WdiRH zHnO!!_|5xQAZi_zb0ccCbjoa#<)iuW@$tdF*9P<H!JpQuVXw}2KR<)3qoShLhKmUw z6R^I715<spd>={8rH?XV%)uu_7=pWJcp@i9Ens<z^mL=1Bqt{aoI){=-F%yBwq`?P zqhb`V51JA&c^~E!Y`;3p$HtbWRbtr~NY|LJR*QQ3HY+zbSMrCT)5fdy@ha?Yo&AE{ zN?aW&@$&SH{PxY-cnywn1`8Ec#Cr8{fcGDNnuw^V7TBl_l5%1SP8Jr^y3dzUMMmvW zn#E>te)@(#UnUm<r}6EZx2Og}=^`Xq4VZ!43Gni8Sfr$+G>mcLOG^bgIddy3E2X@M z;n=!>Ng?81RS;9m>`%ChL+teQY=B$ArFW3Fwzfx8UUc4zGlAlNxHJ$O3VAvNU%}{Y z&}exDg|oQ`J+ZR`a1;n#a3~fdKdYQJr@wI-^k-`|3Mn+m$;->j$+dKL8q;3z5T&Q5 z*U}oH<}(X@cNuJg!qM{Vr^Sdg3YFJ^yK#<^kr9CSBQAd47RiHygOfG0`10AaHpouu z>gtg6^fS}bMVi^ku48^lPW@$w!9vHJxSd6Q(uWTp9v&RngR3(i$bqPvEN*g9hu|#E z+uIu=1<lQyW0miE>gzwDZ+RrlcgCIfsp-9Qc9wqp_(}4Mew&ue`1n@~9WfKG`(rV} zj#m^TA~n?qY@g5F*TBb16MEK`6+E3_SJ*?SXz$<<3kM7A(BI#GqWpqA?SZ13TXkHV zp1u7}ohP9UDKagp*Q_`<*9zVME2}x#f{@jsklB}`QD`(?`OehT6m>5|OYpcT1JhHW zP?bXYv-pznJA{+Gs##r+OVDNsr})vnq=NJn(#Xh2*WEs~mnqMJWbZMIlEQ=vt*7cZ zYfcIvT0uexxh(7(#rn!nA*3k}xVg*GnDB}UVT_>RCOqO)y;q#5OSt!2+Og=}8%up6 zN^Dc7Mywt!Kl;pWqhiZ!-@dH-q=lM=W9@qEpr<z>&>onB#|f!jQ%}#!<QJY^UNidh zN)7(7TRkcABBD%nbnYiykl=bs-sRz2-<fK2X8)wlggcq}Ez>=AJYSHBzM-qj8crX0 zN_Gc+ds-(JLBRuv5%ph)MhXlG;V4=KMMW)7O$EiqR>J{<+@c_0n;0xb!0p5-TNN{u zWganQ_a=ohiyUV|>yhqSq|Q^T*dayDRq*g<`!(lPVqo^yNNGi#iy$=!4-bbl3qmTa zL**C*eK=TF=H@h1RL1)HbwUd1){nisg}mA<2RB{8K0nX=+U4<5bxr9r`I;>poLh4i z^_VqHa%+3rWoHo<baTvc0=+g0F3jV_=KemMgW5!yz@!(Z;O#UT-&Nod5P$ys8B*K; zDdPh)b(0XWN4)xg{m=9{=kwvEnzN(UKYvml`%-$k`>qN}_)>Ak@|lNwc{Rdm#<#x4 zsZ2-3sr$Ak#s3*&h3oOp!a^R5Aj3OIjbM3t{{9_ye~|s8gan+xwUlq}3Us=n@{A!^ z2eqMOs7;?x{!~s*Gw&4+X|_%U<zs?_WQYck7{0c&T-#ad(J*H5QO%?U*QBW#WuEB3 zEQGk;nD`|13+;p&YZ&%AUENqqp>hSZfO$Wgr(}1oUJYcl`Ecqws?X0{BA@+)L^|Vr z)H-<l&sf(pav|X4EBLMt=HiPynNbShdDRQv_*f##6^bcu-Yhe0rG&%0mhlx)39eCo ztug|l3OInQ849VyZZ_S@Z{EZ18<9R`eBe`YjbFVPH9WY5)XdlSl>9Ntn1E3>Cue-t zWx`9&q+pLm8^++r`-z>O*vZH=g11^9%>RTA*S{s=v;p}fC7+o~@!}sLLWyFfR9zl| zk}r^MOqANt3*hUd9tlB0-QY_#XL~qWW(OXNSr{f`(v3t$2|MPz(3s=6vkRV!?0L^x z{qO1Ej@Kjz=ibT%S)^vUJ<C3QxdLCZYNm19w@0Xn_uKxS_#H+UPq2BRyZbqW!0Y!_ z^E$T9lai9OE1jMr`F2c4qS2HdX1}v-2+G1v!91XhdAump*AFo*At7OObQJt%BRuLm zp9cM$x%c~Hj!R2RRxveyvDr1X|DWzmpWZHS7-PAiITfE2@`tZo=nSUh7tJwJwo`SU zrGJ<%NsaupfaIj7r>E>gtqMwA{RZj7!=G<xFT@YqY?(gE?SEt+vux5H#TQ5?4%x<L z{G(40{kx(eXH&gL21y<(A72<cJmTzdfevZAvjeUdzPYo-lmPyb6s8;+6VvXxsROCC z>^*&20tu^=(^CTCTi>FikHMW6bZot_wdE#l&R$U`z)5p>#%|_~nhp)6DAx2hM=1-# zLbbzM<Kg0V#EP~G5qiXqRk;i_Hp(D_z=KzmmgW&b-tX_{cSSj)xkfu&mT2(Hhp!t* zQ5K%Ln;42ZW6a{~H*B2sv;zujSxs_a*mZn384-Sdepc0oU%X2(l88%w5fN&TkIlD7 zQ*mgQzOKLc^EKp-Z*PebZiO)meGH8Wx5sEUCDV3l5Rg`jZDaa>jy?ZUZlKcB+*WSn z><pH^TL6U_><5QVd6CsbEUfsIO_&@+c>_#;cA;^ngPonhH&nVZ;~(ir&A|t4i0e#8 z)A>(b;<Wm?i!wfaT47bHqiy*0ZWGUVeCE$YCAms9_fmJv_wTptW6bW+(;FOa&7pqN ze#XBe3xOZ&;~;s5C?H@l{2S60?U`!+M?7YQ3U}X_6O6k$u~d8~{53dh_68gzRF*mw z4i-HrMBo#zo2-qN>E}B^=9izJpH+xJxPU=Dc5vW#EGYIQq$=pZRm%S!6XQifm-8Y$ zqqocf;c*=dV0t0WUE%3d^NDI#s0P9E)2ty!36{M_!~fRlXom%x`P_ih8n4V+MtH3w zlE(|ypk;Duip!+y4wOA_n#rI$;=u*8c?|<RdGZ7-3Nu`MAHEp&=8xY^WRS_}(XPq@ zZwsRKLV3VOdY_r4AF<<WI}fvj*Y#hZPHAgy)~Isk!`_JuE&xZj4oN?BL*RP`aHL<j zZZ=S%c6t=W=jP{O9*DMh%%zFH$xnS2eL1UZ`*P#UFJHQ3GE^|Pz0fIOHQpvfh<NZR zhu+$_Gxqd&y=HY~MN(1{Z2Q$D<bg~H(8Vz2rN%xrkv;8)8HLc3W~R6sG&F@BxU~{- zVy=+N8tCf>+!k$tf$~1&(7%EDLd1UYzh{gz;%*}FoNs0C1w*n)ift#rxCs6(^yjy` z%YA0W&Kr}z92^{A{U7i+tf<@BZ9_H<$r|`b#8r4~RRslN$EkYLo)mbeHW)_a(!W4D zHEHLud|5{(51K!*(53ikp+!eW2Tyn-`oZgu>TD46?WCnI!kv|dy3iMVEB-G0_953G zz<Jf#)5G)N!2@yexRJrjh`uZ30S{ut-Or$gASNbuJ>J8*M7c@n#ayit$RDta7j{KQ z=39S`&Qlcl9sUOoUSY3Tgx&)*Ng#c6!B*KCi1-&jFqf1xHHYDy$H?wRI(JxAs8oYw zOZoI+Utod~$&v%4@sO&qgtf%S$3xzLwJ}e>TMu8bhTRslo;=)Mz+N`@Xn^$2n)!YH zWdz0Z3WrrFxaJoYtj5a2ATXqfyy(Y~=;Y9=zIFY&p_LWgty|a|h4FwthMtlE<P3uA z6v`R{d#TbVQK1xxp*Osj4<dikTBz0dGLX7bS>Na5P`rmUAT-TB`jhQ7a(GcAEbn{n zX^x`Uvc;T<a-GO1H(J~wcCpLCd3B2|&kP=#dhNeqFg>4!K@$QcWhJHmK7Eo>R_=we zO{>TR>KBRUq&18&8qtIMG)yJ@Mw&#Tm7%UP)<OelZ<AR@lJySCul6eTPV?h8ZI(K> z@T5l~wn@ECr&V(k@g23;NUJboe5~2(M;-eaZx)3<21iF%Sd8!^sUO<jgB?@}Qf4K( zeEIO~cpYrjF9%OW-YtO9eyL}wrqt!aH@lbbaoJsQ*?rrL^ci;7jp?~4R-;J=oWI5V zmaum^o58pzvFN3lJ5!S!{3<gNopI%vvE@-QKN`FK)TE1>Y9QPwx3ivIUjI%w^=Zxe zpY8WZVMY5=G*VPJy_R#Zypc@?$y!j`p1AIK)I0TOikC+iZy{xCfh6pcoBh<<Su25K z^wm6zzY{6?aaoQZa?d{6LYoOfeZpfxD=RCojEpqM3CX)5qC$shT!=@)(D^;R%ssNQ z5<brMw%rQ#`MEUm^?9-&yO)PMJk^Aj0()<*s*N?-NO$#C-n_kg`le<e%a=$;E9$zi z;^h~&=i~(^Pls6IGHX)Bd|yyh)WWlb1oYAs4<*{rVbZ#;s>FWrE(j)^&RsZgxIf%E z2pdRYnb-kt5*t^_m!T|y%64aG2V3f53jk(rWybIq-I=12z9ZvN>+S~C=R|XayBHpt zrr#I2Z7fs1dQ<P@1vfM3`=s@x5-TQB;LEjRwrfmdCm6*}hS!Dm*Bu61ebb6=TQZRa z1!+&uT18!p(Rw?~PrriFM<VabBu4G}B`O+|b^A-1?h0w%Xl9smVcfZTocDPKj2`kw z0bbr)ye8MM+dT{qnxk7)4u=uSqB!uL=ik)juHR(M4lga=UZNX+Xo~+-SjN;hokKak zmtxk;k39)x@Ah&F!cy3fS^l>oYSyN{8%<v=Tb+7Dsul*&Rt9_A9$`Bw!4Za!&F-l# zP`PK=yu_Tdes&j+ZW90d{!<o`Bn2J2sI-?Fum7qdz<Oo8N-MGZ0zUrGpz@EZB!o&A z#CqtvZq779$_NhZK#^AbWwxrzxi;l~;;1xh$-9}dbt^AJm>6G`U)*DsI#n^6vToOo zxi5Ms-fKQS6~tfDy1b_Z+NDs8sxJr$q}C=dMClK@qrL7N?-m63G&vvTBKZ_Fazh@c zpHItu%%Q&p9mjhKccs4M5#uWL4Gj&Um;N${i@Sr%0Vi?N*rhybp}9Kt(jZZiCzP}I z9cOQTL}9v8bC+2Wb=cnHjO94jbONJB$J4Cv-x8s@T}`uOt(sp@JNs5F<^B?k;eU$` z-mmRN&)-F&KS+n|Z^cQg{Oy~*!kKr;fY3+FybwmFfla@mTvlI@NAmQ}^z<}`Zl#Hl zQGccyCz!R<tET_%Lc3?M*n9x$&VP$iE3=o<|2OY?r^B<R>oi!uLww$+W3*=*_;<d0 z|1mN+@`>4D)Q;XtZ@kxa(uaIu6(wAHe;>Bg{i>}hF6-Se>@yM1ncq{qokmzx?`C6X zZlSv(f+|9{;f<}%(+yUiS8YcZT-Tk%)a<UC7g~&d8b8ncx`2@xAoYem2KjSq>pUNy z%V0zzT@{X2k<T2U`TG0!?<hWVXr67*oxAa$oqoOf^#Ogtqx@}ORIht}$Xa7Zh%Rx2 z>DdR1ZIZX>9^aVMLBozfv#biy9VWH0)jC2p5t7D?fS|G}97k_el~1nfxcSDNw~^F> z)^{*>5GSuJEpJm$B&lZR(-2B<a#+e+3e~DAGnhXPyNbWg%+J3U=YE!-m$x`xB@7Q% z`O8&60$?Vl$6w5H_KQD{e04BraUol{^3hdYves3-2HFDH3bPQgAq~w?L++t6yM^H3 z;FZ<PMPpuxK4X0r9jC@P^w(gp(`zduC4t^Y`|F)Tmk@E^A|vrHUd-rQ{zO26ja%0* z>3HqOin%%;ZW+FO*#nJs?5=$|{sILSPX8lBJnj$7#`q5@FYh#nx6;zm*qc6sn<l?7 zb#ihtGGc`1ReIiqc3KY<Kf99vfvu1jw^p2=pC6h8hlhu7Y>i{^5v*6riEHL&X8{y> zn*0}ATtc9J`s>#(l>KZIDfUJQ@t6%Q6B85YvjI5K)|N576phFbTT_Nc6`fkTGB)UW zN(@YuK!E+5Nn(y*#sdJ=%4!{YpHR>Jn+&dwS7VXpYQ90EcN(NA*k@IT9<cW%DF?*o zEASy?<U!xQsh3#l{7)v}<R`3$S5EAq1hX9UA!qWwG~kI~PWA9Wz+ynL!^FUV%`uL= za_SAB@pdl(N{W1#pA{@Wt*}Fq8ioRK>1sK#9!yQU)cO%J$bPvO+g2LKCTssH2=p~X z7oc&~U%kDXT3gNgvm%p|8L*q&h>q#%Qi7>VoOhuQmOI7I?<GJ&3@7={h4JxmI57$e z3b0cAaB;lxqR{*6w{I(;M(^MOx@T!2<a)#lmWBPGGBh$0vR0OmX6Q3DK+Z2=Ej3YU zMT)p{4?eWtThZ{B?tun9v{_+uFC>7^L{X5ELazZ5Q-rJJz*I7%++@!sBoHuS-PH23 zW~xHWLT8*o6R}4vYzx@{8e6~%UGj*x#wepu7qB;0TogJ<RAPqK4+Gf~$l777YoX9E zBI^cc4N26$f#dG0<xo&i@Iq_w_wUcJE{`BbBl>{>xU-!2+?ww9U>aV$V|8`){QNv5 z*gif!uxB3QaL-PF61*?TMB^>S$lfy>DqtYhsdNg05xQttFo=x~$ZejX*fon@(O!`7 z(ER!K-PUY#YXs;1>PQ5da`MA(;jfu4FVs`76|BsD+}g=H+4?^&0OtiAFJpZJgOHGr z)zwuUZEbK$*Y2!oUD)@>jlb{{Epm(I+xWwncMJAl+PG@DiJs}6^6$bua_V`Yt-+80 z?L4r6JI_X2(9ksWm!_vQ;1sV6dRqSz<;%_v(UY{==mUMWnNXN9w9!QB(J?9V(FNFV z0Dfa_Yx~vLx58yVr=&yxfPv&P-nW>)dF&X94TppNI-W)74ft!-V2eYnVTglapfdY( zYusYIp$x<>F`MP-S3f_fHxWB{I$ny?Gcyou08yg7bqhO@EGTiw!Js{02``sC_d33F z(c{YBwCD85a)(uF?7q=~CE3pWAwoiL#Q+ws>DH}VD=RD9JUn#bZrCJ$5!%dgqvdE{ zZ)#qXTG;ej8}pkbe{c{Ja7dZ~lz57L%3MhGpvQWL0!%C@BEs?f%r#wEGgns>YhpRj z1w+{%?^$3cK?2TU2K)kRSWA0*dso+gu!$eGH#hIv(;|Mrf%b<O)|HtXjZpewuOst6 z>GYguPCX6uk5Hd!)e&K}qob9u>{mRen?snee&8KE$)75hee8+yMPKtU`=B)djEh$A zaG_M?#8%dEWzc2L`h-v>)E=0sHb5Y9vEKkR#it3|YlLt78XJqz&2~i8nu8tx2fgH= zpx4j=G&hH$S)$kjW_ANUfVu+@X$!?DRO#iDssfgMcnIAPvhEC(O!dZVVoXe_larI& z6Qcb5;oeZ->_%Kd$UzL0M1j}&YgUX5O54JlovSW&J(Haiw?w~84Dd=+3n>^AfMV5n z-)d2Sq_QLN2~$~^&b#nCI>lyvNl!v{u3sAeo&SaYRL(F*7{);&nV6Vdjc`2#czAdU zi;Lx<8dOmDSyGZaE7RHP`dTR0%1KU+LEMtBclh^b#%wmJu_w;<Oj~tKC5nd1C|2gI zT9cQj7f0s8`C2M3u&CKP7cJ)0C@b}D`z@%gofU#hvvr^a*j+RQ*CY6$uyATp((i@_ z6}N%r_KpJ<h6Ziq&9|?gH<RdOqgcWgD8Bwtt8eK-PbYGWiG@uKcKuHGsYDjwEKJNS zE$}lAL>-oD>v(yi?op4qejc~|WsY3etFhgW+hV&bCKe0*>3G||Y_0v}zRb<d&Gu*k zW3pORq=xnqU#6x;T&$bI59UrX5nQ&9M!o%Nx1DtAVn*A3f3)SeU=VUR1*sKEIaPrc z%qoM_(toC33^56Kr`x20^7`Uplh7pzK7f<&T!nKNuf+Vfr^k>x(%&Cj$oI)Y>%|*e zkbzZ5l)>qckd(x&IvT|HkORc}-&bl~dxZoAv6)nrwT{<u0S@8>%n%Qj8w_1(sZ^@H z?D{pt0ili;L2yWjPg6&Zwz2;O4@W~Ns^7kaE<iT(#Or26EoC_|iM8JSZZv|GuEf;q zxEco`f*lBOPLy(@^pN7s%Lqe2ou5Lp2r<cGPkUQdUY-GY%bHl}uymJLhrnY1jtm0+ zUbn0uE+NK6D1!A$K<9*1LrV+7tJ12vrY6~Q>5DmrM70Jm*;>~Q%}LuvL|8{l%U503 z2?Qb*ygE(}#(IJiC!YIt1+fR<T^kars+90=1R;1^6t>TVJukH73M#3}tb|vtyy1>i zX2q7a!(2Q(fbk+?r3TWMbt|17<%(J3#0O*DHUh40MAN=}`4YPa^yK8^$T~hG!ih*H zHKVn?Jz0&e6anca8gT&u@6413U;)rOh(73SUEg$je?q6Bk@XUxx8z=m8Hy(L;-qys zIq^|uL+7scXBsNK>|{jozMh-?y>pM$=b68}j+qeJsy{o~ahoihXZkp>hOV%wV~d^Y zgV3SkV9?XX;J+d4bK$f!#dKXcaVWO#g^Bv87wPwqk<b2sEui1Ld4oa$be;8Su_v~z zjnCB7aeFHX`JCKf#-_i2Y|a+B<-T!;UtACMh9!vizh<$50_WV{K_4ym*E}mqd-)zP zzrJl5Sxy%>kjZr2XJ^;zQeW|DI#jU?4a^J|6NKDSEM!Ld*7cvDCh$k){9DO=ng%5` zGplVdQx4USR2kS7%xf?qfzDbFsly(Slsp>?jA0V8kJhaaA<T-}8ATK83GFo=N*Oo@ zSWZr7cAF(kuYEt?M`8=&{z=X#=Og0<Bbh(i=Z71dERif#ntRNh^`|ydP2H`HjJq*P zxd8(`p~jiSIZs;Uj_*0WjigHJPs`L)nHGCfMxu>KdsBxIGXMKmH6?{3Tca>0JzY9e zG*@Y*vt_!Rm~=JcWooo`Y>KK^l@r&)yHigd{W`FX%Xf`VG#F58mFa$$>8%&iktM%! z>>r{<!;}5xwr)$cjbIE$2*qm~;^k;e__&-^NW^a4uXM-w5GQf9_0Su#@yvnExrg$< zgB{&I@Itk&*{7%K>OgB)ZL4+=%Xv|L+s>j^-gK?6s7$Q~Sr~aUy4d{2oiJH<vC3+f zLWy)#`9pj2-!)XW+qRfq>yxB?b*74PbCO*5AMd%0XVl2@o%AOZ-+y1O5mVHCG#<<2 zQgh=VGPjU~^x@DzjMzq@qMH0=%dys9<@2@pQjYCIMtAt`B;b$KtWHm)tDI8$EIq*l zoH(yP@zXXEDr%i{AR4v}lB5h=rs`Ud>}~M6oKJf)thmAx8-2Fhj}QNL+%QjVG+xpH ze3d-t$B(=9R}p=bCChVE!`#2jA5ym`EOeGU6mocvE|ntTDZHI)QJEhudr?#UhBxXZ z8JV<}#?7xNyWrqG;Ln)zj!R2t-nz9+b5s6_Y?D%Eg}C#*>ppHdDw+O1&6sWLr##nu z{H~~cA3QnfBqPtAo!6ARr`MOpRa-YLPk!Ff9<#Bc@l|uIr|p@}O+^xy!-r8_$%<a* z(`%%!I^;Jm7wueTb4F^A-%ocJr}6n=GT~R+U%ztiVnY2ko!&XU{Gp^yPmfbANe3V1 z=6dwai0E|9p7k7c$xq>Br9XLHTyI;NlHuj|E}j#aL@tmIy-TRiCSMwQg75aLU)1O! z+4CTL%iFFsP}mC)r$!Fl6ch*(cTc;ulSt^euP0VI^2Wm=<V<CeI^gJ5uHE?%9;pv? z`BAvhe2T8T?Y7-a2pxHl8f|W09LI>5`Ad4onmFPdh6I~+SGI`enwz^d#V=Kl1^YN1 zVviN+yk&d4vOicx?x{L-@Wog*NMAqprp}&^rk&uk-W=k$n~9+77`E4M1=}y55PK?r za5nQ;Tv2z|aVHE{1&1`brm1v)){Su8$k1JS=SO_Jhxb*vQMs##>z}oDOZ$`%IV@qw z1ma}j9G<4O6;Ek9CeA?bC>k0)w4KY!TwimqeO;k3s%Z4ruNTONQ!DR##;W{%p5$*= zD#-ILZq7KQq}b@{9xwMshJ{ju#Oba47RlxZ0$Hbpg@LH3R`fU2?Cj#YX<GU1i6&AX z)S5;6Qy#lhj_`L6mw#83p=L*w#ZLX!KaTi|jzq6VQa(kUQVHMGk`*6X=fmhrL8Gam z<K@RtnRn#GPVNpZ3(M>2oe2~T92<vHb4m2OG8TI#qm4qWyi#GQcN4N^KOSHnR*z-$ z`<(3#p$o2awmq9gIuA{VYdkdF3C>T9@M~{xb#*n8O8@br_km2L6e@eU<N-f7rSI=k zyd#lke(h@4x34enzAK;@@}vteu+)#uW_CLn9&6m+x)ORiyhrN$JAm(&R-e_o-Er~q zi9M5X`FmtT8vWJ<xyOpn?vchE?@N*g{`vF8j{rZj&kPwX+frc6E-HHJMdxNRkP`z~ zED9OaItLj(KuV=HGheC=B<J1%q_@bIl9F=!_U*fO?*fYOidIRfR3%W02>*_JazXe> zNkqct>9H;s7yLIw-HzdDMIj^AzyDAre{N-G$CIxv$=lw)m+~UL*Gw<&Tz>og$xix6 zl?ym-I9vx>KbpGDQilg+y(|6vKDM_98XHpyZx%?t=Aa}g09xr?N=k)3gOQ&|DMS6k ziGb<`3#<118m@`+FI$hf)+O*F2PGIg+LcM4f4Z&8U4~*KMMGE5G&Dg%qmA$=<(*sf z!3H??(VCIhoSa^Nol9e6QPQ?PAvLCw_FU&a<j<o?9gtk4L1Br{+nxV(r}FqL{`pbl zOv~;!t76XUEw=wUGP0@gI%iSR+)-mmB9+no0><1!?L_wZC!K0@3skewEzf)w2Pc>m zbctThviwE@YqtG<6Hh3ms}^{^Ag`G>ECsWFw)AI`4O5Nh-UMo$vFsas$cQ)Z;V7So zimqJgUZwsiy1#xHKHg4m8RH@zZ#5K0EXrax@DQ+ESy@>#vkXf)s4kVUuU@D;MWB3Q zcp4s>E&1qrk`nXU1Tdh^PNBlh0&IM=)FzAk@&(6g+h6vy=IOlh+5LZ8N!mj?I!w*b ztzIO24QQ%l)#%J_b-8<}ou`_^DSm!z{?d|3cVC$B77U1qj`Map@|ph>;JS-6$QKl0 zVp2&qb2=Auj1b9o_?&F`QEvC>H$`!|!jIJ<hCmO>tK?79ky6QhWNMCLr}e^2*{@6& z(x%U-l5vw$?x-2Oy~~iW9UaWM>Xg%_>f4air}QZ2kA$kd)}QG4CDEE3m*|LNF8Qpa z+~CUhuF2B+Xg4k^5+rx=S+3;4exc6^eY-#t>((pH1s`HV_baSl#3}+@*ag^4t;9|u zXmSl+n{haAKPbv{Jm=!)&M{YG;@|9EH{RnsGx<>!7NePXyJ$noGWq`d0sRG=+_{u) zGfT13xrP4!qS;wQ51;F6<5B75tFw{$T<OIhb)vPb4^AGf8*i~}_?*meem&b&(?Ym- z`?ciT7n;E}GBdVfOmnH-Cf>4aZYAv2uYu?D>lbU7oWNs_i2D>*EKPyO2T0ZxPkn$9 zj^qi$+G=Z|7}5qfo<jj3pHv{o0ARF+JEo*C>h<ksDQm6F8Fys(V(#}_mX!)b>B=Yb zic2#?Lq_`fB|+Wn$y;8bp)WZ&Ixb$s*R*I~G+A3>e&31hH};b~$ySqZ&}Bt)^H#1b zYaV>)xKEL*C=wkK@*+(?<x;X`cve7Mx@u;XJBKe#E`14$>4W{%ysPwONhuMVh0Ko! zTa3xiH-6@rC#jkmSDbGjxhGmhd3is}N}?oA9)7DTd80<RzmZb(-T$^QUxrmUC&E!^ zzG_Hkf2(x4R?%HXuelv^$j&NSM=xDh^=m<@nJVVJkq<T8#{?_Z7QZ~A9gmPpYI&dR z6O^CrNkr<YBb<HwEQqExgeSOcq@jbJCzQx!;yhK#{M?ly`9<b*@N~pUb(T*3Pqdlf zS6StOoQ|6O=ct{@q59*_+t;2~3F$&y*+@2E#d0XcWSzc+#-1GM-HnJmDnG~)Dorsw zrF?Pu_^DD@7u5vnhtgF#F>R=x_Sa}>Xrg0cVj?3CPxmJ<W<9|Bu-%${;%ek6M|I=I zH|WI0#-2gtC?FtUnE(_b_cM`^SGe@watv50J9C~JoD>?%6c!fpMNv_=<9mL*;@V+S zq#34qterd@7Wt5!%f`r``U~=TfV2T)kf2;Ls)(Ils>J7)9MZ>yFL+6Qo1(jJP(86P z=gHI70W&_-Kv;_mK7NBDFV~Y7={fWBWZiS4qs++#xN#Az_5UAqfFlef$9YLe(+PPq zDkIK$GlIvLJ*m_`=X?InE*@G-&nI$Le{wZr^tFbwSj40YyUSIK(9VA0vCP?n`NZUz zz;jxmnNOYae!8*Sj+;4j7ugT2r<c>G20H!R*A3P@ww=*c)TIXsXQsnyT9j|@7ZBa! z#JI=t|9a}Kce}u;H+#^1f>&{Z{})889N~i38v^xWTF0KzpEBXQ-H+&h#tw6B50o|L ze(ukld5j{<pKT>E9((U({(GN}<k)g2yla)UIAf7c0)<+oF7j7&yVVu%?-uuc%PBQ* z7*J7h7rqC1(3Nu8Uqd@MFe1ye#axeeU`t;JECe$=Eu{fmzR&;U0AL0*Pm#q)c=TYA zY4^<1Z4svjHq$78Z=e{0I*5)g4t!;DQW8Zh7Dg;@0OIcH?tmWLLV$}aNG@6L{U*ME z4o8IDz^^W#uq?RsK?mdSd0*f6%uEcx8TR6o<BrWN?HKry`|kS01oS_;{=I(vx_jr& zD`;>%e}3-2&$$&9D};vhT>;8CN=ix?1-gU|L5=<a0k_57DkCDO_DiAt0ZbowheJd$ z$S@Y@7BD}!*vQBTTuH^dZKEK=a7JU6^I5Y+a&yd~gM)ZdlGA8~8YiQXtL8AVjLf#0 z-iI$D@ARo?$5y85V{YDTrM*>(*P-?8TM-YJ>EXs}Yi;c)&1~T`vta-BCML!2YvZCJ zA=@eMzW(<W<$~!yz0cIRIxZSf;kdxaaNVT1L4lXd=Vxz@D9hcu%p8`knwqU<c54S7 zfh#U;4p+4{-?}AY2&2XXYZ%@g<gRfSM!1CX2Ud%>uEx;~Pm~|I$elMRjN&XP$j_}= zv_;qlXzu^gd0Z}McCgiK^*?w(+qO@oyBJ1(`&xHD7m1OJ_RQI89Icw<&pN{QrzK~u z7G&%5{A)U%#5I4r&mDXni13E_t~$9MDTb(02-kR{X2y@z_h*h*k8A{l1l9)2Y-GlE z^cU_XSjty8m=A|}JH(E=&aL&mR}mA48f;8ITlQ)76$y_?9{YZmN4GQ2V*by$K(q>x zInVvI1J3!DyvwIuKcvb>dQufRZ9nV)Qx2e!Z^C-APEMtgKbUQCzW#mtWEk7UBBc-Y ztTr8kT?9%TwAqP>h<10`=hZ8LfCH@ek0ZnPf@J>$($&~6z3`WY#$_RFCeWAd3Ps-^ z0J$u<LR9~^_utb7i5;^ymm51eayD}1ww=N9tZF@QJSR+{uL>{V(P44(&CPeGqyUmu z0(pK+2WZ0-kcQp9J)YFu`qIo|tQ<?p;do!`@C^HE1C|G{HT6orFRcJO1IRDsn_SQd zKLG{+450zd7)v=8yYMM?&8&h|RL(S1KUa&GjX3Lz)uJ!@UL$39Jg~a(XW{41QU7aC zTd%dA6PK_!#12F(y?K?l(3h#P^*fxAk?QO`Alt02CeGizMxVOg&--F7pwB_xN1P6S zPY2)qZKX;$B>34bp4TT2HG+P`L-FOBO&Tfpqjd)6%G$bZ>#XG)ks~zLUM4Dhbs8TC z9H|EzYI^EFm)w$3qh`wazC4)bdeh;y%4hCd7hfE>SXVeaRwRD&`t{VpLgScfx-#&q z*tzSq&Ntw!dw%|GeeT<vqvJAMWE$tX7nz;SP6~XAEX6pnmg%4T=La)^o{c1BrKJG< z*^~&p9gL5zc3juh=>WeG`u&1EaADlePaW5OhJ~q24OE5Z4uI~f6nAQRnj0JoP^qyR z1tJ=Lp#0?-G!mC-1H3|@L)zTYahw0`jRBGz?J{oX9h00zphLj!*slx*xri?;EI=#p z2pGP(oOZwn0k%?myS(FB8!&UO-#<G}QI7g<=;BM6DMBELt9+lTgi(O@)%}d%;*Y0J z6t1K}X~w?swj8sM*L?F^#j`D5nmaYUtx94QUu$)q3g5tT#1|~R8>RsSs}}nt^&?lW zJQ6*Ablm}X(W6V!W}sBKc~c`%ng~e^I+ITqiFm2o0YL&{#aXuu-Sx5v)yx<^^M2@F z&e|SgJNG6)eFX^sLjpiE<7IY@BO}pQ&@n)Coo=~d1w_6wXo>?01yoqz>>#-xJW#K3 zt1|sTo))^b`_<p|P;@Fn&u!`NT#XdP%*@P$Jzp9yA#}^_n}7X+k}e)t?4z0Q;JAb^ zDLSl=y8=0@e18>WI;En)aNE_sOe)fJ<qY5~%>(`UaX3pvD{S8wWV683;Rhb8uyC|D zFr+f0fABtR-J@iOo?WdL3%9bb=2($k*zV|5v(VGc&pqfJNlUf~E^{6X#ku0m@(!)* zmOSg_HoDoWaX=2M7z4z&&fpbLVaUkIeV9Q?w0kZK2?EF#kZb(=ddi?^85<piP$7W= z<`0ncp1glwxmIxo#LEd5^<4mN4k7!FVQlH|-veO{;2B-=ET<TtY{bRJDxl!}-x9Qr zFZuTZ<|?@EiJe8Lq$ZsUL3jbg%hDVv6mYAThKn%(AvT{50;6E8D-+ltK&JL{39GNG z>or3MQFDQK09xpzL7AE6z(i7r6O%`2D|Betg&(qOvVCtOpUi&7mQ1*QP^j>n%swU~ z=W1$NNq#<1AX!LFd7}UfvePpobWvRlO?iCLp;E=n%&a4m{2L&LQOCJy-le7b(j~h9 zm^D!Z$@0RzU{>F~0S(#%A<Z)XGC+kzrY}AJeA#{sgkx}cK&3G@*tRuxU((BkuC5}m z)4dZC6X8Ccr!AwS?*TUUrDSK_yR=vL$?3|38>ClLjoEsjSaPw^fqpm>A762ka2^mX z%SYztIXj(I4o=VezZ<&wQW8>`;#~7!Ei)jx!cw110PCJs;R+HEWKDZVM}Lff24e{H z1g}T_*cgn@%9>V`)G5$+d`D3sU;#>pKY#w9Lcf0pKKg5&0Tzc|*2)|J5;e2=IXEoA zmyU)mE-qdsXRPdzEFCcaoAgB3Va22`LuHDHT|+|yyaz4!8}HjZ5p7vr#gSjf?2;nB zTMgge7lLLgjs!GQOLJZx{Rl<<_V=0u$DYu{r40aCFMBrF?C2Judnl$uE&|A|M@@z_ zG&Ey2T6C^EK|cjO12y4Uj3bMS|B?AeCfttM1p<H_0=_ErY~2%%hULglf8jy|=_-&C z9N9*Mt8}HlTrC4ZnyP9)Ac+oZqeJ;Kt$25VWR70{T6cwRM(4l;%jm2N)S8vBAFBer z2YMuK{7Lh}))Pv0RZB|_QXBtU2&XI9Hm+E48Oi92E0-^KuTlwu69bw*wgWDkt_=F4 z<;>jbX*UK+U$DdGF~B7T#;}151r(qMhAp83`!P@M1%sl;wq$>0sNVl)cXL~tHb@-+ zvzCifEg_u-C_tMX)Ai$1NXSbc$Bzl%((H2?NrCe1IO_kmMi=-4lMbigDgZ`w0z?J^ z>Vi>^S@Gz#NTl1*5|ibDuUs<lZ$DT%!+jaZd@Lt7fOP~@EgJ!Pa1T-QGSJ#?{yC}U zOLdz_0Q3siV^c_lb^t9`(;Va7*4D-k_#|)vEUkJW+?804nE^Z)8L3fP(H0{dL32S4 z1<YIC2M;E{yoPz~!Qs8)nJ{=h?!DN`StA03G*DfDh6dz46Yl4(01Cm75XK*)P_uJ$ zv~YlTOixcwwTjJDob+g<86w(YgoXC##$9am7khuu)z=p$ck1j4=^{{hLC~D0S5pnq z!^mhJ?pMkX9U0k|qjS6~;};mXzq9jpxM&HSFF=1~K0uEnyn6Ls!b7|HTfz>0G^!I= z_T=g?sH;G5Y>ky7!bhP~oow<7qScQ9llZ^Jyk(Xl%kIjM9n|^sG6Bz?K222n6pF6l zd+^}k2$O5vdA45a40R3|JDc9w){5_F*F2+q6j0J9%F&rkb<w=01t7V3o+u6UK_g>h ztKp*brmO4DW(n|(#qt1c4)=4Yj+WMHgPPxfADiv)%~s8f;Lte&#$k6wrLJ7^R&V;t z@=xFFLBpiJ;t^&u^9K&Nn23lrw*191*+%q+z{NqRv|b=n&g}Cv=HcblhB%R9R+CvW z-#eofDxB^(WpIGw;h0B~nKARl%+~nkJ0_^1xwyEnTLCf^e}DO@Del&A_WRoQf*>Y3 zoH##QSXp`d>eb}RiU`2*uwKi=pIN3qk%)PJ{Tc<CHRwLHIU;25_4oG!>oQu<1|*Rt zQ#ew|T(4>oBWlJPs}nWiXL>A!ieiVT{S^yPhN@XV-FC)G0)VVw1*|S0<|n;K2Ss3F zqCt(@sic$?lYEr&N<F0Y;-E8u+#M2ec&&rN0|?TD0^a~m9Rp1lBw3J)aYsI53@NLq z2)xNN585)r+itoo-;bPqZFN#NyiF04v~R(e09*q%c#+P=%<MD}@?Kp_3qqWZK-6oX zhr;AVN!ufNQbCRLIG`4Yr;sy%nn!oahvBNZwT;ao=%k(!cVR0K?J)otWlBPb2Rxnb z8yhbOh-SjfA9HY|Z1)e`XJ(dlWW@Z1;|Y2cTDfmOKmiMWj{V(TE9bbyfY$q2I}e|3 zQ@Y+?GykH^!MR|I@VNUHuqVqIxtsi}6r14x9Wed=-heNE`t-?Hv>+uoTf58_)(BX( zbL9ab&}crl!BsA3YkP()U|w5(j;IAmlE^Dl(<dk^Y8Gv0px=U`3swaMqRy&cp9pGt z41coLfwW?wEwVo55J>dkg}z$c_CS{A7-%eBi9pl}4|+A=jV@&A^49}YHeTVFd(zs? z3F=R2|AjPVA_RhN2m8AK)a>ecAU*WJ(#O2C)&ZRS2fcX+i@G0{V3Z$OQETI>sIoM^ zx_r^`ULsbMd<UTf+GrTN4Cpd1f##6rP`aD*cERzY2P?2o2ueGLfQ*gB#z6Im_4!jc zYol0LKP*sKCTQ(M5m76H1?+T2zY6b*Ba|5}t9o=^5hD(OheJ?GXvYYI6D$Dv1~y`T zzGcpK%(Dl_Bk+Imz{_i_YmjDP(f<~F_yR!p|A%QRbB@Y2W_uuN^<a3VOjULyXy$+% z5$`;uDrAX&0da;!1ffp7e?JpCNNYt#2&IP*zUAQAPJrG*5)cr8+Bw)X_+M-_^JOYA zcD5XVg4enZ|7mQ*0+0UjfB}9A^)5;pv)1Rq+>_iBnR)jxLJ0^pbq=&1Ee);}ll@|h zFM5|F1rdeF$1GuU+LF&uM%9wp5f7BIdS&KZ{k>(&ZRc8m=u2DiKH;SGBbi{oHTbT# zk?U(KE6@HR=W4eRPWLVS?QCr`PQ3W}3s36$_l`qD(KnLSerZO36Xaig@kO|Q*HlB? z4zv35rlKY5PVAK{=E5x<f2*~l)sn&A^r}%ae}I5uZEYR7-hqx898|Bu$Mqlsq7Enq zAecOOXj%}IFJgT5Az&d;`AkYpfN$AJ(3y{=o^~~+il&F!rGmye@WNxK1BYO(egLJD zP@l_R?n2&wt(;hb0Vv5hqyUz~FFG*d`1#HGSG=#C{qZAoC8i3#u950dQa|{{&Dzc` zQH`z|p>(;luN@c%Kn7yQ0@iszb}1@qYig?P>%d_p7(kci-uy>J0P0swrTe)U7BiK6 z_UtMay1fI??U&S4CQ_jCNBl3_0dQh0=;|c^La|GLsTYibMDPFj3^2&Nw2TaF*q!%4 z47z;zGNd)5b3o0;0?Ud2FLK7`bx6cev!Ewl_OL^A0q8rvv9kjjW|G??z^wqDxWr^B z=k-yltB6Tq_z;RsTSrG=W8EmgQ|dlD-Pe;Gz`1tCo>pvgcb6dnf*zI|V?C<bAO8ps zED1~gI7kBDhO*zDmxnhl0K6?B3vXV4hbFrRFD51}Ev<p{mpM=G<4IiqkW<eD3^0`a z=@A+(|LmvLP})a?4O(7`pq|dk&IS`ECnNjEb!lpnMVgJ4VgcrVv=$_p4+x@AD6CEy zo;<H~mk{pu0Op(m4IY&J?y?H@5q!03O3^T;1pMwsC5=6;$Ca?~a7qv+85w=abgR>9 z7#E?k<MTsbnKJJ;NK%nc-D1N5&QNKN9gr)r59Om(7R76dq%<fL2)(yAUv~dBPuytB zYg*KS^4}Uwd`lL^u}1?_H>s$ogoP_+XJ^6o;NMu4)BM(4E2<ZA^!`Wj8BgEc+MZPn zaAfkmD4L~iOj@wP=hHnENu-qo5*$vb1q2}tg+vB|_6{uD_!D`nkQ6)%4InjTy1a}N zR}QzkJ1E;K4#~+qY@LNA8Szs4e;M)WOOdAm9*%?+EOaVFX_Wm`9X|HS8Ch9bd3Zub zUj8Hc5CI2^*J^yUwssPt45w}-u+}A%I^x6?ftGbg5KcZY_Wwdu3X^LfVnZNYeZ0Nz zfLr?ovrC2~gR~od9s=mX*C>E#fT2QMx>!!kX%p7~8M7fUiv)pX1)L(#5Mx$X+p)|d zU?y=ETa17Z22{H&oScDJD$peo5~hTIDGL(&%yF<?%`Gi0pv#2|Xyh&<=71@O6+{6M z!ud;1y&Aw0_Yxop#M<{Y_p?K$Dox-7VU6nR@m{m55T3-tu`)ZRyLW$$kKg`;MtmmF z@yZ1PoAH}B_8{=^^ScW7aaxD$14VJ;hW9TaMBOJC7Vs!gm8xd;4f^9NxoHo8WRVbS zS?=IaDR116Mg92k1IQyATDrR9Ad-hXvlM=z<-$dv6_z`$E1)1v1%K-?0VisIx`7Zh z@K{P|$N#bi!Kgty0F;;K&!1y?iGxt}EcHbYAg<j80tmSeYBY5lS~@`Sn&h%1TJBCH zz<S@iFe&&61>OH+Nggai{DZzA1Zd#1=wpeM7l2p^OtikHrbQ6AfS?IG`d?s^`=mja z=tX)ctZ~{k*h@$^`k~VRLLqr!grOY}(2-Y&iH#tZV9A;5yK7_7-o$Y1ffRC{l$;FN z>kVq^i}?6h0_1gwHv1nxeFD(}kSjywumnaCJ78{x$@S$M$k^H0!IJ)?aO$oO7ek_v zqs(fPK<nXH48Oa9TplUm#LfnO!{&25082Z|FKG~REW*Oa0GyKfBthPSWp&{L2OT#D zvjW-G|Cq+Opz}`Ji*&3muc}HEZuxJ7+P=QNi3z<QO5a7^1;gaV2Mdi!NQrJd@Br_c zroJeIixtrzA-5KQo1Xj^6XSYvVB>?@0&M^=*%8+Xb!6_qPmnN^`9OOGs+3wVO%l+v zDWxm_G#?-yIKFUA1SBlh4h~qcx`V?Wv@O8jOnv|bDp@!56R=_5I*8!K`blK-m{<+V zVRs+Z=xW|vXYjh3Z%7yjQW_y$TIypGM1;cc8q9&E0bg{q)D7{vf;RkcQlHXMc<a@2 zq5JjGRYI+})ITb|^qSVER8u!V-vJkcbnFZ)s7$*9R1<y0(5EZb94j<dG&eVgWo8}i ziql4yh@aMLIl7GViBsC#02%pIUST0r0&Sh0ke_2^LMp>hetR?DyZ0HpEI^6+$o+Qk z0TTQ*^DiL6f#BcF&~SI$WgWY}VK_Q6O3=8lu(Wgoz-e*O1a6d(1{FPdckKr}(2KzW zc(i!r&@*#K`U&T}fm#Q)O!+Zu*w>K{e73W)*!>TNnYTl2=xqXhLihyID%ORA%^3(l zFcRd&_}D#s0#=X$Z7^t2LsL>F;MQxP9JL%m*L$f?4HuEd2wI#)_^Fg1YM;mu5(_}t zf+7ww|5@oxJPAG!4oLuJ%pJJ`O?EIGEMMu$5D4q#l0ihT2#NQ<Ck3IB1RN5W=zs|? z<g3`rGL$m=M*nnh8T<i7^ZzJzpsA{e0(Izp4*V;%522ES_6(@ofc}adMb0ya{u!kA zrh|E}_4Se1YoNtXMCwl~3@+^7x`FH`uT)+bei8r<k_V*IYo1@e0Glx22G>XI!Fvnq z4hndEQ`4KIq&C=~2J$1VLL+}rgu+j^fIJ?%Bv|=TYj1C;uul_o_`nCeV!40c98@|e zUemw#;42<D_Oy4SMcx&F>K-y`D88{58Nn6Mb^x8?*5)RxBI1U`0BHeq1NPR&w9=K& zPPRK?lk$M*TP7b3VrA?lgK$YH^rFeSq3qs1%dI-T>bv}GQ1GnH<H03a8)mZ$C={)q z_HWAkctHu|S5#X@_XUP<bxQTue7Ikc%+w>(X0>0a>+YMpdUV%52_GYohvY=|KV~tz z!BXEgMDm8nCZBubs`1(cldXr{Y0u=|vxoBXMOp}EZ{WQ`C<1E&)Ka<vAF){5|GEr{ zML%l3jPi2q@5*2=8?1H}zWckek${trKuL2@Xk{Oy#WB~mK>yqPhI^PDp~DIqbV&X$ zUcBg({?LQFzW=p20Bz*tAzNFvmAQAAqk&Z|*#tkHz{|^PQi4G6!61!uwl$}FT3Zuw z$3W18Al%&C47&u)m!vUV1n+AMvnQzesDTAi>BL1(|H*++g6c96k>L#^XdJ<={y)`R z`6HD3+kR}vd?}$Ub*!awNZMo#35ldlvPBCaMz*nKO$sM;$|&n7TO!G%Fr_S|Q;d{t zB$1^!V=M>R@?P^Uf5h7lq8{@+&*yW0?&Z4g>&pM%s|4hdI_9IhA!xyUlAPk=Et@u( zIy&~ed2^K_OdO6axwnO??)0#<G#e;=YU=)K0oq3xgn8c4z`$8ZN<{wORrDuMAV)z` zOyBKww}-c-5^*{FXP=<RRe*Er@Y#m)6^Y^#lasBjt>#u%>dMMATonhxos#(5XaV8( zO-=52wXh;OA8izn)X({OGK>^NM+5-6AE9I7;xY(0^tiP(kOy44AkonA`Nc`A>gXo9 zQxRV#ZaR-DOF?G<j0l9qfuW&88Co|eB9V(;osagaq=4560zj0%MUY<B1fhE17+=qd z?@Ie#A4(})?(LG7HwbPySbb&C;qt*1KdGFF>qQ>xOkH^)Cm>R{&6mk*A}J%oz+5SI z7a!e9=1DGZZ9S^0swyFof^RU#TD5&eUEzZV7It=wne1an*n2g9)7cm1*!FQmkgnR9 zwERjTU}eed&({}A|6pdfov^m<t4eIedI$*%Lr%xyz=64en^tbaMB_1MXOJi%!t$T# zoPDIei(2rs5OebWS#rpNnM@IB%%*1Dpk|4&h1}#f+|*c{F*Y&D1KuA*e%y*MN)G$o zB_blip^a}hrge~&>&bb8h)1^%Kkw#dM!H`bYOKp|_~Tl(zN_@wY^KeTBd^+zm}1bJ z(_2$xrW79+m(#<mpo!?dqAn;T1Qzs>Jl6w&lcYFHj(59CC})P|tv71iFCS(+p5`}L z|7`+blNo7ZYU-wW9(HO#0jr^*VGSsb$xNcWlaDb{RLq_H+m@wBm={cr*iQB?3zh}k z`h;EQ=iO^!0-dW+Y^eV&Xefc-saVfsTJ7I|mC`JqfACK2pf4xol!rSRMn!W_Db3mt zqot)K>M5Jo(07rm=0NHKs|%nxmd@YI-=A)#v}61BiGTmi?U~$sNk0PcLo0RY!Q6jv z6mOXYe?TW3`C>WLbCO{&J5iKk0^7#M#`_E74n_Fo!UZ5BVV_mBv~Iuo_Mthr3v<yV zMX6(nZ_foWq-hBmR`E(PjAzs86^Tc?q5G5iZl$oWs=9hX5AS#u<)2O;;N!5;=5);@ ziiIu)s38Ql`0vD0tKWU@1Jw5XE+t1zm6n#~;>U7Wc@OyXv9U22S_w0N_)bB;Q)b;d zb5d8?S;5o?*9=;oIgm%I^#){m=N4_%*fIq5<}QtMGAk8hf`WsAc9l=l*8g&gd`L&b zR86hq*|TRj!Z>c6_n=5`kz}T6Slr+Q_m7QjT_coj@ZdngXR~U7$U)yTl=h|SRu+o| z>70hWp0X|lrKP<g3C1`<C>>bZ1jkTG+{DDh-OY_lE2rC^x?0yKqwQ<#<g|RkXDsiN zGOj7Mru^|hX+bIJO+tM9Q5%~G9~pbW#@=5un!>^fa7C8@nBld*oEUwsARUW>$~s2Z zh=Jk%C8T9$q_@|*Y%}6!$N7_M(xqB&zHqW6bzw_!>RI7Jv%mO_NN6E(;n%h{=(WY( z5F>MVdklkueu7R5bQd}@GyO+`1*F8p$~?Pv7&YEfUy8NLGSL-`-1B#WpZIL?nRAa3 zrk}pBCEKe2HK!dBh<5?zjUo2j+yUgKXojt2%S37x!o7hp1bh{q15l>>Frx&!2-^o; zre|K`>Ch{+)vwTsyApas&v16VyGP?Mp9|!F$hF(pBC^q=I^(ryO$zYtJ$v>W3Wzmx z?pZ`kGW@Tcw(mJ$>Y%aF?Z4O>8P!UmXTCV+m*uLyFxM+G_wyLbgy^yEYIt8Pzpufn z2s%{|AE9n_WR0bs9(^f~1hu2YezPbkK0f}_r%$kPy1KeLv$^?@qvH|+D?}o4GpF>) zy)W2fV_E6x7Noui=j|RNwXg2UR;m=ytBESX*c&NQgAQhimrjP?5k2GOB`YB@-RkGh zs%?)l*rln7T9vDAprmA+L#C0&jr{z|uU~Hh!X6zR4Xup*y2DG`SCpeYg_Z1RZx=TT zveR)ran`a}f6U-qu1Jk~-$ge;UgeDQ8ml<HTdMrnpV_K4*RqeVHbO*zuE6u>&#jLi zKQ(o|Q)hfLv~PeX4o?Ja+_(`vx4W5q<B!q&dim1O!r~pKOe#wMVCO4|AAq0<?hV<9 zFEd(J$M)B7BB?{BcBhH>dj%DztOu{h_KvXRcJ15=(#0IGU5#D4z6AZ|DI3&<L4z=e zfZ$A{_VpdVYH?V}#l?j;%1|X`Xkg&r?QKz%M7@-hl)QohM2R&L64ob9>{xN{!nw)Z z5fS!QV*bzf{MJuP#f)HICB?-tMmfOvQc~Kwmt(PBscr4;Lj2K1MMYTnEq3&46p@#l zb33|_xMA9yy2VypOl+@ifgiRJaY{o|^P>n4&C1a+lR5mmv@~OO?V|viEL<`W+V&40 zDnq6{a1^kqqDGAd%X7?{U(=;<)zu->MTv<bIP2ec;}^mJdjlp9^!Gn#+0b++>IK*( zB!1qqlNrg$U%|}K6(p)wf8M~$3Pb_4XU}u6$GC(tGLOrfZSUb@>(5NU>Y{S^2#%1w zAgiFDKuS{5lmxl27l38hGKW3TV|drx41ybZ$y=QGn)!A6mLORhn~s<m{?O0`RF{lR z!iCDJs^w*6VhIgMB_a5<j{A7w7aavpod@1tRaJ$w4cb+7d&9NRxdD%@?BpVpZ%%(F zUM{?9kLuXIYZs{TqKft1-PH_621P^}T(OqgS|flTdLaS?XJyjqSLr~A<pG?1Dm(&9 zfjA5;lke|-6oE+2FSxtEWip>Wd6JjONAyTM9DSM2MkbBpjA={gP;FpK9+ni3JNIjG z4qws1lGY(w#GXN2DGvtL+?*(i9CIi6vldJHWq8S~iWrH%p`qbf8i|mN!T~-3nvs;K zs6vW4FjxSg`*a0QZr!wL2;Km#a!eB{#flLAqPT7MU*>sGAA!hFps%m_fde_2e8tvB zj+{Pwb_&`kPyxc&VM{YlBzaXwz*n#Pg@vG=Acx7z&j+C=og(t+7})-B-0(OfLqoCH z7vHE7J`U#K6fpQu*N2v_sgn4IW*$j9XbZxLAT_e@{f8iE-yQ{g?SU9u9oDe2va6}7 zq@sd~5B%H8U}=q{<m*9Spc@xA`w_`fdQK4d!hJwd1w9L+U0CKyhb^wjmw{-3bJ5Y! z!NKYQJV3;b+%s-3^yN-knjLC_Y^IgDIST?hY#C?1vXlRSJLlwN5IW<zLY7EYcj$<k zy_J%(ag9)=1NrDtEa^=dCU@@QbGXGT9IABaMNPy2nomeftf12w5DbHEjtp}J5s7zH z2Rf#pU}$f@fP{5&zUe8X3oU<N%wB9)PA%WN`G@x>RgOa(<5%ADH~Ho9nHj`J{fJ+S z$%^|1d=C+kQpeo|4K*PO5D0=RN+ag&?e}Oj!(+$FzYQ1PzaKnl|Lw7@e5Gzg=S2D5 z^FJ56e^y&FmBiy5nyHzY?9tJ8eHRnu4HB{9nLPG_U*xaWahnEj{#-jXT3Qnl6eMF1 zo>AA=IQV}4c@W=xzl)Yo(bb~QS;IEAwm<s&k+}AAI0gYD$AdE^37VRo=31RxAQ`9y zVg5MPDB|dTG~N59rGY*^_$noI1#L9$`aZ!iz6bS7NJ=4`J3BjHx}?XJ`7Q_70cjIR zlEgx`5Dj659}nR#w|I$1`!*~Np%53qQW6pp+=mS{MMXs~LUkc5Y^lE9nBk>B_^Wuz zCa(hT6V*bTF?SXN*#=DS3I$?^z|abdiZ*T9WOwo;{*9p4wewWQVOPq_tC20jWi_1H zj?;e_P0oq&afKMLYP~TS%YELZM*)Up#2XO5@YG08F=(TjV(u;#Ra*(H6?$2qA(fVL z`Wx_IMC8$z?L5J)9UU;7{;4_mhg#jGI*a-<W##35aDI?#gfr(}_!t*zmp^)hfn6Ma zz+`VYJA-mwy!e6vpSyQ4@goK-DX33^@L#+5jAstiFt0F)c>rAzs3ch0hS|pJp+d+t zs=PcGb914jH}@R*33GmXL7j%p*_Xs|2DbfKT^)-5V$0CtPD`&^l>`@qE(t~n?l6Zx zZsjEgqf7WQT^iygxHYu2YkRTnl`B{1ev#`i?p9c+j2wzi-v#&w=?%>v`?eY_X}Ef` zEt1{c-A>O#QYa#aMa9J*U+CBx5HJmiCIC|(vA!-b_}puCec%H}KsOI_;y}j+2M6g1 zv}3oZR7i77MI>>0sx{G_c{ljFp`ok0J1|U|AmAOF^Y7jjmzP&xBLuNWHz*W>d&n|T zh`@Ft4u$=2#!NG!y|zp<fSZe}{0JHeubhb*lN&OCU+H7K2FiKX*4Fd{!>qLQ^dwo` znbvk~pZ<D80Foj+{DrX8a|B_BH&S);@YwX<AayF0iYlorKR=ct)@XU=Og{ogbB6Xu zY<-B5wstVSKYHIEH916hR`%!-gs1HH^)Plo@F>hMbC-Wux&HI%>*(Ez8`Yoj2@ls- z#P3y3ZxuyBv5G{ZISO(QzT-9KFyb-lQ-IRCIy&ubZ6CHqCl(bKAGEUaUeZ!iQv*7H zE+5ihD5?Q-$m{-%XhFEDx|NfIA>uyn%**;4hm`@B=Q;ArivJHe*g)T>KL$o-VUbW! zFpN>NAF+_J<=(IaKnfxf=-tqj!O8$(qbCfwc4l0bSd~RzitK^V7IM9Wn&QGjH&0Kf zLVO0g)}TT}raF%j0%-TEsi>^e@ptp_Da*`s49w8oyu-UwJz>nii<8WpjaZ%LyU_Qs zB71uF5xeB$lp|AnU}`DwLDt*SvX6Orc|dCm*kY&+v4gn<1vSq)q1P%~A=2^z(tmJz z|KX2@`CSJphT4ao@MW*D!;zM#MGdF0OH1|rjHRhJC#Nmd7;Q7cLpnks?nNK|9^Ju} zHvMt!xC&QU7jCz*GWhV}7F4_UV|WPql@h*BFq~m7G~WqxgP(g*&1m{MW%{<_>~QTR z*^Jj|7u*ZiexG*G3j6sN(~}i$+5P4b+2GRr+|!AnhrJQI3?>VTTiY*Rc8%riQA`_= z)$M=R_;sH^jA(X`tyRQ@v=<`-*VH#e{PE+rWn~P@U_Qucx(l#2k~b85U|TZoi4!e( z=DNhKb=gcNWPt(opcRZskW4DowEBBfyg6#Ao2Iub_B8g<mm7|*-KnlHp)Rs7$(y29 zW20F&ThMoTh2V6@hM41eL4VOl)%#x$B}vKoWuB|7>(;;jb=iuY(bijNGrVlsxEHvV z@%rGl^B64zQ&>ip`v<6A)ebavHg@V5-pS8*rBEs`9pvhopP9*>lyZ}LzL#BY`ur5b z=6ZUn!?T(3;CuBKn$3)^<;DH_cS6$rysF*P#H;Tvid=PbFT5^&=2FSskWRzPhnlF> zSk}};xYatuB*4``Tfh-{*WhxNI84IbvZ>S)zP^tW5-dDCM&J=pK}3bCpXw<$jSU`r zl2K9QG4ddL_n$u}XQfm%4&*vn%C^s!J=|S7%@?3y9hbYX=jKxgdQJ1e@o;B>Hg66M z4fXQ!s<I}CWnp{4HPLBlEQlRp+JIFRARU|I_^<iy%h#oA2PAvS78(Z{UfEd6^X;+x zsIN08I8@VgN83BN%xrsScQ+Hq84p`q8x5f5<>=S-JC%j3t=n*7AzYNEJmbBT#gM!3 zV!qQaG=$Y9<a2qzr)R41*v5r#39P054=2LT?XWd=xRGn3a`v{<J2~rLb8SDoez-sA zoeO*#+!SnVTn}7on?GSV(N`s+EGlw!!x|yX-dX7mtfV&6Ka4gA@39M-I+VG|s*N0T zzqhuG9iCStG#hknl=b|4g{<zI!M{%Pt*i)U)r`<p4dly|2ZpJVKl%ciS9{I}+UXOK zzJ1D*mj!4sV2fkK^B>OXQSDGAwxnC{$)vMS#|!`~)|to>-zCSTB_SvOXl(^oUH<>g zUw2g4L?p#CanZ$ZK%K5i3tO?TnjpS9I*&%4L1J-Q+7*Ky^nG6g%q=X`wrp{;Aqa+q i$Yq0jJb25{CBfVqxAs4qzmtQXhyx~vj2{{~NB<YZaK2gq literal 0 HcmV?d00001 diff --git a/docs/reference/gdata-docs.xml b/docs/reference/gdata-docs.xml new file mode 100644 index 0000000..a071a97 --- /dev/null +++ b/docs/reference/gdata-docs.xml @@ -0,0 +1,318 @@ +<?xml version="1.0"?> +<!DOCTYPE book PUBLIC "-//OASIS//DTD DocBook XML V4.3//EN" "http://www.oasis-open.org/docbook/xml/4.3/docbookx.dtd" [ + <!ENTITY % local.common.attrib "xmlns:xi CDATA #FIXED 'http://www.w3.org/2003/XInclude'"> + <!ENTITY % gtkdocentities SYSTEM "xml/gtkdocentities.ent"> + %gtkdocentities; +]> +<book id="index" xmlns:xi="http://www.w3.org/2003/XInclude"> + <bookinfo> + <title>GData Reference Manual + for GData &package_version;. + + + + + GData Overview + + + + Object Hierarchy + + + + + + Core API + + Core API + + + + + + + + + + + + + + Access Control List API + + + + + + Batch Operation API + + + + + + Authentication/Authorization API + + + + + + + + + + Comment API + + + + + + + Namespace API + + Atom API + + + + + + + + Atom Publishing Protocol API + + + + + GData API + + + + + + + + + + + + + + GContact API + + + + + + + + + + + Media RSS API + + + + + + + + YouTube API + + + + + + + + + Service APIs + + YouTube API + + + + + + + + + Google Calendar API + + + + + + + + + + Google Contacts API + + + + + + + + Google Documents/Drive API + + + + + + + + + + + + + + + + + + + Google PicasaWeb API + + + + + + + + + + + Google Tasks API + + + + + + + + Google Freebase API + + + + + + + + + + + + Appendices + + API Index + + + + Index of deprecated symbols + + + + Index of new symbols in 0.1.1 + + + + Index of new symbols in 0.2.0 + + + + Index of new symbols in 0.3.0 + + + + Index of new symbols in 0.4.0 + + + + Index of new symbols in 0.5.0 + + + + Index of new symbols in 0.6.0 + + + + Index of new symbols in 0.7.0 + + + + Index of new symbols in 0.8.0 + + + + Index of new symbols in 0.9.0 + + + + Index of new symbols in 0.9.1 + + + + Index of new symbols in 0.10.0 + + + + Index of new symbols in 0.11.0 + + + + Index of new symbols in 0.13.0 + + + + Index of new symbols in 0.13.1 + + + + Index of new symbols in 0.13.3 + + + + Index of new symbols in 0.13.4 + + + + Index of new symbols in 0.15.0 + + + + Index of new symbols in 0.15.1 + + + + Index of new symbols in 0.16.0 + + + + Index of new symbols in 0.17.0 + + + + Index of new symbols in 0.17.2 + + + + Index of new symbols in 0.17.7 + + + + Index of new symbols in 0.17.9 + + + + Index of new symbols in 0.17.10 + + + + Index of new symbols in 0.17.11 + + + + + diff --git a/docs/reference/gdata-overrides.txt b/docs/reference/gdata-overrides.txt new file mode 100644 index 0000000..e69de29 diff --git a/docs/reference/gdata-overview.xml b/docs/reference/gdata-overview.xml new file mode 100644 index 0000000..d2709d2 --- /dev/null +++ b/docs/reference/gdata-overview.xml @@ -0,0 +1,244 @@ + + + + + GData Overview + 3 + GDATA Library + + + GData Overview + overview of libgdata's architecture + + + + Introduction + libgdata is a library to allow access to web services using the GData protocol from the desktop. The GData protocol is a simple protocol for reading and writing + data on the web, designed by Google. + + + Protocols + Google's services were originally only accessible using an XML-based protocol called GData. However, later additions + to the set of available services use a REST-style JSON protocol. libgdata supports both protocols, although specific + services use exactly one of the two protocols. + The core API in libgdata transparently supports both protocols, so client code need not consider which protocol to use. + + + + XML protocol + The GData XML protocol is designed by Google to allow interaction with their web services. It is based on the Atom Publishing + protocol, with namespaced XML additions. Communication between the client and server is broadly achieved through HTTP + requests with query parameters, and Atom feeds being returned with result entries. Each service + has its own namespaced additions to the GData protocol; for example, the Google Calendar service's API has + specialisations for addresses and time periods. +
+ + + + An overview of the data flow when making a request of a GData service. +
+
+ Results are always returned in the form of result feeds, containing multiple + entries. How the entries are interpreted depends on what was queried of the service, but when + using libgdata, this is all taken care of transparently. +
+ + + JSON protocol + The more recent JSON protocol is similar in architecture to the XML protocol: entries are arranged into feeds, and the core + operations available are: listing all entries, getting a specific entry, inserting an entry, updating an entry and deleting an entry. + The key difference between the two protocols, apart from the serialisation format, is that the JSON protocol is not namespaced. Each + service uses a specific JSON format, and there is no formal sharing of data structures between services. For example, every entry + in the XML protocol is required to have a title, ID and update time (as per the Atom specification). Such commonality between + JSON entries is purely ad-hoc. + Differences between the XML and JSON protocols are hidden by the libgdata API. Both protocols are implemented by the standard + GDataService, GDataFeed and + GDataEntry classes. + + + + Structure + The basic design of libgdata mirrors the protocol's structure quite closely: +
+ + + + An overview of the libgdata class structure. +
+
+ + + GDataService + Subclassed for each different web service implemented, this class represents a single client's + connection to the relevant web service, holding their authentication state, and making the necessary + requests to read and write data to and from the service. All top-level actions, such as creating a new + object on the server, are carried out through a service. + There should be one GDataService subclass for + each of the services listed in the GData + documentation. + + + GDataQuery + For queries to have multiple individual parameters, a + GDataQuery can be used to specify the parameters. + Query objects are optional, and can only be used with queries (not with entry insertions, updates + or deletions). The query object builds the query URI used by the + GDataService when sending the query to the + server. + Services can subclass GDataQuery if the service + supports non-standard query parameters. + + + + GDataFeed + Effectively a list of GDataEntrys, the + GDataFeed class is a direct counterpart of the root + <feed> element in the Atom feeds which form the GData protocol. It contains the + elements in a query response, as well as general information about the response, such as links to + related feeds and the categories under which the query response falls. + GDataFeed is usually not subclassed by services, + as there are rarely service-specific elements in a feed itself. + + + GDataEntry + A GDataEntry is a direct counterpart of the + <entry> element in the Atom feeds which form the GData protocol. It represents a + single object of unspecified semantics; an entry could be anything from a calendar event to a video + comment or access control rule. Semantics are given to entries by subclassing + GDataEntry for the various types of entries returned + by queries to a service. Such subclasses implement useful, relevant and query-specific properties + on the entry (such as the duration of a video, or the recurrence rules of a calendar event). + + + +
+
+ + + Development Philosophy + As the GData protocol (and all the service-specific protocols which extend it) is reasonably young, it is subject to fairly + frequent updates and expansions. While backwards compatibility is maintained, these updates necessitate that libgdata + remains fairly flexible in how it treats data. The sections below detail some of the ways in which libgdata achieves this, + and the reasoning behind them, as well as other major design decisions behind libgdata's API. + + + Enumerable Properties + There are many class properties in libgdata which should, at first glance, be implemented as enumerated types. Function + calls such as gdata_link_get_relation_type() + and gdata_gd_im_address_get_protocol() + would, in a conventional library, return a value from an enum, which would work well, and be more typesafe and + memory-efficient than using arbitrary strings. + However, such an implementation would not be forwards-compatible. If a protocol addition was made which added another + link relation type, or added supportf or another IM protocol, there would be no way for libgdata to represent some + of the data it retrieved from the server. It could return an “other” value from the enum, but that could lead to + data loss in the common case of GData entries being queried from the server, processed, then updated again. + For this reason – which is made more troublesome by the fact that it is unpredictable when updates to the protocol are + released, or when updated XML/JSON will start coming over the wire – libgdata uses enumerated types sparingly; they are + only used when it is very improbable (or even impossible) for the property in question to be extended or changed in + the future. In any other case, a string value is used instead, with libgdata providing #defined values + for the known values of the property. These values should be used as much as possible by applications which use + libgdata (i.e. they should be treated as if they were enumerated values), but applications are free to use strings + of their own, too. All validation of such pseudo-enums is left to the server. + One situation where it is acceptable to use enumerated types is in API which is only ever used to query the server, and + isn't involved in processing or representing the response at all, i.e. subclasses of + GDataQuery. + + + + String Constants + As the protocols are XML- or JSON-based, they make extensive use of string constants, typically as + enumerated types or namespaced URIs. To stop the authors of applications + which use libgdata from having to continually look up the correct “magic strings” to use, all such strings should + be #defined in libgdata, and referenced in the appropriate function documentation. + + + + New Services + The API required to implement support for a new service using libgdata is not publicly exposed. This is because doing + so would clutter the API to a large extent; for example, exposing various properties as writeable which are currently + only readable. While the freedom for users of libgdata to write their own services is a good one, it is outweighed by + the muddlement that this would bring to the API. + Furthermore, since it is highly unlikely that anyone except Google will use GData as a basis for communicating with + their service, there is little harm in restricting the implementation of services to libgdata. If someone wants to + implement support for a new GData service, it is for the benefit of everyone if this implementation is done in libgdata + itself, rather than their application. + + + + Cancellable Support + As libgdata is a network library, it has to be able to deal with operations which take a long (and indeterminate) amount + of time due to network latencies. As well as providing asynchronous operation support, every such operation in libgdata + is cancellable, using GCancellable. + Using GCancellable, any ongoing libgdata operation can be cancelled + from any other thread by calling g_cancellable_cancel. + If the ongoing operation is doing network activity, the operation will be cancelled as safely as possible (although + the server's state cannot be guaranteed when cancelling a non-idempotent operation, such as an insertion or update, + since the server may have already committed the results of the operation, but might not have returned them to libgdata + yet) and the operation will return to its calling function with a + G_IO_ERROR_CANCELLED error. Similarly, + if the operation is yet to do network activity, it will return with the above error before the network activity is + started, leaving the server unchanged. + However, if the operation has finished its network activity, libgdata does not guarantee that it will return with an + error — it may return successfully. There is no way to fix this, as it is an inherent race condition between checking + for cancellation for the last time, and returning the successful result. Rather than reduce the probability of the race + condition occurring, but still have the possibility of it occurring, libgdata will just continue to process an operation + after its network activity is over, and return success. + This may be useful in situations where the user is cancelling an operation due to it taking too long; the application + using libgdata may want to make use of the result of the operation, even if it has previously tried to cancel the + operation after network activity finished. + The behaviour of cancellation in libgdata can be represented as follows: +
+ + + + The behaviour of cancellation in libgdata. +
+
+
+ + + Privacy + Privacy is an important consideration with code such as libgdata's, which handles valuable data such as people's + address books and Google Account login details. + Unfortunately, it's infeasible for libgdata to ensure that no private data is ever leaked from a process. To do this + properly would require almost all the data allocated by libgdata (and all the libraries it depends on, all the way down + to the TLS implementation) to use non-pageable memory for all network requests and responses, and to be careful about + zeroing them before freeing them. There isn't enough support for this level of paranoia in the lower levels of the + stack (such as libsoup). + However, it is feasible to ensure that the user's password and authentication/authorization tokens aren't leaked. This + is done in several ways in libgdata: + + + If libgdata is compiled with libgcr support enabled (using the + --enable-gnome configuration flag), it will use libgcr's support for + non-pageable memory. This will try hard to avoid passwords and auth. tokens being paged out to disk at + any point (although there are circumstances, such as when hibernating, where this is + unavoidable). + Otherwise, libgdata will ensure that passwords and auth. tokens are zeroed out in memory before being + freed, which lowers the chance of them reaching disk at a later stage. + + + Unless run with LIBGDATA_DEBUG set to 4, libgdata will attempt to + redact all usernames, passwords and auth. tokens from debug log output. This aims to prevent accidental + disclosure of passwords, etc. in bug reports. Currently, this is implemented using a fixed set of + search patterns, so it's possible that certain bits of private information will not be redacted; any + such occurrence is a bug which should be reported on + GNOME + Bugzilla. + + + + libgdata universally uses HTTPS rather than HTTP for communicating with servers. The port which is used may be changed + for testing purposes, using the LIBGDATA_HTTPS_PORT environment variable; but the protocol used will + always be HTTPS. + + libgdata provides ways to upload and download files, but does not implement code for loading or saving those files to + or from disk. Since these files will typically be user data (such as their Google Drive documents), it is highly + recommended that they are given restricted permissions, any temporary files are only readable by the current user, + and files are potentially encrypted on disk where appropriate. The aim is to avoid leaking user data to other users + of the system, or to attackers who gain access to the user’s hard drive (which may not be encrypted). libgdata itself + only guarantees that data is encrypted while being sent over the network. + +
+
diff --git a/docs/reference/gdata-running.xml b/docs/reference/gdata-running.xml new file mode 100644 index 0000000..c78a2a3 --- /dev/null +++ b/docs/reference/gdata-running.xml @@ -0,0 +1,84 @@ + + + + + Running GData Applications + 3 + GDATA Library + + + Running GData Applications + running and debugging GData applications + + + + Running and Debugging GData Applications + + + Environment variables + libgdata makes use of a few environment variables which affect how it runs, mainly with respect to debugging. + + + <envar>LIBGDATA_DEBUG</envar> + If this environment variable is set to one of the following values, libgdata will give debug output + (at various levels). If it's unset, no debug output will be produced. + + + 0 + Output no debug messages or network logs. + + + 1 + Output debug messages, but not network logs. + + + 2 + Output debug messages and network traffic headers. + + + 3 + Output debug messages and full network traffic logs. + + + + So, to debug a program which uses libgdata, run it from a terminal with the following command: + $LIBGDATA_DEBUG=3 ./my-program-name &> libgdata.log + + + + + Debugging Advice + The easiest way to debug problems with libgdata is to use the + LIBGDATA_DEBUG environment variable to observe all the network + traffic being transmitted and received by libgdata. Typically, any problems will occur in the final network + request/response, which is the last one in the log output. + If debugging using the environment variables and log output is not possible, it is sometimes possible to diagnose problems + by examining the error responses sent by the Google servers to libgdata. These are exposed as the error messages returned + by libgdata methods; so when handling errors from libgdata method calls, it is a good idea to output the message from + the GError to a debug log, or even as a warning in the user's + .xsession-errors file. + + Error Handling when Uploading a Document + + GDataUploadStream *upload_stream; + GError *error = NULL; /* make sure to initialise the GError to NULL */ + + /* Other code goes here. */ + + upload_stream = gdata_documents_service_upload_document (service, document, slug, content_type, destination_folder, NULL, + &error); + + /* Handle any errors. */ + if (error != NULL) { + /* Note that the error message is outputted to the terminal/logs. + * It will contain important debugging information from the Google servers. */ + g_error ("Error getting upload stream: %s", error->message); + g_error_free (error); + + return; + } + + + + + diff --git a/docs/reference/gdata-sections.txt.in b/docs/reference/gdata-sections.txt.in new file mode 100644 index 0000000..e159b00 --- /dev/null +++ b/docs/reference/gdata-sections.txt.in @@ -0,0 +1,2911 @@ +
+gdata-version +Version Information +GDATA_MAJOR_VERSION +GDATA_MINOR_VERSION +GDATA_MICRO_VERSION +GDATA_CHECK_VERSION +
+ +
+gdata-service +GDataService +GDataService +GDataServiceClass +GDataServiceError +GDataParserError +GDataOperationType +GDataQueryProgressCallback +gdata_service_is_authorized +gdata_service_get_authorizer +gdata_service_set_authorizer +gdata_service_get_authorization_domains +gdata_service_query +gdata_service_query_async +gdata_service_query_finish +gdata_service_query_single_entry +gdata_service_query_single_entry_async +gdata_service_query_single_entry_finish +gdata_service_insert_entry +gdata_service_insert_entry_async +gdata_service_insert_entry_finish +gdata_service_update_entry +gdata_service_update_entry_async +gdata_service_update_entry_finish +gdata_service_delete_entry +gdata_service_delete_entry_async +gdata_service_delete_entry_finish +gdata_service_get_proxy_uri +gdata_service_set_proxy_uri +gdata_service_get_proxy_resolver +gdata_service_set_proxy_resolver +gdata_service_get_timeout +gdata_service_set_timeout +gdata_service_get_locale +gdata_service_set_locale + +GDATA_SERVICE +GDATA_IS_SERVICE +GDATA_TYPE_SERVICE +gdata_service_get_type +GDATA_SERVICE_GET_CLASS +GDATA_SERVICE_CLASS +GDATA_IS_SERVICE_CLASS +gdata_service_error_quark +GDATA_SERVICE_ERROR +GDATA_PARSER_ERROR +gdata_parser_error_quark + +GDataServicePrivate +
+ +
+gdata-query +GDataQuery +GDataQuery +GDataQueryClass +gdata_query_new +gdata_query_new_with_limits +gdata_query_get_query_uri +gdata_query_next_page +gdata_query_previous_page +gdata_query_get_q +gdata_query_set_q +gdata_query_get_etag +gdata_query_set_etag +gdata_query_get_author +gdata_query_set_author +gdata_query_get_categories +gdata_query_set_categories +gdata_query_get_published_min +gdata_query_set_published_min +gdata_query_get_published_max +gdata_query_set_published_max +gdata_query_get_updated_min +gdata_query_set_updated_min +gdata_query_get_updated_max +gdata_query_set_updated_max +gdata_query_get_start_index +gdata_query_set_start_index +gdata_query_get_max_results +gdata_query_set_max_results +gdata_query_is_strict +gdata_query_set_is_strict + +gdata_query_get_type +GDATA_QUERY +GDATA_QUERY_CLASS +GDATA_QUERY_GET_CLASS +GDATA_TYPE_QUERY +GDATA_IS_QUERY +GDATA_IS_QUERY_CLASS + +GDataQueryPrivate +
+ +
+gdata-feed +GDataFeed +GDataFeed +GDataFeedClass +gdata_feed_get_title +gdata_feed_get_subtitle +gdata_feed_get_id +gdata_feed_get_etag +gdata_feed_get_authors +gdata_feed_get_categories +gdata_feed_get_entries +gdata_feed_look_up_entry +gdata_feed_get_generator +gdata_feed_get_links +gdata_feed_look_up_link +gdata_feed_get_logo +gdata_feed_get_icon +gdata_feed_get_updated +gdata_feed_get_rights +gdata_feed_get_start_index +gdata_feed_get_total_results +gdata_feed_get_items_per_page +gdata_feed_get_next_page_token + +GDATA_FEED +GDATA_FEED_CLASS +GDATA_FEED_GET_CLASS +gdata_feed_get_type +GDATA_IS_FEED +GDATA_IS_FEED_CLASS +GDATA_TYPE_FEED + +GDataFeedPrivate +
+ +
+gdata-entry +GDataEntry +GDataEntry +GDataEntryClass +gdata_entry_new +gdata_entry_get_title +gdata_entry_set_title +gdata_entry_get_summary +gdata_entry_set_summary +gdata_entry_get_id +gdata_entry_get_etag +gdata_entry_get_content +gdata_entry_set_content +gdata_entry_get_content_uri +gdata_entry_set_content_uri +gdata_entry_get_published +gdata_entry_get_updated +gdata_entry_get_authors +gdata_entry_add_author +gdata_entry_add_category +gdata_entry_get_categories +gdata_entry_add_link +gdata_entry_remove_link +gdata_entry_look_up_link +gdata_entry_look_up_links +gdata_entry_is_inserted +gdata_entry_get_rights +gdata_entry_set_rights + +gdata_entry_get_type +GDATA_ENTRY +GDATA_ENTRY_CLASS +GDATA_ENTRY_GET_CLASS +GDATA_IS_ENTRY +GDATA_IS_ENTRY_CLASS +GDATA_TYPE_ENTRY + +GDataEntryPrivate +
+ +
+gdata-youtube-service +GDataYouTubeService +GDataYouTubeService +GDataYouTubeServiceClass +GDataYouTubeServiceError +GDataYouTubeStandardFeedType +gdata_youtube_service_new +gdata_youtube_service_get_primary_authorization_domain +gdata_youtube_service_query_videos +gdata_youtube_service_query_videos_async +gdata_youtube_service_query_related +gdata_youtube_service_query_related_async +gdata_youtube_service_query_standard_feed +gdata_youtube_service_query_standard_feed_async +gdata_youtube_service_upload_video +gdata_youtube_service_finish_video_upload +gdata_youtube_service_get_categories +gdata_youtube_service_get_categories_async +gdata_youtube_service_get_categories_finish +gdata_youtube_service_get_developer_key + +GDATA_YOUTUBE_SERVICE +GDATA_YOUTUBE_SERVICE_CLASS +GDATA_YOUTUBE_SERVICE_ERROR +GDATA_YOUTUBE_SERVICE_GET_CLASS +GDATA_IS_YOUTUBE_SERVICE +GDATA_IS_YOUTUBE_SERVICE_CLASS +GDATA_TYPE_YOUTUBE_SERVICE +gdata_youtube_service_get_type +gdata_youtube_service_error_quark + +GDataYouTubeServicePrivate +
+ +
+gdata-youtube-video +GDataYouTubeVideo +GDATA_YOUTUBE_ASPECT_RATIO_WIDESCREEN +GDATA_YOUTUBE_ACTION_RATE +GDATA_YOUTUBE_ACTION_COMMENT +GDATA_YOUTUBE_ACTION_COMMENT_VOTE +GDATA_YOUTUBE_ACTION_VIDEO_RESPOND +GDATA_YOUTUBE_ACTION_EMBED +GDATA_YOUTUBE_ACTION_SYNDICATE +GDATA_YOUTUBE_LICENSE_CC +GDATA_YOUTUBE_LICENSE_STANDARD +GDATA_YOUTUBE_RATING_TYPE_SIMPLE +GDATA_YOUTUBE_RATING_TYPE_MPAA +GDATA_YOUTUBE_RATING_TYPE_V_CHIP +GDataYouTubeVideo +GDataYouTubeVideoClass +GDataYouTubePermission +gdata_youtube_video_new +gdata_youtube_video_look_up_content +gdata_youtube_video_get_thumbnails +gdata_youtube_video_get_category +gdata_youtube_video_set_category +gdata_youtube_video_get_credit +gdata_youtube_video_get_description +gdata_youtube_video_set_description +gdata_youtube_video_get_duration +gdata_youtube_video_get_keywords +gdata_youtube_video_set_keywords +gdata_youtube_video_get_location +gdata_youtube_video_set_location +gdata_youtube_video_get_view_count +gdata_youtube_video_get_favorite_count +gdata_youtube_video_is_restricted_in_country +gdata_youtube_video_get_media_rating +gdata_youtube_video_get_access_control +gdata_youtube_video_set_access_control +gdata_youtube_video_get_player_uri +gdata_youtube_video_is_private +gdata_youtube_video_set_is_private +gdata_youtube_video_is_draft +gdata_youtube_video_set_is_draft +gdata_youtube_video_get_state +gdata_youtube_video_get_rating +gdata_youtube_video_get_uploaded +gdata_youtube_video_get_recorded +gdata_youtube_video_set_recorded +gdata_youtube_video_get_video_id +gdata_youtube_video_get_video_id_from_uri +gdata_youtube_video_get_aspect_ratio +gdata_youtube_video_set_aspect_ratio +gdata_youtube_video_get_coordinates +gdata_youtube_video_set_coordinates + +GDATA_IS_YOUTUBE_VIDEO +GDATA_IS_YOUTUBE_VIDEO_CLASS +GDATA_TYPE_YOUTUBE_VIDEO +GDATA_YOUTUBE_VIDEO +GDATA_YOUTUBE_VIDEO_CLASS +GDATA_YOUTUBE_VIDEO_GET_CLASS +gdata_youtube_video_get_type + +GDataYouTubeVideoPrivate +
+ +
+gdata-contacts-service +GDataContactsService +GDataContactsService +GDataContactsServiceClass +gdata_contacts_service_new +gdata_contacts_service_get_primary_authorization_domain +gdata_contacts_service_query_contacts +gdata_contacts_service_query_contacts_async +gdata_contacts_service_insert_contact +gdata_contacts_service_insert_contact_async +gdata_contacts_service_query_groups +gdata_contacts_service_query_groups_async +gdata_contacts_service_insert_group +gdata_contacts_service_insert_group_async + +gdata_contacts_service_get_type +GDATA_CONTACTS_SERVICE +GDATA_CONTACTS_SERVICE_CLASS +GDATA_CONTACTS_SERVICE_GET_CLASS +GDATA_IS_CONTACTS_SERVICE +GDATA_IS_CONTACTS_SERVICE_CLASS +GDATA_TYPE_CONTACTS_SERVICE + +GDataContactsServicePrivate +
+ +
+gdata-contacts-query +GDataContactsQuery +GDataContactsQuery +GDataContactsQueryClass +gdata_contacts_query_new +gdata_contacts_query_new_with_limits +gdata_contacts_query_get_order_by +gdata_contacts_query_set_order_by +gdata_contacts_query_get_sort_order +gdata_contacts_query_set_sort_order +gdata_contacts_query_show_deleted +gdata_contacts_query_set_show_deleted +gdata_contacts_query_get_group +gdata_contacts_query_set_group + +gdata_contacts_query_get_type +GDATA_CONTACTS_QUERY +GDATA_CONTACTS_QUERY_CLASS +GDATA_CONTACTS_QUERY_GET_CLASS +GDATA_IS_CONTACTS_QUERY +GDATA_IS_CONTACTS_QUERY_CLASS +GDATA_TYPE_CONTACTS_QUERY + +GDataContactsQueryPrivate +
+ +
+gdata-contacts-contact +GDataContactsContact +GDATA_CONTACTS_GENDER_MALE +GDATA_CONTACTS_GENDER_FEMALE +GDATA_CONTACTS_PRIORITY_LOW +GDATA_CONTACTS_PRIORITY_NORMAL +GDATA_CONTACTS_PRIORITY_HIGH +GDATA_CONTACTS_SENSITIVITY_CONFIDENTIAL +GDATA_CONTACTS_SENSITIVITY_NORMAL +GDATA_CONTACTS_SENSITIVITY_PERSONAL +GDATA_CONTACTS_SENSITIVITY_PRIVATE +GDataContactsContact +GDataContactsContactClass +gdata_contacts_contact_new +gdata_contacts_contact_get_name +gdata_contacts_contact_set_name +gdata_contacts_contact_get_short_name +gdata_contacts_contact_set_short_name +gdata_contacts_contact_get_initials +gdata_contacts_contact_set_initials +gdata_contacts_contact_get_maiden_name +gdata_contacts_contact_set_maiden_name +gdata_contacts_contact_get_nickname +gdata_contacts_contact_set_nickname +gdata_contacts_contact_get_file_as +gdata_contacts_contact_set_file_as +gdata_contacts_contact_get_birthday +gdata_contacts_contact_set_birthday +gdata_contacts_contact_get_gender +gdata_contacts_contact_set_gender +gdata_contacts_contact_get_mileage +gdata_contacts_contact_set_mileage +gdata_contacts_contact_get_occupation +gdata_contacts_contact_set_occupation +gdata_contacts_contact_get_subject +gdata_contacts_contact_set_subject +gdata_contacts_contact_get_priority +gdata_contacts_contact_set_priority +gdata_contacts_contact_get_sensitivity +gdata_contacts_contact_set_sensitivity +gdata_contacts_contact_get_directory_server +gdata_contacts_contact_set_directory_server +gdata_contacts_contact_get_billing_information +gdata_contacts_contact_set_billing_information +gdata_contacts_contact_get_email_addresses +gdata_contacts_contact_get_primary_email_address +gdata_contacts_contact_add_email_address +gdata_contacts_contact_remove_all_email_addresses +gdata_contacts_contact_get_im_addresses +gdata_contacts_contact_get_primary_im_address +gdata_contacts_contact_add_im_address +gdata_contacts_contact_remove_all_im_addresses +gdata_contacts_contact_get_postal_addresses +gdata_contacts_contact_get_primary_postal_address +gdata_contacts_contact_add_postal_address +gdata_contacts_contact_remove_all_postal_addresses +gdata_contacts_contact_get_phone_numbers +gdata_contacts_contact_get_primary_phone_number +gdata_contacts_contact_add_phone_number +gdata_contacts_contact_remove_all_phone_numbers +gdata_contacts_contact_get_organizations +gdata_contacts_contact_get_primary_organization +gdata_contacts_contact_add_organization +gdata_contacts_contact_remove_all_organizations +gdata_contacts_contact_add_jot +gdata_contacts_contact_get_jots +gdata_contacts_contact_remove_all_jots +gdata_contacts_contact_add_relation +gdata_contacts_contact_get_relations +gdata_contacts_contact_remove_all_relations +gdata_contacts_contact_add_website +gdata_contacts_contact_get_websites +gdata_contacts_contact_get_primary_website +gdata_contacts_contact_remove_all_websites +gdata_contacts_contact_add_event +gdata_contacts_contact_get_events +gdata_contacts_contact_remove_all_events +gdata_contacts_contact_add_calendar +gdata_contacts_contact_get_calendars +gdata_contacts_contact_get_primary_calendar +gdata_contacts_contact_remove_all_calendars +gdata_contacts_contact_add_external_id +gdata_contacts_contact_get_external_ids +gdata_contacts_contact_remove_all_external_ids +gdata_contacts_contact_add_hobby +gdata_contacts_contact_get_hobbies +gdata_contacts_contact_remove_all_hobbies +gdata_contacts_contact_add_language +gdata_contacts_contact_get_languages +gdata_contacts_contact_remove_all_languages +gdata_contacts_contact_get_groups +gdata_contacts_contact_add_group +gdata_contacts_contact_remove_group +gdata_contacts_contact_is_group_deleted +gdata_contacts_contact_get_extended_property +gdata_contacts_contact_get_extended_properties +gdata_contacts_contact_set_extended_property +gdata_contacts_contact_get_user_defined_field +gdata_contacts_contact_get_user_defined_fields +gdata_contacts_contact_set_user_defined_field +gdata_contacts_contact_get_edited +gdata_contacts_contact_is_deleted +gdata_contacts_contact_get_photo_etag +gdata_contacts_contact_get_photo +gdata_contacts_contact_get_photo_async +gdata_contacts_contact_get_photo_finish +gdata_contacts_contact_set_photo +gdata_contacts_contact_set_photo_async +gdata_contacts_contact_set_photo_finish + +gdata_contacts_contact_get_type +GDATA_CONTACTS_CONTACT +GDATA_CONTACTS_CONTACT_CLASS +GDATA_CONTACTS_CONTACT_GET_CLASS +GDATA_IS_CONTACTS_CONTACT +GDATA_IS_CONTACTS_CONTACT_CLASS +GDATA_TYPE_CONTACTS_CONTACT + +GDataContactsContactPrivate +
+ +
+gdata-calendar-service +GDataCalendarService +GDataCalendarService +GDataCalendarServiceClass +gdata_calendar_service_new +gdata_calendar_service_get_primary_authorization_domain +gdata_calendar_service_query_all_calendars +gdata_calendar_service_query_all_calendars_async +gdata_calendar_service_query_own_calendars +gdata_calendar_service_query_own_calendars_async +gdata_calendar_service_query_events +gdata_calendar_service_query_events_async +gdata_calendar_service_insert_event +gdata_calendar_service_insert_event_async +gdata_calendar_service_insert_calendar_event +gdata_calendar_service_insert_calendar_event_async + +gdata_calendar_service_get_type +GDATA_CALENDAR_SERVICE +GDATA_CALENDAR_SERVICE_CLASS +GDATA_CALENDAR_SERVICE_GET_CLASS +GDATA_IS_CALENDAR_SERVICE +GDATA_IS_CALENDAR_SERVICE_CLASS +GDATA_TYPE_CALENDAR_SERVICE + +GDataCalendarServicePrivate +
+ +
+gdata-calendar-query +GDataCalendarQuery +GDataCalendarQuery +GDataCalendarQueryClass +gdata_calendar_query_new +gdata_calendar_query_new_with_limits +gdata_calendar_query_get_future_events +gdata_calendar_query_set_future_events +gdata_calendar_query_get_single_events +gdata_calendar_query_set_single_events +gdata_calendar_query_get_order_by +gdata_calendar_query_set_order_by +gdata_calendar_query_get_sort_order +gdata_calendar_query_set_sort_order +gdata_calendar_query_get_start_min +gdata_calendar_query_set_start_min +gdata_calendar_query_get_start_max +gdata_calendar_query_set_start_max +gdata_calendar_query_get_recurrence_expansion_start +gdata_calendar_query_set_recurrence_expansion_start +gdata_calendar_query_get_recurrence_expansion_end +gdata_calendar_query_set_recurrence_expansion_end +gdata_calendar_query_get_timezone +gdata_calendar_query_set_timezone +gdata_calendar_query_get_max_attendees +gdata_calendar_query_set_max_attendees +gdata_calendar_query_show_deleted +gdata_calendar_query_set_show_deleted + +gdata_calendar_query_get_type +GDATA_CALENDAR_QUERY +GDATA_CALENDAR_QUERY_CLASS +GDATA_CALENDAR_QUERY_GET_CLASS +GDATA_IS_CALENDAR_QUERY +GDATA_IS_CALENDAR_QUERY_CLASS +GDATA_TYPE_CALENDAR_QUERY + +GDataCalendarQueryPrivate +
+ +
+gdata-calendar-calendar +GDataCalendarCalendar +GDataCalendarCalendar +GDataCalendarCalendarClass +gdata_calendar_calendar_new +gdata_calendar_calendar_get_color +gdata_calendar_calendar_set_color +gdata_calendar_calendar_is_hidden +gdata_calendar_calendar_set_is_hidden +gdata_calendar_calendar_is_selected +gdata_calendar_calendar_set_is_selected +gdata_calendar_calendar_get_timezone +gdata_calendar_calendar_set_timezone +gdata_calendar_calendar_get_edited +gdata_calendar_calendar_get_times_cleaned +gdata_calendar_calendar_get_access_level + +gdata_calendar_calendar_get_type +GDATA_CALENDAR_CALENDAR +GDATA_CALENDAR_CALENDAR_CLASS +GDATA_CALENDAR_CALENDAR_GET_CLASS +GDATA_IS_CALENDAR_CALENDAR +GDATA_IS_CALENDAR_CALENDAR_CLASS +GDATA_TYPE_CALENDAR_CALENDAR + +GDataCalendarCalendarPrivate +
+ +
+gdata-calendar-event +GDataCalendarEvent +GDataCalendarEvent +GDataCalendarEventClass +gdata_calendar_event_new +gdata_calendar_event_get_people +gdata_calendar_event_add_person +gdata_calendar_event_get_places +gdata_calendar_event_add_place +gdata_calendar_event_get_times +gdata_calendar_event_get_primary_time +gdata_calendar_event_add_time +gdata_calendar_event_get_recurrence +gdata_calendar_event_set_recurrence +gdata_calendar_event_get_original_event_details +gdata_calendar_event_is_exception +gdata_calendar_event_get_anyone_can_add_self +gdata_calendar_event_set_anyone_can_add_self +gdata_calendar_event_get_guests_can_invite_others +gdata_calendar_event_set_guests_can_invite_others +gdata_calendar_event_get_guests_can_modify +gdata_calendar_event_set_guests_can_modify +gdata_calendar_event_get_guests_can_see_guests +gdata_calendar_event_set_guests_can_see_guests +gdata_calendar_event_get_sequence +gdata_calendar_event_set_sequence +gdata_calendar_event_get_status +gdata_calendar_event_set_status +gdata_calendar_event_get_transparency +gdata_calendar_event_set_transparency +gdata_calendar_event_get_uid +gdata_calendar_event_set_uid +gdata_calendar_event_get_visibility +gdata_calendar_event_set_visibility +gdata_calendar_event_get_edited + +gdata_calendar_event_get_type +GDATA_CALENDAR_EVENT +GDATA_CALENDAR_EVENT_CLASS +GDATA_CALENDAR_EVENT_GET_CLASS +GDATA_IS_CALENDAR_EVENT +GDATA_IS_CALENDAR_EVENT_CLASS +GDATA_TYPE_CALENDAR_EVENT + +GDataCalendarEventPrivate +
+ +
+gdata-types +GData Types +GDataColor +gdata_color_from_hexadecimal +gdata_color_to_hexadecimal + +GDATA_TYPE_COLOR +gdata_color_get_type +
+ +
+gdata-youtube-query +GDataYouTubeQuery +GDataYouTubeQuery +GDataYouTubeQueryClass +GDataYouTubeAge +GDataYouTubeFormat +GDataYouTubeSafeSearch +GDataYouTubeSortOrder +GDataYouTubeUploader +gdata_youtube_query_new +gdata_youtube_query_get_age +gdata_youtube_query_set_age +gdata_youtube_query_get_format +gdata_youtube_query_set_format +gdata_youtube_query_get_language +gdata_youtube_query_set_language +gdata_youtube_query_get_license +gdata_youtube_query_set_license +gdata_youtube_query_get_location +gdata_youtube_query_set_location +gdata_youtube_query_get_order_by +gdata_youtube_query_set_order_by +gdata_youtube_query_get_restriction +gdata_youtube_query_set_restriction +gdata_youtube_query_get_safe_search +gdata_youtube_query_set_safe_search +gdata_youtube_query_get_sort_order +gdata_youtube_query_set_sort_order +gdata_youtube_query_get_uploader +gdata_youtube_query_set_uploader + +GDATA_IS_YOUTUBE_QUERY +GDATA_IS_YOUTUBE_QUERY_CLASS +GDATA_TYPE_YOUTUBE_QUERY +GDATA_YOUTUBE_QUERY +GDATA_YOUTUBE_QUERY_CLASS +GDATA_YOUTUBE_QUERY_GET_CLASS +gdata_youtube_query_get_type + +GDataYouTubeQueryPrivate +
+ +
+gdata-access-handler +GDataAccessHandler +GDATA_LINK_ACCESS_CONTROL_LIST +GDataAccessHandler +GDataAccessHandlerIface +gdata_access_handler_get_rules +gdata_access_handler_get_rules_async + +gdata_access_handler_get_type +GDATA_ACCESS_HANDLER +GDATA_ACCESS_HANDLER_CLASS +GDATA_ACCESS_HANDLER_GET_IFACE +GDATA_IS_ACCESS_HANDLER +GDATA_TYPE_ACCESS_HANDLER +
+ +
+gdata-access-rule +GDataAccessRule +GDATA_ACCESS_SCOPE_USER +GDATA_ACCESS_SCOPE_DOMAIN +GDATA_ACCESS_SCOPE_DEFAULT +GDATA_ACCESS_ROLE_NONE +GDataAccessRule +GDataAccessRuleClass +gdata_access_rule_new +gdata_access_rule_get_role +gdata_access_rule_set_role +gdata_access_rule_get_scope +gdata_access_rule_set_scope +gdata_access_rule_get_edited +gdata_access_rule_get_key + +gdata_access_rule_get_type +GDATA_ACCESS_RULE +GDATA_ACCESS_RULE_CLASS +GDATA_ACCESS_RULE_GET_CLASS +GDATA_IS_ACCESS_RULE +GDATA_IS_ACCESS_RULE_CLASS +GDATA_TYPE_ACCESS_RULE + +GDataAccessRulePrivate +
+ +
+gdata-parsable +GDataParsable +GDataParsable +GDataParsableClass +gdata_parsable_get_content_type +gdata_parsable_new_from_xml +gdata_parsable_get_xml +gdata_parsable_new_from_json +gdata_parsable_get_json + +gdata_parsable_get_type +GDATA_IS_PARSABLE +GDATA_IS_PARSABLE_CLASS +GDATA_PARSABLE +GDATA_PARSABLE_CLASS +GDATA_PARSABLE_GET_CLASS +GDATA_TYPE_PARSABLE + +GDataParsablePrivate +
+ +
+gdata-calendar-feed +GDataCalendarFeed +GDataCalendarFeed +GDataCalendarFeedClass +gdata_calendar_feed_get_timezone +gdata_calendar_feed_get_times_cleaned + +gdata_calendar_feed_get_type +GDATA_CALENDAR_FEED +GDATA_CALENDAR_FEED_CLASS +GDATA_CALENDAR_FEED_GET_CLASS +GDATA_IS_CALENDAR_FEED +GDATA_IS_CALENDAR_FEED_CLASS +GDATA_TYPE_CALENDAR_FEED + +GDataCalendarFeedPrivate +
+ +
+gdata-category +GDataCategory +GDATA_CATEGORY_SCHEMA_LABELS +GDATA_CATEGORY_SCHEMA_LABELS_SHARED +GDATA_CATEGORY_SCHEMA_LABELS_STARRED +GDATA_CATEGORY_SCHEMA_LABELS_VIEWED +GDataCategory +GDataCategoryClass +gdata_category_new +gdata_category_get_term +gdata_category_set_term +gdata_category_get_scheme +gdata_category_set_scheme +gdata_category_get_label +gdata_category_set_label + +gdata_category_get_type +GDATA_CATEGORY +GDATA_CATEGORY_CLASS +GDATA_CATEGORY_GET_CLASS +GDATA_IS_CATEGORY +GDATA_IS_CATEGORY_CLASS +GDATA_TYPE_CATEGORY + +GDataCategoryPrivate +
+ +
+gdata-link +GDataLink +GDATA_LINK_ALTERNATE +GDATA_LINK_BATCH +GDATA_LINK_EDIT +GDATA_LINK_EDIT_MEDIA +GDATA_LINK_ENCLOSURE +GDATA_LINK_RELATED +GDATA_LINK_SELF +GDATA_LINK_VIA +GDATA_LINK_PARENT +GDataLink +GDataLinkClass +gdata_link_new +gdata_link_get_uri +gdata_link_set_uri +gdata_link_get_relation_type +gdata_link_set_relation_type +gdata_link_get_content_type +gdata_link_set_content_type +gdata_link_get_language +gdata_link_set_language +gdata_link_get_title +gdata_link_set_title +gdata_link_get_length +gdata_link_set_length + +gdata_link_get_type +GDATA_IS_LINK +GDATA_IS_LINK_CLASS +GDATA_LINK +GDATA_LINK_CLASS +GDATA_LINK_GET_CLASS +GDATA_TYPE_LINK + +GDataLinkPrivate +
+ +
+gdata-author +GDataAuthor +GDataAuthor +GDataAuthorClass +gdata_author_new +gdata_author_get_name +gdata_author_set_name +gdata_author_get_uri +gdata_author_set_uri +gdata_author_get_email_address +gdata_author_set_email_address + +gdata_author_get_type +GDATA_AUTHOR +GDATA_AUTHOR_CLASS +GDATA_AUTHOR_GET_CLASS +GDATA_IS_AUTHOR +GDATA_IS_AUTHOR_CLASS +GDATA_TYPE_AUTHOR + +GDataAuthorPrivate +
+ +
+gdata-generator +GDataGenerator +GDataGenerator +GDataGeneratorClass +gdata_generator_get_name +gdata_generator_get_uri +gdata_generator_get_version + +gdata_generator_get_type +GDATA_GENERATOR +GDATA_GENERATOR_CLASS +GDATA_GENERATOR_GET_CLASS +GDATA_IS_GENERATOR +GDATA_IS_GENERATOR_CLASS +GDATA_TYPE_GENERATOR + +GDataGeneratorPrivate +
+ +
+gdata-gd-organization +GDataGDOrganization +GDATA_GD_ORGANIZATION_WORK +GDATA_GD_ORGANIZATION_OTHER +GDataGDOrganization +GDataGDOrganizationClass +gdata_gd_organization_new +gdata_gd_organization_get_name +gdata_gd_organization_set_name +gdata_gd_organization_get_title +gdata_gd_organization_set_title +gdata_gd_organization_get_relation_type +gdata_gd_organization_set_relation_type +gdata_gd_organization_get_label +gdata_gd_organization_set_label +gdata_gd_organization_is_primary +gdata_gd_organization_set_is_primary +gdata_gd_organization_get_department +gdata_gd_organization_set_department +gdata_gd_organization_get_job_description +gdata_gd_organization_set_job_description +gdata_gd_organization_get_symbol +gdata_gd_organization_set_symbol +gdata_gd_organization_get_location +gdata_gd_organization_set_location + +gdata_gd_organization_get_type +GDATA_GD_ORGANIZATION +GDATA_GD_ORGANIZATION_CLASS +GDATA_GD_ORGANIZATION_GET_CLASS +GDATA_IS_GD_ORGANIZATION +GDATA_IS_GD_ORGANIZATION_CLASS +GDATA_TYPE_GD_ORGANIZATION + +GDataGDOrganizationPrivate +
+ +
+gdata-gd-when +GDataGDWhen +GDATA_GD_EVENT_STATUS_CANCELED +GDATA_GD_EVENT_STATUS_CONFIRMED +GDATA_GD_EVENT_STATUS_TENTATIVE +GDATA_GD_EVENT_VISIBILITY_CONFIDENTIAL +GDATA_GD_EVENT_VISIBILITY_DEFAULT +GDATA_GD_EVENT_VISIBILITY_PRIVATE +GDATA_GD_EVENT_VISIBILITY_PUBLIC +GDATA_GD_EVENT_TRANSPARENCY_OPAQUE +GDATA_GD_EVENT_TRANSPARENCY_TRANSPARENT +GDataGDWhen +GDataGDWhenClass +gdata_gd_when_new +gdata_gd_when_get_start_time +gdata_gd_when_set_start_time +gdata_gd_when_get_end_time +gdata_gd_when_set_end_time +gdata_gd_when_is_date +gdata_gd_when_set_is_date +gdata_gd_when_get_value_string +gdata_gd_when_set_value_string +gdata_gd_when_get_reminders +gdata_gd_when_add_reminder + +gdata_gd_when_get_type +GDATA_GD_WHEN +GDATA_GD_WHEN_CLASS +GDATA_GD_WHEN_GET_CLASS +GDATA_IS_GD_WHEN +GDATA_IS_GD_WHEN_CLASS +GDATA_TYPE_GD_WHEN + +GDataGDWhenPrivate +
+ +
+gdata-gd-who +GDataGDWho +GDATA_GD_WHO_EVENT_ATTENDEE +GDATA_GD_WHO_EVENT_ORGANIZER +GDATA_GD_WHO_EVENT_PERFORMER +GDATA_GD_WHO_EVENT_SPEAKER +GDataGDWho +GDataGDWhoClass +gdata_gd_who_new +gdata_gd_who_get_relation_type +gdata_gd_who_set_relation_type +gdata_gd_who_get_value_string +gdata_gd_who_set_value_string +gdata_gd_who_get_email_address +gdata_gd_who_set_email_address + +gdata_gd_who_get_type +GDATA_GD_WHO +GDATA_GD_WHO_CLASS +GDATA_GD_WHO_GET_CLASS +GDATA_IS_GD_WHO +GDATA_IS_GD_WHO_CLASS +GDATA_TYPE_GD_WHO + +GDataGDWhoPrivate +
+ +
+gdata-gd-where +GDataGDWhere +GDATA_GD_WHERE_EVENT +GDATA_GD_WHERE_EVENT_ALTERNATE +GDATA_GD_WHERE_EVENT_PARKING +GDataGDWhere +GDataGDWhereClass +gdata_gd_where_new +gdata_gd_where_get_relation_type +gdata_gd_where_set_relation_type +gdata_gd_where_get_value_string +gdata_gd_where_set_value_string +gdata_gd_where_get_label +gdata_gd_where_set_label + +gdata_gd_where_get_type +GDATA_GD_WHERE +GDATA_GD_WHERE_CLASS +GDATA_GD_WHERE_GET_CLASS +GDATA_IS_GD_WHERE +GDATA_IS_GD_WHERE_CLASS +GDATA_TYPE_GD_WHERE + +GDataGDWherePrivate +
+ +
+gdata-gd-email-address +GDataGDEmailAddress +GDATA_GD_EMAIL_ADDRESS_HOME +GDATA_GD_EMAIL_ADDRESS_OTHER +GDATA_GD_EMAIL_ADDRESS_WORK +GDataGDEmailAddress +GDataGDEmailAddressClass +gdata_gd_email_address_new +gdata_gd_email_address_get_address +gdata_gd_email_address_set_address +gdata_gd_email_address_get_relation_type +gdata_gd_email_address_set_relation_type +gdata_gd_email_address_get_label +gdata_gd_email_address_set_label +gdata_gd_email_address_is_primary +gdata_gd_email_address_set_is_primary +gdata_gd_email_address_get_display_name +gdata_gd_email_address_set_display_name + +gdata_gd_email_address_get_type +GDATA_GD_EMAIL_ADDRESS +GDATA_GD_EMAIL_ADDRESS_CLASS +GDATA_GD_EMAIL_ADDRESS_GET_CLASS +GDATA_IS_GD_EMAIL_ADDRESS +GDATA_IS_GD_EMAIL_ADDRESS_CLASS +GDATA_TYPE_GD_EMAIL_ADDRESS + +GDataGDEmailAddressPrivate +
+ +
+gdata-gd-im-address +GDataGDIMAddress +GDATA_GD_IM_ADDRESS_HOME +GDATA_GD_IM_ADDRESS_NETMEETING +GDATA_GD_IM_ADDRESS_OTHER +GDATA_GD_IM_ADDRESS_WORK +GDATA_GD_IM_PROTOCOL_AIM +GDATA_GD_IM_PROTOCOL_LIVE_MESSENGER +GDATA_GD_IM_PROTOCOL_YAHOO_MESSENGER +GDATA_GD_IM_PROTOCOL_SKYPE +GDATA_GD_IM_PROTOCOL_QQ +GDATA_GD_IM_PROTOCOL_GOOGLE_TALK +GDATA_GD_IM_PROTOCOL_ICQ +GDATA_GD_IM_PROTOCOL_JABBER +GDataGDIMAddress +GDataGDIMAddressClass +gdata_gd_im_address_new +gdata_gd_im_address_get_address +gdata_gd_im_address_set_address +gdata_gd_im_address_get_protocol +gdata_gd_im_address_set_protocol +gdata_gd_im_address_get_relation_type +gdata_gd_im_address_set_relation_type +gdata_gd_im_address_get_label +gdata_gd_im_address_set_label +gdata_gd_im_address_is_primary +gdata_gd_im_address_set_is_primary + +gdata_gd_im_address_get_type +GDATA_GD_IM_ADDRESS +GDATA_GD_IM_ADDRESS_CLASS +GDATA_GD_IM_ADDRESS_GET_CLASS +GDATA_IS_GD_IM_ADDRESS +GDATA_IS_GD_IM_ADDRESS_CLASS +GDATA_TYPE_GD_IM_ADDRESS + +GDataGDIMAddressPrivate +
+ +
+gdata-gd-postal-address +GDataGDPostalAddress +GDATA_GD_POSTAL_ADDRESS_WORK +GDATA_GD_POSTAL_ADDRESS_HOME +GDATA_GD_POSTAL_ADDRESS_OTHER +GDATA_GD_ADDRESS_USAGE_GENERAL +GDATA_GD_ADDRESS_USAGE_LOCAL +GDATA_GD_MAIL_CLASS_BOTH +GDATA_GD_MAIL_CLASS_LETTERS +GDATA_GD_MAIL_CLASS_NEITHER +GDATA_GD_MAIL_CLASS_PARCELS +GDataGDPostalAddress +GDataGDPostalAddressClass +gdata_gd_postal_address_new +gdata_gd_postal_address_get_address +gdata_gd_postal_address_set_address +gdata_gd_postal_address_get_relation_type +gdata_gd_postal_address_set_relation_type +gdata_gd_postal_address_get_label +gdata_gd_postal_address_set_label +gdata_gd_postal_address_is_primary +gdata_gd_postal_address_set_is_primary +gdata_gd_postal_address_get_mail_class +gdata_gd_postal_address_set_mail_class +gdata_gd_postal_address_get_usage +gdata_gd_postal_address_set_usage +gdata_gd_postal_address_get_agent +gdata_gd_postal_address_set_agent +gdata_gd_postal_address_get_house_name +gdata_gd_postal_address_set_house_name +gdata_gd_postal_address_get_street +gdata_gd_postal_address_set_street +gdata_gd_postal_address_get_po_box +gdata_gd_postal_address_set_po_box +gdata_gd_postal_address_get_neighborhood +gdata_gd_postal_address_set_neighborhood +gdata_gd_postal_address_get_city +gdata_gd_postal_address_set_city +gdata_gd_postal_address_get_subregion +gdata_gd_postal_address_set_subregion +gdata_gd_postal_address_get_region +gdata_gd_postal_address_set_region +gdata_gd_postal_address_get_postcode +gdata_gd_postal_address_set_postcode +gdata_gd_postal_address_get_country +gdata_gd_postal_address_get_country_code +gdata_gd_postal_address_set_country + +gdata_gd_postal_address_get_type +GDATA_GD_POSTAL_ADDRESS +GDATA_GD_POSTAL_ADDRESS_CLASS +GDATA_GD_POSTAL_ADDRESS_GET_CLASS +GDATA_IS_GD_POSTAL_ADDRESS +GDATA_IS_GD_POSTAL_ADDRESS_CLASS +GDATA_TYPE_GD_POSTAL_ADDRESS + +GDataGDPostalAddressPrivate +
+ +
+gdata-gd-phone-number +GDataGDPhoneNumber +GDATA_GD_PHONE_NUMBER_ASSISTANT +GDATA_GD_PHONE_NUMBER_CALLBACK +GDATA_GD_PHONE_NUMBER_CAR +GDATA_GD_PHONE_NUMBER_COMPANY_MAIN +GDATA_GD_PHONE_NUMBER_FAX +GDATA_GD_PHONE_NUMBER_HOME +GDATA_GD_PHONE_NUMBER_HOME_FAX +GDATA_GD_PHONE_NUMBER_ISDN +GDATA_GD_PHONE_NUMBER_MAIN +GDATA_GD_PHONE_NUMBER_MOBILE +GDATA_GD_PHONE_NUMBER_OTHER +GDATA_GD_PHONE_NUMBER_OTHER_FAX +GDATA_GD_PHONE_NUMBER_PAGER +GDATA_GD_PHONE_NUMBER_RADIO +GDATA_GD_PHONE_NUMBER_TELEX +GDATA_GD_PHONE_NUMBER_TTY_TDD +GDATA_GD_PHONE_NUMBER_WORK +GDATA_GD_PHONE_NUMBER_WORK_FAX +GDATA_GD_PHONE_NUMBER_WORK_MOBILE +GDATA_GD_PHONE_NUMBER_WORK_PAGER +GDataGDPhoneNumber +GDataGDPhoneNumberClass +gdata_gd_phone_number_new +gdata_gd_phone_number_get_number +gdata_gd_phone_number_set_number +gdata_gd_phone_number_get_uri +gdata_gd_phone_number_set_uri +gdata_gd_phone_number_get_relation_type +gdata_gd_phone_number_set_relation_type +gdata_gd_phone_number_get_label +gdata_gd_phone_number_set_label +gdata_gd_phone_number_is_primary +gdata_gd_phone_number_set_is_primary + +gdata_gd_phone_number_get_type +GDATA_GD_PHONE_NUMBER +GDATA_GD_PHONE_NUMBER_CLASS +GDATA_GD_PHONE_NUMBER_GET_CLASS +GDATA_IS_GD_PHONE_NUMBER +GDATA_IS_GD_PHONE_NUMBER_CLASS +GDATA_TYPE_GD_PHONE_NUMBER + +GDataGDPhoneNumberPrivate +
+ +
+gdata-gd-reminder +GDataGDReminder +GDATA_GD_REMINDER_ALERT +GDATA_GD_REMINDER_EMAIL +GDATA_GD_REMINDER_SMS +GDataGDReminder +GDataGDReminderClass +gdata_gd_reminder_new +gdata_gd_reminder_get_method +gdata_gd_reminder_set_method +gdata_gd_reminder_get_absolute_time +gdata_gd_reminder_set_absolute_time +gdata_gd_reminder_is_absolute_time +gdata_gd_reminder_get_relative_time +gdata_gd_reminder_set_relative_time + +gdata_gd_reminder_get_type +GDATA_GD_REMINDER +GDATA_GD_REMINDER_CLASS +GDATA_GD_REMINDER_GET_CLASS +GDATA_IS_GD_REMINDER +GDATA_IS_GD_REMINDER_CLASS +GDATA_TYPE_GD_REMINDER + +GDataGDReminderPrivate +
+ +
+gdata-media-category +GDataMediaCategory +GDataMediaCategory +GDataMediaCategoryClass +gdata_media_category_new +gdata_media_category_get_category +gdata_media_category_set_category +gdata_media_category_get_scheme +gdata_media_category_set_scheme +gdata_media_category_get_label +gdata_media_category_set_label + +gdata_media_category_get_type +GDATA_MEDIA_CATEGORY +GDATA_MEDIA_CATEGORY_CLASS +GDATA_MEDIA_CATEGORY_GET_CLASS +GDATA_IS_MEDIA_CATEGORY +GDATA_IS_MEDIA_CATEGORY_CLASS +GDATA_TYPE_MEDIA_CATEGORY + +GDataMediaCategoryPrivate +
+ +
+gdata-media-credit +GDataMediaCredit +GDataMediaCredit +GDataMediaCreditClass +gdata_media_credit_get_credit +gdata_media_credit_get_scheme +gdata_media_credit_get_role + +gdata_media_credit_get_type +GDATA_MEDIA_CREDIT +GDATA_MEDIA_CREDIT_CLASS +GDATA_MEDIA_CREDIT_GET_CLASS +GDATA_IS_MEDIA_CREDIT +GDATA_IS_MEDIA_CREDIT_CLASS +GDATA_TYPE_MEDIA_CREDIT + +GDataMediaCreditPrivate +
+ +
+gdata-youtube-credit +GDataYouTubeCredit +GDATA_YOUTUBE_CREDIT_ENTITY_PARTNER +GDataYouTubeCredit +GDataYouTubeCreditClass +gdata_youtube_credit_get_entity_type + +gdata_youtube_credit_get_type +GDATA_YOUTUBE_CREDIT +GDATA_YOUTUBE_CREDIT_CLASS +GDATA_YOUTUBE_CREDIT_GET_CLASS +GDATA_IS_YOUTUBE_CREDIT +GDATA_IS_YOUTUBE_CREDIT_CLASS +GDATA_TYPE_YOUTUBE_CREDIT + +GDataYouTubeCreditPrivate +
+ +
+gdata-media-content +GDataMediaContent +GDataMediaContent +GDataMediaContentClass +GDataMediaMedium +GDataMediaExpression +gdata_media_content_get_uri +gdata_media_content_get_filesize +gdata_media_content_get_content_type +gdata_media_content_get_medium +gdata_media_content_is_default +gdata_media_content_get_expression +gdata_media_content_get_duration +gdata_media_content_get_height +gdata_media_content_get_width +gdata_media_content_download + +gdata_media_content_get_type +GDATA_MEDIA_CONTENT +GDATA_MEDIA_CONTENT_CLASS +GDATA_MEDIA_CONTENT_GET_CLASS +GDATA_IS_MEDIA_CONTENT +GDATA_IS_MEDIA_CONTENT_CLASS +GDATA_TYPE_MEDIA_CONTENT + +GDataMediaContentPrivate +
+ +
+gdata-youtube-content +GDataYouTubeContent +GDataYouTubeContent +GDataYouTubeContentClass +gdata_youtube_content_get_format + +gdata_youtube_content_get_type +GDATA_YOUTUBE_CONTENT +GDATA_YOUTUBE_CONTENT_CLASS +GDATA_YOUTUBE_CONTENT_GET_CLASS +GDATA_IS_YOUTUBE_CONTENT +GDATA_IS_YOUTUBE_CONTENT_CLASS +GDATA_TYPE_YOUTUBE_CONTENT + +GDataYouTubeContentPrivate +
+ +
+gdata-media-thumbnail +GDataMediaThumbnail +GDataMediaThumbnail +GDataMediaThumbnailClass +gdata_media_thumbnail_get_uri +gdata_media_thumbnail_get_height +gdata_media_thumbnail_get_width +gdata_media_thumbnail_get_time +gdata_media_thumbnail_download + +gdata_media_thumbnail_get_type +GDATA_MEDIA_THUMBNAIL +GDATA_MEDIA_THUMBNAIL_CLASS +GDATA_MEDIA_THUMBNAIL_GET_CLASS +GDATA_IS_MEDIA_THUMBNAIL +GDATA_IS_MEDIA_THUMBNAIL_CLASS +GDATA_TYPE_MEDIA_THUMBNAIL + +GDataMediaThumbnailPrivate +
+ +
+gdata-youtube-state +GDataYouTubeState +GDataYouTubeState +GDataYouTubeStateClass +gdata_youtube_state_get_name +gdata_youtube_state_get_reason_code +gdata_youtube_state_get_help_uri +gdata_youtube_state_get_message + +gdata_youtube_state_get_type +GDATA_YOUTUBE_STATE +GDATA_YOUTUBE_STATE_CLASS +GDATA_YOUTUBE_STATE_GET_CLASS +GDATA_IS_YOUTUBE_STATE +GDATA_IS_YOUTUBE_STATE_CLASS +GDATA_TYPE_YOUTUBE_STATE + +GDataYouTubeStatePrivate +
+ +
+gdata-picasaweb-service +GDataPicasaWebService +GDataPicasaWebService +GDataPicasaWebServiceClass +gdata_picasaweb_service_new +gdata_picasaweb_service_get_primary_authorization_domain +gdata_picasaweb_service_get_user +gdata_picasaweb_service_get_user_async +gdata_picasaweb_service_get_user_finish +gdata_picasaweb_service_query_all_albums +gdata_picasaweb_service_query_all_albums_async +gdata_picasaweb_service_query_files +gdata_picasaweb_service_query_files_async +gdata_picasaweb_service_upload_file +gdata_picasaweb_service_finish_file_upload +gdata_picasaweb_service_insert_album +gdata_picasaweb_service_insert_album_async + +gdata_picasaweb_service_get_type +GDATA_IS_PICASAWEB_SERVICE +GDATA_IS_PICASAWEB_SERVICE_CLASS +GDATA_PICASAWEB_SERVICE +GDATA_PICASAWEB_SERVICE_CLASS +GDATA_PICASAWEB_SERVICE_GET_CLASS +GDATA_TYPE_PICASAWEB_SERVICE +
+ +
+gdata-picasaweb-feed +GDataPicasaWebFeed +GDataPicasaWebFeed +GDataPicasaWebFeedClass + +gdata_picasaweb_feed_get_type +GDATA_PICASAWEB_FEED +GDATA_PICASAWEB_FEED_CLASS +GDATA_PICASAWEB_FEED_GET_CLASS +GDATA_IS_PICASAWEB_FEED +GDATA_IS_PICASAWEB_FEED_CLASS +GDATA_TYPE_PICASAWEB_FEED +
+ +
+gdata-picasaweb-user +GDataPicasaWebUser +GDataPicasaWebUser +GDataPicasaWebUserClass +gdata_picasaweb_user_get_user +gdata_picasaweb_user_get_nickname +gdata_picasaweb_user_get_quota_limit +gdata_picasaweb_user_get_quota_current +gdata_picasaweb_user_get_max_photos_per_album +gdata_picasaweb_user_get_thumbnail_uri + +gdata_picasaweb_user_get_type +GDATA_PICASAWEB_USER +GDATA_PICASAWEB_USER_CLASS +GDATA_PICASAWEB_USER_GET_CLASS +GDATA_IS_PICASAWEB_USER +GDATA_IS_PICASAWEB_USER_CLASS +GDATA_TYPE_PICASAWEB_USER + +GDataPicasaWebUserPrivate +
+ +
+gdata-picasaweb-query +GDataPicasaWebQuery +GDataPicasaWebQuery +GDataPicasaWebQueryClass +gdata_picasaweb_query_new +gdata_picasaweb_query_new_with_limits +gdata_picasaweb_query_get_visibility +gdata_picasaweb_query_set_visibility +gdata_picasaweb_query_get_thumbnail_size +gdata_picasaweb_query_set_thumbnail_size +gdata_picasaweb_query_get_image_size +gdata_picasaweb_query_set_image_size +gdata_picasaweb_query_get_tag +gdata_picasaweb_query_set_tag +gdata_picasaweb_query_get_bounding_box +gdata_picasaweb_query_set_bounding_box +gdata_picasaweb_query_get_location +gdata_picasaweb_query_set_location + +gdata_picasaweb_query_get_type +GDATA_IS_PICASAWEB_QUERY +GDATA_IS_PICASAWEB_QUERY_CLASS +GDATA_PICASAWEB_QUERY +GDATA_PICASAWEB_QUERY_CLASS +GDATA_PICASAWEB_QUERY_GET_CLASS +GDATA_TYPE_PICASAWEB_QUERY + +GDataPicasaWebQueryPrivate +
+ +
+gdata-picasaweb-album +GDataPicasaWebAlbum +GDataPicasaWebAlbum +GDataPicasaWebAlbumClass +GDataPicasaWebVisibility +gdata_picasaweb_album_new +gdata_picasaweb_album_get_id +gdata_picasaweb_album_get_user +gdata_picasaweb_album_get_nickname +gdata_picasaweb_album_get_edited +gdata_picasaweb_album_get_location +gdata_picasaweb_album_set_location +gdata_picasaweb_album_get_visibility +gdata_picasaweb_album_set_visibility +gdata_picasaweb_album_get_timestamp +gdata_picasaweb_album_set_timestamp +gdata_picasaweb_album_get_num_photos +gdata_picasaweb_album_get_num_photos_remaining +gdata_picasaweb_album_get_bytes_used +gdata_picasaweb_album_is_commenting_enabled +gdata_picasaweb_album_set_is_commenting_enabled +gdata_picasaweb_album_get_comment_count +gdata_picasaweb_album_get_tags +gdata_picasaweb_album_set_tags +gdata_picasaweb_album_get_contents +gdata_picasaweb_album_get_thumbnails +gdata_picasaweb_album_get_coordinates +gdata_picasaweb_album_set_coordinates + +gdata_picasaweb_album_get_type +GDATA_IS_PICASAWEB_ALBUM +GDATA_IS_PICASAWEB_ALBUM_CLASS +GDATA_PICASAWEB_ALBUM +GDATA_PICASAWEB_ALBUM_CLASS +GDATA_PICASAWEB_ALBUM_GET_CLASS +GDATA_TYPE_PICASAWEB_ALBUM + +GDataPicasaWebAlbumPrivate +
+ +
+gdata-picasaweb-file +GDataPicasaWebFile +GDATA_PICASAWEB_VIDEO_STATUS_PENDING +GDATA_PICASAWEB_VIDEO_STATUS_READY +GDATA_PICASAWEB_VIDEO_STATUS_FINAL +GDATA_PICASAWEB_VIDEO_STATUS_FAILED +GDataPicasaWebFile +GDataPicasaWebFileClass +gdata_picasaweb_file_new +gdata_picasaweb_file_get_id +gdata_picasaweb_file_get_edited +gdata_picasaweb_file_get_version +gdata_picasaweb_file_get_album_id +gdata_picasaweb_file_set_album_id +gdata_picasaweb_file_get_width +gdata_picasaweb_file_get_height +gdata_picasaweb_file_get_size +gdata_picasaweb_file_get_checksum +gdata_picasaweb_file_set_checksum +gdata_picasaweb_file_get_timestamp +gdata_picasaweb_file_set_timestamp +gdata_picasaweb_file_is_commenting_enabled +gdata_picasaweb_file_set_is_commenting_enabled +gdata_picasaweb_file_get_comment_count +gdata_picasaweb_file_get_rotation +gdata_picasaweb_file_set_rotation +gdata_picasaweb_file_get_video_status +gdata_picasaweb_file_get_tags +gdata_picasaweb_file_set_tags +gdata_picasaweb_file_get_credit +gdata_picasaweb_file_get_caption +gdata_picasaweb_file_set_caption +gdata_picasaweb_file_get_contents +gdata_picasaweb_file_get_thumbnails +gdata_picasaweb_file_get_distance +gdata_picasaweb_file_get_exposure +gdata_picasaweb_file_get_flash +gdata_picasaweb_file_get_focal_length +gdata_picasaweb_file_get_fstop +gdata_picasaweb_file_get_image_unique_id +gdata_picasaweb_file_get_iso +gdata_picasaweb_file_get_make +gdata_picasaweb_file_get_model +gdata_picasaweb_file_get_coordinates +gdata_picasaweb_file_set_coordinates + +gdata_picasaweb_file_get_type +GDATA_IS_PICASAWEB_FILE +GDATA_IS_PICASAWEB_FILE_CLASS +GDATA_PICASAWEB_FILE +GDATA_PICASAWEB_FILE_CLASS +GDATA_PICASAWEB_FILE_GET_CLASS +GDATA_TYPE_PICASAWEB_FILE + +GDataPicasaWebFilePrivate +
+ +
+gdata-documents-entry +GDataDocumentsEntry +GDATA_DOCUMENTS_ACCESS_ROLE_OWNER +GDATA_DOCUMENTS_ACCESS_ROLE_WRITER +GDATA_DOCUMENTS_ACCESS_ROLE_READER +GDataDocumentsEntry +GDataDocumentsEntryClass +gdata_documents_entry_get_path +gdata_documents_entry_get_resource_id +gdata_documents_entry_get_document_id +gdata_documents_entry_get_edited +gdata_documents_entry_get_last_modified_by +gdata_documents_entry_get_last_viewed +gdata_documents_entry_get_quota_used +gdata_documents_entry_get_file_size +gdata_documents_entry_writers_can_invite +gdata_documents_entry_set_writers_can_invite +gdata_documents_entry_is_deleted +gdata_documents_entry_get_document_properties +gdata_documents_entry_add_documents_property +gdata_documents_entry_remove_documents_property + +gdata_documents_entry_get_type +GDATA_DOCUMENTS_ENTRY +GDATA_DOCUMENTS_ENTRY_CLASS +GDATA_DOCUMENTS_ENTRY_GET_CLASS +GDATA_IS_DOCUMENTS_ENTRY +GDATA_IS_DOCUMENTS_ENTRY_CLASS +GDATA_TYPE_DOCUMENTS_ENTRY + +GDataDocumentsEntryPrivate +
+ +
+gdata-documents-property +GDataDocumentsProperty +GDATA_DOCUMENTS_PROPERTY_VISIBILITY_PUBLIC +GDATA_DOCUMENTS_PROPERTY_VISIBILITY_PRIVATE +GDataDocumentsProperty +GDataDocumentsPropertyClass +gdata_documents_property_new +gdata_documents_property_get_key +gdata_documents_property_get_etag +gdata_documents_property_get_value +gdata_documents_property_set_value +gdata_documents_property_get_visibility +gdata_documents_property_set_visibility + +gdata_documents_property_get_type +GDATA_DOCUMENTS_PROPERTY +GDATA_DOCUMENTS_PROPERTY_CLASS +GDATA_DOCUMENTS_PROPERTY_GET_CLASS +GDATA_IS_DOCUMENTS_PROPERTY +GDATA_IS_DOCUMENTS_PROPERTY_CLASS +GDATA_TYPE_DOCUMENTS_PROPERTY + +GDataDocumentsPropertyPrivate +
+ +
+gdata-documents-feed +GDataDocumentsFeed +GDataDocumentsFeed +GDataDocumentsFeedClass + +gdata_documents_feed_get_type +GDATA_DOCUMENTS_FEED +GDATA_DOCUMENTS_FEED_CLASS +GDATA_DOCUMENTS_FEED_GET_CLASS +GDATA_IS_DOCUMENTS_FEED +GDATA_IS_DOCUMENTS_FEED_CLASS +GDATA_TYPE_DOCUMENTS_FEED + +GDataDocumentsFeedPrivate +
+ +
+gdata-documents-folder +GDataDocumentsFolder +GDataDocumentsFolder +GDataDocumentsFolderClass +gdata_documents_folder_new + +gdata_documents_folder_get_type +GDATA_DOCUMENTS_FOLDER +GDATA_DOCUMENTS_FOLDER_CLASS +GDATA_DOCUMENTS_FOLDER_GET_CLASS +GDATA_IS_DOCUMENTS_FOLDER +GDATA_IS_DOCUMENTS_FOLDER_CLASS +GDATA_TYPE_DOCUMENTS_FOLDER + +GDataDocumentsFolderPrivate +
+ +
+gdata-documents-document +GDataDocumentsDocument +GDataDocumentsDocument +GDataDocumentsDocumentClass +gdata_documents_document_new +gdata_documents_document_download +gdata_documents_document_get_download_uri +gdata_documents_document_get_thumbnail_uri + +gdata_documents_document_get_type +GDATA_DOCUMENTS_DOCUMENT +GDATA_DOCUMENTS_DOCUMENT_CLASS +GDATA_DOCUMENTS_DOCUMENT_GET_CLASS +GDATA_IS_DOCUMENTS_DOCUMENT +GDATA_IS_DOCUMENTS_DOCUMENT_CLASS +GDATA_TYPE_DOCUMENTS_DOCUMENT + +GDataDocumentsDocumentPrivate +
+ +
+gdata-documents-presentation +GDataDocumentsPresentation +GDATA_DOCUMENTS_PRESENTATION_PDF +GDATA_DOCUMENTS_PRESENTATION_PNG +GDATA_DOCUMENTS_PRESENTATION_PPT +GDATA_DOCUMENTS_PRESENTATION_SWF +GDATA_DOCUMENTS_PRESENTATION_TXT +GDataDocumentsPresentation +GDataDocumentsPresentationClass +gdata_documents_presentation_new + +gdata_documents_presentation_get_type +GDATA_DOCUMENTS_PRESENTATION +GDATA_DOCUMENTS_PRESENTATION_CLASS +GDATA_DOCUMENTS_PRESENTATION_GET_CLASS +GDATA_IS_DOCUMENTS_PRESENTATION +GDATA_IS_DOCUMENTS_PRESENTATION_CLASS +GDATA_TYPE_DOCUMENTS_PRESENTATION + +GDataDocumentsPresentationPrivate +
+ +
+gdata-documents-query +GDataDocumentsQuery +GDataDocumentsQuery +GDataDocumentsQueryClass +gdata_documents_query_new +gdata_documents_query_new_with_limits +gdata_documents_query_show_deleted +gdata_documents_query_set_show_deleted +gdata_documents_query_show_folders +gdata_documents_query_set_show_folders +gdata_documents_query_get_folder_id +gdata_documents_query_set_folder_id +gdata_documents_query_get_title +gdata_documents_query_get_exact_title +gdata_documents_query_set_title +gdata_documents_query_get_collaborator_addresses +gdata_documents_query_add_collaborator +gdata_documents_query_get_reader_addresses +gdata_documents_query_add_reader + +gdata_documents_query_get_type +GDATA_DOCUMENTS_QUERY +GDATA_DOCUMENTS_QUERY_CLASS +GDATA_DOCUMENTS_QUERY_GET_CLASS +GDATA_IS_DOCUMENTS_QUERY +GDATA_IS_DOCUMENTS_QUERY_CLASS +GDATA_TYPE_DOCUMENTS_QUERY + +GDataDocumentsQueryPrivate +
+ +
+gdata-documents-spreadsheet +GDataDocumentsSpreadsheet +GDATA_DOCUMENTS_SPREADSHEET_CSV +GDATA_DOCUMENTS_SPREADSHEET_HTML +GDATA_DOCUMENTS_SPREADSHEET_ODS +GDATA_DOCUMENTS_SPREADSHEET_PDF +GDATA_DOCUMENTS_SPREADSHEET_TSV +GDATA_DOCUMENTS_SPREADSHEET_XLS +GDataDocumentsSpreadsheet +GDataDocumentsSpreadsheetClass +gdata_documents_spreadsheet_new +gdata_documents_spreadsheet_get_download_uri + +gdata_documents_spreadsheet_get_type +GDATA_DOCUMENTS_SPREADSHEET +GDATA_DOCUMENTS_SPREADSHEET_CLASS +GDATA_DOCUMENTS_SPREADSHEET_GET_CLASS +GDATA_IS_DOCUMENTS_SPREADSHEET +GDATA_IS_DOCUMENTS_SPREADSHEET_CLASS +GDATA_TYPE_DOCUMENTS_SPREADSHEET + +GDataDocumentsSpreadsheetPrivate +
+ +
+gdata-documents-text +GDataDocumentsText +GDATA_DOCUMENTS_TEXT_DOC +GDATA_DOCUMENTS_TEXT_HTML +GDATA_DOCUMENTS_TEXT_JPEG +GDATA_DOCUMENTS_TEXT_ODT +GDATA_DOCUMENTS_TEXT_PDF +GDATA_DOCUMENTS_TEXT_PNG +GDATA_DOCUMENTS_TEXT_RTF +GDATA_DOCUMENTS_TEXT_TXT +GDATA_DOCUMENTS_TEXT_ZIP +GDataDocumentsText +GDataDocumentsTextClass +gdata_documents_text_new + +gdata_documents_text_get_type +GDATA_DOCUMENTS_TEXT +GDATA_DOCUMENTS_TEXT_CLASS +GDATA_DOCUMENTS_TEXT_GET_CLASS +GDATA_IS_DOCUMENTS_TEXT +GDATA_IS_DOCUMENTS_TEXT_CLASS +GDATA_TYPE_DOCUMENTS_TEXT + +GDataDocumentsTextPrivate +
+ +
+gdata-documents-drawing +GDataDocumentsDrawing +GDATA_DOCUMENTS_DRAWING_JPEG +GDATA_DOCUMENTS_DRAWING_PDF +GDATA_DOCUMENTS_DRAWING_PNG +GDATA_DOCUMENTS_DRAWING_SVG +GDataDocumentsDrawing +GDataDocumentsDrawingClass +gdata_documents_drawing_new + +gdata_documents_drawing_get_type +GDATA_DOCUMENTS_DRAWING +GDATA_DOCUMENTS_DRAWING_CLASS +GDATA_DOCUMENTS_DRAWING_GET_CLASS +GDATA_IS_DOCUMENTS_DRAWING +GDATA_IS_DOCUMENTS_DRAWING_CLASS +GDATA_TYPE_DOCUMENTS_DRAWING + +GDataDocumentsDrawingPrivate +
+ +
+gdata-documents-pdf +GDataDocumentsPdf +GDataDocumentsPdf +GDataDocumentsPdfClass +gdata_documents_pdf_new + +gdata_documents_pdf_get_type +GDATA_DOCUMENTS_PDF +GDATA_DOCUMENTS_PDF_CLASS +GDATA_DOCUMENTS_PDF_GET_CLASS +GDATA_IS_DOCUMENTS_PDF +GDATA_IS_DOCUMENTS_PDF_CLASS +GDATA_TYPE_DOCUMENTS_PDF + +GDataDocumentsPdfPrivate +
+ +
+gdata-documents-service +GDataDocumentsService +GDataDocumentsService +GDataDocumentsServiceClass +GDataDocumentsServiceError +gdata_documents_service_new +gdata_documents_service_get_primary_authorization_domain +gdata_documents_service_get_spreadsheet_authorization_domain +gdata_documents_service_get_metadata +gdata_documents_service_get_metadata_async +gdata_documents_service_get_metadata_finish +gdata_documents_service_query_documents +gdata_documents_service_query_documents_async +gdata_documents_service_upload_document +gdata_documents_service_upload_document_resumable +gdata_documents_service_update_document +gdata_documents_service_update_document_resumable +gdata_documents_service_finish_upload +gdata_documents_service_copy_document +gdata_documents_service_copy_document_async +gdata_documents_service_copy_document_finish +gdata_documents_service_add_entry_to_folder +gdata_documents_service_add_entry_to_folder_async +gdata_documents_service_add_entry_to_folder_finish +gdata_documents_service_remove_entry_from_folder +gdata_documents_service_remove_entry_from_folder_async +gdata_documents_service_remove_entry_from_folder_finish +gdata_documents_service_get_upload_uri + +gdata_documents_service_get_type +GDATA_DOCUMENTS_SERVICE +GDATA_DOCUMENTS_SERVICE_CLASS +GDATA_DOCUMENTS_SERVICE_ERROR +GDATA_DOCUMENTS_SERVICE_GET_CLASS +GDATA_IS_DOCUMENTS_SERVICE +GDATA_IS_DOCUMENTS_SERVICE_CLASS +GDATA_TYPE_DOCUMENTS_SERVICE +gdata_documents_service_error_quark + +GDataDocumentsServicePrivate +
+ +
+gdata-documents-metadata +GDataDocumentsMetadata +GDataDocumentsMetadata +GDataDocumentsMetadataClass +gdata_documents_metadata_get_quota_total +gdata_documents_metadata_get_quota_used + +gdata_documents_metadata_get_type +GDATA_DOCUMENTS_METADATA +GDATA_DOCUMENTS_METADATA_CLASS +GDATA_DOCUMENTS_METADATA_GET_CLASS +GDATA_IS_DOCUMENTS_METADATA +GDATA_IS_DOCUMENTS_METADATA_CLASS +GDATA_TYPE_DOCUMENTS_METADATA + +GDataDocumentsMetadataPrivate +
+ +
+gdata-download-stream +GDataDownloadStream +GDataDownloadStream +GDataDownloadStreamClass +gdata_download_stream_new +gdata_download_stream_get_service +gdata_download_stream_get_authorization_domain +gdata_download_stream_get_cancellable +gdata_download_stream_get_download_uri +gdata_download_stream_get_content_type +gdata_download_stream_get_content_length + +GDATA_DOWNLOAD_STREAM +GDATA_DOWNLOAD_STREAM_CLASS +GDATA_DOWNLOAD_STREAM_GET_CLASS +GDATA_IS_DOWNLOAD_STREAM +GDATA_IS_DOWNLOAD_STREAM_CLASS +GDATA_TYPE_DOWNLOAD_STREAM +gdata_download_stream_get_type + +GDataDownloadStreamPrivate +
+ +
+gdata-upload-stream +GDataUploadStream +GDATA_LINK_RESUMABLE_CREATE_MEDIA +GDATA_LINK_RESUMABLE_EDIT_MEDIA +GDataUploadStream +GDataUploadStreamClass +gdata_upload_stream_new +gdata_upload_stream_new_resumable +gdata_upload_stream_get_response +gdata_upload_stream_get_service +gdata_upload_stream_get_authorization_domain +gdata_upload_stream_get_cancellable +gdata_upload_stream_get_method +gdata_upload_stream_get_upload_uri +gdata_upload_stream_get_entry +gdata_upload_stream_get_slug +gdata_upload_stream_get_content_type +gdata_upload_stream_get_content_length + +gdata_upload_stream_get_type +GDATA_UPLOAD_STREAM +GDATA_UPLOAD_STREAM_CLASS +GDATA_UPLOAD_STREAM_GET_CLASS +GDATA_IS_UPLOAD_STREAM +GDATA_IS_UPLOAD_STREAM_CLASS +GDATA_TYPE_UPLOAD_STREAM + +GDataUploadStreamPrivate +
+ +
+gdata-gd-name +GDataGDName +GDataGDName +GDataGDNameClass +gdata_gd_name_new +gdata_gd_name_get_given_name +gdata_gd_name_set_given_name +gdata_gd_name_get_additional_name +gdata_gd_name_set_additional_name +gdata_gd_name_get_family_name +gdata_gd_name_set_family_name +gdata_gd_name_get_prefix +gdata_gd_name_set_prefix +gdata_gd_name_get_suffix +gdata_gd_name_set_suffix +gdata_gd_name_get_full_name +gdata_gd_name_set_full_name + +gdata_gd_name_get_type +GDATA_GD_NAME +GDATA_GD_NAME_CLASS +GDATA_GD_NAME_GET_CLASS +GDATA_IS_GD_NAME +GDATA_IS_GD_NAME_CLASS +GDATA_TYPE_GD_NAME + +GDataGDNamePrivate +
+ +
+gdata-gcontact-jot +GDataGContactJot +GDATA_GCONTACT_JOT_HOME +GDATA_GCONTACT_JOT_KEYWORDS +GDATA_GCONTACT_JOT_OTHER +GDATA_GCONTACT_JOT_USER +GDATA_GCONTACT_JOT_WORK +GDataGContactJot +GDataGContactJotClass +gdata_gcontact_jot_new +gdata_gcontact_jot_get_content +gdata_gcontact_jot_set_content +gdata_gcontact_jot_get_relation_type +gdata_gcontact_jot_set_relation_type + +gdata_gcontact_jot_get_type +GDATA_GCONTACT_JOT +GDATA_GCONTACT_JOT_CLASS +GDATA_GCONTACT_JOT_GET_CLASS +GDATA_IS_GCONTACT_JOT +GDATA_IS_GCONTACT_JOT_CLASS +GDATA_TYPE_GCONTACT_JOT + +GDataGContactJotPrivate +
+ +
+gdata-gcontact-relation +GDataGContactRelation +GDATA_GCONTACT_RELATION_ASSISTANT +GDATA_GCONTACT_RELATION_BROTHER +GDATA_GCONTACT_RELATION_CHILD +GDATA_GCONTACT_RELATION_DOMESTIC_PARTNER +GDATA_GCONTACT_RELATION_FATHER +GDATA_GCONTACT_RELATION_FRIEND +GDATA_GCONTACT_RELATION_MANAGER +GDATA_GCONTACT_RELATION_MOTHER +GDATA_GCONTACT_RELATION_PARENT +GDATA_GCONTACT_RELATION_PARTNER +GDATA_GCONTACT_RELATION_REFERRER +GDATA_GCONTACT_RELATION_RELATIVE +GDATA_GCONTACT_RELATION_SISTER +GDATA_GCONTACT_RELATION_SPOUSE +GDataGContactRelation +GDataGContactRelationClass +gdata_gcontact_relation_new +gdata_gcontact_relation_get_name +gdata_gcontact_relation_set_name +gdata_gcontact_relation_get_relation_type +gdata_gcontact_relation_set_relation_type +gdata_gcontact_relation_get_label +gdata_gcontact_relation_set_label + +gdata_gcontact_relation_get_type +GDATA_GCONTACT_RELATION +GDATA_GCONTACT_RELATION_CLASS +GDATA_GCONTACT_RELATION_GET_CLASS +GDATA_IS_GCONTACT_RELATION +GDATA_IS_GCONTACT_RELATION_CLASS +GDATA_TYPE_GCONTACT_RELATION + +GDataGContactRelationPrivate +
+ +
+gdata-gcontact-website +GDataGContactWebsite +GDATA_GCONTACT_WEBSITE_HOME_PAGE +GDATA_GCONTACT_WEBSITE_BLOG +GDATA_GCONTACT_WEBSITE_PROFILE +GDATA_GCONTACT_WEBSITE_HOME +GDATA_GCONTACT_WEBSITE_WORK +GDATA_GCONTACT_WEBSITE_OTHER +GDATA_GCONTACT_WEBSITE_FTP +GDataGContactWebsite +GDataGContactWebsiteClass +gdata_gcontact_website_new +gdata_gcontact_website_get_uri +gdata_gcontact_website_set_uri +gdata_gcontact_website_get_relation_type +gdata_gcontact_website_set_relation_type +gdata_gcontact_website_get_label +gdata_gcontact_website_set_label +gdata_gcontact_website_is_primary +gdata_gcontact_website_set_is_primary + +gdata_gcontact_website_get_type +GDATA_GCONTACT_WEBSITE +GDATA_GCONTACT_WEBSITE_CLASS +GDATA_GCONTACT_WEBSITE_GET_CLASS +GDATA_IS_GCONTACT_WEBSITE +GDATA_IS_GCONTACT_WEBSITE_CLASS +GDATA_TYPE_GCONTACT_WEBSITE + +GDataGContactWebsitePrivate +
+ +
+gdata-gcontact-event +GDataGContactEvent +GDATA_GCONTACT_EVENT_ANNIVERSARY +GDATA_GCONTACT_EVENT_OTHER +GDataGContactEvent +GDataGContactEventClass +gdata_gcontact_event_new +gdata_gcontact_event_get_date +gdata_gcontact_event_set_date +gdata_gcontact_event_get_relation_type +gdata_gcontact_event_set_relation_type +gdata_gcontact_event_get_label +gdata_gcontact_event_set_label + +gdata_gcontact_event_get_type +GDATA_GCONTACT_EVENT +GDATA_GCONTACT_EVENT_CLASS +GDATA_GCONTACT_EVENT_GET_CLASS +GDATA_IS_GCONTACT_EVENT +GDATA_IS_GCONTACT_EVENT_CLASS +GDATA_TYPE_GCONTACT_EVENT + +GDataGContactEventPrivate +
+ +
+gdata-gcontact-calendar +GDataGContactCalendar +GDATA_GCONTACT_CALENDAR_HOME +GDATA_GCONTACT_CALENDAR_WORK +GDATA_GCONTACT_CALENDAR_FREE_BUSY +GDataGContactCalendar +GDataGContactCalendarClass +gdata_gcontact_calendar_new +gdata_gcontact_calendar_get_uri +gdata_gcontact_calendar_set_uri +gdata_gcontact_calendar_get_relation_type +gdata_gcontact_calendar_set_relation_type +gdata_gcontact_calendar_get_label +gdata_gcontact_calendar_set_label +gdata_gcontact_calendar_is_primary +gdata_gcontact_calendar_set_is_primary + +gdata_gcontact_calendar_get_type +GDATA_GCONTACT_CALENDAR +GDATA_GCONTACT_CALENDAR_CLASS +GDATA_GCONTACT_CALENDAR_GET_CLASS +GDATA_IS_GCONTACT_CALENDAR +GDATA_IS_GCONTACT_CALENDAR_CLASS +GDATA_TYPE_GCONTACT_CALENDAR + +GDataGContactCalendarPrivate +
+ +
+gdata-gcontact-external-id +GDataGContactExternalID +GDATA_GCONTACT_EXTERNAL_ID_ACCOUNT +GDATA_GCONTACT_EXTERNAL_ID_CUSTOMER +GDATA_GCONTACT_EXTERNAL_ID_NETWORK +GDATA_GCONTACT_EXTERNAL_ID_ORGANIZATION +GDataGContactExternalID +GDataGContactExternalIDClass +gdata_gcontact_external_id_new +gdata_gcontact_external_id_get_value +gdata_gcontact_external_id_set_value +gdata_gcontact_external_id_get_relation_type +gdata_gcontact_external_id_set_relation_type +gdata_gcontact_external_id_get_label +gdata_gcontact_external_id_set_label + +gdata_gcontact_external_id_get_type +GDATA_GCONTACT_EXTERNAL_ID +GDATA_GCONTACT_EXTERNAL_ID_CLASS +GDATA_GCONTACT_EXTERNAL_ID_GET_CLASS +GDATA_IS_GCONTACT_EXTERNAL_ID +GDATA_IS_GCONTACT_EXTERNAL_ID_CLASS +GDATA_TYPE_GCONTACT_EXTERNAL_ID + +GDataGContactExternalIDPrivate +
+ +
+gdata-gcontact-language +GDataGContactLanguage +GDataGContactLanguage +GDataGContactLanguageClass +gdata_gcontact_language_new +gdata_gcontact_language_get_code +gdata_gcontact_language_set_code +gdata_gcontact_language_get_label +gdata_gcontact_language_set_label + +gdata_gcontact_language_get_type +GDATA_GCONTACT_LANGUAGE +GDATA_GCONTACT_LANGUAGE_CLASS +GDATA_GCONTACT_LANGUAGE_GET_CLASS +GDATA_IS_GCONTACT_LANGUAGE +GDATA_IS_GCONTACT_LANGUAGE_CLASS +GDATA_TYPE_GCONTACT_LANGUAGE + +GDataGContactLanguagePrivate +
+ +
+gdata-youtube-category +GDataYouTubeCategory +GDataYouTubeCategory +GDataYouTubeCategoryClass +gdata_youtube_category_is_assignable +gdata_youtube_category_is_browsable +gdata_youtube_category_is_deprecated + +gdata_youtube_category_get_type +GDATA_YOUTUBE_CATEGORY +GDATA_YOUTUBE_CATEGORY_CLASS +GDATA_YOUTUBE_CATEGORY_GET_CLASS +GDATA_IS_YOUTUBE_CATEGORY +GDATA_IS_YOUTUBE_CATEGORY_CLASS +GDATA_TYPE_YOUTUBE_CATEGORY + +GDataYouTubeCategoryPrivate +
+ +
+gdata-app-categories +GDataAPPCategories +GDataAPPCategories +GDataAPPCategoriesClass +gdata_app_categories_get_categories +gdata_app_categories_is_fixed + +gdata_app_categories_get_type +GDATA_APP_CATEGORIES +GDATA_APP_CATEGORIES_CLASS +GDATA_APP_CATEGORIES_GET_CLASS +GDATA_IS_APP_CATEGORIES +GDATA_IS_APP_CATEGORIES_CLASS +GDATA_TYPE_APP_CATEGORIES + +GDataAPPCategoriesPrivate +
+ +
+gdata-comparable +GDataComparable +GDataComparable +GDataComparableIface +gdata_comparable_compare + +gdata_comparable_get_type +GDATA_COMPARABLE +GDATA_COMPARABLE_CLASS +GDATA_COMPARABLE_GET_IFACE +GDATA_IS_COMPARABLE +GDATA_TYPE_COMPARABLE +
+ +
+gdata-batch-operation +GDataBatchOperation +GDataBatchOperation +GDataBatchOperationClass +GDataBatchOperationType +GDataBatchOperationCallback +gdata_batch_operation_add_query +gdata_batch_operation_add_insertion +gdata_batch_operation_add_update +gdata_batch_operation_add_deletion +gdata_batch_operation_run +gdata_batch_operation_run_async +gdata_batch_operation_run_finish +gdata_batch_operation_get_service +gdata_batch_operation_get_authorization_domain +gdata_batch_operation_get_feed_uri + +GDATA_BATCH_OPERATION +GDATA_IS_BATCH_OPERATION +GDATA_TYPE_BATCH_OPERATION +gdata_batch_operation_get_type +GDATA_BATCH_OPERATION_GET_CLASS +GDATA_BATCH_OPERATION_CLASS +GDATA_IS_BATCH_OPERATION_CLASS + +GDataBatchOperationPrivate +
+ +
+gdata-batchable +GDataBatchable +GDataBatchable +GDataBatchableIface +gdata_batchable_create_operation + +gdata_batchable_get_type +GDATA_BATCHABLE +GDATA_BATCHABLE_CLASS +GDATA_BATCHABLE_GET_IFACE +GDATA_IS_BATCHABLE +GDATA_TYPE_BATCHABLE +
+ +
+gdata-contacts-group +GDataContactsGroup +GDATA_CONTACTS_GROUP_CONTACTS +GDATA_CONTACTS_GROUP_FRIENDS +GDATA_CONTACTS_GROUP_FAMILY +GDATA_CONTACTS_GROUP_COWORKERS +GDataContactsGroup +GDataContactsGroupClass +gdata_contacts_group_new +gdata_contacts_group_get_edited +gdata_contacts_group_is_deleted +gdata_contacts_group_get_system_group_id +gdata_contacts_group_get_extended_property +gdata_contacts_group_get_extended_properties +gdata_contacts_group_set_extended_property + +GDATA_CONTACTS_GROUP +GDATA_IS_CONTACTS_GROUP +GDATA_TYPE_CONTACTS_GROUP +gdata_contacts_group_get_type +GDATA_CONTACTS_GROUP_GET_CLASS +GDATA_CONTACTS_GROUP_CLASS +GDATA_IS_CONTACTS_GROUP_CLASS + +GDataContactsGroupPrivate +
+ +
+gdata-authorizer +GDataAuthorizer +GDataAuthorizer +GDataAuthorizerInterface +gdata_authorizer_process_request +gdata_authorizer_is_authorized_for_domain +gdata_authorizer_refresh_authorization +gdata_authorizer_refresh_authorization_async +gdata_authorizer_refresh_authorization_finish + +GDATA_TYPE_AUTHORIZER +GDATA_AUTHORIZER +GDATA_AUTHORIZER_CLASS +GDATA_IS_AUTHORIZER +GDATA_AUTHORIZER_GET_IFACE +gdata_authorizer_get_type +
+ +
+gdata-authorization-domain +GDataAuthorizationDomain +GDataAuthorizationDomain +GDataAuthorizationDomainClass +gdata_authorization_domain_get_service_name +gdata_authorization_domain_get_scope + +GDATA_AUTHORIZATION_DOMAIN +GDATA_IS_AUTHORIZATION_DOMAIN +GDATA_TYPE_AUTHORIZATION_DOMAIN +gdata_authorization_domain_get_type +GDATA_AUTHORIZATION_DOMAIN_GET_CLASS +GDATA_AUTHORIZATION_DOMAIN_CLASS +GDATA_IS_AUTHORIZATION_DOMAIN_CLASS + +GDataAuthorizationDomainPrivate +
+ +
+gdata-client-login-authorizer +GDataClientLoginAuthorizer +GDataClientLoginAuthorizer +GDataClientLoginAuthorizerClass +GDataClientLoginAuthorizerError +gdata_client_login_authorizer_new +gdata_client_login_authorizer_new_for_authorization_domains +gdata_client_login_authorizer_authenticate +gdata_client_login_authorizer_authenticate_async +gdata_client_login_authorizer_authenticate_finish +gdata_client_login_authorizer_get_client_id +gdata_client_login_authorizer_get_username +gdata_client_login_authorizer_get_password +gdata_client_login_authorizer_get_proxy_uri +gdata_client_login_authorizer_set_proxy_uri +gdata_client_login_authorizer_get_proxy_resolver +gdata_client_login_authorizer_set_proxy_resolver +gdata_client_login_authorizer_get_timeout +gdata_client_login_authorizer_set_timeout + +GDATA_TYPE_CLIENT_LOGIN_AUTHORIZER +GDATA_CLIENT_LOGIN_AUTHORIZER +GDATA_CLIENT_LOGIN_AUTHORIZER_CLASS +GDATA_IS_CLIENT_LOGIN_AUTHORIZER +GDATA_IS_CLIENT_LOGIN_AUTHORIZER_CLASS +GDATA_CLIENT_LOGIN_AUTHORIZER_GET_CLASS +gdata_client_login_authorizer_get_type +GDATA_CLIENT_LOGIN_AUTHORIZER_ERROR +gdata_client_login_authorizer_error_quark + +GDataClientLoginAuthorizerPrivate +
+ +
+gdata-oauth1-authorizer +GDataOAuth1Authorizer +GDataOAuth1Authorizer +GDataOAuth1AuthorizerClass +gdata_oauth1_authorizer_new +gdata_oauth1_authorizer_new_for_authorization_domains +gdata_oauth1_authorizer_request_authentication_uri +gdata_oauth1_authorizer_request_authentication_uri_async +gdata_oauth1_authorizer_request_authentication_uri_finish +gdata_oauth1_authorizer_request_authorization +gdata_oauth1_authorizer_request_authorization_async +gdata_oauth1_authorizer_request_authorization_finish +gdata_oauth1_authorizer_get_application_name +gdata_oauth1_authorizer_get_locale +gdata_oauth1_authorizer_set_locale +gdata_oauth1_authorizer_get_proxy_uri +gdata_oauth1_authorizer_set_proxy_uri +gdata_oauth1_authorizer_get_proxy_resolver +gdata_oauth1_authorizer_set_proxy_resolver +gdata_oauth1_authorizer_get_timeout +gdata_oauth1_authorizer_set_timeout + +GDATA_TYPE_OAUTH1_AUTHORIZER +GDATA_OAUTH1_AUTHORIZER +GDATA_OAUTH1_AUTHORIZER_CLASS +GDATA_IS_OAUTH1_AUTHORIZER +GDATA_IS_OAUTH1_AUTHORIZER_CLASS +GDATA_OAUTH1_AUTHORIZER_GET_CLASS +gdata_oauth1_authorizer_get_type + +GDataOAuth1AuthorizerPrivate +
+ +@COMMENT@
+@COMMENT@gdata-goa-authorizer +@COMMENT@GDataGoaAuthorizer +@COMMENT@GDataGoaAuthorizer +@COMMENT@GDataGoaAuthorizerClass +@COMMENT@gdata_goa_authorizer_new +@COMMENT@gdata_goa_authorizer_get_goa_object +@COMMENT@ +@COMMENT@GDATA_TYPE_GOA_AUTHORIZER +@COMMENT@GDATA_GOA_AUTHORIZER +@COMMENT@GDATA_GOA_AUTHORIZER_CLASS +@COMMENT@GDATA_IS_GOA_AUTHORIZER +@COMMENT@GDATA_IS_GOA_AUTHORIZER_CLASS +@COMMENT@GDATA_GOA_AUTHORIZER_GET_CLASS +@COMMENT@gdata_goa_authorizer_get_type +@COMMENT@ +@COMMENT@GDataGoaAuthorizerPrivate +@COMMENT@GOA_API_IS_SUBJECT_TO_CHANGE +@COMMENT@
+ +
+gdata-commentable +GDataCommentable +GDataCommentable +GDataCommentableInterface +gdata_commentable_query_comments +gdata_commentable_query_comments_async +gdata_commentable_query_comments_finish +gdata_commentable_insert_comment +gdata_commentable_insert_comment_async +gdata_commentable_insert_comment_finish +gdata_commentable_delete_comment +gdata_commentable_delete_comment_async +gdata_commentable_delete_comment_finish + +gdata_commentable_get_type +GDATA_COMMENTABLE +GDATA_COMMENTABLE_CLASS +GDATA_COMMENTABLE_GET_IFACE +GDATA_IS_COMMENTABLE +GDATA_TYPE_COMMENTABLE +
+ +
+gdata-comment +GDataComment +GDataComment +GDataCommentClass + +GDATA_TYPE_COMMENT +GDATA_COMMENT +GDATA_COMMENT_CLASS +GDATA_IS_COMMENT +GDATA_IS_COMMENT_CLASS +GDATA_COMMENT_GET_CLASS +gdata_comment_get_type + +GDataCommentPrivate +
+ +
+gdata-youtube-comment +GDataYouTubeComment +GDataYouTubeComment +GDataYouTubeCommentClass +gdata_youtube_comment_new +gdata_youtube_comment_get_parent_comment_uri +gdata_youtube_comment_set_parent_comment_uri + +GDATA_TYPE_YOUTUBE_COMMENT +GDATA_YOUTUBE_COMMENT +GDATA_YOUTUBE_COMMENT_CLASS +GDATA_IS_YOUTUBE_COMMENT +GDATA_IS_YOUTUBE_COMMENT_CLASS +GDATA_YOUTUBE_COMMENT_GET_CLASS +gdata_youtube_comment_get_type + +GDataYouTubeCommentPrivate +
+ +
+gdata-picasaweb-comment +GDataPicasaWebComment +GDataPicasaWebComment +GDataPicasaWebCommentClass +gdata_picasaweb_comment_new + +GDATA_TYPE_PICASAWEB_COMMENT +GDATA_PICASAWEB_COMMENT +GDATA_PICASAWEB_COMMENT_CLASS +GDATA_IS_PICASAWEB_COMMENT +GDATA_IS_PICASAWEB_COMMENT_CLASS +GDATA_PICASAWEB_COMMENT_GET_CLASS +gdata_picasaweb_comment_get_type + +GDataPicasaWebCommentPrivate +
+ +
+gdata-documents-upload-query +GDataDocumentsUploadQuery +GDataDocumentsUploadQuery +GDataDocumentsUploadQueryClass +gdata_documents_upload_query_new +gdata_documents_upload_query_build_uri +gdata_documents_upload_query_get_folder +gdata_documents_upload_query_set_folder +gdata_documents_upload_query_get_convert +gdata_documents_upload_query_set_convert + +gdata_documents_upload_query_get_type +GDATA_DOCUMENTS_UPLOAD_QUERY +GDATA_DOCUMENTS_UPLOAD_QUERY_CLASS +GDATA_DOCUMENTS_UPLOAD_QUERY_GET_CLASS +GDATA_IS_DOCUMENTS_UPLOAD_QUERY +GDATA_IS_DOCUMENTS_UPLOAD_QUERY_CLASS +GDATA_TYPE_DOCUMENTS_UPLOAD_QUERY + +GDataDocumentsUploadQueryPrivate +
+ +
+gdata-tasks-service +GDataTasksService +GDataTasksService +GDataTasksServiceClass +gdata_tasks_service_new +gdata_tasks_service_get_primary_authorization_domain +gdata_tasks_service_query_all_tasklists +gdata_tasks_service_query_all_tasklists_async +gdata_tasks_service_query_tasks +gdata_tasks_service_query_tasks_async +gdata_tasks_service_insert_task +gdata_tasks_service_insert_task_async +gdata_tasks_service_insert_tasklist +gdata_tasks_service_insert_tasklist_async +gdata_tasks_service_delete_task +gdata_tasks_service_delete_task_async +gdata_tasks_service_delete_tasklist +gdata_tasks_service_delete_tasklist_async +gdata_tasks_service_update_task +gdata_tasks_service_update_task_async +gdata_tasks_service_update_tasklist +gdata_tasks_service_update_tasklist_async + +gdata_tasks_service_get_type +GDATA_TASKS_SERVICE +GDATA_TASKS_SERVICE_CLASS +GDATA_TASKS_SERVICE_GET_CLASS +GDATA_IS_TASKS_SERVICE +GDATA_IS_TASKS_SERVICE_CLASS +GDATA_TYPE_TASKS_SERVICE + +GDataTasksServicePrivate +
+ +
+gdata-tasks-query +GDataTasksQuery +GDataTasksQuery +GDataTasksQueryClass +gdata_tasks_query_new +gdata_tasks_query_get_completed_max +gdata_tasks_query_set_completed_max +gdata_tasks_query_get_completed_min +gdata_tasks_query_set_completed_min +gdata_tasks_query_get_due_max +gdata_tasks_query_set_due_max +gdata_tasks_query_get_due_min +gdata_tasks_query_set_due_min +gdata_tasks_query_get_show_completed +gdata_tasks_query_set_show_completed +gdata_tasks_query_get_show_deleted +gdata_tasks_query_set_show_deleted +gdata_tasks_query_get_show_hidden +gdata_tasks_query_set_show_hidden + +gdata_tasks_query_get_type +GDATA_TASKS_QUERY +GDATA_TASKS_QUERY_CLASS +GDATA_TASKS_QUERY_GET_CLASS +GDATA_IS_TASKS_QUERY +GDATA_IS_TASKS_QUERY_CLASS +GDATA_TYPE_TASKS_QUERY + +GDataTasksQueryPrivate +
+ +
+gdata-tasks-task +GDataTasksTask +GDATA_TASKS_STATUS_NEEDS_ACTION +GDATA_TASKS_STATUS_COMPLETED +GDataTasksTask +GDataTasksTaskClass +gdata_tasks_task_new +gdata_tasks_task_get_parent +gdata_tasks_task_set_parent +gdata_tasks_task_get_position +gdata_tasks_task_set_position +gdata_tasks_task_get_notes +gdata_tasks_task_set_notes +gdata_tasks_task_get_status +gdata_tasks_task_set_status +gdata_tasks_task_get_due +gdata_tasks_task_set_due +gdata_tasks_task_get_completed +gdata_tasks_task_set_completed +gdata_tasks_task_is_deleted +gdata_tasks_task_set_is_deleted +gdata_tasks_task_is_hidden + +gdata_tasks_task_get_type +GDATA_TASKS_TASK +GDATA_TASKS_TASK_CLASS +GDATA_TASKS_TASK_GET_CLASS +GDATA_IS_TASKS_TASK +GDATA_IS_TASKS_TASK_CLASS +GDATA_TYPE_TASKS_TASK + +GDataTasksTaskPrivate +
+ +
+gdata-tasks-tasklist +GDataTasksTasklist +GDataTasksTasklist +GDataTasksTasklistClass +gdata_tasks_tasklist_new + +gdata_tasks_tasklist_get_type +GDATA_TASKS_TASKLIST +GDATA_TASKS_TASKLIST_CLASS +GDATA_TASKS_TASKLIST_GET_CLASS +GDATA_IS_TASKS_TASKLIST +GDATA_IS_TASKS_TASKLIST_CLASS +GDATA_TYPE_TASKS_TASKLIST +
+ +
+gdata-freebase-service +GDataFreebaseService +GDataFreebaseService +GDataFreebaseServiceClass +gdata_freebase_service_new +gdata_freebase_service_get_primary_authorization_domain +gdata_freebase_service_query +gdata_freebase_service_query_async +gdata_freebase_service_get_topic +gdata_freebase_service_get_topic_async +gdata_freebase_service_search +gdata_freebase_service_search_async +gdata_freebase_service_get_image + +gdata_freebase_service_get_type +GDATA_FREEBASE_SERVICE +GDATA_FREEBASE_SERVICE_CLASS +GDATA_FREEBASE_SERVICE_GET_CLASS +GDATA_IS_FREEBASE_SERVICE +GDATA_IS_FREEBASE_SERVICE_CLASS +GDATA_TYPE_FREEBASE_SERVICE + +GDataFreebaseServicePrivate +
+ +
+gdata-freebase-query +GDataFreebaseQuery +GDataFreebaseQuery +GDataFreebaseQueryClass +gdata_freebase_query_new +gdata_freebase_query_new_from_variant + +gdata_freebase_query_get_type +GDATA_FREEBASE_QUERY +GDATA_FREEBASE_QUERY_CLASS +GDATA_FREEBASE_QUERY_GET_CLASS +GDATA_IS_FREEBASE_QUERY +GDATA_IS_FREEBASE_QUERY_CLASS +GDATA_TYPE_FREEBASE_QUERY + +GDataFreebaseQueryPrivate +
+ +
+gdata-freebase-result +GDataFreebaseResult +GDataFreebaseResult +GDataFreebaseResultClass +gdata_freebase_result_new +gdata_freebase_result_dup_variant + +gdata_freebase_result_get_type +GDATA_FREEBASE_RESULT +GDATA_FREEBASE_RESULT_CLASS +GDATA_FREEBASE_RESULT_GET_CLASS +GDATA_IS_FREEBASE_RESULT +GDATA_IS_FREEBASE_RESULT_CLASS +GDATA_TYPE_FREEBASE_RESULT + +GDataFreebaseResultPrivate +
+ +
+gdata-freebase-topic-query +GDataFreebaseTopicQuery +GDataFreebaseTopicQuery +GDataFreebaseTopicQueryClass +gdata_freebase_topic_query_new +gdata_freebase_topic_query_set_filter +gdata_freebase_topic_query_get_filter +gdata_freebase_topic_query_set_language +gdata_freebase_topic_query_get_language + +gdata_freebase_topic_query_get_type +GDATA_FREEBASE_TOPIC_QUERY +GDATA_FREEBASE_TOPIC_QUERY_CLASS +GDATA_FREEBASE_TOPIC_QUERY_GET_CLASS +GDATA_IS_FREEBASE_TOPIC_QUERY +GDATA_IS_FREEBASE_TOPIC_QUERY_CLASS +GDATA_TYPE_FREEBASE_TOPIC_QUERY + +GDataFreebaseTopicQueryPrivate +
+ +
+gdata-freebase-topic-result +GDataFreebaseTopicResult +GDataFreebaseTopicResult +GDataFreebaseTopicResultClass +gdata_freebase_topic_result_new +gdata_freebase_topic_result_dup_object +GDataFreebaseTopicObject +gdata_freebase_topic_object_ref +gdata_freebase_topic_object_unref +gdata_freebase_topic_object_list_properties +gdata_freebase_topic_object_get_id +gdata_freebase_topic_object_get_property_count +gdata_freebase_topic_object_get_property_hits +gdata_freebase_topic_object_get_property_value +GDataFreebaseTopicValue +gdata_freebase_topic_value_ref +gdata_freebase_topic_value_unref +gdata_freebase_topic_value_get_property +gdata_freebase_topic_value_get_text +gdata_freebase_topic_value_get_language +gdata_freebase_topic_value_get_creator +gdata_freebase_topic_value_get_timestamp +gdata_freebase_topic_value_get_value_type +gdata_freebase_topic_value_copy_value +gdata_freebase_topic_value_get_int +gdata_freebase_topic_value_get_double +gdata_freebase_topic_value_get_string +gdata_freebase_topic_value_get_object +gdata_freebase_topic_value_is_image + +gdata_freebase_topic_result_get_type +gdata_freebase_topic_object_get_type +gdata_freebase_topic_value_get_type +GDATA_FREEBASE_TOPIC_RESULT +GDATA_FREEBASE_TOPIC_RESULT_CLASS +GDATA_FREEBASE_TOPIC_RESULT_GET_CLASS +GDATA_IS_FREEBASE_TOPIC_RESULT +GDATA_IS_FREEBASE_TOPIC_RESULT_CLASS +GDATA_TYPE_FREEBASE_TOPIC_RESULT +GDATA_TYPE_FREEBASE_TOPIC_OBJECT +GDATA_TYPE_FREEBASE_TOPIC_VALUE + +GDataFreebaseTopicResultPrivate +
+ +
+gdata-freebase-search-query +GDataFreebaseSearchQuery +GDataFreebaseSearchQuery +GDataFreebaseSearchQueryClass +gdata_freebase_search_query_new +gdata_freebase_search_query_set_language +gdata_freebase_search_query_get_language +gdata_freebase_search_query_set_stemmed +gdata_freebase_search_query_get_stemmed +GDataFreebaseSearchFilterType +gdata_freebase_search_query_open_filter +gdata_freebase_search_query_close_filter +gdata_freebase_search_query_add_filter +gdata_freebase_search_query_add_location + +gdata_freebase_search_query_get_type +GDATA_FREEBASE_SEARCH_QUERY +GDATA_FREEBASE_SEARCH_QUERY_CLASS +GDATA_FREEBASE_SEARCH_QUERY_GET_CLASS +GDATA_IS_FREEBASE_SEARCH_QUERY +GDATA_IS_FREEBASE_SEARCH_QUERY_CLASS +GDATA_TYPE_FREEBASE_SEARCH_QUERY +gdata_freebase_search_filter_type_get_type +GDATA_TYPE_FREEBASE_SEARCH_FILTER_TYPE + +GDataFreebaseSearchQueryPrivate +
+ +
+gdata-freebase-search-result +GDataFreebaseSearchResult +GDataFreebaseSearchResult +GDataFreebaseSearchResultClass +GDataFreebaseSearchResultItem +gdata_freebase_search_result_new +gdata_freebase_search_result_get_num_items +gdata_freebase_search_result_get_total_hits +gdata_freebase_search_result_get_item +gdata_freebase_search_result_item_get_mid +gdata_freebase_search_result_item_get_id +gdata_freebase_search_result_item_get_name +gdata_freebase_search_result_item_get_language +gdata_freebase_search_result_item_get_notable_id +gdata_freebase_search_result_item_get_notable_name +gdata_freebase_search_result_item_get_score + +gdata_freebase_search_result_get_type +gdata_freebase_search_result_item_get_type +GDATA_FREEBASE_SEARCH_RESULT +GDATA_FREEBASE_SEARCH_RESULT_CLASS +GDATA_FREEBASE_SEARCH_RESULT_GET_CLASS +GDATA_IS_FREEBASE_SEARCH_RESULT +GDATA_IS_FREEBASE_SEARCH_RESULT_CLASS +GDATA_TYPE_FREEBASE_SEARCH_RESULT +GDATA_TYPE_FREEBASE_SEARCH_RESULT_ITEM + +GDataFreebaseSearchResultPrivate +
+ +
+gdata-oauth2-authorizer +GDataOAuth2Authorizer +GDATA_OAUTH2_REDIRECT_URI_OOB +GDATA_OAUTH2_REDIRECT_URI_OOB_AUTO +GDataOAuth2Authorizer +GDataOAuth2AuthorizerClass +gdata_oauth2_authorizer_new +gdata_oauth2_authorizer_new_for_authorization_domains +gdata_oauth2_authorizer_build_authentication_uri +gdata_oauth2_authorizer_request_authorization +gdata_oauth2_authorizer_request_authorization_async +gdata_oauth2_authorizer_request_authorization_finish +gdata_oauth2_authorizer_get_client_id +gdata_oauth2_authorizer_get_redirect_uri +gdata_oauth2_authorizer_get_client_secret +gdata_oauth2_authorizer_dup_refresh_token +gdata_oauth2_authorizer_set_refresh_token +gdata_oauth2_authorizer_get_locale +gdata_oauth2_authorizer_set_locale +gdata_oauth2_authorizer_get_timeout +gdata_oauth2_authorizer_set_timeout +gdata_oauth2_authorizer_get_proxy_resolver +gdata_oauth2_authorizer_set_proxy_resolver + +GDATA_TYPE_OAUTH2_AUTHORIZER +GDATA_OAUTH2_AUTHORIZER +GDATA_OAUTH2_AUTHORIZER_CLASS +GDATA_IS_OAUTH2_AUTHORIZER +GDATA_IS_OAUTH2_AUTHORIZER_CLASS +GDATA_OAUTH2_AUTHORIZER_GET_CLASS +gdata_oauth2_authorizer_get_type + +GDataOAuth2AuthorizerPrivate +
+ +
+gdata-youtube-feed +GDataYouTubeFeed +GDataYouTubeFeed +GDataYouTubeFeedClass + +gdata_youtube_feed_get_type +GDATA_YOUTUBE_FEED +GDATA_YOUTUBE_FEED_CLASS +GDATA_YOUTUBE_FEED_GET_CLASS +GDATA_IS_YOUTUBE_FEED +GDATA_IS_YOUTUBE_FEED_CLASS +GDATA_TYPE_YOUTUBE_FEED + +GDataYouTubeFeedPrivate +
+ +
+gdata-calendar-access-rule +GDataCalendarAccessRule +GDATA_CALENDAR_ACCESS_ROLE_READ +GDATA_CALENDAR_ACCESS_ROLE_FREE_BUSY +GDATA_CALENDAR_ACCESS_ROLE_EDITOR +GDATA_CALENDAR_ACCESS_ROLE_OWNER +GDATA_CALENDAR_ACCESS_ROLE_ROOT +GDataCalendarAccessRule +GDataCalendarAccessRuleClass +gdata_calendar_access_rule_new + +gdata_calendar_access_rule_get_type +GDATA_CALENDAR_ACCESS_RULE +GDATA_CALENDAR_ACCESS_RULE_CLASS +GDATA_CALENDAR_ACCESS_RULE_GET_CLASS +GDATA_IS_CALENDAR_ACCESS_RULE +GDATA_IS_CALENDAR_ACCESS_RULE_CLASS +GDATA_TYPE_CALENDAR_ACCESS_RULE + +GDataCalendarAccessRulePrivate +
+ +
+gdata-documents-access-rule +GDataDocumentsAccessRule +GDataDocumentsAccessRule +GDataDocumentsAccessRuleClass +gdata_documents_access_rule_new + +gdata_documents_access_rule_get_type +GDATA_DOCUMENTS_ACCESS_RULE +GDATA_DOCUMENTS_ACCESS_RULE_CLASS +GDATA_DOCUMENTS_ACCESS_RULE_GET_CLASS +GDATA_IS_DOCUMENTS_ACCESS_RULE +GDATA_IS_DOCUMENTS_ACCESS_RULE_CLASS +GDATA_TYPE_DOCUMENTS_ACCESS_RULE + +GDataDocumentsAccessRulePrivate +
diff --git a/docs/reference/meson.build b/docs/reference/meson.build new file mode 100644 index 0000000..859ee12 --- /dev/null +++ b/docs/reference/meson.build @@ -0,0 +1,78 @@ +subdir('xml') + +doc_module = 'gdata' + +ignore_headers = [ + 'common.h', + 'gdata-batch-feed.h', + 'gdata-batch-private.h', + 'gdata-buffer.h', + 'gdata-documents-enums.h', + 'gdata-documents-utils.h', + 'gdata-dummy-authorizer.h', + 'gdata-enums.h', + 'gdata-exif-tags.h', + 'gdata-gd-feed-link.h', + 'gdata-georss-where.h', + 'gdata-marshal.h', + 'gdata-media-enums.h', + 'gdata-media-group.h', + 'gdata-parser.h', + 'gdata-picasaweb-enums.h', + 'gdata-private.h', + 'gdata-youtube-enums.h', + 'mock-resolver.h', + 'mock-server.h', + # FIXME: these files are created by enums workaround + 'gdata-documents-enums-in.h', + 'gdata-enums-in.h', + 'gdata-freebase-enums-in.h', + 'gdata-media-enums-in.h', + 'gdata-picasaweb-enums-in.h', + 'gdata-youtube-enums-in.h', +] + +ignore_files = [] + +if not enable_goa + ignore_headers += ['gdata-goa-authorizer.h'] + ignore_files += ['gdata-goa-authorizer.c'] +endif + +scan_args = [ + '--rebuild-types', + '--deprecated-guards=LIBGDATA_DISABLE_DEPRECATED', +] + +content_files = [ + 'gdata-overview.xml', + 'gdata-running.xml', +] + +# Images to copy into HTML directory. +html_assets = [ + 'structure.png', + 'data-flow.png', + 'cancellation.png', +] + +content_files += configure_file( + input: 'gdata-sections.txt.in', + output: '@BASENAME@', + configuration: {'COMMENT': (enable_goa) ? '': '#'}, +) + +gnome.gtkdoc( + doc_module, + main_xml: doc_module + '-docs.xml', + src_dir: gdata_inc_dir, + ignore_headers: ignore_headers, + dependencies: libgdata_dep, + namespace: doc_module, + scan_args: scan_args, + mkdb_args: '--ignore-files=' + ' '.join(ignore_files), + fixxref_args: '--html-dir=' + (gdata_prefix / gnome.gtkdoc_html_dir(gdata_name)), + content_files: content_files, + html_assets: html_assets, + install: true, +) diff --git a/docs/reference/structure.dia b/docs/reference/structure.dia new file mode 100644 index 0000000000000000000000000000000000000000..4d35938f65dd7b534bee99a6f46624b81270966d GIT binary patch literal 1803 zcmV+m2lV(KiwFP!000021MOYkbDKC2e$QXQxUY$feu309>0Ep5-NVh?+_d-Xk&Wzd z#oz&)#4q=^p8z|KZLkwSxa8!Sx;2q^wPL^3r`;|2@bPgTSobnc{3yH`Kwu9n8BQY4 z4`(-nzrTOIVuO#j7au%dyjOo_v6x%x8)1@tx*6Q1>Eiux`0(%mf>k2YC_6zsgRSsKO3_i zm8e1C?DpL+YU6RRm%sED($akRokAI;EHL471jzX$;aGz6R-l%rGyhq?d(v?Tq>_HYZq(Z z(l%iB?u#^2y6c72p6DXlOwoSWsZ43wb~8mH@Mqy%mfuYoF6Sl3 z_+tn8va{&xuyLPHX&)Wisi2oZZW5{ZJxNuZNe+Ov`H6L>BGcMA(w;4lYgYBI(_0fv}mpL#<% zK8rwR_rXw)?x;uRl!klslY5Y}a1Wiw^R{^h6B1!!ct;c7 z;Wh>v*PQ1dF2FXTMV^D&z~L_KQ=a2Xn8qtZHFQ&r!VeA8=qJ-~&cZZU)8L04y;%-S zw^~Z0Fv+kD!#0lMjkmz;wc@Ry_66PwZm%704NNk4Gk81B?qTCTH)88fD`E!_ zs`!18RwPOpacM8pikrU;+1F0?ZIf5*G23UF*?v_tge@dHG)F_C82_fkLJ_dtUPi(% z_sZ2x80;YDVZva4!yrFP(gQZ`BSo&(`U-NM>MNLbQD3QV&)YtM3D2DhW=>#@I7j0~ zQVca0SP%!07v&X<0E2xhuKcx>rnsV?XcRtZct$^Y20Tv>DI_fr4Xx?kf@u`#-hygq zPxm%3$&d|0HcpTY+5*|ooZvt%V6MAK_hJGdLj6ql8t%~*_b^G09+QvrG?7B5h29RT zy|sgEJ3E;E#txI^DEr?lQ^XNB#G?`Ma9gM|>&I{M2sbhnZI;fJz}Y_Jvz%S>lgnPp_d&B+GO^Bi_n2K7z%^H0>iMq!@kqtoo z0tG_<2T;`6mSA}+3G8TFLa+zh(guNcR|q_{EoB1?0^b+{*_jZCS}6JGJbK^^cKOKz z!;S#BYf*Vc!Qk(W;IFF5!8!1NBjDXHQgnviHXbvm6TJv-(2Gz<=-sub{FyQay>AS? zO~9)gyA?GL)chHFRCCRP1Bfpva4@m)b=KO1I8$iG4(&tP<8u^CEB`$JXRLd$!@|ea zrzr6BS3e-YeD|fh_>udg12H3StNMZZQ~hWuG|?79ljc4!7f_rN3dd#aI@3o0MiBq} tacTYZKogp}4Nb})9mJRkO+QI!Dn92RxV_lat=WqaOD zAMcC|b$^}n6Nc2ZR}cQ<*3ZGo-@Nv;tPNahcPF)MQzvRBRf}LQ6C*}jR`Xtyny8Fe zD$nsBnoA_SG`qQdqsZ{$5p~9&Bj1yg%~dai&mO#=B+dJ1Fkr-r`=5Q+mDN=WLD%h# zk*sIWo)r`neE9G|kzB)a*KA9G4GbqsLe%$YkPkc>V%D=>ZEZGN5Yn-zxngB(W!_iI{bx%+`hFY@ z+@yU2>e;LGQJgDo%SXzKk%qxBgiJgTGiz%>%b}EKcyz?1q*}R5F>n=AyTxW<@ALiq ze0u6b*XOL1YqMI;BBC^s6NQsGybz#uaY*_;P zFPuaRF}fv`e0IpS!DN!a+~be$c-sbp5hE@@1|IwjLR;Nbt`%PRcnz15z@t-m*WxRD zw2A#)b*+tTWU?;Mdnm&rT;gWXITZ&q-+)KgR$ciL=oD*c>;E+w$6V+cFHq;RUts24 zqBQy)L`no2LEo;6^+vLhqGQ6zcx@8+oz{xl*ptvFYW?nReQz$GVZ4cN!8&#$_$xpG zTIWmKi4NIc>3r4C;P*cNc(yy=|KvS4Q6U2@tvRyJ0dfrHneXrr3^ndC?{hYa-P{qY zt}v45v@}EB2j;9AV=KMUV`F0t|H#of!=_wVL6<62KI3CA#}}DtX;;B6vNjM#6aEy~ zU2NIg+e55#I*6jq$YMCBVu7aP>avNBh=VCjQaVP)zPY)E6~?eNaTo8aom$dx3vX?~ z@jB4zr^I){z^rzg8NKs(-GCAO{7N8FK<3!9zZp`k*k~3Q&7pv1?(%8bgcl0+t$z-q zqN0jRN?<$0g8__lwf5<11>19@xIFix+ek?cS49x6p#?1c`iw$5r@AH{n=0ay6kPvj z-TQu?b{h)=Uku~ub-}JfW8_xhPV2$+)z5q}?vLu`SGViI;EjPqE+|ZQE|`<3aIMuJ zm7kwK?evi}`oKHT=9?5~)CG2;r!exZx`bMtkkSSXTFPV^b(8)_Om9^Pu+RXkNFw6Nwe*r9L* zx+>1q+u!NmlkT(lVZ-_t$4h**`AX{bGDE6Z}%!9)5sbf?9+b29O_P~dCpt;C>5Q=*rz%< zuWmE86fyuF)^EmXi{7W7pHy94eM}xuP%dC!)qHMrJ!FdL5J&m^l2ynjOQn#;MD2<> z*5DnX%7m@5l$l?PpKy9V5y`VfDZ8I~{Ey+wTFR7!qg_9YU>_VGJ8HhSVU{rKZD$Ik z>{Bi167jNdLo~|&%r2aBHFDqcu*nz>>n_-R&pxh$mU!8BT21Q_*e_kD>7s}Cl1*4T zGA*stw$&PSyapjvLpqliQd;$il<@XNPIvXZ{iwuG%U^jC7LytxDsGJp&X9`Ay4mDV z{uE+m1nB_kW^ijrNZ#SmVs;R=--+XXyO*iY(G-F~I_}kkhW$Aj>HU^&yo`b0zyAzU zS-TgMPn6<`==UFZJ~h7=yZ=ucKw$%#jIk}Zm)0%5Hz}#9m>3vgVPQxl@(DKO_0?Vr zQ*7VtzzPhDN@SqX`SSRKLEioOc%a!{1QVVI@;vXh=(GR(ZEx54zb|30(-ffV^3r_^ zVP^LY#abrR61{*faNU_*U0Z|doqIP|R8(j%Y8FjEUd8uYzs9?7mX8fJ9sQzKKrY~% zU(w8;a+U`+;e#C^c-p1<1zJT%hli)zGe@ncROOM_ltROkmo(Dfi(La(Deo=M zgBUe3^WB}fT3COR=Skt4^R93*)2=XM`^I0ZjuPVH+@yoCOxoj67gg1fU>q86Z|@|q zn9w5dA(WfcHPN8X=js$(nAV+XZ8aYL`Ia#jx;~UTGcyCsKDgB6b;g>GDBG+E?p*r) z`@OxreF!8|g&s^Mf>O9pt0-N_gVTPYF`SH#*J}7Dn67jLC2i(lGM{z7zHN!Uo!vr% z+aA>N-Kk8*p=-MD{!w#q!dGUI__^_J3;nxa>XP82(B&T z%9m@G$(pO^o0}W;_4uEn?$PWI7A950pRoLA&(_)N5T*uaUP?m|IyxMV{1L`U=>Omi z4hn{LLdLmScV!(oB+R;2FUd%J=p&EWOE-*~yc7ob`S{k+?r*;=2#O$AfzlDazv*?`ytq?yemo)+`m*wF~FLmU`EX*2G?S5cV z^QF3`=6i5(d3E)xOb*kof1W&nawi30Q|*El;4EqiJm=%9t*++&ET&TFaC!WGYks}IXFC|&J?{p_YbE68sYQjw=gbduWS|BtyARXU&Ne| z-*|@Nr)b?0IAyH&u^O}98tzD0sF$17T1u*(^QF{vHI!e=PBxw=PW>5%+ zHkH0*zdm)+)k2;k^5)3wqLy;ru;H%zOuVZ8v5QCa{7!@S{`ASR`jz5=>!DnqdyVVj zWpQJ1NK=<)8DEZE@ABlrpwni_9v9b?rMZu#^_tNpyy~XEhI7rLYmaYzx&NF$=vl^YKYpTMYH( zUAA~sbJSA#odON)CJG7kmT^_@Zf{T?J))+j4&DHo!klk=EDup>-aowxG-;tmVf1U| zN^H=e)Uc^A92j8*Wo65&0%)SOm6ba<-Z1Ma!)9-O4vvcQ@^Z7CsL063)Kr#8nR=k_ zf4=qaj-bLDiDS`=V>6;8BlB7xqTmfntx(y)kf-<%dsv1*Gy6s$Sax%09&xIeIui#D zv2D0KgdD4V*|GRlo15Sj=^;G*=HsnDrLPdHUh0ApzCxx*^bX;nst$-ceb@5 z2}!%*Qy>}N-iUp}6q279Ve4J#JUGD4+q}3f8su_9asC}K%A);+Y%Vz%V<{@z$@h)h zk@2^ThxX!kzX~LhTMG5^3p1B84c5Z&tst z5th_sw25@biAhwFA1QT>0s$L-Z`-k3Mwb(*yZ=ncd-|AX>7W}wy<120xVx0AKj@#Fronz{1ZRVWM;v0U= zdVUJ&Eg~)JH;YaeMW_^bl8_Za_g+m1c0S%zFG}|-A8D`J39YX(&M&CxqNNU$Ag83M z0Xo&Dm*@9(`W?4>9YIhxxo!fn1A7s@k@=JgyL&(~ENFzvDXq^jX6s7YsgBz$R?q+a zawUgNx{ySd*m0S%Z?l#2RcgfcZu*b4TztMA`w{aRiJ1lPX+t|??y5VdOG_x;V(GYB zQbMb~BH5l8f8H@c^S#lLF25x#k5`0ZOsQ+aiW^vF0tj$J2=VdD`Aq z{ zPpV@leVTRn!)D(YWSsN)*M|rY8 z^K#_K-7GYsyuAHB;?=!4%TZ|RwEnFjfHA~}vfKF0Ehecp-J6~~kGHDEYL{Ff?mfIT z?kh}9w>`1{UAz1133bx&mPAFQ``?WKvfP{Dp3Yii0#Sq0+1Tj^OS>(z9d}WYLZomZ z&t^`GFU9ZO7So})i}p1eks20$rT~LjI>oEY_MG&lD_OxiUcStB0=dUH=4%$hvfr@} zKio>aetf&5rHT_IBUqzbL22UfU5>y&Ujg#=(c8KPugqFE)JQ8wM^2oQnkuek$B2gd zg_C_NAd_V3ao?x9y z!+N0fu-#Z_Rs$+7v&?EC2`?O%mV~T~>I+?!b%ka<5}r%gPCNM;{Dj#JC*hFp=I_nS z;w|Qv@c!@uF|ADRLy`2qd87tcEHpe)S~YyUYgrPQ(zYiU+m<*kYK1XHA@r}|=Q?J_ zSwo(0*h+!j%~ec>#$!{7==YWsI)`%T>CF|cLNqpcpT=_dTspgo2UJuXY)%v*(nb9a zmO2lXyRA{G1NHzw5*`*7Ob?=B@at>{e72x|VyK){8VwQ?tM`h7W7JUH&d0a5^2AFunk7zsqVR^b%~>}1|{-VOG2Cr#dU@fWM+s>Gg>oZQ8XD(q?wdF zPVYXn9WGx~F74;9v{84)v<}vhclFOSdRd=EYa2CMgzv5*)+T?o4)jj0T$lVqE#Q2h z+P%hV^7*r?^b}1rf!xXQneM&^`RA92#rC9N#tp*4S7q#r@8~TyIyDa$w5c%Oy>b54 zmH||qxj*Jb;1h5E>r8KIv;#~+Vzf6HmSS_w6^NynLPy`R3LAxj`3i-vbRGd7tGPs} z#5CIYC${s+?H|cY$n|(_a43DE4JKfcmNisN>hhM>dC3uWcq6MlOoL6yq=#F3DUG!+ z3FqpSR+L_U)W=YlnfDKaXnudpW+cEl;o;y|`&b9zVqvlGH|ty-H1X6N z$hSlwO-;Z*i|lM9Ju~yLRj%&4k0Fhim|mo0R0srH?SZaw21n3QX#oQcCLfm*2RnU( zbUsdiTF&rx`rlVa-gZ7qX7C^VS>?XVZ-59UvAhok3%!UfB%_;n7vvPKn;$f>ggNgHT%kwT-ee2Yf^fD-v$e3 zo*b;Qoj4hu6g2p#kmVlSJj zdwOJCTgS)8vj<*zVyzn?6nlMvf3Ho`QWlq(c(E};+g!0rC_RM*Jh@_llrXVF#~_>fv2TxOvM<37D|{pV~+Pnlr3cEX3ntQkH5}% zILAvn(3xCg(CJ~>`=Mp?0u55ngB0PT(;IEe$?y@PBr?*kM{eiS^;6{47@jFJ zxEgb>xL;nUdm_9#Z7TL|yW$B{7R> zg&@b}yDeze0ELkIeiW@drHHo-q_?-%cD7ol$O4wVUr- zbzJmVPn8J5!WmiZk4K~llaZ3jL4aRBxloz`g4(iqn)v>m@q#e`V1-zLSlnrCz`@CB ztaNZ_XracGN zo<>Hg{&v;Th7xIr0`#4{Hj&_%Jed&}O(U>!JS~gvNhwaEtir`PdcB&HYnj>AqY^$^ zxW?x70aJ(NZrax4XX%hjc$4o!TlmJu$jIT5zCW^Z*J&-c`Xa6&;T^g;T9`VV*Q=6; z${*nz+q=76^VUnZOSZC(T5{sLCZ?i{SLGa8h&PCC>AP)lb0(p2i)$k1H>8*@HJkX_&juhegY$*O-l9G!SW+{$NPOC=* zq~Sa5L2Rs1xUFU1UQ(m8PTiVELI;=O#Kij6!#`KPvl0--**2=E{K&XmAIppCSE))# z3g(6?B4hO*O6KQH28yj*8ikVf#WZrO6p3O03QA{+nzJUQ| zzGjc3wQX+w5;ZPDsE|bdCz)UAJdLZsM5WfBLg=*nR{Hwg(p5v^AHa08Gzz$~D-H4} z2QK~~i~q1(2q}G5FlOfdSk6nAX%rz{Xk?g!Yues1PPA$P=Wvi6J@K-q%~@rL+3e{i zL1pW@^mvELQ>k4vA$sGXm!VO>lOz~1nnt%Cqd3vq)iE~X-L=V;s#}K^e#`R!Z@lL_ zVzu}}SieB6f2FUX;sZpZ*X|E23?nSinfUys`Q#5r?Ft%P|7Ap2L?-SYz(-(mC4CG% z!hY*z;nFo2yX-&u{}2)oJ;Qt)mrDq7zMRzAkxzX0LJ8r)foMh&)1YL%-9arDtb55R zB3Gc+l_z3Q;icLA2@5Ok6oX@EQt51&CS+rzYP!2uIk=~LMz2Jbs@_whKn;Z3bt~Nk zGat+&#BE+dw>KL=JgU{)s;_jxxBCf-=kO+7S69jV_8Q_VBKXd$;O8ef{9-6|j#PB1 z#%)|Q7ZdHOy1cwdJAVE|mwqWtgfv7jTW#k>^4ESvjm8ANlfneGFOMI=q^d-iir!_Z z;z{BYbTZ+u^48#^smJzxObiPy?KO*(TpeioOltgM>8oPZB9HKGYa+R8`RT!gP^KR% zdU(>foT6{;;o8E0&rw>SV(t22!jd>FGQrxyUJNqj*FW6o-4|fdxSdT@`@>5U1E(N{ zG)I5%HczYhP)UT=i%I@{p9?m}49`u7ANI5OymUUp{2W0R?hm6YZ2{;&Ntt&$hve7Q z)tQl4o*y#hw6?YaNQ_+6w-I1~jIox8G!~L7AXmSBi4}e&WYN7o>}NCW{>}oj27`n1 zKwA}jf?hZ7kLJkFsA=Y?RnWjpD%=5_<#oEvz~>79k6EKH>^wXZgj@D(68XPY-YT*T z{$pg{BH($TDiX20XWXsOXnxNrp`g9qC~OF8fZ9;0|-= z&ZATeL*Eo`kM~s^^4}R_3t5i5spnumpOV}<8H@?lAMh;pg%@S3& z50t#Qb26?I33fDoLgz;d=vOJlsg0?P!NL81hNy05y0Y}#Qs>&)!;(w3&eKf$g}=Gp z+P2I$9co(t!St~)Htt;ZiA}rxtUqL$KqnSV0B@sBY_IuyKv63Nvt79E?dHw4`?kS#4XWVr(Q`(OEtL1%??ygK6QMh$p zy&cI#uyIdMg7xCNH~ZGwExWkXjvwgkp4&7orOK!aHcMOME%YaUfl=8vn2M*!Wsn?H zHFz;aJDLV>#E(?WuKqUGx`~I!q`wPU=%cW)n?-nEo!31qo7Tr>hh5;Ipaqyrl^Ot< zg1c;K$;qJwwO7Dkwv)v(05o}mMgHzE?|Eis=47#s6M$^9vtLm=Iy$0ZVy5!iCPhR< z@UDTla+WIjjmxG+o>FSxE(a^C-OelwWGO=;BI0|^K)^~#NeM(BK)IXK6{e4m^o=Gi zcIO)afCn&STEb9}%WC=frwt&$R;UR8dtKVxEZoV?&+ln%{amtU#PhJ0lSFGx#(GfO z$cM*m7l}aSXY)kB3g?EVanEitEahLrsOIu6YqJCD8Lr>TMSN(G@K#`DM$g}@39>Ug zy<+6-$?F7}kmhjYE#9r$>Dm591tnc4f}K!Z+N(OcK4KB~MDmXjM^0}r>q!6xPo zt-HK|*M&a52}aqRUT2jYLD4EFR3%^Q?LV3<6d)#@4f*mtUyuBI3UP8~8HuHU~#X$y}C7@Kk(! zd@H{mxAA;c5NL5qqdmC$uosBML73D*D+=`1Dc$$QHxn7M4FYP*kHid4&rYi?P*^sV z!u6InClL}G;S)vLM1+L*8_*Ol4zK}#e}9)${0HL(7#vMsbWefxqR#aA^o$_*U<`1nucxbou1k2)15a*-?Pn9Q)cq0WKqKYb71+}qa zrQBG5L!{0@ApkEK3Q;;x??RB;g5*oYk!wIHSS)2ZaExE_};53hG# zh>ltP_J(#H`*E};3XPw(Di1F{@y9Psip(r5FqZq&umh{?_W4Lf@`Q)# z6`O!Jjk;Fx?o6AwN{QR!JAT8{F9CaSEz@=j%C0$)T!O0-s6dv$rl-Qf*l}i@A>EKx zVEs@|oK3o2&$1SLfM?0ccX8b8_-w?UhBhC44dWwpiLSIOP(G*uXJk1hGifNFl`*F1 z`&Y}5u)6u=#4Uk%-BG5Vr6$+OiD`BQbzdF>*TR_0jG_|!=g#6|IwrMMpnT4sh zJ&9UsT1IQ$H>JE^&Br(F!s=qcg}uCJ!87hc2s2wr+Q?fEr8_GxTi9}MqGta+o{o-E z__f4&%Rle0q;y-EUgF__{U6w9b|=Kl^hh~TmF-F5&nFe;cDgS8_hR>{_A`spw0J-O z$ccCL_lE{k;iZ7@cwV;%*2sts9|NP0Yh5X0xc9xfESX36m+TGIc6YolO zgwe@H*@s6*Tzq$yxLhECTv=YuPA%ZHu4w<_UXoR4l%&n@RDtr8N7WMz=Tsaj_ukg4S_fFuU=0-u_i8dPjbe6#>P<-9PX2)TcGApUYCBn`Y4 z-4_}a@4PpLUotTjIku|+V#$Yz!U-_34wHk)F@`3>#r`4fO#vFv{jg=C$G2Vdy`4Ad zP#YWXrH&BbYBe(AnzJ?*fYbm5zvEZLdU{>z&Y8ox15)AsDGT4*`8aPx>OIy<$J^SL zE>E^zzI;jWPu4&H=`h#<;L!~a565gT8OraT89LsnX?!n@zTd5zgQ=So%Fx}D8%9o+ zygCq%y6r8T92^w5;~91qJ!AyY?cd|SV*nE|YWBVuN!F3Jw*aIejJ@~sfCtoGdW!HExM=q+auBY)vz6D#%(BAEtsu|8RK$xiaIHH@IuC+HJBTEho!`SiIKRdJRM}h@o z)2j)y#ee$GzqWWY4r~O~n~y&~jOF@V9*?-Nssw?ozh;q^?5im7+24CTUZ~0BYJ7cu zFgv18Mn*Aw_{ae~jEKO1=;1OOu{umW}; zOqP?2t0;)5>z<)d*a>J5+a6Cb?_VsnsNRn;?^o;psFTn!=JM$09jkubkF>P3xVX5a zB*y1Yaq;k6QdL^agd~ex`9KNL^^=+DMziq7x2hHlnC_JtJklk=XQV3 zAL|^mP|!UA3*nNO$&$!Y zr_Tbf_)qP|W7|(D6-fh+fzee7!Y5eKzco!2vmqSyiz;<0pw(w(V`GA`^D(gr^1R$k zs(d$8GdDf$eSOf4_gX1N=2h%A8X(YhfoWYFt+N?5>*uK9M5Z>h*vnwYOSM|?4%I6u z@|9A|GP4aF+0Ltj(cLeg2c_5R)dQdPz_*xsE`XS)610CFsH%;XJO}6b`$lF8E=CcR zoalWK;qpW()6>h?EU!Z}yq?hI;$z?P6;Q`FOQCFQL#Yk#TOS1)8#b^2Ye)jpY9RCw z@;YU1XSY+Fed0p3`kNqsD;q55?-oUqEyfBL%%>Dl$L!aaBP9oCrOdk38z2z^6fdl{ zw#;1*m?{*o`@;Z83J`zE3ELL3_?&EHZD9Ei=)tpdBoCgYeAJCYq-1B{4p=gNes|zl zUYwt6ls~hhe`3E0paQT{D)jiJzAvemZ?b$R>qx`vG5Q!8tY3 zj=dvgrh@tQ)_NB^HWJ^<ixF6%{~j5w{G+o*m@-~{Ot3z!VBIx5x@OEC+Tr|+ahqc3%}6C z#ahR2$$rVR%4NIn-=wgb5?%%#4H9c*YUn-j{23sGRX z7R0D?Ih-1si_;fuEHFn@Y~#n9=(GkH6z!(WW&P+6mhoy8^J!%-xeQxuvDggHYJsH8 z5bO^bV2qfRg&A)?;*G_2cMD%n&{3V%S&(`s4H!U>(b)kkdBXU3`F%)*c6q6>v@6O1rjnbc>Y&w;wQyME%%7g zBhxCJ(6es}EY7J)sn5N(kgYJTYHSiL?JO;vcB?$)$0y`t7GgdZBxJ*kJ-x_lS!Htv zoU0%G%SAD0SV2WiLDi`ZcMV51e_7uSAxydb)OziJND1nXnsQPvYhzC$%dQe;8+Zd7svA1tqiHyA8 zLX2rz#KMa@u{NMo(CPT>cplb3$1N6DG3~1#EGBZdooy<1!kzbvHzi`i781p!_h^CS z3u&z{bYTajIpg;#4d%@i0g42iHiUL^FYG)e7#wz{=w7)JNg#<8z$Oh0D4>>!MdVTd z&%vOLz163y32H8u=N8_P3roZrrvQt-L_!?f&^I){2y-aX9RftjCyKMPb(e7s-|XqF z7F-}K>nJW?hdUa-Q2Ene>^=?d5zMc$_3r{)a-b4eV1Vkaktm+=4(>>c^Vo$7sIAQu zHI#Z?;=Yn~In0f?uNg?sokf&-T4Va!w5zjEyQ1tddZj-pvqCl+_L|ihWB-G_OCjnj z^zvmZa){t=wC~{CLj#OeaX3mnabJKVsxwCndKu|(r-~gMi87b0BPi^9eGdG}|K$A& zxO@vHt=Uwy-<#I1sJy@Dv1jKeu#y?b`)(e^^8F0WKx!Kke^>sf?WvP#1)@$y)3TSA zi*fZz*`63KK|=1mi&H#opnOZ0X`_#be3v zb#=>UVYE8E2SHPQg-AlG=8A%@8r690PIA4A^Tg_|s>1%tsPqki09_M1lk5>I z-LrK42~2Rx?Cf;#qls^LD+{Yk>{7;E&|uv{Mx;X4KAM&S3(k2+^>B%NE6AETm^@_JKu zhWXcEIpp(D$*t4Q1nQJtp{7PBCr~F+X+I9b-$-aTH02=0f`)E?T(5ZgzE4&tDzs02 z?xGl%wS5cE3aBz3w0t5!;3DS1h#D$)TMa*%c5lzXFks0?9KddCOK@(9!2@oad zyL0~-zU@}zbR)s8T3$r+V(qRX@A@He%WgtZVUXQ+pSzDrfRJADoAYPZuSoI*E2CC; zrpcPW+ z0DlAWdCKXNS2y>;qgeRwin}=w!U7^iEMVnGdfvY-0SmRpZhp2$^c_e4f+?(q*M_ZJ^bbkk(|qhb>h5>`e`mFV%gZofl8`Hv&ywK-k@ zVo6SntfFf`@r{d*?`B2+=aE6qJ+$`Vj)k21TSSB<)zg4B*=Ra2>gPD^?7*vyrc zr+bS=IYLDc#@L}0el9Sv&Q3{s{6lx45C|?lel>933N-q<2GWF+h5rGnWG5LluB?o$ zp%7rFntkP8qIH^3?&mY?Mb5|}2at|BKu1u^vD5)PZGgi7Ep6cJ>tXqVPQg^$N9P?_Z~*0#}Tg`avCHL z?)mS+o-x6^fP4m+-c}Lc4cPhkfE{rAkI5z7`3>!kVf!u+;Y9!FTz5>qoDSQfA|_k` zzK^tBsPd38F((1pg~z+_zdMU89Zg?+y`S88Zw6&3@zN3O*-aIof&}T6s!7do@S@1@ zhuw|mAlvRpLxw%?Y_%%J=T)^yNrIW`_5R(IRMV`d2HpAplyKeRTcz!Ow6Ya*kE~0Wt0e$dEr>)vO_se+mk2x_$KUnt=+!M$K2N9 zq<;R!Wn(W3!I?%zN_@$;Pj)-hz>B-(NYhJT zrcBZ7$*h=ULC1@Zxxt?ADfFjj|p77vK^oYr?a${QCntDa%fcr=73L|DH}Pz_e(UWZ{IHmVNvucp%)kink(m0>ea4KD*G+mUS?t0K1vyf4xZ$% zWW}4zaK;Dw8Xy}axYoCknPYrQqJ|F8p`L4wrsT%n-O0VCljQ|Hrrf|9kOyT}qpUyQ zSb?2mUp1?y+bd;g5cJ?@5mM-IRv6rUU+9!O3DA2M>m3Bjf6j&MW=`Q*63hw#JgEhC zN#e*e5!ie5${QEPrhG;o71w+D)*yxNS-q``7o_GR7aP^R`oCs+HyPLRB&^TvPX)$=CaYbs zxH#C`7OSdzyWifJ&e$}GL$dr1j-i%n^qL|<$yL@}(WO-s;!<&UY1x$xR}8Cdhys+j zhPql#*0_Q_ir()6(PI|lWG5GE8fcjDi19&W_20h&p?S2e<&Kr~w6mW$!Ae85jyyHUX4}5WUkc(E{}?@xdUq0JdvJ^WnpXHU)hE2m<`= z*O~Wd0OJrK;8)qqaJs?)G6CTRRVTnzXTV2uU1%#eZf6uVeOsbs?X-V*s9R|kQu7Zm zciW3Cey}5N772-V0F4$KG@Kr;_Jc@1ARvIY2rv@Ewzq9UAftd2{sfa$$oD!SxW;Ct z();3YdU_h%P;R^(7I0s|VYXTHDAA;I$hyUQCd)_NvWAwqM-y<-ae~_S>&Tfx_UDJ1 z1HE@GMN{s622n-yC${`)yFKFY2Sov!s;&d{TBIHp<;sqzS*x4R>d5dLk zIz4ZjHq~V6L`02?j?r~&*Cx_r?k~SalAgk4JvgI>tv(PIz6MayvMeGTkJCl=o%x?x z@ylwQN2txqM>9QIHv8fED+P zj)CcpcZsS*G28gXZtLg&F79~4-K?P3{_%q|I>;;b=g#PxnJ+PMVli10E#+J{0pXlV zIFtarW6#aAR&jX}a(sI@f--l~aQa(H%TP=3u4XR)%h*2)&(!zLzNy_?yZ*qp(818q zY~<~tkx0G$*1{B}VSMmlF7~-Q!pP5Cz|4Y1+lbl`=8(wae%UQLuz@!^CS}6qeo(%+ zzWe*=98&%M3U}w%X%X(2>(=VVi4fOCRx{oV_u5@$xl@&r?Tu~=EUy~+4ShUMOZ4u2 zR*>Z!kzY1hU=lQxfZF6u#~%(8dEcYfIDM3%+Y4p?AUy~7fsB9<9Mr0BhnlXKkNvgl zbi9afIMxf8rQywf+(GgZT5z7HysTvHyLKH~n3a%sg zmGP(#0mWq3i5%rJ0dIsT+^*#)a{dNy6dALWd&5#c;Oj6b)RfrbW#R3c+g6qg$?_bL zfZzCyY`6x6)SN}ghnKjw`+h8IMH`e!qDfAkF=yUvJ2VK-n!GE^b?UyLO2#&--5w z0BVVOx!bTe4&}KAC82(dOQ0~eN$x!p7qus-z$@@6&#{yRekL&Kmhm%h^>@MoqKf)r zLFGkyI)WAO_3DugVj66SDS`iihE4^EqP3}tami6;6f0wmKl9lcZb)!E1U+up%_oKsHNc0^b9;}1qquRBF)h>ReB6dP=4-XG zq-UqFee@7MuL4?Cr;As0!= zL|v$kYANH1Dh>{un+S1Rbg+~!hTx@ZuoQlo`LN&MpWH@SKTp5YTG1w z=5DOrwu>M$?^$4SRpu)+Wv+CgyQtr1c0C>%s8>CBK=9}Odja0R74M3scGdjvIPFr9 zK9j*y2Zs#xZNdd~=MQw>udX`70}Utqv@);%gX>;=fb7fFo7 zN1%Z0p6tadrg#3GQg{}mI)bO!x<0&KgXV2&3AQ^b=Nk6)u|y>he@Hj36%n0vzF5fZ zKYPq6IrIMWOXc@H@oT*y`EG*BrWp_8+ZD)Wsi_4tGc;nu*~rwPZUm^-+5ytEM1%~v z7Y^Lh>Gjh9O~EBJy zA1|65Q8D~`xbHJ#>}3`~p3v1DxADb+w~oW(hDp1*{~4v8cg@qRQoJDT)(~AJf`)zN z!t0&3H^fE7(73rmWq>dVa{T|AP|s*Sb6&}j3$q)kK_D-QVQ}&;&YIH_tO6=N#BIZSXx=o%Yy(ZeA`>bEhe?y7?TyMkv z|3Han{`r58vaRIHlDG>{y5y{;%M4aXNn96!AOiv+WKwWghyMBl)k72#oX((ivTyLg zC%Vs7Ltn<>zV`oig-v2SxTd}gk5w!ygvTnBDYcrbZ+cv~j4nS`q@KRZRFY?z4;!Gs zG-X}E9ciMOS=dp;>_h^g%-av97Z8|jYx|N)R%mW#M@dRbN^)Vs{F#ORKl${&037(Y z!g)YsI;1M+czb3H0Gy1meXEBqTa%i%l;}V?Q%43L;J?RyV%T$7T*7^6)Db3jt+6p;VmYTKMq2pR!TsQ-);hR5E&et{rVv4p1T=JZy_|P<@yPt=#nV$s85){K22}txG+ht_jnWk-tx!)Cly~0Q1OHFW$ljyQL9J; zlcdP|pu(f|g%{%tLev6)Ob7Jcg4bTtONqd0o0+I4vaOS?DHs(j6hbX1C`i5J2nXq7 z0r&kEI6I(j9KbPlc6PJPl~q->HZ!BZ-~ajZ=hW`>@bE{#QWL$q=E7kCc~A;eP&RKf zbI7yEum(C1bXx#0T@qbDAOgz1F zqY4R$M+iX!*9*;OE#HE&vfcC|f)mEe<4R*^T+&a|tbJP!xcS$8^*!Io*G3f;4@$~@ z$O*bEbcP758}F4)=I@Dy96Nd4GzO53{Gq1F$ck-`jyV_hyMcReu zbq6T*Xg-gFwxh6a%Pq=APqZ2hUMVbZKxbjpfCLX z4lC}8ct@C%K!{9M#!CL7pjimZ#oAC{)sPkx8a^Fm^y37vm~_p&S`@{wt}#A=+$04O z7ChjQ>-vONFX=cc<>n16N4J;i6(X50!XQpA2Ly$n!e6KSeQOvAmw?OW{TJO>PZsyxoqus% z_;OnFY&P!OV7h2}lg>jNKuYSFpKnr57Xgfp>Z+=_>JRGS>%El#2y=Eei|4bQ<%W*u zD~sN6)6;|RE2%=BgP^o(>?2HW@Lm1^#z`39?w{P9?g|(FU%j09Kh)bF$K@t&AxoC5 z5fZ~tLe?6hjO^P8L&`2O)(A0(WQnqKZP%K8$uh_lWuLK(%P?h&Fm@Be_#VFBzv27& z`Fzf2IiJTl=ktEOUe9P{>>s~9-hB&aVR(&Z5Vq)`ryVnrcwgpJU(`cSXWg}8FI6!< zJ7-omIlDHiT4>tX`SCZ+N3(HD%L{#omWKP1^_GuX)L4*ohBjvm1@gY$MC&?`1hL75 znh#!Q5H^nZjyvYblmP|Q_l*IWn+Q2-yV2J6kZI{?tj<7Y(~Asm$`3n49Jc1|MH9q6 zp4~Ucs@Up~cQQNEBh8rp;WU*KI4Xe*o6qz-3~auAz{Fc8z1vmC;t~BDsYn09uAk*hPUBo3 ztyW*@X#ZHvIeTQ{m*|MufTVmsfd|k}h~n|$F&>}9npE#V^M5?cKa9yYHfA<&%~1)l zso$_c0`0YB#=Cm_?S{@;fnSDT_GRJaOfPeZ?0mPv$wx&%&G?0>9ouqoM#Td;aMm{t}Xfj;KSeqF>ayF4EnNaJP3c)At za2;vvx7s`-*xiK%&h%}P5U%g>`f@9A&8C^|qUfb~Clti)a>beeO7`bWqPjVzbv#So z*qXoGqSw!hiw!m?_$2&l6|=V4yyZGUoC))UWELYxv*IRaq=~5T~-189Q;^^_EVFS_E&<)XrZ| z6}1L_QL7oX89W6f-ch1aGiGtwvm(hGu>&LajTW2_8J2^kAw8Z47k6+cg0+`d4YeH@ z)Ij;zs=*E6=;#QC!?m=u;yEb6ZEhA86DJO1Ny%MyiUq3YEpH0&4FEBXlHYDrG8&RF zHS)EjF<{%l+H}mNzWHjsQHeJ|TurN=%WDBno@MnvVPZ+38m_vAmUkE<{5+@p?@Rxs z)tni1vA+WDwr#~eyt!-bZZ~TfBOJGvMN^xYAuew34>4YD6LQF+9%2WOLHAj8gg-Ev`&at=1S~CWq7%TE zc!W8^7ho1Y!@|04#EuCxUEa@s<=#i?Kw-b z^PMPTOPrqZ*uzg(I^N!U{}XAWq-sVU#VuC{#*zANzw9z5-NvEN)t|-a9_kKKmt?D@ z#8vc!_#ukfUX)rR4*fe!OjXFk>Ua{@O(Bu14as@0Ctj@!T#2R*Kk~a~SZTX_Gne_g z@tY?aXWQ)JcJh_QBieI+Ln^GwesHdDZw6qo!`y+6O6&imN7m@&q7@#$b30HL7}U6j zVIKd19mNeDw&|3sQL+3n!X$eUR0FlIuwoi3JR?Xxm~YL$q`Z|C71OFw5dS9uWp3dq z?;7rrL1Lzs=pOql!OW*4v)^*>>;^VcKjC}ODyqJ4WL&zsYBHJrd3iJqPwP-Sv+b6Htg0Ym4< zrav)g`=O>L`q^^;@2PVhc`QwHRpn_c!pa=oLjUn0X>C?i-#>U{p z!9l%?7cWlVMQB|6z9(uY=(pJ31CSFlFUixJtbLt}(4dFBw*&_bLzK3s3-QEoikia(xUJ?<<{@LR;}%GEI4K^|^A{rt953ZB#j+f33{ ze-Pk)&ud&eaMo}4#r`z=0I~Jcn`O(|W4;_twE%Ag9-p3yPcqfXIVLKkZ}~rtGh*>N za6S1UM9Lz+;^&Dbq=-~$8N@PaWu4XOY9kFjMvy$V5NyDH-!c-5^96ZH4fqYXMgHp`j5=n0%m4^dH6nwveuz!Lv>m zR^dc(Aecg-9-U|N^;J&P*HCH)mQVx>(K+Q>S)7ggFYt;9HgIYRN&}%K21i!ZBQqK`o6yvIi=LxFTerw2*KF3+#yjfd7p!oKN2_?|;; z5v^+#RP7@gD&za%j#J8Wu??slev*e`n*7;CYT_uiOuP#XmM|TP#LMoiS>{@8T2~pn zY8C%ZFLtp~<*7Bk%muF|D(lJBv$C>E>q}}eU(ijoiCwq1<~T;i9Q5hNLwkzuvC*@O zZ8_)qF1kwE#K;GVRI!N~U4vZ?8GW1A{4A*X@z3z01cvf31CfOht@dLf^y{^!hLYQg zX0ChpZJC^MEw0quw0rFM=uK(;0|@7FL-M}S=g_|blSZ*##JXkLM9nMjQg5+N(5gw* zp;#=H=qv9#CsAVcF!*qX;`xX$7Mxe*IPUJrum_J2 z{G(JPB$SGqY%>8LukT6C-_4~Bf4_h`o+!~*&1?4RN+sMlO;VxcJ5X_-~xVW@= z$wfL<_{tSqU@NxN+P3aKW{Ioy<^#QPzgCPp+Dm#^{sHJOmw|L0?+7ld3H(qM6&1a% z?N(}O?#mF+P=>|2SKZ1w$R^idmC&?J9s+M6`qKF?fIh|`R8-qQ#Q2QhJV8TSTjyel z{o9UQ_YCQo`JVgu939bs=e0I583pQJnzYaO2hm#!=cV}RLF02VkMPhZ?ubsOQGiSX zx!xro#xFm*be8BpJWYWjgMramO)3-PiAM4TwYCU(Ffqx> z8s=j^`Ty2UZ}j!IO)b;_LmkTW<5NtTdd}d%Qt(G3@k>CLe+g^=@j0*3FF2rel__yi_slQ0mrK6I%1v7{n~g^im#_0-_G(-i;)NDm;) zK-wJ?%F8M%uc0@be+(ynwz2PSVdfR`@l8@>u1QitoW>n2WaEtM75wCguI?_M0#_V- zu>Yp>a@EI1vH-*x8ynl~?5w7+A<_&?Y}@wSVu0re48kCM@@tc6k)+Vjuv%IecJd(a zd1u-Ei&k~W+Tt + + + + + + diff --git a/docs/reference/xml/meson.build b/docs/reference/xml/meson.build new file mode 100644 index 0000000..2c9564f --- /dev/null +++ b/docs/reference/xml/meson.build @@ -0,0 +1,15 @@ +ent_conf = { + 'PACKAGE': gdata_name, + 'PACKAGE_BUGREPORT': 'https://gitlab.gnome.org/GNOME/libgdata/issues', + 'PACKAGE_NAME': gdata_name, + 'PACKAGE_STRING': '@0@ @1@'.format(gdata_name, gdata_version), + 'PACKAGE_TARNAME': gdata_name, + 'PACKAGE_URL': 'https://wiki.gnome.org/Projects/libgdata', + 'PACKAGE_VERSION': gdata_version, +} + +configure_file( + input: 'gtkdocentities.ent.in', + output: '@BASENAME@', + configuration: ent_conf, +) diff --git a/gdata/GData-0.0.metadata b/gdata/GData-0.0.metadata new file mode 100644 index 0000000..9b5009a --- /dev/null +++ b/gdata/GData-0.0.metadata @@ -0,0 +1,12 @@ +Color struct + +Parsable.get_xml#method skip +Parsable.get_json#method skip +Query.get_query_uri#method skip +DOCUMENTS_PRESENTATION_* name="DOCUMENTS_PRESENTATION_(.+)" parent="GData.DocumentsPresentationFormat" +DOCUMENTS_TEXT_* name="DOCUMENTS_TEXT_(.+)" parent="GData.DocumentsTextFormat" +DOCUMENTS_SPREADSHEET_* name="DOCUMENTS_SPREADSHEET_(.+)" parent="GData.DocumentsSpreadsheetFormat" +CONTACTS_GENDER_* name="CONTACTS_GENDER_(.+)" parent="GData.ContactsGender" +CONTACTS_GROUP_* name="CONTACTS_GROUP_(.+)" parent="GData.ContactsGroupType" +CONTACTS_PRIORITY_* name="CONTACTS_PRIORITY_(.+)" parent="GData.ContactsPriority" +CONTACTS_SENSITIVITY_* name="CONTACTS_SENSITIVITY_(.+)" parent="GData.ContactsSensitivity" diff --git a/gdata/app/gdata-app-categories.c b/gdata/app/gdata-app-categories.c new file mode 100644 index 0000000..4a526e3 --- /dev/null +++ b/gdata/app/gdata-app-categories.c @@ -0,0 +1,255 @@ +/* -*- Mode: C; indent-tabs-mode: t; c-basic-offset: 8; tab-width: 8 -*- */ +/* + * GData Client + * Copyright (C) Philip Withnall 2010, 2015 + * + * GData Client is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * GData Client is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with GData Client. If not, see . + */ + +/** + * SECTION:gdata-app-categories + * @short_description: GData APP categories object + * @stability: Stable + * @include: gdata/app/gdata-app-categories.h + * + * #GDataAPPCategories is a list of categories (#GDataCategory) returned as the result of querying an + * Atom Publishing Protocol Category Document. + * + * Since: 0.7.0 + */ + +#include +#include + +#include "gdata-app-categories.h" +#include "atom/gdata-category.h" +#include "gdata-parsable.h" +#include "gdata-parser.h" + +static void gdata_app_categories_dispose (GObject *object); +static void gdata_app_categories_finalize (GObject *object); +static void gdata_app_categories_get_property (GObject *object, guint property_id, GValue *value, GParamSpec *pspec); +static gboolean +parse_json (GDataParsable *parsable, JsonReader *reader, gpointer user_data, + GError **error); +static gboolean +post_parse_json (GDataParsable *parsable, gpointer user_data, GError **error); +static const gchar * +get_content_type (void); + +struct _GDataAPPCategoriesPrivate { + GList *categories; + gchar *scheme; + gboolean fixed; +}; + +enum { + PROP_IS_FIXED = 1 +}; + +G_DEFINE_TYPE (GDataAPPCategories, gdata_app_categories, GDATA_TYPE_PARSABLE) + +static void +gdata_app_categories_class_init (GDataAPPCategoriesClass *klass) +{ + GObjectClass *gobject_class = G_OBJECT_CLASS (klass); + GDataParsableClass *parsable_class = GDATA_PARSABLE_CLASS (klass); + + g_type_class_add_private (klass, sizeof (GDataAPPCategoriesPrivate)); + + gobject_class->get_property = gdata_app_categories_get_property; + gobject_class->dispose = gdata_app_categories_dispose; + gobject_class->finalize = gdata_app_categories_finalize; + + parsable_class->parse_json = parse_json; + parsable_class->post_parse_json = post_parse_json; + parsable_class->get_content_type = get_content_type; + + parsable_class->element_name = "categories"; + parsable_class->element_namespace = "app"; + + /** + * GDataAPPCategories:is-fixed: + * + * Whether entries may use categories not in this category list. + * + * API reference: app:categories + * + * Since: 0.7.0 + */ + g_object_class_install_property (gobject_class, PROP_IS_FIXED, + g_param_spec_boolean ("is-fixed", + "Fixed?", "Whether entries may use categories not in this category list.", + FALSE, + G_PARAM_READABLE | G_PARAM_STATIC_STRINGS)); +} + +static void +gdata_app_categories_init (GDataAPPCategories *self) +{ + self->priv = G_TYPE_INSTANCE_GET_PRIVATE (self, GDATA_TYPE_APP_CATEGORIES, GDataAPPCategoriesPrivate); +} + +static void +gdata_app_categories_dispose (GObject *object) +{ + GDataAPPCategoriesPrivate *priv = GDATA_APP_CATEGORIES (object)->priv; + + g_list_free_full (priv->categories, g_object_unref); + priv->categories = NULL; + + /* Chain up to the parent class */ + G_OBJECT_CLASS (gdata_app_categories_parent_class)->dispose (object); +} + +static void +gdata_app_categories_finalize (GObject *object) +{ + GDataAPPCategoriesPrivate *priv = GDATA_APP_CATEGORIES (object)->priv; + + g_free (priv->scheme); + + /* Chain up to the parent class */ + G_OBJECT_CLASS (gdata_app_categories_parent_class)->finalize (object); +} + +static void +gdata_app_categories_get_property (GObject *object, guint property_id, GValue *value, GParamSpec *pspec) +{ + GDataAPPCategoriesPrivate *priv = GDATA_APP_CATEGORIES (object)->priv; + + switch (property_id) { + case PROP_IS_FIXED: + g_value_set_boolean (value, priv->fixed); + break; + default: + /* We don't have any other property... */ + G_OBJECT_WARN_INVALID_PROPERTY_ID (object, property_id, pspec); + break; + } +} + +/* Reference: https://developers.google.com/youtube/v3/docs/videoCategories/list */ +static gboolean +parse_json (GDataParsable *parsable, JsonReader *reader, gpointer user_data, GError **error) +{ + GDataAPPCategories *self = GDATA_APP_CATEGORIES (parsable); + GDataAPPCategoriesPrivate *priv = self->priv; + GType category_type; + + category_type = (user_data == NULL) ? + GDATA_TYPE_CATEGORY : GPOINTER_TO_SIZE (user_data); + + if (g_strcmp0 (json_reader_get_member_name (reader), "items") == 0) { + guint i, elements; + + /* Loop through the elements array. */ + for (i = 0, elements = (guint) json_reader_count_elements (reader); i < elements; i++) { + GDataCategory *category = NULL; + const gchar *id, *title; + const GError *child_error = NULL; + + json_reader_read_element (reader, i); + + json_reader_read_member (reader, "id"); + id = json_reader_get_string_value (reader); + json_reader_end_member (reader); + + json_reader_read_member (reader, "snippet"); + + json_reader_read_member (reader, "title"); + title = json_reader_get_string_value (reader); + json_reader_end_member (reader); + + child_error = json_reader_get_error (reader); + + if (child_error != NULL) { + return gdata_parser_error_from_json_error (reader, + child_error, + error); + } + + /* Create the category. */ + category = g_object_new (category_type, + "term", id, + "label", title, + NULL); + priv->categories = g_list_prepend (priv->categories, + category); + + json_reader_end_member (reader); /* snippet */ + json_reader_end_element (reader); /* category */ + } + + return TRUE; + } else if (g_strcmp0 (json_reader_get_member_name (reader), "kind") == 0 || + g_strcmp0 (json_reader_get_member_name (reader), "etag") == 0 || + g_strcmp0 (json_reader_get_member_name (reader), "id") == 0) { + /* Ignore. */ + return TRUE; + } else { + return GDATA_PARSABLE_CLASS (gdata_app_categories_parent_class)->parse_json (parsable, reader, user_data, error); + } +} + +static gboolean +post_parse_json (GDataParsable *parsable, gpointer user_data, GError **error) +{ + GDataAPPCategoriesPrivate *priv = GDATA_APP_CATEGORIES (parsable)->priv; + + /* Reverse our lists of stuff. */ + priv->categories = g_list_reverse (priv->categories); + + return TRUE; +} + +static const gchar * +get_content_type (void) +{ + return "application/json"; +} + +/** + * gdata_app_categories_get_categories: + * @self: a #GDataAPPCategories + * + * Returns a list of the categories in this category list. + * + * Return value: (element-type GData.Category) (transfer none): a #GList of #GDataCategorys + * + * Since: 0.7.0 + */ +GList * +gdata_app_categories_get_categories (GDataAPPCategories *self) +{ + g_return_val_if_fail (GDATA_IS_APP_CATEGORIES (self), NULL); + return self->priv->categories; +} + +/** + * gdata_app_categories_is_fixed: + * @self: a #GDataAPPCategories + * + * Returns #GDataAPPCategories:is-fixed. + * + * Return value: whether entries may use categories not in this category list + * + * Since: 0.7.0 + */ +gboolean +gdata_app_categories_is_fixed (GDataAPPCategories *self) +{ + g_return_val_if_fail (GDATA_IS_APP_CATEGORIES (self), FALSE); + return self->priv->fixed; +} diff --git a/gdata/app/gdata-app-categories.h b/gdata/app/gdata-app-categories.h new file mode 100644 index 0000000..cf2f54b --- /dev/null +++ b/gdata/app/gdata-app-categories.h @@ -0,0 +1,77 @@ +/* -*- Mode: C; indent-tabs-mode: t; c-basic-offset: 8; tab-width: 8 -*- */ +/* + * GData Client + * Copyright (C) Philip Withnall 2010 + * + * GData Client is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * GData Client is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with GData Client. If not, see . + */ + +#ifndef GDATA_APP_CATEGORIES_H +#define GDATA_APP_CATEGORIES_H + +#include +#include + +#include + +G_BEGIN_DECLS + +#define GDATA_TYPE_APP_CATEGORIES (gdata_app_categories_get_type ()) +#define GDATA_APP_CATEGORIES(o) (G_TYPE_CHECK_INSTANCE_CAST ((o), GDATA_TYPE_APP_CATEGORIES, GDataAPPCategories)) +#define GDATA_APP_CATEGORIES_CLASS(k) (G_TYPE_CHECK_CLASS_CAST((k), GDATA_TYPE_APP_CATEGORIES, GDataAPPCategoriesClass)) +#define GDATA_IS_APP_CATEGORIES(o) (G_TYPE_CHECK_INSTANCE_TYPE ((o), GDATA_TYPE_APP_CATEGORIES)) +#define GDATA_IS_APP_CATEGORIES_CLASS(k) (G_TYPE_CHECK_CLASS_TYPE ((k), GDATA_TYPE_APP_CATEGORIES)) +#define GDATA_APP_CATEGORIES_GET_CLASS(o) (G_TYPE_INSTANCE_GET_CLASS ((o), GDATA_TYPE_APP_CATEGORIES, GDataAPPCategoriesClass)) + +typedef struct _GDataAPPCategoriesPrivate GDataAPPCategoriesPrivate; + +/** + * GDataAPPCategories: + * + * All the fields in the #GDataAPPCategories structure are private and should never be accessed directly. + * + * Since: 0.7.0 + */ +typedef struct { + /*< private >*/ + GDataParsable parent; + GDataAPPCategoriesPrivate *priv; +} GDataAPPCategories; + +/** + * GDataAPPCategoriesClass: + * + * All the fields in the #GDataAPPCategoriesClass structure are private and should never be accessed directly. + * + * Since: 0.7.0 + */ +typedef struct { + /*< private >*/ + GDataParsableClass parent; + + /*< private >*/ + /* Padding for future expansion */ + void (*_g_reserved0) (void); + void (*_g_reserved1) (void); +} GDataAPPCategoriesClass; + +GType gdata_app_categories_get_type (void) G_GNUC_CONST; +G_DEFINE_AUTOPTR_CLEANUP_FUNC (GDataAPPCategories, g_object_unref) + +GList *gdata_app_categories_get_categories (GDataAPPCategories *self) G_GNUC_PURE; +gboolean gdata_app_categories_is_fixed (GDataAPPCategories *self) G_GNUC_PURE; + +G_END_DECLS + +#endif /* !GDATA_APP_CATEGORIES_H */ diff --git a/gdata/app/meson.build b/gdata/app/meson.build new file mode 100644 index 0000000..e5553c1 --- /dev/null +++ b/gdata/app/meson.build @@ -0,0 +1,10 @@ +headers = files('gdata-app-categories.h') + +install_headers( + headers, + subdir: gdata_include_subdir / 'app', +) + +gir_headers += headers + +sources += files('gdata-app-categories.c') diff --git a/gdata/atom/gdata-author.c b/gdata/atom/gdata-author.c new file mode 100644 index 0000000..09bf03f --- /dev/null +++ b/gdata/atom/gdata-author.c @@ -0,0 +1,377 @@ +/* -*- Mode: C; indent-tabs-mode: t; c-basic-offset: 8; tab-width: 8 -*- */ +/* + * GData Client + * Copyright (C) Philip Withnall 2009–2010 + * + * GData Client is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * GData Client is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with GData Client. If not, see . + */ + +/** + * SECTION:gdata-author + * @short_description: Atom author element + * @stability: Stable + * @include: gdata/atom/gdata-author.h + * + * #GDataAuthor represents a "author" element from the + * Atom specification. + * + * Since: 0.4.0 + */ + +#include +#include + +#include "gdata-author.h" +#include "gdata-parsable.h" +#include "gdata-parser.h" +#include "gdata-comparable.h" + +static void gdata_author_comparable_init (GDataComparableIface *iface); +static void gdata_author_finalize (GObject *object); +static void gdata_author_get_property (GObject *object, guint property_id, GValue *value, GParamSpec *pspec); +static void gdata_author_set_property (GObject *object, guint property_id, const GValue *value, GParamSpec *pspec); +static gboolean parse_xml (GDataParsable *parsable, xmlDoc *doc, xmlNode *node, gpointer user_data, GError **error); +static gboolean post_parse_xml (GDataParsable *parsable, gpointer user_data, GError **error); +static void get_xml (GDataParsable *parsable, GString *xml_string); + +struct _GDataAuthorPrivate { + gchar *name; + gchar *uri; + gchar *email_address; +}; + +enum { + PROP_NAME = 1, + PROP_URI, + PROP_EMAIL_ADDRESS +}; + +G_DEFINE_TYPE_WITH_CODE (GDataAuthor, gdata_author, GDATA_TYPE_PARSABLE, + G_IMPLEMENT_INTERFACE (GDATA_TYPE_COMPARABLE, gdata_author_comparable_init)) + +static void +gdata_author_class_init (GDataAuthorClass *klass) +{ + GObjectClass *gobject_class = G_OBJECT_CLASS (klass); + GDataParsableClass *parsable_class = GDATA_PARSABLE_CLASS (klass); + + g_type_class_add_private (klass, sizeof (GDataAuthorPrivate)); + + gobject_class->set_property = gdata_author_set_property; + gobject_class->get_property = gdata_author_get_property; + gobject_class->finalize = gdata_author_finalize; + + parsable_class->parse_xml = parse_xml; + parsable_class->post_parse_xml = post_parse_xml; + parsable_class->get_xml = get_xml; + parsable_class->element_name = "author"; + + /** + * GDataAuthor:name: + * + * A human-readable name for the person. + * + * For more information, see the + * Atom specification. + * + * Since: 0.4.0 + */ + g_object_class_install_property (gobject_class, PROP_NAME, + g_param_spec_string ("name", + "Name", "A human-readable name for the person.", + NULL, + G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)); + + /** + * GDataAuthor:uri: + * + * An IRI associated with the person. + * + * For more information, see the + * Atom specification. + * + * Since: 0.4.0 + */ + g_object_class_install_property (gobject_class, PROP_URI, + g_param_spec_string ("uri", + "URI", "An IRI associated with the person.", + NULL, + G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)); + + /** + * GDataAuthor:email-address: + * + * An e-mail address associated with the person. + * + * For more information, see the + * Atom specification. + * + * Since: 0.4.0 + */ + g_object_class_install_property (gobject_class, PROP_EMAIL_ADDRESS, + g_param_spec_string ("email-address", + "E-mail address", "An e-mail address associated with the person.", + NULL, + G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)); +} + +static gint +compare_with (GDataComparable *self, GDataComparable *other) +{ + return g_strcmp0 (((GDataAuthor*) self)->priv->name, ((GDataAuthor*) other)->priv->name); +} + +static void +gdata_author_comparable_init (GDataComparableIface *iface) +{ + iface->compare_with = compare_with; +} + +static void +gdata_author_init (GDataAuthor *self) +{ + self->priv = G_TYPE_INSTANCE_GET_PRIVATE (self, GDATA_TYPE_AUTHOR, GDataAuthorPrivate); +} + +static void +gdata_author_finalize (GObject *object) +{ + GDataAuthorPrivate *priv = GDATA_AUTHOR (object)->priv; + + g_free (priv->name); + g_free (priv->uri); + g_free (priv->email_address); + + /* Chain up to the parent class */ + G_OBJECT_CLASS (gdata_author_parent_class)->finalize (object); +} + +static void +gdata_author_get_property (GObject *object, guint property_id, GValue *value, GParamSpec *pspec) +{ + GDataAuthorPrivate *priv = GDATA_AUTHOR (object)->priv; + + switch (property_id) { + case PROP_NAME: + g_value_set_string (value, priv->name); + break; + case PROP_URI: + g_value_set_string (value, priv->uri); + break; + case PROP_EMAIL_ADDRESS: + g_value_set_string (value, priv->email_address); + break; + default: + /* We don't have any other property... */ + G_OBJECT_WARN_INVALID_PROPERTY_ID (object, property_id, pspec); + break; + } +} + +static void +gdata_author_set_property (GObject *object, guint property_id, const GValue *value, GParamSpec *pspec) +{ + GDataAuthor *self = GDATA_AUTHOR (object); + + switch (property_id) { + case PROP_NAME: + gdata_author_set_name (self, g_value_get_string (value)); + break; + case PROP_URI: + gdata_author_set_uri (self, g_value_get_string (value)); + break; + case PROP_EMAIL_ADDRESS: + gdata_author_set_email_address (self, g_value_get_string (value)); + break; + default: + /* We don't have any other property... */ + G_OBJECT_WARN_INVALID_PROPERTY_ID (object, property_id, pspec); + break; + } +} + +static gboolean +parse_xml (GDataParsable *parsable, xmlDoc *doc, xmlNode *node, gpointer user_data, GError **error) +{ + gboolean success; + GDataAuthorPrivate *priv = GDATA_AUTHOR (parsable)->priv; + + if (gdata_parser_is_namespace (node, "http://www.w3.org/2005/Atom") == TRUE && + (gdata_parser_string_from_element (node, "name", P_NO_DUPES | P_REQUIRED | P_NON_EMPTY, &(priv->name), &success, error) == TRUE || + gdata_parser_string_from_element (node, "uri", P_NO_DUPES | P_REQUIRED | P_NON_EMPTY, &(priv->uri), &success, error) == TRUE || + gdata_parser_string_from_element (node, "email", P_NO_DUPES | P_REQUIRED | P_NON_EMPTY, &(priv->email_address), &success, error) == TRUE + )) { + return success; + } else { + return GDATA_PARSABLE_CLASS (gdata_author_parent_class)->parse_xml (parsable, doc, node, user_data, error); + } +} + +static gboolean +post_parse_xml (GDataParsable *parsable, gpointer user_data, GError **error) +{ + GDataAuthorPrivate *priv = GDATA_AUTHOR (parsable)->priv; + + if (priv->name == NULL || *(priv->name) == '\0') + return gdata_parser_error_required_element_missing ("name", "author", error); + + return TRUE; +} + +static void +get_xml (GDataParsable *parsable, GString *xml_string) +{ + GDataAuthorPrivate *priv = GDATA_AUTHOR (parsable)->priv; + + gdata_parser_string_append_escaped (xml_string, "", priv->name, ""); + + if (priv->uri != NULL) + gdata_parser_string_append_escaped (xml_string, "", priv->uri, ""); + + if (priv->email_address != NULL) + gdata_parser_string_append_escaped (xml_string, "", priv->email_address, ""); +} + +/** + * gdata_author_new: + * @name: the author's name + * @uri: (allow-none): an IRI describing the author, or %NULL + * @email_address: (allow-none): the author's e-mail address, or %NULL + * + * Creates a new #GDataAuthor. More information is available in the Atom specification. + * + * @name must be non-%NULL and non-empty. + * + * Return value: a new #GDataAuthor, or %NULL; unref with g_object_unref() + */ +GDataAuthor * +gdata_author_new (const gchar *name, const gchar *uri, const gchar *email_address) +{ + g_return_val_if_fail (name != NULL && *name != '\0', NULL); + return g_object_new (GDATA_TYPE_AUTHOR, "name", name, "uri", uri, "email-address", email_address, NULL); +} + +/** + * gdata_author_get_name: + * @self: a #GDataAuthor + * + * Gets the #GDataAuthor:name property. The name will always be a non-%NULL, non-empty string. + * + * Return value: the author's name + * + * Since: 0.4.0 + */ +const gchar * +gdata_author_get_name (GDataAuthor *self) +{ + g_return_val_if_fail (GDATA_IS_AUTHOR (self), NULL); + return self->priv->name; +} + +/** + * gdata_author_set_name: + * @self: a #GDataAuthor + * @name: the new name for the author + * + * Sets the #GDataAuthor:name property to @name. @name must be non-%NULL and non-empty. + * + * Since: 0.4.0 + */ +void +gdata_author_set_name (GDataAuthor *self, const gchar *name) +{ + g_return_if_fail (GDATA_IS_AUTHOR (self)); + g_return_if_fail (name != NULL && *name != '\0'); + + g_free (self->priv->name); + self->priv->name = g_strdup (name); + g_object_notify (G_OBJECT (self), "name"); +} + +/** + * gdata_author_get_uri: + * @self: a #GDataAuthor + * + * Gets the #GDataAuthor:uri property. If the URI is non-%NULL, it will be non-empty. + * + * Return value: the author's URI, or %NULL + * + * Since: 0.4.0 + */ +const gchar * +gdata_author_get_uri (GDataAuthor *self) +{ + g_return_val_if_fail (GDATA_IS_AUTHOR (self), NULL); + return self->priv->uri; +} + +/** + * gdata_author_set_uri: + * @self: a #GDataAuthor + * @uri: (allow-none): the new URI for the author, or %NULL + * + * Sets the #GDataAuthor:uri property to @uri. @uri must be %NULL or non-empty. + * + * Set @uri to %NULL to unset the property in the author. + * + * Since: 0.4.0 + */ +void +gdata_author_set_uri (GDataAuthor *self, const gchar *uri) +{ + g_return_if_fail (GDATA_IS_AUTHOR (self)); + + g_free (self->priv->uri); + self->priv->uri = g_strdup (uri); + g_object_notify (G_OBJECT (self), "uri"); +} + +/** + * gdata_author_get_email_address: + * @self: a #GDataAuthor + * + * Gets the #GDataAuthor:email-address property. If the e-mail address is non-%NULL, it will be non-empty. + * + * Return value: the author's e-mail address, or %NULL + * + * Since: 0.4.0 + */ +const gchar * +gdata_author_get_email_address (GDataAuthor *self) +{ + g_return_val_if_fail (GDATA_IS_AUTHOR (self), NULL); + return self->priv->email_address; +} + +/** + * gdata_author_set_email_address: + * @self: a #GDataAuthor + * @email_address: (allow-none): the new e-mail address for the author, or %NULL + * + * Sets the #GDataAuthor:email-address property to @email_address. @email_address must be %NULL or non-empty. + * + * Set @email_address to %NULL to unset the property in the author. + * + * Since: 0.4.0 + */ +void +gdata_author_set_email_address (GDataAuthor *self, const gchar *email_address) +{ + g_return_if_fail (GDATA_IS_AUTHOR (self)); + + g_free (self->priv->email_address); + self->priv->email_address = g_strdup (email_address); + g_object_notify (G_OBJECT (self), "email-address"); +} diff --git a/gdata/atom/gdata-author.h b/gdata/atom/gdata-author.h new file mode 100644 index 0000000..7487b4c --- /dev/null +++ b/gdata/atom/gdata-author.h @@ -0,0 +1,81 @@ +/* -*- Mode: C; indent-tabs-mode: t; c-basic-offset: 8; tab-width: 8 -*- */ +/* + * GData Client + * Copyright (C) Philip Withnall 2009 + * + * GData Client is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * GData Client is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with GData Client. If not, see . + */ + +#ifndef GDATA_AUTHOR_H +#define GDATA_AUTHOR_H + +#include +#include + +#include + +G_BEGIN_DECLS + +#define GDATA_TYPE_AUTHOR (gdata_author_get_type ()) +#define GDATA_AUTHOR(o) (G_TYPE_CHECK_INSTANCE_CAST ((o), GDATA_TYPE_AUTHOR, GDataAuthor)) +#define GDATA_AUTHOR_CLASS(k) (G_TYPE_CHECK_CLASS_CAST((k), GDATA_TYPE_AUTHOR, GDataAuthorClass)) +#define GDATA_IS_AUTHOR(o) (G_TYPE_CHECK_INSTANCE_TYPE ((o), GDATA_TYPE_AUTHOR)) +#define GDATA_IS_AUTHOR_CLASS(k) (G_TYPE_CHECK_CLASS_TYPE ((k), GDATA_TYPE_AUTHOR)) +#define GDATA_AUTHOR_GET_CLASS(o) (G_TYPE_INSTANCE_GET_CLASS ((o), GDATA_TYPE_AUTHOR, GDataAuthorClass)) + +typedef struct _GDataAuthorPrivate GDataAuthorPrivate; + +/** + * GDataAuthor: + * + * All the fields in the #GDataAuthor structure are private and should never be accessed directly. + */ +typedef struct { + GDataParsable parent; + GDataAuthorPrivate *priv; +} GDataAuthor; + +/** + * GDataAuthorClass: + * + * All the fields in the #GDataAuthorClass structure are private and should never be accessed directly. + * + * Since: 0.4.0 + */ +typedef struct { + /*< private >*/ + GDataParsableClass parent; + + /*< private >*/ + /* Padding for future expansion */ + void (*_g_reserved0) (void); + void (*_g_reserved1) (void); +} GDataAuthorClass; + +GType gdata_author_get_type (void) G_GNUC_CONST; + +GDataAuthor *gdata_author_new (const gchar *name, const gchar *uri, const gchar *email_address) G_GNUC_WARN_UNUSED_RESULT G_GNUC_MALLOC; + +const gchar *gdata_author_get_name (GDataAuthor *self) G_GNUC_PURE; +void gdata_author_set_name (GDataAuthor *self, const gchar *name); + +const gchar *gdata_author_get_uri (GDataAuthor *self) G_GNUC_PURE; +void gdata_author_set_uri (GDataAuthor *self, const gchar *uri); + +const gchar *gdata_author_get_email_address (GDataAuthor *self) G_GNUC_PURE; +void gdata_author_set_email_address (GDataAuthor *self, const gchar *email_address); + +G_END_DECLS + +#endif /* !GDATA_AUTHOR_H */ diff --git a/gdata/atom/gdata-category.c b/gdata/atom/gdata-category.c new file mode 100644 index 0000000..c02771c --- /dev/null +++ b/gdata/atom/gdata-category.c @@ -0,0 +1,377 @@ +/* -*- Mode: C; indent-tabs-mode: t; c-basic-offset: 8; tab-width: 8 -*- */ +/* + * GData Client + * Copyright (C) Philip Withnall 2009–2010 + * + * GData Client is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * GData Client is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with GData Client. If not, see . + */ + +/** + * SECTION:gdata-category + * @short_description: Atom category element + * @stability: Stable + * @include: gdata/atom/gdata-category.h + * + * #GDataCategory represents a "category" element from the + * Atom specification. + * + * Since: 0.4.0 + */ + +#include +#include + +#include "gdata-category.h" +#include "gdata-parsable.h" +#include "gdata-parser.h" +#include "gdata-comparable.h" + +static void gdata_category_comparable_init (GDataComparableIface *iface); +static void gdata_category_finalize (GObject *object); +static void gdata_category_get_property (GObject *object, guint property_id, GValue *value, GParamSpec *pspec); +static void gdata_category_set_property (GObject *object, guint property_id, const GValue *value, GParamSpec *pspec); +static gboolean pre_parse_xml (GDataParsable *parsable, xmlDoc *doc, xmlNode *root_node, gpointer user_data, GError **error); +static void pre_get_xml (GDataParsable *parsable, GString *xml_string); + +struct _GDataCategoryPrivate { + gchar *term; + gchar *scheme; + gchar *label; +}; + +enum { + PROP_TERM = 1, + PROP_SCHEME, + PROP_LABEL +}; + +G_DEFINE_TYPE_WITH_CODE (GDataCategory, gdata_category, GDATA_TYPE_PARSABLE, + G_IMPLEMENT_INTERFACE (GDATA_TYPE_COMPARABLE, gdata_category_comparable_init)) + +static void +gdata_category_class_init (GDataCategoryClass *klass) +{ + GObjectClass *gobject_class = G_OBJECT_CLASS (klass); + GDataParsableClass *parsable_class = GDATA_PARSABLE_CLASS (klass); + + g_type_class_add_private (klass, sizeof (GDataCategoryPrivate)); + + gobject_class->set_property = gdata_category_set_property; + gobject_class->get_property = gdata_category_get_property; + gobject_class->finalize = gdata_category_finalize; + + parsable_class->pre_parse_xml = pre_parse_xml; + parsable_class->pre_get_xml = pre_get_xml; + parsable_class->element_name = "category"; + + /** + * GDataCategory:term: + * + * Identifies the category to which the entry or feed belongs. + * + * For more information, see the + * + * Atom specification. + * + * Since: 0.4.0 + */ + g_object_class_install_property (gobject_class, PROP_TERM, + g_param_spec_string ("term", + "Term", "Identifies the category to which the entry or feed belongs.", + NULL, + G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)); + + /** + * GDataCategory:scheme: + * + * An IRI that identifies a categorization scheme. + * + * For more information, see the + * + * Atom specification. + * + * Since: 0.4.0 + */ + g_object_class_install_property (gobject_class, PROP_SCHEME, + g_param_spec_string ("scheme", + "Scheme", "An IRI that identifies a categorization scheme.", + NULL, + G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)); + + /** + * GDataCategory:label: + * + * A human-readable label for display in end-user applications. + * + * For more information, see the + * + * Atom specification. + * + * Since: 0.4.0 + */ + g_object_class_install_property (gobject_class, PROP_LABEL, + g_param_spec_string ("label", + "Label", "A human-readable label for display in end-user applications.", + NULL, + G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)); +} + +static gint +compare_with (GDataComparable *self, GDataComparable *other) +{ + return g_strcmp0 (((GDataCategory*) self)->priv->term, ((GDataCategory*) other)->priv->term); +} + +static void +gdata_category_comparable_init (GDataComparableIface *iface) +{ + iface->compare_with = compare_with; +} + +static void +gdata_category_init (GDataCategory *self) +{ + self->priv = G_TYPE_INSTANCE_GET_PRIVATE (self, GDATA_TYPE_CATEGORY, GDataCategoryPrivate); +} + +static void +gdata_category_finalize (GObject *object) +{ + GDataCategoryPrivate *priv = GDATA_CATEGORY (object)->priv; + + g_free (priv->term); + g_free (priv->scheme); + g_free (priv->label); + + /* Chain up to the parent class */ + G_OBJECT_CLASS (gdata_category_parent_class)->finalize (object); +} + +static void +gdata_category_get_property (GObject *object, guint property_id, GValue *value, GParamSpec *pspec) +{ + GDataCategoryPrivate *priv = GDATA_CATEGORY (object)->priv; + + switch (property_id) { + case PROP_TERM: + g_value_set_string (value, priv->term); + break; + case PROP_SCHEME: + g_value_set_string (value, priv->scheme); + break; + case PROP_LABEL: + g_value_set_string (value, priv->label); + break; + default: + /* We don't have any other property... */ + G_OBJECT_WARN_INVALID_PROPERTY_ID (object, property_id, pspec); + break; + } +} + +static void +gdata_category_set_property (GObject *object, guint property_id, const GValue *value, GParamSpec *pspec) +{ + GDataCategory *self = GDATA_CATEGORY (object); + + switch (property_id) { + case PROP_TERM: + gdata_category_set_term (self, g_value_get_string (value)); + break; + case PROP_SCHEME: + gdata_category_set_scheme (self, g_value_get_string (value)); + break; + case PROP_LABEL: + gdata_category_set_label (self, g_value_get_string (value)); + break; + default: + /* We don't have any other property... */ + G_OBJECT_WARN_INVALID_PROPERTY_ID (object, property_id, pspec); + break; + } +} + +static gboolean +pre_parse_xml (GDataParsable *parsable, xmlDoc *doc, xmlNode *root_node, gpointer user_data, GError **error) +{ + xmlChar *term, *scheme; + GDataCategory *self = GDATA_CATEGORY (parsable); + + term = xmlGetProp (root_node, (xmlChar*) "term"); + if (term == NULL || *term == '\0') { + xmlFree (term); + return gdata_parser_error_required_property_missing (root_node, "term", error); + } + + scheme = xmlGetProp (root_node, (xmlChar*) "scheme"); + if (scheme != NULL && *scheme == '\0') { + xmlFree (term); + xmlFree (scheme); + return gdata_parser_error_required_property_missing (root_node, "scheme", error); + } + + self->priv->term = (gchar*) term; + self->priv->scheme = (gchar*) scheme; + self->priv->label = (gchar*) xmlGetProp (root_node, (xmlChar*) "label"); + + return TRUE; +} + +static void +pre_get_xml (GDataParsable *parsable, GString *xml_string) +{ + GDataCategoryPrivate *priv = GDATA_CATEGORY (parsable)->priv; + + gdata_parser_string_append_escaped (xml_string, " term='", priv->term, "'"); + + if (priv->scheme != NULL) + gdata_parser_string_append_escaped (xml_string, " scheme='", priv->scheme, "'"); + + if (priv->label != NULL) + gdata_parser_string_append_escaped (xml_string, " label='", priv->label, "'"); +} + +/** + * gdata_category_new: + * @term: a category identifier + * @scheme: (allow-none): an IRI to define the categorisation scheme, or %NULL + * @label: (allow-none): a human-readable label for the category, or %NULL + * + * Creates a new #GDataCategory. More information is available in the Atom specification. + * + * @term must be non-%NULL and non-empty. @scheme must be %NULL or non-empty. + * + * Return value: a new #GDataCategory, or %NULL; unref with g_object_unref() + */ +GDataCategory * +gdata_category_new (const gchar *term, const gchar *scheme, const gchar *label) +{ + g_return_val_if_fail (term != NULL && *term != '\0', NULL); + g_return_val_if_fail (scheme == NULL || *scheme != '\0', NULL); + return g_object_new (GDATA_TYPE_CATEGORY, "term", term, "scheme", scheme, "label", label, NULL); +} + +/** + * gdata_category_get_term: + * @self: a #GDataCategory + * + * Gets the #GDataCategory:term property. The term will always be a non-%NULL, non-empty string. + * + * Return value: the category's term + * + * Since: 0.4.0 + */ +const gchar * +gdata_category_get_term (GDataCategory *self) +{ + g_return_val_if_fail (GDATA_IS_CATEGORY (self), NULL); + return self->priv->term; +} + +/** + * gdata_category_set_term: + * @self: a #GDataCategory + * @term: the new term for the category + * + * Sets the #GDataCategory:term property to @term. @term must be non-%NULL and non-empty. + * + * Since: 0.4.0 + */ +void +gdata_category_set_term (GDataCategory *self, const gchar *term) +{ + g_return_if_fail (GDATA_IS_CATEGORY (self)); + g_return_if_fail (term != NULL && *term != '\0'); + + g_free (self->priv->term); + self->priv->term = g_strdup (term); + g_object_notify (G_OBJECT (self), "term"); +} + +/** + * gdata_category_get_scheme: + * @self: a #GDataCategory + * + * Gets the #GDataCategory:scheme property. If the scheme is non-%NULL, it will be non-empty. + * + * Return value: the category's scheme, or %NULL + * + * Since: 0.4.0 + */ +const gchar * +gdata_category_get_scheme (GDataCategory *self) +{ + g_return_val_if_fail (GDATA_IS_CATEGORY (self), NULL); + return self->priv->scheme; +} + +/** + * gdata_category_set_scheme: + * @self: a #GDataCategory + * @scheme: (allow-none): the new scheme for the category, or %NULL + * + * Sets the #GDataCategory:scheme property to @scheme. @scheme must be %NULL or non-empty. + * + * Set @scheme to %NULL to unset the property in the category. + * + * Since: 0.4.0 + */ +void +gdata_category_set_scheme (GDataCategory *self, const gchar *scheme) +{ + g_return_if_fail (GDATA_IS_CATEGORY (self)); + + g_free (self->priv->scheme); + self->priv->scheme = g_strdup (scheme); + g_object_notify (G_OBJECT (self), "scheme"); +} + +/** + * gdata_category_get_label: + * @self: a #GDataCategory + * + * Gets the #GDataCategory:label property. + * + * Return value: the category's label, or %NULL + * + * Since: 0.4.0 + */ +const gchar * +gdata_category_get_label (GDataCategory *self) +{ + g_return_val_if_fail (GDATA_IS_CATEGORY (self), NULL); + return self->priv->label; +} + +/** + * gdata_category_set_label: + * @self: a #GDataCategory + * @label: (allow-none): the new label for the category, or %NULL + * + * Sets the #GDataCategory:label property to @label. + * + * Set @label to %NULL to unset the property in the category. + * + * Since: 0.4.0 + */ +void +gdata_category_set_label (GDataCategory *self, const gchar *label) +{ + g_return_if_fail (GDATA_IS_CATEGORY (self)); + + g_free (self->priv->label); + self->priv->label = g_strdup (label); + g_object_notify (G_OBJECT (self), "label"); +} diff --git a/gdata/atom/gdata-category.h b/gdata/atom/gdata-category.h new file mode 100644 index 0000000..20f7cac --- /dev/null +++ b/gdata/atom/gdata-category.h @@ -0,0 +1,121 @@ +/* -*- Mode: C; indent-tabs-mode: t; c-basic-offset: 8; tab-width: 8 -*- */ +/* + * GData Client + * Copyright (C) Philip Withnall 2009 + * + * GData Client is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * GData Client is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with GData Client. If not, see . + */ + +#ifndef GDATA_CATEGORY_H +#define GDATA_CATEGORY_H + +#include +#include + +#include + +G_BEGIN_DECLS + +/** + * GDATA_CATEGORY_SCHEMA_LABELS: + * + * A schema for categories which label the entry they're applied to in some way, such as starring it. The semantics of the various labels + * (such as %GDATA_CATEGORY_SCHEMA_LABELS_STARRED) are service-specific. + * + * Since: 0.11.0 + */ +#define GDATA_CATEGORY_SCHEMA_LABELS "http://schemas.google.com/g/2005/labels" + +/** + * GDATA_CATEGORY_SCHEMA_LABELS_SHARED: + * + * A term for categories of the %GDATA_CATEGORY_SCHEMA_LABELS schema which labels an entry as being “shared”. The semantics of this label are + * service-specific, but are obvious for services such as Google Documents. + * + * Since: 0.17.0 + */ +#define GDATA_CATEGORY_SCHEMA_LABELS_SHARED GDATA_CATEGORY_SCHEMA_LABELS"#shared" + +/** + * GDATA_CATEGORY_SCHEMA_LABELS_STARRED: + * + * A term for categories of the %GDATA_CATEGORY_SCHEMA_LABELS schema which labels an entry as being “starred”. The semantics of this label are + * service-specific, but are obvious for services such as Google Documents. + * + * Since: 0.11.0 + */ +#define GDATA_CATEGORY_SCHEMA_LABELS_STARRED GDATA_CATEGORY_SCHEMA_LABELS"#starred" + +/** + * GDATA_CATEGORY_SCHEMA_LABELS_VIEWED: + * + * A term for categories of the %GDATA_CATEGORY_SCHEMA_LABELS schema which labels an entry as being “viewed”. The semantics of this label are + * service-specific, but are obvious for services such as Google Documents. + * + * Since: 0.17.0 + */ +#define GDATA_CATEGORY_SCHEMA_LABELS_VIEWED GDATA_CATEGORY_SCHEMA_LABELS"#viewed" + +#define GDATA_TYPE_CATEGORY (gdata_category_get_type ()) +#define GDATA_CATEGORY(o) (G_TYPE_CHECK_INSTANCE_CAST ((o), GDATA_TYPE_CATEGORY, GDataCategory)) +#define GDATA_CATEGORY_CLASS(k) (G_TYPE_CHECK_CLASS_CAST((k), GDATA_TYPE_CATEGORY, GDataCategoryClass)) +#define GDATA_IS_CATEGORY(o) (G_TYPE_CHECK_INSTANCE_TYPE ((o), GDATA_TYPE_CATEGORY)) +#define GDATA_IS_CATEGORY_CLASS(k) (G_TYPE_CHECK_CLASS_TYPE ((k), GDATA_TYPE_CATEGORY)) +#define GDATA_CATEGORY_GET_CLASS(o) (G_TYPE_INSTANCE_GET_CLASS ((o), GDATA_TYPE_CATEGORY, GDataCategoryClass)) + +typedef struct _GDataCategoryPrivate GDataCategoryPrivate; + +/** + * GDataCategory: + * + * All the fields in the #GDataCategory structure are private and should never be accessed directly. + */ +typedef struct { + GDataParsable parent; + GDataCategoryPrivate *priv; +} GDataCategory; + +/** + * GDataCategoryClass: + * + * All the fields in the #GDataCategoryClass structure are private and should never be accessed directly. + * + * Since: 0.4.0 + */ +typedef struct { + /*< private >*/ + GDataParsableClass parent; + + /*< private >*/ + /* Padding for future expansion */ + void (*_g_reserved0) (void); + void (*_g_reserved1) (void); +} GDataCategoryClass; + +GType gdata_category_get_type (void) G_GNUC_CONST; + +GDataCategory *gdata_category_new (const gchar *term, const gchar *scheme, const gchar *label) G_GNUC_WARN_UNUSED_RESULT G_GNUC_MALLOC; + +const gchar *gdata_category_get_term (GDataCategory *self) G_GNUC_PURE; +void gdata_category_set_term (GDataCategory *self, const gchar *term); + +const gchar *gdata_category_get_scheme (GDataCategory *self) G_GNUC_PURE; +void gdata_category_set_scheme (GDataCategory *self, const gchar *scheme); + +const gchar *gdata_category_get_label (GDataCategory *self) G_GNUC_PURE; +void gdata_category_set_label (GDataCategory *self, const gchar *label); + +G_END_DECLS + +#endif /* !GDATA_CATEGORY_H */ diff --git a/gdata/atom/gdata-generator.c b/gdata/atom/gdata-generator.c new file mode 100644 index 0000000..69a17d2 --- /dev/null +++ b/gdata/atom/gdata-generator.c @@ -0,0 +1,264 @@ +/* -*- Mode: C; indent-tabs-mode: t; c-basic-offset: 8; tab-width: 8 -*- */ +/* + * GData Client + * Copyright (C) Philip Withnall 2009–2010 + * + * GData Client is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * GData Client is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with GData Client. If not, see . + */ + +/** + * SECTION:gdata-generator + * @short_description: Atom generator element + * @stability: Stable + * @include: gdata/atom/gdata-generator.h + * + * #GDataGenerator represents a "generator" element from the + * Atom specification. + */ + +#include +#include + +#include "gdata-generator.h" +#include "gdata-parsable.h" +#include "gdata-parser.h" +#include "gdata-comparable.h" + +static void gdata_generator_comparable_init (GDataComparableIface *iface); +static void gdata_generator_finalize (GObject *object); +static void gdata_generator_get_property (GObject *object, guint property_id, GValue *value, GParamSpec *pspec); +static gboolean pre_parse_xml (GDataParsable *parsable, xmlDoc *doc, xmlNode *root_node, gpointer user_data, GError **error); +static gboolean parse_xml (GDataParsable *parsable, xmlDoc *doc, xmlNode *root_node, gpointer user_data, GError **error); + +struct _GDataGeneratorPrivate { + gchar *name; + gchar *uri; + gchar *version; +}; + +enum { + PROP_NAME = 1, + PROP_URI, + PROP_VERSION +}; + +G_DEFINE_TYPE_WITH_CODE (GDataGenerator, gdata_generator, GDATA_TYPE_PARSABLE, + G_IMPLEMENT_INTERFACE (GDATA_TYPE_COMPARABLE, gdata_generator_comparable_init)) + +static void +gdata_generator_class_init (GDataGeneratorClass *klass) +{ + GObjectClass *gobject_class = G_OBJECT_CLASS (klass); + GDataParsableClass *parsable_class = GDATA_PARSABLE_CLASS (klass); + + g_type_class_add_private (klass, sizeof (GDataGeneratorPrivate)); + + gobject_class->get_property = gdata_generator_get_property; + gobject_class->finalize = gdata_generator_finalize; + + parsable_class->pre_parse_xml = pre_parse_xml; + parsable_class->parse_xml = parse_xml; + parsable_class->element_name = "generator"; + + /** + * GDataGenerator:name: + * + * A human-readable name for the generating agent. + * + * For more information, see the + * + * Atom specification. + * + * Since: 0.4.0 + */ + g_object_class_install_property (gobject_class, PROP_NAME, + g_param_spec_string ("name", + "Name", "A human-readable name for the generating agent.", + NULL, + G_PARAM_READABLE | G_PARAM_STATIC_STRINGS)); + + /** + * GDataGenerator:uri: + * + * An IRI reference that is relevant to the agent. + * + * For more information, see the + * + * Atom specification. + * + * Since: 0.4.0 + */ + g_object_class_install_property (gobject_class, PROP_URI, + g_param_spec_string ("uri", + "URI", "An IRI reference that is relevant to the agent.", + NULL, + G_PARAM_READABLE | G_PARAM_STATIC_STRINGS)); + + /** + * GDataGenerator:version: + * + * Indicates the version of the generating agent. + * + * For more information, see the + * + * Atom specification. + * + * Since: 0.4.0 + */ + g_object_class_install_property (gobject_class, PROP_VERSION, + g_param_spec_string ("version", + "Version", "Indicates the version of the generating agent.", + NULL, + G_PARAM_READABLE | G_PARAM_STATIC_STRINGS)); +} + +static gint +compare_with (GDataComparable *self, GDataComparable *other) +{ + return g_strcmp0 (((GDataGenerator*) self)->priv->name, ((GDataGenerator*) other)->priv->name); +} + +static void +gdata_generator_comparable_init (GDataComparableIface *iface) +{ + iface->compare_with = compare_with; +} + +static void +gdata_generator_init (GDataGenerator *self) +{ + self->priv = G_TYPE_INSTANCE_GET_PRIVATE (self, GDATA_TYPE_GENERATOR, GDataGeneratorPrivate); +} + +static void +gdata_generator_finalize (GObject *object) +{ + GDataGeneratorPrivate *priv = GDATA_GENERATOR (object)->priv; + + g_free (priv->name); + g_free (priv->uri); + g_free (priv->version); + + /* Chain up to the parent class */ + G_OBJECT_CLASS (gdata_generator_parent_class)->finalize (object); +} + +static void +gdata_generator_get_property (GObject *object, guint property_id, GValue *value, GParamSpec *pspec) +{ + GDataGeneratorPrivate *priv = GDATA_GENERATOR (object)->priv; + + switch (property_id) { + case PROP_NAME: + g_value_set_string (value, priv->name); + break; + case PROP_URI: + g_value_set_string (value, priv->uri); + break; + case PROP_VERSION: + g_value_set_string (value, priv->version); + break; + default: + /* We don't have any other property... */ + G_OBJECT_WARN_INVALID_PROPERTY_ID (object, property_id, pspec); + break; + } +} + +static gboolean +pre_parse_xml (GDataParsable *parsable, xmlDoc *doc, xmlNode *root_node, gpointer user_data, GError **error) +{ + xmlChar *uri, *name; + GDataGeneratorPrivate *priv = GDATA_GENERATOR (parsable)->priv; + + uri = xmlGetProp (root_node, (xmlChar*) "uri"); + if (uri != NULL && *uri == '\0') { + xmlFree (uri); + return gdata_parser_error_required_property_missing (root_node, "uri", error); + } + + name = xmlNodeListGetString (doc, root_node->children, TRUE); + if (name != NULL && *name == '\0') { + xmlFree (uri); + xmlFree (name); + return gdata_parser_error_required_content_missing (root_node, error); + } + + priv->uri = (gchar*) uri; + priv->name = (gchar*) name; + priv->version = (gchar*) xmlGetProp (root_node, (xmlChar*) "version"); + + return TRUE; +} + +static gboolean +parse_xml (GDataParsable *parsable, xmlDoc *doc, xmlNode *node, gpointer user_data, GError **error) +{ + /* Textual content's handled in pre_parse_xml */ + if (node->type != XML_ELEMENT_NODE) + return TRUE; + + return GDATA_PARSABLE_CLASS (gdata_generator_parent_class)->parse_xml (parsable, doc, node, user_data, error); +} + +/** + * gdata_generator_get_name: + * @self: a #GDataGenerator + * + * Gets the #GDataGenerator:name property. The name will be %NULL or non-empty. + * + * Return value: (nullable): the generator's name + * + * Since: 0.4.0 + */ +const gchar * +gdata_generator_get_name (GDataGenerator *self) +{ + g_return_val_if_fail (GDATA_IS_GENERATOR (self), NULL); + return self->priv->name; +} + +/** + * gdata_generator_get_uri: + * @self: a #GDataGenerator + * + * Gets the #GDataGenerator:uri property. The URI will be %NULL or non-empty. + * + * Return value: (nullable): the generator's URI, or %NULL + * + * Since: 0.4.0 + */ +const gchar * +gdata_generator_get_uri (GDataGenerator *self) +{ + g_return_val_if_fail (GDATA_IS_GENERATOR (self), NULL); + return self->priv->uri; +} + +/** + * gdata_generator_get_version: + * @self: a #GDataGenerator + * + * Gets the #GDataGenerator:version property. + * + * Return value: the generator's version, or %NULL + * + * Since: 0.4.0 + */ +const gchar * +gdata_generator_get_version (GDataGenerator *self) +{ + g_return_val_if_fail (GDATA_IS_GENERATOR (self), NULL); + return self->priv->version; +} diff --git a/gdata/atom/gdata-generator.h b/gdata/atom/gdata-generator.h new file mode 100644 index 0000000..d4d81d6 --- /dev/null +++ b/gdata/atom/gdata-generator.h @@ -0,0 +1,74 @@ +/* -*- Mode: C; indent-tabs-mode: t; c-basic-offset: 8; tab-width: 8 -*- */ +/* + * GData Client + * Copyright (C) Philip Withnall 2009 + * + * GData Client is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * GData Client is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with GData Client. If not, see . + */ + +#ifndef GDATA_GENERATOR_H +#define GDATA_GENERATOR_H + +#include +#include + +#include + +G_BEGIN_DECLS + +#define GDATA_TYPE_GENERATOR (gdata_generator_get_type ()) +#define GDATA_GENERATOR(o) (G_TYPE_CHECK_INSTANCE_CAST ((o), GDATA_TYPE_GENERATOR, GDataGenerator)) +#define GDATA_GENERATOR_CLASS(k) (G_TYPE_CHECK_CLASS_CAST((k), GDATA_TYPE_GENERATOR, GDataGeneratorClass)) +#define GDATA_IS_GENERATOR(o) (G_TYPE_CHECK_INSTANCE_TYPE ((o), GDATA_TYPE_GENERATOR)) +#define GDATA_IS_GENERATOR_CLASS(k) (G_TYPE_CHECK_CLASS_TYPE ((k), GDATA_TYPE_GENERATOR)) +#define GDATA_GENERATOR_GET_CLASS(o) (G_TYPE_INSTANCE_GET_CLASS ((o), GDATA_TYPE_GENERATOR, GDataGeneratorClass)) + +typedef struct _GDataGeneratorPrivate GDataGeneratorPrivate; + +/** + * GDataGenerator: + * + * All the fields in the #GDataGenerator structure are private and should never be accessed directly. + */ +typedef struct { + GDataParsable parent; + GDataGeneratorPrivate *priv; +} GDataGenerator; + +/** + * GDataGeneratorClass: + * + * All the fields in the #GDataGeneratorClass structure are private and should never be accessed directly. + * + * Since: 0.4.0 + */ +typedef struct { + /*< private >*/ + GDataParsableClass parent; + + /*< private >*/ + /* Padding for future expansion */ + void (*_g_reserved0) (void); + void (*_g_reserved1) (void); +} GDataGeneratorClass; + +GType gdata_generator_get_type (void) G_GNUC_CONST; + +const gchar *gdata_generator_get_name (GDataGenerator *self) G_GNUC_PURE; +const gchar *gdata_generator_get_uri (GDataGenerator *self) G_GNUC_PURE; +const gchar *gdata_generator_get_version (GDataGenerator *self) G_GNUC_PURE; + +G_END_DECLS + +#endif /* !GDATA_GENERATOR_H */ diff --git a/gdata/atom/gdata-link.c b/gdata/atom/gdata-link.c new file mode 100644 index 0000000..f975481 --- /dev/null +++ b/gdata/atom/gdata-link.c @@ -0,0 +1,625 @@ +/* -*- Mode: C; indent-tabs-mode: t; c-basic-offset: 8; tab-width: 8 -*- */ +/* + * GData Client + * Copyright (C) Philip Withnall 2009–2010 + * + * GData Client is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * GData Client is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with GData Client. If not, see . + */ + +/** + * SECTION:gdata-link + * @short_description: Atom link element + * @stability: Stable + * @include: gdata/atom/gdata-link.h + * + * #GDataLink represents a "link" element from the + * Atom specification. + * + * Since: 0.4.0 + */ + +#include +#include +#include + +#include "gdata-link.h" +#include "gdata-parsable.h" +#include "gdata-parser.h" +#include "gdata-comparable.h" + +static void gdata_link_comparable_init (GDataComparableIface *iface); +static void gdata_link_finalize (GObject *object); +static void gdata_link_get_property (GObject *object, guint property_id, GValue *value, GParamSpec *pspec); +static void gdata_link_set_property (GObject *object, guint property_id, const GValue *value, GParamSpec *pspec); +static gboolean pre_parse_xml (GDataParsable *parsable, xmlDoc *doc, xmlNode *root_node, gpointer user_data, GError **error); +static void pre_get_xml (GDataParsable *parsable, GString *xml_string); + +struct _GDataLinkPrivate { + gchar *uri; + gchar *relation_type; + gchar *content_type; + gchar *language; + gchar *title; + gint length; +}; + +enum { + PROP_URI = 1, + PROP_RELATION_TYPE, + PROP_CONTENT_TYPE, + PROP_LANGUAGE, + PROP_TITLE, + PROP_LENGTH +}; + +G_DEFINE_TYPE_WITH_CODE (GDataLink, gdata_link, GDATA_TYPE_PARSABLE, + G_IMPLEMENT_INTERFACE (GDATA_TYPE_COMPARABLE, gdata_link_comparable_init)) + +static void +gdata_link_class_init (GDataLinkClass *klass) +{ + GObjectClass *gobject_class = G_OBJECT_CLASS (klass); + GDataParsableClass *parsable_class = GDATA_PARSABLE_CLASS (klass); + + g_type_class_add_private (klass, sizeof (GDataLinkPrivate)); + + gobject_class->set_property = gdata_link_set_property; + gobject_class->get_property = gdata_link_get_property; + gobject_class->finalize = gdata_link_finalize; + + parsable_class->pre_parse_xml = pre_parse_xml; + parsable_class->pre_get_xml = pre_get_xml; + parsable_class->element_name = "link"; + + /** + * GDataLink:uri: + * + * The link's IRI. + * + * For more information, see the + * Atom specification. + * + * Since: 0.4.0 + */ + g_object_class_install_property (gobject_class, PROP_URI, + g_param_spec_string ("uri", + "URI", "The link's IRI.", + NULL, + G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)); + + /** + * GDataLink:relation-type: + * + * The link relation type. + * + * For more information, see the + * Atom specification. + * + * Since: 0.4.0 + */ + g_object_class_install_property (gobject_class, PROP_RELATION_TYPE, + g_param_spec_string ("relation-type", + "Relation type", "The link relation type.", + GDATA_LINK_ALTERNATE, + G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)); + + /** + * GDataLink:content-type: + * + * An advisory media type: it is a hint about the type of the representation that is expected to be returned when the value + * of the #GDataLink:uri property is dereferenced. + * + * For more information, see the + * Atom specification. + * + * Since: 0.4.0 + */ + g_object_class_install_property (gobject_class, PROP_CONTENT_TYPE, + g_param_spec_string ("content-type", + "Content type", "An advisory media type.", + NULL, + G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)); + + /** + * GDataLink:language: + * + * Describes the language of the resource pointed to by the #GDataLink:uri property. + * + * For more information, see the + * Atom specification. + * + * Since: 0.4.0 + */ + g_object_class_install_property (gobject_class, PROP_LANGUAGE, + g_param_spec_string ("language", + "Language", "Describes the language of the resource pointed to by the uri property.", + NULL, + G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)); + + /** + * GDataLink:title: + * + * Conveys human-readable information about the link. + * + * For more information, see the + * Atom specification. + * + * Since: 0.4.0 + */ + g_object_class_install_property (gobject_class, PROP_TITLE, + g_param_spec_string ("title", + "Title", "Conveys human-readable information about the link.", + NULL, + G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)); + + /** + * GDataLink:length: + * + * Indicates an advisory length of the linked content in octets. -1 means the length is unspecified. + * + * For more information, see the + * Atom specification. + * + * Since: 0.4.0 + */ + g_object_class_install_property (gobject_class, PROP_LENGTH, + g_param_spec_int ("length", + "Length", "Indicates an advisory length of the linked content in octets.", + -1, G_MAXINT, -1, + G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)); +} + +static gint +compare_with (GDataComparable *self, GDataComparable *other) +{ + GDataLinkPrivate *a = ((GDataLink*) self)->priv, *b = ((GDataLink*) other)->priv; + + if (g_strcmp0 (a->uri, b->uri) == 0 && g_strcmp0 (a->relation_type, b->relation_type) == 0) + return 0; + return 1; +} + +static void +gdata_link_comparable_init (GDataComparableIface *iface) +{ + iface->compare_with = compare_with; +} + +static void +gdata_link_init (GDataLink *self) +{ + self->priv = G_TYPE_INSTANCE_GET_PRIVATE (self, GDATA_TYPE_LINK, GDataLinkPrivate); + self->priv->length = -1; + self->priv->relation_type = g_strdup (GDATA_LINK_ALTERNATE); +} + +static void +gdata_link_finalize (GObject *object) +{ + GDataLinkPrivate *priv = GDATA_LINK (object)->priv; + + g_free (priv->uri); + g_free (priv->relation_type); + g_free (priv->content_type); + g_free (priv->language); + g_free (priv->title); + + /* Chain up to the parent class */ + G_OBJECT_CLASS (gdata_link_parent_class)->finalize (object); +} + +static void +gdata_link_get_property (GObject *object, guint property_id, GValue *value, GParamSpec *pspec) +{ + GDataLinkPrivate *priv = GDATA_LINK (object)->priv; + + switch (property_id) { + case PROP_URI: + g_value_set_string (value, priv->uri); + break; + case PROP_RELATION_TYPE: + g_value_set_string (value, priv->relation_type); + break; + case PROP_CONTENT_TYPE: + g_value_set_string (value, priv->content_type); + break; + case PROP_LANGUAGE: + g_value_set_string (value, priv->language); + break; + case PROP_TITLE: + g_value_set_string (value, priv->title); + break; + case PROP_LENGTH: + g_value_set_int (value, priv->length); + break; + default: + /* We don't have any other property... */ + G_OBJECT_WARN_INVALID_PROPERTY_ID (object, property_id, pspec); + break; + } +} + +static void +gdata_link_set_property (GObject *object, guint property_id, const GValue *value, GParamSpec *pspec) +{ + GDataLink *self = GDATA_LINK (object); + + switch (property_id) { + case PROP_URI: + gdata_link_set_uri (self, g_value_get_string (value)); + break; + case PROP_RELATION_TYPE: + gdata_link_set_relation_type (self, g_value_get_string (value)); + break; + case PROP_CONTENT_TYPE: + gdata_link_set_content_type (self, g_value_get_string (value)); + break; + case PROP_LANGUAGE: + gdata_link_set_language (self, g_value_get_string (value)); + break; + case PROP_TITLE: + gdata_link_set_title (self, g_value_get_string (value)); + break; + case PROP_LENGTH: + gdata_link_set_length (self, g_value_get_int (value)); + break; + default: + /* We don't have any other property... */ + G_OBJECT_WARN_INVALID_PROPERTY_ID (object, property_id, pspec); + break; + } +} + +static gboolean +pre_parse_xml (GDataParsable *parsable, xmlDoc *doc, xmlNode *root_node, gpointer user_data, GError **error) +{ + xmlChar *uri, *relation_type, *content_type, *language, *length; + GDataLink *self = GDATA_LINK (parsable); + + /* href */ + uri = xmlGetProp (root_node, (xmlChar*) "href"); + if (uri == NULL || *uri == '\0') { + xmlFree (uri); + return gdata_parser_error_required_property_missing (root_node, "href", error); + } + + /* rel */ + relation_type = xmlGetProp (root_node, (xmlChar*) "rel"); + if (relation_type != NULL && *relation_type == '\0') { + xmlFree (uri); + xmlFree (relation_type); + return gdata_parser_error_required_property_missing (root_node, "rel", error); + } + + /* type */ + content_type = xmlGetProp (root_node, (xmlChar*) "type"); + if (content_type != NULL && *content_type == '\0') { + xmlFree (uri); + xmlFree (relation_type); + xmlFree (content_type); + return gdata_parser_error_required_property_missing (root_node, "type", error); + } + + /* hreflang */ + language = xmlGetProp (root_node, (xmlChar*) "hreflang"); + if (language != NULL && *language == '\0') { + xmlFree (uri); + xmlFree (relation_type); + xmlFree (content_type); + xmlFree (language); + return gdata_parser_error_required_property_missing (root_node, "hreflang", error); + } + + self->priv->uri = (gchar*) uri; + gdata_link_set_relation_type (self, (const gchar*) relation_type); + xmlFree (relation_type); + self->priv->content_type = (gchar*) content_type; + self->priv->language = (gchar*) language; + self->priv->title = (gchar*) xmlGetProp (root_node, (xmlChar*) "title"); + + length = xmlGetProp (root_node, (xmlChar*) "length"); + if (length == NULL) + self->priv->length = -1; + else + self->priv->length = g_ascii_strtoull ((gchar*) length, NULL, 10); + xmlFree (length); + + return TRUE; +} + +static void +pre_get_xml (GDataParsable *parsable, GString *xml_string) +{ + GDataLinkPrivate *priv = GDATA_LINK (parsable)->priv; + + gdata_parser_string_append_escaped (xml_string, " href='", priv->uri, "'"); + + if (priv->title != NULL) + gdata_parser_string_append_escaped (xml_string, " title='", priv->title, "'"); + if (priv->relation_type != NULL) + gdata_parser_string_append_escaped (xml_string, " rel='", priv->relation_type, "'"); + if (priv->content_type != NULL) + gdata_parser_string_append_escaped (xml_string, " type='", priv->content_type, "'"); + if (priv->language != NULL) + gdata_parser_string_append_escaped (xml_string, " hreflang='", priv->language, "'"); + if (priv->length != -1) + g_string_append_printf (xml_string, " length='%i'", priv->length); +} + +/** + * gdata_link_new: + * @uri: the link's IRI + * @relation_type: (allow-none): the relationship of the link to the current document, or %NULL + * + * Creates a new #GDataLink. More information is available in the Atom specification. + * + * @uri must be non-%NULL and non-empty. @relation_type must be %NULL or non-empty. + * + * Return value: a new #GDataLink, or %NULL; unref with g_object_unref() + */ +GDataLink * +gdata_link_new (const gchar *uri, const gchar *relation_type) +{ + g_return_val_if_fail (uri != NULL && *uri != '\0', NULL); + g_return_val_if_fail (relation_type == NULL || *relation_type != '\0', NULL); + + return g_object_new (GDATA_TYPE_LINK, "uri", uri, "relation-type", relation_type, NULL); +} + +/** + * gdata_link_get_uri: + * @self: a #GDataLink + * + * Gets the #GDataLink:uri property. The return value is guaranteed to be a valid IRI, as + * specified by the Atom protocol. Common relationship values such as alternate + * are returned as http://www.iana.org/assignments/relation/alternate. + * + * For more information, see the + * Atom specification. + * + * Return value: the link's URI + * + * Since: 0.4.0 + */ +const gchar * +gdata_link_get_uri (GDataLink *self) +{ + g_return_val_if_fail (GDATA_IS_LINK (self), NULL); + return self->priv->uri; +} + +/** + * gdata_link_set_uri: + * @self: a #GDataLink + * @uri: the new URI for the link + * + * Sets the #GDataLink:uri property to @uri. @uri must be non-%NULL and non-empty. + * + * Since: 0.4.0 + */ +void +gdata_link_set_uri (GDataLink *self, const gchar *uri) +{ + g_return_if_fail (GDATA_IS_LINK (self)); + g_return_if_fail (uri != NULL && *uri != '\0'); + + g_free (self->priv->uri); + self->priv->uri = g_strdup (uri); + g_object_notify (G_OBJECT (self), "uri"); +} + +/** + * gdata_link_get_relation_type: + * @self: a #GDataLink + * + * Gets the #GDataLink:relation-type property. If the relation type is non-%NULL, it will be non-empty. + * + * Return value: (nullable): the link's relation type + * + * Since: 0.4.0 + */ +const gchar * +gdata_link_get_relation_type (GDataLink *self) +{ + g_return_val_if_fail (GDATA_IS_LINK (self), NULL); + return self->priv->relation_type; +} + +/** + * gdata_link_set_relation_type: + * @self: a #GDataLink + * @relation_type: (allow-none): the new relation type for the link, or %NULL + * + * Sets the #GDataLink:relation-type property to @relation_type. If @relation_type is one of the standard Atom relation types, + * use one of the defined relation type values, instead of a static string. e.g. %GDATA_LINK_EDIT or %GDATA_LINK_SELF. + * + * Set @relation_type to %NULL to unset the property in the link. + * + * Since: 0.4.0 + */ +void +gdata_link_set_relation_type (GDataLink *self, const gchar *relation_type) +{ + g_return_if_fail (GDATA_IS_LINK (self)); + g_return_if_fail (relation_type == NULL || *relation_type != '\0'); + + /* If the relation type is unset, use the default "alternate" relation type. If it's set, and isn't an IRI, turn it into an IRI + * by appending it to "http://www.iana.org/assignments/relation/". If it's set and is an IRI, just use the IRI. + * See: http://www.atomenabled.org/developers/syndication/atom-format-spec.php#rel_attribute + */ + g_free (self->priv->relation_type); + if (relation_type == NULL) + self->priv->relation_type = g_strdup (GDATA_LINK_ALTERNATE); + else if (strchr ((char*) relation_type, ':') == NULL) + self->priv->relation_type = g_strconcat ("http://www.iana.org/assignments/relation/", (const gchar*) relation_type, NULL); + else + self->priv->relation_type = g_strdup ((gchar*) relation_type); + + g_object_notify (G_OBJECT (self), "relation-type"); +} + +/** + * gdata_link_get_content_type: + * @self: a #GDataLink + * + * Gets the #GDataLink:content-type property. If the content type is non-%NULL, it will be non-empty. + * + * Return value: (nullable): the link's content type, or %NULL + * + * Since: 0.4.0 + */ +const gchar * +gdata_link_get_content_type (GDataLink *self) +{ + g_return_val_if_fail (GDATA_IS_LINK (self), NULL); + return self->priv->content_type; +} + +/** + * gdata_link_set_content_type: + * @self: a #GDataLink + * @content_type: (allow-none): the new content type for the link, or %NULL + * + * Sets the #GDataLink:content-type property to @content_type. @content_type must be %NULL or non-empty. + * + * Set @content_type to %NULL to unset the property in the link. + * + * Since: 0.4.0 + */ +void +gdata_link_set_content_type (GDataLink *self, const gchar *content_type) +{ + g_return_if_fail (GDATA_IS_LINK (self)); + g_return_if_fail (content_type == NULL || *content_type != '\0'); + + g_free (self->priv->content_type); + self->priv->content_type = g_strdup (content_type); + g_object_notify (G_OBJECT (self), "content-type"); +} + +/** + * gdata_link_get_language: + * @self: a #GDataLink + * + * Gets the #GDataLink:language property. If the language is non-%NULL, it will be non-empty. + * + * Return value: (nullable): the link's language, or %NULL + * + * Since: 0.4.0 + */ +const gchar * +gdata_link_get_language (GDataLink *self) +{ + g_return_val_if_fail (GDATA_IS_LINK (self), NULL); + return self->priv->language; +} + +/** + * gdata_link_set_language: + * @self: a #GDataLink + * @language: (allow-none): the new language for the link, or %NULL + * + * Sets the #GDataLink:language property to @language. @language must be %NULL or non-empty. + * + * Set @language to %NULL to unset the property in the link. + * + * Since: 0.4.0 + */ +void +gdata_link_set_language (GDataLink *self, const gchar *language) +{ + g_return_if_fail (GDATA_IS_LINK (self)); + g_return_if_fail (language == NULL || *language != '\0'); + + g_free (self->priv->language); + self->priv->language = g_strdup (language); + g_object_notify (G_OBJECT (self), "language"); +} + +/** + * gdata_link_get_title: + * @self: a #GDataLink + * + * Gets the #GDataLink:title property. + * + * Return value: the link's title, or %NULL + * + * Since: 0.4.0 + */ +const gchar * +gdata_link_get_title (GDataLink *self) +{ + g_return_val_if_fail (GDATA_IS_LINK (self), NULL); + return self->priv->title; +} + +/** + * gdata_link_set_title: + * @self: a #GDataLink + * @title: (allow-none): the new title for the link, or %NULL + * + * Sets the #GDataLink:title property to @title. + * + * Set @title to %NULL to unset the property in the link. + * + * Since: 0.4.0 + */ +void +gdata_link_set_title (GDataLink *self, const gchar *title) +{ + g_return_if_fail (GDATA_IS_LINK (self)); + + g_free (self->priv->title); + self->priv->title = g_strdup (title); + g_object_notify (G_OBJECT (self), "title"); +} + +/** + * gdata_link_get_length: + * @self: a #GDataLink + * + * Gets the #GDataLink:length property. + * + * Return value: the link's length, or -1 + * + * Since: 0.4.0 + */ +gint +gdata_link_get_length (GDataLink *self) +{ + g_return_val_if_fail (GDATA_IS_LINK (self), -1); + return self->priv->length; +} + +/** + * gdata_link_set_length: + * @self: a #GDataLink + * @length: the new length for the link, or -1 + * + * Sets the #GDataLink:length property to @length. + * + * Set @length to -1 to unset the property in the link. + * + * Since: 0.4.0 + */ +void +gdata_link_set_length (GDataLink *self, gint length) +{ + g_return_if_fail (GDATA_IS_LINK (self)); + g_return_if_fail (length >= -1); + + self->priv->length = length; + g_object_notify (G_OBJECT (self), "length"); +} diff --git a/gdata/atom/gdata-link.h b/gdata/atom/gdata-link.h new file mode 100644 index 0000000..75ba5d6 --- /dev/null +++ b/gdata/atom/gdata-link.h @@ -0,0 +1,190 @@ +/* -*- Mode: C; indent-tabs-mode: t; c-basic-offset: 8; tab-width: 8 -*- */ +/* + * GData Client + * Copyright (C) Philip Withnall 2009 + * + * GData Client is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * GData Client is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with GData Client. If not, see . + */ + +#ifndef GDATA_LINK_H +#define GDATA_LINK_H + +#include +#include + +#include + +G_BEGIN_DECLS + +/** + * GDATA_LINK_ALTERNATE: + * + * The relation type URI for alternate resources to the current one. + * + * For more information, see the + * Atom specification. + * + * Since: 0.4.0 + */ +#define GDATA_LINK_ALTERNATE "http://www.iana.org/assignments/relation/alternate" + +/** + * GDATA_LINK_RELATED: + * + * The relation type URI for resources related to the current one. + * + * For more information, see the + * Atom specification. + * + * Since: 0.4.0 + */ +#define GDATA_LINK_RELATED "http://www.iana.org/assignments/relation/related" + +/** + * GDATA_LINK_SELF: + * + * The relation type URI for the current resource. + * + * For more information, see the + * Atom specification. + * + * Since: 0.4.0 + */ +#define GDATA_LINK_SELF "http://www.iana.org/assignments/relation/self" + +/** + * GDATA_LINK_ENCLOSURE: + * + * The relation type URI for attached objects which may be large in size. + * + * For more information, see the + * Atom specification. + * + * Since: 0.4.0 + */ +#define GDATA_LINK_ENCLOSURE "http://www.iana.org/assignments/relation/enclosure" + +/** + * GDATA_LINK_VIA: + * + * The relation type URI for the source document of the current resource. + * + * For more information, see the + * Atom specification. + * + * Since: 0.4.0 + */ +#define GDATA_LINK_VIA "http://www.iana.org/assignments/relation/via" + +/** + * GDATA_LINK_EDIT: + * + * The relation type URI of the edit location for this resource. + * + * For more information, see the + * Atom Publishing Protocol specification. + * + * Since: 0.4.0 + */ +#define GDATA_LINK_EDIT "http://www.iana.org/assignments/relation/edit" + +/** + * GDATA_LINK_EDIT_MEDIA: + * + * The relation type URI of the edit location for media resources attached to this resource. + * + * For more information, see the + * + * Atom Publishing Protocol specification. + * + * Since: 0.4.0 + */ +#define GDATA_LINK_EDIT_MEDIA "http://www.iana.org/assignments/relation/edit-media" + +/** + * GDATA_LINK_PARENT: + * + * The relation type URI of the of the location of the parent resource in a + * hierarchy of entries. + * + * This is an undocumented GData-specific addition to the Atom specification, + * and is not included in the GData documentation except in examples and in the + * + * RelaxNG schema. + * + * Since: 0.15.1 + */ +#define GDATA_LINK_PARENT "http://schemas.google.com/docs/2007#parent" + +#define GDATA_TYPE_LINK (gdata_link_get_type ()) +#define GDATA_LINK(o) (G_TYPE_CHECK_INSTANCE_CAST ((o), GDATA_TYPE_LINK, GDataLink)) +#define GDATA_LINK_CLASS(k) (G_TYPE_CHECK_CLASS_CAST((k), GDATA_TYPE_LINK, GDataLinkClass)) +#define GDATA_IS_LINK(o) (G_TYPE_CHECK_INSTANCE_TYPE ((o), GDATA_TYPE_LINK)) +#define GDATA_IS_LINK_CLASS(k) (G_TYPE_CHECK_CLASS_TYPE ((k), GDATA_TYPE_LINK)) +#define GDATA_LINK_GET_CLASS(o) (G_TYPE_INSTANCE_GET_CLASS ((o), GDATA_TYPE_LINK, GDataLinkClass)) + +typedef struct _GDataLinkPrivate GDataLinkPrivate; + +/** + * GDataLink: + * + * All the fields in the #GDataLink structure are private and should never be accessed directly. + */ +typedef struct { + GDataParsable parent; + GDataLinkPrivate *priv; +} GDataLink; + +/** + * GDataLinkClass: + * + * All the fields in the #GDataLinkClass structure are private and should never be accessed directly. + * + * Since: 0.4.0 + */ +typedef struct { + /*< private >*/ + GDataParsableClass parent; + + /*< private >*/ + /* Padding for future expansion */ + void (*_g_reserved0) (void); + void (*_g_reserved1) (void); +} GDataLinkClass; + +GType gdata_link_get_type (void) G_GNUC_CONST; + +GDataLink *gdata_link_new (const gchar *uri, const gchar *relation_type) G_GNUC_WARN_UNUSED_RESULT G_GNUC_MALLOC; + +const gchar *gdata_link_get_uri (GDataLink *self) G_GNUC_PURE; +void gdata_link_set_uri (GDataLink *self, const gchar *uri); + +const gchar *gdata_link_get_relation_type (GDataLink *self) G_GNUC_PURE; +void gdata_link_set_relation_type (GDataLink *self, const gchar *relation_type); + +const gchar *gdata_link_get_content_type (GDataLink *self) G_GNUC_PURE; +void gdata_link_set_content_type (GDataLink *self, const gchar *content_type); + +const gchar *gdata_link_get_language (GDataLink *self) G_GNUC_PURE; +void gdata_link_set_language (GDataLink *self, const gchar *language); + +const gchar *gdata_link_get_title (GDataLink *self) G_GNUC_PURE; +void gdata_link_set_title (GDataLink *self, const gchar *title); + +gint gdata_link_get_length (GDataLink *self) G_GNUC_PURE; +void gdata_link_set_length (GDataLink *self, gint length); + +G_END_DECLS + +#endif /* !GDATA_LINK_H */ diff --git a/gdata/atom/meson.build b/gdata/atom/meson.build new file mode 100644 index 0000000..9a43695 --- /dev/null +++ b/gdata/atom/meson.build @@ -0,0 +1,20 @@ +headers = files( + 'gdata-author.h', + 'gdata-category.h', + 'gdata-generator.h', + 'gdata-link.h', +) + +install_headers( + headers, + subdir: gdata_include_subdir / 'atom', +) + +gir_headers += headers + +sources += files( + 'gdata-author.c', + 'gdata-category.c', + 'gdata-generator.c', + 'gdata-link.c', +) diff --git a/gdata/exif/gdata-exif-tags.c b/gdata/exif/gdata-exif-tags.c new file mode 100644 index 0000000..0a456cf --- /dev/null +++ b/gdata/exif/gdata-exif-tags.c @@ -0,0 +1,343 @@ +/* -*- Mode: C; indent-tabs-mode: t; c-basic-offset: 8; tab-width: 8 -*- */ +/* + * GData Client + * Copyright (C) Richard Schwarting 2009 + * + * GData Client is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * GData Client is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with GData Client. If not, see . + */ + +/* + * SECTION:gdata-exif-tags + * @short_description: EXIF tags element + * @stability: Stable + * @include: gdata/exif/gdata-exif-tags.h + * + * #GDataExifTags represents a "tags" element from the + * EXIF specification. + * + * It is private API, since implementing classes are likely to proxy the properties and functions + * of #GDataExifTags as appropriate; most entry types which implement #GDataExifTags have no use + * for most of its properties, and it would be unnecessary and confusing to expose #GDataExifTags itself. + * + * Also note that modified EXIF values submitted back to the Google (in an update or on the original + * upload) appear to be ignored. Google's EXIF values for the uploaded image will be set to the EXIF + * metadata found in the image itself. + * + * For these reasons, properties have not been implemented on #GDataExifTags (yet). + * + * Since: 0.5.0 + */ + +#include +#include +#include + +#include "gdata-exif-tags.h" +#include "gdata-parsable.h" +#include "gdata-parser.h" +#include "gdata-private.h" + +static void gdata_exif_tags_finalize (GObject *object); +static gboolean parse_xml (GDataParsable *parsable, xmlDoc *doc, xmlNode *node, gpointer user_data, GError **error); +static void get_namespaces (GDataParsable *parsable, GHashTable *namespaces); + +struct _GDataExifTagsPrivate { + gdouble distance; + gdouble exposure; + gboolean flash; + gdouble focal_length; + gdouble fstop; + gchar *image_unique_id; + gint iso; + gchar *make; + gchar *model; + gint64 _time; /* in milliseconds! */ +}; + +G_DEFINE_TYPE (GDataExifTags, gdata_exif_tags, GDATA_TYPE_PARSABLE) + +static void +gdata_exif_tags_class_init (GDataExifTagsClass *klass) +{ + GObjectClass *gobject_class = G_OBJECT_CLASS (klass); + GDataParsableClass *parsable_class = GDATA_PARSABLE_CLASS (klass); + + g_type_class_add_private (klass, sizeof (GDataExifTagsPrivate)); + + gobject_class->finalize = gdata_exif_tags_finalize; + + parsable_class->parse_xml = parse_xml; + parsable_class->get_namespaces = get_namespaces; + parsable_class->element_name = "tags"; + parsable_class->element_namespace = "exif"; +} + +static void +gdata_exif_tags_init (GDataExifTags *self) +{ + self->priv = G_TYPE_INSTANCE_GET_PRIVATE (self, GDATA_TYPE_EXIF_TAGS, GDataExifTagsPrivate); + self->priv->_time = -1; +} + +static void +gdata_exif_tags_finalize (GObject *object) +{ + GDataExifTagsPrivate *priv = GDATA_EXIF_TAGS (object)->priv; + + g_free (priv->make); + g_free (priv->model); + g_free (priv->image_unique_id); + + /* Chain up to the parent class */ + G_OBJECT_CLASS (gdata_exif_tags_parent_class)->finalize (object); +} + +static gboolean +parse_xml (GDataParsable *parsable, xmlDoc *doc, xmlNode *node, gpointer user_data, GError **error) +{ + gboolean success; + GDataExifTags *self = GDATA_EXIF_TAGS (parsable); + + if (gdata_parser_is_namespace (node, "http://schemas.google.com/photos/exif/2007") == FALSE) + return GDATA_PARSABLE_CLASS (gdata_exif_tags_parent_class)->parse_xml (parsable, doc, node, user_data, error); + + if (xmlStrcmp (node->name, (xmlChar*) "distance") == 0 ) { + /* exif:distance */ + xmlChar *distance = xmlNodeListGetString (doc, node->children, TRUE); + self->priv->distance = g_ascii_strtod ((gchar*) distance, NULL); + xmlFree (distance); + } else if (xmlStrcmp (node->name, (xmlChar*) "fstop") == 0) { + /* exif:fstop */ + xmlChar *fstop = xmlNodeListGetString (doc, node->children, TRUE); + self->priv->fstop = g_ascii_strtod ((gchar*) fstop, NULL); + xmlFree (fstop); + } else if (gdata_parser_string_from_element (node, "make", P_NONE, &(self->priv->make), &success, error) == TRUE || + gdata_parser_string_from_element (node, "model", P_NONE, &(self->priv->model), &success, error) == TRUE || + gdata_parser_string_from_element (node, "imageUniqueID", P_NONE, &(self->priv->image_unique_id), &success, error) == TRUE) { + return success; + } else if (xmlStrcmp (node->name, (xmlChar*) "exposure") == 0) { + /* exif:exposure */ + xmlChar *exposure = xmlNodeListGetString (doc, node->children, TRUE); + self->priv->exposure = g_ascii_strtod ((gchar*) exposure, NULL); + xmlFree (exposure); + } else if (xmlStrcmp (node->name, (xmlChar*) "flash") == 0) { + /* exif:flash */ + xmlChar *flash = xmlNodeListGetString (doc, node->children, TRUE); + if (flash == NULL) + return gdata_parser_error_required_content_missing (node, error); + self->priv->flash = (xmlStrcmp (flash, (xmlChar*) "true") == 0 ? TRUE : FALSE); + xmlFree (flash); + } else if (xmlStrcmp (node->name, (xmlChar*) "focallength") == 0) { + /* exif:focal-length */ + xmlChar *focal_length = xmlNodeListGetString (doc, node->children, TRUE); + self->priv->focal_length = g_ascii_strtod ((gchar*) focal_length, NULL); + xmlFree (focal_length); + } else if (xmlStrcmp (node->name, (xmlChar*) "iso") == 0) { + /* exif:iso */ + xmlChar *iso = xmlNodeListGetString (doc, node->children, TRUE); + self->priv->iso = g_ascii_strtoll ((gchar*) iso, NULL, 10); + xmlFree (iso); + } else if (xmlStrcmp (node->name, (xmlChar*) "time") == 0) { + /* exif:time */ + xmlChar *time_str; + guint64 milliseconds; + + time_str = xmlNodeListGetString (doc, node->children, TRUE); + milliseconds = g_ascii_strtoull ((gchar*) time_str, NULL, 10); + xmlFree (time_str); + + self->priv->_time = (gint64) milliseconds; + } else { + return GDATA_PARSABLE_CLASS (gdata_exif_tags_parent_class)->parse_xml (parsable, doc, node, user_data, error); + } + + return TRUE; +} + +static void +get_namespaces (GDataParsable *parsable, GHashTable *namespaces) +{ + g_hash_table_insert (namespaces, (gchar*) "exif", (gchar*) "http://schemas.google.com/photos/exif/2007"); +} + +/** + * gdata_exif_tags_get_distance: + * @self: a #GDataExifTags + * + * Gets the #GDataExifTags:distance property. + * + * Return value: the distance value, or -1 if unknown + * + * Since: 0.5.0 + */ +gdouble +gdata_exif_tags_get_distance (GDataExifTags *self) +{ + g_return_val_if_fail (GDATA_IS_EXIF_TAGS (self), -1); + return self->priv->distance; +} + +/** + * gdata_exif_tags_get_exposure: + * @self: a #GDataExifTags + * + * Gets the #GDataExifTags:exposure property. + * + * Return value: the exposure value, or 0 if unknown + * + * Since: 0.5.0 + */ +gdouble +gdata_exif_tags_get_exposure (GDataExifTags *self) +{ + g_return_val_if_fail (GDATA_IS_EXIF_TAGS (self), 0); + return self->priv->exposure; +} + +/** + * gdata_exif_tags_get_flash: + * @self: a #GDataExifTags + * + * Gets the #GDataExifTags:flash property. + * + * Return value: %TRUE if flash was used, %FALSE otherwise + * + * Since: 0.5.0 + */ +gboolean +gdata_exif_tags_get_flash (GDataExifTags *self) +{ + g_return_val_if_fail (GDATA_IS_EXIF_TAGS (self), FALSE); + return self->priv->flash; +} + +/** + * gdata_exif_tags_get_focal_length: + * @self: a #GDataExifTags + * + * Gets the #GDataExifTags:focal-length property. + * + * Return value: the focal-length value, or -1 if unknown + * + * Since: 0.5.0 + */ +gdouble +gdata_exif_tags_get_focal_length (GDataExifTags *self) +{ + g_return_val_if_fail (GDATA_IS_EXIF_TAGS (self), -1); + return self->priv->focal_length; +} + +/** + * gdata_exif_tags_get_fstop: + * @self: a #GDataExifTags + * + * Gets the #GDataExifTags:fstop property. + * + * Return value: the F-stop value, or 0 if unknown + * + * Since: 0.5.0 + */ +gdouble +gdata_exif_tags_get_fstop (GDataExifTags *self) +{ + g_return_val_if_fail (GDATA_IS_EXIF_TAGS (self), 0); + return self->priv->fstop; +} + +/** + * gdata_exif_tags_get_image_unique_id: + * @self: a #GDataExifTags + * + * Gets the #GDataExifTags:image-unique-id property. + * + * Return value: the photo's unique EXIF identifier, or %NULL + * + * Since: 0.5.0 + */ +const gchar * +gdata_exif_tags_get_image_unique_id (GDataExifTags *self) +{ + g_return_val_if_fail (GDATA_IS_EXIF_TAGS (self), NULL); + return self->priv->image_unique_id; +} + +/** + * gdata_exif_tags_get_iso: + * @self: a #GDataExifTags + * + * Gets the #GDataExifTags:iso property. + * + * Return value: the ISO speed, or -1 if unknown + * + * Since: 0.5.0 + */ +gint +gdata_exif_tags_get_iso (GDataExifTags *self) +{ + g_return_val_if_fail (GDATA_IS_EXIF_TAGS (self), -1); + return self->priv->iso; +} + +/** + * gdata_exif_tags_get_make: + * @self: a #GDataExifTags + * + * Gets the #GDataExifTags:make property. + * + * Return value: the name of the manufacturer of the camera, or %NULL if unknown + * + * Since: 0.5.0 + */ +const gchar * +gdata_exif_tags_get_make (GDataExifTags *self) +{ + g_return_val_if_fail (GDATA_IS_EXIF_TAGS (self), NULL); + return self->priv->make; +} + +/** + * gdata_exif_tags_get_model: + * @self: a #GDataExifTags + * + * Gets the #GDataExifTags:model property. + * + * Return value: the model name of the camera, or %NULL if unknown + * + * Since: 0.5.0 + */ +const gchar * +gdata_exif_tags_get_model (GDataExifTags *self) +{ + g_return_val_if_fail (GDATA_IS_EXIF_TAGS (self), NULL); + return self->priv->model; +} + +/** + * gdata_exif_tags_get_time: + * @self: a #GDataExifTags + * + * Gets the #GDataExifTags:time property as a number of milliseconds since the epoch. If the property is unset, -1 will + * be returned. + * + * Return value: the UNIX timestamp for the time property in milliseconds, or -1 + * + * Since: 0.5.0 + */ +gint64 +gdata_exif_tags_get_time (GDataExifTags *self) +{ + g_return_val_if_fail (GDATA_IS_EXIF_TAGS (self), -1); + return self->priv->_time; +} diff --git a/gdata/exif/gdata-exif-tags.h b/gdata/exif/gdata-exif-tags.h new file mode 100644 index 0000000..efb586f --- /dev/null +++ b/gdata/exif/gdata-exif-tags.h @@ -0,0 +1,83 @@ +/* -*- Mode: C; indent-tabs-mode: t; c-basic-offset: 8; tab-width: 8 -*- */ +/* + * GData Client + * Copyright (C) Richard Schwarting 2009 + * + * GData Client is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * GData Client is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with GData Client. If not, see . + */ + +#ifndef GDATA_EXIF_TAGS_H +#define GDATA_EXIF_TAGS_H + +#include +#include + +#include + +G_BEGIN_DECLS + +#define GDATA_TYPE_EXIF_TAGS (gdata_exif_tags_get_type ()) +#define GDATA_EXIF_TAGS(o) (G_TYPE_CHECK_INSTANCE_CAST ((o), GDATA_TYPE_EXIF_TAGS, GDataExifTags)) +#define GDATA_EXIF_TAGS_CLASS(k) (G_TYPE_CHECK_CLASS_CAST((k), GDATA_TYPE_EXIF_TAGS, GDataExifTagsClass)) +#define GDATA_IS_EXIF_TAGS(o) (G_TYPE_CHECK_INSTANCE_TYPE ((o), GDATA_TYPE_EXIF_TAGS)) +#define GDATA_IS_EXIF_TAGS_CLASS(k) (G_TYPE_CHECK_CLASS_TYPE ((k), GDATA_TYPE_EXIF_TAGS)) +#define GDATA_EXIF_TAGS_GET_CLASS(o) (G_TYPE_INSTANCE_GET_CLASS ((o), GDATA_TYPE_EXIF_TAGS, GDataExifTagsClass)) + +typedef struct _GDataExifTagsPrivate GDataExifTagsPrivate; + +/** + * GDataExifTags: + * + * All the fields in the #GDataExifTags structure are private and should never be accessed directly. + * + * Since: 0.5.0 + */ +typedef struct { + GDataParsable parent; + GDataExifTagsPrivate *priv; +} GDataExifTags; + +/** + * GDataExifTagsClass: + * + * All the fields in the #GDataExifTagsClass structure are private and should never be accessed directly. + * + * Since: 0.5.0 + */ +typedef struct { + /*< private >*/ + GDataParsableClass parent; + + /*< private >*/ + /* Padding for future expansion */ + void (*_g_reserved0) (void); + void (*_g_reserved1) (void); +} GDataExifTagsClass; + +GType gdata_exif_tags_get_type (void) G_GNUC_CONST; + +gdouble gdata_exif_tags_get_distance (GDataExifTags *self) G_GNUC_PURE; +gdouble gdata_exif_tags_get_exposure (GDataExifTags *self) G_GNUC_PURE; +gboolean gdata_exif_tags_get_flash (GDataExifTags *self) G_GNUC_PURE; +gdouble gdata_exif_tags_get_focal_length (GDataExifTags *self) G_GNUC_PURE; +gdouble gdata_exif_tags_get_fstop (GDataExifTags *self) G_GNUC_PURE; +const gchar *gdata_exif_tags_get_image_unique_id (GDataExifTags *self) G_GNUC_PURE; +gint gdata_exif_tags_get_iso (GDataExifTags *self) G_GNUC_PURE; +const gchar *gdata_exif_tags_get_make (GDataExifTags *self) G_GNUC_PURE; +const gchar *gdata_exif_tags_get_model (GDataExifTags *self) G_GNUC_PURE; +gint64 gdata_exif_tags_get_time (GDataExifTags *self); + +G_END_DECLS + +#endif /* !GDATA_EXIF_TAGS_H */ diff --git a/gdata/exif/meson.build b/gdata/exif/meson.build new file mode 100644 index 0000000..a900085 --- /dev/null +++ b/gdata/exif/meson.build @@ -0,0 +1 @@ +sources += files('gdata-exif-tags.c') diff --git a/gdata/gcontact/gdata-gcontact-calendar.c b/gdata/gcontact/gdata-gcontact-calendar.c new file mode 100644 index 0000000..90562d2 --- /dev/null +++ b/gdata/gcontact/gdata-gcontact-calendar.c @@ -0,0 +1,478 @@ +/* -*- Mode: C; indent-tabs-mode: t; c-basic-offset: 8; tab-width: 8 -*- */ +/* + * GData Client + * Copyright (C) Philip Withnall 2010 + * + * GData Client is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * GData Client is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with GData Client. If not, see . + */ + +/** + * SECTION:gdata-gcontact-calendar + * @short_description: gContact calendar element + * @stability: Stable + * @include: gdata/gcontact/gdata-gcontact-calendar.h + * + * #GDataGContactCalendar represents a "calendarLink" element from the + * gContact specification. + * + * Since: 0.7.0 + */ + +#include +#include + +#include "gdata-gcontact-calendar.h" +#include "gdata-parsable.h" +#include "gdata-parser.h" +#include "gdata-comparable.h" + +static void gdata_gcontact_calendar_comparable_init (GDataComparableIface *iface); +static void gdata_gcontact_calendar_finalize (GObject *object); +static void gdata_gcontact_calendar_get_property (GObject *object, guint property_id, GValue *value, GParamSpec *pspec); +static void gdata_gcontact_calendar_set_property (GObject *object, guint property_id, const GValue *value, GParamSpec *pspec); +static gboolean pre_parse_xml (GDataParsable *parsable, xmlDoc *doc, xmlNode *root_node, gpointer user_data, GError **error); +static void pre_get_xml (GDataParsable *parsable, GString *xml_string); +static void get_namespaces (GDataParsable *parsable, GHashTable *namespaces); + +struct _GDataGContactCalendarPrivate { + gchar *uri; + gchar *relation_type; + gchar *label; + gboolean is_primary; +}; + +enum { + PROP_URI = 1, + PROP_RELATION_TYPE, + PROP_LABEL, + PROP_IS_PRIMARY +}; + +G_DEFINE_TYPE_WITH_CODE (GDataGContactCalendar, gdata_gcontact_calendar, GDATA_TYPE_PARSABLE, + G_IMPLEMENT_INTERFACE (GDATA_TYPE_COMPARABLE, gdata_gcontact_calendar_comparable_init)) + +static void +gdata_gcontact_calendar_class_init (GDataGContactCalendarClass *klass) +{ + GObjectClass *gobject_class = G_OBJECT_CLASS (klass); + GDataParsableClass *parsable_class = GDATA_PARSABLE_CLASS (klass); + + g_type_class_add_private (klass, sizeof (GDataGContactCalendarPrivate)); + + gobject_class->get_property = gdata_gcontact_calendar_get_property; + gobject_class->set_property = gdata_gcontact_calendar_set_property; + gobject_class->finalize = gdata_gcontact_calendar_finalize; + + parsable_class->pre_parse_xml = pre_parse_xml; + parsable_class->pre_get_xml = pre_get_xml; + parsable_class->get_namespaces = get_namespaces; + parsable_class->element_name = "calendarLink"; + parsable_class->element_namespace = "gContact"; + + /** + * GDataGContactCalendar:uri: + * + * The URI of the calendar. + * + * For more information, see the + * gContact specification. + * + * Since: 0.7.0 + */ + g_object_class_install_property (gobject_class, PROP_URI, + g_param_spec_string ("uri", + "URI", "The URI of the calendar.", + NULL, + G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)); + + /** + * GDataGContactCalendar:relation-type: + * + * A programmatic value that identifies the type of calendar. It is mutually exclusive with #GDataGContactCalendar:label. + * Examples are %GDATA_GCONTACT_CALENDAR_HOME or %GDATA_GCONTACT_CALENDAR_FREE_BUSY. + * + * For more information, see the + * gContact specification. + * + * Since: 0.7.0 + */ + g_object_class_install_property (gobject_class, PROP_RELATION_TYPE, + g_param_spec_string ("relation-type", + "Relation type", "A programmatic value that identifies the type of calendar.", + NULL, + G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)); + + /** + * GDataGContactCalendar:label: + * + * A free-form string that identifies the type of calendar. It is mutually exclusive with #GDataGContactCalendar:relation-type. + * + * For more information, see the + * gContact specification. + * + * Since: 0.7.0 + */ + g_object_class_install_property (gobject_class, PROP_LABEL, + g_param_spec_string ("label", + "Label", "A free-form string that identifies the type of calendar.", + NULL, + G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)); + + /** + * GDataGContactCalendar:is-primary: + * + * Indicates which calendar out of a group is primary. + * + * For more information, see the + * gContact specification. + * + * Since: 0.7.0 + */ + g_object_class_install_property (gobject_class, PROP_IS_PRIMARY, + g_param_spec_boolean ("is-primary", + "Primary?", "Indicates which calendar out of a group is primary.", + FALSE, + G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)); +} + +static gint +compare_with (GDataComparable *self, GDataComparable *other) +{ + GDataGContactCalendarPrivate *a = ((GDataGContactCalendar*) self)->priv, *b = ((GDataGContactCalendar*) other)->priv; + + if (g_strcmp0 (a->uri, b->uri) == 0 && g_strcmp0 (a->relation_type, b->relation_type) == 0 && g_strcmp0 (a->label, b->label) == 0) + return 0; + return 1; +} + +static void +gdata_gcontact_calendar_comparable_init (GDataComparableIface *iface) +{ + iface->compare_with = compare_with; +} + +static void +gdata_gcontact_calendar_init (GDataGContactCalendar *self) +{ + self->priv = G_TYPE_INSTANCE_GET_PRIVATE (self, GDATA_TYPE_GCONTACT_CALENDAR, GDataGContactCalendarPrivate); +} + +static void +gdata_gcontact_calendar_finalize (GObject *object) +{ + GDataGContactCalendarPrivate *priv = GDATA_GCONTACT_CALENDAR (object)->priv; + + g_free (priv->uri); + g_free (priv->relation_type); + g_free (priv->label); + + /* Chain up to the parent class */ + G_OBJECT_CLASS (gdata_gcontact_calendar_parent_class)->finalize (object); +} + +static void +gdata_gcontact_calendar_get_property (GObject *object, guint property_id, GValue *value, GParamSpec *pspec) +{ + GDataGContactCalendarPrivate *priv = GDATA_GCONTACT_CALENDAR (object)->priv; + + switch (property_id) { + case PROP_URI: + g_value_set_string (value, priv->uri); + break; + case PROP_RELATION_TYPE: + g_value_set_string (value, priv->relation_type); + break; + case PROP_LABEL: + g_value_set_string (value, priv->label); + break; + case PROP_IS_PRIMARY: + g_value_set_boolean (value, priv->is_primary); + break; + default: + /* We don't have any other property... */ + G_OBJECT_WARN_INVALID_PROPERTY_ID (object, property_id, pspec); + break; + } +} + +static void +gdata_gcontact_calendar_set_property (GObject *object, guint property_id, const GValue *value, GParamSpec *pspec) +{ + GDataGContactCalendar *self = GDATA_GCONTACT_CALENDAR (object); + + switch (property_id) { + case PROP_URI: + gdata_gcontact_calendar_set_uri (self, g_value_get_string (value)); + break; + case PROP_RELATION_TYPE: + gdata_gcontact_calendar_set_relation_type (self, g_value_get_string (value)); + break; + case PROP_LABEL: + gdata_gcontact_calendar_set_label (self, g_value_get_string (value)); + break; + case PROP_IS_PRIMARY: + gdata_gcontact_calendar_set_is_primary (self, g_value_get_boolean (value)); + break; + default: + /* We don't have any other property... */ + G_OBJECT_WARN_INVALID_PROPERTY_ID (object, property_id, pspec); + break; + } +} + +static gboolean +pre_parse_xml (GDataParsable *parsable, xmlDoc *doc, xmlNode *root_node, gpointer user_data, GError **error) +{ + xmlChar *uri, *rel, *label; + gboolean primary_bool; + GDataGContactCalendarPrivate *priv = GDATA_GCONTACT_CALENDAR (parsable)->priv; + + /* Is it the primary calendar? */ + if (gdata_parser_boolean_from_property (root_node, "primary", &primary_bool, 0, error) == FALSE) + return FALSE; + + uri = xmlGetProp (root_node, (xmlChar*) "href"); + if (uri == NULL || *uri == '\0') { + xmlFree (uri); + return gdata_parser_error_required_property_missing (root_node, "href", error); + } + + rel = xmlGetProp (root_node, (xmlChar*) "rel"); + label = xmlGetProp (root_node, (xmlChar*) "label"); + if ((rel == NULL || *rel == '\0') && (label == NULL || *label == '\0')) { + xmlFree (uri); + xmlFree (rel); + xmlFree (label); + return gdata_parser_error_required_property_missing (root_node, "rel", error); + } else if (rel != NULL && label != NULL) { + /* Can't have both set at once */ + xmlFree (uri); + xmlFree (rel); + xmlFree (label); + return gdata_parser_error_mutexed_properties (root_node, "rel", "label", error); + } + + priv->uri = (gchar*) uri; + priv->relation_type = (gchar*) rel; + priv->label = (gchar*) label; + priv->is_primary = primary_bool; + + return TRUE; +} + +static void +pre_get_xml (GDataParsable *parsable, GString *xml_string) +{ + GDataGContactCalendarPrivate *priv = GDATA_GCONTACT_CALENDAR (parsable)->priv; + + gdata_parser_string_append_escaped (xml_string, " href='", priv->uri, "'"); + + if (priv->relation_type != NULL) + gdata_parser_string_append_escaped (xml_string, " rel='", priv->relation_type, "'"); + else if (priv->label != NULL) + gdata_parser_string_append_escaped (xml_string, " label='", priv->label, "'"); + else + g_assert_not_reached (); + + if (priv->is_primary == TRUE) + g_string_append (xml_string, " primary='true'"); + else + g_string_append (xml_string, " primary='false'"); +} + +static void +get_namespaces (GDataParsable *parsable, GHashTable *namespaces) +{ + g_hash_table_insert (namespaces, (gchar*) "gContact", (gchar*) "http://schemas.google.com/contact/2008"); +} + +/** + * gdata_gcontact_calendar_new: + * @uri: the URI of the calendar + * @relation_type: (allow-none): the type of calendar, or %NULL + * @label: (allow-none): a free-form label for the calendar, or %NULL + * @is_primary: %TRUE if this calendar is its owner's primary calendar, %FALSE otherwise + * + * Creates a new #GDataGContactCalendar. More information is available in the gContact specification. + * + * Exactly one of @relation_type and @label should be provided; the other must be %NULL. + * + * Return value: a new #GDataGContactCalendar; unref with g_object_unref() + * + * Since: 0.7.0 + */ +GDataGContactCalendar * +gdata_gcontact_calendar_new (const gchar *uri, const gchar *relation_type, const gchar *label, gboolean is_primary) +{ + g_return_val_if_fail (uri != NULL && *uri != '\0', NULL); + g_return_val_if_fail ((relation_type != NULL && *relation_type != '\0' && label == NULL) || + (relation_type == NULL && label != NULL && *label != '\0'), NULL); + + return g_object_new (GDATA_TYPE_GCONTACT_CALENDAR, + "uri", uri, "relation-type", relation_type, "label", label, "is-primary", is_primary, NULL); +} + +/** + * gdata_gcontact_calendar_get_uri: + * @self: a #GDataGContactCalendar + * + * Gets the #GDataGContactCalendar:uri property. + * + * Return value: the calendar's URI + * + * Since: 0.7.0 + */ +const gchar * +gdata_gcontact_calendar_get_uri (GDataGContactCalendar *self) +{ + g_return_val_if_fail (GDATA_IS_GCONTACT_CALENDAR (self), NULL); + return self->priv->uri; +} + +/** + * gdata_gcontact_calendar_set_uri: + * @self: a #GDataGContactCalendar + * @uri: the new URI for the calendar + * + * Sets the #GDataGContactCalendar:uri property to @uri. + * + * Since: 0.7.0 + */ +void +gdata_gcontact_calendar_set_uri (GDataGContactCalendar *self, const gchar *uri) +{ + g_return_if_fail (GDATA_IS_GCONTACT_CALENDAR (self)); + g_return_if_fail (uri != NULL && *uri != '\0'); + + g_free (self->priv->uri); + self->priv->uri = g_strdup (uri); + g_object_notify (G_OBJECT (self), "uri"); +} + +/** + * gdata_gcontact_calendar_get_relation_type: + * @self: a #GDataGContactCalendar + * + * Gets the #GDataGContactCalendar:relation-type property. + * + * Return value: the type of the relation, or %NULL + * + * Since: 0.7.0 + */ +const gchar * +gdata_gcontact_calendar_get_relation_type (GDataGContactCalendar *self) +{ + g_return_val_if_fail (GDATA_IS_GCONTACT_CALENDAR (self), NULL); + return self->priv->relation_type; +} + +/** + * gdata_gcontact_calendar_set_relation_type: + * @self: a #GDataGContactCalendar + * @relation_type: (allow-none): the new type for the calendar, or %NULL + * + * Sets the #GDataGContactCalendar:relation-type property to @relation_type, + * such as %GDATA_GCONTACT_CALENDAR_HOME or %GDATA_GCONTACT_CALENDAR_FREE_BUSY. + * + * If @relation_type is %NULL, the relation type will be unset. When the #GDataGContactCalendar is used in a query, however, + * exactly one of #GDataGContactCalendar:relation-type and #GDataGContactCalendar:label must be %NULL. + * + * Since: 0.7.0 + */ +void +gdata_gcontact_calendar_set_relation_type (GDataGContactCalendar *self, const gchar *relation_type) +{ + g_return_if_fail (GDATA_IS_GCONTACT_CALENDAR (self)); + g_return_if_fail (relation_type == NULL || *relation_type != '\0'); + + g_free (self->priv->relation_type); + self->priv->relation_type = g_strdup (relation_type); + g_object_notify (G_OBJECT (self), "relation-type"); +} + +/** + * gdata_gcontact_calendar_get_label: + * @self: a #GDataGContactCalendar + * + * Gets the #GDataGContactCalendar:label property. + * + * Return value: a free-form label for the calendar, or %NULL + * + * Since: 0.7.0 + */ +const gchar * +gdata_gcontact_calendar_get_label (GDataGContactCalendar *self) +{ + g_return_val_if_fail (GDATA_IS_GCONTACT_CALENDAR (self), NULL); + return self->priv->label; +} + +/** + * gdata_gcontact_calendar_set_label: + * @self: a #GDataGContactCalendar + * @label: (allow-none): the new free-form label for the calendar, or %NULL + * + * Sets the #GDataGContactCalendar:label property to @label. + * + * If @label is %NULL, the label will be unset. When the #GDataGContactCalendar is used in a query, however, + * exactly one of #GDataGContactCalendar:relation-type and #GDataGContactCalendar:label must be %NULL. + * + * Since: 0.7.0 + */ +void +gdata_gcontact_calendar_set_label (GDataGContactCalendar *self, const gchar *label) +{ + g_return_if_fail (GDATA_IS_GCONTACT_CALENDAR (self)); + g_return_if_fail (label == NULL || *label != '\0'); + + g_free (self->priv->label); + self->priv->label = g_strdup (label); + g_object_notify (G_OBJECT (self), "label"); +} + +/** + * gdata_gcontact_calendar_is_primary: + * @self: a #GDataGContactCalendar + * + * Gets the #GDataGContactCalendar:is-primary property. + * + * Return value: %TRUE if this is the contact's primary calendar, %FALSE otherwise + * + * Since: 0.7.0 + */ +gboolean +gdata_gcontact_calendar_is_primary (GDataGContactCalendar *self) +{ + g_return_val_if_fail (GDATA_IS_GCONTACT_CALENDAR (self), FALSE); + return self->priv->is_primary; +} + +/** + * gdata_gcontact_calendar_set_is_primary: + * @self: a #GDataGContactCalendar + * @is_primary: %TRUE if this is the contact's primary calendar, %FALSE otherwise + * + * Sets the #GDataGContactCalendar:is-primary property to @is_primary. + * + * Since: 0.7.0 + */ +void +gdata_gcontact_calendar_set_is_primary (GDataGContactCalendar *self, gboolean is_primary) +{ + g_return_if_fail (GDATA_IS_GCONTACT_CALENDAR (self)); + + self->priv->is_primary = is_primary; + g_object_notify (G_OBJECT (self), "is-primary"); +} diff --git a/gdata/gcontact/gdata-gcontact-calendar.h b/gdata/gcontact/gdata-gcontact-calendar.h new file mode 100644 index 0000000..125ee6d --- /dev/null +++ b/gdata/gcontact/gdata-gcontact-calendar.h @@ -0,0 +1,123 @@ +/* -*- Mode: C; indent-tabs-mode: t; c-basic-offset: 8; tab-width: 8 -*- */ +/* + * GData Client + * Copyright (C) Philip Withnall 2010 + * + * GData Client is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * GData Client is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with GData Client. If not, see . + */ + +#ifndef GDATA_GCONTACT_CALENDAR_H +#define GDATA_GCONTACT_CALENDAR_H + +#include +#include + +#include + +G_BEGIN_DECLS + +/** + * GDATA_GCONTACT_CALENDAR_WORK: + * + * The relation type URI for a contact's work calendar. + * + * For more information, see the + * gContact specification. + * + * Since: 0.7.0 + */ +#define GDATA_GCONTACT_CALENDAR_WORK "work" + +/** + * GDATA_GCONTACT_CALENDAR_HOME: + * + * The relation type URI for a contact's home calendar. + * + * For more information, see the + * gContact specification. + * + * Since: 0.7.0 + */ +#define GDATA_GCONTACT_CALENDAR_HOME "home" + +/** + * GDATA_GCONTACT_CALENDAR_FREE_BUSY: + * + * The relation type URI for a contact's free/busy calendar. + * + * For more information, see the + * gContact specification. + * + * Since: 0.7.0 + */ +#define GDATA_GCONTACT_CALENDAR_FREE_BUSY "free-busy" + +#define GDATA_TYPE_GCONTACT_CALENDAR (gdata_gcontact_calendar_get_type ()) +#define GDATA_GCONTACT_CALENDAR(o) (G_TYPE_CHECK_INSTANCE_CAST ((o), GDATA_TYPE_GCONTACT_CALENDAR, GDataGContactCalendar)) +#define GDATA_GCONTACT_CALENDAR_CLASS(k) (G_TYPE_CHECK_CLASS_CAST((k), GDATA_TYPE_GCONTACT_CALENDAR, GDataGContactCalendarClass)) +#define GDATA_IS_GCONTACT_CALENDAR(o) (G_TYPE_CHECK_INSTANCE_TYPE ((o), GDATA_TYPE_GCONTACT_CALENDAR)) +#define GDATA_IS_GCONTACT_CALENDAR_CLASS(k) (G_TYPE_CHECK_CLASS_TYPE ((k), GDATA_TYPE_GCONTACT_CALENDAR)) +#define GDATA_GCONTACT_CALENDAR_GET_CLASS(o) (G_TYPE_INSTANCE_GET_CLASS ((o), GDATA_TYPE_GCONTACT_CALENDAR, GDataGContactCalendarClass)) + +typedef struct _GDataGContactCalendarPrivate GDataGContactCalendarPrivate; + +/** + * GDataGContactCalendar: + * + * All the fields in the #GDataGContactCalendar structure are private and should never be accessed directly. + * + * Since: 0.7.0 + */ +typedef struct { + GDataParsable parent; + GDataGContactCalendarPrivate *priv; +} GDataGContactCalendar; + +/** + * GDataGContactCalendarClass: + * + * All the fields in the #GDataGContactCalendarClass structure are private and should never be accessed directly. + * + * Since: 0.7.0 + */ +typedef struct { + /*< private >*/ + GDataParsableClass parent; + + /*< private >*/ + /* Padding for future expansion */ + void (*_g_reserved0) (void); + void (*_g_reserved1) (void); +} GDataGContactCalendarClass; + +GType gdata_gcontact_calendar_get_type (void) G_GNUC_CONST; + +GDataGContactCalendar *gdata_gcontact_calendar_new (const gchar *uri, const gchar *relation_type, + const gchar *label, gboolean is_primary) G_GNUC_WARN_UNUSED_RESULT G_GNUC_MALLOC; + +const gchar *gdata_gcontact_calendar_get_uri (GDataGContactCalendar *self) G_GNUC_PURE; +void gdata_gcontact_calendar_set_uri (GDataGContactCalendar *self, const gchar *uri); + +const gchar *gdata_gcontact_calendar_get_relation_type (GDataGContactCalendar *self) G_GNUC_PURE; +void gdata_gcontact_calendar_set_relation_type (GDataGContactCalendar *self, const gchar *relation_type); + +const gchar *gdata_gcontact_calendar_get_label (GDataGContactCalendar *self) G_GNUC_PURE; +void gdata_gcontact_calendar_set_label (GDataGContactCalendar *self, const gchar *label); + +gboolean gdata_gcontact_calendar_is_primary (GDataGContactCalendar *self) G_GNUC_PURE; +void gdata_gcontact_calendar_set_is_primary (GDataGContactCalendar *self, gboolean is_primary); + +G_END_DECLS + +#endif /* !GDATA_GCONTACT_CALENDAR_H */ diff --git a/gdata/gcontact/gdata-gcontact-event.c b/gdata/gcontact/gdata-gcontact-event.c new file mode 100644 index 0000000..6ea8257 --- /dev/null +++ b/gdata/gcontact/gdata-gcontact-event.c @@ -0,0 +1,446 @@ +/* -*- Mode: C; indent-tabs-mode: t; c-basic-offset: 8; tab-width: 8 -*- */ +/* + * GData Client + * Copyright (C) Philip Withnall 2010 + * + * GData Client is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * GData Client is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with GData Client. If not, see . + */ + +/** + * SECTION:gdata-gcontact-event + * @short_description: gContact event element + * @stability: Stable + * @include: gdata/gcontact/gdata-gcontact-event.h + * + * #GDataGContactEvent represents a "event" element from the + * gContact specification. + * + * Since: 0.7.0 + */ + +#include +#include +#include + +#include "gdata-gcontact-event.h" +#include "gdata-parsable.h" +#include "gdata-parser.h" + +static void gdata_gcontact_event_finalize (GObject *object); +static void gdata_gcontact_event_get_property (GObject *object, guint property_id, GValue *value, GParamSpec *pspec); +static void gdata_gcontact_event_set_property (GObject *object, guint property_id, const GValue *value, GParamSpec *pspec); +static gboolean pre_parse_xml (GDataParsable *parsable, xmlDoc *doc, xmlNode *root_node, gpointer user_data, GError **error); +static gboolean parse_xml (GDataParsable *parsable, xmlDoc *doc, xmlNode *root_node, gpointer user_data, GError **error); +static gboolean post_parse_xml (GDataParsable *parsable, gpointer user_data, GError **error); +static void pre_get_xml (GDataParsable *parsable, GString *xml_string); +static void get_xml (GDataParsable *parsable, GString *xml_string); +static void get_namespaces (GDataParsable *parsable, GHashTable *namespaces); + +struct _GDataGContactEventPrivate { + GDate date; + gchar *relation_type; + gchar *label; +}; + +enum { + PROP_DATE = 1, + PROP_RELATION_TYPE, + PROP_LABEL +}; + +G_DEFINE_TYPE (GDataGContactEvent, gdata_gcontact_event, GDATA_TYPE_PARSABLE) + +static void +gdata_gcontact_event_class_init (GDataGContactEventClass *klass) +{ + GObjectClass *gobject_class = G_OBJECT_CLASS (klass); + GDataParsableClass *parsable_class = GDATA_PARSABLE_CLASS (klass); + + g_type_class_add_private (klass, sizeof (GDataGContactEventPrivate)); + + gobject_class->get_property = gdata_gcontact_event_get_property; + gobject_class->set_property = gdata_gcontact_event_set_property; + gobject_class->finalize = gdata_gcontact_event_finalize; + + parsable_class->pre_parse_xml = pre_parse_xml; + parsable_class->parse_xml = parse_xml; + parsable_class->post_parse_xml = post_parse_xml; + parsable_class->pre_get_xml = pre_get_xml; + parsable_class->get_xml = get_xml; + parsable_class->get_namespaces = get_namespaces; + parsable_class->element_name = "event"; + parsable_class->element_namespace = "gContact"; + + /** + * GDataGContactEvent:date: + * + * The date of the event. + * + * For more information, see the + * GContact specification. + * + * Since: 0.7.0 + */ + g_object_class_install_property (gobject_class, PROP_DATE, + g_param_spec_boxed ("date", + "Date", "The date of the event.", + G_TYPE_DATE, + G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)); + + /** + * GDataGContactEvent:relation-type: + * + * A programmatic value that identifies the type of event. It is mutually exclusive with #GDataGContactEvent:label. + * Examples are %GDATA_GCONTACT_EVENT_ANNIVERSARY or %GDATA_GCONTACT_EVENT_OTHER. + * + * For more information, see the + * gContact specification. + * + * Since: 0.7.0 + */ + g_object_class_install_property (gobject_class, PROP_RELATION_TYPE, + g_param_spec_string ("relation-type", + "Relation type", "A programmatic value that identifies the type of website.", + NULL, + G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)); + + /** + * GDataGContactEvent:label: + * + * A simple string value used to name this event. It is mutually exclusive with #GDataGContactEvent:relation-type. + * It allows UIs to display a label such as "Wedding anniversary". + * + * For more information, see the + * gContact specification. + * + * Since: 0.7.0 + */ + g_object_class_install_property (gobject_class, PROP_LABEL, + g_param_spec_string ("label", + "Label", "A simple string value used to name this event.", + NULL, + G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)); +} + +static void +gdata_gcontact_event_init (GDataGContactEvent *self) +{ + self->priv = G_TYPE_INSTANCE_GET_PRIVATE (self, GDATA_TYPE_GCONTACT_EVENT, GDataGContactEventPrivate); + + /* Clear the date to an invalid but sane value */ + g_date_clear (&(self->priv->date), 1); +} + +static void +gdata_gcontact_event_finalize (GObject *object) +{ + GDataGContactEventPrivate *priv = GDATA_GCONTACT_EVENT (object)->priv; + + g_free (priv->relation_type); + g_free (priv->label); + + /* Chain up to the parent class */ + G_OBJECT_CLASS (gdata_gcontact_event_parent_class)->finalize (object); +} + +static void +gdata_gcontact_event_get_property (GObject *object, guint property_id, GValue *value, GParamSpec *pspec) +{ + GDataGContactEventPrivate *priv = GDATA_GCONTACT_EVENT (object)->priv; + + switch (property_id) { + case PROP_DATE: + g_value_set_boxed (value, &(priv->date)); + break; + case PROP_RELATION_TYPE: + g_value_set_string (value, priv->relation_type); + break; + case PROP_LABEL: + g_value_set_string (value, priv->label); + break; + default: + /* We don't have any other property... */ + G_OBJECT_WARN_INVALID_PROPERTY_ID (object, property_id, pspec); + break; + } +} + +static void +gdata_gcontact_event_set_property (GObject *object, guint property_id, const GValue *value, GParamSpec *pspec) +{ + GDataGContactEvent *self = GDATA_GCONTACT_EVENT (object); + + switch (property_id) { + case PROP_DATE: + gdata_gcontact_event_set_date (self, g_value_get_boxed (value)); + break; + case PROP_RELATION_TYPE: + gdata_gcontact_event_set_relation_type (self, g_value_get_string (value)); + break; + case PROP_LABEL: + gdata_gcontact_event_set_label (self, g_value_get_string (value)); + break; + default: + /* We don't have any other property... */ + G_OBJECT_WARN_INVALID_PROPERTY_ID (object, property_id, pspec); + break; + } +} + +static gboolean +pre_parse_xml (GDataParsable *parsable, xmlDoc *doc, xmlNode *root_node, gpointer user_data, GError **error) +{ + xmlChar *rel, *label; + GDataGContactEventPrivate *priv = GDATA_GCONTACT_EVENT (parsable)->priv; + + rel = xmlGetProp (root_node, (xmlChar*) "rel"); + label = xmlGetProp (root_node, (xmlChar*) "label"); + if ((rel == NULL || *rel == '\0') && (label == NULL || *label == '\0')) { + xmlFree (rel); + xmlFree (label); + return gdata_parser_error_required_property_missing (root_node, "rel", error); + } else if (rel != NULL && label != NULL) { + /* Can't have both set at once */ + xmlFree (rel); + xmlFree (label); + return gdata_parser_error_mutexed_properties (root_node, "rel", "label", error); + } + + priv->relation_type = (gchar*) rel; + priv->label = (gchar*) label; + + return TRUE; +} + +static gboolean +parse_xml (GDataParsable *parsable, xmlDoc *doc, xmlNode *node, gpointer user_data, GError **error) +{ + GDataGContactEventPrivate *priv = GDATA_GCONTACT_EVENT (parsable)->priv; + + if (gdata_parser_is_namespace (node, "http://schemas.google.com/g/2005") == TRUE && xmlStrcmp (node->name, (xmlChar*) "when") == 0) { + xmlChar *start_time; + guint year, month, day; + + /* gd:when; note we don't use GDataGDWhen here because gContact:event only uses a limited subset + * of gd:when (i.e. only the startTime property in date format) */ + if (g_date_valid (&(priv->date)) == TRUE) + return gdata_parser_error_duplicate_element (node, error); + + start_time = xmlGetProp (node, (xmlChar*) "startTime"); + if (start_time == NULL) + return gdata_parser_error_required_property_missing (node, "startTime", error); + + /* Try parsing the date format: YYYY-MM-DD */ + if (strlen ((char*) start_time) == 10 && + sscanf ((char*) start_time, "%4u-%2u-%2u", &year, &month, &day) == 3 && g_date_valid_dmy (day, month, year) == TRUE) { + /* Store the values in the GDate */ + g_date_set_dmy (&(priv->date), day, month, year); + xmlFree (start_time); + } else { + /* Parsing failed */ + gdata_parser_error_not_iso8601_format (node, (gchar*) start_time, error); + xmlFree (start_time); + return FALSE; + } + + return TRUE; + } + + return GDATA_PARSABLE_CLASS (gdata_gcontact_event_parent_class)->parse_xml (parsable, doc, node, user_data, error); +} + +static gboolean +post_parse_xml (GDataParsable *parsable, gpointer user_data, GError **error) +{ + GDataGContactEventPrivate *priv = GDATA_GCONTACT_EVENT (parsable)->priv; + + /* Check for missing required elements */ + if (g_date_valid (&(priv->date)) == FALSE) + return gdata_parser_error_required_element_missing ("gd:when", "gContact:event", error); + + return TRUE; +} + +static void +pre_get_xml (GDataParsable *parsable, GString *xml_string) +{ + GDataGContactEventPrivate *priv = GDATA_GCONTACT_EVENT (parsable)->priv; + + if (priv->relation_type != NULL) + gdata_parser_string_append_escaped (xml_string, " rel='", priv->relation_type, "'"); + else if (priv->label != NULL) + gdata_parser_string_append_escaped (xml_string, " label='", priv->label, "'"); + else + g_assert_not_reached (); +} + +static void +get_xml (GDataParsable *parsable, GString *xml_string) +{ + GDataGContactEventPrivate *priv = GDATA_GCONTACT_EVENT (parsable)->priv; + + g_string_append_printf (xml_string, "", + g_date_get_year (&(priv->date)), + g_date_get_month (&(priv->date)), + g_date_get_day (&(priv->date))); +} + +static void +get_namespaces (GDataParsable *parsable, GHashTable *namespaces) +{ + g_hash_table_insert (namespaces, (gchar*) "gd", (gchar*) "http://schemas.google.com/g/2005"); + g_hash_table_insert (namespaces, (gchar*) "gContact", (gchar*) "http://schemas.google.com/contact/2008"); +} + +/** + * gdata_gcontact_event_new: + * @date: the date of the event + * @relation_type: (allow-none): the relationship between the event and its owner, or %NULL + * @label: (allow-none): a human-readable label for the event, or %NULL + * + * Creates a new #GDataGContactEvent. More information is available in the gContact specification. + * + * Exactly one of @relation_type and @label should be provided; the other must be %NULL. + * + * Return value: a new #GDataGContactEvent; unref with g_object_unref() + * + * Since: 0.7.0 + */ +GDataGContactEvent * +gdata_gcontact_event_new (const GDate *date, const gchar *relation_type, const gchar *label) +{ + g_return_val_if_fail (date != NULL && g_date_valid (date) == TRUE, NULL); + g_return_val_if_fail ((relation_type != NULL && *relation_type != '\0' && label == NULL) || + (relation_type == NULL && label != NULL && *label != '\0'), NULL); + + return g_object_new (GDATA_TYPE_GCONTACT_EVENT, "date", date, "relation-type", relation_type, "label", label, NULL); +} + +/** + * gdata_gcontact_event_get_date: + * @self: a #GDataGContactEvent + * @date: (out caller-allocates): return location for the date of the event + * + * Gets the #GDataGContactEvent:date property. + * + * Since: 0.7.0 + */ +void +gdata_gcontact_event_get_date (GDataGContactEvent *self, GDate *date) +{ + g_return_if_fail (GDATA_IS_GCONTACT_EVENT (self)); + g_return_if_fail (date != NULL); + *date = self->priv->date; +} + +/** + * gdata_gcontact_event_set_date: + * @self: a #GDataGContactEvent + * @date: the new date for the event + * + * Sets the #GDataGContactEvent:date property to @date. + * + * Since: 0.7.0 + */ +void +gdata_gcontact_event_set_date (GDataGContactEvent *self, const GDate *date) +{ + g_return_if_fail (GDATA_IS_GCONTACT_EVENT (self)); + g_return_if_fail (date != NULL && g_date_valid (date) == TRUE); + + self->priv->date = *date; + g_object_notify (G_OBJECT (self), "date"); +} + +/** + * gdata_gcontact_event_get_relation_type: + * @self: a #GDataGContactEvent + * + * Gets the #GDataGContactEvent:relation-type property. + * + * Return value: the event's relation type, or %NULL + * + * Since: 0.7.0 + */ +const gchar * +gdata_gcontact_event_get_relation_type (GDataGContactEvent *self) +{ + g_return_val_if_fail (GDATA_IS_GCONTACT_EVENT (self), NULL); + return self->priv->relation_type; +} + +/** + * gdata_gcontact_event_set_relation_type: + * @self: a #GDataGContactEvent + * @relation_type: (allow-none): the new relation type for the event, or %NULL + * + * Sets the #GDataGContactEvent:relation-type property to @relation_type + * such as %GDATA_GCONTACT_EVENT_ANNIVERSARY or %GDATA_GCONTACT_EVENT_OTHER. + * + * If @relation_type is %NULL, the relation type will be unset. When the #GDataGContactEvent is used in a query, however, + * exactly one of #GDataGContactEvent:relation-type and #GDataGContactEvent:label must be %NULL. + * + * Since: 0.7.0 + */ +void +gdata_gcontact_event_set_relation_type (GDataGContactEvent *self, const gchar *relation_type) +{ + g_return_if_fail (GDATA_IS_GCONTACT_EVENT (self)); + g_return_if_fail (relation_type == NULL || *relation_type != '\0'); + + g_free (self->priv->relation_type); + self->priv->relation_type = g_strdup (relation_type); + g_object_notify (G_OBJECT (self), "relation-type"); +} + +/** + * gdata_gcontact_event_get_label: + * @self: a #GDataGContactEvent + * + * Gets the #GDataGContactEvent:label property. + * + * Return value: the event's label, or %NULL + * + * Since: 0.7.0 + */ +const gchar * +gdata_gcontact_event_get_label (GDataGContactEvent *self) +{ + g_return_val_if_fail (GDATA_IS_GCONTACT_EVENT (self), NULL); + return self->priv->label; +} + +/** + * gdata_gcontact_event_set_label: + * @self: a #GDataGContactEvent + * @label: (allow-none): the new label for the event, or %NULL + * + * Sets the #GDataGContactEvent:label property to @label. + * + * If @label is %NULL, the label will be unset. When the #GDataGContactEvent is used in a query, however, + * exactly one of #GDataGContactEvent:relation-type and #GDataGContactEvent:label must be %NULL. + * + * Since: 0.7.0 + */ +void +gdata_gcontact_event_set_label (GDataGContactEvent *self, const gchar *label) +{ + g_return_if_fail (GDATA_IS_GCONTACT_EVENT (self)); + g_return_if_fail (label == NULL || *label != '\0'); + + g_free (self->priv->label); + self->priv->label = g_strdup (label); + g_object_notify (G_OBJECT (self), "label"); +} diff --git a/gdata/gcontact/gdata-gcontact-event.h b/gdata/gcontact/gdata-gcontact-event.h new file mode 100644 index 0000000..d1c6875 --- /dev/null +++ b/gdata/gcontact/gdata-gcontact-event.h @@ -0,0 +1,108 @@ +/* -*- Mode: C; indent-tabs-mode: t; c-basic-offset: 8; tab-width: 8 -*- */ +/* + * GData Client + * Copyright (C) Philip Withnall 2010 + * + * GData Client is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * GData Client is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with GData Client. If not, see . + */ + +#ifndef GDATA_GCONTACT_EVENT_H +#define GDATA_GCONTACT_EVENT_H + +#include +#include + +#include + +G_BEGIN_DECLS + +/** + * GDATA_GCONTACT_EVENT_ANNIVERSARY: + * + * The relation type URI for an anniversary event. + * + * For more information, see the + * gContact specification. + * + * Since: 0.7.0 + */ +#define GDATA_GCONTACT_EVENT_ANNIVERSARY "anniversary" + +/** + * GDATA_GCONTACT_EVENT_OTHER: + * + * The relation type URI for a miscellaneous event. + * + * For more information, see the + * gContact specification. + * + * Since: 0.7.0 + */ +#define GDATA_GCONTACT_EVENT_OTHER "other" + +#define GDATA_TYPE_GCONTACT_EVENT (gdata_gcontact_event_get_type ()) +#define GDATA_GCONTACT_EVENT(o) (G_TYPE_CHECK_INSTANCE_CAST ((o), GDATA_TYPE_GCONTACT_EVENT, GDataGContactEvent)) +#define GDATA_GCONTACT_EVENT_CLASS(k) (G_TYPE_CHECK_CLASS_CAST((k), GDATA_TYPE_GCONTACT_EVENT, GDataGContactEventClass)) +#define GDATA_IS_GCONTACT_EVENT(o) (G_TYPE_CHECK_INSTANCE_TYPE ((o), GDATA_TYPE_GCONTACT_EVENT)) +#define GDATA_IS_GCONTACT_EVENT_CLASS(k) (G_TYPE_CHECK_CLASS_TYPE ((k), GDATA_TYPE_GCONTACT_EVENT)) +#define GDATA_GCONTACT_EVENT_GET_CLASS(o) (G_TYPE_INSTANCE_GET_CLASS ((o), GDATA_TYPE_GCONTACT_EVENT, GDataGContactEventClass)) + +typedef struct _GDataGContactEventPrivate GDataGContactEventPrivate; + +/** + * GDataGContactEvent: + * + * All the fields in the #GDataGContactEvent structure are private and should never be accessed directly. + * + * Since: 0.7.0 + */ +typedef struct { + GDataParsable parent; + GDataGContactEventPrivate *priv; +} GDataGContactEvent; + +/** + * GDataGContactEventClass: + * + * All the fields in the #GDataGContactEventClass structure are private and should never be accessed directly. + * + * Since: 0.7.0 + */ +typedef struct { + /*< private >*/ + GDataParsableClass parent; + + /*< private >*/ + /* Padding for future expansion */ + void (*_g_reserved0) (void); + void (*_g_reserved1) (void); +} GDataGContactEventClass; + +GType gdata_gcontact_event_get_type (void) G_GNUC_CONST; + +GDataGContactEvent *gdata_gcontact_event_new (const GDate *date, const gchar *relation_type, + const gchar *label) G_GNUC_WARN_UNUSED_RESULT G_GNUC_MALLOC; + +void gdata_gcontact_event_get_date (GDataGContactEvent *self, GDate *date); +void gdata_gcontact_event_set_date (GDataGContactEvent *self, const GDate *date); + +const gchar *gdata_gcontact_event_get_relation_type (GDataGContactEvent *self) G_GNUC_PURE; +void gdata_gcontact_event_set_relation_type (GDataGContactEvent *self, const gchar *relation_type); + +const gchar *gdata_gcontact_event_get_label (GDataGContactEvent *self) G_GNUC_PURE; +void gdata_gcontact_event_set_label (GDataGContactEvent *self, const gchar *label); + +G_END_DECLS + +#endif /* !GDATA_GCONTACT_EVENT_H */ diff --git a/gdata/gcontact/gdata-gcontact-external-id.c b/gdata/gcontact/gdata-gcontact-external-id.c new file mode 100644 index 0000000..3da3ef0 --- /dev/null +++ b/gdata/gcontact/gdata-gcontact-external-id.c @@ -0,0 +1,406 @@ +/* -*- Mode: C; indent-tabs-mode: t; c-basic-offset: 8; tab-width: 8 -*- */ +/* + * GData Client + * Copyright (C) Philip Withnall 2010 + * + * GData Client is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * GData Client is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with GData Client. If not, see . + */ + +/** + * SECTION:gdata-gcontact-external-id + * @short_description: gContact externalId element + * @stability: Stable + * @include: gdata/gcontact/gdata-gcontact-external-id.h + * + * #GDataGContactExternalID represents an "externalId" element from the + * gContact specification. + * + * Since: 0.7.0 + */ + +#include +#include + +#include "gdata-gcontact-external-id.h" +#include "gdata-parsable.h" +#include "gdata-parser.h" +#include "gdata-comparable.h" + +static void gdata_gcontact_external_id_comparable_init (GDataComparableIface *iface); +static void gdata_gcontact_external_id_finalize (GObject *object); +static void gdata_gcontact_external_id_get_property (GObject *object, guint property_id, GValue *value, GParamSpec *pspec); +static void gdata_gcontact_external_id_set_property (GObject *object, guint property_id, const GValue *value, GParamSpec *pspec); +static gboolean pre_parse_xml (GDataParsable *parsable, xmlDoc *doc, xmlNode *root_node, gpointer user_data, GError **error); +static void pre_get_xml (GDataParsable *parsable, GString *xml_string); +static void get_namespaces (GDataParsable *parsable, GHashTable *namespaces); + +struct _GDataGContactExternalIDPrivate { + gchar *value; + gchar *relation_type; + gchar *label; +}; + +enum { + PROP_VALUE = 1, + PROP_RELATION_TYPE, + PROP_LABEL +}; + +G_DEFINE_TYPE_WITH_CODE (GDataGContactExternalID, gdata_gcontact_external_id, GDATA_TYPE_PARSABLE, + G_IMPLEMENT_INTERFACE (GDATA_TYPE_COMPARABLE, gdata_gcontact_external_id_comparable_init)) + +static void +gdata_gcontact_external_id_class_init (GDataGContactExternalIDClass *klass) +{ + GObjectClass *gobject_class = G_OBJECT_CLASS (klass); + GDataParsableClass *parsable_class = GDATA_PARSABLE_CLASS (klass); + + g_type_class_add_private (klass, sizeof (GDataGContactExternalIDPrivate)); + + gobject_class->get_property = gdata_gcontact_external_id_get_property; + gobject_class->set_property = gdata_gcontact_external_id_set_property; + gobject_class->finalize = gdata_gcontact_external_id_finalize; + + parsable_class->pre_parse_xml = pre_parse_xml; + parsable_class->pre_get_xml = pre_get_xml; + parsable_class->get_namespaces = get_namespaces; + parsable_class->element_name = "externalId"; + parsable_class->element_namespace = "gContact"; + + /** + * GDataGContactExternalID:value: + * + * The value of the external ID. + * + * For more information, see the + * gContact specification. + * + * Since: 0.7.0 + */ + g_object_class_install_property (gobject_class, PROP_VALUE, + g_param_spec_string ("value", + "Value", "The value of the external ID.", + NULL, + G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)); + + /** + * GDataGContactExternalID:relation-type: + * + * A programmatic value that identifies the type of external ID. It is mutually exclusive with #GDataGContactExternalID:label. + * Examples are %GDATA_GCONTACT_EXTERNAL_ID_NETWORK or %GDATA_GCONTACT_EXTERNAL_ID_ACCOUNT. + * + * For more information, see the + * gContact specification. + * + * Since: 0.7.0 + */ + g_object_class_install_property (gobject_class, PROP_RELATION_TYPE, + g_param_spec_string ("relation-type", + "Relation type", "A programmatic value that identifies the type of external ID.", + NULL, + G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)); + + /** + * GDataGContactExternalID:label: + * + * A free-form string that identifies the type of external ID. It is mutually exclusive with #GDataGContactExternalID:relation-type. + * + * For more information, see the + * gContact specification. + * + * Since: 0.7.0 + */ + g_object_class_install_property (gobject_class, PROP_LABEL, + g_param_spec_string ("label", + "Label", "A free-form string that identifies the type of external ID.", + NULL, + G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)); +} + +static gint +compare_with (GDataComparable *self, GDataComparable *other) +{ + GDataGContactExternalIDPrivate *a = ((GDataGContactExternalID*) self)->priv, *b = ((GDataGContactExternalID*) other)->priv; + + if (g_strcmp0 (a->value, b->value) == 0 && g_strcmp0 (a->relation_type, b->relation_type) == 0 && g_strcmp0 (a->label, b->label) == 0) + return 0; + return 1; +} + +static void +gdata_gcontact_external_id_comparable_init (GDataComparableIface *iface) +{ + iface->compare_with = compare_with; +} + +static void +gdata_gcontact_external_id_init (GDataGContactExternalID *self) +{ + self->priv = G_TYPE_INSTANCE_GET_PRIVATE (self, GDATA_TYPE_GCONTACT_EXTERNAL_ID, GDataGContactExternalIDPrivate); +} + +static void +gdata_gcontact_external_id_finalize (GObject *object) +{ + GDataGContactExternalIDPrivate *priv = GDATA_GCONTACT_EXTERNAL_ID (object)->priv; + + g_free (priv->value); + g_free (priv->relation_type); + g_free (priv->label); + + /* Chain up to the parent class */ + G_OBJECT_CLASS (gdata_gcontact_external_id_parent_class)->finalize (object); +} + +static void +gdata_gcontact_external_id_get_property (GObject *object, guint property_id, GValue *value, GParamSpec *pspec) +{ + GDataGContactExternalIDPrivate *priv = GDATA_GCONTACT_EXTERNAL_ID (object)->priv; + + switch (property_id) { + case PROP_VALUE: + g_value_set_string (value, priv->value); + break; + case PROP_RELATION_TYPE: + g_value_set_string (value, priv->relation_type); + break; + case PROP_LABEL: + g_value_set_string (value, priv->label); + break; + default: + /* We don't have any other property... */ + G_OBJECT_WARN_INVALID_PROPERTY_ID (object, property_id, pspec); + break; + } +} + +static void +gdata_gcontact_external_id_set_property (GObject *object, guint property_id, const GValue *value, GParamSpec *pspec) +{ + GDataGContactExternalID *self = GDATA_GCONTACT_EXTERNAL_ID (object); + + switch (property_id) { + case PROP_VALUE: + gdata_gcontact_external_id_set_value (self, g_value_get_string (value)); + break; + case PROP_RELATION_TYPE: + gdata_gcontact_external_id_set_relation_type (self, g_value_get_string (value)); + break; + case PROP_LABEL: + gdata_gcontact_external_id_set_label (self, g_value_get_string (value)); + break; + default: + /* We don't have any other property... */ + G_OBJECT_WARN_INVALID_PROPERTY_ID (object, property_id, pspec); + break; + } +} + +static gboolean +pre_parse_xml (GDataParsable *parsable, xmlDoc *doc, xmlNode *root_node, gpointer user_data, GError **error) +{ + xmlChar *value, *rel, *label; + GDataGContactExternalIDPrivate *priv = GDATA_GCONTACT_EXTERNAL_ID (parsable)->priv; + + value = xmlGetProp (root_node, (xmlChar*) "value"); + if (value == NULL) { + xmlFree (value); + return gdata_parser_error_required_property_missing (root_node, "value", error); + } + + rel = xmlGetProp (root_node, (xmlChar*) "rel"); + label = xmlGetProp (root_node, (xmlChar*) "label"); + if ((rel == NULL || *rel == '\0') && (label == NULL || *label == '\0')) { + xmlFree (value); + xmlFree (rel); + xmlFree (label); + return gdata_parser_error_required_property_missing (root_node, "rel", error); + } else if (rel != NULL && label != NULL) { + /* Can't have both set at once */ + xmlFree (value); + xmlFree (rel); + xmlFree (label); + return gdata_parser_error_mutexed_properties (root_node, "rel", "label", error); + } + + priv->value = (gchar*) value; + priv->relation_type = (gchar*) rel; + priv->label = (gchar*) label; + + return TRUE; +} + +static void +pre_get_xml (GDataParsable *parsable, GString *xml_string) +{ + GDataGContactExternalIDPrivate *priv = GDATA_GCONTACT_EXTERNAL_ID (parsable)->priv; + + gdata_parser_string_append_escaped (xml_string, " value='", priv->value, "'"); + + if (priv->relation_type != NULL) + gdata_parser_string_append_escaped (xml_string, " rel='", priv->relation_type, "'"); + else if (priv->label != NULL) + gdata_parser_string_append_escaped (xml_string, " label='", priv->label, "'"); + else + g_assert_not_reached (); +} + +static void +get_namespaces (GDataParsable *parsable, GHashTable *namespaces) +{ + g_hash_table_insert (namespaces, (gchar*) "gContact", (gchar*) "http://schemas.google.com/contact/2008"); +} + +/** + * gdata_gcontact_external_id_new: + * @value: the value of the external ID + * @relation_type: (allow-none): the type of external ID, or %NULL + * @label: (allow-none): a free-form label for the external ID, or %NULL + * + * Creates a new #GDataGContactExternalID. More information is available in the gContact specification. + * + * Exactly one of @relation_type and @label should be provided; the other must be %NULL. + * + * Return value: a new #GDataGContactExternalID; unref with g_object_unref() + * + * Since: 0.7.0 + */ +GDataGContactExternalID * +gdata_gcontact_external_id_new (const gchar *value, const gchar *relation_type, const gchar *label) +{ + g_return_val_if_fail (value != NULL, NULL); + g_return_val_if_fail ((relation_type != NULL && *relation_type != '\0' && label == NULL) || + (relation_type == NULL && label != NULL && *label != '\0'), NULL); + + return g_object_new (GDATA_TYPE_GCONTACT_EXTERNAL_ID, "value", value, "relation-type", relation_type, "label", label, NULL); +} + +/** + * gdata_gcontact_external_id_get_value: + * @self: a #GDataGContactExternalID + * + * Gets the #GDataGContactExternalID:value property. + * + * Return value: the external ID's value + * + * Since: 0.7.0 + */ +const gchar * +gdata_gcontact_external_id_get_value (GDataGContactExternalID *self) +{ + g_return_val_if_fail (GDATA_IS_GCONTACT_EXTERNAL_ID (self), NULL); + return self->priv->value; +} + +/** + * gdata_gcontact_external_id_set_value: + * @self: a #GDataGContactExternalID + * @value: the new value for the external ID + * + * Sets the #GDataGContactExternalID:value property to @value. + * + * Since: 0.7.0 + */ +void +gdata_gcontact_external_id_set_value (GDataGContactExternalID *self, const gchar *value) +{ + g_return_if_fail (GDATA_IS_GCONTACT_EXTERNAL_ID (self)); + g_return_if_fail (value != NULL); + + g_free (self->priv->value); + self->priv->value = g_strdup (value); + g_object_notify (G_OBJECT (self), "value"); +} + +/** + * gdata_gcontact_external_id_get_relation_type: + * @self: a #GDataGContactExternalID + * + * Gets the #GDataGContactExternalID:relation-type property. + * + * Return value: the type of the relation, or %NULL + * + * Since: 0.7.0 + */ +const gchar * +gdata_gcontact_external_id_get_relation_type (GDataGContactExternalID *self) +{ + g_return_val_if_fail (GDATA_IS_GCONTACT_EXTERNAL_ID (self), NULL); + return self->priv->relation_type; +} + +/** + * gdata_gcontact_external_id_set_relation_type: + * @self: a #GDataGContactExternalID + * @relation_type: (allow-none): the new type for the external ID, or %NULL + * + * Sets the #GDataGContactExternalID:relation-type property to @relation_type, + * such as %GDATA_GCONTACT_EXTERNAL_ID_NETWORK or %GDATA_GCONTACT_EXTERNAL_ID_ACCOUNT. + * + * If @relation_type is %NULL, the relation type will be unset. When the #GDataGContactExternalID is used in a query, however, + * exactly one of #GDataGContactExternalID:relation-type and #GDataGContactExternalID:label must be %NULL. + * + * Since: 0.7.0 + */ +void +gdata_gcontact_external_id_set_relation_type (GDataGContactExternalID *self, const gchar *relation_type) +{ + g_return_if_fail (GDATA_IS_GCONTACT_EXTERNAL_ID (self)); + g_return_if_fail (relation_type == NULL || *relation_type != '\0'); + + g_free (self->priv->relation_type); + self->priv->relation_type = g_strdup (relation_type); + g_object_notify (G_OBJECT (self), "relation-type"); +} + +/** + * gdata_gcontact_external_id_get_label: + * @self: a #GDataGContactExternalID + * + * Gets the #GDataGContactExternalID:label property. + * + * Return value: a free-form label for the external ID, or %NULL + * + * Since: 0.7.0 + */ +const gchar * +gdata_gcontact_external_id_get_label (GDataGContactExternalID *self) +{ + g_return_val_if_fail (GDATA_IS_GCONTACT_EXTERNAL_ID (self), NULL); + return self->priv->label; +} + +/** + * gdata_gcontact_external_id_set_label: + * @self: a #GDataGContactExternalID + * @label: (allow-none): the new free-form label for the external ID, or %NULL + * + * Sets the #GDataGContactExternalID:label property to @label. + * + * If @label is %NULL, the label will be unset. When the #GDataGContactExternalID is used in a query, however, + * exactly one of #GDataGContactExternalID:relation-type and #GDataGContactExternalID:label must be %NULL. + * + * Since: 0.7.0 + */ +void +gdata_gcontact_external_id_set_label (GDataGContactExternalID *self, const gchar *label) +{ + g_return_if_fail (GDATA_IS_GCONTACT_EXTERNAL_ID (self)); + g_return_if_fail (label == NULL || *label != '\0'); + + g_free (self->priv->label); + self->priv->label = g_strdup (label); + g_object_notify (G_OBJECT (self), "label"); +} diff --git a/gdata/gcontact/gdata-gcontact-external-id.h b/gdata/gcontact/gdata-gcontact-external-id.h new file mode 100644 index 0000000..e0a35f4 --- /dev/null +++ b/gdata/gcontact/gdata-gcontact-external-id.h @@ -0,0 +1,132 @@ +/* -*- Mode: C; indent-tabs-mode: t; c-basic-offset: 8; tab-width: 8 -*- */ +/* + * GData Client + * Copyright (C) Philip Withnall 2010 + * + * GData Client is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * GData Client is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with GData Client. If not, see . + */ + +#ifndef GDATA_GCONTACT_EXTERNAL_ID_H +#define GDATA_GCONTACT_EXTERNAL_ID_H + +#include +#include + +#include + +G_BEGIN_DECLS + +/** + * GDATA_GCONTACT_EXTERNAL_ID_ACCOUNT: + * + * The relation type URI for an account number identifier. + * + * For more information, see the + * gContact specification. + * + * Since: 0.7.0 + */ +#define GDATA_GCONTACT_EXTERNAL_ID_ACCOUNT "account" + +/** + * GDATA_GCONTACT_EXTERNAL_ID_CUSTOMER: + * + * The relation type URI for a customer identifier. + * + * For more information, see the + * gContact specification. + * + * Since: 0.7.0 + */ +#define GDATA_GCONTACT_EXTERNAL_ID_CUSTOMER "customer" + +/** + * GDATA_GCONTACT_EXTERNAL_ID_NETWORK: + * + * The relation type URI for a network identifier. + * + * For more information, see the + * gContact specification. + * + * Since: 0.7.0 + */ +#define GDATA_GCONTACT_EXTERNAL_ID_NETWORK "network" + +/** + * GDATA_GCONTACT_EXTERNAL_ID_ORGANIZATION: + * + * The relation type URI for an identifier related to an organization the contact is associated with. + * + * For more information, see the + * gContact specification. + * + * Since: 0.7.0 + */ +#define GDATA_GCONTACT_EXTERNAL_ID_ORGANIZATION "organization" + +#define GDATA_TYPE_GCONTACT_EXTERNAL_ID (gdata_gcontact_external_id_get_type ()) +#define GDATA_GCONTACT_EXTERNAL_ID(o) (G_TYPE_CHECK_INSTANCE_CAST ((o), GDATA_TYPE_GCONTACT_EXTERNAL_ID, GDataGContactExternalID)) +#define GDATA_GCONTACT_EXTERNAL_ID_CLASS(k) (G_TYPE_CHECK_CLASS_CAST((k), GDATA_TYPE_GCONTACT_EXTERNAL_ID, GDataGContactExternalIDClass)) +#define GDATA_IS_GCONTACT_EXTERNAL_ID(o) (G_TYPE_CHECK_INSTANCE_TYPE ((o), GDATA_TYPE_GCONTACT_EXTERNAL_ID)) +#define GDATA_IS_GCONTACT_EXTERNAL_ID_CLASS(k) (G_TYPE_CHECK_CLASS_TYPE ((k), GDATA_TYPE_GCONTACT_EXTERNAL_ID)) +#define GDATA_GCONTACT_EXTERNAL_ID_GET_CLASS(o) (G_TYPE_INSTANCE_GET_CLASS ((o), GDATA_TYPE_GCONTACT_EXTERNAL_ID, GDataGContactExternalIDClass)) + +typedef struct _GDataGContactExternalIDPrivate GDataGContactExternalIDPrivate; + +/** + * GDataGContactExternalID: + * + * All the fields in the #GDataGContactExternalID structure are private and should never be accessed directly. + * + * Since: 0.7.0 + */ +typedef struct { + GDataParsable parent; + GDataGContactExternalIDPrivate *priv; +} GDataGContactExternalID; + +/** + * GDataGContactExternalIDClass: + * + * All the fields in the #GDataGContactExternalIDClass structure are private and should never be accessed directly. + * + * Since: 0.7.0 + */ +typedef struct { + /*< private >*/ + GDataParsableClass parent; + + /*< private >*/ + /* Padding for future expansion */ + void (*_g_reserved0) (void); + void (*_g_reserved1) (void); +} GDataGContactExternalIDClass; + +GType gdata_gcontact_external_id_get_type (void) G_GNUC_CONST; + +GDataGContactExternalID *gdata_gcontact_external_id_new (const gchar *value, const gchar *relation_type, + const gchar *label) G_GNUC_WARN_UNUSED_RESULT G_GNUC_MALLOC; + +const gchar *gdata_gcontact_external_id_get_value (GDataGContactExternalID *self) G_GNUC_PURE; +void gdata_gcontact_external_id_set_value (GDataGContactExternalID *self, const gchar *value); + +const gchar *gdata_gcontact_external_id_get_relation_type (GDataGContactExternalID *self) G_GNUC_PURE; +void gdata_gcontact_external_id_set_relation_type (GDataGContactExternalID *self, const gchar *relation_type); + +const gchar *gdata_gcontact_external_id_get_label (GDataGContactExternalID *self) G_GNUC_PURE; +void gdata_gcontact_external_id_set_label (GDataGContactExternalID *self, const gchar *label); + +G_END_DECLS + +#endif /* !GDATA_GCONTACT_EXTERNAL_ID_H */ diff --git a/gdata/gcontact/gdata-gcontact-jot.c b/gdata/gcontact/gdata-gcontact-jot.c new file mode 100644 index 0000000..0e58d1b --- /dev/null +++ b/gdata/gcontact/gdata-gcontact-jot.c @@ -0,0 +1,308 @@ +/* -*- Mode: C; indent-tabs-mode: t; c-basic-offset: 8; tab-width: 8 -*- */ +/* + * GData Client + * Copyright (C) Philip Withnall 2010 + * + * GData Client is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * GData Client is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with GData Client. If not, see . + */ + +/** + * SECTION:gdata-gcontact-jot + * @short_description: gContact jot element + * @stability: Stable + * @include: gdata/gcontact/gdata-gcontact-jot.h + * + * #GDataGContactJot represents a "jot" element from the + * gContact specification. + * + * Since: 0.7.0 + */ + +#include +#include + +#include "gdata-gcontact-jot.h" +#include "gdata-parsable.h" +#include "gdata-parser.h" + +static void gdata_gcontact_jot_finalize (GObject *object); +static void gdata_gcontact_jot_get_property (GObject *object, guint property_id, GValue *value, GParamSpec *pspec); +static void gdata_gcontact_jot_set_property (GObject *object, guint property_id, const GValue *value, GParamSpec *pspec); +static gboolean pre_parse_xml (GDataParsable *parsable, xmlDoc *doc, xmlNode *root_node, gpointer user_data, GError **error); +static gboolean parse_xml (GDataParsable *parsable, xmlDoc *doc, xmlNode *root_node, gpointer user_data, GError **error); +static void pre_get_xml (GDataParsable *parsable, GString *xml_string); +static void get_xml (GDataParsable *parsable, GString *xml_string); +static void get_namespaces (GDataParsable *parsable, GHashTable *namespaces); + +struct _GDataGContactJotPrivate { + gchar *content; + gchar *relation_type; +}; + +enum { + PROP_CONTENT = 1, + PROP_RELATION_TYPE +}; + +G_DEFINE_TYPE (GDataGContactJot, gdata_gcontact_jot, GDATA_TYPE_PARSABLE) + +static void +gdata_gcontact_jot_class_init (GDataGContactJotClass *klass) +{ + GObjectClass *gobject_class = G_OBJECT_CLASS (klass); + GDataParsableClass *parsable_class = GDATA_PARSABLE_CLASS (klass); + + g_type_class_add_private (klass, sizeof (GDataGContactJotPrivate)); + + gobject_class->get_property = gdata_gcontact_jot_get_property; + gobject_class->set_property = gdata_gcontact_jot_set_property; + gobject_class->finalize = gdata_gcontact_jot_finalize; + + parsable_class->pre_parse_xml = pre_parse_xml; + parsable_class->parse_xml = parse_xml; + parsable_class->pre_get_xml = pre_get_xml; + parsable_class->get_xml = get_xml; + parsable_class->get_namespaces = get_namespaces; + parsable_class->element_name = "jot"; + parsable_class->element_namespace = "gContact"; + + /** + * GDataGContactJot:content: + * + * The content of the jot. + * + * For more information, see the + * gContact specification. + * + * Since: 0.7.0 + */ + g_object_class_install_property (gobject_class, PROP_CONTENT, + g_param_spec_string ("content", + "Content", "The content of the jot.", + NULL, + G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)); + + /** + * GDataGContactJot:relation-type: + * + * A programmatic value that identifies the type of jot. Examples are %GDATA_GCONTACT_JOT_HOME or %GDATA_GCONTACT_JOT_OTHER. + * + * For more information, see the + * gContact specification. + * + * Since: 0.7.0 + */ + g_object_class_install_property (gobject_class, PROP_RELATION_TYPE, + g_param_spec_string ("relation-type", + "Relation type", "A programmatic value that identifies the type of jot.", + NULL, + G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)); +} + +static void +gdata_gcontact_jot_init (GDataGContactJot *self) +{ + self->priv = G_TYPE_INSTANCE_GET_PRIVATE (self, GDATA_TYPE_GCONTACT_JOT, GDataGContactJotPrivate); +} + +static void +gdata_gcontact_jot_finalize (GObject *object) +{ + GDataGContactJotPrivate *priv = GDATA_GCONTACT_JOT (object)->priv; + + g_free (priv->content); + g_free (priv->relation_type); + + /* Chain up to the parent class */ + G_OBJECT_CLASS (gdata_gcontact_jot_parent_class)->finalize (object); +} + +static void +gdata_gcontact_jot_get_property (GObject *object, guint property_id, GValue *value, GParamSpec *pspec) +{ + GDataGContactJotPrivate *priv = GDATA_GCONTACT_JOT (object)->priv; + + switch (property_id) { + case PROP_CONTENT: + g_value_set_string (value, priv->content); + break; + case PROP_RELATION_TYPE: + g_value_set_string (value, priv->relation_type); + break; + default: + /* We don't have any other property... */ + G_OBJECT_WARN_INVALID_PROPERTY_ID (object, property_id, pspec); + break; + } +} + +static void +gdata_gcontact_jot_set_property (GObject *object, guint property_id, const GValue *value, GParamSpec *pspec) +{ + GDataGContactJot *self = GDATA_GCONTACT_JOT (object); + + switch (property_id) { + case PROP_CONTENT: + gdata_gcontact_jot_set_content (self, g_value_get_string (value)); + break; + case PROP_RELATION_TYPE: + gdata_gcontact_jot_set_relation_type (self, g_value_get_string (value)); + break; + default: + /* We don't have any other property... */ + G_OBJECT_WARN_INVALID_PROPERTY_ID (object, property_id, pspec); + break; + } +} + +static gboolean +pre_parse_xml (GDataParsable *parsable, xmlDoc *doc, xmlNode *root_node, gpointer user_data, GError **error) +{ + xmlChar *rel; + GDataGContactJotPrivate *priv = GDATA_GCONTACT_JOT (parsable)->priv; + + rel = xmlGetProp (root_node, (xmlChar*) "rel"); + if (rel == NULL || *rel == '\0') { + xmlFree (rel); + return gdata_parser_error_required_property_missing (root_node, "rel", error); + } + + priv->content = (gchar*) xmlNodeListGetString (doc, root_node->children, TRUE); + priv->relation_type = (gchar*) rel; + + return TRUE; +} + +static gboolean +parse_xml (GDataParsable *parsable, xmlDoc *doc, xmlNode *node, gpointer user_data, GError **error) +{ + /* Textual content's handled in pre_parse_xml */ + if (node->type != XML_ELEMENT_NODE) + return TRUE; + + return GDATA_PARSABLE_CLASS (gdata_gcontact_jot_parent_class)->parse_xml (parsable, doc, node, user_data, error); +} + +static void +pre_get_xml (GDataParsable *parsable, GString *xml_string) +{ + gdata_parser_string_append_escaped (xml_string, " rel='", GDATA_GCONTACT_JOT (parsable)->priv->relation_type, "'"); +} + +static void +get_xml (GDataParsable *parsable, GString *xml_string) +{ + gdata_parser_string_append_escaped (xml_string, NULL, GDATA_GCONTACT_JOT (parsable)->priv->content, NULL); +} + +static void +get_namespaces (GDataParsable *parsable, GHashTable *namespaces) +{ + g_hash_table_insert (namespaces, (gchar*) "gContact", (gchar*) "http://schemas.google.com/contact/2008"); +} + +/** + * gdata_gcontact_jot_new: + * @content: the content of the jot + * @relation_type: the relationship between the jot and its owner + * + * Creates a new #GDataGContactJot. More information is available in the gContact specification. + * + * Return value: a new #GDataGContactJot; unref with g_object_unref() + * + * Since: 0.7.0 + */ +GDataGContactJot * +gdata_gcontact_jot_new (const gchar *content, const gchar *relation_type) +{ + g_return_val_if_fail (content != NULL, NULL); + g_return_val_if_fail (relation_type != NULL && *relation_type != '\0', NULL); + return g_object_new (GDATA_TYPE_GCONTACT_JOT, "content", content, "relation-type", relation_type, NULL); +} + +/** + * gdata_gcontact_jot_get_content: + * @self: a #GDataGContactJot + * + * Gets the #GDataGContactJot:content property. + * + * Return value: the jot's content + * + * Since: 0.7.0 + */ +const gchar * +gdata_gcontact_jot_get_content (GDataGContactJot *self) +{ + g_return_val_if_fail (GDATA_IS_GCONTACT_JOT (self), NULL); + return self->priv->content; +} + +/** + * gdata_gcontact_jot_set_content: + * @self: a #GDataGContactJot + * @content: the new content + * + * Sets the #GDataGContactJot:content property to @content. + * + * Since: 0.7.0 + */ +void +gdata_gcontact_jot_set_content (GDataGContactJot *self, const gchar *content) +{ + g_return_if_fail (GDATA_IS_GCONTACT_JOT (self)); + g_return_if_fail (content != NULL); + + g_free (self->priv->content); + self->priv->content = g_strdup (content); + g_object_notify (G_OBJECT (self), "content"); +} + +/** + * gdata_gcontact_jot_get_relation_type: + * @self: a #GDataGContactJot + * + * Gets the #GDataGContactJot:relation-type property. + * + * Return value: the jot's relation type + * + * Since: 0.7.0 + */ +const gchar * +gdata_gcontact_jot_get_relation_type (GDataGContactJot *self) +{ + g_return_val_if_fail (GDATA_IS_GCONTACT_JOT (self), NULL); + return self->priv->relation_type; +} + +/** + * gdata_gcontact_jot_set_relation_type: + * @self: a #GDataGContactJot + * @relation_type: the new relation type for the jot, or %NULL + * + * Sets the #GDataGContactJot:relation-type property to @relation_type + * such as %GDATA_GCONTACT_JOT_HOME or %GDATA_GCONTACT_JOT_OTHER. + * + * Since: 0.7.0 + */ +void +gdata_gcontact_jot_set_relation_type (GDataGContactJot *self, const gchar *relation_type) +{ + g_return_if_fail (GDATA_IS_GCONTACT_JOT (self)); + g_return_if_fail (relation_type != NULL && *relation_type != '\0'); + + g_free (self->priv->relation_type); + self->priv->relation_type = g_strdup (relation_type); + g_object_notify (G_OBJECT (self), "relation-type"); +} diff --git a/gdata/gcontact/gdata-gcontact-jot.h b/gdata/gcontact/gdata-gcontact-jot.h new file mode 100644 index 0000000..b9272b9 --- /dev/null +++ b/gdata/gcontact/gdata-gcontact-jot.h @@ -0,0 +1,140 @@ +/* -*- Mode: C; indent-tabs-mode: t; c-basic-offset: 8; tab-width: 8 -*- */ +/* + * GData Client + * Copyright (C) Philip Withnall 2010 + * + * GData Client is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * GData Client is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with GData Client. If not, see . + */ + +#ifndef GDATA_GCONTACT_JOT_H +#define GDATA_GCONTACT_JOT_H + +#include +#include + +#include + +G_BEGIN_DECLS + +/** + * GDATA_GCONTACT_JOT_HOME: + * + * The relation type URI for a jot about a contact's home. + * + * For more information, see the + * gContact specification. + * + * Since: 0.7.0 + */ +#define GDATA_GCONTACT_JOT_HOME "home" + +/** + * GDATA_GCONTACT_JOT_WORK: + * + * The relation type URI for a jot about a contact's work. + * + * For more information, see the + * gContact specification. + * + * Since: 0.7.0 + */ +#define GDATA_GCONTACT_JOT_WORK "work" + +/** + * GDATA_GCONTACT_JOT_OTHER: + * + * The relation type URI for a jot about an other facet of a contact. + * + * For more information, see the + * gContact specification. + * + * Since: 0.7.0 + */ +#define GDATA_GCONTACT_JOT_OTHER "other" + +/** + * GDATA_GCONTACT_JOT_KEYWORDS: + * + * The relation type URI for a jot with keywords about a contact. + * + * For more information, see the + * gContact specification. + * + * Since: 0.7.0 + */ +#define GDATA_GCONTACT_JOT_KEYWORDS "keywords" + +/** + * GDATA_GCONTACT_JOT_USER: + * + * The relation type URI for a jot about the relationship between a contact and the user. + * + * For more information, see the + * gContact specification. + * + * Since: 0.7.0 + */ +#define GDATA_GCONTACT_JOT_USER "user" + +#define GDATA_TYPE_GCONTACT_JOT (gdata_gcontact_jot_get_type ()) +#define GDATA_GCONTACT_JOT(o) (G_TYPE_CHECK_INSTANCE_CAST ((o), GDATA_TYPE_GCONTACT_JOT, GDataGContactJot)) +#define GDATA_GCONTACT_JOT_CLASS(k) (G_TYPE_CHECK_CLASS_CAST((k), GDATA_TYPE_GCONTACT_JOT, GDataGContactJotClass)) +#define GDATA_IS_GCONTACT_JOT(o) (G_TYPE_CHECK_INSTANCE_TYPE ((o), GDATA_TYPE_GCONTACT_JOT)) +#define GDATA_IS_GCONTACT_JOT_CLASS(k) (G_TYPE_CHECK_CLASS_TYPE ((k), GDATA_TYPE_GCONTACT_JOT)) +#define GDATA_GCONTACT_JOT_GET_CLASS(o) (G_TYPE_INSTANCE_GET_CLASS ((o), GDATA_TYPE_GCONTACT_JOT, GDataGContactJotClass)) + +typedef struct _GDataGContactJotPrivate GDataGContactJotPrivate; + +/** + * GDataGContactJot: + * + * All the fields in the #GDataGContactJot structure are private and should never be accessed directly. + * + * Since: 0.7.0 + */ +typedef struct { + GDataParsable parent; + GDataGContactJotPrivate *priv; +} GDataGContactJot; + +/** + * GDataGContactJotClass: + * + * All the fields in the #GDataGContactJotClass structure are private and should never be accessed directly. + * + * Since: 0.7.0 + */ +typedef struct { + /*< private >*/ + GDataParsableClass parent; + + /*< private >*/ + /* Padding for future expansion */ + void (*_g_reserved0) (void); + void (*_g_reserved1) (void); +} GDataGContactJotClass; + +GType gdata_gcontact_jot_get_type (void) G_GNUC_CONST; + +GDataGContactJot *gdata_gcontact_jot_new (const gchar *content, const gchar *relation_type) G_GNUC_WARN_UNUSED_RESULT G_GNUC_MALLOC; + +const gchar *gdata_gcontact_jot_get_content (GDataGContactJot *self) G_GNUC_PURE; +void gdata_gcontact_jot_set_content (GDataGContactJot *self, const gchar *content); + +const gchar *gdata_gcontact_jot_get_relation_type (GDataGContactJot *self) G_GNUC_PURE; +void gdata_gcontact_jot_set_relation_type (GDataGContactJot *self, const gchar *relation_type); + +G_END_DECLS + +#endif /* !GDATA_GCONTACT_JOT_H */ diff --git a/gdata/gcontact/gdata-gcontact-language.c b/gdata/gcontact/gdata-gcontact-language.c new file mode 100644 index 0000000..5fe867f --- /dev/null +++ b/gdata/gcontact/gdata-gcontact-language.c @@ -0,0 +1,327 @@ +/* -*- Mode: C; indent-tabs-mode: t; c-basic-offset: 8; tab-width: 8 -*- */ +/* + * GData Client + * Copyright (C) Philip Withnall 2010 + * + * GData Client is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * GData Client is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with GData Client. If not, see . + */ + +/** + * SECTION:gdata-gcontact-language + * @short_description: gContact language element + * @stability: Stable + * @include: gdata/gcontact/gdata-gcontact-language.h + * + * #GDataGContactLanguage represents a "language" element from the + * gContact specification. + * + * Since: 0.7.0 + */ + +#include +#include + +#include "gdata-gcontact-language.h" +#include "gdata-parsable.h" +#include "gdata-parser.h" +#include "gdata-comparable.h" + +static void gdata_gcontact_language_comparable_init (GDataComparableIface *iface); +static void gdata_gcontact_language_finalize (GObject *object); +static void gdata_gcontact_language_get_property (GObject *object, guint property_id, GValue *value, GParamSpec *pspec); +static void gdata_gcontact_language_set_property (GObject *object, guint property_id, const GValue *value, GParamSpec *pspec); +static gboolean pre_parse_xml (GDataParsable *parsable, xmlDoc *doc, xmlNode *root_node, gpointer user_data, GError **error); +static void pre_get_xml (GDataParsable *parsable, GString *xml_string); +static void get_namespaces (GDataParsable *parsable, GHashTable *namespaces); + +struct _GDataGContactLanguagePrivate { + gchar *code; + gchar *label; +}; + +enum { + PROP_CODE = 1, + PROP_LABEL +}; + +G_DEFINE_TYPE_WITH_CODE (GDataGContactLanguage, gdata_gcontact_language, GDATA_TYPE_PARSABLE, + G_IMPLEMENT_INTERFACE (GDATA_TYPE_COMPARABLE, gdata_gcontact_language_comparable_init)) + +static void +gdata_gcontact_language_class_init (GDataGContactLanguageClass *klass) +{ + GObjectClass *gobject_class = G_OBJECT_CLASS (klass); + GDataParsableClass *parsable_class = GDATA_PARSABLE_CLASS (klass); + + g_type_class_add_private (klass, sizeof (GDataGContactLanguagePrivate)); + + gobject_class->get_property = gdata_gcontact_language_get_property; + gobject_class->set_property = gdata_gcontact_language_set_property; + gobject_class->finalize = gdata_gcontact_language_finalize; + + parsable_class->pre_parse_xml = pre_parse_xml; + parsable_class->pre_get_xml = pre_get_xml; + parsable_class->get_namespaces = get_namespaces; + parsable_class->element_name = "language"; + parsable_class->element_namespace = "gContact"; + + /** + * GDataGContactLanguage:code: + * + * A code identifying the language, conforming to the IETF BCP 47 specification. It is mutually exclusive with #GDataGContactLanguage:label. + * + * For more information, see the + * gContact specification. + * + * Since: 0.7.0 + */ + g_object_class_install_property (gobject_class, PROP_CODE, + g_param_spec_string ("code", + "Code", "A code identifying the language, conforming to the IETF BCP 47 specification.", + NULL, + G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)); + + /** + * GDataGContactLanguage:label: + * + * A free-form string that identifies the language. It is mutually exclusive with #GDataGContactLanguage:code. + * + * For more information, see the + * gContact specification. + * + * Since: 0.7.0 + */ + g_object_class_install_property (gobject_class, PROP_LABEL, + g_param_spec_string ("label", + "Label", "A free-form string that identifies the language.", + NULL, + G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)); +} + +static gint +compare_with (GDataComparable *self, GDataComparable *other) +{ + GDataGContactLanguagePrivate *a = ((GDataGContactLanguage*) self)->priv, *b = ((GDataGContactLanguage*) other)->priv; + + if (g_strcmp0 (a->code, b->code) == 0 && g_strcmp0 (a->label, b->label) == 0) + return 0; + return 1; +} + +static void +gdata_gcontact_language_comparable_init (GDataComparableIface *iface) +{ + iface->compare_with = compare_with; +} + +static void +gdata_gcontact_language_init (GDataGContactLanguage *self) +{ + self->priv = G_TYPE_INSTANCE_GET_PRIVATE (self, GDATA_TYPE_GCONTACT_LANGUAGE, GDataGContactLanguagePrivate); +} + +static void +gdata_gcontact_language_finalize (GObject *object) +{ + GDataGContactLanguagePrivate *priv = GDATA_GCONTACT_LANGUAGE (object)->priv; + + g_free (priv->code); + g_free (priv->label); + + /* Chain up to the parent class */ + G_OBJECT_CLASS (gdata_gcontact_language_parent_class)->finalize (object); +} + +static void +gdata_gcontact_language_get_property (GObject *object, guint property_id, GValue *value, GParamSpec *pspec) +{ + GDataGContactLanguagePrivate *priv = GDATA_GCONTACT_LANGUAGE (object)->priv; + + switch (property_id) { + case PROP_CODE: + g_value_set_string (value, priv->code); + break; + case PROP_LABEL: + g_value_set_string (value, priv->label); + break; + default: + /* We don't have any other property... */ + G_OBJECT_WARN_INVALID_PROPERTY_ID (object, property_id, pspec); + break; + } +} + +static void +gdata_gcontact_language_set_property (GObject *object, guint property_id, const GValue *value, GParamSpec *pspec) +{ + GDataGContactLanguage *self = GDATA_GCONTACT_LANGUAGE (object); + + switch (property_id) { + case PROP_CODE: + gdata_gcontact_language_set_code (self, g_value_get_string (value)); + break; + case PROP_LABEL: + gdata_gcontact_language_set_label (self, g_value_get_string (value)); + break; + default: + /* We don't have any other property... */ + G_OBJECT_WARN_INVALID_PROPERTY_ID (object, property_id, pspec); + break; + } +} + +static gboolean +pre_parse_xml (GDataParsable *parsable, xmlDoc *doc, xmlNode *root_node, gpointer user_data, GError **error) +{ + xmlChar *code, *label; + GDataGContactLanguagePrivate *priv = GDATA_GCONTACT_LANGUAGE (parsable)->priv; + + code = xmlGetProp (root_node, (xmlChar*) "code"); + label = xmlGetProp (root_node, (xmlChar*) "label"); + if ((code == NULL || *code == '\0') && (label == NULL || *label == '\0')) { + xmlFree (code); + xmlFree (label); + return gdata_parser_error_required_property_missing (root_node, "code", error); + } else if (code != NULL && label != NULL) { + /* Can't have both set at once */ + xmlFree (code); + xmlFree (label); + return gdata_parser_error_mutexed_properties (root_node, "code", "label", error); + } + + priv->code = (gchar*) code; + priv->label = (gchar*) label; + + return TRUE; +} + +static void +pre_get_xml (GDataParsable *parsable, GString *xml_string) +{ + GDataGContactLanguagePrivate *priv = GDATA_GCONTACT_LANGUAGE (parsable)->priv; + + if (priv->code != NULL) + gdata_parser_string_append_escaped (xml_string, " code='", priv->code, "'"); + else if (priv->label != NULL) + gdata_parser_string_append_escaped (xml_string, " label='", priv->label, "'"); + else + g_assert_not_reached (); +} + +static void +get_namespaces (GDataParsable *parsable, GHashTable *namespaces) +{ + g_hash_table_insert (namespaces, (gchar*) "gContact", (gchar*) "http://schemas.google.com/contact/2008"); +} + +/** + * gdata_gcontact_language_new: + * @code: (allow-none): the language code, or %NULL + * @label: (allow-none): a free-form label for the language, or %NULL + * + * Creates a new #GDataGContactLanguage. More information is available in the gContact specification. + * + * Exactly one of @code and @label should be provided; the other must be %NULL. + * + * Return value: a new #GDataGContactLanguage; unref with g_object_unref() + * + * Since: 0.7.0 + */ +GDataGContactLanguage * +gdata_gcontact_language_new (const gchar *code, const gchar *label) +{ + g_return_val_if_fail ((code != NULL && *code != '\0' && label == NULL) || (code == NULL && label != NULL && *label != '\0'), NULL); + return g_object_new (GDATA_TYPE_GCONTACT_LANGUAGE, "code", code, "label", label, NULL); +} + +/** + * gdata_gcontact_language_get_code: + * @self: a #GDataGContactLanguage + * + * Gets the #GDataGContactLanguage:code property. + * + * Return value: the language's code, or %NULL + * + * Since: 0.7.0 + */ +const gchar * +gdata_gcontact_language_get_code (GDataGContactLanguage *self) +{ + g_return_val_if_fail (GDATA_IS_GCONTACT_LANGUAGE (self), NULL); + return self->priv->code; +} + +/** + * gdata_gcontact_language_set_code: + * @self: a #GDataGContactLanguage + * @code: (allow-none): the new code for the language, or %NULL + * + * Sets the #GDataGContactLanguage:code property to @code. + * + * If @code is %NULL, the code will be unset. When the #GDataGContactLanguage is used in a query, however, + * exactly one of #GDataGContactLanguage:code and #GDataGContactLanguage:label must be %NULL. + * + * Since: 0.7.0 + */ +void +gdata_gcontact_language_set_code (GDataGContactLanguage *self, const gchar *code) +{ + g_return_if_fail (GDATA_IS_GCONTACT_LANGUAGE (self)); + g_return_if_fail (code == NULL || *code != '\0'); + + g_free (self->priv->code); + self->priv->code = g_strdup (code); + g_object_notify (G_OBJECT (self), "code"); +} + +/** + * gdata_gcontact_language_get_label: + * @self: a #GDataGContactLanguage + * + * Gets the #GDataGContactLanguage:label property. + * + * Return value: a free-form label for the language, or %NULL + * + * Since: 0.7.0 + */ +const gchar * +gdata_gcontact_language_get_label (GDataGContactLanguage *self) +{ + g_return_val_if_fail (GDATA_IS_GCONTACT_LANGUAGE (self), NULL); + return self->priv->label; +} + +/** + * gdata_gcontact_language_set_label: + * @self: a #GDataGContactLanguage + * @label: (allow-none): the new free-form label for the language, or %NULL + * + * Sets the #GDataGContactLanguage:label property to @label. + * + * If @label is %NULL, the label will be unset. When the #GDataGContactLanguage is used in a query, however, + * exactly one of #GDataGContactLanguage:code and #GDataGContactLanguage:label must be %NULL. + * + * Since: 0.7.0 + */ +void +gdata_gcontact_language_set_label (GDataGContactLanguage *self, const gchar *label) +{ + g_return_if_fail (GDATA_IS_GCONTACT_LANGUAGE (self)); + g_return_if_fail (label == NULL || *label != '\0'); + + g_free (self->priv->label); + self->priv->label = g_strdup (label); + g_object_notify (G_OBJECT (self), "label"); +} diff --git a/gdata/gcontact/gdata-gcontact-language.h b/gdata/gcontact/gdata-gcontact-language.h new file mode 100644 index 0000000..acd9265 --- /dev/null +++ b/gdata/gcontact/gdata-gcontact-language.h @@ -0,0 +1,80 @@ +/* -*- Mode: C; indent-tabs-mode: t; c-basic-offset: 8; tab-width: 8 -*- */ +/* + * GData Client + * Copyright (C) Philip Withnall 2010 + * + * GData Client is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * GData Client is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with GData Client. If not, see . + */ + +#ifndef GDATA_GCONTACT_LANGUAGE_H +#define GDATA_GCONTACT_LANGUAGE_H + +#include +#include + +#include + +G_BEGIN_DECLS + +#define GDATA_TYPE_GCONTACT_LANGUAGE (gdata_gcontact_language_get_type ()) +#define GDATA_GCONTACT_LANGUAGE(o) (G_TYPE_CHECK_INSTANCE_CAST ((o), GDATA_TYPE_GCONTACT_LANGUAGE, GDataGContactLanguage)) +#define GDATA_GCONTACT_LANGUAGE_CLASS(k) (G_TYPE_CHECK_CLASS_CAST((k), GDATA_TYPE_GCONTACT_LANGUAGE, GDataGContactLanguageClass)) +#define GDATA_IS_GCONTACT_LANGUAGE(o) (G_TYPE_CHECK_INSTANCE_TYPE ((o), GDATA_TYPE_GCONTACT_LANGUAGE)) +#define GDATA_IS_GCONTACT_LANGUAGE_CLASS(k) (G_TYPE_CHECK_CLASS_TYPE ((k), GDATA_TYPE_GCONTACT_LANGUAGE)) +#define GDATA_GCONTACT_LANGUAGE_GET_CLASS(o) (G_TYPE_INSTANCE_GET_CLASS ((o), GDATA_TYPE_GCONTACT_LANGUAGE, GDataGContactLanguageClass)) + +typedef struct _GDataGContactLanguagePrivate GDataGContactLanguagePrivate; + +/** + * GDataGContactLanguage: + * + * All the fields in the #GDataGContactLanguage structure are private and should never be accessed directly. + * + * Since: 0.7.0 + */ +typedef struct { + GDataParsable parent; + GDataGContactLanguagePrivate *priv; +} GDataGContactLanguage; + +/** + * GDataGContactLanguageClass: + * + * All the fields in the #GDataGContactLanguageClass structure are private and should never be accessed directly. + * + * Since: 0.7.0 + */ +typedef struct { + /*< private >*/ + GDataParsableClass parent; + + /*< private >*/ + /* Padding for future expansion */ + void (*_g_reserved0) (void); + void (*_g_reserved1) (void); +} GDataGContactLanguageClass; + +GType gdata_gcontact_language_get_type (void) G_GNUC_CONST; + +GDataGContactLanguage *gdata_gcontact_language_new (const gchar *code, const gchar *label) G_GNUC_WARN_UNUSED_RESULT G_GNUC_MALLOC; + +const gchar *gdata_gcontact_language_get_code (GDataGContactLanguage *self) G_GNUC_PURE; +void gdata_gcontact_language_set_code (GDataGContactLanguage *self, const gchar *code); + +const gchar *gdata_gcontact_language_get_label (GDataGContactLanguage *self) G_GNUC_PURE; +void gdata_gcontact_language_set_label (GDataGContactLanguage *self, const gchar *label); + +G_END_DECLS + +#endif /* !GDATA_GCONTACT_LANGUAGE_H */ diff --git a/gdata/gcontact/gdata-gcontact-relation.c b/gdata/gcontact/gdata-gcontact-relation.c new file mode 100644 index 0000000..b562fa4 --- /dev/null +++ b/gdata/gcontact/gdata-gcontact-relation.c @@ -0,0 +1,406 @@ +/* -*- Mode: C; indent-tabs-mode: t; c-basic-offset: 8; tab-width: 8 -*- */ +/* + * GData Client + * Copyright (C) Philip Withnall 2010 + * + * GData Client is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * GData Client is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with GData Client. If not, see . + */ + +/** + * SECTION:gdata-gcontact-relation + * @short_description: gContact relation element + * @stability: Stable + * @include: gdata/gcontact/gdata-gcontact-relation.h + * + * #GDataGContactRelation represents a "relation" element from the + * gContact specification. + * + * Since: 0.7.0 + */ + +#include +#include + +#include "gdata-gcontact-relation.h" +#include "gdata-parsable.h" +#include "gdata-parser.h" + +static void gdata_gcontact_relation_finalize (GObject *object); +static void gdata_gcontact_relation_get_property (GObject *object, guint property_id, GValue *value, GParamSpec *pspec); +static void gdata_gcontact_relation_set_property (GObject *object, guint property_id, const GValue *value, GParamSpec *pspec); +static gboolean pre_parse_xml (GDataParsable *parsable, xmlDoc *doc, xmlNode *root_node, gpointer user_data, GError **error); +static gboolean parse_xml (GDataParsable *parsable, xmlDoc *doc, xmlNode *root_node, gpointer user_data, GError **error); +static void pre_get_xml (GDataParsable *parsable, GString *xml_string); +static void get_xml (GDataParsable *parsable, GString *xml_string); +static void get_namespaces (GDataParsable *parsable, GHashTable *namespaces); + +struct _GDataGContactRelationPrivate { + gchar *name; + gchar *relation_type; + gchar *label; +}; + +enum { + PROP_NAME = 1, + PROP_RELATION_TYPE, + PROP_LABEL +}; + +G_DEFINE_TYPE (GDataGContactRelation, gdata_gcontact_relation, GDATA_TYPE_PARSABLE) + +static void +gdata_gcontact_relation_class_init (GDataGContactRelationClass *klass) +{ + GObjectClass *gobject_class = G_OBJECT_CLASS (klass); + GDataParsableClass *parsable_class = GDATA_PARSABLE_CLASS (klass); + + g_type_class_add_private (klass, sizeof (GDataGContactRelationPrivate)); + + gobject_class->get_property = gdata_gcontact_relation_get_property; + gobject_class->set_property = gdata_gcontact_relation_set_property; + gobject_class->finalize = gdata_gcontact_relation_finalize; + + parsable_class->pre_parse_xml = pre_parse_xml; + parsable_class->parse_xml = parse_xml; + parsable_class->pre_get_xml = pre_get_xml; + parsable_class->get_xml = get_xml; + parsable_class->get_namespaces = get_namespaces; + parsable_class->element_name = "relation"; + parsable_class->element_namespace = "gContact"; + + /** + * GDataGContactRelation:name: + * + * The name of the relation. It need not be a full name, and there need not be a contact representing the name. + * + * For more information, see the + * gContact specification. + * + * Since: 0.7.0 + */ + g_object_class_install_property (gobject_class, PROP_NAME, + g_param_spec_string ("name", + "Name", "The name of the relation.", + NULL, + G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)); + + /** + * GDataGContactRelation:relation-type: + * + * A programmatic value that identifies the type of relation. It is mutually exclusive with #GDataGContactRelation:label. + * Examples are %GDATA_GCONTACT_RELATION_MANAGER or %GDATA_GCONTACT_RELATION_CHILD. + * + * For more information, see the + * gContact specification. + * + * Since: 0.7.0 + */ + g_object_class_install_property (gobject_class, PROP_RELATION_TYPE, + g_param_spec_string ("relation-type", + "Relation type", "A programmatic value that identifies the type of relation.", + NULL, + G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)); + + /** + * GDataGContactRelation:label: + * + * A free-form string that identifies the type of relation. It is mutually exclusive with #GDataGContactRelation:relation-type. + * + * For more information, see the + * gContact specification. + * + * Since: 0.7.0 + */ + g_object_class_install_property (gobject_class, PROP_LABEL, + g_param_spec_string ("label", + "Label", "A free-form string that identifies the type of relation.", + NULL, + G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)); +} + +static void +gdata_gcontact_relation_init (GDataGContactRelation *self) +{ + self->priv = G_TYPE_INSTANCE_GET_PRIVATE (self, GDATA_TYPE_GCONTACT_RELATION, GDataGContactRelationPrivate); +} + +static void +gdata_gcontact_relation_finalize (GObject *object) +{ + GDataGContactRelationPrivate *priv = GDATA_GCONTACT_RELATION (object)->priv; + + g_free (priv->name); + g_free (priv->relation_type); + g_free (priv->label); + + /* Chain up to the parent class */ + G_OBJECT_CLASS (gdata_gcontact_relation_parent_class)->finalize (object); +} + +static void +gdata_gcontact_relation_get_property (GObject *object, guint property_id, GValue *value, GParamSpec *pspec) +{ + GDataGContactRelationPrivate *priv = GDATA_GCONTACT_RELATION (object)->priv; + + switch (property_id) { + case PROP_NAME: + g_value_set_string (value, priv->name); + break; + case PROP_RELATION_TYPE: + g_value_set_string (value, priv->relation_type); + break; + case PROP_LABEL: + g_value_set_string (value, priv->label); + break; + default: + /* We don't have any other property... */ + G_OBJECT_WARN_INVALID_PROPERTY_ID (object, property_id, pspec); + break; + } +} + +static void +gdata_gcontact_relation_set_property (GObject *object, guint property_id, const GValue *value, GParamSpec *pspec) +{ + GDataGContactRelation *self = GDATA_GCONTACT_RELATION (object); + + switch (property_id) { + case PROP_NAME: + gdata_gcontact_relation_set_name (self, g_value_get_string (value)); + break; + case PROP_RELATION_TYPE: + gdata_gcontact_relation_set_relation_type (self, g_value_get_string (value)); + break; + case PROP_LABEL: + gdata_gcontact_relation_set_label (self, g_value_get_string (value)); + break; + default: + /* We don't have any other property... */ + G_OBJECT_WARN_INVALID_PROPERTY_ID (object, property_id, pspec); + break; + } +} + +static gboolean +pre_parse_xml (GDataParsable *parsable, xmlDoc *doc, xmlNode *root_node, gpointer user_data, GError **error) +{ + xmlChar *rel, *label, *name; + GDataGContactRelationPrivate *priv = GDATA_GCONTACT_RELATION (parsable)->priv; + + rel = xmlGetProp (root_node, (xmlChar*) "rel"); + label = xmlGetProp (root_node, (xmlChar*) "label"); + if ((rel == NULL || *rel == '\0') && (label == NULL || *label == '\0')) { + xmlFree (rel); + xmlFree (label); + return gdata_parser_error_required_property_missing (root_node, "rel", error); + } else if (rel != NULL && label != NULL) { + /* Can't have both set at once */ + xmlFree (rel); + xmlFree (label); + return gdata_parser_error_mutexed_properties (root_node, "rel", "label", error); + } + + /* Get the name */ + name = xmlNodeListGetString (doc, root_node->children, TRUE); + if (name == NULL || *name == '\0') { + xmlFree (rel); + xmlFree (label); + xmlFree (name); + return gdata_parser_error_required_content_missing (root_node, error); + } + + priv->name = (gchar*) name; + priv->relation_type = (gchar*) rel; + priv->label = (gchar*) label; + + return TRUE; +} + +static gboolean +parse_xml (GDataParsable *parsable, xmlDoc *doc, xmlNode *node, gpointer user_data, GError **error) +{ + /* Textual content's handled in pre_parse_xml */ + if (node->type != XML_ELEMENT_NODE) + return TRUE; + + return GDATA_PARSABLE_CLASS (gdata_gcontact_relation_parent_class)->parse_xml (parsable, doc, node, user_data, error); +} + +static void +pre_get_xml (GDataParsable *parsable, GString *xml_string) +{ + GDataGContactRelationPrivate *priv = GDATA_GCONTACT_RELATION (parsable)->priv; + + if (priv->relation_type != NULL) + gdata_parser_string_append_escaped (xml_string, " rel='", priv->relation_type, "'"); + else if (priv->label != NULL) + gdata_parser_string_append_escaped (xml_string, " label='", priv->label, "'"); + else + g_assert_not_reached (); +} + +static void +get_xml (GDataParsable *parsable, GString *xml_string) +{ + gdata_parser_string_append_escaped (xml_string, NULL, GDATA_GCONTACT_RELATION (parsable)->priv->name, NULL); +} + +static void +get_namespaces (GDataParsable *parsable, GHashTable *namespaces) +{ + g_hash_table_insert (namespaces, (gchar*) "gContact", (gchar*) "http://schemas.google.com/contact/2008"); +} + +/** + * gdata_gcontact_relation_new: + * @name: the name of the relation + * @relation_type: (allow-none): the type of relation, or %NULL + * @label: (allow-none): a free-form label for the type of relation, or %NULL + * + * Creates a new #GDataGContactRelation. More information is available in the gContact specification. + * + * Exactly one of @relation_type and @label should be provided; the other must be %NULL. + * + * Return value: a new #GDataGContactRelation; unref with g_object_unref() + * + * Since: 0.7.0 + */ +GDataGContactRelation * +gdata_gcontact_relation_new (const gchar *name, const gchar *relation_type, const gchar *label) +{ + g_return_val_if_fail (name != NULL && *name != '\0', NULL); + g_return_val_if_fail ((relation_type != NULL && *relation_type != '\0' && label == NULL) || + (relation_type == NULL && label != NULL && *label != '\0'), NULL); + + return g_object_new (GDATA_TYPE_GCONTACT_RELATION, "name", name, "relation-type", relation_type, "label", label, NULL); +} + +/** + * gdata_gcontact_relation_get_name: + * @self: a #GDataGContactRelation + * + * Gets the #GDataGContactRelation:name property. + * + * Return value: the relation's name + * + * Since: 0.7.0 + */ +const gchar * +gdata_gcontact_relation_get_name (GDataGContactRelation *self) +{ + g_return_val_if_fail (GDATA_IS_GCONTACT_RELATION (self), NULL); + return self->priv->name; +} + +/** + * gdata_gcontact_relation_set_name: + * @self: a #GDataGContactRelation + * @name: (allow-none): the new name for the relation + * + * Sets the #GDataGContactRelation:name property to @name. + * + * Since: 0.7.0 + */ +void +gdata_gcontact_relation_set_name (GDataGContactRelation *self, const gchar *name) +{ + g_return_if_fail (GDATA_IS_GCONTACT_RELATION (self)); + g_return_if_fail (name != NULL && *name != '\0'); + + g_free (self->priv->name); + self->priv->name = g_strdup (name); + g_object_notify (G_OBJECT (self), "name"); +} + +/** + * gdata_gcontact_relation_get_relation_type: + * @self: a #GDataGContactRelation + * + * Gets the #GDataGContactRelation:relation-type property. + * + * Return value: the type of the relation, or %NULL + * + * Since: 0.7.0 + */ +const gchar * +gdata_gcontact_relation_get_relation_type (GDataGContactRelation *self) +{ + g_return_val_if_fail (GDATA_IS_GCONTACT_RELATION (self), NULL); + return self->priv->relation_type; +} + +/** + * gdata_gcontact_relation_set_relation_type: + * @self: a #GDataGContactRelation + * @relation_type: (allow-none): the new type for the relation, or %NULL + * + * Sets the #GDataGContactRelation:relation-type property to @relation_type, + * such as %GDATA_GCONTACT_RELATION_MANAGER or %GDATA_GCONTACT_RELATION_CHILD. + * + * If @relation_type is %NULL, the relation type will be unset. When the #GDataGContactRelation is used in a query, however, + * exactly one of #GDataGContactRelation:relation-type and #GDataGContactRelation:label must be %NULL. + * + * Since: 0.7.0 + */ +void +gdata_gcontact_relation_set_relation_type (GDataGContactRelation *self, const gchar *relation_type) +{ + g_return_if_fail (GDATA_IS_GCONTACT_RELATION (self)); + g_return_if_fail (relation_type == NULL || *relation_type != '\0'); + + g_free (self->priv->relation_type); + self->priv->relation_type = g_strdup (relation_type); + g_object_notify (G_OBJECT (self), "relation-type"); +} + +/** + * gdata_gcontact_relation_get_label: + * @self: a #GDataGContactRelation + * + * Gets the #GDataGContactRelation:label property. + * + * Return value: a free-form label for the type of the relation, or %NULL + * + * Since: 0.7.0 + */ +const gchar * +gdata_gcontact_relation_get_label (GDataGContactRelation *self) +{ + g_return_val_if_fail (GDATA_IS_GCONTACT_RELATION (self), NULL); + return self->priv->label; +} + +/** + * gdata_gcontact_relation_set_label: + * @self: a #GDataGContactRelation + * @label: (allow-none): the new free-form type for the relation, or %NULL + * + * Sets the #GDataGContactRelation:label property to @label. + * + * If @label is %NULL, the label will be unset. When the #GDataGContactRelation is used in a query, however, + * exactly one of #GDataGContactRelation:relation-type and #GDataGContactRelation:label must be %NULL. + * + * Since: 0.7.0 + */ +void +gdata_gcontact_relation_set_label (GDataGContactRelation *self, const gchar *label) +{ + g_return_if_fail (GDATA_IS_GCONTACT_RELATION (self)); + g_return_if_fail (label == NULL || *label != '\0'); + + g_free (self->priv->label); + self->priv->label = g_strdup (label); + g_object_notify (G_OBJECT (self), "label"); +} diff --git a/gdata/gcontact/gdata-gcontact-relation.h b/gdata/gcontact/gdata-gcontact-relation.h new file mode 100644 index 0000000..74cad06 --- /dev/null +++ b/gdata/gcontact/gdata-gcontact-relation.h @@ -0,0 +1,252 @@ +/* -*- Mode: C; indent-tabs-mode: t; c-basic-offset: 8; tab-width: 8 -*- */ +/* + * GData Client + * Copyright (C) Philip Withnall 2010 + * + * GData Client is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * GData Client is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with GData Client. If not, see . + */ + +#ifndef GDATA_GCONTACT_RELATION_H +#define GDATA_GCONTACT_RELATION_H + +#include +#include + +#include + +G_BEGIN_DECLS + +/** + * GDATA_GCONTACT_RELATION_ASSISTANT: + * + * The relation type URI for a contact's assistant. + * + * For more information, see the + * gContact specification. + * + * Since: 0.7.0 + */ +#define GDATA_GCONTACT_RELATION_ASSISTANT "assistant" + +/** + * GDATA_GCONTACT_RELATION_BROTHER: + * + * The relation type URI for a contact's brother. + * + * For more information, see the + * gContact specification. + * + * Since: 0.7.0 + */ +#define GDATA_GCONTACT_RELATION_BROTHER "brother" + +/** + * GDATA_GCONTACT_RELATION_CHILD: + * + * The relation type URI for a contact's child. + * + * For more information, see the + * gContact specification. + * + * Since: 0.7.0 + */ +#define GDATA_GCONTACT_RELATION_CHILD "child" + +/** + * GDATA_GCONTACT_RELATION_DOMESTIC_PARTNER: + * + * The relation type URI for a contact's domestic partner. + * + * For more information, see the + * gContact specification. + * + * Since: 0.7.0 + */ +#define GDATA_GCONTACT_RELATION_DOMESTIC_PARTNER "domestic-partner" + +/** + * GDATA_GCONTACT_RELATION_FATHER: + * + * The relation type URI for a contact's father. + * + * For more information, see the + * gContact specification. + * + * Since: 0.7.0 + */ +#define GDATA_GCONTACT_RELATION_FATHER "father" + +/** + * GDATA_GCONTACT_RELATION_FRIEND: + * + * The relation type URI for a contact's friend. + * + * For more information, see the + * gContact specification. + * + * Since: 0.7.0 + */ +#define GDATA_GCONTACT_RELATION_FRIEND "friend" + +/** + * GDATA_GCONTACT_RELATION_MANAGER: + * + * The relation type URI for a contact's manager. + * + * For more information, see the + * gContact specification. + * + * Since: 0.7.0 + */ +#define GDATA_GCONTACT_RELATION_MANAGER "manager" + +/** + * GDATA_GCONTACT_RELATION_MOTHER: + * + * The relation type URI for a contact's mother. + * + * For more information, see the + * gContact specification. + * + * Since: 0.7.0 + */ +#define GDATA_GCONTACT_RELATION_MOTHER "mother" + +/** + * GDATA_GCONTACT_RELATION_PARENT: + * + * The relation type URI for a contact's parent. + * + * For more information, see the + * gContact specification. + * + * Since: 0.7.0 + */ +#define GDATA_GCONTACT_RELATION_PARENT "parent" + +/** + * GDATA_GCONTACT_RELATION_PARTNER: + * + * The relation type URI for a contact's business partner. + * + * For more information, see the + * gContact specification. + * + * Since: 0.7.0 + */ +#define GDATA_GCONTACT_RELATION_PARTNER "partner" + +/** + * GDATA_GCONTACT_RELATION_REFERRER: + * + * The relation type URI for a contact's referrer. + * + * For more information, see the + * gContact specification. + * + * Since: 0.7.0 + */ +#define GDATA_GCONTACT_RELATION_REFERRER "referred-by" + +/** + * GDATA_GCONTACT_RELATION_RELATIVE: + * + * The relation type URI for a contact's (general) family relative. + * + * For more information, see the + * gContact specification. + * + * Since: 0.7.0 + */ +#define GDATA_GCONTACT_RELATION_RELATIVE "relative" + +/** + * GDATA_GCONTACT_RELATION_SISTER: + * + * The relation type URI for a contact's sister. + * + * For more information, see the + * gContact specification. + * + * Since: 0.7.0 + */ +#define GDATA_GCONTACT_RELATION_SISTER "sister" + +/** + * GDATA_GCONTACT_RELATION_SPOUSE: + * + * The relation type URI for a contact's spouse. + * + * For more information, see the + * gContact specification. + * + * Since: 0.7.0 + */ +#define GDATA_GCONTACT_RELATION_SPOUSE "spouse" + +#define GDATA_TYPE_GCONTACT_RELATION (gdata_gcontact_relation_get_type ()) +#define GDATA_GCONTACT_RELATION(o) (G_TYPE_CHECK_INSTANCE_CAST ((o), GDATA_TYPE_GCONTACT_RELATION, GDataGContactRelation)) +#define GDATA_GCONTACT_RELATION_CLASS(k) (G_TYPE_CHECK_CLASS_CAST((k), GDATA_TYPE_GCONTACT_RELATION, GDataGContactRelationClass)) +#define GDATA_IS_GCONTACT_RELATION(o) (G_TYPE_CHECK_INSTANCE_TYPE ((o), GDATA_TYPE_GCONTACT_RELATION)) +#define GDATA_IS_GCONTACT_RELATION_CLASS(k) (G_TYPE_CHECK_CLASS_TYPE ((k), GDATA_TYPE_GCONTACT_RELATION)) +#define GDATA_GCONTACT_RELATION_GET_CLASS(o) (G_TYPE_INSTANCE_GET_CLASS ((o), GDATA_TYPE_GCONTACT_RELATION, GDataGContactRelationClass)) + +typedef struct _GDataGContactRelationPrivate GDataGContactRelationPrivate; + +/** + * GDataGContactRelation: + * + * All the fields in the #GDataGContactRelation structure are private and should never be accessed directly. + * + * Since: 0.7.0 + */ +typedef struct { + GDataParsable parent; + GDataGContactRelationPrivate *priv; +} GDataGContactRelation; + +/** + * GDataGContactRelationClass: + * + * All the fields in the #GDataGContactRelationClass structure are private and should never be accessed directly. + * + * Since: 0.7.0 + */ +typedef struct { + /*< private >*/ + GDataParsableClass parent; + + /*< private >*/ + /* Padding for future expansion */ + void (*_g_reserved0) (void); + void (*_g_reserved1) (void); +} GDataGContactRelationClass; + +GType gdata_gcontact_relation_get_type (void) G_GNUC_CONST; + +GDataGContactRelation *gdata_gcontact_relation_new (const gchar *name, const gchar *relation_type, + const gchar *label) G_GNUC_WARN_UNUSED_RESULT G_GNUC_MALLOC; + +const gchar *gdata_gcontact_relation_get_name (GDataGContactRelation *self) G_GNUC_PURE; +void gdata_gcontact_relation_set_name (GDataGContactRelation *self, const gchar *name); + +const gchar *gdata_gcontact_relation_get_relation_type (GDataGContactRelation *self) G_GNUC_PURE; +void gdata_gcontact_relation_set_relation_type (GDataGContactRelation *self, const gchar *relation_type); + +const gchar *gdata_gcontact_relation_get_label (GDataGContactRelation *self) G_GNUC_PURE; +void gdata_gcontact_relation_set_label (GDataGContactRelation *self, const gchar *label); + +G_END_DECLS + +#endif /* !GDATA_GCONTACT_RELATION_H */ diff --git a/gdata/gcontact/gdata-gcontact-website.c b/gdata/gcontact/gdata-gcontact-website.c new file mode 100644 index 0000000..e0ec4c6 --- /dev/null +++ b/gdata/gcontact/gdata-gcontact-website.c @@ -0,0 +1,481 @@ +/* -*- Mode: C; indent-tabs-mode: t; c-basic-offset: 8; tab-width: 8 -*- */ +/* + * GData Client + * Copyright (C) Philip Withnall 2010 + * + * GData Client is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * GData Client is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with GData Client. If not, see . + */ + +/** + * SECTION:gdata-gcontact-website + * @short_description: gContact website element + * @stability: Stable + * @include: gdata/gcontact/gdata-gcontact-website.h + * + * #GDataGContactWebsite represents a "website" element from the + * gContact specification. + * + * Since: 0.7.0 + */ + +#include +#include + +#include "gdata-gcontact-website.h" +#include "gdata-parsable.h" +#include "gdata-parser.h" +#include "gdata-comparable.h" + +static void gdata_gcontact_website_comparable_init (GDataComparableIface *iface); +static void gdata_gcontact_website_finalize (GObject *object); +static void gdata_gcontact_website_get_property (GObject *object, guint property_id, GValue *value, GParamSpec *pspec); +static void gdata_gcontact_website_set_property (GObject *object, guint property_id, const GValue *value, GParamSpec *pspec); +static gboolean pre_parse_xml (GDataParsable *parsable, xmlDoc *doc, xmlNode *root_node, gpointer user_data, GError **error); +static void pre_get_xml (GDataParsable *parsable, GString *xml_string); +static void get_namespaces (GDataParsable *parsable, GHashTable *namespaces); + +struct _GDataGContactWebsitePrivate { + gchar *uri; + gchar *relation_type; + gchar *label; + gboolean is_primary; +}; + +enum { + PROP_URI = 1, + PROP_RELATION_TYPE, + PROP_LABEL, + PROP_IS_PRIMARY +}; + +G_DEFINE_TYPE_WITH_CODE (GDataGContactWebsite, gdata_gcontact_website, GDATA_TYPE_PARSABLE, + G_IMPLEMENT_INTERFACE (GDATA_TYPE_COMPARABLE, gdata_gcontact_website_comparable_init)) + +static void +gdata_gcontact_website_class_init (GDataGContactWebsiteClass *klass) +{ + GObjectClass *gobject_class = G_OBJECT_CLASS (klass); + GDataParsableClass *parsable_class = GDATA_PARSABLE_CLASS (klass); + + g_type_class_add_private (klass, sizeof (GDataGContactWebsitePrivate)); + + gobject_class->get_property = gdata_gcontact_website_get_property; + gobject_class->set_property = gdata_gcontact_website_set_property; + gobject_class->finalize = gdata_gcontact_website_finalize; + + parsable_class->pre_parse_xml = pre_parse_xml; + parsable_class->pre_get_xml = pre_get_xml; + parsable_class->get_namespaces = get_namespaces; + parsable_class->element_name = "website"; + parsable_class->element_namespace = "gContact"; + + /** + * GDataGContactWebsite:uri: + * + * The URI of the website. + * + * For more information, see the + * gContact specification. + * + * Since: 0.7.0 + */ + g_object_class_install_property (gobject_class, PROP_URI, + g_param_spec_string ("uri", + "URI", "The URI of the website.", + NULL, + G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)); + + /** + * GDataGContactWebsite:relation-type: + * + * A programmatic value that identifies the type of website. Examples are %GDATA_GCONTACT_WEBSITE_HOME_PAGE or %GDATA_GCONTACT_WEBSITE_FTP. + * It is mutually exclusive with #GDataGContactWebsite:label. + * + * For more information, see the + * gContact specification. + * + * Since: 0.7.0 + */ + g_object_class_install_property (gobject_class, PROP_RELATION_TYPE, + g_param_spec_string ("relation-type", + "Relation type", "A programmatic value that identifies the type of website.", + NULL, + G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)); + + /** + * GDataGContactWebsite:label: + * + * A simple string value used to name this website. It allows UIs to display a label such as "Work", "Travel blog", "Personal blog", etc. + * It is mutually exclusive with #GDataGContactWebsite:relation-type. + * + * For more information, see the + * gContact specification. + * + * Since: 0.7.0 + */ + g_object_class_install_property (gobject_class, PROP_LABEL, + g_param_spec_string ("label", + "Label", "A simple string value used to name this website.", + NULL, + G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)); + + /** + * GDataGContactWebsite:is-primary: + * + * Indicates which website out of a group is primary. + * + * For more information, see the + * gContact specification. + * + * Since: 0.7.0 + */ + g_object_class_install_property (gobject_class, PROP_IS_PRIMARY, + g_param_spec_boolean ("is-primary", + "Primary?", "Indicates which website out of a group is primary.", + FALSE, + G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)); +} + +static gint +compare_with (GDataComparable *self, GDataComparable *other) +{ + GDataGContactWebsitePrivate *a = ((GDataGContactWebsite*) self)->priv, *b = ((GDataGContactWebsite*) other)->priv; + + if (g_strcmp0 (a->uri, b->uri) == 0 && g_strcmp0 (a->relation_type, b->relation_type) == 0 && g_strcmp0 (a->label, b->label) == 0) + return 0; + return 1; +} + +static void +gdata_gcontact_website_comparable_init (GDataComparableIface *iface) +{ + iface->compare_with = compare_with; +} + +static void +gdata_gcontact_website_init (GDataGContactWebsite *self) +{ + self->priv = G_TYPE_INSTANCE_GET_PRIVATE (self, GDATA_TYPE_GCONTACT_WEBSITE, GDataGContactWebsitePrivate); +} + +static void +gdata_gcontact_website_finalize (GObject *object) +{ + GDataGContactWebsitePrivate *priv = GDATA_GCONTACT_WEBSITE (object)->priv; + + g_free (priv->uri); + g_free (priv->relation_type); + g_free (priv->label); + + /* Chain up to the parent class */ + G_OBJECT_CLASS (gdata_gcontact_website_parent_class)->finalize (object); +} + +static void +gdata_gcontact_website_get_property (GObject *object, guint property_id, GValue *value, GParamSpec *pspec) +{ + GDataGContactWebsitePrivate *priv = GDATA_GCONTACT_WEBSITE (object)->priv; + + switch (property_id) { + case PROP_URI: + g_value_set_string (value, priv->uri); + break; + case PROP_RELATION_TYPE: + g_value_set_string (value, priv->relation_type); + break; + case PROP_LABEL: + g_value_set_string (value, priv->label); + break; + case PROP_IS_PRIMARY: + g_value_set_boolean (value, priv->is_primary); + break; + default: + /* We don't have any other property... */ + G_OBJECT_WARN_INVALID_PROPERTY_ID (object, property_id, pspec); + break; + } +} + +static void +gdata_gcontact_website_set_property (GObject *object, guint property_id, const GValue *value, GParamSpec *pspec) +{ + GDataGContactWebsite *self = GDATA_GCONTACT_WEBSITE (object); + + switch (property_id) { + case PROP_URI: + gdata_gcontact_website_set_uri (self, g_value_get_string (value)); + break; + case PROP_RELATION_TYPE: + gdata_gcontact_website_set_relation_type (self, g_value_get_string (value)); + break; + case PROP_LABEL: + gdata_gcontact_website_set_label (self, g_value_get_string (value)); + break; + case PROP_IS_PRIMARY: + gdata_gcontact_website_set_is_primary (self, g_value_get_boolean (value)); + break; + default: + /* We don't have any other property... */ + G_OBJECT_WARN_INVALID_PROPERTY_ID (object, property_id, pspec); + break; + } +} + +static gboolean +pre_parse_xml (GDataParsable *parsable, xmlDoc *doc, xmlNode *root_node, gpointer user_data, GError **error) +{ + xmlChar *uri, *rel, *label; + gboolean primary_bool; + GDataGContactWebsitePrivate *priv = GDATA_GCONTACT_WEBSITE (parsable)->priv; + + /* Is it the primary website? */ + if (gdata_parser_boolean_from_property (root_node, "primary", &primary_bool, 0, error) == FALSE) + return FALSE; + + uri = xmlGetProp (root_node, (xmlChar*) "href"); + if (uri == NULL || *uri == '\0') { + xmlFree (uri); + return gdata_parser_error_required_property_missing (root_node, "href", error); + } + + /* NOTE: We allow both rel and label to be present when we should probably be asserting that they're mutually exclusive. See the comment in + * pre_get_xml() for details. */ + rel = xmlGetProp (root_node, (xmlChar*) "rel"); + label = xmlGetProp (root_node, (xmlChar*) "label"); + if ((rel == NULL || *rel == '\0') && (label == NULL || *label == '\0')) { + xmlFree (rel); + xmlFree (label); + xmlFree (uri); + return gdata_parser_error_required_property_missing (root_node, "rel", error); + } + + priv->relation_type = (gchar*) rel; + priv->label = (gchar*) label; + priv->uri = (gchar*) uri; + priv->is_primary = primary_bool; + + return TRUE; +} + +static void +pre_get_xml (GDataParsable *parsable, GString *xml_string) +{ + GDataGContactWebsitePrivate *priv = GDATA_GCONTACT_WEBSITE (parsable)->priv; + + gdata_parser_string_append_escaped (xml_string, " href='", priv->uri, "'"); + + /* NOTE: We previously allowed both rel and label to be set, making rel mandatory. Since bgo#659016, we treat rel and label as mutually + * exclusive attributes when parsing. We should treat them as mutually exclusive here as well, and g_assert_not_reached() if neither or + * both are set (as in gdata-gcontact-event.c:pre_get_xml()), but in order to maintain backwards compatibility, we don't. + * Sigh, Google. */ + if (priv->relation_type != NULL) { + gdata_parser_string_append_escaped (xml_string, " rel='", priv->relation_type, "'"); + } + + if (priv->label != NULL) { + gdata_parser_string_append_escaped (xml_string, " label='", priv->label, "'"); + } + + if (priv->is_primary == TRUE) + g_string_append (xml_string, " primary='true'"); + else + g_string_append (xml_string, " primary='false'"); +} + +static void +get_namespaces (GDataParsable *parsable, GHashTable *namespaces) +{ + g_hash_table_insert (namespaces, (gchar*) "gContact", (gchar*) "http://schemas.google.com/contact/2008"); +} + +/** + * gdata_gcontact_website_new: + * @uri: the website URI + * @relation_type: the relationship between the website and its owner, or %NULL + * @label: (allow-none): a human-readable label for the website, or %NULL + * @is_primary: %TRUE if this website is its owner's primary website, %FALSE otherwise + * + * Creates a new #GDataGContactWebsite. More information is available in the gContact specification. + * + * Exactly one of @relation_type and @label should be provided; the other must be %NULL. + * + * Return value: a new #GDataGContactWebsite; unref with g_object_unref() + * + * Since: 0.7.0 + */ +GDataGContactWebsite * +gdata_gcontact_website_new (const gchar *uri, const gchar *relation_type, const gchar *label, gboolean is_primary) +{ + g_return_val_if_fail (uri != NULL && *uri != '\0', NULL); + g_return_val_if_fail ((relation_type != NULL && *relation_type != '\0'/* && label == NULL*/) || + (relation_type == NULL && label != NULL && *label != '\0'), NULL); + /* NOTE: As in pre_get_xml(), we should treat rel and label as mutually exclusive here, but we can't for backwards compatibility reasons. */ + + return g_object_new (GDATA_TYPE_GCONTACT_WEBSITE, "uri", uri, "relation-type", relation_type, "label", label, "is-primary", is_primary, NULL); +} + +/** + * gdata_gcontact_website_get_uri: + * @self: a #GDataGContactWebsite + * + * Gets the #GDataGContactWebsite:uri property. + * + * Return value: the URI of the website + * + * Since: 0.7.0 + */ +const gchar * +gdata_gcontact_website_get_uri (GDataGContactWebsite *self) +{ + g_return_val_if_fail (GDATA_IS_GCONTACT_WEBSITE (self), NULL); + return self->priv->uri; +} + +/** + * gdata_gcontact_website_set_uri: + * @self: a #GDataGContactWebsite + * @uri: the new website URI + * + * Sets the #GDataGContactWebsite:uri property to @uri. + * + * Since: 0.7.0 + */ +void +gdata_gcontact_website_set_uri (GDataGContactWebsite *self, const gchar *uri) +{ + g_return_if_fail (GDATA_IS_GCONTACT_WEBSITE (self)); + g_return_if_fail (uri != NULL && *uri != '\0'); + + g_free (self->priv->uri); + self->priv->uri = g_strdup (uri); + g_object_notify (G_OBJECT (self), "uri"); +} + +/** + * gdata_gcontact_website_get_relation_type: + * @self: a #GDataGContactWebsite + * + * Gets the #GDataGContactWebsite:relation-type property. + * + * Return value: the website's relation type + * + * Since: 0.7.0 + */ +const gchar * +gdata_gcontact_website_get_relation_type (GDataGContactWebsite *self) +{ + g_return_val_if_fail (GDATA_IS_GCONTACT_WEBSITE (self), NULL); + return self->priv->relation_type; +} + +/** + * gdata_gcontact_website_set_relation_type: + * @self: a #GDataGContactWebsite + * @relation_type: the new relation type for the website + * + * Sets the #GDataGContactWebsite:relation-type property to @relation_type + * such as %GDATA_GCONTACT_WEBSITE_HOME_PAGE or %GDATA_GCONTACT_WEBSITE_FTP. + * + * If @relation_type is %NULL, the relation type will be unset. When the #GDataGContactWebsite is used in a query, however, + * exactly one of #GDataGContactWebsite:relation-type and #GDataGContactWebsite:label must be %NULL. + * + * Since: 0.7.0 + */ +void +gdata_gcontact_website_set_relation_type (GDataGContactWebsite *self, const gchar *relation_type) +{ + g_return_if_fail (GDATA_IS_GCONTACT_WEBSITE (self)); + g_return_if_fail (relation_type == NULL || *relation_type != '\0'); + + g_free (self->priv->relation_type); + self->priv->relation_type = g_strdup (relation_type); + g_object_notify (G_OBJECT (self), "relation-type"); +} + +/** + * gdata_gcontact_website_get_label: + * @self: a #GDataGContactWebsite + * + * Gets the #GDataGContactWebsite:label property. + * + * Return value: the website's label, or %NULL + * + * Since: 0.7.0 + */ +const gchar * +gdata_gcontact_website_get_label (GDataGContactWebsite *self) +{ + g_return_val_if_fail (GDATA_IS_GCONTACT_WEBSITE (self), NULL); + return self->priv->label; +} + +/** + * gdata_gcontact_website_set_label: + * @self: a #GDataGContactWebsite + * @label: (allow-none): the new label for the website, or %NULL + * + * Sets the #GDataGContactWebsite:label property to @label. + * + * If @label is %NULL, the label will be unset. When the #GDataGContactWebsite is used in a query, however, + * exactly one of #GDataGContactWebsite:relation-type and #GDataGContactWebsite:label must be %NULL. + * + * Since: 0.7.0 + */ +void +gdata_gcontact_website_set_label (GDataGContactWebsite *self, const gchar *label) +{ + g_return_if_fail (GDATA_IS_GCONTACT_WEBSITE (self)); + /* NOTE: We should be validating using the code below, but we can't. See pre_get_xml() for details. */ + g_return_if_fail (label == NULL || *label != '\0'); + + g_free (self->priv->label); + self->priv->label = g_strdup (label); + g_object_notify (G_OBJECT (self), "label"); +} + +/** + * gdata_gcontact_website_is_primary: + * @self: a #GDataGContactWebsite + * + * Gets the #GDataGContactWebsite:is-primary property. + * + * Return value: %TRUE if this is the primary website, %FALSE otherwise + * + * Since: 0.7.0 + */ +gboolean +gdata_gcontact_website_is_primary (GDataGContactWebsite *self) +{ + g_return_val_if_fail (GDATA_IS_GCONTACT_WEBSITE (self), FALSE); + return self->priv->is_primary; +} + +/** + * gdata_gcontact_website_set_is_primary: + * @self: a #GDataGContactWebsite + * @is_primary: %TRUE if this is the primary website, %FALSE otherwise + * + * Sets the #GDataGContactWebsite:is-primary property to @is_primary. + * + * Since: 0.7.0 + */ +void +gdata_gcontact_website_set_is_primary (GDataGContactWebsite *self, gboolean is_primary) +{ + g_return_if_fail (GDATA_IS_GCONTACT_WEBSITE (self)); + + self->priv->is_primary = is_primary; + g_object_notify (G_OBJECT (self), "is-primary"); +} diff --git a/gdata/gcontact/gdata-gcontact-website.h b/gdata/gcontact/gdata-gcontact-website.h new file mode 100644 index 0000000..c96d30b --- /dev/null +++ b/gdata/gcontact/gdata-gcontact-website.h @@ -0,0 +1,171 @@ +/* -*- Mode: C; indent-tabs-mode: t; c-basic-offset: 8; tab-width: 8 -*- */ +/* + * GData Client + * Copyright (C) Philip Withnall 2010 + * + * GData Client is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * GData Client is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with GData Client. If not, see . + */ + +#ifndef GDATA_GCONTACT_WEBSITE_H +#define GDATA_GCONTACT_WEBSITE_H + +#include +#include + +#include + +G_BEGIN_DECLS + +/** + * GDATA_GCONTACT_WEBSITE_HOME_PAGE: + * + * The relation type URI for a contact's home page. + * + * For more information, see the + * gContact specification. + * + * Since: 0.7.0 + */ +#define GDATA_GCONTACT_WEBSITE_HOME_PAGE "home-page" + +/** + * GDATA_GCONTACT_WEBSITE_BLOG: + * + * The relation type URI for a contact's blog. + * + * For more information, see the + * gContact specification. + * + * Since: 0.7.0 + */ +#define GDATA_GCONTACT_WEBSITE_BLOG "blog" + +/** + * GDATA_GCONTACT_WEBSITE_PROFILE: + * + * The relation type URI for a contact's online profile. + * + * For more information, see the + * gContact specification. + * + * Since: 0.7.0 + */ +#define GDATA_GCONTACT_WEBSITE_PROFILE "profile" + +/** + * GDATA_GCONTACT_WEBSITE_HOME: + * + * The relation type URI for a contact's home website. + * + * For more information, see the + * gContact specification. + * + * Since: 0.7.0 + */ +#define GDATA_GCONTACT_WEBSITE_HOME "home" + +/** + * GDATA_GCONTACT_WEBSITE_WORK: + * + * The relation type URI for a contact's work website. + * + * For more information, see the + * gContact specification. + * + * Since: 0.7.0 + */ +#define GDATA_GCONTACT_WEBSITE_WORK "work" + +/** + * GDATA_GCONTACT_WEBSITE_OTHER: + * + * The relation type URI for a miscellaneous website of the contact. + * + * For more information, see the + * gContact specification. + * + * Since: 0.7.0 + */ +#define GDATA_GCONTACT_WEBSITE_OTHER "other" + +/** + * GDATA_GCONTACT_WEBSITE_FTP: + * + * The relation type URI for a contact's FTP site. + * + * For more information, see the + * gContact specification. + * + * Since: 0.7.0 + */ +#define GDATA_GCONTACT_WEBSITE_FTP "ftp" + +#define GDATA_TYPE_GCONTACT_WEBSITE (gdata_gcontact_website_get_type ()) +#define GDATA_GCONTACT_WEBSITE(o) (G_TYPE_CHECK_INSTANCE_CAST ((o), GDATA_TYPE_GCONTACT_WEBSITE, GDataGContactWebsite)) +#define GDATA_GCONTACT_WEBSITE_CLASS(k) (G_TYPE_CHECK_CLASS_CAST((k), GDATA_TYPE_GCONTACT_WEBSITE, GDataGContactWebsiteClass)) +#define GDATA_IS_GCONTACT_WEBSITE(o) (G_TYPE_CHECK_INSTANCE_TYPE ((o), GDATA_TYPE_GCONTACT_WEBSITE)) +#define GDATA_IS_GCONTACT_WEBSITE_CLASS(k) (G_TYPE_CHECK_CLASS_TYPE ((k), GDATA_TYPE_GCONTACT_WEBSITE)) +#define GDATA_GCONTACT_WEBSITE_GET_CLASS(o) (G_TYPE_INSTANCE_GET_CLASS ((o), GDATA_TYPE_GCONTACT_WEBSITE, GDataGContactWebsiteClass)) + +typedef struct _GDataGContactWebsitePrivate GDataGContactWebsitePrivate; + +/** + * GDataGContactWebsite: + * + * All the fields in the #GDataGContactWebsite structure are private and should never be accessed directly. + * + * Since: 0.7.0 + */ +typedef struct { + GDataParsable parent; + GDataGContactWebsitePrivate *priv; +} GDataGContactWebsite; + +/** + * GDataGContactWebsiteClass: + * + * All the fields in the #GDataGContactWebsiteClass structure are private and should never be accessed directly. + * + * Since: 0.7.0 + */ +typedef struct { + /*< private >*/ + GDataParsableClass parent; + + /*< private >*/ + /* Padding for future expansion */ + void (*_g_reserved0) (void); + void (*_g_reserved1) (void); +} GDataGContactWebsiteClass; + +GType gdata_gcontact_website_get_type (void) G_GNUC_CONST; + +GDataGContactWebsite *gdata_gcontact_website_new (const gchar *uri, const gchar *relation_type, + const gchar *label, gboolean is_primary) G_GNUC_WARN_UNUSED_RESULT G_GNUC_MALLOC; + +const gchar *gdata_gcontact_website_get_uri (GDataGContactWebsite *self) G_GNUC_PURE; +void gdata_gcontact_website_set_uri (GDataGContactWebsite *self, const gchar *uri); + +const gchar *gdata_gcontact_website_get_relation_type (GDataGContactWebsite *self) G_GNUC_PURE; +void gdata_gcontact_website_set_relation_type (GDataGContactWebsite *self, const gchar *relation_type); + +const gchar *gdata_gcontact_website_get_label (GDataGContactWebsite *self) G_GNUC_PURE; +void gdata_gcontact_website_set_label (GDataGContactWebsite *self, const gchar *label); + +gboolean gdata_gcontact_website_is_primary (GDataGContactWebsite *self) G_GNUC_PURE; +void gdata_gcontact_website_set_is_primary (GDataGContactWebsite *self, gboolean is_primary); + +G_END_DECLS + +#endif /* !GDATA_GCONTACT_WEBSITE_H */ diff --git a/gdata/gcontact/meson.build b/gdata/gcontact/meson.build new file mode 100644 index 0000000..7dbcd1e --- /dev/null +++ b/gdata/gcontact/meson.build @@ -0,0 +1,26 @@ +headers = files( + 'gdata-gcontact-calendar.h', + 'gdata-gcontact-event.h', + 'gdata-gcontact-external-id.h', + 'gdata-gcontact-jot.h', + 'gdata-gcontact-language.h', + 'gdata-gcontact-relation.h', + 'gdata-gcontact-website.h', +) + +install_headers( + headers, + subdir: gdata_include_subdir / 'gcontact', +) + +gir_headers += headers + +sources += files( + 'gdata-gcontact-calendar.c', + 'gdata-gcontact-event.c', + 'gdata-gcontact-external-id.c', + 'gdata-gcontact-jot.c', + 'gdata-gcontact-language.c', + 'gdata-gcontact-relation.c', + 'gdata-gcontact-website.c', +) diff --git a/gdata/gd/gdata-gd-email-address.c b/gdata/gd/gdata-gd-email-address.c new file mode 100644 index 0000000..63ae95b --- /dev/null +++ b/gdata/gd/gdata-gd-email-address.c @@ -0,0 +1,520 @@ +/* -*- Mode: C; indent-tabs-mode: t; c-basic-offset: 8; tab-width: 8 -*- */ +/* + * GData Client + * Copyright (C) Philip Withnall 2009–2010 + * + * GData Client is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * GData Client is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with GData Client. If not, see . + */ + +/** + * SECTION:gdata-gd-email-address + * @short_description: GData e-mail address element + * @stability: Stable + * @include: gdata/gd/gdata-gd-email-address.h + * + * #GDataGDEmailAddress represents an "email" element from the + * GData specification. + * + * Since: 0.4.0 + */ + +#include +#include + +#include "gdata-gd-email-address.h" +#include "gdata-parsable.h" +#include "gdata-parser.h" +#include "gdata-comparable.h" + +static void gdata_gd_email_address_comparable_init (GDataComparableIface *iface); +static void gdata_gd_email_address_finalize (GObject *object); +static void gdata_gd_email_address_get_property (GObject *object, guint property_id, GValue *value, GParamSpec *pspec); +static void gdata_gd_email_address_set_property (GObject *object, guint property_id, const GValue *value, GParamSpec *pspec); +static gboolean pre_parse_xml (GDataParsable *parsable, xmlDoc *doc, xmlNode *root_node, gpointer user_data, GError **error); +static void pre_get_xml (GDataParsable *parsable, GString *xml_string); +static void get_namespaces (GDataParsable *parsable, GHashTable *namespaces); + +struct _GDataGDEmailAddressPrivate { + gchar *address; + gchar *relation_type; + gchar *label; + gboolean is_primary; + gchar *display_name; +}; + +enum { + PROP_ADDRESS = 1, + PROP_RELATION_TYPE, + PROP_LABEL, + PROP_IS_PRIMARY, + PROP_DISPLAY_NAME +}; + +G_DEFINE_TYPE_WITH_CODE (GDataGDEmailAddress, gdata_gd_email_address, GDATA_TYPE_PARSABLE, + G_IMPLEMENT_INTERFACE (GDATA_TYPE_COMPARABLE, gdata_gd_email_address_comparable_init)) + +static void +gdata_gd_email_address_class_init (GDataGDEmailAddressClass *klass) +{ + GObjectClass *gobject_class = G_OBJECT_CLASS (klass); + GDataParsableClass *parsable_class = GDATA_PARSABLE_CLASS (klass); + + g_type_class_add_private (klass, sizeof (GDataGDEmailAddressPrivate)); + + gobject_class->get_property = gdata_gd_email_address_get_property; + gobject_class->set_property = gdata_gd_email_address_set_property; + gobject_class->finalize = gdata_gd_email_address_finalize; + + parsable_class->pre_parse_xml = pre_parse_xml; + parsable_class->pre_get_xml = pre_get_xml; + parsable_class->get_namespaces = get_namespaces; + parsable_class->element_name = "email"; + parsable_class->element_namespace = "gd"; + + /** + * GDataGDEmailAddress:address: + * + * The e-mail address itself. + * + * For more information, see the + * GData specification. + * + * Since: 0.4.0 + */ + g_object_class_install_property (gobject_class, PROP_ADDRESS, + g_param_spec_string ("address", + "Address", "The e-mail address itself.", + NULL, + G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)); + + /** + * GDataGDEmailAddress:relation-type: + * + * A programmatic value that identifies the type of e-mail address. For example: %GDATA_GD_EMAIL_ADDRESS_HOME or %GDATA_GD_EMAIL_ADDRESS_WORK. + * + * For more information, see the + * GData specification. + * + * Since: 0.4.0 + */ + g_object_class_install_property (gobject_class, PROP_RELATION_TYPE, + g_param_spec_string ("relation-type", + "Relation type", "A programmatic value that identifies the type of e-mail address.", + NULL, + G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)); + + /** + * GDataGDEmailAddress:label: + * + * A simple string value used to name this e-mail address. It allows UIs to display a label such as "Work", "Personal", "Preferred", etc. + * + * For more information, see the + * GData specification. + * + * Since: 0.4.0 + */ + g_object_class_install_property (gobject_class, PROP_LABEL, + g_param_spec_string ("label", + "Label", "A simple string value used to name this e-mail address.", + NULL, + G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)); + + /** + * GDataGDEmailAddress:is-primary: + * + * Indicates which e-mail address out of a group is primary. + * + * For more information, see the + * GData specification. + * + * Since: 0.4.0 + */ + g_object_class_install_property (gobject_class, PROP_IS_PRIMARY, + g_param_spec_boolean ("is-primary", + "Primary?", "Indicates which e-mail address out of a group is primary.", + FALSE, + G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)); + + /** + * GDataGDEmailAddress:display-name: + * + * A display name of the entity (e.g. a person) the e-mail address belongs to. + * + * For more information, see the + * GData specification. + * + * Since: 0.6.0 + */ + g_object_class_install_property (gobject_class, PROP_DISPLAY_NAME, + g_param_spec_string ("display-name", + "Display name", "A display name of the entity the e-mail address belongs to.", + NULL, + G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)); +} + +static gint +compare_with (GDataComparable *self, GDataComparable *other) +{ + return g_strcmp0 (((GDataGDEmailAddress*) self)->priv->address, ((GDataGDEmailAddress*) other)->priv->address); +} + +static void +gdata_gd_email_address_comparable_init (GDataComparableIface *iface) +{ + iface->compare_with = compare_with; +} + +static void +gdata_gd_email_address_init (GDataGDEmailAddress *self) +{ + self->priv = G_TYPE_INSTANCE_GET_PRIVATE (self, GDATA_TYPE_GD_EMAIL_ADDRESS, GDataGDEmailAddressPrivate); +} + +static void +gdata_gd_email_address_finalize (GObject *object) +{ + GDataGDEmailAddressPrivate *priv = GDATA_GD_EMAIL_ADDRESS (object)->priv; + + g_free (priv->address); + g_free (priv->relation_type); + g_free (priv->label); + g_free (priv->display_name); + + /* Chain up to the parent class */ + G_OBJECT_CLASS (gdata_gd_email_address_parent_class)->finalize (object); +} + +static void +gdata_gd_email_address_get_property (GObject *object, guint property_id, GValue *value, GParamSpec *pspec) +{ + GDataGDEmailAddressPrivate *priv = GDATA_GD_EMAIL_ADDRESS (object)->priv; + + switch (property_id) { + case PROP_ADDRESS: + g_value_set_string (value, priv->address); + break; + case PROP_RELATION_TYPE: + g_value_set_string (value, priv->relation_type); + break; + case PROP_LABEL: + g_value_set_string (value, priv->label); + break; + case PROP_IS_PRIMARY: + g_value_set_boolean (value, priv->is_primary); + break; + case PROP_DISPLAY_NAME: + g_value_set_string (value, priv->display_name); + break; + default: + /* We don't have any other property... */ + G_OBJECT_WARN_INVALID_PROPERTY_ID (object, property_id, pspec); + break; + } +} + +static void +gdata_gd_email_address_set_property (GObject *object, guint property_id, const GValue *value, GParamSpec *pspec) +{ + GDataGDEmailAddress *self = GDATA_GD_EMAIL_ADDRESS (object); + + switch (property_id) { + case PROP_ADDRESS: + gdata_gd_email_address_set_address (self, g_value_get_string (value)); + break; + case PROP_RELATION_TYPE: + gdata_gd_email_address_set_relation_type (self, g_value_get_string (value)); + break; + case PROP_LABEL: + gdata_gd_email_address_set_label (self, g_value_get_string (value)); + break; + case PROP_IS_PRIMARY: + gdata_gd_email_address_set_is_primary (self, g_value_get_boolean (value)); + break; + case PROP_DISPLAY_NAME: + gdata_gd_email_address_set_display_name (self, g_value_get_string (value)); + break; + default: + /* We don't have any other property... */ + G_OBJECT_WARN_INVALID_PROPERTY_ID (object, property_id, pspec); + break; + } +} + +static gboolean +pre_parse_xml (GDataParsable *parsable, xmlDoc *doc, xmlNode *root_node, gpointer user_data, GError **error) +{ + xmlChar *address, *rel; + gboolean primary_bool; + GDataGDEmailAddressPrivate *priv = GDATA_GD_EMAIL_ADDRESS (parsable)->priv; + + /* Is it the primary e-mail address? */ + if (gdata_parser_boolean_from_property (root_node, "primary", &primary_bool, 0, error) == FALSE) + return FALSE; + + address = xmlGetProp (root_node, (xmlChar*) "address"); + if (address == NULL || *address == '\0') { + xmlFree (address); + return gdata_parser_error_required_property_missing (root_node, "address", error); + } + + rel = xmlGetProp (root_node, (xmlChar*) "rel"); + if (rel != NULL && *rel == '\0') { + xmlFree (address); + xmlFree (rel); + return gdata_parser_error_required_property_missing (root_node, "rel", error); + } + + priv->address = (gchar*) address; + priv->relation_type = (gchar*) rel; + priv->label = (gchar*) xmlGetProp (root_node, (xmlChar*) "label"); + priv->is_primary = primary_bool; + priv->display_name = (gchar*) xmlGetProp (root_node, (xmlChar*) "displayName"); + + return TRUE; +} + +static void +pre_get_xml (GDataParsable *parsable, GString *xml_string) +{ + GDataGDEmailAddressPrivate *priv = GDATA_GD_EMAIL_ADDRESS (parsable)->priv; + + gdata_parser_string_append_escaped (xml_string, " address='", priv->address, "'"); + if (priv->relation_type != NULL) + gdata_parser_string_append_escaped (xml_string, " rel='", priv->relation_type, "'"); + if (priv->label != NULL) + gdata_parser_string_append_escaped (xml_string, " label='", priv->label, "'"); + if (priv->display_name != NULL) + gdata_parser_string_append_escaped (xml_string, " displayName='", priv->display_name, "'"); + + if (priv->is_primary == TRUE) + g_string_append (xml_string, " primary='true'"); + else + g_string_append (xml_string, " primary='false'"); +} + +static void +get_namespaces (GDataParsable *parsable, GHashTable *namespaces) +{ + g_hash_table_insert (namespaces, (gchar*) "gd", (gchar*) "http://schemas.google.com/g/2005"); +} + +/** + * gdata_gd_email_address_new: + * @address: the e-mail address + * @relation_type: (allow-none): the relationship between the e-mail address and its owner, or %NULL + * @label: (allow-none): a human-readable label for the e-mail address, or %NULL + * @is_primary: %TRUE if this e-mail address is its owner's primary address, %FALSE otherwise + * + * Creates a new #GDataGDEmailAddress. More information is available in the GData specification. + * + * Return value: a new #GDataGDEmailAddress, or %NULL; unref with g_object_unref() + * + * Since: 0.2.0 + */ +GDataGDEmailAddress * +gdata_gd_email_address_new (const gchar *address, const gchar *relation_type, const gchar *label, gboolean is_primary) +{ + g_return_val_if_fail (address != NULL && *address != '\0', NULL); + g_return_val_if_fail (relation_type == NULL || *relation_type != '\0', NULL); + return g_object_new (GDATA_TYPE_GD_EMAIL_ADDRESS, "address", address, "relation-type", relation_type, + "label", label, "is-primary", is_primary, NULL); +} + +/** + * gdata_gd_email_address_get_address: + * @self: a #GDataGDEmailAddress + * + * Gets the #GDataGDEmailAddress:address property. + * + * Return value: the e-mail address itself, or %NULL + * + * Since: 0.4.0 + */ +const gchar * +gdata_gd_email_address_get_address (GDataGDEmailAddress *self) +{ + g_return_val_if_fail (GDATA_IS_GD_EMAIL_ADDRESS (self), NULL); + return self->priv->address; +} + +/** + * gdata_gd_email_address_set_address: + * @self: a #GDataGDEmailAddress + * @address: the new e-mail address + * + * Sets the #GDataGDEmailAddress:address property to @address. + * + * Since: 0.4.0 + */ +void +gdata_gd_email_address_set_address (GDataGDEmailAddress *self, const gchar *address) +{ + g_return_if_fail (GDATA_IS_GD_EMAIL_ADDRESS (self)); + g_return_if_fail (address != NULL && *address != '\0'); + + g_free (self->priv->address); + self->priv->address = g_strdup (address); + g_object_notify (G_OBJECT (self), "address"); +} + +/** + * gdata_gd_email_address_get_relation_type: + * @self: a #GDataGDEmailAddress + * + * Gets the #GDataGDEmailAddress:relation-type property. + * + * Return value: the e-mail address' relation type, or %NULL + * + * Since: 0.4.0 + */ +const gchar * +gdata_gd_email_address_get_relation_type (GDataGDEmailAddress *self) +{ + g_return_val_if_fail (GDATA_IS_GD_EMAIL_ADDRESS (self), NULL); + return self->priv->relation_type; +} + +/** + * gdata_gd_email_address_set_relation_type: + * @self: a #GDataGDEmailAddress + * @relation_type: (allow-none): the new relation type for the email_address, or %NULL + * + * Sets the #GDataGDEmailAddress:relation-type property to @relation_type. + * + * Set @relation_type to %NULL to unset the property in the e-mail address. + * + * Since: 0.4.0 + */ +void +gdata_gd_email_address_set_relation_type (GDataGDEmailAddress *self, const gchar *relation_type) +{ + g_return_if_fail (GDATA_IS_GD_EMAIL_ADDRESS (self)); + g_return_if_fail (relation_type == NULL || *relation_type != '\0'); + + g_free (self->priv->relation_type); + self->priv->relation_type = g_strdup (relation_type); + g_object_notify (G_OBJECT (self), "relation-type"); +} + +/** + * gdata_gd_email_address_get_label: + * @self: a #GDataGDEmailAddress + * + * Gets the #GDataGDEmailAddress:label property. + * + * Return value: the e-mail address' label, or %NULL + * + * Since: 0.4.0 + */ +const gchar * +gdata_gd_email_address_get_label (GDataGDEmailAddress *self) +{ + g_return_val_if_fail (GDATA_IS_GD_EMAIL_ADDRESS (self), NULL); + return self->priv->label; +} + +/** + * gdata_gd_email_address_set_label: + * @self: a #GDataGDEmailAddress + * @label: (allow-none): the new label for the e-mail address, or %NULL + * + * Sets the #GDataGDEmailAddress:label property to @label. + * + * Set @label to %NULL to unset the property in the e-mail address. + * + * Since: 0.4.0 + */ +void +gdata_gd_email_address_set_label (GDataGDEmailAddress *self, const gchar *label) +{ + g_return_if_fail (GDATA_IS_GD_EMAIL_ADDRESS (self)); + + g_free (self->priv->label); + self->priv->label = g_strdup (label); + g_object_notify (G_OBJECT (self), "label"); +} + +/** + * gdata_gd_email_address_is_primary: + * @self: a #GDataGDEmailAddress + * + * Gets the #GDataGDEmailAddress:is-primary property. + * + * Return value: %TRUE if this is the primary e-mail address, %FALSE otherwise + * + * Since: 0.4.0 + */ +gboolean +gdata_gd_email_address_is_primary (GDataGDEmailAddress *self) +{ + g_return_val_if_fail (GDATA_IS_GD_EMAIL_ADDRESS (self), FALSE); + return self->priv->is_primary; +} + +/** + * gdata_gd_email_address_set_is_primary: + * @self: a #GDataGDEmailAddress + * @is_primary: %TRUE if this is the primary e-mail address, %FALSE otherwise + * + * Sets the #GDataGDEmailAddress:is-primary property to @is_primary. + * + * Since: 0.4.0 + */ +void +gdata_gd_email_address_set_is_primary (GDataGDEmailAddress *self, gboolean is_primary) +{ + g_return_if_fail (GDATA_IS_GD_EMAIL_ADDRESS (self)); + + self->priv->is_primary = is_primary; + g_object_notify (G_OBJECT (self), "is-primary"); +} + +/** + * gdata_gd_email_address_get_display_name: + * @self: a #GDataGDEmailAddress + * + * Gets the #GDataGDEmailAddress:display-name property. + * + * Return value: a display name for the e-mail address, or %NULL + * + * Since: 0.6.0 + */ +const gchar * +gdata_gd_email_address_get_display_name (GDataGDEmailAddress *self) +{ + g_return_val_if_fail (GDATA_IS_GD_EMAIL_ADDRESS (self), NULL); + return self->priv->display_name; +} + +/** + * gdata_gd_email_address_set_display_name: + * @self: a #GDataGDEmailAddress + * @display_name: (allow-none): the new display name, or %NULL + * + * Sets the #GDataGDEmailAddress:display-name property to @display_name. + * + * Set @display_name to %NULL to unset the property in the e-mail address. + * + * Since: 0.6.0 + */ +void +gdata_gd_email_address_set_display_name (GDataGDEmailAddress *self, const gchar *display_name) +{ + g_return_if_fail (GDATA_IS_GD_EMAIL_ADDRESS (self)); + + g_free (self->priv->display_name); + self->priv->display_name = g_strdup (display_name); + g_object_notify (G_OBJECT (self), "display-name"); +} diff --git a/gdata/gd/gdata-gd-email-address.h b/gdata/gd/gdata-gd-email-address.h new file mode 100644 index 0000000..588f9a9 --- /dev/null +++ b/gdata/gd/gdata-gd-email-address.h @@ -0,0 +1,117 @@ +/* -*- Mode: C; indent-tabs-mode: t; c-basic-offset: 8; tab-width: 8 -*- */ +/* + * GData Client + * Copyright (C) Philip Withnall 2009–2010 + * + * GData Client is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * GData Client is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with GData Client. If not, see . + */ + +#ifndef GDATA_GD_EMAIL_ADDRESS_H +#define GDATA_GD_EMAIL_ADDRESS_H + +#include +#include + +#include + +G_BEGIN_DECLS + +/** + * GDATA_GD_EMAIL_ADDRESS_HOME: + * + * The relation type URI for a home e-mail address. + * + * Since: 0.7.0 + */ +#define GDATA_GD_EMAIL_ADDRESS_HOME "http://schemas.google.com/g/2005#home" + +/** + * GDATA_GD_EMAIL_ADDRESS_OTHER: + * + * The relation type URI for a miscellaneous e-mail address. + * + * Since: 0.7.0 + */ +#define GDATA_GD_EMAIL_ADDRESS_OTHER "http://schemas.google.com/g/2005#other" + +/** + * GDATA_GD_EMAIL_ADDRESS_WORK: + * + * The relation type URI for a work e-mail address. + * + * Since: 0.7.0 + */ +#define GDATA_GD_EMAIL_ADDRESS_WORK "http://schemas.google.com/g/2005#work" + +#define GDATA_TYPE_GD_EMAIL_ADDRESS (gdata_gd_email_address_get_type ()) +#define GDATA_GD_EMAIL_ADDRESS(o) (G_TYPE_CHECK_INSTANCE_CAST ((o), GDATA_TYPE_GD_EMAIL_ADDRESS, GDataGDEmailAddress)) +#define GDATA_GD_EMAIL_ADDRESS_CLASS(k) (G_TYPE_CHECK_CLASS_CAST((k), GDATA_TYPE_GD_EMAIL_ADDRESS, GDataGDEmailAddressClass)) +#define GDATA_IS_GD_EMAIL_ADDRESS(o) (G_TYPE_CHECK_INSTANCE_TYPE ((o), GDATA_TYPE_GD_EMAIL_ADDRESS)) +#define GDATA_IS_GD_EMAIL_ADDRESS_CLASS(k) (G_TYPE_CHECK_CLASS_TYPE ((k), GDATA_TYPE_GD_EMAIL_ADDRESS)) +#define GDATA_GD_EMAIL_ADDRESS_GET_CLASS(o) (G_TYPE_INSTANCE_GET_CLASS ((o), GDATA_TYPE_GD_EMAIL_ADDRESS, GDataGDEmailAddressClass)) + +typedef struct _GDataGDEmailAddressPrivate GDataGDEmailAddressPrivate; + +/** + * GDataGDEmailAddress: + * + * All the fields in the #GDataGDEmailAddress structure are private and should never be accessed directly. + * + * Since: 0.2.0 + */ +typedef struct { + GDataParsable parent; + GDataGDEmailAddressPrivate *priv; +} GDataGDEmailAddress; + +/** + * GDataGDEmailAddressClass: + * + * All the fields in the #GDataGDEmailAddressClass structure are private and should never be accessed directly. + * + * Since: 0.4.0 + */ +typedef struct { + /*< private >*/ + GDataParsableClass parent; + + /*< private >*/ + /* Padding for future expansion */ + void (*_g_reserved0) (void); + void (*_g_reserved1) (void); +} GDataGDEmailAddressClass; + +GType gdata_gd_email_address_get_type (void) G_GNUC_CONST; + +GDataGDEmailAddress *gdata_gd_email_address_new (const gchar *address, const gchar *relation_type, + const gchar *label, gboolean is_primary) G_GNUC_WARN_UNUSED_RESULT G_GNUC_MALLOC; + +const gchar *gdata_gd_email_address_get_address (GDataGDEmailAddress *self) G_GNUC_PURE; +void gdata_gd_email_address_set_address (GDataGDEmailAddress *self, const gchar *address); + +const gchar *gdata_gd_email_address_get_relation_type (GDataGDEmailAddress *self) G_GNUC_PURE; +void gdata_gd_email_address_set_relation_type (GDataGDEmailAddress *self, const gchar *relation_type); + +const gchar *gdata_gd_email_address_get_label (GDataGDEmailAddress *self) G_GNUC_PURE; +void gdata_gd_email_address_set_label (GDataGDEmailAddress *self, const gchar *label); + +const gchar *gdata_gd_email_address_get_display_name (GDataGDEmailAddress *self) G_GNUC_PURE; +void gdata_gd_email_address_set_display_name (GDataGDEmailAddress *self, const gchar *display_name); + +gboolean gdata_gd_email_address_is_primary (GDataGDEmailAddress *self) G_GNUC_PURE; +void gdata_gd_email_address_set_is_primary (GDataGDEmailAddress *self, gboolean is_primary); + +G_END_DECLS + +#endif /* !GDATA_GD_EMAIL_ADDRESS_H */ diff --git a/gdata/gd/gdata-gd-feed-link.c b/gdata/gd/gdata-gd-feed-link.c new file mode 100644 index 0000000..e29ee51 --- /dev/null +++ b/gdata/gd/gdata-gd-feed-link.c @@ -0,0 +1,447 @@ +/* -*- Mode: C; indent-tabs-mode: t; c-basic-offset: 8; tab-width: 8 -*- */ +/* + * GData Client + * Copyright (C) Philip Withnall 2010 + * Copyright (C) Richard Schwarting 2010 + * + * GData Client is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * GData Client is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with GData Client. If not, see . + */ + +/* + * SECTION:gdata-gd-feed-link + * @short_description: GD feed link element + * @stability: Stable + * @include: gdata/gd/gdata-gd-feed-link.h + * + * #GDataGDFeedLink represents a "feedLink" element from the + * GData specification. + * + * It is private API, since implementing classes are likely to proxy the properties and functions + * of #GDataGDFeedLink as appropriate; most entry types which implement #GDataGDFeedLink have no use + * for most of its properties, and it would be unnecessary and confusing to expose #GDataGDFeedLink itself. + * + * In its current state, #GDataGDFeedLink supports the href attribute, but doesn't support inline + * feed elements, since they don't seem to appear in the wild. + * + * Since: 0.10.0 + */ + +#include +#include +#include + +#include "gdata-gd-feed-link.h" +#include "gdata-parsable.h" +#include "gdata-parser.h" +#include "gdata-private.h" + +static void gdata_gd_feed_link_finalize (GObject *object); +static void gdata_gd_feed_link_get_property (GObject *object, guint property_id, GValue *value, GParamSpec *pspec); +static void gdata_gd_feed_link_set_property (GObject *object, guint property_id, const GValue *value, GParamSpec *pspec); +static gboolean pre_parse_xml (GDataParsable *parsable, xmlDoc *doc, xmlNode *root_node, gpointer user_data, GError **error); +static void pre_get_xml (GDataParsable *parsable, GString *xml_string); +static void get_namespaces (GDataParsable *parsable, GHashTable *namespaces); + +struct _GDataGDFeedLinkPrivate { + gchar *uri; + gchar *relation_type; + gint count_hint; + gboolean is_read_only; +}; + +enum { + PROP_RELATION_TYPE = 1, + PROP_URI, + PROP_COUNT_HINT, + PROP_IS_READ_ONLY, +}; + +G_DEFINE_TYPE (GDataGDFeedLink, gdata_gd_feed_link, GDATA_TYPE_PARSABLE) + +static void +gdata_gd_feed_link_class_init (GDataGDFeedLinkClass *klass) +{ + GObjectClass *gobject_class = G_OBJECT_CLASS (klass); + GDataParsableClass *parsable_class = GDATA_PARSABLE_CLASS (klass); + + g_type_class_add_private (klass, sizeof (GDataGDFeedLinkPrivate)); + + gobject_class->set_property = gdata_gd_feed_link_set_property; + gobject_class->get_property = gdata_gd_feed_link_get_property; + gobject_class->finalize = gdata_gd_feed_link_finalize; + + parsable_class->pre_parse_xml = pre_parse_xml; + parsable_class->pre_get_xml = pre_get_xml; + parsable_class->get_namespaces = get_namespaces; + parsable_class->element_name = "feedLink"; + parsable_class->element_namespace = "gd"; + + /** + * GDataGDFeedLink:relation-type: + * + * Describes the relation type of the given feed to its parent feed. + * + * For more information, see the + * GData specification. + * + * Since: 0.10.0 + */ + g_object_class_install_property (gobject_class, PROP_RELATION_TYPE, + g_param_spec_string ("relation-type", + "Relation type", "Describes the relation type of the given feed to its parent feed.", + GDATA_LINK_ALTERNATE, + G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)); + + /** + * GDataGDFeedLink:uri: + * + * A URI describing the location of the designated feed. + * + * For more information, see the + * GData specification. + * + * Since: 0.10.0 + */ + g_object_class_install_property (gobject_class, PROP_URI, + g_param_spec_string ("uri", + "URI", "A URI describing the location of the designated feed.", + NULL, + G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)); + + /** + * GDataGDFeedLink:count-hint: + * + * Hints at the number of entries contained in the designated feed, and may not be reliable. + * + * For more information, see the + * GData specification. + * + * Since: 0.10.0 + */ + g_object_class_install_property (gobject_class, PROP_COUNT_HINT, + g_param_spec_int ("count-hint", + "Count hint", "Hints at the number of entries contained in the designated feed.", + -1, G_MAXINT, -1, + G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)); + + /** + * GDataGDFeedLink:is-read-only: + * + * Indicates whether the feed is read only. + * + * For more information, see the + * GData specification. + * + * Since: 0.10.0 + */ + g_object_class_install_property (gobject_class, PROP_IS_READ_ONLY, + g_param_spec_boolean ("is-read-only", + "Read only?", "Indicates whether the feed is read only.", + TRUE, + G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)); +} + +static void +gdata_gd_feed_link_init (GDataGDFeedLink *self) +{ + self->priv = G_TYPE_INSTANCE_GET_PRIVATE (self, GDATA_TYPE_GD_FEED_LINK, GDataGDFeedLinkPrivate); + self->priv->count_hint = -1; + self->priv->relation_type = g_strdup (GDATA_LINK_ALTERNATE); +} + +static void +gdata_gd_feed_link_finalize (GObject *object) +{ + GDataGDFeedLinkPrivate *priv = GDATA_GD_FEED_LINK (object)->priv; + + g_free (priv->uri); + g_free (priv->relation_type); + + /* Chain up to the parent class */ + G_OBJECT_CLASS (gdata_gd_feed_link_parent_class)->finalize (object); +} + +static void +gdata_gd_feed_link_get_property (GObject *object, guint property_id, GValue *value, GParamSpec *pspec) +{ + GDataGDFeedLinkPrivate *priv = GDATA_GD_FEED_LINK (object)->priv; + + switch (property_id) { + case PROP_RELATION_TYPE: + g_value_set_string (value, priv->relation_type); + break; + case PROP_URI: + g_value_set_string (value, priv->uri); + break; + case PROP_COUNT_HINT: + g_value_set_int (value, priv->count_hint); + break; + case PROP_IS_READ_ONLY: + g_value_set_boolean (value, priv->is_read_only); + break; + default: + /* We don't have any other properties... */ + G_OBJECT_WARN_INVALID_PROPERTY_ID (object, property_id, pspec); + break; + } +} + +static void +gdata_gd_feed_link_set_property (GObject *object, guint property_id, const GValue *value, GParamSpec *pspec) +{ + GDataGDFeedLink *self = GDATA_GD_FEED_LINK (object); + + switch (property_id) { + case PROP_RELATION_TYPE: + gdata_gd_feed_link_set_relation_type (self, g_value_get_string (value)); + break; + case PROP_URI: + gdata_gd_feed_link_set_uri (self, g_value_get_string (value)); + break; + case PROP_COUNT_HINT: + gdata_gd_feed_link_set_count_hint (self, g_value_get_int (value)); + break; + case PROP_IS_READ_ONLY: + gdata_gd_feed_link_set_is_read_only (self, g_value_get_boolean (value)); + break; + default: + /* We don't have any other properties... */ + G_OBJECT_WARN_INVALID_PROPERTY_ID (object, property_id, pspec); + break; + } +} + +static gboolean +pre_parse_xml (GDataParsable *parsable, xmlDoc *doc, xmlNode *root_node, gpointer user_data, GError **error) +{ + xmlChar *rel, *href, *count_hint; + GDataGDFeedLink *self = GDATA_GD_FEED_LINK (parsable); + + rel = xmlGetProp (root_node, (xmlChar*) "rel"); + if (rel != NULL && *rel == '\0') { + xmlFree (rel); + return gdata_parser_error_required_property_missing (root_node, "rel", error); + } + + gdata_gd_feed_link_set_relation_type (self, (const gchar*) rel); + xmlFree (rel); + + href = xmlGetProp (root_node, (xmlChar*) "href"); + if (href == NULL || *href == '\0') { + xmlFree (href); + return gdata_parser_error_required_property_missing (root_node, "href", error); + } + self->priv->uri = (gchar*) href; + + count_hint = xmlGetProp (root_node, (xmlChar*) "countHint"); + self->priv->count_hint = (count_hint != NULL) ? g_ascii_strtoll ((char*) count_hint, NULL, 10) : -1; + xmlFree (count_hint); + + return gdata_parser_boolean_from_property (root_node, "readOnly", &(self->priv->is_read_only), 0, error); +} + +static void +pre_get_xml (GDataParsable *parsable, GString *xml_string) +{ + GDataGDFeedLinkPrivate *priv = GDATA_GD_FEED_LINK (parsable)->priv; + + if (priv->relation_type != NULL) { + gdata_parser_string_append_escaped (xml_string, " rel='", priv->relation_type, "'"); + } + + if (priv->uri != NULL) { + gdata_parser_string_append_escaped (xml_string, " href='", priv->uri, "'"); + } + + if (priv->count_hint != -1) { + g_string_append_printf (xml_string, " countHint='%i'", priv->count_hint); + } + + if (priv->is_read_only == TRUE) { + g_string_append_printf (xml_string, " readOnly='true'"); + } else { + g_string_append_printf (xml_string, " readOnly='false'"); + } +} + +static void +get_namespaces (GDataParsable *parsable, GHashTable *namespaces) +{ + g_hash_table_insert (namespaces, (gchar*) "gd", (gchar*) "http://schemas.google.com/g/2005"); +} + +/** + * gdata_gd_feed_link_get_relation_type: + * @self: a #GDataGDFeedLink + * + * Gets the #GDataGDFeedLink:relation-type property. + * + * Return value: the feed's relation to its owner, or %NULL + * + * Since: 0.10.0 + */ +const gchar * +gdata_gd_feed_link_get_relation_type (GDataGDFeedLink *self) +{ + g_return_val_if_fail (GDATA_IS_GD_FEED_LINK (self), NULL); + + return self->priv->relation_type; +} + +/** + * gdata_gd_feed_link_get_uri: + * @self: a #GDataGDFeedLink + * + * Gets the #GDataGDFeedLink:uri property. + * + * Return value: the related feed's URI + * + * Since: 0.10.0 + */ +const gchar * +gdata_gd_feed_link_get_uri (GDataGDFeedLink *self) +{ + g_return_val_if_fail (GDATA_IS_GD_FEED_LINK (self), NULL); + + return self->priv->uri; +} + +/** + * gdata_gd_feed_link_get_count_hint: + * @self: a #GDataGDFeedLink + * + * Gets the #GDataGDFeedLink:count-hint property. + * + * Return value: the potential number of entries in the related feed, or -1 if not set + * + * Since: 0.10.0 + */ +gint +gdata_gd_feed_link_get_count_hint (GDataGDFeedLink *self) +{ + g_return_val_if_fail (GDATA_IS_GD_FEED_LINK (self), -1); + + return self->priv->count_hint; +} + +/** + * gdata_gd_feed_link_get_read_only: + * @self: a #GDataGDFeedLink + * + * Gets the #GDataGDFeedLink:read-only property. + * + * Return value: %TRUE if the feed is read only, %FALSE otherwise + * + * Since: 0.10.0 + */ +gboolean +gdata_gd_feed_link_is_read_only (GDataGDFeedLink *self) +{ + g_return_val_if_fail (GDATA_IS_GD_FEED_LINK (self), FALSE); + + return self->priv->is_read_only; +} + +/** + * gdata_gd_feed_link_set_relation_type: + * @self: a #GDataGDFeedLink + * @relation_type: (allow-none): the new relation type between the feed and its owner, or %NULL + * + * Sets the relation type of the #GDataGDFeedLink's related feed to @relation_type. If @relation_type is one of the standard Atom relation types, + * use one of the defined relation type values, instead of a static string. e.g. %GDATA_LINK_EDIT or %GDATA_LINK_SELF. + * + * Since: 0.10.0 + */ +void +gdata_gd_feed_link_set_relation_type (GDataGDFeedLink *self, const gchar *relation_type) +{ + g_return_if_fail (GDATA_IS_GD_FEED_LINK (self)); + g_return_if_fail (relation_type == NULL || *relation_type != '\0'); + + /* If the relation type is unset, use the default "alternate" relation type. If it's set, and isn't an IRI, turn it into an IRI + * by appending it to "http://www.iana.org/assignments/relation/". If it's set and is an IRI, just use the IRI. + * See: http://www.atomenabled.org/developers/syndication/atom-format-spec.php#rel_attribute + */ + g_free (self->priv->relation_type); + if (relation_type == NULL) { + self->priv->relation_type = g_strdup (GDATA_LINK_ALTERNATE); + } else if (strchr ((char*) relation_type, ':') == NULL) { + self->priv->relation_type = g_strconcat ("http://www.iana.org/assignments/relation/", (const gchar*) relation_type, NULL); + } else { + self->priv->relation_type = g_strdup ((gchar*) relation_type); + } + + g_object_notify (G_OBJECT (self), "relation-type"); +} + +/** + * gdata_gd_feed_link_set_uri: + * @self: a #GDataGDFeedLink + * @uri: the new URI for the related feed + * + * Sets the URI of the #GDataGDFeedLink's related feed to @uri. + * + * Since: 0.10.0 + */ +void +gdata_gd_feed_link_set_uri (GDataGDFeedLink *self, const gchar *uri) +{ + g_return_if_fail (GDATA_IS_GD_FEED_LINK (self)); + g_return_if_fail (uri != NULL && *uri != '\0'); + + g_free (self->priv->uri); + self->priv->uri = g_strdup (uri); + + g_object_notify (G_OBJECT (self), "uri"); +} + +/** + * gdata_gd_feed_link_set_count_hint: + * @self: a #GDataGDFeedLink + * @count_hint: the new number of entries in the related feed, or -1 if unknown + * + * Sets the number of entries in the #GDataGDFeedLink's related feed to @count_hint. This number may be an imprecise estimate. + * + * Since: 0.10.0 + */ +void +gdata_gd_feed_link_set_count_hint (GDataGDFeedLink *self, gint count_hint) +{ + g_return_if_fail (GDATA_IS_GD_FEED_LINK (self)); + g_return_if_fail (count_hint >= -1); + + self->priv->count_hint = count_hint; + + g_object_notify (G_OBJECT (self), "count-hint"); +} + +/** + * gdata_gd_feed_link_set_is_read_only: + * @self: a #GDataGDFeedLink + * @is_read_only: %TRUE if the #GDataGDFeedLink's related feed is read only, %FALSE otherwise + * + * Sets the read only status of the #GDataGDFeedLink's related feed to @is_read_only. + * + * Since: 0.10.0 + */ +void +gdata_gd_feed_link_set_is_read_only (GDataGDFeedLink *self, gboolean is_read_only) +{ + g_return_if_fail (GDATA_IS_GD_FEED_LINK (self)); + + self->priv->is_read_only = is_read_only; + + g_object_notify (G_OBJECT (self), "is-read-only"); +} + diff --git a/gdata/gd/gdata-gd-feed-link.h b/gdata/gd/gdata-gd-feed-link.h new file mode 100644 index 0000000..8a970b6 --- /dev/null +++ b/gdata/gd/gdata-gd-feed-link.h @@ -0,0 +1,84 @@ +/* -*- Mode: C; indent-tabs-mode: t; c-basic-offset: 8; tab-width: 8 -*- */ +/* + * GData Client + * Copyright (C) Richard Schwarting 2010 + * + * GData Client is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * GData Client is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with GData Client. If not, see . + */ + +#ifndef GDATA_GD_FEED_LINK_H +#define GDATA_GD_FEED_LINK_H + +#include +#include + +#include + +G_BEGIN_DECLS + +#define GDATA_TYPE_GD_FEED_LINK (gdata_gd_feed_link_get_type ()) +#define GDATA_GD_FEED_LINK(o) (G_TYPE_CHECK_INSTANCE_CAST ((o), GDATA_TYPE_GD_FEED_LINK, GDataGDFeedLink)) +#define GDATA_GD_FEED_LINK_CLASS(k) (G_TYPE_CHECK_CLASS_CAST((k), GDATA_TYPE_GD_FEED_LINK, GDataGDFeedLinkClass)) +#define GDATA_IS_GD_FEED_LINK(o) (G_TYPE_CHECK_INSTANCE_TYPE ((o), GDATA_TYPE_GD_FEED_LINK)) +#define GDATA_IS_GD_FEED_LINK_CLASS(k) (G_TYPE_CHECK_CLASS_TYPE ((k), GDATA_TYPE_GD_FEED_LINK)) +#define GDATA_GD_FEED_LINK_GET_CLASS(o) (G_TYPE_INSTANCE_GET_CLASS ((o), GDATA_TYPE_GD_FEED_LINK, GDataGDFeedLinkClass)) + +typedef struct _GDataGDFeedLinkPrivate GDataGDFeedLinkPrivate; + +/** + * GDataGDFeedLink: + * + * All the fields in the #GDataGDFeedLink structure are private and should never be accessed directly. + * + * Since: 0.10.0 + */ +typedef struct { + GDataParsable parent; + GDataGDFeedLinkPrivate *priv; +} GDataGDFeedLink; + +/** + * GDataGDFeedLinkClass: + * + * All the fields in the #GDataGDFeedLinkClass structure are private and should never be accessed directly. + * + * Since: 0.10.0 + */ +typedef struct { + /*< private >*/ + GDataParsableClass parent; + + /*< private >*/ + /* Padding for future expansion */ + void (*_g_reserved0) (void); + void (*_g_reserved1) (void); +} GDataGDFeedLinkClass; + +GType gdata_gd_feed_link_get_type (void) G_GNUC_CONST; + +const gchar *gdata_gd_feed_link_get_relation_type (GDataGDFeedLink *self) G_GNUC_PURE; +void gdata_gd_feed_link_set_relation_type (GDataGDFeedLink *self, const gchar *relation_type); + +const gchar *gdata_gd_feed_link_get_uri (GDataGDFeedLink *self) G_GNUC_PURE; +void gdata_gd_feed_link_set_uri (GDataGDFeedLink *self, const gchar *uri); + +gint gdata_gd_feed_link_get_count_hint (GDataGDFeedLink *self) G_GNUC_PURE; +void gdata_gd_feed_link_set_count_hint (GDataGDFeedLink *self, gint count_hint); + +gboolean gdata_gd_feed_link_is_read_only (GDataGDFeedLink *self) G_GNUC_PURE; +void gdata_gd_feed_link_set_is_read_only (GDataGDFeedLink *self, gboolean is_read_only); + +G_END_DECLS + +#endif /* !GDATA_GD_FEED_LINK_H */ diff --git a/gdata/gd/gdata-gd-im-address.c b/gdata/gd/gdata-gd-im-address.c new file mode 100644 index 0000000..5b44680 --- /dev/null +++ b/gdata/gd/gdata-gd-im-address.c @@ -0,0 +1,526 @@ +/* -*- Mode: C; indent-tabs-mode: t; c-basic-offset: 8; tab-width: 8 -*- */ +/* + * GData Client + * Copyright (C) Philip Withnall 2009–2010 + * + * GData Client is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * GData Client is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with GData Client. If not, see . + */ + +/** + * SECTION:gdata-gd-im-address + * @short_description: GData instant messaging address element + * @stability: Stable + * @include: gdata/gd/gdata-gd-im-address.h + * + * #GDataGDIMAddress represents an "im" element from the + * GData specification. + * + * Since: 0.4.0 + */ + +#include +#include + +#include "gdata-gd-im-address.h" +#include "gdata-parsable.h" +#include "gdata-parser.h" +#include "gdata-comparable.h" + +static void gdata_gd_im_address_comparable_init (GDataComparableIface *iface); +static void gdata_gd_im_address_finalize (GObject *object); +static void gdata_gd_im_address_get_property (GObject *object, guint property_id, GValue *value, GParamSpec *pspec); +static void gdata_gd_im_address_set_property (GObject *object, guint property_id, const GValue *value, GParamSpec *pspec); +static gboolean pre_parse_xml (GDataParsable *parsable, xmlDoc *doc, xmlNode *root_node, gpointer user_data, GError **error); +static void pre_get_xml (GDataParsable *parsable, GString *xml_string); +static void get_namespaces (GDataParsable *parsable, GHashTable *namespaces); + +struct _GDataGDIMAddressPrivate { + gchar *address; + gchar *protocol; + gchar *relation_type; + gchar *label; + gboolean is_primary; +}; + +enum { + PROP_ADDRESS = 1, + PROP_PROTOCOL, + PROP_RELATION_TYPE, + PROP_LABEL, + PROP_IS_PRIMARY +}; + +G_DEFINE_TYPE_WITH_CODE (GDataGDIMAddress, gdata_gd_im_address, GDATA_TYPE_PARSABLE, + G_IMPLEMENT_INTERFACE (GDATA_TYPE_COMPARABLE, gdata_gd_im_address_comparable_init)) + +static void +gdata_gd_im_address_class_init (GDataGDIMAddressClass *klass) +{ + GObjectClass *gobject_class = G_OBJECT_CLASS (klass); + GDataParsableClass *parsable_class = GDATA_PARSABLE_CLASS (klass); + + g_type_class_add_private (klass, sizeof (GDataGDIMAddressPrivate)); + + gobject_class->get_property = gdata_gd_im_address_get_property; + gobject_class->set_property = gdata_gd_im_address_set_property; + gobject_class->finalize = gdata_gd_im_address_finalize; + + parsable_class->pre_parse_xml = pre_parse_xml; + parsable_class->pre_get_xml = pre_get_xml; + parsable_class->get_namespaces = get_namespaces; + parsable_class->element_name = "im"; + parsable_class->element_namespace = "gd"; + + /** + * GDataGDIMAddress:address: + * + * The IM address itself. + * + * For more information, see the + * GData specification. + * + * Since: 0.4.0 + */ + g_object_class_install_property (gobject_class, PROP_ADDRESS, + g_param_spec_string ("address", + "Address", "The IM address itself.", + NULL, + G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)); + + /** + * GDataGDIMAddress:protocol: + * + * Identifies the IM network. For example: %GDATA_GD_IM_PROTOCOL_JABBER or %GDATA_GD_IM_PROTOCOL_GOOGLE_TALK. + * + * For more information, see the + * GData specification. + * + * Since: 0.4.0 + */ + g_object_class_install_property (gobject_class, PROP_PROTOCOL, + g_param_spec_string ("protocol", + "Protocol", "Identifies the IM network.", + NULL, + G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)); + + /** + * GDataGDIMAddress:relation-type: + * + * A programmatic value that identifies the type of IM address. For example: %GDATA_GD_IM_ADDRESS_HOME or %GDATA_GD_IM_ADDRESS_WORK. + * + * For more information, see the + * GData specification. + * + * Since: 0.4.0 + */ + g_object_class_install_property (gobject_class, PROP_RELATION_TYPE, + g_param_spec_string ("relation-type", + "Relation type", "A programmatic value that identifies the type of IM address.", + NULL, + G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)); + + /** + * GDataGDIMAddress:label: + * + * A simple string value used to name this IM address. It allows UIs to display a label such as "Work", "Personal", "Preferred", etc. + * + * For more information, see the + * GData specification. + * + * Since: 0.4.0 + */ + g_object_class_install_property (gobject_class, PROP_LABEL, + g_param_spec_string ("label", + "Label", "A simple string value used to name this IM address.", + NULL, + G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)); + + /** + * GDataGDIMAddress:is-primary: + * + * Indicates which IM address out of a group is primary. + * + * For more information, see the + * GData specification. + * + * Since: 0.4.0 + */ + g_object_class_install_property (gobject_class, PROP_IS_PRIMARY, + g_param_spec_boolean ("is-primary", + "Primary?", "Indicates which IM address out of a group is primary.", + FALSE, + G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)); +} + +static gint +compare_with (GDataComparable *self, GDataComparable *other) +{ + GDataGDIMAddressPrivate *a = ((GDataGDIMAddress*) self)->priv, *b = ((GDataGDIMAddress*) other)->priv; + + if (g_strcmp0 (a->address, b->address) == 0 && g_strcmp0 (a->protocol, b->protocol) == 0) + return 0; + return 1; +} + +static void +gdata_gd_im_address_comparable_init (GDataComparableIface *iface) +{ + iface->compare_with = compare_with; +} + +static void +gdata_gd_im_address_init (GDataGDIMAddress *self) +{ + self->priv = G_TYPE_INSTANCE_GET_PRIVATE (self, GDATA_TYPE_GD_IM_ADDRESS, GDataGDIMAddressPrivate); +} + +static void +gdata_gd_im_address_finalize (GObject *object) +{ + GDataGDIMAddressPrivate *priv = GDATA_GD_IM_ADDRESS (object)->priv; + + g_free (priv->address); + g_free (priv->protocol); + g_free (priv->relation_type); + g_free (priv->label); + + /* Chain up to the parent class */ + G_OBJECT_CLASS (gdata_gd_im_address_parent_class)->finalize (object); +} + +static void +gdata_gd_im_address_get_property (GObject *object, guint property_id, GValue *value, GParamSpec *pspec) +{ + GDataGDIMAddressPrivate *priv = GDATA_GD_IM_ADDRESS (object)->priv; + + switch (property_id) { + case PROP_ADDRESS: + g_value_set_string (value, priv->address); + break; + case PROP_PROTOCOL: + g_value_set_string (value, priv->protocol); + break; + case PROP_RELATION_TYPE: + g_value_set_string (value, priv->relation_type); + break; + case PROP_LABEL: + g_value_set_string (value, priv->label); + break; + case PROP_IS_PRIMARY: + g_value_set_boolean (value, priv->is_primary); + break; + default: + /* We don't have any other property... */ + G_OBJECT_WARN_INVALID_PROPERTY_ID (object, property_id, pspec); + break; + } +} + +static void +gdata_gd_im_address_set_property (GObject *object, guint property_id, const GValue *value, GParamSpec *pspec) +{ + GDataGDIMAddress *self = GDATA_GD_IM_ADDRESS (object); + + switch (property_id) { + case PROP_ADDRESS: + gdata_gd_im_address_set_address (self, g_value_get_string (value)); + break; + case PROP_PROTOCOL: + gdata_gd_im_address_set_protocol (self, g_value_get_string (value)); + break; + case PROP_RELATION_TYPE: + gdata_gd_im_address_set_relation_type (self, g_value_get_string (value)); + break; + case PROP_LABEL: + gdata_gd_im_address_set_label (self, g_value_get_string (value)); + break; + case PROP_IS_PRIMARY: + gdata_gd_im_address_set_is_primary (self, g_value_get_boolean (value)); + break; + default: + /* We don't have any other property... */ + G_OBJECT_WARN_INVALID_PROPERTY_ID (object, property_id, pspec); + break; + } +} + +static gboolean +pre_parse_xml (GDataParsable *parsable, xmlDoc *doc, xmlNode *root_node, gpointer user_data, GError **error) +{ + xmlChar *address, *rel; + gboolean primary_bool; + GDataGDIMAddressPrivate *priv = GDATA_GD_IM_ADDRESS (parsable)->priv; + + /* Is it the primary IM address? */ + if (gdata_parser_boolean_from_property (root_node, "primary", &primary_bool, 0, error) == FALSE) + return FALSE; + + address = xmlGetProp (root_node, (xmlChar*) "address"); + if (address == NULL || *address == '\0') { + xmlFree (address); + return gdata_parser_error_required_property_missing (root_node, "address", error); + } + + rel = xmlGetProp (root_node, (xmlChar*) "rel"); + if (rel != NULL && *rel == '\0') { + xmlFree (address); + xmlFree (rel); + return gdata_parser_error_required_property_missing (root_node, "rel", error); + } + + priv->address = (gchar*) address; + priv->protocol = (gchar*) xmlGetProp (root_node, (xmlChar*) "protocol"); + priv->relation_type = (gchar*) rel; + priv->label = (gchar*) xmlGetProp (root_node, (xmlChar*) "label"); + priv->is_primary = primary_bool; + + return TRUE; +} + +static void +pre_get_xml (GDataParsable *parsable, GString *xml_string) +{ + GDataGDIMAddressPrivate *priv = GDATA_GD_IM_ADDRESS (parsable)->priv; + + gdata_parser_string_append_escaped (xml_string, " address='", priv->address, "'"); + if (priv->protocol != NULL) + gdata_parser_string_append_escaped (xml_string, " protocol='", priv->protocol, "'"); + + if (priv->relation_type != NULL) + gdata_parser_string_append_escaped (xml_string, " rel='", priv->relation_type, "'"); + if (priv->label != NULL) + gdata_parser_string_append_escaped (xml_string, " label='", priv->label, "'"); + + if (priv->is_primary == TRUE) + g_string_append (xml_string, " primary='true'"); + else + g_string_append (xml_string, " primary='false'"); +} + +static void +get_namespaces (GDataParsable *parsable, GHashTable *namespaces) +{ + g_hash_table_insert (namespaces, (gchar*) "gd", (gchar*) "http://schemas.google.com/g/2005"); +} + +/** + * gdata_gd_im_address_new: + * @address: the IM address + * @protocol: (allow-none): a URI identifying the IM protocol, or %NULL + * @relation_type: (allow-none): the relationship between the IM address and its owner, or %NULL + * @label: (allow-none): a human-readable label for the IM address, or %NULL + * @is_primary: %TRUE if this IM address is its owner's primary address, %FALSE otherwise + * + * Creates a new #GDataGDIMAddress. More information is available in the GData specification. + * + * Return value: a new #GDataGDIMAddress, or %NULL; unref with g_object_unref() + * + * Since: 0.2.0 + */ +GDataGDIMAddress * +gdata_gd_im_address_new (const gchar *address, const gchar *protocol, const gchar *relation_type, const gchar *label, gboolean is_primary) +{ + g_return_val_if_fail (address != NULL && *address != '\0', NULL); + g_return_val_if_fail (protocol == NULL || *protocol != '\0', NULL); + g_return_val_if_fail (relation_type == NULL || *relation_type != '\0', NULL); + return g_object_new (GDATA_TYPE_GD_IM_ADDRESS, "address", address, "protocol", protocol, "relation-type", relation_type, + "label", label, "is-primary", is_primary, NULL); +} + +/** + * gdata_gd_im_address_get_address: + * @self: a #GDataGDIMAddress + * + * Gets the #GDataGDIMAddress:address property. + * + * Return value: the IM address itself, or %NULL + * + * Since: 0.4.0 + */ +const gchar * +gdata_gd_im_address_get_address (GDataGDIMAddress *self) +{ + g_return_val_if_fail (GDATA_IS_GD_IM_ADDRESS (self), NULL); + return self->priv->address; +} + +/** + * gdata_gd_im_address_set_address: + * @self: a #GDataGDIMAddress + * @address: the new IM address + * + * Sets the #GDataGDIMAddress:address property to @address. + * + * Since: 0.4.0 + */ +void +gdata_gd_im_address_set_address (GDataGDIMAddress *self, const gchar *address) +{ + g_return_if_fail (GDATA_IS_GD_IM_ADDRESS (self)); + g_return_if_fail (address != NULL && *address != '\0'); + + g_free (self->priv->address); + self->priv->address = g_strdup (address); + g_object_notify (G_OBJECT (self), "address"); +} + +/** + * gdata_gd_im_address_get_protocol: + * @self: a #GDataGDIMAddress + * + * Gets the #GDataGDIMAddress:protocol property. + * + * Return value: the IM address' protocol, or %NULL + * + * Since: 0.4.0 + */ +const gchar * +gdata_gd_im_address_get_protocol (GDataGDIMAddress *self) +{ + g_return_val_if_fail (GDATA_IS_GD_IM_ADDRESS (self), NULL); + return self->priv->protocol; +} + +/** + * gdata_gd_im_address_set_protocol: + * @self: a #GDataGDIMAddress + * @protocol: (allow-none): the new IM protocol, or %NULL + * + * Sets the #GDataGDIMAddress:protocol property to @protocol. + * + * Since: 0.4.0 + */ +void +gdata_gd_im_address_set_protocol (GDataGDIMAddress *self, const gchar *protocol) +{ + g_return_if_fail (GDATA_IS_GD_IM_ADDRESS (self)); + g_return_if_fail (protocol == NULL || *protocol != '\0'); + + g_free (self->priv->protocol); + self->priv->protocol = g_strdup (protocol); + g_object_notify (G_OBJECT (self), "protocol"); +} + +/** + * gdata_gd_im_address_get_relation_type: + * @self: a #GDataGDIMAddress + * + * Gets the #GDataGDIMAddress:relation-type property. + * + * Return value: the IM address' relation type, or %NULL + * + * Since: 0.4.0 + */ +const gchar * +gdata_gd_im_address_get_relation_type (GDataGDIMAddress *self) +{ + g_return_val_if_fail (GDATA_IS_GD_IM_ADDRESS (self), NULL); + return self->priv->relation_type; +} + +/** + * gdata_gd_im_address_set_relation_type: + * @self: a #GDataGDIMAddress + * @relation_type: (allow-none): the new relation type for the im_address, or %NULL + * + * Sets the #GDataGDIMAddress:relation-type property to @relation_type. + * + * Set @relation_type to %NULL to unset the property in the IM address. + * + * Since: 0.4.0 + */ +void +gdata_gd_im_address_set_relation_type (GDataGDIMAddress *self, const gchar *relation_type) +{ + g_return_if_fail (GDATA_IS_GD_IM_ADDRESS (self)); + g_return_if_fail (relation_type == NULL || *relation_type != '\0'); + + g_free (self->priv->relation_type); + self->priv->relation_type = g_strdup (relation_type); + g_object_notify (G_OBJECT (self), "relation-type"); +} + +/** + * gdata_gd_im_address_get_label: + * @self: a #GDataGDIMAddress + * + * Gets the #GDataGDIMAddress:label property. + * + * Return value: the IM address' label, or %NULL + * + * Since: 0.4.0 + */ +const gchar * +gdata_gd_im_address_get_label (GDataGDIMAddress *self) +{ + g_return_val_if_fail (GDATA_IS_GD_IM_ADDRESS (self), NULL); + return self->priv->label; +} + +/** + * gdata_gd_im_address_set_label: + * @self: a #GDataGDIMAddress + * @label: (allow-none): the new label for the IM address, or %NULL + * + * Sets the #GDataGDIMAddress:label property to @label. + * + * Set @label to %NULL to unset the property in the IM address. + * + * Since: 0.4.0 + */ +void +gdata_gd_im_address_set_label (GDataGDIMAddress *self, const gchar *label) +{ + g_return_if_fail (GDATA_IS_GD_IM_ADDRESS (self)); + + g_free (self->priv->label); + self->priv->label = g_strdup (label); + g_object_notify (G_OBJECT (self), "label"); +} + +/** + * gdata_gd_im_address_is_primary: + * @self: a #GDataGDIMAddress + * + * Gets the #GDataGDIMAddress:is-primary property. + * + * Return value: %TRUE if this is the primary IM address, %FALSE otherwise + * + * Since: 0.4.0 + */ +gboolean +gdata_gd_im_address_is_primary (GDataGDIMAddress *self) +{ + g_return_val_if_fail (GDATA_IS_GD_IM_ADDRESS (self), FALSE); + return self->priv->is_primary; +} + +/** + * gdata_gd_im_address_set_is_primary: + * @self: a #GDataGDIMAddress + * @is_primary: %TRUE if this is the primary IM address, %FALSE otherwise + * + * Sets the #GDataGDIMAddress:is-primary property to @is_primary. + * + * Since: 0.4.0 + */ +void +gdata_gd_im_address_set_is_primary (GDataGDIMAddress *self, gboolean is_primary) +{ + g_return_if_fail (GDATA_IS_GD_IM_ADDRESS (self)); + + self->priv->is_primary = is_primary; + g_object_notify (G_OBJECT (self), "is-primary"); +} diff --git a/gdata/gd/gdata-gd-im-address.h b/gdata/gd/gdata-gd-im-address.h new file mode 100644 index 0000000..9e717c1 --- /dev/null +++ b/gdata/gd/gdata-gd-im-address.h @@ -0,0 +1,198 @@ +/* -*- Mode: C; indent-tabs-mode: t; c-basic-offset: 8; tab-width: 8 -*- */ +/* + * GData Client + * Copyright (C) Philip Withnall 2009–2010 + * + * GData Client is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * GData Client is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with GData Client. If not, see . + */ + +#ifndef GDATA_GD_IM_ADDRESS_H +#define GDATA_GD_IM_ADDRESS_H + +#include +#include + +#include + +G_BEGIN_DECLS + +/** + * GDATA_GD_IM_ADDRESS_HOME: + * + * The relation type URI for a home IM address. + * + * Since: 0.7.0 + */ +#define GDATA_GD_IM_ADDRESS_HOME "http://schemas.google.com/g/2005#home" + +/** + * GDATA_GD_IM_ADDRESS_NETMEETING: + * + * The relation type URI for a Microsoft NetMeeting IM address. + * + * Since: 0.7.0 + */ +#define GDATA_GD_IM_ADDRESS_NETMEETING "http://schemas.google.com/g/2005#netmeeting" + +/** + * GDATA_GD_IM_ADDRESS_OTHER: + * + * The relation type URI for a miscellaneous IM address. + * + * Since: 0.7.0 + */ +#define GDATA_GD_IM_ADDRESS_OTHER "http://schemas.google.com/g/2005#other" + +/** + * GDATA_GD_IM_ADDRESS_WORK: + * + * The relation type URI for a work IM address. + * + * Since: 0.7.0 + */ +#define GDATA_GD_IM_ADDRESS_WORK "http://schemas.google.com/g/2005#work" + +/** + * GDATA_GD_IM_PROTOCOL_AIM: + * + * The protocol type URI for an AIM IM address. + * + * Since: 0.7.0 + */ +#define GDATA_GD_IM_PROTOCOL_AIM "http://schemas.google.com/g/2005#AIM" + +/** + * GDATA_GD_IM_PROTOCOL_LIVE_MESSENGER: + * + * The protocol type URI for an Windows Live Messenger IM address. + * + * Since: 0.7.0 + */ +#define GDATA_GD_IM_PROTOCOL_LIVE_MESSENGER "http://schemas.google.com/g/2005#MSN" + +/** + * GDATA_GD_IM_PROTOCOL_YAHOO_MESSENGER: + * + * The protocol type URI for a Yahoo! Messenger IM address. + * + * Since: 0.7.0 + */ +#define GDATA_GD_IM_PROTOCOL_YAHOO_MESSENGER "http://schemas.google.com/g/2005#YAHOO" + +/** + * GDATA_GD_IM_PROTOCOL_SKYPE: + * + * The protocol type URI for a Skype IM address. + * + * Since: 0.7.0 + */ +#define GDATA_GD_IM_PROTOCOL_SKYPE "http://schemas.google.com/g/2005#SKYPE" + +/** + * GDATA_GD_IM_PROTOCOL_QQ: + * + * The protocol type URI for a QQ IM address. + * + * Since: 0.7.0 + */ +#define GDATA_GD_IM_PROTOCOL_QQ "http://schemas.google.com/g/2005#QQ" + +/** + * GDATA_GD_IM_PROTOCOL_GOOGLE_TALK: + * + * The protocol type URI for a Google Talk IM address. + * + * Since: 0.7.0 + */ +#define GDATA_GD_IM_PROTOCOL_GOOGLE_TALK "http://schemas.google.com/g/2005#GOOGLE_TALK" + +/** + * GDATA_GD_IM_PROTOCOL_ICQ: + * + * The protocol type URI for an ICQ IM address. + * + * Since: 0.7.0 + */ +#define GDATA_GD_IM_PROTOCOL_ICQ "http://schemas.google.com/g/2005#ICQ" + +/** + * GDATA_GD_IM_PROTOCOL_JABBER: + * + * The protocol type URI for a Jabber IM address. + * + * Since: 0.7.0 + */ +#define GDATA_GD_IM_PROTOCOL_JABBER "http://schemas.google.com/g/2005#JABBER" + +#define GDATA_TYPE_GD_IM_ADDRESS (gdata_gd_im_address_get_type ()) +#define GDATA_GD_IM_ADDRESS(o) (G_TYPE_CHECK_INSTANCE_CAST ((o), GDATA_TYPE_GD_IM_ADDRESS, GDataGDIMAddress)) +#define GDATA_GD_IM_ADDRESS_CLASS(k) (G_TYPE_CHECK_CLASS_CAST((k), GDATA_TYPE_GD_IM_ADDRESS, GDataGDIMAddressClass)) +#define GDATA_IS_GD_IM_ADDRESS(o) (G_TYPE_CHECK_INSTANCE_TYPE ((o), GDATA_TYPE_GD_IM_ADDRESS)) +#define GDATA_IS_GD_IM_ADDRESS_CLASS(k) (G_TYPE_CHECK_CLASS_TYPE ((k), GDATA_TYPE_GD_IM_ADDRESS)) +#define GDATA_GD_IM_ADDRESS_GET_CLASS(o) (G_TYPE_INSTANCE_GET_CLASS ((o), GDATA_TYPE_GD_IM_ADDRESS, GDataGDIMAddressClass)) + +typedef struct _GDataGDIMAddressPrivate GDataGDIMAddressPrivate; + +/** + * GDataGDIMAddress: + * + * All the fields in the #GDataGDIMAddress structure are private and should never be accessed directly. + * + * Since: 0.2.0 + */ +typedef struct { + GDataParsable parent; + GDataGDIMAddressPrivate *priv; +} GDataGDIMAddress; + +/** + * GDataGDIMAddressClass: + * + * All the fields in the #GDataGDIMAddressClass structure are private and should never be accessed directly. + * + * Since: 0.4.0 + */ +typedef struct { + /*< private >*/ + GDataParsableClass parent; + + /*< private >*/ + /* Padding for future expansion */ + void (*_g_reserved0) (void); + void (*_g_reserved1) (void); +} GDataGDIMAddressClass; + +GType gdata_gd_im_address_get_type (void) G_GNUC_CONST; + +GDataGDIMAddress *gdata_gd_im_address_new (const gchar *address, const gchar *protocol, const gchar *relation_type, const gchar *label, + gboolean is_primary) G_GNUC_WARN_UNUSED_RESULT G_GNUC_MALLOC; + +const gchar *gdata_gd_im_address_get_address (GDataGDIMAddress *self) G_GNUC_PURE; +void gdata_gd_im_address_set_address (GDataGDIMAddress *self, const gchar *address); + +const gchar *gdata_gd_im_address_get_protocol (GDataGDIMAddress *self) G_GNUC_PURE; +void gdata_gd_im_address_set_protocol (GDataGDIMAddress *self, const gchar *protocol); + +const gchar *gdata_gd_im_address_get_relation_type (GDataGDIMAddress *self) G_GNUC_PURE; +void gdata_gd_im_address_set_relation_type (GDataGDIMAddress *self, const gchar *relation_type); + +const gchar *gdata_gd_im_address_get_label (GDataGDIMAddress *self) G_GNUC_PURE; +void gdata_gd_im_address_set_label (GDataGDIMAddress *self, const gchar *label); + +gboolean gdata_gd_im_address_is_primary (GDataGDIMAddress *self) G_GNUC_PURE; +void gdata_gd_im_address_set_is_primary (GDataGDIMAddress *self, gboolean is_primary); + +G_END_DECLS + +#endif /* !GDATA_GD_IM_ADDRESS_H */ diff --git a/gdata/gd/gdata-gd-name.c b/gdata/gd/gdata-gd-name.c new file mode 100644 index 0000000..4c1fde6 --- /dev/null +++ b/gdata/gd/gdata-gd-name.c @@ -0,0 +1,589 @@ +/* -*- Mode: C; indent-tabs-mode: t; c-basic-offset: 8; tab-width: 8 -*- */ +/* + * GData Client + * Copyright (C) Philip Withnall 2009–2010 + * + * GData Client is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * GData Client is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with GData Client. If not, see . + */ + +/** + * SECTION:gdata-gd-name + * @short_description: GData name element + * @stability: Stable + * @include: gdata/gd/gdata-gd-name.h + * + * #GDataGDName represents a "name" element from the + * GData specification. + * + * Given a name such as Sir Winston Leonard Spencer-Churchill, KG, the properties of the #GDataGDName should be + * set as follows: + * + * #GDataGDName:given-nameWinston + * #GDataGDName:additional-nameLeonard + * #GDataGDName:family-nameSpencer-Churchill + * #GDataGDName:prefixSir + * #GDataGDName:suffixKG + * + * + * Since: 0.5.0 + */ + +#include +#include + +#include "gdata-gd-name.h" +#include "gdata-parsable.h" +#include "gdata-parser.h" +#include "gdata-comparable.h" + +static void gdata_gd_name_comparable_init (GDataComparableIface *iface); +static void gdata_gd_name_finalize (GObject *object); +static void gdata_gd_name_get_property (GObject *object, guint property_id, GValue *value, GParamSpec *pspec); +static void gdata_gd_name_set_property (GObject *object, guint property_id, const GValue *value, GParamSpec *pspec); +static gboolean parse_xml (GDataParsable *parsable, xmlDoc *doc, xmlNode *node, gpointer user_data, GError **error); +static void get_xml (GDataParsable *parsable, GString *xml_string); +static void get_namespaces (GDataParsable *parsable, GHashTable *namespaces); + +struct _GDataGDNamePrivate { + gchar *given_name; + gchar *additional_name; + gchar *family_name; + gchar *prefix; + gchar *suffix; + gchar *full_name; +}; + +enum { + PROP_GIVEN_NAME = 1, + PROP_ADDITIONAL_NAME, + PROP_FAMILY_NAME, + PROP_PREFIX, + PROP_SUFFIX, + PROP_FULL_NAME +}; + +G_DEFINE_TYPE_WITH_CODE (GDataGDName, gdata_gd_name, GDATA_TYPE_PARSABLE, + G_IMPLEMENT_INTERFACE (GDATA_TYPE_COMPARABLE, gdata_gd_name_comparable_init)) + +static void +gdata_gd_name_class_init (GDataGDNameClass *klass) +{ + GObjectClass *gobject_class = G_OBJECT_CLASS (klass); + GDataParsableClass *parsable_class = GDATA_PARSABLE_CLASS (klass); + + g_type_class_add_private (klass, sizeof (GDataGDNamePrivate)); + + gobject_class->get_property = gdata_gd_name_get_property; + gobject_class->set_property = gdata_gd_name_set_property; + gobject_class->finalize = gdata_gd_name_finalize; + + parsable_class->parse_xml = parse_xml; + parsable_class->get_xml = get_xml; + parsable_class->get_namespaces = get_namespaces; + parsable_class->element_name = "name"; + parsable_class->element_namespace = "gd"; + + /** + * GDataGDName:given-name: + * + * The person's given name. + * + * For more information, see the + * GData specification. + * + * Since: 0.5.0 + */ + g_object_class_install_property (gobject_class, PROP_GIVEN_NAME, + g_param_spec_string ("given-name", + "Given name", "The person's given name.", + NULL, + G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)); + + /** + * GDataGDName:additional-name: + * + * An additional name for the person (e.g. a middle name). + * + * For more information, see the + * GData specification. + * + * Since: 0.5.0 + */ + g_object_class_install_property (gobject_class, PROP_ADDITIONAL_NAME, + g_param_spec_string ("additional-name", + "Additional name", "An additional name for the person (e.g. a middle name).", + NULL, + G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)); + + /** + * GDataGDName:family-name: + * + * The person's family name. + * + * For more information, see the + * GData specification. + * + * Since: 0.5.0 + */ + g_object_class_install_property (gobject_class, PROP_FAMILY_NAME, + g_param_spec_string ("family-name", + "Family name", "The person's family name.", + NULL, + G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)); + + /** + * GDataGDName:prefix: + * + * An honorific prefix (e.g. Mr or Mrs). + * + * For more information, see the + * GData specification. + * + * Since: 0.5.0 + */ + g_object_class_install_property (gobject_class, PROP_PREFIX, + g_param_spec_string ("prefix", + "Prefix", "An honorific prefix.", + NULL, + G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)); + + /** + * GDataGDName:suffix: + * + * An honorific suffix (e.g. san or III). + * + * For more information, see the + * GData specification. + * + * Since: 0.5.0 + */ + g_object_class_install_property (gobject_class, PROP_SUFFIX, + g_param_spec_string ("suffix", + "Suffix", "An honorific suffix.", + NULL, + G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)); + + /** + * GDataGDName:full-name: + * + * An unstructured representation of the person's full name. It's generally advised to use the other individual properties in preference + * to this one, which can fall out of synchronisation with the other properties. + * + * For more information, see the + * GData specification. + * + * Since: 0.5.0 + */ + g_object_class_install_property (gobject_class, PROP_FULL_NAME, + g_param_spec_string ("full-name", + "Full name", "An unstructured representation of the person's full name.", + NULL, + G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)); +} + +static gint +compare_with (GDataComparable *self, GDataComparable *other) +{ + GDataGDNamePrivate *a = ((GDataGDName*) self)->priv, *b = ((GDataGDName*) other)->priv; + + if (g_strcmp0 (a->given_name, b->given_name) == 0 && g_strcmp0 (a->additional_name, b->additional_name) == 0 && + g_strcmp0 (a->family_name, b->family_name) == 0 && g_strcmp0 (a->prefix, b->prefix) == 0) + return 0; + return 1; +} + +static void +gdata_gd_name_comparable_init (GDataComparableIface *iface) +{ + iface->compare_with = compare_with; +} + +static void +gdata_gd_name_init (GDataGDName *self) +{ + self->priv = G_TYPE_INSTANCE_GET_PRIVATE (self, GDATA_TYPE_GD_NAME, GDataGDNamePrivate); +} + +static void +gdata_gd_name_finalize (GObject *object) +{ + GDataGDNamePrivate *priv = GDATA_GD_NAME (object)->priv; + + g_free (priv->given_name); + g_free (priv->additional_name); + g_free (priv->family_name); + g_free (priv->prefix); + g_free (priv->suffix); + g_free (priv->full_name); + + /* Chain up to the parent class */ + G_OBJECT_CLASS (gdata_gd_name_parent_class)->finalize (object); +} + +static void +gdata_gd_name_get_property (GObject *object, guint property_id, GValue *value, GParamSpec *pspec) +{ + GDataGDNamePrivate *priv = GDATA_GD_NAME (object)->priv; + + switch (property_id) { + case PROP_GIVEN_NAME: + g_value_set_string (value, priv->given_name); + break; + case PROP_ADDITIONAL_NAME: + g_value_set_string (value, priv->additional_name); + break; + case PROP_FAMILY_NAME: + g_value_set_string (value, priv->family_name); + break; + case PROP_PREFIX: + g_value_set_string (value, priv->prefix); + break; + case PROP_SUFFIX: + g_value_set_string (value, priv->suffix); + break; + case PROP_FULL_NAME: + g_value_set_string (value, priv->full_name); + break; + default: + /* We don't have any other property... */ + G_OBJECT_WARN_INVALID_PROPERTY_ID (object, property_id, pspec); + break; + } +} + +static void +gdata_gd_name_set_property (GObject *object, guint property_id, const GValue *value, GParamSpec *pspec) +{ + GDataGDName *self = GDATA_GD_NAME (object); + + switch (property_id) { + case PROP_GIVEN_NAME: + gdata_gd_name_set_given_name (self, g_value_get_string (value)); + break; + case PROP_ADDITIONAL_NAME: + gdata_gd_name_set_additional_name (self, g_value_get_string (value)); + break; + case PROP_FAMILY_NAME: + gdata_gd_name_set_family_name (self, g_value_get_string (value)); + break; + case PROP_PREFIX: + gdata_gd_name_set_prefix (self, g_value_get_string (value)); + break; + case PROP_SUFFIX: + gdata_gd_name_set_suffix (self, g_value_get_string (value)); + break; + case PROP_FULL_NAME: + gdata_gd_name_set_full_name (self, g_value_get_string (value)); + break; + default: + /* We don't have any other property... */ + G_OBJECT_WARN_INVALID_PROPERTY_ID (object, property_id, pspec); + break; + } +} + +static gboolean +parse_xml (GDataParsable *parsable, xmlDoc *doc, xmlNode *node, gpointer user_data, GError **error) +{ + gboolean success; + GDataGDNamePrivate *priv = GDATA_GD_NAME (parsable)->priv; + + if (gdata_parser_is_namespace (node, "http://schemas.google.com/g/2005") == TRUE && ( + gdata_parser_string_from_element (node, "givenName", P_NO_DUPES, &(priv->given_name), &success, error) == TRUE || + gdata_parser_string_from_element (node, "additionalName", P_NO_DUPES, &(priv->additional_name), &success, error) == TRUE || + gdata_parser_string_from_element (node, "familyName", P_NO_DUPES, &(priv->family_name), &success, error) == TRUE || + gdata_parser_string_from_element (node, "namePrefix", P_NO_DUPES, &(priv->prefix), &success, error) == TRUE || + gdata_parser_string_from_element (node, "nameSuffix", P_NO_DUPES, &(priv->suffix), &success, error) == TRUE || + gdata_parser_string_from_element (node, "fullName", P_NO_DUPES, &(priv->full_name), &success, error) == TRUE)) { + return success; + } else { + return GDATA_PARSABLE_CLASS (gdata_gd_name_parent_class)->parse_xml (parsable, doc, node, user_data, error); + } +} + +static void +get_xml (GDataParsable *parsable, GString *xml_string) +{ + GDataGDNamePrivate *priv = GDATA_GD_NAME (parsable)->priv; + +#define OUTPUT_STRING_ELEMENT(E,F) \ + if (priv->F != NULL) \ + gdata_parser_string_append_escaped (xml_string, "", priv->F, ""); + + OUTPUT_STRING_ELEMENT ("givenName", given_name) + OUTPUT_STRING_ELEMENT ("additionalName", additional_name) + OUTPUT_STRING_ELEMENT ("familyName", family_name) + OUTPUT_STRING_ELEMENT ("namePrefix", prefix) + OUTPUT_STRING_ELEMENT ("nameSuffix", suffix) + + /* We can't guarantee that priv->full_name is non-empty without breaking API. */ + if (priv->full_name != NULL && *(priv->full_name) != '\0') { + gdata_parser_string_append_escaped (xml_string, "", priv->full_name, ""); + } + +#undef OUTPUT_STRING_ELEMENT +} + +static void +get_namespaces (GDataParsable *parsable, GHashTable *namespaces) +{ + g_hash_table_insert (namespaces, (gchar*) "gd", (gchar*) "http://schemas.google.com/g/2005"); +} + +/** + * gdata_gd_name_new: + * @given_name: (allow-none): the person's given name, or %NULL + * @family_name: (allow-none): the person's family name, or %NULL + * + * Creates a new #GDataGDName. More information is available in the GData specification. + * + * Return value: a new #GDataGDName, or %NULL; unref with g_object_unref() + * + * Since: 0.5.0 + */ +GDataGDName * +gdata_gd_name_new (const gchar *given_name, const gchar *family_name) +{ + g_return_val_if_fail (given_name == NULL || *given_name != '\0', NULL); + g_return_val_if_fail (family_name == NULL || *family_name != '\0', NULL); + return g_object_new (GDATA_TYPE_GD_NAME, "given-name", given_name, "family-name", family_name, NULL); +} + +/** + * gdata_gd_name_get_given_name: + * @self: a #GDataGDName + * + * Gets the #GDataGDName:given-name property. + * + * Return value: the person's given name, or %NULL + * + * Since: 0.5.0 + */ +const gchar * +gdata_gd_name_get_given_name (GDataGDName *self) +{ + g_return_val_if_fail (GDATA_IS_GD_NAME (self), NULL); + return self->priv->given_name; +} + +/** + * gdata_gd_name_set_given_name: + * @self: a #GDataGDName + * @given_name: (allow-none): the new given name, or %NULL + * + * Sets the #GDataGDName:given-name property to @given_name. + * + * Since: 0.5.0 + */ +void +gdata_gd_name_set_given_name (GDataGDName *self, const gchar *given_name) +{ + g_return_if_fail (GDATA_IS_GD_NAME (self)); + g_return_if_fail (given_name == NULL || *given_name != '\0'); + + g_free (self->priv->given_name); + self->priv->given_name = g_strdup (given_name); + g_object_notify (G_OBJECT (self), "given-name"); +} + +/** + * gdata_gd_name_get_additional_name: + * @self: a #GDataGDName + * + * Gets the #GDataGDName:additional-name property. + * + * Return value: the person's additional name, or %NULL + * + * Since: 0.5.0 + */ +const gchar * +gdata_gd_name_get_additional_name (GDataGDName *self) +{ + g_return_val_if_fail (GDATA_IS_GD_NAME (self), NULL); + return self->priv->additional_name; +} + +/** + * gdata_gd_name_set_additional_name: + * @self: a #GDataGDName + * @additional_name: (allow-none): the new additional name, or %NULL + * + * Sets the #GDataGDName:additional-name property to @additional_name. + * + * Since: 0.5.0 + */ +void +gdata_gd_name_set_additional_name (GDataGDName *self, const gchar *additional_name) +{ + g_return_if_fail (GDATA_IS_GD_NAME (self)); + g_return_if_fail (additional_name == NULL || *additional_name != '\0'); + + g_free (self->priv->additional_name); + self->priv->additional_name = g_strdup (additional_name); + g_object_notify (G_OBJECT (self), "additional-name"); +} + +/** + * gdata_gd_name_get_family_name: + * @self: a #GDataGDName + * + * Gets the #GDataGDName:family-name property. + * + * Return value: the person's family name, or %NULL + * + * Since: 0.5.0 + */ +const gchar * +gdata_gd_name_get_family_name (GDataGDName *self) +{ + g_return_val_if_fail (GDATA_IS_GD_NAME (self), NULL); + return self->priv->family_name; +} + +/** + * gdata_gd_name_set_family_name: + * @self: a #GDataGDName + * @family_name: (allow-none): the new family name, or %NULL + * + * Sets the #GDataGDName:family-name property to @family_name. + * + * Since: 0.5.0 + */ +void +gdata_gd_name_set_family_name (GDataGDName *self, const gchar *family_name) +{ + g_return_if_fail (GDATA_IS_GD_NAME (self)); + g_return_if_fail (family_name == NULL || *family_name != '\0'); + + g_free (self->priv->family_name); + self->priv->family_name = g_strdup (family_name); + g_object_notify (G_OBJECT (self), "family-name"); +} + +/** + * gdata_gd_name_get_prefix: + * @self: a #GDataGDName + * + * Gets the #GDataGDName:prefix property. + * + * Return value: the person's name prefix, or %NULL + * + * Since: 0.5.0 + */ +const gchar * +gdata_gd_name_get_prefix (GDataGDName *self) +{ + g_return_val_if_fail (GDATA_IS_GD_NAME (self), NULL); + return self->priv->prefix; +} + +/** + * gdata_gd_name_set_prefix: + * @self: a #GDataGDName + * @prefix: (allow-none): the new prefix, or %NULL + * + * Sets the #GDataGDName:prefix property to @prefix. + * + * Since: 0.5.0 + */ +void +gdata_gd_name_set_prefix (GDataGDName *self, const gchar *prefix) +{ + g_return_if_fail (GDATA_IS_GD_NAME (self)); + g_return_if_fail (prefix == NULL || *prefix != '\0'); + + g_free (self->priv->prefix); + self->priv->prefix = g_strdup (prefix); + g_object_notify (G_OBJECT (self), "prefix"); +} + +/** + * gdata_gd_name_get_suffix: + * @self: a #GDataGDName + * + * Gets the #GDataGDName:suffix property. + * + * Return value: the person's name suffix, or %NULL + * + * Since: 0.5.0 + */ +const gchar * +gdata_gd_name_get_suffix (GDataGDName *self) +{ + g_return_val_if_fail (GDATA_IS_GD_NAME (self), NULL); + return self->priv->suffix; +} + +/** + * gdata_gd_name_set_suffix: + * @self: a #GDataGDName + * @suffix: (allow-none): the new suffix, or %NULL + * + * Sets the #GDataGDName:suffix property to @suffix. + * + * Since: 0.5.0 + */ +void +gdata_gd_name_set_suffix (GDataGDName *self, const gchar *suffix) +{ + g_return_if_fail (GDATA_IS_GD_NAME (self)); + g_return_if_fail (suffix == NULL || *suffix != '\0'); + + g_free (self->priv->suffix); + self->priv->suffix = g_strdup (suffix); + g_object_notify (G_OBJECT (self), "suffix"); +} + +/** + * gdata_gd_name_get_full_name: + * @self: a #GDataGDName + * + * Gets the #GDataGDName:full-name property. + * + * Return value: the person's full name, or %NULL + * + * Since: 0.5.0 + */ +const gchar * +gdata_gd_name_get_full_name (GDataGDName *self) +{ + g_return_val_if_fail (GDATA_IS_GD_NAME (self), NULL); + return self->priv->full_name; +} + +/** + * gdata_gd_name_set_full_name: + * @self: a #GDataGDName + * @full_name: (allow-none): the new full name, or %NULL + * + * Sets the #GDataGDName:full-name property to @full_name. + * + * Since: 0.5.0 + */ +void +gdata_gd_name_set_full_name (GDataGDName *self, const gchar *full_name) +{ + g_return_if_fail (GDATA_IS_GD_NAME (self)); + + /* Coerce empty strings to NULL. Ideally, we should have this as a precondition (as all the other setters in GDataGDName have) but that would + * break API. */ + if (full_name != NULL && *full_name == '\0') { + full_name = NULL; + } + + g_free (self->priv->full_name); + self->priv->full_name = g_strdup (full_name); + g_object_notify (G_OBJECT (self), "full-name"); +} diff --git a/gdata/gd/gdata-gd-name.h b/gdata/gd/gdata-gd-name.h new file mode 100644 index 0000000..2044564 --- /dev/null +++ b/gdata/gd/gdata-gd-name.h @@ -0,0 +1,92 @@ +/* -*- Mode: C; indent-tabs-mode: t; c-basic-offset: 8; tab-width: 8 -*- */ +/* + * GData Client + * Copyright (C) Philip Withnall 2009 + * + * GData Client is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * GData Client is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with GData Client. If not, see . + */ + +#ifndef GDATA_GD_NAME_H +#define GDATA_GD_NAME_H + +#include +#include + +#include + +G_BEGIN_DECLS + +#define GDATA_TYPE_GD_NAME (gdata_gd_name_get_type ()) +#define GDATA_GD_NAME(o) (G_TYPE_CHECK_INSTANCE_CAST ((o), GDATA_TYPE_GD_NAME, GDataGDName)) +#define GDATA_GD_NAME_CLASS(k) (G_TYPE_CHECK_CLASS_CAST((k), GDATA_TYPE_GD_NAME, GDataGDNameClass)) +#define GDATA_IS_GD_NAME(o) (G_TYPE_CHECK_INSTANCE_TYPE ((o), GDATA_TYPE_GD_NAME)) +#define GDATA_IS_GD_NAME_CLASS(k) (G_TYPE_CHECK_CLASS_TYPE ((k), GDATA_TYPE_GD_NAME)) +#define GDATA_GD_NAME_GET_CLASS(o) (G_TYPE_INSTANCE_GET_CLASS ((o), GDATA_TYPE_GD_NAME, GDataGDNameClass)) + +typedef struct _GDataGDNamePrivate GDataGDNamePrivate; + +/** + * GDataGDName: + * + * All the fields in the #GDataGDName structure are private and should never be accessed directly. + * + * Since: 0.5.0 + */ +typedef struct { + GDataParsable parent; + GDataGDNamePrivate *priv; +} GDataGDName; + +/** + * GDataGDNameClass: + * + * All the fields in the #GDataGDNameClass structure are private and should never be accessed directly. + * + * Since: 0.5.0 + */ +typedef struct { + /*< private >*/ + GDataParsableClass parent; + + /*< private >*/ + /* Padding for future expansion */ + void (*_g_reserved0) (void); + void (*_g_reserved1) (void); +} GDataGDNameClass; + +GType gdata_gd_name_get_type (void) G_GNUC_CONST; + +GDataGDName *gdata_gd_name_new (const gchar *given_name, const gchar *family_name) G_GNUC_WARN_UNUSED_RESULT G_GNUC_MALLOC; + +const gchar *gdata_gd_name_get_given_name (GDataGDName *self) G_GNUC_PURE; +void gdata_gd_name_set_given_name (GDataGDName *self, const gchar *given_name); + +const gchar *gdata_gd_name_get_additional_name (GDataGDName *self) G_GNUC_PURE; +void gdata_gd_name_set_additional_name (GDataGDName *self, const gchar *additional_name); + +const gchar *gdata_gd_name_get_family_name (GDataGDName *self) G_GNUC_PURE; +void gdata_gd_name_set_family_name (GDataGDName *self, const gchar *family_name); + +const gchar *gdata_gd_name_get_prefix (GDataGDName *self) G_GNUC_PURE; +void gdata_gd_name_set_prefix (GDataGDName *self, const gchar *prefix); + +const gchar *gdata_gd_name_get_suffix (GDataGDName *self) G_GNUC_PURE; +void gdata_gd_name_set_suffix (GDataGDName *self, const gchar *suffix); + +const gchar *gdata_gd_name_get_full_name (GDataGDName *self) G_GNUC_PURE; +void gdata_gd_name_set_full_name (GDataGDName *self, const gchar *full_name); + +G_END_DECLS + +#endif /* !GDATA_GD_NAME_H */ diff --git a/gdata/gd/gdata-gd-organization.c b/gdata/gd/gdata-gd-organization.c new file mode 100644 index 0000000..c5d6a23 --- /dev/null +++ b/gdata/gd/gdata-gd-organization.c @@ -0,0 +1,826 @@ +/* -*- Mode: C; indent-tabs-mode: t; c-basic-offset: 8; tab-width: 8 -*- */ +/* + * GData Client + * Copyright (C) Philip Withnall 2009–2010 + * + * GData Client is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * GData Client is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with GData Client. If not, see . + */ + +/** + * SECTION:gdata-gd-organization + * @short_description: GData organization element + * @stability: Stable + * @include: gdata/gd/gdata-gd-organization.h + * + * #GDataGDOrganization represents an "organization" element from the + * GData specification. + * + * Since: 0.4.0 + */ + +#include +#include + +#include "gdata-gd-organization.h" +#include "gdata-parsable.h" +#include "gdata-parser.h" +#include "gdata-gd-where.h" +#include "gdata-private.h" +#include "gdata-comparable.h" + +static void gdata_gd_organization_comparable_init (GDataComparableIface *iface); +static void gdata_gd_organization_dispose (GObject *object); +static void gdata_gd_organization_finalize (GObject *object); +static void gdata_gd_organization_get_property (GObject *object, guint property_id, GValue *value, GParamSpec *pspec); +static void gdata_gd_organization_set_property (GObject *object, guint property_id, const GValue *value, GParamSpec *pspec); +static gboolean pre_parse_xml (GDataParsable *parsable, xmlDoc *doc, xmlNode *root_node, gpointer user_data, GError **error); +static gboolean parse_xml (GDataParsable *parsable, xmlDoc *doc, xmlNode *root_node, gpointer user_data, GError **error); +static void pre_get_xml (GDataParsable *parsable, GString *xml_string); +static void get_xml (GDataParsable *parsable, GString *xml_string); +static void get_namespaces (GDataParsable *parsable, GHashTable *namespaces); + +struct _GDataGDOrganizationPrivate { + gchar *name; + gchar *title; + gchar *relation_type; + gchar *label; + gboolean is_primary; + gchar *department; + gchar *job_description; + gchar *symbol; + GDataGDWhere *location; +}; + +enum { + PROP_NAME = 1, + PROP_TITLE, + PROP_RELATION_TYPE, + PROP_LABEL, + PROP_IS_PRIMARY, + PROP_DEPARTMENT, + PROP_JOB_DESCRIPTION, + PROP_SYMBOL, + PROP_LOCATION +}; + +G_DEFINE_TYPE_WITH_CODE (GDataGDOrganization, gdata_gd_organization, GDATA_TYPE_PARSABLE, + G_IMPLEMENT_INTERFACE (GDATA_TYPE_COMPARABLE, gdata_gd_organization_comparable_init)) + +static void +gdata_gd_organization_class_init (GDataGDOrganizationClass *klass) +{ + GObjectClass *gobject_class = G_OBJECT_CLASS (klass); + GDataParsableClass *parsable_class = GDATA_PARSABLE_CLASS (klass); + + g_type_class_add_private (klass, sizeof (GDataGDOrganizationPrivate)); + + gobject_class->get_property = gdata_gd_organization_get_property; + gobject_class->set_property = gdata_gd_organization_set_property; + gobject_class->dispose = gdata_gd_organization_dispose; + gobject_class->finalize = gdata_gd_organization_finalize; + + parsable_class->pre_parse_xml = pre_parse_xml; + parsable_class->parse_xml = parse_xml; + parsable_class->pre_get_xml = pre_get_xml; + parsable_class->get_xml = get_xml; + parsable_class->get_namespaces = get_namespaces; + parsable_class->element_name = "organization"; + parsable_class->element_namespace = "gd"; + + /** + * GDataGDOrganization:name: + * + * The name of the organization. + * + * For more information, see the + * GData specification. + * + * Since: 0.4.0 + */ + g_object_class_install_property (gobject_class, PROP_NAME, + g_param_spec_string ("name", + "Name", "The name of the organization.", + NULL, + G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)); + + /** + * GDataGDOrganization:title: + * + * The title of a person within the organization. + * + * For more information, see the + * GData specification. + * + * Since: 0.4.0 + */ + g_object_class_install_property (gobject_class, PROP_TITLE, + g_param_spec_string ("title", + "Title", "The title of a person within the organization.", + NULL, + G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)); + + /** + * GDataGDOrganization:relation-type: + * + * A programmatic value that identifies the type of organization. For example: %GDATA_GD_ORGANIZATION_WORK or %GDATA_GD_ORGANIZATION_OTHER. + * + * For more information, see the + * GData specification. + * + * Since: 0.4.0 + */ + g_object_class_install_property (gobject_class, PROP_RELATION_TYPE, + g_param_spec_string ("relation-type", + "Relation type", "A programmatic value that identifies the type of organization.", + NULL, + G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)); + + /** + * GDataGDOrganization:label: + * + * A simple string value used to name this organization. It allows UIs to display a label such as "Work", "Volunteer", + * "Professional Society", etc. + * + * For more information, see the + * GData specification. + * + * Since: 0.4.0 + */ + g_object_class_install_property (gobject_class, PROP_LABEL, + g_param_spec_string ("label", + "Label", "A simple string value used to name this organization.", + NULL, + G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)); + + /** + * GDataGDOrganization:is-primary: + * + * Indicates which organization out of a group is primary. + * + * For more information, see the + * GData specification. + * + * Since: 0.4.0 + */ + g_object_class_install_property (gobject_class, PROP_IS_PRIMARY, + g_param_spec_boolean ("is-primary", + "Primary?", "Indicates which organization out of a group is primary.", + FALSE, + G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)); + + /** + * GDataGDOrganization:department: + * + * Specifies a department within the organization. + * + * For more information, see the + * GData specification. + * + * Since: 0.5.0 + */ + g_object_class_install_property (gobject_class, PROP_DEPARTMENT, + g_param_spec_string ("department", + "Department", "Specifies a department within the organization.", + NULL, + G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)); + + /** + * GDataGDOrganization:job-description: + * + * Description of a job within the organization. + * + * For more information, see the + * GData specification. + * + * Since: 0.5.0 + */ + g_object_class_install_property (gobject_class, PROP_JOB_DESCRIPTION, + g_param_spec_string ("job-description", + "Job description", "Description of a job within the organization.", + NULL, + G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)); + + /** + * GDataGDOrganization:symbol: + * + * Stock symbol of the organization. + * + * For more information, see the + * GData specification. + * + * Since: 0.5.0 + */ + g_object_class_install_property (gobject_class, PROP_SYMBOL, + g_param_spec_string ("symbol", + "Symbol", "Symbol of the organization.", + NULL, + G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)); + + /** + * GDataGDOrganization:location: + * + * A place associated with the organization, e.g. office location. + * + * For more information, see the + * GData specification. + * + * Since: 0.6.0 + */ + g_object_class_install_property (gobject_class, PROP_LOCATION, + g_param_spec_object ("location", + "Location", "A place associated with the organization, e.g. office location.", + GDATA_TYPE_GD_WHERE, + G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)); +} + +static gint +compare_with (GDataComparable *self, GDataComparable *other) +{ + GDataGDOrganizationPrivate *a = ((GDataGDOrganization*) self)->priv, *b = ((GDataGDOrganization*) other)->priv; + + if (g_strcmp0 (a->name, b->name) == 0 && g_strcmp0 (a->title, b->title) == 0 && g_strcmp0 (a->department, b->department) == 0) + return 0; + return 1; +} + +static void +gdata_gd_organization_comparable_init (GDataComparableIface *iface) +{ + iface->compare_with = compare_with; +} + +static void +gdata_gd_organization_init (GDataGDOrganization *self) +{ + self->priv = G_TYPE_INSTANCE_GET_PRIVATE (self, GDATA_TYPE_GD_ORGANIZATION, GDataGDOrganizationPrivate); +} + +static void +gdata_gd_organization_dispose (GObject *object) +{ + GDataGDOrganizationPrivate *priv = GDATA_GD_ORGANIZATION (object)->priv; + + if (priv->location != NULL) + g_object_unref (priv->location); + + /* Chain up to the parent class */ + G_OBJECT_CLASS (gdata_gd_organization_parent_class)->dispose (object); +} + +static void +gdata_gd_organization_finalize (GObject *object) +{ + GDataGDOrganizationPrivate *priv = GDATA_GD_ORGANIZATION (object)->priv; + + g_free (priv->name); + g_free (priv->title); + g_free (priv->relation_type); + g_free (priv->label); + g_free (priv->department); + g_free (priv->job_description); + g_free (priv->symbol); + + /* Chain up to the parent class */ + G_OBJECT_CLASS (gdata_gd_organization_parent_class)->finalize (object); +} + +static void +gdata_gd_organization_get_property (GObject *object, guint property_id, GValue *value, GParamSpec *pspec) +{ + GDataGDOrganizationPrivate *priv = GDATA_GD_ORGANIZATION (object)->priv; + + switch (property_id) { + case PROP_NAME: + g_value_set_string (value, priv->name); + break; + case PROP_TITLE: + g_value_set_string (value, priv->title); + break; + case PROP_RELATION_TYPE: + g_value_set_string (value, priv->relation_type); + break; + case PROP_LABEL: + g_value_set_string (value, priv->label); + break; + case PROP_IS_PRIMARY: + g_value_set_boolean (value, priv->is_primary); + break; + case PROP_DEPARTMENT: + g_value_set_string (value, priv->department); + break; + case PROP_JOB_DESCRIPTION: + g_value_set_string (value, priv->job_description); + break; + case PROP_SYMBOL: + g_value_set_string (value, priv->symbol); + break; + case PROP_LOCATION: + g_value_set_object (value, priv->location); + break; + default: + /* We don't have any other property... */ + G_OBJECT_WARN_INVALID_PROPERTY_ID (object, property_id, pspec); + break; + } +} + +static void +gdata_gd_organization_set_property (GObject *object, guint property_id, const GValue *value, GParamSpec *pspec) +{ + GDataGDOrganization *self = GDATA_GD_ORGANIZATION (object); + + switch (property_id) { + case PROP_NAME: + gdata_gd_organization_set_name (self, g_value_get_string (value)); + break; + case PROP_TITLE: + gdata_gd_organization_set_title (self, g_value_get_string (value)); + break; + case PROP_RELATION_TYPE: + gdata_gd_organization_set_relation_type (self, g_value_get_string (value)); + break; + case PROP_LABEL: + gdata_gd_organization_set_label (self, g_value_get_string (value)); + break; + case PROP_IS_PRIMARY: + gdata_gd_organization_set_is_primary (self, g_value_get_boolean (value)); + break; + case PROP_DEPARTMENT: + gdata_gd_organization_set_department (self, g_value_get_string (value)); + break; + case PROP_JOB_DESCRIPTION: + gdata_gd_organization_set_job_description (self, g_value_get_string (value)); + break; + case PROP_SYMBOL: + gdata_gd_organization_set_symbol (self, g_value_get_string (value)); + break; + case PROP_LOCATION: + gdata_gd_organization_set_location (self, g_value_get_object (value)); + break; + default: + /* We don't have any other property... */ + G_OBJECT_WARN_INVALID_PROPERTY_ID (object, property_id, pspec); + break; + } +} + +static gboolean +pre_parse_xml (GDataParsable *parsable, xmlDoc *doc, xmlNode *root_node, gpointer user_data, GError **error) +{ + xmlChar *rel; + gboolean primary_bool; + GDataGDOrganizationPrivate *priv = GDATA_GD_ORGANIZATION (parsable)->priv; + + /* Is it the primary organisation? */ + if (gdata_parser_boolean_from_property (root_node, "primary", &primary_bool, 0, error) == FALSE) + return FALSE; + + rel = xmlGetProp (root_node, (xmlChar*) "rel"); + if (rel != NULL && *rel == '\0') { + xmlFree (rel); + return gdata_parser_error_required_property_missing (root_node, "rel", error); + } + + priv->relation_type = (gchar*) rel; + priv->label = (gchar*) xmlGetProp (root_node, (xmlChar*) "label"); + priv->is_primary = primary_bool; + + return TRUE; +} + +static gboolean +parse_xml (GDataParsable *parsable, xmlDoc *doc, xmlNode *node, gpointer user_data, GError **error) +{ + gboolean success; + GDataGDOrganizationPrivate *priv = GDATA_GD_ORGANIZATION (parsable)->priv; + + if (gdata_parser_is_namespace (node, "http://schemas.google.com/g/2005") == TRUE && ( + gdata_parser_string_from_element (node, "orgName", P_NO_DUPES, &(priv->name), &success, error) == TRUE || + gdata_parser_string_from_element (node, "orgTitle", P_NO_DUPES, &(priv->title), &success, error) == TRUE || + gdata_parser_string_from_element (node, "orgDepartment", P_NO_DUPES, &(priv->department), &success, error) == TRUE || + gdata_parser_string_from_element (node, "orgJobDescription", P_NO_DUPES, &(priv->job_description), &success, error) == TRUE || + gdata_parser_string_from_element (node, "orgSymbol", P_NO_DUPES, &(priv->symbol), &success, error) == TRUE || + gdata_parser_object_from_element (node, "where", P_REQUIRED | P_NO_DUPES, GDATA_TYPE_GD_WHERE, + &(priv->location), &success, error) == TRUE)) { + return success; + } else { + return GDATA_PARSABLE_CLASS (gdata_gd_organization_parent_class)->parse_xml (parsable, doc, node, user_data, error); + } +} + +static void +pre_get_xml (GDataParsable *parsable, GString *xml_string) +{ + GDataGDOrganizationPrivate *priv = GDATA_GD_ORGANIZATION (parsable)->priv; + + if (priv->relation_type != NULL) + gdata_parser_string_append_escaped (xml_string, " rel='", priv->relation_type, "'"); + if (priv->label != NULL) + gdata_parser_string_append_escaped (xml_string, " label='", priv->label, "'"); + + if (priv->is_primary == TRUE) + g_string_append (xml_string, " primary='true'"); + else + g_string_append (xml_string, " primary='false'"); +} + +static void +get_xml (GDataParsable *parsable, GString *xml_string) +{ + GDataGDOrganizationPrivate *priv = GDATA_GD_ORGANIZATION (parsable)->priv; + + if (priv->name != NULL) + gdata_parser_string_append_escaped (xml_string, "", priv->name, ""); + if (priv->title != NULL) + gdata_parser_string_append_escaped (xml_string, "", priv->title, ""); + if (priv->department != NULL && *(priv->department) != '\0') + gdata_parser_string_append_escaped (xml_string, "", priv->department, ""); + if (priv->job_description != NULL) + gdata_parser_string_append_escaped (xml_string, "", priv->job_description, ""); + if (priv->symbol != NULL) + gdata_parser_string_append_escaped (xml_string, "", priv->symbol, ""); + if (priv->location != NULL) + _gdata_parsable_get_xml (GDATA_PARSABLE (priv->location), xml_string, FALSE); +} + +static void +get_namespaces (GDataParsable *parsable, GHashTable *namespaces) +{ + g_hash_table_insert (namespaces, (gchar*) "gd", (gchar*) "http://schemas.google.com/g/2005"); +} + +/** + * gdata_gd_organization_new: + * @name: (allow-none): the name of the organization, or %NULL + * @title: (allow-none): the owner's title within the organization, or %NULL + * @relation_type: (allow-none): the relationship between the organization and its owner, or %NULL + * @label: (allow-none): a human-readable label for the organization, or %NULL + * @is_primary: %TRUE if this organization is its owner's primary organization, %FALSE otherwise + * + * Creates a new #GDataGDOrganization. More information is available in the GData specification. + * + * Return value: a new #GDataGDOrganization, or %NULL; unref with g_object_unref() + * + * Since: 0.2.0 + */ +GDataGDOrganization * +gdata_gd_organization_new (const gchar *name, const gchar *title, const gchar *relation_type, const gchar *label, gboolean is_primary) +{ + g_return_val_if_fail (relation_type == NULL || *relation_type != '\0', NULL); + return g_object_new (GDATA_TYPE_GD_ORGANIZATION, "name", name, "title", title, "relation-type", relation_type, + "label", label, "is-primary", is_primary, NULL); +} + +/** + * gdata_gd_organization_get_name: + * @self: a #GDataGDOrganization + * + * Gets the #GDataGDOrganization:name property. + * + * Return value: the organization's name, or %NULL + * + * Since: 0.4.0 + */ +const gchar * +gdata_gd_organization_get_name (GDataGDOrganization *self) +{ + g_return_val_if_fail (GDATA_IS_GD_ORGANIZATION (self), NULL); + return self->priv->name; +} + +/** + * gdata_gd_organization_set_name: + * @self: a #GDataGDOrganization + * @name: (allow-none): the new name for the organization, or %NULL + * + * Sets the #GDataGDOrganization:name property to @name. + * + * Set @name to %NULL to unset the property in the organization. + * + * Since: 0.4.0 + */ +void +gdata_gd_organization_set_name (GDataGDOrganization *self, const gchar *name) +{ + g_return_if_fail (GDATA_IS_GD_ORGANIZATION (self)); + + g_free (self->priv->name); + self->priv->name = g_strdup (name); + g_object_notify (G_OBJECT (self), "name"); +} + +/** + * gdata_gd_organization_get_title: + * @self: a #GDataGDOrganization + * + * Gets the #GDataGDOrganization:title property. + * + * Return value: the organization's title, or %NULL + * + * Since: 0.4.0 + */ +const gchar * +gdata_gd_organization_get_title (GDataGDOrganization *self) +{ + g_return_val_if_fail (GDATA_IS_GD_ORGANIZATION (self), NULL); + return self->priv->title; +} + +/** + * gdata_gd_organization_set_title: + * @self: a #GDataGDOrganization + * @title: (allow-none): the new title for the organization, or %NULL + * + * Sets the #GDataGDOrganization:title property to @title. + * + * Set @title to %NULL to unset the property in the organization. + * + * Since: 0.4.0 + */ +void +gdata_gd_organization_set_title (GDataGDOrganization *self, const gchar *title) +{ + g_return_if_fail (GDATA_IS_GD_ORGANIZATION (self)); + + g_free (self->priv->title); + self->priv->title = g_strdup (title); + g_object_notify (G_OBJECT (self), "title"); +} + +/** + * gdata_gd_organization_get_relation_type: + * @self: a #GDataGDOrganization + * + * Gets the #GDataGDOrganization:relation-type property. + * + * Return value: the organization's relation type, or %NULL + * + * Since: 0.4.0 + */ +const gchar * +gdata_gd_organization_get_relation_type (GDataGDOrganization *self) +{ + g_return_val_if_fail (GDATA_IS_GD_ORGANIZATION (self), NULL); + return self->priv->relation_type; +} + +/** + * gdata_gd_organization_set_relation_type: + * @self: a #GDataGDOrganization + * @relation_type: (allow-none): the new relation type for the organization, or %NULL + * + * Sets the #GDataGDOrganization:relation-type property to @relation_type. + * + * Set @relation_type to %NULL to unset the property in the organization. + * + * Since: 0.4.0 + */ +void +gdata_gd_organization_set_relation_type (GDataGDOrganization *self, const gchar *relation_type) +{ + g_return_if_fail (GDATA_IS_GD_ORGANIZATION (self)); + g_return_if_fail (relation_type == NULL || *relation_type != '\0'); + + g_free (self->priv->relation_type); + self->priv->relation_type = g_strdup (relation_type); + g_object_notify (G_OBJECT (self), "relation-type"); +} + +/** + * gdata_gd_organization_get_label: + * @self: a #GDataGDOrganization + * + * Gets the #GDataGDOrganization:label property. + * + * Return value: the organization's label, or %NULL + * + * Since: 0.4.0 + */ +const gchar * +gdata_gd_organization_get_label (GDataGDOrganization *self) +{ + g_return_val_if_fail (GDATA_IS_GD_ORGANIZATION (self), NULL); + return self->priv->label; +} + +/** + * gdata_gd_organization_set_label: + * @self: a #GDataGDOrganization + * @label: (allow-none): the new label for the organization, or %NULL + * + * Sets the #GDataGDOrganization:label property to @label. + * + * Set @label to %NULL to unset the property in the organization. + * + * Since: 0.4.0 + */ +void +gdata_gd_organization_set_label (GDataGDOrganization *self, const gchar *label) +{ + g_return_if_fail (GDATA_IS_GD_ORGANIZATION (self)); + + g_free (self->priv->label); + self->priv->label = g_strdup (label); + g_object_notify (G_OBJECT (self), "label"); +} + +/** + * gdata_gd_organization_is_primary: + * @self: a #GDataGDOrganization + * + * Gets the #GDataGDOrganization:is-primary property. + * + * Return value: %TRUE if this is the primary organization, %FALSE otherwise + * + * Since: 0.4.0 + */ +gboolean +gdata_gd_organization_is_primary (GDataGDOrganization *self) +{ + g_return_val_if_fail (GDATA_IS_GD_ORGANIZATION (self), FALSE); + return self->priv->is_primary; +} + +/** + * gdata_gd_organization_set_is_primary: + * @self: a #GDataGDOrganization + * @is_primary: %TRUE if this is the primary organization, %FALSE otherwise + * + * Sets the #GDataGDOrganization:is-primary property to @is_primary. + * + * Since: 0.4.0 + */ +void +gdata_gd_organization_set_is_primary (GDataGDOrganization *self, gboolean is_primary) +{ + g_return_if_fail (GDATA_IS_GD_ORGANIZATION (self)); + + self->priv->is_primary = is_primary; + g_object_notify (G_OBJECT (self), "is-primary"); +} + +/** + * gdata_gd_organization_get_department: + * @self: a #GDataGDOrganization + * + * Gets the #GDataGDOrganization:department property. + * + * Return value: the department in which the person works in this organization, or %NULL + * + * Since: 0.5.0 + */ +const gchar * +gdata_gd_organization_get_department (GDataGDOrganization *self) +{ + g_return_val_if_fail (GDATA_IS_GD_ORGANIZATION (self), NULL); + return self->priv->department; +} + +/** + * gdata_gd_organization_set_department: + * @self: a #GDataGDOrganization + * @department: (allow-none): the new department for the person working in the organization, or %NULL + * + * Sets the #GDataGDOrganization:department property to @department. + * + * Set @department to %NULL to unset the property in the organization. + * + * Since: 0.5.0 + */ +void +gdata_gd_organization_set_department (GDataGDOrganization *self, const gchar *department) +{ + g_return_if_fail (GDATA_IS_GD_ORGANIZATION (self)); + + g_free (self->priv->department); + self->priv->department = g_strdup (department); + g_object_notify (G_OBJECT (self), "department"); +} + +/** + * gdata_gd_organization_get_job_description: + * @self: a #GDataGDOrganization + * + * Gets the #GDataGDOrganization:job-description property. + * + * Return value: the job description of the person in the organization, or %NULL + * + * Since: 0.5.0 + */ +const gchar * +gdata_gd_organization_get_job_description (GDataGDOrganization *self) +{ + g_return_val_if_fail (GDATA_IS_GD_ORGANIZATION (self), NULL); + return self->priv->job_description; +} + +/** + * gdata_gd_organization_set_job_description: + * @self: a #GDataGDOrganization + * @job_description: (allow-none): the new job description for the person in the organization, or %NULL + * + * Sets the #GDataGDOrganization:job-description property to @job_description. + * + * Set @job_description to %NULL to unset the property in the organization. + * + * Since: 0.5.0 + */ +void +gdata_gd_organization_set_job_description (GDataGDOrganization *self, const gchar *job_description) +{ + g_return_if_fail (GDATA_IS_GD_ORGANIZATION (self)); + + g_free (self->priv->job_description); + self->priv->job_description = g_strdup (job_description); + g_object_notify (G_OBJECT (self), "job-description"); +} + +/** + * gdata_gd_organization_get_symbol: + * @self: a #GDataGDOrganization + * + * Gets the #GDataGDOrganization:symbol property. + * + * Return value: the organization's stock symbol, or %NULL + * + * Since: 0.5.0 + */ +const gchar * +gdata_gd_organization_get_symbol (GDataGDOrganization *self) +{ + g_return_val_if_fail (GDATA_IS_GD_ORGANIZATION (self), NULL); + return self->priv->symbol; +} + +/** + * gdata_gd_organization_set_symbol: + * @self: a #GDataGDOrganization + * @symbol: (allow-none): the new stock symbol for the organization, or %NULL + * + * Sets the #GDataGDOrganization:symbol property to @symbol. + * + * Set @symbol to %NULL to unset the property in the organization. + * + * Since: 0.5.0 + */ +void +gdata_gd_organization_set_symbol (GDataGDOrganization *self, const gchar *symbol) +{ + g_return_if_fail (GDATA_IS_GD_ORGANIZATION (self)); + + g_free (self->priv->symbol); + self->priv->symbol = g_strdup (symbol); + g_object_notify (G_OBJECT (self), "symbol"); +} + +/** + * gdata_gd_organization_get_location: + * @self: a #GDataGDOrganization + * + * Gets the #GDataGDOrganization:location property. + * + * Return value: (transfer none): the organization's location, or %NULL + * + * Since: 0.6.0 + */ +GDataGDWhere * +gdata_gd_organization_get_location (GDataGDOrganization *self) +{ + g_return_val_if_fail (GDATA_IS_GD_ORGANIZATION (self), NULL); + return self->priv->location; +} + +/** + * gdata_gd_organization_set_location: + * @self: a #GDataGDOrganization + * @location: (allow-none): the new location for the organization, or %NULL + * + * Sets the #GDataGDOrganization:location property to @location. + * + * Set @location to %NULL to unset the property in the organization. + * + * Since: 0.6.0 + */ +void +gdata_gd_organization_set_location (GDataGDOrganization *self, GDataGDWhere *location) +{ + g_return_if_fail (GDATA_IS_GD_ORGANIZATION (self)); + g_return_if_fail (location == NULL || GDATA_IS_GD_WHERE (location)); + + if (self->priv->location != NULL) + g_object_unref (self->priv->location); + self->priv->location = (location != NULL) ? g_object_ref (location) : NULL; + g_object_notify (G_OBJECT (self), "location"); +} diff --git a/gdata/gd/gdata-gd-organization.h b/gdata/gd/gdata-gd-organization.h new file mode 100644 index 0000000..331d31a --- /dev/null +++ b/gdata/gd/gdata-gd-organization.h @@ -0,0 +1,121 @@ +/* -*- Mode: C; indent-tabs-mode: t; c-basic-offset: 8; tab-width: 8 -*- */ +/* + * GData Client + * Copyright (C) Philip Withnall 2009–2010 + * + * GData Client is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * GData Client is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with GData Client. If not, see . + */ + +#ifndef GDATA_GD_ORGANIZATION_H +#define GDATA_GD_ORGANIZATION_H + +#include +#include + +#include +#include + +G_BEGIN_DECLS + +/** + * GDATA_GD_ORGANIZATION_WORK: + * + * The relation type URI for a work organization. + * + * Since: 0.7.0 + */ +#define GDATA_GD_ORGANIZATION_WORK "http://schemas.google.com/g/2005#work" + +/** + * GDATA_GD_ORGANIZATION_OTHER: + * + * The relation type URI for a miscellaneous organization. + * + * Since: 0.7.0 + */ +#define GDATA_GD_ORGANIZATION_OTHER "http://schemas.google.com/g/2005#other" + +#define GDATA_TYPE_GD_ORGANIZATION (gdata_gd_organization_get_type ()) +#define GDATA_GD_ORGANIZATION(o) (G_TYPE_CHECK_INSTANCE_CAST ((o), GDATA_TYPE_GD_ORGANIZATION, GDataGDOrganization)) +#define GDATA_GD_ORGANIZATION_CLASS(k) (G_TYPE_CHECK_CLASS_CAST((k), GDATA_TYPE_GD_ORGANIZATION, GDataGDOrganizationClass)) +#define GDATA_IS_GD_ORGANIZATION(o) (G_TYPE_CHECK_INSTANCE_TYPE ((o), GDATA_TYPE_GD_ORGANIZATION)) +#define GDATA_IS_GD_ORGANIZATION_CLASS(k) (G_TYPE_CHECK_CLASS_TYPE ((k), GDATA_TYPE_GD_ORGANIZATION)) +#define GDATA_GD_ORGANIZATION_GET_CLASS(o) (G_TYPE_INSTANCE_GET_CLASS ((o), GDATA_TYPE_GD_ORGANIZATION, GDataGDOrganizationClass)) + +typedef struct _GDataGDOrganizationPrivate GDataGDOrganizationPrivate; + +/** + * GDataGDOrganization: + * + * All the fields in the #GDataGDOrganization structure are private and should never be accessed directly. + * + * Since: 0.2.0 + */ +typedef struct { + GDataParsable parent; + GDataGDOrganizationPrivate *priv; +} GDataGDOrganization; + +/** + * GDataGDOrganizationClass: + * + * All the fields in the #GDataGDOrganizationClass structure are private and should never be accessed directly. + * + * Since: 0.4.0 + */ +typedef struct { + /*< private >*/ + GDataParsableClass parent; + + /*< private >*/ + /* Padding for future expansion */ + void (*_g_reserved0) (void); + void (*_g_reserved1) (void); +} GDataGDOrganizationClass; + +GType gdata_gd_organization_get_type (void) G_GNUC_CONST; + +GDataGDOrganization *gdata_gd_organization_new (const gchar *name, const gchar *title, const gchar *relation_type, + const gchar *label, gboolean is_primary) G_GNUC_WARN_UNUSED_RESULT G_GNUC_MALLOC; + +const gchar *gdata_gd_organization_get_name (GDataGDOrganization *self) G_GNUC_PURE; +void gdata_gd_organization_set_name (GDataGDOrganization *self, const gchar *name); + +const gchar *gdata_gd_organization_get_title (GDataGDOrganization *self) G_GNUC_PURE; +void gdata_gd_organization_set_title (GDataGDOrganization *self, const gchar *title); + +const gchar *gdata_gd_organization_get_relation_type (GDataGDOrganization *self) G_GNUC_PURE; +void gdata_gd_organization_set_relation_type (GDataGDOrganization *self, const gchar *relation_type); + +const gchar *gdata_gd_organization_get_label (GDataGDOrganization *self) G_GNUC_PURE; +void gdata_gd_organization_set_label (GDataGDOrganization *self, const gchar *label); + +gboolean gdata_gd_organization_is_primary (GDataGDOrganization *self) G_GNUC_PURE; +void gdata_gd_organization_set_is_primary (GDataGDOrganization *self, gboolean is_primary); + +const gchar *gdata_gd_organization_get_department (GDataGDOrganization *self) G_GNUC_PURE; +void gdata_gd_organization_set_department (GDataGDOrganization *self, const gchar *department); + +const gchar *gdata_gd_organization_get_job_description (GDataGDOrganization *self) G_GNUC_PURE; +void gdata_gd_organization_set_job_description (GDataGDOrganization *self, const gchar *job_description); + +const gchar *gdata_gd_organization_get_symbol (GDataGDOrganization *self) G_GNUC_PURE; +void gdata_gd_organization_set_symbol (GDataGDOrganization *self, const gchar *symbol); + +GDataGDWhere *gdata_gd_organization_get_location (GDataGDOrganization *self) G_GNUC_PURE; +void gdata_gd_organization_set_location (GDataGDOrganization *self, GDataGDWhere *location); + +G_END_DECLS + +#endif /* !GDATA_GD_ORGANIZATION_H */ diff --git a/gdata/gd/gdata-gd-phone-number.c b/gdata/gd/gdata-gd-phone-number.c new file mode 100644 index 0000000..06c0be9 --- /dev/null +++ b/gdata/gd/gdata-gd-phone-number.c @@ -0,0 +1,562 @@ +/* -*- Mode: C; indent-tabs-mode: t; c-basic-offset: 8; tab-width: 8 -*- */ +/* + * GData Client + * Copyright (C) Philip Withnall 2009–2010 + * + * GData Client is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * GData Client is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with GData Client. If not, see . + */ + +/** + * SECTION:gdata-gd-phone-number + * @short_description: GData phone number element + * @stability: Stable + * @include: gdata/gd/gdata-gd-phone-number.h + * + * #GDataGDPhoneNumber represents a "phoneNumber" element from the + * GData specification. + * + * Since: 0.4.0 + */ + +#include +#include +#include + +#include "gdata-gd-phone-number.h" +#include "gdata-parsable.h" +#include "gdata-parser.h" +#include "gdata-comparable.h" + +static void gdata_gd_phone_number_comparable_init (GDataComparableIface *iface); +static void gdata_gd_phone_number_finalize (GObject *object); +static void gdata_gd_phone_number_get_property (GObject *object, guint property_id, GValue *value, GParamSpec *pspec); +static void gdata_gd_phone_number_set_property (GObject *object, guint property_id, const GValue *value, GParamSpec *pspec); +static gboolean pre_parse_xml (GDataParsable *parsable, xmlDoc *doc, xmlNode *root_node, gpointer user_data, GError **error); +static gboolean parse_xml (GDataParsable *parsable, xmlDoc *doc, xmlNode *node, gpointer user_data, GError **error); +static void pre_get_xml (GDataParsable *parsable, GString *xml_string); +static void get_xml (GDataParsable *parsable, GString *xml_string); +static void get_namespaces (GDataParsable *parsable, GHashTable *namespaces); + +struct _GDataGDPhoneNumberPrivate { + gchar *number; + gchar *uri; + gchar *relation_type; + gchar *label; + gboolean is_primary; +}; + +enum { + PROP_NUMBER = 1, + PROP_URI, + PROP_RELATION_TYPE, + PROP_LABEL, + PROP_IS_PRIMARY +}; + +G_DEFINE_TYPE_WITH_CODE (GDataGDPhoneNumber, gdata_gd_phone_number, GDATA_TYPE_PARSABLE, + G_IMPLEMENT_INTERFACE (GDATA_TYPE_COMPARABLE, gdata_gd_phone_number_comparable_init)) + +static void +gdata_gd_phone_number_class_init (GDataGDPhoneNumberClass *klass) +{ + GObjectClass *gobject_class = G_OBJECT_CLASS (klass); + GDataParsableClass *parsable_class = GDATA_PARSABLE_CLASS (klass); + + g_type_class_add_private (klass, sizeof (GDataGDPhoneNumberPrivate)); + + gobject_class->get_property = gdata_gd_phone_number_get_property; + gobject_class->set_property = gdata_gd_phone_number_set_property; + gobject_class->finalize = gdata_gd_phone_number_finalize; + + parsable_class->pre_parse_xml = pre_parse_xml; + parsable_class->parse_xml = parse_xml; + parsable_class->pre_get_xml = pre_get_xml; + parsable_class->get_xml = get_xml; + parsable_class->get_namespaces = get_namespaces; + parsable_class->element_name = "phoneNumber"; + parsable_class->element_namespace = "gd"; + + /** + * GDataGDPhoneNumber:number: + * + * Human-readable phone number; may be in any telephone number format. + * + * For more information, see the + * GData specification. + * + * Since: 0.4.0 + */ + g_object_class_install_property (gobject_class, PROP_NUMBER, + g_param_spec_string ("number", + "Number", "Human-readable phone number; may be in any telephone number format.", + NULL, + G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)); + + /** + * GDataGDPhoneNumber:uri: + * + * An optional "tel URI" used to represent the number in a formal way. Useful for programmatic access, such as a VoIP/PSTN bridge. + * + * For more information, see the + * GData specification. + * + * Since: 0.4.0 + */ + g_object_class_install_property (gobject_class, PROP_URI, + g_param_spec_string ("uri", + "URI", "An optional \"tel URI\" used to represent the number in a formal way.", + NULL, + G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)); + + /** + * GDataGDPhoneNumber:relation-type: + * + * A programmatic value that identifies the type of phone number. For example: %GDATA_GD_PHONE_NUMBER_WORK or %GDATA_GD_PHONE_NUMBER_PAGER. + * + * For more information, see the + * GData specification. + * + * Since: 0.4.0 + */ + g_object_class_install_property (gobject_class, PROP_RELATION_TYPE, + g_param_spec_string ("relation-type", + "Relation type", "A programmatic value that identifies the type of phone number.", + NULL, + G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)); + + /** + * GDataGDPhoneNumber:label: + * + * A simple string value used to name this phone number. It allows UIs to display a label such as "Mobile", "Home", "Work", etc. + * + * For more information, see the + * GData specification. + * + * Since: 0.4.0 + */ + g_object_class_install_property (gobject_class, PROP_LABEL, + g_param_spec_string ("label", + "Label", "A simple string value used to name this phone number.", + NULL, + G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)); + + /** + * GDataGDPhoneNumber:is-primary: + * + * Indicates which phone number out of a group is primary. + * + * For more information, see the + * GData specification. + * + * Since: 0.4.0 + */ + g_object_class_install_property (gobject_class, PROP_IS_PRIMARY, + g_param_spec_boolean ("is-primary", + "Primary?", "Indicates which phone number out of a group is primary.", + FALSE, + G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)); +} + +static gint +compare_with (GDataComparable *self, GDataComparable *other) +{ + GDataGDPhoneNumber *a = (GDataGDPhoneNumber*) self, *b = (GDataGDPhoneNumber*) other; + gint number_comparison, uri_comparison; + + number_comparison = g_strcmp0 (a->priv->number, b->priv->number); + uri_comparison = g_strcmp0 (a->priv->uri, b->priv->uri); + + /* NULL URIs should not compare equal. */ + if (a->priv->uri == NULL && b->priv->uri == NULL) { + uri_comparison = 1; + } + + /* If the numbers or the URIs are equal, the objects are equal. */ + if (number_comparison == 0 || uri_comparison == 0) { + return 0; + } + + return number_comparison; +} + +static void +gdata_gd_phone_number_comparable_init (GDataComparableIface *iface) +{ + iface->compare_with = compare_with; +} + +static void +gdata_gd_phone_number_init (GDataGDPhoneNumber *self) +{ + self->priv = G_TYPE_INSTANCE_GET_PRIVATE (self, GDATA_TYPE_GD_PHONE_NUMBER, GDataGDPhoneNumberPrivate); +} + +static void +gdata_gd_phone_number_finalize (GObject *object) +{ + GDataGDPhoneNumberPrivate *priv = GDATA_GD_PHONE_NUMBER (object)->priv; + + g_free (priv->number); + g_free (priv->uri); + g_free (priv->relation_type); + g_free (priv->label); + + /* Chain up to the parent class */ + G_OBJECT_CLASS (gdata_gd_phone_number_parent_class)->finalize (object); +} + +static void +gdata_gd_phone_number_get_property (GObject *object, guint property_id, GValue *value, GParamSpec *pspec) +{ + GDataGDPhoneNumberPrivate *priv = GDATA_GD_PHONE_NUMBER (object)->priv; + + switch (property_id) { + case PROP_NUMBER: + g_value_set_string (value, priv->number); + break; + case PROP_URI: + g_value_set_string (value, priv->uri); + break; + case PROP_RELATION_TYPE: + g_value_set_string (value, priv->relation_type); + break; + case PROP_LABEL: + g_value_set_string (value, priv->label); + break; + case PROP_IS_PRIMARY: + g_value_set_boolean (value, priv->is_primary); + break; + default: + /* We don't have any other property... */ + G_OBJECT_WARN_INVALID_PROPERTY_ID (object, property_id, pspec); + break; + } +} + +static void +gdata_gd_phone_number_set_property (GObject *object, guint property_id, const GValue *value, GParamSpec *pspec) +{ + GDataGDPhoneNumber *self = GDATA_GD_PHONE_NUMBER (object); + + switch (property_id) { + case PROP_NUMBER: + gdata_gd_phone_number_set_number (self, g_value_get_string (value)); + break; + case PROP_URI: + gdata_gd_phone_number_set_uri (self, g_value_get_string (value)); + break; + case PROP_RELATION_TYPE: + gdata_gd_phone_number_set_relation_type (self, g_value_get_string (value)); + break; + case PROP_LABEL: + gdata_gd_phone_number_set_label (self, g_value_get_string (value)); + break; + case PROP_IS_PRIMARY: + gdata_gd_phone_number_set_is_primary (self, g_value_get_boolean (value)); + break; + default: + /* We don't have any other property... */ + G_OBJECT_WARN_INVALID_PROPERTY_ID (object, property_id, pspec); + break; + } +} + +static gboolean +pre_parse_xml (GDataParsable *parsable, xmlDoc *doc, xmlNode *root_node, gpointer user_data, GError **error) +{ + xmlChar *number, *rel; + gboolean primary_bool; + GDataGDPhoneNumberPrivate *priv = GDATA_GD_PHONE_NUMBER (parsable)->priv; + + /* Is it the primary phone number? */ + if (gdata_parser_boolean_from_property (root_node, "primary", &primary_bool, 0, error) == FALSE) + return FALSE; + + number = xmlNodeListGetString (doc, root_node->children, TRUE); + if (number == NULL || *number == '\0') { + xmlFree (number); + return gdata_parser_error_required_content_missing (root_node, error); + } + + rel = xmlGetProp (root_node, (xmlChar*) "rel"); + if (rel != NULL && *rel == '\0') { + xmlFree (rel); + xmlFree (number); + return gdata_parser_error_required_property_missing (root_node, "rel", error); + } + + gdata_gd_phone_number_set_number (GDATA_GD_PHONE_NUMBER (parsable), (gchar*) number); + priv->uri = (gchar*) xmlGetProp (root_node, (xmlChar*) "uri"); + priv->relation_type = (gchar*) rel; + priv->label = (gchar*) xmlGetProp (root_node, (xmlChar*) "label"); + priv->is_primary = primary_bool; + + xmlFree (number); + + return TRUE; +} + +static gboolean +parse_xml (GDataParsable *parsable, xmlDoc *doc, xmlNode *node, gpointer user_data, GError **error) +{ + /* Textual content's handled in pre_parse_xml */ + if (node->type != XML_ELEMENT_NODE) + return TRUE; + + return GDATA_PARSABLE_CLASS (gdata_gd_phone_number_parent_class)->parse_xml (parsable, doc, node, user_data, error); +} + +static void +pre_get_xml (GDataParsable *parsable, GString *xml_string) +{ + GDataGDPhoneNumberPrivate *priv = GDATA_GD_PHONE_NUMBER (parsable)->priv; + + if (priv->uri != NULL) + gdata_parser_string_append_escaped (xml_string, " uri='", priv->uri, "'"); + if (priv->relation_type != NULL) + gdata_parser_string_append_escaped (xml_string, " rel='", priv->relation_type, "'"); + if (priv->label != NULL) + gdata_parser_string_append_escaped (xml_string, " label='", priv->label, "'"); + + if (priv->is_primary == TRUE) + g_string_append (xml_string, " primary='true'"); + else + g_string_append (xml_string, " primary='false'"); +} + +static void +get_xml (GDataParsable *parsable, GString *xml_string) +{ + gdata_parser_string_append_escaped (xml_string, NULL, GDATA_GD_PHONE_NUMBER (parsable)->priv->number, NULL); +} + +static void +get_namespaces (GDataParsable *parsable, GHashTable *namespaces) +{ + g_hash_table_insert (namespaces, (gchar*) "gd", (gchar*) "http://schemas.google.com/g/2005"); +} + +/** + * gdata_gd_phone_number_new: + * @number: the phone number, in human-readable format + * @relation_type: (allow-none): the relationship between the phone number and its owner, or %NULL + * @label: (allow-none): a human-readable label for the phone number, or %NULL + * @uri: (allow-none): a "tel URI" to represent the number formally (see + * RFC 3966), or %NULL + * @is_primary: %TRUE if this phone number is its owner's primary number, %FALSE otherwise + * + * Creates a new #GDataGDPhoneNumber. More information is available in the GData specification. + * + * Return value: a new #GDataGDPhoneNumber, or %NULL; unref with g_object_unref() + * + * Since: 0.2.0 + */ +GDataGDPhoneNumber * +gdata_gd_phone_number_new (const gchar *number, const gchar *relation_type, const gchar *label, const gchar *uri, gboolean is_primary) +{ + g_return_val_if_fail (number != NULL && *number != '\0', NULL); + g_return_val_if_fail (relation_type == NULL || *relation_type != '\0', NULL); + return g_object_new (GDATA_TYPE_GD_PHONE_NUMBER, "number", number, "uri", uri, "relation-type", relation_type, + "label", label, "is-primary", is_primary, NULL); +} + +/** + * gdata_gd_phone_number_get_number: + * @self: a #GDataGDPhoneNumber + * + * Gets the #GDataGDPhoneNumber:number property. + * + * Return value: the phone number itself + * + * Since: 0.4.0 + */ +const gchar * +gdata_gd_phone_number_get_number (GDataGDPhoneNumber *self) +{ + g_return_val_if_fail (GDATA_IS_GD_PHONE_NUMBER (self), NULL); + return self->priv->number; +} + +/** + * gdata_gd_phone_number_set_number: + * @self: a #GDataGDPhoneNumber + * @number: the new phone number + * + * Sets the #GDataGDPhoneNumber:number property to @number. + * + * Since: 0.4.0 + */ +void +gdata_gd_phone_number_set_number (GDataGDPhoneNumber *self, const gchar *number) +{ + g_return_if_fail (GDATA_IS_GD_PHONE_NUMBER (self)); + g_return_if_fail (number != NULL && *number != '\0'); + + /* Trim leading and trailing whitespace from the number. + * See here: http://code.google.com/apis/gdata/docs/1.0/elements.html#gdPhoneNumber */ + g_free (self->priv->number); + self->priv->number = gdata_parser_utf8_trim_whitespace (number); + g_object_notify (G_OBJECT (self), "number"); +} + +/** + * gdata_gd_phone_number_get_uri: + * @self: a #GDataGDPhoneNumber + * + * Gets the #GDataGDPhoneNumber:uri property. + * + * Return value: the phone number's URI, or %NULL + * + * Since: 0.4.0 + */ +const gchar * +gdata_gd_phone_number_get_uri (GDataGDPhoneNumber *self) +{ + g_return_val_if_fail (GDATA_IS_GD_PHONE_NUMBER (self), NULL); + return self->priv->uri; +} + +/** + * gdata_gd_phone_number_set_uri: + * @self: a #GDataGDPhoneNumber + * @uri: (allow-none): the new URI for the phone number, or %NULL + * + * Sets the #GDataGDPhoneNumber:uri property to @uri. + * + * Set @uri to %NULL to unset the property in the phone number. + * + * Since: 0.4.0 + */ +void +gdata_gd_phone_number_set_uri (GDataGDPhoneNumber *self, const gchar *uri) +{ + g_return_if_fail (GDATA_IS_GD_PHONE_NUMBER (self)); + + g_free (self->priv->uri); + self->priv->uri = g_strdup (uri); + g_object_notify (G_OBJECT (self), "uri"); +} + +/** + * gdata_gd_phone_number_get_relation_type: + * @self: a #GDataGDPhoneNumber + * + * Gets the #GDataGDPhoneNumber:relation-type property. + * + * Return value: the phone number's relation type, or %NULL + * + * Since: 0.4.0 + */ +const gchar * +gdata_gd_phone_number_get_relation_type (GDataGDPhoneNumber *self) +{ + g_return_val_if_fail (GDATA_IS_GD_PHONE_NUMBER (self), NULL); + return self->priv->relation_type; +} + +/** + * gdata_gd_phone_number_set_relation_type: + * @self: a #GDataGDPhoneNumber + * @relation_type: (allow-none): the new relation type for the phone number, or %NULL + * + * Sets the #GDataGDPhoneNumber:relation-type property to @relation_type. + * + * Set @relation_type to %NULL to unset the property in the phone number. + * + * Since: 0.4.0 + */ +void +gdata_gd_phone_number_set_relation_type (GDataGDPhoneNumber *self, const gchar *relation_type) +{ + g_return_if_fail (GDATA_IS_GD_PHONE_NUMBER (self)); + g_return_if_fail (relation_type == NULL || *relation_type != '\0'); + + g_free (self->priv->relation_type); + self->priv->relation_type = g_strdup (relation_type); + g_object_notify (G_OBJECT (self), "relation-type"); +} + +/** + * gdata_gd_phone_number_get_label: + * @self: a #GDataGDPhoneNumber + * + * Gets the #GDataGDPhoneNumber:label property. + * + * Return value: the phone number's label, or %NULL + * + * Since: 0.4.0 + */ +const gchar * +gdata_gd_phone_number_get_label (GDataGDPhoneNumber *self) +{ + g_return_val_if_fail (GDATA_IS_GD_PHONE_NUMBER (self), NULL); + return self->priv->label; +} + +/** + * gdata_gd_phone_number_set_label: + * @self: a #GDataGDPhoneNumber + * @label: (allow-none): the new label for the phone number, or %NULL + * + * Sets the #GDataGDPhoneNumber:label property to @label. + * + * Set @label to %NULL to unset the property in the phone number. + * + * Since: 0.4.0 + */ +void +gdata_gd_phone_number_set_label (GDataGDPhoneNumber *self, const gchar *label) +{ + g_return_if_fail (GDATA_IS_GD_PHONE_NUMBER (self)); + + g_free (self->priv->label); + self->priv->label = g_strdup (label); + g_object_notify (G_OBJECT (self), "label"); +} + +/** + * gdata_gd_phone_number_is_primary: + * @self: a #GDataGDPhoneNumber + * + * Gets the #GDataGDPhoneNumber:is-primary property. + * + * Return value: %TRUE if this is the primary phone number, %FALSE otherwise + * + * Since: 0.4.0 + */ +gboolean +gdata_gd_phone_number_is_primary (GDataGDPhoneNumber *self) +{ + g_return_val_if_fail (GDATA_IS_GD_PHONE_NUMBER (self), FALSE); + return self->priv->is_primary; +} + +/** + * gdata_gd_phone_number_set_is_primary: + * @self: a #GDataGDPhoneNumber + * @is_primary: %TRUE if this is the primary phone number, %FALSE otherwise + * + * Sets the #GDataGDPhoneNumber:is-primary property to @is_primary. + * + * Since: 0.4.0 + */ +void +gdata_gd_phone_number_set_is_primary (GDataGDPhoneNumber *self, gboolean is_primary) +{ + g_return_if_fail (GDATA_IS_GD_PHONE_NUMBER (self)); + + self->priv->is_primary = is_primary; + g_object_notify (G_OBJECT (self), "is-primary"); +} diff --git a/gdata/gd/gdata-gd-phone-number.h b/gdata/gd/gdata-gd-phone-number.h new file mode 100644 index 0000000..4a2995f --- /dev/null +++ b/gdata/gd/gdata-gd-phone-number.h @@ -0,0 +1,270 @@ +/* -*- Mode: C; indent-tabs-mode: t; c-basic-offset: 8; tab-width: 8 -*- */ +/* + * GData Client + * Copyright (C) Philip Withnall 2009–2010 + * + * GData Client is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * GData Client is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with GData Client. If not, see . + */ + +#ifndef GDATA_GD_PHONE_NUMBER_H +#define GDATA_GD_PHONE_NUMBER_H + +#include +#include + +#include + +G_BEGIN_DECLS + +/** + * GDATA_GD_PHONE_NUMBER_ASSISTANT: + * + * The relation type URI for the phone number of an assistant. + * + * Since: 0.7.0 + */ +#define GDATA_GD_PHONE_NUMBER_ASSISTANT "http://schemas.google.com/g/2005#assistant" + +/** + * GDATA_GD_PHONE_NUMBER_CALLBACK: + * + * The relation type URI for the phone number of a callback service. + * + * Since: 0.7.0 + */ +#define GDATA_GD_PHONE_NUMBER_CALLBACK "http://schemas.google.com/g/2005#callback" + +/** + * GDATA_GD_PHONE_NUMBER_CAR: + * + * The relation type URI for the phone number of a car phone. + * + * Since: 0.7.0 + */ +#define GDATA_GD_PHONE_NUMBER_CAR "http://schemas.google.com/g/2005#car" + +/** + * GDATA_GD_PHONE_NUMBER_COMPANY_MAIN: + * + * The relation type URI for the main phone number of a company. + * + * Since: 0.7.0 + */ +#define GDATA_GD_PHONE_NUMBER_COMPANY_MAIN "http://schemas.google.com/g/2005#company_main" + +/** + * GDATA_GD_PHONE_NUMBER_FAX: + * + * The relation type URI for the phone number of a fax machine. + * + * Since: 0.7.0 + */ +#define GDATA_GD_PHONE_NUMBER_FAX "http://schemas.google.com/g/2005#fax" + +/** + * GDATA_GD_PHONE_NUMBER_HOME: + * + * The relation type URI for a home phone number. + * + * Since: 0.7.0 + */ +#define GDATA_GD_PHONE_NUMBER_HOME "http://schemas.google.com/g/2005#home" + +/** + * GDATA_GD_PHONE_NUMBER_HOME_FAX: + * + * The relation type URI for the phone number of a home fax machine. + * + * Since: 0.7.0 + */ +#define GDATA_GD_PHONE_NUMBER_HOME_FAX "http://schemas.google.com/g/2005#home_fax" + +/** + * GDATA_GD_PHONE_NUMBER_ISDN: + * + * The relation type URI for the phone number of an ISDN phone. + * + * Since: 0.7.0 + */ +#define GDATA_GD_PHONE_NUMBER_ISDN "http://schemas.google.com/g/2005#isdn" + +/** + * GDATA_GD_PHONE_NUMBER_MAIN: + * + * The relation type URI for the main phone number of a person. + * + * Since: 0.7.0 + */ +#define GDATA_GD_PHONE_NUMBER_MAIN "http://schemas.google.com/g/2005#main" + +/** + * GDATA_GD_PHONE_NUMBER_MOBILE: + * + * The relation type URI for the phone number of a mobile phone. + * + * Since: 0.7.0 + */ +#define GDATA_GD_PHONE_NUMBER_MOBILE "http://schemas.google.com/g/2005#mobile" + +/** + * GDATA_GD_PHONE_NUMBER_OTHER: + * + * The relation type URI for a miscellaneous phone number. + * + * Since: 0.7.0 + */ +#define GDATA_GD_PHONE_NUMBER_OTHER "http://schemas.google.com/g/2005#other" + +/** + * GDATA_GD_PHONE_NUMBER_OTHER_FAX: + * + * The relation type URI for a miscellaneous fax machine's phone number. + * + * Since: 0.7.0 + */ +#define GDATA_GD_PHONE_NUMBER_OTHER_FAX "http://schemas.google.com/g/2005#other_fax" + +/** + * GDATA_GD_PHONE_NUMBER_PAGER: + * + * The relation type URI for the phone number of a pager. + * + * Since: 0.7.0 + */ +#define GDATA_GD_PHONE_NUMBER_PAGER "http://schemas.google.com/g/2005#pager" + +/** + * GDATA_GD_PHONE_NUMBER_RADIO: + * + * The relation type URI for the phone number of a radio phone. + * + * Since: 0.7.0 + */ +#define GDATA_GD_PHONE_NUMBER_RADIO "http://schemas.google.com/g/2005#radio" + +/** + * GDATA_GD_PHONE_NUMBER_TELEX: + * + * The relation type URI for the phone number of a telex machine. + * + * Since: 0.7.0 + */ +#define GDATA_GD_PHONE_NUMBER_TELEX "http://schemas.google.com/g/2005#telex" + +/** + * GDATA_GD_PHONE_NUMBER_TTY_TDD: + * + * The relation type URI for the phone number of a TTY TTD. + * + * Since: 0.7.0 + */ +#define GDATA_GD_PHONE_NUMBER_TTY_TDD "http://schemas.google.com/g/2005#tty_tdd" + +/** + * GDATA_GD_PHONE_NUMBER_WORK: + * + * The relation type URI for the phone number of a work place. + * + * Since: 0.7.0 + */ +#define GDATA_GD_PHONE_NUMBER_WORK "http://schemas.google.com/g/2005#work" + +/** + * GDATA_GD_PHONE_NUMBER_WORK_FAX: + * + * The relation type URI for the phone number of a work fax machine. + * + * Since: 0.7.0 + */ +#define GDATA_GD_PHONE_NUMBER_WORK_FAX "http://schemas.google.com/g/2005#work_fax" + +/** + * GDATA_GD_PHONE_NUMBER_WORK_MOBILE: + * + * The relation type URI for the phone number of a work mobile phone. + * + * Since: 0.7.0 + */ +#define GDATA_GD_PHONE_NUMBER_WORK_MOBILE "http://schemas.google.com/g/2005#work_mobile" + +/** + * GDATA_GD_PHONE_NUMBER_WORK_PAGER: + * + * The relation type URI for the phone number of a work pager. + * + * Since: 0.7.0 + */ +#define GDATA_GD_PHONE_NUMBER_WORK_PAGER "http://schemas.google.com/g/2005#work_pager" + +#define GDATA_TYPE_GD_PHONE_NUMBER (gdata_gd_phone_number_get_type ()) +#define GDATA_GD_PHONE_NUMBER(o) (G_TYPE_CHECK_INSTANCE_CAST ((o), GDATA_TYPE_GD_PHONE_NUMBER, GDataGDPhoneNumber)) +#define GDATA_GD_PHONE_NUMBER_CLASS(k) (G_TYPE_CHECK_CLASS_CAST((k), GDATA_TYPE_GD_PHONE_NUMBER, GDataGDPhoneNumberClass)) +#define GDATA_IS_GD_PHONE_NUMBER(o) (G_TYPE_CHECK_INSTANCE_TYPE ((o), GDATA_TYPE_GD_PHONE_NUMBER)) +#define GDATA_IS_GD_PHONE_NUMBER_CLASS(k) (G_TYPE_CHECK_CLASS_TYPE ((k), GDATA_TYPE_GD_PHONE_NUMBER)) +#define GDATA_GD_PHONE_NUMBER_GET_CLASS(o) (G_TYPE_INSTANCE_GET_CLASS ((o), GDATA_TYPE_GD_PHONE_NUMBER, GDataGDPhoneNumberClass)) + +typedef struct _GDataGDPhoneNumberPrivate GDataGDPhoneNumberPrivate; + +/** + * GDataGDPhoneNumber: + * + * All the fields in the #GDataGDPhoneNumber structure are private and should never be accessed directly. + * + * Since: 0.2.0 + */ +typedef struct { + GDataParsable parent; + GDataGDPhoneNumberPrivate *priv; +} GDataGDPhoneNumber; + +/** + * GDataGDPhoneNumberClass: + * + * All the fields in the #GDataGDPhoneNumberClass structure are private and should never be accessed directly. + * + * Since: 0.4.0 + */ +typedef struct { + /*< private >*/ + GDataParsableClass parent; + + /*< private >*/ + /* Padding for future expansion */ + void (*_g_reserved0) (void); + void (*_g_reserved1) (void); +} GDataGDPhoneNumberClass; + +GType gdata_gd_phone_number_get_type (void) G_GNUC_CONST; + +GDataGDPhoneNumber *gdata_gd_phone_number_new (const gchar *number, const gchar *relation_type, const gchar *label, const gchar *uri, + gboolean is_primary) G_GNUC_WARN_UNUSED_RESULT G_GNUC_MALLOC; + +const gchar *gdata_gd_phone_number_get_number (GDataGDPhoneNumber *self) G_GNUC_PURE; +void gdata_gd_phone_number_set_number (GDataGDPhoneNumber *self, const gchar *number); + +const gchar *gdata_gd_phone_number_get_uri (GDataGDPhoneNumber *self) G_GNUC_PURE; +void gdata_gd_phone_number_set_uri (GDataGDPhoneNumber *self, const gchar *uri); + +const gchar *gdata_gd_phone_number_get_relation_type (GDataGDPhoneNumber *self) G_GNUC_PURE; +void gdata_gd_phone_number_set_relation_type (GDataGDPhoneNumber *self, const gchar *relation_type); + +const gchar *gdata_gd_phone_number_get_label (GDataGDPhoneNumber *self) G_GNUC_PURE; +void gdata_gd_phone_number_set_label (GDataGDPhoneNumber *self, const gchar *label); + +gboolean gdata_gd_phone_number_is_primary (GDataGDPhoneNumber *self) G_GNUC_PURE; +void gdata_gd_phone_number_set_is_primary (GDataGDPhoneNumber *self, gboolean is_primary); + +G_END_DECLS + +#endif /* !GDATA_GD_PHONE_NUMBER_H */ diff --git a/gdata/gd/gdata-gd-postal-address.c b/gdata/gd/gdata-gd-postal-address.c new file mode 100644 index 0000000..a037b48 --- /dev/null +++ b/gdata/gd/gdata-gd-postal-address.c @@ -0,0 +1,1342 @@ +/* -*- Mode: C; indent-tabs-mode: t; c-basic-offset: 8; tab-width: 8 -*- */ +/* + * GData Client + * Copyright (C) Philip Withnall 2009–2010 + * + * GData Client is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * GData Client is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with GData Client. If not, see . + */ + +/** + * SECTION:gdata-gd-postal-address + * @short_description: GData postal address element + * @stability: Stable + * @include: gdata/gd/gdata-gd-postal-address.h + * + * #GDataGDPostalAddress represents a "structuredPostalAddress" element from the + * GData specification. + * Note that it does not represent a simple "postalAddress" element, as "structuredPostalAddress" is now used wherever possible in the GData API. + * + * Since: 0.4.0 + */ + +#include +#include +#include + +#include "gdata-gd-postal-address.h" +#include "gdata-parsable.h" +#include "gdata-parser.h" +#include "gdata-comparable.h" + +static void gdata_gd_postal_address_comparable_init (GDataComparableIface *iface); +static void gdata_gd_postal_address_finalize (GObject *object); +static void gdata_gd_postal_address_get_property (GObject *object, guint property_id, GValue *value, GParamSpec *pspec); +static void gdata_gd_postal_address_set_property (GObject *object, guint property_id, const GValue *value, GParamSpec *pspec); +static gboolean pre_parse_xml (GDataParsable *parsable, xmlDoc *doc, xmlNode *root_node, gpointer user_data, GError **error); +static gboolean parse_xml (GDataParsable *parsable, xmlDoc *doc, xmlNode *node, gpointer user_data, GError **error); +static void pre_get_xml (GDataParsable *parsable, GString *xml_string); +static void get_xml (GDataParsable *parsable, GString *xml_string); +static void get_namespaces (GDataParsable *parsable, GHashTable *namespaces); + +struct _GDataGDPostalAddressPrivate { + gchar *formatted_address; + gchar *relation_type; + gchar *label; + gboolean is_primary; + gchar *mail_class; + gchar *usage; + gchar *agent; + gchar *house_name; + gchar *street; + gchar *po_box; + gchar *neighborhood; + gchar *city; + gchar *subregion; + gchar *region; + gchar *postcode; + gchar *country; + gchar *country_code; +}; + +enum { + PROP_FORMATTED_ADDRESS = 1, + PROP_RELATION_TYPE, + PROP_LABEL, + PROP_IS_PRIMARY, + PROP_MAIL_CLASS, + PROP_USAGE, + PROP_AGENT, + PROP_HOUSE_NAME, + PROP_STREET, + PROP_PO_BOX, + PROP_NEIGHBORHOOD, + PROP_CITY, + PROP_SUBREGION, + PROP_REGION, + PROP_POSTCODE, + PROP_COUNTRY, + PROP_COUNTRY_CODE +}; + +G_DEFINE_TYPE_WITH_CODE (GDataGDPostalAddress, gdata_gd_postal_address, GDATA_TYPE_PARSABLE, + G_IMPLEMENT_INTERFACE (GDATA_TYPE_COMPARABLE, gdata_gd_postal_address_comparable_init)) + +static void +gdata_gd_postal_address_class_init (GDataGDPostalAddressClass *klass) +{ + GObjectClass *gobject_class = G_OBJECT_CLASS (klass); + GDataParsableClass *parsable_class = GDATA_PARSABLE_CLASS (klass); + + g_type_class_add_private (klass, sizeof (GDataGDPostalAddressPrivate)); + + gobject_class->get_property = gdata_gd_postal_address_get_property; + gobject_class->set_property = gdata_gd_postal_address_set_property; + gobject_class->finalize = gdata_gd_postal_address_finalize; + + parsable_class->pre_parse_xml = pre_parse_xml; + parsable_class->parse_xml = parse_xml; + parsable_class->pre_get_xml = pre_get_xml; + parsable_class->get_xml = get_xml; + parsable_class->get_namespaces = get_namespaces; + parsable_class->element_name = "structuredPostalAddress"; + parsable_class->element_namespace = "gd"; + + /** + * GDataGDPostalAddress:address: + * + * The postal address itself, formatted and unstructured. It is preferred to use the other, structured properties rather than this one. + * + * For more information, see the + * GData specification. + * + * Since: 0.4.0 + */ + g_object_class_install_property (gobject_class, PROP_FORMATTED_ADDRESS, + g_param_spec_string ("address", + "Address", "The postal address itself.", + NULL, + G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)); + + /** + * GDataGDPostalAddress:relation-type: + * + * A programmatic value that identifies the type of postal address. For example: %GDATA_GD_POSTAL_ADDRESS_WORK or + * %GDATA_GD_POSTAL_ADDRESS_OTHER. + * + * For more information, see the + * GData specification. + * + * Since: 0.4.0 + */ + g_object_class_install_property (gobject_class, PROP_RELATION_TYPE, + g_param_spec_string ("relation-type", + "Relation type", "A programmatic value that identifies the type of postal address.", + GDATA_GD_POSTAL_ADDRESS_WORK, + G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)); + + /** + * GDataGDPostalAddress:label: + * + * A simple string value used to name this postal address. It allows UIs to display a label such as "Work", "Personal", "Preferred", etc. + * + * For more information, see the + * GData specification. + * + * Since: 0.4.0 + */ + g_object_class_install_property (gobject_class, PROP_LABEL, + g_param_spec_string ("label", + "Label", "A simple string value used to name this postal address.", + NULL, + G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)); + + /** + * GDataGDPostalAddress:is-primary: + * + * Indicates which postal address out of a group is primary. + * + * For more information, see the + * GData specification. + * + * Since: 0.4.0 + */ + g_object_class_install_property (gobject_class, PROP_IS_PRIMARY, + g_param_spec_boolean ("is-primary", + "Primary?", "Indicates which postal address out of a group is primary.", + FALSE, + G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)); + + /** + * GDataGDPostalAddress:mail-class: + * + * Classes of mail accepted at this address. For example: %GDATA_GD_MAIL_CLASS_LETTERS or %GDATA_GD_MAIL_CLASS_BOTH. + * + * For more information, see the + * GData specification. + * + * Since: 0.5.0 + */ + g_object_class_install_property (gobject_class, PROP_MAIL_CLASS, + g_param_spec_string ("mail-class", + "Mail class", "Classes of mail accepted at this address.", + GDATA_GD_MAIL_CLASS_BOTH, + G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)); + + /** + * GDataGDPostalAddress:usage: + * + * The context in which this address can be used. For example: %GDATA_GD_ADDRESS_USAGE_GENERAL or %GDATA_GD_ADDRESS_USAGE_LOCAL. + * + * For more information, see the + * GData specification. + * + * Since: 0.5.0 + */ + g_object_class_install_property (gobject_class, PROP_USAGE, + g_param_spec_string ("usage", + "Usage", "The context in which this address can be used.", + GDATA_GD_ADDRESS_USAGE_GENERAL, + G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)); + + /** + * GDataGDPostalAddress:agent: + * + * The agent who actually receives the mail. Used in work addresses. Also for "in care of" or "c/o". + * + * For more information, see the + * GData specification. + * + * Since: 0.5.0 + */ + g_object_class_install_property (gobject_class, PROP_AGENT, + g_param_spec_string ("agent", + "Agent", "The agent who actually receives the mail.", + NULL, + G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)); + + /** + * GDataGDPostalAddress:house-name: + * + * Used in places where houses or buildings have names (and not necessarily numbers). + * + * For more information, see the + * GData specification. + * + * Since: 0.5.0 + */ + g_object_class_install_property (gobject_class, PROP_HOUSE_NAME, + g_param_spec_string ("house-name", + "House name", "Used in places where houses or buildings have names (and not numbers).", + NULL, + G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)); + + /** + * GDataGDPostalAddress:street: + * + * Can be street, avenue, road, etc. This element also includes the house number and room/apartment/flat/floor number. + * + * For more information, see the + * GData specification. + * + * Since: 0.5.0 + */ + g_object_class_install_property (gobject_class, PROP_STREET, + g_param_spec_string ("street", + "Street", "Can be street, avenue, road, etc.", + NULL, + G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)); + + /** + * GDataGDPostalAddress:po-box: + * + * Covers actual P.O. boxes, drawers, locked bags, etc. This is usually but not always mutually exclusive with #GDataGDPostalAddress:street. + * + * For more information, see the + * GData specification. + * + * Since: 0.5.0 + */ + g_object_class_install_property (gobject_class, PROP_PO_BOX, + g_param_spec_string ("po-box", + "PO box", "Covers actual P.O. boxes, drawers, locked bags, etc.", + NULL, + G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)); + + /** + * GDataGDPostalAddress:neighborhood: + * + * This is used to disambiguate a street address when a city contains more than one street with the same name, or to specify a small place + * whose mail is routed through a larger postal town. In China it could be a county or a minor city. + * + * For more information, see the + * GData specification. + * + * Since: 0.5.0 + */ + g_object_class_install_property (gobject_class, PROP_NEIGHBORHOOD, + g_param_spec_string ("neighborhood", + "Neighborhood", "This is used to disambiguate a street address.", + NULL, + G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)); + + /** + * GDataGDPostalAddress:city: + * + * Can be city, village, town, borough, etc. This is the postal town and not necessarily the place of residence or place of business. + * + * For more information, see the + * GData specification. + * + * Since: 0.5.0 + */ + g_object_class_install_property (gobject_class, PROP_CITY, + g_param_spec_string ("city", + "City", "Can be city, village, town, borough, etc.", + NULL, + G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)); + + /** + * GDataGDPostalAddress:subregion: + * + * Handles administrative districts such as U.S. or U.K. counties that are not used for mail addressing purposes. + * Subregion is not intended for delivery addresses. + * + * For more information, see the + * GData specification. + * + * Since: 0.5.0 + */ + g_object_class_install_property (gobject_class, PROP_SUBREGION, + g_param_spec_string ("subregion", + "Subregion", "Handles administrative districts such as U.S. or U.K. counties.", + NULL, + G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)); + + /** + * GDataGDPostalAddress:region: + * + * A state, province, county (in Ireland), Land (in Germany), departement (in France), etc. + * + * For more information, see the + * GData specification. + * + * Since: 0.5.0 + */ + g_object_class_install_property (gobject_class, PROP_REGION, + g_param_spec_string ("region", + "Region", "A state, province, county, Land, departement, etc.", + NULL, + G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)); + + /** + * GDataGDPostalAddress:postcode: + * + * Postal code. Usually country-wide, but sometimes specific to the city (e.g. "2" in "Dublin 2, Ireland" addresses). + * + * For more information, see the + * GData specification. + * + * Since: 0.5.0 + */ + g_object_class_install_property (gobject_class, PROP_POSTCODE, + g_param_spec_string ("postcode", + "Postcode", "Postal code.", + NULL, + G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)); + + /** + * GDataGDPostalAddress:country: + * + * The name of the country. Since this is paired with #GDataGDPostalAddress:country-code, they must both be set with + * gdata_gd_postal_address_set_country(). + * + * For more information, see the + * GData specification. + * + * Since: 0.5.0 + */ + g_object_class_install_property (gobject_class, PROP_COUNTRY, + g_param_spec_string ("country", + "Country", "The name of the country.", + NULL, + G_PARAM_READABLE | G_PARAM_STATIC_STRINGS)); + + /** + * GDataGDPostalAddress:country-code: + * + * The ISO 3166-1 alpha-2 country code for the country in #GDataGDPostalAddress:country. Since this is paired with + * #GDataGDPostalAddress:country, they must both be set with gdata_gd_postal_address_set_country(). + * + * For more information, see the + * GData specification + * or ISO 3166-1 alpha-2. + * + * Since: 0.5.0 + */ + g_object_class_install_property (gobject_class, PROP_COUNTRY_CODE, + g_param_spec_string ("country-code", + "Country code", "The ISO 3166-1 alpha-2 country code for the country.", + NULL, + G_PARAM_READABLE | G_PARAM_STATIC_STRINGS)); +} + +static gint +compare_with (GDataComparable *self, GDataComparable *other) +{ + GDataGDPostalAddressPrivate *a = ((GDataGDPostalAddress*) self)->priv, *b = ((GDataGDPostalAddress*) other)->priv; + + if (g_strcmp0 (a->street, b->street) == 0 && g_strcmp0 (a->po_box, b->po_box) == 0 && + g_strcmp0 (a->city, b->city) == 0 && g_strcmp0 (a->postcode, b->postcode) == 0) + return 0; + return 1; +} + +static void +gdata_gd_postal_address_comparable_init (GDataComparableIface *iface) +{ + iface->compare_with = compare_with; +} + +static void +gdata_gd_postal_address_init (GDataGDPostalAddress *self) +{ + self->priv = G_TYPE_INSTANCE_GET_PRIVATE (self, GDATA_TYPE_GD_POSTAL_ADDRESS, GDataGDPostalAddressPrivate); +} + +static void +gdata_gd_postal_address_finalize (GObject *object) +{ + GDataGDPostalAddressPrivate *priv = GDATA_GD_POSTAL_ADDRESS (object)->priv; + + g_free (priv->formatted_address); + g_free (priv->relation_type); + g_free (priv->label); + g_free (priv->mail_class); + g_free (priv->usage); + g_free (priv->agent); + g_free (priv->house_name); + g_free (priv->street); + g_free (priv->po_box); + g_free (priv->neighborhood); + g_free (priv->city); + g_free (priv->subregion); + g_free (priv->region); + g_free (priv->postcode); + g_free (priv->country); + g_free (priv->country_code); + + /* Chain up to the parent class */ + G_OBJECT_CLASS (gdata_gd_postal_address_parent_class)->finalize (object); +} + +static void +gdata_gd_postal_address_get_property (GObject *object, guint property_id, GValue *value, GParamSpec *pspec) +{ + GDataGDPostalAddressPrivate *priv = GDATA_GD_POSTAL_ADDRESS (object)->priv; + + switch (property_id) { + case PROP_FORMATTED_ADDRESS: + g_value_set_string (value, priv->formatted_address); + break; + case PROP_RELATION_TYPE: + g_value_set_string (value, priv->relation_type); + break; + case PROP_LABEL: + g_value_set_string (value, priv->label); + break; + case PROP_IS_PRIMARY: + g_value_set_boolean (value, priv->is_primary); + break; + case PROP_MAIL_CLASS: + g_value_set_string (value, priv->mail_class); + break; + case PROP_USAGE: + g_value_set_string (value, priv->usage); + break; + case PROP_AGENT: + g_value_set_string (value, priv->agent); + break; + case PROP_HOUSE_NAME: + g_value_set_string (value, priv->house_name); + break; + case PROP_STREET: + g_value_set_string (value, priv->street); + break; + case PROP_PO_BOX: + g_value_set_string (value, priv->po_box); + break; + case PROP_NEIGHBORHOOD: + g_value_set_string (value, priv->neighborhood); + break; + case PROP_CITY: + g_value_set_string (value, priv->city); + break; + case PROP_SUBREGION: + g_value_set_string (value, priv->subregion); + break; + case PROP_REGION: + g_value_set_string (value, priv->region); + break; + case PROP_POSTCODE: + g_value_set_string (value, priv->postcode); + break; + case PROP_COUNTRY: + g_value_set_string (value, priv->country); + break; + case PROP_COUNTRY_CODE: + g_value_set_string (value, priv->country_code); + break; + default: + /* We don't have any other property... */ + G_OBJECT_WARN_INVALID_PROPERTY_ID (object, property_id, pspec); + break; + } +} + +static void +gdata_gd_postal_address_set_property (GObject *object, guint property_id, const GValue *value, GParamSpec *pspec) +{ + GDataGDPostalAddress *self = GDATA_GD_POSTAL_ADDRESS (object); + + switch (property_id) { + case PROP_FORMATTED_ADDRESS: + gdata_gd_postal_address_set_address (self, g_value_get_string (value)); + break; + case PROP_RELATION_TYPE: + gdata_gd_postal_address_set_relation_type (self, g_value_get_string (value)); + break; + case PROP_LABEL: + gdata_gd_postal_address_set_label (self, g_value_get_string (value)); + break; + case PROP_IS_PRIMARY: + gdata_gd_postal_address_set_is_primary (self, g_value_get_boolean (value)); + break; + case PROP_MAIL_CLASS: + gdata_gd_postal_address_set_mail_class (self, g_value_get_string (value)); + break; + case PROP_USAGE: + gdata_gd_postal_address_set_usage (self, g_value_get_string (value)); + break; + case PROP_AGENT: + gdata_gd_postal_address_set_agent (self, g_value_get_string (value)); + break; + case PROP_HOUSE_NAME: + gdata_gd_postal_address_set_house_name (self, g_value_get_string (value)); + break; + case PROP_STREET: + gdata_gd_postal_address_set_street (self, g_value_get_string (value)); + break; + case PROP_PO_BOX: + gdata_gd_postal_address_set_po_box (self, g_value_get_string (value)); + break; + case PROP_NEIGHBORHOOD: + gdata_gd_postal_address_set_neighborhood (self, g_value_get_string (value)); + break; + case PROP_CITY: + gdata_gd_postal_address_set_city (self, g_value_get_string (value)); + break; + case PROP_SUBREGION: + gdata_gd_postal_address_set_subregion (self, g_value_get_string (value)); + break; + case PROP_REGION: + gdata_gd_postal_address_set_region (self, g_value_get_string (value)); + break; + case PROP_POSTCODE: + gdata_gd_postal_address_set_postcode (self, g_value_get_string (value)); + break; + default: + /* We don't have any other property... */ + G_OBJECT_WARN_INVALID_PROPERTY_ID (object, property_id, pspec); + break; + } +} + +static gboolean +pre_parse_xml (GDataParsable *parsable, xmlDoc *doc, xmlNode *root_node, gpointer user_data, GError **error) +{ + xmlChar *rel; + gboolean primary_bool; + GDataGDPostalAddressPrivate *priv = GDATA_GD_POSTAL_ADDRESS (parsable)->priv; + + /* Is it the primary postal address? */ + if (gdata_parser_boolean_from_property (root_node, "primary", &primary_bool, 0, error) == FALSE) + return FALSE; + + rel = xmlGetProp (root_node, (xmlChar*) "rel"); + if (rel != NULL && *rel == '\0') { + xmlFree (rel); + return gdata_parser_error_required_property_missing (root_node, "rel", error); + } + + priv->relation_type = (gchar*) rel; + priv->label = (gchar*) xmlGetProp (root_node, (xmlChar*) "label"); + priv->mail_class = (gchar*) xmlGetProp (root_node, (xmlChar*) "mailClass"); + priv->usage = (gchar*) xmlGetProp (root_node, (xmlChar*) "usage"); + priv->is_primary = primary_bool; + + return TRUE; +} + +static gboolean +parse_xml (GDataParsable *parsable, xmlDoc *doc, xmlNode *node, gpointer user_data, GError **error) +{ + gboolean success; + GDataGDPostalAddressPrivate *priv = GDATA_GD_POSTAL_ADDRESS (parsable)->priv; + + if (gdata_parser_is_namespace (node, "http://schemas.google.com/g/2005") == TRUE) { + if (gdata_parser_string_from_element (node, "agent", P_NO_DUPES, &(priv->agent), &success, error) == TRUE || + gdata_parser_string_from_element (node, "housename", P_NO_DUPES, &(priv->house_name), &success, error) == TRUE || + gdata_parser_string_from_element (node, "pobox", P_NO_DUPES, &(priv->po_box), &success, error) == TRUE || + gdata_parser_string_from_element (node, "street", P_NO_DUPES, &(priv->street), &success, error) == TRUE || + gdata_parser_string_from_element (node, "neighborhood", P_NO_DUPES, &(priv->neighborhood), &success, error) == TRUE || + gdata_parser_string_from_element (node, "city", P_NO_DUPES, &(priv->city), &success, error) == TRUE || + gdata_parser_string_from_element (node, "subregion", P_NO_DUPES, &(priv->subregion), &success, error) == TRUE || + gdata_parser_string_from_element (node, "region", P_NO_DUPES, &(priv->region), &success, error) == TRUE || + gdata_parser_string_from_element (node, "postcode", P_NO_DUPES, &(priv->postcode), &success, error) == TRUE || + gdata_parser_string_from_element (node, "formattedAddress", P_NO_DUPES, &(priv->formatted_address), &success, error) == TRUE) { + return success; + } else if (xmlStrcmp (node->name, (xmlChar*) "country") == 0) { + /* gd:country */ + priv->country_code = (gchar*) xmlGetProp (node, (xmlChar*) "code"); + priv->country = (gchar*) xmlNodeListGetString (doc, node->children, TRUE); + + return TRUE; + } + } + + return GDATA_PARSABLE_CLASS (gdata_gd_postal_address_parent_class)->parse_xml (parsable, doc, node, user_data, error); +} + +static void +pre_get_xml (GDataParsable *parsable, GString *xml_string) +{ + GDataGDPostalAddressPrivate *priv = GDATA_GD_POSTAL_ADDRESS (parsable)->priv; + + if (priv->relation_type != NULL) + gdata_parser_string_append_escaped (xml_string, " rel='", priv->relation_type, "'"); + if (priv->label != NULL) + gdata_parser_string_append_escaped (xml_string, " label='", priv->label, "'"); + if (priv->mail_class != NULL) + gdata_parser_string_append_escaped (xml_string, " mailClass='", priv->mail_class, "'"); + if (priv->usage != NULL) + gdata_parser_string_append_escaped (xml_string, " usage='", priv->usage, "'"); + + if (priv->is_primary == TRUE) + g_string_append (xml_string, " primary='true'"); + else + g_string_append (xml_string, " primary='false'"); +} + +static void +get_xml (GDataParsable *parsable, GString *xml_string) +{ + GDataGDPostalAddressPrivate *priv = GDATA_GD_POSTAL_ADDRESS (parsable)->priv; + +#define OUTPUT_STRING_ELEMENT(E,F) \ + if (priv->F != NULL) \ + gdata_parser_string_append_escaped (xml_string, "", priv->F, ""); + + OUTPUT_STRING_ELEMENT ("agent", agent) + OUTPUT_STRING_ELEMENT ("housename", house_name) + OUTPUT_STRING_ELEMENT ("street", street) + OUTPUT_STRING_ELEMENT ("pobox", po_box) + OUTPUT_STRING_ELEMENT ("neighborhood", neighborhood) + OUTPUT_STRING_ELEMENT ("city", city) + OUTPUT_STRING_ELEMENT ("subregion", subregion) + OUTPUT_STRING_ELEMENT ("region", region) + OUTPUT_STRING_ELEMENT ("postcode", postcode) + + if (priv->country != NULL) { + if (priv->country_code != NULL) + gdata_parser_string_append_escaped (xml_string, ""); + else + g_string_append (xml_string, ""); + gdata_parser_string_append_escaped (xml_string, NULL, priv->country, ""); + } + + OUTPUT_STRING_ELEMENT ("formattedAddress", formatted_address) + +#undef OUTPUT_STRING_ELEMENT +} + +static void +get_namespaces (GDataParsable *parsable, GHashTable *namespaces) +{ + g_hash_table_insert (namespaces, (gchar*) "gd", (gchar*) "http://schemas.google.com/g/2005"); +} + +/** + * gdata_gd_postal_address_new: + * @relation_type: (allow-none): the relationship between the address and its owner, or %NULL + * @label: (allow-none): a human-readable label for the address, or %NULL + * @is_primary: %TRUE if this phone number is its owner's primary number, %FALSE otherwise + * + * Creates a new #GDataGDPostalAddress. More information is available in the GData specification. + * + * Return value: a new #GDataGDPostalAddress, or %NULL; unref with g_object_unref() + * + * Since: 0.2.0 + */ +GDataGDPostalAddress * +gdata_gd_postal_address_new (const gchar *relation_type, const gchar *label, gboolean is_primary) +{ + g_return_val_if_fail (relation_type == NULL || *relation_type != '\0', NULL); + return g_object_new (GDATA_TYPE_GD_POSTAL_ADDRESS, "relation-type", relation_type, "label", label, "is-primary", is_primary, NULL); +} + +/** + * gdata_gd_postal_address_get_address: + * @self: a #GDataGDPostalAddress + * + * Gets the #GDataGDPostalAddress:address property. + * + * Return value: the postal address itself, or %NULL + * + * Since: 0.4.0 + */ +const gchar * +gdata_gd_postal_address_get_address (GDataGDPostalAddress *self) +{ + g_return_val_if_fail (GDATA_IS_GD_POSTAL_ADDRESS (self), NULL); + return self->priv->formatted_address; +} + +/** + * gdata_gd_postal_address_set_address: + * @self: a #GDataGDPostalAddress + * @address: (allow-none): the new postal address, or %NULL + * + * Sets the #GDataGDPostalAddress:address property to @address. + * + * Since: 0.4.0 + */ +void +gdata_gd_postal_address_set_address (GDataGDPostalAddress *self, const gchar *address) +{ + g_return_if_fail (GDATA_IS_GD_POSTAL_ADDRESS (self)); + + /* Trim leading and trailing whitespace from the address. + * See here: http://code.google.com/apis/gdata/docs/1.0/elements.html#gdPostalAddress */ + g_free (self->priv->formatted_address); + self->priv->formatted_address = gdata_parser_utf8_trim_whitespace (address); + g_object_notify (G_OBJECT (self), "address"); +} + +/** + * gdata_gd_postal_address_get_relation_type: + * @self: a #GDataGDPostalAddress + * + * Gets the #GDataGDPostalAddress:relation-type property. + * + * Return value: the postal address' relation type, or %NULL + * + * Since: 0.4.0 + */ +const gchar * +gdata_gd_postal_address_get_relation_type (GDataGDPostalAddress *self) +{ + g_return_val_if_fail (GDATA_IS_GD_POSTAL_ADDRESS (self), NULL); + return self->priv->relation_type; +} + +/** + * gdata_gd_postal_address_set_relation_type: + * @self: a #GDataGDPostalAddress + * @relation_type: (allow-none): the new relation type for the postal_address, or %NULL + * + * Sets the #GDataGDPostalAddress:relation-type property to @relation_type. + * + * Set @relation_type to %NULL to unset the property in the postal address. + * + * Since: 0.4.0 + */ +void +gdata_gd_postal_address_set_relation_type (GDataGDPostalAddress *self, const gchar *relation_type) +{ + g_return_if_fail (GDATA_IS_GD_POSTAL_ADDRESS (self)); + g_return_if_fail (relation_type == NULL || *relation_type != '\0'); + + g_free (self->priv->relation_type); + self->priv->relation_type = g_strdup (relation_type); + g_object_notify (G_OBJECT (self), "relation-type"); +} + +/** + * gdata_gd_postal_address_get_label: + * @self: a #GDataGDPostalAddress + * + * Gets the #GDataGDPostalAddress:label property. + * + * Return value: the postal address' label, or %NULL + * + * Since: 0.4.0 + */ +const gchar * +gdata_gd_postal_address_get_label (GDataGDPostalAddress *self) +{ + g_return_val_if_fail (GDATA_IS_GD_POSTAL_ADDRESS (self), NULL); + return self->priv->label; +} + +/** + * gdata_gd_postal_address_set_label: + * @self: a #GDataGDPostalAddress + * @label: (allow-none): the new label for the postal address, or %NULL + * + * Sets the #GDataGDPostalAddress:label property to @label. + * + * Set @label to %NULL to unset the property in the postal address. + * + * Since: 0.4.0 + */ +void +gdata_gd_postal_address_set_label (GDataGDPostalAddress *self, const gchar *label) +{ + g_return_if_fail (GDATA_IS_GD_POSTAL_ADDRESS (self)); + + g_free (self->priv->label); + self->priv->label = g_strdup (label); + g_object_notify (G_OBJECT (self), "label"); +} + +/** + * gdata_gd_postal_address_is_primary: + * @self: a #GDataGDPostalAddress + * + * Gets the #GDataGDPostalAddress:is-primary property. + * + * Return value: %TRUE if this is the primary postal address, %FALSE otherwise + * + * Since: 0.4.0 + */ +gboolean +gdata_gd_postal_address_is_primary (GDataGDPostalAddress *self) +{ + g_return_val_if_fail (GDATA_IS_GD_POSTAL_ADDRESS (self), FALSE); + return self->priv->is_primary; +} + +/** + * gdata_gd_postal_address_set_is_primary: + * @self: a #GDataGDPostalAddress + * @is_primary: %TRUE if this is the primary postal address, %FALSE otherwise + * + * Sets the #GDataGDPostalAddress:is-primary property to @is_primary. + * + * Since: 0.4.0 + */ +void +gdata_gd_postal_address_set_is_primary (GDataGDPostalAddress *self, gboolean is_primary) +{ + g_return_if_fail (GDATA_IS_GD_POSTAL_ADDRESS (self)); + + self->priv->is_primary = is_primary; + g_object_notify (G_OBJECT (self), "is-primary"); +} + +/** + * gdata_gd_postal_address_get_mail_class: + * @self: a #GDataGDPostalAddress + * + * Gets the #GDataGDPostalAddress:mail-class property. + * + * Return value: the postal address' mail class, or %NULL + * + * Since: 0.5.0 + */ +const gchar * +gdata_gd_postal_address_get_mail_class (GDataGDPostalAddress *self) +{ + g_return_val_if_fail (GDATA_IS_GD_POSTAL_ADDRESS (self), NULL); + return self->priv->mail_class; +} + +/** + * gdata_gd_postal_address_set_mail_class: + * @self: a #GDataGDPostalAddress + * @mail_class: (allow-none): the new mail class for the postal address, or %NULL + * + * Sets the #GDataGDPostalAddress:mail-class property to @mail_class. + * + * Set @mail_class to %NULL to unset the property in the postal address. + * + * Since: 0.5.0 + */ +void +gdata_gd_postal_address_set_mail_class (GDataGDPostalAddress *self, const gchar *mail_class) +{ + g_return_if_fail (GDATA_IS_GD_POSTAL_ADDRESS (self)); + g_return_if_fail (mail_class == NULL || *mail_class != '\0'); + + g_free (self->priv->mail_class); + self->priv->mail_class = g_strdup (mail_class); + g_object_notify (G_OBJECT (self), "mail-class"); +} + +/** + * gdata_gd_postal_address_get_usage: + * @self: a #GDataGDPostalAddress + * + * Gets the #GDataGDPostalAddress:usage property. + * + * Return value: the postal address' usage, or %NULL + * + * Since: 0.5.0 + */ +const gchar * +gdata_gd_postal_address_get_usage (GDataGDPostalAddress *self) +{ + g_return_val_if_fail (GDATA_IS_GD_POSTAL_ADDRESS (self), NULL); + return self->priv->usage; +} + +/** + * gdata_gd_postal_address_set_usage: + * @self: a #GDataGDPostalAddress + * @usage: (allow-none): the new usage for the postal address, or %NULL + * + * Sets the #GDataGDPostalAddress:usage property to @usage. + * + * Set @usage to %NULL to unset the property in the postal address. + * + * Since: 0.5.0 + */ +void +gdata_gd_postal_address_set_usage (GDataGDPostalAddress *self, const gchar *usage) +{ + g_return_if_fail (GDATA_IS_GD_POSTAL_ADDRESS (self)); + g_return_if_fail (usage == NULL || *usage != '\0'); + + g_free (self->priv->usage); + self->priv->usage = g_strdup (usage); + g_object_notify (G_OBJECT (self), "usage"); +} + +/** + * gdata_gd_postal_address_get_agent: + * @self: a #GDataGDPostalAddress + * + * Gets the #GDataGDPostalAddress:agent property. + * + * Return value: the postal address' agent, or %NULL + * + * Since: 0.5.0 + */ +const gchar * +gdata_gd_postal_address_get_agent (GDataGDPostalAddress *self) +{ + g_return_val_if_fail (GDATA_IS_GD_POSTAL_ADDRESS (self), NULL); + return self->priv->agent; +} + +/** + * gdata_gd_postal_address_set_agent: + * @self: a #GDataGDPostalAddress + * @agent: (allow-none): the new agent for the postal address, or %NULL + * + * Sets the #GDataGDPostalAddress:agent property to @agent. + * + * Set @agent to %NULL to unset the property in the postal address. + * + * Since: 0.5.0 + */ +void +gdata_gd_postal_address_set_agent (GDataGDPostalAddress *self, const gchar *agent) +{ + g_return_if_fail (GDATA_IS_GD_POSTAL_ADDRESS (self)); + g_return_if_fail (agent == NULL || *agent != '\0'); + + g_free (self->priv->agent); + self->priv->agent = g_strdup (agent); + g_object_notify (G_OBJECT (self), "agent"); +} + +/** + * gdata_gd_postal_address_get_house_name: + * @self: a #GDataGDPostalAddress + * + * Gets the #GDataGDPostalAddress:house-name property. + * + * Return value: the postal address' house name, or %NULL + * + * Since: 0.5.0 + */ +const gchar * +gdata_gd_postal_address_get_house_name (GDataGDPostalAddress *self) +{ + g_return_val_if_fail (GDATA_IS_GD_POSTAL_ADDRESS (self), NULL); + return self->priv->house_name; +} + +/** + * gdata_gd_postal_address_set_house_name: + * @self: a #GDataGDPostalAddress + * @house_name: (allow-none): the new house name for the postal address, or %NULL + * + * Sets the #GDataGDPostalAddress:house-name property to @house_name. + * + * Set @house_name to %NULL to unset the property in the postal address. + * + * Since: 0.5.0 + */ +void +gdata_gd_postal_address_set_house_name (GDataGDPostalAddress *self, const gchar *house_name) +{ + g_return_if_fail (GDATA_IS_GD_POSTAL_ADDRESS (self)); + g_return_if_fail (house_name == NULL || *house_name != '\0'); + + g_free (self->priv->house_name); + self->priv->house_name = g_strdup (house_name); + g_object_notify (G_OBJECT (self), "house-name"); +} + +/** + * gdata_gd_postal_address_get_street: + * @self: a #GDataGDPostalAddress + * + * Gets the #GDataGDPostalAddress:street property. + * + * Return value: the postal address' street, or %NULL + * + * Since: 0.5.0 + */ +const gchar * +gdata_gd_postal_address_get_street (GDataGDPostalAddress *self) +{ + g_return_val_if_fail (GDATA_IS_GD_POSTAL_ADDRESS (self), NULL); + return self->priv->street; +} + +/** + * gdata_gd_postal_address_set_street: + * @self: a #GDataGDPostalAddress + * @street: (allow-none): the new street for the postal address, or %NULL + * + * Sets the #GDataGDPostalAddress:street property to @street. + * + * Set @street to %NULL to unset the property in the postal address. + * + * Since: 0.5.0 + */ +void +gdata_gd_postal_address_set_street (GDataGDPostalAddress *self, const gchar *street) +{ + g_return_if_fail (GDATA_IS_GD_POSTAL_ADDRESS (self)); + g_return_if_fail (street == NULL || *street != '\0'); + + g_free (self->priv->street); + self->priv->street = g_strdup (street); + g_object_notify (G_OBJECT (self), "street"); +} + +/** + * gdata_gd_postal_address_get_po_box: + * @self: a #GDataGDPostalAddress + * + * Gets the #GDataGDPostalAddress:po-box property. + * + * Return value: the postal address' P.O. box, or %NULL + * + * Since: 0.5.0 + */ +const gchar * +gdata_gd_postal_address_get_po_box (GDataGDPostalAddress *self) +{ + g_return_val_if_fail (GDATA_IS_GD_POSTAL_ADDRESS (self), NULL); + return self->priv->po_box; +} + +/** + * gdata_gd_postal_address_set_po_box: + * @self: a #GDataGDPostalAddress + * @po_box: (allow-none): the new P.O. box for the postal address, or %NULL + * + * Sets the #GDataGDPostalAddress:po-box property to @po_box. + * + * Set @po_box to %NULL to unset the property in the postal address. + * + * Since: 0.5.0 + */ +void +gdata_gd_postal_address_set_po_box (GDataGDPostalAddress *self, const gchar *po_box) +{ + g_return_if_fail (GDATA_IS_GD_POSTAL_ADDRESS (self)); + g_return_if_fail (po_box == NULL || *po_box != '\0'); + + g_free (self->priv->po_box); + self->priv->po_box = g_strdup (po_box); + g_object_notify (G_OBJECT (self), "po-box"); +} + +/** + * gdata_gd_postal_address_get_neighborhood: + * @self: a #GDataGDPostalAddress + * + * Gets the #GDataGDPostalAddress:neighborhood property. + * + * Return value: the postal address' neighborhood, or %NULL + * + * Since: 0.5.0 + */ +const gchar * +gdata_gd_postal_address_get_neighborhood (GDataGDPostalAddress *self) +{ + g_return_val_if_fail (GDATA_IS_GD_POSTAL_ADDRESS (self), NULL); + return self->priv->neighborhood; +} + +/** + * gdata_gd_postal_address_set_neighborhood: + * @self: a #GDataGDPostalAddress + * @neighborhood: (allow-none): the new neighborhood for the postal address, or %NULL + * + * Sets the #GDataGDPostalAddress:neighborhood property to @neighborhood. + * + * Set @neighborhood to %NULL to unset the property in the postal address. + * + * Since: 0.5.0 + */ +void +gdata_gd_postal_address_set_neighborhood (GDataGDPostalAddress *self, const gchar *neighborhood) +{ + g_return_if_fail (GDATA_IS_GD_POSTAL_ADDRESS (self)); + g_return_if_fail (neighborhood == NULL || *neighborhood != '\0'); + + g_free (self->priv->neighborhood); + self->priv->neighborhood = g_strdup (neighborhood); + g_object_notify (G_OBJECT (self), "neighborhood"); +} + +/** + * gdata_gd_postal_address_get_city: + * @self: a #GDataGDPostalAddress + * + * Gets the #GDataGDPostalAddress:city property. + * + * Return value: the postal address' city, or %NULL + * + * Since: 0.5.0 + */ +const gchar * +gdata_gd_postal_address_get_city (GDataGDPostalAddress *self) +{ + g_return_val_if_fail (GDATA_IS_GD_POSTAL_ADDRESS (self), NULL); + return self->priv->city; +} + +/** + * gdata_gd_postal_address_set_city: + * @self: a #GDataGDPostalAddress + * @city: (allow-none): the new city for the postal address, or %NULL + * + * Sets the #GDataGDPostalAddress:city property to @city. + * + * Set @city to %NULL to unset the property in the postal address. + * + * Since: 0.5.0 + */ +void +gdata_gd_postal_address_set_city (GDataGDPostalAddress *self, const gchar *city) +{ + g_return_if_fail (GDATA_IS_GD_POSTAL_ADDRESS (self)); + g_return_if_fail (city == NULL || *city != '\0'); + + g_free (self->priv->city); + self->priv->city = g_strdup (city); + g_object_notify (G_OBJECT (self), "city"); +} + +/** + * gdata_gd_postal_address_get_subregion: + * @self: a #GDataGDPostalAddress + * + * Gets the #GDataGDPostalAddress:subregion property. + * + * Return value: the postal address' subregion, or %NULL + * + * Since: 0.5.0 + */ +const gchar * +gdata_gd_postal_address_get_subregion (GDataGDPostalAddress *self) +{ + g_return_val_if_fail (GDATA_IS_GD_POSTAL_ADDRESS (self), NULL); + return self->priv->subregion; +} + +/** + * gdata_gd_postal_address_set_subregion: + * @self: a #GDataGDPostalAddress + * @subregion: (allow-none): the new subregion for the postal address, or %NULL + * + * Sets the #GDataGDPostalAddress:subregion property to @subregion. + * + * Set @subregion to %NULL to unset the property in the postal address. + * + * Since: 0.5.0 + */ +void +gdata_gd_postal_address_set_subregion (GDataGDPostalAddress *self, const gchar *subregion) +{ + g_return_if_fail (GDATA_IS_GD_POSTAL_ADDRESS (self)); + g_return_if_fail (subregion == NULL || *subregion != '\0'); + + g_free (self->priv->subregion); + self->priv->subregion = g_strdup (subregion); + g_object_notify (G_OBJECT (self), "subregion"); +} + +/** + * gdata_gd_postal_address_get_region: + * @self: a #GDataGDPostalAddress + * + * Gets the #GDataGDPostalAddress:region property. + * + * Return value: the postal address' region, or %NULL + * + * Since: 0.5.0 + */ +const gchar * +gdata_gd_postal_address_get_region (GDataGDPostalAddress *self) +{ + g_return_val_if_fail (GDATA_IS_GD_POSTAL_ADDRESS (self), NULL); + return self->priv->region; +} + +/** + * gdata_gd_postal_address_set_region: + * @self: a #GDataGDPostalAddress + * @region: (allow-none): the new region for the postal address, or %NULL + * + * Sets the #GDataGDPostalAddress:region property to @region. + * + * Set @region to %NULL to unset the property in the postal address. + * + * Since: 0.5.0 + */ +void +gdata_gd_postal_address_set_region (GDataGDPostalAddress *self, const gchar *region) +{ + g_return_if_fail (GDATA_IS_GD_POSTAL_ADDRESS (self)); + g_return_if_fail (region == NULL || *region != '\0'); + + g_free (self->priv->region); + self->priv->region = g_strdup (region); + g_object_notify (G_OBJECT (self), "region"); +} + +/** + * gdata_gd_postal_address_get_postcode: + * @self: a #GDataGDPostalAddress + * + * Gets the #GDataGDPostalAddress:postcode property. + * + * Return value: the postal address' postcode, or %NULL + * + * Since: 0.5.0 + */ +const gchar * +gdata_gd_postal_address_get_postcode (GDataGDPostalAddress *self) +{ + g_return_val_if_fail (GDATA_IS_GD_POSTAL_ADDRESS (self), NULL); + return self->priv->postcode; +} + +/** + * gdata_gd_postal_address_set_postcode: + * @self: a #GDataGDPostalAddress + * @postcode: (allow-none): the new postcode for the postal address, or %NULL + * + * Sets the #GDataGDPostalAddress:postcode property to @postcode. + * + * Set @postcode to %NULL to unset the property in the postal address. + * + * Since: 0.5.0 + */ +void +gdata_gd_postal_address_set_postcode (GDataGDPostalAddress *self, const gchar *postcode) +{ + g_return_if_fail (GDATA_IS_GD_POSTAL_ADDRESS (self)); + g_return_if_fail (postcode == NULL || *postcode != '\0'); + + g_free (self->priv->postcode); + self->priv->postcode = g_strdup (postcode); + g_object_notify (G_OBJECT (self), "postcode"); +} + +/** + * gdata_gd_postal_address_get_country: + * @self: a #GDataGDPostalAddress + * + * Gets the #GDataGDPostalAddress:country property. + * + * Return value: the postal address' country, or %NULL + * + * Since: 0.5.0 + */ +const gchar * +gdata_gd_postal_address_get_country (GDataGDPostalAddress *self) +{ + g_return_val_if_fail (GDATA_IS_GD_POSTAL_ADDRESS (self), NULL); + return self->priv->country; +} + +/** + * gdata_gd_postal_address_get_country_code: + * @self: a #GDataGDPostalAddress + * + * Gets the #GDataGDPostalAddress:country-code property. + * + * Return value: the postal address' ISO 3166-1 alpha-2 country code, or %NULL + * + * Since: 0.5.0 + */ +const gchar * +gdata_gd_postal_address_get_country_code (GDataGDPostalAddress *self) +{ + g_return_val_if_fail (GDATA_IS_GD_POSTAL_ADDRESS (self), NULL); + return self->priv->country_code; +} + +/** + * gdata_gd_postal_address_set_country: + * @self: a #GDataGDPostalAddress + * @country: (allow-none): the new country for the postal address, or %NULL + * @country_code: (allow-none): the new country code for the postal address, or %NULL + * + * Sets the #GDataGDPostalAddress:country property to @country, and #GDataGDPostalAddress:country-code to @country_code. + * + * Set @country or @country_code to %NULL to unset the relevant property in the postal address. If a @country_code is provided, a @country must + * also be provided. + * + * Since: 0.5.0 + */ +void +gdata_gd_postal_address_set_country (GDataGDPostalAddress *self, const gchar *country, const gchar *country_code) +{ + g_return_if_fail (GDATA_IS_GD_POSTAL_ADDRESS (self)); + g_return_if_fail (country != NULL || country_code == NULL); + g_return_if_fail (country == NULL || *country != '\0'); + g_return_if_fail (country_code == NULL || *country_code != '\0'); + + g_free (self->priv->country); + g_free (self->priv->country_code); + self->priv->country = g_strdup (country); + self->priv->country_code = g_strdup (country_code); + + g_object_freeze_notify (G_OBJECT (self)); + g_object_notify (G_OBJECT (self), "country"); + g_object_notify (G_OBJECT (self), "country-code"); + g_object_thaw_notify (G_OBJECT (self)); +} diff --git a/gdata/gd/gdata-gd-postal-address.h b/gdata/gd/gdata-gd-postal-address.h new file mode 100644 index 0000000..c544c41 --- /dev/null +++ b/gdata/gd/gdata-gd-postal-address.h @@ -0,0 +1,205 @@ +/* -*- Mode: C; indent-tabs-mode: t; c-basic-offset: 8; tab-width: 8 -*- */ +/* + * GData Client + * Copyright (C) Philip Withnall 2009–2010 + * + * GData Client is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * GData Client is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with GData Client. If not, see . + */ + +#ifndef GDATA_GD_POSTAL_ADDRESS_H +#define GDATA_GD_POSTAL_ADDRESS_H + +#include +#include + +#include + +G_BEGIN_DECLS + +/** + * GDATA_GD_POSTAL_ADDRESS_WORK: + * + * The relation type URI for the postal address of a workplace. + * + * Since: 0.7.0 + */ +#define GDATA_GD_POSTAL_ADDRESS_WORK "http://schemas.google.com/g/2005#work" + +/** + * GDATA_GD_POSTAL_ADDRESS_HOME: + * + * The relation type URI for the postal address of a home. + * + * Since: 0.7.0 + */ +#define GDATA_GD_POSTAL_ADDRESS_HOME "http://schemas.google.com/g/2005#home" + +/** + * GDATA_GD_POSTAL_ADDRESS_OTHER: + * + * The relation type URI for a miscellaneous postal address. + * + * Since: 0.7.0 + */ +#define GDATA_GD_POSTAL_ADDRESS_OTHER "http://schemas.google.com/g/2005#other" + +/** + * GDATA_GD_MAIL_CLASS_BOTH: + * + * Parcels and letters can be sent to the address. Value for #GDataGDPostalAddress:mail-class. + * + * Since: 0.5.0 + */ +#define GDATA_GD_MAIL_CLASS_BOTH "http://schemas.google.com/g/2005#both" + +/** + * GDATA_GD_MAIL_CLASS_LETTERS: + * + * Only letters can be sent to the address. Value for #GDataGDPostalAddress:mail-class. + * + * Since: 0.5.0 + */ +#define GDATA_GD_MAIL_CLASS_LETTERS "http://schemas.google.com/g/2005#letters" + +/** + * GDATA_GD_MAIL_CLASS_PARCELS: + * + * Only parcels can be sent to the address. Value for #GDataGDPostalAddress:mail-class. + * + * Since: 0.5.0 + */ +#define GDATA_GD_MAIL_CLASS_PARCELS "http://schemas.google.com/g/2005#parcels" + +/** + * GDATA_GD_MAIL_CLASS_NEITHER: + * + * Address is purely locational and cannot be used for mail. Value for #GDataGDPostalAddress:mail-class. + * + * Since: 0.5.0 + */ +#define GDATA_GD_MAIL_CLASS_NEITHER "http://schemas.google.com/g/2005#neither" + +/** + * GDATA_GD_ADDRESS_USAGE_GENERAL: + * + * The address is for general usage. Value for #GDataGDPostalAddress:usage. + * + * Since: 0.5.0 + */ +#define GDATA_GD_ADDRESS_USAGE_GENERAL "http://schemas.google.com/g/2005#general" + +/** + * GDATA_GD_ADDRESS_USAGE_LOCAL: + * + * The address is for local usage. Value for #GDataGDPostalAddress:usage. + * + * Since: 0.5.0 + */ +#define GDATA_GD_ADDRESS_USAGE_LOCAL "http://schemas.google.com/g/2005#local" + +#define GDATA_TYPE_GD_POSTAL_ADDRESS (gdata_gd_postal_address_get_type ()) +#define GDATA_GD_POSTAL_ADDRESS(o) (G_TYPE_CHECK_INSTANCE_CAST ((o), GDATA_TYPE_GD_POSTAL_ADDRESS, GDataGDPostalAddress)) +#define GDATA_GD_POSTAL_ADDRESS_CLASS(k) (G_TYPE_CHECK_CLASS_CAST((k), GDATA_TYPE_GD_POSTAL_ADDRESS, GDataGDPostalAddressClass)) +#define GDATA_IS_GD_POSTAL_ADDRESS(o) (G_TYPE_CHECK_INSTANCE_TYPE ((o), GDATA_TYPE_GD_POSTAL_ADDRESS)) +#define GDATA_IS_GD_POSTAL_ADDRESS_CLASS(k) (G_TYPE_CHECK_CLASS_TYPE ((k), GDATA_TYPE_GD_POSTAL_ADDRESS)) +#define GDATA_GD_POSTAL_ADDRESS_GET_CLASS(o) (G_TYPE_INSTANCE_GET_CLASS ((o), GDATA_TYPE_GD_POSTAL_ADDRESS, GDataGDPostalAddressClass)) + +typedef struct _GDataGDPostalAddressPrivate GDataGDPostalAddressPrivate; + +/** + * GDataGDPostalAddress: + * + * All the fields in the #GDataGDPostalAddress structure are private and should never be accessed directly. + * + * Since: 0.2.0 + */ +typedef struct { + GDataParsable parent; + GDataGDPostalAddressPrivate *priv; +} GDataGDPostalAddress; + +/** + * GDataGDPostalAddressClass: + * + * All the fields in the #GDataGDPostalAddressClass structure are private and should never be accessed directly. + * + * Since: 0.4.0 + */ +typedef struct { + /*< private >*/ + GDataParsableClass parent; + + /*< private >*/ + /* Padding for future expansion */ + void (*_g_reserved0) (void); + void (*_g_reserved1) (void); +} GDataGDPostalAddressClass; + +GType gdata_gd_postal_address_get_type (void) G_GNUC_CONST; + +GDataGDPostalAddress *gdata_gd_postal_address_new (const gchar *relation_type, const gchar *label, + gboolean is_primary) G_GNUC_WARN_UNUSED_RESULT G_GNUC_MALLOC; + +const gchar *gdata_gd_postal_address_get_address (GDataGDPostalAddress *self) G_GNUC_PURE; +void gdata_gd_postal_address_set_address (GDataGDPostalAddress *self, const gchar *address); + +const gchar *gdata_gd_postal_address_get_relation_type (GDataGDPostalAddress *self) G_GNUC_PURE; +void gdata_gd_postal_address_set_relation_type (GDataGDPostalAddress *self, const gchar *relation_type); + +const gchar *gdata_gd_postal_address_get_label (GDataGDPostalAddress *self) G_GNUC_PURE; +void gdata_gd_postal_address_set_label (GDataGDPostalAddress *self, const gchar *label); + +gboolean gdata_gd_postal_address_is_primary (GDataGDPostalAddress *self) G_GNUC_PURE; +void gdata_gd_postal_address_set_is_primary (GDataGDPostalAddress *self, gboolean is_primary); + +const gchar *gdata_gd_postal_address_get_mail_class (GDataGDPostalAddress *self) G_GNUC_PURE; +void gdata_gd_postal_address_set_mail_class (GDataGDPostalAddress *self, const gchar *mail_class); + +const gchar *gdata_gd_postal_address_get_usage (GDataGDPostalAddress *self) G_GNUC_PURE; +void gdata_gd_postal_address_set_usage (GDataGDPostalAddress *self, const gchar *usage); + +const gchar *gdata_gd_postal_address_get_agent (GDataGDPostalAddress *self) G_GNUC_PURE; +void gdata_gd_postal_address_set_agent (GDataGDPostalAddress *self, const gchar *agent); + +const gchar *gdata_gd_postal_address_get_house_name (GDataGDPostalAddress *self) G_GNUC_PURE; +void gdata_gd_postal_address_set_house_name (GDataGDPostalAddress *self, const gchar *house_name); + +const gchar *gdata_gd_postal_address_get_street (GDataGDPostalAddress *self) G_GNUC_PURE; +void gdata_gd_postal_address_set_street (GDataGDPostalAddress *self, const gchar *street); + +const gchar *gdata_gd_postal_address_get_po_box (GDataGDPostalAddress *self) G_GNUC_PURE; +void gdata_gd_postal_address_set_po_box (GDataGDPostalAddress *self, const gchar *po_box); + +const gchar *gdata_gd_postal_address_get_neighborhood (GDataGDPostalAddress *self) G_GNUC_PURE; +void gdata_gd_postal_address_set_neighborhood (GDataGDPostalAddress *self, const gchar *neighborhood); + +const gchar *gdata_gd_postal_address_get_city (GDataGDPostalAddress *self) G_GNUC_PURE; +void gdata_gd_postal_address_set_city (GDataGDPostalAddress *self, const gchar *city); + +const gchar *gdata_gd_postal_address_get_subregion (GDataGDPostalAddress *self) G_GNUC_PURE; +void gdata_gd_postal_address_set_subregion (GDataGDPostalAddress *self, const gchar *subregion); + +const gchar *gdata_gd_postal_address_get_region (GDataGDPostalAddress *self) G_GNUC_PURE; +void gdata_gd_postal_address_set_region (GDataGDPostalAddress *self, const gchar *region); + +const gchar *gdata_gd_postal_address_get_postcode (GDataGDPostalAddress *self) G_GNUC_PURE; +void gdata_gd_postal_address_set_postcode (GDataGDPostalAddress *self, const gchar *postcode); + +const gchar *gdata_gd_postal_address_get_country (GDataGDPostalAddress *self) G_GNUC_PURE; +const gchar *gdata_gd_postal_address_get_country_code (GDataGDPostalAddress *self) G_GNUC_PURE; +void gdata_gd_postal_address_set_country (GDataGDPostalAddress *self, const gchar *country, const gchar *country_code); + +G_END_DECLS + +#endif /* !GDATA_GD_POSTAL_ADDRESS_H */ diff --git a/gdata/gd/gdata-gd-reminder.c b/gdata/gd/gdata-gd-reminder.c new file mode 100644 index 0000000..6c1e25d --- /dev/null +++ b/gdata/gd/gdata-gd-reminder.c @@ -0,0 +1,467 @@ +/* -*- Mode: C; indent-tabs-mode: t; c-basic-offset: 8; tab-width: 8 -*- */ +/* + * GData Client + * Copyright (C) Philip Withnall 2009–2010 + * + * GData Client is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * GData Client is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with GData Client. If not, see . + */ + +/** + * SECTION:gdata-gd-reminder + * @short_description: GData reminder element + * @stability: Stable + * @include: gdata/gd/gdata-gd-reminder.h + * + * #GDataGDReminder represents a "reminder" element from the + * GData specification. + * + * Since: 0.4.0 + */ + +#include +#include + +#include "gdata-gd-reminder.h" +#include "gdata-parsable.h" +#include "gdata-parser.h" +#include "gdata-types.h" +#include "gdata-comparable.h" + +static void gdata_gd_reminder_comparable_init (GDataComparableIface *iface); +static void gdata_gd_reminder_finalize (GObject *object); +static void gdata_gd_reminder_get_property (GObject *object, guint property_id, GValue *value, GParamSpec *pspec); +static void gdata_gd_reminder_set_property (GObject *object, guint property_id, const GValue *value, GParamSpec *pspec); +static gboolean pre_parse_xml (GDataParsable *parsable, xmlDoc *doc, xmlNode *root_node, gpointer user_data, GError **error); +static void pre_get_xml (GDataParsable *parsable, GString *xml_string); +static void get_namespaces (GDataParsable *parsable, GHashTable *namespaces); + +struct _GDataGDReminderPrivate { + gchar *method; + gint64 absolute_time; + gint relative_time; +}; + +enum { + PROP_METHOD = 1, + PROP_ABSOLUTE_TIME, + PROP_IS_ABSOLUTE_TIME, + PROP_RELATIVE_TIME +}; + +G_DEFINE_TYPE_WITH_CODE (GDataGDReminder, gdata_gd_reminder, GDATA_TYPE_PARSABLE, + G_IMPLEMENT_INTERFACE (GDATA_TYPE_COMPARABLE, gdata_gd_reminder_comparable_init)) + +static void +gdata_gd_reminder_class_init (GDataGDReminderClass *klass) +{ + GObjectClass *gobject_class = G_OBJECT_CLASS (klass); + GDataParsableClass *parsable_class = GDATA_PARSABLE_CLASS (klass); + + g_type_class_add_private (klass, sizeof (GDataGDReminderPrivate)); + + gobject_class->get_property = gdata_gd_reminder_get_property; + gobject_class->set_property = gdata_gd_reminder_set_property; + gobject_class->finalize = gdata_gd_reminder_finalize; + + parsable_class->pre_parse_xml = pre_parse_xml; + parsable_class->pre_get_xml = pre_get_xml; + parsable_class->get_namespaces = get_namespaces; + parsable_class->element_name = "reminder"; + parsable_class->element_namespace = "gd"; + + /** + * GDataGDReminder:method: + * + * The notification method the reminder should use. For example: %GDATA_GD_REMINDER_ALERT or %GDATA_GD_REMINDER_EMAIL. + * + * For more information, see the + * GData specification. + * + * Since: 0.4.0 + */ + g_object_class_install_property (gobject_class, PROP_METHOD, + g_param_spec_string ("method", + "Method", "The notification method the reminder should use.", + NULL, + G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)); + + /** + * GDataGDReminder:absolute-time: + * + * Absolute time at which the reminder should be issued. + * + * For more information, see the + * GData specification. + * + * Since: 0.4.0 + */ + g_object_class_install_property (gobject_class, PROP_ABSOLUTE_TIME, + g_param_spec_int64 ("absolute-time", + "Absolute time", "Absolute time at which the reminder should be issued.", + -1, G_MAXINT64, -1, + G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)); + + /** + * GDataGDReminder:is-absolute-time: + * + * Whether the reminder is specified as an absolute or relative time. + * + * For more information, see the + * GData specification. + * + * Since: 0.4.0 + */ + g_object_class_install_property (gobject_class, PROP_IS_ABSOLUTE_TIME, + g_param_spec_boolean ("is-absolute-time", + "Absolute time?", "Whether the reminder is specified as an absolute or relative time.", + FALSE, + G_PARAM_READABLE | G_PARAM_STATIC_STRINGS)); + + /** + * GDataGDReminder:relative-time: + * + * Time at which the reminder should be issued, in minutes relative to the start time of the corresponding event. + * + * For more information, see the + * GData specification. + * + * Since: 0.4.0 + */ + g_object_class_install_property (gobject_class, PROP_RELATIVE_TIME, + g_param_spec_int ("relative-time", + "Relative time", "Time at which the reminder should be issued, in minutes.", + -1, G_MAXINT, -1, + G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)); +} + +static gint +compare_with (GDataComparable *self, GDataComparable *other) +{ + gint method_cmp, time_cmp; + GDataGDReminder *a = (GDataGDReminder*) self, *b = (GDataGDReminder*) other; + + if (gdata_gd_reminder_is_absolute_time (a) != gdata_gd_reminder_is_absolute_time (b)) + return 1; + + method_cmp = g_strcmp0 (a->priv->method, b->priv->method); + if (gdata_gd_reminder_is_absolute_time (a) == TRUE) { + time_cmp = a->priv->absolute_time - b->priv->absolute_time; + } else { + time_cmp = a->priv->relative_time - b->priv->relative_time; + } + + if (method_cmp == 0) + return time_cmp; + else + return method_cmp; +} + +static void +gdata_gd_reminder_comparable_init (GDataComparableIface *iface) +{ + iface->compare_with = compare_with; +} + +static void +gdata_gd_reminder_init (GDataGDReminder *self) +{ + self->priv = G_TYPE_INSTANCE_GET_PRIVATE (self, GDATA_TYPE_GD_REMINDER, GDataGDReminderPrivate); + self->priv->absolute_time = -1; +} + +static void +gdata_gd_reminder_finalize (GObject *object) +{ + GDataGDReminderPrivate *priv = GDATA_GD_REMINDER (object)->priv; + + g_free (priv->method); + + /* Chain up to the parent class */ + G_OBJECT_CLASS (gdata_gd_reminder_parent_class)->finalize (object); +} + +static void +gdata_gd_reminder_get_property (GObject *object, guint property_id, GValue *value, GParamSpec *pspec) +{ + GDataGDReminderPrivate *priv = GDATA_GD_REMINDER (object)->priv; + + switch (property_id) { + case PROP_METHOD: + g_value_set_string (value, priv->method); + break; + case PROP_ABSOLUTE_TIME: + g_value_set_int64 (value, priv->absolute_time); + break; + case PROP_IS_ABSOLUTE_TIME: + g_value_set_boolean (value, gdata_gd_reminder_is_absolute_time (GDATA_GD_REMINDER (object))); + break; + case PROP_RELATIVE_TIME: + g_value_set_int (value, priv->relative_time); + break; + default: + /* We don't have any other property... */ + G_OBJECT_WARN_INVALID_PROPERTY_ID (object, property_id, pspec); + break; + } +} + +static void +gdata_gd_reminder_set_property (GObject *object, guint property_id, const GValue *value, GParamSpec *pspec) +{ + GDataGDReminder *self = GDATA_GD_REMINDER (object); + + switch (property_id) { + case PROP_METHOD: + gdata_gd_reminder_set_method (self, g_value_get_string (value)); + break; + case PROP_ABSOLUTE_TIME: + gdata_gd_reminder_set_absolute_time (self, g_value_get_int64 (value)); + break; + case PROP_RELATIVE_TIME: + gdata_gd_reminder_set_relative_time (self, g_value_get_int (value)); + break; + default: + /* We don't have any other property... */ + G_OBJECT_WARN_INVALID_PROPERTY_ID (object, property_id, pspec); + break; + } +} + +static gboolean +pre_parse_xml (GDataParsable *parsable, xmlDoc *doc, xmlNode *root_node, gpointer user_data, GError **error) +{ + GDataGDReminderPrivate *priv = GDATA_GD_REMINDER (parsable)->priv; + xmlChar *absolute_time, *relative_time; + gint64 absolute_time_int64; + gint relative_time_int = -1; + gboolean is_absolute_time = FALSE; + + /* Absolute time */ + absolute_time = xmlGetProp (root_node, (xmlChar*) "absoluteTime"); + if (absolute_time != NULL) { + is_absolute_time = TRUE; + if (gdata_parser_int64_from_iso8601 ((gchar*) absolute_time, &absolute_time_int64) == FALSE) { + /* Error */ + gdata_parser_error_not_iso8601_format (root_node, (gchar*) absolute_time, error); + xmlFree (absolute_time); + return FALSE; + } + xmlFree (absolute_time); + } + + /* Relative time */ + relative_time = xmlGetProp (root_node, (xmlChar*) "days"); + if (relative_time != NULL) { + relative_time_int = g_ascii_strtoll ((gchar*) relative_time, NULL, 10) * 60 * 24; + } else { + relative_time = xmlGetProp (root_node, (xmlChar*) "hours"); + if (relative_time != NULL) { + relative_time_int = g_ascii_strtoll ((gchar*) relative_time, NULL, 10) * 60; + } else { + relative_time = xmlGetProp (root_node, (xmlChar*) "minutes"); + if (relative_time != NULL) + relative_time_int = g_ascii_strtoll ((gchar*) relative_time, NULL, 10); + } + } + xmlFree (relative_time); + + if (is_absolute_time == TRUE) { + priv->absolute_time = absolute_time_int64; + priv->relative_time = -1; + } else { + priv->absolute_time = -1; + priv->relative_time = relative_time_int; + } + + priv->method = (gchar*) xmlGetProp (root_node, (xmlChar*) "method"); + + return TRUE; +} + +static void +pre_get_xml (GDataParsable *parsable, GString *xml_string) +{ + GDataGDReminderPrivate *priv = GDATA_GD_REMINDER (parsable)->priv; + + if (priv->relative_time == -1) { + gchar *absolute_time = gdata_parser_int64_to_iso8601 (priv->absolute_time); + g_string_append_printf (xml_string, " absoluteTime='%s'", absolute_time); + g_free (absolute_time); + } else { + g_string_append_printf (xml_string, " minutes='%i'", priv->relative_time); + } + + if (priv->method != NULL) + gdata_parser_string_append_escaped (xml_string, " method='", priv->method, "'"); +} + +static void +get_namespaces (GDataParsable *parsable, GHashTable *namespaces) +{ + g_hash_table_insert (namespaces, (gchar*) "gd", (gchar*) "http://schemas.google.com/g/2005"); +} + +/** + * gdata_gd_reminder_new: + * @method: (allow-none): the notification method the reminder should use, or %NULL + * @absolute_time: the absolute time for the reminder, or -1 + * @relative_time: the relative time for the reminder, in minutes, or -1 + * + * Creates a new #GDataGDReminder. More information is available in the GData specification. + * + * Return value: a new #GDataGDReminder, or %NULL; unref with g_object_unref() + * + * Since: 0.2.0 + */ +GDataGDReminder * +gdata_gd_reminder_new (const gchar *method, gint64 absolute_time, gint relative_time) +{ + g_return_val_if_fail (absolute_time == -1 || relative_time == -1, NULL); + g_return_val_if_fail (absolute_time >= -1, NULL); + g_return_val_if_fail (relative_time >= -1, NULL); + return g_object_new (GDATA_TYPE_GD_REMINDER, "absolute-time", absolute_time, "relative-time", relative_time, "method", method, NULL); +} + +/** + * gdata_gd_reminder_get_method: + * @self: a #GDataGDReminder + * + * Gets the #GDataGDReminder:method property. + * + * Return value: the method, or %NULL + * + * Since: 0.4.0 + */ +const gchar * +gdata_gd_reminder_get_method (GDataGDReminder *self) +{ + g_return_val_if_fail (GDATA_IS_GD_REMINDER (self), NULL); + return self->priv->method; +} + +/** + * gdata_gd_reminder_set_method: + * @self: a #GDataGDReminder + * @method: (allow-none): the new method, or %NULL + * + * Sets the #GDataGDReminder:method property to @method. + * + * Set @method to %NULL to unset the property. + * + * Since: 0.4.0 + */ +void +gdata_gd_reminder_set_method (GDataGDReminder *self, const gchar *method) +{ + g_return_if_fail (GDATA_IS_GD_REMINDER (self)); + + g_free (self->priv->method); + self->priv->method = g_strdup (method); + g_object_notify (G_OBJECT (self), "method"); +} + +/** + * gdata_gd_reminder_get_absolute_time: + * @self: a #GDataGDReminder + * + * Gets the #GDataGDReminder:absolute-time property. If the property is unset, -1 will be returned. + * + * Return value: the UNIX timestamp of the absolute time for the reminder, or -1 + * + * Since: 0.4.0 + */ +gint64 +gdata_gd_reminder_get_absolute_time (GDataGDReminder *self) +{ + g_return_val_if_fail (GDATA_IS_GD_REMINDER (self), -1); + return self->priv->absolute_time; +} + +/** + * gdata_gd_reminder_set_absolute_time: + * @self: a #GDataGDReminder + * @absolute_time: the new absolute time, or -1 + * + * Sets the #GDataGDReminder:absolute-time property to @absolute_time. + * + * Set @absolute_time to -1 to unset the property. + * + * Since: 0.4.0 + */ +void +gdata_gd_reminder_set_absolute_time (GDataGDReminder *self, gint64 absolute_time) +{ + g_return_if_fail (GDATA_IS_GD_REMINDER (self)); + g_return_if_fail (absolute_time >= -1); + + self->priv->absolute_time = absolute_time; + g_object_notify (G_OBJECT (self), "absolute-time"); +} + +/** + * gdata_gd_reminder_is_absolute_time: + * @self: a #GDataGDReminder + * + * Returns whether the reminder is specified as an absolute time, or as a number of minutes after + * the corresponding event's start time. + * + * Return value: %TRUE if the reminder is absolute, %FALSE otherwise + * + * Since: 0.4.0 + */ +gboolean +gdata_gd_reminder_is_absolute_time (GDataGDReminder *self) +{ + g_return_val_if_fail (GDATA_IS_GD_REMINDER (self), FALSE); + return (self->priv->relative_time == -1) ? TRUE : FALSE; +} + +/** + * gdata_gd_reminder_get_relative_time: + * @self: a #GDataGDReminder + * + * Gets the #GDataGDReminder:relative-time property. + * + * Return value: the relative time, or -1 + * + * Since: 0.4.0 + */ +gint +gdata_gd_reminder_get_relative_time (GDataGDReminder *self) +{ + g_return_val_if_fail (GDATA_IS_GD_REMINDER (self), -1); + return self->priv->relative_time; +} + +/** + * gdata_gd_reminder_set_relative_time: + * @self: a #GDataGDReminder + * @relative_time: the new relative time, or -1 + * + * Sets the #GDataGDReminder:relative-time property to @relative_time. + * + * Set @relative_time to -1 to unset the property. + * + * Since: 0.4.0 + */ +void +gdata_gd_reminder_set_relative_time (GDataGDReminder *self, gint relative_time) +{ + g_return_if_fail (GDATA_IS_GD_REMINDER (self)); + g_return_if_fail (relative_time >= -1); + + self->priv->relative_time = relative_time; + g_object_notify (G_OBJECT (self), "method"); +} diff --git a/gdata/gd/gdata-gd-reminder.h b/gdata/gd/gdata-gd-reminder.h new file mode 100644 index 0000000..9f7373d --- /dev/null +++ b/gdata/gd/gdata-gd-reminder.h @@ -0,0 +1,111 @@ +/* -*- Mode: C; indent-tabs-mode: t; c-basic-offset: 8; tab-width: 8 -*- */ +/* + * GData Client + * Copyright (C) Philip Withnall 2009–2010 + * + * GData Client is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * GData Client is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with GData Client. If not, see . + */ + +#ifndef GDATA_GD_REMINDER_H +#define GDATA_GD_REMINDER_H + +#include +#include + +#include + +G_BEGIN_DECLS + +/** + * GDATA_GD_REMINDER_ALERT: + * + * The #GDataGDReminder:method for an alert to appear in the user's browser. + * + * Since: 0.7.0 + */ +#define GDATA_GD_REMINDER_ALERT "alert" + +/** + * GDATA_GD_REMINDER_EMAIL: + * + * The #GDataGDReminder:method for an alert to be sent to the user by e-mail. + * + * Since: 0.7.0 + */ +#define GDATA_GD_REMINDER_EMAIL "email" + +/** + * GDATA_GD_REMINDER_SMS: + * + * The #GDataGDReminder:method for an alert to be sent to the user by SMS. + * + * Since: 0.7.0 + */ +#define GDATA_GD_REMINDER_SMS "sms" + +#define GDATA_TYPE_GD_REMINDER (gdata_gd_reminder_get_type ()) +#define GDATA_GD_REMINDER(o) (G_TYPE_CHECK_INSTANCE_CAST ((o), GDATA_TYPE_GD_REMINDER, GDataGDReminder)) +#define GDATA_GD_REMINDER_CLASS(k) (G_TYPE_CHECK_CLASS_CAST((k), GDATA_TYPE_GD_REMINDER, GDataGDReminderClass)) +#define GDATA_IS_GD_REMINDER(o) (G_TYPE_CHECK_INSTANCE_TYPE ((o), GDATA_TYPE_GD_REMINDER)) +#define GDATA_IS_GD_REMINDER_CLASS(k) (G_TYPE_CHECK_CLASS_TYPE ((k), GDATA_TYPE_GD_REMINDER)) +#define GDATA_GD_REMINDER_GET_CLASS(o) (G_TYPE_INSTANCE_GET_CLASS ((o), GDATA_TYPE_GD_REMINDER, GDataGDReminderClass)) + +typedef struct _GDataGDReminderPrivate GDataGDReminderPrivate; + +/** + * GDataGDReminder: + * + * All the fields in the #GDataGDReminder structure are private and should never be accessed directly. + * + * Since: 0.2.0 + */ +typedef struct { + GDataParsable parent; + GDataGDReminderPrivate *priv; +} GDataGDReminder; + +/** + * GDataGDReminderClass: + * + * All the fields in the #GDataGDReminderClass structure are private and should never be accessed directly. + * + * Since: 0.4.0 + */ +typedef struct { + /*< private >*/ + GDataParsableClass parent; + + /*< private >*/ + /* Padding for future expansion */ + void (*_g_reserved0) (void); + void (*_g_reserved1) (void); +} GDataGDReminderClass; + +GType gdata_gd_reminder_get_type (void) G_GNUC_CONST; + +GDataGDReminder *gdata_gd_reminder_new (const gchar *method, gint64 absolute_time, gint relative_time) G_GNUC_WARN_UNUSED_RESULT G_GNUC_MALLOC; + +const gchar *gdata_gd_reminder_get_method (GDataGDReminder *self) G_GNUC_PURE; +void gdata_gd_reminder_set_method (GDataGDReminder *self, const gchar *method); + +gint64 gdata_gd_reminder_get_absolute_time (GDataGDReminder *self); +void gdata_gd_reminder_set_absolute_time (GDataGDReminder *self, gint64 absolute_time); +gboolean gdata_gd_reminder_is_absolute_time (GDataGDReminder *self); + +gint gdata_gd_reminder_get_relative_time (GDataGDReminder *self) G_GNUC_PURE; +void gdata_gd_reminder_set_relative_time (GDataGDReminder *self, gint relative_time); + +G_END_DECLS + +#endif /* !GDATA_GD_REMINDER_H */ diff --git a/gdata/gd/gdata-gd-when.c b/gdata/gd/gdata-gd-when.c new file mode 100644 index 0000000..4df94a2 --- /dev/null +++ b/gdata/gd/gdata-gd-when.c @@ -0,0 +1,593 @@ +/* -*- Mode: C; indent-tabs-mode: t; c-basic-offset: 8; tab-width: 8 -*- */ +/* + * GData Client + * Copyright (C) Philip Withnall 2009–2010 + * + * GData Client is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * GData Client is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with GData Client. If not, see . + */ + +/** + * SECTION:gdata-gd-when + * @short_description: GData when element + * @stability: Stable + * @include: gdata/gd/gdata-gd-when.h + * + * #GDataGDWhen represents a "when" element from the + * GData specification. + * + * Since: 0.4.0 + */ + +#include +#include + +#include "gdata-gd-when.h" +#include "gdata-gd-reminder.h" +#include "gdata-private.h" +#include "gdata-parsable.h" +#include "gdata-parser.h" +#include "gdata-types.h" +#include "gdata-comparable.h" + +static void gdata_gd_when_comparable_init (GDataComparableIface *iface); +static void gdata_gd_when_dispose (GObject *object); +static void gdata_gd_when_finalize (GObject *object); +static void gdata_gd_when_get_property (GObject *object, guint property_id, GValue *value, GParamSpec *pspec); +static void gdata_gd_when_set_property (GObject *object, guint property_id, const GValue *value, GParamSpec *pspec); +static gboolean pre_parse_xml (GDataParsable *parsable, xmlDoc *doc, xmlNode *root_node, gpointer user_data, GError **error); +static gboolean parse_xml (GDataParsable *parsable, xmlDoc *doc, xmlNode *root_node, gpointer user_data, GError **error); +static gboolean post_parse_xml (GDataParsable *parsable, gpointer user_data, GError **error); +static void pre_get_xml (GDataParsable *parsable, GString *xml_string); +static void get_xml (GDataParsable *parsable, GString *xml_string); +static void get_namespaces (GDataParsable *parsable, GHashTable *namespaces); + +struct _GDataGDWhenPrivate { + gint64 start_time; + gint64 end_time; + gboolean is_date; + gchar *value_string; + GList *reminders; +}; + +enum { + PROP_START_TIME = 1, + PROP_END_TIME, + PROP_IS_DATE, + PROP_VALUE_STRING +}; + +G_DEFINE_TYPE_WITH_CODE (GDataGDWhen, gdata_gd_when, GDATA_TYPE_PARSABLE, + G_IMPLEMENT_INTERFACE (GDATA_TYPE_COMPARABLE, gdata_gd_when_comparable_init)) + +static void +gdata_gd_when_class_init (GDataGDWhenClass *klass) +{ + GObjectClass *gobject_class = G_OBJECT_CLASS (klass); + GDataParsableClass *parsable_class = GDATA_PARSABLE_CLASS (klass); + + g_type_class_add_private (klass, sizeof (GDataGDWhenPrivate)); + + gobject_class->get_property = gdata_gd_when_get_property; + gobject_class->set_property = gdata_gd_when_set_property; + gobject_class->dispose = gdata_gd_when_dispose; + gobject_class->finalize = gdata_gd_when_finalize; + + parsable_class->pre_parse_xml = pre_parse_xml; + parsable_class->parse_xml = parse_xml; + parsable_class->post_parse_xml = post_parse_xml; + parsable_class->pre_get_xml = pre_get_xml; + parsable_class->get_xml = get_xml; + parsable_class->get_namespaces = get_namespaces; + parsable_class->element_name = "when"; + parsable_class->element_namespace = "gd"; + + /** + * GDataGDWhen:start-time: + * + * The name of the when. + * + * For more information, see the + * GData specification. + * + * Since: 0.4.0 + */ + g_object_class_install_property (gobject_class, PROP_START_TIME, + g_param_spec_int64 ("start-time", + "Start time", "The name of the when.", + 0, G_MAXINT64, 0, + G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)); + + /** + * GDataGDWhen:end-time: + * + * The title of a person within the when. + * + * For more information, see the + * GData specification. + * + * Since: 0.4.0 + */ + g_object_class_install_property (gobject_class, PROP_END_TIME, + g_param_spec_int64 ("end-time", + "End time", "The title of a person within the when.", + -1, G_MAXINT64, -1, + G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)); + + /** + * GDataGDWhen:is-date: + * + * A programmatic value that identifies the type of when. + * + * For more information, see the + * GData specification. + * + * Since: 0.4.0 + */ + g_object_class_install_property (gobject_class, PROP_IS_DATE, + g_param_spec_boolean ("is-date", + "Date?", "A programmatic value that identifies the type of when.", + FALSE, + G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)); + + /** + * GDataGDWhen:value-string: + * + * A simple string value used to name this when. It allows UIs to display a label such as "Work", "Volunteer", + * "Professional Society", etc. + * + * For more information, see the + * GData specification. + * + * Since: 0.4.0 + */ + g_object_class_install_property (gobject_class, PROP_VALUE_STRING, + g_param_spec_string ("value-string", + "Value string", "A simple string value used to name this when.", + NULL, + G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)); +} + +static gint +compare_with (GDataComparable *self, GDataComparable *other) +{ + gint64 start_diff, end_diff; + GDataGDWhenPrivate *a = ((GDataGDWhen*) self)->priv, *b = ((GDataGDWhen*) other)->priv; + + if (a->is_date != b->is_date) + return CLAMP (b->is_date - a->is_date, -1, 1); + + start_diff = b->start_time - a->start_time; + end_diff = b->end_time - a->end_time; + + if (start_diff == 0) + return CLAMP (end_diff, -1, 1); + return CLAMP (start_diff, -1, 1); +} + +static void +gdata_gd_when_comparable_init (GDataComparableIface *iface) +{ + iface->compare_with = compare_with; +} + +static void +gdata_gd_when_init (GDataGDWhen *self) +{ + self->priv = G_TYPE_INSTANCE_GET_PRIVATE (self, GDATA_TYPE_GD_WHEN, GDataGDWhenPrivate); + self->priv->end_time = -1; +} + +static void +gdata_gd_when_dispose (GObject *object) +{ + GDataGDWhenPrivate *priv = GDATA_GD_WHEN (object)->priv; + + g_list_free_full (priv->reminders, g_object_unref); + priv->reminders = NULL; + + /* Chain up to the parent class */ + G_OBJECT_CLASS (gdata_gd_when_parent_class)->dispose (object); +} + +static void +gdata_gd_when_finalize (GObject *object) +{ + GDataGDWhenPrivate *priv = GDATA_GD_WHEN (object)->priv; + + g_free (priv->value_string); + + /* Chain up to the parent class */ + G_OBJECT_CLASS (gdata_gd_when_parent_class)->finalize (object); +} + +static void +gdata_gd_when_get_property (GObject *object, guint property_id, GValue *value, GParamSpec *pspec) +{ + GDataGDWhenPrivate *priv = GDATA_GD_WHEN (object)->priv; + + switch (property_id) { + case PROP_START_TIME: + g_value_set_int64 (value, priv->start_time); + break; + case PROP_END_TIME: + g_value_set_int64 (value, priv->end_time); + break; + case PROP_IS_DATE: + g_value_set_boolean (value, priv->is_date); + break; + case PROP_VALUE_STRING: + g_value_set_string (value, priv->value_string); + break; + default: + /* We don't have any other property... */ + G_OBJECT_WARN_INVALID_PROPERTY_ID (object, property_id, pspec); + break; + } +} + +static void +gdata_gd_when_set_property (GObject *object, guint property_id, const GValue *value, GParamSpec *pspec) +{ + GDataGDWhen *self = GDATA_GD_WHEN (object); + + switch (property_id) { + case PROP_START_TIME: + gdata_gd_when_set_start_time (self, g_value_get_int64 (value)); + break; + case PROP_END_TIME: + gdata_gd_when_set_end_time (self, g_value_get_int64 (value)); + break; + case PROP_IS_DATE: + gdata_gd_when_set_is_date (self, g_value_get_boolean (value)); + break; + case PROP_VALUE_STRING: + gdata_gd_when_set_value_string (self, g_value_get_string (value)); + break; + default: + /* We don't have any other property... */ + G_OBJECT_WARN_INVALID_PROPERTY_ID (object, property_id, pspec); + break; + } +} + +static gboolean +pre_parse_xml (GDataParsable *parsable, xmlDoc *doc, xmlNode *root_node, gpointer user_data, GError **error) +{ + GDataGDWhenPrivate *priv = GDATA_GD_WHEN (parsable)->priv; + xmlChar *start_time, *end_time; + gint64 start_time_int64, end_time_int64; + gboolean is_date = FALSE; + + /* Start time */ + start_time = xmlGetProp (root_node, (xmlChar*) "startTime"); + if (gdata_parser_int64_from_date ((gchar*) start_time, &start_time_int64) == TRUE) { + is_date = TRUE; + } else if (gdata_parser_int64_from_iso8601 ((gchar*) start_time, &start_time_int64) == FALSE) { + /* Error */ + gdata_parser_error_not_iso8601_format (root_node, (gchar*) start_time, error); + xmlFree (start_time); + return FALSE; + } + xmlFree (start_time); + + /* End time (optional) */ + end_time = xmlGetProp (root_node, (xmlChar*) "endTime"); + if (end_time != NULL) { + gboolean success; + + if (is_date == TRUE) + success = gdata_parser_int64_from_date ((gchar*) end_time, &end_time_int64); + else + success = gdata_parser_int64_from_iso8601 ((gchar*) end_time, &end_time_int64); + + if (success == FALSE) { + /* Error */ + gdata_parser_error_not_iso8601_format (root_node, (gchar*) end_time, error); + xmlFree (end_time); + return FALSE; + } + xmlFree (end_time); + } else { + /* Give a default */ + end_time_int64 = -1; + } + + priv->start_time = start_time_int64; + priv->end_time = end_time_int64; + priv->is_date = is_date; + priv->value_string = (gchar*) xmlGetProp (root_node, (xmlChar*) "valueString"); + + return TRUE; +} + +static gboolean +parse_xml (GDataParsable *parsable, xmlDoc *doc, xmlNode *node, gpointer user_data, GError **error) +{ + gboolean success; + + if (gdata_parser_is_namespace (node, "http://schemas.google.com/g/2005") == TRUE && + gdata_parser_object_from_element_setter (node, "reminder", P_REQUIRED, GDATA_TYPE_GD_REMINDER, + gdata_gd_when_add_reminder, parsable, &success, error) == TRUE) { + return success; + } else { + return GDATA_PARSABLE_CLASS (gdata_gd_when_parent_class)->parse_xml (parsable, doc, node, user_data, error); + } +} + +static gboolean +post_parse_xml (GDataParsable *parsable, gpointer user_data, GError **error) +{ + GDataGDWhenPrivate *priv = GDATA_GD_WHEN (parsable)->priv; + + /* Reverse our lists of stuff */ + priv->reminders = g_list_reverse (priv->reminders); + + return TRUE; +} + +static void +pre_get_xml (GDataParsable *parsable, GString *xml_string) +{ + GDataGDWhenPrivate *priv = GDATA_GD_WHEN (parsable)->priv; + gchar *start_time; + + if (priv->is_date == TRUE) + start_time = gdata_parser_date_from_int64 (priv->start_time); + else + start_time = gdata_parser_int64_to_iso8601 (priv->start_time); + + g_string_append_printf (xml_string, " startTime='%s'", start_time); + g_free (start_time); + + if (priv->end_time != -1) { + gchar *end_time; + + if (priv->is_date == TRUE) + end_time = gdata_parser_date_from_int64 (priv->end_time); + else + end_time = gdata_parser_int64_to_iso8601 (priv->end_time); + + g_string_append_printf (xml_string, " endTime='%s'", end_time); + g_free (end_time); + } + + if (priv->value_string != NULL) + gdata_parser_string_append_escaped (xml_string, " valueString='", priv->value_string, "'"); +} + +static void +get_xml (GDataParsable *parsable, GString *xml_string) +{ + GList *reminders; + GDataGDWhenPrivate *priv = GDATA_GD_WHEN (parsable)->priv; + + for (reminders = priv->reminders; reminders != NULL; reminders = reminders->next) + _gdata_parsable_get_xml (GDATA_PARSABLE (reminders->data), xml_string, FALSE); +} + +static void +get_namespaces (GDataParsable *parsable, GHashTable *namespaces) +{ + g_hash_table_insert (namespaces, (gchar*) "gd", (gchar*) "http://schemas.google.com/g/2005"); +} + +/** + * gdata_gd_when_new: + * @start_time: when the event starts or (for zero-duration events) when it occurs + * @end_time: when the event ends, or -1 + * @is_date: %TRUE if @start_time and @end_time specify dates rather than times, %FALSE otherwise + * + * Creates a new #GDataGDWhen. More information is available in the GData specification. + * + * Return value: a new #GDataGDWhen, or %NULL; unref with g_object_unref() + * + * Since: 0.2.0 + */ +GDataGDWhen * +gdata_gd_when_new (gint64 start_time, gint64 end_time, gboolean is_date) +{ + g_return_val_if_fail (start_time >= 0, NULL); + g_return_val_if_fail (end_time >= -1, NULL); + + return g_object_new (GDATA_TYPE_GD_WHEN, "start-time", start_time, "end-time", end_time, "is-date", is_date, NULL); +} + +/** + * gdata_gd_when_get_start_time: + * @self: a #GDataGDWhen + * + * Gets the #GDataGDWhen:start-time property. + * + * Return value: the UNIX timestamp for the start time of the event + * + * Since: 0.4.0 + */ +gint64 +gdata_gd_when_get_start_time (GDataGDWhen *self) +{ + g_return_val_if_fail (GDATA_IS_GD_WHEN (self), -1); + return self->priv->start_time; +} + +/** + * gdata_gd_when_set_start_time: + * @self: a #GDataGDWhen + * @start_time: the new start time + * + * Sets the #GDataGDWhen:start-time property to @start_time. + * + * Since: 0.4.0 + */ +void +gdata_gd_when_set_start_time (GDataGDWhen *self, gint64 start_time) +{ + g_return_if_fail (GDATA_IS_GD_WHEN (self)); + g_return_if_fail (start_time >= 0); + + self->priv->start_time = start_time; + g_object_notify (G_OBJECT (self), "start-time"); +} + +/** + * gdata_gd_when_get_end_time: + * @self: a #GDataGDWhen + * + * Gets the #GDataGDWhen:end-time property. + * + * If the end time is unset, -1 will be returned. + * + * Return value: the UNIX timestamp for the end time of the event, or + * -1 + * + * Since: 0.4.0 + */ +gint64 +gdata_gd_when_get_end_time (GDataGDWhen *self) +{ + g_return_val_if_fail (GDATA_IS_GD_WHEN (self), -1); + return self->priv->end_time; +} + +/** + * gdata_gd_when_set_end_time: + * @self: a #GDataGDWhen + * @end_time: the new end time, or -1 + * + * Sets the #GDataGDWhen:end-time property to @end_time. + * + * Set @end_time to -1 to unset the property. + * + * Since: 0.4.0 + */ +void +gdata_gd_when_set_end_time (GDataGDWhen *self, gint64 end_time) +{ + g_return_if_fail (GDATA_IS_GD_WHEN (self)); + g_return_if_fail (end_time >= -1); + + self->priv->end_time = end_time; + g_object_notify (G_OBJECT (self), "end-time"); +} + +/** + * gdata_gd_when_is_date: + * @self: a #GDataGDWhen + * + * Gets the #GDataGDWhen:is-date property. + * + * Return value: %TRUE if #GDataGDWhen:start-time and #GDataGDWhen:end-time are dates rather than times, %FALSE otherwise + * + * Since: 0.4.0 + */ +gboolean +gdata_gd_when_is_date (GDataGDWhen *self) +{ + g_return_val_if_fail (GDATA_IS_GD_WHEN (self), FALSE); + return self->priv->is_date; +} + +/** + * gdata_gd_when_set_is_date: + * @self: a #GDataGDWhen + * @is_date: %TRUE if #GDataGDWhen:start-time and #GDataGDWhen:end-time should be dates rather than times, %FALSE otherwise + * + * Sets the #GDataGDWhen:is-date property to @is_date. + * + * Since: 0.4.0 + */ +void +gdata_gd_when_set_is_date (GDataGDWhen *self, gboolean is_date) +{ + g_return_if_fail (GDATA_IS_GD_WHEN (self)); + + self->priv->is_date = is_date; + g_object_notify (G_OBJECT (self), "is-date"); +} + +/** + * gdata_gd_when_get_value_string: + * @self: a #GDataGDWhen + * + * Gets the #GDataGDWhen:value-string property. + * + * Return value: the value string, or %NULL + * + * Since: 0.4.0 + */ +const gchar * +gdata_gd_when_get_value_string (GDataGDWhen *self) +{ + g_return_val_if_fail (GDATA_IS_GD_WHEN (self), NULL); + return self->priv->value_string; +} + +/** + * gdata_gd_when_set_value_string: + * @self: a #GDataGDWhen + * @value_string: (allow-none): the new value string, or %NULL + * + * Sets the #GDataGDWhen:value-string property to @value_string. + * + * Set @value_string to %NULL to unset the property. + * + * Since: 0.4.0 + */ +void +gdata_gd_when_set_value_string (GDataGDWhen *self, const gchar *value_string) +{ + g_return_if_fail (GDATA_IS_GD_WHEN (self)); + + g_free (self->priv->value_string); + self->priv->value_string = g_strdup (value_string); + g_object_notify (G_OBJECT (self), "value-string"); +} + +/** + * gdata_gd_when_get_reminders: + * @self: a #GDataGDWhen + * + * Returns a list of the #GDataGDReminders which are associated with this #GDataGDWhen. + * + * Return value: (element-type GData.GDReminder) (transfer none): a #GList of #GDataGDReminders, or %NULL + * + * Since: 0.4.0 + */ +GList * +gdata_gd_when_get_reminders (GDataGDWhen *self) +{ + g_return_val_if_fail (GDATA_IS_GD_WHEN (self), NULL); + return self->priv->reminders; +} + +/** + * gdata_gd_when_add_reminder: + * @self: a #GDataGDWhen + * @reminder: a #GDataGDReminder to add + * + * Adds a reminder to the #GDataGDWhen's list of reminders and increments its reference count. + * + * Duplicate reminders will not be added to the list. + * + * Since: 0.7.0 + */ +void +gdata_gd_when_add_reminder (GDataGDWhen *self, GDataGDReminder *reminder) +{ + g_return_if_fail (GDATA_IS_GD_WHEN (self)); + g_return_if_fail (GDATA_IS_GD_REMINDER (reminder)); + + if (g_list_find_custom (self->priv->reminders, reminder, (GCompareFunc) gdata_comparable_compare) == NULL) + self->priv->reminders = g_list_append (self->priv->reminders, g_object_ref (reminder)); +} diff --git a/gdata/gd/gdata-gd-when.h b/gdata/gd/gdata-gd-when.h new file mode 100644 index 0000000..6bf9f05 --- /dev/null +++ b/gdata/gd/gdata-gd-when.h @@ -0,0 +1,172 @@ +/* -*- Mode: C; indent-tabs-mode: t; c-basic-offset: 8; tab-width: 8 -*- */ +/* + * GData Client + * Copyright (C) Philip Withnall 2009–2010 + * + * GData Client is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * GData Client is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with GData Client. If not, see . + */ + +#ifndef GDATA_GD_WHEN_H +#define GDATA_GD_WHEN_H + +#include +#include + +#include +#include + +G_BEGIN_DECLS + +/** + * GDATA_GD_EVENT_STATUS_CANCELED: + * + * The event has been canceled. + * + * Since: 0.7.0 + */ +#define GDATA_GD_EVENT_STATUS_CANCELED "http://schemas.google.com/g/2005#event.canceled" + +/** + * GDATA_GD_EVENT_STATUS_CONFIRMED: + * + * The event has been planned and confirmed. + * + * Since: 0.7.0 + */ +#define GDATA_GD_EVENT_STATUS_CONFIRMED "http://schemas.google.com/g/2005#event.confirmed" + +/** + * GDATA_GD_EVENT_STATUS_TENTATIVE: + * + * The event has been planned, but only tentatively scheduled. + * + * Since: 0.7.0 + */ +#define GDATA_GD_EVENT_STATUS_TENTATIVE "http://schemas.google.com/g/2005#event.tentative" + +/** + * GDATA_GD_EVENT_VISIBILITY_CONFIDENTIAL: + * + * The event is visible to only certain people. + * + * Since: 0.7.0 + */ +#define GDATA_GD_EVENT_VISIBILITY_CONFIDENTIAL "http://schemas.google.com/g/2005#event.confidential" + +/** + * GDATA_GD_EVENT_VISIBILITY_DEFAULT: + * + * The event's visibility is inherited from the preferences of its owner. + * + * Since: 0.7.0 + */ +#define GDATA_GD_EVENT_VISIBILITY_DEFAULT "http://schemas.google.com/g/2005#event.default" + +/** + * GDATA_GD_EVENT_VISIBILITY_PRIVATE: + * + * The event is visible to very few people. + * + * Since: 0.7.0 + */ +#define GDATA_GD_EVENT_VISIBILITY_PRIVATE "http://schemas.google.com/g/2005#event.private" + +/** + * GDATA_GD_EVENT_VISIBILITY_PUBLIC: + * + * The event is visible to most people. + * + * Since: 0.7.0 + */ +#define GDATA_GD_EVENT_VISIBILITY_PUBLIC "http://schemas.google.com/g/2005#event.public" + +/** + * GDATA_GD_EVENT_TRANSPARENCY_OPAQUE: + * + * The event consumes time in calendars; its time will be marked as busy in a free/busy search. + * + * Since: 0.7.0 + */ +#define GDATA_GD_EVENT_TRANSPARENCY_OPAQUE "http://schemas.google.com/g/2005#event.opaque" + +/** + * GDATA_GD_EVENT_TRANSPARENCY_TRANSPARENT: + * + * The event does not consume time in calendars; its time will be not marked as busy in a free/busy search. + * + * Since: 0.7.0 + */ +#define GDATA_GD_EVENT_TRANSPARENCY_TRANSPARENT "http://schemas.google.com/g/2005#event.transparent" + +#define GDATA_TYPE_GD_WHEN (gdata_gd_when_get_type ()) +#define GDATA_GD_WHEN(o) (G_TYPE_CHECK_INSTANCE_CAST ((o), GDATA_TYPE_GD_WHEN, GDataGDWhen)) +#define GDATA_GD_WHEN_CLASS(k) (G_TYPE_CHECK_CLASS_CAST((k), GDATA_TYPE_GD_WHEN, GDataGDWhenClass)) +#define GDATA_IS_GD_WHEN(o) (G_TYPE_CHECK_INSTANCE_TYPE ((o), GDATA_TYPE_GD_WHEN)) +#define GDATA_IS_GD_WHEN_CLASS(k) (G_TYPE_CHECK_CLASS_TYPE ((k), GDATA_TYPE_GD_WHEN)) +#define GDATA_GD_WHEN_GET_CLASS(o) (G_TYPE_INSTANCE_GET_CLASS ((o), GDATA_TYPE_GD_WHEN, GDataGDWhenClass)) + +typedef struct _GDataGDWhenPrivate GDataGDWhenPrivate; + +/** + * GDataGDWhen: + * + * All the fields in the #GDataGDWhen structure are private and should never be accessed directly. + * + * Since: 0.2.0 + */ +typedef struct { + GDataParsable parent; + GDataGDWhenPrivate *priv; +} GDataGDWhen; + +/** + * GDataGDWhenClass: + * + * All the fields in the #GDataGDWhenClass structure are private and should never be accessed directly. + * + * Since: 0.4.0 + */ +typedef struct { + /*< private >*/ + GDataParsableClass parent; + + /*< private >*/ + /* Padding for future expansion */ + void (*_g_reserved0) (void); + void (*_g_reserved1) (void); +} GDataGDWhenClass; + +GType gdata_gd_when_get_type (void) G_GNUC_CONST; + +GDataGDWhen *gdata_gd_when_new (gint64 start_time, gint64 end_time, gboolean is_date) G_GNUC_WARN_UNUSED_RESULT G_GNUC_MALLOC; + +gint64 gdata_gd_when_get_start_time (GDataGDWhen *self); +void gdata_gd_when_set_start_time (GDataGDWhen *self, gint64 start_time); + +gint64 gdata_gd_when_get_end_time (GDataGDWhen *self); +void gdata_gd_when_set_end_time (GDataGDWhen *self, gint64 end_time); + +gboolean gdata_gd_when_is_date (GDataGDWhen *self) G_GNUC_PURE; +void gdata_gd_when_set_is_date (GDataGDWhen *self, gboolean is_date); + +const gchar *gdata_gd_when_get_value_string (GDataGDWhen *self) G_GNUC_PURE; +void gdata_gd_when_set_value_string (GDataGDWhen *self, const gchar *value_string); + +GList *gdata_gd_when_get_reminders (GDataGDWhen *self) G_GNUC_PURE; +void gdata_gd_when_add_reminder (GDataGDWhen *self, GDataGDReminder *reminder); +/* TODO: More reminder API */ + +G_END_DECLS + +#endif /* !GDATA_GD_WHEN_H */ diff --git a/gdata/gd/gdata-gd-where.c b/gdata/gd/gdata-gd-where.c new file mode 100644 index 0000000..ea299c0 --- /dev/null +++ b/gdata/gd/gdata-gd-where.c @@ -0,0 +1,407 @@ +/* -*- Mode: C; indent-tabs-mode: t; c-basic-offset: 8; tab-width: 8 -*- */ +/* + * GData Client + * Copyright (C) Philip Withnall 2009–2010 + * + * GData Client is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * GData Client is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with GData Client. If not, see . + */ + +/** + * SECTION:gdata-gd-where + * @short_description: GData where element + * @stability: Stable + * @include: gdata/gd/gdata-gd-where.h + * + * #GDataGDWhere represents a "where" element from the + * GData specification. + * + * Since: 0.4.0 + */ + +#include +#include + +#include "gdata-gd-where.h" +#include "gdata-parsable.h" +#include "gdata-parser.h" +#include "gdata-comparable.h" + +static void gdata_gd_where_comparable_init (GDataComparableIface *iface); +static void gdata_gd_where_finalize (GObject *object); +static void gdata_gd_where_get_property (GObject *object, guint property_id, GValue *value, GParamSpec *pspec); +static void gdata_gd_where_set_property (GObject *object, guint property_id, const GValue *value, GParamSpec *pspec); +static gboolean pre_parse_xml (GDataParsable *parsable, xmlDoc *doc, xmlNode *root_node, gpointer user_data, GError **error); +/*static gboolean parse_xml (GDataParsable *parsable, xmlDoc *doc, xmlNode *root_node, gpointer user_data, GError **error);*/ +static void pre_get_xml (GDataParsable *parsable, GString *xml_string); +/*static void get_xml (GDataParsable *parsable, GString *xml_string);*/ +static void get_namespaces (GDataParsable *parsable, GHashTable *namespaces); + +struct _GDataGDWherePrivate { + gchar *relation_type; + gchar *value_string; + gchar *label; +}; + +enum { + PROP_RELATION_TYPE = 1, + PROP_VALUE_STRING, + PROP_LABEL +}; + +G_DEFINE_TYPE_WITH_CODE (GDataGDWhere, gdata_gd_where, GDATA_TYPE_PARSABLE, + G_IMPLEMENT_INTERFACE (GDATA_TYPE_COMPARABLE, gdata_gd_where_comparable_init)) + +static void +gdata_gd_where_class_init (GDataGDWhereClass *klass) +{ + GObjectClass *gobject_class = G_OBJECT_CLASS (klass); + GDataParsableClass *parsable_class = GDATA_PARSABLE_CLASS (klass); + + g_type_class_add_private (klass, sizeof (GDataGDWherePrivate)); + + gobject_class->get_property = gdata_gd_where_get_property; + gobject_class->set_property = gdata_gd_where_set_property; + gobject_class->finalize = gdata_gd_where_finalize; + + parsable_class->pre_parse_xml = pre_parse_xml; + /*parsable_class->parse_xml = parse_xml;*/ + parsable_class->pre_get_xml = pre_get_xml; + /*parsable_class->get_xml = get_xml;*/ + parsable_class->get_namespaces = get_namespaces; + parsable_class->element_name = "where"; + parsable_class->element_namespace = "gd"; + + /** + * GDataGDWhere:relation-type: + * + * Specifies the relationship between the containing entity and the contained location. For example: %GDATA_GD_WHERE_EVENT or + * %GDATA_GD_WHERE_EVENT_PARKING. + * + * For more information, see the + * GData specification. + * + * Since: 0.4.0 + */ + g_object_class_install_property (gobject_class, PROP_RELATION_TYPE, + g_param_spec_string ("relation-type", + "Relation type", "Specifies the relationship between the container and the containee.", + NULL, + G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)); + + /** + * GDataGDWhere:value-string: + * + * A simple string representation of this location. + * + * For more information, see the + * GData specification. + * + * Since: 0.4.0 + */ + g_object_class_install_property (gobject_class, PROP_VALUE_STRING, + g_param_spec_string ("value-string", + "Value string", "A simple string representation of this location.", + NULL, + G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)); + + /** + * GDataGDWhere:label: + * + * Specifies a user-readable label to distinguish this location from others. + * + * For more information, see the + * GData specification. + * + * Since: 0.4.0 + */ + g_object_class_install_property (gobject_class, PROP_LABEL, + g_param_spec_string ("label", + "Label", "Specifies a user-readable label to distinguish this location from others.", + NULL, + G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)); +} + +static gint +compare_with (GDataComparable *self, GDataComparable *other) +{ + GDataGDWherePrivate *a = ((GDataGDWhere*) self)->priv, *b = ((GDataGDWhere*) other)->priv; + + if (g_strcmp0 (a->value_string, b->value_string) == 0 && g_strcmp0 (a->label, b->label) == 0) + return 0; + return 1; +} + +static void +gdata_gd_where_comparable_init (GDataComparableIface *iface) +{ + iface->compare_with = compare_with; +} + +static void +gdata_gd_where_init (GDataGDWhere *self) +{ + self->priv = G_TYPE_INSTANCE_GET_PRIVATE (self, GDATA_TYPE_GD_WHERE, GDataGDWherePrivate); +} + +static void +gdata_gd_where_finalize (GObject *object) +{ + GDataGDWherePrivate *priv = GDATA_GD_WHERE (object)->priv; + + g_free (priv->relation_type); + g_free (priv->value_string); + g_free (priv->label); + + /* Chain up to the parent class */ + G_OBJECT_CLASS (gdata_gd_where_parent_class)->finalize (object); +} + +static void +gdata_gd_where_get_property (GObject *object, guint property_id, GValue *value, GParamSpec *pspec) +{ + GDataGDWherePrivate *priv = GDATA_GD_WHERE (object)->priv; + + switch (property_id) { + case PROP_RELATION_TYPE: + g_value_set_string (value, priv->relation_type); + break; + case PROP_VALUE_STRING: + g_value_set_string (value, priv->value_string); + break; + case PROP_LABEL: + g_value_set_string (value, priv->label); + break; + default: + /* We don't have any other property... */ + G_OBJECT_WARN_INVALID_PROPERTY_ID (object, property_id, pspec); + break; + } +} + +static void +gdata_gd_where_set_property (GObject *object, guint property_id, const GValue *value, GParamSpec *pspec) +{ + GDataGDWhere *self = GDATA_GD_WHERE (object); + + switch (property_id) { + case PROP_RELATION_TYPE: + gdata_gd_where_set_relation_type (self, g_value_get_string (value)); + break; + case PROP_VALUE_STRING: + gdata_gd_where_set_value_string (self, g_value_get_string (value)); + break; + case PROP_LABEL: + gdata_gd_where_set_label (self, g_value_get_string (value)); + break; + default: + /* We don't have any other property... */ + G_OBJECT_WARN_INVALID_PROPERTY_ID (object, property_id, pspec); + break; + } +} + +static gboolean +pre_parse_xml (GDataParsable *parsable, xmlDoc *doc, xmlNode *root_node, gpointer user_data, GError **error) +{ + xmlChar *rel; + GDataGDWherePrivate *priv = GDATA_GD_WHERE (parsable)->priv; + + rel = xmlGetProp (root_node, (xmlChar*) "rel"); + if (rel != NULL && *rel == '\0') { + xmlFree (rel); + return gdata_parser_error_required_property_missing (root_node, "rel", error); + } + + priv->relation_type = (gchar*) rel; + priv->value_string = (gchar*) xmlGetProp (root_node, (xmlChar*) "valueString"); + priv->label = (gchar*) xmlGetProp (root_node, (xmlChar*) "label"); + + return TRUE; +} + +/*static gboolean +parse_xml (GDataParsable *parsable, xmlDoc *doc, xmlNode *node, gpointer user_data, GError **error) +{ + GDataGDWherePrivate *priv = GDATA_GD_WHERE (parsable)->priv; + + TODO: deal with the entryLink + + return TRUE; +}*/ + +static void +pre_get_xml (GDataParsable *parsable, GString *xml_string) +{ + GDataGDWherePrivate *priv = GDATA_GD_WHERE (parsable)->priv; + + if (priv->label != NULL) + gdata_parser_string_append_escaped (xml_string, " label='", priv->label, "'"); + + if (priv->relation_type != NULL) + gdata_parser_string_append_escaped (xml_string, " rel='", priv->relation_type, "'"); + + if (priv->value_string != NULL) + gdata_parser_string_append_escaped (xml_string, " valueString='", priv->value_string, "'"); +} + +/*static void +get_xml (GDataParsable *parsable, GString *xml_string) +{ + GDataGDWherePrivate *priv = GDATA_GD_WHERE (parsable)->priv; + + TODO: deal with the entryLink +}*/ + +static void +get_namespaces (GDataParsable *parsable, GHashTable *namespaces) +{ + g_hash_table_insert (namespaces, (gchar*) "gd", (gchar*) "http://schemas.google.com/g/2005"); +} + +/** + * gdata_gd_where_new: + * @relation_type: (allow-none): the relationship between the item and this place, or %NULL + * @value_string: (allow-none): a string to represent the place, or %NULL + * @label: (allow-none): a human-readable label for the place, or %NULL + * + * Creates a new #GDataGDWhere. More information is available in the GData specification. + * + * Currently, entryLink functionality is not implemented in #GDataGDWhere. + * + * Return value: a new #GDataGDWhere; unref with g_object_unref() + * + * Since: 0.2.0 + */ +GDataGDWhere * +gdata_gd_where_new (const gchar *relation_type, const gchar *value_string, const gchar *label) +{ + g_return_val_if_fail (relation_type == NULL || *relation_type != '\0', NULL); + return g_object_new (GDATA_TYPE_GD_WHERE, "relation-type", relation_type, "value-string", value_string, "label", label, NULL); +} + +/** + * gdata_gd_where_get_relation_type: + * @self: a #GDataGDWhere + * + * Gets the #GDataGDWhere:relation-type property. + * + * Return value: the relation type, or %NULL + * + * Since: 0.4.0 + */ +const gchar * +gdata_gd_where_get_relation_type (GDataGDWhere *self) +{ + g_return_val_if_fail (GDATA_IS_GD_WHERE (self), NULL); + return self->priv->relation_type; +} + +/** + * gdata_gd_where_set_relation_type: + * @self: a #GDataGDWhere + * @relation_type: (allow-none): the new relation type, or %NULL + * + * Sets the #GDataGDWhere:relation-type property to @relation_type. + * + * Set @relation_type to %NULL to unset the property. + * + * Since: 0.4.0 + */ +void +gdata_gd_where_set_relation_type (GDataGDWhere *self, const gchar *relation_type) +{ + g_return_if_fail (GDATA_IS_GD_WHERE (self)); + g_return_if_fail (relation_type == NULL || *relation_type != '\0'); + + g_free (self->priv->relation_type); + self->priv->relation_type = g_strdup (relation_type); + g_object_notify (G_OBJECT (self), "relation-type"); +} + +/** + * gdata_gd_where_get_value_string: + * @self: a #GDataGDWhere + * + * Gets the #GDataGDWhere:value-string property. + * + * Return value: the value string, or %NULL + * + * Since: 0.4.0 + */ +const gchar * +gdata_gd_where_get_value_string (GDataGDWhere *self) +{ + g_return_val_if_fail (GDATA_IS_GD_WHERE (self), NULL); + return self->priv->value_string; +} + +/** + * gdata_gd_where_set_value_string: + * @self: a #GDataGDWhere + * @value_string: (allow-none): the new value string, or %NULL + * + * Sets the #GDataGDWhere:value-string property to @value_string. + * + * Set @value_string to %NULL to unset the property. + * + * Since: 0.4.0 + */ +void +gdata_gd_where_set_value_string (GDataGDWhere *self, const gchar *value_string) +{ + g_return_if_fail (GDATA_IS_GD_WHERE (self)); + + g_free (self->priv->value_string); + self->priv->value_string = g_strdup (value_string); + g_object_notify (G_OBJECT (self), "value-string"); +} + +/** + * gdata_gd_where_get_label: + * @self: a #GDataGDWhere + * + * Gets the #GDataGDWhere:label property. + * + * Return value: the label, or %NULL + * + * Since: 0.4.0 + */ +const gchar * +gdata_gd_where_get_label (GDataGDWhere *self) +{ + g_return_val_if_fail (GDATA_IS_GD_WHERE (self), NULL); + return self->priv->label; +} + +/** + * gdata_gd_where_set_label: + * @self: a #GDataGDWhere + * @label: (allow-none): the new label, or %NULL + * + * Sets the #GDataGDWhere:label property to @label. + * + * Set @label to %NULL to unset the property. + * + * Since: 0.4.0 + */ +void +gdata_gd_where_set_label (GDataGDWhere *self, const gchar *label) +{ + g_return_if_fail (GDATA_IS_GD_WHERE (self)); + + g_free (self->priv->label); + self->priv->label = g_strdup (label); + g_object_notify (G_OBJECT (self), "label"); +} diff --git a/gdata/gd/gdata-gd-where.h b/gdata/gd/gdata-gd-where.h new file mode 100644 index 0000000..a44cac4 --- /dev/null +++ b/gdata/gd/gdata-gd-where.h @@ -0,0 +1,110 @@ +/* -*- Mode: C; indent-tabs-mode: t; c-basic-offset: 8; tab-width: 8 -*- */ +/* + * GData Client + * Copyright (C) Philip Withnall 2009–2010 + * + * GData Client is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * GData Client is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with GData Client. If not, see . + */ + +#ifndef GDATA_GD_WHERE_H +#define GDATA_GD_WHERE_H + +#include +#include + +#include + +G_BEGIN_DECLS + +/** + * GDATA_GD_WHERE_EVENT: + * + * The relation type URI for an event location. + * + * Since: 0.7.0 + */ +#define GDATA_GD_WHERE_EVENT "http://schemas.google.com/g/2005#event" + +/** + * GDATA_GD_WHERE_EVENT_ALTERNATE: + * + * The relation type URI for an alternate event location, such as a video conference site. + * + * Since: 0.7.0 + */ +#define GDATA_GD_WHERE_EVENT_ALTERNATE "http://schemas.google.com/g/2005#event.alternate" + +/** + * GDATA_GD_WHERE_EVENT_PARKING: + * + * The relation type URI for an event's parking lot. + * + * Since: 0.7.0 + */ +#define GDATA_GD_WHERE_EVENT_PARKING "http://schemas.google.com/g/2005#event.parking" + +#define GDATA_TYPE_GD_WHERE (gdata_gd_where_get_type ()) +#define GDATA_GD_WHERE(o) (G_TYPE_CHECK_INSTANCE_CAST ((o), GDATA_TYPE_GD_WHERE, GDataGDWhere)) +#define GDATA_GD_WHERE_CLASS(k) (G_TYPE_CHECK_CLASS_CAST((k), GDATA_TYPE_GD_WHERE, GDataGDWhereClass)) +#define GDATA_IS_GD_WHERE(o) (G_TYPE_CHECK_INSTANCE_TYPE ((o), GDATA_TYPE_GD_WHERE)) +#define GDATA_IS_GD_WHERE_CLASS(k) (G_TYPE_CHECK_CLASS_TYPE ((k), GDATA_TYPE_GD_WHERE)) +#define GDATA_GD_WHERE_GET_CLASS(o) (G_TYPE_INSTANCE_GET_CLASS ((o), GDATA_TYPE_GD_WHERE, GDataGDWhereClass)) + +typedef struct _GDataGDWherePrivate GDataGDWherePrivate; + +/** + * GDataGDWhere: + * + * All the fields in the #GDataGDWhere structure are private and should never be accessed directly. + * + * Since: 0.2.0 + */ +typedef struct { + GDataParsable parent; + GDataGDWherePrivate *priv; +} GDataGDWhere; + +/** + * GDataGDWhereClass: + * + * All the fields in the #GDataGDWhereClass structure are private and should never be accessed directly. + * + * Since: 0.4.0 + */ +typedef struct { + /*< private >*/ + GDataParsableClass parent; + + /*< private >*/ + /* Padding for future expansion */ + void (*_g_reserved0) (void); + void (*_g_reserved1) (void); +} GDataGDWhereClass; + +GType gdata_gd_where_get_type (void) G_GNUC_CONST; + +GDataGDWhere *gdata_gd_where_new (const gchar *relation_type, const gchar *value_string, const gchar *label) G_GNUC_WARN_UNUSED_RESULT G_GNUC_MALLOC; + +const gchar *gdata_gd_where_get_relation_type (GDataGDWhere *self) G_GNUC_PURE; +void gdata_gd_where_set_relation_type (GDataGDWhere *self, const gchar *relation_type); + +const gchar *gdata_gd_where_get_value_string (GDataGDWhere *self) G_GNUC_PURE; +void gdata_gd_where_set_value_string (GDataGDWhere *self, const gchar *value_string); + +const gchar *gdata_gd_where_get_label (GDataGDWhere *self) G_GNUC_PURE; +void gdata_gd_where_set_label (GDataGDWhere *self, const gchar *label); + +G_END_DECLS + +#endif /* !GDATA_GD_WHERE_H */ diff --git a/gdata/gd/gdata-gd-who.c b/gdata/gd/gdata-gd-who.c new file mode 100644 index 0000000..f637ee9 --- /dev/null +++ b/gdata/gd/gdata-gd-who.c @@ -0,0 +1,414 @@ +/* -*- Mode: C; indent-tabs-mode: t; c-basic-offset: 8; tab-width: 8 -*- */ +/* + * GData Client + * Copyright (C) Philip Withnall 2009–2010 + * + * GData Client is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * GData Client is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with GData Client. If not, see . + */ + +/** + * SECTION:gdata-gd-who + * @short_description: GData who element + * @stability: Stable + * @include: gdata/gd/gdata-gd-who.h + * + * #GDataGDWho represents an "who" element from the + * GData specification. + * + * Since: 0.4.0 + */ + +#include +#include + +#include "gdata-gd-who.h" +#include "gdata-parsable.h" +#include "gdata-parser.h" +#include "gdata-comparable.h" + +static void gdata_gd_who_comparable_init (GDataComparableIface *iface); +static void gdata_gd_who_finalize (GObject *object); +static void gdata_gd_who_get_property (GObject *object, guint property_id, GValue *value, GParamSpec *pspec); +static void gdata_gd_who_set_property (GObject *object, guint property_id, const GValue *value, GParamSpec *pspec); +static gboolean pre_parse_xml (GDataParsable *parsable, xmlDoc *doc, xmlNode *root_node, gpointer user_data, GError **error); +/*static gboolean parse_xml (GDataParsable *parsable, xmlDoc *doc, xmlNode *root_node, gpointer user_data, GError **error);*/ +static void pre_get_xml (GDataParsable *parsable, GString *xml_string); +/*static void get_xml (GDataParsable *parsable, GString *xml_string);*/ +static void get_namespaces (GDataParsable *parsable, GHashTable *namespaces); + +struct _GDataGDWhoPrivate { + gchar *relation_type; + gchar *value_string; + gchar *email_address; +}; + +enum { + PROP_RELATION_TYPE = 1, + PROP_VALUE_STRING, + PROP_EMAIL_ADDRESS +}; + +G_DEFINE_TYPE_WITH_CODE (GDataGDWho, gdata_gd_who, GDATA_TYPE_PARSABLE, + G_IMPLEMENT_INTERFACE (GDATA_TYPE_COMPARABLE, gdata_gd_who_comparable_init)) + +static void +gdata_gd_who_class_init (GDataGDWhoClass *klass) +{ + GObjectClass *gobject_class = G_OBJECT_CLASS (klass); + GDataParsableClass *parsable_class = GDATA_PARSABLE_CLASS (klass); + + g_type_class_add_private (klass, sizeof (GDataGDWhoPrivate)); + + gobject_class->get_property = gdata_gd_who_get_property; + gobject_class->set_property = gdata_gd_who_set_property; + gobject_class->finalize = gdata_gd_who_finalize; + + parsable_class->pre_parse_xml = pre_parse_xml; + /*parsable_class->parse_xml = parse_xml;*/ + parsable_class->pre_get_xml = pre_get_xml; + /*parsable_class->get_xml = get_xml;*/ + parsable_class->get_namespaces = get_namespaces; + parsable_class->element_name = "who"; + parsable_class->element_namespace = "gd"; + + /** + * GDataGDWho:relation-type: + * + * Specifies the relationship between the containing entity and the contained person. For example: %GDATA_GD_WHO_EVENT_PERFORMER or + * %GDATA_GD_WHO_EVENT_ATTENDEE. + * + * For more information, see the + * GData specification. + * + * Since: 0.4.0 + */ + g_object_class_install_property (gobject_class, PROP_RELATION_TYPE, + g_param_spec_string ("relation-type", + "Relation type", "Specifies the relationship between the container and the containee.", + NULL, + G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)); + + /** + * GDataGDWho:value-string: + * + * A simple string representation of this person. + * + * For more information, see the + * GData specification. + * + * Since: 0.4.0 + */ + g_object_class_install_property (gobject_class, PROP_VALUE_STRING, + g_param_spec_string ("value-string", + "Value string", "A simple string representation of this person.", + NULL, + G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)); + + /** + * GDataGDWho:email-address: + * + * The e-mail address of the person represented by the #GDataGDWho. + * + * For more information, see the + * GData specification. + * + * Since: 0.4.0 + */ + g_object_class_install_property (gobject_class, PROP_EMAIL_ADDRESS, + g_param_spec_string ("email-address", + "E-mail address", "The e-mail address of the person represented by the #GDataGDWho.", + NULL, + G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)); +} + +static gint +compare_with (GDataComparable *self, GDataComparable *other) +{ + GDataGDWhoPrivate *a = ((GDataGDWho*) self)->priv, *b = ((GDataGDWho*) other)->priv; + + if (g_strcmp0 (a->value_string, b->value_string) == 0 && g_strcmp0 (a->email_address, b->email_address) == 0) + return 0; + return 1; +} + +static void +gdata_gd_who_comparable_init (GDataComparableIface *iface) +{ + iface->compare_with = compare_with; +} + +static void +gdata_gd_who_init (GDataGDWho *self) +{ + self->priv = G_TYPE_INSTANCE_GET_PRIVATE (self, GDATA_TYPE_GD_WHO, GDataGDWhoPrivate); +} + +static void +gdata_gd_who_finalize (GObject *object) +{ + GDataGDWhoPrivate *priv = GDATA_GD_WHO (object)->priv; + + g_free (priv->relation_type); + g_free (priv->value_string); + g_free (priv->email_address); + + /* Chain up to the parent class */ + G_OBJECT_CLASS (gdata_gd_who_parent_class)->finalize (object); +} + +static void +gdata_gd_who_get_property (GObject *object, guint property_id, GValue *value, GParamSpec *pspec) +{ + GDataGDWhoPrivate *priv = GDATA_GD_WHO (object)->priv; + + switch (property_id) { + case PROP_RELATION_TYPE: + g_value_set_string (value, priv->relation_type); + break; + case PROP_VALUE_STRING: + g_value_set_string (value, priv->value_string); + break; + case PROP_EMAIL_ADDRESS: + g_value_set_string (value, priv->email_address); + break; + default: + /* We don't have any other property... */ + G_OBJECT_WARN_INVALID_PROPERTY_ID (object, property_id, pspec); + break; + } +} + +static void +gdata_gd_who_set_property (GObject *object, guint property_id, const GValue *value, GParamSpec *pspec) +{ + GDataGDWho *self = GDATA_GD_WHO (object); + + switch (property_id) { + case PROP_RELATION_TYPE: + gdata_gd_who_set_relation_type (self, g_value_get_string (value)); + break; + case PROP_VALUE_STRING: + gdata_gd_who_set_value_string (self, g_value_get_string (value)); + break; + case PROP_EMAIL_ADDRESS: + gdata_gd_who_set_email_address (self, g_value_get_string (value)); + break; + default: + /* We don't have any other property... */ + G_OBJECT_WARN_INVALID_PROPERTY_ID (object, property_id, pspec); + break; + } +} + +static gboolean +pre_parse_xml (GDataParsable *parsable, xmlDoc *doc, xmlNode *root_node, gpointer user_data, GError **error) +{ + xmlChar *rel, *email; + GDataGDWhoPrivate *priv = GDATA_GD_WHO (parsable)->priv; + + rel = xmlGetProp (root_node, (xmlChar*) "rel"); + if (rel != NULL && *rel == '\0') { + xmlFree (rel); + return gdata_parser_error_required_property_missing (root_node, "rel", error); + } + + email = xmlGetProp (root_node, (xmlChar*) "email"); + if (email != NULL && *email == '\0') { + xmlFree (rel); + xmlFree (email); + return gdata_parser_error_required_property_missing (root_node, "email", error); + } + + priv->relation_type = (gchar*) rel; + priv->value_string = (gchar*) xmlGetProp (root_node, (xmlChar*) "valueString"); + priv->email_address = (gchar*) email; + + return TRUE; +} + +/*static gboolean +parse_xml (GDataParsable *parsable, xmlDoc *doc, xmlNode *node, gpointer user_data, GError **error) +{ + GDataGDWhoPrivate *priv = GDATA_GD_WHO (parsable)->priv; + + TODO: deal with the attendeeType, attendeeStatus and entryLink + + return TRUE; +}*/ + +static void +pre_get_xml (GDataParsable *parsable, GString *xml_string) +{ + GDataGDWhoPrivate *priv = GDATA_GD_WHO (parsable)->priv; + + if (priv->email_address != NULL) + gdata_parser_string_append_escaped (xml_string, " email='", priv->email_address, "'"); + if (priv->relation_type != NULL) + gdata_parser_string_append_escaped (xml_string, " rel='", priv->relation_type, "'"); + if (priv->value_string != NULL) + gdata_parser_string_append_escaped (xml_string, " valueString='", priv->value_string, "'"); +} + +/*static void +get_xml (GDataParsable *parsable, GString *xml_string) +{ + GDataGDWhoPrivate *priv = GDATA_GD_WHO (parsable)->priv; + + TODO: deal with the attendeeType, attendeeStatus and entryLink +}*/ + +static void +get_namespaces (GDataParsable *parsable, GHashTable *namespaces) +{ + g_hash_table_insert (namespaces, (gchar*) "gd", (gchar*) "http://schemas.google.com/g/2005"); +} + +/** + * gdata_gd_who_new: + * @relation_type: (allow-none): the relationship between the item and this person, or %NULL + * @value_string: (allow-none): a string to represent the person, or %NULL + * @email_address: (allow-none): the person's e-mail address, or %NULL + * + * Creates a new #GDataGDWho. More information is available in the GData specification. + * + * Currently, entryLink functionality is not implemented in #GDataGDWho. + * + * Return value: a new #GDataGDWho; unref with g_object_unref() + * + * Since: 0.2.0 + */ +GDataGDWho * +gdata_gd_who_new (const gchar *relation_type, const gchar *value_string, const gchar *email_address) +{ + g_return_val_if_fail (relation_type == NULL || *relation_type != '\0', NULL); + g_return_val_if_fail (email_address == NULL || *email_address != '\0', NULL); + return g_object_new (GDATA_TYPE_GD_WHO, "relation-type", relation_type, "value-string", value_string, "email-address", email_address, NULL); +} + +/** + * gdata_gd_who_get_relation_type: + * @self: a #GDataGDWho + * + * Gets the #GDataGDWho:relation-type property. + * + * Return value: the relation type, or %NULL + * + * Since: 0.4.0 + */ +const gchar * +gdata_gd_who_get_relation_type (GDataGDWho *self) +{ + g_return_val_if_fail (GDATA_IS_GD_WHO (self), NULL); + return self->priv->relation_type; +} + +/** + * gdata_gd_who_set_relation_type: + * @self: a #GDataGDWho + * @relation_type: (allow-none): the new relation type, or %NULL + * + * Sets the #GDataGDWho:relation-type property to @relation_type. + * + * Set @relation_type to %NULL to unset the property. + * + * Since: 0.4.0 + */ +void +gdata_gd_who_set_relation_type (GDataGDWho *self, const gchar *relation_type) +{ + g_return_if_fail (GDATA_IS_GD_WHO (self)); + g_return_if_fail (relation_type == NULL || *relation_type != '\0'); + + g_free (self->priv->relation_type); + self->priv->relation_type = g_strdup (relation_type); + g_object_notify (G_OBJECT (self), "relation-type"); +} + +/** + * gdata_gd_who_get_value_string: + * @self: a #GDataGDWho + * + * Gets the #GDataGDWho:value-string property. + * + * Return value: the value string, or %NULL + * + * Since: 0.4.0 + */ +const gchar * +gdata_gd_who_get_value_string (GDataGDWho *self) +{ + g_return_val_if_fail (GDATA_IS_GD_WHO (self), NULL); + return self->priv->value_string; +} + +/** + * gdata_gd_who_set_value_string: + * @self: a #GDataGDWho + * @value_string: (allow-none): the new value string, or %NULL + * + * Sets the #GDataGDWho:value-string property to @value_string. + * + * Set @value_string to %NULL to unset the property. + * + * Since: 0.4.0 + */ +void +gdata_gd_who_set_value_string (GDataGDWho *self, const gchar *value_string) +{ + g_return_if_fail (GDATA_IS_GD_WHO (self)); + + g_free (self->priv->value_string); + self->priv->value_string = g_strdup (value_string); + g_object_notify (G_OBJECT (self), "value-string"); +} + +/** + * gdata_gd_who_get_email_address: + * @self: a #GDataGDWho + * + * Gets the #GDataGDWho:email-address property. + * + * Return value: the e-mail address, or %NULL + * + * Since: 0.4.0 + */ +const gchar * +gdata_gd_who_get_email_address (GDataGDWho *self) +{ + g_return_val_if_fail (GDATA_IS_GD_WHO (self), NULL); + return self->priv->email_address; +} + +/** + * gdata_gd_who_set_email_address: + * @self: a #GDataGDWho + * @email_address: (allow-none): the new e-mail address, or %NULL + * + * Sets the #GDataGDWho:email-address property to @email_address. + * + * Set @email_address to %NULL to unset the property. + * + * Since: 0.4.0 + */ +void +gdata_gd_who_set_email_address (GDataGDWho *self, const gchar *email_address) +{ + g_return_if_fail (GDATA_IS_GD_WHO (self)); + g_return_if_fail (email_address == NULL || *email_address != '\0'); + + g_free (self->priv->email_address); + self->priv->email_address = g_strdup (email_address); + g_object_notify (G_OBJECT (self), "email-address"); +} diff --git a/gdata/gd/gdata-gd-who.h b/gdata/gd/gdata-gd-who.h new file mode 100644 index 0000000..00a5cc6 --- /dev/null +++ b/gdata/gd/gdata-gd-who.h @@ -0,0 +1,122 @@ +/* -*- Mode: C; indent-tabs-mode: t; c-basic-offset: 8; tab-width: 8 -*- */ +/* + * GData Client + * Copyright (C) Philip Withnall 2009–2010 + * + * GData Client is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * GData Client is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with GData Client. If not, see . + */ + +#ifndef GDATA_GD_WHO_H +#define GDATA_GD_WHO_H + +#include +#include + +#include + +G_BEGIN_DECLS + +/** + * GDATA_GD_WHO_EVENT_ATTENDEE: + * + * The relation type URI for a general meeting or event attendee. + * + * Since: 0.7.0 + */ +#define GDATA_GD_WHO_EVENT_ATTENDEE "http://schemas.google.com/g/2005#event.attendee" + +/** + * GDATA_GD_WHO_EVENT_ORGANIZER: + * + * The relation type URI for an event organizer (not necessarily an attendee). + * + * Since: 0.7.0 + */ +#define GDATA_GD_WHO_EVENT_ORGANIZER "http://schemas.google.com/g/2005#event.organizer" + +/** + * GDATA_GD_WHO_EVENT_PERFORMER: + * + * The relation type URI for an event performer, which is similar to %GDATA_GD_WHO_EVENT_SPEAKER, but with more emphasis on art rather than speaking. + * + * Since: 0.7.0 + */ +#define GDATA_GD_WHO_EVENT_PERFORMER "http://schemas.google.com/g/2005#event.performer" + +/** + * GDATA_GD_WHO_EVENT_SPEAKER: + * + * The relation type URI for a speaker at an event. + * + * Since: 0.7.0 + */ +#define GDATA_GD_WHO_EVENT_SPEAKER "http://schemas.google.com/g/2005#event.speaker" + +/* TODO: Message kind relation types (http://code.google.com/apis/gdata/docs/2.0/elements.html#gdWho) */ + +#define GDATA_TYPE_GD_WHO (gdata_gd_who_get_type ()) +#define GDATA_GD_WHO(o) (G_TYPE_CHECK_INSTANCE_CAST ((o), GDATA_TYPE_GD_WHO, GDataGDWho)) +#define GDATA_GD_WHO_CLASS(k) (G_TYPE_CHECK_CLASS_CAST((k), GDATA_TYPE_GD_WHO, GDataGDWhoClass)) +#define GDATA_IS_GD_WHO(o) (G_TYPE_CHECK_INSTANCE_TYPE ((o), GDATA_TYPE_GD_WHO)) +#define GDATA_IS_GD_WHO_CLASS(k) (G_TYPE_CHECK_CLASS_TYPE ((k), GDATA_TYPE_GD_WHO)) +#define GDATA_GD_WHO_GET_CLASS(o) (G_TYPE_INSTANCE_GET_CLASS ((o), GDATA_TYPE_GD_WHO, GDataGDWhoClass)) + +typedef struct _GDataGDWhoPrivate GDataGDWhoPrivate; + +/** + * GDataGDWho: + * + * All the fields in the #GDataGDWho structure are private and should never be accessed directly. + * + * Since: 0.2.0 + */ +typedef struct { + GDataParsable parent; + GDataGDWhoPrivate *priv; +} GDataGDWho; + +/** + * GDataGDWhoClass: + * + * All the fields in the #GDataGDWhoClass structure are private and should never be accessed directly. + * + * Since: 0.4.0 + */ +typedef struct { + /*< private >*/ + GDataParsableClass parent; + + /*< private >*/ + /* Padding for future expansion */ + void (*_g_reserved0) (void); + void (*_g_reserved1) (void); +} GDataGDWhoClass; + +GType gdata_gd_who_get_type (void) G_GNUC_CONST; + +GDataGDWho *gdata_gd_who_new (const gchar *relation_type, const gchar *value_string, + const gchar *email_address) G_GNUC_WARN_UNUSED_RESULT G_GNUC_MALLOC; + +const gchar *gdata_gd_who_get_relation_type (GDataGDWho *self) G_GNUC_PURE; +void gdata_gd_who_set_relation_type (GDataGDWho *self, const gchar *relation_type); + +const gchar *gdata_gd_who_get_value_string (GDataGDWho *self) G_GNUC_PURE; +void gdata_gd_who_set_value_string (GDataGDWho *self, const gchar *value_string); + +const gchar *gdata_gd_who_get_email_address (GDataGDWho *self) G_GNUC_PURE; +void gdata_gd_who_set_email_address (GDataGDWho *self, const gchar *email_address); + +G_END_DECLS + +#endif /* !GDATA_GD_WHO_H */ diff --git a/gdata/gd/meson.build b/gdata/gd/meson.build new file mode 100644 index 0000000..40a9784 --- /dev/null +++ b/gdata/gd/meson.build @@ -0,0 +1,33 @@ +headers = files( + 'gdata-gd-email-address.h', + 'gdata-gd-im-address.h', + 'gdata-gd-name.h', + 'gdata-gd-organization.h', + 'gdata-gd-phone-number.h', + 'gdata-gd-postal-address.h', + 'gdata-gd-reminder.h', + 'gdata-gd-when.h', + 'gdata-gd-where.h', + 'gdata-gd-who.h', +) + +install_headers( + headers, + subdir: gdata_include_subdir / 'gd', +) + +gir_headers += headers + +sources += files( + 'gdata-gd-email-address.c', + 'gdata-gd-feed-link.c', + 'gdata-gd-im-address.c', + 'gdata-gd-name.c', + 'gdata-gd-organization.c', + 'gdata-gd-phone-number.c', + 'gdata-gd-postal-address.c', + 'gdata-gd-reminder.c', + 'gdata-gd-when.c', + 'gdata-gd-where.c', + 'gdata-gd-who.c', +) diff --git a/gdata/gdata-access-handler.c b/gdata/gdata-access-handler.c new file mode 100644 index 0000000..8b044ec --- /dev/null +++ b/gdata/gdata-access-handler.c @@ -0,0 +1,251 @@ +/* -*- Mode: C; indent-tabs-mode: t; c-basic-offset: 8; tab-width: 8 -*- */ +/* + * GData Client + * Copyright (C) Philip Withnall 2009–2010, 2015 + * Copyright (C) Red Hat, Inc. 2015 + * + * GData Client is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * GData Client is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with GData Client. If not, see . + */ + +/** + * SECTION:gdata-access-handler + * @short_description: GData access handler interface + * @stability: Stable + * @include: gdata/gdata-access-handler.h + * + * #GDataAccessHandler is an interface which can be implemented by #GDataEntrys which can have their permissions controlled by an + * access control list (ACL). It has a set of methods which allow the #GDataAccessRules for the access handler/entry to be retrieved, + * added, modified and deleted, with immediate effect. + * + * For an example of inserting an access rule into an ACL, see the documentation for #GDataAccessRule. + * + * When implementing the interface, classes must implement an is_owner_rule function. It's optional to implement a + * get_authorization_domain function, but if it's not implemented, any operations on the access handler's + * #GDataAccessRules will be performed unauthorized (i.e. as if by a non-logged-in user). This will not usually work. + * + * Since: 0.3.0 + */ + +#include +#include +#include +#include + +#include "gdata-access-handler.h" +#include "gdata-private.h" +#include "gdata-access-rule.h" + +static GDataFeed * +gdata_access_handler_real_get_rules (GDataAccessHandler *self, + GDataService *service, + GCancellable *cancellable, + GDataQueryProgressCallback progress_callback, + gpointer progress_user_data, + GError **error); + +typedef GDataAccessHandlerIface GDataAccessHandlerInterface; +G_DEFINE_INTERFACE (GDataAccessHandler, gdata_access_handler, + GDATA_TYPE_ENTRY); + +static void +gdata_access_handler_default_init (GDataAccessHandlerInterface *iface) +{ + iface->get_rules = gdata_access_handler_real_get_rules; +} + +typedef struct { + GDataService *service; + GDataQueryProgressCallback progress_callback; + gpointer progress_user_data; + GDestroyNotify destroy_progress_user_data; +} GetRulesAsyncData; + +static void +get_rules_async_data_free (GetRulesAsyncData *self) +{ + if (self->service != NULL) + g_object_unref (self->service); + + g_slice_free (GetRulesAsyncData, self); +} + +static GDataFeed * +gdata_access_handler_real_get_rules (GDataAccessHandler *self, + GDataService *service, + GCancellable *cancellable, + GDataQueryProgressCallback progress_callback, + gpointer progress_user_data, + GError **error) +{ + GDataAccessHandlerIface *iface; + GDataAuthorizationDomain *domain = NULL; + GDataFeed *feed; + GDataLink *_link; + SoupMessage *message; + SoupMessageHeaders *headers; + const gchar *content_type; + + _link = gdata_entry_look_up_link (GDATA_ENTRY (self), GDATA_LINK_ACCESS_CONTROL_LIST); + g_assert (_link != NULL); + + iface = GDATA_ACCESS_HANDLER_GET_IFACE (self); + if (iface->get_authorization_domain != NULL) { + domain = iface->get_authorization_domain (self); + } + + message = _gdata_service_query (service, domain, gdata_link_get_uri (_link), NULL, cancellable, error); + if (message == NULL) { + return NULL; + } + + g_assert (message->response_body->data != NULL); + + headers = message->response_headers; + content_type = soup_message_headers_get_content_type (headers, NULL); + + if (g_strcmp0 (content_type, "application/json") == 0) { + /* Definitely JSON. */ + g_debug("JSON content type detected."); + feed = _gdata_feed_new_from_json (GDATA_TYPE_FEED, message->response_body->data, message->response_body->length, GDATA_TYPE_ACCESS_RULE, + progress_callback, progress_user_data, error); + } else { + /* Potentially XML. Don't bother checking the Content-Type, since the parser + * will fail gracefully if the response body is not valid XML. */ + g_debug("XML content type detected."); + feed = _gdata_feed_new_from_xml (GDATA_TYPE_FEED, message->response_body->data, message->response_body->length, GDATA_TYPE_ACCESS_RULE, + progress_callback, progress_user_data, error); + } + + g_object_unref (message); + + return feed; +} + +static void +get_rules_thread (GTask *task, gpointer source_object, gpointer task_data, GCancellable *cancellable) +{ + GDataAccessHandler *access_handler = GDATA_ACCESS_HANDLER (source_object); + GDataAccessHandlerIface *iface; + g_autoptr(GError) error = NULL; + g_autoptr(GDataFeed) feed = NULL; + GetRulesAsyncData *data = task_data; + + /* Execute the query and return */ + iface = GDATA_ACCESS_HANDLER_GET_IFACE (access_handler); + g_assert (iface->get_rules != NULL); + + feed = iface->get_rules (access_handler, data->service, + cancellable, data->progress_callback, + data->progress_user_data, &error); + + if (feed == NULL && error != NULL) + g_task_return_error (task, g_steal_pointer (&error)); + else + g_task_return_pointer (task, g_steal_pointer (&feed), g_object_unref); + + if (data->destroy_progress_user_data != NULL) { + data->destroy_progress_user_data (data->progress_user_data); + } +} + +/** + * gdata_access_handler_get_rules_async: + * @self: a #GDataAccessHandler + * @service: a #GDataService + * @cancellable: (allow-none): optional #GCancellable object, or %NULL + * @progress_callback: (allow-none) (closure progress_user_data): a #GDataQueryProgressCallback to call when a rule is loaded, or %NULL + * @progress_user_data: (closure): data to pass to the @progress_callback function + * @destroy_progress_user_data: (allow-none): the function to call when @progress_callback will not be called any more, or %NULL. This function will be + * called with @progress_user_data as a parameter and can be used to free any memory allocated for it. + * @callback: a #GAsyncReadyCallback to call when the query is finished + * @user_data: (closure): data to pass to the @callback function + * + * Retrieves a #GDataFeed containing all the access rules which apply to the given #GDataAccessHandler. Only the owner of a #GDataAccessHandler may + * view its rule feed. @self and @service are both reffed when this function is called, so can safely be unreffed after this function returns. + * + * For more details, see gdata_access_handler_get_rules(), which is the synchronous version of this function, and gdata_service_query_async(), which + * is the base asynchronous query function. + * + * When the operation is finished, @callback will be called. You can then call gdata_service_query_finish() + * to get the results of the operation. + * + * Since: 0.9.1 + */ +void +gdata_access_handler_get_rules_async (GDataAccessHandler *self, GDataService *service, GCancellable *cancellable, + GDataQueryProgressCallback progress_callback, gpointer progress_user_data, + GDestroyNotify destroy_progress_user_data, + GAsyncReadyCallback callback, gpointer user_data) +{ + g_autoptr(GTask) task = NULL; + GetRulesAsyncData *data; + + g_return_if_fail (GDATA_IS_ACCESS_HANDLER (self)); + g_return_if_fail (GDATA_IS_SERVICE (service)); + g_return_if_fail (cancellable == NULL || G_IS_CANCELLABLE (cancellable)); + g_return_if_fail (callback != NULL); + + data = g_slice_new (GetRulesAsyncData); + data->service = g_object_ref (service); + data->progress_callback = progress_callback; + data->progress_user_data = progress_user_data; + data->destroy_progress_user_data = destroy_progress_user_data; + + task = g_task_new (self, cancellable, callback, user_data); + g_task_set_source_tag (task, gdata_service_query_async); + g_task_set_task_data (task, g_steal_pointer (&data), (GDestroyNotify) get_rules_async_data_free); + g_task_run_in_thread (task, get_rules_thread); +} + +/** + * gdata_access_handler_get_rules: + * @self: a #GDataAccessHandler + * @service: a #GDataService + * @cancellable: (allow-none): optional #GCancellable object, or %NULL + * @progress_callback: (allow-none) (scope call) (closure progress_user_data): a #GDataQueryProgressCallback to call when a rule is loaded, or %NULL + * @progress_user_data: (closure): data to pass to the @progress_callback function + * @error: a #GError, or %NULL + * + * Retrieves a #GDataFeed containing all the access rules which apply to the given #GDataAccessHandler. Only the owner of a #GDataAccessHandler may + * view its rule feed. + * + * If @cancellable is not %NULL, then the operation can be cancelled by triggering the @cancellable object from another thread. + * If the operation was cancelled, the error %G_IO_ERROR_CANCELLED will be returned. + * + * A %GDATA_SERVICE_ERROR_PROTOCOL_ERROR will be returned if the server indicates there is a problem with the query. + * + * For each rule in the response feed, @progress_callback will be called in the main thread. If there was an error parsing the XML response, + * a #GDataParserError will be returned. + * + * Return value: (transfer full): a #GDataFeed of access control rules, or %NULL; unref with g_object_unref() + * + * Since: 0.3.0 + */ +GDataFeed * +gdata_access_handler_get_rules (GDataAccessHandler *self, GDataService *service, GCancellable *cancellable, + GDataQueryProgressCallback progress_callback, gpointer progress_user_data, GError **error) +{ + GDataAccessHandlerIface *iface; + + g_return_val_if_fail (GDATA_IS_ACCESS_HANDLER (self), NULL); + g_return_val_if_fail (GDATA_IS_SERVICE (service), NULL); + g_return_val_if_fail (cancellable == NULL || G_IS_CANCELLABLE (cancellable), NULL); + g_return_val_if_fail (error == NULL || *error == NULL, NULL); + + iface = GDATA_ACCESS_HANDLER_GET_IFACE (self); + g_assert (iface->get_rules != NULL); + + return iface->get_rules (self, service, cancellable, progress_callback, + progress_user_data, error); +} diff --git a/gdata/gdata-access-handler.h b/gdata/gdata-access-handler.h new file mode 100644 index 0000000..eff96c3 --- /dev/null +++ b/gdata/gdata-access-handler.h @@ -0,0 +1,109 @@ +/* -*- Mode: C; indent-tabs-mode: t; c-basic-offset: 8; tab-width: 8 -*- */ +/* + * GData Client + * Copyright (C) Philip Withnall 2009, 2015 + * + * GData Client is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * GData Client is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with GData Client. If not, see . + */ + +#ifndef GDATA_ACCESS_HANDLER_H +#define GDATA_ACCESS_HANDLER_H + +#include +#include + +#include +#include +#include +#include + +G_BEGIN_DECLS + +/** + * GDATA_LINK_ACCESS_CONTROL_LIST: + * + * The relation type URI of the access control list location for this resource. + * + * For more information, see the + * ACL specification. + * + * Since: 0.7.0 + */ +#define GDATA_LINK_ACCESS_CONTROL_LIST "http://schemas.google.com/acl/2007#accessControlList" + +#define GDATA_TYPE_ACCESS_HANDLER (gdata_access_handler_get_type ()) +#define GDATA_ACCESS_HANDLER(o) (G_TYPE_CHECK_INSTANCE_CAST ((o), GDATA_TYPE_ACCESS_HANDLER, GDataAccessHandler)) +#define GDATA_ACCESS_HANDLER_CLASS(k) (G_TYPE_CHECK_CLASS_CAST((k), GDATA_TYPE_ACCESS_HANDLER, GDataAccessHandlerIface)) +#define GDATA_IS_ACCESS_HANDLER(o) (G_TYPE_CHECK_INSTANCE_TYPE ((o), GDATA_TYPE_ACCESS_HANDLER)) +#define GDATA_ACCESS_HANDLER_GET_IFACE(o) (G_TYPE_INSTANCE_GET_INTERFACE ((o), GDATA_TYPE_ACCESS_HANDLER, GDataAccessHandlerIface)) + +/** + * GDataAccessHandler: + * + * All the fields in the #GDataAccessHandler structure are private and should never be accessed directly. + * + * Since: 0.3.0 + */ +typedef struct _GDataAccessHandler GDataAccessHandler; /* dummy typedef */ + +/** + * GDataAccessHandlerIface: + * @parent: the parent type + * @is_owner_rule: a function to return whether the given #GDataAccessRule has the role of an owner (of a #GDataAccessHandler). + * @get_authorization_domain: (allow-none): a function to return the #GDataAuthorizationDomain to be used for all operations on the access rules + * belonging to this access handler; not implementing this function is equivalent to returning %NULL from it, which signifies that operations on the + * access rules don't require authorization; new in version 0.9.0 + * @get_rules: (nullable): a function to query, parse and return a #GDataFeed of + * #GDataAccessRules for a given entry — the virtual function for + * gdata_access_handler_get_rules(); new in version 0.17.2 + * + * The class structure for the #GDataAccessHandler interface. + * + * Since: 0.9.0 + */ +typedef struct { + GTypeInterface parent; + + gboolean (*is_owner_rule) (GDataAccessRule *rule); + GDataAuthorizationDomain *(*get_authorization_domain) (GDataAccessHandler *self); + + GDataFeed *(*get_rules) (GDataAccessHandler *self, + GDataService *service, + GCancellable *cancellable, + GDataQueryProgressCallback progress_callback, + gpointer progress_user_data, + GError **error); + + /*< private >*/ + /* Padding for future expansion */ + void (*_g_reserved1) (void); + void (*_g_reserved2) (void); + void (*_g_reserved3) (void); + void (*_g_reserved4) (void); + void (*_g_reserved5) (void); +} GDataAccessHandlerIface; + +GType gdata_access_handler_get_type (void) G_GNUC_CONST; + +GDataFeed *gdata_access_handler_get_rules (GDataAccessHandler *self, GDataService *service, GCancellable *cancellable, + GDataQueryProgressCallback progress_callback, gpointer progress_user_data, + GError **error) G_GNUC_WARN_UNUSED_RESULT G_GNUC_MALLOC; +void gdata_access_handler_get_rules_async (GDataAccessHandler *self, GDataService *service, GCancellable *cancellable, + GDataQueryProgressCallback progress_callback, gpointer progress_user_data, + GDestroyNotify destroy_progress_user_data, + GAsyncReadyCallback callback, gpointer user_data); + +G_END_DECLS + +#endif /* !GDATA_ACCESS_HANDLER_H */ diff --git a/gdata/gdata-access-rule.c b/gdata/gdata-access-rule.c new file mode 100644 index 0000000..ae501ec --- /dev/null +++ b/gdata/gdata-access-rule.c @@ -0,0 +1,661 @@ +/* -*- Mode: C; indent-tabs-mode: t; c-basic-offset: 8; tab-width: 8 -*- */ +/* + * GData Client + * Copyright (C) Thibault Saunier 2009 + * Copyright (C) Philip Withnall 2009–2010, 2014 + * Copyright (C) Red Hat, Inc. 2015 + * + * GData Client is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * GData Client is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with GData Client. If not, see . + */ + +/** + * SECTION:gdata-access-rule + * @short_description: GData access rule object + * @stability: Stable + * @include: gdata/gdata-access-rule.h + * + * #GDataAccessRule is a subclass of #GDataEntry to represent a generic access rule from an access control list (ACL). + * It is returned by the ACL methods implemented in the #GDataAccessHandler interface. + * + * Access rules should be inserted to the %GDATA_LINK_ACCESS_CONTROL_LIST URI of the feed or entry they should be applied to. This will return a + * %GDATA_SERVICE_ERROR_CONFLICT error if a rule already exists on that feed or entry for that scope type and value. + * + * + * Adding a Rule to the Access Control List for an Entry + * + * GDataAuthorizationDomain *domain; + * GDataService *service; + * GDataEntry *entry; + * GDataFeed *acl_feed; + * GDataAccessRule *rule, *new_rule; + * GError *error = NULL; + * + * domain = gdata_documents_service_get_primary_authorization_domain (); + * + * /* Retrieve a GDataEntry which will have a new rule inserted into its ACL. */ + * service = build_my_service (); + * entry = get_the_entry (service); + * + * /* Create and insert a new access rule for example@gmail.com which grants them _no_ permissions on the entry. + * * In a real application, the GDataEntry subclass would define its own access roles which are more useful. For example, + * * GDataDocumentsEntry defines access roles for users who can read (but not write) a Google Document, and users who + * * can also write to the document. */ + * rule = gdata_access_rule_new (NULL); + * gdata_access_rule_set_role (rule, GDATA_ACCESS_ROLE_NONE); /* or, for example, GDATA_DOCUMENTS_ACCESS_ROLE_READER */ + * gdata_access_rule_set_scope (rule, GDATA_ACCESS_SCOPE_USER, "example@gmail.com"); /* e-mail address of the user the ACL applies to */ + * + * acl_link = gdata_entry_look_up_link (entry, GDATA_LINK_ACCESS_CONTROL_LIST); + * new_rule = GDATA_ACCESS_RULE (gdata_service_insert_entry (GDATA_SERVICE (service), domain, gdata_link_get_uri (acl_link), + * GDATA_ENTRY (rule), NULL, &error)); + * + * g_object_unref (rule); + * g_object_unref (entry); + * g_object_unref (service); + * + * if (error != NULL) { + * g_error ("Error inserting access rule: %s", error->message); + * g_error_free (error); + * return; + * } + * + * /* Potentially do something with the new_rule here, such as store its ID for later use. */ + * + * g_object_unref (new_rule); + * + * + * + * Since: 0.3.0 + */ + +#include +#include +#include +#include + +#include "gdata-access-rule.h" +#include "gdata-parser.h" +#include "gdata-types.h" +#include "gdata-private.h" + +static GObject *gdata_access_rule_constructor (GType type, guint n_construct_params, GObjectConstructParam *construct_params); +static void gdata_access_rule_finalize (GObject *object); +static void get_namespaces (GDataParsable *parsable, GHashTable *namespaces); +static void get_xml (GDataParsable *parsable, GString *xml_string); +static void gdata_access_rule_set_property (GObject *object, guint property_id, const GValue *value, GParamSpec *pspec); +static void gdata_access_rule_get_property (GObject *object, guint property_id, GValue *value, GParamSpec *pspec); +static gboolean parse_xml (GDataParsable *parsable, xmlDoc *doc, xmlNode *node, gpointer user_data, GError **error); +static gboolean post_parse_xml (GDataParsable *parsable, gpointer user_data, GError **error); + +struct _GDataAccessRulePrivate { + gchar *role; + gchar *scope_type; + gchar *scope_value; + gint64 edited; + gchar *key; +}; + +enum { + PROP_ROLE = 1, + PROP_SCOPE_TYPE, + PROP_SCOPE_VALUE, + PROP_EDITED, + PROP_ETAG, + PROP_KEY, +}; + +G_DEFINE_TYPE (GDataAccessRule, gdata_access_rule, GDATA_TYPE_ENTRY) + +static void +gdata_access_rule_class_init (GDataAccessRuleClass *klass) +{ + GObjectClass *gobject_class = G_OBJECT_CLASS (klass); + GDataParsableClass *parsable_class = GDATA_PARSABLE_CLASS (klass); + GDataEntryClass *entry_class = GDATA_ENTRY_CLASS (klass); + + g_type_class_add_private (klass, sizeof (GDataAccessRulePrivate)); + + gobject_class->constructor = gdata_access_rule_constructor; + gobject_class->finalize = gdata_access_rule_finalize; + gobject_class->get_property = gdata_access_rule_get_property; + gobject_class->set_property = gdata_access_rule_set_property; + + parsable_class->parse_xml = parse_xml; + parsable_class->post_parse_xml = post_parse_xml; + parsable_class->get_xml = get_xml; + parsable_class->get_namespaces = get_namespaces; + + entry_class->kind_term = "http://schemas.google.com/acl/2007#accessRule"; + + /** + * GDataAccessRule:role: + * + * The role of the person concerned by this ACL. By default, this can only be %GDATA_ACCESS_ROLE_NONE. Services may extend it with + * their own namespaced roles. + * + * Since: 0.3.0 + */ + g_object_class_install_property (gobject_class, PROP_ROLE, + g_param_spec_string ("role", + "Role", "The role of the person concerned by this ACL.", + GDATA_ACCESS_ROLE_NONE, + G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)); + + /** + * GDataAccessRule:scope-type: + * + * Specifies to whom this access rule applies. For example, %GDATA_ACCESS_SCOPE_USER or %GDATA_ACCESS_SCOPE_DEFAULT. + * + * Since: 0.3.0 + */ + g_object_class_install_property (gobject_class, PROP_SCOPE_TYPE, + g_param_spec_string ("scope-type", + "Scope type", "Specifies to whom this access rule applies.", + GDATA_ACCESS_SCOPE_DEFAULT, + G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)); + + /** + * GDataAccessRule:scope-value: + * + * A value representing the user who is represented by the access rule, such as an + * e-mail address for users, or a domain name for domains. + * + * This must be %NULL if and only if #GDataAccessRule:scope-type is %GDATA_ACCESS_SCOPE_DEFAULT. + * + * Since: 0.3.0 + */ + g_object_class_install_property (gobject_class, PROP_SCOPE_VALUE, + g_param_spec_string ("scope-value", + "Scope value", "The scope value for this access rule.", + NULL, + G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)); + + /** + * GDataAccessRule:edited: + * + * The last time the access rule was edited. If the rule has not been edited yet, the content indicates the time it was created. + * + * For more information, see the + * Atom Publishing Protocol specification. + * + * Since: 0.7.0 + */ + g_object_class_install_property (gobject_class, PROP_EDITED, + g_param_spec_int64 ("edited", + "Edited", "The last time the access rule was edited.", + -1, G_MAXINT64, -1, + G_PARAM_READABLE | G_PARAM_STATIC_STRINGS)); + + /** + * GDataAccessRule:key: + * + * An optional authorisation key required to access this item with the given scope. If set, this restricts + * access to those principals who have a copy of the key. The key is generated server-side and cannot be + * modified by the client. If no authorisation key is set (and hence none is needed for access to the item), + * this will be %NULL. + * + * Since: 0.16.0 + */ + g_object_class_install_property (gobject_class, PROP_KEY, + g_param_spec_string ("key", + "Key", "An optional authorisation key required to access this item.", + NULL, + G_PARAM_READABLE | G_PARAM_STATIC_STRINGS)); + + /* Override the ETag property since ETags don't seem to be supported for ACL entries. TODO: Investigate this further (might only be + * unsupported for Google Calendar). */ + g_object_class_override_property (gobject_class, PROP_ETAG, "etag"); +} + +static void notify_role_cb (GDataAccessRule *self, GParamSpec *pspec, gpointer user_data); + +static void +notify_title_cb (GDataAccessRule *self, GParamSpec *pspec, gpointer user_data) +{ + /* Update GDataAccessRule:role */ + g_signal_handlers_block_by_func (self, notify_role_cb, self); + gdata_access_rule_set_role (self, gdata_entry_get_title (GDATA_ENTRY (self))); + g_signal_handlers_unblock_by_func (self, notify_role_cb, self); +} + +static void +notify_role_cb (GDataAccessRule *self, GParamSpec *pspec, gpointer user_data) +{ + /* Update GDataEntry:title */ + g_signal_handlers_block_by_func (self, notify_title_cb, self); + gdata_entry_set_title (GDATA_ENTRY (self), gdata_access_rule_get_role (self)); + g_signal_handlers_unblock_by_func (self, notify_title_cb, self); +} + +static void +gdata_access_rule_init (GDataAccessRule *self) +{ + self->priv = G_TYPE_INSTANCE_GET_PRIVATE (self, GDATA_TYPE_ACCESS_RULE, GDataAccessRulePrivate); + self->priv->edited = -1; + + /* Listen to change notifications for the entry's title, since it's linked to GDataAccessRule:role */ + g_signal_connect (self, "notify::title", (GCallback) notify_title_cb, self); + g_signal_connect (self, "notify::role", (GCallback) notify_role_cb, self); +} + +static GObject * +gdata_access_rule_constructor (GType type, guint n_construct_params, GObjectConstructParam *construct_params) +{ + GObject *object; + + /* Chain up to the parent class */ + object = G_OBJECT_CLASS (gdata_access_rule_parent_class)->constructor (type, n_construct_params, construct_params); + + /* We can't create these in init, or they would collide with the group and control created when parsing the XML */ + if (_gdata_parsable_is_constructed_from_xml (GDATA_PARSABLE (object)) == FALSE) { + GDataAccessRulePrivate *priv = GDATA_ACCESS_RULE (object)->priv; + GTimeVal time_val; + + /* Set the edited property to the current time (creation time). We don't do this in *_init() since that would cause + * setting it from parse_xml() to fail (duplicate element). */ + g_get_current_time (&time_val); + priv->edited = time_val.tv_sec; + + /* Set up the role and scope type */ + priv->role = g_strdup (GDATA_ACCESS_ROLE_NONE); + priv->scope_type = g_strdup (GDATA_ACCESS_SCOPE_DEFAULT); + } + + return object; +} + +static void +gdata_access_rule_finalize (GObject *object) +{ + GDataAccessRulePrivate *priv = GDATA_ACCESS_RULE (object)->priv; + + g_free (priv->role); + g_free (priv->scope_type); + g_free (priv->scope_value); + g_free (priv->key); + + /* Chain up to the parent class */ + G_OBJECT_CLASS (gdata_access_rule_parent_class)->finalize (object); +} + +static void +gdata_access_rule_get_property (GObject *object, guint property_id, GValue *value, GParamSpec *pspec) +{ + GDataAccessRulePrivate *priv = GDATA_ACCESS_RULE (object)->priv; + + switch (property_id) { + case PROP_ROLE: + g_value_set_string (value, priv->role); + break; + case PROP_SCOPE_TYPE: + g_value_set_string (value, priv->scope_type); + break; + case PROP_SCOPE_VALUE: + g_value_set_string (value, priv->scope_value); + break; + case PROP_EDITED: + g_value_set_int64 (value, priv->edited); + break; + case PROP_ETAG: + /* Never return an ETag */ + g_value_set_string (value, NULL); + break; + case PROP_KEY: + g_value_set_string (value, priv->key); + break; + default: + /* We don't have any other property... */ + G_OBJECT_WARN_INVALID_PROPERTY_ID (object, property_id, pspec); + break; + } +} + +static void +gdata_access_rule_set_property (GObject *object, guint property_id, const GValue *value, GParamSpec *pspec) +{ + GDataAccessRule *self = GDATA_ACCESS_RULE (object); + + switch (property_id) { + case PROP_ROLE: + gdata_access_rule_set_role (self, g_value_get_string (value)); + break; + case PROP_SCOPE_TYPE: + g_free (self->priv->scope_type); + self->priv->scope_type = g_value_dup_string (value); + g_object_notify (object, "scope-type"); + break; + case PROP_SCOPE_VALUE: + g_free (self->priv->scope_value); + self->priv->scope_value = g_value_dup_string (value); + g_object_notify (object, "scope-value"); + break; + case PROP_ETAG: + /* Never set an ETag (note that this doesn't stop it being set in GDataEntry due to XML parsing) */ + break; + case PROP_KEY: + /* Read only; fall through */ + default: + /* We don't have any other property... */ + G_OBJECT_WARN_INVALID_PROPERTY_ID (object, property_id, pspec); + break; + } +} + +static gboolean +parse_xml (GDataParsable *parsable, xmlDoc *doc, xmlNode *node, gpointer user_data, GError **error) +{ + gboolean success; + GDataAccessRule *self = GDATA_ACCESS_RULE (parsable); + + if (gdata_parser_is_namespace (node, "http://www.w3.org/2007/app") == TRUE && + gdata_parser_int64_time_from_element (node, "edited", P_REQUIRED | P_NO_DUPES, &(self->priv->edited), &success, error) == TRUE) { + return success; + } else if (gdata_parser_is_namespace (node, "http://schemas.google.com/acl/2007") == TRUE) { + if (xmlStrcmp (node->name, (xmlChar*) "role") == 0) { + /* gAcl:role */ + xmlChar *role = xmlGetProp (node, (xmlChar*) "value"); + if (role == NULL || *role == '\0') { + xmlFree (role); + return gdata_parser_error_required_property_missing (node, "value", error); + } + self->priv->role = (gchar*) role; + } else if (xmlStrcmp (node->name, (xmlChar*) "scope") == 0) { + /* gAcl:scope */ + xmlChar *scope_type, *scope_value; + + scope_type = xmlGetProp (node, (xmlChar*) "type"); + if (scope_type == NULL || *scope_type == '\0') { + xmlFree (scope_type); + return gdata_parser_error_required_property_missing (node, "type", error); + } + + scope_value = xmlGetProp (node, (xmlChar*) "value"); + + /* The @value property is required for all scope types except "default". + * See: https://developers.google.com/google-apps/calendar/v2/reference#gacl_reference */ + if (xmlStrcmp (scope_type, (xmlChar*) GDATA_ACCESS_SCOPE_DEFAULT) != 0 && scope_value == NULL) { + xmlFree (scope_type); + return gdata_parser_error_required_property_missing (node, "value", error); + } + + self->priv->scope_type = (gchar*) scope_type; + self->priv->scope_value = (gchar*) scope_value; + } else if (xmlStrcmp (node->name, (xmlChar*) "withKey") == 0) { + /* gAcl:withKey */ + gboolean found_role = FALSE; + xmlNode *child; + xmlChar *key; + + /* Extract the key. */ + key = xmlGetProp (node, (xmlChar *) "key"); + if (key == NULL) { + return gdata_parser_error_required_property_missing (node, "key", error); + } + + self->priv->key = (gchar *) key; + + /* Look for a gAcl:role child element. */ + for (child = node->children; child != NULL; child = child->next) { + if (xmlStrcmp (child->name, (xmlChar*) "role") == 0) { + xmlChar *role = xmlGetProp (child, (xmlChar *) "value"); + if (role == NULL) { + return gdata_parser_error_required_property_missing (child, "value", error); + } + + self->priv->role = (gchar *) role; + found_role = TRUE; + } else { + /* TODO: this logic copied from gdata-parsable.c. Re-evaluate this at some point in the future. + * If GeoRSS and GML support were to be used more widely, it might due to implement GML objects. */ + xmlBuffer *buffer; + + /* Unhandled XML */ + buffer = xmlBufferCreate (); + xmlNodeDump (buffer, doc, child, 0, 0); + g_debug ("Unhandled XML in : %s", (gchar *) xmlBufferContent (buffer)); + xmlBufferFree (buffer); + } + } + + if (!found_role) { + return gdata_parser_error_required_element_missing ("role", "gAcl:withKey", error); + } + } else { + return GDATA_PARSABLE_CLASS (gdata_access_rule_parent_class)->parse_xml (parsable, doc, node, user_data, error); + } + } else { + return GDATA_PARSABLE_CLASS (gdata_access_rule_parent_class)->parse_xml (parsable, doc, node, user_data, error); + } + + return TRUE; +} + +static gboolean +post_parse_xml (GDataParsable *parsable, gpointer user_data, GError **error) +{ + GDataAccessRulePrivate *priv = GDATA_ACCESS_RULE (parsable)->priv; + + /* Check for missing required elements */ + if (gdata_entry_get_title (GDATA_ENTRY (parsable)) == NULL || *gdata_entry_get_title (GDATA_ENTRY (parsable)) == '\0') + return gdata_parser_error_required_element_missing ("role", "entry", error); + if (priv->scope_type == NULL) + return gdata_parser_error_required_element_missing ("scope", "entry", error); + + return TRUE; +} + +static void +get_xml (GDataParsable *parsable, GString *xml_string) +{ + GDataAccessRulePrivate *priv = GDATA_ACCESS_RULE (parsable)->priv; + + /* Chain up to the parent class */ + GDATA_PARSABLE_CLASS (gdata_access_rule_parent_class)->get_xml (parsable, xml_string); + + if (priv->key != NULL) { + /* gAcl:withKey; has to wrap gAcl:role */ + gdata_parser_string_append_escaped (xml_string, ""); + } + + if (priv->role != NULL) { + /* gAcl:role */ + gdata_parser_string_append_escaped (xml_string, ""); + } + + if (priv->key != NULL) { + g_string_append (xml_string, ""); + } + + if (priv->scope_value != NULL) { + /* gAcl:scope */ + if (priv->scope_type != NULL) { + gdata_parser_string_append_escaped (xml_string, ""); + } else { + gdata_parser_string_append_escaped (xml_string, ""); + } + } else { + /* gAcl:scope of type GDATA_ACCESS_SCOPE_DEFAULT. */ + g_assert (priv->scope_type != NULL && strcmp (priv->scope_type, GDATA_ACCESS_SCOPE_DEFAULT) == 0); + g_string_append (xml_string, ""); + } +} + +static void +get_namespaces (GDataParsable *parsable, GHashTable *namespaces) +{ + /* Chain up to the parent class */ + GDATA_PARSABLE_CLASS (gdata_access_rule_parent_class)->get_namespaces (parsable, namespaces); + + g_hash_table_insert (namespaces, (gchar*) "gAcl", (gchar*) "http://schemas.google.com/acl/2007"); +} + +/** + * gdata_access_rule_new: + * @id: the access rule's ID, or %NULL + * + * Creates a new #GDataAccessRule with the given ID and default properties. + * + * Return value: a new #GDataAccessRule; unref with g_object_unref() + * + * Since: 0.3.0 + */ +GDataAccessRule * +gdata_access_rule_new (const gchar *id) +{ + return GDATA_ACCESS_RULE (g_object_new (GDATA_TYPE_ACCESS_RULE, "id", id, NULL)); +} + +/** + * gdata_access_rule_set_role: + * @self: a #GDataAccessRule + * @role: a new role, or %NULL + * + * Sets the #GDataAccessRule:role property to @role. @role must be a non-empty string, such as %GDATA_ACCESS_ROLE_NONE. + * + * Set @role to %NULL to unset the property in the access rule. + * + * Since: 0.3.0 + */ +void +gdata_access_rule_set_role (GDataAccessRule *self, const gchar *role) +{ + g_return_if_fail (GDATA_IS_ACCESS_RULE (self)); + g_return_if_fail (role == NULL || *role != '\0'); + + g_free (self->priv->role); + self->priv->role = g_strdup (role); + g_object_notify (G_OBJECT (self), "role"); +} + +/** + * gdata_access_rule_get_role: + * @self: a #GDataAccessRule + * + * Gets the #GDataAccessRule:role property. + * + * Return value: the access rule's role, or %NULL + * + * Since: 0.3.0 + */ +const gchar * +gdata_access_rule_get_role (GDataAccessRule *self) +{ + g_return_val_if_fail (GDATA_IS_ACCESS_RULE (self), NULL); + return self->priv->role; +} + + +/** + * gdata_access_rule_set_scope: + * @self: a #GDataAccessRule + * @type: a new scope type + * @value: (allow-none): a new scope value, or %NULL + * + * Sets the #GDataAccessRule:scope-type property to @type and the #GDataAccessRule:scope-value property to @value. + * + * Set @scope_value to %NULL to unset the #GDataAccessRule:scope-value property in the access rule. @type cannot + * be %NULL. @scope_value must be %NULL if @type is default, and non-%NULL otherwise. + * + * See the + * online + * documentation for more information. + * + * Since: 0.3.0 + */ +void +gdata_access_rule_set_scope (GDataAccessRule *self, const gchar *type, const gchar *value) +{ + g_return_if_fail (GDATA_IS_ACCESS_RULE (self)); + g_return_if_fail (type != NULL && *type != '\0'); + g_return_if_fail ((strcmp (type, GDATA_ACCESS_SCOPE_DEFAULT) == 0 && value == NULL) || value != NULL); + + g_free (self->priv->scope_type); + self->priv->scope_type = g_strdup (type); + + g_free (self->priv->scope_value); + self->priv->scope_value = g_strdup (value); + + g_object_freeze_notify (G_OBJECT (self)); + g_object_notify (G_OBJECT (self), "scope-type"); + g_object_notify (G_OBJECT (self), "scope-value"); + g_object_thaw_notify (G_OBJECT (self)); +} + +/** + * gdata_access_rule_get_scope: + * @self: a #GDataAccessRule + * @type: (out callee-allocates) (transfer none) (allow-none): return location for the scope type, or %NULL + * @value: (out callee-allocates) (transfer none) (allow-none): return location for the scope value, or %NULL + * + * Gets the #GDataAccessRule:scope-type and #GDataAccessRule:scope-value properties. + * + * Since: 0.3.0 + */ +void +gdata_access_rule_get_scope (GDataAccessRule *self, const gchar **type, const gchar **value) +{ + g_return_if_fail (GDATA_IS_ACCESS_RULE (self)); + if (type != NULL) + *type = self->priv->scope_type; + if (value != NULL) + *value = self->priv->scope_value; +} + +/** + * gdata_access_rule_get_edited: + * @self: a #GDataAccessRule + * + * Gets the #GDataAccessRule:edited property. If the property is unset, -1 will be returned. + * + * Return value: the UNIX timestamp for the time the access rule was last edited, or -1 + * + * Since: 0.7.0 + */ +gint64 +gdata_access_rule_get_edited (GDataAccessRule *self) +{ + g_return_val_if_fail (GDATA_IS_ACCESS_RULE (self), -1); + return self->priv->edited; +} + +void +_gdata_access_rule_set_key (GDataAccessRule *self, const gchar *key) +{ + g_return_if_fail (GDATA_IS_ACCESS_RULE (self)); + + if (g_strcmp0 (key, self->priv->key) == 0) + return; + + g_free (self->priv->key); + self->priv->key = g_strdup (key); + + g_object_notify (G_OBJECT (self), "key"); +} + +/** + * gdata_access_rule_get_key: + * @self: a #GDataAccessRule + * + * Gets the #GDataAccessRule:key property. + * + * Return value: the access rule's authorisation key, or %NULL + * + * Since: 0.16.0 + */ +const gchar * +gdata_access_rule_get_key (GDataAccessRule *self) +{ + g_return_val_if_fail (GDATA_IS_ACCESS_RULE (self), NULL); + return self->priv->key; +} diff --git a/gdata/gdata-access-rule.h b/gdata/gdata-access-rule.h new file mode 100644 index 0000000..34db2c8 --- /dev/null +++ b/gdata/gdata-access-rule.h @@ -0,0 +1,118 @@ +/* -*- Mode: C; indent-tabs-mode: t; c-basic-offset: 8; tab-width: 8 -*- */ +/* + * GData Client + * Copyright (C) Thibault Saunier 2009 + * Copyright (C) Philip Withnall 2009 + * + * GData Client is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * GData Client is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with GData Client. If not, see . + */ + +#ifndef GDATA_ACCESS_RULE_H +#define GDATA_ACCESS_RULE_H + +#include +#include + +#include + +G_BEGIN_DECLS + +/** + * GDATA_ACCESS_SCOPE_USER: + * + * The #GDataAccessRule applies to a single individual, whose e-mail address is given in #GDataAccessRule:scope-value. + * + * Since: 0.7.0 + */ +#define GDATA_ACCESS_SCOPE_USER "user" + +/** + * GDATA_ACCESS_SCOPE_DOMAIN: + * + * The #GDataAccessRule applies to all users in a Google Apps For Your Domain domain, given in #GDataAccessRule:scope-value. + * + * Since: 0.7.0 + */ +#define GDATA_ACCESS_SCOPE_DOMAIN "domain" + +/** + * GDATA_ACCESS_SCOPE_DEFAULT: + * + * The #GDataAccessRule applies to all users. + * + * Since: 0.7.0 + */ +#define GDATA_ACCESS_SCOPE_DEFAULT "default" + +/** + * GDATA_ACCESS_ROLE_NONE: + * + * The users specified by the #GDataAccessRule have no rights. + * + * Since: 0.7.0 + */ +#define GDATA_ACCESS_ROLE_NONE "none" + +#define GDATA_TYPE_ACCESS_RULE (gdata_access_rule_get_type ()) +#define GDATA_ACCESS_RULE(o) (G_TYPE_CHECK_INSTANCE_CAST ((o), GDATA_TYPE_ACCESS_RULE, GDataAccessRule)) +#define GDATA_ACCESS_RULE_CLASS(k) (G_TYPE_CHECK_CLASS_CAST((k), GDATA_TYPE_ACCESS_RULE, GDataAccessRuleClass)) +#define GDATA_IS_ACCESS_RULE(o) (G_TYPE_CHECK_INSTANCE_TYPE ((o), GDATA_TYPE_ACCESS_RULE)) +#define GDATA_IS_ACCESS_RULE_CLASS(k) (G_TYPE_CHECK_CLASS_TYPE ((k), GDATA_TYPE_ACCESS_RULE)) +#define GDATA_ACCESS_RULE_GET_CLASS(o) (G_TYPE_INSTANCE_GET_CLASS ((o), GDATA_TYPE_ACCESS_RULE, GDataAccessRuleClass)) + +typedef struct _GDataAccessRulePrivate GDataAccessRulePrivate; + +/** + * GDataAccessRule: + * + * All the fields in the #GDataAccessRule structure are private and should never be accessed directly. + * + * Since: 0.3.0 + */ +typedef struct { + GDataEntry parent; + GDataAccessRulePrivate *priv; +} GDataAccessRule; + +/** + * GDataAccessRuleClass: + * + * All the fields in the #GDataAccessRuleClass structure are private and should never be accessed directly. + * + * Since: 0.3.0 + */ +typedef struct { + /*< private >*/ + GDataEntryClass parent; + + /*< private >*/ + /* Padding for future expansion */ + void (*_g_reserved0) (void); + void (*_g_reserved1) (void); +} GDataAccessRuleClass; + +GType gdata_access_rule_get_type (void) G_GNUC_CONST; + +GDataAccessRule *gdata_access_rule_new (const gchar *id) G_GNUC_WARN_UNUSED_RESULT G_GNUC_MALLOC; + +const gchar *gdata_access_rule_get_role (GDataAccessRule *self) G_GNUC_PURE; +void gdata_access_rule_set_role (GDataAccessRule *self, const gchar *role); +void gdata_access_rule_get_scope (GDataAccessRule *self, const gchar **type, const gchar **value); +void gdata_access_rule_set_scope (GDataAccessRule *self, const gchar *type, const gchar *value); +gint64 gdata_access_rule_get_edited (GDataAccessRule *self); +const gchar *gdata_access_rule_get_key (GDataAccessRule *self) G_GNUC_PURE; + +G_END_DECLS + +#endif /* !GDATA_ACCESS_RULE_H */ diff --git a/gdata/gdata-authorization-domain.c b/gdata/gdata-authorization-domain.c new file mode 100644 index 0000000..1867974 --- /dev/null +++ b/gdata/gdata-authorization-domain.c @@ -0,0 +1,197 @@ +/* -*- Mode: C; indent-tabs-mode: t; c-basic-offset: 8; tab-width: 8 -*- */ +/* + * GData Client + * Copyright (C) Philip Withnall 2011 + * + * GData Client is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * GData Client is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with GData Client. If not, see . + */ + +/** + * SECTION:gdata-authorization-domain + * @short_description: GData authorization domain + * @stability: Stable + * @include: gdata/gdata-authorization-domain.h + * + * A #GDataAuthorizationDomain represents a single data domain which a user can authorize libgdata to access. This might be a domain covering the + * whole of the user's Google Contacts account, for example. Typically, #GDataServices map to #GDataAuthorizationDomains in a one-to-one + * fashion, though some services (such as #GDataDocumentsService) use multiple authorization domains. + * + * The #GDataAuthorizationDomainss used by a service can be retrieved using gdata_service_get_authorization_domains(). The set of domains + * used by a given service is static and will never change at runtime. + * + * #GDataAuthorizationDomains are used by a #GDataAuthorizer instance to request authorization to interact with data in those domains when + * first authenticating and authorizing with the online service. Typically, a given #GDataAuthorizer will be passed a set of domains (or a service + * type, from which it can retrieve the service's set of domains) at construction time, and will use those domains when initially asking the user for + * authorization and whenever the authorization is refreshed afterwards. It's not expected that the set of domains used by a #GDataAuthorizer will + * change after construction time. + * + * Note that it's not expected that #GDataAuthorizationDomains will have to be constructed manually. All #GDataServices should provide + * accessor functions to return instances of all the authorization domains they support. + * + * Since: 0.9.0 + */ + +#include + +#include "gdata-authorization-domain.h" + +static void finalize (GObject *object); +static void get_property (GObject *object, guint property_id, GValue *value, GParamSpec *pspec); +static void set_property (GObject *object, guint property_id, const GValue *value, GParamSpec *pspec); + +struct _GDataAuthorizationDomainPrivate { + gchar *service_name; + gchar *scope; +}; + +enum { + PROP_SERVICE_NAME = 1, + PROP_SCOPE, +}; + +G_DEFINE_TYPE (GDataAuthorizationDomain, gdata_authorization_domain, G_TYPE_OBJECT) + +static void +gdata_authorization_domain_class_init (GDataAuthorizationDomainClass *klass) +{ + GObjectClass *gobject_class = G_OBJECT_CLASS (klass); + + g_type_class_add_private (klass, sizeof (GDataAuthorizationDomainPrivate)); + + gobject_class->get_property = get_property; + gobject_class->set_property = set_property; + gobject_class->finalize = finalize; + + /** + * GDataAuthorizationDomain:service-name: + * + * The name of the service which contains the authorization domain, as enumerated in the + * online documentation. + * + * Since: 0.9.0 + */ + g_object_class_install_property (gobject_class, PROP_SERVICE_NAME, + g_param_spec_string ("service-name", + "Service name", "The name of the service which contains the authorization domain.", + NULL, + G_PARAM_CONSTRUCT_ONLY | G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)); + + /** + * GDataAuthorizationDomain:scope: + * + * A URI detailing the scope of the authorization domain, as enumerated in the + * online documentation. + * + * Since: 0.9.0 + */ + g_object_class_install_property (gobject_class, PROP_SCOPE, + g_param_spec_string ("scope", + "Scope", "A URI detailing the scope of the authorization domain.", + NULL, + G_PARAM_CONSTRUCT_ONLY | G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)); +} + +static void +gdata_authorization_domain_init (GDataAuthorizationDomain *self) +{ + self->priv = G_TYPE_INSTANCE_GET_PRIVATE (self, GDATA_TYPE_AUTHORIZATION_DOMAIN, GDataAuthorizationDomainPrivate); +} + +static void +finalize (GObject *object) +{ + GDataAuthorizationDomainPrivate *priv = GDATA_AUTHORIZATION_DOMAIN (object)->priv; + + g_free (priv->service_name); + g_free (priv->scope); + + /* Chain up to the parent class */ + G_OBJECT_CLASS (gdata_authorization_domain_parent_class)->finalize (object); +} + +static void +get_property (GObject *object, guint property_id, GValue *value, GParamSpec *pspec) +{ + GDataAuthorizationDomainPrivate *priv = GDATA_AUTHORIZATION_DOMAIN (object)->priv; + + switch (property_id) { + case PROP_SERVICE_NAME: + g_value_set_string (value, priv->service_name); + break; + case PROP_SCOPE: + g_value_set_string (value, priv->scope); + break; + default: + /* We don't have any other property... */ + G_OBJECT_WARN_INVALID_PROPERTY_ID (object, property_id, pspec); + break; + } +} + +static void +set_property (GObject *object, guint property_id, const GValue *value, GParamSpec *pspec) +{ + GDataAuthorizationDomainPrivate *priv = GDATA_AUTHORIZATION_DOMAIN (object)->priv; + + switch (property_id) { + /* Construct only */ + case PROP_SERVICE_NAME: + priv->service_name = g_value_dup_string (value); + break; + /* Construct only */ + case PROP_SCOPE: + priv->scope = g_value_dup_string (value); + break; + default: + /* We don't have any other property... */ + G_OBJECT_WARN_INVALID_PROPERTY_ID (object, property_id, pspec); + break; + } +} + +/** + * gdata_authorization_domain_get_service_name: + * @self: a #GDataAuthorizationDomain + * + * Returns the name of the service containing the authorization domain. See #GDataAuthorizationDomain:service-name for more details. + * + * Return value: name of the service containing the authorization domain + * + * Since: 0.9.0 + */ +const gchar * +gdata_authorization_domain_get_service_name (GDataAuthorizationDomain *self) +{ + g_return_val_if_fail (GDATA_IS_AUTHORIZATION_DOMAIN (self), NULL); + + return self->priv->service_name; +} + +/** + * gdata_authorization_domain_get_scope: + * @self: a #GDataAuthorizationDomain + * + * Returns a URI detailing the scope of the authorization domain. See #GDataAuthorizationDomain:scope for more details. + * + * Return value: URI detailing the scope of the authorization domain + * + * Since: 0.9.0 + */ +const gchar * +gdata_authorization_domain_get_scope (GDataAuthorizationDomain *self) +{ + g_return_val_if_fail (GDATA_IS_AUTHORIZATION_DOMAIN (self), NULL); + + return self->priv->scope; +} diff --git a/gdata/gdata-authorization-domain.h b/gdata/gdata-authorization-domain.h new file mode 100644 index 0000000..a4f8419 --- /dev/null +++ b/gdata/gdata-authorization-domain.h @@ -0,0 +1,78 @@ +/* -*- Mode: C; indent-tabs-mode: t; c-basic-offset: 8; tab-width: 8 -*- */ +/* + * GData Client + * Copyright (C) Philip Withnall 2011 + * + * GData Client is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * GData Client is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with GData Client. If not, see . + */ + +#ifndef GDATA_AUTHORIZATION_DOMAIN_H +#define GDATA_AUTHORIZATION_DOMAIN_H + +#include +#include + +G_BEGIN_DECLS + +#define GDATA_TYPE_AUTHORIZATION_DOMAIN (gdata_authorization_domain_get_type ()) +#define GDATA_AUTHORIZATION_DOMAIN(o) (G_TYPE_CHECK_INSTANCE_CAST ((o), GDATA_TYPE_AUTHORIZATION_DOMAIN, GDataAuthorizationDomain)) +#define GDATA_AUTHORIZATION_DOMAIN_CLASS(k) (G_TYPE_CHECK_CLASS_CAST((k), GDATA_TYPE_AUTHORIZATION_DOMAIN, GDataAuthorizationDomainClass)) +#define GDATA_IS_AUTHORIZATION_DOMAIN(o) (G_TYPE_CHECK_INSTANCE_TYPE ((o), GDATA_TYPE_AUTHORIZATION_DOMAIN)) +#define GDATA_IS_AUTHORIZATION_DOMAIN_CLASS(k) (G_TYPE_CHECK_CLASS_TYPE ((k), GDATA_TYPE_AUTHORIZATION_DOMAIN)) +#define GDATA_AUTHORIZATION_DOMAIN_GET_CLASS(o) (G_TYPE_INSTANCE_GET_CLASS ((o), GDATA_TYPE_AUTHORIZATION_DOMAIN, GDataAuthorizationDomainClass)) + +typedef struct _GDataAuthorizationDomainPrivate GDataAuthorizationDomainPrivate; + +/** + * GDataAuthorizationDomain: + * + * All the fields in the #GDataAuthorizationDomain structure are private and should never be accessed directly. + * + * Since: 0.9.0 + */ +typedef struct { + /*< private >*/ + GObject parent; + GDataAuthorizationDomainPrivate *priv; +} GDataAuthorizationDomain; + +/** + * GDataAuthorizationDomainClass: + * + * All the fields in the #GDataAuthorizationDomainClass structure are private and should never be accessed directly. + * + * Since: 0.9.0 + */ +typedef struct { + /*< private >*/ + GObjectClass parent; + + /*< private >*/ + /* Padding for future expansion */ + void (*_g_reserved0) (void); + void (*_g_reserved1) (void); + void (*_g_reserved2) (void); + void (*_g_reserved3) (void); + void (*_g_reserved4) (void); + void (*_g_reserved5) (void); +} GDataAuthorizationDomainClass; + +GType gdata_authorization_domain_get_type (void) G_GNUC_CONST; + +const gchar *gdata_authorization_domain_get_service_name (GDataAuthorizationDomain *self) G_GNUC_PURE; +const gchar *gdata_authorization_domain_get_scope (GDataAuthorizationDomain *self) G_GNUC_PURE; + +G_END_DECLS + +#endif /* !GDATA_AUTHORIZATION_DOMAIN_H */ diff --git a/gdata/gdata-authorizer.c b/gdata/gdata-authorizer.c new file mode 100644 index 0000000..ca8002a --- /dev/null +++ b/gdata/gdata-authorizer.c @@ -0,0 +1,312 @@ +/* -*- Mode: C; indent-tabs-mode: t; c-basic-offset: 8; tab-width: 8 -*- */ +/* + * GData Client + * Copyright (C) Philip Withnall 2011, 2014 + * + * GData Client is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * GData Client is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with GData Client. If not, see . + */ + +/** + * SECTION:gdata-authorizer + * @short_description: GData authorization interface + * @stability: Stable + * @include: gdata/gdata-authorizer.h + * + * The #GDataAuthorizer interface provides a uniform way to implement authentication and authorization processes for use by #GDataServices. + * Client code will construct a new #GDataAuthorizer instance of their choosing, such as #GDataClientLoginAuthorizer or #GDataOAuth2Authorizer, for + * the #GDataServices which will be used by the client, then authenticates and authorizes with the #GDataAuthorizer instead of the + * #GDataService. The #GDataService then uses the #GDataAuthorizer to authorize individual network requests using whatever authorization token was + * returned to the #GDataAuthorizer by the Google Accounts service. + * + * All #GDataAuthorizer implementations are expected to operate against a set of #GDataAuthorizationDomains which are provided to the + * authorizer at construction time. These domains specify which data domains the client expects to access using the #GDataServices they + * have using the #GDataAuthorizer instance. Following the principle of least privilege, the set of domains should be the minimum such set of domains + * which still allows the client to operate normally. Note that implementations of #GDataAuthorizationDomain may display the list of requested + * authorization domains to the user for verification before authorization is granted. + * + * #GDataAuthorizer implementations are provided for some of the standard authorization processes supported by Google for installed applications, as + * listed in their online documentation: + * + * #GDataClientLoginAuthorizer for + * ClientLogin (deprecated) + * #GDataOAuth1Authorizer for + * OAuth 1.0 (deprecated) + * #GDataOAuth2Authorizer for + * OAuth 2.0 (preferred) + * + * + * It is quite possible for clients to write their own #GDataAuthorizer implementation. For example, if a client already uses OAuth 2.0 and handles + * authentication itself, it may want to use its own #GDataAuthorizer implementation which simply exposes the client's existing access token to + * libgdata and does nothing more. + * + * It must be noted that all #GDataAuthorizer implementations must be thread safe, as methods such as gdata_authorizer_refresh_authorization() may be + * called from any thread (such as the thread performing an asynchronous query operation) at any time. + * + * Examples of code using #GDataAuthorizer can be found in the documentation for the various implementations of the #GDataAuthorizer interface. + * + * Since: 0.9.0 + */ + +#include + +#include "gdata-authorizer.h" + +G_DEFINE_INTERFACE (GDataAuthorizer, gdata_authorizer, G_TYPE_OBJECT) + +static void +gdata_authorizer_default_init (GDataAuthorizerInterface *iface) +{ + /* Nothing to see here */ +} + +/** + * gdata_authorizer_process_request: + * @self: a #GDataAuthorizer + * @domain: (allow-none): the #GDataAuthorizationDomain the query falls under, or %NULL + * @message: the query to process + * + * Processes @message, adding all the necessary extra headers and parameters to ensure that it's correctly authenticated and authorized under the + * given @domain for the online service. Basically, if a query is not processed by calling this method on it, it will be sent to the online service as + * if it's a query from a non-logged-in user. Similarly, if the #GDataAuthorizer isn't authenticated or authorized (for @domain), no changes will + * be made to the @message. + * + * @domain may be %NULL if the request doesn't require authorization. + * + * This modifies @message in place. + * + * This method is thread safe. + * + * Since: 0.9.0 + */ +void +gdata_authorizer_process_request (GDataAuthorizer *self, GDataAuthorizationDomain *domain, SoupMessage *message) +{ + GDataAuthorizerInterface *iface; + + g_return_if_fail (GDATA_IS_AUTHORIZER (self)); + g_return_if_fail (domain == NULL || GDATA_IS_AUTHORIZATION_DOMAIN (domain)); + g_return_if_fail (SOUP_IS_MESSAGE (message)); + + iface = GDATA_AUTHORIZER_GET_IFACE (self); + g_assert (iface->process_request != NULL); + + iface->process_request (self, domain, message); +} + +/** + * gdata_authorizer_is_authorized_for_domain: + * @self: (allow-none): a #GDataAuthorizer, or %NULL + * @domain: the #GDataAuthorizationDomain to check against + * + * Returns whether the #GDataAuthorizer instance believes it's currently authorized to access the given @domain. Note that this will not perform any + * network requests, and will just look up the result in the #GDataAuthorizer's local cache of authorizations. This means that the result may be out + * of date, as the server may have since invalidated the authorization. If the #GDataAuthorizer class supports timeouts and TTLs on authorizations, + * they will not be taken into account; this method effectively returns whether the last successful authorization operation performed on the + * #GDataAuthorizer included @domain in the list of requested authorization domains. + * + * Note that %NULL may be passed as the #GDataAuthorizer, in which case %FALSE will always be returned, regardless of the @domain. This is for + * convenience of checking whether a domain is authorized by the #GDataAuthorizer returned by gdata_service_get_authorizer(), which may be %NULL. + * For example: + * |[ + * if (gdata_authorizer_is_authorized_for_domain (gdata_service_get_authorizer (my_service), my_domain) == TRUE) { + * /* Code to execute only if we're authorized for the given domain */ + * } + * ]| + * + * This method is thread safe. + * + * Return value: %TRUE if the #GDataAuthorizer has been authorized to access @domain, %FALSE otherwise + * + * Since: 0.9.0 + */ +gboolean +gdata_authorizer_is_authorized_for_domain (GDataAuthorizer *self, GDataAuthorizationDomain *domain) +{ + GDataAuthorizerInterface *iface; + + g_return_val_if_fail (self == NULL || GDATA_IS_AUTHORIZER (self), FALSE); + g_return_val_if_fail (GDATA_IS_AUTHORIZATION_DOMAIN (domain), FALSE); + + if (self == NULL) { + return FALSE; + } + + iface = GDATA_AUTHORIZER_GET_IFACE (self); + g_assert (iface->is_authorized_for_domain != NULL); + + return iface->is_authorized_for_domain (self, domain); +} + +/** + * gdata_authorizer_refresh_authorization: + * @self: a #GDataAuthorizer + * @cancellable: (allow-none): optional #GCancellable object, or %NULL + * @error: a #GError, or %NULL + * + * Forces the #GDataAuthorizer to refresh any authorization tokens it holds with the online service. This should typically be called when a + * #GDataService query returns %GDATA_SERVICE_ERROR_AUTHENTICATION_REQUIRED, and is already called transparently by methods such as + * gdata_service_query() and gdata_service_insert_entry() (see their documentation for more details). + * + * If re-authorization is successful, it's guaranteed that by the time this method returns, the properties containing the relevant authorization + * tokens on the #GDataAuthorizer instance will have been updated. + * + * If %FALSE is returned, @error will be set if (and only if) it's due to a refresh being attempted and failing. If a refresh is not attempted, %FALSE + * will be returned but @error will not be set. + * + * If the #GDataAuthorizer has not been previously authenticated or authorized (using the class' specific methods), no authorization will be + * attempted, %FALSE will be returned immediately and @error will not be set. + * + * Some #GDataAuthorizer implementations may not support refreshing authorization tokens at all; for example if doing so requires user interaction. + * %FALSE will be returned immediately in that case and @error will not be set. + * + * This method is thread safe. + * + * Return value: %TRUE if an authorization refresh was attempted and was successful, %FALSE if a refresh wasn't attempted or was unsuccessful + * + * Since: 0.9.0 + */ +gboolean +gdata_authorizer_refresh_authorization (GDataAuthorizer *self, GCancellable *cancellable, GError **error) +{ + GDataAuthorizerInterface *iface; + + g_return_val_if_fail (GDATA_IS_AUTHORIZER (self), FALSE); + g_return_val_if_fail (cancellable == NULL || G_IS_CANCELLABLE (cancellable), FALSE); + g_return_val_if_fail (error == NULL || *error == NULL, FALSE); + + iface = GDATA_AUTHORIZER_GET_IFACE (self); + + /* Return FALSE with no error if the method isn't implemented */ + if (iface->refresh_authorization == NULL) { + return FALSE; + } + + return iface->refresh_authorization (self, cancellable, error); +} + +static void +refresh_authorization_thread (GTask *task, gpointer source_object, gpointer task_data, GCancellable *cancellable) +{ + GDataAuthorizer *authorizer = GDATA_AUTHORIZER (source_object); + g_autoptr(GError) error = NULL; + + /* Refresh the authorisation and return */ + gdata_authorizer_refresh_authorization (authorizer, cancellable, &error); + + if (error != NULL) + g_task_return_error (task, g_steal_pointer (&error)); + else + g_task_return_boolean (task, TRUE); +} + +/** + * gdata_authorizer_refresh_authorization_async: + * @self: a #GDataAuthorizer + * @cancellable: (allow-none): optional #GCancellable object, or %NULL + * @callback: (allow-none) (scope async): a #GAsyncReadyCallback to call when the authorization refresh operation is finished, or %NULL + * @user_data: (closure): data to pass to the @callback function + * + * Forces the #GDataAuthorizer to refresh any authorization tokens it holds with the online service. @self and @cancellable are reffed when this + * method is called, so can safely be freed after this method returns. + * + * For more details, see gdata_authorizer_refresh_authorization(), which is the synchronous version of this method. If the #GDataAuthorizer class + * doesn't implement #GDataAuthorizerInterface.refresh_authorization_async but does implement #GDataAuthorizerInterface.refresh_authorization, the + * latter will be called from a new thread to make it asynchronous. + * + * When the authorization refresh operation is finished, @callback will be called. You can then call gdata_authorizer_refresh_authorization_finish() + * to get the results of the operation. + * + * This method is thread safe. + * + * Since: 0.9.0 + */ +void +gdata_authorizer_refresh_authorization_async (GDataAuthorizer *self, GCancellable *cancellable, GAsyncReadyCallback callback, gpointer user_data) +{ + GDataAuthorizerInterface *iface; + + g_return_if_fail (GDATA_IS_AUTHORIZER (self)); + g_return_if_fail (cancellable == NULL || G_IS_CANCELLABLE (cancellable)); + + iface = GDATA_AUTHORIZER_GET_IFACE (self); + + /* Either both _async() and _finish() must be defined, or they must both be undefined. */ + g_assert ((iface->refresh_authorization_async == NULL && iface->refresh_authorization_finish == NULL) || + (iface->refresh_authorization_async != NULL && iface->refresh_authorization_finish != NULL)); + + if (iface->refresh_authorization_async != NULL) { + /* Call the method */ + iface->refresh_authorization_async (self, cancellable, callback, user_data); + } else { + g_autoptr(GTask) task = NULL; + + task = g_task_new (self, cancellable, callback, user_data); + g_task_set_source_tag (task, gdata_authorizer_refresh_authorization_async); + + + if (iface->refresh_authorization != NULL) { + /* If the _async() method isn't implemented, fall back to running the sync method in a thread */ + g_task_run_in_thread (task, refresh_authorization_thread); + } else { + /* If neither are implemented, immediately return FALSE with no error in a callback */ + g_task_return_boolean (task, FALSE); + } + + return; + } +} + +/** + * gdata_authorizer_refresh_authorization_finish: + * @self: a #GDataAuthorizer + * @async_result: a #GAsyncResult + * @error: a #GError, or %NULL + * + * Finishes an asynchronous authorization refresh operation for the #GDataAuthorizer, as started with gdata_authorizer_refresh_authorization_async(). + * + * This method is thread safe. + * + * Return value: %TRUE if an authorization refresh was attempted and was successful, %FALSE if a refresh wasn't attempted or was unsuccessful + * + * Since: 0.9.0 + */ +gboolean +gdata_authorizer_refresh_authorization_finish (GDataAuthorizer *self, GAsyncResult *async_result, GError **error) +{ + GDataAuthorizerInterface *iface; + + g_return_val_if_fail (GDATA_IS_AUTHORIZER (self), FALSE); + g_return_val_if_fail (G_IS_ASYNC_RESULT (async_result), FALSE); + g_return_val_if_fail (error == NULL || *error == NULL, FALSE); + + iface = GDATA_AUTHORIZER_GET_IFACE (self); + + /* Either both _async() and _finish() must be defined, or they must both be undefined. */ + g_assert ((iface->refresh_authorization_async == NULL && iface->refresh_authorization_finish == NULL) || + (iface->refresh_authorization_async != NULL && iface->refresh_authorization_finish != NULL)); + + if (iface->refresh_authorization_finish != NULL) { + /* Call the method */ + return iface->refresh_authorization_finish (self, async_result, error); + } else if (iface->refresh_authorization != NULL) { + /* If the _async() method isn't implemented, fall back to finishing off running the sync method in a thread */ + g_return_val_if_fail (g_task_is_valid (async_result, self), FALSE); + g_return_val_if_fail (g_async_result_is_tagged (async_result, gdata_authorizer_refresh_authorization_async), FALSE); + + return g_task_propagate_boolean (G_TASK (async_result), error); + } + + /* Fall back to just returning FALSE if none of the methods are implemented */ + return FALSE; +} diff --git a/gdata/gdata-authorizer.h b/gdata/gdata-authorizer.h new file mode 100644 index 0000000..ed1aa76 --- /dev/null +++ b/gdata/gdata-authorizer.h @@ -0,0 +1,92 @@ +/* -*- Mode: C; indent-tabs-mode: t; c-basic-offset: 8; tab-width: 8 -*- */ +/* + * GData Client + * Copyright (C) Philip Withnall 2011 + * + * GData Client is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * GData Client is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with GData Client. If not, see . + */ + +#ifndef GDATA_AUTHORIZER_H +#define GDATA_AUTHORIZER_H + +#include +#include +#include +#include + +#include + +G_BEGIN_DECLS + +#define GDATA_TYPE_AUTHORIZER (gdata_authorizer_get_type ()) +#define GDATA_AUTHORIZER(o) (G_TYPE_CHECK_INSTANCE_CAST ((o), GDATA_TYPE_AUTHORIZER, GDataAuthorizer)) +#define GDATA_AUTHORIZER_CLASS(k) (G_TYPE_CHECK_CLASS_CAST((k), GDATA_TYPE_AUTHORIZER, GDataAuthorizerInterface)) +#define GDATA_IS_AUTHORIZER(o) (G_TYPE_CHECK_INSTANCE_TYPE ((o), GDATA_TYPE_AUTHORIZER)) +#define GDATA_AUTHORIZER_GET_IFACE(o) (G_TYPE_INSTANCE_GET_INTERFACE ((o), GDATA_TYPE_AUTHORIZER, GDataAuthorizerInterface)) + +/** + * GDataAuthorizer: + * + * All the fields in the #GDataAuthorizer structure are private and should never be accessed directly. + * + * Since: 0.9.0 + */ +typedef struct _GDataAuthorizer GDataAuthorizer; /* dummy typedef */ + +/** + * GDataAuthorizerInterface: + * @parent: the parent type + * @process_request: a function to append authorization headers to queries before they are submitted to the online service under the given + * authorization domain (which may be %NULL); this must be implemented and must be thread safe, and must also handle being called multiple times on + * the same #SoupMessage instance (so must be careful to replace headers rather than append them, for example) + * @is_authorized_for_domain: a function to check whether the authorizer is authorized against the given domain; this must be implemented and must + * be thread safe + * @refresh_authorization: (allow-none): a function to force a refresh of any authorization tokens the authorizer holds, returning %TRUE if a refresh + * was attempted and was successful, or %FALSE if a refresh wasn't attempted or was unsuccessful; if this isn't implemented it's assumed %FALSE + * would've been returned, if it is implemented it must be thread safe + * @refresh_authorization_async: (allow-none): an asynchronous version of @refresh_authorization; if this isn't implemented and @refresh_authorization + * is, @refresh_authorization will be called in a thread to simulate this function, whereas if this is implemented @refresh_authorization_finish must + * also be implemented and both functions must be thread safe + * @refresh_authorization_finish: (allow-none): a finish function for the asynchronous version of @refresh_authorization; this must be implemented + * exactly if @refresh_authorization_async is implemented, and must be thread safe if it is implemented + * + * The class structure for the #GDataAuthorizer interface. + * + * Since: 0.9.0 + */ +typedef struct { + GTypeInterface parent; + + void (*process_request) (GDataAuthorizer *self, GDataAuthorizationDomain *domain, SoupMessage *message); + gboolean (*is_authorized_for_domain) (GDataAuthorizer *self, GDataAuthorizationDomain *domain); + gboolean (*refresh_authorization) (GDataAuthorizer *self, GCancellable *cancellable, GError **error); + void (*refresh_authorization_async) (GDataAuthorizer *self, GCancellable *cancellable, + GAsyncReadyCallback callback, gpointer user_data); + gboolean (*refresh_authorization_finish) (GDataAuthorizer *self, GAsyncResult *async_result, GError **error); +} GDataAuthorizerInterface; + +GType gdata_authorizer_get_type (void) G_GNUC_CONST; +G_DEFINE_AUTOPTR_CLEANUP_FUNC (GDataAuthorizer, g_object_unref) + +void gdata_authorizer_process_request (GDataAuthorizer *self, GDataAuthorizationDomain *domain, SoupMessage *message); +gboolean gdata_authorizer_is_authorized_for_domain (GDataAuthorizer *self, GDataAuthorizationDomain *domain); + +gboolean gdata_authorizer_refresh_authorization (GDataAuthorizer *self, GCancellable *cancellable, GError **error); +void gdata_authorizer_refresh_authorization_async (GDataAuthorizer *self, GCancellable *cancellable, + GAsyncReadyCallback callback, gpointer user_data); +gboolean gdata_authorizer_refresh_authorization_finish (GDataAuthorizer *self, GAsyncResult *async_result, GError **error); + +G_END_DECLS + +#endif /* !GDATA_AUTHORIZER_H */ diff --git a/gdata/gdata-batch-feed.c b/gdata/gdata-batch-feed.c new file mode 100644 index 0000000..103ec9c --- /dev/null +++ b/gdata/gdata-batch-feed.c @@ -0,0 +1,170 @@ +/* -*- Mode: C; indent-tabs-mode: t; c-basic-offset: 8; tab-width: 8 -*- */ +/* + * GData Client + * Copyright (C) Philip Withnall 2010 + * + * GData Client is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * GData Client is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with GData Client. If not, see . + */ + +/* + * SECTION:gdata-batch-feed + * @short_description: GData batch feed helper object + * @stability: Stable + * @include: gdata/gdata-batch-feed.h + * + * Helper class to parse the feed returned from a batch operation and instantiate different types of #GDataEntry according to the batch operation + * associated with each one. It's tightly coupled with #GDataBatchOperation, and isn't exposed publicly. + * + * For more information, see the online documentation. + * + * Since: 0.7.0 + */ + +#include +#include + +#include "gdata-batch-feed.h" +#include "gdata-private.h" +#include "gdata-batch-private.h" + +static gboolean parse_xml (GDataParsable *parsable, xmlDoc *doc, xmlNode *root_node, gpointer user_data, GError **error); + +G_DEFINE_TYPE (GDataBatchFeed, gdata_batch_feed, GDATA_TYPE_FEED) + +static void +gdata_batch_feed_class_init (GDataBatchFeedClass *klass) +{ + GDataParsableClass *parsable_class = GDATA_PARSABLE_CLASS (klass); + parsable_class->parse_xml = parse_xml; +} + +static void +gdata_batch_feed_init (GDataBatchFeed *self) +{ + /* Nothing to see here */ +} + +static gboolean +parse_xml (GDataParsable *parsable, xmlDoc *doc, xmlNode *node, gpointer user_data, GError **error) +{ + GDataBatchOperation *operation = GDATA_BATCH_OPERATION (user_data); + + if (xmlStrcmp (node->name, (xmlChar*) "entry") == 0) { + GDataEntry *entry = NULL; + xmlBuffer *status_response = NULL; + gchar *status_reason = NULL; + guint id = 0, status_code = 0; + xmlNode *entry_node; + BatchOperation *op; + + status_response = xmlBufferCreate (); + + /* Parse the child nodes of the to get the batch namespace elements containing information about this operation */ + for (entry_node = node->children; entry_node != NULL; entry_node = entry_node->next) { + /* We have to be careful about namespaces here, and we can skip text nodes (since none of the nodes we're looking for + * are text nodes) */ + if (entry_node->type == XML_TEXT_NODE || + gdata_parser_is_namespace (entry_node, "http://schemas.google.com/gdata/batch") == FALSE) + continue; + + if (xmlStrcmp (entry_node->name, (xmlChar*) "id") == 0) { + /* batch:id */ + xmlChar *id_string = xmlNodeListGetString (doc, entry_node->children, TRUE); + id = g_ascii_strtoull ((char*) id_string, NULL, 10); + xmlFree (id_string); + } else if (xmlStrcmp (entry_node->name, (xmlChar*) "status") == 0) { + /* batch:status */ + xmlChar *status_code_string; + xmlNode *child_node; + + status_code_string = xmlGetProp (entry_node, (xmlChar*) "code"); + status_code = g_ascii_strtoull ((char*) status_code_string, NULL, 10); + xmlFree (status_code_string); + + status_reason = (gchar*) xmlGetProp (entry_node, (xmlChar*) "reason"); + + /* Dump the content of the status node, since it's service-specific, and could be anything from plain text to XML */ + for (child_node = entry_node->children; child_node != NULL; child_node = child_node->next) + xmlNodeDump (status_response, doc, child_node, 0, 0); + } + + if (id != 0 && status_code != 0) + break; + } + + /* Check we've got all the required data */ + if (id == 0) { + gdata_parser_error_required_element_missing ("batch:id", "entry", error); + goto error; + } else if (status_code == 0) { + gdata_parser_error_required_element_missing ("batch:status", "entry", error); + goto error; + } + + op = _gdata_batch_operation_get_operation (operation, id); + + /* Check for errors */ + if (SOUP_STATUS_IS_SUCCESSFUL (status_code) == FALSE) { + /* Handle the error */ + GDataService *service = gdata_batch_operation_get_service (operation); + GDataServiceClass *klass = GDATA_SERVICE_GET_CLASS (service); + GError *child_error = NULL; + + /* Parse the error (it's returned in a service-specific format */ + g_assert (klass->parse_error_response != NULL); + klass->parse_error_response (service, (GDataOperationType) op->type, status_code, + status_reason, (gchar*) xmlBufferContent (status_response), + xmlBufferLength (status_response), &child_error); + + /* Run the operation's callback. This takes ownership of @child_error. */ + _gdata_batch_operation_run_callback (operation, op, NULL, child_error); + + g_free (status_reason); + xmlBufferFree (status_response); + + /* We return TRUE because we parsed the XML successfully; despite it being an error that we parsed */ + return TRUE; + } + + /* If there wasn't an error, parse the resulting GDataEntry and run the operation's callback */ + if (op->type == GDATA_BATCH_OPERATION_QUERY) + entry = GDATA_ENTRY (_gdata_parsable_new_from_xml_node (op->entry_type, doc, node, NULL, error)); + else if (op->type != GDATA_BATCH_OPERATION_DELETION) + entry = GDATA_ENTRY (_gdata_parsable_new_from_xml_node (G_OBJECT_TYPE (op->entry), doc, node, NULL, error)); + + if (op->type != GDATA_BATCH_OPERATION_DELETION && entry == NULL) + goto error; + + _gdata_batch_operation_run_callback (operation, op, entry, NULL); + + if (entry != NULL) + g_object_unref (entry); + + g_free (status_reason); + xmlBufferFree (status_response); + + return TRUE; + +error: + g_free (status_reason); + xmlBufferFree (status_response); + + return FALSE; + } else if (GDATA_PARSABLE_CLASS (gdata_batch_feed_parent_class)->parse_xml (parsable, doc, node, user_data, error) == FALSE) { + /* Error! */ + return FALSE; + } + + return TRUE; +} diff --git a/gdata/gdata-batch-feed.h b/gdata/gdata-batch-feed.h new file mode 100644 index 0000000..3e50d65 --- /dev/null +++ b/gdata/gdata-batch-feed.h @@ -0,0 +1,73 @@ +/* -*- Mode: C; indent-tabs-mode: t; c-basic-offset: 8; tab-width: 8 -*- */ +/* + * GData Client + * Copyright (C) Philip Withnall 2010 + * + * GData Client is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * GData Client is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with GData Client. If not, see . + */ + +#ifndef GDATA_BATCH_FEED_H +#define GDATA_BATCH_FEED_H + +#include +#include + +#include + +G_BEGIN_DECLS + +#define GDATA_TYPE_BATCH_FEED (gdata_batch_feed_get_type ()) +#define GDATA_BATCH_FEED(o) (G_TYPE_CHECK_INSTANCE_CAST ((o), GDATA_TYPE_BATCH_FEED, GDataBatchFeed)) +#define GDATA_BATCH_FEED_CLASS(k) (G_TYPE_CHECK_CLASS_CAST((k), GDATA_TYPE_BATCH_FEED, GDataBatchFeedClass)) +#define GDATA_IS_BATCH_FEED(o) (G_TYPE_CHECK_INSTANCE_TYPE ((o), GDATA_TYPE_BATCH_FEED)) +#define GDATA_IS_BATCH_FEED_CLASS(k) (G_TYPE_CHECK_CLASS_TYPE ((k), GDATA_TYPE_BATCH_FEED)) +#define GDATA_BATCH_FEED_GET_CLASS(o) (G_TYPE_INSTANCE_GET_CLASS ((o), GDATA_TYPE_BATCH_FEED, GDataBatchFeedClass)) + +typedef struct _GDataBatchFeedPrivate GDataBatchFeedPrivate; + +/** + * GDataBatchFeed: + * + * All the fields in the #GDataBatchFeed structure are private and should never be accessed directly. + * + * Since: 0.7.0 + */ +typedef struct { + /*< private >*/ + GDataFeed parent; + GDataBatchFeedPrivate *priv; +} GDataBatchFeed; + +/** + * GDataBatchFeedClass: + * + * All the fields in the #GDataBatchFeedClass structure are private and should never be accessed directly. + * + * Since: 0.7.0 + */ +typedef struct { + /*< private >*/ + GDataFeedClass parent; + + /*< private >*/ + /* Padding for future expansion */ + void (*_g_reserved0) (void); + void (*_g_reserved1) (void); +} GDataBatchFeedClass; + +GType gdata_batch_feed_get_type (void) G_GNUC_CONST; + +G_END_DECLS + +#endif /* !GDATA_BATCH_FEED_H */ diff --git a/gdata/gdata-batch-operation.c b/gdata/gdata-batch-operation.c new file mode 100644 index 0000000..adac8b5 --- /dev/null +++ b/gdata/gdata-batch-operation.c @@ -0,0 +1,825 @@ +/* -*- Mode: C; indent-tabs-mode: t; c-basic-offset: 8; tab-width: 8 -*- */ +/* + * GData Client + * Copyright (C) Philip Withnall 2010 + * + * GData Client is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * GData Client is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with GData Client. If not, see . + */ + +/** + * SECTION:gdata-batch-operation + * @short_description: GData batch operation object + * @stability: Stable + * @include: gdata/gdata-batch-operation.h + * + * #GDataBatchOperation is a transient standalone class which represents and handles a single batch operation request to a service. To make a batch + * operation request: create a new #GDataBatchOperation; add the required queries, insertions, updates and deletions to the operation using + * gdata_batch_operation_add_query(), gdata_batch_operation_add_insertion(), gdata_batch_operation_add_update() and + * gdata_batch_operation_add_deletion(), respectively; run the request with gdata_batch_operation_run() or gdata_batch_operation_run_async(); and + * handle the results in the callback functions which are invoked by the operation as the results are received and parsed. + * + * If authorization is required for any of the requests in the batch operation, the #GDataService set in #GDataBatchOperation:service must have + * a #GDataAuthorizer set as its #GDataService:authorizer property, and that authorizer must be authorized for the #GDataAuthorizationDomain set + * in #GDataBatchOperation:authorization-domain. It's not possible for requests in a single batch operation to be authorized under multiple domains; + * in that case, the requests must be split up across several batch operations using different authorization domains. + * + * If all of the requests in the batch operation don't require authorization (i.e. they all operate on public data; see the documentation for the + * #GDataService subclass in question's operations for details of which require authorization), #GDataBatchOperation:authorization-domain can be set + * to %NULL to save the overhead of sending authorization data to the online service. + * + * + * Running a Synchronous Operation + * + * guint op_id, op_id2; + * GDataBatchOperation *operation; + * GDataContactsContact *contact; + * GDataService *service; + * GDataAuthorizationDomain *domain; + * + * service = create_contacts_service (); + * domain = get_authorization_domain_from_service (service); + * contact = create_new_contact (); + * batch_link = gdata_feed_look_up_link (contacts_feed, GDATA_LINK_BATCH); + * + * operation = gdata_batchable_create_operation (GDATA_BATCHABLE (service), domain, gdata_link_get_uri (batch_link)); + * + * /* Add to the operation to insert a new contact and query for another one */ + * op_id = gdata_batch_operation_add_insertion (operation, GDATA_ENTRY (contact), insertion_cb, user_data); + * op_id2 = gdata_batch_operation_add_query (operation, gdata_entry_get_id (other_contact), GDATA_TYPE_CONTACTS_CONTACT, query_cb, user_data); + * + * g_object_unref (contact); + * g_object_unref (domain); + * g_object_unref (service); + * + * /* Run the operations in a blocking fashion. Ideally, check and free the error as appropriate after running the operation. */ + * gdata_batch_operation_run (operation, NULL, &error); + * + * g_object_unref (operation); + * + * static void + * insertion_cb (guint operation_id, GDataBatchOperationType operation_type, GDataEntry *entry, GError *error, gpointer user_data) + * { + * /* operation_id == op_id, operation_type == GDATA_BATCH_OPERATION_INSERTION */ + * + * /* Process the new inserted entry, ideally after checking for errors. Note that the entry should be reffed if it needs to stay + * * alive after execution of the callback finishes. */ + * process_inserted_entry (entry, user_data); + * } + * + * static void + * query_cb (guint operation_id, GDataBatchOperationType operation_type, GDataEntry *entry, GError *error, gpointer user_data) + * { + * /* operation_id == op_id2, operation_type == GDATA_BATCH_OPERATION_QUERY */ + * + * /* Process the results of the query, ideally after checking for errors. Note that the entry should be reffed if it needs to + * * stay alive after execution of the callback finishes. */ + * process_queried_entry (entry, user_data); + * } + * + * + * + * Since: 0.7.0 + */ + +#include +#include +#include +#include + +#include "gdata-batch-operation.h" +#include "gdata-batch-feed.h" +#include "gdata-batchable.h" +#include "gdata-private.h" +#include "gdata-batch-private.h" + +static void operation_free (BatchOperation *op); + +static void gdata_batch_operation_dispose (GObject *object); +static void gdata_batch_operation_finalize (GObject *object); +static void gdata_batch_operation_get_property (GObject *object, guint property_id, GValue *value, GParamSpec *pspec); +static void gdata_batch_operation_set_property (GObject *object, guint property_id, const GValue *value, GParamSpec *pspec); + +struct _GDataBatchOperationPrivate { + GDataService *service; + GDataAuthorizationDomain *authorization_domain; + gchar *feed_uri; + GHashTable *operations; + guint next_id; /* next available operation ID */ + gboolean has_run; /* TRUE if the operation has been run already (though it does not necessarily have to have finished running) */ + gboolean is_async; /* TRUE if the operation was run with *_run_async(); FALSE if run with *_run() */ +}; + +enum { + PROP_SERVICE = 1, + PROP_FEED_URI, + PROP_AUTHORIZATION_DOMAIN, +}; + +G_DEFINE_TYPE (GDataBatchOperation, gdata_batch_operation, G_TYPE_OBJECT) +#define GDATA_BATCH_OPERATION_GET_PRIVATE(obj) (G_TYPE_INSTANCE_GET_PRIVATE ((obj), GDATA_TYPE_BATCH_OPERATION, GDataBatchOperationPrivate)) + +static void +gdata_batch_operation_class_init (GDataBatchOperationClass *klass) +{ + GObjectClass *gobject_class = G_OBJECT_CLASS (klass); + + g_type_class_add_private (klass, sizeof (GDataBatchOperationPrivate)); + + gobject_class->dispose = gdata_batch_operation_dispose; + gobject_class->finalize = gdata_batch_operation_finalize; + gobject_class->get_property = gdata_batch_operation_get_property; + gobject_class->set_property = gdata_batch_operation_set_property; + + /** + * GDataBatchOperation:service: + * + * The service this batch operation is attached to. + * + * Since: 0.7.0 + */ + g_object_class_install_property (gobject_class, PROP_SERVICE, + g_param_spec_object ("service", + "Service", "The service this batch operation is attached to.", + GDATA_TYPE_SERVICE, + G_PARAM_CONSTRUCT_ONLY | G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)); + + /** + * GDataBatchOperation:authorization-domain: + * + * The authorization domain for the batch operation, against which the #GDataService:authorizer for the #GDataBatchOperation:service should be + * authorized. This may be %NULL if authorization is not needed for any of the requests in the batch operation. + * + * All requests in the batch operation must be authorizable under this single authorization domain. If requests need different authorization + * domains, they must be performed in different batch operations. + * + * Since: 0.9.0 + */ + g_object_class_install_property (gobject_class, PROP_AUTHORIZATION_DOMAIN, + g_param_spec_object ("authorization-domain", + "Authorization domain", "The authorization domain for the batch operation.", + GDATA_TYPE_AUTHORIZATION_DOMAIN, + G_PARAM_CONSTRUCT_ONLY | G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)); + + /** + * GDataBatchOperation:feed-uri: + * + * The feed URI that this batch operation will be sent to. + * + * Since: 0.7.0 + */ + g_object_class_install_property (gobject_class, PROP_FEED_URI, + g_param_spec_string ("feed-uri", + "Feed URI", "The feed URI that this batch operation will be sent to.", + NULL, + G_PARAM_CONSTRUCT_ONLY | G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)); +} + +static void +gdata_batch_operation_get_property (GObject *object, guint property_id, GValue *value, GParamSpec *pspec) +{ + GDataBatchOperationPrivate *priv = GDATA_BATCH_OPERATION_GET_PRIVATE (object); + + switch (property_id) { + case PROP_SERVICE: + g_value_set_object (value, priv->service); + break; + case PROP_AUTHORIZATION_DOMAIN: + g_value_set_object (value, priv->authorization_domain); + break; + case PROP_FEED_URI: + g_value_set_string (value, priv->feed_uri); + break; + default: + /* We don't have any other property... */ + G_OBJECT_WARN_INVALID_PROPERTY_ID (object, property_id, pspec); + break; + } +} + +static void +gdata_batch_operation_set_property (GObject *object, guint property_id, const GValue *value, GParamSpec *pspec) +{ + GDataBatchOperationPrivate *priv = GDATA_BATCH_OPERATION_GET_PRIVATE (object); + + switch (property_id) { + case PROP_SERVICE: + priv->service = g_value_dup_object (value); + break; + /* Construct only */ + case PROP_AUTHORIZATION_DOMAIN: + priv->authorization_domain = g_value_dup_object (value); + break; + case PROP_FEED_URI: + priv->feed_uri = g_value_dup_string (value); + break; + default: + /* We don't have any other property... */ + G_OBJECT_WARN_INVALID_PROPERTY_ID (object, property_id, pspec); + break; + } +} + +static void +gdata_batch_operation_init (GDataBatchOperation *self) +{ + self->priv = G_TYPE_INSTANCE_GET_PRIVATE (self, GDATA_TYPE_BATCH_OPERATION, GDataBatchOperationPrivate); + self->priv->next_id = 1; /* reserve ID 0 for error conditions */ + self->priv->operations = g_hash_table_new_full (g_direct_hash, g_direct_equal, NULL, (GDestroyNotify) operation_free); +} + +static void +gdata_batch_operation_dispose (GObject *object) +{ + GDataBatchOperationPrivate *priv = GDATA_BATCH_OPERATION_GET_PRIVATE (object); + + if (priv->authorization_domain != NULL) + g_object_unref (priv->authorization_domain); + priv->authorization_domain = NULL; + + if (priv->service != NULL) + g_object_unref (priv->service); + priv->service = NULL; + + /* Chain up to the parent class */ + G_OBJECT_CLASS (gdata_batch_operation_parent_class)->dispose (object); +} + +static void +gdata_batch_operation_finalize (GObject *object) +{ + GDataBatchOperationPrivate *priv = GDATA_BATCH_OPERATION_GET_PRIVATE (object); + + g_free (priv->feed_uri); + g_hash_table_destroy (priv->operations); + + /* Chain up to the parent class */ + G_OBJECT_CLASS (gdata_batch_operation_parent_class)->finalize (object); +} + +/** + * gdata_batch_operation_get_service: + * @self: a #GDataBatchOperation + * + * Gets the #GDataBatchOperation:service property. + * + * Return value: (transfer none): the batch operation's attached service + * + * Since: 0.7.0 + */ +GDataService * +gdata_batch_operation_get_service (GDataBatchOperation *self) +{ + g_return_val_if_fail (GDATA_IS_BATCH_OPERATION (self), NULL); + return self->priv->service; +} + +/** + * gdata_batch_operation_get_authorization_domain: + * @self: a #GDataBatchOperation + * + * Gets the #GDataBatchOperation:authorization-domain property. + * + * Return value: (transfer none) (allow-none): the #GDataAuthorizationDomain used to authorize the batch operation, or %NULL + * + * Since: 0.9.0 + */ +GDataAuthorizationDomain * +gdata_batch_operation_get_authorization_domain (GDataBatchOperation *self) +{ + g_return_val_if_fail (GDATA_IS_BATCH_OPERATION (self), NULL); + + return self->priv->authorization_domain; +} + +/** + * gdata_batch_operation_get_feed_uri: + * @self: a #GDataBatchOperation + * + * Gets the #GDataBatchOperation:feed-uri property. + * + * Return value: the batch operation's feed URI + * + * Since: 0.7.0 + */ +const gchar * +gdata_batch_operation_get_feed_uri (GDataBatchOperation *self) +{ + g_return_val_if_fail (GDATA_IS_BATCH_OPERATION (self), NULL); + return self->priv->feed_uri; +} + +/* Add an operation to the list of operations to be executed when the #GDataBatchOperation is run, and return its operation ID */ +static guint +add_operation (GDataBatchOperation *self, GDataBatchOperationType type, GDataEntry *entry, GDataBatchOperationCallback callback, gpointer user_data) +{ + BatchOperation *op; + + /* Create the operation */ + op = g_slice_new0 (BatchOperation); + op->id = (self->priv->next_id++); + op->type = type; + op->callback = callback; + op->user_data = user_data; + op->entry = g_object_ref (entry); + + /* Add the operation to the table */ + g_hash_table_insert (self->priv->operations, GUINT_TO_POINTER (op->id), op); + + return op->id; +} + +/** + * _gdata_batch_operation_get_operation: + * @self: a #GDataBatchOperation + * @id: the operation ID + * + * Return the #BatchOperation for the given operation ID. + * + * Return value: the relevant #BatchOperation, or %NULL + * + * Since: 0.7.0 + */ +BatchOperation * +_gdata_batch_operation_get_operation (GDataBatchOperation *self, guint id) +{ + g_return_val_if_fail (GDATA_IS_BATCH_OPERATION (self), NULL); + g_return_val_if_fail (id > 0, NULL); + + return g_hash_table_lookup (self->priv->operations, GUINT_TO_POINTER (id)); +} + +/* Run a user-supplied callback for a #BatchOperation whose return value we've just processed. This is designed to be used in an idle handler, so + * that the callback is run in the main thread. It can be called if the user-supplied callback is %NULL (e.g. in the case that the callback's been + * called before). */ +static gboolean +run_callback_cb (BatchOperation *op) +{ + if (op->callback != NULL) + op->callback (op->id, op->type, op->entry, op->error, op->user_data); + + /* Unset the callback so that it can't be called again */ + op->callback = NULL; + + return FALSE; +} + +/** + * _gdata_batch_operation_run_callback: + * @self: a #GDataBatchOperation + * @op: the #BatchOperation which has been finished + * @entry: (allow-none): the entry representing the operation's result, or %NULL + * @error: the error from the operation, or %NULL + * + * Run the callback for @op to notify the user code that the operation's result has been received and processed. Either @entry or @error should be + * set (and the other should be %NULL), signifying a successful operation or a failed operation, respectively. + * + * The function will call @op's user-supplied callback, if available, in either the current or the main thread, depending on whether the + * #GDataBatchOperation was run with gdata_batch_operation_run() or gdata_batch_operation_run_async(). + * + * Since: 0.7.0 + */ +void +_gdata_batch_operation_run_callback (GDataBatchOperation *self, BatchOperation *op, GDataEntry *entry, GError *error) +{ + g_return_if_fail (GDATA_IS_BATCH_OPERATION (self)); + g_return_if_fail (op != NULL); + g_return_if_fail (entry == NULL || GDATA_IS_ENTRY (entry)); + g_return_if_fail (entry == NULL || error == NULL); + + /* We can free the request data, and replace it with the response data */ + g_free (op->query_id); + op->query_id = NULL; + if (op->entry != NULL) + g_object_unref (op->entry); + if (entry != NULL) + g_object_ref (entry); + op->entry = entry; + op->error = error; + + /* Don't bother scheduling run_callback_cb() if there is no callback to run */ + if (op->callback == NULL) + return; + + /* Only dispatch it in the main thread if the request was run with *_run_async(). This allows applications to run batch operations entirely in + * application-owned threads if desired. */ + if (self->priv->is_async == TRUE) { + /* Send the callback; use G_PRIORITY_DEFAULT rather than G_PRIORITY_DEFAULT_IDLE + * to contend with the priorities used by the callback functions in GAsyncResult */ + g_idle_add_full (G_PRIORITY_DEFAULT, (GSourceFunc) run_callback_cb, op, NULL); + } else { + run_callback_cb (op); + } +} + +/* Free a #BatchOperation */ +static void +operation_free (BatchOperation *op) +{ + g_free (op->query_id); + if (op->entry != NULL) + g_object_unref (op->entry); + if (op->error != NULL) + g_error_free (op->error); + + g_slice_free (BatchOperation, op); +} + +/** + * gdata_batch_operation_add_query: + * @self: a #GDataBatchOperation + * @id: the ID of the entry being queried for + * @entry_type: the type of the entry which will be returned + * @callback: (scope async): a #GDataBatchOperationCallback to call when the query is finished, or %NULL + * @user_data: (closure): data to pass to the @callback function + * + * Add a query to the #GDataBatchOperation, to be executed when the operation is run. The query will return a #GDataEntry (of subclass type + * @entry_type) representing the given entry @id. The ID is of the same format as that returned by gdata_entry_get_id(). + * + * Note that a single batch operation should not operate on a given #GDataEntry more than once, as there's no guarantee about the order in which the + * batch operation's operations will be performed. + * + * @callback will be called when the #GDataBatchOperation is run with gdata_batch_operation_run() (in which case it will be called in the thread which + * ran the batch operation), or with gdata_batch_operation_run_async() (in which case it will be called in an idle handler in the main thread). The + * @operation_id passed to the callback will match the return value of gdata_batch_operation_add_query(), and the @operation_type will be + * %GDATA_BATCH_OPERATION_QUERY. If the query was successful, the resulting entry will be passed to the callback function as @entry, and @error will + * be %NULL. If, however, the query was unsuccessful, @entry will be %NULL and @error will contain a #GError detailing what went wrong. + * + * Return value: operation ID for the added query, or 0 + * + * Since: 0.7.0 + */ +guint +gdata_batch_operation_add_query (GDataBatchOperation *self, const gchar *id, GType entry_type, + GDataBatchOperationCallback callback, gpointer user_data) +{ + BatchOperation *op; + + g_return_val_if_fail (GDATA_IS_BATCH_OPERATION (self), 0); + g_return_val_if_fail (id != NULL, 0); + g_return_val_if_fail (g_type_is_a (entry_type, GDATA_TYPE_ENTRY), 0); + g_return_val_if_fail (self->priv->has_run == FALSE, 0); + + /* Create the operation manually, since it would be messy to special-case add_operation() to do this */ + op = g_slice_new0 (BatchOperation); + op->id = (self->priv->next_id++); + op->type = GDATA_BATCH_OPERATION_QUERY; + op->callback = callback; + op->user_data = user_data; + op->query_id = g_strdup (id); + op->entry_type = entry_type; + + /* Add the operation to the table */ + g_hash_table_insert (self->priv->operations, GUINT_TO_POINTER (op->id), op); + + return op->id; +} + +/** + * gdata_batch_operation_add_insertion: + * @self: a #GDataBatchOperation + * @entry: the #GDataEntry to insert + * @callback: (scope async): a #GDataBatchOperationCallback to call when the insertion is finished, or %NULL + * @user_data: (closure): data to pass to the @callback function + * + * Add an entry to the #GDataBatchOperation, to be inserted on the server when the operation is run. The insertion will return the inserted version + * of @entry. @entry is reffed by the function, so may be freed after it returns. + * + * @callback will be called as specified in the documentation for gdata_batch_operation_add_query(), with an @operation_type of + * %GDATA_BATCH_OPERATION_INSERTION. + * + * Return value: operation ID for the added insertion, or 0 + * + * Since: 0.7.0 + */ +guint +gdata_batch_operation_add_insertion (GDataBatchOperation *self, GDataEntry *entry, GDataBatchOperationCallback callback, gpointer user_data) +{ + g_return_val_if_fail (GDATA_IS_BATCH_OPERATION (self), 0); + g_return_val_if_fail (GDATA_IS_ENTRY (entry), 0); + g_return_val_if_fail (self->priv->has_run == FALSE, 0); + + return add_operation (self, GDATA_BATCH_OPERATION_INSERTION, entry, callback, user_data); +} + +/** + * gdata_batch_operation_add_update: + * @self: a #GDataBatchOperation + * @entry: the #GDataEntry to update + * @callback: (scope async): a #GDataBatchOperationCallback to call when the update is finished, or %NULL + * @user_data: (closure): data to pass to the @callback function + * + * Add an entry to the #GDataBatchOperation, to be updated on the server when the operation is run. The update will return the updated version of + * @entry. @entry is reffed by the function, so may be freed after it returns. + * + * Note that a single batch operation should not operate on a given #GDataEntry more than once, as there's no guarantee about the order in which the + * batch operation's operations will be performed. + * + * @callback will be called as specified in the documentation for gdata_batch_operation_add_query(), with an @operation_type of + * %GDATA_BATCH_OPERATION_UPDATE. + * + * Return value: operation ID for the added update, or 0 + * + * Since: 0.7.0 + */ +guint +gdata_batch_operation_add_update (GDataBatchOperation *self, GDataEntry *entry, GDataBatchOperationCallback callback, gpointer user_data) +{ + g_return_val_if_fail (GDATA_IS_BATCH_OPERATION (self), 0); + g_return_val_if_fail (GDATA_IS_ENTRY (entry), 0); + g_return_val_if_fail (self->priv->has_run == FALSE, 0); + + return add_operation (self, GDATA_BATCH_OPERATION_UPDATE, entry, callback, user_data); +} + +/** + * gdata_batch_operation_add_deletion: + * @self: a #GDataBatchOperation + * @entry: the #GDataEntry to delete + * @callback: (scope async): a #GDataBatchOperationCallback to call when the deletion is finished, or %NULL + * @user_data: (closure): data to pass to the @callback function + * + * Add an entry to the #GDataBatchOperation, to be deleted on the server when the operation is run. @entry is reffed by the function, so may be freed + * after it returns. + * + * Note that a single batch operation should not operate on a given #GDataEntry more than once, as there's no guarantee about the order in which the + * batch operation's operations will be performed. + * + * @callback will be called as specified in the documentation for gdata_batch_operation_add_query(), with an @operation_type of + * %GDATA_BATCH_OPERATION_DELETION. + * + * Return value: operation ID for the added deletion, or 0 + * + * Since: 0.7.0 + */ +guint +gdata_batch_operation_add_deletion (GDataBatchOperation *self, GDataEntry *entry, GDataBatchOperationCallback callback, gpointer user_data) +{ + g_return_val_if_fail (GDATA_IS_BATCH_OPERATION (self), 0); + g_return_val_if_fail (GDATA_IS_ENTRY (entry), 0); + g_return_val_if_fail (self->priv->has_run == FALSE, 0); + + return add_operation (self, GDATA_BATCH_OPERATION_DELETION, entry, callback, user_data); +} + +/** + * gdata_batch_operation_run: + * @self: a #GDataBatchOperation + * @cancellable: (allow-none): a #GCancellable, or %NULL + * @error: a #GError, or %NULL + * + * Run the #GDataBatchOperation synchronously. This will send all the operations in the batch operation to the server, and call their respective + * callbacks synchronously (i.e. before gdata_batch_operation_run() returns, and in the same thread that called gdata_batch_operation_run()) as the + * server returns results for each operation. + * + * The callbacks for all of the operations in the batch operation are always guaranteed to be called, even if the batch operation as a whole fails. + * Each callback will be called exactly once for each time gdata_batch_operation_run() is called. + * + * The return value of the function indicates whether the overall batch operation was successful, and doesn't indicate the status of any of the + * operations it comprises. gdata_batch_operation_run() could return %TRUE even if all of its operations failed. + * + * @cancellable can be used to cancel the entire batch operation any time before or during the network activity. If @cancellable is cancelled + * after network activity has finished, gdata_batch_operation_run() will continue and finish as normal. + * + * Return value: %TRUE on success, %FALSE otherwise + * + * Since: 0.7.0 + */ +gboolean +gdata_batch_operation_run (GDataBatchOperation *self, GCancellable *cancellable, GError **error) +{ + GDataBatchOperationPrivate *priv = self->priv; + SoupMessage *message; + GDataFeed *feed; + GTimeVal updated; + gchar *upload_data; + guint status; + GHashTableIter iter; + gpointer op_id; + BatchOperation *op; + GError *child_error = NULL; + + g_return_val_if_fail (GDATA_IS_BATCH_OPERATION (self), FALSE); + g_return_val_if_fail (cancellable == NULL || G_IS_CANCELLABLE (cancellable), FALSE); + g_return_val_if_fail (error == NULL || *error == NULL, FALSE); + g_return_val_if_fail (priv->has_run == FALSE, FALSE); + + /* Check for early cancellation. */ + if (g_cancellable_set_error_if_cancelled (cancellable, error)) { + return FALSE; + } + + /* Check whether the service actually supports these kinds of + * operations. */ + g_hash_table_iter_init (&iter, priv->operations); + while (g_hash_table_iter_next (&iter, &op_id, (gpointer*) &op) == TRUE) { + GDataBatchable *batchable = GDATA_BATCHABLE (priv->service); + GDataBatchableIface *batchable_iface; + + batchable_iface = GDATA_BATCHABLE_GET_IFACE (batchable); + + if (batchable_iface->is_supported != NULL && + !batchable_iface->is_supported (op->type)) { + g_set_error (error, GDATA_SERVICE_ERROR, + GDATA_SERVICE_ERROR_WITH_BATCH_OPERATION, + _("Batch operations are unsupported by " + "this service.")); + return FALSE; + } + } + + message = _gdata_service_build_message (priv->service, priv->authorization_domain, SOUP_METHOD_POST, priv->feed_uri, NULL, TRUE); + + /* Build the request */ + g_get_current_time (&updated); + feed = _gdata_feed_new (GDATA_TYPE_FEED, "Batch operation feed", + "batch1", updated.tv_sec); + + g_hash_table_iter_init (&iter, priv->operations); + while (g_hash_table_iter_next (&iter, &op_id, (gpointer*) &op) == TRUE) { + if (op->type == GDATA_BATCH_OPERATION_QUERY) { + /* Queries are weird; build a new throwaway entry, and add it to the feed */ + GDataEntry *entry; + GDataEntryClass *klass; + gchar *entry_uri; + + klass = g_type_class_ref (op->entry_type); + g_assert (klass->get_entry_uri != NULL); + + entry_uri = klass->get_entry_uri (op->query_id); + entry = gdata_entry_new (entry_uri); + g_free (entry_uri); + + gdata_entry_set_title (entry, "Batch operation query"); + _gdata_entry_set_updated (entry, updated.tv_sec); + + _gdata_entry_set_batch_data (entry, op->id, op->type); + _gdata_feed_add_entry (feed, entry); + + g_type_class_unref (klass); + g_object_unref (entry); + } else { + /* Everything else just dumps the entry's XML in the request */ + _gdata_entry_set_batch_data (op->entry, op->id, op->type); + _gdata_feed_add_entry (feed, op->entry); + } + } + + upload_data = gdata_parsable_get_xml (GDATA_PARSABLE (feed)); + soup_message_set_request (message, "application/atom+xml", SOUP_MEMORY_TAKE, upload_data, strlen (upload_data)); + + g_object_unref (feed); + + /* Ensure that this GDataBatchOperation can't be run again */ + priv->has_run = TRUE; + + /* Send the message */ + status = _gdata_service_send_message (priv->service, message, cancellable, &child_error); + + if (status != SOUP_STATUS_OK) { + /* Iff status is SOUP_STATUS_NONE or SOUP_STATUS_CANCELLED, child_error has already been set */ + if (status != SOUP_STATUS_NONE && status != SOUP_STATUS_CANCELLED) { + /* Error */ + GDataServiceClass *klass = GDATA_SERVICE_GET_CLASS (priv->service); + g_assert (klass->parse_error_response != NULL); + klass->parse_error_response (priv->service, GDATA_OPERATION_BATCH, status, message->reason_phrase, message->response_body->data, + message->response_body->length, &child_error); + } + g_object_unref (message); + + goto error; + } + + /* Parse the XML; GDataBatchFeed will fire off the relevant callbacks */ + g_assert (message->response_body->data != NULL); + feed = GDATA_FEED (_gdata_parsable_new_from_xml (GDATA_TYPE_BATCH_FEED, message->response_body->data, message->response_body->length, + self, &child_error)); + g_object_unref (message); + + if (feed == NULL) + goto error; + g_object_unref (feed); + + return TRUE; + +error: + /* Call the callbacks for each of our operations to notify them of the error */ + g_hash_table_iter_init (&iter, priv->operations); + while (g_hash_table_iter_next (&iter, &op_id, (gpointer*) &op) == TRUE) + _gdata_batch_operation_run_callback (self, op, NULL, g_error_copy (child_error)); + + g_propagate_error (error, child_error); + + return FALSE; +} + +static void +run_thread (GTask *task, gpointer source_object, gpointer task_data, GCancellable *cancellable) +{ + GDataBatchOperation *operation = GDATA_BATCH_OPERATION (source_object); + g_autoptr(GError) error = NULL; + + /* Run the batch operation and return */ + if (!gdata_batch_operation_run (operation, cancellable, &error)) + g_task_return_error (task, g_steal_pointer (&error)); + else + g_task_return_boolean (task, TRUE); +} + +/** + * gdata_batch_operation_run_async: + * @self: a #GDataBatchOperation + * @cancellable: (allow-none): a #GCancellable, or %NULL + * @callback: a #GAsyncReadyCallback to call when the batch operation is finished, or %NULL + * @user_data: (closure): data to pass to the @callback function + * + * Run the #GDataBatchOperation asynchronously. This will send all the operations in the batch operation to the server, and call their respective + * callbacks asynchronously (i.e. in idle functions in the main thread, usually after gdata_batch_operation_run_async() has returned) as the + * server returns results for each operation. @self is reffed when this function is called, so can safely be unreffed after this function returns. + * + * For more details, see gdata_batch_operation_run(), which is the synchronous version of this function. + * + * When the entire batch operation is finished, @callback will be called. You can then call gdata_batch_operation_run_finish() to get the results of + * the batch operation. + * + * Since: 0.7.0 + */ +void +gdata_batch_operation_run_async (GDataBatchOperation *self, GCancellable *cancellable, GAsyncReadyCallback callback, gpointer user_data) +{ + g_autoptr(GTask) task = NULL; + + g_return_if_fail (GDATA_IS_BATCH_OPERATION (self)); + g_return_if_fail (cancellable == NULL || G_IS_CANCELLABLE (cancellable)); + g_return_if_fail (self->priv->has_run == FALSE); + + /* Mark the operation as async for the purposes of deciding where to call the callbacks */ + self->priv->is_async = TRUE; + + task = g_task_new (self, cancellable, callback, user_data); + g_task_set_source_tag (task, gdata_batch_operation_run_async); + g_task_run_in_thread (task, run_thread); +} + +/** + * gdata_batch_operation_run_finish: + * @self: a #GDataBatchOperation + * @async_result: a #GAsyncResult + * @error: a #GError, or %NULL + * + * Finishes an asynchronous batch operation run with gdata_batch_operation_run_async(). + * + * Return values are as for gdata_batch_operation_run(). + * + * Return value: %TRUE on success, %FALSE otherwise + * + * Since: 0.7.0 + */ +gboolean +gdata_batch_operation_run_finish (GDataBatchOperation *self, GAsyncResult *async_result, GError **error) +{ + GDataBatchOperationPrivate *priv = self->priv; + g_autoptr(GError) child_error = NULL; + + g_return_val_if_fail (GDATA_IS_BATCH_OPERATION (self), FALSE); + g_return_val_if_fail (G_IS_ASYNC_RESULT (async_result), FALSE); + g_return_val_if_fail (error == NULL || *error == NULL, FALSE); + g_return_val_if_fail (g_task_is_valid (async_result, self), FALSE); + g_return_val_if_fail (g_async_result_is_tagged (async_result, gdata_batch_operation_run_async), FALSE); + + if (!g_task_propagate_boolean (G_TASK (async_result), &child_error)) { + if (priv->has_run == FALSE) { + GHashTableIter iter; + gpointer op_id; + BatchOperation *op; + + /* Temporarily mark the operation as synchronous so that the callbacks get dispatched in this thread */ + priv->is_async = FALSE; + + /* If has_run hasn't been set, the call to gdata_batch_operation_run() was never made in the thread, and so none of the + * operations' callbacks have been called. Call the callbacks for each of our operations to notify them of the error. + * If has_run has been set, gdata_batch_operation_run() has already done this for us. */ + g_hash_table_iter_init (&iter, priv->operations); + while (g_hash_table_iter_next (&iter, &op_id, (gpointer*) &op) == TRUE) + _gdata_batch_operation_run_callback (self, op, NULL, g_error_copy (child_error)); + + priv->is_async = TRUE; + } + + g_propagate_error (error, g_steal_pointer (&child_error)); + + return FALSE; + } + + return TRUE; +} diff --git a/gdata/gdata-batch-operation.h b/gdata/gdata-batch-operation.h new file mode 100644 index 0000000..1626a28 --- /dev/null +++ b/gdata/gdata-batch-operation.h @@ -0,0 +1,150 @@ +/* -*- Mode: C; indent-tabs-mode: t; c-basic-offset: 8; tab-width: 8 -*- */ +/* + * GData Client + * Copyright (C) Philip Withnall 2010 + * + * GData Client is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * GData Client is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with GData Client. If not, see . + */ + +#ifndef GDATA_BATCH_OPERATION_H +#define GDATA_BATCH_OPERATION_H + +#include +#include + +#include +#include +#include + +G_BEGIN_DECLS + +/** + * GDATA_LINK_BATCH: + * + * The relation type URI for the batch operation URI for a given #GDataFeed. + * + * For more information, see the GData specification. + * + * Since: 0.7.0 + */ +#define GDATA_LINK_BATCH "http://schemas.google.com/g/2005#batch" + +/** + * GDataBatchOperationType: + * @GDATA_BATCH_OPERATION_QUERY: a query operation + * @GDATA_BATCH_OPERATION_INSERTION: an insertion operation + * @GDATA_BATCH_OPERATION_UPDATE: an update operation + * @GDATA_BATCH_OPERATION_DELETION: a deletion operation + * + * Indicates which type of batch operation caused the current #GDataBatchOperationCallback to be called. + * + * Since: 0.7.0 + */ +typedef enum { + GDATA_BATCH_OPERATION_QUERY = 0, + GDATA_BATCH_OPERATION_INSERTION, + GDATA_BATCH_OPERATION_UPDATE, + GDATA_BATCH_OPERATION_DELETION +} GDataBatchOperationType; + +/** + * GDataBatchOperationCallback: + * @operation_id: the operation ID returned from gdata_batch_operation_add_*() + * @operation_type: the type of operation which was requested + * @entry: the result of the operation, or %NULL + * @error: a #GError describing any error which occurred, or %NULL + * @user_data: user data passed to the callback + * + * Callback function called once for each operation in a batch operation run. The operation is identified by @operation_id and @operation_type (where + * @operation_id is the ID returned by the relevant call to gdata_batch_operation_add_query(), gdata_batch_operation_add_insertion(), + * gdata_batch_operation_add_update() or gdata_batch_operation_add_deletion(), and @operation_type shows which one of the above was called). + * + * If the operation was successful, the resulting #GDataEntry will be passed in as @entry, and @error will be %NULL. Otherwise, @entry will be %NULL + * and a descriptive error will be in @error. If @operation_type is %GDATA_BATCH_OPERATION_DELETION, @entry will always be %NULL, and @error will be + * %NULL or non-%NULL as appropriate. + * + * If the callback code needs to retain a copy of @entry, it must be referenced (with g_object_ref()). Similarly, @error is owned by the calling code, + * and must not be freed. + * + * The callback is called in the main thread, and there is no guarantee on the order in which the callbacks for the operations in a run are executed, + * or whether they will be called in a timely manner. It is, however, guaranteed that they will all be called before the #GAsyncReadyCallback which + * signals the completion of the run (if initiated with gdata_batch_operation_run_async()) is called; or gdata_batch_operation_run() returns (if + * initiated synchronously). + * + * Since: 0.7.0 + */ +typedef void (*GDataBatchOperationCallback) (guint operation_id, GDataBatchOperationType operation_type, GDataEntry *entry, + GError *error, gpointer user_data); + +#define GDATA_TYPE_BATCH_OPERATION (gdata_batch_operation_get_type ()) +#define GDATA_BATCH_OPERATION(o) (G_TYPE_CHECK_INSTANCE_CAST ((o), GDATA_TYPE_BATCH_OPERATION, GDataBatchOperation)) +#define GDATA_BATCH_OPERATION_CLASS(k) (G_TYPE_CHECK_CLASS_CAST((k), GDATA_TYPE_BATCH_OPERATION, GDataBatchOperationClass)) +#define GDATA_IS_BATCH_OPERATION(o) (G_TYPE_CHECK_INSTANCE_TYPE ((o), GDATA_TYPE_BATCH_OPERATION)) +#define GDATA_IS_BATCH_OPERATION_CLASS(k) (G_TYPE_CHECK_CLASS_TYPE ((k), GDATA_TYPE_BATCH_OPERATION)) +#define GDATA_BATCH_OPERATION_GET_CLASS(o) (G_TYPE_INSTANCE_GET_CLASS ((o), GDATA_TYPE_BATCH_OPERATION, GDataBatchOperationClass)) + +typedef struct _GDataBatchOperationPrivate GDataBatchOperationPrivate; + +/** + * GDataBatchOperation: + * + * All the fields in the #GDataBatchOperation structure are private and should never be accessed directly. + * + * Since: 0.7.0 + */ +typedef struct { + GObject parent; + GDataBatchOperationPrivate *priv; +} GDataBatchOperation; + +/** + * GDataBatchOperationClass: + * + * All the fields in the #GDataBatchOperationClass structure are private and should never be accessed directly. + * + * Since: 0.7.0 + */ +typedef struct { + /*< private >*/ + GObjectClass parent; + + /*< private >*/ + /* Padding for future expansion */ + void (*_g_reserved0) (void); + void (*_g_reserved1) (void); + void (*_g_reserved2) (void); + void (*_g_reserved3) (void); + void (*_g_reserved4) (void); + void (*_g_reserved5) (void); +} GDataBatchOperationClass; + +GType gdata_batch_operation_get_type (void) G_GNUC_CONST; + +GDataService *gdata_batch_operation_get_service (GDataBatchOperation *self) G_GNUC_PURE; +GDataAuthorizationDomain *gdata_batch_operation_get_authorization_domain (GDataBatchOperation *self) G_GNUC_PURE; +const gchar *gdata_batch_operation_get_feed_uri (GDataBatchOperation *self) G_GNUC_PURE; + +guint gdata_batch_operation_add_query (GDataBatchOperation *self, const gchar *id, GType entry_type, + GDataBatchOperationCallback callback, gpointer user_data); +guint gdata_batch_operation_add_insertion (GDataBatchOperation *self, GDataEntry *entry, GDataBatchOperationCallback callback, gpointer user_data); +guint gdata_batch_operation_add_update (GDataBatchOperation *self, GDataEntry *entry, GDataBatchOperationCallback callback, gpointer user_data); +guint gdata_batch_operation_add_deletion (GDataBatchOperation *self, GDataEntry *entry, GDataBatchOperationCallback callback, gpointer user_data); + +gboolean gdata_batch_operation_run (GDataBatchOperation *self, GCancellable *cancellable, GError **error); +void gdata_batch_operation_run_async (GDataBatchOperation *self, GCancellable *cancellable, GAsyncReadyCallback callback, gpointer user_data); +gboolean gdata_batch_operation_run_finish (GDataBatchOperation *self, GAsyncResult *async_result, GError **error); + +G_END_DECLS + +#endif /* !GDATA_BATCH_OPERATION_H */ diff --git a/gdata/gdata-batch-private.h b/gdata/gdata-batch-private.h new file mode 100644 index 0000000..8c682f0 --- /dev/null +++ b/gdata/gdata-batch-private.h @@ -0,0 +1,44 @@ +/* -*- Mode: C; indent-tabs-mode: t; c-basic-offset: 8; tab-width: 8 -*- */ +/* + * GData Client + * Copyright (C) Philip Withnall 2010 + * + * GData Client is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * GData Client is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with GData Client. If not, see . + */ + +#ifndef GDATA_BATCH_PRIVATE_H +#define GDATA_BATCH_PRIVATE_H + +#include +#include + +G_BEGIN_DECLS + +typedef struct { + guint id; + GDataBatchOperationType type; + GDataBatchOperationCallback callback; + gpointer user_data; + gchar *query_id; /* only used for queries */ + GType entry_type; /* only used for queries */ + GError *error; + GDataEntry *entry; /* used for anything except queries, and to store the results of all operations */ +} BatchOperation; + +G_GNUC_INTERNAL BatchOperation *_gdata_batch_operation_get_operation (GDataBatchOperation *self, guint id) G_GNUC_PURE; +G_GNUC_INTERNAL void _gdata_batch_operation_run_callback (GDataBatchOperation *self, BatchOperation *op, GDataEntry *entry, GError *error); + +G_END_DECLS + +#endif /* !GDATA_BATCH_PRIVATE_H */ diff --git a/gdata/gdata-batchable.c b/gdata/gdata-batchable.c new file mode 100644 index 0000000..4568dec --- /dev/null +++ b/gdata/gdata-batchable.c @@ -0,0 +1,81 @@ +/* -*- Mode: C; indent-tabs-mode: t; c-basic-offset: 8; tab-width: 8 -*- */ +/* + * GData Client + * Copyright (C) Philip Withnall 2010 + * + * GData Client is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * GData Client is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with GData Client. If not, see . + */ + +/** + * SECTION:gdata-batchable + * @short_description: GData batch service interface + * @stability: Stable + * @include: gdata/gdata-batchable.h + * + * #GDataBatchable is an interface which can be implemented by #GDataServices which support batch operations on their entries. It allows the + * creation of a #GDataBatchOperation for the service, which allows a set of batch operations to be run. + * + * Since: 0.7.0 + */ + +#include +#include + +#include "gdata-batchable.h" +#include "gdata-service.h" +#include "gdata-batch-operation.h" + +GType +gdata_batchable_get_type (void) +{ + static GType batchable_type = 0; + + if (!batchable_type) { + batchable_type = g_type_register_static_simple (G_TYPE_INTERFACE, "GDataBatchable", + sizeof (GDataBatchableIface), + NULL, 0, NULL, 0); + g_type_interface_add_prerequisite (batchable_type, GDATA_TYPE_SERVICE); + } + + return batchable_type; +} + +/** + * gdata_batchable_create_operation: + * @self: a #GDataBatchable + * @domain: (allow-none): the #GDataAuthorizationDomain to authorize the operation, or %NULL + * @feed_uri: the URI to send the batch operation request to + * + * Creates a new #GDataBatchOperation for the given #GDataBatchable service, and with the given @feed_uri. @feed_uri is normally the %GDATA_LINK_BATCH + * link URI in the appropriate #GDataFeed from the service. If authorization will be required to perform any of the requests in the batch operation, + * @domain must be non-%NULL, and must be an authorization domain which covers all of the requests. Otherwise, @domain may be %NULL if authorization + * is not required. + * + * Return value: (transfer full): a new #GDataBatchOperation; unref with g_object_unref() + * + * Since: 0.9.0 + */ +GDataBatchOperation * +gdata_batchable_create_operation (GDataBatchable *self, GDataAuthorizationDomain *domain, const gchar *feed_uri) +{ + g_return_val_if_fail (GDATA_IS_BATCHABLE (self), NULL); + g_return_val_if_fail (domain == NULL || GDATA_IS_AUTHORIZATION_DOMAIN (domain), NULL); + g_return_val_if_fail (feed_uri != NULL, NULL); + + return g_object_new (GDATA_TYPE_BATCH_OPERATION, + "service", self, + "authorization-domain", domain, + "feed-uri", feed_uri, + NULL); +} diff --git a/gdata/gdata-batchable.h b/gdata/gdata-batchable.h new file mode 100644 index 0000000..5dce9a1 --- /dev/null +++ b/gdata/gdata-batchable.h @@ -0,0 +1,76 @@ +/* -*- Mode: C; indent-tabs-mode: t; c-basic-offset: 8; tab-width: 8 -*- */ +/* + * GData Client + * Copyright (C) Philip Withnall 2010 + * + * GData Client is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * GData Client is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with GData Client. If not, see . + */ + +#ifndef GDATA_BATCHABLE_H +#define GDATA_BATCHABLE_H + +#include +#include + +#include +#include +#include + +G_BEGIN_DECLS + +#define GDATA_TYPE_BATCHABLE (gdata_batchable_get_type ()) +#define GDATA_BATCHABLE(o) (G_TYPE_CHECK_INSTANCE_CAST ((o), GDATA_TYPE_BATCHABLE, GDataBatchable)) +#define GDATA_BATCHABLE_CLASS(k) (G_TYPE_CHECK_CLASS_CAST((k), GDATA_TYPE_BATCHABLE, GDataBatchableIface)) +#define GDATA_IS_BATCHABLE(o) (G_TYPE_CHECK_INSTANCE_TYPE ((o), GDATA_TYPE_BATCHABLE)) +#define GDATA_BATCHABLE_GET_IFACE(o) (G_TYPE_INSTANCE_GET_INTERFACE ((o), GDATA_TYPE_BATCHABLE, GDataBatchableIface)) + +/** + * GDataBatchable: + * + * All the fields in the #GDataBatchable structure are private and should never be accessed directly. + * + * Since: 0.7.0 + */ +typedef struct _GDataBatchable GDataBatchable; /* dummy typedef */ + +/** + * GDataBatchableIface: + * @is_supported: Determines whether the given #GDataBatchOperationType is + * supported by this #GDataBatchable; if not, operations using it will return + * %GDATA_SERVICE_ERROR_WITH_BATCH_OPERATION. It is valid for a + * #GDataBatchable to return %FALSE for all #GDataBatchOperationTypes if the + * server no longer supports batch operations. If this method is not + * implemented, it is assumed that all #GDataBatchOperationTypes are + * supported. Since: 0.17.2. + * + * All the fields in the #GDataBatchableIface structure are private and should never be accessed directly. + * + * Since: 0.7.0 + */ +typedef struct { + /*< private >*/ + GTypeInterface parent; + + /*< public >*/ + gboolean (*is_supported) (GDataBatchOperationType operation_type); +} GDataBatchableIface; + +GType gdata_batchable_get_type (void) G_GNUC_CONST; + +GDataBatchOperation *gdata_batchable_create_operation (GDataBatchable *self, GDataAuthorizationDomain *domain, + const gchar *feed_uri) G_GNUC_WARN_UNUSED_RESULT G_GNUC_MALLOC; + +G_END_DECLS + +#endif /* !GDATA_BATCHABLE_H */ diff --git a/gdata/gdata-buffer.c b/gdata/gdata-buffer.c new file mode 100644 index 0000000..ac42636 --- /dev/null +++ b/gdata/gdata-buffer.c @@ -0,0 +1,351 @@ +/* -*- Mode: C; indent-tabs-mode: t; c-basic-offset: 8; tab-width: 8 -*- */ +/* + * GData Client + * Copyright (C) Philip Withnall 2009 + * + * GData Client is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * GData Client is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with GData Client. If not, see . + */ + +/* + * SECTION:gdata-buffer + * @short_description: GData buffer to allow threadsafe buffering + * @stability: Stable + * @include: gdata/gdata-buffer.h + * + * #GDataBuffer is a simple object which allows threadsafe buffering of data meaning, for example, data can be received from + * the network in a "push" fashion, buffered, then sent out to an output stream in a "pull" fashion. + */ + +#include +#include +#include + +#include "gdata-buffer.h" + +struct _GDataBufferChunk { + /*< private >*/ + guint8 *data; + gsize length; + GDataBufferChunk *next; + /* Note: the data is actually allocated in the same memory block, so it's inside this comment right now. + * We simply set chunk->data to point to chunk + sizeof (GDataBufferChunk). */ +}; + +/** + * gdata_buffer_new: + * + * Creates a new empty #GDataBuffer. + * + * Return value: a new #GDataBuffer; free with gdata_buffer_free() + * + * Since: 0.5.0 + */ +GDataBuffer * +gdata_buffer_new (void) +{ + GDataBuffer *buffer = g_slice_new0 (GDataBuffer); + + g_mutex_init (&(buffer->mutex)); + g_cond_init (&(buffer->cond)); + + return buffer; +} + +/** + * gdata_buffer_free: + * + * Frees a #GDataBuffer. The function isn't threadsafe, so should only be called once + * use of the buffer has been reduced to only one thread (the reading thread, after + * the EOF has been reached). + * + * Since: 0.5.0 + */ +void +gdata_buffer_free (GDataBuffer *self) +{ + GDataBufferChunk *chunk, *next_chunk; + + g_return_if_fail (self != NULL); + + for (chunk = self->head; chunk != NULL; chunk = next_chunk) { + next_chunk = chunk->next; + g_free (chunk); + } + + g_cond_clear (&(self->cond)); + g_mutex_clear (&(self->mutex)); + + g_slice_free (GDataBuffer, self); +} + +/** + * gdata_buffer_push_data: + * @self: a #GDataBuffer + * @data: the data to push onto the buffer + * @length: the length of @data + * + * Pushes @length bytes of @data onto the buffer, taking a copy of the data. If @data is %NULL and @length is 0, + * the buffer will be marked as having reached the EOF, and subsequent calls to gdata_buffer_push_data() + * will fail and return %FALSE. + * + * Assuming the buffer hasn't reached EOF, this operation is guaranteed to succeed (unless memory allocation fails). + * + * This function holds the lock on the #GDataBuffer, and signals any waiting calls to gdata_buffer_pop_data() once + * the new data has been pushed onto the buffer. This function is threadsafe. + * + * Return value: %TRUE on success, %FALSE otherwise + * + * Since: 0.5.0 + */ +gboolean +gdata_buffer_push_data (GDataBuffer *self, const guint8 *data, gsize length) +{ + GDataBufferChunk *chunk; + + g_return_val_if_fail (self != NULL, 0); + + g_mutex_lock (&(self->mutex)); + + if (G_UNLIKELY (self->reached_eof == TRUE)) { + /* If we're marked as having reached EOF, don't accept any more data */ + g_mutex_unlock (&(self->mutex)); + return FALSE; + } else if (G_UNLIKELY (data == NULL && length == 0)) { + /* If @data is NULL and @length is 0, mark the buffer as having reached EOF, + * and signal any waiting threads. */ + self->reached_eof = TRUE; + g_cond_signal (&(self->cond)); + g_mutex_unlock (&(self->mutex)); + return FALSE; + } + + /* Create the chunk */ + chunk = g_malloc (sizeof (GDataBufferChunk) + length); + chunk->data = (guint8*) ((guint8*) chunk + sizeof (GDataBufferChunk)); /* pointer arithmetic in terms of bytes here */ + chunk->length = length; + chunk->next = NULL; + + /* Copy the data to the chunk */ + if (G_LIKELY (data != NULL)) + memcpy (chunk->data, data, length); + + /* Add it to the buffer's tail */ + if (self->tail != NULL) + *(self->tail) = chunk; + else + self->head = chunk; + self->tail = &(chunk->next); + self->total_length += length; + + /* Signal any threads waiting to pop that data is available */ + g_cond_signal (&(self->cond)); + + g_mutex_unlock (&(self->mutex)); + + return TRUE; +} + +typedef struct { + GDataBuffer *buffer; + gboolean *cancelled; +} CancelledData; + +static void +pop_cancelled_cb (GCancellable *cancellable, CancelledData *data) +{ + /* Signal the pop_data function that it should stop blocking and cancel */ + g_mutex_lock (&(data->buffer->mutex)); + *(data->cancelled) = TRUE; + g_cond_signal (&(data->buffer->cond)); + g_mutex_unlock (&(data->buffer->mutex)); +} + +/** + * gdata_buffer_pop_data: + * @self: a #GDataBuffer + * @data: (allow-none): return location for the popped data, or %NULL to just drop the data + * @length_requested: the number of bytes of data requested + * @reached_eof: return location for a value which is %TRUE when we've reached EOF, %FALSE otherwise, or %NULL + * @cancellable: (allow-none): a #GCancellable, or %NULL + * + * Pops up to @length_requested bytes off the head of the buffer and copies them to @data, which must be allocated by + * the caller and have enough space to store at most @length_requested bytes of output. + * + * If the buffer contains enough data to satisfy @length_requested, this function returns immediately. + * Otherwise, this function blocks until data is pushed onto the head of the buffer with gdata_buffer_pop_data(). If + * the buffer is marked as having reached the EOF, this function will not block, and will instead return the + * remaining data in the buffer. + * + * This function holds the lock on the #GDataBuffer, and will automatically be signalled of new data pushed onto the + * buffer if it's blocking. + * + * If @cancellable is provided, calling g_cancellable_cancel() on it from another thread will cause the call to + * gdata_buffer_pop_data() to return immediately with whatever data it can find. + * + * Return value: the number of bytes returned in @data + * + * Since: 0.5.0 + */ +gsize +gdata_buffer_pop_data (GDataBuffer *self, guint8 *data, gsize length_requested, gboolean *reached_eof, GCancellable *cancellable) +{ + GDataBufferChunk *chunk; + gsize return_length = 0, length_remaining; + gulong cancelled_signal = 0; + gboolean cancelled = FALSE; + + g_return_val_if_fail (self != NULL, 0); + g_return_val_if_fail (cancellable == NULL || G_IS_CANCELLABLE (cancellable), 0); + + /* In the case: + * - length_requested < amount available: return length_requested + * - length_requested > amount available: block until more is available, return length_requested + * - length_requested > amount available and we've reached EOF: don't block, return all remaining data + * - length_requested is a whole number of chunks: remove those chunks, return length_requested + * - length_requested is less than one chunk: remove no chunks, return length_requested, set head_read_offset + * - length_requested is a fraction of multiple chunks: remove whole chunks, return length_requested, set head_read_offset + * for remaining fraction */ + + /* Set up a handler so we can stop if we're cancelled. This must be done before we lock @self->mutex, or deadlock could occur if the + * cancellable has already been cancelled — g_cancellable_connect() would call pop_cancelled_cb() directly, and it would attempt to lock + * @self->mutex again. */ + if (cancellable != NULL) { + CancelledData cancelled_data; + + cancelled_data.buffer = self; + cancelled_data.cancelled = &cancelled; + + cancelled_signal = g_cancellable_connect (cancellable, (GCallback) pop_cancelled_cb, &cancelled_data, NULL); + } + + g_mutex_lock (&(self->mutex)); + + if (self->reached_eof == TRUE && length_requested > self->total_length) { + /* Return data up to the EOF */ + return_length = self->total_length; + } else if (length_requested > self->total_length) { + /* Block until more data is available */ + while (length_requested > self->total_length) { + /* If we've already been cancelled, don't wait on @self->cond, since it'll never be signalled again. */ + if (cancelled == FALSE) { + g_cond_wait (&(self->cond), &(self->mutex)); + } + + /* If the g_cond_wait() returned because it was signalled from the GCancellable callback (rather than from + * data being pushed into the buffer), stop blocking for data and make do with what we have so far. */ + if (cancelled == TRUE || self->reached_eof == TRUE) { + return_length = MIN (length_requested, self->total_length); + break; + } else { + return_length = length_requested; + } + } + } else { + return_length = length_requested; + } + + /* Set reached_eof */ + if (reached_eof != NULL) + *reached_eof = self->reached_eof && length_requested >= self->total_length; + + /* Return if we haven't got any data to pop (i.e. if we were cancelled before even one chunk arrived) */ + if (return_length == 0) + goto done; + + /* Otherwise, get on with things */ + length_remaining = return_length; + + /* We can't assume we'll have enough data, since we may have reached EOF */ + chunk = self->head; + while (chunk != NULL && self->head_read_offset + length_remaining >= chunk->length) { + GDataBufferChunk *next_chunk; + gsize chunk_length = chunk->length - self->head_read_offset; + + /* Copy the data to the output */ + length_remaining -= chunk_length; + if (data != NULL) { + memcpy (data, chunk->data + self->head_read_offset, chunk_length); + data += chunk_length; + } + + /* Free the chunk and move on */ + next_chunk = chunk->next; + g_free (chunk); + chunk = next_chunk; + + /* Reset the head read offset, since we've processed at least the first chunk now */ + self->head_read_offset = 0; + } + + /* If the requested length is still > 0, it must be < chunk->length, and chunk must != NULL (if it does, the cached total_length has + * been corrupted somewhere). */ + if (G_LIKELY (length_remaining > 0)) { + g_assert (chunk != NULL); + g_assert_cmpuint (length_remaining, <=, chunk->length); + + /* Copy the requested data to the output */ + if (data != NULL) { + memcpy (data, chunk->data + self->head_read_offset, length_remaining); + } + self->head_read_offset += length_remaining; + } + + self->head = chunk; + if (self->head == NULL) + self->tail = NULL; + self->total_length -= return_length; + +done: + g_mutex_unlock (&(self->mutex)); + + /* Disconnect from the cancelled signal. Note that this has to be done without @self->mutex held, or deadlock can occur. + * (g_cancellable_disconnect() waits for any in-progress signal handler call to finish, which can't happen until the mutex is released.) */ + if (cancelled_signal != 0) + g_cancellable_disconnect (cancellable, cancelled_signal); + + return return_length; +} + +/** + * gdata_buffer_pop_all_data: + * @self: a #GDataBuffer + * @data: return location for the popped data + * @maximum_length: the maximum number of bytes to return + * @reached_eof: return location for a value which is %TRUE when we've reached EOF, %FALSE otherwise, or %NULL + * + * Pops as much data as possible off the #GDataBuffer, up to a limit of @maximum_length bytes. If fewer bytes exist + * in the buffer, fewer bytes will be returned. If more bytes exist in the buffer, @maximum_length bytes will be returned. + * + * If 0 bytes exist in the buffer, this function will block until data is available. Otherwise, it will never block. + * + * Return value: the number of bytes returned in @data (guaranteed to be more than 0 and at most @maximum_length) + * + * Since: 0.5.0 + */ +gsize +gdata_buffer_pop_data_limited (GDataBuffer *self, guint8 *data, gsize maximum_length, gboolean *reached_eof) +{ + g_return_val_if_fail (self != NULL, 0); + g_return_val_if_fail (data != NULL, 0); + g_return_val_if_fail (maximum_length > 0, 0); + + /* If there's no data in the buffer, block until some is available */ + g_mutex_lock (&(self->mutex)); + if (self->total_length == 0 && self->reached_eof == FALSE) { + g_cond_wait (&(self->cond), &(self->mutex)); + } + g_mutex_unlock (&(self->mutex)); + + return gdata_buffer_pop_data (self, data, MIN (maximum_length, self->total_length), reached_eof, NULL); +} diff --git a/gdata/gdata-buffer.h b/gdata/gdata-buffer.h new file mode 100644 index 0000000..0fbd14b --- /dev/null +++ b/gdata/gdata-buffer.h @@ -0,0 +1,59 @@ +/* -*- Mode: C; indent-tabs-mode: t; c-basic-offset: 8; tab-width: 8 -*- */ +/* + * GData Client + * Copyright (C) Philip Withnall 2009 + * + * GData Client is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * GData Client is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with GData Client. If not, see . + */ + +#ifndef GDATA_BUFFER_H +#define GDATA_BUFFER_H + +#include +#include +#include + +G_BEGIN_DECLS + +typedef struct _GDataBufferChunk GDataBufferChunk; + +/** + * GDataBuffer: + * + * All the fields in the #GDataBuffer structure are private and should never be accessed directly. + * + * Since: 0.5.0 + */ +typedef struct { + /*< private >*/ + GDataBufferChunk *head; + gsize head_read_offset; /* number of bytes which have already been popped from the head chunk */ + gsize total_length; /* total length of all the chunks available to read (i.e. head_read_offset is already subtracted) */ + gboolean reached_eof; /* set to TRUE only once we've reached EOF */ + GDataBufferChunk **tail; /* pointer to the GDataBufferChunk->next field of the current tail chunk */ + + GMutex mutex; /* mutex protecting the entire structure on push and pop */ + GCond cond; /* a GCond to allow a popping thread to block on data being pushed into the buffer */ +} GDataBuffer; + +GDataBuffer *gdata_buffer_new (void) G_GNUC_WARN_UNUSED_RESULT G_GNUC_MALLOC; +void gdata_buffer_free (GDataBuffer *self); + +gboolean gdata_buffer_push_data (GDataBuffer *self, const guint8 *data, gsize length); +gsize gdata_buffer_pop_data (GDataBuffer *self, guint8 *data, gsize length_requested, gboolean *reached_eof, GCancellable *cancellable); +gsize gdata_buffer_pop_data_limited (GDataBuffer *self, guint8 *data, gsize maximum_length, gboolean *reached_eof); + +G_END_DECLS + +#endif /* !GDATA_BUFFER_H */ diff --git a/gdata/gdata-client-login-authorizer.c b/gdata/gdata-client-login-authorizer.c new file mode 100644 index 0000000..31edee3 --- /dev/null +++ b/gdata/gdata-client-login-authorizer.c @@ -0,0 +1,1344 @@ +/* -*- Mode: C; indent-tabs-mode: t; c-basic-offset: 8; tab-width: 8 -*- */ +/* + * GData Client + * Copyright (C) Philip Withnall 2011 + * + * GData Client is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * GData Client is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with GData Client. If not, see . + */ + +/** + * SECTION:gdata-client-login-authorizer + * @short_description: GData ClientLogin authorization interface + * @stability: Stable + * @include: gdata/gdata-client-login-authorizer.h + * + * #GDataClientLoginAuthorizer provides an implementation of the #GDataAuthorizer interface for authentication and authorization using the deprecated + * ClientLogin process. + * + * As noted, the ClientLogin process is being deprecated in favour of OAuth 2.0. This API is not (yet) deprecated, however. One of the main reasons + * for ClientLogin being deprecated is that it cannot support two-factor authentication as now available to Google Accounts. Any account which has + * two-factor authentication enabled has to use a service-specific one-time password instead if a client is authenticating with + * #GDataClientLoginAuthorizer. More documentation about this is + * available online. + * Note that newer services cannot be authenticated against using ClientLogin, + * and a #GDataOAuth2Authorizer must be used instead. + * + * The ClientLogin process is a simple one whereby the user's Google Account username and password are sent over an HTTPS connection to the Google + * Account servers (when gdata_client_login_authorizer_authenticate() is called), which return an authorization token. This token is then attached to + * all future requests to the online service. A slight complication is that the Google Accounts service may return a CAPTCHA challenge instead of + * immediately returning an authorization token. In this case, the #GDataClientLoginAuthorizer::captcha-challenge signal will be emitted, and the + * user's response to the CAPTCHA should be returned by the handler. + * + * ClientLogin does not natively support authorization against multiple authorization domains concurrently with a single authorization token, so it + * has to be simulated by maintaining multiple authorization tokens if multiple authorization domains are used. This means that proportionally more + * network requests are made when gdata_client_login_authorizer_authenticate() is called, which will be proportionally slower. Handling of the + * multiple authorization tokens is otherwise transparent to the client. + * + * Each authorization token is long lived, so reauthorization is rarely necessary with #GDataClientLoginAuthorizer. Consequently, refreshing + * authorization using gdata_authorizer_refresh_authorization() is not supported by #GDataClientLoginAuthorizer, and will immediately return %FALSE + * with no error set. + * + * + * Authenticating Asynchronously Using ClientLogin + * + * GDataSomeService *service; + * GDataClientLoginAuthorizer *authorizer; + * + * /* Create an authorizer and authenticate and authorize the service we're using, asynchronously. */ + * authorizer = gdata_client_login_authorizer_new ("companyName-applicationName-versionID", GDATA_TYPE_SOME_SERVICE); + * gdata_client_login_authorizer_authenticate_async (authorizer, username, password, cancellable, + * (GAsyncReadyCallback) authenticate_cb, user_data); + * + * /* Create a service object and link it with the authorizer */ + * service = gdata_some_service_new (GDATA_AUTHORIZER (authorizer)); + * + * static void + * authenticate_cb (GDataClientLoginAuthorizer *authorizer, GAsyncResult *async_result, gpointer user_data) + * { + * GError *error = NULL; + * + * if (gdata_client_login_authorizer_authenticate_finish (authorizer, async_result, &error) == FALSE) { + * /* Notify the user of all errors except cancellation errors */ + * if (!g_error_matches (error, G_IO_ERROR, G_IO_ERROR_CANCELLED)) { + * g_error ("Authentication failed: %s", error->message); + * } + * g_error_free (error); + * return; + * } + * + * /* (The client is now authenticated and authorized against the service. + * * It can now proceed to execute queries on the service object which require the user to be authenticated.) */ + * } + * + * g_object_unref (service); + * g_object_unref (authorizer); + * + * + * + * Since: 0.9.0 + */ + +#include +#include +#include +#include + +#include "gdata-service.h" +#include "gdata-private.h" +#include "gdata-marshal.h" +#include "gdata-client-login-authorizer.h" + +/* The default e-mail domain to use for usernames */ +#define EMAIL_DOMAIN "gmail.com" + +GQuark +gdata_client_login_authorizer_error_quark (void) +{ + return g_quark_from_static_string ("gdata-client-login-authorizer-error-quark"); +} + +static void authorizer_init (GDataAuthorizerInterface *iface); +static void dispose (GObject *object); +static void finalize (GObject *object); +static void get_property (GObject *object, guint property_id, GValue *value, GParamSpec *pspec); +static void set_property (GObject *object, guint property_id, const GValue *value, GParamSpec *pspec); + +static void process_request (GDataAuthorizer *self, GDataAuthorizationDomain *domain, SoupMessage *message); +static gboolean is_authorized_for_domain (GDataAuthorizer *self, GDataAuthorizationDomain *domain); + +static void notify_proxy_uri_cb (GObject *gobject, GParamSpec *pspec, GDataClientLoginAuthorizer *self); +static void notify_timeout_cb (GObject *gobject, GParamSpec *pspec, GObject *self); + +static SoupURI *_get_proxy_uri (GDataClientLoginAuthorizer *self); +static void _set_proxy_uri (GDataClientLoginAuthorizer *self, SoupURI *proxy_uri); + +struct _GDataClientLoginAuthorizerPrivate { + SoupSession *session; + SoupURI *proxy_uri; /* cached version only set if gdata_client_login_authorizer_get_proxy_uri() is called */ + GProxyResolver *proxy_resolver; + + gchar *client_id; + + /* Mutex for username, password and auth_tokens. It has to be recursive as the top-level authentication functions need to hold a lock on + * auth_tokens while looping over it, but lower-level functions also need to modify auth_tokens to add the auth_tokens themselves once they're + * returned by the online service. */ + GRecMutex mutex; + + gchar *username; + GDataSecureString password; /* must be allocated by _gdata_service_secure_strdup() */ + + /* Mapping from GDataAuthorizationDomain to string? auth_token; auth_token is NULL for domains which aren't authorised at the moment */ + GHashTable *auth_tokens; +}; + +enum { + PROP_CLIENT_ID = 1, + PROP_USERNAME, + PROP_PASSWORD, + PROP_PROXY_URI, + PROP_TIMEOUT, + PROP_PROXY_RESOLVER, +}; + +enum { + SIGNAL_CAPTCHA_CHALLENGE, + LAST_SIGNAL +}; + +static guint authorizer_signals[LAST_SIGNAL] = { 0, }; + +G_DEFINE_TYPE_WITH_CODE (GDataClientLoginAuthorizer, gdata_client_login_authorizer, G_TYPE_OBJECT, + G_IMPLEMENT_INTERFACE (GDATA_TYPE_AUTHORIZER, authorizer_init)) + +static void +gdata_client_login_authorizer_class_init (GDataClientLoginAuthorizerClass *klass) +{ + GObjectClass *gobject_class = G_OBJECT_CLASS (klass); + + g_type_class_add_private (klass, sizeof (GDataClientLoginAuthorizerPrivate)); + + gobject_class->get_property = get_property; + gobject_class->set_property = set_property; + gobject_class->dispose = dispose; + gobject_class->finalize = finalize; + + /** + * GDataClientLoginAuthorizer:client-id: + * + * A client ID for your application (see the + * reference documentation). + * + * It is recommended that the ID is of the form company name-application name- + * version ID. + * + * Since: 0.9.0 + */ + g_object_class_install_property (gobject_class, PROP_CLIENT_ID, + g_param_spec_string ("client-id", + "Client ID", "A client ID for your application.", + NULL, + G_PARAM_CONSTRUCT_ONLY | G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)); + + /** + * GDataClientLoginAuthorizer:username: + * + * The user's Google username for authentication. This will always be a full e-mail address. + * + * This will only be set after authentication using gdata_client_login_authorizer_authenticate() is completed successfully. It will + * then be set to the username passed to gdata_client_login_authorizer_authenticate(), and a #GObject::notify signal will be emitted. If + * authentication fails, it will be set to %NULL. + * + * Since: 0.9.0 + */ + g_object_class_install_property (gobject_class, PROP_USERNAME, + g_param_spec_string ("username", + "Username", "The user's Google username for authentication.", + NULL, + G_PARAM_READABLE | G_PARAM_STATIC_STRINGS)); + + /** + * GDataClientLoginAuthorizer:password: + * + * The user's account password for authentication. + * + * This will only be set after authentication using gdata_client_login_authorizer_authenticate() is completed successfully. It will + * then be set to the password passed to gdata_client_login_authorizer_authenticate(), and a #GObject::notify signal will be emitted. If + * authentication fails, it will be set to %NULL. + * + * If libgdata is compiled with libgcr support, the password will be stored in non-pageable memory. However, if it is retrieved + * using g_object_get() (or related functions) it will be copied to non-pageable memory and could end up being written to disk. Accessing + * the password using gdata_client_login_authorizer_get_password() will not perform any copies, and so maintains privacy. + * + * Since: 0.9.0 + */ + g_object_class_install_property (gobject_class, PROP_PASSWORD, + g_param_spec_string ("password", + "Password", "The user's account password for authentication.", + NULL, + G_PARAM_READABLE | G_PARAM_STATIC_STRINGS)); + + /** + * GDataClientLoginAuthorizer:proxy-uri: + * + * The proxy URI used internally for all network requests. + * + * Since: 0.9.0 + * Deprecated: 0.15.0: Use #GDataClientLoginAuthorizer:proxy-resolver instead, which gives more flexibility over the proxy used. + */ + g_object_class_install_property (gobject_class, PROP_PROXY_URI, + g_param_spec_boxed ("proxy-uri", + "Proxy URI", "The proxy URI used internally for all network requests.", + SOUP_TYPE_URI, + G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)); + + /** + * GDataClientLoginAuthorizer:timeout: + * + * A timeout, in seconds, for network operations. If the timeout is exceeded, the operation will be cancelled and + * %GDATA_SERVICE_ERROR_NETWORK_ERROR will be returned. + * + * If the timeout is 0, operations will never time out. + * + * Since: 0.9.0 + */ + g_object_class_install_property (gobject_class, PROP_TIMEOUT, + g_param_spec_uint ("timeout", + "Timeout", "A timeout, in seconds, for network operations.", + 0, G_MAXUINT, 0, + G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)); + + /** + * GDataClientLoginAuthorizer:proxy-resolver: + * + * The #GProxyResolver used to determine a proxy URI. Setting this will clear the #GDataClientLoginAuthorizer:proxy-uri property. + * + * Since: 0.15.0 + */ + g_object_class_install_property (gobject_class, PROP_PROXY_RESOLVER, + g_param_spec_object ("proxy-resolver", + "Proxy Resolver", "A GProxyResolver used to determine a proxy URI.", + G_TYPE_PROXY_RESOLVER, + G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)); + + /** + * GDataClientLoginAuthorizer::captcha-challenge: + * @authorizer: the #GDataClientLoginAuthorizer which received the challenge + * @uri: the URI of the CAPTCHA image to be used + * + * The #GDataClientLoginAuthorizer::captcha-challenge signal is emitted during the authentication process if the authorizer requires a CAPTCHA + * to be completed. The URI of a CAPTCHA image is given, and the program should display this to the user, and return their response (the text + * displayed in the image). There is no timeout imposed by the library for the response. + * + * Return value: a newly allocated string containing the text in the CAPTCHA image + * + * Since: 0.9.0 + */ + authorizer_signals[SIGNAL_CAPTCHA_CHALLENGE] = g_signal_new ("captcha-challenge", + G_TYPE_FROM_CLASS (klass), + G_SIGNAL_RUN_LAST, + 0, NULL, NULL, + gdata_marshal_STRING__OBJECT_STRING, + G_TYPE_STRING, 1, G_TYPE_STRING); +} + +static void +authorizer_init (GDataAuthorizerInterface *iface) +{ + iface->process_request = process_request; + iface->is_authorized_for_domain = is_authorized_for_domain; +} + +static void +gdata_client_login_authorizer_init (GDataClientLoginAuthorizer *self) +{ + self->priv = G_TYPE_INSTANCE_GET_PRIVATE (self, GDATA_TYPE_CLIENT_LOGIN_AUTHORIZER, GDataClientLoginAuthorizerPrivate); + + /* Set up the authentication mutex */ + g_rec_mutex_init (&(self->priv->mutex)); + self->priv->auth_tokens = g_hash_table_new_full (g_direct_hash, g_direct_equal, g_object_unref, (GDestroyNotify) _gdata_service_secure_strfree); + + /* Set up the session */ + self->priv->session = _gdata_service_build_session (); + + /* Proxy the SoupSession's proxy-uri and timeout properties */ + g_signal_connect (self->priv->session, "notify::proxy-uri", (GCallback) notify_proxy_uri_cb, self); + g_signal_connect (self->priv->session, "notify::timeout", (GCallback) notify_timeout_cb, self); + + /* Keep our GProxyResolver synchronized with SoupSession's. */ + g_object_bind_property (self->priv->session, "proxy-resolver", self, "proxy-resolver", G_BINDING_BIDIRECTIONAL | G_BINDING_SYNC_CREATE); +} + +static void +dispose (GObject *object) +{ + GDataClientLoginAuthorizerPrivate *priv = GDATA_CLIENT_LOGIN_AUTHORIZER (object)->priv; + + if (priv->session != NULL) { + g_object_unref (priv->session); + } + priv->session = NULL; + + g_clear_object (&priv->proxy_resolver); + + /* Chain up to the parent class */ + G_OBJECT_CLASS (gdata_client_login_authorizer_parent_class)->dispose (object); +} + +static void +finalize (GObject *object) +{ + GDataClientLoginAuthorizerPrivate *priv = GDATA_CLIENT_LOGIN_AUTHORIZER (object)->priv; + + g_free (priv->username); + _gdata_service_secure_strfree (priv->password); + g_free (priv->client_id); + g_hash_table_destroy (priv->auth_tokens); + g_rec_mutex_clear (&(priv->mutex)); + + if (priv->proxy_uri != NULL) { + soup_uri_free (priv->proxy_uri); + } + + /* Chain up to the parent class */ + G_OBJECT_CLASS (gdata_client_login_authorizer_parent_class)->finalize (object); +} + +static void +get_property (GObject *object, guint property_id, GValue *value, GParamSpec *pspec) +{ + GDataClientLoginAuthorizerPrivate *priv = GDATA_CLIENT_LOGIN_AUTHORIZER (object)->priv; + + switch (property_id) { + case PROP_CLIENT_ID: + g_value_set_string (value, priv->client_id); + break; + case PROP_USERNAME: + g_rec_mutex_lock (&(priv->mutex)); + g_value_set_string (value, priv->username); + g_rec_mutex_unlock (&(priv->mutex)); + break; + case PROP_PASSWORD: + /* NOTE: This takes a pageable copy of non-pageable memory and thus could result in the password hitting disk. */ + g_rec_mutex_lock (&(priv->mutex)); + g_value_set_string (value, priv->password); + g_rec_mutex_unlock (&(priv->mutex)); + break; + case PROP_PROXY_URI: + g_value_set_boxed (value, _get_proxy_uri (GDATA_CLIENT_LOGIN_AUTHORIZER (object))); + break; + case PROP_TIMEOUT: + g_value_set_uint (value, gdata_client_login_authorizer_get_timeout (GDATA_CLIENT_LOGIN_AUTHORIZER (object))); + break; + case PROP_PROXY_RESOLVER: + g_value_set_object (value, gdata_client_login_authorizer_get_proxy_resolver (GDATA_CLIENT_LOGIN_AUTHORIZER (object))); + break; + default: + /* We don't have any other property... */ + G_OBJECT_WARN_INVALID_PROPERTY_ID (object, property_id, pspec); + break; + } +} + +static void +set_property (GObject *object, guint property_id, const GValue *value, GParamSpec *pspec) +{ + GDataClientLoginAuthorizerPrivate *priv = GDATA_CLIENT_LOGIN_AUTHORIZER (object)->priv; + + switch (property_id) { + case PROP_CLIENT_ID: + priv->client_id = g_value_dup_string (value); + break; + case PROP_PROXY_URI: + _set_proxy_uri (GDATA_CLIENT_LOGIN_AUTHORIZER (object), g_value_get_boxed (value)); + break; + case PROP_TIMEOUT: + gdata_client_login_authorizer_set_timeout (GDATA_CLIENT_LOGIN_AUTHORIZER (object), g_value_get_uint (value)); + break; + case PROP_PROXY_RESOLVER: + gdata_client_login_authorizer_set_proxy_resolver (GDATA_CLIENT_LOGIN_AUTHORIZER (object), g_value_get_object (value)); + break; + default: + /* We don't have any other property... */ + G_OBJECT_WARN_INVALID_PROPERTY_ID (object, property_id, pspec); + break; + } +} + +static void +process_request (GDataAuthorizer *self, GDataAuthorizationDomain *domain, SoupMessage *message) +{ + GDataConstSecureString auth_token; /* privacy sensitive */ + GDataClientLoginAuthorizerPrivate *priv = GDATA_CLIENT_LOGIN_AUTHORIZER (self)->priv; + + /* If the domain's NULL, return immediately */ + if (domain == NULL) { + return; + } + + /* Set the authorisation header */ + g_rec_mutex_lock (&(priv->mutex)); + + auth_token = (GDataConstSecureString) g_hash_table_lookup (priv->auth_tokens, domain); + + if (auth_token != NULL) { + /* Ensure that we're using HTTPS: if not, we shouldn't set the Authorization header or we could be revealing the auth token to + * anyone snooping the connection, which would give them the same rights as us on the user's data. Generally a bad thing to happen. */ + if (soup_message_get_uri (message)->scheme != SOUP_URI_SCHEME_HTTPS) { + g_warning ("Not authorizing a non-HTTPS message with the user's ClientLogin auth token as the connection isn't secure."); + } else { + /* Ideally, authorisation_header would be allocated in non-pageable memory. However, it's copied by + * soup_message_headers_replace() immediately anyway, so there's not much point. However, we do ensure we zero it out before + * freeing. */ + gchar *authorisation_header = g_strdup_printf ("GoogleLogin auth=%s", auth_token); + soup_message_headers_replace (message->request_headers, "Authorization", authorisation_header); + memset (authorisation_header, 0, strlen (authorisation_header)); + g_free (authorisation_header); + } + } + + g_rec_mutex_unlock (&(priv->mutex)); +} + +static gboolean +is_authorized_for_domain (GDataAuthorizer *self, GDataAuthorizationDomain *domain) +{ + GDataClientLoginAuthorizerPrivate *priv = GDATA_CLIENT_LOGIN_AUTHORIZER (self)->priv; + gpointer result; + + g_rec_mutex_lock (&(priv->mutex)); + result = g_hash_table_lookup (priv->auth_tokens, domain); + g_rec_mutex_unlock (&(priv->mutex)); + + return (result != NULL) ? TRUE : FALSE; +} + +/** + * gdata_client_login_authorizer_new: + * @client_id: your application's client ID + * @service_type: the #GType of a #GDataService subclass which the #GDataClientLoginAuthorizer will be used with + * + * Creates a new #GDataClientLoginAuthorizer. The @client_id must be unique for your application, and as registered with Google. + * + * The #GDataAuthorizationDomains for the given @service_type (i.e. as returned by gdata_service_get_authorization_domains()) are the ones the + * user will be logged in to using the provided username and password when gdata_client_login_authorizer_authenticate() is called. Note that the same + * username and password will be used for all domains. + * + * Return value: (transfer full): a new #GDataClientLoginAuthorizer, or %NULL; unref with g_object_unref() + * + * Since: 0.9.0 + */ +GDataClientLoginAuthorizer * +gdata_client_login_authorizer_new (const gchar *client_id, GType service_type) +{ + g_return_val_if_fail (client_id != NULL && *client_id != '\0', NULL); + g_return_val_if_fail (g_type_is_a (service_type, GDATA_TYPE_SERVICE), NULL); + + return gdata_client_login_authorizer_new_for_authorization_domains (client_id, + gdata_service_get_authorization_domains (service_type)); +} + +/** + * gdata_client_login_authorizer_new_for_authorization_domains: + * @client_id: your application's client ID + * @authorization_domains: (element-type GDataAuthorizationDomain) (transfer none): a non-empty list of #GDataAuthorizationDomains to be + * authorized against by the #GDataClientLoginAuthorizer + * + * Creates a new #GDataClientLoginAuthorizer. The @client_id must be unique for your application, and as registered with Google. This function is + * intended to be used only when the default authorization domain list for a single #GDataService, as used by gdata_client_login_authorizer_new(), + * isn't suitable. For example, this could be because the #GDataClientLoginAuthorizer will be used with multiple #GDataService subclasses, or because + * the client requires a specific set of authorization domains. + * + * The specified #GDataAuthorizationDomains are the ones the user will be logged in to using the provided username and password when + * gdata_client_login_authorizer_authenticate() is called. Note that the same username and password will be used for all domains. + * + * Return value: (transfer full): a new #GDataClientLoginAuthorizer, or %NULL; unref with g_object_unref() + * + * Since: 0.9.0 + */ +GDataClientLoginAuthorizer * +gdata_client_login_authorizer_new_for_authorization_domains (const gchar *client_id, GList *authorization_domains) +{ + GList *i; + GDataClientLoginAuthorizer *authorizer; + + g_return_val_if_fail (client_id != NULL && *client_id != '\0', NULL); + g_return_val_if_fail (authorization_domains != NULL, NULL); + + authorizer = GDATA_CLIENT_LOGIN_AUTHORIZER (g_object_new (GDATA_TYPE_CLIENT_LOGIN_AUTHORIZER, + "client-id", client_id, + NULL)); + + /* Register all the domains with the authorizer */ + for (i = authorization_domains; i != NULL; i = i->next) { + g_return_val_if_fail (GDATA_IS_AUTHORIZATION_DOMAIN (i->data), NULL); + + /* We don't have to lock the authoriser's mutex here as no other code has seen the authoriser yet */ + g_hash_table_insert (authorizer->priv->auth_tokens, g_object_ref (GDATA_AUTHORIZATION_DOMAIN (i->data)), NULL); + } + + return authorizer; +} + +/* Called in the main thread to notify of changes to the username and password properties from the authentication thread. It swallows a reference + * the authoriser. */ +static gboolean +notify_authentication_details_cb (GDataClientLoginAuthorizer *self) +{ + GObject *authorizer = G_OBJECT (self); + + g_object_freeze_notify (authorizer); + g_object_notify (authorizer, "username"); + g_object_notify (authorizer, "password"); + g_object_thaw_notify (authorizer); + + g_object_unref (self); + + /* Only execute once */ + return FALSE; +} + +static void +set_authentication_details (GDataClientLoginAuthorizer *self, const gchar *username, const gchar *password, GHashTable *new_auth_tokens, + gboolean is_async) +{ + GDataClientLoginAuthorizerPrivate *priv = self->priv; + GHashTableIter iter; + + g_rec_mutex_lock (&(priv->mutex)); + + /* Ensure the username is always a full e-mail address */ + g_free (priv->username); + if (username != NULL && strchr (username, '@') == NULL) { + priv->username = g_strdup_printf ("%s@" EMAIL_DOMAIN, username); + } else { + priv->username = g_strdup (username); + } + + _gdata_service_secure_strfree (priv->password); + priv->password = _gdata_service_secure_strdup (password); + + /* Transfer all successful auth. tokens to the object-wide auth. token store. */ + if (new_auth_tokens == NULL) { + /* Reset ->auth_tokens to contain no auth. tokens, just the domains. */ + g_hash_table_iter_init (&iter, priv->auth_tokens); + + while (g_hash_table_iter_next (&iter, NULL, NULL) == TRUE) { + g_hash_table_iter_replace (&iter, NULL); + } + } else { + /* Replace the existing ->auth_tokens with the new one, which contains all the shiny new auth. tokens. */ + g_hash_table_ref (new_auth_tokens); + g_hash_table_unref (priv->auth_tokens); + priv->auth_tokens = new_auth_tokens; + } + + g_rec_mutex_unlock (&(priv->mutex)); + + /* Notify of the property changes in the main thread; i.e. if we're running an async operation, schedule the notification in an idle + * callback; but if we're running a sync operation, emit them immediately. + * This guarantees that: + * • notifications will always be emitted before gdata_client_login_authorizer_authenticate() returns; and + * • notifications will always be emitted in the main thread for calls to gdata_client_login_authorizer_authenticate_async(). */ + if (is_async == TRUE) { + g_idle_add ((GSourceFunc) notify_authentication_details_cb, g_object_ref (self)); + } else { + notify_authentication_details_cb (g_object_ref (self)); + } +} + +static GDataSecureString +parse_authentication_response (GDataClientLoginAuthorizer *self, GDataAuthorizationDomain *domain, guint status, + const gchar *response_body, gint length, GError **error) +{ + gchar *auth_start, *auth_end; + GDataSecureString auth_token; /* NOTE: auth_token must be allocated using _gdata_service_secure_strdup() and friends */ + + /* Parse the response */ + auth_start = strstr (response_body, "Auth="); + if (auth_start == NULL) { + goto protocol_error; + } + auth_start += strlen ("Auth="); + + auth_end = strstr (auth_start, "\n"); + if (auth_end == NULL) { + goto protocol_error; + } + + auth_token = _gdata_service_secure_strndup (auth_start, auth_end - auth_start); + if (auth_token == NULL || strlen (auth_token) == 0) { + _gdata_service_secure_strfree (auth_token); + goto protocol_error; + } + + return auth_token; + +protocol_error: + g_set_error_literal (error, GDATA_SERVICE_ERROR, GDATA_SERVICE_ERROR_PROTOCOL_ERROR, + _("The server returned a malformed response.")); + return NULL; +} + +static void +parse_error_response (GDataClientLoginAuthorizer *self, guint status, const gchar *reason_phrase, const gchar *response_body, gint length, + GError **error) +{ + /* We prefer to include the @response_body in the error message, but if it's empty, fall back to the @reason_phrase */ + if (response_body == NULL || *response_body == '\0') { + response_body = reason_phrase; + } + + /* See: http://code.google.com/apis/gdata/docs/2.0/reference.html#HTTPStatusCodes */ + switch (status) { + case SOUP_STATUS_CANT_RESOLVE: + case SOUP_STATUS_CANT_CONNECT: + case SOUP_STATUS_SSL_FAILED: + case SOUP_STATUS_IO_ERROR: + g_set_error (error, GDATA_SERVICE_ERROR, GDATA_SERVICE_ERROR_NETWORK_ERROR, + _("Cannot connect to the service’s server.")); + return; + case SOUP_STATUS_CANT_RESOLVE_PROXY: + case SOUP_STATUS_CANT_CONNECT_PROXY: + g_set_error (error, GDATA_SERVICE_ERROR, GDATA_SERVICE_ERROR_PROXY_ERROR, + _("Cannot connect to the proxy server.")); + return; + case SOUP_STATUS_MALFORMED: + case SOUP_STATUS_BAD_REQUEST: /* 400 */ + g_set_error (error, GDATA_SERVICE_ERROR, GDATA_SERVICE_ERROR_PROTOCOL_ERROR, + /* Translators: the parameter is an error message returned by the server. */ + _("Invalid request URI or header, or unsupported nonstandard parameter: %s"), response_body); + return; + case SOUP_STATUS_UNAUTHORIZED: /* 401 */ + case SOUP_STATUS_FORBIDDEN: /* 403 */ + g_set_error (error, GDATA_SERVICE_ERROR, GDATA_SERVICE_ERROR_AUTHENTICATION_REQUIRED, + /* Translators: the parameter is an error message returned by the server. */ + _("Authentication required: %s"), response_body); + return; + case SOUP_STATUS_NOT_FOUND: /* 404 */ + g_set_error (error, GDATA_SERVICE_ERROR, GDATA_SERVICE_ERROR_NOT_FOUND, + /* Translators: the parameter is an error message returned by the server. */ + _("The requested resource was not found: %s"), response_body); + return; + case SOUP_STATUS_CONFLICT: /* 409 */ + case SOUP_STATUS_PRECONDITION_FAILED: /* 412 */ + g_set_error (error, GDATA_SERVICE_ERROR, GDATA_SERVICE_ERROR_CONFLICT, + /* Translators: the parameter is an error message returned by the server. */ + _("The entry has been modified since it was downloaded: %s"), response_body); + return; + case SOUP_STATUS_INTERNAL_SERVER_ERROR: /* 500 */ + default: + /* We'll fall back to a generic error, below */ + break; + } + + /* If the error hasn't been handled already, throw a generic error */ + g_set_error (error, GDATA_SERVICE_ERROR, GDATA_SERVICE_ERROR_PROTOCOL_ERROR, + /* Translators: the first parameter is an HTTP status, + * and the second is an error message returned by the server. */ + _("Error code %u when authenticating: %s"), status, response_body); +} + +static GDataSecureString +authenticate (GDataClientLoginAuthorizer *self, GDataAuthorizationDomain *domain, const gchar *username, const gchar *password, + gchar *captcha_token, gchar *captcha_answer, GCancellable *cancellable, GError **error) +{ + GDataClientLoginAuthorizerPrivate *priv = self->priv; + SoupMessage *message; + gchar *request_body; + const gchar *service_name; + guint status; + GDataSecureString auth_token; + SoupURI *_uri; + + /* Prepare the request. + * NOTE: At this point, our non-pageable password is copied into a pageable HTTP request structure. We can't do much about this + * except note that the request is transient and so the chance of it getting paged out is low (but still positive). */ + service_name = gdata_authorization_domain_get_service_name (domain); + request_body = soup_form_encode ("accountType", "HOSTED_OR_GOOGLE", + "Email", username, + "Passwd", password, + "service", service_name, + "source", priv->client_id, + (captcha_token == NULL) ? NULL : "logintoken", captcha_token, + "loginanswer", captcha_answer, + NULL); + + /* Free the CAPTCHA token and answer if necessary */ + g_free (captcha_token); + g_free (captcha_answer); + + /* Build the message */ + _uri = soup_uri_new ("https://www.google.com/accounts/ClientLogin"); + soup_uri_set_port (_uri, _gdata_service_get_https_port ()); + message = soup_message_new_from_uri (SOUP_METHOD_POST, _uri); + soup_uri_free (_uri); + soup_message_set_request (message, "application/x-www-form-urlencoded", SOUP_MEMORY_TAKE, request_body, strlen (request_body)); + + /* Send the message */ + _gdata_service_actually_send_message (priv->session, message, cancellable, error); + status = message->status_code; + + if (status == SOUP_STATUS_CANCELLED) { + /* Cancelled (the error has already been set) */ + g_object_unref (message); + return NULL; + } else if (status != SOUP_STATUS_OK) { + const gchar *response_body = message->response_body->data; + gchar *error_start, *error_end, *uri_start, *uri_end, *uri = NULL; + + /* Parse the error response; see: http://code.google.com/apis/accounts/docs/AuthForInstalledApps.html#Errors */ + if (response_body == NULL) { + goto protocol_error; + } + + /* Error */ + error_start = strstr (response_body, "Error="); + if (error_start == NULL) { + goto protocol_error; + } + error_start += strlen ("Error="); + + error_end = strstr (error_start, "\n"); + if (error_end == NULL) { + goto protocol_error; + } + + if (strncmp (error_start, "CaptchaRequired", error_end - error_start) == 0) { + const gchar *captcha_base_uri = "http://www.google.com/accounts/"; + gchar *captcha_start, *captcha_end, *captcha_uri, *new_captcha_answer; + guint captcha_base_uri_length; + + /* CAPTCHA required to log in */ + captcha_start = strstr (response_body, "CaptchaUrl="); + if (captcha_start == NULL) { + goto protocol_error; + } + captcha_start += strlen ("CaptchaUrl="); + + captcha_end = strstr (captcha_start, "\n"); + if (captcha_end == NULL) { + goto protocol_error; + } + + /* Do some fancy memory stuff to save ourselves another alloc */ + captcha_base_uri_length = strlen (captcha_base_uri); + captcha_uri = g_malloc (captcha_base_uri_length + (captcha_end - captcha_start) + 1); + memcpy (captcha_uri, captcha_base_uri, captcha_base_uri_length); + memcpy (captcha_uri + captcha_base_uri_length, captcha_start, (captcha_end - captcha_start)); + captcha_uri[captcha_base_uri_length + (captcha_end - captcha_start)] = '\0'; + + /* Request a CAPTCHA answer from the application */ + g_signal_emit (self, authorizer_signals[SIGNAL_CAPTCHA_CHALLENGE], 0, captcha_uri, &new_captcha_answer); + g_free (captcha_uri); + + if (new_captcha_answer == NULL || *new_captcha_answer == '\0') { + g_set_error_literal (error, GDATA_CLIENT_LOGIN_AUTHORIZER_ERROR, GDATA_CLIENT_LOGIN_AUTHORIZER_ERROR_CAPTCHA_REQUIRED, + /* Translators: see http://en.wikipedia.org/wiki/CAPTCHA for information about CAPTCHAs */ + _("A CAPTCHA must be filled out to log in.")); + goto login_error; + } + + /* Get the CAPTCHA token */ + captcha_start = strstr (response_body, "CaptchaToken="); + if (captcha_start == NULL) { + goto protocol_error; + } + captcha_start += strlen ("CaptchaToken="); + + captcha_end = strstr (captcha_start, "\n"); + if (captcha_end == NULL) { + goto protocol_error; + } + + /* Save the CAPTCHA token and answer, and attempt to log in with them */ + g_object_unref (message); + + return authenticate (self, domain, username, password, + g_strndup (captcha_start, captcha_end - captcha_start), new_captcha_answer, + cancellable, error); + } else if (strncmp (error_start, "Unknown", error_end - error_start) == 0) { + goto protocol_error; + } else if (strncmp (error_start, "BadAuthentication", error_end - error_start) == 0) { + /* Looks like Error=BadAuthentication errors don't return a URI */ + gchar *info_start, *info_end; + + info_start = strstr (response_body, "Info="); + if (info_start != NULL) { + info_start += strlen ("Info="); + info_end = strstr (info_start, "\n"); + } + + /* If Info=InvalidSecondFactor, the user needs to generate an application-specific password and use that instead */ + if (info_start != NULL && info_end != NULL && strncmp (info_start, "InvalidSecondFactor", info_end - info_start) == 0) { + g_set_error (error, GDATA_CLIENT_LOGIN_AUTHORIZER_ERROR, GDATA_CLIENT_LOGIN_AUTHORIZER_ERROR_INVALID_SECOND_FACTOR, + /* Translators: the parameter is a URI for further information. */ + _("This account requires an application-specific password. (%s)"), + "http://www.google.com/support/accounts/bin/static.py?page=guide.cs&guide=1056283&topic=1056286"); + goto login_error; + } + + /* Fall back to a generic "bad authentication details" message */ + g_set_error_literal (error, GDATA_CLIENT_LOGIN_AUTHORIZER_ERROR, GDATA_CLIENT_LOGIN_AUTHORIZER_ERROR_BAD_AUTHENTICATION, + _("Your username or password were incorrect.")); + goto login_error; + } + + /* Get the information URI */ + uri_start = strstr (response_body, "Url="); + if (uri_start == NULL) { + goto protocol_error; + } + uri_start += strlen ("Url="); + + uri_end = strstr (uri_start, "\n"); + if (uri_end == NULL) { + goto protocol_error; + } + + uri = g_strndup (uri_start, uri_end - uri_start); + + if (strncmp (error_start, "NotVerified", error_end - error_start) == 0) { + g_set_error (error, GDATA_CLIENT_LOGIN_AUTHORIZER_ERROR, GDATA_CLIENT_LOGIN_AUTHORIZER_ERROR_NOT_VERIFIED, + /* Translators: the parameter is a URI for further information. */ + _("Your account’s e-mail address has not been verified. (%s)"), uri); + goto login_error; + } else if (strncmp (error_start, "TermsNotAgreed", error_end - error_start) == 0) { + g_set_error (error, GDATA_CLIENT_LOGIN_AUTHORIZER_ERROR, GDATA_CLIENT_LOGIN_AUTHORIZER_ERROR_TERMS_NOT_AGREED, + /* Translators: the parameter is a URI for further information. */ + _("You have not agreed to the service’s terms and conditions. (%s)"), uri); + goto login_error; + } else if (strncmp (error_start, "AccountMigrated", error_end - error_start) == 0) { + /* This is non-standard, and used by YouTube since it's got messed-up accounts */ + g_set_error (error, GDATA_CLIENT_LOGIN_AUTHORIZER_ERROR, GDATA_CLIENT_LOGIN_AUTHORIZER_ERROR_ACCOUNT_MIGRATED, + /* Translators: the parameter is a URI for further information. */ + _("This account has been migrated. Please log in online to receive your new username and password. (%s)"), uri); + goto login_error; + } else if (strncmp (error_start, "AccountDeleted", error_end - error_start) == 0) { + g_set_error (error, GDATA_CLIENT_LOGIN_AUTHORIZER_ERROR, GDATA_CLIENT_LOGIN_AUTHORIZER_ERROR_ACCOUNT_DELETED, + /* Translators: the parameter is a URI for further information. */ + _("This account has been deleted. (%s)"), uri); + goto login_error; + } else if (strncmp (error_start, "AccountDisabled", error_end - error_start) == 0) { + g_set_error (error, GDATA_CLIENT_LOGIN_AUTHORIZER_ERROR, GDATA_CLIENT_LOGIN_AUTHORIZER_ERROR_ACCOUNT_DISABLED, + /* Translators: the parameter is a URI for further information. */ + _("This account has been disabled. (%s)"), uri); + goto login_error; + } else if (strncmp (error_start, "ServiceDisabled", error_end - error_start) == 0) { + g_set_error (error, GDATA_CLIENT_LOGIN_AUTHORIZER_ERROR, GDATA_CLIENT_LOGIN_AUTHORIZER_ERROR_SERVICE_DISABLED, + /* Translators: the parameter is a URI for further information. */ + _("This account’s access to this service has been disabled. (%s)"), uri); + goto login_error; + } else if (strncmp (error_start, "ServiceUnavailable", error_end - error_start) == 0) { + g_set_error (error, GDATA_SERVICE_ERROR, GDATA_SERVICE_ERROR_UNAVAILABLE, + /* Translators: the parameter is a URI for further information. */ + _("This service is not available at the moment. (%s)"), uri); + goto login_error; + } + + /* Unknown error type! */ + goto protocol_error; + +login_error: + g_free (uri); + g_object_unref (message); + + return NULL; + } + + g_assert (message->response_body->data != NULL); + + auth_token = parse_authentication_response (self, domain, status, message->response_body->data, message->response_body->length, error); + + /* Zero out the response body to lower the chance of it (with all the juicy passwords and auth. tokens it contains) hitting disk or getting + * leaked in free memory. */ + memset ((void*) message->response_body->data, 0, message->response_body->length); + + g_object_unref (message); + + return auth_token; + +protocol_error: + parse_error_response (self, status, message->reason_phrase, message->response_body->data, message->response_body->length, error); + + g_object_unref (message); + + return NULL; +} + +static gboolean +authenticate_loop (GDataClientLoginAuthorizer *authorizer, gboolean is_async, const gchar *username, const gchar *password, GCancellable *cancellable, + GError **error) +{ + GDataClientLoginAuthorizerPrivate *priv = authorizer->priv; + gboolean cumulative_success = TRUE; + GHashTable *new_auth_tokens; + GHashTableIter iter; + GDataAuthorizationDomain *domain; + GDataSecureString auth_token; + + g_rec_mutex_lock (&(priv->mutex)); + + /* Authenticate and authorize against each of the services registered with the authorizer */ + new_auth_tokens = g_hash_table_new_full (g_direct_hash, g_direct_equal, g_object_unref, (GDestroyNotify) _gdata_service_secure_strfree); + g_hash_table_iter_init (&iter, priv->auth_tokens); + + while (g_hash_table_iter_next (&iter, (gpointer*) &domain, NULL) == TRUE) { + GError *authenticate_error = NULL; + + auth_token = authenticate (authorizer, domain, username, password, NULL, NULL, cancellable, &authenticate_error); + + if (auth_token == NULL && cumulative_success == TRUE) { + /* Only propagate the first error which occurs. */ + g_propagate_error (error, authenticate_error); + authenticate_error = NULL; + } + + cumulative_success = (auth_token != NULL) && cumulative_success; + + /* Store the auth. token (or lack thereof if authentication failed). */ + g_hash_table_insert (new_auth_tokens, g_object_ref (domain), auth_token); + + g_clear_error (&authenticate_error); + } + + g_rec_mutex_unlock (&(priv->mutex)); + + /* Set or clear the authentication details and return now that we're done */ + if (cumulative_success == TRUE) { + set_authentication_details (authorizer, username, password, new_auth_tokens, is_async); + } else { + set_authentication_details (authorizer, NULL, NULL, NULL, is_async); + } + + g_hash_table_unref (new_auth_tokens); + + return cumulative_success; +} + +typedef struct { + gchar *username; + GDataSecureString password; /* NOTE: This must be allocated in non-pageable memory using _gdata_service_secure_strdup(). */ +} AuthenticateAsyncData; + +static void +authenticate_async_data_free (AuthenticateAsyncData *self) +{ + g_free (self->username); + _gdata_service_secure_strfree (self->password); + + g_slice_free (AuthenticateAsyncData, self); +} + +static void +authenticate_thread (GTask *task, gpointer source_object, gpointer task_data, GCancellable *cancellable) +{ + GDataClientLoginAuthorizer *authorizer = GDATA_CLIENT_LOGIN_AUTHORIZER (source_object); + g_autoptr(GError) error = NULL; + AuthenticateAsyncData *data = task_data; + + if (!authenticate_loop (authorizer, TRUE, data->username, data->password, cancellable, &error)) + g_task_return_error (task, g_steal_pointer (&error)); + else + g_task_return_boolean (task, TRUE); +} + +/** + * gdata_client_login_authorizer_authenticate_async: + * @self: a #GDataClientLoginAuthorizer + * @username: the user's username + * @password: the user's password + * @cancellable: (allow-none): optional #GCancellable object, or %NULL + * @callback: a #GAsyncReadyCallback to call when authentication is finished + * @user_data: (closure): data to pass to the @callback function + * + * Authenticates the #GDataClientLoginAuthorizer with the Google accounts service using the given @username and @password. @self, @username and + * @password are all reffed/copied when this function is called, so can safely be freed after this function returns. + * + * For more details, see gdata_client_login_authorizer_authenticate(), which is the synchronous version of this function. + * + * When the operation is finished, @callback will be called. You can then call gdata_client_login_authorizer_authenticate_finish() + * to get the results of the operation. + * + * Since: 0.9.0 + */ +void +gdata_client_login_authorizer_authenticate_async (GDataClientLoginAuthorizer *self, const gchar *username, const gchar *password, + GCancellable *cancellable, GAsyncReadyCallback callback, gpointer user_data) +{ + g_autoptr(GTask) task = NULL; + AuthenticateAsyncData *data; + + g_return_if_fail (GDATA_IS_CLIENT_LOGIN_AUTHORIZER (self)); + g_return_if_fail (username != NULL); + g_return_if_fail (password != NULL); + g_return_if_fail (cancellable == NULL || G_IS_CANCELLABLE (cancellable)); + + data = g_slice_new (AuthenticateAsyncData); + data->username = g_strdup (username); + data->password = _gdata_service_secure_strdup (password); + + task = g_task_new (self, cancellable, callback, user_data); + g_task_set_source_tag (task, gdata_client_login_authorizer_authenticate_async); + g_task_set_task_data (task, g_steal_pointer (&data), (GDestroyNotify) authenticate_async_data_free); + g_task_run_in_thread (task, authenticate_thread); +} + +/** + * gdata_client_login_authorizer_authenticate_finish: + * @self: a #GDataClientLoginAuthorizer + * @async_result: a #GAsyncResult + * @error: a #GError, or %NULL + * + * Finishes an asynchronous authentication operation started with gdata_client_login_authorizer_authenticate_async(). + * + * Return value: %TRUE if authentication was successful, %FALSE otherwise + * + * Since: 0.9.0 + */ +gboolean +gdata_client_login_authorizer_authenticate_finish (GDataClientLoginAuthorizer *self, GAsyncResult *async_result, GError **error) +{ + g_return_val_if_fail (GDATA_IS_CLIENT_LOGIN_AUTHORIZER (self), FALSE); + g_return_val_if_fail (G_IS_ASYNC_RESULT (async_result), FALSE); + g_return_val_if_fail (error == NULL || *error == NULL, FALSE); + g_return_val_if_fail (g_task_is_valid (async_result, self), FALSE); + g_return_val_if_fail (g_async_result_is_tagged (async_result, gdata_client_login_authorizer_authenticate_async), FALSE); + + return g_task_propagate_boolean (G_TASK (async_result), error); +} + +/** + * gdata_client_login_authorizer_authenticate: + * @self: a #GDataClientLoginAuthorizer + * @username: the user's username + * @password: the user's password + * @cancellable: (allow-none): optional #GCancellable object, or %NULL + * @error: a #GError, or %NULL + * + * Authenticates the #GDataClientLoginAuthorizer with the Google Accounts service using @username and @password and authorizes it against all the + * service types passed to gdata_client_login_authorizer_new(); i.e. logs into the service with the given user account. @username should be a full + * e-mail address (e.g. john.smith\@gmail.com). If a full e-mail address is not given, @username will have + * \@gmail.com appended to create an e-mail address + * + * If @cancellable is not %NULL, then the operation can be cancelled by triggering the @cancellable object from another thread. + * If the operation was cancelled, the error %G_IO_ERROR_CANCELLED will be returned. + * + * If the operation errors or is cancelled part-way through, gdata_authorizer_is_authorized_for_domain() is guaranteed to return %FALSE + * for all #GDataAuthorizationDomains, even if authentication has succeeded for some of them already. + * + * A %GDATA_CLIENT_LOGIN_AUTHORIZER_ERROR_BAD_AUTHENTICATION will be returned if authentication failed due to an incorrect username or password. + * Other #GDataClientLoginAuthorizerError errors can be returned for other conditions. + * + * If the service requires a CAPTCHA to be completed, the #GDataClientLoginAuthorizer::captcha-challenge signal will be emitted. + * The return value from a signal handler for the signal should be a newly allocated string containing the text from the image. If the text is %NULL + * or empty, authentication will fail with a %GDATA_CLIENT_LOGIN_AUTHORIZER_ERROR_CAPTCHA_REQUIRED error. Otherwise, authentication will be + * automatically and transparently restarted with the new CAPTCHA details. + * + * A %GDATA_SERVICE_ERROR_PROTOCOL_ERROR will be returned if the server's responses were invalid. + * + * Return value: %TRUE if authentication and authorization was successful against all the services, %FALSE otherwise + * + * Since: 0.9.0 + */ +gboolean +gdata_client_login_authorizer_authenticate (GDataClientLoginAuthorizer *self, const gchar *username, const gchar *password, + GCancellable *cancellable, GError **error) +{ + g_return_val_if_fail (GDATA_IS_CLIENT_LOGIN_AUTHORIZER (self), FALSE); + g_return_val_if_fail (username != NULL, FALSE); + g_return_val_if_fail (password != NULL, FALSE); + g_return_val_if_fail (cancellable == NULL || G_IS_CANCELLABLE (cancellable), FALSE); + g_return_val_if_fail (error == NULL || *error == NULL, FALSE); + + return authenticate_loop (self, FALSE, username, password, cancellable, error); +} + +static void +notify_proxy_uri_cb (GObject *object, GParamSpec *pspec, GDataClientLoginAuthorizer *self) +{ + /* Flush our cached version */ + if (self->priv->proxy_uri != NULL) { + soup_uri_free (self->priv->proxy_uri); + self->priv->proxy_uri = NULL; + } + + g_object_notify (G_OBJECT (self), "proxy-uri"); +} + +/* Static function which isn't deprecated so we can continue using it internally. */ +static SoupURI * +_get_proxy_uri (GDataClientLoginAuthorizer *self) +{ + SoupURI *proxy_uri; + + g_return_val_if_fail (GDATA_IS_CLIENT_LOGIN_AUTHORIZER (self), NULL); + + /* If we have a cached version, return that */ + if (self->priv->proxy_uri != NULL) { + return self->priv->proxy_uri; + } + + g_object_get (self->priv->session, SOUP_SESSION_PROXY_URI, &proxy_uri, NULL); + + /* Update the cache; it takes ownership of the URI */ + self->priv->proxy_uri = proxy_uri; + + return proxy_uri; +} + +/** + * gdata_client_login_authorizer_get_proxy_uri: + * @self: a #GDataClientLoginAuthorizer + * + * Gets the proxy URI on the #GDataClientLoginAuthorizer's #SoupSession. + * + * Return value: (transfer full): the proxy URI, or %NULL; free with soup_uri_free() + * + * Since: 0.9.0 + * Deprecated: 0.15.0: Use gdata_client_login_authorizer_get_proxy_resolver() instead, which gives more flexibility over the proxy used. + */ +SoupURI * +gdata_client_login_authorizer_get_proxy_uri (GDataClientLoginAuthorizer *self) +{ + return _get_proxy_uri (self); +} + +/* Static function which isn't deprecated so we can continue using it internally. */ +static void +_set_proxy_uri (GDataClientLoginAuthorizer *self, SoupURI *proxy_uri) +{ + g_return_if_fail (GDATA_IS_CLIENT_LOGIN_AUTHORIZER (self)); + + g_object_set (self->priv->session, SOUP_SESSION_PROXY_URI, proxy_uri, NULL); + + /* Notification is handled in notify_proxy_uri_cb() which is called as a result of setting the property on the session */ +} + +/** + * gdata_client_login_authorizer_set_proxy_uri: + * @self: a #GDataClientLoginAuthorizer + * @proxy_uri: (allow-none): the proxy URI, or %NULL + * + * Sets the proxy URI on the #SoupSession used internally by the #GDataClientLoginAuthorizer. This forces all requests through the given proxy. + * + * If @proxy_uri is %NULL, no proxy will be used. + * + * Since: 0.9.0 + * Deprecated: 0.15.0: Use gdata_client_login_authorizer_set_proxy_resolver() instead, which gives more flexibility over the proxy used. + */ +void +gdata_client_login_authorizer_set_proxy_uri (GDataClientLoginAuthorizer *self, SoupURI *proxy_uri) +{ + _set_proxy_uri (self, proxy_uri); +} + +/** + * gdata_client_login_authorizer_get_proxy_resolver: + * @self: a #GDataClientLoginAuthorizer + * + * Gets the #GProxyResolver on the #GDataClientLoginAuthorizer's #SoupSession. + * + * Return value: (transfer none) (allow-none): a #GProxyResolver, or %NULL + * + * Since: 0.15.0 + */ +GProxyResolver * +gdata_client_login_authorizer_get_proxy_resolver (GDataClientLoginAuthorizer *self) +{ + g_return_val_if_fail (GDATA_IS_CLIENT_LOGIN_AUTHORIZER (self), NULL); + + return self->priv->proxy_resolver; +} + +/** + * gdata_client_login_authorizer_set_proxy_resolver: + * @self: a #GDataClientLoginAuthorizer + * @proxy_resolver: (allow-none): a #GProxyResolver, or %NULL + * + * Sets the #GProxyResolver on the #SoupSession used internally by the given #GDataClientLoginAuthorizer. + * + * Setting this will clear the #GDataClientLoginAuthorizer:proxy-uri property. + * + * Since: 0.15.0 + */ +void +gdata_client_login_authorizer_set_proxy_resolver (GDataClientLoginAuthorizer *self, GProxyResolver *proxy_resolver) +{ + g_return_if_fail (GDATA_IS_CLIENT_LOGIN_AUTHORIZER (self)); + g_return_if_fail (proxy_resolver == NULL || G_IS_PROXY_RESOLVER (proxy_resolver)); + + if (proxy_resolver != NULL) { + g_object_ref (proxy_resolver); + } + + g_clear_object (&self->priv->proxy_resolver); + self->priv->proxy_resolver = proxy_resolver; + + g_object_notify (G_OBJECT (self), "proxy-resolver"); +} + +static void +notify_timeout_cb (GObject *gobject, GParamSpec *pspec, GObject *self) +{ + g_object_notify (self, "timeout"); +} + +/** + * gdata_client_login_authorizer_get_timeout: + * @self: a #GDataClientLoginAuthorizer + * + * Gets the #GDataClientLoginAuthorizer:timeout property; the network timeout, in seconds. + * + * Return value: the timeout, or 0 + * + * Since: 0.9.0 + */ +guint +gdata_client_login_authorizer_get_timeout (GDataClientLoginAuthorizer *self) +{ + guint timeout; + + g_return_val_if_fail (GDATA_IS_CLIENT_LOGIN_AUTHORIZER (self), 0); + + g_object_get (self->priv->session, SOUP_SESSION_TIMEOUT, &timeout, NULL); + + return timeout; +} + +/** + * gdata_client_login_authorizer_set_timeout: + * @self: a #GDataClientLoginAuthorizer + * @timeout: the timeout, or 0 + * + * Sets the #GDataClientLoginAuthorizer:timeout property; the network timeout, in seconds. + * + * If @timeout is 0, network operations will never time out. + * + * Since: 0.9.0 + */ +void +gdata_client_login_authorizer_set_timeout (GDataClientLoginAuthorizer *self, guint timeout) +{ + g_return_if_fail (GDATA_IS_CLIENT_LOGIN_AUTHORIZER (self)); + + g_object_set (self->priv->session, SOUP_SESSION_TIMEOUT, timeout, NULL); + + /* Notification is handled in notify_proxy_uri_cb() which is called as a result of setting the property on the session */ +} + +/** + * gdata_client_login_authorizer_get_client_id: + * @self: a #GDataClientLoginAuthorizer + * + * Returns the authorizer's client ID, as specified on constructing the #GDataClientLoginAuthorizer. + * + * Return value: the authorizer's client ID + * + * Since: 0.9.0 + */ +const gchar * +gdata_client_login_authorizer_get_client_id (GDataClientLoginAuthorizer *self) +{ + g_return_val_if_fail (GDATA_IS_CLIENT_LOGIN_AUTHORIZER (self), NULL); + + return self->priv->client_id; +} + +/** + * gdata_client_login_authorizer_get_username: + * @self: a #GDataClientLoginAuthorizer + * + * Returns the username of the currently authenticated user, or %NULL if nobody is authenticated. + * + * It is not safe to call this while an authentication operation is ongoing. + * + * Return value: the username of the currently authenticated user, or %NULL + * + * Since: 0.9.0 + */ +const gchar * +gdata_client_login_authorizer_get_username (GDataClientLoginAuthorizer *self) +{ + g_return_val_if_fail (GDATA_IS_CLIENT_LOGIN_AUTHORIZER (self), NULL); + + /* There's little point protecting this with ->mutex, as the data's meaningless if accessed during an authentication operation, + * and not being accessed concurrently otherwise. */ + return self->priv->username; +} + +/** + * gdata_client_login_authorizer_get_password: + * @self: a #GDataClientLoginAuthorizer + * + * Returns the password of the currently authenticated user, or %NULL if nobody is authenticated. + * + * It is not safe to call this while an authentication operation is ongoing. + * + * If libgdata is compiled with libgcr support, the password will be stored in non-pageable memory. Since this function doesn't return + * a copy of the password, the returned value is guaranteed to not hit disk. It's advised that any copies of the password made in client programs + * also use non-pageable memory. + * + * Return value: the password of the currently authenticated user, or %NULL + * + * Since: 0.9.0 + */ +const gchar * +gdata_client_login_authorizer_get_password (GDataClientLoginAuthorizer *self) +{ + g_return_val_if_fail (GDATA_IS_CLIENT_LOGIN_AUTHORIZER (self), NULL); + + /* There's little point protecting this with ->mutex, as the data's meaningless if accessed during an authentication operation, + * and not being accessed concurrently otherwise. */ + return self->priv->password; +} diff --git a/gdata/gdata-client-login-authorizer.h b/gdata/gdata-client-login-authorizer.h new file mode 100644 index 0000000..7e13ca1 --- /dev/null +++ b/gdata/gdata-client-login-authorizer.h @@ -0,0 +1,141 @@ +/* -*- Mode: C; indent-tabs-mode: t; c-basic-offset: 8; tab-width: 8 -*- */ +/* + * GData Client + * Copyright (C) Philip Withnall 2011 + * + * GData Client is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * GData Client is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with GData Client. If not, see . + */ + +#ifndef GDATA_CLIENT_LOGIN_AUTHORIZER_H +#define GDATA_CLIENT_LOGIN_AUTHORIZER_H + +#include +#include + +#include "gdata-authorizer.h" + +G_BEGIN_DECLS + +/** + * GDataClientLoginAuthorizerError: + * @GDATA_CLIENT_LOGIN_AUTHORIZER_ERROR_BAD_AUTHENTICATION: The login request used a username or password that is not recognized. + * @GDATA_CLIENT_LOGIN_AUTHORIZER_ERROR_NOT_VERIFIED: The account email address has not been verified. The user will need to access their Google + * account directly to resolve the issue before logging in using a non-Google application. + * @GDATA_CLIENT_LOGIN_AUTHORIZER_ERROR_TERMS_NOT_AGREED: The user has not agreed to terms. The user will need to access their Google account directly + * to resolve the issue before logging in using a non-Google application. + * @GDATA_CLIENT_LOGIN_AUTHORIZER_ERROR_CAPTCHA_REQUIRED: A CAPTCHA is required. (A response with this error code will also contain an image URI and a + * CAPTCHA token.) + * @GDATA_CLIENT_LOGIN_AUTHORIZER_ERROR_ACCOUNT_DELETED: The user account has been deleted. + * @GDATA_CLIENT_LOGIN_AUTHORIZER_ERROR_ACCOUNT_DISABLED: The user account has been disabled. + * @GDATA_CLIENT_LOGIN_AUTHORIZER_ERROR_SERVICE_DISABLED: The user's access to the specified service has been disabled. (The user account may still be + * valid.) + * @GDATA_CLIENT_LOGIN_AUTHORIZER_ERROR_ACCOUNT_MIGRATED: The user's account login details have been migrated to a new system. (This is used for the + * transition from the old YouTube login details to the new ones.) + * @GDATA_CLIENT_LOGIN_AUTHORIZER_ERROR_INVALID_SECOND_FACTOR: The user's account requires an application-specific password to be used. + * + * Error codes for authentication and authorization operations on #GDataClientLoginAuthorizer. See the + * online ClientLogin documentation for + * more information. + * + * Since: 0.9.0 + */ +typedef enum { + GDATA_CLIENT_LOGIN_AUTHORIZER_ERROR_BAD_AUTHENTICATION = 1, + GDATA_CLIENT_LOGIN_AUTHORIZER_ERROR_NOT_VERIFIED, + GDATA_CLIENT_LOGIN_AUTHORIZER_ERROR_TERMS_NOT_AGREED, + GDATA_CLIENT_LOGIN_AUTHORIZER_ERROR_CAPTCHA_REQUIRED, + GDATA_CLIENT_LOGIN_AUTHORIZER_ERROR_ACCOUNT_DELETED, + GDATA_CLIENT_LOGIN_AUTHORIZER_ERROR_ACCOUNT_DISABLED, + GDATA_CLIENT_LOGIN_AUTHORIZER_ERROR_SERVICE_DISABLED, + GDATA_CLIENT_LOGIN_AUTHORIZER_ERROR_ACCOUNT_MIGRATED, + GDATA_CLIENT_LOGIN_AUTHORIZER_ERROR_INVALID_SECOND_FACTOR +} GDataClientLoginAuthorizerError; + +GQuark gdata_client_login_authorizer_error_quark (void) G_GNUC_CONST; + +#define GDATA_CLIENT_LOGIN_AUTHORIZER_ERROR gdata_client_login_authorizer_error_quark () + +#define GDATA_TYPE_CLIENT_LOGIN_AUTHORIZER (gdata_client_login_authorizer_get_type ()) +#define GDATA_CLIENT_LOGIN_AUTHORIZER(o) \ + (G_TYPE_CHECK_INSTANCE_CAST ((o), GDATA_TYPE_CLIENT_LOGIN_AUTHORIZER, GDataClientLoginAuthorizer)) +#define GDATA_CLIENT_LOGIN_AUTHORIZER_CLASS(k) \ + (G_TYPE_CHECK_CLASS_CAST((k), GDATA_TYPE_CLIENT_LOGIN_AUTHORIZER, GDataClientLoginAuthorizerClass)) +#define GDATA_IS_CLIENT_LOGIN_AUTHORIZER(o) (G_TYPE_CHECK_INSTANCE_TYPE ((o), GDATA_TYPE_CLIENT_LOGIN_AUTHORIZER)) +#define GDATA_IS_CLIENT_LOGIN_AUTHORIZER_CLASS(k) (G_TYPE_CHECK_CLASS_TYPE ((k), GDATA_TYPE_CLIENT_LOGIN_AUTHORIZER)) +#define GDATA_CLIENT_LOGIN_AUTHORIZER_GET_CLASS(o) \ + (G_TYPE_INSTANCE_GET_CLASS ((o), GDATA_TYPE_CLIENT_LOGIN_AUTHORIZER, GDataClientLoginAuthorizerClass)) + +typedef struct _GDataClientLoginAuthorizerPrivate GDataClientLoginAuthorizerPrivate; + +/** + * GDataClientLoginAuthorizer: + * + * All the fields in the #GDataClientLoginAuthorizer structure are private and should never be accessed directly. + * + * Since: 0.9.0 + */ +typedef struct { + /*< private >*/ + GObject parent; + GDataClientLoginAuthorizerPrivate *priv; +} GDataClientLoginAuthorizer; + +/** + * GDataClientLoginAuthorizerClass: + * + * All the fields in the #GDataClientLoginAuthorizerClass structure are private and should never be accessed directly. + * + * Since: 0.9.0 + */ +typedef struct { + /*< private >*/ + GObjectClass parent; + + /*< private >*/ + /* Padding for future expansion */ + void (*_g_reserved0) (void); + void (*_g_reserved1) (void); +} GDataClientLoginAuthorizerClass; + +GType gdata_client_login_authorizer_get_type (void) G_GNUC_CONST; +G_DEFINE_AUTOPTR_CLEANUP_FUNC (GDataClientLoginAuthorizer, g_object_unref) + +GDataClientLoginAuthorizer *gdata_client_login_authorizer_new (const gchar *client_id, GType service_type) G_GNUC_WARN_UNUSED_RESULT G_GNUC_MALLOC; +GDataClientLoginAuthorizer *gdata_client_login_authorizer_new_for_authorization_domains (const gchar *client_id, GList *authorization_domains) + G_GNUC_WARN_UNUSED_RESULT G_GNUC_MALLOC; + +gboolean gdata_client_login_authorizer_authenticate (GDataClientLoginAuthorizer *self, const gchar *username, const gchar *password, + GCancellable *cancellable, GError **error); +void gdata_client_login_authorizer_authenticate_async (GDataClientLoginAuthorizer *self, const gchar *username, const gchar *password, + GCancellable *cancellable, GAsyncReadyCallback callback, gpointer user_data); +gboolean gdata_client_login_authorizer_authenticate_finish (GDataClientLoginAuthorizer *self, GAsyncResult *async_result, GError **error); + +const gchar *gdata_client_login_authorizer_get_client_id (GDataClientLoginAuthorizer *self) G_GNUC_PURE; +const gchar *gdata_client_login_authorizer_get_username (GDataClientLoginAuthorizer *self) G_GNUC_PURE; +const gchar *gdata_client_login_authorizer_get_password (GDataClientLoginAuthorizer *self) G_GNUC_PURE; + +#ifndef LIBGDATA_DISABLE_DEPRECATED +SoupURI *gdata_client_login_authorizer_get_proxy_uri (GDataClientLoginAuthorizer *self) G_GNUC_PURE G_GNUC_DEPRECATED_FOR (gdata_client_login_authorizer_get_proxy_resolver); +void gdata_client_login_authorizer_set_proxy_uri (GDataClientLoginAuthorizer *self, SoupURI *proxy_uri) G_GNUC_DEPRECATED_FOR (gdata_client_login_authorizer_set_proxy_resolver); +#endif /* !LIBGDATA_DISABLE_DEPRECATED */ + +GProxyResolver *gdata_client_login_authorizer_get_proxy_resolver (GDataClientLoginAuthorizer *self) G_GNUC_PURE; +void gdata_client_login_authorizer_set_proxy_resolver (GDataClientLoginAuthorizer *self, GProxyResolver *proxy_resolver); + +guint gdata_client_login_authorizer_get_timeout (GDataClientLoginAuthorizer *self) G_GNUC_PURE; +void gdata_client_login_authorizer_set_timeout (GDataClientLoginAuthorizer *self, guint timeout); + +G_END_DECLS + +#endif /* !GDATA_CLIENT_LOGIN_AUTHORIZER_H */ diff --git a/gdata/gdata-comment.c b/gdata/gdata-comment.c new file mode 100644 index 0000000..c5bcc10 --- /dev/null +++ b/gdata/gdata-comment.c @@ -0,0 +1,54 @@ +/* -*- Mode: C; indent-tabs-mode: t; c-basic-offset: 8; tab-width: 8 -*- */ +/* + * GData Client + * Copyright (C) Philip Withnall 2011 + * + * GData Client is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * GData Client is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with GData Client. If not, see . + */ + +/** + * SECTION:gdata-comment + * @short_description: GData comment object + * @stability: Stable + * @include: gdata/gdata-comment.h + * + * #GDataComment is a subclass of #GDataEntry to represent a generic comment on an entry. It is returned by the methods implemented in the + * #GDataCommentable interface. + * + * Any class which implements #GDataCommentable should have its own concrete subclass of #GDataComment which provides service-specific functionality. + * + * All subclasses of #GDataComment should ensure that the body of a comment is accessible using gdata_entry_get_content(), and that each comment has + * at least one #GDataAuthor object representing the person who wrote the comment, accessible using gdata_entry_get_authors(). + * + * Since: 0.10.0 + */ + +#include +#include + +#include "gdata-comment.h" + +G_DEFINE_ABSTRACT_TYPE (GDataComment, gdata_comment, GDATA_TYPE_ENTRY) + +static void +gdata_comment_class_init (GDataCommentClass *klass) +{ + /* Nothing to see here */ +} + +static void +gdata_comment_init (GDataComment *self) +{ + /* Nothing to see here */ +} diff --git a/gdata/gdata-comment.h b/gdata/gdata-comment.h new file mode 100644 index 0000000..973ac1e --- /dev/null +++ b/gdata/gdata-comment.h @@ -0,0 +1,72 @@ +/* -*- Mode: C; indent-tabs-mode: t; c-basic-offset: 8; tab-width: 8 -*- */ +/* + * GData Client + * Copyright (C) Philip Withnall 2011 + * + * GData Client is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * GData Client is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with GData Client. If not, see . + */ + +#ifndef GDATA_COMMENT_H +#define GDATA_COMMENT_H + +#include +#include + +#include + +G_BEGIN_DECLS + +#define GDATA_TYPE_COMMENT (gdata_comment_get_type ()) +#define GDATA_COMMENT(o) (G_TYPE_CHECK_INSTANCE_CAST ((o), GDATA_TYPE_COMMENT, GDataComment)) +#define GDATA_COMMENT_CLASS(k) (G_TYPE_CHECK_CLASS_CAST((k), GDATA_TYPE_COMMENT, GDataCommentClass)) +#define GDATA_IS_COMMENT(o) (G_TYPE_CHECK_INSTANCE_TYPE ((o), GDATA_TYPE_COMMENT)) +#define GDATA_IS_COMMENT_CLASS(k) (G_TYPE_CHECK_CLASS_TYPE ((k), GDATA_TYPE_COMMENT)) +#define GDATA_COMMENT_GET_CLASS(o) (G_TYPE_INSTANCE_GET_CLASS ((o), GDATA_TYPE_COMMENT, GDataCommentClass)) + +typedef struct _GDataCommentPrivate GDataCommentPrivate; + +/** + * GDataComment: + * + * All the fields in the #GDataComment structure are private and should never be accessed directly. + * + * Since: 0.10.0 + */ +typedef struct { + GDataEntry parent; + GDataCommentPrivate *priv; +} GDataComment; + +/** + * GDataCommentClass: + * + * All the fields in the #GDataCommentClass structure are private and should never be accessed directly. + * + * Since: 0.10.0 + */ +typedef struct { + /*< private >*/ + GDataEntryClass parent; + + /*< private >*/ + /* Padding for future expansion */ + void (*_g_reserved0) (void); + void (*_g_reserved1) (void); +} GDataCommentClass; + +GType gdata_comment_get_type (void) G_GNUC_CONST; + +G_END_DECLS + +#endif /* !GDATA_COMMENT_H */ diff --git a/gdata/gdata-commentable.c b/gdata/gdata-commentable.c new file mode 100644 index 0000000..4718a9e --- /dev/null +++ b/gdata/gdata-commentable.c @@ -0,0 +1,598 @@ +/* -*- Mode: C; indent-tabs-mode: t; c-basic-offset: 8; tab-width: 8 -*- */ +/* + * GData Client + * Copyright (C) Philip Withnall 2008–2010 + * Copyright (C) Richard Schwarting 2010 + * + * GData Client is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * GData Client is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with GData Client. If not, see . + */ + +/** + * SECTION:gdata-commentable + * @short_description: GData commentable interface + * @stability: Stable + * @include: gdata/gdata-commentable.h + * + * #GDataCommentable is an interface which can be implemented by commentable objects: objects which support having comments added to them by users, + * such as videos and photos. + * + * Comments may be queried, added and deleted. Note that they may not be edited. + * + * #GDataCommentable objects may not support all operations on comments, on an instance-by-instance basis (i.e. it's an invalid assumption that if, + * for example, one #GDataYouTubeVideo doesn't support adding comments all other #GDataYouTubeVideos don't support adding comments either). + * Specific documentation for a particular type of #GDataCommentable may state otherwise, though. + * + * + * Querying for Comments + * + * GDataService *service; + * GDataCommentable *commentable; + * + * /* Create a service */ + * service = create_service (); + * + * /* Retrieve the GDataCommentable which is going to be queried. This may be, for example, a GDataYouTubeVideo. */ + * commentable = get_commentable (); + * + * /* Start the async. query for the comments. */ + * gdata_commentable_query_comments_async (commentable, service, NULL, NULL, NULL, NULL, NULL, (GAsyncReadyCallback) query_comments_cb, NULL); + * + * g_object_unref (service); + * g_object_unref (commentable); + * + * static void + * query_comments_cb (GDataCommentable *commentable, GAsyncResult *result, gpointer user_data) + * { + * GDataFeed *comment_feed; + * GList *comments, *i; + * GError *error = NULL; + * + * comment_feed = gdata_commentable_query_comments_finish (commentable, result, &error); + * + * if (error != NULL) { + * /* Error! */ + * g_error ("Error querying comments: %s", error->message); + * g_error_free (error); + * return; + * } + * + * /* Examine the comments. */ + * comments = gdata_feed_get_entries (comment_feed); + * for (i = comments; i != NULL; i = i->next) { + * /* Note that this will actually be a subclass of GDataComment, + * * such as GDataYouTubeComment or GDataPicasaWebComment. */ + * GDataComment *comment = GDATA_COMMENT (i->data); + * GDataAuthor *author; + * + * /* Note that in practice it might not always be safe to assume that a comment always has an author. */ + * author = GDATA_AUTHOR (gdata_entry_get_authors (GDATA_ENTRY (comment))->data); + * + * g_message ("Comment by %s (%s): %s", + * gdata_author_get_name (author), + * gdata_author_get_uri (author), + * gdata_entry_get_content (GDATA_ENTRY (comment))); + * } + * + * g_object_unref (comment_feed); + * } + * + * + * + * Since: 0.10.0 + */ + +#include +#include +#include +#include + +#include "gdata-commentable.h" +#include "gdata-service.h" + +G_DEFINE_INTERFACE (GDataCommentable, gdata_commentable, GDATA_TYPE_ENTRY) + +static void +gdata_commentable_default_init (GDataCommentableInterface *iface) +{ + iface->comment_type = G_TYPE_INVALID; + iface->get_authorization_domain = NULL; + iface->get_query_comments_uri = NULL; + iface->get_insert_comment_uri = NULL; + iface->is_comment_deletable = NULL; +} + +static GType +get_comment_type (GDataCommentableInterface *iface) +{ + GType comment_type; + + comment_type = iface->comment_type; + g_assert (g_type_is_a (comment_type, GDATA_TYPE_COMMENT) == TRUE); + + return comment_type; +} + +/** + * gdata_commentable_query_comments: + * @self: a #GDataCommentable + * @service: a #GDataService representing the service with which the object's comments will be manipulated + * @query: (allow-none): a #GDataQuery with query parameters, or %NULL + * @cancellable: (allow-none): optional #GCancellable object, or %NULL + * @progress_callback: (allow-none) (scope call) (closure progress_user_data): a #GDataQueryProgressCallback to call when a comment is loaded, or %NULL + * @progress_user_data: (closure): data to pass to the @progress_callback function + * @error: a #GError, or %NULL + * + * Retrieves a #GDataFeed containing the #GDataComments representing the comments on the #GDataCommentable which match the given @query. + * + * If the #GDataCommentable doesn't support commenting, %NULL will be returned and @error will be set to %GDATA_SERVICE_ERROR_FORBIDDEN. This is in + * contrast to if it does support commenting but hasn't had any comments added yet, in which case an empty #GDataFeed will be returned and no error + * will be set. + * + * Return value: (transfer full) (allow-none): a #GDataFeed of #GDataComments, or %NULL; unref with g_object_unref() + * + * Since: 0.10.0 + */ +GDataFeed * +gdata_commentable_query_comments (GDataCommentable *self, GDataService *service, GDataQuery *query, + GCancellable *cancellable, GDataQueryProgressCallback progress_callback, + gpointer progress_user_data, GError **error) +{ + GDataCommentableInterface *iface; + gchar *uri; + GDataFeed *feed; + GDataAuthorizationDomain *domain = NULL; + + g_return_val_if_fail (GDATA_IS_COMMENTABLE (self), NULL); + g_return_val_if_fail (GDATA_IS_SERVICE (service), NULL); + g_return_val_if_fail (query == NULL || GDATA_IS_QUERY (query), NULL); + g_return_val_if_fail (cancellable == NULL || G_IS_CANCELLABLE (cancellable), NULL); + g_return_val_if_fail (error == NULL || *error == NULL, NULL); + + iface = GDATA_COMMENTABLE_GET_IFACE (self); + + /* Get the comment feed URI. */ + g_assert (iface->get_query_comments_uri != NULL); + uri = iface->get_query_comments_uri (self); + + /* The URI can be NULL when no comments and thus no feedLink is present in a GDataCommentable */ + if (uri == NULL) { + /* Translators: This is an error message for if a user attempts to retrieve comments from an entry (such as a video) which doesn't + * support comments. */ + g_set_error_literal (error, GDATA_SERVICE_ERROR, GDATA_SERVICE_ERROR_FORBIDDEN, _("This entry does not support comments.")); + return NULL; + } + + /* Get the authorisation domain. */ + if (iface->get_authorization_domain != NULL) { + domain = iface->get_authorization_domain (self); + } + + /* Get the comment feed. */ + feed = gdata_service_query (service, domain, uri, query, get_comment_type (iface), cancellable, progress_callback, progress_user_data, error); + g_free (uri); + + return feed; +} + +static void +query_comments_async_cb (GDataService *service, GAsyncResult *service_result, gpointer user_data) +{ + g_autoptr(GTask) commentable_task = G_TASK (user_data); + g_autoptr(GDataFeed) feed = NULL; + g_autoptr(GError) error = NULL; + + feed = gdata_service_query_finish (service, service_result, &error); + + if (error != NULL) + g_task_return_error (commentable_task, g_steal_pointer (&error)); + else + g_task_return_pointer (commentable_task, g_steal_pointer (&feed), g_object_unref); +} + +/** + * gdata_commentable_query_comments_async: + * @self: a #GDataCommentable + * @service: a #GDataService representing the service with which the object's comments will be manipulated + * @query: (allow-none): a #GDataQuery with query parameters, or %NULL + * @cancellable: (allow-none): optional #GCancellable object, or %NULL + * @progress_callback: (allow-none) (scope notified) (closure progress_user_data): a #GDataQueryProgressCallback to call when a comment is loaded, + * or %NULL + * @progress_user_data: (closure): data to pass to the @progress_callback function + * @destroy_progress_user_data: (allow-none): a function to call when @progress_callback will not be called any more, or %NULL; this function will be + * called with @progress_user_data as a parameter and can be used to free any memory allocated for it + * @callback: a #GAsyncReadyCallback to call when the query is finished + * @user_data: (closure): data to pass to the @callback function + * + * Retrieves a #GDataFeed containing the #GDataComments representing the comments on the #GDataCommentable which match the given @query. + * @self, @service and @query are all reffed when this method is called, so can safely be freed after this method returns. + * + * For more details, see gdata_commentable_query_comments(), which is the synchronous version of this method. + * + * When the operation is finished, @callback will be called. You can then call gdata_commentable_query_comments_finish() to get the results of the + * operation. + * + * Since: 0.10.0 + */ +void +gdata_commentable_query_comments_async (GDataCommentable *self, GDataService *service, GDataQuery *query, GCancellable *cancellable, + GDataQueryProgressCallback progress_callback, gpointer progress_user_data, + GDestroyNotify destroy_progress_user_data, GAsyncReadyCallback callback, gpointer user_data) +{ + GDataCommentableInterface *iface; + gchar *uri; + g_autoptr(GTask) task = NULL; + GDataAuthorizationDomain *domain = NULL; + + g_return_if_fail (GDATA_IS_COMMENTABLE (self)); + g_return_if_fail (GDATA_IS_SERVICE (service)); + g_return_if_fail (query == NULL || GDATA_IS_QUERY (query)); + g_return_if_fail (cancellable == NULL || G_IS_CANCELLABLE (cancellable)); + g_return_if_fail (callback != NULL); + + iface = GDATA_COMMENTABLE_GET_IFACE (self); + + /* Get the comment feed URI. */ + g_assert (iface->get_query_comments_uri != NULL); + uri = iface->get_query_comments_uri (self); + + /* Build the async result. */ + task = g_task_new (self, cancellable, callback, user_data); + g_task_set_source_tag (task, gdata_commentable_query_comments_async); + + /* The URI can be NULL when no comments and thus no feedLink is present in a GDataCommentable */ + if (uri == NULL) { + g_task_return_new_error (task, GDATA_SERVICE_ERROR, GDATA_SERVICE_ERROR_FORBIDDEN, + /* Translators: This is an error message for if a user attempts to retrieve comments from an entry + * (such as a video) which doesn't support comments. */ + _("This entry does not support comments.")); + return; + } + + /* Get the authorisation domain. */ + if (iface->get_authorization_domain != NULL) { + domain = iface->get_authorization_domain (self); + } + + /* Get the comment feed. */ + gdata_service_query_async (service, domain, uri, query, get_comment_type (iface), cancellable, progress_callback, progress_user_data, + destroy_progress_user_data, (GAsyncReadyCallback) query_comments_async_cb, g_object_ref (task)); + g_free (uri); +} + +/** + * gdata_commentable_query_comments_finish: + * @self: a #GDataCommentable + * @result: a #GAsyncResult + * @error: a #GError, or %NULL + * + * Finishes an asynchronous comment query operation started with gdata_commentable_query_comments_async(). + * + * Return value: (transfer full) (allow-none): a #GDataFeed of #GDataComments, or %NULL; unref with g_object_unref() + * + * Since: 0.10.0 + */ +GDataFeed * +gdata_commentable_query_comments_finish (GDataCommentable *self, GAsyncResult *result, GError **error) +{ + g_return_val_if_fail (GDATA_IS_COMMENTABLE (self), NULL); + g_return_val_if_fail (G_IS_ASYNC_RESULT (result), NULL); + g_return_val_if_fail (error == NULL || *error == NULL, NULL); + g_return_val_if_fail (g_task_is_valid (result, self), NULL); + g_return_val_if_fail (g_async_result_is_tagged (result, gdata_commentable_query_comments_async), NULL); + + return g_task_propagate_pointer (G_TASK (result), error); +} + +/** + * gdata_commentable_insert_comment: + * @self: a #GDataCommentable + * @service: a #GDataService with which the comment will be added + * @comment_: a new comment to be added to the #GDataCommentable + * @cancellable: (allow-none): optional #GCancellable object, or %NULL + * @error: a #GError, or %NULL + * + * Adds @comment to the #GDataCommentable. + * + * If the #GDataCommentable doesn't support commenting, %NULL will be returned and @error will be set to %GDATA_SERVICE_ERROR_FORBIDDEN. + * + * Return value: (transfer full) (allow-none): the added #GDataComment, or %NULL; unref with g_object_unref() + * + * Since: 0.10.0 + */ +GDataComment * +gdata_commentable_insert_comment (GDataCommentable *self, GDataService *service, GDataComment *comment_, GCancellable *cancellable, GError **error) +{ + GDataCommentableInterface *iface; + gchar *uri; + GDataComment *new_comment; + GDataAuthorizationDomain *domain = NULL; + + g_return_val_if_fail (GDATA_IS_COMMENTABLE (self), NULL); + g_return_val_if_fail (GDATA_IS_SERVICE (service), NULL); + g_return_val_if_fail (GDATA_IS_COMMENT (comment_), NULL); + g_return_val_if_fail (cancellable == NULL || G_IS_CANCELLABLE (cancellable), NULL); + g_return_val_if_fail (error == NULL || *error == NULL, NULL); + + iface = GDATA_COMMENTABLE_GET_IFACE (self); + + g_return_val_if_fail (g_type_is_a (G_OBJECT_TYPE (comment_), get_comment_type (iface)) == TRUE, NULL); + + /* Get the upload URI. */ + g_assert (iface->get_insert_comment_uri != NULL); + uri = iface->get_insert_comment_uri (self, comment_); + + if (uri == NULL) { + /* Translators: This is an error message for if a user attempts to add a comment to an entry (such as a video) which doesn't support + * comments. */ + g_set_error_literal (error, GDATA_SERVICE_ERROR, GDATA_SERVICE_ERROR_FORBIDDEN, _("Comments may not be added to this entry.")); + return NULL; + } + + /* Get the authorisation domain. */ + if (iface->get_authorization_domain != NULL) { + domain = iface->get_authorization_domain (self); + } + + /* Add the comment. */ + new_comment = GDATA_COMMENT (gdata_service_insert_entry (service, domain, uri, GDATA_ENTRY (comment_), cancellable, error)); + + g_free (uri); + + return new_comment; +} + +static void +insert_comment_async_cb (GDataService *service, GAsyncResult *service_result, gpointer user_data) +{ + g_autoptr(GTask) commentable_task = G_TASK (user_data); + g_autoptr(GDataEntry) new_comment = NULL; + g_autoptr(GError) error = NULL; + + new_comment = gdata_service_insert_entry_finish (service, service_result, &error); + + if (error != NULL) + g_task_return_error (commentable_task, g_steal_pointer (&error)); + else + g_task_return_pointer (commentable_task, g_steal_pointer (&new_comment), g_object_unref); +} + +/** + * gdata_commentable_insert_comment_async: + * @self: a #GDataCommentable + * @service: a #GDataService with which the comment will be added + * @comment_: a new comment to be added to the #GDataCommentable + * @cancellable: (allow-none): optional #GCancellable object, or %NULL + * @callback: a #GAsyncReadyCallback to call when the operation is finished + * @user_data: (closure): data to pass to the @callback function + * + * Adds @comment to the #GDataCommentable. @self, @service and @comment_ are all reffed when this method is called, so can safely be freed after this + * method returns. + * + * For more details, see gdata_commentable_insert_comment(), which is the synchronous version of this method. + * + * When the operation is finished, @callback will be called. You can then call gdata_commentable_insert_comment_finish() to get the results of the + * operation. + * + * Since: 0.10.0 + */ +void +gdata_commentable_insert_comment_async (GDataCommentable *self, GDataService *service, GDataComment *comment_, GCancellable *cancellable, + GAsyncReadyCallback callback, gpointer user_data) +{ + GDataCommentableInterface *iface; + g_autofree gchar *uri = NULL; + g_autoptr(GTask) task = NULL; + GDataAuthorizationDomain *domain = NULL; + + g_return_if_fail (GDATA_IS_COMMENTABLE (self)); + g_return_if_fail (GDATA_IS_SERVICE (service)); + g_return_if_fail (GDATA_IS_COMMENT (comment_)); + g_return_if_fail (cancellable == NULL || G_IS_CANCELLABLE (cancellable)); + + iface = GDATA_COMMENTABLE_GET_IFACE (self); + + g_return_if_fail (g_type_is_a (G_OBJECT_TYPE (comment_), get_comment_type (iface)) == TRUE); + + /* Get the upload URI. */ + g_assert (iface->get_insert_comment_uri != NULL); + uri = iface->get_insert_comment_uri (self, comment_); + + /* Build the async result. */ + task = g_task_new (self, cancellable, callback, user_data); + g_task_set_source_tag (task, gdata_commentable_insert_comment_async); + + /* The URI can be NULL when no comments and thus no feedLink is present in a GDataCommentable */ + if (uri == NULL) { + g_task_return_new_error (task, GDATA_SERVICE_ERROR, GDATA_SERVICE_ERROR_FORBIDDEN, + /* Translators: This is an error message for if a user attempts to add a comment to an entry + * (such as a video) which doesn't support comments. */ + _("Comments may not be added to this entry.")); + return; + } + + /* Get the authorisation domain. */ + if (iface->get_authorization_domain != NULL) { + domain = iface->get_authorization_domain (self); + } + + /* Add the comment. */ + gdata_service_insert_entry_async (service, domain, uri, GDATA_ENTRY (comment_), cancellable, (GAsyncReadyCallback) insert_comment_async_cb, + g_object_ref (task)); +} + +/** + * gdata_commentable_insert_comment_finish: + * @self: a #GDataCommentable + * @result: a #GAsyncResult + * @error: a #GError, or %NULL + * + * Finishes an asynchronous comment insertion operation started with gdata_commentable_insert_comment_async(). + * + * Return value: (transfer full) (allow-none): the added #GDataComment, or %NULL; unref with g_object_unref() + * + * Since: 0.10.0 + */ +GDataComment * +gdata_commentable_insert_comment_finish (GDataCommentable *self, GAsyncResult *result, GError **error) +{ + g_return_val_if_fail (GDATA_IS_COMMENTABLE (self), NULL); + g_return_val_if_fail (G_IS_ASYNC_RESULT (result), NULL); + g_return_val_if_fail (error == NULL || *error == NULL, NULL); + g_return_val_if_fail (g_task_is_valid (result, self), NULL); + g_return_val_if_fail (g_async_result_is_tagged (result, gdata_commentable_insert_comment_async), NULL); + + return g_task_propagate_pointer (G_TASK (result), error); +} + +/** + * gdata_commentable_delete_comment: + * @self: a #GDataCommentable + * @service: a #GDataService with which the comment will be deleted + * @comment_: a comment to be deleted + * @cancellable: (allow-none): optional #GCancellable object, or %NULL + * @error: a #GError, or %NULL + * + * Deletes @comment from the #GDataCommentable. + * + * If the given @comment isn't deletable (either because the service doesn't support deleting comments at all, or because this particular comment + * is not deletable due to having insufficient permissions), %GDATA_SERVICE_ERROR_FORBIDDEN will be set in @error and %FALSE will be returned. + * + * Return value: %TRUE if the comment was successfully deleted, %FALSE otherwise + * + * Since: 0.10.0 + */ +gboolean +gdata_commentable_delete_comment (GDataCommentable *self, GDataService *service, GDataComment *comment_, GCancellable *cancellable, GError **error) +{ + GDataCommentableInterface *iface; + GDataAuthorizationDomain *domain = NULL; + + g_return_val_if_fail (GDATA_IS_COMMENTABLE (self), FALSE); + g_return_val_if_fail (GDATA_IS_SERVICE (service), FALSE); + g_return_val_if_fail (GDATA_IS_COMMENT (comment_), FALSE); + g_return_val_if_fail (cancellable == NULL || G_IS_CANCELLABLE (cancellable), FALSE); + g_return_val_if_fail (error == NULL || *error == NULL, FALSE); + + iface = GDATA_COMMENTABLE_GET_IFACE (self); + + g_return_val_if_fail (g_type_is_a (G_OBJECT_TYPE (comment_), get_comment_type (iface)) == TRUE, FALSE); + + g_assert (iface->is_comment_deletable != NULL); + if (iface->is_comment_deletable (self, comment_) == FALSE) { + /* Translators: This is an error message for if a user attempts to delete a comment they're not allowed to delete. */ + g_set_error_literal (error, GDATA_SERVICE_ERROR, GDATA_SERVICE_ERROR_FORBIDDEN, _("This comment may not be deleted.")); + return FALSE; + } + + /* Get the authorisation domain. */ + if (iface->get_authorization_domain != NULL) { + domain = iface->get_authorization_domain (self); + } + + /* Delete the comment. */ + return gdata_service_delete_entry (service, domain, GDATA_ENTRY (comment_), cancellable, error); +} + +static void +delete_comment_async_cb (GDataService *service, GAsyncResult *service_result, gpointer user_data) +{ + g_autoptr(GTask) commentable_task = G_TASK (user_data); + g_autoptr(GError) error = NULL; + + if (!gdata_service_delete_entry_finish (service, service_result, &error)) + g_task_return_error (commentable_task, g_steal_pointer (&error)); + else + g_task_return_boolean (commentable_task, TRUE); +} + +/** + * gdata_commentable_delete_comment_async: + * @self: a #GDataCommentable + * @service: a #GDataService with which the comment will be deleted + * @comment_: a comment to be deleted + * @cancellable: (allow-none): optional #GCancellable object, or %NULL + * @callback: a #GAsyncReadyCallback to call when the operation is finished + * @user_data: (closure): data to pass to the @callback function + * + * Deletes @comment from the #GDataCommentable. @self, @service and @comment_ are all reffed when this method is called, so can safely be freed after + * this method returns. + * + * For more details, see gdata_commentable_delete_comment(), which is the synchronous version of this method. + * + * When the operation is finished, @callback will be called. You can then call gdata_commentable_delete_comment_finish() to get the results of the + * operation. + * + * Since: 0.10.0 + */ +void +gdata_commentable_delete_comment_async (GDataCommentable *self, GDataService *service, GDataComment *comment_, GCancellable *cancellable, + GAsyncReadyCallback callback, gpointer user_data) +{ + GDataCommentableInterface *iface; + g_autoptr(GTask) task = NULL; + GDataAuthorizationDomain *domain = NULL; + + g_return_if_fail (GDATA_IS_COMMENTABLE (self)); + g_return_if_fail (GDATA_IS_SERVICE (service)); + g_return_if_fail (GDATA_IS_COMMENT (comment_)); + g_return_if_fail (cancellable == NULL || G_IS_CANCELLABLE (cancellable)); + + iface = GDATA_COMMENTABLE_GET_IFACE (self); + + g_return_if_fail (g_type_is_a (G_OBJECT_TYPE (comment_), get_comment_type (iface)) == TRUE); + + /* Build the async result. */ + task = g_task_new (self, cancellable, callback, user_data); + g_task_set_source_tag (task, gdata_commentable_delete_comment_async); + + g_assert (iface->is_comment_deletable != NULL); + if (iface->is_comment_deletable (self, comment_) == FALSE) { + g_task_return_new_error (task, GDATA_SERVICE_ERROR, GDATA_SERVICE_ERROR_FORBIDDEN, + /* Translators: This is an error message for if a user attempts to delete a comment they're not allowed to delete. */ + _("This comment may not be deleted.")); + return; + } + + /* Get the authorisation domain. */ + if (iface->get_authorization_domain != NULL) { + domain = iface->get_authorization_domain (self); + } + + /* Delete the comment. */ + gdata_service_delete_entry_async (service, domain, GDATA_ENTRY (comment_), cancellable, (GAsyncReadyCallback) delete_comment_async_cb, g_object_ref (task)); +} + +/** + * gdata_commentable_delete_comment_finish: + * @self: a #GDataCommentable + * @result: a #GAsyncResult + * @error: a #GError, or %NULL + * + * Finishes an asynchronous comment deletion operation started with gdata_commentable_delete_comment_async(). + * + * Return value: %TRUE if the comment was successfully deleted, %FALSE otherwise + * + * Since: 0.10.0 + */ +gboolean +gdata_commentable_delete_comment_finish (GDataCommentable *self, GAsyncResult *result, GError **error) +{ + g_return_val_if_fail (GDATA_IS_COMMENTABLE (self), FALSE); + g_return_val_if_fail (G_IS_ASYNC_RESULT (result), FALSE); + g_return_val_if_fail (error == NULL || *error == NULL, FALSE); + g_return_val_if_fail (g_task_is_valid (result, self), FALSE); + g_return_val_if_fail (g_async_result_is_tagged (result, gdata_commentable_delete_comment_async), FALSE); + + return g_task_propagate_boolean (G_TASK (result), error); +} diff --git a/gdata/gdata-commentable.h b/gdata/gdata-commentable.h new file mode 100644 index 0000000..0810b19 --- /dev/null +++ b/gdata/gdata-commentable.h @@ -0,0 +1,103 @@ +/* -*- Mode: C; indent-tabs-mode: t; c-basic-offset: 8; tab-width: 8 -*- */ +/* + * GData Client + * Copyright (C) Philip Withnall 2009 + * Copyright (C) Richard Schwarting 2010 + * + * GData Client is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * GData Client is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with GData Client. If not, see . + */ + +#ifndef GDATA_COMMENTABLE_H +#define GDATA_COMMENTABLE_H + +#include +#include + +#include +#include +#include + +G_BEGIN_DECLS + +#define GDATA_TYPE_COMMENTABLE (gdata_commentable_get_type ()) +#define GDATA_COMMENTABLE(o) (G_TYPE_CHECK_INSTANCE_CAST ((o), GDATA_TYPE_COMMENTABLE, GDataCommentable)) +#define GDATA_COMMENTABLE_CLASS(k) (G_TYPE_CHECK_CLASS_CAST((k), GDATA_TYPE_COMMENTABLE, GDataCommentableInterface)) +#define GDATA_IS_COMMENTABLE(o) (G_TYPE_CHECK_INSTANCE_TYPE ((o), GDATA_TYPE_COMMENTABLE)) +#define GDATA_COMMENTABLE_GET_IFACE(o) (G_TYPE_INSTANCE_GET_INTERFACE ((o), GDATA_TYPE_COMMENTABLE, GDataCommentableInterface)) + +/** + * GDataCommentable: + * + * All the fields in the #GDataCommentable structure are private and should never be accessed directly + * + * Since: 0.10.0 + */ +typedef struct _GDataCommentable GDataCommentable; /* dummy typedef */ + +/** + * GDataCommentableInterface: + * @parent: the parent type + * @comment_type: the #GType of the comment class (subclass of #GDataComment) to use for query results from this commentable object + * @get_authorization_domain: (allow-none): a function to return the #GDataAuthorizationDomain to be used for all operations on the comments + * belonging to this commentable object; not implementing this function is equivalent to returning %NULL from it, which signifies that operations on the + * comments don't require authorization + * @get_query_comments_uri: a function that returns the URI of a #GDataFeed of comments from a commentable object, or %NULL if the given commentable + * object doesn't support commenting; free with g_free() + * @get_insert_comment_uri: a function that returns the URI to add new comments to the commentable object, or %NULL if the given commentable object + * doesn't support adding comments; free with g_free() + * @is_comment_deletable: a function that returns %TRUE if the given comment may be deleted, %FALSE otherwise + * + * The interface structure for the #GDataCommentable interface. + * + * Since: 0.10.0 + */ +typedef struct { + GTypeInterface parent; + + GType comment_type; + + GDataAuthorizationDomain *(*get_authorization_domain) (GDataCommentable *self); + + gchar *(*get_query_comments_uri) (GDataCommentable *self); + gchar *(*get_insert_comment_uri) (GDataCommentable *self, GDataComment *comment); + gboolean (*is_comment_deletable) (GDataCommentable *self, GDataComment *comment); +} GDataCommentableInterface; + +GType gdata_commentable_get_type (void) G_GNUC_CONST; + +GDataFeed *gdata_commentable_query_comments (GDataCommentable *self, GDataService *service, GDataQuery *query, GCancellable *cancellable, + GDataQueryProgressCallback progress_callback, gpointer progress_user_data, + GError **error) G_GNUC_WARN_UNUSED_RESULT G_GNUC_MALLOC; +void gdata_commentable_query_comments_async (GDataCommentable *self, GDataService *service, GDataQuery *query, GCancellable *cancellable, + GDataQueryProgressCallback progress_callback, gpointer progress_user_data, + GDestroyNotify destroy_progress_user_data, GAsyncReadyCallback callback, gpointer user_data); +GDataFeed *gdata_commentable_query_comments_finish (GDataCommentable *self, GAsyncResult *result, + GError **error) G_GNUC_WARN_UNUSED_RESULT G_GNUC_MALLOC; + +GDataComment *gdata_commentable_insert_comment (GDataCommentable *self, GDataService *service, GDataComment *comment_, GCancellable *cancellable, + GError **error) G_GNUC_WARN_UNUSED_RESULT G_GNUC_MALLOC; +void gdata_commentable_insert_comment_async (GDataCommentable *self, GDataService *service, GDataComment *comment_, GCancellable *cancellable, + GAsyncReadyCallback callback, gpointer user_data); +GDataComment *gdata_commentable_insert_comment_finish (GDataCommentable *self, GAsyncResult *result, + GError **error) G_GNUC_WARN_UNUSED_RESULT G_GNUC_MALLOC; + +gboolean gdata_commentable_delete_comment (GDataCommentable *self, GDataService *service, GDataComment *comment_, GCancellable *cancellable, + GError **error); +void gdata_commentable_delete_comment_async (GDataCommentable *self, GDataService *service, GDataComment *comment_, GCancellable *cancellable, + GAsyncReadyCallback callback, gpointer user_data); +gboolean gdata_commentable_delete_comment_finish (GDataCommentable *self, GAsyncResult *result, GError **error); + +G_END_DECLS + +#endif /* !GDATA_COMMENTABLE_H */ diff --git a/gdata/gdata-comparable.c b/gdata/gdata-comparable.c new file mode 100644 index 0000000..d4c5d18 --- /dev/null +++ b/gdata/gdata-comparable.c @@ -0,0 +1,95 @@ +/* -*- Mode: C; indent-tabs-mode: t; c-basic-offset: 8; tab-width: 8 -*- */ +/* + * GData Client + * Copyright (C) Philip Withnall 2010 + * + * GData Client is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * GData Client is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with GData Client. If not, see . + */ + +/** + * SECTION:gdata-comparable + * @short_description: GData comparable interface + * @stability: Stable + * @include: gdata/gdata-comparable.h + * + * #GDataComparable is an interface which can be implemented by any object which needs to be compared to another object of the same type or of a + * derived type. + * + * When implementing the interface, classes must implement the compare_with function, and the implementation must be + * pure + * . + * + * Since: 0.7.0 + */ + +#include +#include + +#include "gdata-comparable.h" + +GType +gdata_comparable_get_type (void) +{ + static GType comparable_type = 0; + + if (!comparable_type) { + comparable_type = g_type_register_static_simple (G_TYPE_INTERFACE, "GDataComparable", + sizeof (GDataComparableIface), + NULL, 0, NULL, 0); + } + + return comparable_type; +} + +/** + * gdata_comparable_compare: + * @self: (allow-none): a #GDataComparable, or %NULL + * @other: (allow-none): another #GDataComparable of the same type, or %NULL + * + * Compares the two objects, returning -1 if @self is "less than" @other by some metric, 0 + * if they're equal, or 1 if @self is "greater than" @other. + * + * %NULL values are handled gracefully, with 0 returned if both @self and @other are %NULL, + * -1 if @self is %NULL and 1 if @other is %NULL. + * + * The @other object must be of the same type as @self, or of a type derived from @self's type. + * + * Return value: %TRUE on success, %FALSE otherwise + * + * Since: 0.7.0 + */ +gint +gdata_comparable_compare (GDataComparable *self, GDataComparable *other) +{ + GDataComparableIface *iface; + + g_return_val_if_fail (self == NULL || GDATA_IS_COMPARABLE (self), 0); + g_return_val_if_fail (other == NULL || GDATA_IS_COMPARABLE (other), 0); + g_return_val_if_fail (self == NULL || other == NULL || g_type_is_a (G_OBJECT_TYPE (other), G_OBJECT_TYPE (self)), 0); + + /* Deal with NULL values */ + if (self == NULL && other != NULL) + return -1; + else if (self != NULL && other == NULL) + return 1; + + if (self == other) + return 0; + + /* Use the comparator method for non-NULL values */ + iface = GDATA_COMPARABLE_GET_IFACE (self); + g_assert (iface->compare_with != NULL); + + return iface->compare_with (self, other); +} diff --git a/gdata/gdata-comparable.h b/gdata/gdata-comparable.h new file mode 100644 index 0000000..7843afe --- /dev/null +++ b/gdata/gdata-comparable.h @@ -0,0 +1,66 @@ +/* -*- Mode: C; indent-tabs-mode: t; c-basic-offset: 8; tab-width: 8 -*- */ +/* + * GData Client + * Copyright (C) Philip Withnall 2010 + * + * GData Client is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * GData Client is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with GData Client. If not, see . + */ + +#ifndef GDATA_COMPARABLE_H +#define GDATA_COMPARABLE_H + +#include +#include + +G_BEGIN_DECLS + +#define GDATA_TYPE_COMPARABLE (gdata_comparable_get_type ()) +#define GDATA_COMPARABLE(o) (G_TYPE_CHECK_INSTANCE_CAST ((o), GDATA_TYPE_COMPARABLE, GDataComparable)) +#define GDATA_COMPARABLE_CLASS(k) (G_TYPE_CHECK_CLASS_CAST((k), GDATA_TYPE_COMPARABLE, GDataComparableIface)) +#define GDATA_IS_COMPARABLE(o) (G_TYPE_CHECK_INSTANCE_TYPE ((o), GDATA_TYPE_COMPARABLE)) +#define GDATA_COMPARABLE_GET_IFACE(o) (G_TYPE_INSTANCE_GET_INTERFACE ((o), GDATA_TYPE_COMPARABLE, GDataComparableIface)) + +/** + * GDataComparable: + * + * All the fields in the #GDataComparable structure are private and should never be accessed directly. + * + * Since: 0.7.0 + */ +typedef struct _GDataComparable GDataComparable; /* dummy typedef */ + +/** + * GDataComparableIface: + * @parent: the parent type + * @compare_with: compares the object with an @other object of the same type, returning -1 if the object is "less than" + * the other object, 0 if they're equal, or 1 if the object is "greater than" the other. The + * function can assume that neither @self or @other will be %NULL, and that both have correct types. The function must be pure. + * + * The class structure for the #GDataComparable interface. + * + * Since: 0.7.0 + */ +typedef struct { + GTypeInterface parent; + + gint (*compare_with) (GDataComparable *self, GDataComparable *other); +} GDataComparableIface; + +GType gdata_comparable_get_type (void) G_GNUC_CONST; + +gint gdata_comparable_compare (GDataComparable *self, GDataComparable *other) G_GNUC_PURE; + +G_END_DECLS + +#endif /* !GDATA_COMPARABLE_H */ diff --git a/gdata/gdata-core.symbols b/gdata/gdata-core.symbols new file mode 100644 index 0000000..29e94fd --- /dev/null +++ b/gdata/gdata-core.symbols @@ -0,0 +1,1128 @@ +gdata_color_get_type +gdata_color_from_hexadecimal +gdata_color_to_hexadecimal +gdata_entry_get_type +gdata_entry_new +gdata_entry_get_title +gdata_entry_set_title +gdata_entry_get_summary +gdata_entry_set_summary +gdata_entry_get_id +gdata_entry_get_etag +gdata_entry_get_updated +gdata_entry_get_published +gdata_entry_add_category +gdata_entry_get_categories +gdata_entry_get_content +gdata_entry_set_content +gdata_entry_get_content_uri +gdata_entry_set_content_uri +gdata_entry_add_link +gdata_entry_remove_link +gdata_entry_look_up_link +gdata_entry_look_up_links +gdata_entry_add_author +gdata_entry_get_authors +gdata_entry_is_inserted +gdata_entry_get_rights +gdata_entry_set_rights +gdata_feed_get_type +gdata_feed_get_entries +gdata_feed_look_up_entry +gdata_feed_get_categories +gdata_feed_get_links +gdata_feed_look_up_link +gdata_feed_get_authors +gdata_feed_get_title +gdata_feed_get_subtitle +gdata_feed_get_id +gdata_feed_get_etag +gdata_feed_get_updated +gdata_feed_get_logo +gdata_feed_get_icon +gdata_feed_get_generator +gdata_feed_get_rights +gdata_feed_get_items_per_page +gdata_feed_get_start_index +gdata_feed_get_total_results +gdata_feed_get_next_page_token +gdata_service_get_type +gdata_service_error_quark +gdata_service_query +gdata_service_query_async +gdata_service_query_finish +gdata_service_query_single_entry +gdata_service_query_single_entry_async +gdata_service_query_single_entry_finish +gdata_service_insert_entry +gdata_service_insert_entry_async +gdata_service_insert_entry_finish +gdata_service_update_entry +gdata_service_update_entry_async +gdata_service_update_entry_finish +gdata_service_delete_entry +gdata_service_delete_entry_async +gdata_service_delete_entry_finish +gdata_service_get_proxy_uri +gdata_service_set_proxy_uri +gdata_service_get_proxy_resolver +gdata_service_set_proxy_resolver +gdata_query_get_type +gdata_query_new +gdata_query_new_with_limits +gdata_query_get_query_uri +gdata_query_next_page +gdata_query_previous_page +gdata_query_get_q +gdata_query_set_q +gdata_query_get_categories +gdata_query_set_categories +gdata_query_get_author +gdata_query_set_author +gdata_query_get_updated_min +gdata_query_set_updated_min +gdata_query_get_updated_max +gdata_query_set_updated_max +gdata_query_get_published_min +gdata_query_set_published_min +gdata_query_get_published_max +gdata_query_set_published_max +gdata_query_get_start_index +gdata_query_set_start_index +gdata_query_is_strict +gdata_query_set_is_strict +gdata_query_get_max_results +gdata_query_set_max_results +gdata_query_get_etag +gdata_query_set_etag +gdata_youtube_standard_feed_type_get_type +gdata_youtube_feed_get_type +gdata_youtube_service_error_get_type +gdata_youtube_service_error_quark +gdata_youtube_service_get_type +gdata_youtube_service_new +gdata_youtube_service_query_standard_feed +gdata_youtube_service_query_standard_feed_async +gdata_youtube_service_query_videos +gdata_youtube_service_query_videos_async +gdata_youtube_service_query_related +gdata_youtube_service_query_related_async +gdata_youtube_service_get_developer_key +gdata_youtube_video_get_type +gdata_youtube_video_new +gdata_youtube_video_get_view_count +gdata_youtube_video_get_favorite_count +gdata_youtube_video_get_location +gdata_youtube_video_set_location +gdata_youtube_video_get_access_control +gdata_youtube_video_set_access_control +gdata_youtube_video_get_rating +gdata_youtube_video_get_keywords +gdata_youtube_video_set_keywords +gdata_youtube_video_get_player_uri +gdata_youtube_video_is_restricted_in_country +gdata_youtube_video_get_category +gdata_youtube_video_set_category +gdata_youtube_video_get_credit +gdata_youtube_video_get_description +gdata_youtube_video_set_description +gdata_youtube_video_look_up_content +gdata_youtube_video_get_thumbnails +gdata_youtube_video_get_duration +gdata_youtube_video_is_private +gdata_youtube_video_set_is_private +gdata_youtube_video_get_uploaded +gdata_youtube_video_get_video_id +gdata_youtube_video_is_draft +gdata_youtube_video_set_is_draft +gdata_youtube_video_get_state +gdata_youtube_video_get_recorded +gdata_youtube_video_set_recorded +gdata_youtube_video_get_video_id_from_uri +gdata_youtube_video_get_aspect_ratio +gdata_youtube_video_set_aspect_ratio +gdata_youtube_format_get_type +gdata_youtube_safe_search_get_type +gdata_youtube_sort_order_get_type +gdata_youtube_age_get_type +gdata_youtube_uploader_get_type +gdata_youtube_query_get_type +gdata_youtube_query_new +gdata_youtube_query_get_format +gdata_youtube_query_set_format +gdata_youtube_query_get_location +gdata_youtube_query_set_location +gdata_youtube_query_get_language +gdata_youtube_query_set_language +gdata_youtube_query_get_order_by +gdata_youtube_query_set_order_by +gdata_youtube_query_get_restriction +gdata_youtube_query_set_restriction +gdata_youtube_query_get_safe_search +gdata_youtube_query_set_safe_search +gdata_youtube_query_get_sort_order +gdata_youtube_query_set_sort_order +gdata_youtube_query_get_age +gdata_youtube_query_set_age +gdata_youtube_query_get_uploader +gdata_youtube_query_set_uploader +gdata_calendar_calendar_get_type +gdata_calendar_calendar_new +gdata_calendar_calendar_get_timezone +gdata_calendar_calendar_set_timezone +gdata_calendar_calendar_get_times_cleaned +gdata_calendar_calendar_is_hidden +gdata_calendar_calendar_set_is_hidden +gdata_calendar_calendar_get_color +gdata_calendar_calendar_set_color +gdata_calendar_calendar_is_selected +gdata_calendar_calendar_set_is_selected +gdata_calendar_calendar_get_access_level +gdata_calendar_calendar_get_edited +gdata_calendar_event_get_type +gdata_calendar_event_new +gdata_calendar_event_get_edited +gdata_calendar_event_get_status +gdata_calendar_event_set_status +gdata_calendar_event_get_visibility +gdata_calendar_event_set_visibility +gdata_calendar_event_get_transparency +gdata_calendar_event_set_transparency +gdata_calendar_event_get_uid +gdata_calendar_event_set_uid +gdata_calendar_event_get_sequence +gdata_calendar_event_set_sequence +gdata_calendar_event_get_guests_can_modify +gdata_calendar_event_set_guests_can_modify +gdata_calendar_event_get_guests_can_invite_others +gdata_calendar_event_set_guests_can_invite_others +gdata_calendar_event_get_guests_can_see_guests +gdata_calendar_event_set_guests_can_see_guests +gdata_calendar_event_get_anyone_can_add_self +gdata_calendar_event_set_anyone_can_add_self +gdata_calendar_event_add_person +gdata_calendar_event_get_people +gdata_calendar_event_add_place +gdata_calendar_event_get_places +gdata_calendar_event_add_time +gdata_calendar_event_get_times +gdata_calendar_event_get_primary_time +gdata_calendar_event_get_recurrence +gdata_calendar_event_set_recurrence +gdata_calendar_event_get_original_event_details +gdata_calendar_event_is_exception +gdata_calendar_query_get_type +gdata_calendar_query_new +gdata_calendar_query_new_with_limits +gdata_calendar_query_get_future_events +gdata_calendar_query_set_future_events +gdata_calendar_query_get_order_by +gdata_calendar_query_set_order_by +gdata_calendar_query_get_recurrence_expansion_start +gdata_calendar_query_set_recurrence_expansion_start +gdata_calendar_query_get_recurrence_expansion_end +gdata_calendar_query_set_recurrence_expansion_end +gdata_calendar_query_get_single_events +gdata_calendar_query_set_single_events +gdata_calendar_query_get_sort_order +gdata_calendar_query_set_sort_order +gdata_calendar_query_get_start_min +gdata_calendar_query_set_start_min +gdata_calendar_query_get_start_max +gdata_calendar_query_set_start_max +gdata_calendar_query_get_timezone +gdata_calendar_query_set_timezone +gdata_calendar_service_get_type +gdata_calendar_service_new +gdata_calendar_service_query_all_calendars +gdata_calendar_service_query_all_calendars_async +gdata_calendar_service_query_own_calendars +gdata_calendar_service_query_own_calendars_async +gdata_calendar_service_query_events +gdata_calendar_service_insert_event +gdata_calendar_service_insert_calendar_event +gdata_operation_type_get_type +gdata_service_error_get_type +gdata_media_expression_get_type +gdata_media_medium_get_type +gdata_parser_error_get_type +gdata_parser_error_quark +gdata_contacts_service_get_type +gdata_contacts_service_new +gdata_contacts_service_query_contacts +gdata_contacts_service_query_contacts_async +gdata_contacts_service_insert_contact +gdata_contacts_service_insert_contact_async +gdata_contacts_query_get_type +gdata_contacts_query_new +gdata_contacts_query_new_with_limits +gdata_contacts_query_get_order_by +gdata_contacts_query_set_order_by +gdata_contacts_query_show_deleted +gdata_contacts_query_set_show_deleted +gdata_contacts_query_get_sort_order +gdata_contacts_query_set_sort_order +gdata_contacts_query_get_group +gdata_contacts_query_set_group +gdata_contacts_contact_get_type +gdata_contacts_contact_new +gdata_contacts_contact_get_edited +gdata_contacts_contact_get_name +gdata_contacts_contact_set_name +gdata_contacts_contact_add_email_address +gdata_contacts_contact_get_email_addresses +gdata_contacts_contact_get_primary_email_address +gdata_contacts_contact_remove_all_email_addresses +gdata_contacts_contact_add_im_address +gdata_contacts_contact_get_im_addresses +gdata_contacts_contact_get_primary_im_address +gdata_contacts_contact_remove_all_im_addresses +gdata_contacts_contact_add_phone_number +gdata_contacts_contact_get_phone_numbers +gdata_contacts_contact_get_primary_phone_number +gdata_contacts_contact_remove_all_phone_numbers +gdata_contacts_contact_add_postal_address +gdata_contacts_contact_get_postal_addresses +gdata_contacts_contact_get_primary_postal_address +gdata_contacts_contact_remove_all_postal_addresses +gdata_contacts_contact_add_organization +gdata_contacts_contact_get_organizations +gdata_contacts_contact_get_primary_organization +gdata_contacts_contact_remove_all_organizations +gdata_contacts_contact_get_extended_property +gdata_contacts_contact_get_extended_properties +gdata_contacts_contact_set_extended_property +gdata_contacts_contact_add_group +gdata_contacts_contact_remove_group +gdata_contacts_contact_is_group_deleted +gdata_contacts_contact_get_groups +gdata_contacts_contact_is_deleted +gdata_contacts_contact_get_photo_etag +gdata_contacts_contact_get_photo +gdata_contacts_contact_set_photo +gdata_access_handler_get_type +gdata_access_handler_get_rules +gdata_access_handler_get_rules_async +gdata_access_rule_get_type +gdata_access_rule_new +gdata_access_rule_get_role +gdata_access_rule_set_role +gdata_access_rule_get_scope +gdata_access_rule_set_scope +gdata_access_rule_get_edited +gdata_access_rule_get_key +gdata_parsable_get_type +gdata_parsable_get_content_type +gdata_parsable_new_from_xml +gdata_parsable_get_xml +gdata_parsable_new_from_json +gdata_parsable_get_json +gdata_calendar_feed_get_type +gdata_calendar_feed_get_timezone +gdata_calendar_feed_get_times_cleaned +gdata_category_get_type +gdata_category_new +gdata_category_get_term +gdata_category_set_term +gdata_category_get_scheme +gdata_category_set_scheme +gdata_category_get_label +gdata_category_set_label +gdata_link_get_type +gdata_link_new +gdata_link_get_uri +gdata_link_set_uri +gdata_link_get_relation_type +gdata_link_set_relation_type +gdata_link_get_content_type +gdata_link_set_content_type +gdata_link_get_language +gdata_link_set_language +gdata_link_get_title +gdata_link_set_title +gdata_link_get_length +gdata_link_set_length +gdata_author_get_type +gdata_author_new +gdata_author_get_name +gdata_author_set_name +gdata_author_get_uri +gdata_author_set_uri +gdata_author_get_email_address +gdata_author_set_email_address +gdata_generator_get_type +gdata_generator_get_name +gdata_generator_get_uri +gdata_generator_get_version +gdata_gd_organization_get_type +gdata_gd_organization_new +gdata_gd_organization_get_name +gdata_gd_organization_set_name +gdata_gd_organization_get_title +gdata_gd_organization_set_title +gdata_gd_organization_get_relation_type +gdata_gd_organization_set_relation_type +gdata_gd_organization_get_label +gdata_gd_organization_set_label +gdata_gd_organization_is_primary +gdata_gd_organization_set_is_primary +gdata_gd_organization_get_department +gdata_gd_organization_set_department +gdata_gd_organization_get_job_description +gdata_gd_organization_set_job_description +gdata_gd_organization_get_symbol +gdata_gd_organization_set_symbol +gdata_gd_organization_get_location +gdata_gd_organization_set_location +gdata_gd_when_get_type +gdata_gd_when_new +gdata_gd_when_get_start_time +gdata_gd_when_set_start_time +gdata_gd_when_get_end_time +gdata_gd_when_set_end_time +gdata_gd_when_is_date +gdata_gd_when_set_is_date +gdata_gd_when_get_value_string +gdata_gd_when_set_value_string +gdata_gd_when_get_reminders +gdata_gd_when_add_reminder +gdata_gd_who_get_type +gdata_gd_who_new +gdata_gd_who_get_relation_type +gdata_gd_who_set_relation_type +gdata_gd_who_get_value_string +gdata_gd_who_set_value_string +gdata_gd_who_get_email_address +gdata_gd_who_set_email_address +gdata_gd_where_get_type +gdata_gd_where_new +gdata_gd_where_get_relation_type +gdata_gd_where_set_relation_type +gdata_gd_where_get_value_string +gdata_gd_where_set_value_string +gdata_gd_where_get_label +gdata_gd_where_set_label +gdata_gd_email_address_get_type +gdata_gd_email_address_new +gdata_gd_email_address_get_address +gdata_gd_email_address_set_address +gdata_gd_email_address_get_relation_type +gdata_gd_email_address_set_relation_type +gdata_gd_email_address_get_label +gdata_gd_email_address_set_label +gdata_gd_email_address_is_primary +gdata_gd_email_address_set_is_primary +gdata_gd_email_address_get_display_name +gdata_gd_email_address_set_display_name +gdata_gd_im_address_get_type +gdata_gd_im_address_new +gdata_gd_im_address_get_address +gdata_gd_im_address_set_address +gdata_gd_im_address_get_protocol +gdata_gd_im_address_set_protocol +gdata_gd_im_address_get_relation_type +gdata_gd_im_address_set_relation_type +gdata_gd_im_address_get_label +gdata_gd_im_address_set_label +gdata_gd_im_address_is_primary +gdata_gd_im_address_set_is_primary +gdata_gd_postal_address_get_type +gdata_gd_postal_address_new +gdata_gd_postal_address_get_address +gdata_gd_postal_address_set_address +gdata_gd_postal_address_get_relation_type +gdata_gd_postal_address_set_relation_type +gdata_gd_postal_address_get_label +gdata_gd_postal_address_set_label +gdata_gd_postal_address_is_primary +gdata_gd_postal_address_set_is_primary +gdata_gd_postal_address_get_mail_class +gdata_gd_postal_address_set_mail_class +gdata_gd_postal_address_get_usage +gdata_gd_postal_address_set_usage +gdata_gd_postal_address_get_agent +gdata_gd_postal_address_set_agent +gdata_gd_postal_address_get_house_name +gdata_gd_postal_address_set_house_name +gdata_gd_postal_address_get_street +gdata_gd_postal_address_set_street +gdata_gd_postal_address_get_po_box +gdata_gd_postal_address_set_po_box +gdata_gd_postal_address_get_neighborhood +gdata_gd_postal_address_set_neighborhood +gdata_gd_postal_address_get_city +gdata_gd_postal_address_set_city +gdata_gd_postal_address_get_subregion +gdata_gd_postal_address_set_subregion +gdata_gd_postal_address_get_region +gdata_gd_postal_address_set_region +gdata_gd_postal_address_get_postcode +gdata_gd_postal_address_set_postcode +gdata_gd_postal_address_get_country +gdata_gd_postal_address_get_country_code +gdata_gd_postal_address_set_country +gdata_gd_phone_number_get_type +gdata_gd_phone_number_new +gdata_gd_phone_number_get_number +gdata_gd_phone_number_set_number +gdata_gd_phone_number_get_uri +gdata_gd_phone_number_set_uri +gdata_gd_phone_number_get_relation_type +gdata_gd_phone_number_set_relation_type +gdata_gd_phone_number_get_label +gdata_gd_phone_number_set_label +gdata_gd_phone_number_is_primary +gdata_gd_phone_number_set_is_primary +gdata_gd_reminder_get_type +gdata_gd_reminder_new +gdata_gd_reminder_get_method +gdata_gd_reminder_set_method +gdata_gd_reminder_get_absolute_time +gdata_gd_reminder_set_absolute_time +gdata_gd_reminder_is_absolute_time +gdata_gd_reminder_get_relative_time +gdata_gd_reminder_set_relative_time +gdata_media_category_get_type +gdata_media_category_new +gdata_media_category_get_category +gdata_media_category_set_category +gdata_media_category_get_scheme +gdata_media_category_set_scheme +gdata_media_category_get_label +gdata_media_category_set_label +gdata_media_credit_get_type +gdata_media_credit_get_credit +gdata_media_credit_get_scheme +gdata_media_credit_get_role +gdata_youtube_credit_get_type +gdata_youtube_credit_get_entity_type +gdata_media_content_get_type +gdata_media_content_get_uri +gdata_media_content_get_filesize +gdata_media_content_get_content_type +gdata_media_content_get_medium +gdata_media_content_is_default +gdata_media_content_get_expression +gdata_media_content_get_duration +gdata_media_content_get_height +gdata_media_content_get_width +gdata_media_content_download +gdata_youtube_content_get_type +gdata_youtube_content_get_format +gdata_media_thumbnail_get_type +gdata_media_thumbnail_get_uri +gdata_media_thumbnail_get_height +gdata_media_thumbnail_get_width +gdata_media_thumbnail_get_time +gdata_media_thumbnail_download +gdata_youtube_state_get_type +gdata_youtube_state_get_name +gdata_youtube_state_get_reason_code +gdata_youtube_state_get_help_uri +gdata_youtube_state_get_message +gdata_picasaweb_album_get_type +gdata_picasaweb_album_new +gdata_picasaweb_album_get_id +gdata_picasaweb_album_get_user +gdata_picasaweb_album_get_nickname +gdata_picasaweb_album_get_edited +gdata_picasaweb_album_get_location +gdata_picasaweb_album_set_location +gdata_picasaweb_album_get_visibility +gdata_picasaweb_album_set_visibility +gdata_picasaweb_album_get_timestamp +gdata_picasaweb_album_set_timestamp +gdata_picasaweb_album_get_num_photos +gdata_picasaweb_album_get_num_photos_remaining +gdata_picasaweb_album_get_bytes_used +gdata_picasaweb_album_is_commenting_enabled +gdata_picasaweb_album_set_is_commenting_enabled +gdata_picasaweb_album_get_comment_count +gdata_picasaweb_album_get_tags +gdata_picasaweb_album_set_tags +gdata_picasaweb_album_get_contents +gdata_picasaweb_album_get_thumbnails +gdata_picasaweb_album_get_coordinates +gdata_picasaweb_album_set_coordinates +gdata_picasaweb_file_get_type +gdata_picasaweb_file_new +gdata_picasaweb_file_get_id +gdata_picasaweb_file_get_edited +gdata_picasaweb_file_get_version +gdata_picasaweb_file_get_album_id +gdata_picasaweb_file_set_album_id +gdata_picasaweb_file_get_width +gdata_picasaweb_file_get_height +gdata_picasaweb_file_get_size +gdata_picasaweb_file_get_checksum +gdata_picasaweb_file_set_checksum +gdata_picasaweb_file_get_timestamp +gdata_picasaweb_file_set_timestamp +gdata_picasaweb_file_is_commenting_enabled +gdata_picasaweb_file_set_is_commenting_enabled +gdata_picasaweb_file_get_comment_count +gdata_picasaweb_file_get_rotation +gdata_picasaweb_file_set_rotation +gdata_picasaweb_file_get_video_status +gdata_picasaweb_file_get_tags +gdata_picasaweb_file_set_tags +gdata_picasaweb_file_get_credit +gdata_picasaweb_file_get_caption +gdata_picasaweb_file_set_caption +gdata_picasaweb_file_get_contents +gdata_picasaweb_file_get_thumbnails +gdata_picasaweb_file_get_distance +gdata_picasaweb_file_get_exposure +gdata_picasaweb_file_get_flash +gdata_picasaweb_file_get_focal_length +gdata_picasaweb_file_get_fstop +gdata_picasaweb_file_get_image_unique_id +gdata_picasaweb_file_get_iso +gdata_picasaweb_file_get_make +gdata_picasaweb_file_get_model +gdata_picasaweb_file_get_coordinates +gdata_picasaweb_file_set_coordinates +gdata_picasaweb_service_get_type +gdata_picasaweb_service_new +gdata_picasaweb_service_get_user +gdata_picasaweb_service_query_all_albums +gdata_picasaweb_service_query_all_albums_async +gdata_picasaweb_service_query_files +gdata_picasaweb_service_insert_album +gdata_picasaweb_feed_get_type +gdata_picasaweb_user_get_type +gdata_picasaweb_user_get_user +gdata_picasaweb_user_get_nickname +gdata_picasaweb_user_get_quota_limit +gdata_picasaweb_user_get_quota_current +gdata_picasaweb_user_get_max_photos_per_album +gdata_picasaweb_user_get_thumbnail_uri +gdata_picasaweb_query_get_type +gdata_picasaweb_query_new +gdata_picasaweb_query_new_with_limits +gdata_picasaweb_query_get_visibility +gdata_picasaweb_query_set_visibility +gdata_picasaweb_query_get_thumbnail_size +gdata_picasaweb_query_set_thumbnail_size +gdata_picasaweb_query_get_image_size +gdata_picasaweb_query_set_image_size +gdata_picasaweb_query_get_tag +gdata_picasaweb_query_set_tag +gdata_picasaweb_query_get_bounding_box +gdata_picasaweb_query_set_bounding_box +gdata_picasaweb_query_get_location +gdata_picasaweb_query_set_location +gdata_picasaweb_visibility_get_type +gdata_documents_presentation_get_type +gdata_documents_presentation_new +gdata_documents_drawing_get_type +gdata_documents_drawing_new +gdata_documents_pdf_get_type +gdata_documents_pdf_new +gdata_documents_text_get_type +gdata_documents_text_new +gdata_documents_spreadsheet_get_type +gdata_documents_spreadsheet_new +gdata_documents_spreadsheet_get_download_uri +gdata_documents_folder_get_type +gdata_documents_folder_new +gdata_documents_service_get_type +gdata_documents_service_new +gdata_documents_service_get_metadata +gdata_documents_service_get_metadata_async +gdata_documents_service_get_metadata_finish +gdata_documents_service_query_documents +gdata_documents_service_query_documents_async +gdata_documents_service_upload_document +gdata_documents_service_update_document +gdata_documents_service_get_upload_uri +gdata_documents_metadata_get_type +gdata_documents_metadata_get_quota_total +gdata_documents_metadata_get_quota_used +gdata_documents_feed_get_type +gdata_documents_entry_get_type +gdata_documents_entry_get_path +gdata_documents_entry_get_document_id +gdata_documents_entry_get_edited +gdata_documents_entry_get_last_viewed +gdata_documents_entry_set_writers_can_invite +gdata_documents_entry_writers_can_invite +gdata_documents_entry_get_last_modified_by +gdata_documents_entry_is_deleted +gdata_documents_query_get_type +gdata_documents_query_new +gdata_documents_query_new_with_limits +gdata_documents_query_show_deleted +gdata_documents_query_set_show_deleted +gdata_documents_query_show_folders +gdata_documents_query_set_show_folders +gdata_documents_query_get_folder_id +gdata_documents_query_set_folder_id +gdata_documents_query_get_title +gdata_documents_query_get_exact_title +gdata_documents_query_set_title +gdata_documents_query_get_collaborator_addresses +gdata_documents_query_get_reader_addresses +gdata_documents_query_add_reader +gdata_documents_query_add_collaborator +gdata_documents_service_error_get_type +gdata_documents_service_error_quark +gdata_documents_access_rule_get_type +gdata_documents_access_rule_new +gdata_download_stream_get_type +gdata_download_stream_new +gdata_download_stream_get_service +gdata_download_stream_get_download_uri +gdata_download_stream_get_content_type +gdata_download_stream_get_content_length +gdata_upload_stream_get_type +gdata_upload_stream_new +gdata_upload_stream_get_service +gdata_upload_stream_get_upload_uri +gdata_upload_stream_get_entry +gdata_upload_stream_get_slug +gdata_upload_stream_get_content_type +gdata_gd_name_get_type +gdata_gd_name_new +gdata_gd_name_get_given_name +gdata_gd_name_set_given_name +gdata_gd_name_get_additional_name +gdata_gd_name_set_additional_name +gdata_gd_name_get_family_name +gdata_gd_name_set_family_name +gdata_gd_name_get_prefix +gdata_gd_name_set_prefix +gdata_gd_name_get_suffix +gdata_gd_name_set_suffix +gdata_gd_name_get_full_name +gdata_gd_name_set_full_name +gdata_youtube_permission_get_type +gdata_gcontact_jot_get_type +gdata_gcontact_jot_new +gdata_gcontact_jot_get_content +gdata_gcontact_jot_set_content +gdata_gcontact_jot_get_relation_type +gdata_gcontact_jot_set_relation_type +gdata_contacts_contact_add_jot +gdata_contacts_contact_get_jots +gdata_contacts_contact_remove_all_jots +gdata_contacts_contact_get_nickname +gdata_contacts_contact_set_nickname +gdata_contacts_contact_get_birthday +gdata_contacts_contact_set_birthday +gdata_gcontact_relation_get_type +gdata_gcontact_relation_new +gdata_gcontact_relation_get_name +gdata_gcontact_relation_set_name +gdata_gcontact_relation_get_relation_type +gdata_gcontact_relation_set_relation_type +gdata_gcontact_relation_get_label +gdata_gcontact_relation_set_label +gdata_contacts_contact_add_relation +gdata_contacts_contact_get_relations +gdata_contacts_contact_remove_all_relations +gdata_gcontact_website_get_type +gdata_gcontact_website_new +gdata_gcontact_website_get_uri +gdata_gcontact_website_set_uri +gdata_gcontact_website_get_relation_type +gdata_gcontact_website_set_relation_type +gdata_gcontact_website_get_label +gdata_gcontact_website_set_label +gdata_gcontact_website_is_primary +gdata_gcontact_website_set_is_primary +gdata_contacts_contact_add_website +gdata_contacts_contact_get_websites +gdata_contacts_contact_get_primary_website +gdata_contacts_contact_remove_all_websites +gdata_gcontact_event_get_type +gdata_gcontact_event_new +gdata_gcontact_event_get_date +gdata_gcontact_event_set_date +gdata_gcontact_event_get_relation_type +gdata_gcontact_event_set_relation_type +gdata_gcontact_event_get_label +gdata_gcontact_event_set_label +gdata_contacts_contact_add_event +gdata_contacts_contact_get_events +gdata_contacts_contact_remove_all_events +gdata_gcontact_calendar_get_type +gdata_gcontact_calendar_new +gdata_gcontact_calendar_get_uri +gdata_gcontact_calendar_set_uri +gdata_gcontact_calendar_get_relation_type +gdata_gcontact_calendar_set_relation_type +gdata_gcontact_calendar_get_label +gdata_gcontact_calendar_set_label +gdata_gcontact_calendar_is_primary +gdata_gcontact_calendar_set_is_primary +gdata_contacts_contact_add_calendar +gdata_contacts_contact_get_calendars +gdata_contacts_contact_get_primary_calendar +gdata_contacts_contact_remove_all_calendars +gdata_contacts_contact_get_directory_server +gdata_contacts_contact_set_directory_server +gdata_contacts_contact_get_gender +gdata_contacts_contact_set_gender +gdata_contacts_contact_get_initials +gdata_contacts_contact_set_initials +gdata_contacts_contact_get_maiden_name +gdata_contacts_contact_set_maiden_name +gdata_contacts_contact_get_mileage +gdata_contacts_contact_set_mileage +gdata_contacts_contact_get_occupation +gdata_contacts_contact_set_occupation +gdata_contacts_contact_get_priority +gdata_contacts_contact_set_priority +gdata_contacts_contact_get_sensitivity +gdata_contacts_contact_set_sensitivity +gdata_contacts_contact_get_short_name +gdata_contacts_contact_set_short_name +gdata_contacts_contact_get_subject +gdata_contacts_contact_set_subject +gdata_contacts_contact_get_billing_information +gdata_contacts_contact_set_billing_information +gdata_contacts_contact_get_user_defined_field +gdata_contacts_contact_get_user_defined_fields +gdata_contacts_contact_set_user_defined_field +gdata_gcontact_external_id_get_type +gdata_gcontact_external_id_new +gdata_gcontact_external_id_get_value +gdata_gcontact_external_id_set_value +gdata_gcontact_external_id_get_relation_type +gdata_gcontact_external_id_set_relation_type +gdata_gcontact_external_id_get_label +gdata_gcontact_external_id_set_label +gdata_contacts_contact_add_external_id +gdata_contacts_contact_get_external_ids +gdata_contacts_contact_remove_all_external_ids +gdata_contacts_contact_add_hobby +gdata_contacts_contact_get_hobbies +gdata_contacts_contact_remove_all_hobbies +gdata_gcontact_language_get_type +gdata_gcontact_language_new +gdata_gcontact_language_get_code +gdata_gcontact_language_set_code +gdata_gcontact_language_get_label +gdata_gcontact_language_set_label +gdata_contacts_contact_add_language +gdata_contacts_contact_get_languages +gdata_contacts_contact_remove_all_languages +gdata_service_get_timeout +gdata_service_set_timeout +gdata_service_get_locale +gdata_service_set_locale +gdata_youtube_service_get_categories +gdata_youtube_service_get_categories_async +gdata_youtube_service_get_categories_finish +gdata_youtube_category_get_type +gdata_youtube_category_is_assignable +gdata_youtube_category_is_browsable +gdata_youtube_category_is_deprecated +gdata_app_categories_get_type +gdata_app_categories_get_categories +gdata_app_categories_is_fixed +gdata_comparable_get_type +gdata_comparable_compare +gdata_batch_operation_get_type +gdata_batch_operation_get_service +gdata_batch_operation_get_feed_uri +gdata_batch_operation_add_query +gdata_batch_operation_add_insertion +gdata_batch_operation_add_update +gdata_batch_operation_add_deletion +gdata_batch_operation_run +gdata_batch_operation_run_async +gdata_batch_operation_run_finish +gdata_batch_operation_type_get_type +gdata_batchable_get_type +gdata_batchable_create_operation +gdata_upload_stream_get_method +gdata_documents_document_get_type +gdata_documents_document_download +gdata_documents_document_get_download_uri +gdata_contacts_group_get_type +gdata_contacts_group_new +gdata_contacts_group_get_edited +gdata_contacts_group_is_deleted +gdata_contacts_group_get_system_group_id +gdata_contacts_group_get_extended_property +gdata_contacts_group_get_extended_properties +gdata_contacts_group_set_extended_property +gdata_contacts_service_query_groups +gdata_contacts_service_query_groups_async +gdata_contacts_service_insert_group +gdata_contacts_service_insert_group_async +gdata_picasaweb_service_insert_album_async +gdata_picasaweb_service_query_files_async +gdata_documents_service_finish_upload +gdata_documents_service_add_entry_to_folder +gdata_documents_service_remove_entry_from_folder +gdata_documents_service_add_entry_to_folder_async +gdata_documents_service_add_entry_to_folder_finish +gdata_documents_service_remove_entry_from_folder_async +gdata_documents_service_remove_entry_from_folder_finish +gdata_picasaweb_service_upload_file +gdata_picasaweb_service_finish_file_upload +gdata_youtube_service_upload_video +gdata_youtube_service_finish_video_upload +gdata_calendar_service_query_events_async +gdata_calendar_service_insert_event_async +gdata_calendar_service_insert_calendar_event_async +gdata_contacts_contact_get_photo_async +gdata_contacts_contact_get_photo_finish +gdata_contacts_contact_set_photo_async +gdata_contacts_contact_set_photo_finish +gdata_youtube_video_get_coordinates +gdata_youtube_video_set_coordinates +gdata_upload_stream_get_cancellable +gdata_download_stream_get_cancellable +gdata_service_is_authorized +gdata_service_get_authorizer +gdata_service_set_authorizer +gdata_authorizer_get_type +gdata_authorizer_process_request +gdata_authorizer_is_authorized_for_domain +gdata_authorizer_refresh_authorization +gdata_authorizer_refresh_authorization_async +gdata_authorizer_refresh_authorization_finish +gdata_authorization_domain_get_type +gdata_authorization_domain_get_service_name +gdata_authorization_domain_get_scope +gdata_client_login_authorizer_get_type +gdata_client_login_authorizer_new +gdata_client_login_authorizer_new_for_authorization_domains +gdata_client_login_authorizer_authenticate +gdata_client_login_authorizer_authenticate_async +gdata_client_login_authorizer_authenticate_finish +gdata_client_login_authorizer_get_client_id +gdata_client_login_authorizer_get_username +gdata_client_login_authorizer_get_password +gdata_client_login_authorizer_get_proxy_uri +gdata_client_login_authorizer_set_proxy_uri +gdata_client_login_authorizer_get_proxy_resolver +gdata_client_login_authorizer_set_proxy_resolver +gdata_client_login_authorizer_get_timeout +gdata_client_login_authorizer_set_timeout +gdata_client_login_authorizer_error_quark +gdata_client_login_authorizer_error_get_type +gdata_download_stream_get_authorization_domain +gdata_upload_stream_get_authorization_domain +gdata_batch_operation_get_authorization_domain +gdata_contacts_service_get_primary_authorization_domain +gdata_calendar_service_get_primary_authorization_domain +gdata_documents_service_get_primary_authorization_domain +gdata_documents_service_get_spreadsheet_authorization_domain +gdata_picasaweb_service_get_primary_authorization_domain +gdata_youtube_service_get_primary_authorization_domain +gdata_service_get_authorization_domains +gdata_oauth1_authorizer_get_type +gdata_oauth1_authorizer_new +gdata_oauth1_authorizer_new_for_authorization_domains +gdata_oauth1_authorizer_request_authentication_uri +gdata_oauth1_authorizer_request_authentication_uri_async +gdata_oauth1_authorizer_request_authentication_uri_finish +gdata_oauth1_authorizer_request_authorization +gdata_oauth1_authorizer_request_authorization_async +gdata_oauth1_authorizer_request_authorization_finish +gdata_oauth1_authorizer_get_application_name +gdata_oauth1_authorizer_get_locale +gdata_oauth1_authorizer_set_locale +gdata_oauth1_authorizer_get_proxy_uri +gdata_oauth1_authorizer_set_proxy_uri +gdata_oauth1_authorizer_get_proxy_resolver +gdata_oauth1_authorizer_set_proxy_resolver +gdata_oauth1_authorizer_get_timeout +gdata_oauth1_authorizer_set_timeout +gdata_calendar_query_get_max_attendees +gdata_calendar_query_set_max_attendees +gdata_calendar_query_show_deleted +gdata_calendar_query_set_show_deleted +gdata_picasaweb_service_get_user_async +gdata_picasaweb_service_get_user_finish +gdata_commentable_get_type +gdata_commentable_query_comments +gdata_commentable_query_comments_async +gdata_commentable_query_comments_finish +gdata_commentable_insert_comment +gdata_commentable_insert_comment_async +gdata_commentable_insert_comment_finish +gdata_commentable_delete_comment +gdata_commentable_delete_comment_async +gdata_commentable_delete_comment_finish +gdata_comment_get_type +gdata_youtube_comment_get_type +gdata_youtube_comment_new +gdata_youtube_comment_get_parent_comment_uri +gdata_youtube_comment_set_parent_comment_uri +gdata_picasaweb_comment_get_type +gdata_picasaweb_comment_new +gdata_youtube_video_get_media_rating +gdata_documents_entry_get_resource_id +gdata_youtube_query_get_license +gdata_youtube_query_set_license +gdata_contacts_contact_get_file_as +gdata_contacts_contact_set_file_as +gdata_upload_stream_new_resumable +gdata_upload_stream_get_content_length +gdata_documents_service_upload_document_resumable +gdata_documents_service_update_document_resumable +gdata_documents_upload_query_get_type +gdata_documents_upload_query_new +gdata_documents_upload_query_build_uri +gdata_documents_upload_query_get_folder +gdata_documents_upload_query_set_folder +gdata_documents_document_new +gdata_documents_upload_query_get_convert +gdata_documents_upload_query_set_convert +gdata_documents_entry_get_quota_used +gdata_documents_entry_get_file_size +gdata_documents_service_copy_document +gdata_documents_service_copy_document_async +gdata_documents_service_copy_document_finish +gdata_documents_document_get_thumbnail_uri +gdata_tasks_task_get_type +gdata_tasks_task_new +gdata_tasks_task_get_parent +gdata_tasks_task_set_parent +gdata_tasks_task_get_position +gdata_tasks_task_set_position +gdata_tasks_task_get_notes +gdata_tasks_task_set_notes +gdata_tasks_task_get_status +gdata_tasks_task_set_status +gdata_tasks_task_get_due +gdata_tasks_task_set_due +gdata_tasks_task_get_completed +gdata_tasks_task_set_completed +gdata_tasks_task_is_deleted +gdata_tasks_task_set_is_deleted +gdata_tasks_task_is_hidden +gdata_tasks_tasklist_get_type +gdata_tasks_tasklist_new +gdata_tasks_query_get_type +gdata_tasks_query_new +gdata_tasks_query_get_completed_max +gdata_tasks_query_set_completed_max +gdata_tasks_query_get_completed_min +gdata_tasks_query_set_completed_min +gdata_tasks_query_get_due_max +gdata_tasks_query_set_due_max +gdata_tasks_query_get_due_min +gdata_tasks_query_set_due_min +gdata_tasks_query_get_show_completed +gdata_tasks_query_set_show_completed +gdata_tasks_query_get_show_deleted +gdata_tasks_query_set_show_deleted +gdata_tasks_query_get_show_hidden +gdata_tasks_query_set_show_hidden +gdata_tasks_service_get_type +gdata_tasks_service_new +gdata_tasks_service_get_primary_authorization_domain +gdata_tasks_service_query_all_tasklists +gdata_tasks_service_query_all_tasklists_async +gdata_tasks_service_query_tasks +gdata_tasks_service_query_tasks_async +gdata_tasks_service_insert_task +gdata_tasks_service_insert_task_async +gdata_tasks_service_insert_tasklist +gdata_tasks_service_insert_tasklist_async +gdata_tasks_service_delete_task +gdata_tasks_service_delete_task_async +gdata_tasks_service_delete_tasklist +gdata_tasks_service_delete_tasklist_async +gdata_tasks_service_update_task +gdata_tasks_service_update_task_async +gdata_tasks_service_update_tasklist +gdata_tasks_service_update_tasklist_async +gdata_freebase_service_get_type +gdata_freebase_service_new +gdata_freebase_service_query +gdata_freebase_service_query_async +gdata_freebase_service_get_topic +gdata_freebase_service_get_topic_async +gdata_freebase_service_search +gdata_freebase_service_search_async +gdata_freebase_service_get_image +gdata_freebase_query_get_type +gdata_freebase_query_new +gdata_freebase_query_new_from_variant +gdata_freebase_search_filter_type_get_type +gdata_freebase_search_query_get_type +gdata_freebase_search_query_new +gdata_freebase_search_query_open_filter +gdata_freebase_search_query_close_filter +gdata_freebase_search_query_add_filter +gdata_freebase_search_query_add_location +gdata_freebase_search_query_set_language +gdata_freebase_search_query_get_language +gdata_freebase_search_query_set_stemmed +gdata_freebase_search_query_get_stemmed +gdata_freebase_search_result_get_type +gdata_freebase_search_result_new +gdata_freebase_search_result_get_num_items +gdata_freebase_search_result_get_total_hits +gdata_freebase_search_result_get_item +gdata_freebase_search_result_item_get_type +gdata_freebase_search_result_item_get_mid +gdata_freebase_search_result_item_get_id +gdata_freebase_search_result_item_get_name +gdata_freebase_search_result_item_get_language +gdata_freebase_search_result_item_get_notable_name +gdata_freebase_search_result_item_get_notable_id +gdata_freebase_search_result_item_get_score +gdata_freebase_topic_query_get_type +gdata_freebase_topic_query_new +gdata_freebase_topic_query_set_filter +gdata_freebase_topic_query_get_filter +gdata_freebase_topic_query_set_language +gdata_freebase_topic_query_get_language +gdata_freebase_topic_object_get_type +gdata_freebase_topic_object_ref +gdata_freebase_topic_object_unref +gdata_freebase_topic_object_list_properties +gdata_freebase_topic_object_get_id +gdata_freebase_topic_object_get_property_count +gdata_freebase_topic_object_get_property_hits +gdata_freebase_topic_object_get_property_value +gdata_freebase_topic_value_get_type +gdata_freebase_topic_value_ref +gdata_freebase_topic_value_unref +gdata_freebase_topic_value_get_property +gdata_freebase_topic_value_get_text +gdata_freebase_topic_value_get_language +gdata_freebase_topic_value_get_creator +gdata_freebase_topic_value_get_timestamp +gdata_freebase_topic_value_get_value_type +gdata_freebase_topic_value_copy_value +gdata_freebase_topic_value_get_int +gdata_freebase_topic_value_get_double +gdata_freebase_topic_value_get_string +gdata_freebase_topic_value_get_object +gdata_freebase_topic_value_is_image +gdata_freebase_topic_result_get_type +gdata_freebase_topic_result_new +gdata_freebase_topic_result_dup_object +gdata_freebase_result_get_type +gdata_freebase_result_new +gdata_freebase_result_dup_variant +gdata_oauth2_authorizer_get_type +gdata_oauth2_authorizer_new +gdata_oauth2_authorizer_new_for_authorization_domains +gdata_oauth2_authorizer_build_authentication_uri +gdata_oauth2_authorizer_request_authorization +gdata_oauth2_authorizer_request_authorization_async +gdata_oauth2_authorizer_request_authorization_finish +gdata_oauth2_authorizer_get_client_id +gdata_oauth2_authorizer_get_redirect_uri +gdata_oauth2_authorizer_get_client_secret +gdata_oauth2_authorizer_dup_refresh_token +gdata_oauth2_authorizer_set_refresh_token +gdata_oauth2_authorizer_get_locale +gdata_oauth2_authorizer_set_locale +gdata_oauth2_authorizer_get_timeout +gdata_oauth2_authorizer_set_timeout +gdata_oauth2_authorizer_get_proxy_resolver +gdata_oauth2_authorizer_set_proxy_resolver +gdata_calendar_access_rule_get_type +gdata_calendar_access_rule_new diff --git a/gdata/gdata-download-stream.c b/gdata/gdata-download-stream.c new file mode 100644 index 0000000..a797de6 --- /dev/null +++ b/gdata/gdata-download-stream.c @@ -0,0 +1,1100 @@ +/* -*- Mode: C; indent-tabs-mode: t; c-basic-offset: 8; tab-width: 8 -*- */ +/* + * GData Client + * Copyright (C) Philip Withnall 2009 + * + * GData Client is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * GData Client is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with GData Client. If not, see . + */ + +/** + * SECTION:gdata-download-stream + * @short_description: GData download stream object + * @stability: Stable + * @include: gdata/gdata-download-stream.h + * + * #GDataDownloadStream is a #GInputStream subclass to allow downloading of files from GData services with authorization from a #GDataService under + * the given #GDataAuthorizationDomain. If authorization is not required to perform the download, a #GDataAuthorizationDomain doesn't have to be + * specified. + * + * Once a #GDataDownloadStream is instantiated with gdata_download_stream_new(), the standard #GInputStream API can be used on the stream to download + * the file. Network communication may not actually begin until the first call to g_input_stream_read(), so having a #GDataDownloadStream around is no + * guarantee that the file is being downloaded. + * + * The content type and length of the file being downloaded are made available through #GDataDownloadStream:content-type and + * #GDataDownloadStream:content-length as soon as the appropriate data is received from the server. Connect to the + * #GObject::notify content-type and content-length details to be notified as + * soon as the data is available. + * + * The entire download operation can be cancelled using the #GCancellable instance provided to gdata_download_stream_new(), or returned by + * gdata_download_stream_get_cancellable(). Cancelling this at any time will cause all future #GInputStream method calls to return + * %G_IO_ERROR_CANCELLED. If any #GInputStream methods are in the process of being called, they will be cancelled and return %G_IO_ERROR_CANCELLED as + * soon as possible. + * + * Note that cancelling an individual method call (such as a call to g_input_stream_read()) using the #GCancellable parameter of the method will not + * cancel the download as a whole — just that particular method call. In the case of g_input_stream_read(), this will cause it to successfully return + * any data that it has in memory at the moment (up to the requested number of bytes), or return a %G_IO_ERROR_CANCELLED if it was blocking on receiving + * data from the network. This is also the behaviour of g_input_stream_read() when the download operation as a whole is cancelled. + * + * In the case of g_input_stream_close(), the call will return immediately if network activity hasn't yet started. If it has, the network activity will + * be cancelled, regardless of whether the call to g_input_stream_close() is cancelled. Cancelling a pending call to g_input_stream_close() (either + * using the method's #GCancellable, or by cancelling the download stream as a whole) will cause it to stop waiting for the network activity to finish, + * and return %G_IO_ERROR_CANCELLED immediately. Network activity will continue to be shut down in the background. + * + * If the server returns an error message (for example, if the user is not correctly authenticated/authorized or doesn't have suitable permissions to + * download from the given URI), it will be returned as a #GDataServiceError by the first call to g_input_stream_read(). + * + * + * Downloading to a File + * + * GDataService *service; + * GDataAuthorizationDomain *domain; + * GCancellable *cancellable; + * GInputStream *download_stream; + * GOutputStream *output_stream; + * + * /* Create the download stream */ + * service = create_my_service (); + * domain = get_my_authorization_domain_from_service (service); + * cancellable = g_cancellable_new (); /* cancel this to cancel the entire download operation */ + * download_stream = gdata_download_stream_new (service, domain, download_uri, cancellable); + * output_stream = create_file_and_return_output_stream (); + * + * /* Perform the download asynchronously */ + * g_output_stream_splice_async (output_stream, download_stream, G_OUTPUT_STREAM_SPLICE_CLOSE_SOURCE | G_OUTPUT_STREAM_SPLICE_CLOSE_TARGET, + * G_PRIORITY_DEFAULT, NULL, (GAsyncReadyCallback) download_splice_cb, NULL); + * + * g_object_unref (output_stream); + * g_object_unref (download_stream); + * g_object_unref (cancellable); + * g_object_unref (domain); + * g_object_unref (service); + * + * static void + * download_splice_cb (GOutputStream *output_stream, GAsyncResult *result, gpointer user_data) + * { + * GError *error = NULL; + * + * g_output_stream_splice_finish (output_stream, result, &error); + * + * if (error != NULL && g_error_matches (error, G_IO_ERROR, G_IO_ERROR_CANCELLED) == FALSE)) { + * /* Error downloading the file; potentially an I/O error (GIOError), or an error response from the server + * * (GDataServiceError). You might want to delete the newly created file because of the error. */ + * g_error ("Error downloading file: %s", error->message); + * g_error_free (error); + * } + * } + * + * + * + * Since: 0.5.0 + */ + +#include +#include +#include + +#include "gdata-download-stream.h" +#include "gdata-buffer.h" +#include "gdata-private.h" + +static void gdata_download_stream_seekable_iface_init (GSeekableIface *seekable_iface); +static GObject *gdata_download_stream_constructor (GType type, guint n_construct_params, GObjectConstructParam *construct_params); +static void gdata_download_stream_dispose (GObject *object); +static void gdata_download_stream_finalize (GObject *object); +static void gdata_download_stream_get_property (GObject *object, guint property_id, GValue *value, GParamSpec *pspec); +static void gdata_download_stream_set_property (GObject *object, guint property_id, const GValue *value, GParamSpec *pspec); + +static gssize gdata_download_stream_read (GInputStream *stream, void *buffer, gsize count, GCancellable *cancellable, GError **error); +static gboolean gdata_download_stream_close (GInputStream *stream, GCancellable *cancellable, GError **error); + +static goffset gdata_download_stream_tell (GSeekable *seekable); +static gboolean gdata_download_stream_can_seek (GSeekable *seekable); +static gboolean gdata_download_stream_seek (GSeekable *seekable, goffset offset, GSeekType type, GCancellable *cancellable, GError **error); +static gboolean gdata_download_stream_can_truncate (GSeekable *seekable); +static gboolean gdata_download_stream_truncate (GSeekable *seekable, goffset offset, GCancellable *cancellable, GError **error); + +static void create_network_thread (GDataDownloadStream *self, GError **error); +static void reset_network_thread (GDataDownloadStream *self); + +/* + * The GDataDownloadStream can be in one of several states: + * 1. Pre-network activity. This is the state that the stream is created in. @network_thread and @cancellable are both %NULL, and @finished is %FALSE. + * The stream will remain in this state until gdata_download_stream_read() or gdata_download_stream_seek() are called for the first time. + * @content_type and @content_length are at their default values (NULL and -1, respectively). + * 2. Network activity. This state is entered when gdata_download_stream_read() is called for the first time. + * @network_thread, @buffer and @cancellable are created, while @finished remains %FALSE. + * As soon as the headers are downloaded, which is guaranteed to be before the first call to gdata_download_stream_read() returns, @content_type + * and @content_length are set from the headers. From this point onwards, they are immutable. + * 3. Reset network activity. This state is entered only if case 3 is encountered in a call to gdata_download_stream_seek(): a seek to an offset which + * has already been read out of the buffer. In this state, @buffer is freed and set to %NULL, @network_thread is cancelled (then set to %NULL), + * and @offset is set to the seeked-to offset. @finished remains at %FALSE. + * When the next call to gdata_download_stream_read() is made, the download stream will go back to state 2 as if this was the first call to + * gdata_download_stream_read(). + * 4. Post-network activity. This state is reached once the download thread finishes downloading, due to having downloaded everything. + * @buffer is non-%NULL, @network_thread is non-%NULL, but meaningless; @cancellable is still a valid #GCancellable instance; and @finished is set + * to %TRUE. At the same time, @finished_cond is signalled. + * This state can be exited either by making a call to gdata_download_stream_seek(), in which case the stream will go back to state 3; or by + * calling gdata_download_stream_close(), in which case the stream will return errors for all operations, as the underlying %GInputStream will be + * marked as closed. + */ +struct _GDataDownloadStreamPrivate { + gchar *download_uri; + GDataService *service; + GDataAuthorizationDomain *authorization_domain; + SoupSession *session; + SoupMessage *message; + GDataBuffer *buffer; + goffset offset; /* current position in the stream */ + + GThread *network_thread; + GCancellable *cancellable; + GCancellable *network_cancellable; /* see the comment in gdata_download_stream_constructor() about the relationship between these two */ + gulong network_cancellable_id; + + gboolean finished; + GCond finished_cond; + GMutex finished_mutex; /* mutex for ->finished, protected by ->finished_cond */ + + /* Cached data from the SoupMessage */ + gchar *content_type; + gssize content_length; + GMutex content_mutex; /* mutex to protect them */ +}; + +enum { + PROP_SERVICE = 1, + PROP_DOWNLOAD_URI, + PROP_CONTENT_TYPE, + PROP_CONTENT_LENGTH, + PROP_CANCELLABLE, + PROP_AUTHORIZATION_DOMAIN, +}; + +G_DEFINE_TYPE_WITH_CODE (GDataDownloadStream, gdata_download_stream, G_TYPE_INPUT_STREAM, + G_IMPLEMENT_INTERFACE (G_TYPE_SEEKABLE, gdata_download_stream_seekable_iface_init)) + +static void +gdata_download_stream_class_init (GDataDownloadStreamClass *klass) +{ + GObjectClass *gobject_class = G_OBJECT_CLASS (klass); + GInputStreamClass *stream_class = G_INPUT_STREAM_CLASS (klass); + + g_type_class_add_private (klass, sizeof (GDataDownloadStreamPrivate)); + + gobject_class->constructor = gdata_download_stream_constructor; + gobject_class->dispose = gdata_download_stream_dispose; + gobject_class->finalize = gdata_download_stream_finalize; + gobject_class->get_property = gdata_download_stream_get_property; + gobject_class->set_property = gdata_download_stream_set_property; + + /* We use the default implementations of the async functions, which just run + * our implementation of the sync function in a thread. */ + stream_class->read_fn = gdata_download_stream_read; + stream_class->close_fn = gdata_download_stream_close; + + /** + * GDataDownloadStream:service: + * + * The service which is used to authorize the download, and to which the download relates. + * + * Since: 0.5.0 + */ + g_object_class_install_property (gobject_class, PROP_SERVICE, + g_param_spec_object ("service", + "Service", "The service which is used to authorize the download.", + GDATA_TYPE_SERVICE, + G_PARAM_CONSTRUCT_ONLY | G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)); + + /** + * GDataDownloadStream:authorization-domain: + * + * The authorization domain for the download, against which the #GDataService:authorizer for the #GDataDownloadStream:service should be + * authorized. This may be %NULL if authorization is not needed for the download. + * + * Since: 0.9.0 + */ + g_object_class_install_property (gobject_class, PROP_AUTHORIZATION_DOMAIN, + g_param_spec_object ("authorization-domain", + "Authorization domain", "The authorization domain for the download.", + GDATA_TYPE_AUTHORIZATION_DOMAIN, + G_PARAM_CONSTRUCT_ONLY | G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)); + + /** + * GDataDownloadStream:download-uri: + * + * The URI of the file to download. This must be HTTPS. + * + * Since: 0.5.0 + */ + g_object_class_install_property (gobject_class, PROP_DOWNLOAD_URI, + g_param_spec_string ("download-uri", + "Download URI", "The URI of the file to download.", + NULL, + G_PARAM_CONSTRUCT_ONLY | G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)); + + /** + * GDataDownloadStream:content-type: + * + * The content type of the file being downloaded. This will initially be %NULL, and will be populated as soon as the appropriate header is + * received from the server. Its value will never change after this. + * + * Note that change notifications for this property (#GObject::notify emissions) may be emitted in threads other than the one which created + * the #GDataDownloadStream. It is the client's responsibility to ensure that any notification signal handlers are either multi-thread safe + * or marshal the notification to the thread which owns the #GDataDownloadStream as appropriate. + * + * Since: 0.5.0 + */ + g_object_class_install_property (gobject_class, PROP_CONTENT_TYPE, + g_param_spec_string ("content-type", + "Content type", "The content type of the file being downloaded.", + NULL, + G_PARAM_READABLE | G_PARAM_STATIC_STRINGS)); + + /** + * GDataDownloadStream:content-length: + * + * The length (in bytes) of the file being downloaded. This will initially be -1, and will be populated as soon as + * the appropriate header is received from the server. Its value will never change after this. + * + * Note that change notifications for this property (#GObject::notify emissions) may be emitted in threads other than the one which created + * the #GDataDownloadStream. It is the client's responsibility to ensure that any notification signal handlers are either multi-thread safe + * or marshal the notification to the thread which owns the #GDataDownloadStream as appropriate. + * + * Since: 0.5.0 + */ + g_object_class_install_property (gobject_class, PROP_CONTENT_LENGTH, + g_param_spec_long ("content-length", + "Content length", "The length (in bytes) of the file being downloaded.", + -1, G_MAXSSIZE, -1, + G_PARAM_READABLE | G_PARAM_STATIC_STRINGS)); + + /** + * GDataDownloadStream:cancellable: + * + * An optional cancellable used to cancel the entire download operation. If a #GCancellable instance isn't provided for this property at + * construction time (i.e. to gdata_download_stream_new()), one will be created internally and can be retrieved using + * gdata_download_stream_get_cancellable() and used to cancel the download operation with g_cancellable_cancel() just as if it was passed to + * gdata_download_stream_new(). + * + * If the download operation is cancelled using this #GCancellable, any ongoing network activity will be stopped, and any pending or future + * calls to #GInputStream API on the #GDataDownloadStream will return %G_IO_ERROR_CANCELLED. Note that the #GCancellable objects which can be + * passed to individual #GInputStream operations will not cancel the download operation proper if cancelled — they will merely cancel that API + * call. The only way to cancel the download operation completely is using #GDataDownloadStream:cancellable. + * + * Since: 0.8.0 + */ + g_object_class_install_property (gobject_class, PROP_CANCELLABLE, + g_param_spec_object ("cancellable", + "Cancellable", "An optional cancellable used to cancel the entire download operation.", + G_TYPE_CANCELLABLE, + G_PARAM_CONSTRUCT_ONLY | G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)); +} + +static void +gdata_download_stream_seekable_iface_init (GSeekableIface *seekable_iface) +{ + seekable_iface->tell = gdata_download_stream_tell; + seekable_iface->can_seek = gdata_download_stream_can_seek; + seekable_iface->seek = gdata_download_stream_seek; + seekable_iface->can_truncate = gdata_download_stream_can_truncate; + seekable_iface->truncate_fn = gdata_download_stream_truncate; +} + +static void +gdata_download_stream_init (GDataDownloadStream *self) +{ + self->priv = G_TYPE_INSTANCE_GET_PRIVATE (self, GDATA_TYPE_DOWNLOAD_STREAM, GDataDownloadStreamPrivate); + self->priv->buffer = NULL; /* created when the network thread is started and destroyed when the stream is closed */ + + self->priv->finished = FALSE; + g_cond_init (&(self->priv->finished_cond)); + g_mutex_init (&(self->priv->finished_mutex)); + + self->priv->content_type = NULL; + self->priv->content_length = -1; + g_mutex_init (&(self->priv->content_mutex)); +} + +static void +cancellable_cancel_cb (GCancellable *cancellable, GCancellable *network_cancellable) +{ + g_cancellable_cancel (network_cancellable); +} + +static GObject * +gdata_download_stream_constructor (GType type, guint n_construct_params, GObjectConstructParam *construct_params) +{ + GDataDownloadStreamPrivate *priv; + GDataServiceClass *klass; + GObject *object; + SoupURI *_uri; + + /* Chain up to the parent class */ + object = G_OBJECT_CLASS (gdata_download_stream_parent_class)->constructor (type, n_construct_params, construct_params); + priv = GDATA_DOWNLOAD_STREAM (object)->priv; + + /* Create a #GCancellable for the network. Cancellation of ->cancellable is chained to this one, so that if ->cancellable is cancelled, + * ->network_cancellable is also cancelled. However, if ->network_cancellable is cancelled, the cancellation doesn't propagate back upwards + * to ->cancellable. This allows closing the stream part-way through a download to be implemented by cancelling ->network_cancellable, without + * causing ->cancellable to be unnecessarily cancelled (which would be a nasty side-effect of closing the stream early otherwise). */ + priv->network_cancellable = g_cancellable_new (); + + /* Create a #GCancellable for the entire download operation if one wasn't specified for #GDataDownloadStream:cancellable during construction */ + if (priv->cancellable == NULL) + priv->cancellable = g_cancellable_new (); + priv->network_cancellable_id = g_cancellable_connect (priv->cancellable, (GCallback) cancellable_cancel_cb, priv->network_cancellable, NULL); + + /* Build the message. The URI must be HTTPS. */ + _uri = soup_uri_new (priv->download_uri); + soup_uri_set_port (_uri, _gdata_service_get_https_port ()); + g_assert_cmpstr (soup_uri_get_scheme (_uri), ==, SOUP_URI_SCHEME_HTTPS); + priv->message = soup_message_new_from_uri (SOUP_METHOD_GET, _uri); + soup_uri_free (_uri); + + /* Make sure the headers are set */ + klass = GDATA_SERVICE_GET_CLASS (priv->service); + if (klass->append_query_headers != NULL) { + klass->append_query_headers (priv->service, priv->authorization_domain, priv->message); + } + + /* We don't want to accumulate chunks */ + soup_message_body_set_accumulate (priv->message->request_body, FALSE); + + /* Downloading doesn't actually start until the first call to read() */ + + return object; +} + +static void +gdata_download_stream_dispose (GObject *object) +{ + GDataDownloadStreamPrivate *priv = GDATA_DOWNLOAD_STREAM (object)->priv; + + /* Block on closing the stream */ + g_input_stream_close (G_INPUT_STREAM (object), NULL, NULL); + + if (priv->cancellable != NULL) { + if (priv->network_cancellable_id != 0) { + g_cancellable_disconnect (priv->cancellable, priv->network_cancellable_id); + } + + g_object_unref (priv->cancellable); + } + + priv->network_cancellable_id = 0; + priv->cancellable = NULL; + + if (priv->network_cancellable != NULL) + g_object_unref (priv->network_cancellable); + priv->network_cancellable = NULL; + + if (priv->authorization_domain != NULL) + g_object_unref (priv->authorization_domain); + priv->authorization_domain = NULL; + + if (priv->service != NULL) + g_object_unref (priv->service); + priv->service = NULL; + + if (priv->message != NULL) + g_object_unref (priv->message); + priv->message = NULL; + + /* Chain up to the parent class */ + G_OBJECT_CLASS (gdata_download_stream_parent_class)->dispose (object); +} + +static void +gdata_download_stream_finalize (GObject *object) +{ + GDataDownloadStreamPrivate *priv = GDATA_DOWNLOAD_STREAM (object)->priv; + + reset_network_thread (GDATA_DOWNLOAD_STREAM (object)); + + g_cond_clear (&(priv->finished_cond)); + g_mutex_clear (&(priv->finished_mutex)); + + g_mutex_clear (&(priv->content_mutex)); + + g_free (priv->download_uri); + g_free (priv->content_type); + + /* Chain up to the parent class */ + G_OBJECT_CLASS (gdata_download_stream_parent_class)->finalize (object); +} + +static void +gdata_download_stream_get_property (GObject *object, guint property_id, GValue *value, GParamSpec *pspec) +{ + GDataDownloadStreamPrivate *priv = GDATA_DOWNLOAD_STREAM (object)->priv; + + switch (property_id) { + case PROP_SERVICE: + g_value_set_object (value, priv->service); + break; + case PROP_AUTHORIZATION_DOMAIN: + g_value_set_object (value, priv->authorization_domain); + break; + case PROP_DOWNLOAD_URI: + g_value_set_string (value, priv->download_uri); + break; + case PROP_CONTENT_TYPE: + g_mutex_lock (&(priv->content_mutex)); + g_value_set_string (value, priv->content_type); + g_mutex_unlock (&(priv->content_mutex)); + break; + case PROP_CONTENT_LENGTH: + g_mutex_lock (&(priv->content_mutex)); + g_value_set_long (value, priv->content_length); + g_mutex_unlock (&(priv->content_mutex)); + break; + case PROP_CANCELLABLE: + g_value_set_object (value, priv->cancellable); + break; + default: + /* We don't have any other property... */ + G_OBJECT_WARN_INVALID_PROPERTY_ID (object, property_id, pspec); + break; + } +} + +static void +gdata_download_stream_set_property (GObject *object, guint property_id, const GValue *value, GParamSpec *pspec) +{ + GDataDownloadStreamPrivate *priv = GDATA_DOWNLOAD_STREAM (object)->priv; + + switch (property_id) { + case PROP_SERVICE: + priv->service = g_value_dup_object (value); + priv->session = _gdata_service_get_session (priv->service); + break; + case PROP_AUTHORIZATION_DOMAIN: + priv->authorization_domain = g_value_dup_object (value); + break; + case PROP_DOWNLOAD_URI: + priv->download_uri = g_value_dup_string (value); + break; + case PROP_CANCELLABLE: + /* Construction only */ + priv->cancellable = g_value_dup_object (value); + break; + default: + /* We don't have any other property... */ + G_OBJECT_WARN_INVALID_PROPERTY_ID (object, property_id, pspec); + break; + } +} + +static void +read_cancelled_cb (GCancellable *cancellable, GCancellable *child_cancellable) +{ + g_cancellable_cancel (child_cancellable); +} + +static gssize +gdata_download_stream_read (GInputStream *stream, void *buffer, gsize count, GCancellable *cancellable, GError **error) +{ + GDataDownloadStreamPrivate *priv = GDATA_DOWNLOAD_STREAM (stream)->priv; + gssize length_read = -1; + gboolean reached_eof = FALSE; + gulong cancelled_signal = 0, global_cancelled_signal = 0; + GCancellable *child_cancellable; + GError *child_error = NULL; + + /* Listen for cancellation from either @cancellable or @priv->cancellable. We have to multiplex cancellation signals from the two sources + * into a single #GCancellabel, @child_cancellable. */ + child_cancellable = g_cancellable_new (); + + global_cancelled_signal = g_cancellable_connect (priv->cancellable, (GCallback) read_cancelled_cb, child_cancellable, NULL); + + if (cancellable != NULL) + cancelled_signal = g_cancellable_connect (cancellable, (GCallback) read_cancelled_cb, child_cancellable, NULL); + + /* We're lazy about starting the network operation so we don't end up with a massive buffer */ + if (priv->network_thread == NULL) { + /* Handle early cancellation so that we don't create the network thread unnecessarily */ + if (g_cancellable_set_error_if_cancelled (child_cancellable, &child_error) == TRUE) { + length_read = -1; + goto done; + } + + /* Create the network thread */ + create_network_thread (GDATA_DOWNLOAD_STREAM (stream), &child_error); + if (priv->network_thread == NULL) { + length_read = -1; + goto done; + } + } + + /* Read the data off the buffer. If the operation is cancelled, it'll probably still return a positive number of bytes read — if it does, we + * can return without error. Iff it returns a non-positive number of bytes should we return an error. */ + g_assert (priv->buffer != NULL); + length_read = (gssize) gdata_buffer_pop_data (priv->buffer, buffer, count, &reached_eof, child_cancellable); + + if (length_read < 1 && g_cancellable_set_error_if_cancelled (child_cancellable, &child_error) == TRUE) { + /* Handle cancellation */ + length_read = -1; + + goto done; + } else if (SOUP_STATUS_IS_SUCCESSFUL (priv->message->status_code) == FALSE) { + GDataServiceClass *klass = GDATA_SERVICE_GET_CLASS (priv->service); + + /* Set an appropriate error */ + g_assert (klass->parse_error_response != NULL); + klass->parse_error_response (priv->service, GDATA_OPERATION_DOWNLOAD, priv->message->status_code, priv->message->reason_phrase, + NULL, 0, &child_error); + length_read = -1; + + goto done; + } + +done: + /* Disconnect from the cancelled signals. */ + if (cancelled_signal != 0) + g_cancellable_disconnect (cancellable, cancelled_signal); + if (global_cancelled_signal != 0) + g_cancellable_disconnect (priv->cancellable, global_cancelled_signal); + + g_object_unref (child_cancellable); + + g_assert ((reached_eof == FALSE && length_read > 0 && length_read <= (gssize) count && child_error == NULL) || + (reached_eof == TRUE && length_read >= 0 && length_read <= (gssize) count && child_error == NULL) || + (length_read == -1 && child_error != NULL)); + + if (child_error != NULL) + g_propagate_error (error, child_error); + + /* Update our internal offset */ + if (length_read > 0) { + priv->offset += length_read; + } + + return length_read; +} + +typedef struct { + GDataDownloadStream *download_stream; + gboolean *cancelled; +} CancelledData; + +static void +close_cancelled_cb (GCancellable *cancellable, CancelledData *data) +{ + GDataDownloadStreamPrivate *priv = data->download_stream->priv; + + g_mutex_lock (&(priv->finished_mutex)); + *(data->cancelled) = TRUE; + g_cond_signal (&(priv->finished_cond)); + g_mutex_unlock (&(priv->finished_mutex)); +} + +/* Even though calling g_input_stream_close() multiple times on this stream is guaranteed to call gdata_download_stream_close() at most once, other + * GIO methods (notably g_output_stream_splice()) can call gdata_download_stream_close() directly. Consequently, we need to be careful to be idempotent + * after the first call. + * + * If the network thread hasn't yet been started (i.e. gdata_download_stream_read() hasn't been called at all yet), %TRUE will be returned immediately. + * + * If the global cancellable, ->cancellable, or @cancellable are cancelled before the call to gdata_download_stream_close(), + * gdata_download_stream_close() should return immediately with %G_IO_ERROR_CANCELLED. If they're cancelled during the call, + * gdata_download_stream_close() should stop waiting for any outstanding network activity to finish and return %G_IO_ERROR_CANCELLED (though the + * operation to finish off network activity and close the stream will still continue). + * + * If the call to gdata_download_stream_close() is not cancelled by any #GCancellable, it will cancel the ongoing network activity, and wait until + * the operation has been cleaned up before returning success. */ +static gboolean +gdata_download_stream_close (GInputStream *stream, GCancellable *cancellable, GError **error) +{ + GDataDownloadStreamPrivate *priv = GDATA_DOWNLOAD_STREAM (stream)->priv; + gulong cancelled_signal = 0, global_cancelled_signal = 0; + gboolean cancelled = FALSE; /* must only be touched with ->finished_mutex held */ + gboolean success = TRUE; + CancelledData data; + GError *child_error = NULL; + + /* If the operation was never started, return successfully immediately */ + if (priv->network_thread == NULL) { + goto done; + } + + /* Allow cancellation */ + data.download_stream = GDATA_DOWNLOAD_STREAM (stream); + data.cancelled = &cancelled; + + global_cancelled_signal = g_cancellable_connect (priv->cancellable, (GCallback) close_cancelled_cb, &data, NULL); + + if (cancellable != NULL) + cancelled_signal = g_cancellable_connect (cancellable, (GCallback) close_cancelled_cb, &data, NULL); + + g_mutex_lock (&(priv->finished_mutex)); + + /* If the operation has started but hasn't already finished, cancel the network thread and wait for it to finish before returning */ + if (priv->finished == FALSE) { + g_cancellable_cancel (priv->network_cancellable); + + /* Allow the close() call to be cancelled by cancelling either @cancellable or ->cancellable. Note that this won't prevent the stream + * from continuing to be closed in the background — it'll just stop waiting on the operation to finish being cancelled. */ + if (cancelled == FALSE) { + g_cond_wait (&(priv->finished_cond), &(priv->finished_mutex)); + } + } + + /* Error handling */ + if (priv->finished == FALSE && cancelled == TRUE) { + /* Cancelled? If ->finished is TRUE, the network activity finished before the gdata_download_stream_close() operation was cancelled, + * so we don't need to return an error. */ + g_assert (g_cancellable_set_error_if_cancelled (cancellable, &child_error) == TRUE || + g_cancellable_set_error_if_cancelled (priv->cancellable, &child_error) == TRUE); + success = FALSE; + } + + g_mutex_unlock (&(priv->finished_mutex)); + + /* Disconnect from the signal handlers. Note that we have to do this without @finished_mutex held, as g_cancellable_disconnect() blocks + * until any outstanding cancellation callbacks return, and they will block on @finished_mutex. */ + if (cancelled_signal != 0) + g_cancellable_disconnect (cancellable, cancelled_signal); + if (global_cancelled_signal != 0) + g_cancellable_disconnect (priv->cancellable, global_cancelled_signal); + +done: + /* If we were successful, tidy up various bits of state */ + g_mutex_lock (&(priv->finished_mutex)); + + if (success == TRUE && priv->finished == TRUE) { + reset_network_thread (GDATA_DOWNLOAD_STREAM (stream)); + } + + g_mutex_unlock (&(priv->finished_mutex)); + + g_assert ((success == TRUE && child_error == NULL) || (success == FALSE && child_error != NULL)); + + if (child_error != NULL) + g_propagate_error (error, child_error); + + return success; +} + +static goffset +gdata_download_stream_tell (GSeekable *seekable) +{ + return GDATA_DOWNLOAD_STREAM (seekable)->priv->offset; +} + +static gboolean +gdata_download_stream_can_seek (GSeekable *seekable) +{ + return TRUE; +} + +static gboolean +gdata_download_stream_seek (GSeekable *seekable, goffset offset, GSeekType type, GCancellable *cancellable, GError **error) +{ + GDataDownloadStreamPrivate *priv = GDATA_DOWNLOAD_STREAM (seekable)->priv; + GError *child_error = NULL; + + if (type == G_SEEK_END && priv->content_length == -1) { + /* If we don't have the Content-Length, we can't calculate the offset from the start of the stream properly, so just give up. + * We could technically use a HEAD request to get the Content-Length, but this hasn't been tried yet (FIXME). */ + g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_NOT_SUPPORTED, "G_SEEK_END not currently supported"); + return FALSE; + } + + if (g_input_stream_set_pending (G_INPUT_STREAM (seekable), error) == FALSE) { + return FALSE; + } + + /* Ensure that offset is relative to the start of the stream. */ + switch (type) { + case G_SEEK_CUR: + offset += priv->offset; + break; + case G_SEEK_SET: + /* Nothing needs doing */ + break; + case G_SEEK_END: + offset += priv->content_length; + break; + default: + g_assert_not_reached (); + } + + /* There are three cases to consider: + * 1. The network thread hasn't been started. In this case, we need to set the offset and do nothing. When the network thread is started + * (in the next read() call), a Range header will be set on it which will give the correct seek. + * 2. The network thread has been started and the seek is to a position greater than our current position (i.e. one which already does, or + * will soon, exist in the buffer). In this case, we need to pop the intervening bytes off the buffer (which may block) and update the + * offset. + * 3. The network thread has been started and the seek is to a position which has already been popped off the buffer. In this case, we need + * to set the offset and cancel the network thread. When the network thread is restarted (in the next read() call), a Range header will + * be set on it which will give the correct seek. + */ + + if (priv->network_thread == NULL) { + /* Case 1. Set the offset and we're done. */ + priv->offset = offset; + + goto done; + } + + /* Cases 2 and 3. The network thread has already been started. */ + if (offset >= priv->offset) { + goffset num_intervening_bytes; + gssize length_read; + + /* Case 2. Pop off the intervening bytes and update the offset. If we can't pop enough bytes off, we throw an error. */ + num_intervening_bytes = offset - priv->offset; + g_assert (priv->buffer != NULL); + length_read = (gssize) gdata_buffer_pop_data (priv->buffer, NULL, num_intervening_bytes, NULL, cancellable); + + if (length_read != num_intervening_bytes) { + if (g_cancellable_set_error_if_cancelled (cancellable, &child_error) == FALSE) { + /* Tried to seek too far */ + g_set_error_literal (&child_error, G_IO_ERROR, G_IO_ERROR_INVALID_ARGUMENT, _("Invalid seek request")); + } + + goto done; + } + + /* Update the offset */ + priv->offset = offset; + + goto done; + } else { + /* Case 3. Cancel the current network thread. Note that we don't allow cancellation of this call, as we depend on it waiting for + * the network thread to join. */ + if (gdata_download_stream_close (G_INPUT_STREAM (seekable), NULL, &child_error) == FALSE) { + goto done; + } + + /* Update the offset */ + priv->offset = offset; + + /* Mark the thread as unfinished */ + g_mutex_lock (&(priv->finished_mutex)); + priv->finished = FALSE; + g_mutex_unlock (&(priv->finished_mutex)); + + goto done; + } + +done: + g_input_stream_clear_pending (G_INPUT_STREAM (seekable)); + + if (child_error != NULL) { + g_propagate_error (error, child_error); + return FALSE; + } + + return TRUE; +} + +static gboolean +gdata_download_stream_can_truncate (GSeekable *seekable) +{ + return FALSE; +} + +static gboolean +gdata_download_stream_truncate (GSeekable *seekable, goffset offset, GCancellable *cancellable, GError **error) +{ + g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_NOT_SUPPORTED, "Truncate not allowed on input stream"); + return FALSE; +} + +static void +got_headers_cb (SoupMessage *message, GDataDownloadStream *self) +{ + goffset end; + goffset start; + goffset total_length; + + /* Don't get the client's hopes up by setting the Content-Type or -Length if the response + * is actually unsuccessful. */ + if (SOUP_STATUS_IS_SUCCESSFUL (message->status_code) == FALSE) + return; + + g_mutex_lock (&(self->priv->content_mutex)); + self->priv->content_type = g_strdup (soup_message_headers_get_content_type (message->response_headers, NULL)); + self->priv->content_length = soup_message_headers_get_content_length (message->response_headers); + if (soup_message_headers_get_content_range (message->response_headers, &start, &end, &total_length)) { + self->priv->content_length = (gssize) total_length; + } + g_mutex_unlock (&(self->priv->content_mutex)); + + /* Emit the notifications for the Content-Length and -Type properties */ + g_object_freeze_notify (G_OBJECT (self)); + g_object_notify (G_OBJECT (self), "content-length"); + g_object_notify (G_OBJECT (self), "content-type"); + g_object_thaw_notify (G_OBJECT (self)); +} + +static void +got_chunk_cb (SoupMessage *message, SoupBuffer *buffer, GDataDownloadStream *self) +{ + /* Ignore the chunk if the response is unsuccessful or it has zero length */ + if (SOUP_STATUS_IS_SUCCESSFUL (message->status_code) == FALSE || buffer->length == 0) + return; + + /* Push the data onto the buffer immediately */ + g_assert (self->priv->buffer != NULL); + gdata_buffer_push_data (self->priv->buffer, (const guint8*) buffer->data, buffer->length); +} + +static gpointer +download_thread (GDataDownloadStream *self) +{ + GDataDownloadStreamPrivate *priv = self->priv; + GDataAuthorizer *authorizer; + + g_object_ref (self); + + g_assert (priv->network_cancellable != NULL); + + /* FIXME: Refresh authorization before sending message in order to prevent authorization errors during transfer. + * See: https://gitlab.gnome.org/GNOME/libgdata/issues/23 */ + authorizer = gdata_service_get_authorizer (priv->service); + if (authorizer) { + g_autoptr(GError) error = NULL; + + gdata_authorizer_refresh_authorization (authorizer, priv->cancellable, &error); + if (error != NULL) + g_debug ("Error returned when refreshing authorization: %s", error->message); + else + gdata_authorizer_process_request (authorizer, priv->authorization_domain, priv->message); + } + /* Connect to the got-headers signal so we can notify clients of the values of content-type and content-length */ + g_signal_connect (priv->message, "got-headers", (GCallback) got_headers_cb, self); + g_signal_connect (priv->message, "got-chunk", (GCallback) got_chunk_cb, self); + + /* Set a Range header if our starting offset is non-zero */ + if (priv->offset > 0) { + soup_message_headers_set_range (priv->message->request_headers, priv->offset, -1); + } else { + soup_message_headers_remove (priv->message->request_headers, "Range"); + } + + _gdata_service_actually_send_message (priv->session, priv->message, priv->network_cancellable, NULL); + + /* Mark the buffer as having reached EOF */ + g_assert (priv->buffer != NULL); + gdata_buffer_push_data (priv->buffer, NULL, 0); + + /* Mark the download as finished */ + g_mutex_lock (&(priv->finished_mutex)); + priv->finished = TRUE; + g_cond_signal (&(priv->finished_cond)); + g_mutex_unlock (&(priv->finished_mutex)); + + g_object_unref (self); + + return NULL; +} + +static void +create_network_thread (GDataDownloadStream *self, GError **error) +{ + GDataDownloadStreamPrivate *priv = self->priv; + + g_assert (priv->buffer == NULL); + priv->buffer = gdata_buffer_new (); + + g_assert (priv->network_thread == NULL); + priv->network_thread = g_thread_try_new ("download-thread", (GThreadFunc) download_thread, self, error); +} + +static void +reset_network_thread (GDataDownloadStream *self) +{ + GDataDownloadStreamPrivate *priv = self->priv; + + priv->network_thread = NULL; + + if (priv->buffer != NULL) { + gdata_buffer_free (priv->buffer); + priv->buffer = NULL; + } + + if (priv->message != NULL) { + soup_session_cancel_message (priv->session, priv->message, SOUP_STATUS_CANCELLED); + g_signal_handlers_disconnect_by_func (priv->message, got_headers_cb, self); + g_signal_handlers_disconnect_by_func (priv->message, got_chunk_cb, self); + } + + priv->offset = 0; + + if (priv->network_cancellable != NULL) { + g_cancellable_reset (priv->network_cancellable); + } +} + +/** + * gdata_download_stream_new: + * @service: a #GDataService + * @domain: (allow-none): the #GDataAuthorizationDomain to authorize the download, or %NULL + * @download_uri: the URI to download; this must be HTTPS + * @cancellable: (allow-none): a #GCancellable for the entire download stream, or %NULL + * + * Creates a new #GDataDownloadStream, allowing a file to be downloaded from a GData service using standard #GInputStream API. + * + * As well as the standard GIO errors, calls to the #GInputStream API on a #GDataDownloadStream can also return any relevant specific error from + * #GDataServiceError, or %GDATA_SERVICE_ERROR_PROTOCOL_ERROR in the general case. + * + * If a #GCancellable is provided in @cancellable, the download operation may be cancelled at any time from another thread using g_cancellable_cancel(). + * In this case, any ongoing network activity will be stopped, and any pending or future calls to #GInputStream API on the #GDataDownloadStream will + * return %G_IO_ERROR_CANCELLED. Note that the #GCancellable objects which can be passed to individual #GInputStream operations will not cancel the + * download operation proper if cancelled — they will merely cancel that API call. The only way to cancel the download operation completely is using + * this @cancellable. + * + * Return value: a new #GInputStream, or %NULL; unref with g_object_unref() + * + * Since: 0.9.0 + */ +GInputStream * +gdata_download_stream_new (GDataService *service, GDataAuthorizationDomain *domain, const gchar *download_uri, GCancellable *cancellable) +{ + g_return_val_if_fail (GDATA_IS_SERVICE (service), NULL); + g_return_val_if_fail (domain == NULL || GDATA_IS_AUTHORIZATION_DOMAIN (domain), NULL); + g_return_val_if_fail (download_uri != NULL, NULL); + g_return_val_if_fail (cancellable == NULL || G_IS_CANCELLABLE (cancellable), NULL); + + return G_INPUT_STREAM (g_object_new (GDATA_TYPE_DOWNLOAD_STREAM, + "download-uri", download_uri, + "service", service, + "authorization-domain", domain, + "cancellable", cancellable, + NULL)); +} + +/** + * gdata_download_stream_get_service: + * @self: a #GDataDownloadStream + * + * Gets the service used to authorize the download, as passed to gdata_download_stream_new(). + * + * Return value: (transfer none): the #GDataService used to authorize the download + * + * Since: 0.5.0 + */ +GDataService * +gdata_download_stream_get_service (GDataDownloadStream *self) +{ + g_return_val_if_fail (GDATA_IS_DOWNLOAD_STREAM (self), NULL); + return self->priv->service; +} + +/** + * gdata_download_stream_get_authorization_domain: + * @self: a #GDataDownloadStream + * + * Gets the authorization domain used to authorize the download, as passed to gdata_download_stream_new(). It may be %NULL if authorization is not + * needed for the download. + * + * Return value: (transfer none) (allow-none): the #GDataAuthorizationDomain used to authorize the download, or %NULL + * + * Since: 0.9.0 + */ +GDataAuthorizationDomain * +gdata_download_stream_get_authorization_domain (GDataDownloadStream *self) +{ + g_return_val_if_fail (GDATA_IS_DOWNLOAD_STREAM (self), NULL); + return self->priv->authorization_domain; +} + +/** + * gdata_download_stream_get_download_uri: + * @self: a #GDataDownloadStream + * + * Gets the URI of the file being downloaded, as passed to gdata_download_stream_new(). + * + * Return value: the URI of the file being downloaded + * + * Since: 0.5.0 + */ +const gchar * +gdata_download_stream_get_download_uri (GDataDownloadStream *self) +{ + g_return_val_if_fail (GDATA_IS_DOWNLOAD_STREAM (self), NULL); + return self->priv->download_uri; +} + +/** + * gdata_download_stream_get_content_type: + * @self: a #GDataDownloadStream + * + * Gets the content type of the file being downloaded. If the Content-Type header has not yet + * been received, %NULL will be returned. + * + * Return value: the content type of the file being downloaded, or %NULL + * + * Since: 0.5.0 + */ +const gchar * +gdata_download_stream_get_content_type (GDataDownloadStream *self) +{ + const gchar *content_type; + + g_return_val_if_fail (GDATA_IS_DOWNLOAD_STREAM (self), NULL); + + g_mutex_lock (&(self->priv->content_mutex)); + content_type = self->priv->content_type; + g_mutex_unlock (&(self->priv->content_mutex)); + + /* It's safe to return this, even though we're not taking a copy of it, as it's immutable once set. */ + return content_type; +} + +/** + * gdata_download_stream_get_content_length: + * @self: a #GDataDownloadStream + * + * Gets the length (in bytes) of the file being downloaded. If the Content-Length header has not yet + * been received from the server, -1 will be returned. + * + * Return value: the content length of the file being downloaded, or -1 + * + * Since: 0.5.0 + */ +gssize +gdata_download_stream_get_content_length (GDataDownloadStream *self) +{ + gssize content_length; + + g_return_val_if_fail (GDATA_IS_DOWNLOAD_STREAM (self), -1); + + g_mutex_lock (&(self->priv->content_mutex)); + content_length = self->priv->content_length; + g_mutex_unlock (&(self->priv->content_mutex)); + + g_assert (content_length >= -1); + + return content_length; +} + +/** + * gdata_download_stream_get_cancellable: + * @self: a #GDataDownloadStream + * + * Gets the #GCancellable for the entire download operation, #GDataDownloadStream:cancellable. + * + * Return value: (transfer none): the #GCancellable for the entire download operation + * + * Since: 0.8.0 + */ +GCancellable * +gdata_download_stream_get_cancellable (GDataDownloadStream *self) +{ + g_return_val_if_fail (GDATA_IS_DOWNLOAD_STREAM (self), NULL); + g_assert (self->priv->cancellable != NULL); + return self->priv->cancellable; +} diff --git a/gdata/gdata-download-stream.h b/gdata/gdata-download-stream.h new file mode 100644 index 0000000..9086f2a --- /dev/null +++ b/gdata/gdata-download-stream.h @@ -0,0 +1,87 @@ +/* -*- Mode: C; indent-tabs-mode: t; c-basic-offset: 8; tab-width: 8 -*- */ +/* + * GData Client + * Copyright (C) Philip Withnall 2009 + * + * GData Client is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * GData Client is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with GData Client. If not, see . + */ + +#ifndef GDATA_DOWNLOAD_STREAM_H +#define GDATA_DOWNLOAD_STREAM_H + +#include +#include +#include + +#include + +G_BEGIN_DECLS + +#define GDATA_TYPE_DOWNLOAD_STREAM (gdata_download_stream_get_type ()) +#define GDATA_DOWNLOAD_STREAM(o) (G_TYPE_CHECK_INSTANCE_CAST ((o), GDATA_TYPE_DOWNLOAD_STREAM, GDataDownloadStream)) +#define GDATA_DOWNLOAD_STREAM_CLASS(k) (G_TYPE_CHECK_CLASS_CAST((k), GDATA_TYPE_DOWNLOAD_STREAM, GDataDownloadStreamClass)) +#define GDATA_IS_DOWNLOAD_STREAM(o) (G_TYPE_CHECK_INSTANCE_TYPE ((o), GDATA_TYPE_DOWNLOAD_STREAM)) +#define GDATA_IS_DOWNLOAD_STREAM_CLASS(k) (G_TYPE_CHECK_CLASS_TYPE ((k), GDATA_TYPE_DOWNLOAD_STREAM)) +#define GDATA_DOWNLOAD_STREAM_GET_CLASS(o) (G_TYPE_INSTANCE_GET_CLASS ((o), GDATA_TYPE_DOWNLOAD_STREAM, GDataDownloadStreamClass)) + +typedef struct _GDataDownloadStreamPrivate GDataDownloadStreamPrivate; + +/** + * GDataDownloadStream: + * + * All the fields in the #GDataDownloadStream structure are private and should never be accessed directly. + * + * Since: 0.5.0 + */ +typedef struct { + GInputStream parent; + GDataDownloadStreamPrivate *priv; +} GDataDownloadStream; + +/** + * GDataDownloadStreamClass: + * + * All the fields in the #GDataDownloadStreamClass structure are private and should never be accessed directly. + * + * Since: 0.5.0 + */ +typedef struct { + /*< private >*/ + GInputStreamClass parent; + + /*< private >*/ + /* Padding for future expansion */ + void (*_g_reserved0) (void); + void (*_g_reserved1) (void); + void (*_g_reserved2) (void); + void (*_g_reserved3) (void); + void (*_g_reserved4) (void); + void (*_g_reserved5) (void); +} GDataDownloadStreamClass; + +GType gdata_download_stream_get_type (void) G_GNUC_CONST; + +GInputStream *gdata_download_stream_new (GDataService *service, GDataAuthorizationDomain *domain, const gchar *download_uri, + GCancellable *cancellable) G_GNUC_WARN_UNUSED_RESULT G_GNUC_MALLOC; + +GDataService *gdata_download_stream_get_service (GDataDownloadStream *self) G_GNUC_PURE; +GDataAuthorizationDomain *gdata_download_stream_get_authorization_domain (GDataDownloadStream *self) G_GNUC_PURE; +const gchar *gdata_download_stream_get_download_uri (GDataDownloadStream *self) G_GNUC_PURE; +const gchar *gdata_download_stream_get_content_type (GDataDownloadStream *self) G_GNUC_PURE; +gssize gdata_download_stream_get_content_length (GDataDownloadStream *self) G_GNUC_PURE; +GCancellable *gdata_download_stream_get_cancellable (GDataDownloadStream *self) G_GNUC_PURE; + +G_END_DECLS + +#endif /* !GDATA_DOWNLOAD_STREAM_H */ diff --git a/gdata/gdata-entry.c b/gdata/gdata-entry.c new file mode 100644 index 0000000..30488a8 --- /dev/null +++ b/gdata/gdata-entry.c @@ -0,0 +1,1300 @@ +/* -*- Mode: C; indent-tabs-mode: t; c-basic-offset: 8; tab-width: 8 -*- */ +/* + * GData Client + * Copyright (C) Philip Withnall 2008–2010 + * + * GData Client is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * GData Client is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with GData Client. If not, see . + */ + +/** + * SECTION:gdata-entry + * @short_description: GData entry object + * @stability: Stable + * @include: gdata/gdata-entry.h + * + * #GDataEntry represents a single object on the online service, such as a playlist, video or calendar event. It is a snapshot of the + * state of that object at the time of querying the service, so modifications made to a #GDataEntry will not be automatically or + * magically propagated to the server. + */ + +#include +#include +#include +#include +#include +#include + +#include "gdata-entry.h" +#include "gdata-types.h" +#include "gdata-service.h" +#include "gdata-private.h" +#include "gdata-comparable.h" +#include "atom/gdata-category.h" +#include "atom/gdata-link.h" +#include "atom/gdata-author.h" + +static void gdata_entry_constructed (GObject *object); +static void gdata_entry_dispose (GObject *object); +static void gdata_entry_finalize (GObject *object); +static void gdata_entry_get_property (GObject *object, guint property_id, GValue *value, GParamSpec *pspec); +static void gdata_entry_set_property (GObject *object, guint property_id, const GValue *value, GParamSpec *pspec); +static gboolean pre_parse_xml (GDataParsable *parsable, xmlDoc *doc, xmlNode *root_node, gpointer user_data, GError **error); +static gboolean parse_xml (GDataParsable *parsable, xmlDoc *doc, xmlNode *node, gpointer user_data, GError **error); +static gboolean post_parse_xml (GDataParsable *parsable, gpointer user_data, GError **error); +static void pre_get_xml (GDataParsable *parsable, GString *xml_string); +static void get_xml (GDataParsable *parsable, GString *xml_string); +static void get_namespaces (GDataParsable *parsable, GHashTable *namespaces); +static gchar *get_entry_uri (const gchar *id) G_GNUC_WARN_UNUSED_RESULT; +static gboolean parse_json (GDataParsable *parsable, JsonReader *reader, gpointer user_data, GError **error); +static void get_json (GDataParsable *parsable, JsonBuilder *builder); + +struct _GDataEntryPrivate { + gchar *title; + gchar *summary; + gchar *id; + gchar *etag; + gint64 updated; + gint64 published; + GList *categories; /* GDataCategory */ + gchar *content; + gboolean content_is_uri; + GList *links; /* GDataLink */ + GList *authors; /* GDataAuthor */ + gchar *rights; + + /* Batch processing data */ + GDataBatchOperationType batch_operation_type; + guint batch_id; +}; + +enum { + PROP_TITLE = 1, + PROP_SUMMARY, + PROP_ETAG, + PROP_ID, + PROP_UPDATED, + PROP_PUBLISHED, + PROP_CONTENT, + PROP_IS_INSERTED, + PROP_RIGHTS, + PROP_CONTENT_URI +}; + +G_DEFINE_TYPE (GDataEntry, gdata_entry, GDATA_TYPE_PARSABLE) + +static void +gdata_entry_class_init (GDataEntryClass *klass) +{ + GObjectClass *gobject_class = G_OBJECT_CLASS (klass); + GDataParsableClass *parsable_class = GDATA_PARSABLE_CLASS (klass); + + g_type_class_add_private (klass, sizeof (GDataEntryPrivate)); + + gobject_class->constructed = gdata_entry_constructed; + gobject_class->get_property = gdata_entry_get_property; + gobject_class->set_property = gdata_entry_set_property; + gobject_class->dispose = gdata_entry_dispose; + gobject_class->finalize = gdata_entry_finalize; + + parsable_class->pre_parse_xml = pre_parse_xml; + parsable_class->parse_xml = parse_xml; + parsable_class->post_parse_xml = post_parse_xml; + parsable_class->pre_get_xml = pre_get_xml; + parsable_class->get_xml = get_xml; + parsable_class->get_namespaces = get_namespaces; + parsable_class->element_name = "entry"; + + parsable_class->parse_json = parse_json; + parsable_class->get_json = get_json; + + klass->get_entry_uri = get_entry_uri; + + /** + * GDataEntry:title: + * + * A human-readable title for the entry. + * + * For more information, see the Atom specification. + */ + g_object_class_install_property (gobject_class, PROP_TITLE, + g_param_spec_string ("title", + "Title", "A human-readable title for the entry.", + NULL, + G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)); + + /** + * GDataEntry:summary: + * + * A short summary, abstract, or excerpt of the entry. + * + * For more information, see the Atom specification. + * + * Since: 0.4.0 + */ + g_object_class_install_property (gobject_class, PROP_SUMMARY, + g_param_spec_string ("summary", + "Summary", "A short summary, abstract, or excerpt of the entry.", + NULL, + G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)); + + /** + * GDataEntry:id: + * + * A permanent, universally unique identifier for the entry, in IRI form. This is %NULL for new entries (i.e. ones which haven't yet been + * inserted on the server, created with gdata_entry_new()), and a non-empty IRI string for all other entries. + * + * For more information, see the + * Atom specification. + */ + g_object_class_install_property (gobject_class, PROP_ID, + g_param_spec_string ("id", + "ID", "A permanent, universally unique identifier for the entry, in IRI form.", + NULL, + G_PARAM_READWRITE | G_PARAM_CONSTRUCT_ONLY | G_PARAM_STATIC_STRINGS)); + + /** + * GDataEntry:etag: + * + * An identifier for a particular version of the entry. This changes every time the entry on the server changes, and can be used + * for conditional retrieval and locking. + * + * For more information, see the + * GData specification. + * + * Since: 0.2.0 + */ + g_object_class_install_property (gobject_class, PROP_ETAG, + g_param_spec_string ("etag", + "ETag", "An identifier for a particular version of the entry.", + NULL, + G_PARAM_READWRITE | G_PARAM_CONSTRUCT_ONLY | G_PARAM_STATIC_STRINGS)); + + /** + * GDataEntry:updated: + * + * The date and time when the entry was most recently updated significantly. + * + * For more information, see the Atom specification. + */ + g_object_class_install_property (gobject_class, PROP_UPDATED, + g_param_spec_int64 ("updated", + "Updated", "The date and time when the entry was most recently updated significantly.", + -1, G_MAXINT64, -1, + G_PARAM_READABLE | G_PARAM_STATIC_STRINGS)); + + /** + * GDataEntry:published: + * + * The date and time the entry was first published or made available. + * + * For more information, see the Atom specification. + */ + g_object_class_install_property (gobject_class, PROP_PUBLISHED, + g_param_spec_int64 ("published", + "Published", "The date and time the entry was first published or made available.", + -1, G_MAXINT64, -1, + G_PARAM_READABLE | G_PARAM_STATIC_STRINGS)); + + /** + * GDataEntry:content: + * + * The content of the entry. This is mutually exclusive with #GDataEntry:content. + * + * For more information, see the Atom specification. + */ + g_object_class_install_property (gobject_class, PROP_CONTENT, + g_param_spec_string ("content", + "Content", "The content of the entry.", + NULL, + G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)); + + /** + * GDataEntry:content-uri: + * + * A URI pointing to the location of the content of the entry. This is mutually exclusive with #GDataEntry:content. + * + * For more information, see the + * Atom specification. + * + * Since: 0.7.0 + */ + g_object_class_install_property (gobject_class, PROP_CONTENT_URI, + g_param_spec_string ("content-uri", + "Content URI", "A URI pointing to the location of the content of the entry.", + NULL, + G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)); + + /** + * GDataEntry:is-inserted: + * + * Whether the entry has been inserted on the server. This is %FALSE for entries which have just been created using gdata_entry_new() and + * %TRUE for entries returned from the server by queries. It is set to %TRUE when an entry is inserted using gdata_service_insert_entry(). + */ + g_object_class_install_property (gobject_class, PROP_IS_INSERTED, + g_param_spec_boolean ("is-inserted", + "Inserted?", "Whether the entry has been inserted on the server.", + FALSE, + G_PARAM_READABLE | G_PARAM_STATIC_STRINGS)); + + /** + * GDataEntry:rights: + * + * The ownership rights pertaining to the entry. + * + * For more information, see the Atom specification. + * + * Since: 0.5.0 + */ + g_object_class_install_property (gobject_class, PROP_RIGHTS, + g_param_spec_string ("rights", + "Rights", "The ownership rights pertaining to the entry.", + NULL, + G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)); +} + +static void +gdata_entry_init (GDataEntry *self) +{ + self->priv = G_TYPE_INSTANCE_GET_PRIVATE (self, GDATA_TYPE_ENTRY, GDataEntryPrivate); + self->priv->updated = -1; + self->priv->published = -1; +} + +static void +gdata_entry_constructed (GObject *object) +{ + GDataEntryClass *klass = GDATA_ENTRY_GET_CLASS (object); + GObjectClass *parent_class = G_OBJECT_CLASS (gdata_entry_parent_class); + + /* This can't be done in *_init() because the class properties haven't been properly set then */ + if (klass->kind_term != NULL) { + /* Ensure we have the correct category/kind */ + GDataCategory *category = gdata_category_new (klass->kind_term, "http://schemas.google.com/g/2005#kind", NULL); + gdata_entry_add_category (GDATA_ENTRY (object), category); + g_object_unref (category); + } + + /* Chain up to the parent class */ + if (parent_class->constructed != NULL) + parent_class->constructed (object); +} + +static void +gdata_entry_dispose (GObject *object) +{ + GDataEntryPrivate *priv = GDATA_ENTRY (object)->priv; + + g_list_free_full (priv->categories, g_object_unref); + priv->categories = NULL; + + g_list_free_full (priv->links, g_object_unref); + priv->links = NULL; + + g_list_free_full (priv->authors, g_object_unref); + priv->authors = NULL; + + /* Chain up to the parent class */ + G_OBJECT_CLASS (gdata_entry_parent_class)->dispose (object); +} + +static void +gdata_entry_finalize (GObject *object) +{ + GDataEntryPrivate *priv = GDATA_ENTRY (object)->priv; + + g_free (priv->title); + g_free (priv->summary); + g_free (priv->id); + g_free (priv->etag); + g_free (priv->rights); + g_free (priv->content); + + /* Chain up to the parent class */ + G_OBJECT_CLASS (gdata_entry_parent_class)->finalize (object); +} + +static void +gdata_entry_get_property (GObject *object, guint property_id, GValue *value, GParamSpec *pspec) +{ + GDataEntryPrivate *priv = GDATA_ENTRY (object)->priv; + + switch (property_id) { + case PROP_TITLE: + g_value_set_string (value, priv->title); + break; + case PROP_SUMMARY: + g_value_set_string (value, priv->summary); + break; + case PROP_ID: + g_value_set_string (value, priv->id); + break; + case PROP_ETAG: + g_value_set_string (value, priv->etag); + break; + case PROP_UPDATED: + g_value_set_int64 (value, priv->updated); + break; + case PROP_PUBLISHED: + g_value_set_int64 (value, priv->published); + break; + case PROP_CONTENT: + g_value_set_string (value, (priv->content_is_uri == FALSE) ? priv->content : NULL); + break; + case PROP_CONTENT_URI: + g_value_set_string (value, (priv->content_is_uri == TRUE) ? priv->content : NULL); + break; + case PROP_IS_INSERTED: + g_value_set_boolean (value, gdata_entry_is_inserted (GDATA_ENTRY (object))); + break; + case PROP_RIGHTS: + g_value_set_string (value, priv->rights); + break; + default: + /* We don't have any other property... */ + G_OBJECT_WARN_INVALID_PROPERTY_ID (object, property_id, pspec); + break; + } +} + +static void +gdata_entry_set_property (GObject *object, guint property_id, const GValue *value, GParamSpec *pspec) +{ + GDataEntry *self = GDATA_ENTRY (object); + + switch (property_id) { + case PROP_ID: + /* Construct only */ + self->priv->id = g_value_dup_string (value); + break; + case PROP_ETAG: + /* Construct only */ + self->priv->etag = g_value_dup_string (value); + break; + case PROP_TITLE: + gdata_entry_set_title (self, g_value_get_string (value)); + break; + case PROP_SUMMARY: + gdata_entry_set_summary (self, g_value_get_string (value)); + break; + case PROP_CONTENT: + gdata_entry_set_content (self, g_value_get_string (value)); + break; + case PROP_CONTENT_URI: + gdata_entry_set_content_uri (self, g_value_get_string (value)); + break; + case PROP_RIGHTS: + gdata_entry_set_rights (self, g_value_get_string (value)); + break; + default: + /* We don't have any other property... */ + G_OBJECT_WARN_INVALID_PROPERTY_ID (object, property_id, pspec); + break; + } +} + +static gboolean +pre_parse_xml (GDataParsable *parsable, xmlDoc *doc, xmlNode *root_node, gpointer user_data, GError **error) +{ + /* Extract the ETag */ + GDATA_ENTRY (parsable)->priv->etag = (gchar*) xmlGetProp (root_node, (xmlChar*) "etag"); + + return TRUE; +} + +static gboolean +parse_xml (GDataParsable *parsable, xmlDoc *doc, xmlNode *node, gpointer user_data, GError **error) +{ + gboolean success; + GDataEntryPrivate *priv = GDATA_ENTRY (parsable)->priv; + + if (gdata_parser_is_namespace (node, "http://www.w3.org/2005/Atom") == TRUE) { + if (gdata_parser_string_from_element (node, "title", P_DEFAULT | P_NO_DUPES, &(priv->title), &success, error) == TRUE || + gdata_parser_string_from_element (node, "id", P_REQUIRED | P_NON_EMPTY | P_NO_DUPES, &(priv->id), &success, error) == TRUE || + gdata_parser_string_from_element (node, "summary", P_NONE, &(priv->summary), &success, error) == TRUE || + gdata_parser_string_from_element (node, "rights", P_NONE, &(priv->rights), &success, error) == TRUE || + gdata_parser_int64_time_from_element (node, "updated", P_REQUIRED | P_NO_DUPES, &(priv->updated), &success, error) == TRUE || + gdata_parser_int64_time_from_element (node, "published", P_REQUIRED | P_NO_DUPES, &(priv->published), &success, error) == TRUE || + gdata_parser_object_from_element_setter (node, "category", P_REQUIRED, GDATA_TYPE_CATEGORY, + gdata_entry_add_category, parsable, &success, error) == TRUE || + gdata_parser_object_from_element_setter (node, "link", P_REQUIRED, GDATA_TYPE_LINK, + gdata_entry_add_link, parsable, &success, error) == TRUE || + gdata_parser_object_from_element_setter (node, "author", P_REQUIRED, GDATA_TYPE_AUTHOR, + gdata_entry_add_author, parsable, &success, error) == TRUE) { + return success; + } else if (xmlStrcmp (node->name, (xmlChar*) "content") == 0) { + /* atom:content */ + priv->content = (gchar*) xmlGetProp (node, (xmlChar*) "src"); + priv->content_is_uri = TRUE; + + if (priv->content == NULL) { + priv->content = (gchar*) xmlNodeListGetString (doc, node->children, TRUE); + priv->content_is_uri = FALSE; + } + + return TRUE; + } + } else if (gdata_parser_is_namespace (node, "http://schemas.google.com/gdata/batch") == TRUE) { + if (xmlStrcmp (node->name, (xmlChar*) "id") == 0 || + xmlStrcmp (node->name, (xmlChar*) "status") == 0 || + xmlStrcmp (node->name, (xmlChar*) "operation") == 0) { + /* Ignore batch operation elements; they're handled in GDataBatchFeed */ + return TRUE; + } + } + + return GDATA_PARSABLE_CLASS (gdata_entry_parent_class)->parse_xml (parsable, doc, node, user_data, error); +} + +static gboolean +post_parse_xml (GDataParsable *parsable, gpointer user_data, GError **error) +{ + GDataEntryPrivate *priv = GDATA_ENTRY (parsable)->priv; + + /* Check for missing required elements */ + /* Can't uncomment it, as things like access rules break the Atom standard */ + /*if (priv->title == NULL) + return gdata_parser_error_required_element_missing ("title", "entry", error); + if (priv->id == NULL) + return gdata_parser_error_required_element_missing ("id", "entry", error); + if (priv->updated.tv_sec == 0 && priv->updated.tv_usec == 0) + return gdata_parser_error_required_element_missing ("updated", "entry", error);*/ + + /* Reverse our lists of stuff */ + priv->categories = g_list_reverse (priv->categories); + priv->links = g_list_reverse (priv->links); + priv->authors = g_list_reverse (priv->authors); + + return TRUE; +} + +static void +pre_get_xml (GDataParsable *parsable, GString *xml_string) +{ + GDataEntryPrivate *priv = GDATA_ENTRY (parsable)->priv; + + /* Add the entry's ETag, if available */ + if (gdata_entry_get_etag (GDATA_ENTRY (parsable)) != NULL) + gdata_parser_string_append_escaped (xml_string, " gd:etag='", priv->etag, "'"); +} + +static void +get_xml (GDataParsable *parsable, GString *xml_string) +{ + GDataEntryPrivate *priv = GDATA_ENTRY (parsable)->priv; + GList *categories, *links, *authors; + + gdata_parser_string_append_escaped (xml_string, "", priv->title, ""); + + if (priv->id != NULL) + gdata_parser_string_append_escaped (xml_string, "", priv->id, ""); + + if (priv->updated != -1) { + gchar *updated = gdata_parser_int64_to_iso8601 (priv->updated); + g_string_append_printf (xml_string, "%s", updated); + g_free (updated); + } + + if (priv->published != -1) { + gchar *published = gdata_parser_int64_to_iso8601 (priv->published); + g_string_append_printf (xml_string, "%s", published); + g_free (published); + } + + if (priv->summary != NULL) + gdata_parser_string_append_escaped (xml_string, "", priv->summary, ""); + + if (priv->rights != NULL) + gdata_parser_string_append_escaped (xml_string, "", priv->rights, ""); + + if (priv->content != NULL) { + if (priv->content_is_uri == TRUE) + gdata_parser_string_append_escaped (xml_string, ""); + else + gdata_parser_string_append_escaped (xml_string, "", priv->content, ""); + } + + for (categories = priv->categories; categories != NULL; categories = categories->next) + _gdata_parsable_get_xml (GDATA_PARSABLE (categories->data), xml_string, FALSE); + + for (links = priv->links; links != NULL; links = links->next) + _gdata_parsable_get_xml (GDATA_PARSABLE (links->data), xml_string, FALSE); + + for (authors = priv->authors; authors != NULL; authors = authors->next) + _gdata_parsable_get_xml (GDATA_PARSABLE (authors->data), xml_string, FALSE); + + /* Batch operation data */ + if (priv->batch_id != 0) { + const gchar *batch_op; + + switch (priv->batch_operation_type) { + case GDATA_BATCH_OPERATION_QUERY: + batch_op = "query"; + break; + case GDATA_BATCH_OPERATION_INSERTION: + batch_op = "insert"; + break; + case GDATA_BATCH_OPERATION_UPDATE: + batch_op = "update"; + break; + case GDATA_BATCH_OPERATION_DELETION: + batch_op = "delete"; + break; + default: + g_assert_not_reached (); + break; + } + + g_string_append_printf (xml_string, "%u", priv->batch_id, batch_op); + } +} + +static void +get_namespaces (GDataParsable *parsable, GHashTable *namespaces) +{ + g_hash_table_insert (namespaces, (gchar*) "gd", (gchar*) "http://schemas.google.com/g/2005"); + + if (GDATA_ENTRY (parsable)->priv->batch_id != 0) + g_hash_table_insert (namespaces, (gchar*) "batch", (gchar*) "http://schemas.google.com/gdata/batch"); +} + +static gchar * +get_entry_uri (const gchar *id) +{ + /* We assume the entry ID is also its entry URI; subclasses can override this + * if the service they implement has a convoluted API */ + return g_strdup (id); +} + +static gboolean +parse_json (GDataParsable *parsable, JsonReader *reader, gpointer user_data, GError **error) +{ + gboolean success; + GDataEntryPrivate *priv = GDATA_ENTRY (parsable)->priv; + + if (gdata_parser_string_from_json_member (reader, "title", P_DEFAULT | P_NO_DUPES, &(priv->title), &success, error) == TRUE || + gdata_parser_string_from_json_member (reader, "id", P_NON_EMPTY | P_NO_DUPES, &(priv->id), &success, error) == TRUE || + gdata_parser_string_from_json_member (reader, "description", P_NONE, &(priv->summary), &success, error) == TRUE || + gdata_parser_int64_time_from_json_member (reader, "updated", P_REQUIRED | P_NO_DUPES, &(priv->updated), &success, error) == TRUE || + gdata_parser_string_from_json_member (reader, "etag", P_NON_EMPTY | P_NO_DUPES, &(priv->etag), &success, error) == TRUE) { + return success; + } else if (g_strcmp0 (json_reader_get_member_name (reader), "selfLink") == 0) { + GDataLink *_link; + const gchar *uri; + + /* Empty URI? */ + uri = json_reader_get_string_value (reader); + if (uri == NULL || *uri == '\0') { + return gdata_parser_error_required_json_content_missing (reader, error); + } + + _link = gdata_link_new (uri, GDATA_LINK_SELF); + gdata_entry_add_link (GDATA_ENTRY (parsable), _link); + g_object_unref (_link); + + return TRUE; + } else if (g_strcmp0 (json_reader_get_member_name (reader), "kind") == 0) { + GDataCategory *category; + const gchar *kind; + + /* Empty kind? */ + kind = json_reader_get_string_value (reader); + if (kind == NULL || *kind == '\0') { + return gdata_parser_error_required_json_content_missing (reader, error); + } + + category = gdata_category_new (kind, "http://schemas.google.com/g/2005#kind", NULL); + gdata_entry_add_category (GDATA_ENTRY (parsable), category); + g_object_unref (category); + + return TRUE; + } + + return GDATA_PARSABLE_CLASS (gdata_entry_parent_class)->parse_json (parsable, reader, user_data, error); +} + +static void +get_json (GDataParsable *parsable, JsonBuilder *builder) +{ + GDataEntryPrivate *priv = GDATA_ENTRY (parsable)->priv; + GList *i; + GDataLink *_link; + + json_builder_set_member_name (builder, "title"); + json_builder_add_string_value (builder, priv->title); + + if (priv->id != NULL) { + json_builder_set_member_name (builder, "id"); + json_builder_add_string_value (builder, priv->id); + } + + if (priv->summary != NULL) { + json_builder_set_member_name (builder, "description"); + json_builder_add_string_value (builder, priv->summary); + } + + if (priv->updated != -1) { + gchar *updated = gdata_parser_int64_to_iso8601 (priv->updated); + json_builder_set_member_name (builder, "updated"); + json_builder_add_string_value (builder, updated); + g_free (updated); + } + + /* If we have a "kind" category, add that. */ + for (i = priv->categories; i != NULL; i = i->next) { + GDataCategory *category = GDATA_CATEGORY (i->data); + + if (g_strcmp0 (gdata_category_get_scheme (category), "http://schemas.google.com/g/2005#kind") == 0) { + json_builder_set_member_name (builder, "kind"); + json_builder_add_string_value (builder, gdata_category_get_term (category)); + } + } + + /* Add the ETag, if available. */ + if (gdata_entry_get_etag (GDATA_ENTRY (parsable)) != NULL) { + json_builder_set_member_name (builder, "etag"); + json_builder_add_string_value (builder, priv->etag); + } + + /* Add the self-link. */ + _link = gdata_entry_look_up_link (GDATA_ENTRY (parsable), GDATA_LINK_SELF); + if (_link != NULL) { + json_builder_set_member_name (builder, "selfLink"); + json_builder_add_string_value (builder, gdata_link_get_uri (_link)); + } +} + +/** + * gdata_entry_new: + * @id: (allow-none): the entry's ID, or %NULL + * + * Creates a new #GDataEntry with the given ID and default properties. + * + * Return value: a new #GDataEntry; unref with g_object_unref() + */ +GDataEntry * +gdata_entry_new (const gchar *id) +{ + GDataEntry *entry = GDATA_ENTRY (g_object_new (GDATA_TYPE_ENTRY, "id", id, NULL)); + + /* Set this here, as it interferes with P_NO_DUPES when parsing */ + entry->priv->title = g_strdup (""); /* title can't be NULL */ + + return entry; +} + +/** + * gdata_entry_get_title: + * @self: a #GDataEntry + * + * Returns the title of the entry. This will never be %NULL, but may be an empty string. + * + * Return value: the entry's title + */ +const gchar * +gdata_entry_get_title (GDataEntry *self) +{ + g_return_val_if_fail (GDATA_IS_ENTRY (self), NULL); + return self->priv->title; +} + +/** + * gdata_entry_set_title: + * @self: a #GDataEntry + * @title: (allow-none): the new entry title, or %NULL + * + * Sets the title of the entry. + */ +void +gdata_entry_set_title (GDataEntry *self, const gchar *title) +{ + g_return_if_fail (GDATA_IS_ENTRY (self)); + + g_free (self->priv->title); + self->priv->title = g_strdup (title); + g_object_notify (G_OBJECT (self), "title"); +} + +/** + * gdata_entry_get_summary: + * @self: a #GDataEntry + * + * Returns the summary of the entry. + * + * Return value: the entry's summary, or %NULL + * + * Since: 0.4.0 + */ +const gchar * +gdata_entry_get_summary (GDataEntry *self) +{ + g_return_val_if_fail (GDATA_IS_ENTRY (self), NULL); + return self->priv->summary; +} + +/** + * gdata_entry_set_summary: + * @self: a #GDataEntry + * @summary: (allow-none): the new entry summary, or %NULL + * + * Sets the summary of the entry. + * + * Since: 0.4.0 + */ +void +gdata_entry_set_summary (GDataEntry *self, const gchar *summary) +{ + g_return_if_fail (GDATA_IS_ENTRY (self)); + + g_free (self->priv->summary); + self->priv->summary = g_strdup (summary); + g_object_notify (G_OBJECT (self), "summary"); +} + +/** + * gdata_entry_get_id: + * @self: a #GDataEntry + * + * Returns the URN ID of the entry; a unique and permanent identifier for the object the entry represents. + * + * The ID may be %NULL if and only if the #GDataEntry has been newly created, and hasn't yet been inserted on the server. + * + * Return value: (nullable): the entry's ID, or %NULL + */ +const gchar * +gdata_entry_get_id (GDataEntry *self) +{ + gchar *id; + + g_return_val_if_fail (GDATA_IS_ENTRY (self), NULL); + + /* We have to get the actual property since GDataDocumentsEntry overrides it. We then store it in our own ID field so that we can + * free it later on. */ + g_object_get (G_OBJECT (self), "id", &id, NULL); + if (g_strcmp0 (id, self->priv->id) != 0) { + g_free (self->priv->id); + self->priv->id = id; + } else { + g_free (id); + } + + return self->priv->id; +} + +/** + * gdata_entry_get_etag: + * @self: a #GDataEntry + * + * Returns the ETag of the entry; a unique identifier for each version of the entry. For more information, see the + * online documentation. + * + * The ETag will never be empty; it's either %NULL or a valid ETag. + * + * Return value: (nullable): the entry's ETag, or %NULL + * + * Since: 0.2.0 + */ +const gchar * +gdata_entry_get_etag (GDataEntry *self) +{ + gchar *etag; + + g_return_val_if_fail (GDATA_IS_ENTRY (self), NULL); + + /* We have to check if the property's set since GDataAccessRule overrides it and sets it to always be NULL (since ACL entries don't support + * ETags, for some reason). */ + g_object_get (G_OBJECT (self), "etag", &etag, NULL); + if (etag != NULL) { + g_free (etag); + return self->priv->etag; + } + + return NULL; +} + +/* + * _gdata_entry_set_etag: + * @self: a #GDataEntry + * @etag: the new ETag value + * + * Sets the value of the #GDataEntry:etag property to @etag. + * + * Since: 0.17.2 + */ +void +_gdata_entry_set_etag (GDataEntry *self, const gchar *etag) +{ + g_return_if_fail (GDATA_IS_ENTRY (self)); + + g_free (self->priv->etag); + self->priv->etag = g_strdup (etag); +} + +/** + * gdata_entry_get_updated: + * @self: a #GDataEntry + * + * Gets the time the entry was last updated. + * + * Return value: the UNIX timestamp for the last update of the entry + */ +gint64 +gdata_entry_get_updated (GDataEntry *self) +{ + g_return_val_if_fail (GDATA_IS_ENTRY (self), -1); + return self->priv->updated; +} + +/* + * _gdata_entry_set_updated: + * @self: a #GDataEntry + * @updated: the new updated value + * + * Sets the value of the #GDataEntry:updated property to @updated. + * + * Since: 0.6.0 + */ +void +_gdata_entry_set_updated (GDataEntry *self, gint64 updated) +{ + g_return_if_fail (GDATA_IS_ENTRY (self)); + self->priv->updated = updated; +} + +/* + * _gdata_entry_set_published: + * @self: a #GDataEntry + * @updated: the new published value + * + * Sets the value of the #GDataEntry:published property to @published. + * + * Since: 0.17.0 + */ +void +_gdata_entry_set_published (GDataEntry *self, gint64 published) +{ + g_return_if_fail (GDATA_IS_ENTRY (self)); + self->priv->published = published; +} + +/* + * _gdata_entry_set_id: + * @self: a #GDataEntry + * @id: (nullable): the new ID + * + * Sets the value of the #GDataEntry:id property to @id. + * + * Since: 0.17.0 + */ +void +_gdata_entry_set_id (GDataEntry *self, const gchar *id) +{ + g_return_if_fail (GDATA_IS_ENTRY (self)); + + g_free (self->priv->id); + self->priv->id = g_strdup (id); +} + +/** + * gdata_entry_get_published: + * @self: a #GDataEntry + * + * Gets the time the entry was originally published. + * + * Return value: the UNIX timestamp for the original publish time of the entry + */ +gint64 +gdata_entry_get_published (GDataEntry *self) +{ + g_return_val_if_fail (GDATA_IS_ENTRY (self), -1); + return self->priv->published; +} + +/** + * gdata_entry_add_category: + * @self: a #GDataEntry + * @category: a #GDataCategory to add + * + * Adds @category to the list of categories in the given #GDataEntry, and increments its reference count. + * + * Duplicate categories will not be added to the list. + */ +void +gdata_entry_add_category (GDataEntry *self, GDataCategory *category) +{ + g_return_if_fail (GDATA_IS_ENTRY (self)); + g_return_if_fail (GDATA_IS_CATEGORY (category)); + + /* Check to see if it's a kind category and if it matches the entry's predetermined kind */ + if (g_strcmp0 (gdata_category_get_scheme (category), "http://schemas.google.com/g/2005#kind") == 0) { + GDataEntryClass *klass = GDATA_ENTRY_GET_CLASS (self); + GList *element; + + if (klass->kind_term != NULL && g_strcmp0 (gdata_category_get_term (category), klass->kind_term) != 0) { + /* This used to make sense as a warning, but the new + * JSON APIs use a lot of different kinds for very + * highly related JSON schemas, which libgdata uses a + * single class for…so it makes less sense now. */ + g_debug ("Adding a kind category term, '%s', to an entry of kind '%s'.", + gdata_category_get_term (category), klass->kind_term); + } + + /* If it is a kind category, remove the entry’s existing kind category to allow the new one + * to be added. This is necessary because the existing category was set in + * gdata_entry_constructed() and might not contain all the attributes of the actual XML + * category. + * + * See: https://bugzilla.gnome.org/show_bug.cgi?id=707477 */ + element = g_list_find_custom (self->priv->categories, category, (GCompareFunc) gdata_comparable_compare); + if (element != NULL) { + g_assert (GDATA_IS_CATEGORY (element->data)); + g_object_unref (element->data); + self->priv->categories = g_list_delete_link (self->priv->categories, element); + } + } + + /* Add the category if we don't already have it */ + if (g_list_find_custom (self->priv->categories, category, (GCompareFunc) gdata_comparable_compare) == NULL) + self->priv->categories = g_list_prepend (self->priv->categories, g_object_ref (category)); +} + +/** + * gdata_entry_get_categories: + * @self: a #GDataEntry + * + * Gets a list of the #GDataCategorys containing this entry. + * + * Return value: (element-type GData.Category) (transfer none): a #GList of #GDataCategorys + * + * Since: 0.2.0 + */ +GList * +gdata_entry_get_categories (GDataEntry *self) +{ + g_return_val_if_fail (GDATA_IS_ENTRY (self), NULL); + return self->priv->categories; +} + +/** + * gdata_entry_get_authors: + * @self: a #GDataEntry + * + * Gets a list of the #GDataAuthors for this entry. + * + * Return value: (element-type GData.Author) (transfer none): a #GList of #GDataAuthors + * + * Since: 0.7.0 + */ +GList * +gdata_entry_get_authors (GDataEntry *self) +{ + g_return_val_if_fail (GDATA_IS_ENTRY (self), NULL); + return self->priv->authors; +} + +/** + * gdata_entry_get_content: + * @self: a #GDataEntry + * + * Returns the textual content in this entry. If the content in this entry is pointed to by a URI, %NULL will be returned; the content URI will be + * returned by gdata_entry_get_content_uri(). + * + * Return value: the entry's content, or %NULL + */ +const gchar * +gdata_entry_get_content (GDataEntry *self) +{ + g_return_val_if_fail (GDATA_IS_ENTRY (self), NULL); + return (self->priv->content_is_uri == FALSE) ? self->priv->content : NULL; +} + +/** + * gdata_entry_set_content: + * @self: a #GDataEntry + * @content: (allow-none): the new content for the entry, or %NULL + * + * Sets the entry's content to @content. This unsets #GDataEntry:content-uri. + */ +void +gdata_entry_set_content (GDataEntry *self, const gchar *content) +{ + g_return_if_fail (GDATA_IS_ENTRY (self)); + + g_free (self->priv->content); + self->priv->content = g_strdup (content); + self->priv->content_is_uri = FALSE; + + g_object_freeze_notify (G_OBJECT (self)); + g_object_notify (G_OBJECT (self), "content"); + g_object_notify (G_OBJECT (self), "content-uri"); + g_object_thaw_notify (G_OBJECT (self)); +} + +/** + * gdata_entry_get_content_uri: + * @self: a #GDataEntry + * + * Returns a URI pointing to the content of this entry. If the content in this entry is stored directly, %NULL will be returned; the content will be + * returned by gdata_entry_get_content(). + * + * Return value: a URI pointing to the entry's content, or %NULL + * + * Since: 0.7.0 + */ +const gchar * +gdata_entry_get_content_uri (GDataEntry *self) +{ + g_return_val_if_fail (GDATA_IS_ENTRY (self), NULL); + return (self->priv->content_is_uri == TRUE) ? self->priv->content : NULL; +} + +/** + * gdata_entry_set_content_uri: + * @self: a #GDataEntry + * @content_uri: (allow-none): the new URI pointing to the content for the entry, or %NULL + * + * Sets the URI pointing to the entry's content to @content. This unsets #GDataEntry:content. + * + * Since: 0.7.0 + */ +void +gdata_entry_set_content_uri (GDataEntry *self, const gchar *content_uri) +{ + g_return_if_fail (GDATA_IS_ENTRY (self)); + + g_free (self->priv->content); + self->priv->content = g_strdup (content_uri); + self->priv->content_is_uri = TRUE; + + g_object_freeze_notify (G_OBJECT (self)); + g_object_notify (G_OBJECT (self), "content"); + g_object_notify (G_OBJECT (self), "content-uri"); + g_object_thaw_notify (G_OBJECT (self)); +} + +/** + * gdata_entry_add_link: + * @self: a #GDataEntry + * @_link: a #GDataLink to add + * + * Adds @_link to the list of links in the given #GDataEntry and increments its reference count. + * + * Duplicate links will not be added to the list. + */ +void +gdata_entry_add_link (GDataEntry *self, GDataLink *_link) +{ + /* TODO: More link API */ + g_return_if_fail (GDATA_IS_ENTRY (self)); + g_return_if_fail (GDATA_IS_LINK (_link)); + + if (g_list_find_custom (self->priv->links, _link, (GCompareFunc) gdata_comparable_compare) == NULL) + self->priv->links = g_list_prepend (self->priv->links, g_object_ref (_link)); +} + +/** + * gdata_entry_remove_link: + * @self: a #GDataEntry + * @_link: a #GDataLink to remove + * + * Removes @_link from the list of links in the given #GDataEntry and decrements its reference count (since the #GDataEntry held a reference to it + * while it was in the list). + * + * Return value: %TRUE if @_link was found in the #GDataEntry and removed, %FALSE if it was not found + * + * Since: 0.10.0 + */ +gboolean +gdata_entry_remove_link (GDataEntry *self, GDataLink *_link) +{ + GList *i; + + g_return_val_if_fail (GDATA_IS_ENTRY (self), FALSE); + g_return_val_if_fail (GDATA_IS_LINK (_link), FALSE); + + i = g_list_find_custom (self->priv->links, _link, (GCompareFunc) gdata_comparable_compare); + + if (i == NULL) { + return FALSE; + } + + self->priv->links = g_list_delete_link (self->priv->links, i); + g_object_unref (_link); + + return TRUE; +} + +static gint +link_compare_cb (const GDataLink *_link, const gchar *rel) +{ + return strcmp (gdata_link_get_relation_type ((GDataLink*) _link), rel); +} + +/** + * gdata_entry_look_up_link: + * @self: a #GDataEntry + * @rel: the value of the rel attribute of the desired link + * + * Looks up a link by relation type from the list of links in the entry. If the link has one of the standard Atom relation types, + * use one of the defined @rel values, instead of a static string. e.g. %GDATA_LINK_EDIT or %GDATA_LINK_SELF. + * + * In the rare event of requiring a list of links with the same @rel value, use gdata_entry_look_up_links(). + * + * Return value: (transfer none): a #GDataLink, or %NULL if one was not found + * + * Since: 0.1.1 + */ +GDataLink * +gdata_entry_look_up_link (GDataEntry *self, const gchar *rel) +{ + GList *element; + + g_return_val_if_fail (GDATA_IS_ENTRY (self), NULL); + g_return_val_if_fail (rel != NULL, NULL); + + element = g_list_find_custom (self->priv->links, rel, (GCompareFunc) link_compare_cb); + if (element == NULL) + return NULL; + return GDATA_LINK (element->data); +} + +/** + * gdata_entry_look_up_links: + * @self: a #GDataEntry + * @rel: the value of the rel attribute of the desired links + * + * Looks up a list of links by relation type from the list of links in the entry. If the links have one of the standard Atom + * relation types, use one of the defined @rel values, instead of a static string. e.g. %GDATA_LINK_EDIT or %GDATA_LINK_SELF. + * + * If you will only use the first link found, consider calling gdata_entry_look_up_link() instead. + * + * Return value: (element-type GData.Link) (transfer container): a #GList of #GDataLinks, or %NULL if none were found; free the list with + * g_list_free() + * + * Since: 0.4.0 + */ +GList * +gdata_entry_look_up_links (GDataEntry *self, const gchar *rel) +{ + GList *i, *results = NULL; + + g_return_val_if_fail (GDATA_IS_ENTRY (self), NULL); + g_return_val_if_fail (rel != NULL, NULL); + + for (i = self->priv->links; i != NULL; i = i->next) { + const gchar *relation_type = gdata_link_get_relation_type (((GDataLink*) i->data)); + if (strcmp (relation_type, rel) == 0) + results = g_list_prepend (results, i->data); + } + + return g_list_reverse (results); +} + +/** + * gdata_entry_add_author: + * @self: a #GDataEntry + * @author: a #GDataAuthor to add + * + * Adds @author to the list of authors in the given #GDataEntry and increments its reference count. + * + * Duplicate authors will not be added to the list. + */ +void +gdata_entry_add_author (GDataEntry *self, GDataAuthor *author) +{ + /* TODO: More author API */ + g_return_if_fail (GDATA_IS_ENTRY (self)); + g_return_if_fail (GDATA_IS_AUTHOR (author)); + + if (g_list_find_custom (self->priv->authors, author, (GCompareFunc) gdata_comparable_compare) == NULL) + self->priv->authors = g_list_prepend (self->priv->authors, g_object_ref (author)); +} + +/** + * gdata_entry_is_inserted: + * @self: a #GDataEntry + * + * Returns whether the entry is marked as having been inserted on (uploaded to) the server already. + * + * Return value: %TRUE if the entry has been inserted already, %FALSE otherwise + */ +gboolean +gdata_entry_is_inserted (GDataEntry *self) +{ + g_return_val_if_fail (GDATA_IS_ENTRY (self), FALSE); + + if (self->priv->id != NULL || self->priv->updated != -1) + return TRUE; + return FALSE; +} + +/** + * gdata_entry_get_rights: + * @self: a #GDataEntry + * + * Returns the rights pertaining to the entry, or %NULL if not set. + * + * Return value: the entry's rights information + * + * Since: 0.5.0 + */ +const gchar * +gdata_entry_get_rights (GDataEntry *self) +{ + g_return_val_if_fail (GDATA_IS_ENTRY (self), NULL); + return self->priv->rights; +} + +/** + * gdata_entry_set_rights: + * @self: a #GDataEntry + * @rights: (allow-none): the new rights, or %NULL + * + * Sets the rights for this entry. + * + * Since: 0.5.0 + */ +void +gdata_entry_set_rights (GDataEntry *self, const gchar *rights) +{ + g_return_if_fail (GDATA_IS_ENTRY (self)); + + g_free (self->priv->rights); + self->priv->rights = g_strdup (rights); + g_object_notify (G_OBJECT (self), "rights"); +} + +/* + * _gdata_entry_set_batch_data: + * @self: a #GDataEntry + * @id: the batch operation ID + * @type: the type of batch operation being performed on the #GDataEntry + * + * Sets the batch operation data needed when outputting the XML for a #GDataEntry to be put into a batch operation feed. + * + * Since: 0.6.0 + */ +void +_gdata_entry_set_batch_data (GDataEntry *self, guint id, GDataBatchOperationType type) +{ + g_return_if_fail (GDATA_IS_ENTRY (self)); + + self->priv->batch_id = id; + self->priv->batch_operation_type = type; +} diff --git a/gdata/gdata-entry.h b/gdata/gdata-entry.h new file mode 100644 index 0000000..5d878c9 --- /dev/null +++ b/gdata/gdata-entry.h @@ -0,0 +1,111 @@ +/* -*- Mode: C; indent-tabs-mode: t; c-basic-offset: 8; tab-width: 8 -*- */ +/* + * GData Client + * Copyright (C) Philip Withnall 2008–2010 + * + * GData Client is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * GData Client is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with GData Client. If not, see . + */ + +#ifndef GDATA_ENTRY_H +#define GDATA_ENTRY_H + +#include +#include + +#include +#include +#include +#include + +G_BEGIN_DECLS + +#define GDATA_TYPE_ENTRY (gdata_entry_get_type ()) +#define GDATA_ENTRY(o) (G_TYPE_CHECK_INSTANCE_CAST ((o), GDATA_TYPE_ENTRY, GDataEntry)) +#define GDATA_ENTRY_CLASS(k) (G_TYPE_CHECK_CLASS_CAST((k), GDATA_TYPE_ENTRY, GDataEntryClass)) +#define GDATA_IS_ENTRY(o) (G_TYPE_CHECK_INSTANCE_TYPE ((o), GDATA_TYPE_ENTRY)) +#define GDATA_IS_ENTRY_CLASS(k) (G_TYPE_CHECK_CLASS_TYPE ((k), GDATA_TYPE_ENTRY)) +#define GDATA_ENTRY_GET_CLASS(o) (G_TYPE_INSTANCE_GET_CLASS ((o), GDATA_TYPE_ENTRY, GDataEntryClass)) + +typedef struct _GDataEntryPrivate GDataEntryPrivate; + +/** + * GDataEntry: + * + * All the fields in the #GDataEntry structure are private and should never be accessed directly. + */ +typedef struct { + GDataParsable parent; + GDataEntryPrivate *priv; +} GDataEntry; + +/** + * GDataEntryClass: + * @parent: the parent class + * @get_entry_uri: a function to build the entry URI for the entry, given its entry ID; free the URI with g_free() + * @kind_term: the term for this entry's kind category (see the + * documentation on kinds) + * + * The class structure for the #GDataEntry type. + */ +typedef struct { + GDataParsableClass parent; + + gchar *(*get_entry_uri) (const gchar *id); /* G_GNUC_WARN_UNUSED_RESULT G_GNUC_MALLOC */ + const gchar *kind_term; + + /*< private >*/ + /* Padding for future expansion */ + void (*_g_reserved0) (void); + void (*_g_reserved1) (void); + void (*_g_reserved2) (void); + void (*_g_reserved3) (void); + void (*_g_reserved4) (void); + void (*_g_reserved5) (void); + void (*_g_reserved6) (void); + void (*_g_reserved7) (void); +} GDataEntryClass; + +GType gdata_entry_get_type (void) G_GNUC_CONST; +G_DEFINE_AUTOPTR_CLEANUP_FUNC (GDataEntry, g_object_unref) + +GDataEntry *gdata_entry_new (const gchar *id) G_GNUC_WARN_UNUSED_RESULT G_GNUC_MALLOC; + +const gchar *gdata_entry_get_title (GDataEntry *self) G_GNUC_PURE; +void gdata_entry_set_title (GDataEntry *self, const gchar *title); +const gchar *gdata_entry_get_summary (GDataEntry *self) G_GNUC_PURE; +void gdata_entry_set_summary (GDataEntry *self, const gchar *summary); +const gchar *gdata_entry_get_id (GDataEntry *self) G_GNUC_PURE; +const gchar *gdata_entry_get_etag (GDataEntry *self) G_GNUC_PURE; +gint64 gdata_entry_get_updated (GDataEntry *self); +gint64 gdata_entry_get_published (GDataEntry *self); +void gdata_entry_add_category (GDataEntry *self, GDataCategory *category); +GList *gdata_entry_get_categories (GDataEntry *self) G_GNUC_PURE; +const gchar *gdata_entry_get_content (GDataEntry *self) G_GNUC_PURE; +void gdata_entry_set_content (GDataEntry *self, const gchar *content); +const gchar *gdata_entry_get_content_uri (GDataEntry *self) G_GNUC_PURE; +void gdata_entry_set_content_uri (GDataEntry *self, const gchar *content_uri); +void gdata_entry_add_link (GDataEntry *self, GDataLink *_link); +gboolean gdata_entry_remove_link (GDataEntry *self, GDataLink *_link); +GDataLink *gdata_entry_look_up_link (GDataEntry *self, const gchar *rel) G_GNUC_PURE; +GList *gdata_entry_look_up_links (GDataEntry *self, const gchar *rel) G_GNUC_WARN_UNUSED_RESULT G_GNUC_MALLOC; +void gdata_entry_add_author (GDataEntry *self, GDataAuthor *author); +GList *gdata_entry_get_authors (GDataEntry *self) G_GNUC_PURE; +const gchar *gdata_entry_get_rights (GDataEntry *self) G_GNUC_PURE; +void gdata_entry_set_rights (GDataEntry *self, const gchar *rights); + +gboolean gdata_entry_is_inserted (GDataEntry *self) G_GNUC_PURE; + +G_END_DECLS + +#endif /* !GDATA_ENTRY_H */ diff --git a/gdata/gdata-feed.c b/gdata/gdata-feed.c new file mode 100644 index 0000000..c1e6aa9 --- /dev/null +++ b/gdata/gdata-feed.c @@ -0,0 +1,1175 @@ +/* -*- Mode: C; indent-tabs-mode: t; c-basic-offset: 8; tab-width: 8 -*- */ +/* + * GData Client + * Copyright (C) Philip Withnall 2008–2010 + * Copyright (C) Red Hat, Inc. 2015 + * + * GData Client is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * GData Client is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with GData Client. If not, see . + */ + +/** + * SECTION:gdata-feed + * @short_description: GData feed object + * @stability: Stable + * @include: gdata/gdata-feed.h + * + * #GDataFeed is a list of entries (#GDataEntry) returned as the result of a query to a #GDataService, or given as the input to another + * operation on the online service. It also has pieces of data associated with the query on the #GDataService, such as the query title + * or timestamp when it was last updated. + * + * Each #GDataEntry represents a single object on the online service, such as a playlist, video or calendar entry, and the #GDataFeed + * represents a collection of similar objects. + */ + +#include +#include +#include +#include +#include +#include + +#include "gdata-feed.h" +#include "gdata-entry.h" +#include "gdata-types.h" +#include "gdata-private.h" +#include "gdata-service.h" +#include "gdata-parsable.h" + +static void gdata_feed_dispose (GObject *object); +static void gdata_feed_finalize (GObject *object); +static void gdata_feed_get_property (GObject *object, guint property_id, GValue *value, GParamSpec *pspec); +static gboolean pre_parse_xml (GDataParsable *parsable, xmlDoc *doc, xmlNode *root_node, gpointer user_data, GError **error); +static gboolean parse_xml (GDataParsable *parsable, xmlDoc *doc, xmlNode *node, gpointer user_data, GError **error); +static gboolean post_parse_xml (GDataParsable *parsable, gpointer user_data, GError **error); +static void get_xml (GDataParsable *parsable, GString *xml_string); +static void get_namespaces (GDataParsable *parsable, GHashTable *namespaces); + +static void _gdata_feed_add_category (GDataFeed *self, GDataCategory *category); +static void _gdata_feed_add_author (GDataFeed *self, GDataAuthor *author); + +static gboolean parse_json (GDataParsable *parsable, JsonReader *reader, gpointer user_data, GError **error); +static gboolean post_parse_json (GDataParsable *parsable, gpointer user_data, GError **error); + +struct _GDataFeedPrivate { + GList *entries; + gchar *title; + gchar *subtitle; + gchar *id; + gchar *etag; + gint64 updated; + GList *categories; /* GDataCategory */ + gchar *logo; + gchar *icon; + GList *links; /* GDataLink */ + GList *authors; /* GDataAuthor */ + GDataGenerator *generator; + guint items_per_page; + guint start_index; + guint total_results; + gchar *rights; + gchar *next_page_token; +}; + +enum { + PROP_ID = 1, + PROP_ETAG, + PROP_UPDATED, + PROP_TITLE, + PROP_SUBTITLE, + PROP_LOGO, + PROP_ICON, + PROP_GENERATOR, + PROP_ITEMS_PER_PAGE, + PROP_START_INDEX, + PROP_TOTAL_RESULTS, + PROP_RIGHTS, + PROP_NEXT_PAGE_TOKEN, +}; + +G_DEFINE_TYPE (GDataFeed, gdata_feed, GDATA_TYPE_PARSABLE) + +static void +gdata_feed_class_init (GDataFeedClass *klass) +{ + GObjectClass *gobject_class = G_OBJECT_CLASS (klass); + GDataParsableClass *parsable_class = GDATA_PARSABLE_CLASS (klass); + + g_type_class_add_private (klass, sizeof (GDataFeedPrivate)); + + gobject_class->get_property = gdata_feed_get_property; + gobject_class->dispose = gdata_feed_dispose; + gobject_class->finalize = gdata_feed_finalize; + + parsable_class->pre_parse_xml = pre_parse_xml; + parsable_class->parse_xml = parse_xml; + parsable_class->post_parse_xml = post_parse_xml; + parsable_class->get_xml = get_xml; + parsable_class->get_namespaces = get_namespaces; + parsable_class->element_name = "feed"; + + parsable_class->parse_json = parse_json; + parsable_class->post_parse_json = post_parse_json; + + /** + * GDataFeed:title: + * + * The title of the feed. + * + * API reference: + * atom:title + */ + g_object_class_install_property (gobject_class, PROP_TITLE, + g_param_spec_string ("title", + "Title", "The title of the feed.", + NULL, + G_PARAM_READABLE | G_PARAM_STATIC_STRINGS)); + + /** + * GDataFeed:subtitle: + * + * The subtitle of the feed. + * + * API reference: atom:subtitle + */ + g_object_class_install_property (gobject_class, PROP_SUBTITLE, + g_param_spec_string ("subtitle", + "Subtitle", "The subtitle of the feed.", + NULL, + G_PARAM_READABLE | G_PARAM_STATIC_STRINGS)); + + /** + * GDataFeed:id: + * + * The unique and permanent URN ID for the feed. + * + * API reference: atom:id + */ + g_object_class_install_property (gobject_class, PROP_ID, + g_param_spec_string ("id", + "ID", "The unique and permanent URN ID for the feed.", + NULL, + G_PARAM_READABLE | G_PARAM_STATIC_STRINGS)); + + /** + * GDataFeed:etag: + * + * The unique ETag for this version of the feed. See the + * online documentation for + * more information. + * + * Since: 0.2.0 + */ + g_object_class_install_property (gobject_class, PROP_ETAG, + g_param_spec_string ("etag", + "ETag", "The unique ETag for this version of the feed.", + NULL, + G_PARAM_READABLE | G_PARAM_STATIC_STRINGS)); + + /** + * GDataFeed:updated: + * + * The time the feed was last updated. + * + * API reference: + * atom:updated + */ + g_object_class_install_property (gobject_class, PROP_UPDATED, + g_param_spec_int64 ("updated", + "Updated", "The time the feed was last updated.", + 0, G_MAXINT64, 0, + G_PARAM_READABLE | G_PARAM_STATIC_STRINGS)); + + /** + * GDataFeed:logo: + * + * The URI of a logo for the feed. + * + * API reference: atom:logo + */ + g_object_class_install_property (gobject_class, PROP_LOGO, + g_param_spec_string ("logo", + "Logo", "The URI of a logo for the feed.", + NULL, + G_PARAM_READABLE | G_PARAM_STATIC_STRINGS)); + + /** + * GDataFeed:icon: + * + * The URI of an icon for the feed. + * + * API reference: + * atom:icon + * + * Since: 0.6.0 + */ + g_object_class_install_property (gobject_class, PROP_ICON, + g_param_spec_string ("icon", + "Icon", "The URI of an icon for the feed.", + NULL, + G_PARAM_READABLE | G_PARAM_STATIC_STRINGS)); + + /** + * GDataFeed:generator: + * + * Details of the software used to generate the feed. + * + * API reference: + * atom:generator + */ + g_object_class_install_property (gobject_class, PROP_GENERATOR, + g_param_spec_object ("generator", + "Generator", "Details of the software used to generate the feed.", + GDATA_TYPE_GENERATOR, + G_PARAM_READABLE | G_PARAM_STATIC_STRINGS)); + + /** + * GDataFeed:rights: + * + * The ownership rights pertaining to the entire feed. + * + * For more information, see the Atom specification. + * + * Since: 0.7.0 + */ + g_object_class_install_property (gobject_class, PROP_RIGHTS, + g_param_spec_string ("rights", + "Rights", "The ownership rights pertaining to the entire feed.", + NULL, + G_PARAM_READABLE | G_PARAM_STATIC_STRINGS)); + + /** + * GDataFeed:items-per-page: + * + * The number of items per results page feed. + * + * API reference: + * + * openSearch:itemsPerPage + */ + g_object_class_install_property (gobject_class, PROP_ITEMS_PER_PAGE, + g_param_spec_uint ("items-per-page", + "Items per page", "The number of items per results page feed.", + 0, G_MAXUINT, 0, + G_PARAM_READABLE | G_PARAM_STATIC_STRINGS)); + + /** + * GDataFeed:start-index: + * + * The one-based index of the first item in the results feed. + * + * This should not be used manually for pagination. Instead, use a #GDataQuery and call its gdata_query_next_page() + * or gdata_query_previous_page() functions before making the query to the service. + * + * API reference: + * openSearch:startIndex + */ + g_object_class_install_property (gobject_class, PROP_START_INDEX, + g_param_spec_uint ("start-index", + "Start index", "The one-based index of the first item in the results feed.", + 1, G_MAXUINT, 1, + G_PARAM_READABLE | G_PARAM_STATIC_STRINGS)); + + /** + * GDataFeed:total-results: + * + * The number of items in the result set for the feed, including those on other pages. If this is zero, the total number is unknown. + * + * This should not be used manually for pagination. Instead, use a #GDataQuery and call its gdata_query_next_page() + * or gdata_query_previous_page() functions before making the query to the service. + * + * API reference: + * + * openSearch:totalResults + */ + g_object_class_install_property (gobject_class, PROP_TOTAL_RESULTS, + g_param_spec_uint ("total-results", + "Total results", "The total number of results in the feed.", + 0, 1000000, 0, + G_PARAM_READABLE | G_PARAM_STATIC_STRINGS)); + + /** + * GDataFeed:next-page-token: + * + * The next page token for feeds. Pass this to + * gdata_query_set_page_token() to advance to the next page when + * querying APIs which use page tokens rather than page numbers or + * offsets. + * + * Since: 0.17.7 + */ + g_object_class_install_property (gobject_class, PROP_NEXT_PAGE_TOKEN, + g_param_spec_string ("next-page-token", + "Next page token", "The next page token for feeds.", + NULL, + G_PARAM_READABLE | G_PARAM_STATIC_STRINGS)); +} + +static void +gdata_feed_init (GDataFeed *self) +{ + self->priv = G_TYPE_INSTANCE_GET_PRIVATE (self, GDATA_TYPE_FEED, GDataFeedPrivate); + self->priv->updated = -1; +} + +static void +gdata_feed_dispose (GObject *object) +{ + GDataFeedPrivate *priv = GDATA_FEED (object)->priv; + + g_list_free_full (priv->entries, g_object_unref); + priv->entries = NULL; + + g_list_free_full (priv->categories, g_object_unref); + priv->categories = NULL; + + g_list_free_full (priv->links, g_object_unref); + priv->links = NULL; + + g_list_free_full (priv->authors, g_object_unref); + priv->authors = NULL; + + if (priv->generator != NULL) + g_object_unref (priv->generator); + priv->generator = NULL; + + /* Chain up to the parent class */ + G_OBJECT_CLASS (gdata_feed_parent_class)->dispose (object); +} + +static void +gdata_feed_finalize (GObject *object) +{ + GDataFeedPrivate *priv = GDATA_FEED (object)->priv; + + g_free (priv->title); + g_free (priv->subtitle); + g_free (priv->id); + g_free (priv->etag); + g_free (priv->logo); + g_free (priv->icon); + g_free (priv->rights); + g_free (priv->next_page_token); + + /* Chain up to the parent class */ + G_OBJECT_CLASS (gdata_feed_parent_class)->finalize (object); +} + +static void +gdata_feed_get_property (GObject *object, guint property_id, GValue *value, GParamSpec *pspec) +{ + GDataFeedPrivate *priv = GDATA_FEED (object)->priv; + + switch (property_id) { + case PROP_TITLE: + g_value_set_string (value, priv->title); + break; + case PROP_SUBTITLE: + g_value_set_string (value, priv->subtitle); + break; + case PROP_ID: + g_value_set_string (value, priv->id); + break; + case PROP_ETAG: + g_value_set_string (value, priv->etag); + break; + case PROP_UPDATED: + g_value_set_int64 (value, priv->updated); + break; + case PROP_LOGO: + g_value_set_string (value, priv->logo); + break; + case PROP_ICON: + g_value_set_string (value, priv->icon); + break; + case PROP_GENERATOR: + g_value_set_object (value, priv->generator); + break; + case PROP_RIGHTS: + g_value_set_string (value, priv->rights); + break; + case PROP_ITEMS_PER_PAGE: + g_value_set_uint (value, priv->items_per_page); + break; + case PROP_START_INDEX: + g_value_set_uint (value, priv->start_index); + break; + case PROP_TOTAL_RESULTS: + g_value_set_uint (value, priv->total_results); + break; + case PROP_NEXT_PAGE_TOKEN: + g_value_set_string (value, priv->next_page_token); + break; + default: + /* We don't have any other property... */ + G_OBJECT_WARN_INVALID_PROPERTY_ID (object, property_id, pspec); + break; + } +} + +typedef struct { + GType entry_type; + GDataQueryProgressCallback progress_callback; + gpointer progress_user_data; + guint entry_i; +} ParseData; + +static gboolean +pre_parse_xml (GDataParsable *parsable, xmlDoc *doc, xmlNode *root_node, gpointer user_data, GError **error) +{ + /* Extract the ETag */ + GDATA_FEED (parsable)->priv->etag = (gchar*) xmlGetProp (root_node, (xmlChar*) "etag"); + return TRUE; +} + +typedef struct { + GDataQueryProgressCallback progress_callback; + gpointer progress_user_data; + GDataEntry *entry; + guint entry_i; + guint total_results; +} ProgressCallbackData; + +static gboolean +parse_xml (GDataParsable *parsable, xmlDoc *doc, xmlNode *node, gpointer user_data, GError **error) +{ + gboolean success; + GDataFeed *self = GDATA_FEED (parsable); + ParseData *data = user_data; + + if (gdata_parser_is_namespace (node, "http://www.w3.org/2005/Atom") == TRUE) { + if (xmlStrcmp (node->name, (xmlChar*) "entry") == 0) { + /* atom:entry */ + GDataEntry *entry; + GType entry_type; + + /* Allow @data to be %NULL, and assume we're parsing a vanilla feed, so that we can test #GDataFeed in tests/general.c. + * A little hacky, but not too much so, and valuable for testing. */ + entry_type = (data != NULL) ? data->entry_type : GDATA_TYPE_ENTRY; + entry = GDATA_ENTRY (_gdata_parsable_new_from_xml_node (entry_type, doc, node, NULL, error)); + if (entry == NULL) + return FALSE; + + /* Calls the callbacks in the main thread */ + if (data != NULL) + _gdata_feed_call_progress_callback (self, data, entry); + _gdata_feed_add_entry (self, entry); + g_object_unref (entry); + } else if (gdata_parser_string_from_element (node, "title", P_DEFAULT | P_NO_DUPES, &(self->priv->title), &success, error) == TRUE || + gdata_parser_string_from_element (node, "subtitle", P_NO_DUPES, &(self->priv->subtitle), &success, error) == TRUE || + gdata_parser_string_from_element (node, "id", P_REQUIRED | P_NON_EMPTY | P_NO_DUPES, + &(self->priv->id), &success, error) == TRUE || + gdata_parser_string_from_element (node, "logo", P_NO_DUPES, &(self->priv->logo), &success, error) == TRUE || + gdata_parser_string_from_element (node, "icon", P_NO_DUPES, &(self->priv->icon), &success, error) == TRUE || + gdata_parser_object_from_element_setter (node, "category", P_REQUIRED, GDATA_TYPE_CATEGORY, + _gdata_feed_add_category, self, &success, error) == TRUE || + gdata_parser_object_from_element_setter (node, "link", P_REQUIRED, GDATA_TYPE_LINK, + _gdata_feed_add_link, self, &success, error) == TRUE || + gdata_parser_object_from_element_setter (node, "author", P_REQUIRED, GDATA_TYPE_AUTHOR, + _gdata_feed_add_author, self, &success, error) == TRUE || + gdata_parser_object_from_element (node, "generator", P_REQUIRED | P_NO_DUPES, GDATA_TYPE_GENERATOR, + &(self->priv->generator), &success, error) == TRUE || + gdata_parser_int64_time_from_element (node, "updated", P_REQUIRED | P_NO_DUPES, + &(self->priv->updated), &success, error) == TRUE || + gdata_parser_string_from_element (node, "rights", P_NONE, &(self->priv->rights), &success, error) == TRUE) { + return success; + } else { + return GDATA_PARSABLE_CLASS (gdata_feed_parent_class)->parse_xml (parsable, doc, node, user_data, error); + } + } else if (gdata_parser_is_namespace (node, "http://a9.com/-/spec/opensearch/1.1/") == TRUE) { + if (xmlStrcmp (node->name, (xmlChar*) "totalResults") == 0) { + /* openSearch:totalResults */ + xmlChar *total_results_string; + + /* Duplicate checking */ + if (self->priv->total_results != 0) + return gdata_parser_error_duplicate_element (node, error); + + /* Parse the number */ + total_results_string = xmlNodeListGetString (doc, node->children, TRUE); + if (total_results_string == NULL) + return gdata_parser_error_required_content_missing (node, error); + + self->priv->total_results = g_ascii_strtoull ((gchar*) total_results_string, NULL, 10); + xmlFree (total_results_string); + } else if (xmlStrcmp (node->name, (xmlChar*) "startIndex") == 0) { + /* openSearch:startIndex */ + xmlChar *start_index_string; + + /* Duplicate checking */ + if (self->priv->start_index != 0) + return gdata_parser_error_duplicate_element (node, error); + + /* Parse the number */ + start_index_string = xmlNodeListGetString (doc, node->children, TRUE); + if (start_index_string == NULL) + return gdata_parser_error_required_content_missing (node, error); + + self->priv->start_index = g_ascii_strtoull ((gchar*) start_index_string, NULL, 10); + xmlFree (start_index_string); + } else if (xmlStrcmp (node->name, (xmlChar*) "itemsPerPage") == 0) { + /* openSearch:itemsPerPage */ + xmlChar *items_per_page_string; + + /* Duplicate checking */ + if (self->priv->items_per_page != 0) + return gdata_parser_error_duplicate_element (node, error); + + /* Parse the number */ + items_per_page_string = xmlNodeListGetString (doc, node->children, TRUE); + if (items_per_page_string == NULL) + return gdata_parser_error_required_content_missing (node, error); + + self->priv->items_per_page = g_ascii_strtoull ((gchar*) items_per_page_string, NULL, 10); + xmlFree (items_per_page_string); + } else { + return GDATA_PARSABLE_CLASS (gdata_feed_parent_class)->parse_xml (parsable, doc, node, user_data, error); + } + } else { + return GDATA_PARSABLE_CLASS (gdata_feed_parent_class)->parse_xml (parsable, doc, node, user_data, error); + } + + return TRUE; +} + +static gboolean +post_parse_xml (GDataParsable *parsable, gpointer user_data, GError **error) +{ + GDataFeedPrivate *priv = GDATA_FEED (parsable)->priv; + + /* Check for missing required elements */ + /* FIXME: The YouTube comments feed seems to have lost its element, making it an invalid Atom feed and meaning + * the check below has to be commented out. + * Filed as: https://code.google.com/p/gdata-issues/issues/detail?id=2908. + * Discovered in: https://bugzilla.gnome.org/show_bug.cgi?id=679072#c12. */ + /*if (priv->title == NULL) + return gdata_parser_error_required_element_missing ("title", "feed", error);*/ + if (priv->id == NULL) + return gdata_parser_error_required_element_missing ("id", "feed", error); + if (priv->updated == -1) + return gdata_parser_error_required_element_missing ("updated", "feed", error); + + /* Reverse our lists of stuff */ + priv->entries = g_list_reverse (priv->entries); + priv->categories = g_list_reverse (priv->categories); + priv->links = g_list_reverse (priv->links); + priv->authors = g_list_reverse (priv->authors); + + return TRUE; +} + +static void +get_xml (GDataParsable *parsable, GString *xml_string) +{ + GDataFeedPrivate *priv = GDATA_FEED (parsable)->priv; + GList *entries; + gchar *updated; + + /* NOTE: Only the required elements are implemented at the moment */ + gdata_parser_string_append_escaped (xml_string, "", priv->title, ""); + gdata_parser_string_append_escaped (xml_string, "", priv->id, ""); + + updated = gdata_parser_int64_to_iso8601 (priv->updated); + g_string_append_printf (xml_string, "%s", updated); + g_free (updated); + + /* Entries */ + for (entries = priv->entries; entries != NULL; entries = entries->next) + _gdata_parsable_get_xml (GDATA_PARSABLE (entries->data), xml_string, FALSE); +} + +static void +get_namespaces (GDataParsable *parsable, GHashTable *namespaces) +{ + GDataFeedPrivate *priv = GDATA_FEED (parsable)->priv; + GList *i; + + /* We can't assume that all the entries in the feed have identical namespaces, so we have to call get_namespaces() for all of them. + * GDataBatchFeeds, for example, can easily contain entries with differing sets of namespaces. */ + for (i = priv->entries; i != NULL; i = i->next) + GDATA_PARSABLE_GET_CLASS (i->data)->get_namespaces (GDATA_PARSABLE (i->data), namespaces); +} + +static gboolean +parse_json (GDataParsable *parsable, JsonReader *reader, gpointer user_data, GError **error) +{ + GDataFeed *self = GDATA_FEED (parsable); + ParseData *data = user_data; + + if (g_strcmp0 (json_reader_get_member_name (reader), "items") == 0) { + gint i, elements; + + /* Loop through the elements array. */ + for (i = 0, elements = json_reader_count_elements (reader); i < elements; i++) { + GDataEntry *entry; + GType entry_type; + + json_reader_read_element (reader, i); + + /* Allow @data to be %NULL, and assume we're parsing a vanilla feed, so that we can test #GDataFeed in tests/general.c. + * A little hacky, but not too much so, and valuable for testing. */ + entry_type = (data != NULL) ? data->entry_type : GDATA_TYPE_ENTRY; + + /* Parse the node, passing it the reader cursor. */ + entry = GDATA_ENTRY (_gdata_parsable_new_from_json_node (entry_type, reader, NULL, error)); + if (entry == NULL) { + json_reader_end_element (reader); + return FALSE; + } + + /* Calls the callbacks in the main thread */ + if (data != NULL) + _gdata_feed_call_progress_callback (self, data, entry); + _gdata_feed_add_entry (self, entry); + g_object_unref (entry); + + json_reader_end_element (reader); + } + } else if (g_strcmp0 (json_reader_get_member_name (reader), "selfLink") == 0) { + GDataLink *_link; + const gchar *uri; + + /* Empty URI? */ + uri = json_reader_get_string_value (reader); + if (uri == NULL || *uri == '\0') { + return gdata_parser_error_required_json_content_missing (reader, error); + } + + _link = gdata_link_new (uri, GDATA_LINK_SELF); + _gdata_feed_add_link (self, _link); + g_object_unref (_link); + } else if (g_strcmp0 (json_reader_get_member_name (reader), "kind") == 0) { + /* Ignore. */ + } else if (g_strcmp0 (json_reader_get_member_name (reader), "etag") == 0) { + GDATA_FEED (parsable)->priv->etag = g_strdup (json_reader_get_string_value (reader)); + } else if (g_strcmp0 (json_reader_get_member_name (reader), "nextPageToken") == 0) { + GDATA_FEED (parsable)->priv->next_page_token = g_strdup (json_reader_get_string_value (reader)); + } else { + return GDATA_PARSABLE_CLASS (gdata_feed_parent_class)->parse_json (parsable, reader, user_data, error); + } + + return TRUE; +} + +static gboolean +post_parse_json (GDataParsable *parsable, gpointer user_data, GError **error) +{ + GDataFeedPrivate *priv = GDATA_FEED (parsable)->priv; + + /* Reverse our lists of stuff. */ + priv->entries = g_list_reverse (priv->entries); + + return TRUE; +} + +/* Internal helper method to set these properties. */ +void +_gdata_feed_set_page_info (GDataFeed *self, guint total_results, + guint items_per_page) +{ + g_return_if_fail (GDATA_IS_FEED (self)); + + self->priv->total_results = total_results; + self->priv->items_per_page = items_per_page; +} + +/* + * _gdata_feed_new: + * @feed_type: the type of #GDataFeed subclass + * @title: the feed's title + * @id: the feed's ID + * @updated: when the feed was last updated + * + * Creates a new #GDataFeed or subclass with the bare minimum of data to be + * valid. + * + * Return value: a new #GDataFeed + * + * Since: 0.17.0 + */ +GDataFeed * +_gdata_feed_new (GType feed_type, + const gchar *title, + const gchar *id, + gint64 updated) +{ + GDataFeed *feed; + + g_return_val_if_fail (g_type_is_a (feed_type, GDATA_TYPE_FEED), NULL); + g_return_val_if_fail (title != NULL, NULL); + g_return_val_if_fail (id != NULL, NULL); + g_return_val_if_fail (updated >= 0, NULL); + + feed = g_object_new (feed_type, NULL); + feed->priv->title = g_strdup (title); + feed->priv->id = g_strdup (id); + feed->priv->updated = updated; + + return feed; +} + +GDataFeed * +_gdata_feed_new_from_xml (GType feed_type, const gchar *xml, gint length, GType entry_type, + GDataQueryProgressCallback progress_callback, gpointer progress_user_data, GError **error) +{ + ParseData *data; + GDataFeed *feed; + + g_return_val_if_fail (g_type_is_a (feed_type, GDATA_TYPE_FEED), NULL); + g_return_val_if_fail (xml != NULL, NULL); + g_return_val_if_fail (g_type_is_a (entry_type, GDATA_TYPE_ENTRY), NULL); + g_return_val_if_fail (error == NULL || *error == NULL, NULL); + + data = _gdata_feed_parse_data_new (entry_type, progress_callback, progress_user_data); + feed = GDATA_FEED (_gdata_parsable_new_from_xml (feed_type, xml, length, data, error)); + _gdata_feed_parse_data_free (data); + + return feed; +} + +GDataFeed * +_gdata_feed_new_from_json (GType feed_type, const gchar *json, gint length, GType entry_type, + GDataQueryProgressCallback progress_callback, gpointer progress_user_data, GError **error) +{ + ParseData *data; + GDataFeed *feed; + + g_return_val_if_fail (g_type_is_a (feed_type, GDATA_TYPE_FEED), NULL); + g_return_val_if_fail (json != NULL, NULL); + g_return_val_if_fail (g_type_is_a (entry_type, GDATA_TYPE_ENTRY), NULL); + g_return_val_if_fail (error == NULL || *error == NULL, NULL); + + data = _gdata_feed_parse_data_new (entry_type, progress_callback, progress_user_data); + feed = GDATA_FEED (_gdata_parsable_new_from_json (feed_type, json, length, data, error)); + _gdata_feed_parse_data_free (data); + + return feed; +} + +/** + * gdata_feed_get_entries: + * @self: a #GDataFeed + * + * Returns a list of the entries contained in this feed. + * + * Return value: (element-type GData.Entry) (transfer none): a #GList of #GDataEntrys + */ +GList * +gdata_feed_get_entries (GDataFeed *self) +{ + g_return_val_if_fail (GDATA_IS_FEED (self), NULL); + return self->priv->entries; +} + +static gint +entry_compare_cb (const GDataEntry *entry, const gchar *id) +{ + return strcmp (gdata_entry_get_id (GDATA_ENTRY (entry)), id); +} + +/** + * gdata_feed_look_up_entry: + * @self: a #GDataFeed + * @id: the entry's ID + * + * Returns the entry in the feed with the given @id, if found. + * + * Return value: (transfer none): the #GDataEntry, or %NULL + * + * Since: 0.2.0 + */ +GDataEntry * +gdata_feed_look_up_entry (GDataFeed *self, const gchar *id) +{ + GList *element; + + g_return_val_if_fail (GDATA_IS_FEED (self), NULL); + g_return_val_if_fail (id != NULL, NULL); + + element = g_list_find_custom (self->priv->entries, id, (GCompareFunc) entry_compare_cb); + if (element == NULL) + return NULL; + return GDATA_ENTRY (element->data); +} + +/** + * gdata_feed_get_categories: + * @self: a #GDataFeed + * + * Returns a list of the categories listed in this feed. + * + * Return value: (element-type GData.Category) (transfer none): a #GList of #GDataCategorys + */ +GList * +gdata_feed_get_categories (GDataFeed *self) +{ + g_return_val_if_fail (GDATA_IS_FEED (self), NULL); + return self->priv->categories; +} + +static void +_gdata_feed_add_category (GDataFeed *self, GDataCategory *category) +{ + self->priv->categories = g_list_prepend (self->priv->categories, g_object_ref (category)); +} + +/** + * gdata_feed_get_links: + * @self: a #GDataFeed + * + * Returns a list of the links listed in this feed. + * + * Return value: (element-type GData.Link) (transfer none): a #GList of #GDataLinks + */ +GList * +gdata_feed_get_links (GDataFeed *self) +{ + g_return_val_if_fail (GDATA_IS_FEED (self), NULL); + return self->priv->links; +} + +static gint +link_compare_cb (const GDataLink *_link, const gchar *rel) +{ + return strcmp (gdata_link_get_relation_type ((GDataLink*) _link), rel); +} + +/** + * gdata_feed_look_up_link: + * @self: a #GDataFeed + * @rel: the value of the #GDataLink:relation-type property of the desired link + * + * Looks up a link by #GDataLink:relation-type value from the list of links in the feed. + * + * Return value: (transfer none): a #GDataLink, or %NULL if one was not found + * + * Since: 0.1.1 + */ +GDataLink * +gdata_feed_look_up_link (GDataFeed *self, const gchar *rel) +{ + GList *element; + + g_return_val_if_fail (GDATA_IS_FEED (self), NULL); + g_return_val_if_fail (rel != NULL, NULL); + + element = g_list_find_custom (self->priv->links, rel, (GCompareFunc) link_compare_cb); + if (element == NULL) + return NULL; + return GDATA_LINK (element->data); +} + +void +_gdata_feed_add_link (GDataFeed *self, GDataLink *_link) +{ + self->priv->links = g_list_prepend (self->priv->links, g_object_ref (_link)); +} + +/** + * gdata_feed_get_authors: + * @self: a #GDataFeed + * + * Returns a list of the authors listed in this feed. + * + * Return value: (element-type GData.Author) (transfer none): a #GList of #GDataAuthors + */ +GList * +gdata_feed_get_authors (GDataFeed *self) +{ + g_return_val_if_fail (GDATA_IS_FEED (self), NULL); + return self->priv->authors; +} + +static void +_gdata_feed_add_author (GDataFeed *self, GDataAuthor *author) +{ + self->priv->authors = g_list_prepend (self->priv->authors, g_object_ref (author)); +} + +/** + * gdata_feed_get_title: + * @self: a #GDataFeed + * + * Returns the title of the feed. + * + * Return value: the feed's title + */ +const gchar * +gdata_feed_get_title (GDataFeed *self) +{ + g_return_val_if_fail (GDATA_IS_FEED (self), NULL); + return self->priv->title; +} + +/** + * gdata_feed_get_subtitle: + * @self: a #GDataFeed + * + * Returns the subtitle of the feed. + * + * Return value: the feed's subtitle, or %NULL + */ +const gchar * +gdata_feed_get_subtitle (GDataFeed *self) +{ + g_return_val_if_fail (GDATA_IS_FEED (self), NULL); + return self->priv->subtitle; +} + +/** + * gdata_feed_get_id: + * @self: a #GDataFeed + * + * Returns the feed's unique and permanent URN ID. + * + * Return value: the feed's ID + */ +const gchar * +gdata_feed_get_id (GDataFeed *self) +{ + g_return_val_if_fail (GDATA_IS_FEED (self), NULL); + return self->priv->id; +} + +/** + * gdata_feed_get_etag: + * @self: a #GDataFeed + * + * Returns the feed's unique ETag for this version. + * + * Return value: the feed's ETag + * + * Since: 0.2.0 + */ +const gchar * +gdata_feed_get_etag (GDataFeed *self) +{ + g_return_val_if_fail (GDATA_IS_FEED (self), NULL); + return self->priv->etag; +} + +/** + * gdata_feed_get_updated: + * @self: a #GDataFeed + * + * Gets the time the feed was last updated. + * + * Return value: the UNIX timestamp for the time the feed was last updated + */ +gint64 +gdata_feed_get_updated (GDataFeed *self) +{ + g_return_val_if_fail (GDATA_IS_FEED (self), -1); + return self->priv->updated; +} + +/** + * gdata_feed_get_logo: + * @self: a #GDataFeed + * + * Returns the logo URI of the feed. + * + * Return value: the feed's logo URI, or %NULL + */ +const gchar * +gdata_feed_get_logo (GDataFeed *self) +{ + g_return_val_if_fail (GDATA_IS_FEED (self), NULL); + return self->priv->logo; +} + +/** + * gdata_feed_get_icon: + * @self: a #GDataFeed + * + * Returns the icon URI of the feed. + * + * Return value: the feed's icon URI, or %NULL + * + * Since: 0.6.0 + */ +const gchar * +gdata_feed_get_icon (GDataFeed *self) +{ + g_return_val_if_fail (GDATA_IS_FEED (self), NULL); + return self->priv->icon; +} + +/** + * gdata_feed_get_generator: + * @self: a #GDataFeed + * + * Returns details about the software which generated the feed. + * + * Return value: (transfer none): a #GDataGenerator, or %NULL + */ +GDataGenerator * +gdata_feed_get_generator (GDataFeed *self) +{ + g_return_val_if_fail (GDATA_IS_FEED (self), NULL); + return self->priv->generator; +} + +/** + * gdata_feed_get_rights: + * @self: a #GDataFeed + * + * Returns the rights pertaining to the entire feed, or %NULL if not set. + * + * Return value: the feed's rights information + * + * Since: 0.7.0 + */ +const gchar * +gdata_feed_get_rights (GDataFeed *self) +{ + g_return_val_if_fail (GDATA_IS_FEED (self), NULL); + return self->priv->rights; +} + +/** + * gdata_feed_get_items_per_page: + * @self: a #GDataFeed + * + * Returns the number of items per results page feed. + * + * Return value: the number of items per results page feed, or 0 + */ +guint +gdata_feed_get_items_per_page (GDataFeed *self) +{ + g_return_val_if_fail (GDATA_IS_FEED (self), 0); + return self->priv->items_per_page; +} + +/** + * gdata_feed_get_start_index: + * @self: a #GDataFeed + * + * Returns the one-based start index of the results feed in the result set. + * + * Return value: the one-based start index, or 0 + */ +guint +gdata_feed_get_start_index (GDataFeed *self) +{ + g_return_val_if_fail (GDATA_IS_FEED (self), 0); + return self->priv->start_index; +} + +/** + * gdata_feed_get_total_results: + * @self: a #GDataFeed + * + * Returns the total number of results in the result set, including results on other + * pages. If this is zero, the total number is unknown. + * + * Return value: the total number of results, or 0 + */ +guint +gdata_feed_get_total_results (GDataFeed *self) +{ + g_return_val_if_fail (GDATA_IS_FEED (self), 0); + return self->priv->total_results; +} + +/** + * gdata_feed_get_next_page_token: + * @self: a #GDataFeed + * + * Returns the next page token for a query result, or %NULL if not set. + * This is #GDataFeed:next-page-token. The page token might not be set if there + * is no next page, or if this service does not use token based paging (for + * example, if it uses page number or offset based paging instead). Most more + * recent services use token based paging. + * + * Return value: (nullable): the next page token + * + * Since: 0.17.7 + */ +const gchar * +gdata_feed_get_next_page_token (GDataFeed *self) +{ + g_return_val_if_fail (GDATA_IS_FEED (self), NULL); + return self->priv->next_page_token; +} + +void +_gdata_feed_add_entry (GDataFeed *self, GDataEntry *entry) +{ + g_return_if_fail (GDATA_IS_FEED (self)); + g_return_if_fail (GDATA_IS_ENTRY (entry)); + self->priv->entries = g_list_prepend (self->priv->entries, g_object_ref (entry)); +} + +gpointer +_gdata_feed_parse_data_new (GType entry_type, GDataQueryProgressCallback progress_callback, gpointer progress_user_data) +{ + ParseData *data; + data = g_slice_new (ParseData); + data->entry_type = entry_type; + data->progress_callback = progress_callback; + data->progress_user_data = progress_user_data; + data->entry_i = 0; + + return data; +} + +void +_gdata_feed_parse_data_free (gpointer data) +{ + g_slice_free (ParseData, data); +} + +static gboolean +progress_callback_idle (ProgressCallbackData *data) +{ + data->progress_callback (data->entry, data->entry_i, data->total_results, data->progress_user_data); + + return G_SOURCE_REMOVE; +} + +static void +progress_callback_data_free (ProgressCallbackData *data) +{ + g_object_unref (data->entry); + g_slice_free (ProgressCallbackData, data); +} + +void +_gdata_feed_call_progress_callback (GDataFeed *self, gpointer user_data, GDataEntry *entry) +{ + ParseData *data = user_data; + + if (data->progress_callback != NULL) { + ProgressCallbackData *progress_data; + + /* Build the data for the callback */ + progress_data = g_slice_new (ProgressCallbackData); + progress_data->progress_callback = data->progress_callback; + progress_data->progress_user_data = data->progress_user_data; + progress_data->entry = g_object_ref (entry); + progress_data->entry_i = data->entry_i; + progress_data->total_results = MIN (self->priv->items_per_page, self->priv->total_results); + + /* Send the callback; use G_PRIORITY_DEFAULT rather than G_PRIORITY_DEFAULT_IDLE + * to contend with the priorities used by the callback functions in GAsyncResult */ + g_main_context_invoke_full (NULL, G_PRIORITY_DEFAULT, + (GSourceFunc) progress_callback_idle, + progress_data, + (GDestroyNotify) progress_callback_data_free); + } + data->entry_i++; +} + diff --git a/gdata/gdata-feed.h b/gdata/gdata-feed.h new file mode 100644 index 0000000..4da0e87 --- /dev/null +++ b/gdata/gdata-feed.h @@ -0,0 +1,98 @@ +/* -*- Mode: C; indent-tabs-mode: t; c-basic-offset: 8; tab-width: 8 -*- */ +/* + * GData Client + * Copyright (C) Philip Withnall 2008-2009 + * + * GData Client is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * GData Client is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with GData Client. If not, see . + */ + +#ifndef GDATA_FEED_H +#define GDATA_FEED_H + +#include +#include + +#include +#include +#include +#include + +G_BEGIN_DECLS + +#define GDATA_TYPE_FEED (gdata_feed_get_type ()) +#define GDATA_FEED(o) (G_TYPE_CHECK_INSTANCE_CAST ((o), GDATA_TYPE_FEED, GDataFeed)) +#define GDATA_FEED_CLASS(k) (G_TYPE_CHECK_CLASS_CAST((k), GDATA_TYPE_FEED, GDataFeedClass)) +#define GDATA_IS_FEED(o) (G_TYPE_CHECK_INSTANCE_TYPE ((o), GDATA_TYPE_FEED)) +#define GDATA_IS_FEED_CLASS(k) (G_TYPE_CHECK_CLASS_TYPE ((k), GDATA_TYPE_FEED)) +#define GDATA_FEED_GET_CLASS(o) (G_TYPE_INSTANCE_GET_CLASS ((o), GDATA_TYPE_FEED, GDataFeedClass)) + +typedef struct _GDataFeedPrivate GDataFeedPrivate; + +/** + * GDataFeed: + * + * All the fields in the #GDataFeed structure are private and should never be accessed directly. + */ +typedef struct { + /*< private >*/ + GDataParsable parent; + GDataFeedPrivate *priv; +} GDataFeed; + +/** + * GDataFeedClass: + * + * All the fields in the #GDataFeedClass structure are private and should never be accessed directly. + */ +typedef struct { + /*< private >*/ + GDataParsableClass parent; + + /*< private >*/ + /* Padding for future expansion */ + void (*_g_reserved0) (void); + void (*_g_reserved1) (void); + void (*_g_reserved2) (void); + void (*_g_reserved3) (void); + void (*_g_reserved4) (void); + void (*_g_reserved5) (void); +} GDataFeedClass; + +GType gdata_feed_get_type (void) G_GNUC_CONST; +G_DEFINE_AUTOPTR_CLEANUP_FUNC (GDataFeed, g_object_unref) + +GList *gdata_feed_get_entries (GDataFeed *self) G_GNUC_PURE; +GDataEntry *gdata_feed_look_up_entry (GDataFeed *self, const gchar *id) G_GNUC_PURE; +GList *gdata_feed_get_categories (GDataFeed *self) G_GNUC_PURE; +GList *gdata_feed_get_links (GDataFeed *self) G_GNUC_PURE; +GDataLink *gdata_feed_look_up_link (GDataFeed *self, const gchar *rel) G_GNUC_PURE; +GList *gdata_feed_get_authors (GDataFeed *self) G_GNUC_PURE; + +const gchar *gdata_feed_get_title (GDataFeed *self) G_GNUC_PURE; +const gchar *gdata_feed_get_subtitle (GDataFeed *self) G_GNUC_PURE; +const gchar *gdata_feed_get_id (GDataFeed *self) G_GNUC_PURE; +const gchar *gdata_feed_get_etag (GDataFeed *self) G_GNUC_PURE; +gint64 gdata_feed_get_updated (GDataFeed *self); +const gchar *gdata_feed_get_logo (GDataFeed *self) G_GNUC_PURE; +GDataGenerator *gdata_feed_get_generator (GDataFeed *self) G_GNUC_PURE; +const gchar *gdata_feed_get_rights (GDataFeed *self) G_GNUC_PURE; +guint gdata_feed_get_items_per_page (GDataFeed *self) G_GNUC_PURE; +guint gdata_feed_get_start_index (GDataFeed *self) G_GNUC_PURE; +guint gdata_feed_get_total_results (GDataFeed *self) G_GNUC_PURE; +const gchar *gdata_feed_get_icon (GDataFeed *self) G_GNUC_PURE; +const gchar *gdata_feed_get_next_page_token (GDataFeed *self) G_GNUC_PURE; + +G_END_DECLS + +#endif /* !GDATA_FEED_H */ diff --git a/gdata/gdata-goa-authorizer.c b/gdata/gdata-goa-authorizer.c new file mode 100644 index 0000000..a5e650d --- /dev/null +++ b/gdata/gdata-goa-authorizer.c @@ -0,0 +1,401 @@ +/* -*- Mode: C; indent-tabs-mode: t; c-basic-offset: 8; tab-width: 8 -*- */ +/* + * GData Client + * Copyright (C) Matthew Barnes 2011 + * + * GData Client is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * GData Client is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with GData Client. If not, see . + */ + +/** + * SECTION:gdata-goa-authorizer + * @short_description: GData GOA authorization interface + * @stability: Stable + * @include: gdata/gdata-goa-authorizer.h + * + * #GDataGoaAuthorizer provides an implementation of the #GDataAuthorizer interface for authentication and authorization using GNOME Online Accounts + * (GOA) over D-Bus. This allows a single login session (managed by the GOA daemon) to be used by multiple applications simultaneously, without each + * of those applications having to go through the authentication process themselves. Applications making use of #GDataGoaAuthorizer don't get access + * to the user's password (it's handled solely by the GOA daemon). + * + * Internally, GOA authenticates with the Google servers using the + * OAuth 1.0 or + * OAuth 2.0 processes. + * + * #GDataGoaAuthorizer natively supports authorization against multiple services (unlike #GDataClientLoginAuthorizer), depending entirely on which + * services the user has enabled for their Google account in GOA. #GDataGoaAuthorizer cannot authenticate for more services than are enabled in GOA. + * + * + * Authenticating Using GOA + * + * GDataSomeService *service; + * GoaObject *goa_object; + * GDataGoaAuthorizer *authorizer; + * + * /* Create an authorizer and pass it an existing #GoaObject. */ + * goa_object = get_goa_object (); + * authorizer = gdata_goa_authorizer_new (goa_object); + * + * /* Create a service object and link it with the authorizer */ + * service = gdata_some_service_new (GDATA_AUTHORIZER (authorizer)); + * + * /* Use the service! */ + * + * g_object_unref (service); + * g_object_unref (authorizer); + * g_object_unref (goa_object); + * + * + * + * Since: 0.13.1 + */ + +#include +#include +#include +#include + +#include "gdata-goa-authorizer.h" +#include "gdata-authorizer.h" +#include "gdata-service.h" + +#include "services/calendar/gdata-calendar-service.h" +#include "services/contacts/gdata-contacts-service.h" +#include "services/documents/gdata-documents-service.h" +#include "services/picasaweb/gdata-picasaweb-service.h" + +#define HMAC_SHA1_LEN 20 /* bytes, raw */ + +static void gdata_goa_authorizer_interface_init (GDataAuthorizerInterface *interface); + +/* GDataAuthorizer methods must be thread-safe. */ +static GMutex mutex; + +struct _GDataGoaAuthorizerPrivate { + /* GoaObject is already thread-safe. */ + GoaObject *goa_object; + + /* These members are protected by the global mutex (above). */ + gchar *access_token; + gchar *access_token_secret; + GHashTable *authorization_domains; +}; + +enum { + PROP_GOA_OBJECT = 1, +}; + +G_DEFINE_TYPE_WITH_CODE (GDataGoaAuthorizer, gdata_goa_authorizer, G_TYPE_OBJECT, + G_IMPLEMENT_INTERFACE (GDATA_TYPE_AUTHORIZER, gdata_goa_authorizer_interface_init)) + +static void +gdata_goa_authorizer_add_oauth2_authorization (GDataAuthorizer *authorizer, SoupMessage *message) +{ + GDataGoaAuthorizerPrivate *priv; + GString *authorization; + + /* This MUST be called with the mutex already locked. */ + + priv = GDATA_GOA_AUTHORIZER (authorizer)->priv; + + /* We can't add an Authorization header without an access token. Let the request fail. GData should refresh us if it gets back a + * "401 Authorization required" response from Google, and then automatically retry the request. */ + if (priv->access_token == NULL) { + return; + } + + authorization = g_string_new ("Bearer "); + g_string_append (authorization, priv->access_token); + + /* Use replace here, not append, to make sure there's only one "Authorization" header. */ + soup_message_headers_replace (message->request_headers, "Authorization", authorization->str); + + g_string_free (authorization, TRUE); +} + +static void +gdata_goa_authorizer_add_authorization (GDataAuthorizer *authorizer, SoupMessage *message) +{ + GDataGoaAuthorizerPrivate *priv; + + /* This MUST be called with the mutex already locked. */ + + priv = GDATA_GOA_AUTHORIZER (authorizer)->priv; + + /* Only support OAuth 2.0. OAuth 1.0 was deprecated in 2012. */ + if (goa_object_peek_oauth2_based (priv->goa_object) != NULL) { + gdata_goa_authorizer_add_oauth2_authorization (authorizer, message); + } else { + g_warn_if_reached (); + } +} + +static gboolean +gdata_goa_authorizer_is_authorized (GDataAuthorizer *authorizer, GDataAuthorizationDomain *domain) +{ + /* This MUST be called with the mutex already locked. */ + + if (domain == NULL) { + return TRUE; + } + + domain = g_hash_table_lookup (GDATA_GOA_AUTHORIZER (authorizer)->priv->authorization_domains, domain); + + return (domain != NULL); +} + +static void +add_authorization_domains (GDataGoaAuthorizer *self, GType service_type) +{ + GList/**/ *domains; + + domains = gdata_service_get_authorization_domains (service_type); + + while (domains != NULL) { + g_hash_table_insert (self->priv->authorization_domains, g_object_ref (domains->data), domains->data); + domains = g_list_delete_link (domains, domains); + } +} + +static void +gdata_goa_authorizer_set_goa_object (GDataGoaAuthorizer *self, GoaObject *goa_object) +{ + g_return_if_fail (GOA_IS_OBJECT (goa_object)); + g_return_if_fail (self->priv->goa_object == NULL); + + self->priv->goa_object = g_object_ref (goa_object); + + /* Add authorisation domains for all the services supported by our GoaObject. */ + if (goa_object_peek_calendar (goa_object) != NULL) { + add_authorization_domains (self, GDATA_TYPE_CALENDAR_SERVICE); + } + + if (goa_object_peek_contacts (goa_object) != NULL) { + add_authorization_domains (self, GDATA_TYPE_CONTACTS_SERVICE); + } + + if (goa_object_peek_documents (goa_object) != NULL || goa_object_peek_files (goa_object) != NULL) { + add_authorization_domains (self, GDATA_TYPE_DOCUMENTS_SERVICE); + } + + if (goa_object_peek_photos (goa_object) != NULL) { + add_authorization_domains (self, GDATA_TYPE_PICASAWEB_SERVICE); + } +} + +static void +gdata_goa_authorizer_set_property (GObject *object, guint property_id, const GValue *value, GParamSpec *pspec) +{ + switch (property_id) { + case PROP_GOA_OBJECT: + gdata_goa_authorizer_set_goa_object (GDATA_GOA_AUTHORIZER (object), g_value_get_object (value)); + return; + default: + g_assert_not_reached (); + } + + G_OBJECT_WARN_INVALID_PROPERTY_ID (object, property_id, pspec); +} + +static void +gdata_goa_authorizer_get_property (GObject *object, guint property_id, GValue *value, GParamSpec *pspec) +{ + switch (property_id) { + case PROP_GOA_OBJECT: + g_value_set_object (value, gdata_goa_authorizer_get_goa_object (GDATA_GOA_AUTHORIZER (object))); + return; + default: + g_assert_not_reached (); + } + + G_OBJECT_WARN_INVALID_PROPERTY_ID (object, property_id, pspec); +} + +static void +gdata_goa_authorizer_dispose (GObject *object) +{ + GDataGoaAuthorizerPrivate *priv; + + priv = GDATA_GOA_AUTHORIZER (object)->priv; + + g_clear_object (&priv->goa_object); + g_hash_table_remove_all (priv->authorization_domains); + + /* Chain up to parent's dispose() method. */ + G_OBJECT_CLASS (gdata_goa_authorizer_parent_class)->dispose (object); +} + +static void +gdata_goa_authorizer_finalize (GObject *object) +{ + GDataGoaAuthorizerPrivate *priv; + + priv = GDATA_GOA_AUTHORIZER (object)->priv; + + g_free (priv->access_token); + g_free (priv->access_token_secret); + g_hash_table_destroy (priv->authorization_domains); + + /* Chain up to parent's finalize() method. */ + G_OBJECT_CLASS (gdata_goa_authorizer_parent_class)->finalize (object); +} + +static void +gdata_goa_authorizer_process_request (GDataAuthorizer *authorizer, GDataAuthorizationDomain *domain, SoupMessage *message) +{ + g_mutex_lock (&mutex); + + if (gdata_goa_authorizer_is_authorized (authorizer, domain)) { + gdata_goa_authorizer_add_authorization (authorizer, message); + } + + g_mutex_unlock (&mutex); +} + +static gboolean +gdata_goa_authorizer_is_authorized_for_domain (GDataAuthorizer *authorizer, GDataAuthorizationDomain *domain) +{ + gboolean authorized; + + g_mutex_lock (&mutex); + + authorized = gdata_goa_authorizer_is_authorized (authorizer, domain); + + g_mutex_unlock (&mutex); + + return authorized; +} + +static gboolean +gdata_goa_authorizer_refresh_authorization (GDataAuthorizer *authorizer, GCancellable *cancellable, GError **error) +{ + GDataGoaAuthorizerPrivate *priv; + GoaOAuth2Based *goa_oauth2_based; + GoaAccount *goa_account; + gboolean success = FALSE; + + priv = GDATA_GOA_AUTHORIZER (authorizer)->priv; + + g_mutex_lock (&mutex); + + g_free (priv->access_token); + priv->access_token = NULL; + + g_free (priv->access_token_secret); + priv->access_token_secret = NULL; + + goa_account = goa_object_get_account (priv->goa_object); + goa_oauth2_based = goa_object_get_oauth2_based (priv->goa_object); + + success = goa_account_call_ensure_credentials_sync (goa_account, NULL, cancellable, error); + + if (success == FALSE) { + goto exit; + } + + /* Only support OAuth 2.0. */ + if (goa_oauth2_based != NULL) { + success = goa_oauth2_based_call_get_access_token_sync (goa_oauth2_based, &priv->access_token, NULL, cancellable, error); + } else { + g_warn_if_reached (); /* should never happen */ + } + +exit: + g_clear_object (&goa_account); + g_clear_object (&goa_oauth2_based); + + g_mutex_unlock (&mutex); + + return success; +} + +static void +gdata_goa_authorizer_class_init (GDataGoaAuthorizerClass *class) +{ + GObjectClass *object_class; + + g_type_class_add_private (class, sizeof (GDataGoaAuthorizerPrivate)); + + object_class = G_OBJECT_CLASS (class); + object_class->set_property = gdata_goa_authorizer_set_property; + object_class->get_property = gdata_goa_authorizer_get_property; + object_class->dispose = gdata_goa_authorizer_dispose; + object_class->finalize = gdata_goa_authorizer_finalize; + + /** + * GDataGoaAuthorizer:goa-object: + * + * The GOA account providing authentication. This should have all the necessary services enabled on it. + * + * Since: 0.13.1 + */ + g_object_class_install_property (object_class, PROP_GOA_OBJECT, + g_param_spec_object ("goa-object", "GOA object", "The GOA account providing authentication.", + GOA_TYPE_OBJECT, G_PARAM_READWRITE | G_PARAM_CONSTRUCT_ONLY | G_PARAM_STATIC_STRINGS)); +} + +static void +gdata_goa_authorizer_interface_init (GDataAuthorizerInterface *interface) +{ + interface->process_request = gdata_goa_authorizer_process_request; + interface->is_authorized_for_domain = gdata_goa_authorizer_is_authorized_for_domain; + interface->refresh_authorization = gdata_goa_authorizer_refresh_authorization; +} + +static void +gdata_goa_authorizer_init (GDataGoaAuthorizer *authorizer) +{ + GHashTable *authorization_domains; + + authorization_domains = g_hash_table_new_full ((GHashFunc) g_direct_hash, (GEqualFunc) g_direct_equal, + (GDestroyNotify) g_object_unref, (GDestroyNotify) NULL); + + authorizer->priv = G_TYPE_INSTANCE_GET_PRIVATE (authorizer, GDATA_TYPE_GOA_AUTHORIZER, GDataGoaAuthorizerPrivate); + authorizer->priv->authorization_domains = authorization_domains; +} + +/** + * gdata_goa_authorizer_new: + * @goa_object: (transfer none): the GOA account providing authentication + * + * Create a new #GDataGoaAuthorizer using the authentication token from the given @goa_object. + * + * Return value: (transfer full): a new #GDataGoaAuthorizer; unref with g_object_unref() + * + * Since: 0.13.1 + */ +GDataGoaAuthorizer * +gdata_goa_authorizer_new (GoaObject *goa_object) +{ + g_return_val_if_fail (GOA_IS_OBJECT (goa_object), NULL); + + return g_object_new (GDATA_TYPE_GOA_AUTHORIZER, "goa-object", goa_object, NULL); +} + +/** + * gdata_goa_authorizer_get_goa_object: + * @self: a #GDataGoaAuthorizer + * + * The GOA account providing authentication. This is the same as #GDataGoaAuthorizer:goa-object. + * + * Return value: (transfer none): the GOA account providing authentication + * + * Since: 0.13.1 + */ +GoaObject * +gdata_goa_authorizer_get_goa_object (GDataGoaAuthorizer *self) +{ + g_return_val_if_fail (GDATA_IS_GOA_AUTHORIZER (self), NULL); + + return self->priv->goa_object; +} diff --git a/gdata/gdata-goa-authorizer.h b/gdata/gdata-goa-authorizer.h new file mode 100644 index 0000000..34b8747 --- /dev/null +++ b/gdata/gdata-goa-authorizer.h @@ -0,0 +1,79 @@ +/* -*- Mode: C; indent-tabs-mode: t; c-basic-offset: 8; tab-width: 8 -*- */ +/* + * GData Client + * Copyright (C) Matthew Barnes 2011 + * + * GData Client is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * GData Client is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with GData Client. If not, see . + */ + +#ifndef GDATA_GOA_AUTHORIZER_H +#define GDATA_GOA_AUTHORIZER_H + +#include +#include + +#define GOA_API_IS_SUBJECT_TO_CHANGE +#include + +/* Standard GObject macros */ +#define GDATA_TYPE_GOA_AUTHORIZER (gdata_goa_authorizer_get_type ()) +#define GDATA_GOA_AUTHORIZER(obj) (G_TYPE_CHECK_INSTANCE_CAST ((obj), GDATA_TYPE_GOA_AUTHORIZER, GDataGoaAuthorizer)) +#define GDATA_GOA_AUTHORIZER_CLASS(cls) (G_TYPE_CHECK_CLASS_CAST ((cls), GDATA_TYPE_GOA_AUTHORIZER, GDataGoaAuthorizerClass)) +#define GDATA_IS_GOA_AUTHORIZER(obj) (G_TYPE_CHECK_INSTANCE_TYPE ((obj), GDATA_TYPE_GOA_AUTHORIZER)) +#define GDATA_IS_GOA_AUTHORIZER_CLASS(cls) (G_TYPE_CHECK_CLASS_TYPE ((cls), GDATA_TYPE_GOA_AUTHORIZER)) +#define GDATA_GOA_AUTHORIZER_GET_CLASS(obj) (G_TYPE_INSTANCE_GET_CLASS ((obj), GDATA_TYPE_GOA_AUTHORIZER, GDataGoaAuthorizerClass)) + +G_BEGIN_DECLS + +typedef struct _GDataGoaAuthorizerPrivate GDataGoaAuthorizerPrivate; + +/** + * GDataGoaAuthorizer: + * + * All the fields in the #GDataGoaAuthorizer structure are private and should never be accessed directly. + * + * Since: 0.13.1 + */ +typedef struct { + /*< private >*/ + GObject parent; + GDataGoaAuthorizerPrivate *priv; +} GDataGoaAuthorizer; + +/** + * GDataGoaAuthorizerClass: + * + * All the fields in the #GDataGoaAuthorizerClass structure are private and should never be accessed directly. + * + * Since: 0.13.1 + */ +typedef struct { + /*< private >*/ + GObjectClass parent_class; + + /*< private >*/ + /* Padding for future expansion */ + void (*_g_reserved0) (void); + void (*_g_reserved1) (void); +} GDataGoaAuthorizerClass; + +GType gdata_goa_authorizer_get_type (void) G_GNUC_CONST; +G_DEFINE_AUTOPTR_CLEANUP_FUNC (GDataGoaAuthorizer, g_object_unref) + +GDataGoaAuthorizer *gdata_goa_authorizer_new (GoaObject *goa_object) G_GNUC_WARN_UNUSED_RESULT G_GNUC_MALLOC; +GoaObject *gdata_goa_authorizer_get_goa_object (GDataGoaAuthorizer *self) G_GNUC_PURE; + +G_END_DECLS + +#endif /* GDATA_GOA_AUTHORIZER_H */ diff --git a/gdata/gdata-goa.symbols b/gdata/gdata-goa.symbols new file mode 100644 index 0000000..f870ec1 --- /dev/null +++ b/gdata/gdata-goa.symbols @@ -0,0 +1,3 @@ +gdata_goa_authorizer_get_type +gdata_goa_authorizer_new +gdata_goa_authorizer_get_goa_object diff --git a/gdata/gdata-marshal.list b/gdata/gdata-marshal.list new file mode 100644 index 0000000..a8d5b2a --- /dev/null +++ b/gdata/gdata-marshal.list @@ -0,0 +1,2 @@ +VOID:OBJECT,OBJECT,POINTER +STRING:OBJECT,STRING diff --git a/gdata/gdata-oauth1-authorizer.c b/gdata/gdata-oauth1-authorizer.c new file mode 100644 index 0000000..09d766e --- /dev/null +++ b/gdata/gdata-oauth1-authorizer.c @@ -0,0 +1,1498 @@ +/* -*- Mode: C; indent-tabs-mode: t; c-basic-offset: 8; tab-width: 8 -*- */ +/* + * GData Client + * Copyright (C) Philip Withnall 2011 + * + * GData Client is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * GData Client is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with GData Client. If not, see . + */ + +/** + * SECTION:gdata-oauth1-authorizer + * @short_description: GData OAuth 1.0 authorization interface + * @stability: Stable + * @include: gdata/gdata-oauth1-authorizer.h + * + * OAuth 1.0 has been deprecated since 2012, and OAuth 2.0 (#GDataOAuth2Authorizer) should be used instead. + * + * #GDataOAuth1Authorizer provides an implementation of the #GDataAuthorizer interface for authentication and authorization using the + * OAuth 1.0 process, + * which was preferred by Google until OAuth 2.0 was released — it is now + * preferred to use #GDataOAuth2Authorizer. + * + * OAuth 1.0 replaces the deprecated ClientLogin process. One of the main reasons for this is to allow two-factor authentication to be supported, by + * moving the authentication interface to a web page under Google's control. + * + * The OAuth 1.0 process as implemented by Google follows the OAuth 1.0 protocol as + * specified by IETF in RFC 5849, with a few additions to support scopes (implemented in libgdata by #GDataAuthorizationDomains), + * locales and custom domains. Briefly, the process is initiated by requesting an authenticated request token from the Google accounts service + * (using gdata_oauth1_authorizer_request_authentication_uri()), going to the authentication URI for the request token, authenticating and authorizing + * access to the desired scopes, then providing the verifier returned by Google to the Google accounts service again (using + * gdata_oauth1_authorizer_request_authorization()) to authorize the token. This results in an access token which is attached to all future requests + * to the online service. + * + * While Google supports unregistered and registered modes for OAuth 1.0 authorization, it only supports unregistered mode for installed applications. + * Consequently, libgdata also only supports unregistered mode. For this purpose, the application name to be presented to the user on the + * authentication page at the URI returned by gdata_oauth1_authorizer_request_authentication_uri() can be specified when constructing the + * #GDataOAuth1Authorizer. + * + * As described, each authentication/authorization operation is in two parts: gdata_oauth1_authorizer_request_authentication_uri() and + * gdata_oauth1_authorizer_request_authorization(). #GDataOAuth1Authorizer stores no state about ongoing authentication operations (i.e. ones which + * have successfully called gdata_oauth1_authorizer_request_authentication_uri(), but are yet to successfully call + * gdata_oauth1_authorizer_request_authorization()). Consequently, operations can be abandoned before calling + * gdata_oauth1_authorizer_request_authorization() without problems. The only state necessary between the calls is the request token and request token + * secret, as returned by gdata_oauth1_authorizer_request_authentication_uri() and taken as parameters to + * gdata_oauth1_authorizer_request_authorization(). + * + * #GDataOAuth1Authorizer natively supports authorization against multiple services in a single authorization request (unlike + * #GDataClientLoginAuthorizer). + * + * Each access token is long lived, so reauthorization is rarely necessary with #GDataOAuth1Authorizer. Consequently, refreshing authorization using + * gdata_authorizer_refresh_authorization() is not supported by #GDataOAuth1Authorizer, and will immediately return %FALSE with no error set. + * + * + * Authenticating Asynchronously Using OAuth 1.0 + * + * GDataSomeService *service; + * GDataOAuth1Authorizer *authorizer; + * + * /* Create an authorizer and authenticate and authorize the service we're using, asynchronously. */ + * authorizer = gdata_oauth1_authorizer_new (_("My libgdata application"), GDATA_TYPE_SOME_SERVICE); + * gdata_oauth1_authorizer_request_authentication_uri_async (authorizer, cancellable, + * (GAsyncReadyCallback) request_authentication_uri_cb, user_data); + * + * /* Create a service object and link it with the authorizer */ + * service = gdata_some_service_new (GDATA_AUTHORIZER (authorizer)); + * + * static void + * request_authentication_uri_cb (GDataOAuth1Authorizer *authorizer, GAsyncResult *async_result, gpointer user_data) + * { + * gchar *authentication_uri, *token, *token_secret, *verifier; + * GError *error = NULL; + * + * authentication_uri = gdata_oauth1_authorizer_request_authentication_uri_finish (authorizer, async_result, &token, &token_secret, + * &error); + * + * if (error != NULL) { + * /* Notify the user of all errors except cancellation errors */ + * if (!g_error_matches (error, G_IO_ERROR, G_IO_ERROR_CANCELLED)) { + * g_error ("Requesting a token failed: %s", error->message); + * } + * + * g_error_free (error); + * goto finish; + * } + * + * /* (Present the page at the authentication URI to the user, either in an embedded or stand-alone web browser, and + * * ask them to grant access to the application and return the verifier Google gives them.) */ + * verifier = ask_user_for_verifier (authentication_uri); + * + * gdata_oauth1_authorizer_request_authorization_async (authorizer, token, token_secret, verifier, cancellable, + * (GAsyncReadyCallback) request_authorization_cb, user_data); + * + * finish: + * g_free (verifier); + * g_free (authentication_uri); + * g_free (token); + * + * /* Zero out the secret before freeing. */ + * if (token_secret != NULL) { + * memset (token_secret, 0, strlen (token_secret)); + * } + * + * g_free (token_secret); + * } + * + * static void + * request_authorization_cb (GDataOAuth1Authorizer *authorizer, GAsyncResult *async_result, gpointer user_data) + * { + * GError *error = NULL; + * + * if (gdata_oauth1_authorizer_request_authorization_finish (authorizer, async_result, &error) == FALSE) { + * /* Notify the user of all errors except cancellation errors */ + * if (!g_error_matches (error, G_IO_ERROR, G_IO_ERROR_CANCELLED)) { + * g_error ("Authorization failed: %s", error->message); + * } + * + * g_error_free (error); + * return; + * } + * + * /* (The client is now authenticated and authorized against the service. + * * It can now proceed to execute queries on the service object which require the user to be authenticated.) */ + * } + * + * g_object_unref (service); + * g_object_unref (authorizer); + * + * + * + * Since: 0.9.0 + */ + +#include +#include +#include +#include + +#ifdef ENABLE_OAUTH1 +#include +#endif + +#include "gdata-oauth1-authorizer.h" +#include "gdata-private.h" + +#define HMAC_SHA1_LEN 20 /* bytes, raw */ + +static void authorizer_init (GDataAuthorizerInterface *iface); +static void dispose (GObject *object); +static void finalize (GObject *object); +static void get_property (GObject *object, guint property_id, GValue *value, GParamSpec *pspec); +static void set_property (GObject *object, guint property_id, const GValue *value, GParamSpec *pspec); + +static void process_request (GDataAuthorizer *self, GDataAuthorizationDomain *domain, SoupMessage *message); +static gboolean is_authorized_for_domain (GDataAuthorizer *self, GDataAuthorizationDomain *domain); + +static void sign_message (GDataOAuth1Authorizer *self, SoupMessage *message, const gchar *token, const gchar *token_secret, GHashTable *parameters); + +static void notify_proxy_uri_cb (GObject *object, GParamSpec *pspec, GDataOAuth1Authorizer *self); +static void notify_timeout_cb (GObject *gobject, GParamSpec *pspec, GObject *self); + +static SoupURI *_get_proxy_uri (GDataOAuth1Authorizer *self); +static void _set_proxy_uri (GDataOAuth1Authorizer *self, SoupURI *proxy_uri); + +struct _GDataOAuth1AuthorizerPrivate { + SoupSession *session; + SoupURI *proxy_uri; /* cached version only set if gdata_oauth1_authorizer_get_proxy_uri() is called */ + GProxyResolver *proxy_resolver; + + gchar *application_name; + gchar *locale; + + GMutex mutex; /* mutex for token, token_secret and authorization_domains */ + + /* Note: This is the access token, not the request token returned by gdata_oauth1_authorizer_request_authentication_uri(). + * It's NULL iff the authorizer isn't authenticated. token_secret must be NULL iff token is NULL. */ + gchar *token; + GDataSecureString token_secret; /* must be allocated by _gdata_service_secure_strdup() */ + + /* Mapping from GDataAuthorizationDomain to itself; a set of domains for which ->access_token is valid. */ + GHashTable *authorization_domains; +}; + +enum { + PROP_APPLICATION_NAME = 1, + PROP_LOCALE, + PROP_PROXY_URI, + PROP_TIMEOUT, + PROP_PROXY_RESOLVER, +}; + +G_DEFINE_TYPE_WITH_CODE (GDataOAuth1Authorizer, gdata_oauth1_authorizer, G_TYPE_OBJECT, + G_IMPLEMENT_INTERFACE (GDATA_TYPE_AUTHORIZER, authorizer_init)) + +static void +gdata_oauth1_authorizer_class_init (GDataOAuth1AuthorizerClass *klass) +{ + GObjectClass *gobject_class = G_OBJECT_CLASS (klass); + + g_type_class_add_private (klass, sizeof (GDataOAuth1AuthorizerPrivate)); + + gobject_class->get_property = get_property; + gobject_class->set_property = set_property; + gobject_class->dispose = dispose; + gobject_class->finalize = finalize; + + /** + * GDataOAuth1Authorizer:application-name: + * + * The human-readable, translated application name for the client, to be presented to the user on the authentication page at the URI + * returned by gdata_oauth1_authorizer_request_authentication_uri(). + * + * If %NULL is provided in the constructor to #GDataOAuth1Authorizer, the value returned by g_get_application_name() will be used as a + * fallback. Note that this may also be %NULL: in this case, the authentication page will use the application name “anonymous”. + * + * Since: 0.9.0 + */ + g_object_class_install_property (gobject_class, PROP_APPLICATION_NAME, + g_param_spec_string ("application-name", + "Application name", "The human-readable, translated application name for the client.", + NULL, + G_PARAM_CONSTRUCT_ONLY | G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)); + + /** + * GDataOAuth1Authorizer:locale: + * + * The locale to use for network requests, in Unix locale format. (e.g. "en_GB", "cs", "de_DE".) Use %NULL for the default "C" locale + * (typically "en_US"). + * + * This locale will be used by the server-side software to localise the authentication and authorization pages at the URI returned by + * gdata_oauth1_authorizer_request_authentication_uri(). + * + * The server-side behaviour is undefined if it doesn't support a given locale. + * + * Since: 0.9.0 + */ + g_object_class_install_property (gobject_class, PROP_LOCALE, + g_param_spec_string ("locale", + "Locale", "The locale to use for network requests, in Unix locale format.", + NULL, + G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)); + + /** + * GDataOAuth1Authorizer:proxy-uri: + * + * The proxy URI used internally for all network requests. + * + * Since: 0.9.0 + * Deprecated: 0.15.0: Use #GDataClientLoginAuthorizer:proxy-resolver instead, which gives more flexibility over the proxy used. + */ + g_object_class_install_property (gobject_class, PROP_PROXY_URI, + g_param_spec_boxed ("proxy-uri", + "Proxy URI", "The proxy URI used internally for all network requests.", + SOUP_TYPE_URI, + G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)); + + /** + * GDataOAuth1Authorizer:timeout: + * + * A timeout, in seconds, for network operations. If the timeout is exceeded, the operation will be cancelled and + * %GDATA_SERVICE_ERROR_NETWORK_ERROR will be returned. + * + * If the timeout is 0, operations will never time out. + * + * Since: 0.9.0 + */ + g_object_class_install_property (gobject_class, PROP_TIMEOUT, + g_param_spec_uint ("timeout", + "Timeout", "A timeout, in seconds, for network operations.", + 0, G_MAXUINT, 0, + G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)); + + /** + * GDataOAuth1Authorizer:proxy-resolver: + * + * The #GProxyResolver used to determine a proxy URI. Setting this will clear the #GDataOAuth1Authorizer:proxy-uri property. + * + * Since: 0.15.0 + */ + g_object_class_install_property (gobject_class, PROP_PROXY_RESOLVER, + g_param_spec_object ("proxy-resolver", + "Proxy Resolver", "A GProxyResolver used to determine a proxy URI.", + G_TYPE_PROXY_RESOLVER, + G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)); +} + +static void +authorizer_init (GDataAuthorizerInterface *iface) +{ + iface->process_request = process_request; + iface->is_authorized_for_domain = is_authorized_for_domain; +} + +static void +gdata_oauth1_authorizer_init (GDataOAuth1Authorizer *self) +{ + self->priv = G_TYPE_INSTANCE_GET_PRIVATE (self, GDATA_TYPE_OAUTH1_AUTHORIZER, GDataOAuth1AuthorizerPrivate); + + /* Set up the authorizer's mutex */ + g_mutex_init (&(self->priv->mutex)); + self->priv->authorization_domains = g_hash_table_new_full (g_direct_hash, g_direct_equal, g_object_unref, NULL); + + /* Set up the session */ + self->priv->session = _gdata_service_build_session (); + + /* Proxy the SoupSession's proxy-uri and timeout properties */ + g_signal_connect (self->priv->session, "notify::proxy-uri", (GCallback) notify_proxy_uri_cb, self); + g_signal_connect (self->priv->session, "notify::timeout", (GCallback) notify_timeout_cb, self); + + /* Keep our GProxyResolver synchronized with SoupSession's. */ + g_object_bind_property (self->priv->session, "proxy-resolver", self, "proxy-resolver", G_BINDING_BIDIRECTIONAL | G_BINDING_SYNC_CREATE); +} + +static void +dispose (GObject *object) +{ + GDataOAuth1AuthorizerPrivate *priv = GDATA_OAUTH1_AUTHORIZER (object)->priv; + + if (priv->session != NULL) + g_object_unref (priv->session); + priv->session = NULL; + + g_clear_object (&priv->proxy_resolver); + + /* Chain up to the parent class */ + G_OBJECT_CLASS (gdata_oauth1_authorizer_parent_class)->dispose (object); +} + +static void +finalize (GObject *object) +{ + GDataOAuth1AuthorizerPrivate *priv = GDATA_OAUTH1_AUTHORIZER (object)->priv; + + g_free (priv->application_name); + g_free (priv->locale); + + g_hash_table_destroy (priv->authorization_domains); + g_mutex_clear (&(priv->mutex)); + + if (priv->proxy_uri != NULL) { + soup_uri_free (priv->proxy_uri); + } + + g_free (priv->token); + _gdata_service_secure_strfree (priv->token_secret); + + /* Chain up to the parent class */ + G_OBJECT_CLASS (gdata_oauth1_authorizer_parent_class)->finalize (object); +} + +static void +get_property (GObject *object, guint property_id, GValue *value, GParamSpec *pspec) +{ + GDataOAuth1AuthorizerPrivate *priv = GDATA_OAUTH1_AUTHORIZER (object)->priv; + + switch (property_id) { + case PROP_APPLICATION_NAME: + g_value_set_string (value, priv->application_name); + break; + case PROP_LOCALE: + g_value_set_string (value, priv->locale); + break; + case PROP_PROXY_URI: + g_value_set_boxed (value, _get_proxy_uri (GDATA_OAUTH1_AUTHORIZER (object))); + break; + case PROP_TIMEOUT: + g_value_set_uint (value, gdata_oauth1_authorizer_get_timeout (GDATA_OAUTH1_AUTHORIZER (object))); + break; + case PROP_PROXY_RESOLVER: + g_value_set_object (value, gdata_oauth1_authorizer_get_proxy_resolver (GDATA_OAUTH1_AUTHORIZER (object))); + break; + default: + /* We don't have any other property... */ + G_OBJECT_WARN_INVALID_PROPERTY_ID (object, property_id, pspec); + break; + } +} + +static void +set_property (GObject *object, guint property_id, const GValue *value, GParamSpec *pspec) +{ + GDataOAuth1AuthorizerPrivate *priv = GDATA_OAUTH1_AUTHORIZER (object)->priv; + + switch (property_id) { + /* Construct only */ + case PROP_APPLICATION_NAME: + priv->application_name = g_value_dup_string (value); + + /* Default to the value of g_get_application_name() */ + if (priv->application_name == NULL || *(priv->application_name) == '\0') { + g_free (priv->application_name); + priv->application_name = g_strdup (g_get_application_name ()); + } + + break; + case PROP_LOCALE: + gdata_oauth1_authorizer_set_locale (GDATA_OAUTH1_AUTHORIZER (object), g_value_get_string (value)); + break; + case PROP_PROXY_URI: + _set_proxy_uri (GDATA_OAUTH1_AUTHORIZER (object), g_value_get_boxed (value)); + break; + case PROP_TIMEOUT: + gdata_oauth1_authorizer_set_timeout (GDATA_OAUTH1_AUTHORIZER (object), g_value_get_uint (value)); + break; + case PROP_PROXY_RESOLVER: + gdata_oauth1_authorizer_set_proxy_resolver (GDATA_OAUTH1_AUTHORIZER (object), g_value_get_object (value)); + break; + default: + /* We don't have any other property... */ + G_OBJECT_WARN_INVALID_PROPERTY_ID (object, property_id, pspec); + break; + } +} + +static void +process_request (GDataAuthorizer *self, GDataAuthorizationDomain *domain, SoupMessage *message) +{ + GDataOAuth1AuthorizerPrivate *priv = GDATA_OAUTH1_AUTHORIZER (self)->priv; + + /* Set the authorisation header */ + g_mutex_lock (&(priv->mutex)); + + /* Sanity check */ + g_assert ((priv->token == NULL) == (priv->token_secret == NULL)); + + if (priv->token != NULL && g_hash_table_lookup (priv->authorization_domains, domain) != NULL) { + sign_message (GDATA_OAUTH1_AUTHORIZER (self), message, priv->token, priv->token_secret, NULL); + } + + g_mutex_unlock (&(priv->mutex)); +} + +static gboolean +is_authorized_for_domain (GDataAuthorizer *self, GDataAuthorizationDomain *domain) +{ + GDataOAuth1AuthorizerPrivate *priv = GDATA_OAUTH1_AUTHORIZER (self)->priv; + gpointer result; + const gchar *token; + + g_mutex_lock (&(priv->mutex)); + token = priv->token; + result = g_hash_table_lookup (priv->authorization_domains, domain); + g_mutex_unlock (&(priv->mutex)); + + /* Sanity check */ + g_assert (result == NULL || result == domain); + + return (token != NULL && result != NULL) ? TRUE : FALSE; +} + +/* Sign the message and add the Authorization header to it containing the signature. + * NOTE: This must not lock priv->mutex, as it's called from within a critical section in process_request() and priv->mutex isn't recursive. */ +static void +sign_message (GDataOAuth1Authorizer *self, SoupMessage *message, const gchar *token, const gchar *token_secret, GHashTable *parameters) +{ +#ifdef ENABLE_OAUTH1 + GHashTableIter iter; + const gchar *key, *value, *consumer_key, *consumer_secret, *signature_method; + gsize params_length = 0; + GList *sorted_params = NULL, *i; + GString *query_string, *signature_base_string, *secret_string, *authorization_header; + SoupURI *normalised_uri; + gchar *uri, *signature, *timestamp; + char *nonce; + gboolean is_first = TRUE; + GTimeVal time_val; + guchar signature_buf[HMAC_SHA1_LEN]; + gsize signature_buf_len; + GHmac *signature_hmac; + + g_return_if_fail (GDATA_IS_OAUTH1_AUTHORIZER (self)); + g_return_if_fail (SOUP_IS_MESSAGE (message)); + g_return_if_fail (token == NULL || *token != '\0'); + g_return_if_fail (token_secret == NULL || *token_secret != '\0'); + g_return_if_fail ((token == NULL) == (token_secret == NULL)); + + /* Build and return a HMAC-SHA1 signature for the given SoupMessage. We always use HMAC-SHA1, since installed applications have to be + * unregistered (see: http://code.google.com/apis/accounts/docs/OAuth_ref.html#SigningOAuth). + * Reference: http://tools.ietf.org/html/rfc5849#section-3.4 */ + signature_method = "HMAC-SHA1"; + + /* As described here, we use an anonymous consumer key and secret, since we're designed for installed applications: + * http://code.google.com/apis/accounts/docs/OAuth_ref.html#SigningOAuth */ + consumer_key = "anonymous"; + consumer_secret = "anonymous"; + + /* Add various standard parameters to the list (note: this modifies the hash table belonging to the caller) */ + nonce = oauth_gen_nonce (); + g_get_current_time (&time_val); + timestamp = g_strdup_printf ("%li", time_val.tv_sec); + + if (parameters == NULL) { + parameters = g_hash_table_new (g_str_hash, g_str_equal); + } else { + g_hash_table_ref (parameters); + } + + g_hash_table_insert (parameters, (gpointer) "oauth_signature_method", (gpointer) signature_method); + g_hash_table_insert (parameters, (gpointer) "oauth_consumer_key", (gpointer) consumer_key); + g_hash_table_insert (parameters, (gpointer) "oauth_nonce", nonce); + g_hash_table_insert (parameters, (gpointer) "oauth_timestamp", timestamp); + g_hash_table_insert (parameters, (gpointer) "oauth_version", (gpointer) "1.0"); + + /* Only add the token if it's been provided */ + if (token != NULL) { + g_hash_table_insert (parameters, (gpointer) "oauth_token", (gpointer) token); + } + + /* Sort the parameters and build a query string, as defined here: http://tools.ietf.org/html/rfc5849#section-3.4.1.3 */ + g_hash_table_iter_init (&iter, parameters); + + while (g_hash_table_iter_next (&iter, (gpointer*) &key, (gpointer*) &value) == TRUE) { + GString *pair = g_string_new (NULL); + + g_string_append_uri_escaped (pair, key, NULL, FALSE); + g_string_append_c (pair, '='); + g_string_append_uri_escaped (pair, value, NULL, FALSE); + + /* Append the pair to the list for sorting, and keep track of the total length of the strings in the list so far */ + params_length += pair->len + 1 /* sep */; + sorted_params = g_list_prepend (sorted_params, g_string_free (pair, FALSE)); + } + + g_hash_table_unref (parameters); + + sorted_params = g_list_sort (sorted_params, (GCompareFunc) g_strcmp0); + + /* Concatenate the parameters to give the query string */ + query_string = g_string_sized_new (params_length); + + for (i = sorted_params; i != NULL; i = i->next) { + if (is_first == FALSE) { + g_string_append_c (query_string, '&'); + } + + g_string_append (query_string, i->data); + + g_free (i->data); + is_first = FALSE; + } + + g_list_free (sorted_params); + + /* Normalise the URI as described here: http://tools.ietf.org/html/rfc5849#section-3.4.1.2 */ + normalised_uri = soup_uri_copy (soup_message_get_uri (message)); + soup_uri_set_query (normalised_uri, NULL); + soup_uri_set_fragment (normalised_uri, NULL); + + /* Append it to the signature base string */ + uri = soup_uri_to_string (normalised_uri, FALSE); + + /* Start building the signature base string as described here: http://tools.ietf.org/html/rfc5849#section-3.4.1.1 */ + signature_base_string = g_string_sized_new (4 /* method */ + 1 /* sep */ + strlen (uri) + 1 /* sep */ + params_length /* query string */); + g_string_append_uri_escaped (signature_base_string, message->method, NULL, FALSE); + g_string_append_c (signature_base_string, '&'); + g_string_append_uri_escaped (signature_base_string, uri, NULL, FALSE); + g_string_append_c (signature_base_string, '&'); + g_string_append_uri_escaped (signature_base_string, query_string->str, NULL, FALSE); + + g_free (uri); + soup_uri_free (normalised_uri); + g_string_free (query_string, TRUE); + + /* Build the secret key to use in the HMAC */ + secret_string = g_string_new (NULL); + g_string_append_uri_escaped (secret_string, consumer_secret, NULL, FALSE); + g_string_append_c (secret_string, '&'); + + /* Only add token_secret if it was provided */ + if (token_secret != NULL) { + g_string_append_uri_escaped (secret_string, token_secret, NULL, FALSE); + } + + /* Create the signature as described here: http://tools.ietf.org/html/rfc5849#section-3.4.2 */ + signature_hmac = g_hmac_new (G_CHECKSUM_SHA1, (const guchar*) secret_string->str, secret_string->len); + g_hmac_update (signature_hmac, (const guchar*) signature_base_string->str, signature_base_string->len); + + signature_buf_len = G_N_ELEMENTS (signature_buf); + g_hmac_get_digest (signature_hmac, signature_buf, &signature_buf_len); + + g_hmac_unref (signature_hmac); + + signature = g_base64_encode (signature_buf, signature_buf_len); + + /*g_debug ("Signing message using Signature Base String: “%s” and key “%s” using method “%s” to give signature: “%s”.", + signature_base_string->str, secret_string->str, signature_method, signature);*/ + + /* Zero out the secret_string before freeing it, to reduce the chance of secrets hitting disk. */ + memset (secret_string->str, 0, secret_string->allocated_len); + + g_string_free (secret_string, TRUE); + g_string_free (signature_base_string, TRUE); + + /* Build the Authorization header and append it to the message */ + authorization_header = g_string_new ("OAuth oauth_consumer_key=\""); + g_string_append_uri_escaped (authorization_header, consumer_key, NULL, FALSE); + + /* Only add the token if it's been provided */ + if (token != NULL) { + g_string_append (authorization_header, "\",oauth_token=\""); + g_string_append_uri_escaped (authorization_header, token, NULL, FALSE); + } + + g_string_append (authorization_header, "\",oauth_signature_method=\""); + g_string_append_uri_escaped (authorization_header, signature_method, NULL, FALSE); + g_string_append (authorization_header, "\",oauth_signature=\""); + g_string_append_uri_escaped (authorization_header, signature, NULL, FALSE); + g_string_append (authorization_header, "\",oauth_timestamp=\""); + g_string_append_uri_escaped (authorization_header, timestamp, NULL, FALSE); + g_string_append (authorization_header, "\",oauth_nonce=\""); + g_string_append_uri_escaped (authorization_header, nonce, NULL, FALSE); + g_string_append (authorization_header, "\",oauth_version=\"1.0\""); + + soup_message_headers_replace (message->request_headers, "Authorization", authorization_header->str); + + g_string_free (authorization_header, TRUE); + free (signature); + g_free (timestamp); + free (nonce); +#endif /* ENABLE_OAUTH1 */ +} + +/** + * gdata_oauth1_authorizer_new: + * @application_name: (allow-none): a human-readable, translated application name to use on authentication pages, or %NULL + * @service_type: the #GType of a #GDataService subclass which the #GDataOAuth1Authorizer will be used with + * + * Creates a new #GDataOAuth1Authorizer. + * + * The #GDataAuthorizationDomains for the given @service_type (i.e. as returned by gdata_service_get_authorization_domains()) are the ones the + * user will be requested to authorize access to on the page at the URI returned by gdata_oauth1_authorizer_request_authentication_uri(). + * + * The given @application_name will set the value of #GDataOAuth1Authorizer:application-name and will be displayed to the user on authentication pages + * returned by Google. If %NULL is provided, the value of g_get_application_name() will be used as a fallback. + * + * Return value: (transfer full): a new #GDataOAuth1Authorizer; unref with g_object_unref() + * + * Since: 0.9.0 + */ +GDataOAuth1Authorizer * +gdata_oauth1_authorizer_new (const gchar *application_name, GType service_type) +{ + g_return_val_if_fail (g_type_is_a (service_type, GDATA_TYPE_SERVICE), NULL); + + return gdata_oauth1_authorizer_new_for_authorization_domains (application_name, gdata_service_get_authorization_domains (service_type)); +} + +/** + * gdata_oauth1_authorizer_new_for_authorization_domains: + * @application_name: (allow-none): a human-readable, translated application name to use on authentication pages, or %NULL + * @authorization_domains: (element-type GDataAuthorizationDomain) (transfer none): a non-empty list of #GDataAuthorizationDomains to be + * authorized against by the #GDataOAuth1Authorizer + * + * Creates a new #GDataOAuth1Authorizer. This function is intended to be used only when the default authorization domain list for a single + * #GDataService, as used by gdata_oauth1_authorizer_new(), isn't suitable. For example, this could be because the #GDataOAuth1Authorizer will be used + * with multiple #GDataService subclasses, or because the client requires a specific set of authorization domains. + * + * The specified #GDataAuthorizationDomains are the ones the user will be requested to authorize access to on the page at the URI returned by + * gdata_oauth1_authorizer_request_authentication_uri(). + * + * The given @application_name will set the value of #GDataOAuth1Authorizer:application-name and will be displayed to the user on authentication pages + * returned by Google. If %NULL is provided, the value of g_get_application_name() will be used as a fallback. + * + * Return value: (transfer full): a new #GDataOAuth1Authorizer; unref with g_object_unref() + * + * Since: 0.9.0 + */ +GDataOAuth1Authorizer * +gdata_oauth1_authorizer_new_for_authorization_domains (const gchar *application_name, GList *authorization_domains) +{ + GList *i; + GDataOAuth1Authorizer *authorizer; + + g_return_val_if_fail (authorization_domains != NULL, NULL); + + authorizer = GDATA_OAUTH1_AUTHORIZER (g_object_new (GDATA_TYPE_OAUTH1_AUTHORIZER, + "application-name", application_name, + NULL)); + + /* Register all the domains with the authorizer */ + for (i = authorization_domains; i != NULL; i = i->next) { + g_return_val_if_fail (GDATA_IS_AUTHORIZATION_DOMAIN (i->data), NULL); + + /* We don't have to lock the authoriser's mutex here as no other code has seen the authoriser yet */ + g_hash_table_insert (authorizer->priv->authorization_domains, g_object_ref (GDATA_AUTHORIZATION_DOMAIN (i->data)), i->data); + } + + return authorizer; +} + +/** + * gdata_oauth1_authorizer_request_authentication_uri: + * @self: a #GDataOAuth1Authorizer + * @token: (out callee-allocates): return location for the temporary credentials token returned by the authentication service; free with g_free() + * @token_secret: (out callee-allocates): return location for the temporary credentials token secret returned by the authentication service; free with + * g_free() + * @cancellable: (allow-none): optional #GCancellable object, or %NULL + * @error: a #GError, or %NULL + * + * Requests a fresh unauthenticated token from the Google accounts service and builds and returns the URI of an authentication page for that token. + * This should then be presented to the user (e.g. in an embedded or stand alone web browser). The authentication page will ask the user to log in + * using their Google account, then ask them to grant access to the #GDataAuthorizationDomains passed to the constructor of the + * #GDataOAuth1Authorizer. If the user grants access, they will be given a verifier, which can then be passed to + * gdata_oauth1_authorizer_request_authorization() (along with the @token and @token_secret values returned by this method) to authorize the token. + * + * This method can fail if the server returns an error, but this is unlikely. If it does happen, a %GDATA_SERVICE_ERROR_PROTOCOL_ERROR will be + * raised, @token and @token_secret will be set to %NULL and %NULL will be returned. + * + * This method implements Section 2.1 and + * Section 2.2 of the + * OAuth 1.0 protocol. + * + * When freeing @token_secret, it's advisable to set it to all zeros first, to reduce the chance of the sensitive token being recoverable from the + * free memory pool and (accidentally) leaked by a different part of the process. This can be achieved with the following code: + * |[ + * if (token_secret != NULL) { + * memset (token_secret, 0, strlen (token_secret)); + * g_free (token_secret); + * } + * ]| + * + * Return value: (transfer full): the URI of an authentication page for the user to use; free with g_free() + * + * Since: 0.9.0 + */ +gchar * +gdata_oauth1_authorizer_request_authentication_uri (GDataOAuth1Authorizer *self, gchar **token, gchar **token_secret, + GCancellable *cancellable, GError **error) +{ +#ifdef ENABLE_OAUTH1 + GDataOAuth1AuthorizerPrivate *priv; + SoupMessage *message; + guint status; + gchar *request_body; + GString *scope_string, *authentication_uri; + GHashTable *parameters; + GHashTableIter iter; + gboolean is_first = TRUE; + GDataAuthorizationDomain *domain; + GHashTable *response_details; + const gchar *callback_uri, *_token, *_token_secret, *callback_confirmed; + SoupURI *_uri; +#endif + + g_return_val_if_fail (GDATA_IS_OAUTH1_AUTHORIZER (self), NULL); + g_return_val_if_fail (token != NULL, NULL); + g_return_val_if_fail (token_secret != NULL, NULL); + g_return_val_if_fail (cancellable == NULL || G_IS_CANCELLABLE (cancellable), NULL); + g_return_val_if_fail (error == NULL || *error == NULL, NULL); + +#ifdef ENABLE_OAUTH1 + priv = self->priv; + + /* This implements OAuthGetRequestToken and returns the URI for OAuthAuthorizeToken, which the client must then use themselves (e.g. in an + * embedded web browser) to authorise the temporary credentials token. They then pass the request token and verification code they get back + * from that to gdata_oauth1_authorizer_request_authorization(). */ + + /* We default to out-of-band callbacks */ + callback_uri = "oob"; + + /* Set the output parameters to NULL in case of failure */ + *token = NULL; + *token_secret = NULL; + + /* Build up the space-separated list of scopes we're requesting authorisation for */ + g_mutex_lock (&(priv->mutex)); + + scope_string = g_string_new (NULL); + g_hash_table_iter_init (&iter, priv->authorization_domains); + + while (g_hash_table_iter_next (&iter, (gpointer*) &domain, NULL) == TRUE) { + if (is_first == FALSE) { + /* Delimiter */ + g_string_append_c (scope_string, ' '); + } + + g_string_append (scope_string, gdata_authorization_domain_get_scope (domain)); + + is_first = FALSE; + } + + g_mutex_unlock (&(priv->mutex)); + + /* Build the request body and the set of parameters to be signed */ + parameters = g_hash_table_new (g_str_hash, g_str_equal); + g_hash_table_insert (parameters, (gpointer) "scope", scope_string->str); + g_hash_table_insert (parameters, (gpointer) "xoauth_displayname", priv->application_name); + g_hash_table_insert (parameters, (gpointer) "oauth_callback", (gpointer) callback_uri); + request_body = soup_form_encode_hash (parameters); + + /* Build the message */ + _uri = soup_uri_new ("https://www.google.com/accounts/OAuthGetRequestToken"); + soup_uri_set_port (_uri, _gdata_service_get_https_port ()); + message = soup_message_new_from_uri (SOUP_METHOD_POST, _uri); + soup_uri_free (_uri); + + soup_message_set_request (message, "application/x-www-form-urlencoded", SOUP_MEMORY_TAKE, request_body, strlen (request_body)); + + sign_message (self, message, NULL, NULL, parameters); + + g_hash_table_destroy (parameters); + g_string_free (scope_string, TRUE); + + /* Send the message */ + _gdata_service_actually_send_message (priv->session, message, cancellable, error); + status = message->status_code; + + if (status == SOUP_STATUS_CANCELLED) { + /* Cancelled (the error has already been set) */ + g_object_unref (message); + return NULL; + } else if (status != SOUP_STATUS_OK) { + /* Server returned an error. Not much we can do, since the error codes aren't documented and it shouldn't normally ever happen + * anyway. */ + g_set_error_literal (error, GDATA_SERVICE_ERROR, GDATA_SERVICE_ERROR_PROTOCOL_ERROR, + _("The server rejected the temporary credentials request.")); + g_object_unref (message); + + return NULL; + } + + g_assert (message->response_body->data != NULL); + + /* Parse the response. We expect something like: + * oauth_token=ab3cd9j4ks73hf7g&oauth_token_secret=ZXhhbXBsZS5jb20&oauth_callback_confirmed=true + * See: http://code.google.com/apis/accounts/docs/OAuth_ref.html#RequestToken and + * http://tools.ietf.org/html/rfc5849#section-2.1 for details. */ + response_details = soup_form_decode (message->response_body->data); + + g_object_unref (message); + + _token = g_hash_table_lookup (response_details, "oauth_token"); + _token_secret = g_hash_table_lookup (response_details, "oauth_token_secret"); + callback_confirmed = g_hash_table_lookup (response_details, "oauth_callback_confirmed"); + + /* Validate the returned values */ + if (_token == NULL || _token_secret == NULL || callback_confirmed == NULL || + *_token == '\0' || *_token_secret == '\0' || + strcmp (callback_confirmed, "true") != 0) { + g_set_error_literal (error, GDATA_SERVICE_ERROR, GDATA_SERVICE_ERROR_PROTOCOL_ERROR, + _("The server returned a malformed response.")); + g_hash_table_destroy (response_details); + + return NULL; + } + + /* Build the authentication URI which the user will then open in a web browser and use to authenticate and authorise our application. + * We expect to build something like this: + * https://www.google.com/accounts/OAuthAuthorizeToken?oauth_token=ab3cd9j4ks73hf7g&hd=mycollege.edu&hl=en&btmpl=mobile + * See: http://code.google.com/apis/accounts/docs/OAuth_ref.html#GetAuth for more details. */ + authentication_uri = g_string_new ("https://www.google.com/accounts/OAuthAuthorizeToken?oauth_token="); + g_string_append_uri_escaped (authentication_uri, g_hash_table_lookup (response_details, "oauth_token"), NULL, TRUE); + + if (priv->locale != NULL) { + g_string_append (authentication_uri, "&hl="); + g_string_append_uri_escaped (authentication_uri, priv->locale, NULL, TRUE); + } + + /* Return the token and token secret */ + *token = g_strdup (_token); + *token_secret = g_strdup (_token_secret); /* NOTE: Ideally this would be allocated in non-pageable memory, but changing that would break API */ + + g_hash_table_destroy (response_details); + + return g_string_free (authentication_uri, FALSE); +#else /* if !ENABLE_OAUTH1 */ + *token = NULL; + *token_secret = NULL; + + if (!g_cancellable_set_error_if_cancelled (cancellable, error)) + g_set_error_literal (error, GDATA_SERVICE_ERROR, GDATA_SERVICE_ERROR_UNAVAILABLE, + _("OAuth 1.0 support is disabled.")); + + return NULL; +#endif +} + +typedef struct { + /* All return values */ + gchar *token; + gchar *token_secret; /* NOTE: Ideally this would be allocated in non-pageable memory, but changing that would break API */ + gchar *authentication_uri; +} RequestAuthenticationUriAsyncData; + +static void +request_authentication_uri_async_data_free (RequestAuthenticationUriAsyncData *data) +{ + g_free (data->token); + g_free (data->token_secret); + g_free (data->authentication_uri); + + g_slice_free (RequestAuthenticationUriAsyncData, data); +} + +G_DEFINE_AUTOPTR_CLEANUP_FUNC (RequestAuthenticationUriAsyncData, request_authentication_uri_async_data_free) + +static void +request_authentication_uri_thread (GTask *task, gpointer source_object, gpointer task_data, GCancellable *cancellable) +{ + GDataOAuth1Authorizer *authorizer = GDATA_OAUTH1_AUTHORIZER (source_object); + g_autoptr(RequestAuthenticationUriAsyncData) data = NULL; + g_autoptr(GError) error = NULL; + + data = g_slice_new0 (RequestAuthenticationUriAsyncData); + data->authentication_uri = gdata_oauth1_authorizer_request_authentication_uri (authorizer, &(data->token), &(data->token_secret), + cancellable, &error); + + if (error != NULL) + g_task_return_error (task, g_steal_pointer (&error)); + else + g_task_return_pointer (task, g_steal_pointer (&data), (GDestroyNotify) request_authentication_uri_async_data_free); +} + +/** + * gdata_oauth1_authorizer_request_authentication_uri_async: + * @self: a #GDataOAuth1Authorizer + * @cancellable: (allow-none): optional #GCancellable object, or %NULL + * @callback: a #GAsyncReadyCallback to call when building the URI is finished + * @user_data: (closure): data to pass to the @callback function + * + * Requests a fresh unauthenticated token from the Google accounts service and builds and returns the URI of an authentication page for that token. + * @self is reffed when this method is called, so can safely be unreffed after this method returns. + * + * For more details, see gdata_oauth1_authorizer_request_authentication_uri(), which is the synchronous version of this method. + * + * When the operation is finished, @callback will be called. You can then call gdata_oauth1_authorizer_request_authentication_uri_finish() to get the + * results of the operation. + * + * Since: 0.9.0 + */ +void +gdata_oauth1_authorizer_request_authentication_uri_async (GDataOAuth1Authorizer *self, GCancellable *cancellable, + GAsyncReadyCallback callback, gpointer user_data) +{ + g_autoptr(GTask) task = NULL; + + g_return_if_fail (GDATA_IS_OAUTH1_AUTHORIZER (self)); + g_return_if_fail (cancellable == NULL || G_IS_CANCELLABLE (cancellable)); + g_return_if_fail (callback != NULL); + + task = g_task_new (self, cancellable, callback, user_data); + g_task_set_source_tag (task, gdata_oauth1_authorizer_request_authentication_uri_async); + g_task_run_in_thread (task, request_authentication_uri_thread); +} + +/** + * gdata_oauth1_authorizer_request_authentication_uri_finish: + * @self: a #GDataOAuth1Authorizer + * @async_result: a #GAsyncResult + * @token: (out callee-allocates): return location for the temporary credentials token returned by the authentication service; free with g_free() + * @token_secret: (out callee-allocates): return location for the temporary credentials token secret returned by the authentication service; free with + * g_free() + * @error: a #GError, or %NULL + * + * Finishes an asynchronous authentication URI building operation started with gdata_oauth1_authorizer_request_authentication_uri_async(). + * + * This method can fail if the server has returned an error, but this is unlikely. If it does happen, a %GDATA_SERVICE_ERROR_PROTOCOL_ERROR will be + * raised, @token and @token_secret will be set to %NULL and %NULL will be returned. + * + * When freeing @token_secret, it's advisable to set it to all zeros first, to reduce the chance of the sensitive token being recoverable from the + * free memory pool and (accidentally) leaked by a different part of the process. This can be achieved with the following code: + * |[ + * if (token_secret != NULL) { + * memset (token_secret, 0, strlen (token_secret)); + * g_free (token_secret); + * } + * ]| + * + * Return value: (transfer full): the URI of an authentication page for the user to use; free with g_free() + * + * Since: 0.9.0 + */ +gchar * +gdata_oauth1_authorizer_request_authentication_uri_finish (GDataOAuth1Authorizer *self, GAsyncResult *async_result, gchar **token, + gchar **token_secret, GError **error) +{ + g_autoptr(RequestAuthenticationUriAsyncData) data = NULL; + + g_return_val_if_fail (GDATA_IS_OAUTH1_AUTHORIZER (self), NULL); + g_return_val_if_fail (G_IS_ASYNC_RESULT (async_result), NULL); + g_return_val_if_fail (token != NULL, NULL); + g_return_val_if_fail (token_secret != NULL, NULL); + g_return_val_if_fail (error == NULL || *error == NULL, NULL); + g_return_val_if_fail (g_task_is_valid (async_result, self), NULL); + g_return_val_if_fail (g_async_result_is_tagged (async_result, gdata_oauth1_authorizer_request_authentication_uri_async), NULL); + + data = g_task_propagate_pointer (G_TASK (async_result), error); + + if (data == NULL) { + /* Return the error and set all of the output parameters to NULL */ + *token = NULL; + *token_secret = NULL; + + return NULL; + } + + /* Success! Transfer the output to the appropriate parameters and nullify it so it doesn't get freed when the async result gets finalised */ + *token = g_steal_pointer (&data->token); + *token_secret = g_steal_pointer (&data->token_secret); + + return g_steal_pointer (&data->authentication_uri); +} + +/** + * gdata_oauth1_authorizer_request_authorization: + * @self: a #GDataOAuth1Authorizer + * @token: the request token returned by gdata_oauth1_authorizer_request_authentication_uri() + * @token_secret: the request token secret returned by gdata_oauth1_authorizer_request_authentication_uri() + * @verifier: the verifier entered by the user from the authentication page + * @cancellable: (allow-none): optional #GCancellable object, or %NULL + * @error: a #GError, or %NULL + * + * Requests authorization of the given request @token from the Google accounts service using the given @verifier as entered by the user from the + * authentication page at the URI returned by gdata_oauth1_authorizer_request_authentication_uri(). @token and @token_secret must be the same values + * as were returned by gdata_oauth1_authorizer_request_authentication_uri() if it was successful. + * + * If the verifier is valid (i.e. the user granted access to the application and the Google accounts service has no reason to distrust the client), + * %TRUE will be returned and any operations performed from that point onwards on #GDataServices using this #GDataAuthorizer will be + * authorized. + * + * If the user denies access to the application or the Google accounts service distrusts it, a bogus verifier could be returned. In this case, %FALSE + * will be returned and a %GDATA_SERVICE_ERROR_FORBIDDEN error will be raised. + * + * Note that if the user denies access to the application, it may be the case that they have no verifier to enter. In this case, the client can simply + * not call this method. The #GDataOAuth1Authorizer stores no state for authentication operations which have succeeded in calling + * gdata_oauth1_authorizer_request_authentication_uri() but not yet successfully called gdata_oauth1_authorizer_request_authorization(). + * + * This method implements Section 2.3 of the + * OAuth 1.0 protocol. + * + * Return value: %TRUE if authorization was successful, %FALSE otherwise + * + * Since: 0.9.0 + */ +gboolean +gdata_oauth1_authorizer_request_authorization (GDataOAuth1Authorizer *self, const gchar *token, const gchar *token_secret, const gchar *verifier, + GCancellable *cancellable, GError **error) +{ +#ifdef ENABLE_OAUTH1 + GDataOAuth1AuthorizerPrivate *priv; + SoupMessage *message; + guint status; + gchar *request_body; + GHashTable *parameters; + GHashTable *response_details; + const gchar *_token, *_token_secret; + SoupURI *_uri; +#endif + + g_return_val_if_fail (GDATA_IS_OAUTH1_AUTHORIZER (self), FALSE); + g_return_val_if_fail (token != NULL && *token != '\0', FALSE); + g_return_val_if_fail (token_secret != NULL && *token_secret != '\0', FALSE); + g_return_val_if_fail (verifier != NULL && *verifier != '\0', FALSE); + g_return_val_if_fail (cancellable == NULL || G_IS_CANCELLABLE (cancellable), FALSE); + g_return_val_if_fail (error == NULL || *error == NULL, FALSE); + +#ifdef ENABLE_OAUTH1 + /* This implements OAuthGetAccessToken using the request token returned by OAuthGetRequestToken and the verification code returned by + * OAuthAuthorizeToken. See: + * • http://code.google.com/apis/accounts/docs/OAuth_ref.html#AccessToken + * • http://tools.ietf.org/html/rfc5849#section-2.3 + */ + + priv = self->priv; + + /* Build the request body and the set of parameters to be signed */ + parameters = g_hash_table_new (g_str_hash, g_str_equal); + g_hash_table_insert (parameters, (gpointer) "oauth_verifier", (gpointer) verifier); + request_body = soup_form_encode_hash (parameters); + + /* Build the message */ + _uri = soup_uri_new ("https://www.google.com/accounts/OAuthGetAccessToken"); + soup_uri_set_port (_uri, _gdata_service_get_https_port ()); + message = soup_message_new_from_uri (SOUP_METHOD_POST, _uri); + soup_uri_free (_uri); + soup_message_set_request (message, "application/x-www-form-urlencoded", SOUP_MEMORY_TAKE, request_body, strlen (request_body)); + + sign_message (self, message, token, token_secret, parameters); + + g_hash_table_destroy (parameters); + + /* Send the message */ + _gdata_service_actually_send_message (priv->session, message, cancellable, error); + status = message->status_code; + + if (status == SOUP_STATUS_CANCELLED) { + /* Cancelled (the error has already been set) */ + g_object_unref (message); + return FALSE; + } else if (status != SOUP_STATUS_OK) { + /* Server returned an error. This either means that there was a server error or, more likely, the server doesn't trust the client + * or the user denied authorization to the token on the authorization web page. */ + g_set_error_literal (error, GDATA_SERVICE_ERROR, GDATA_SERVICE_ERROR_FORBIDDEN, _("Access was denied by the user or server.")); + g_object_unref (message); + + return FALSE; + } + + g_assert (message->response_body->data != NULL); + + /* Parse the response. We expect something like: + * oauth_token=ab3cd9j4ks73hf7g&oauth_token_secret=ZXhhbXBsZS5jb20&oauth_callback_confirmed=true + * See: http://code.google.com/apis/accounts/docs/OAuth_ref.html#AccessToken and + * http://tools.ietf.org/html/rfc5849#section-2.3 for details. */ + response_details = soup_form_decode (message->response_body->data); + + /* Zero out the response body to lower the chance of it (with all the auth. tokens it contains) hitting disk or getting leaked in + * free memory. */ + memset ((void*) message->response_body->data, 0, message->response_body->length); + + g_object_unref (message); + + _token = g_hash_table_lookup (response_details, "oauth_token"); + _token_secret = g_hash_table_lookup (response_details, "oauth_token_secret"); + + /* Validate the returned values */ + if (_token == NULL || _token_secret == NULL || + *_token == '\0' || *_token_secret == '\0') { + g_set_error_literal (error, GDATA_SERVICE_ERROR, GDATA_SERVICE_ERROR_PROTOCOL_ERROR, _("The server returned a malformed response.")); + g_hash_table_destroy (response_details); + + return FALSE; + } + + /* Store the token and token secret in the authoriser */ + g_mutex_lock (&(priv->mutex)); + + g_free (priv->token); + priv->token = g_strdup (_token); + + _gdata_service_secure_strfree (priv->token_secret); + priv->token_secret = _gdata_service_secure_strdup (_token_secret); + + g_mutex_unlock (&(priv->mutex)); + + /* Zero out the secret token before freeing the hash table, to reduce the chance of it hitting disk later. */ + memset ((void*) _token_secret, 0, strlen (_token_secret)); + + g_hash_table_destroy (response_details); + + return TRUE; +#else /* if !ENABLE_OAUTH1 */ + if (!g_cancellable_set_error_if_cancelled (cancellable, error)) + g_set_error_literal (error, GDATA_SERVICE_ERROR, GDATA_SERVICE_ERROR_UNAVAILABLE, + _("OAuth 1.0 support is disabled.")); + + return FALSE; +#endif +} + +typedef struct { + /* Input */ + gchar *token; + GDataSecureString token_secret; /* must be allocated by _gdata_service_secure_strdup() */ + gchar *verifier; +} RequestAuthorizationAsyncData; + +static void +request_authorization_async_data_free (RequestAuthorizationAsyncData *data) +{ + g_free (data->token); + _gdata_service_secure_strfree (data->token_secret); + g_free (data->verifier); + + g_slice_free (RequestAuthorizationAsyncData, data); +} + +static void +request_authorization_thread (GTask *task, gpointer source_object, gpointer task_data, GCancellable *cancellable) +{ + GDataOAuth1Authorizer *authorizer = GDATA_OAUTH1_AUTHORIZER (source_object); + RequestAuthorizationAsyncData *data = task_data; + g_autoptr(GError) error = NULL; + + if (!gdata_oauth1_authorizer_request_authorization (authorizer, data->token, data->token_secret, data->verifier, cancellable, &error)) + g_task_return_error (task, g_steal_pointer (&error)); + else + g_task_return_boolean (task, TRUE); +} + +/** + * gdata_oauth1_authorizer_request_authorization_async: + * @self: a #GDataOAuth1Authorizer + * @token: the request token returned by gdata_oauth1_authorizer_request_authentication_uri() + * @token_secret: the request token secret returned by gdata_oauth1_authorizer_request_authentication_uri() + * @verifier: the verifier entered by the user from the authentication page + * @cancellable: (allow-none): an optional #GCancellable, or %NULL + * @callback: a #GAsyncReadyCallback to call when authorization is finished + * @user_data: (closure): data to pass to the @callback function + * + * Requests authorization of the given request @token from the Google accounts service using the given @verifier as entered by the user. + * @self, @token, @token_secret and @verifier are reffed/copied when this method is called, so can safely be freed after this method returns. + * + * For more details, see gdata_oauth1_authorizer_request_authorization(), which is the synchronous version of this method. + * + * When the operation is finished, @callback will be called. You can then call gdata_oauth1_authorizer_request_authorization_finish() to get the + * results of the operation. + * + * Since: 0.9.0 + */ +void +gdata_oauth1_authorizer_request_authorization_async (GDataOAuth1Authorizer *self, const gchar *token, const gchar *token_secret, + const gchar *verifier, + GCancellable *cancellable, GAsyncReadyCallback callback, gpointer user_data) +{ + g_autoptr(GTask) task = NULL; + RequestAuthorizationAsyncData *data; + + g_return_if_fail (GDATA_IS_OAUTH1_AUTHORIZER (self)); + g_return_if_fail (token != NULL && *token != '\0'); + g_return_if_fail (token_secret != NULL && *token_secret != '\0'); + g_return_if_fail (verifier != NULL && *verifier != '\0'); + g_return_if_fail (cancellable == NULL || G_IS_CANCELLABLE (cancellable)); + + data = g_slice_new (RequestAuthorizationAsyncData); + data->token = g_strdup (token); + data->token_secret = _gdata_service_secure_strdup (token_secret); + data->verifier = g_strdup (verifier); + + task = g_task_new (self, cancellable, callback, user_data); + g_task_set_source_tag (task, gdata_oauth1_authorizer_request_authorization_async); + g_task_set_task_data (task, g_steal_pointer (&data), (GDestroyNotify) request_authorization_async_data_free); + g_task_run_in_thread (task, request_authorization_thread); +} + +/** + * gdata_oauth1_authorizer_request_authorization_finish: + * @self: a #GDataOAuth1Authorizer + * @async_result: a #GAsyncResult + * @error: a #GError, or %NULL + * + * Finishes an asynchronous authorization operation started with gdata_oauth1_authorizer_request_authorization_async(). + * + * Return value: %TRUE if authorization was successful, %FALSE otherwise + * + * Since: 0.9.0 + */ +gboolean +gdata_oauth1_authorizer_request_authorization_finish (GDataOAuth1Authorizer *self, GAsyncResult *async_result, GError **error) +{ + g_return_val_if_fail (GDATA_IS_OAUTH1_AUTHORIZER (self), FALSE); + g_return_val_if_fail (G_IS_ASYNC_RESULT (async_result), FALSE); + g_return_val_if_fail (error == NULL || *error == NULL, FALSE); + g_return_val_if_fail (g_task_is_valid (async_result, self), FALSE); + g_return_val_if_fail (g_async_result_is_tagged (async_result, gdata_oauth1_authorizer_request_authorization_async), FALSE); + + return g_task_propagate_boolean (G_TASK (async_result), error); +} + +/** + * gdata_oauth1_authorizer_get_application_name: + * @self: a #GDataOAuth1Authorizer + * + * Returns the application name being used on the authentication page at the URI returned by gdata_oauth1_authorizer_request_authentication_uri(); + * i.e. the value of #GDataOAuth1Authorizer:application-name. + * + * Return value: (allow-none): the application name, or %NULL if one isn't set + * + * Since: 0.9.0 + */ +const gchar * +gdata_oauth1_authorizer_get_application_name (GDataOAuth1Authorizer *self) +{ + g_return_val_if_fail (GDATA_IS_OAUTH1_AUTHORIZER (self), NULL); + return self->priv->application_name; +} + +/** + * gdata_oauth1_authorizer_get_locale: + * @self: a #GDataOAuth1Authorizer + * + * Returns the locale currently being used for network requests, or %NULL if the locale is the default. + * + * Return value: (allow-none): the current locale + * + * Since: 0.9.0 + */ +const gchar * +gdata_oauth1_authorizer_get_locale (GDataOAuth1Authorizer *self) +{ + g_return_val_if_fail (GDATA_IS_OAUTH1_AUTHORIZER (self), NULL); + return self->priv->locale; +} + +/** + * gdata_oauth1_authorizer_set_locale: + * @self: a #GDataOAuth1Authorizer + * @locale: (allow-none): the new locale in Unix locale format, or %NULL for the default locale + * + * Set the locale used for network requests to @locale, given in standard Unix locale format. See #GDataOAuth1Authorizer:locale for more details. + * + * Note that while it's possible to change the locale after sending network requests (i.e. calling + * gdata_oauth1_authorizer_request_authentication_uri() for the first time), it is unsupported, as the server-side software may behave unexpectedly. + * The only supported use of this method is after creation of the authorizer, but before any network requests are made. + * + * Since: 0.9.0 + */ +void +gdata_oauth1_authorizer_set_locale (GDataOAuth1Authorizer *self, const gchar *locale) +{ + g_return_if_fail (GDATA_IS_OAUTH1_AUTHORIZER (self)); + + if (g_strcmp0 (locale, self->priv->locale) == 0) { + /* Already has this value */ + return; + } + + g_free (self->priv->locale); + self->priv->locale = g_strdup (locale); + g_object_notify (G_OBJECT (self), "locale"); +} + +static void +notify_proxy_uri_cb (GObject *gobject, GParamSpec *pspec, GDataOAuth1Authorizer *self) +{ + /* Flush our cached version */ + if (self->priv->proxy_uri != NULL) { + soup_uri_free (self->priv->proxy_uri); + self->priv->proxy_uri = NULL; + } + + g_object_notify (G_OBJECT (self), "proxy-uri"); +} + +/* Static function which isn't deprecated so we can continue using it internally. */ +static SoupURI * +_get_proxy_uri (GDataOAuth1Authorizer *self) +{ + SoupURI *proxy_uri; + + g_return_val_if_fail (GDATA_IS_OAUTH1_AUTHORIZER (self), NULL); + + /* If we have a cached version, return that */ + if (self->priv->proxy_uri != NULL) { + return self->priv->proxy_uri; + } + + g_object_get (self->priv->session, SOUP_SESSION_PROXY_URI, &proxy_uri, NULL); + + /* Update the cache; it takes ownership of the URI */ + self->priv->proxy_uri = proxy_uri; + + return proxy_uri; +} + +/** + * gdata_oauth1_authorizer_get_proxy_uri: + * @self: a #GDataOAuth1Authorizer + * + * Gets the proxy URI on the #GDataOAuth1Authorizer's #SoupSession. + * + * Return value: (transfer full) (allow-none): the proxy URI, or %NULL; free with soup_uri_free() + * + * Since: 0.9.0 + * Deprecated: 0.15.0: Use gdata_oauth1_authorizer_get_proxy_resolver() instead, which gives more flexibility over the proxy used. + */ +SoupURI * +gdata_oauth1_authorizer_get_proxy_uri (GDataOAuth1Authorizer *self) +{ + return _get_proxy_uri (self); +} + +/* Static function which isn't deprecated so we can continue using it internally. */ +static void +_set_proxy_uri (GDataOAuth1Authorizer *self, SoupURI *proxy_uri) +{ + g_return_if_fail (GDATA_IS_OAUTH1_AUTHORIZER (self)); + + g_object_set (self->priv->session, SOUP_SESSION_PROXY_URI, proxy_uri, NULL); + + /* Notification is handled in notify_proxy_uri_cb() which is called as a result of setting the property on the session */ +} + +/** + * gdata_oauth1_authorizer_set_proxy_uri: + * @self: a #GDataOAuth1Authorizer + * @proxy_uri: (allow-none): the proxy URI, or %NULL + * + * Sets the proxy URI on the #SoupSession used internally by the #GDataOAuth1Authorizer. This forces all requests through the given proxy. + * + * If @proxy_uri is %NULL, no proxy will be used. + * + * Since: 0.9.0 + * Deprecated: 0.15.0: Use gdata_oauth1_authorizer_set_proxy_resolver() instead, which gives more flexibility over the proxy used. + */ +void +gdata_oauth1_authorizer_set_proxy_uri (GDataOAuth1Authorizer *self, SoupURI *proxy_uri) +{ + _set_proxy_uri (self, proxy_uri); +} + +/** + * gdata_oauth1_authorizer_get_proxy_resolver: + * @self: a #GDataOAuth1Authorizer + * + * Gets the #GProxyResolver on the #GDataOAuth1Authorizer's #SoupSession. + * + * Return value: (transfer none) (allow-none): a #GProxyResolver, or %NULL + * + * Since: 0.15.0 + */ +GProxyResolver * +gdata_oauth1_authorizer_get_proxy_resolver (GDataOAuth1Authorizer *self) +{ + g_return_val_if_fail (GDATA_IS_OAUTH1_AUTHORIZER (self), NULL); + + return self->priv->proxy_resolver; +} + +/** + * gdata_oauth1_authorizer_set_proxy_resolver: + * @self: a #GDataOAuth1Authorizer + * @proxy_resolver: (allow-none): a #GProxyResolver, or %NULL + * + * Sets the #GProxyResolver on the #SoupSession used internally by the given #GDataOAuth1Authorizer. + * + * Setting this will clear the #GDataOAuth1Authorizer:proxy-uri property. + * + * Since: 0.15.0 + */ +void +gdata_oauth1_authorizer_set_proxy_resolver (GDataOAuth1Authorizer *self, GProxyResolver *proxy_resolver) +{ + g_return_if_fail (GDATA_IS_OAUTH1_AUTHORIZER (self)); + g_return_if_fail (proxy_resolver == NULL || G_IS_PROXY_RESOLVER (proxy_resolver)); + + if (proxy_resolver != NULL) { + g_object_ref (proxy_resolver); + } + + g_clear_object (&self->priv->proxy_resolver); + self->priv->proxy_resolver = proxy_resolver; + + g_object_notify (G_OBJECT (self), "proxy-resolver"); +} + +static void +notify_timeout_cb (GObject *gobject, GParamSpec *pspec, GObject *self) +{ + g_object_notify (self, "timeout"); +} + +/** + * gdata_oauth1_authorizer_get_timeout: + * @self: a #GDataOAuth1Authorizer + * + * Gets the #GDataOAuth1Authorizer:timeout property; the network timeout, in seconds. + * + * Return value: the timeout, or 0 + * + * Since: 0.9.0 + */ +guint +gdata_oauth1_authorizer_get_timeout (GDataOAuth1Authorizer *self) +{ + guint timeout; + + g_return_val_if_fail (GDATA_IS_OAUTH1_AUTHORIZER (self), 0); + + g_object_get (self->priv->session, SOUP_SESSION_TIMEOUT, &timeout, NULL); + + return timeout; +} + +/** + * gdata_oauth1_authorizer_set_timeout: + * @self: a #GDataOAuth1Authorizer + * @timeout: the timeout, or 0 + * + * Sets the #GDataOAuth1Authorizer:timeout property; the network timeout, in seconds. + * + * If @timeout is 0, network operations will never time out. + * + * Since: 0.9.0 + */ +void +gdata_oauth1_authorizer_set_timeout (GDataOAuth1Authorizer *self, guint timeout) +{ + g_return_if_fail (GDATA_IS_OAUTH1_AUTHORIZER (self)); + + if (gdata_oauth1_authorizer_get_timeout (self) == timeout) { + /* Already has this value */ + return; + } + + g_object_set (self->priv->session, SOUP_SESSION_TIMEOUT, timeout, NULL); + + /* Notification is handled in notify_timeout_cb() which is called as a result of setting the property on the session */ +} diff --git a/gdata/gdata-oauth1-authorizer.h b/gdata/gdata-oauth1-authorizer.h new file mode 100644 index 0000000..6e16a4b --- /dev/null +++ b/gdata/gdata-oauth1-authorizer.h @@ -0,0 +1,108 @@ +/* -*- Mode: C; indent-tabs-mode: t; c-basic-offset: 8; tab-width: 8 -*- */ +/* + * GData Client + * Copyright (C) Philip Withnall 2011 + * + * GData Client is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * GData Client is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with GData Client. If not, see . + */ + +#ifndef GDATA_OAUTH1_AUTHORIZER_H +#define GDATA_OAUTH1_AUTHORIZER_H + +#include +#include + +#include "gdata-authorizer.h" + +G_BEGIN_DECLS + +#define GDATA_TYPE_OAUTH1_AUTHORIZER (gdata_oauth1_authorizer_get_type ()) +#define GDATA_OAUTH1_AUTHORIZER(o) (G_TYPE_CHECK_INSTANCE_CAST ((o), GDATA_TYPE_OAUTH1_AUTHORIZER, GDataOAuth1Authorizer)) +#define GDATA_OAUTH1_AUTHORIZER_CLASS(k) (G_TYPE_CHECK_CLASS_CAST((k), GDATA_TYPE_OAUTH1_AUTHORIZER, GDataOAuth1AuthorizerClass)) +#define GDATA_IS_OAUTH1_AUTHORIZER(o) (G_TYPE_CHECK_INSTANCE_TYPE ((o), GDATA_TYPE_OAUTH1_AUTHORIZER)) +#define GDATA_IS_OAUTH1_AUTHORIZER_CLASS(k) (G_TYPE_CHECK_CLASS_TYPE ((k), GDATA_TYPE_OAUTH1_AUTHORIZER)) +#define GDATA_OAUTH1_AUTHORIZER_GET_CLASS(o) (G_TYPE_INSTANCE_GET_CLASS ((o), GDATA_TYPE_OAUTH1_AUTHORIZER, GDataOAuth1AuthorizerClass)) + +typedef struct _GDataOAuth1AuthorizerPrivate GDataOAuth1AuthorizerPrivate; + +/** + * GDataOAuth1Authorizer: + * + * All the fields in the #GDataOAuth1Authorizer structure are private and should never be accessed directly. + * + * Since: 0.9.0 + */ +typedef struct { + /*< private >*/ + GObject parent; + GDataOAuth1AuthorizerPrivate *priv; +} GDataOAuth1Authorizer; + +/** + * GDataOAuth1AuthorizerClass: + * + * All the fields in the #GDataOAuth1AuthorizerClass structure are private and should never be accessed directly. + * + * Since: 0.9.0 + */ +typedef struct { + /*< private >*/ + GObjectClass parent; + + /*< private >*/ + /* Padding for future expansion */ + void (*_g_reserved0) (void); + void (*_g_reserved1) (void); +} GDataOAuth1AuthorizerClass; + +GType gdata_oauth1_authorizer_get_type (void) G_GNUC_CONST; +G_DEFINE_AUTOPTR_CLEANUP_FUNC (GDataOAuth1Authorizer, g_object_unref) + +GDataOAuth1Authorizer *gdata_oauth1_authorizer_new (const gchar *application_name, GType service_type) G_GNUC_WARN_UNUSED_RESULT G_GNUC_MALLOC; +GDataOAuth1Authorizer *gdata_oauth1_authorizer_new_for_authorization_domains (const gchar *application_name, + GList *authorization_domains) G_GNUC_WARN_UNUSED_RESULT G_GNUC_MALLOC; + +gchar *gdata_oauth1_authorizer_request_authentication_uri (GDataOAuth1Authorizer *self, gchar **token, gchar **token_secret, + GCancellable *cancellable, GError **error); +void gdata_oauth1_authorizer_request_authentication_uri_async (GDataOAuth1Authorizer *self, GCancellable *cancellable, + GAsyncReadyCallback callback, gpointer user_data); +gchar *gdata_oauth1_authorizer_request_authentication_uri_finish (GDataOAuth1Authorizer *self, GAsyncResult *async_result, gchar **token, + gchar **token_secret, GError **error); + +gboolean gdata_oauth1_authorizer_request_authorization (GDataOAuth1Authorizer *self, const gchar *token, const gchar *token_secret, + const gchar *verifier, GCancellable *cancellable, GError **error); +void gdata_oauth1_authorizer_request_authorization_async (GDataOAuth1Authorizer *self, const gchar *token, const gchar *token_secret, + const gchar *verifier, GCancellable *cancellable, GAsyncReadyCallback callback, + gpointer user_data); +gboolean gdata_oauth1_authorizer_request_authorization_finish (GDataOAuth1Authorizer *self, GAsyncResult *async_result, GError **error); + +const gchar *gdata_oauth1_authorizer_get_application_name (GDataOAuth1Authorizer *self) G_GNUC_PURE; + +const gchar *gdata_oauth1_authorizer_get_locale (GDataOAuth1Authorizer *self) G_GNUC_PURE; +void gdata_oauth1_authorizer_set_locale (GDataOAuth1Authorizer *self, const gchar *locale); + +#ifndef LIBGDATA_DISABLE_DEPRECATED +SoupURI *gdata_oauth1_authorizer_get_proxy_uri (GDataOAuth1Authorizer *self) G_GNUC_PURE G_GNUC_DEPRECATED_FOR (gdata_oauth1_authorizer_get_proxy_resolver); +void gdata_oauth1_authorizer_set_proxy_uri (GDataOAuth1Authorizer *self, SoupURI *proxy_uri) G_GNUC_DEPRECATED_FOR (gdata_oauth1_authorizer_set_proxy_resolver); +#endif /* !LIBGDATA_DISABLE_DEPRECATED */ + +GProxyResolver *gdata_oauth1_authorizer_get_proxy_resolver (GDataOAuth1Authorizer *self) G_GNUC_PURE; +void gdata_oauth1_authorizer_set_proxy_resolver (GDataOAuth1Authorizer *self, GProxyResolver *proxy_resolver); + +guint gdata_oauth1_authorizer_get_timeout (GDataOAuth1Authorizer *self) G_GNUC_PURE; +void gdata_oauth1_authorizer_set_timeout (GDataOAuth1Authorizer *self, guint timeout); + +G_END_DECLS + +#endif /* !GDATA_OAUTH1_AUTHORIZER_H */ diff --git a/gdata/gdata-oauth2-authorizer.c b/gdata/gdata-oauth2-authorizer.c new file mode 100644 index 0000000..a08a265 --- /dev/null +++ b/gdata/gdata-oauth2-authorizer.c @@ -0,0 +1,1592 @@ +/* -*- Mode: C; indent-tabs-mode: t; c-basic-offset: 8; tab-width: 8 -*- */ +/* + * GData Client + * Copyright (C) Philip Withnall 2011, 2014, 2015 + * + * GData Client is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * GData Client is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with GData Client. If not, see . + */ + +/** + * SECTION:gdata-oauth2-authorizer + * @short_description: GData OAuth 2.0 authorization interface + * @stability: Stable + * @include: gdata/gdata-oauth2-authorizer.h + * + * #GDataOAuth2Authorizer provides an implementation of the #GDataAuthorizer + * interface for authentication and authorization using the + * OAuth 2.0 + * process, which is Google’s currently preferred authentication and + * authorization process. + * + * OAuth 2.0 replaces the deprecated OAuth 1.0 and ClientLogin processes. One of + * the main reasons for this is to allow two-factor authentication to be + * supported, by moving the authentication interface to a web page under + * Google’s control. + * + * The OAuth 2.0 process as implemented by Google follows the + * OAuth 2.0 + * protocol as specified by IETF in RFC 6749, with a few additions to + * support scopes (implemented in libgdata by #GDataAuthorizationDomains), + * locales and custom domains. Briefly, the process is initiated by building an + * authentication URI (using gdata_oauth2_authorizer_build_authentication_uri()) + * and opening it in the user’s web browser. The user authenticates and + * authorizes the requested scopes on Google’s website, then an authorization + * code is returned (via #GDataOAuth2Authorizer:redirect-uri) to the + * application, which then converts the code into an access and refresh token + * (using gdata_oauth2_authorizer_request_authorization()). The access token is + * then attached to all future requests to the online service, and the refresh + * token can be used in future (with gdata_authorizer_refresh_authorization()) + * to refresh authorization after the access token expires. + * + * The refresh token may also be accessed as + * #GDataOAuth2Authorizer:refresh-token and saved by the application. It may + * later be set on a new instance of #GDataOAuth2Authorizer, and + * gdata_authorizer_refresh_authorization_async() called to establish a new + * access token without requiring the user to re-authenticate unless they have + * explicitly revoked the refresh token. + * + * For an overview of the standard OAuth 2.0 flow, see + * RFC 6749. + * + * Before an application can be authorized using OAuth 2.0, it must be + * registered with + * Google’s + * Developer Console, and a client ID, client secret and redirect URI + * retrieved. These must be built into your application, and knowledge of them + * will allow any application to impersonate yours, so it is recommended that + * they are kept secret (e.g. as a configure-time option). + * + * libgdata supports + * incremental + * authorization, where multiple #GDataOAuth2Authorizers can be used to + * incrementally build up authorizations against multiple scopes. Typically, + * you should use one #GDataOAuth2Authorizer per #GDataService your application + * uses, limit the scope of each authorizer, and enable incremental + * authorization when calling + * gdata_oauth2_authorizer_build_authentication_uri(). + * + * Each access token is long lived, so reauthorization is rarely necessary with + * #GDataOAuth2Authorizer. It is supported using + * gdata_authorizer_refresh_authorization(). + * + * + * Authenticating Asynchronously Using OAuth 2.0 + * + * GDataSomeService *service; + * GDataOAuth2Authorizer *authorizer; + * gchar *authentication_uri, *authorization_code; + * + * /* Create an authorizer and authenticate and authorize the service we're using, asynchronously. */ + * authorizer = gdata_oauth2_authorizer_new ("some-client-id", "some-client-secret", + * GDATA_OAUTH2_REDIRECT_URI_OOB, GDATA_TYPE_SOME_SERVICE); + * authentication_uri = gdata_oauth2_authorizer_build_authentication_uri (authorizer, NULL, FALSE); + * + * /* (Present the page at the authentication URI to the user, either in an embedded or stand-alone web browser, and + * * ask them to grant access to the application and return the code Google gives them.) */ + * authorization_code = ask_user_for_code (authentication_uri); + * + * gdata_oauth2_authorizer_request_authorization_async (authorizer, authorization_code, cancellable, + * (GAsyncReadyCallback) request_authorization_cb, user_data); + * + * g_free (authentication_uri); + * + * /* Zero out the code before freeing. */ + * if (token_secret != NULL) { + * memset (authorization_code, 0, strlen (authorization_code)); + * } + * + * g_free (authorization_code); + * + * /* Create a service object and link it with the authorizer */ + * service = gdata_some_service_new (GDATA_AUTHORIZER (authorizer)); + * + * static void + * request_authorization_cb (GDataOAuth2Authorizer *authorizer, GAsyncResult *async_result, gpointer user_data) + * { + * GError *error = NULL; + * + * if (gdata_oauth2_authorizer_request_authorization_finish (authorizer, async_result, &error) == FALSE) { + * /* Notify the user of all errors except cancellation errors */ + * if (!g_error_matches (error, G_IO_ERROR, G_IO_ERROR_CANCELLED)) { + * g_error ("Authorization failed: %s", error->message); + * } + * + * g_error_free (error); + * return; + * } + * + * /* (The client is now authenticated and authorized against the service. + * * It can now proceed to execute queries on the service object which require the user to be authenticated.) */ + * } + * + * g_object_unref (service); + * g_object_unref (authorizer); + * + * + * + * Since: 0.17.0 + */ + +#include +#include +#include +#include + +#include "gdata-oauth2-authorizer.h" +#include "gdata-private.h" + +static void authorizer_init (GDataAuthorizerInterface *iface); +static void dispose (GObject *object); +static void finalize (GObject *object); +static void get_property (GObject *object, guint property_id, GValue *value, + GParamSpec *pspec); +static void set_property (GObject *object, guint property_id, + const GValue *value, GParamSpec *pspec); + +static void process_request (GDataAuthorizer *self, + GDataAuthorizationDomain *domain, + SoupMessage *message); +static void sign_message_locked (GDataOAuth2Authorizer *self, + SoupMessage *message, + const gchar *access_token); +static gboolean is_authorized_for_domain (GDataAuthorizer *self, + GDataAuthorizationDomain *domain); +static gboolean refresh_authorization (GDataAuthorizer *self, + GCancellable *cancellable, + GError **error); + +static void parse_grant_response (GDataOAuth2Authorizer *self, guint status, + const gchar *reason_phrase, + const gchar *response_body, gssize length, + GError **error); +static void parse_grant_error (GDataOAuth2Authorizer *self, guint status, + const gchar *reason_phrase, + const gchar *response_body, gssize length, + GError **error); + +static void notify_timeout_cb (GObject *gobject, GParamSpec *pspec, + GObject *self); + +struct _GDataOAuth2AuthorizerPrivate { + SoupSession *session; /* owned */ + GProxyResolver *proxy_resolver; /* owned */ + + gchar *client_id; /* owned */ + gchar *redirect_uri; /* owned */ + gchar *client_secret; /* owned */ + gchar *locale; /* owned */ + + /* Mutex for access_token, refresh_token and authentication_domains. */ + GMutex mutex; + + /* These are both non-NULL when authorised. refresh_token may be + * non-NULL if access_token is NULL and refresh_authorization() has not + * yet been called on this authorizer. They may be both NULL. */ + gchar *access_token; /* owned */ + gchar *refresh_token; /* owned */ + + /* Mapping from GDataAuthorizationDomain to itself; a set of domains for + * which ->access_token is valid. */ + GHashTable *authentication_domains; /* owned */ +}; + +enum { + PROP_CLIENT_ID = 1, + PROP_REDIRECT_URI, + PROP_CLIENT_SECRET, + PROP_LOCALE, + PROP_TIMEOUT, + PROP_PROXY_RESOLVER, + PROP_REFRESH_TOKEN, +}; + +G_DEFINE_TYPE_WITH_CODE (GDataOAuth2Authorizer, gdata_oauth2_authorizer, + G_TYPE_OBJECT, + G_IMPLEMENT_INTERFACE (GDATA_TYPE_AUTHORIZER, + authorizer_init)) + +static void +gdata_oauth2_authorizer_class_init (GDataOAuth2AuthorizerClass *klass) +{ + GObjectClass *gobject_class = G_OBJECT_CLASS (klass); + + g_type_class_add_private (klass, sizeof (GDataOAuth2AuthorizerPrivate)); + + gobject_class->get_property = get_property; + gobject_class->set_property = set_property; + gobject_class->dispose = dispose; + gobject_class->finalize = finalize; + + /** + * GDataOAuth2Authorizer:client-id: + * + * A client ID for your application (see the + * reference documentation). + * + * It is recommended that the ID is of the form + * company name- + * application name- + * version ID. + * + * Since: 0.17.0 + */ + g_object_class_install_property (gobject_class, PROP_CLIENT_ID, + g_param_spec_string ("client-id", + "Client ID", + "A client ID for your application.", + NULL, + G_PARAM_CONSTRUCT_ONLY | G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)); + + /** + * GDataOAuth2Authorizer:redirect-uri: + * + * Redirect URI to send the response from the authorisation request to. + * This must either be %GDATA_OAUTH2_REDIRECT_URI_OOB, + * %GDATA_OAUTH2_REDIRECT_URI_OOB_AUTO, or a + * http://localhost URI with any port number (optionally) + * specified. + * + * This URI is where the authorisation server will redirect the user + * after they have completed interacting with the authentication page + * (gdata_oauth2_authorizer_build_authentication_uri()). If it is + * %GDATA_OAUTH2_REDIRECT_URI_OOB, a page will be returned in the user’s + * browser with the authorisation code in its title and also embedded in + * the page for the user to copy if it is not possible to automatically + * extract the code from the page title. If it is + * %GDATA_OAUTH2_REDIRECT_URI_OOB_AUTO, a similar page will be returned + * with the authorisation code in its title, but without displaying the + * code to the user — the user will simply be asked to close the page. + * If it is a localhost URI, the authentication page will redirect to + * that URI with the authorisation code appended as a code + * query parameter. If the user denies the authentication request, the + * authentication page will redirect to that URI with + * error=access_denied appended as a query parameter. + * + * Note that the redirect URI used must match that registered in + * Google’s Developer Console for your application. + * + * See the reference + * documentation for details about choosing a redirect URI. + * + * Since: 0.17.0 + */ + g_object_class_install_property (gobject_class, PROP_REDIRECT_URI, + g_param_spec_string ("redirect-uri", + "Redirect URI", + "Redirect URI to send the response from the authorisation request to.", + NULL, + G_PARAM_CONSTRUCT_ONLY | G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)); + + /** + * GDataOAuth2Authorizer:client-secret: + * + * Client secret provided by Google. This is unique for each application + * and is accessible from Google’s Developer Console when registering + * an application. It must be paired with the + * #GDataOAuth2Authorizer:client-id. + * + * See the + * reference + * documentation for details. + * + * Since: 0.17.0 + */ + g_object_class_install_property (gobject_class, PROP_CLIENT_SECRET, + g_param_spec_string ("client-secret", + "Client secret", + "Client secret provided by Google.", + NULL, + G_PARAM_CONSTRUCT_ONLY | G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)); + + /** + * GDataOAuth2Authorizer:locale: + * + * The locale to use for network requests, in UNIX locale format. + * (e.g. "en_GB", "cs", "de_DE".) Use %NULL for the default "C" locale + * (typically "en_US"). + * + * This locale will be used by the server-side software to localise the + * authentication and authorization pages at the URI returned by + * gdata_oauth2_authorizer_build_authentication_uri(). + * + * The server-side behaviour is undefined if it doesn't support a given + * locale. + * + * Since: 0.17.0 + */ + g_object_class_install_property (gobject_class, PROP_LOCALE, + g_param_spec_string ("locale", + "Locale", + "The locale to use for network requests, in UNIX locale format.", + NULL, + G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)); + + /** + * GDataOAuth2Authorizer:timeout: + * + * A timeout, in seconds, for network operations. If the timeout is + * exceeded, the operation will be cancelled and + * %GDATA_SERVICE_ERROR_NETWORK_ERROR will be returned. + * + * If the timeout is 0, operations will + * never time out. + * + * Since: 0.17.0 + */ + g_object_class_install_property (gobject_class, PROP_TIMEOUT, + g_param_spec_uint ("timeout", + "Timeout", + "A timeout, in seconds, for network operations.", + 0, G_MAXUINT, 0, + G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)); + + /** + * GDataOAuth2Authorizer:proxy-resolver: + * + * The #GProxyResolver used to determine a proxy URI. + * + * Since: 0.17.0 + */ + g_object_class_install_property (gobject_class, PROP_PROXY_RESOLVER, + g_param_spec_object ("proxy-resolver", + "Proxy Resolver", + "A GProxyResolver used to determine a proxy URI.", + G_TYPE_PROXY_RESOLVER, + G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)); + + /** + * GDataOAuth2Authorizer:refresh-token: + * + * The server provided refresh token, which can be stored and passed in + * to new #GDataOAuth2Authorizer instances before calling + * gdata_authorizer_refresh_authorization_async() to create a new + * short-lived access token. + * + * The refresh token is opaque data and must not be parsed. + * + * Since: 0.17.2 + */ + g_object_class_install_property (gobject_class, PROP_REFRESH_TOKEN, + g_param_spec_string ("refresh-token", + "Refresh Token", + "The server provided refresh token.", + NULL, + G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)); +} + +static void +authorizer_init (GDataAuthorizerInterface *iface) +{ + iface->process_request = process_request; + iface->is_authorized_for_domain = is_authorized_for_domain; + + /* We only implement the synchronous version, as GDataAuthorizer will + * automatically wrap it in a thread for the asynchronous versions if + * they’re not specifically implemented, which is fine for our needs. We + * couldn’t do any better by implementing the asynchronous versions + * ourselves. */ + iface->refresh_authorization = refresh_authorization; +} + +static void +gdata_oauth2_authorizer_init (GDataOAuth2Authorizer *self) +{ + self->priv = G_TYPE_INSTANCE_GET_PRIVATE (self, + GDATA_TYPE_OAUTH2_AUTHORIZER, + GDataOAuth2AuthorizerPrivate); + + /* Set up the authorizer's mutex */ + g_mutex_init (&self->priv->mutex); + self->priv->authentication_domains = g_hash_table_new_full (g_direct_hash, + g_direct_equal, + g_object_unref, + NULL); + + /* Set up the session */ + self->priv->session = _gdata_service_build_session (); + + /* Proxy the SoupSession’s timeout property. */ + g_signal_connect (self->priv->session, "notify::timeout", + (GCallback) notify_timeout_cb, self); + + /* Keep our GProxyResolver synchronized with SoupSession’s. */ + g_object_bind_property (self->priv->session, "proxy-resolver", + self, "proxy-resolver", + G_BINDING_BIDIRECTIONAL | G_BINDING_SYNC_CREATE); +} + +static void +dispose (GObject *object) +{ + GDataOAuth2AuthorizerPrivate *priv; + + priv = GDATA_OAUTH2_AUTHORIZER (object)->priv; + + g_clear_object (&priv->session); + g_clear_object (&priv->proxy_resolver); + + /* Chain up to the parent class */ + G_OBJECT_CLASS (gdata_oauth2_authorizer_parent_class)->dispose (object); +} + +static void +finalize (GObject *object) +{ + GDataOAuth2AuthorizerPrivate *priv; + + priv = GDATA_OAUTH2_AUTHORIZER (object)->priv; + + g_free (priv->client_id); + g_free (priv->client_secret); + g_free (priv->redirect_uri); + g_free (priv->locale); + + g_free (priv->access_token); + g_free (priv->refresh_token); + + g_hash_table_unref (priv->authentication_domains); + g_mutex_clear (&priv->mutex); + + /* Chain up to the parent class */ + G_OBJECT_CLASS (gdata_oauth2_authorizer_parent_class)->finalize (object); +} + +static void +get_property (GObject *object, guint property_id, GValue *value, + GParamSpec *pspec) +{ + GDataOAuth2Authorizer *self; + GDataOAuth2AuthorizerPrivate *priv; + + self = GDATA_OAUTH2_AUTHORIZER (object); + priv = self->priv; + + switch (property_id) { + case PROP_CLIENT_ID: + g_value_set_string (value, priv->client_id); + break; + case PROP_REDIRECT_URI: + g_value_set_string (value, priv->redirect_uri); + break; + case PROP_CLIENT_SECRET: + g_value_set_string (value, priv->client_secret); + break; + case PROP_LOCALE: + g_value_set_string (value, priv->locale); + break; + case PROP_TIMEOUT: + g_value_set_uint (value, + gdata_oauth2_authorizer_get_timeout (self)); + break; + case PROP_PROXY_RESOLVER: + g_value_set_object (value, + gdata_oauth2_authorizer_get_proxy_resolver (self)); + break; + case PROP_REFRESH_TOKEN: + g_mutex_lock (&priv->mutex); + g_value_set_string (value, priv->refresh_token); + g_mutex_unlock (&priv->mutex); + break; + default: + /* We don't have any other property... */ + G_OBJECT_WARN_INVALID_PROPERTY_ID (object, property_id, pspec); + break; + } +} + +static void +set_property (GObject *object, guint property_id, const GValue *value, GParamSpec *pspec) +{ + GDataOAuth2Authorizer *self; + GDataOAuth2AuthorizerPrivate *priv; + + self = GDATA_OAUTH2_AUTHORIZER (object); + priv = self->priv; + + switch (property_id) { + /* Construct only. */ + case PROP_CLIENT_ID: + priv->client_id = g_value_dup_string (value); + break; + /* Construct only. */ + case PROP_REDIRECT_URI: + priv->redirect_uri = g_value_dup_string (value); + break; + /* Construct only. */ + case PROP_CLIENT_SECRET: + priv->client_secret = g_value_dup_string (value); + break; + case PROP_LOCALE: + gdata_oauth2_authorizer_set_locale (self, + g_value_get_string (value)); + break; + case PROP_TIMEOUT: + gdata_oauth2_authorizer_set_timeout (self, + g_value_get_uint (value)); + break; + case PROP_PROXY_RESOLVER: + gdata_oauth2_authorizer_set_proxy_resolver (self, + g_value_get_object (value)); + break; + case PROP_REFRESH_TOKEN: + gdata_oauth2_authorizer_set_refresh_token (self, + g_value_get_string (value)); + break; + default: + /* We don't have any other property... */ + G_OBJECT_WARN_INVALID_PROPERTY_ID (object, property_id, pspec); + break; + } +} + +static void +process_request (GDataAuthorizer *self, GDataAuthorizationDomain *domain, + SoupMessage *message) +{ + GDataOAuth2AuthorizerPrivate *priv; + + priv = GDATA_OAUTH2_AUTHORIZER (self)->priv; + + /* Set the authorisation header */ + g_mutex_lock (&priv->mutex); + + /* Sanity check */ + g_assert ((priv->access_token == NULL) || + (priv->refresh_token != NULL)); + + if (priv->access_token != NULL && + g_hash_table_lookup (priv->authentication_domains, + domain) != NULL) { + sign_message_locked (GDATA_OAUTH2_AUTHORIZER (self), message, + priv->access_token); + } + + g_mutex_unlock (&priv->mutex); +} + +static gboolean +is_authorized_for_domain (GDataAuthorizer *self, + GDataAuthorizationDomain *domain) +{ + GDataOAuth2AuthorizerPrivate *priv; + gpointer result; + const gchar *access_token; + + priv = GDATA_OAUTH2_AUTHORIZER (self)->priv; + + g_mutex_lock (&priv->mutex); + access_token = priv->access_token; + result = g_hash_table_lookup (priv->authentication_domains, domain); + g_mutex_unlock (&priv->mutex); + + /* Sanity check */ + g_assert (result == NULL || result == domain); + + return (access_token != NULL && result != NULL); +} + +/* Sign the message and add the Authorization header to it containing the + * signature. + * + * Reference: https://developers.google.com/accounts/docs/OAuth2InstalledApp#callinganapi + * + * NOTE: This must be called with the mutex locked. */ +static void +sign_message_locked (GDataOAuth2Authorizer *self, SoupMessage *message, + const gchar *access_token) +{ + SoupURI *message_uri; /* unowned */ + gchar *auth_header = NULL; /* owned */ + + g_return_if_fail (GDATA_IS_OAUTH2_AUTHORIZER (self)); + g_return_if_fail (SOUP_IS_MESSAGE (message)); + g_return_if_fail (access_token != NULL && *access_token != '\0'); + + /* Ensure that we’re using HTTPS: if not, we shouldn’t set the + * Authorization header or we could be revealing the access + * token to anyone snooping the connection, which would give + * them the same rights as us on the user’s data. Generally a + * bad thing to happen. */ + message_uri = soup_message_get_uri (message); + + if (message_uri->scheme != SOUP_URI_SCHEME_HTTPS) { + g_warning ("Not authorizing a non-HTTPS message with the " + "user’s OAuth 2.0 access token as the connection " + "isn’t secure."); + return; + } + + /* Add the authorisation header. */ + auth_header = g_strdup_printf ("Bearer %s", access_token); + soup_message_headers_append (message->request_headers, + "Authorization", auth_header); + g_free (auth_header); +} + +static gboolean +refresh_authorization (GDataAuthorizer *self, GCancellable *cancellable, + GError **error) +{ + /* See http://code.google.com/apis/accounts/docs/OAuth2.html#IAMoreToken */ + GDataOAuth2AuthorizerPrivate *priv; + SoupMessage *message = NULL; /* owned */ + SoupURI *_uri = NULL; /* owned */ + gchar *request_body; + guint status; + GError *child_error = NULL; + + g_return_val_if_fail (GDATA_IS_OAUTH2_AUTHORIZER (self), FALSE); + + priv = GDATA_OAUTH2_AUTHORIZER (self)->priv; + + g_mutex_lock (&priv->mutex); + + /* If we don’t have a refresh token, we can’t refresh the + * authorisation. Do not set @error, as we haven’t been successfully + * authorised previously. */ + if (priv->refresh_token == NULL) { + g_mutex_unlock (&priv->mutex); + return FALSE; + } + + /* Prepare the request */ + request_body = soup_form_encode ("client_id", priv->client_id, + "client_secret", priv->client_secret, + "refresh_token", priv->refresh_token, + "grant_type", "refresh_token", + NULL); + + g_mutex_unlock (&priv->mutex); + + /* Build the message */ + _uri = soup_uri_new ("https://accounts.google.com/o/oauth2/token"); + soup_uri_set_port (_uri, _gdata_service_get_https_port ()); + message = soup_message_new_from_uri (SOUP_METHOD_POST, _uri); + soup_uri_free (_uri); + + soup_message_set_request (message, "application/x-www-form-urlencoded", + SOUP_MEMORY_TAKE, request_body, + strlen (request_body)); + + /* Send the message */ + _gdata_service_actually_send_message (priv->session, message, + cancellable, error); + status = message->status_code; + + if (status == SOUP_STATUS_CANCELLED) { + /* Cancelled (the error has already been set) */ + g_object_unref (message); + return FALSE; + } else if (status != SOUP_STATUS_OK) { + parse_grant_error (GDATA_OAUTH2_AUTHORIZER (self), + status, message->reason_phrase, + message->response_body->data, + message->response_body->length, + error); + g_object_unref (message); + + return FALSE; + } + + g_assert (message->response_body->data != NULL); + + /* Parse and handle the response */ + parse_grant_response (GDATA_OAUTH2_AUTHORIZER (self), + status, message->reason_phrase, + message->response_body->data, + message->response_body->length, &child_error); + + g_object_unref (message); + + if (child_error != NULL) { + g_propagate_error (error, child_error); + return FALSE; + } + + return TRUE; +} + +/** + * gdata_oauth2_authorizer_new: + * @client_id: your application’s client ID + * @client_secret: your application’s client secret + * @redirect_uri: authorisation redirect URI + * @service_type: the #GType of a #GDataService subclass which the + * #GDataOAuth2Authorizer will be used with + * + * Creates a new #GDataOAuth2Authorizer. The @client_id must be unique for your + * application, and as registered with Google, and the @client_secret must be + * paired with it. + * + * Return value: (transfer full): a new #GDataOAuth2Authorizer; unref with + * g_object_unref() + * + * Since: 0.17.0 + */ +GDataOAuth2Authorizer * +gdata_oauth2_authorizer_new (const gchar *client_id, const gchar *client_secret, + const gchar *redirect_uri, GType service_type) +{ + GList/**/ *domains; /* owned */ + GDataOAuth2Authorizer *retval = NULL; /* owned */ + + g_return_val_if_fail (client_id != NULL && *client_id != '\0', NULL); + g_return_val_if_fail (client_secret != NULL && *client_secret != '\0', + NULL); + g_return_val_if_fail (redirect_uri != NULL && *redirect_uri != '\0', + NULL); + g_return_val_if_fail (g_type_is_a (service_type, GDATA_TYPE_SERVICE), + NULL); + + domains = gdata_service_get_authorization_domains (service_type); + + retval = gdata_oauth2_authorizer_new_for_authorization_domains (client_id, + client_secret, + redirect_uri, + domains); + g_list_free (domains); + + return retval; +} + +/** + * gdata_oauth2_authorizer_new_for_authorization_domains: + * @client_id: your application’s client ID + * @client_secret: your application’s client secret + * @redirect_uri: authorisation redirect URI + * @authorization_domains: (element-type GDataAuthorizationDomain) (transfer none): + * a non-empty list of #GDataAuthorizationDomains to be authorized against by + * the #GDataOAuth2Authorizer + * + * Creates a new #GDataOAuth2Authorizer. The @client_id must be unique for your + * application, and as registered with Google, and the @client_secret must be + * paired with it. + * + * Return value: (transfer full): a new #GDataOAuth2Authorizer; unref with + * g_object_unref() + * + * Since: 0.17.0 + */ +GDataOAuth2Authorizer * +gdata_oauth2_authorizer_new_for_authorization_domains (const gchar *client_id, + const gchar *client_secret, + const gchar *redirect_uri, + GList *authorization_domains) +{ + GList *i; + GDataOAuth2Authorizer *authorizer; + + g_return_val_if_fail (client_id != NULL && *client_id != '\0', NULL); + g_return_val_if_fail (client_secret != NULL && *client_secret != '\0', + NULL); + g_return_val_if_fail (redirect_uri != NULL && *redirect_uri != '\0', + NULL); + g_return_val_if_fail (authorization_domains != NULL, NULL); + + authorizer = GDATA_OAUTH2_AUTHORIZER (g_object_new (GDATA_TYPE_OAUTH2_AUTHORIZER, + "client-id", client_id, + "client-secret", client_secret, + "redirect-uri", redirect_uri, + NULL)); + + /* Register all the domains with the authorizer */ + for (i = authorization_domains; i != NULL; i = i->next) { + GDataAuthorizationDomain *domain; /* unowned */ + + g_return_val_if_fail (GDATA_IS_AUTHORIZATION_DOMAIN (i->data), + NULL); + + /* We don’t have to lock the authoriser’s mutex here as no other + * code has seen the authoriser yet */ + domain = GDATA_AUTHORIZATION_DOMAIN (i->data); + g_hash_table_insert (authorizer->priv->authentication_domains, + g_object_ref (domain), domain); + } + + return authorizer; +} + +/** + * gdata_oauth2_authorizer_build_authentication_uri: + * @self: a #GDataOAuth2Authorizer + * @login_hint: (nullable): optional e-mail address or sub identifier for the + * user + * @include_granted_scopes: %TRUE to enable incremental authorisation + * + * Build an authentication URI to open in the user’s web browser (or an embedded + * browser widget). This will display an authentication page from Google, + * including an authentication form and confirmation of the authorisation + * domains being requested by this #GDataAuthorizer. The user will authenticate + * in the browser, then an authorisation code will be returned via the + * #GDataOAuth2Authorizer:redirect-uri, ready to be passed to + * gdata_oauth2_authorizer_request_authorization(). + * + * If @login_hint is non-%NULL, it will be passed to the server as a hint of + * which user is attempting to authenticate, which can be used to pre-fill the + * e-mail address box in the authentication form. + * + * If @include_granted_scopes is %TRUE, the authentication request will + * automatically include all authorisation domains previously granted to this + * user/application pair, allowing for incremental authentication — asking for + * permissions as needed, rather than all in one large bundle at the first + * opportunity. If @include_granted_scopes is %FALSE, incremental authentication + * will not be enabled, and only the domains passed to the + * #GDataOAuth2Authorizer constructor will eventually be authenticated. + * See the + * reference + * documentation for more details. + * + * Return value: (transfer full): the authentication URI to open in a web + * browser; free with g_free() + * + * Since: 0.17.0 + */ +gchar * +gdata_oauth2_authorizer_build_authentication_uri (GDataOAuth2Authorizer *self, + const gchar *login_hint, + gboolean include_granted_scopes) +{ + GDataOAuth2AuthorizerPrivate *priv; + GString *uri = NULL; /* owned */ + GDataAuthorizationDomain *domain; /* unowned */ + GHashTableIter iter; + gboolean is_first = TRUE; + + g_return_val_if_fail (GDATA_IS_OAUTH2_AUTHORIZER (self), NULL); + + priv = self->priv; + + g_mutex_lock (&priv->mutex); + + /* Build and memoise the URI. + * + * Reference: https://developers.google.com/accounts/docs/OAuth2InstalledApp#formingtheurl + */ + g_assert (g_hash_table_size (priv->authentication_domains) > 0); + + uri = g_string_new ("https://accounts.google.com/o/oauth2/auth" + "?response_type=code" + "&client_id="); + g_string_append_uri_escaped (uri, priv->client_id, NULL, TRUE); + g_string_append (uri, "&redirect_uri="); + g_string_append_uri_escaped (uri, priv->redirect_uri, NULL, TRUE); + g_string_append (uri, "&scope="); + + /* Add the scopes of all our domains */ + g_hash_table_iter_init (&iter, priv->authentication_domains); + + while (g_hash_table_iter_next (&iter, (gpointer *) &domain, NULL)) { + const gchar *scope; + + if (!is_first) { + /* Delimiter */ + g_string_append (uri, "%20"); + } + + scope = gdata_authorization_domain_get_scope (domain); + g_string_append_uri_escaped (uri, scope, NULL, TRUE); + + is_first = FALSE; + } + + if (login_hint != NULL && *login_hint != '\0') { + g_string_append (uri, "&login_hint="); + g_string_append_uri_escaped (uri, login_hint, NULL, TRUE); + } + + if (priv->locale != NULL) { + g_string_append (uri, "&hl="); + g_string_append_uri_escaped (uri, priv->locale, NULL, TRUE); + } + + if (include_granted_scopes) { + g_string_append (uri, "&include_granted_scopes=true"); + } else { + g_string_append (uri, "&include_granted_scopes=false"); + } + + g_mutex_unlock (&priv->mutex); + + return g_string_free (uri, FALSE); +} + +/* NOTE: This has to be thread safe, as it can be called from + * refresh_authorization() at any time. + * + * Reference: https://developers.google.com/accounts/docs/OAuth2InstalledApp#handlingtheresponse + */ +static void +parse_grant_response (GDataOAuth2Authorizer *self, guint status, + const gchar *reason_phrase, const gchar *response_body, + gssize length, GError **error) +{ + GDataOAuth2AuthorizerPrivate *priv; + JsonParser *parser = NULL; /* owned */ + JsonNode *root_node; /* unowned */ + JsonObject *root_object; /* unowned */ + const gchar *access_token = NULL, *refresh_token = NULL; + GError *child_error = NULL; + + priv = self->priv; + + /* Parse the successful response */ + parser = json_parser_new (); + + json_parser_load_from_data (parser, response_body, length, + &child_error); + + if (child_error != NULL) { + g_clear_error (&child_error); + g_set_error_literal (&child_error, GDATA_SERVICE_ERROR, + GDATA_SERVICE_ERROR_PROTOCOL_ERROR, + _("The server returned a malformed response.")); + + goto done; + } + + /* Extract the access token, TTL and refresh token */ + root_node = json_parser_get_root (parser); + + if (JSON_NODE_HOLDS_OBJECT (root_node) == FALSE) { + g_set_error_literal (&child_error, GDATA_SERVICE_ERROR, + GDATA_SERVICE_ERROR_PROTOCOL_ERROR, + _("The server returned a malformed response.")); + goto done; + } + + root_object = json_node_get_object (root_node); + + if (json_object_has_member (root_object, "access_token")) { + access_token = json_object_get_string_member (root_object, + "access_token"); + } + if (json_object_has_member (root_object, "refresh_token")) { + refresh_token = json_object_get_string_member (root_object, + "refresh_token"); + } + + /* Always require an access token. */ + if (access_token == NULL || *access_token == '\0') { + g_set_error_literal (&child_error, GDATA_SERVICE_ERROR, + GDATA_SERVICE_ERROR_PROTOCOL_ERROR, + _("The server returned a malformed response.")); + + access_token = NULL; + refresh_token = NULL; + + goto done; + } + + /* Only require a refresh token if this is the first authentication. + * See the documentation for refreshing authentication: + * https://developers.google.com/accounts/docs/OAuth2InstalledApp#refresh + */ + if ((refresh_token == NULL || *refresh_token == '\0') && + priv->refresh_token == NULL) { + g_set_error_literal (&child_error, GDATA_SERVICE_ERROR, + GDATA_SERVICE_ERROR_PROTOCOL_ERROR, + _("The server returned a malformed response.")); + + access_token = NULL; + refresh_token = NULL; + + goto done; + } + +done: + /* Postconditions. */ + g_assert ((refresh_token == NULL) || (access_token != NULL)); + g_assert ((child_error != NULL) == (access_token == NULL)); + + /* Update state. */ + g_mutex_lock (&priv->mutex); + + g_free (priv->access_token); + priv->access_token = g_strdup (access_token); + + if (refresh_token != NULL) { + g_free (priv->refresh_token); + priv->refresh_token = g_strdup (refresh_token); + } + + g_mutex_unlock (&priv->mutex); + + if (child_error != NULL) { + g_propagate_error (error, child_error); + } + + g_object_unref (parser); +} + +/* NOTE: This has to be thread safe, as it can be called from + * refresh_authorization() at any time. + * + * There is no reference for this, because Google apparently don’t deem it + * necessary to document. + * + * Example response: + * HTTP/1.1 400 Bad Request + * Content-Type: application/json + * + * { + * "error" : "invalid_grant" + * } + */ +static void +parse_grant_error (GDataOAuth2Authorizer *self, guint status, + const gchar *reason_phrase, const gchar *response_body, + gssize length, GError **error) +{ + JsonParser *parser = NULL; /* owned */ + JsonNode *root_node; /* unowned */ + JsonObject *root_object; /* unowned */ + const gchar *error_code = NULL; + GError *child_error = NULL; + + /* Parse the error response */ + parser = json_parser_new (); + + if (response_body == NULL) { + g_clear_error (&child_error); + g_set_error_literal (&child_error, GDATA_SERVICE_ERROR, + GDATA_SERVICE_ERROR_PROTOCOL_ERROR, + _("The server returned a malformed response.")); + + goto done; + } + + json_parser_load_from_data (parser, response_body, length, + &child_error); + + if (child_error != NULL) { + g_clear_error (&child_error); + g_set_error_literal (&child_error, GDATA_SERVICE_ERROR, + GDATA_SERVICE_ERROR_PROTOCOL_ERROR, + _("The server returned a malformed response.")); + + goto done; + } + + /* Extract the error code. */ + root_node = json_parser_get_root (parser); + + if (JSON_NODE_HOLDS_OBJECT (root_node) == FALSE) { + g_set_error_literal (&child_error, GDATA_SERVICE_ERROR, + GDATA_SERVICE_ERROR_PROTOCOL_ERROR, + _("The server returned a malformed response.")); + goto done; + } + + root_object = json_node_get_object (root_node); + + if (json_object_has_member (root_object, "error")) { + error_code = json_object_get_string_member (root_object, + "error"); + } + + /* Always require an error_code. */ + if (error_code == NULL || *error_code == '\0') { + g_set_error_literal (&child_error, GDATA_SERVICE_ERROR, + GDATA_SERVICE_ERROR_PROTOCOL_ERROR, + _("The server returned a malformed response.")); + + error_code = NULL; + + goto done; + } + + /* Parse the error code. */ + if (strcmp (error_code, "invalid_grant") == 0) { + g_set_error_literal (&child_error, GDATA_SERVICE_ERROR, + GDATA_SERVICE_ERROR_FORBIDDEN, + _("Access was denied by the user or server.")); + } else { + /* Unknown error code. */ + g_set_error_literal (&child_error, GDATA_SERVICE_ERROR, + GDATA_SERVICE_ERROR_PROTOCOL_ERROR, + _("The server returned a malformed response.")); + } + +done: + /* Postconditions. */ + g_assert (child_error != NULL); + + if (child_error != NULL) { + g_propagate_error (error, child_error); + } + + g_object_unref (parser); +} + +/** + * gdata_oauth2_authorizer_request_authorization: + * @self: a #GDataOAuth2Authorizer + * @authorization_code: code returned from the authentication page + * @cancellable: (allow-none): a #GCancellable, or %NULL + * @error: return location for a #GError, or %NULL + * + * Request an authorisation code from the user’s web browser is converted to + * authorisation (access and refresh) tokens. This is the final step in the + * authentication process; once complete, the #GDataOAuth2Authorizer should be + * fully authorised for its domains. + * + * On failure, %GDATA_SERVICE_ERROR_FORBIDDEN will be returned if the user or + * server denied the authorisation request. %GDATA_SERVICE_ERROR_PROTOCOL_ERROR + * will be returned if the server didn’t follow the expected protocol. + * %G_IO_ERROR_CANCELLED will be returned if the operation was cancelled using + * @cancellable. + * + * Return value: %TRUE on success, %FALSE otherwise + * + * Since: 0.17.0 + */ +gboolean +gdata_oauth2_authorizer_request_authorization (GDataOAuth2Authorizer *self, + const gchar *authorization_code, + GCancellable *cancellable, + GError **error) +{ + GDataOAuth2AuthorizerPrivate *priv; + SoupMessage *message = NULL; /* owned */ + SoupURI *_uri = NULL; /* owned */ + gchar *request_body = NULL; /* owned */ + guint status; + GError *child_error = NULL; + + g_return_val_if_fail (GDATA_IS_OAUTH2_AUTHORIZER (self), FALSE); + g_return_val_if_fail (authorization_code != NULL && + *authorization_code != '\0', FALSE); + g_return_val_if_fail (cancellable == NULL || + G_IS_CANCELLABLE (cancellable), FALSE); + g_return_val_if_fail (error == NULL || *error == NULL, FALSE); + + priv = self->priv; + + /* Prepare the request. + * + * Reference: https://developers.google.com/accounts/docs/OAuth2InstalledApp#handlingtheresponse + */ + request_body = soup_form_encode ("client_id", priv->client_id, + "client_secret", priv->client_secret, + "code", authorization_code, + "redirect_uri", priv->redirect_uri, + "grant_type", "authorization_code", + NULL); + + /* Build the message */ + _uri = soup_uri_new ("https://accounts.google.com/o/oauth2/token"); + soup_uri_set_port (_uri, _gdata_service_get_https_port ()); + message = soup_message_new_from_uri (SOUP_METHOD_POST, _uri); + soup_uri_free (_uri); + + soup_message_set_request (message, "application/x-www-form-urlencoded", + SOUP_MEMORY_TAKE, request_body, + strlen (request_body)); + request_body = NULL; + + /* Send the message */ + _gdata_service_actually_send_message (priv->session, message, + cancellable, error); + status = message->status_code; + + if (status == SOUP_STATUS_CANCELLED) { + /* Cancelled (the error has already been set) */ + g_object_unref (message); + return FALSE; + } else if (status != SOUP_STATUS_OK) { + parse_grant_error (self, status, message->reason_phrase, + message->response_body->data, + message->response_body->length, + error); + g_object_unref (message); + + return FALSE; + } + + g_assert (message->response_body->data != NULL); + + /* Parse and handle the response */ + parse_grant_response (self, status, message->reason_phrase, + message->response_body->data, + message->response_body->length, &child_error); + + g_object_unref (message); + + if (child_error != NULL) { + g_propagate_error (error, child_error); + return FALSE; + } + + return TRUE; +} + +static void +request_authorization_thread (GTask *task, + gpointer source_object, + gpointer task_data, + GCancellable *cancellable) +{ + GDataOAuth2Authorizer *authorizer = GDATA_OAUTH2_AUTHORIZER (source_object); + g_autoptr(GError) error = NULL; + const gchar *authorization_code = task_data; + + if (!gdata_oauth2_authorizer_request_authorization (authorizer, + authorization_code, + cancellable, + &error)) + g_task_return_error (task, g_steal_pointer (&error)); + else + g_task_return_boolean (task, TRUE); +} + +/** + * gdata_oauth2_authorizer_request_authorization_async: + * @self: a #GDataOAuth2Authorizer + * @authorization_code: code returned from the authentication page + * @cancellable: (allow-none): an optional #GCancellable, or %NULL + * @callback: a #GAsyncReadyCallback to call when authorization is finished + * @user_data: (closure): data to pass to the @callback function + * + * Asynchronous version of gdata_oauth2_authorizer_request_authorization(). + * + * Since: 0.17.0 + */ +void +gdata_oauth2_authorizer_request_authorization_async (GDataOAuth2Authorizer *self, + const gchar *authorization_code, + GCancellable *cancellable, + GAsyncReadyCallback callback, + gpointer user_data) +{ + g_autoptr(GTask) task = NULL; + + g_return_if_fail (GDATA_IS_OAUTH2_AUTHORIZER (self)); + g_return_if_fail (authorization_code != NULL && + *authorization_code != '\0'); + g_return_if_fail (cancellable == NULL || + G_IS_CANCELLABLE (cancellable)); + + task = g_task_new (self, cancellable, callback, user_data); + g_task_set_source_tag (task, gdata_oauth2_authorizer_request_authorization_async); + g_task_set_task_data (task, g_strdup (authorization_code), + (GDestroyNotify) g_free); + g_task_run_in_thread (task, request_authorization_thread); +} + +/** + * gdata_oauth2_authorizer_request_authorization_finish: + * @self: a #GDataOAuth2Authorizer + * @async_result: a #GAsyncResult + * @error: a #GError, or %NULL + * + * Finishes an asynchronous authorization operation started with + * gdata_oauth2_authorizer_request_authorization_async(). + * + * Return value: %TRUE if authorization was successful, %FALSE otherwise + * + * Since: 0.17.0 + */ +gboolean +gdata_oauth2_authorizer_request_authorization_finish (GDataOAuth2Authorizer *self, + GAsyncResult *async_result, + GError **error) +{ + g_return_val_if_fail (GDATA_IS_OAUTH2_AUTHORIZER (self), FALSE); + g_return_val_if_fail (G_IS_ASYNC_RESULT (async_result), FALSE); + g_return_val_if_fail (error == NULL || *error == NULL, FALSE); + g_return_val_if_fail (g_task_is_valid (async_result, self), FALSE); + g_return_val_if_fail (g_async_result_is_tagged (async_result, gdata_oauth2_authorizer_request_authorization_async), FALSE); + + return g_task_propagate_boolean (G_TASK (async_result), error); +} + +/** + * gdata_oauth2_authorizer_get_client_id: + * @self: a #GDataOAuth2Authorizer + * + * Returns the authorizer's client ID, #GDataOAuth2Authorizer:client-id, as + * specified on constructing the #GDataOAuth2Authorizer. + * + * Return value: the authorizer's client ID + * + * Since: 0.17.0 + */ +const gchar * +gdata_oauth2_authorizer_get_client_id (GDataOAuth2Authorizer *self) +{ + g_return_val_if_fail (GDATA_IS_OAUTH2_AUTHORIZER (self), NULL); + return self->priv->client_id; +} + +/** + * gdata_oauth2_authorizer_get_redirect_uri: + * @self: a #GDataOAuth2Authorizer + * + * Returns the authorizer’s redirect URI, #GDataOAuth2Authorizer:redirect-uri, + * as specified on constructing the #GDataOAuth2Authorizer. + * + * Return value: the authorizer’s redirect URI + * + * Since: 0.17.0 + */ +const gchar * +gdata_oauth2_authorizer_get_redirect_uri (GDataOAuth2Authorizer *self) +{ + g_return_val_if_fail (GDATA_IS_OAUTH2_AUTHORIZER (self), NULL); + return self->priv->redirect_uri; +} + +/** + * gdata_oauth2_authorizer_get_client_secret: + * @self: a #GDataOAuth2Authorizer + * + * Returns the authorizer's client secret, #GDataOAuth2Authorizer:client-secret, + * as specified on constructing the #GDataOAuth2Authorizer. + * + * Return value: the authorizer's client secret + * + * Since: 0.17.0 + */ +const gchar * +gdata_oauth2_authorizer_get_client_secret (GDataOAuth2Authorizer *self) +{ + g_return_val_if_fail (GDATA_IS_OAUTH2_AUTHORIZER (self), NULL); + return self->priv->client_secret; +} + +/** + * gdata_oauth2_authorizer_dup_refresh_token: + * @self: a #GDataOAuth2Authorizer + * + * Returns the authorizer's refresh token, #GDataOAuth2Authorizer:refresh-token, + * as set by client code previously on the #GDataOAuth2Authorizer, or as + * returned by the most recent authentication operation. + * + * Return value: (transfer full): the authorizer's refresh token + * + * Since: 0.17.2 + */ +gchar * +gdata_oauth2_authorizer_dup_refresh_token (GDataOAuth2Authorizer *self) +{ + GDataOAuth2AuthorizerPrivate *priv; + gchar *refresh_token; /* owned */ + + g_return_val_if_fail (GDATA_IS_OAUTH2_AUTHORIZER (self), NULL); + + priv = self->priv; + + g_mutex_lock (&priv->mutex); + refresh_token = g_strdup (priv->refresh_token); + g_mutex_unlock (&priv->mutex); + + return refresh_token; +} + +/** + * gdata_oauth2_authorizer_set_refresh_token: + * @self: a #GDataOAuth2Authorizer + * @refresh_token: (nullable): the new refresh token, or %NULL to clear + * authorization + * + * Sets the authorizer's refresh token, #GDataOAuth2Authorizer:refresh-token. + * This is used to periodically refresh the access token. Set it to %NULL to + * clear the current authentication from the authorizer. + * + * Since: 0.17.2 + */ +void +gdata_oauth2_authorizer_set_refresh_token (GDataOAuth2Authorizer *self, + const gchar *refresh_token) +{ + GDataOAuth2AuthorizerPrivate *priv; + + g_return_if_fail (GDATA_IS_OAUTH2_AUTHORIZER (self)); + + priv = self->priv; + + g_mutex_lock (&priv->mutex); + + if (g_strcmp0 (priv->refresh_token, refresh_token) == 0) { + g_mutex_unlock (&priv->mutex); + return; + } + + /* Clear the access token; if the refresh token has changed, it can + * no longer be valid, and we must avoid the situation: + * (access_token != NULL) && (refresh_token == NULL) */ + g_free (priv->access_token); + priv->access_token = NULL; + + /* Update the refresh token. */ + g_free (priv->refresh_token); + priv->refresh_token = g_strdup (refresh_token); + + g_mutex_unlock (&priv->mutex); + + g_object_notify (G_OBJECT (self), "refresh-token"); +} + +/** + * gdata_oauth2_authorizer_get_locale: + * @self: a #GDataOAuth2Authorizer + * + * Returns the locale currently being used for network requests, or %NULL if the + * locale is the default. + * + * Return value: (allow-none): the current locale + * + * Since: 0.17.0 + */ +const gchar * +gdata_oauth2_authorizer_get_locale (GDataOAuth2Authorizer *self) +{ + g_return_val_if_fail (GDATA_IS_OAUTH2_AUTHORIZER (self), NULL); + return self->priv->locale; +} + +/** + * gdata_oauth2_authorizer_set_locale: + * @self: a #GDataOAuth2Authorizer + * @locale: (allow-none): the new locale in UNIX locale format, or %NULL for the + * default locale + * + * Set the locale used for network requests to @locale, given in standard UNIX + * locale format. See #GDataOAuth2Authorizer:locale for more details. + * + * Note that while it’s possible to change the locale after sending network + * requests (i.e. calling gdata_oauth2_authorizer_build_authentication_uri() for + * the first time), it is unsupported, as the server-side software may behave + * unexpectedly. The only supported use of this method is after creation of the + * authorizer, but before any network requests are made. + * + * Since: 0.17.0 + */ +void +gdata_oauth2_authorizer_set_locale (GDataOAuth2Authorizer *self, + const gchar *locale) +{ + g_return_if_fail (GDATA_IS_OAUTH2_AUTHORIZER (self)); + + if (g_strcmp0 (locale, self->priv->locale) == 0) { + /* Already has this value */ + return; + } + + g_free (self->priv->locale); + self->priv->locale = g_strdup (locale); + g_object_notify (G_OBJECT (self), "locale"); +} + +static void +notify_timeout_cb (GObject *gobject, GParamSpec *pspec, GObject *self) +{ + g_object_notify (self, "timeout"); +} + +/** + * gdata_oauth2_authorizer_get_timeout: + * @self: a #GDataOAuth2Authorizer + * + * Gets the #GDataOAuth2Authorizer:timeout property; the network timeout, in + * seconds. + * + * Return value: the timeout, or 0 + * + * Since: 0.17.0 + */ +guint +gdata_oauth2_authorizer_get_timeout (GDataOAuth2Authorizer *self) +{ + guint timeout; + + g_return_val_if_fail (GDATA_IS_OAUTH2_AUTHORIZER (self), 0); + + g_object_get (self->priv->session, + SOUP_SESSION_TIMEOUT, &timeout, + NULL); + + return timeout; +} + +/** + * gdata_oauth2_authorizer_set_timeout: + * @self: a #GDataOAuth2Authorizer + * @timeout: the timeout, or 0 + * + * Sets the #GDataOAuth2Authorizer:timeout property; the network timeout, in + * seconds. + * + * If @timeout is 0, network operations will never + * time out. + * + * Since: 0.17.0 + */ +void +gdata_oauth2_authorizer_set_timeout (GDataOAuth2Authorizer *self, guint timeout) +{ + g_return_if_fail (GDATA_IS_OAUTH2_AUTHORIZER (self)); + + if (timeout == gdata_oauth2_authorizer_get_timeout (self)) { + return; + } + + g_object_set (self->priv->session, SOUP_SESSION_TIMEOUT, timeout, NULL); +} + +/** + * gdata_oauth2_authorizer_get_proxy_resolver: + * @self: a #GDataOAuth2Authorizer + * + * Gets the #GProxyResolver on the #GDataOAuth2Authorizer's #SoupSession. + * + * Return value: (transfer none) (allow-none): a #GProxyResolver, or %NULL + * + * Since: 0.17.0 + */ +GProxyResolver * +gdata_oauth2_authorizer_get_proxy_resolver (GDataOAuth2Authorizer *self) +{ + g_return_val_if_fail (GDATA_IS_OAUTH2_AUTHORIZER (self), NULL); + + return self->priv->proxy_resolver; +} + +/** + * gdata_oauth2_authorizer_set_proxy_resolver: + * @self: a #GDataOAuth2Authorizer + * @proxy_resolver: (allow-none): a #GProxyResolver, or %NULL + * + * Sets the #GProxyResolver on the #SoupSession used internally by the given + * #GDataOAuth2Authorizer. + * + * Since: 0.17.0 + */ +void +gdata_oauth2_authorizer_set_proxy_resolver (GDataOAuth2Authorizer *self, + GProxyResolver *proxy_resolver) +{ + g_return_if_fail (GDATA_IS_OAUTH2_AUTHORIZER (self)); + g_return_if_fail (proxy_resolver == NULL || + G_IS_PROXY_RESOLVER (proxy_resolver)); + + if (proxy_resolver != NULL) { + g_object_ref (proxy_resolver); + } + + g_clear_object (&self->priv->proxy_resolver); + self->priv->proxy_resolver = proxy_resolver; + + g_object_notify (G_OBJECT (self), "proxy-resolver"); +} diff --git a/gdata/gdata-oauth2-authorizer.h b/gdata/gdata-oauth2-authorizer.h new file mode 100644 index 0000000..97cd1e2 --- /dev/null +++ b/gdata/gdata-oauth2-authorizer.h @@ -0,0 +1,137 @@ +/* -*- Mode: C; indent-tabs-mode: t; c-basic-offset: 8; tab-width: 8 -*- */ +/* + * GData Client + * Copyright (C) Philip Withnall 2011, 2014, 2015 + * + * GData Client is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * GData Client is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with GData Client. If not, see . + */ + +#ifndef GDATA_OAUTH2_AUTHORIZER_H +#define GDATA_OAUTH2_AUTHORIZER_H + +#include +#include + +#include "gdata-authorizer.h" + +G_BEGIN_DECLS + +/** + * GDATA_OAUTH2_REDIRECT_URI_OOB: + * + * OAuth 2 redirect URI for out-of-band authorisation code transfer, where the + * user is shown the authorisation code and asked to copy it. + * + * See + * reference + * documentation for details. + * + * Since: 0.17.0 + */ +#define GDATA_OAUTH2_REDIRECT_URI_OOB "urn:ietf:wg:oauth:2.0:oob" + +/** + * GDATA_OAUTH2_REDIRECT_URI_OOB_AUTO: + * + * OAuth 2 redirect URI for out-of-band authorisation code transfer, where the + * user is not shown the authorisation code or asked to copy it. + * + * See + * reference + * documentation for details. + * + * Since: 0.17.0 + */ +#define GDATA_OAUTH2_REDIRECT_URI_OOB_AUTO "urn:ietf:wg:oauth:2.0:oob:auto" + +#define GDATA_TYPE_OAUTH2_AUTHORIZER (gdata_oauth2_authorizer_get_type ()) +#define GDATA_OAUTH2_AUTHORIZER(o) (G_TYPE_CHECK_INSTANCE_CAST ((o), GDATA_TYPE_OAUTH2_AUTHORIZER, GDataOAuth2Authorizer)) +#define GDATA_OAUTH2_AUTHORIZER_CLASS(k) (G_TYPE_CHECK_CLASS_CAST((k), GDATA_TYPE_OAUTH2_AUTHORIZER, GDataOAuth2AuthorizerClass)) +#define GDATA_IS_OAUTH2_AUTHORIZER(o) (G_TYPE_CHECK_INSTANCE_TYPE ((o), GDATA_TYPE_OAUTH2_AUTHORIZER)) +#define GDATA_IS_OAUTH2_AUTHORIZER_CLASS(k) (G_TYPE_CHECK_CLASS_TYPE ((k), GDATA_TYPE_OAUTH2_AUTHORIZER)) +#define GDATA_OAUTH2_AUTHORIZER_GET_CLASS(o) (G_TYPE_INSTANCE_GET_CLASS ((o), GDATA_TYPE_OAUTH2_AUTHORIZER, GDataOAuth2AuthorizerClass)) + +typedef struct _GDataOAuth2AuthorizerPrivate GDataOAuth2AuthorizerPrivate; + +/** + * GDataOAuth2Authorizer: + * + * All the fields in the #GDataOAuth2Authorizer structure are private and should never be accessed directly. + * + * Since: 0.17.0 + */ +typedef struct { + /*< private >*/ + GObject parent; + GDataOAuth2AuthorizerPrivate *priv; +} GDataOAuth2Authorizer; + +/** + * GDataOAuth2AuthorizerClass: + * + * All the fields in the #GDataOAuth2AuthorizerClass structure are private and should never be accessed directly. + * + * Since: 0.17.0 + */ +typedef struct { + /*< private >*/ + GObjectClass parent; + + /*< private >*/ + /* Padding for future expansion */ + void (*_g_reserved0) (void); + void (*_g_reserved1) (void); +} GDataOAuth2AuthorizerClass; + +GType gdata_oauth2_authorizer_get_type (void) G_GNUC_CONST; +G_DEFINE_AUTOPTR_CLEANUP_FUNC (GDataOAuth2Authorizer, g_object_unref) + +GDataOAuth2Authorizer *gdata_oauth2_authorizer_new (const gchar *client_id, + const gchar *client_secret, + const gchar *redirect_uri, + GType service_type) G_GNUC_WARN_UNUSED_RESULT G_GNUC_MALLOC; +GDataOAuth2Authorizer *gdata_oauth2_authorizer_new_for_authorization_domains (const gchar *client_id, + const gchar *client_secret, + const gchar *redirect_uri, + GList *authorization_domains) G_GNUC_WARN_UNUSED_RESULT G_GNUC_MALLOC; + +gchar *gdata_oauth2_authorizer_build_authentication_uri (GDataOAuth2Authorizer *self, + const gchar *login_hint, + gboolean include_granted_scopes) G_GNUC_PURE; + +gboolean gdata_oauth2_authorizer_request_authorization (GDataOAuth2Authorizer *self, const gchar *authorization_code, + GCancellable *cancellable, GError **error); +void gdata_oauth2_authorizer_request_authorization_async (GDataOAuth2Authorizer *self, const gchar *authorization_code, + GCancellable *cancellable, GAsyncReadyCallback callback, gpointer user_data); +gboolean gdata_oauth2_authorizer_request_authorization_finish (GDataOAuth2Authorizer *self, GAsyncResult *async_result, GError **error); + +const gchar *gdata_oauth2_authorizer_get_client_id (GDataOAuth2Authorizer *self) G_GNUC_PURE; +const gchar *gdata_oauth2_authorizer_get_redirect_uri (GDataOAuth2Authorizer *self) G_GNUC_PURE; +const gchar *gdata_oauth2_authorizer_get_client_secret (GDataOAuth2Authorizer *self) G_GNUC_PURE; + +gchar *gdata_oauth2_authorizer_dup_refresh_token (GDataOAuth2Authorizer *self) G_GNUC_PURE; +void gdata_oauth2_authorizer_set_refresh_token (GDataOAuth2Authorizer *self, const gchar *refresh_token); + +const gchar *gdata_oauth2_authorizer_get_locale (GDataOAuth2Authorizer *self) G_GNUC_PURE; +void gdata_oauth2_authorizer_set_locale (GDataOAuth2Authorizer *self, const gchar *locale); + +guint gdata_oauth2_authorizer_get_timeout (GDataOAuth2Authorizer *self) G_GNUC_PURE; +void gdata_oauth2_authorizer_set_timeout (GDataOAuth2Authorizer *self, guint timeout); + +GProxyResolver *gdata_oauth2_authorizer_get_proxy_resolver (GDataOAuth2Authorizer *self) G_GNUC_PURE; +void gdata_oauth2_authorizer_set_proxy_resolver (GDataOAuth2Authorizer *self, GProxyResolver *proxy_resolver); + +G_END_DECLS + +#endif /* !GDATA_OAUTH2_AUTHORIZER_H */ diff --git a/gdata/gdata-parsable.c b/gdata/gdata-parsable.c new file mode 100644 index 0000000..80b1a10 --- /dev/null +++ b/gdata/gdata-parsable.c @@ -0,0 +1,781 @@ +/* -*- Mode: C; indent-tabs-mode: t; c-basic-offset: 8; tab-width: 8 -*- */ +/* + * GData Client + * Copyright (C) Philip Withnall 2009–2010 + * + * GData Client is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * GData Client is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with GData Client. If not, see . + */ + +/** + * SECTION:gdata-parsable + * @short_description: GData parsable object + * @stability: Stable + * @include: gdata/gdata-parsable.h + * + * #GDataParsable is an abstract class allowing easy implementation of an extensible parser. It is primarily extended by #GDataFeed and #GDataEntry, + * both of which require XML parsing which can be extended by subclassing. + * + * It allows methods to be defined for handling the root XML node, each of its child nodes, and a method to be called after parsing is complete. + * + * Since: 0.3.0 + */ + +#include +#include +#include +#include +#include +#include + +#include "gdata-parsable.h" +#include "gdata-private.h" +#include "gdata-parser.h" + +GQuark +gdata_parser_error_quark (void) +{ + return g_quark_from_static_string ("gdata-parser-error-quark"); +} + +static void gdata_parsable_get_property (GObject *object, guint property_id, GValue *value, GParamSpec *pspec); +static void gdata_parsable_set_property (GObject *object, guint property_id, const GValue *value, GParamSpec *pspec); +static void gdata_parsable_finalize (GObject *object); +static gboolean real_parse_xml (GDataParsable *parsable, xmlDoc *doc, xmlNode *node, gpointer user_data, GError **error); +static gboolean real_parse_json (GDataParsable *parsable, JsonReader *reader, gpointer user_data, GError **error); +static const gchar *get_content_type (void); + +struct _GDataParsablePrivate { + /* XML stuff. */ + GString *extra_xml; + GHashTable *extra_namespaces; + + /* JSON stuff. */ + GHashTable/**/ *extra_json; + + gboolean constructed_from_xml; +}; + +enum { + PROP_CONSTRUCTED_FROM_XML = 1, +}; + +G_DEFINE_ABSTRACT_TYPE (GDataParsable, gdata_parsable, G_TYPE_OBJECT) + +static void +gdata_parsable_class_init (GDataParsableClass *klass) +{ + GObjectClass *gobject_class = G_OBJECT_CLASS (klass); + + g_type_class_add_private (klass, sizeof (GDataParsablePrivate)); + + gobject_class->get_property = gdata_parsable_get_property; + gobject_class->set_property = gdata_parsable_set_property; + gobject_class->finalize = gdata_parsable_finalize; + klass->parse_xml = real_parse_xml; + klass->parse_json = real_parse_json; + klass->get_content_type = get_content_type; + + /** + * GDataParsable:constructed-from-xml: + * + * Specifies whether the object was constructed by parsing XML or manually. + * + * Since: 0.7.0 + */ + g_object_class_install_property (gobject_class, PROP_CONSTRUCTED_FROM_XML, + g_param_spec_boolean ("constructed-from-xml", + "Constructed from XML?", + "Specifies whether the object was constructed by parsing XML or manually.", + FALSE, + G_PARAM_CONSTRUCT_ONLY | G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)); +} + +static void +gdata_parsable_init (GDataParsable *self) +{ + self->priv = G_TYPE_INSTANCE_GET_PRIVATE (self, GDATA_TYPE_PARSABLE, GDataParsablePrivate); + + self->priv->extra_xml = g_string_new (""); + self->priv->extra_namespaces = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, g_free); + + self->priv->extra_json = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, (GDestroyNotify) json_node_free); + + self->priv->constructed_from_xml = FALSE; +} + + +static void +gdata_parsable_get_property (GObject *object, guint property_id, GValue *value, GParamSpec *pspec) +{ + GDataParsablePrivate *priv = GDATA_PARSABLE (object)->priv; + + switch (property_id) { + case PROP_CONSTRUCTED_FROM_XML: + g_value_set_boolean (value, priv->constructed_from_xml); + break; + default: + /* We don't have any other property... */ + G_OBJECT_WARN_INVALID_PROPERTY_ID (object, property_id, pspec); + break; + } +} + +static void +gdata_parsable_set_property (GObject *object, guint property_id, const GValue *value, GParamSpec *pspec) +{ + GDataParsablePrivate *priv = GDATA_PARSABLE (object)->priv; + + switch (property_id) { + case PROP_CONSTRUCTED_FROM_XML: + priv->constructed_from_xml = g_value_get_boolean (value); + break; + default: + /* We don't have any other property... */ + G_OBJECT_WARN_INVALID_PROPERTY_ID (object, property_id, pspec); + break; + } +} + +static void +gdata_parsable_finalize (GObject *object) +{ + GDataParsablePrivate *priv = GDATA_PARSABLE (object)->priv; + + g_string_free (priv->extra_xml, TRUE); + g_hash_table_destroy (priv->extra_namespaces); + + g_hash_table_destroy (priv->extra_json); + + /* Chain up to the parent class */ + G_OBJECT_CLASS (gdata_parsable_parent_class)->finalize (object); +} + +static gboolean +real_parse_xml (GDataParsable *parsable, xmlDoc *doc, xmlNode *node, gpointer user_data, GError **error) +{ + xmlBuffer *buffer; + xmlNs **namespaces, **namespace; + + /* Unhandled XML */ + buffer = xmlBufferCreate (); + xmlNodeDump (buffer, doc, node, 0, 0); + g_string_append (parsable->priv->extra_xml, (gchar*) xmlBufferContent (buffer)); + g_debug ("Unhandled XML in %s: %s", G_OBJECT_TYPE_NAME (parsable), (gchar*) xmlBufferContent (buffer)); + xmlBufferFree (buffer); + + /* Get the namespaces */ + namespaces = xmlGetNsList (doc, node); + if (namespaces == NULL) + return TRUE; + + for (namespace = namespaces; *namespace != NULL; namespace++) { + if ((*namespace)->prefix != NULL) { + /* NOTE: These two g_strdup()s leak, but it's probably acceptable, given that it saves us + * g_strdup()ing every other namespace we put in @extra_namespaces. */ + g_hash_table_insert (parsable->priv->extra_namespaces, + g_strdup ((gchar*) ((*namespace)->prefix)), + g_strdup ((gchar*) ((*namespace)->href))); + } + } + xmlFree (namespaces); + + return TRUE; +} + +/* Extract the member node. This would be a lot easier if JsonReader had an API to return + * the current node (regardless of whether it's a value, object or array). FIXME: bgo#707100. */ +static JsonNode * /* transfer full */ +_json_reader_dup_current_node (JsonReader *reader) +{ + JsonNode *value; + + if (json_reader_is_value (reader) == TRUE) { + /* Value nodes are easy. Well, ignoring the complication of nulls. */ + if (json_reader_get_null_value (reader) == TRUE) { + value = json_node_new (JSON_NODE_NULL); + } else { + value = json_node_copy (json_reader_get_value (reader)); + } + } else if (json_reader_is_object (reader) == TRUE) { + /* Object nodes require deep copies. */ + gint i; + gchar **members; + JsonObject *obj; + + obj = json_object_new (); + + for (i = 0, members = json_reader_list_members (reader); members[i] != NULL; i++) { + json_reader_read_member (reader, members[i]); + json_object_set_member (obj, members[i], _json_reader_dup_current_node (reader)); + json_reader_end_member (reader); + } + + g_strfreev (members); + + value = json_node_new (JSON_NODE_OBJECT); + json_node_take_object (value, obj); + } else if (json_reader_is_array (reader) == TRUE) { + /* Array nodes require deep copies. */ + gint i, elements; + JsonArray *arr; + + arr = json_array_new (); + + for (i = 0, elements = json_reader_count_elements (reader); i < elements; i++) { + json_reader_read_element (reader, i); + json_array_add_element (arr, _json_reader_dup_current_node (reader)); + json_reader_end_element (reader); + } + + value = json_node_new (JSON_NODE_ARRAY); + json_node_take_array (value, arr); + } else { + /* Uh-oh. */ + g_assert_not_reached (); + } + + return value; +} + +static gboolean +real_parse_json (GDataParsable *parsable, JsonReader *reader, gpointer user_data, GError **error) +{ + gchar *json, *member_name; + JsonGenerator *generator; + JsonNode *value; + + /* Unhandled JSON member. Save it and its value to ->extra_xml so that it's not lost if we + * re-upload this Parsable to the server. */ + member_name = g_strdup (json_reader_get_member_name (reader)); + g_assert (member_name != NULL); + + /* Extract a copy of the current node. */ + value = _json_reader_dup_current_node (reader); + g_assert (value != NULL); + + /* Serialise the value for debugging. */ + generator = json_generator_new (); + json_generator_set_root (generator, value); + + json = json_generator_to_data (generator, NULL); + g_debug ("Unhandled JSON member ‘%s’ in %s: %s", member_name, G_OBJECT_TYPE_NAME (parsable), json); + g_free (json); + + g_object_unref (generator); + + /* Save the value. Transfer ownership of the member_name and value. */ + g_hash_table_replace (parsable->priv->extra_json, (gpointer) member_name, (gpointer) value); + + return TRUE; +} + +static const gchar * +get_content_type (void) { + return "application/atom+xml"; +} + +/** + * gdata_parsable_new_from_xml: + * @parsable_type: the type of the class represented by the XML + * @xml: the XML for just the parsable object, with full namespace declarations + * @length: the length of @xml, or -1 + * @error: a #GError, or %NULL + * + * Creates a new #GDataParsable subclass (of the given @parsable_type) from the given @xml. + * + * An object of the given @parsable_type is created, and its pre_parse_xml, parse_xml and + * post_parse_xml class functions called on the XML tree obtained from @xml. pre_parse_xml and + * post_parse_xml are called once each on the root node of the tree, while parse_xml is called for + * each of the child nodes of the root node. + * + * If @length is -1, @xml will be assumed to be null-terminated. + * + * If an error occurs during parsing, a suitable error from #GDataParserError will be returned. + * + * Return value: a new #GDataParsable, or %NULL; unref with g_object_unref() + * + * Since: 0.4.0 + */ +GDataParsable * +gdata_parsable_new_from_xml (GType parsable_type, const gchar *xml, gint length, GError **error) +{ + g_return_val_if_fail (g_type_is_a (parsable_type, GDATA_TYPE_PARSABLE), NULL); + g_return_val_if_fail (xml != NULL && *xml != '\0', NULL); + g_return_val_if_fail (length >= -1, NULL); + g_return_val_if_fail (error == NULL || *error == NULL, NULL); + + return _gdata_parsable_new_from_xml (parsable_type, xml, length, NULL, error); +} + +GDataParsable * +_gdata_parsable_new_from_xml (GType parsable_type, const gchar *xml, gint length, gpointer user_data, GError **error) +{ + xmlDoc *doc; + xmlNode *node; + GDataParsable *parsable; + static gboolean libxml_initialised = FALSE; + + g_return_val_if_fail (g_type_is_a (parsable_type, GDATA_TYPE_PARSABLE), NULL); + g_return_val_if_fail (xml != NULL && *xml != '\0', NULL); + g_return_val_if_fail (length >= -1, NULL); + g_return_val_if_fail (error == NULL || *error == NULL, NULL); + + /* Set up libxml. We do this here to avoid introducing a libgdata setup function, which would be unnecessary hassle. This is the only place + * that libxml can be initialised in the library. */ + if (libxml_initialised == FALSE) { + /* Change the libxml memory allocation functions to be GLib's. This means we don't have to re-allocate all the strings we get from + * libxml, which cuts down on strdup() calls dramatically. */ + xmlMemSetup ((xmlFreeFunc) g_free, (xmlMallocFunc) g_malloc, (xmlReallocFunc) g_realloc, (xmlStrdupFunc) g_strdup); + libxml_initialised = TRUE; + } + + if (length == -1) + length = strlen (xml); + + /* Parse the XML */ + doc = xmlReadMemory (xml, length, "/dev/null", NULL, 0); + if (doc == NULL) { + xmlError *xml_error = xmlGetLastError (); + g_set_error (error, GDATA_PARSER_ERROR, GDATA_PARSER_ERROR_PARSING_STRING, + /* Translators: the parameter is an error message */ + _("Error parsing XML: %s"), + (xml_error != NULL) ? xml_error->message : NULL); + return NULL; + } + + /* Get the root element */ + node = xmlDocGetRootElement (doc); + if (node == NULL) { + /* XML document's empty */ + xmlFreeDoc (doc); + g_set_error (error, GDATA_PARSER_ERROR, GDATA_PARSER_ERROR_EMPTY_DOCUMENT, + _("Error parsing XML: %s"), + /* Translators: this is a dummy error message to be substituted into "Error parsing XML: %s". */ + _("Empty document.")); + return NULL; + } + + parsable = _gdata_parsable_new_from_xml_node (parsable_type, doc, node, user_data, error); + xmlFreeDoc (doc); + + return parsable; +} + +GDataParsable * +_gdata_parsable_new_from_xml_node (GType parsable_type, xmlDoc *doc, xmlNode *node, gpointer user_data, GError **error) +{ + GDataParsable *parsable; + GDataParsableClass *klass; + + g_return_val_if_fail (g_type_is_a (parsable_type, GDATA_TYPE_PARSABLE), NULL); + g_return_val_if_fail (doc != NULL, NULL); + g_return_val_if_fail (node != NULL, NULL); + g_return_val_if_fail (error == NULL || *error == NULL, NULL); + + parsable = g_object_new (parsable_type, "constructed-from-xml", TRUE, NULL); + + klass = GDATA_PARSABLE_GET_CLASS (parsable); + if (klass->parse_xml == NULL) { + g_object_unref (parsable); + return NULL; + } + + g_assert (klass->element_name != NULL); + /* TODO: See gdata-documents-entry.c:260 for an example of where the code below doesn't work */ + /*if (xmlStrcmp (node->name, (xmlChar*) klass->element_name) != 0 || + (node->ns != NULL && xmlStrcmp (node->ns->prefix, (xmlChar*) klass->element_namespace) != 0)) { + * No element (required) * + gdata_parser_error_required_element_missing (klass->element_name, "root", error); + return NULL; + }*/ + + /* Call the pre-parse function first */ + if (klass->pre_parse_xml != NULL && + klass->pre_parse_xml (parsable, doc, node, user_data, error) == FALSE) { + g_object_unref (parsable); + return NULL; + } + + /* Parse each child element */ + node = node->children; + while (node != NULL) { + if (klass->parse_xml (parsable, doc, node, user_data, error) == FALSE) { + g_object_unref (parsable); + return NULL; + } + node = node->next; + } + + /* Call the post-parse function */ + if (klass->post_parse_xml != NULL && + klass->post_parse_xml (parsable, user_data, error) == FALSE) { + g_object_unref (parsable); + return NULL; + } + + return parsable; +} + +/** + * gdata_parsable_new_from_json: + * @parsable_type: the type of the class represented by the JSON + * @json: the JSON for just the parsable object + * @length: the length of @json, or -1 + * @error: a #GError, or %NULL + * + * Creates a new #GDataParsable subclass (of the given @parsable_type) from the given @json. + * + * An object of the given @parsable_type is created, and its parse_json and + * post_parse_json class functions called on the JSON node obtained from @json. + * post_parse_json is called once on the root node, while parse_json is called for + * each of the node's members. + * + * If @length is -1, @json will be assumed to be nul-terminated. + * + * If an error occurs during parsing, a suitable error from #GDataParserError will be returned. + * + * Return value: a new #GDataParsable, or %NULL; unref with g_object_unref() + * + * Since: 0.15.0 + */ +GDataParsable * +gdata_parsable_new_from_json (GType parsable_type, const gchar *json, gint length, GError **error) +{ + g_return_val_if_fail (g_type_is_a (parsable_type, GDATA_TYPE_PARSABLE), NULL); + g_return_val_if_fail (json != NULL && *json != '\0', NULL); + g_return_val_if_fail (length >= -1, NULL); + g_return_val_if_fail (error == NULL || *error == NULL, NULL); + + return _gdata_parsable_new_from_json (parsable_type, json, length, NULL, error); +} + +GDataParsable * +_gdata_parsable_new_from_json (GType parsable_type, const gchar *json, gint length, gpointer user_data, GError **error) +{ + JsonParser *parser; + JsonReader *reader; + GDataParsable *parsable; + GError *child_error = NULL; + + g_return_val_if_fail (g_type_is_a (parsable_type, GDATA_TYPE_PARSABLE), NULL); + g_return_val_if_fail (json != NULL && *json != '\0', NULL); + g_return_val_if_fail (length >= -1, NULL); + g_return_val_if_fail (error == NULL || *error == NULL, NULL); + + if (length == -1) + length = strlen (json); + + parser = json_parser_new (); + if (!json_parser_load_from_data (parser, json, length, &child_error)) { + g_set_error (error, GDATA_PARSER_ERROR, GDATA_PARSER_ERROR_PARSING_STRING, + /* Translators: the parameter is an error message */ + _("Error parsing JSON: %s"), child_error->message); + g_error_free (child_error); + g_object_unref (parser); + + return NULL; + } + + reader = json_reader_new (json_parser_get_root (parser)); + parsable = _gdata_parsable_new_from_json_node (parsable_type, reader, user_data, error); + + g_object_unref (reader); + g_object_unref (parser); + + return parsable; +} + +GDataParsable * +_gdata_parsable_new_from_json_node (GType parsable_type, JsonReader *reader, gpointer user_data, GError **error) +{ + GDataParsable *parsable; + GDataParsableClass *klass; + gint i; + + g_return_val_if_fail (g_type_is_a (parsable_type, GDATA_TYPE_PARSABLE), NULL); + g_return_val_if_fail (reader != NULL, NULL); + g_return_val_if_fail (error == NULL || *error == NULL, NULL); + + /* Indicator property which allows distinguishing between locally created and server based objects + * as it is used for non-XML tasks, and adding another one for JSON would be a bit pointless. */ + parsable = g_object_new (parsable_type, "constructed-from-xml", TRUE, NULL); + + klass = GDATA_PARSABLE_GET_CLASS (parsable); + g_assert (klass->parse_json != NULL); + + /* Check that the outermost node is an object. */ + if (json_reader_is_object (reader) == FALSE) { + g_set_error (error, GDATA_PARSER_ERROR, GDATA_PARSER_ERROR_PARSING_STRING, + /* Translators: the parameter is an error message */ + _("Error parsing JSON: %s"), + _("Outermost JSON node is not an object.")); + g_object_unref (parsable); + return NULL; + } + + /* Parse each child member. This assumes the outermost node is an object. */ + for (i = 0; i < json_reader_count_members (reader); i++) { + g_return_val_if_fail (json_reader_read_element (reader, i), NULL); + + if (klass->parse_json (parsable, reader, user_data, error) == FALSE) { + json_reader_end_element (reader); + g_object_unref (parsable); + return NULL; + } + + json_reader_end_element (reader); + } + + /* Call the post-parse function */ + if (klass->post_parse_json != NULL && + klass->post_parse_json (parsable, user_data, error) == FALSE) { + g_object_unref (parsable); + return NULL; + } + + return parsable; +} + +/** + * gdata_parsable_get_content_type: + * @self: a #GDataParsable + * + * Returns the content type upon which the #GDataParsable is built. For example, `application/atom+xml` or `application/json`. + * + * Return value: the parsable's content type + * + * Since: 0.17.7 + */ +const gchar * +gdata_parsable_get_content_type (GDataParsable *self) +{ + GDataParsableClass *klass; + + g_return_val_if_fail (GDATA_IS_PARSABLE (self), NULL); + + klass = GDATA_PARSABLE_GET_CLASS (self); + g_assert (klass->get_content_type != NULL); + + return klass->get_content_type (); +} + +static void +build_namespaces_cb (gchar *prefix, gchar *href, GString *output) +{ + g_string_append_printf (output, " xmlns:%s='%s'", prefix, href); +} + +static gboolean +filter_namespaces_cb (gchar *prefix, gchar *href, GHashTable *canonical_namespaces) +{ + if (g_hash_table_lookup (canonical_namespaces, prefix) != NULL) + return TRUE; + return FALSE; +} + +/** + * gdata_parsable_get_xml: + * @self: a #GDataParsable + * + * Builds an XML representation of the #GDataParsable in its current state, such that it could be inserted on the server. The XML is guaranteed + * to have all its namespaces declared properly in a self-contained fashion, and is valid for stand-alone use. + * + * Return value: the object's XML; free with g_free() + * + * Since: 0.4.0 + */ +gchar * +gdata_parsable_get_xml (GDataParsable *self) +{ + GString *xml_string; + + g_return_val_if_fail (GDATA_IS_PARSABLE (self), NULL); + + xml_string = g_string_sized_new (1000); + g_string_append (xml_string, ""); + _gdata_parsable_get_xml (self, xml_string, TRUE); + return g_string_free (xml_string, FALSE); +} + +/* + * _gdata_parsable_get_xml: + * @self: a #GDataParsable + * @xml_string: a #GString to build the XML in + * @declare_namespaces: %TRUE if all the namespaces used in the outputted XML should be declared in the opening tag of the root element, + * %FALSE otherwise + * + * Builds an XML representation of the #GDataParsable in its current state, such that it could be inserted on the server. If @declare_namespaces is + * %TRUE, the XML is guaranteed to have all its namespaces declared properly in a self-contained fashion, and is valid for stand-alone use. If + * @declare_namespaces is %FALSE, none of the used namespaces are declared, and the XML is suitable for insertion into a larger XML tree. + * + * Return value: the object's XML; free with g_free() + * + * Since: 0.4.0 + */ +void +_gdata_parsable_get_xml (GDataParsable *self, GString *xml_string, gboolean declare_namespaces) +{ + GDataParsableClass *klass; + guint length; + GHashTable *namespaces = NULL; /* shut up, gcc */ + + g_return_if_fail (GDATA_IS_PARSABLE (self)); + g_return_if_fail (xml_string != NULL); + + klass = GDATA_PARSABLE_GET_CLASS (self); + g_assert (klass->element_name != NULL); + + /* Get the namespaces the class uses */ + if (declare_namespaces == TRUE && klass->get_namespaces != NULL) { + namespaces = g_hash_table_new (g_str_hash, g_str_equal); + klass->get_namespaces (self, namespaces); + + /* Remove any duplicate extra namespaces */ + g_hash_table_foreach_remove (self->priv->extra_namespaces, (GHRFunc) filter_namespaces_cb, namespaces); + } + + /* Build up the namespace list */ + if (klass->element_namespace != NULL) + g_string_append_printf (xml_string, "<%s:%s", klass->element_namespace, klass->element_name); + else + g_string_append_printf (xml_string, "<%s", klass->element_name); + + /* We only include the normal namespaces if we're not at the top level of XML building */ + if (declare_namespaces == TRUE) { + g_string_append (xml_string, " xmlns='http://www.w3.org/2005/Atom'"); + if (namespaces != NULL) { + g_hash_table_foreach (namespaces, (GHFunc) build_namespaces_cb, xml_string); + g_hash_table_destroy (namespaces); + } + } + + g_hash_table_foreach (self->priv->extra_namespaces, (GHFunc) build_namespaces_cb, xml_string); + + /* Add anything the class thinks is suitable */ + if (klass->pre_get_xml != NULL) + klass->pre_get_xml (self, xml_string); + g_string_append_c (xml_string, '>'); + + /* Store the length before we close the opening tag, so we can determine whether to self-close later on */ + length = xml_string->len; + + /* Add the rest of the XML */ + if (klass->get_xml != NULL) + klass->get_xml (self, xml_string); + + /* Any extra XML? */ + if (self->priv->extra_xml != NULL && self->priv->extra_xml->str != NULL) + g_string_append (xml_string, self->priv->extra_xml->str); + + /* Close the element; either by self-closing the opening tag, or by writing out a closing tag */ + if (xml_string->len == length) + g_string_overwrite (xml_string, length - 1, "/>"); + else if (klass->element_namespace != NULL) + g_string_append_printf (xml_string, "", klass->element_namespace, klass->element_name); + else + g_string_append_printf (xml_string, "", klass->element_name); +} + +/** + * gdata_parsable_get_json: + * @self: a #GDataParsable + * + * Builds a JSON representation of the #GDataParsable in its current state, such that it could be inserted on the server. The JSON + * is valid for stand-alone use. + * + * Return value: the object's JSON; free with g_free() + * + * Since: 0.15.0 + */ +gchar * +gdata_parsable_get_json (GDataParsable *self) +{ + JsonGenerator *generator; + JsonBuilder *builder; + JsonNode *root; + gchar *output; + + g_return_val_if_fail (GDATA_IS_PARSABLE (self), NULL); + + /* Build the JSON tree. */ + builder = json_builder_new (); + _gdata_parsable_get_json (self, builder); + root = json_builder_get_root (builder); + g_object_unref (builder); + + /* Serialise it to a string. */ + generator = json_generator_new (); + json_generator_set_root (generator, root); + output = json_generator_to_data (generator, NULL); + g_object_unref (generator); + + json_node_free (root); + + return output; +} + +/* + * _gdata_parsable_get_json: + * @self: a #GDataParsable + * @builder: a #JsonBuilder to build the JSON in + * + * Builds a JSON representation of the #GDataParsable in its current state, such that it could be inserted on the server. + * + * Since: 0.15.0 + */ +void +_gdata_parsable_get_json (GDataParsable *self, JsonBuilder *builder) +{ + GDataParsableClass *klass; + GHashTableIter iter; + gchar *member_name; + JsonNode *value; + + g_return_if_fail (GDATA_IS_PARSABLE (self)); + g_return_if_fail (JSON_IS_BUILDER (builder)); + + klass = GDATA_PARSABLE_GET_CLASS (self); + + json_builder_begin_object (builder); + + /* Add the JSON. */ + if (klass->get_json != NULL) + klass->get_json (self, builder); + + /* Any extra JSON which we couldn't parse before? */ + g_hash_table_iter_init (&iter, self->priv->extra_json); + while (g_hash_table_iter_next (&iter, (gpointer *) &member_name, (gpointer *) &value) == TRUE) { + json_builder_set_member_name (builder, member_name); + json_builder_add_value (builder, json_node_copy (value)); /* transfers ownership */ + } + + json_builder_end_object (builder); +} + +/* + * _gdata_parsable_is_constructed_from_xml: + * @self: a #GDataParsable + * + * Returns the value of #GDataParsable:constructed-from-xml. + * + * Return value: %TRUE if the #GDataParsable was constructed from XML, %FALSE otherwise + * + * Since: 0.7.0 + */ +gboolean +_gdata_parsable_is_constructed_from_xml (GDataParsable *self) +{ + g_return_val_if_fail (GDATA_IS_PARSABLE (self), FALSE); + return self->priv->constructed_from_xml; +} diff --git a/gdata/gdata-parsable.h b/gdata/gdata-parsable.h new file mode 100644 index 0000000..f4a090f --- /dev/null +++ b/gdata/gdata-parsable.h @@ -0,0 +1,135 @@ +/* -*- Mode: C; indent-tabs-mode: t; c-basic-offset: 8; tab-width: 8 -*- */ +/* + * GData Client + * Copyright (C) Philip Withnall 2009 + * + * GData Client is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * GData Client is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with GData Client. If not, see . + */ + +#ifndef GDATA_PARSABLE_H +#define GDATA_PARSABLE_H + +#include +#include +#include +#include + +G_BEGIN_DECLS + +/** + * GDataParserError: + * @GDATA_PARSER_ERROR_PARSING_STRING: Error parsing the XML or JSON syntax itself + * @GDATA_PARSER_ERROR_EMPTY_DOCUMENT: Empty document + * + * Error codes for XML or JSON parsing operations. + */ +typedef enum { + GDATA_PARSER_ERROR_PARSING_STRING = 1, + GDATA_PARSER_ERROR_EMPTY_DOCUMENT +} GDataParserError; + +#define GDATA_PARSER_ERROR gdata_parser_error_quark () +GQuark gdata_parser_error_quark (void) G_GNUC_CONST; + +#define GDATA_TYPE_PARSABLE (gdata_parsable_get_type ()) +#define GDATA_PARSABLE(o) (G_TYPE_CHECK_INSTANCE_CAST ((o), GDATA_TYPE_PARSABLE, GDataParsable)) +#define GDATA_PARSABLE_CLASS(k) (G_TYPE_CHECK_CLASS_CAST((k), GDATA_TYPE_PARSABLE, GDataParsableClass)) +#define GDATA_IS_PARSABLE(o) (G_TYPE_CHECK_INSTANCE_TYPE ((o), GDATA_TYPE_PARSABLE)) +#define GDATA_IS_PARSABLE_CLASS(k) (G_TYPE_CHECK_CLASS_TYPE ((k), GDATA_TYPE_PARSABLE)) +#define GDATA_PARSABLE_GET_CLASS(o) (G_TYPE_INSTANCE_GET_CLASS ((o), GDATA_TYPE_PARSABLE, GDataParsableClass)) + +typedef struct _GDataParsablePrivate GDataParsablePrivate; + +/** + * GDataParsable: + * + * All the fields in the #GDataParsable structure are private and should never be accessed directly. + * + * Since: 0.3.0 + */ +typedef struct { + GObject parent; + GDataParsablePrivate *priv; +} GDataParsable; + +/** + * GDataParsableClass: + * @parent: the parent class + * @pre_parse_xml: a function called before parsing of an XML tree is started, which allows properties from the root node to be extracted + * and used in @parsable + * @parse_xml: a function to parse an XML representation of the #GDataParsable to set the properties of the @parsable + * @post_parse_xml: a function called after parsing an XML tree, to allow the @parsable to validate the parsed properties + * @pre_get_xml: a function called before building the XML representation of the children of the #GDataParsable, which allows attributes of the root + * XML node to be added to @xml_string + * @get_xml: a function to build an XML representation of the #GDataParsable in its current state, appending it to the provided #GString + * @get_namespaces: a function to return a string containing the namespace declarations used by the @parsable when represented in XML form + * @parse_json: a function to parse a JSON representation of the #GDataParsable to set the properties of the @parsable + * @post_parse_json: a function called after parsing a JSON object, to allow the @parsable to validate the parsed properties + * @get_json: a function to build a JSON representation of the #GDataParsable in its current state, appending it to the provided #JsonBuilder + * @get_content_type: a function which returns content type upon which is #GDataParsable built + * @element_name: the name of the XML element which represents this parsable + * @element_namespace: the prefix of the XML namespace used for the parsable + * + * The class structure for the #GDataParsable class. Note that JSON and XML functions are mutually exclusive: + * a given implementation of #GDataParsable is represented as exactly one of JSON and XML. + * + * Since: 0.3.0 + */ +typedef struct { + GObjectClass parent; + + gboolean (*pre_parse_xml) (GDataParsable *parsable, xmlDoc *doc, xmlNode *root_node, gpointer user_data, GError **error); + gboolean (*parse_xml) (GDataParsable *parsable, xmlDoc *doc, xmlNode *node, gpointer user_data, GError **error); + gboolean (*post_parse_xml) (GDataParsable *parsable, gpointer user_data, GError **error); + + void (*pre_get_xml) (GDataParsable *parsable, GString *xml_string); + void (*get_xml) (GDataParsable *parsable, GString *xml_string); + void (*get_namespaces) (GDataParsable *parsable, GHashTable *namespaces); + + gboolean (*parse_json) (GDataParsable *parsable, JsonReader *reader, gpointer user_data, GError **error); + gboolean (*post_parse_json) (GDataParsable *parsable, gpointer user_data, GError **error); + void (*get_json) (GDataParsable *parsable, JsonBuilder *builder); + + const gchar *(*get_content_type) (void); + + const gchar *element_name; + const gchar *element_namespace; + + /*< private >*/ + /* Padding for future expansion */ + void (*_g_reserved0) (void); + void (*_g_reserved1) (void); + void (*_g_reserved2) (void); + void (*_g_reserved3) (void); + void (*_g_reserved4) (void); + void (*_g_reserved5) (void); + void (*_g_reserved6) (void); + void (*_g_reserved7) (void); +} GDataParsableClass; + +GType gdata_parsable_get_type (void) G_GNUC_CONST; + +const gchar *gdata_parsable_get_content_type (GDataParsable *self); + +GDataParsable *gdata_parsable_new_from_xml (GType parsable_type, const gchar *xml, gint length, + GError **error) G_GNUC_WARN_UNUSED_RESULT G_GNUC_MALLOC; +gchar *gdata_parsable_get_xml (GDataParsable *self) G_GNUC_WARN_UNUSED_RESULT G_GNUC_MALLOC; + +GDataParsable *gdata_parsable_new_from_json (GType parsable_type, const gchar *json, gint length, + GError **error) G_GNUC_WARN_UNUSED_RESULT G_GNUC_MALLOC; +gchar *gdata_parsable_get_json (GDataParsable *self) G_GNUC_WARN_UNUSED_RESULT G_GNUC_MALLOC; + +G_END_DECLS + +#endif /* !GDATA_PARSABLE_H */ diff --git a/gdata/gdata-parser.c b/gdata/gdata-parser.c new file mode 100644 index 0000000..c1cfe00 --- /dev/null +++ b/gdata/gdata-parser.c @@ -0,0 +1,1295 @@ +/* -*- Mode: C; indent-tabs-mode: t; c-basic-offset: 8; tab-width: 8 -*- */ +/* + * GData Client + * Copyright (C) Philip Withnall 2009 + * + * GData Client is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * GData Client is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with GData Client. If not, see . + */ + +#include +#include +#include +#include +#include +#include +#include +#include + +#include "gdata-parser.h" +#include "gdata-service.h" +#include "gdata-types.h" +#include "gdata-private.h" + +static gchar * +print_element (xmlNode *node) +{ + gboolean node_has_ns = (node->ns == NULL || node->ns->prefix == NULL || + xmlStrcmp (node->ns->href, (xmlChar*) "http://www.w3.org/2005/Atom") == 0) ? FALSE : TRUE; + + if (node->parent == NULL) { + /* No parent node */ + if (node_has_ns == TRUE) + return g_strdup_printf ("<%s:%s>", node->ns->prefix, node->name); + else + return g_strdup_printf ("<%s>", node->name); + } else { + /* We have a parent node, which makes things a lot more complex */ + gboolean parent_has_ns = (node->parent->type == XML_DOCUMENT_NODE || node->parent->ns == NULL || node->parent->ns->prefix == NULL || + xmlStrcmp (node->parent->ns->href, (xmlChar*) "http://www.w3.org/2005/Atom") == 0) ? FALSE : TRUE; + + if (parent_has_ns == TRUE && node_has_ns == TRUE) + return g_strdup_printf ("<%s:%s/%s:%s>", node->parent->ns->prefix, node->parent->name, node->ns->prefix, node->name); + else if (parent_has_ns == FALSE && node_has_ns == TRUE) + return g_strdup_printf ("<%s/%s:%s>", node->parent->name, node->ns->prefix, node->name); + else + return g_strdup_printf ("<%s/%s>", node->parent->name, node->name); + } +} + +gboolean +gdata_parser_error_required_content_missing (xmlNode *element, GError **error) +{ + gchar *element_string = print_element (element); + + /* Translators: the parameter is the name of an XML element, including the angle brackets ("<" and ">"). + * + * For example: + * A element was missing required content. */ + g_set_error (error, GDATA_SERVICE_ERROR, GDATA_SERVICE_ERROR_PROTOCOL_ERROR, _("A %s element was missing required content."), element_string); + g_free (element_string); + + return FALSE; +} + +gboolean +gdata_parser_error_not_iso8601_format (xmlNode *element, const gchar *actual_value, GError **error) +{ + gchar *element_string = print_element (element); + g_set_error (error, GDATA_SERVICE_ERROR, GDATA_SERVICE_ERROR_PROTOCOL_ERROR, + /* Translators: the first parameter is the name of an XML element (including the angle brackets ("<" and ">")), + * and the second parameter is the erroneous value (which was not in ISO 8601 format). + * + * For example: + * The content of a <media:group/media:uploaded> element (‘2009-05-06 26:30Z’) was not in ISO 8601 format. */ + _("The content of a %s element (‘%s’) was not in ISO 8601 format."), element_string, actual_value); + g_free (element_string); + + return FALSE; +} + +gboolean +gdata_parser_error_unknown_property_value (xmlNode *element, const gchar *property_name, const gchar *actual_value, GError **error) +{ + gchar *property_string, *element_string; + + property_string = g_strdup_printf ("@%s", property_name); + element_string = print_element (element); + + g_set_error (error, GDATA_SERVICE_ERROR, GDATA_SERVICE_ERROR_PROTOCOL_ERROR, + /* Translators: the first parameter is the name of an XML property, the second is the name of an XML element + * (including the angle brackets ("<" and ">")) to which the property belongs, and the third is the unknown value. + * + * For example: + * The value of the @time property of a <media:group/media:thumbnail> element (‘00:01:42.500’) was unknown. */ + _("The value of the %s property of a %s element (‘%s’) was unknown."), property_string, element_string, actual_value); + g_free (property_string); + g_free (element_string); + + return FALSE; +} + +gboolean +gdata_parser_error_unknown_content (xmlNode *element, const gchar *actual_content, GError **error) +{ + gchar *element_string = print_element (element); + + g_set_error (error, GDATA_SERVICE_ERROR, GDATA_SERVICE_ERROR_PROTOCOL_ERROR, + /* Translators: the first parameter is the name of an XML element (including the angle brackets ("<" and ">")), + * and the second parameter is the unknown content of that element. + * + * For example: + * The content of a <gphoto:access> element (‘protected’) was unknown. */ + _("The content of a %s element (‘%s’) was unknown."), element_string, actual_content); + g_free (element_string); + + return FALSE; +} + +gboolean +gdata_parser_error_required_property_missing (xmlNode *element, const gchar *property_name, GError **error) +{ + gchar *property_string, *element_string; + + property_string = g_strdup_printf ("@%s", property_name); + element_string = print_element (element); + + g_set_error (error, GDATA_SERVICE_ERROR, GDATA_SERVICE_ERROR_PROTOCOL_ERROR, + /* Translators: the first parameter is the name of an XML element (including the angle brackets ("<" and ">")), + * and the second is the name of an XML property which it should have contained. + * + * For example: + * A required property of a <entry/gAcl:role> element (@value) was not present. */ + _("A required property of a %s element (%s) was not present."), element_string, property_string); + g_free (property_string); + g_free (element_string); + + return FALSE; +} + +gboolean +gdata_parser_error_mutexed_properties (xmlNode *element, const gchar *property1_name, const gchar *property2_name, GError **error) +{ + gchar *property1_string, *property2_string, *element_string; + + property1_string = g_strdup_printf ("@%s", property1_name); + property2_string = g_strdup_printf ("@%s", property2_name); + element_string = print_element (element); + + g_set_error (error, GDATA_SERVICE_ERROR, GDATA_SERVICE_ERROR_PROTOCOL_ERROR, + /* Translators: the first two parameters are the names of XML properties of an XML element given in the third + * parameter (including the angle brackets ("<" and ">")). + * + * For example: + * Values were present for properties @rel and @label of a <entry/gContact:relation> element when only one of the + * two is allowed. */ + _("Values were present for properties %s and %s of a %s element when only one of the two is allowed."), + property1_string, property2_string, element_string); + g_free (property1_string); + g_free (property2_string); + g_free (element_string); + + return FALSE; +} + +gboolean +gdata_parser_error_required_element_missing (const gchar *element_name, const gchar *parent_element_name, GError **error) +{ + /* NOTE: This can't take an xmlNode, since such a node wouldn't exist. */ + gchar *element_string = g_strdup_printf ("<%s/%s>", parent_element_name, element_name); + + /* Translators: the parameter is the name of an XML element, including the angle brackets ("<" and ">"). + * + * For example: + * A required element (<entry/title>) was not present. */ + g_set_error (error, GDATA_SERVICE_ERROR, GDATA_SERVICE_ERROR_PROTOCOL_ERROR, _("A required element (%s) was not present."), element_string); + g_free (element_string); + + return FALSE; +} + +gboolean +gdata_parser_error_duplicate_element (xmlNode *element, GError **error) +{ + gchar *element_string = print_element (element); + + /* Translators: the parameter is the name of an XML element, including the angle brackets ("<" and ">"). + * + * For example: + * A singleton element (<feed/title>) was duplicated. */ + g_set_error (error, GDATA_SERVICE_ERROR, GDATA_SERVICE_ERROR_PROTOCOL_ERROR, _("A singleton element (%s) was duplicated."), element_string); + g_free (element_string); + + return FALSE; +} + +gboolean +gdata_parser_int64_from_date (const gchar *date, gint64 *_time) +{ + gchar *iso8601_date; + gboolean success; + GTimeVal time_val; + + if (strlen (date) != 10 && strlen (date) != 8) + return FALSE; + + /* Note: This doesn't need translating, as it's outputting an ISO 8601 time string */ + iso8601_date = g_strdup_printf ("%sT00:00:00Z", date); + success = g_time_val_from_iso8601 (iso8601_date, &time_val); + g_free (iso8601_date); + + if (success == TRUE) + *_time = time_val.tv_sec; + + return success; +} + +gchar * +gdata_parser_date_from_int64 (gint64 _time) +{ + time_t secs; + struct tm *tm; + + secs = _time; + tm = gmtime (&secs); + + /* Note: This doesn't need translating, as it's outputting an ISO 8601 date string */ + return g_strdup_printf ("%04d-%02d-%02d", tm->tm_year + 1900, tm->tm_mon + 1, tm->tm_mday); +} + +gchar * +gdata_parser_int64_to_iso8601 (gint64 _time) +{ + GTimeVal time_val; + + time_val.tv_sec = _time; + time_val.tv_usec = 0; + + return g_time_val_to_iso8601 (&time_val); +} + +gboolean +gdata_parser_int64_from_iso8601 (const gchar *date, gint64 *_time) +{ + GTimeVal time_val; + + if (g_time_val_from_iso8601 (date, &time_val) == TRUE) { + *_time = time_val.tv_sec; + return TRUE; + } + + return FALSE; +} + +gboolean +gdata_parser_error_required_json_content_missing (JsonReader *reader, GError **error) +{ + const gchar *element_string = json_reader_get_member_name (reader); + + /* Translators: the parameter is the name of an JSON element. + * + * For example: + * A ‘title’ element was missing required content. */ + g_set_error (error, GDATA_SERVICE_ERROR, GDATA_SERVICE_ERROR_PROTOCOL_ERROR, _("A ‘%s’ element was missing required content."), element_string); + + return FALSE; +} + +gboolean +gdata_parser_error_duplicate_json_element (JsonReader *reader, GError **error) +{ + const gchar *element_string = json_reader_get_member_name (reader); + + /* Translators: the parameter is the name of an JSON element. + * + * For example: + * A singleton element (title) was duplicated. */ + g_set_error (error, GDATA_SERVICE_ERROR, GDATA_SERVICE_ERROR_PROTOCOL_ERROR, _("A singleton element (%s) was duplicated."), element_string); + + return FALSE; +} + +gboolean +gdata_parser_error_not_iso8601_format_json (JsonReader *reader, const gchar *actual_value, GError **error) +{ + const gchar *element_string = json_reader_get_member_name (reader); + + g_set_error (error, GDATA_SERVICE_ERROR, GDATA_SERVICE_ERROR_PROTOCOL_ERROR, + /* Translators: the first parameter is the name of an JSON element, + * and the second parameter is the erroneous value (which was not in ISO 8601 format). + * + * For example: + * The content of a ‘uploaded’ element (‘2009-05-06 26:30Z’) was not in ISO 8601 format. */ + _("The content of a ‘%s’ element (‘%s’) was not in ISO 8601 format."), element_string, actual_value); + + return FALSE; +} + +gboolean +gdata_parser_error_from_json_error (JsonReader *reader, + const GError *json_error, GError **error) +{ + g_set_error (error, GDATA_SERVICE_ERROR, GDATA_SERVICE_ERROR_PROTOCOL_ERROR, + /* Translators: the parameter is an error message. */ + _("Invalid JSON was received from the server: %s"), json_error->message); + + return FALSE; +} + +/* + * gdata_parser_boolean_from_property: + * @element: the XML element which owns the property to parse + * @property_name: the name of the property to parse + * @output: the return location for the parsed boolean value + * @default_output: the default value to return in @output if the property can't be found + * @error: a #GError, or %NULL + * + * Parses a GData boolean value from the property @property_name of @element. + * The boolean value should be of the form: "<element property_name='[true|false]'/>". + * A %GDATA_SERVICE_ERROR_PROTOCOL_ERROR error will be returned in @error if parsing fails, and @output will not be set. + * + * If no property with the name @property_name exists in @element and @default_output is <code class="literal">0</code>, + * @output will be set to %FALSE. + * If @default_output is <code class="literal">1</code>, @output will be set to %TRUE. If @default_output is <code class="literal">-1</code>, + * a %GDATA_SERVICE_ERROR_PROTOCOL_ERROR will be returned in @error. + * + * Return value: %TRUE on successful parsing, %FALSE otherwise + * + * Since: 0.7.0 + */ +gboolean +gdata_parser_boolean_from_property (xmlNode *element, const gchar *property_name, gboolean *output, gint default_output, GError **error) +{ + xmlChar *value = xmlGetProp (element, (xmlChar*) property_name); + + if (value == NULL) { + /* Missing property */ + if (default_output == -1) + return gdata_parser_error_required_property_missing (element, property_name, error); + *output = (default_output == 1) ? TRUE : FALSE; + } else if (xmlStrcmp (value, (xmlChar*) "false") == 0) { + *output = FALSE; + } else if (xmlStrcmp (value, (xmlChar*) "true") == 0) { + *output = TRUE; + } else { + /* Parsing failed */ + gdata_parser_error_unknown_property_value (element, property_name, (gchar*) value, error); + xmlFree (value); + return FALSE; + } + + xmlFree (value); + return TRUE; +} + +/* + * gdata_parser_is_namespace: + * @element: the element to check + * @namespace_uri: the URI of the desired namespace + * + * Checks whether @element is in the namespace identified by @namespace_uri. If @element isn't in a namespace, + * %FALSE is returned. + * + * Return value: %TRUE if @element is in @namespace_uri; %FALSE otherwise + * + * Since: 0.7.0 + */ +gboolean +gdata_parser_is_namespace (xmlNode *element, const gchar *namespace_uri) +{ + if ((element->ns != NULL && xmlStrcmp (element->ns->href, (const xmlChar*) namespace_uri) == 0) || + (element->ns == NULL && strcmp (namespace_uri, "http://www.w3.org/2005/Atom") == 0)) + return TRUE; + return FALSE; +} + +/* + * gdata_parser_string_from_element: + * @element: the element to check against + * @element_name: the name of the element to parse + * @options: a bitwise combination of parsing options from #GDataParserOptions, or %P_NONE + * @output: the return location for the parsed string content + * @success: the return location for a value which is %TRUE if the string was parsed successfully, %FALSE if an error was encountered, + * and undefined if @element didn't match @element_name + * @error: a #GError, or %NULL + * + * Gets the string content of @element if its name is @element_name, subject to various checks specified by @options. + * + * If @element doesn't match @element_name, %FALSE will be returned, @error will be unset and @success will be unset. + * + * If @element matches @element_name but one of the checks specified by @options fails, %TRUE will be returned, @error will be set to a + * %GDATA_SERVICE_ERROR_PROTOCOL_ERROR error and @success will be set to %FALSE. + * + * If @element matches @element_name and all of the checks specified by @options pass, %TRUE will be returned, @error will be unset and + * @success will be set to %TRUE. + * + * The reason for returning the success of the parsing in @success is so that calls to gdata_parser_string_from_element() can be chained + * together in a large "or" statement based on their return values, for the purposes of determining whether any of the calls matched + * a given @element. If any of the calls to gdata_parser_string_from_element() return %TRUE, the value of @success can be examined. + * + * Return value: %TRUE if @element matched @element_name, %FALSE otherwise + * + * Since: 0.7.0 + */ +gboolean +gdata_parser_string_from_element (xmlNode *element, const gchar *element_name, GDataParserOptions options, + gchar **output, gboolean *success, GError **error) +{ + xmlChar *text; + + /* Check it's the right element */ + if (xmlStrcmp (element->name, (xmlChar*) element_name) != 0) + return FALSE; + + /* Check if the output string has already been set */ + if (options & P_NO_DUPES && *output != NULL) { + *success = gdata_parser_error_duplicate_element (element, error); + return TRUE; + } + + /* Get the string and check it for NULLness or emptiness */ + text = xmlNodeListGetString (element->doc, element->children, TRUE); + if ((options & P_REQUIRED && text == NULL) || (options & P_NON_EMPTY && text != NULL && *text == '\0')) { + xmlFree (text); + *success = gdata_parser_error_required_content_missing (element, error); + return TRUE; + } else if (options & P_DEFAULT && (text == NULL || *text == '\0')) { + text = (xmlChar*) g_strdup (""); + } + + /* Success! */ + g_free (*output); + *output = (gchar*) text; + *success = TRUE; + + return TRUE; +} + +/* + * gdata_parser_int64_time_from_element: + * @element: the element to check against + * @element_name: the name of the element to parse + * @options: a bitwise combination of parsing options from #GDataParserOptions, or %P_NONE + * @output: (out caller-allocates): the return location for the parsed time value + * @success: the return location for a value which is %TRUE if the time val was parsed successfully, %FALSE if an error was encountered, + * and undefined if @element didn't match @element_name + * @error: a #GError, or %NULL + * + * Gets the time value of @element if its name is @element_name, subject to various checks specified by @options. It expects the text content + * of @element to be a date or time value in ISO 8601 format. The returned time value will be a UNIX timestamp (seconds since the epoch). + * + * If @element doesn't match @element_name, %FALSE will be returned, @error will be unset and @success will be unset. + * + * If @element matches @element_name but one of the checks specified by @options fails, %TRUE will be returned, @error will be set to a + * %GDATA_SERVICE_ERROR_PROTOCOL_ERROR error and @success will be set to %FALSE. + * + * If @element matches @element_name and all of the checks specified by @options pass, %TRUE will be returned, @error will be unset and + * @success will be set to %TRUE. + * + * The reason for returning the success of the parsing in @success is so that calls to gdata_parser_int64_time_from_element() can be chained + * together in a large "or" statement based on their return values, for the purposes of determining whether any of the calls matched + * a given @element. If any of the calls to gdata_parser_int64_time_from_element() return %TRUE, the value of @success can be examined. + * + * Return value: %TRUE if @element matched @element_name, %FALSE otherwise + * + * Since: 0.7.0 + */ +gboolean +gdata_parser_int64_time_from_element (xmlNode *element, const gchar *element_name, GDataParserOptions options, + gint64 *output, gboolean *success, GError **error) +{ + xmlChar *text; + GTimeVal time_val; + + /* Check it's the right element */ + if (xmlStrcmp (element->name, (xmlChar*) element_name) != 0) + return FALSE; + + /* Check if the output time val has already been set */ + if (options & P_NO_DUPES && *output != -1) { + *success = gdata_parser_error_duplicate_element (element, error); + return TRUE; + } + + /* Get the string and check it for NULLness */ + text = xmlNodeListGetString (element->doc, element->children, TRUE); + if (options & P_REQUIRED && (text == NULL || *text == '\0')) { + xmlFree (text); + *success = gdata_parser_error_required_content_missing (element, error); + return TRUE; + } + + /* Attempt to parse the string as a GTimeVal */ + if (g_time_val_from_iso8601 ((gchar*) text, &time_val) == FALSE) { + *success = gdata_parser_error_not_iso8601_format (element, (gchar*) text, error); + xmlFree (text); + return TRUE; + } + + *output = time_val.tv_sec; + + /* Success! */ + xmlFree (text); + *success = TRUE; + + return TRUE; +} + +/* + * gdata_parser_int64_from_element: + * @element: the element to check against + * @element_name: the name of the element to parse + * @options: a bitwise combination of parsing options from #GDataParserOptions, or %P_NONE + * @output: (out caller-allocates): the return location for the parsed integer value + * @default_output: default value for the property, used with %P_NO_DUPES to detect duplicates + * @success: the return location for a value which is %TRUE if the integer was parsed successfully, %FALSE if an error was encountered, + * and undefined if @element didn't match @element_name + * @error: a #GError, or %NULL + * + * Gets the integer value of @element if its name is @element_name, subject to various checks specified by @options. It expects the text content + * of @element to be an integer in base 10 format. + * + * If @element doesn't match @element_name, %FALSE will be returned, @error will be unset and @success will be unset. + * + * If @element matches @element_name but one of the checks specified by @options fails, %TRUE will be returned, @error will be set to a + * %GDATA_SERVICE_ERROR_PROTOCOL_ERROR error and @success will be set to %FALSE. + * + * If @element matches @element_name and all of the checks specified by @options pass, %TRUE will be returned, @error will be unset and + * @success will be set to %TRUE. + * + * The reason for returning the success of the parsing in @success is so that calls to gdata_parser_int64_from_element() can be chained + * together in a large "or" statement based on their return values, for the purposes of determining whether any of the calls matched + * a given @element. If any of the calls to gdata_parser_int64_from_element() return %TRUE, the value of @success can be examined. + * + * Return value: %TRUE if @element matched @element_name, %FALSE otherwise + * + * Since: 0.13.0 + */ +gboolean +gdata_parser_int64_from_element (xmlNode *element, const gchar *element_name, GDataParserOptions options, + gint64 *output, gint64 default_output, gboolean *success, GError **error) +{ + xmlChar *text; + gchar *end_ptr; + gint64 val; + + /* Check it's the right element */ + if (xmlStrcmp (element->name, (xmlChar*) element_name) != 0) { + return FALSE; + } + + /* Check if the output value has already been set */ + if (options & P_NO_DUPES && *output != default_output) { + *success = gdata_parser_error_duplicate_element (element, error); + return TRUE; + } + + /* Get the string and check it for NULLness */ + text = xmlNodeListGetString (element->doc, element->children, TRUE); + if (options & P_REQUIRED && (text == NULL || *text == '\0')) { + xmlFree (text); + *success = gdata_parser_error_required_content_missing (element, error); + return TRUE; + } + + /* Attempt to parse the string as a 64-bit integer */ + val = g_ascii_strtoll ((const gchar*) text, &end_ptr, 10); + if (*end_ptr != '\0') { + *success = gdata_parser_error_unknown_content (element, (gchar*) text, error); + xmlFree (text); + return TRUE; + } + + *output = val; + + /* Success! */ + xmlFree (text); + *success = TRUE; + + return TRUE; +} + +/* + * gdata_parser_object_from_element_setter: + * @element: the element to check against + * @element_name: the name of the element to parse + * @options: a bitwise combination of parsing options from #GDataParserOptions, or %P_NONE + * @object_type: the type of the object to parse + * @_setter: a function to call once parsing's finished to return the object (#GDataParserSetterFunc) + * @_parent_parsable: the first parameter to pass to @_setter (of type #GDataParsable) + * @success: the return location for a value which is %TRUE if the object was parsed successfully, %FALSE if an error was encountered, + * and undefined if @element didn't match @element_name + * @error: a #GError, or %NULL + * + * Gets the object content of @element if its name is @element_name, subject to various checks specified by @options. If @element matches + * @element_name, @element will be parsed as an @object_type, which must extend #GDataParsable. If parsing is successful, @_setter will be called + * with its first parameter as @_parent_parsable, and its second as the parsed object of type @object_type. @_setter must reference the parsed object + * it's passed if it wants to keep it, as gdata_parser_object_from_element_setter will unreference it before returning. + * + * If @element doesn't match @element_name, %FALSE will be returned, @error will be unset and @success will be unset. + * + * If @element matches @element_name but one of the checks specified by @options fails, %TRUE will be returned, @error will be set to a + * %GDATA_SERVICE_ERROR_PROTOCOL_ERROR error and @success will be set to %FALSE. + * + * If @element matches @element_name and all of the checks specified by @options pass, %TRUE will be returned, @error will be unset and + * @success will be set to %TRUE. + * + * The reason for returning the success of the parsing in @success is so that calls to gdata_parser_object_from_element_setter() can be chained + * together in a large "or" statement based on their return values, for the purposes of determining whether any of the calls matched + * a given @element. If any of the calls to gdata_parser_object_from_element_setter() return %TRUE, the value of @success can be examined. + * + * @_setter and @_parent_parsable are both #gpointers to avoid casts having to be put into calls to gdata_parser_object_from_element_setter(). + * @_setter is actually of type #GDataParserSetterFunc, and @_parent_parsable should be a subclass of #GDataParsable. + * Neither parameter should be %NULL. No checks are implemented against these conditions (for efficiency reasons), so calling code must be correct. + * + * Return value: %TRUE if @element matched @element_name, %FALSE otherwise + * + * Since: 0.7.0 + */ +gboolean +gdata_parser_object_from_element_setter (xmlNode *element, const gchar *element_name, GDataParserOptions options, GType object_type, + gpointer /* GDataParserSetterFunc */ _setter, gpointer /* GDataParsable * */ _parent_parsable, + gboolean *success, GError **error) +{ + GDataParsable *parsable, *parent_parsable; + GDataParserSetterFunc setter; + GError *local_error = NULL; + + g_return_val_if_fail (!(options & P_REQUIRED) || !(options & P_IGNORE_ERROR), FALSE); + + /* We're lax on the types so that we don't have to do loads of casting when calling the function, which makes the parsing code more legible */ + setter = (GDataParserSetterFunc) _setter; + parent_parsable = (GDataParsable*) _parent_parsable; + + /* Check it's the right element */ + if (xmlStrcmp (element->name, (xmlChar*) element_name) != 0) + return FALSE; + + /* Get the object and check for instantiation failure */ + parsable = _gdata_parsable_new_from_xml_node (object_type, element->doc, element, NULL, &local_error); + g_assert ((parsable == NULL) == (local_error != NULL)); + + if (options & P_REQUIRED && parsable == NULL) { + /* The error has already been set by _gdata_parsable_new_from_xml_node() */ + g_propagate_error (error, g_steal_pointer (&local_error)); + *success = FALSE; + return TRUE; + } else if ((options & P_IGNORE_ERROR) && parsable == NULL) { + g_clear_error (&local_error); + *success = TRUE; + return TRUE; + } else if (local_error != NULL) { + g_propagate_error (error, g_steal_pointer (&local_error)); + *success = FALSE; + return TRUE; + } + + /* Success! */ + setter (parent_parsable, parsable); + g_object_unref (parsable); + *success = TRUE; + + return TRUE; +} + +/* + * gdata_parser_object_from_element: + * @element: the element to check against + * @element_name: the name of the element to parse + * @options: a bitwise combination of parsing options from #GDataParserOptions, or %P_NONE + * @object_type: the type of the object to parse + * @_output: the return location for the parsed object (of type #GDataParsable) + * @success: the return location for a value which is %TRUE if the object was parsed successfully, %FALSE if an error was encountered, + * and undefined if @element didn't match @element_name + * @error: a #GError, or %NULL + * + * Gets the object content of @element if its name is @element_name, subject to various checks specified by @options. If @element matches + * @element_name, @element will be parsed as an @object_type, which must extend #GDataParsable. If parsing is successful, the parsed object will be + * returned in @_output, which must be of type #GDataParsable (or a subclass). Ownership of the parsed object will pass to the calling code. + * + * If @element doesn't match @element_name, %FALSE will be returned, @error will be unset and @success will be unset. + * + * If @element matches @element_name but one of the checks specified by @options fails, %TRUE will be returned, @error will be set to a + * %GDATA_SERVICE_ERROR_PROTOCOL_ERROR error and @success will be set to %FALSE. + * + * If @element matches @element_name and all of the checks specified by @options pass, %TRUE will be returned, @error will be unset and + * @success will be set to %TRUE. + * + * The reason for returning the success of the parsing in @success is so that calls to gdata_parser_object_from_element() can be chained + * together in a large "or" statement based on their return values, for the purposes of determining whether any of the calls matched + * a given @element. If any of the calls to gdata_parser_object_from_element() return %TRUE, the value of @success can be examined. + * + * @_object is a #gpointer to avoid casts having to be put into calls to gdata_parser_object_from_element(). It is actually of type #GDataParsable + * and must not be %NULL. No check is implemented against this condition (for efficiency reasons), so calling code must be correct. + * + * Return value: %TRUE if @element matched @element_name, %FALSE otherwise + * + * Since: 0.7.0 + */ +gboolean +gdata_parser_object_from_element (xmlNode *element, const gchar *element_name, GDataParserOptions options, GType object_type, + gpointer /* GDataParsable ** */ _output, gboolean *success, GError **error) +{ + GDataParsable *parsable, **output; + + /* We're lax on the types so that we don't have to do loads of casting when calling the function, which makes the parsing code more legible */ + output = (GDataParsable**) _output; + + /* Check it's the right element */ + if (xmlStrcmp (element->name, (xmlChar*) element_name) != 0) + return FALSE; + + /* If we're not using a setter, check if the output already exists */ + if (options & P_NO_DUPES && *output != NULL) { + *success = gdata_parser_error_duplicate_element (element, error); + return TRUE; + } + + /* Get the object and check for instantiation failure */ + parsable = _gdata_parsable_new_from_xml_node (object_type, element->doc, element, NULL, error); + if (options & P_REQUIRED && parsable == NULL) { + /* The error has already been set by _gdata_parsable_new_from_xml_node() */ + *success = FALSE; + return TRUE; + } + + /* Success! */ + if (*output != NULL) + g_object_unref (*output); + *output = parsable; + *success = TRUE; + + return TRUE; +} + +/* + * gdata_parser_string_from_json_member: + * @reader: #JsonReader cursor object to read JSON node from + * @member_name: the name of the member to parse + * @options: a bitwise combination of parsing options from #GDataParserOptions, or %P_NONE + * @output: the return location for the parsed string content + * @success: the return location for a value which is %TRUE if the string was parsed successfully, %FALSE if an error was encountered, + * and undefined if @element didn't match @element_name + * @error: a #GError, or %NULL + * + * Gets the string content of @element if its name is @element_name, subject to various checks specified by @options. + * + * If @element doesn't match @element_name, %FALSE will be returned, @error will be unset and @success will be unset. + * + * If @element matches @element_name but one of the checks specified by @options fails, %TRUE will be returned, @error will be set to a + * %GDATA_SERVICE_ERROR_PROTOCOL_ERROR error and @success will be set to %FALSE. + * + * If @element matches @element_name and all of the checks specified by @options pass, %TRUE will be returned, @error will be unset and + * @success will be set to %TRUE. + * + * The reason for returning the success of the parsing in @success is so that calls to gdata_parser_string_from_element() can be chained + * together in a large "or" statement based on their return values, for the purposes of determining whether any of the calls matched + * a given @element. If any of the calls to gdata_parser_string_from_element() return %TRUE, the value of @success can be examined. + * + * Return value: %TRUE if @element matched @element_name, %FALSE otherwise + * + * Since: 0.15.0 + */ +gboolean +gdata_parser_string_from_json_member (JsonReader *reader, const gchar *member_name, GDataParserOptions options, + gchar **output, gboolean *success, GError **error) +{ + const gchar *text; + const GError *child_error = NULL; + + /* Check if there's such element */ + if (g_strcmp0 (json_reader_get_member_name (reader), member_name) != 0) { + return FALSE; + } + + /* Check if the output string has already been set. The JSON parser guarantees this can't happen. */ + g_assert (!(options & P_NO_DUPES) || *output == NULL); + + /* Get the string and check it for NULLness or emptiness. Check for parser errors first. */ + text = json_reader_get_string_value (reader); + child_error = json_reader_get_error (reader); + if (child_error != NULL) { + *success = gdata_parser_error_from_json_error (reader, + child_error, + error); + return TRUE; + } else if ((options & P_REQUIRED && text == NULL) || (options & P_NON_EMPTY && text != NULL && *text == '\0')) { + *success = gdata_parser_error_required_json_content_missing (reader, error); + return TRUE; + } else if (options & P_DEFAULT && (text == NULL || *text == '\0')) { + text = ""; + } + + /* Success! */ + g_free (*output); + *output = g_strdup (text); + *success = TRUE; + + return TRUE; +} + +/* + * gdata_parser_int_from_json_member: + * @reader: #JsonReader cursor object to read JSON node from + * @member_name: the name of the member to parse + * @options: a bitwise combination of parsing options from #GDataParserOptions, + * or %P_NONE + * @output: the return location for the parsed integer content + * @success: the return location for a value which is %TRUE if the integer was + * parsed successfully, %FALSE if an error was encountered, and undefined if + * @element didn't match @element_name + * @error: a #GError, or %NULL + * + * Gets the integer content of @element if its name is @element_name, subject to + * various checks specified by @options. + * + * If @element doesn't match @element_name, %FALSE will be returned, @error will + * be unset and @success will be unset. + * + * If @element matches @element_name but one of the checks specified by @options + * fails, %TRUE will be returned, @error will be set to a +* %GDATA_SERVICE_ERROR_PROTOCOL_ERROR error and @success will be set to %FALSE. + * + * If @element matches @element_name and all of the checks specified by @options + * pass, %TRUE will be returned, @error will be unset and @success will be set + * to %TRUE. + * + * The reason for returning the success of the parsing in @success is so that + * calls to gdata_parser_int_from_element() can be chained together in a large + * "or" statement based on their return values, for the purposes of determining + * whether any of the calls matched a given @element. If any of the calls to + * gdata_parser_int_from_element() return %TRUE, the value of @success can be + * examined. + * + * Return value: %TRUE if @element matched @element_name, %FALSE otherwise + * + * Since: 0.17.0 + */ +gboolean +gdata_parser_int_from_json_member (JsonReader *reader, + const gchar *member_name, + GDataParserOptions options, + gint64 *output, gboolean *success, + GError **error) +{ + gint64 value; + const GError *child_error = NULL; + + /* Check if there's such element */ + if (g_strcmp0 (json_reader_get_member_name (reader), member_name) != 0) { + return FALSE; + } + + value = json_reader_get_int_value (reader); + child_error = json_reader_get_error (reader); + + if (child_error != NULL) { + *success = gdata_parser_error_from_json_error (reader, + child_error, + error); + return TRUE; + } + + /* Success! */ + *output = value; + *success = TRUE; + + return TRUE; +} + +/* + * gdata_parser_int64_time_from_json_member: + * @reader: #JsonReader cursor object to read JSON node from + * @element_name: the name of the element to parse + * @options: a bitwise combination of parsing options from #GDataParserOptions, or %P_NONE + * @output: (out caller-allocates): the return location for the parsed time value + * @success: the return location for a value which is %TRUE if the time val was parsed successfully, %FALSE if an error was encountered, + * and undefined if @element didn't match @element_name + * @error: a #GError, or %NULL + * + * Gets the time value of @element if its name is @element_name, subject to various checks specified by @options. It expects the text content + * of @element to be a date or time value in ISO 8601 format. The returned time value will be a UNIX timestamp (seconds since the epoch). + * + * If @element doesn't match @element_name, %FALSE will be returned, @error will be unset and @success will be unset. + * + * If @element matches @element_name but one of the checks specified by @options fails, %TRUE will be returned, @error will be set to a + * %GDATA_SERVICE_ERROR_PROTOCOL_ERROR error and @success will be set to %FALSE. + * + * If @element matches @element_name and all of the checks specified by @options pass, %TRUE will be returned, @error will be unset and + * @success will be set to %TRUE. + * + * The reason for returning the success of the parsing in @success is so that calls to gdata_parser_int64_time_from_element() can be chained + * together in a large "or" statement based on their return values, for the purposes of determining whether any of the calls matched + * a given @element. If any of the calls to gdata_parser_int64_time_from_element() return %TRUE, the value of @success can be examined. + * + * Return value: %TRUE if @element matched @element_name, %FALSE otherwise + * + * Since: 0.15.0 + */ +gboolean +gdata_parser_int64_time_from_json_member (JsonReader *reader, const gchar *member_name, GDataParserOptions options, + gint64 *output, gboolean *success, GError **error) +{ + const gchar *text; + GTimeVal time_val; + const GError *child_error = NULL; + + /* Check if there's such element */ + if (g_strcmp0 (json_reader_get_member_name (reader), member_name) != 0) { + return FALSE; + } + + /* Check if the output time val has already been set. The JSON parser guarantees this can't happen. */ + g_assert (!(options & P_NO_DUPES) || *output == -1); + + /* Get the string and check it for NULLness. Check for errors first. */ + text = json_reader_get_string_value (reader); + child_error = json_reader_get_error (reader); + if (child_error != NULL) { + *success = gdata_parser_error_from_json_error (reader, + child_error, + error); + return TRUE; + } else if (options & P_REQUIRED && (text == NULL || *text == '\0')) { + *success = gdata_parser_error_required_json_content_missing (reader, error); + return TRUE; + } + + /* Attempt to parse the string as a GTimeVal */ + if (g_time_val_from_iso8601 ((gchar*) text, &time_val) == FALSE) { + *success = gdata_parser_error_not_iso8601_format_json (reader, text, error); + return TRUE; + } + + /* Success! */ + *output = time_val.tv_sec; + *success = TRUE; + + return TRUE; +} + +/* + * gdata_parser_boolean_from_json_member: + * @reader: #JsonReader cursor object to read the JSON node from + * @member_name: the name of the JSON object member to parse + * @options: a bitwise combination of parsing options from #GDataParserOptions, or %P_NONE + * @output: (out caller-allocates): the return location for the parsed boolean value + * @success: (out caller-allocates): the return location for a value which is %TRUE if the boolean was parsed successfully, %FALSE if an error was encountered, + * and undefined if @member_name was not found in the current object in @reader + * @error: (allow-none): a #GError, or %NULL + * + * Gets the boolean value of the @member_name member of the current object in the #JsonReader, subject to various checks specified by @options. + * + * If no member matching @member_name can be found in the current @reader JSON object, %FALSE will be returned, @error will be unset and @success will be unset. @output will be undefined. + * + * If @member_name is found but one of the checks specified by @options fails, %TRUE will be returned, @error will be set to a + * %GDATA_SERVICE_ERROR_PROTOCOL_ERROR error and @success will be set to %FALSE. @output will be undefined. + * + * If @member_name is found and all of the checks specified by @options pass, %TRUE will be returned, @error will be unset and + * @success will be set to %TRUE. @output will be set to the parsed value. + * + * The reason for returning the success of the parsing in @success is so that calls to gdata_parser_boolean_from_json_node() can be chained + * together in a large "or" statement based on their return values, for the purposes of determining whether any of the calls matched + * a given JSON node. If any of the calls to gdata_parser_boolean_from_json_node() return %TRUE, the value of @success can be examined. + * + * Return value: %TRUE if @member_name was found, %FALSE otherwise + * + * Since: 0.15.0 + */ +gboolean +gdata_parser_boolean_from_json_member (JsonReader *reader, const gchar *member_name, GDataParserOptions options, gboolean *output, gboolean *success, GError **error) +{ + gboolean val; + const GError *child_error = NULL; + + /* Check if there's such an element. */ + if (g_strcmp0 (json_reader_get_member_name (reader), member_name) != 0) { + return FALSE; + } + + /* Get the boolean. Check for parse errors. */ + val = json_reader_get_boolean_value (reader); + child_error = json_reader_get_error (reader); + if (child_error != NULL) { + *success = gdata_parser_error_from_json_error (reader, + child_error, + error); + return TRUE; + } + + /* Success! */ + *output = val; + *success = TRUE; + + return TRUE; +} + +/* + * gdata_parser_strv_from_json_member: + * @reader: #JsonReader cursor object to read JSON node from + * @element_name: the name of the element to parse + * @options: a bitwise combination of parsing options from #GDataParserOptions, + * or %P_NONE + * @output: (out callee-allocates) (transfer full): the return location for the + * parsed string array + * @success: the return location for a value which is %TRUE if the string array + * was parsed successfully, %FALSE if an error was encountered, and undefined + * if @element didn't match @element_name + * @error: a #GError, or %NULL + * + * Gets the string array of @element if its name is @element_name, subject to + * various checks specified by @options. It expects the @element to be an array + * of strings. + * + * If @element doesn't match @element_name, %FALSE will be returned, @error will + * be unset and @success will be unset. + * + * If @element matches @element_name but one of the checks specified by @options + * fails, %TRUE will be returned, @error will be set to a + * %GDATA_SERVICE_ERROR_PROTOCOL_ERROR error and @success will be set to %FALSE. + * + * If @element matches @element_name and all of the checks specified by @options + * pass, %TRUE will be returned, @error will be unset and @success will be set + * to %TRUE. + * + * The reason for returning the success of the parsing in @success is so that + * calls to gdata_parser_strv_from_element() can be chained together in a large + * "or" statement based on their return values, for the purposes of determining + * whether any of the calls matched a given @element. If any of the calls to + * gdata_parser_strv_from_element() return %TRUE, the value of @success can be + * examined. + * + * Return value: %TRUE if @element matched @element_name, %FALSE otherwise + * + * Since: 0.17.0 + */ +gboolean +gdata_parser_strv_from_json_member (JsonReader *reader, + const gchar *member_name, + GDataParserOptions options, + gchar ***output, gboolean *success, + GError **error) +{ + guint i, len; + GPtrArray *out; + const GError *child_error = NULL; + + /* Check if there's such element */ + if (g_strcmp0 (json_reader_get_member_name (reader), + member_name) != 0) { + return FALSE; + } + + /* Check if the output strv has already been set. The JSON parser + * guarantees this can't happen. */ + g_assert (!(options & P_NO_DUPES) || *output == NULL); + + len = json_reader_count_elements (reader); + child_error = json_reader_get_error (reader); + + if (child_error != NULL) { + *success = gdata_parser_error_from_json_error (reader, + child_error, + error); + return TRUE; + } + + out = g_ptr_array_new_full (len + 1 /* NULL terminator */, g_free); + + for (i = 0; i < len; i++) { + const gchar *val; + + json_reader_read_element (reader, i); + val = json_reader_get_string_value (reader); + child_error = json_reader_get_error (reader); + + if (child_error != NULL) { + *success = gdata_parser_error_from_json_error (reader, + child_error, + error); + json_reader_end_element (reader); + g_ptr_array_unref (out); + return TRUE; + } + + g_ptr_array_add (out, g_strdup (val)); + + json_reader_end_element (reader); + } + + /* NULL terminator. */ + g_ptr_array_add (out, NULL); + + /* Success! */ + *output = (gchar **) g_ptr_array_free (out, FALSE); + *success = TRUE; + + return TRUE; +} + +/* + * gdata_parser_color_from_json_member: + * @reader: #JsonReader cursor object to read JSON node from + * @element_name: the name of the element to parse + * @options: a bitwise combination of parsing options from #GDataParserOptions, + * or %P_NONE + * @output: (out caller-allocates): the return location for the parsed colour + * value + * @success: the return location for a value which is %TRUE if the colour was + * parsed successfully, %FALSE if an error was encountered, and undefined if + * @element didn't match @element_name + * @error: a #GError, or %NULL + * + * Gets the colour value of @element if its name is @element_name, subject to + * various checks specified by @options. It expects the text content of + * @element to be an RGB colour in hexadecimal format, with an optional leading + * hash symbol (for example, `#RRGGBB` or `RRGGBB`). + * + * If @element doesn't match @element_name, %FALSE will be returned, @error + * will be unset and @success will be unset. + * + * If @element matches @element_name but one of the checks specified by + * @options fails, %TRUE will be returned, @error will be set to a + * %GDATA_SERVICE_ERROR_PROTOCOL_ERROR error and @success will be set to %FALSE. + * + * If @element matches @element_name and all of the checks specified by + * @options pass, %TRUE will be returned, @error will be unset and @success + * will be set to %TRUE. + * + * The reason for returning the success of the parsing in @success is so that + * calls to gdata_parser_color_from_json_member() can be chained together in a + * large "or" statement based on their return values, for the purposes of + * determining whether any of the calls matched a given @element. If any of the + * calls to gdata_parser_color_from_json_member() return %TRUE, the value of + * @success can be examined. + * + * Return value: %TRUE if @element matched @element_name, %FALSE otherwise + * + * Since: 0.17.2 + */ +gboolean +gdata_parser_color_from_json_member (JsonReader *reader, + const gchar *member_name, + GDataParserOptions options, + GDataColor *output, + gboolean *success, + GError **error) +{ + const gchar *text; + GDataColor colour; + const GError *child_error = NULL; + + /* Check if there's such an element */ + if (g_strcmp0 (json_reader_get_member_name (reader), member_name) != 0) { + return FALSE; + } + + /* Check if the output colour has already been set. The JSON parser + * guarantees this can't happen. */ + g_assert (!(options & P_NO_DUPES) || + (output->red == 0 && output->green == 0 && output->blue == 0)); + + /* Get the string and check it for NULLness. Check for errors first. */ + text = json_reader_get_string_value (reader); + child_error = json_reader_get_error (reader); + if (child_error != NULL) { + *success = gdata_parser_error_from_json_error (reader, child_error, error); + return TRUE; + } else if (options & P_REQUIRED && (text == NULL || *text == '\0')) { + *success = gdata_parser_error_required_json_content_missing (reader, error); + return TRUE; + } + + /* Attempt to parse the string as a hexadecimal colour. */ + if (gdata_color_from_hexadecimal (text, &colour) == FALSE) { + /* Error */ + g_set_error (error, GDATA_SERVICE_ERROR, GDATA_SERVICE_ERROR_PROTOCOL_ERROR, + /* Translators: the first parameter is the name of an XML element (including the angle brackets + * ("<" and ">"), and the second parameter is the erroneous value (which was not in hexadecimal + * RGB format). + * + * For example: + * The content of a <entry/gCal:color> element (‘00FG56’) was not in hexadecimal RGB format. */ + _("The content of a %s element (‘%s’) was not in hexadecimal RGB format."), + member_name, text); + *success = FALSE; + + return TRUE; + } + + /* Success! */ + *output = colour; + *success = TRUE; + + return TRUE; +} + +void +gdata_parser_string_append_escaped (GString *xml_string, const gchar *pre, const gchar *element_content, const gchar *post) +{ + /* Allocate 10 extra bytes when reallocating the GString, to try and avoid having to reallocate again, by assuming + * there will be an increase in the length of element_content when escaped of less than 10 characters. */ +/* #define SIZE_FUZZINESS 10*/ + +/* guint new_size;*/ + const gchar *p; + + /* Expand xml_string as necessary */ + /* TODO: There is no way to expand the allocation of a GString if you know in advance how much room + * lots of append operations are going to require. */ +/* new_size = xml_string->len + strlen (pre) + strlen (element_content) + strlen (post) + SIZE_FUZZINESS; + if (new_size > xml_string->allocated_len) + g_string_set_size (xml_string, new_size);*/ + + /* Append the pre content */ + if (pre != NULL) + g_string_append (xml_string, pre); + + /* Loop through the string to be escaped. Code adapted from GLib's g_markup_escape_text() function. + * Copyright 2000, 2003 Red Hat, Inc. + * Copyright 2007, 2008 Ryan Lortie <desrt@desrt.ca> */ + p = element_content; + while (p != NULL && *p != '\0') { + const gchar *next = g_utf8_next_char (p); + + switch (*p) { + case '&': + g_string_append (xml_string, "&"); + break; + case '<': + g_string_append (xml_string, "<"); + break; + case '>': + g_string_append (xml_string, ">"); + break; + case '\'': + g_string_append (xml_string, "'"); + break; + case '"': + g_string_append (xml_string, """); + break; + default: { + gunichar c = g_utf8_get_char (p); + + if ((0x1 <= c && c <= 0x8) || + (0xb <= c && c <= 0xc) || + (0xe <= c && c <= 0x1f) || + (0x7f <= c && c <= 0x84) || + (0x86 <= c && c <= 0x9f)) { + g_string_append_printf (xml_string, "&#x%x;", c); + } else { + g_string_append_len (xml_string, p, next - p); + break; + } + } + } + p = next; + } + + /* Append the post content */ + if (post != NULL) + g_string_append (xml_string, post); +} + +/* TODO: Should be perfectly possible to make this modify the string in-place */ +gchar * +gdata_parser_utf8_trim_whitespace (const gchar *s) +{ + glong len; + const gchar *_s; + + /* Skip the leading whitespace */ + while (*s != '\0' && g_unichar_isspace (g_utf8_get_char (s))) + s = g_utf8_next_char (s); + + /* Find the end of the string and backtrack until we've passed all the whitespace */ + len = g_utf8_strlen (s, -1); + _s = g_utf8_offset_to_pointer (s, len - 1); + while (len > 0 && g_unichar_isspace (g_utf8_get_char (_s))) { + _s = g_utf8_prev_char (_s); + len--; + } + _s = g_utf8_next_char (_s); + + return g_strndup (s, _s - s); +} diff --git a/gdata/gdata-parser.h b/gdata/gdata-parser.h new file mode 100644 index 0000000..0eddf13 --- /dev/null +++ b/gdata/gdata-parser.h @@ -0,0 +1,124 @@ +/* -*- Mode: C; indent-tabs-mode: t; c-basic-offset: 8; tab-width: 8 -*- */ +/* + * GData Client + * Copyright (C) Philip Withnall 2009 <philip@tecnocode.co.uk> + * + * GData Client is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * GData Client is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with GData Client. If not, see <http://www.gnu.org/licenses/>. + */ + +#include <glib.h> + +#include "gdata-parsable.h" +#include "gdata-types.h" + +#ifndef GDATA_PARSER_H +#define GDATA_PARSER_H + +G_BEGIN_DECLS + +gboolean gdata_parser_error_required_content_missing (xmlNode *element, GError **error); +gboolean gdata_parser_error_not_iso8601_format (xmlNode *element, const gchar *actual_value, GError **error); +gboolean gdata_parser_error_unknown_property_value (xmlNode *element, const gchar *property_name, const gchar *actual_value, GError **error); +gboolean gdata_parser_error_unknown_content (xmlNode *element, const gchar *actual_content, GError **error); +gboolean gdata_parser_error_required_property_missing (xmlNode *element, const gchar *property_name, GError **error); +gboolean gdata_parser_error_mutexed_properties (xmlNode *element, const gchar *property1_name, const gchar *property2_name, GError **error); +gboolean gdata_parser_error_required_element_missing (const gchar *element_name, const gchar *parent_element_name, GError **error); +gboolean gdata_parser_error_duplicate_element (xmlNode *element, GError **error); + +gboolean gdata_parser_error_duplicate_json_element (JsonReader *reader, GError **error); +gboolean gdata_parser_error_required_json_content_missing (JsonReader *reader, GError **error); +gboolean gdata_parser_error_not_iso8601_format_json (JsonReader *reader, const gchar *actual_value, GError **error); +gboolean +gdata_parser_error_from_json_error (JsonReader *reader, + const GError *json_error, GError **error); + +gboolean gdata_parser_int64_from_date (const gchar *date, gint64 *_time); +gchar *gdata_parser_date_from_int64 (gint64 _time) G_GNUC_WARN_UNUSED_RESULT G_GNUC_MALLOC; +gchar *gdata_parser_int64_to_iso8601 (gint64 _time) G_GNUC_WARN_UNUSED_RESULT G_GNUC_MALLOC; +gboolean gdata_parser_int64_from_iso8601 (const gchar *date, gint64 *_time); + +/* + * GDataParserOptions: + * @P_NONE: no special options; the content of the element will be outputted directly without any checks + * @P_NO_DUPES: the element must be encountered at most once; if encountered more than once, an error will be returned + * @P_REQUIRED: the element content must not be %NULL if the element exists + * @P_NON_EMPTY: the element content must not be empty (i.e. a zero-length string) if the element exists; + * this only applies to gdata_parser_string_from_element() + * @P_DEFAULT: if the element content is %NULL or empty, return an empty value instead of erroring (this is mutually exclusive with %P_REQUIRED + * and %P_NON_EMPTY) + * @P_IGNORE_ERROR: ignore any error when the parse fails; can be used to skip empty values (this is mutually exclusive with %P_REQUIRED) + * + * Parsing options to be passed in a bitwise fashion to gdata_parser_string_from_element() or gdata_parser_object_from_element(). + * Their names aren't namespaced as they aren't public, and brevity is important, since they're used frequently in the parsing code. + * + * Since: 0.7.0 + */ +typedef enum { + P_NONE = 0, + P_NO_DUPES = 1 << 0, + P_REQUIRED = 1 << 1, + P_NON_EMPTY = 1 << 2, + P_DEFAULT = 1 << 3, + P_IGNORE_ERROR = 1 << 4 +} GDataParserOptions; + +typedef void (*GDataParserSetterFunc) (GDataParsable *parent_parsable, GDataParsable *parsable); + +gboolean gdata_parser_boolean_from_property (xmlNode *element, const gchar *property_name, gboolean *output, gint default_output, GError **error); + +gboolean gdata_parser_is_namespace (xmlNode *element, const gchar *namespace_uri); + +gboolean gdata_parser_string_from_element (xmlNode *element, const gchar *element_name, GDataParserOptions options, + gchar **output, gboolean *success, GError **error); +gboolean gdata_parser_int64_time_from_element (xmlNode *element, const gchar *element_name, GDataParserOptions options, + gint64 *output, gboolean *success, GError **error); +gboolean gdata_parser_int64_from_element (xmlNode *element, const gchar *element_name, GDataParserOptions options, + gint64 *output, gint64 default_output, gboolean *success, GError **error); +gboolean gdata_parser_object_from_element_setter (xmlNode *element, const gchar *element_name, GDataParserOptions options, GType object_type, + gpointer /* GDataParserSetterFunc */ _setter, gpointer /* GDataParsable * */ _parent_parsable, + gboolean *success, GError **error); +gboolean gdata_parser_object_from_element (xmlNode *element, const gchar *element_name, GDataParserOptions options, GType object_type, + gpointer /* GDataParsable ** */ _output, gboolean *success, GError **error); +gboolean gdata_parser_string_from_json_member (JsonReader *reader, const gchar *member_name, GDataParserOptions options, + gchar **output, gboolean *success, GError **error); +gboolean +gdata_parser_int_from_json_member (JsonReader *reader, + const gchar *member_name, + GDataParserOptions options, + gint64 *output, gboolean *success, + GError **error); +gboolean gdata_parser_int64_time_from_json_member (JsonReader *reader, const gchar *member_name, GDataParserOptions options, + gint64 *output, gboolean *success, GError **error); +gboolean gdata_parser_boolean_from_json_member (JsonReader *reader, const gchar *member_name, GDataParserOptions options, + gboolean *output, gboolean *success, GError **error); +gboolean +gdata_parser_strv_from_json_member (JsonReader *reader, + const gchar *member_name, + GDataParserOptions options, + gchar ***output, gboolean *success, + GError **error); +gboolean +gdata_parser_color_from_json_member (JsonReader *reader, + const gchar *member_name, + GDataParserOptions options, + GDataColor *output, + gboolean *success, + GError **error); + +void gdata_parser_string_append_escaped (GString *xml_string, const gchar *pre, const gchar *element_content, const gchar *post); +gchar *gdata_parser_utf8_trim_whitespace (const gchar *s) G_GNUC_WARN_UNUSED_RESULT G_GNUC_MALLOC; + +G_END_DECLS + +#endif /* !GDATA_PARSER_H */ diff --git a/gdata/gdata-private.h b/gdata/gdata-private.h new file mode 100644 index 0000000..90b055c --- /dev/null +++ b/gdata/gdata-private.h @@ -0,0 +1,174 @@ +/* -*- Mode: C; indent-tabs-mode: t; c-basic-offset: 8; tab-width: 8 -*- */ +/* + * GData Client + * Copyright (C) Philip Withnall 2008-2009 <philip@tecnocode.co.uk> + * + * GData Client is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * GData Client is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with GData Client. If not, see <http://www.gnu.org/licenses/>. + */ + +#ifndef GDATA_PRIVATE_H +#define GDATA_PRIVATE_H + +#include <glib.h> +#include <libxml/parser.h> +#include <libsoup/soup.h> + +#include <gdata/gdata-service.h> + +G_BEGIN_DECLS + +/** + * GDataLogLevel: + * @GDATA_LOG_NONE: Output no debug messages or network logs + * @GDATA_LOG_MESSAGES: Output debug messages, but not network logs + * @GDATA_LOG_HEADERS: Output debug messages and network traffic headers + * @GDATA_LOG_FULL: Output debug messages and full network traffic logs, + * redacting usernames, passwords and auth. tokens + * @GDATA_LOG_FULL_UNREDACTED: Output debug messages and full network traffic + * logs, and don't redact usernames, passwords and auth. tokens + * + * Logging level. + */ +typedef enum { + GDATA_LOG_NONE = 0, + GDATA_LOG_MESSAGES = 1, + GDATA_LOG_HEADERS = 2, + GDATA_LOG_FULL = 3, + GDATA_LOG_FULL_UNREDACTED = 4, +} GDataLogLevel; + +#include "gdata-service.h" +G_GNUC_INTERNAL SoupSession *_gdata_service_get_session (GDataService *self) G_GNUC_PURE; +G_GNUC_INTERNAL SoupMessage *_gdata_service_build_message (GDataService *self, GDataAuthorizationDomain *domain, const gchar *method, const gchar *uri, + const gchar *etag, gboolean etag_if_match); +G_GNUC_INTERNAL void _gdata_service_actually_send_message (SoupSession *session, SoupMessage *message, GCancellable *cancellable, GError **error); +G_GNUC_INTERNAL guint _gdata_service_send_message (GDataService *self, SoupMessage *message, GCancellable *cancellable, GError **error); +G_GNUC_INTERNAL SoupMessage *_gdata_service_query (GDataService *self, GDataAuthorizationDomain *domain, const gchar *feed_uri, GDataQuery *query, + GCancellable *cancellable, GError **error) G_GNUC_WARN_UNUSED_RESULT G_GNUC_MALLOC; +G_GNUC_INTERNAL const gchar *_gdata_service_get_scheme (void) G_GNUC_CONST; +G_GNUC_INTERNAL gchar *_gdata_service_build_uri (const gchar *format, ...) G_GNUC_PRINTF (1, 2) G_GNUC_WARN_UNUSED_RESULT G_GNUC_MALLOC; +G_GNUC_INTERNAL guint _gdata_service_get_https_port (void); +G_GNUC_INTERNAL gchar *_gdata_service_fix_uri_scheme (const gchar *uri) G_GNUC_WARN_UNUSED_RESULT G_GNUC_MALLOC; +G_GNUC_INTERNAL GDataLogLevel _gdata_service_get_log_level (void) G_GNUC_CONST; +G_GNUC_INTERNAL SoupSession *_gdata_service_build_session (void) G_GNUC_WARN_UNUSED_RESULT G_GNUC_MALLOC; + +typedef gchar *GDataSecureString; +typedef const gchar *GDataConstSecureString; + +G_GNUC_INTERNAL GDataSecureString _gdata_service_secure_strdup (const gchar *str) G_GNUC_WARN_UNUSED_RESULT G_GNUC_MALLOC; +G_GNUC_INTERNAL GDataSecureString _gdata_service_secure_strndup (const gchar *str, gsize n_bytes) G_GNUC_WARN_UNUSED_RESULT G_GNUC_MALLOC; +G_GNUC_INTERNAL void _gdata_service_secure_strfree (GDataSecureString str); + +#include "gdata-query.h" +typedef enum { + GDATA_QUERY_PAGINATION_INDEXED, + GDATA_QUERY_PAGINATION_URIS, + GDATA_QUERY_PAGINATION_TOKENS, +} GDataQueryPaginationType; + +G_GNUC_INTERNAL void _gdata_query_add_q_internal (GDataQuery *self, const gchar *q); +G_GNUC_INTERNAL void _gdata_query_clear_q_internal (GDataQuery *self); +G_GNUC_INTERNAL void _gdata_query_clear_pagination (GDataQuery *self); +G_GNUC_INTERNAL void _gdata_query_set_pagination_type (GDataQuery *self, + GDataQueryPaginationType type); +G_GNUC_INTERNAL void _gdata_query_set_next_page_token (GDataQuery *self, const gchar *next_page_token); +G_GNUC_INTERNAL void _gdata_query_set_next_uri (GDataQuery *self, const gchar *next_uri); +G_GNUC_INTERNAL gboolean _gdata_query_is_finished (GDataQuery *self); +G_GNUC_INTERNAL void _gdata_query_set_previous_uri (GDataQuery *self, const gchar *previous_uri); + +#include "gdata-parsable.h" +G_GNUC_INTERNAL GDataParsable *_gdata_parsable_new_from_xml (GType parsable_type, const gchar *xml, gint length, gpointer user_data, + GError **error) G_GNUC_WARN_UNUSED_RESULT G_GNUC_MALLOC; +G_GNUC_INTERNAL GDataParsable *_gdata_parsable_new_from_xml_node (GType parsable_type, xmlDoc *doc, xmlNode *node, gpointer user_data, + GError **error) G_GNUC_WARN_UNUSED_RESULT G_GNUC_MALLOC; +G_GNUC_INTERNAL GDataParsable *_gdata_parsable_new_from_json (GType parsable_type, const gchar *json, gint length, gpointer user_data, + GError **error) G_GNUC_WARN_UNUSED_RESULT G_GNUC_MALLOC; +G_GNUC_INTERNAL GDataParsable *_gdata_parsable_new_from_json_node (GType parsable_type, JsonReader *reader, gpointer user_data, + GError **error) G_GNUC_WARN_UNUSED_RESULT G_GNUC_MALLOC; +G_GNUC_INTERNAL void _gdata_parsable_get_xml (GDataParsable *self, GString *xml_string, gboolean declare_namespaces); +G_GNUC_INTERNAL void _gdata_parsable_get_json (GDataParsable *self, JsonBuilder *builder); +G_GNUC_INTERNAL void _gdata_parsable_string_append_escaped (GString *xml_string, const gchar *pre, const gchar *element_content, const gchar *post); +G_GNUC_INTERNAL gboolean _gdata_parsable_is_constructed_from_xml (GDataParsable *self); + +#include "gdata-feed.h" +G_GNUC_INTERNAL GDataFeed *_gdata_feed_new (GType feed_type, + const gchar *title, + const gchar *id, + gint64 updated) G_GNUC_WARN_UNUSED_RESULT; +G_GNUC_INTERNAL GDataFeed *_gdata_feed_new_from_xml (GType feed_type, const gchar *xml, gint length, GType entry_type, + GDataQueryProgressCallback progress_callback, gpointer progress_user_data, + GError **error) G_GNUC_WARN_UNUSED_RESULT G_GNUC_MALLOC; +G_GNUC_INTERNAL GDataFeed *_gdata_feed_new_from_json (GType feed_type, const gchar *json, gint length, GType entry_type, + GDataQueryProgressCallback progress_callback, gpointer progress_user_data, + GError **error) G_GNUC_WARN_UNUSED_RESULT G_GNUC_MALLOC; +G_GNUC_INTERNAL void _gdata_feed_add_entry (GDataFeed *self, GDataEntry *entry); +G_GNUC_INTERNAL void _gdata_feed_add_link (GDataFeed *self, GDataLink *_link); +G_GNUC_INTERNAL gpointer _gdata_feed_parse_data_new (GType entry_type, GDataQueryProgressCallback progress_callback, gpointer progress_user_data); +G_GNUC_INTERNAL void _gdata_feed_parse_data_free (gpointer data); +G_GNUC_INTERNAL void _gdata_feed_call_progress_callback (GDataFeed *self, gpointer user_data, GDataEntry *entry); +G_GNUC_INTERNAL void +_gdata_feed_set_page_info (GDataFeed *self, guint total_results, + guint items_per_page); + +#include "gdata-entry.h" +#include "gdata-batch-operation.h" +G_GNUC_INTERNAL void _gdata_entry_set_updated (GDataEntry *self, gint64 updated); +G_GNUC_INTERNAL void _gdata_entry_set_published (GDataEntry *self, gint64 published); +G_GNUC_INTERNAL void _gdata_entry_set_id (GDataEntry *self, const gchar *id); +G_GNUC_INTERNAL void _gdata_entry_set_etag (GDataEntry *self, const gchar *etag); +G_GNUC_INTERNAL void _gdata_entry_set_batch_data (GDataEntry *self, guint id, GDataBatchOperationType type); + +#include "gdata-access-rule.h" +G_GNUC_INTERNAL void _gdata_access_rule_set_key (GDataAccessRule *self, const gchar *key); + +#include "gdata-parser.h" + +/** + * _GDATA_DEFINE_AUTHORIZATION_DOMAIN: + * @l_n: lowercase name for the authorization domain, separated by underscores + * @SERVICE_NAME: the service name, as listed here: http://code.google.com/apis/documents/faq_gdata.html#clientlogin + * @SCOPE: the scope URI, as listed here: http://code.google.com/apis/documents/faq_gdata.html#AuthScopes + * + * Defines a static function to return an interned singleton #GDataAuthorizationDomain instance for the given parameters. Every time it's called, the + * function will return the same instance. + * + * The function will be named <code class="literal">get_(l_n)_authorization_domain</code>. + * + * Return value: (transfer none): a #GDataAuthorizationDomain instance for the given parameters + * + * Since: 0.9.0 + */ +#define _GDATA_DEFINE_AUTHORIZATION_DOMAIN(l_n, SERVICE_NAME, SCOPE) \ +static GDataAuthorizationDomain * \ +get_##l_n##_authorization_domain (void) \ +{ \ + static volatile GDataAuthorizationDomain *domain__volatile = NULL; \ + \ + if (g_once_init_enter (&domain__volatile) == TRUE) { \ + GDataAuthorizationDomain *domain; \ + \ + domain = g_object_new (GDATA_TYPE_AUTHORIZATION_DOMAIN, \ + "service-name", SERVICE_NAME, \ + "scope", SCOPE, \ + NULL); \ + \ + g_once_init_leave (&domain__volatile, domain); \ + } \ + \ + return GDATA_AUTHORIZATION_DOMAIN (domain__volatile); \ +} + +G_END_DECLS + +#endif /* !GDATA_PRIVATE_H */ diff --git a/gdata/gdata-query.c b/gdata/gdata-query.c new file mode 100644 index 0000000..e2d5948 --- /dev/null +++ b/gdata/gdata-query.c @@ -0,0 +1,1222 @@ +/* -*- Mode: C; indent-tabs-mode: t; c-basic-offset: 8; tab-width: 8 -*- */ +/* + * GData Client + * Copyright (C) Philip Withnall 2009–2010 <philip@tecnocode.co.uk> + * Copyright (C) Red Hat, Inc. 2015 + * + * GData Client is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * GData Client is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with GData Client. If not, see <http://www.gnu.org/licenses/>. + */ + +/** + * SECTION:gdata-query + * @short_description: GData query object + * @stability: Stable + * @include: gdata/gdata-query.h + * + * #GDataQuery represents a collection of query parameters used in a series of queries on a #GDataService. It allows the query parameters to be + * set, with the aim of building a query URI using gdata_query_get_query_uri(). Pagination is supported using gdata_query_next_page() and + * gdata_query_previous_page(). + * + * Each query can have an ETag associated with it, which is a unique identifier for the set of query results produced by the query. + * Each time a query is made, gdata_service_query() will set the #GDataQuery:etag property of the accompanying query to a value returned by the + * server. If the same query is made again (using the same #GDataQuery instance), the server can skip returning the resulting #GDataFeed if its + * contents haven't changed (in this case, gdata_service_query() will return %NULL with an empty error). + * + * For this reason, code using #GDataQuery should be careful when reusing #GDataQuery instances: the code should either unset #GDataQuery:etag after + * every query or (preferably) gracefully handle the case where gdata_service_query() returns %NULL to signify unchanged results. + * + * Every time a property of a #GDataQuery instance is changed, the instance's ETag will be unset. + * + * For more information on the standard GData query parameters supported by #GDataQuery, see the <ulink type="http" + * url="http://code.google.com/apis/gdata/docs/2.0/reference.html#Queries">online documentation</ulink>. + */ + +#include <glib.h> +#include <string.h> + +#include "gdata-query.h" +#include "gdata-private.h" +#include "gdata-types.h" + +static void gdata_query_finalize (GObject *object); +static void gdata_query_get_property (GObject *object, guint property_id, GValue *value, GParamSpec *pspec); +static void gdata_query_set_property (GObject *object, guint property_id, const GValue *value, GParamSpec *pspec); +static void get_query_uri (GDataQuery *self, const gchar *feed_uri, GString *query_uri, gboolean *params_started); + +struct _GDataQueryPrivate { + /* Standard query parameters (see: http://code.google.com/apis/gdata/docs/2.0/reference.html#Queries) */ + gchar *q; + gchar *q_internal; + gchar *categories; + gchar *author; + gint64 updated_min; + gint64 updated_max; + gint64 published_min; + gint64 published_max; + guint start_index; + gboolean is_strict; + guint max_results; + + /* Pagination management. The type of pagination is set as + * pagination_type, and should be set in the init() vfunc implementation + * of any class derived from GDataQuery. It defaults to + * %GDATA_QUERY_PAGINATION_INDEXED, which most subclasses will not want. + * + * The next_uri, previous_uri or next_page_token are set by + * #GDataService if a query returns a new #GDataFeed containing them. If + * the user then calls next_page() or previous_page(), use_next_page or + * use_previous_page are set as appropriate, and the next call to + * get_uri() will return a URI for the next or previous page. This might + * be next_uri, previous_uri, or a constructed URI which appends the + * next_page_token. + * + * Note that %GDATA_QUERY_PAGINATION_TOKENS does not support returning + * to the previous page. + * + * It is not invalid to have use_next_page set and to not have a + * next_uri for %GDATA_QUERY_PAGINATION_URIS; or to not have a + * next_page_token for %GDATA_QUERY_PAGINATION_TOKENS: this signifies + * that the current set of results are the last page. There are no + * further pages. Similarly for use_previous_page and a %NULL + * previous_page. + */ + GDataQueryPaginationType pagination_type; + + gchar *next_uri; + gchar *previous_uri; + gchar *next_page_token; + + gboolean use_next_page; + gboolean use_previous_page; + + gchar *etag; +}; + +enum { + PROP_Q = 1, + PROP_CATEGORIES, + PROP_AUTHOR, + PROP_UPDATED_MIN, + PROP_UPDATED_MAX, + PROP_PUBLISHED_MIN, + PROP_PUBLISHED_MAX, + PROP_START_INDEX, + PROP_IS_STRICT, + PROP_MAX_RESULTS, + PROP_ETAG +}; + +G_DEFINE_TYPE (GDataQuery, gdata_query, G_TYPE_OBJECT) + +static void +gdata_query_class_init (GDataQueryClass *klass) +{ + GObjectClass *gobject_class = G_OBJECT_CLASS (klass); + + g_type_class_add_private (klass, sizeof (GDataQueryPrivate)); + + gobject_class->set_property = gdata_query_set_property; + gobject_class->get_property = gdata_query_get_property; + gobject_class->finalize = gdata_query_finalize; + + klass->get_query_uri = get_query_uri; + + /** + * GDataQuery:q: + * + * A full-text query string. + * + * When creating a query, list search terms separated by spaces, in the form <userinput>term1 term2 term3</userinput>. + * (As with all of the query parameter values, the spaces must be URL encoded.) The service returns all entries that match all of the + * search terms (like using AND between terms). Like Google's web search, a service searches on complete words (and related words with + * the same stem), not substrings. + * + * To search for an exact phrase, enclose the phrase in quotation marks: <userinput>"exact phrase"</userinput>. + * + * To exclude entries that match a given term, use the form <userinput>-term</userinput>. + * + * The search is case-insensitive. + * + * Example: to search for all entries that contain the exact phrase "Elizabeth Bennet" and the word "Darcy" but don't contain the + * word "Austen", use the following query: <userinput>"Elizabeth Bennet" Darcy -Austen</userinput>. + */ + g_object_class_install_property (gobject_class, PROP_Q, + g_param_spec_string ("q", + "Query terms", "Query terms for which to search.", + NULL, + G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)); + + /** + * GDataQuery:categories: + * + * A category filter. + * + * You can query on multiple categories by listing multiple categories separated by slashes. The service returns all entries that match all + * of the categories (like using AND between terms). For example: <userinput>Fritz/Laurie</userinput> returns + * entries that match both categories ("Fritz" and "Laurie"). + * + * To do an OR between terms, use a pipe character (<literal>|</literal>). For example: <userinput>Fritz\%7CLaurie</userinput> returns + * entries that match either category. + * + * An entry matches a specified category if the entry is in a category that has a matching term or label, as defined in the Atom + * specification. (Roughly, the "term" is the internal string used by the software to identify the category, while the "label" is the + * human-readable string presented to a user in a user interface.) + * + * To exclude entries that match a given category, use the form <userinput>-categoryname</userinput>. + * + * To query for a category that has a scheme – such as <literal><category scheme="urn:google.com" term="public"/></literal> – you must + * place the scheme in curly braces before the category name. For example: <userinput>{urn:google.com}public</userinput>. To match a category + * that has no scheme, use an empty pair of curly braces. If you don't specify curly braces, then categories in any scheme will match. + * + * The above features can be combined. For example: <userinput>A|-{urn:google.com}B/-C</userinput> means (A OR (NOT B)) AND (NOT C). + */ + g_object_class_install_property (gobject_class, PROP_CATEGORIES, + g_param_spec_string ("categories", + "Category string", "Category search string.", + NULL, + G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)); + + /** + * GDataQuery:author: + * + * An entry author. The service returns entries where the author name and/or e-mail address match your query string. + */ + g_object_class_install_property (gobject_class, PROP_AUTHOR, + g_param_spec_string ("author", + "Author", "Author search string.", + NULL, + G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)); + + /** + * GDataQuery:updated-min: + * + * Lower bound on the entry update date, inclusive. + */ + g_object_class_install_property (gobject_class, PROP_UPDATED_MIN, + g_param_spec_int64 ("updated-min", + "Minimum update date", "Minimum date for updates on returned entries.", + -1, G_MAXINT64, -1, + G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)); + + /** + * GDataQuery:updated-max: + * + * Upper bound on the entry update date, exclusive. + */ + g_object_class_install_property (gobject_class, PROP_UPDATED_MAX, + g_param_spec_int64 ("updated-max", + "Maximum update date", "Maximum date for updates on returned entries.", + -1, G_MAXINT64, -1, + G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)); + + /** + * GDataQuery:published-min: + * + * Lower bound on the entry publish date, inclusive. + */ + g_object_class_install_property (gobject_class, PROP_PUBLISHED_MIN, + g_param_spec_int64 ("published-min", + "Minimum publish date", "Minimum date for returned entries to be published.", + -1, G_MAXINT64, -1, + G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)); + + /** + * GDataQuery:published-max: + * + * Upper bound on the entry publish date, exclusive. + */ + g_object_class_install_property (gobject_class, PROP_PUBLISHED_MAX, + g_param_spec_int64 ("published-max", + "Maximum publish date", "Maximum date for returned entries to be published.", + -1, G_MAXINT64, -1, + G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)); + + /** + * GDataQuery:start-index: + * + * The one-based index of the first result to be retrieved. Use gdata_query_next_page() and gdata_query_previous_page() to + * implement pagination, rather than manually changing #GDataQuery:start-index. + * + * Use <code class="literal">0</code> to not specify a start index. + */ + g_object_class_install_property (gobject_class, PROP_START_INDEX, + g_param_spec_uint ("start-index", + "Start index", "One-based result start index.", + 0, G_MAXUINT, 0, + G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)); + + /** + * GDataQuery:is-strict: + * + * Strict query parameter checking. If this is enabled, an error will be returned by the online service if a parameter is + * not recognised. + * + * Since: 0.2.0 + */ + g_object_class_install_property (gobject_class, PROP_IS_STRICT, + g_param_spec_boolean ("is-strict", + "Strict?", "Should the server be strict about the query?", + FALSE, + G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)); + + /** + * GDataQuery:max-results: + * + * Maximum number of results to be retrieved. Most services have a default #GDataQuery:max-results size imposed by the server; if you wish + * to receive the entire feed, specify a large number such as %G_MAXUINT for this property. + * + * Use <code class="literal">0</code> to not specify a maximum number of results. + */ + g_object_class_install_property (gobject_class, PROP_MAX_RESULTS, + g_param_spec_uint ("max-results", + "Maximum number of results", "The maximum number of entries to return.", + 0, G_MAXUINT, 0, + G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)); + + /** + * GDataQuery:etag: + * + * The ETag against which to check for updates. If the server-side ETag matches this one, the requested feed hasn't changed, and is not + * returned unnecessarily. + * + * Setting any of the other query properties will unset the ETag, as ETags match against entire queries. If the ETag should be used in a + * query, it must be set again using gdata_query_set_etag() after setting any other properties. + * + * Since: 0.2.0 + */ + g_object_class_install_property (gobject_class, PROP_ETAG, + g_param_spec_string ("etag", + "ETag", "An ETag against which to check.", + NULL, + G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)); +} + +static void +gdata_query_init (GDataQuery *self) +{ + self->priv = G_TYPE_INSTANCE_GET_PRIVATE (self, GDATA_TYPE_QUERY, GDataQueryPrivate); + self->priv->updated_min = -1; + self->priv->updated_max = -1; + self->priv->published_min = -1; + self->priv->published_max = -1; + + _gdata_query_set_pagination_type (self, GDATA_QUERY_PAGINATION_INDEXED); +} + +static void +gdata_query_finalize (GObject *object) +{ + GDataQueryPrivate *priv = GDATA_QUERY (object)->priv; + + g_free (priv->q); + g_free (priv->q_internal); + g_free (priv->categories); + g_free (priv->author); + g_free (priv->next_uri); + g_free (priv->previous_uri); + g_free (priv->etag); + g_free (priv->next_page_token); + + /* Chain up to the parent class */ + G_OBJECT_CLASS (gdata_query_parent_class)->finalize (object); +} + +static void +gdata_query_get_property (GObject *object, guint property_id, GValue *value, GParamSpec *pspec) +{ + GDataQueryPrivate *priv = GDATA_QUERY (object)->priv; + + switch (property_id) { + case PROP_Q: + g_value_set_string (value, priv->q); + break; + case PROP_CATEGORIES: + g_value_set_string (value, priv->categories); + break; + case PROP_AUTHOR: + g_value_set_string (value, priv->author); + break; + case PROP_UPDATED_MIN: + g_value_set_int64 (value, priv->updated_min); + break; + case PROP_UPDATED_MAX: + g_value_set_int64 (value, priv->updated_max); + break; + case PROP_PUBLISHED_MIN: + g_value_set_int64 (value, priv->published_min); + break; + case PROP_PUBLISHED_MAX: + g_value_set_int64 (value, priv->published_max); + break; + case PROP_START_INDEX: + g_value_set_uint (value, priv->start_index); + break; + case PROP_IS_STRICT: + g_value_set_boolean (value, priv->is_strict); + break; + case PROP_MAX_RESULTS: + g_value_set_uint (value, priv->max_results); + break; + case PROP_ETAG: + g_value_set_string (value, priv->etag); + break; + default: + /* We don't have any other property... */ + G_OBJECT_WARN_INVALID_PROPERTY_ID (object, property_id, pspec); + break; + } +} + +static void +gdata_query_set_property (GObject *object, guint property_id, const GValue *value, GParamSpec *pspec) +{ + GDataQuery *self = GDATA_QUERY (object); + + switch (property_id) { + case PROP_Q: + gdata_query_set_q (self, g_value_get_string (value)); + break; + case PROP_CATEGORIES: + gdata_query_set_categories (self, g_value_get_string (value)); + break; + case PROP_AUTHOR: + gdata_query_set_author (self, g_value_get_string (value)); + break; + case PROP_UPDATED_MIN: + gdata_query_set_updated_min (self, g_value_get_int64 (value)); + break; + case PROP_UPDATED_MAX: + gdata_query_set_updated_max (self, g_value_get_int64 (value)); + break; + case PROP_PUBLISHED_MIN: + gdata_query_set_published_min (self, g_value_get_int64 (value)); + break; + case PROP_PUBLISHED_MAX: + gdata_query_set_published_max (self, g_value_get_int64 (value)); + break; + case PROP_START_INDEX: + gdata_query_set_start_index (self, g_value_get_uint (value)); + break; + case PROP_IS_STRICT: + gdata_query_set_is_strict (self, g_value_get_boolean (value)); + break; + case PROP_MAX_RESULTS: + gdata_query_set_max_results (self, g_value_get_uint (value)); + break; + case PROP_ETAG: + gdata_query_set_etag (self, g_value_get_string (value)); + break; + default: + /* We don't have any other property... */ + G_OBJECT_WARN_INVALID_PROPERTY_ID (object, property_id, pspec); + break; + } +} + +static void +get_query_uri (GDataQuery *self, const gchar *feed_uri, GString *query_uri, gboolean *params_started) +{ + GDataQueryPrivate *priv = self->priv; + + #define APPEND_SEP g_string_append_c (query_uri, (*params_started == FALSE) ? '?' : '&'); *params_started = TRUE; + + /* Categories */ + if (priv->categories != NULL) { + g_string_append (query_uri, "/-/"); + g_string_append_uri_escaped (query_uri, priv->categories, "/", FALSE); + } + + /* q param */ + if (priv->q != NULL || priv->q_internal != NULL) { + APPEND_SEP + g_string_append (query_uri, "q="); + + if (priv->q != NULL) { + g_string_append_uri_escaped (query_uri, priv->q, NULL, FALSE); + if (priv->q_internal != NULL) + g_string_append (query_uri, "%20and%20"); + } + if (priv->q_internal != NULL) + g_string_append_uri_escaped (query_uri, priv->q_internal, NULL, FALSE); + } + + if (priv->author != NULL) { + APPEND_SEP + g_string_append (query_uri, "author="); + g_string_append_uri_escaped (query_uri, priv->author, NULL, FALSE); + } + + if (priv->updated_min != -1) { + gchar *updated_min; + + APPEND_SEP + g_string_append (query_uri, "updated-min="); + updated_min = gdata_parser_int64_to_iso8601 (priv->updated_min); + g_string_append (query_uri, updated_min); + g_free (updated_min); + } + + if (priv->updated_max != -1) { + gchar *updated_max; + + APPEND_SEP + g_string_append (query_uri, "updated-max="); + updated_max = gdata_parser_int64_to_iso8601 (priv->updated_max); + g_string_append (query_uri, updated_max); + g_free (updated_max); + } + + if (priv->published_min != -1) { + gchar *published_min; + + APPEND_SEP + g_string_append (query_uri, "published-min="); + published_min = gdata_parser_int64_to_iso8601 (priv->published_min); + g_string_append (query_uri, published_min); + g_free (published_min); + } + + if (priv->published_max != -1) { + gchar *published_max; + + APPEND_SEP + g_string_append (query_uri, "published-max="); + published_max = gdata_parser_int64_to_iso8601 (priv->published_max); + g_string_append (query_uri, published_max); + g_free (published_max); + } + + if (priv->start_index > 0) { + APPEND_SEP + g_string_append_printf (query_uri, "start-index=%u", priv->start_index); + } + + if (priv->is_strict == TRUE) { + APPEND_SEP + g_string_append (query_uri, "strict=true"); + } + + if (priv->max_results > 0) { + APPEND_SEP + g_string_append_printf (query_uri, "max-results=%u", priv->max_results); + } + + if (priv->pagination_type == GDATA_QUERY_PAGINATION_TOKENS && priv->use_next_page && + priv->next_page_token != NULL && *priv->next_page_token != '\0') { + APPEND_SEP + g_string_append (query_uri, "pageToken="); + g_string_append_uri_escaped (query_uri, priv->next_page_token, NULL, FALSE); + } +} + +/** + * gdata_query_new: + * @q: (allow-none): a query string, or %NULL + * + * Creates a new #GDataQuery with its #GDataQuery:q property set to @q. + * + * Return value: a new #GDataQuery + */ +GDataQuery * +gdata_query_new (const gchar *q) +{ + return g_object_new (GDATA_TYPE_QUERY, "q", q, NULL); +} + +/** + * gdata_query_new_with_limits: + * @q: (allow-none): a query string, or %NULL + * @start_index: a one-based start index for the results, or <code class="literal">0</code> + * @max_results: the maximum number of results to return, or <code class="literal">0</code> + * + * Creates a new #GDataQuery with its #GDataQuery:q property set to @q, and the limits @start_index and @max_results + * applied. + * + * Return value: a new #GDataQuery + */ +GDataQuery * +gdata_query_new_with_limits (const gchar *q, guint start_index, guint max_results) +{ + return g_object_new (GDATA_TYPE_QUERY, + "q", q, + "start-index", start_index, + "max-results", max_results, + NULL); +} + +/** + * gdata_query_get_query_uri: + * @self: a #GDataQuery + * @feed_uri: the feed URI on which to build the query URI + * + * Builds a query URI from the given base feed URI, using the properties of the #GDataQuery. This function will take care + * of all necessary URI escaping, so it should <emphasis>not</emphasis> be done beforehand. + * + * The query URI is what functions like gdata_service_query() use to query the online service. + * + * Return value: a query URI; free with g_free() + */ +gchar * +gdata_query_get_query_uri (GDataQuery *self, const gchar *feed_uri) +{ + GDataQueryClass *klass; + GString *query_uri; + gboolean params_started; + + g_return_val_if_fail (GDATA_IS_QUERY (self), NULL); + g_return_val_if_fail (feed_uri != NULL, NULL); + + /* Check to see if we're paginating first */ + if (self->priv->pagination_type == GDATA_QUERY_PAGINATION_URIS) { + if (self->priv->use_next_page) + return g_strdup (self->priv->next_uri); + if (self->priv->use_previous_page) + return g_strdup (self->priv->previous_uri); + } + + klass = GDATA_QUERY_GET_CLASS (self); + g_assert (klass->get_query_uri != NULL); + + /* Determine whether the first param has already been appended (e.g. it exists in the feed_uri) */ + params_started = (strstr (feed_uri, "?") != NULL) ? TRUE : FALSE; + + /* Build the query URI */ + query_uri = g_string_new (feed_uri); + klass->get_query_uri (self, feed_uri, query_uri, ¶ms_started); + + return g_string_free (query_uri, FALSE); +} + +/* Used internally by child classes of GDataQuery to add search clauses that represent service-specific + * query properties. For example, in the Drive v2 API, certain GDataDocumentsQuery properties like + * show-deleted and show-folders no longer have their own parameters, but have to be specified as a search + * clause in the query string. */ +void +_gdata_query_add_q_internal (GDataQuery *self, const gchar *q) +{ + GDataQueryPrivate *priv = self->priv; + GString *str; + + g_return_if_fail (GDATA_IS_QUERY (self)); + g_return_if_fail (q != NULL && q[0] != '\0'); + + str = g_string_new (priv->q_internal); + + /* Search parameters: https://developers.google.com/drive/web/search-parameters */ + if (str->len > 0) + g_string_append (str, " and "); + + g_string_append (str, q); + + g_free (priv->q_internal); + priv->q_internal = g_string_free (str, FALSE); +} + +/* Used internally by child classes of GDataQuery to clear the internal query string when building the + * query URI in GDataQueryClass->get_query_uri */ +void +_gdata_query_clear_q_internal (GDataQuery *self) +{ + GDataQueryPrivate *priv = self->priv; + + g_return_if_fail (GDATA_IS_QUERY (self)); + + g_free (priv->q_internal); + priv->q_internal = NULL; +} + +/** + * gdata_query_get_q: + * @self: a #GDataQuery + * + * Gets the #GDataQuery:q property. + * + * Return value: the q property, or %NULL if it is unset + */ +const gchar * +gdata_query_get_q (GDataQuery *self) +{ + g_return_val_if_fail (GDATA_IS_QUERY (self), NULL); + return self->priv->q; +} + +/** + * gdata_query_set_q: + * @self: a #GDataQuery + * @q: (allow-none): a new query string, or %NULL + * + * Sets the #GDataQuery:q property of the #GDataQuery to the new query string, @q. + * + * Set @q to %NULL to unset the property in the query URI. + */ +void +gdata_query_set_q (GDataQuery *self, const gchar *q) +{ + g_return_if_fail (GDATA_IS_QUERY (self)); + + g_free (self->priv->q); + self->priv->q = g_strdup (q); + g_object_notify (G_OBJECT (self), "q"); + + /* Our current ETag will no longer be relevant */ + gdata_query_set_etag (self, NULL); +} + +/** + * gdata_query_get_categories: + * @self: a #GDataQuery + * + * Gets the #GDataQuery:categories property. + * + * Return value: the categories property, or %NULL if it is unset + */ +const gchar * +gdata_query_get_categories (GDataQuery *self) +{ + g_return_val_if_fail (GDATA_IS_QUERY (self), NULL); + return self->priv->categories; +} + +/** + * gdata_query_set_categories: + * @self: a #GDataQuery + * @categories: (allow-none): the new category string, or %NULL + * + * Sets the #GDataQuery:categories property of the #GDataQuery to the new category string, @categories. + * + * Set @categories to %NULL to unset the property in the query URI. + */ +void +gdata_query_set_categories (GDataQuery *self, const gchar *categories) +{ + g_return_if_fail (GDATA_IS_QUERY (self)); + + g_free (self->priv->categories); + self->priv->categories = g_strdup (categories); + g_object_notify (G_OBJECT (self), "categories"); + + /* Our current ETag will no longer be relevant */ + gdata_query_set_etag (self, NULL); +} + +/** + * gdata_query_get_author: + * @self: a #GDataQuery + * + * Gets the #GDataQuery:author property. + * + * Return value: the author property, or %NULL if it is unset + */ +const gchar * +gdata_query_get_author (GDataQuery *self) +{ + g_return_val_if_fail (GDATA_IS_QUERY (self), NULL); + return self->priv->author; +} + +/** + * gdata_query_set_author: + * @self: a #GDataQuery + * @author: (allow-none): the new author string, or %NULL + * + * Sets the #GDataQuery:author property of the #GDataQuery to the new author string, @author. + * + * Set @author to %NULL to unset the property in the query URI. + */ +void +gdata_query_set_author (GDataQuery *self, const gchar *author) +{ + g_return_if_fail (GDATA_IS_QUERY (self)); + + g_free (self->priv->author); + self->priv->author = g_strdup (author); + g_object_notify (G_OBJECT (self), "author"); + + /* Our current ETag will no longer be relevant */ + gdata_query_set_etag (self, NULL); +} + +/** + * gdata_query_get_updated_min: + * @self: a #GDataQuery + * + * Gets the #GDataQuery:updated-min property. If the property is unset, <code class="literal">-1</code> will be returned. + * + * Return value: the updated-min property, or <code class="literal">-1</code> + */ +gint64 +gdata_query_get_updated_min (GDataQuery *self) +{ + g_return_val_if_fail (GDATA_IS_QUERY (self), -1); + return self->priv->updated_min; +} + +/** + * gdata_query_set_updated_min: + * @self: a #GDataQuery + * @updated_min: the new minimum update time, or <code class="literal">-1</code> + * + * Sets the #GDataQuery:updated-min property of the #GDataQuery to the new minimum update time, @updated_min. + * + * Set @updated_min to <code class="literal">-1</code> to unset the property in the query URI. + */ +void +gdata_query_set_updated_min (GDataQuery *self, gint64 updated_min) +{ + g_return_if_fail (GDATA_IS_QUERY (self)); + g_return_if_fail (updated_min >= -1); + + self->priv->updated_min = updated_min; + g_object_notify (G_OBJECT (self), "updated-min"); + + /* Our current ETag will no longer be relevant */ + gdata_query_set_etag (self, NULL); +} + +/** + * gdata_query_get_updated_max: + * @self: a #GDataQuery + * + * Gets the #GDataQuery:updated-max property. If the property is unset, <code class="literal">-1</code> will be returned. + * + * Return value: the updated-max property, or <code class="literal">-1</code> + */ +gint64 +gdata_query_get_updated_max (GDataQuery *self) +{ + g_return_val_if_fail (GDATA_IS_QUERY (self), -1); + return self->priv->updated_max; +} + +/** + * gdata_query_set_updated_max: + * @self: a #GDataQuery + * @updated_max: the new maximum update time, or <code class="literal">-1</code> + * + * Sets the #GDataQuery:updated-max property of the #GDataQuery to the new maximum update time, @updated_max. + * + * Set @updated_max to <code class="literal">-1</code> to unset the property in the query URI. + */ +void +gdata_query_set_updated_max (GDataQuery *self, gint64 updated_max) +{ + g_return_if_fail (GDATA_IS_QUERY (self)); + g_return_if_fail (updated_max >= -1); + + self->priv->updated_max = updated_max; + g_object_notify (G_OBJECT (self), "updated-max"); + + /* Our current ETag will no longer be relevant */ + gdata_query_set_etag (self, NULL); +} + +/** + * gdata_query_get_published_min: + * @self: a #GDataQuery + * + * Gets the #GDataQuery:published-min property. If the property is unset, <code class="literal">-1</code> will be returned. + * + * Return value: the published-min property, or <code class="literal">-1</code> + */ +gint64 +gdata_query_get_published_min (GDataQuery *self) +{ + g_return_val_if_fail (GDATA_IS_QUERY (self), -1); + return self->priv->published_min; +} + +/** + * gdata_query_set_published_min: + * @self: a #GDataQuery + * @published_min: the new minimum publish time, or <code class="literal">-1</code> + * + * Sets the #GDataQuery:published-min property of the #GDataQuery to the new minimum publish time, @published_min. + * + * Set @published_min to <code class="literal">-1</code> to unset the property in the query URI. + */ +void +gdata_query_set_published_min (GDataQuery *self, gint64 published_min) +{ + g_return_if_fail (GDATA_IS_QUERY (self)); + g_return_if_fail (published_min >= -1); + + self->priv->published_min = published_min; + g_object_notify (G_OBJECT (self), "published-min"); + + /* Our current ETag will no longer be relevant */ + gdata_query_set_etag (self, NULL); +} + +/** + * gdata_query_get_published_max: + * @self: a #GDataQuery + * + * Gets the #GDataQuery:published-max property. If the property is unset, <code class="literal">-1</code> will be returned. + * + * Return value: the published-max property, or <code class="literal">-1</code> + */ +gint64 +gdata_query_get_published_max (GDataQuery *self) +{ + g_return_val_if_fail (GDATA_IS_QUERY (self), -1); + return self->priv->published_max; +} + +/** + * gdata_query_set_published_max: + * @self: a #GDataQuery + * @published_max: the new maximum publish time, or <code class="literal">-1</code> + * + * Sets the #GDataQuery:published-max property of the #GDataQuery to the new maximum publish time, @published_max. + * + * Set @published_max to <code class="literal">-1</code> to unset the property in the query URI. + */ +void +gdata_query_set_published_max (GDataQuery *self, gint64 published_max) +{ + g_return_if_fail (GDATA_IS_QUERY (self)); + g_return_if_fail (published_max >= -1); + + self->priv->published_max = published_max; + g_object_notify (G_OBJECT (self), "published-max"); + + /* Our current ETag will no longer be relevant */ + gdata_query_set_etag (self, NULL); +} + +/** + * gdata_query_get_start_index: + * @self: a #GDataQuery + * + * Gets the #GDataQuery:start-index property. + * + * Return value: the start index property, or <code class="literal">0</code> if it is unset + */ +guint +gdata_query_get_start_index (GDataQuery *self) +{ + g_return_val_if_fail (GDATA_IS_QUERY (self), 0); + return self->priv->start_index; +} + +/** + * gdata_query_set_start_index: + * @self: a #GDataQuery + * @start_index: the new start index, or <code class="literal">0</code> + * + * Sets the #GDataQuery:start-index property of the #GDataQuery to the new one-based start index, @start_index. + * + * Set @start_index to <code class="literal">0</code> to unset the property in the query URI. + */ +void +gdata_query_set_start_index (GDataQuery *self, guint start_index) +{ + g_return_if_fail (GDATA_IS_QUERY (self)); + + self->priv->start_index = start_index; + g_object_notify (G_OBJECT (self), "start-index"); + + /* Our current ETag will no longer be relevant */ + gdata_query_set_etag (self, NULL); +} + +/** + * gdata_query_is_strict: + * @self: a #GDataQuery + * + * Gets the #GDataQuery:is-strict property. + * + * Return value: the strict property + * + * Since: 0.2.0 + */ +gboolean +gdata_query_is_strict (GDataQuery *self) +{ + g_return_val_if_fail (GDATA_IS_QUERY (self), FALSE); + return self->priv->is_strict; +} + +/** + * gdata_query_set_is_strict: + * @self: a #GDataQuery + * @is_strict: the new strict value + * + * Sets the #GDataQuery:is-strict property of the #GDataQuery to the new strict value, @is_strict. + * + * Since: 0.2.0 + */ +void +gdata_query_set_is_strict (GDataQuery *self, gboolean is_strict) +{ + g_return_if_fail (GDATA_IS_QUERY (self)); + + self->priv->is_strict = is_strict; + g_object_notify (G_OBJECT (self), "is-strict"); + + /* Our current ETag will no longer be relevant */ + gdata_query_set_etag (self, NULL); +} + +/** + * gdata_query_get_max_results: + * @self: a #GDataQuery + * + * Gets the #GDataQuery:max-results property. + * + * Return value: the maximum results property, or <code class="literal">0</code> if it is unset + */ +guint +gdata_query_get_max_results (GDataQuery *self) +{ + g_return_val_if_fail (GDATA_IS_QUERY (self), 0); + return self->priv->max_results; +} + +/** + * gdata_query_set_max_results: + * @self: a #GDataQuery + * @max_results: the new maximum results value, or <code class="literal">0</code> + * + * Sets the #GDataQuery:max-results property of the #GDataQuery to the new maximum results value, @max_results. + * + * Set @max_results to <code class="literal">0</code> to unset the property in the query URI. + */ +void +gdata_query_set_max_results (GDataQuery *self, guint max_results) +{ + g_return_if_fail (GDATA_IS_QUERY (self)); + + self->priv->max_results = max_results; + g_object_notify (G_OBJECT (self), "max-results"); + + /* Our current ETag will no longer be relevant */ + gdata_query_set_etag (self, NULL); +} + +/** + * gdata_query_get_etag: + * @self: a #GDataQuery + * + * Gets the #GDataQuery:etag property. + * + * Return value: the ETag property, or %NULL if it is unset + * + * Since: 0.2.0 + */ +const gchar * +gdata_query_get_etag (GDataQuery *self) +{ + g_return_val_if_fail (GDATA_IS_QUERY (self), NULL); + return self->priv->etag; +} + +/** + * gdata_query_set_etag: + * @self: a #GDataQuery + * @etag: (allow-none): the new ETag, or %NULL + * + * Sets the #GDataQuery:etag property of the #GDataQuery to the new ETag, @etag. + * + * Set @etag to %NULL to not check against the server-side ETag. + * + * Since: 0.2.0 + */ +void +gdata_query_set_etag (GDataQuery *self, const gchar *etag) +{ + g_return_if_fail (GDATA_IS_QUERY (self)); + + g_free (self->priv->etag); + self->priv->etag = g_strdup (etag); + g_object_notify (G_OBJECT (self), "etag"); +} + +void +_gdata_query_clear_pagination (GDataQuery *self) +{ + g_return_if_fail (GDATA_IS_QUERY (self)); + + switch (self->priv->pagination_type) { + case GDATA_QUERY_PAGINATION_INDEXED: + /* Nothing to do here: indexes can always be incremented. */ + break; + case GDATA_QUERY_PAGINATION_URIS: + g_clear_pointer (&self->priv->next_uri, g_free); + g_clear_pointer (&self->priv->previous_uri, g_free); + break; + case GDATA_QUERY_PAGINATION_TOKENS: + g_clear_pointer (&self->priv->next_page_token, g_free); + break; + default: + g_assert_not_reached (); + } + + self->priv->use_next_page = FALSE; + self->priv->use_previous_page = FALSE; +} + +void +_gdata_query_set_pagination_type (GDataQuery *self, + GDataQueryPaginationType type) +{ + g_debug ("%s: Pagination type set to %u", G_STRFUNC, type); + + _gdata_query_clear_pagination (self); + self->priv->pagination_type = type; +} + +void +_gdata_query_set_next_page_token (GDataQuery *self, + const gchar *next_page_token) +{ + g_return_if_fail (GDATA_IS_QUERY (self)); + g_return_if_fail (self->priv->pagination_type == + GDATA_QUERY_PAGINATION_TOKENS); + + g_free (self->priv->next_page_token); + self->priv->next_page_token = g_strdup (next_page_token); +} + +void +_gdata_query_set_next_uri (GDataQuery *self, const gchar *next_uri) +{ + g_return_if_fail (GDATA_IS_QUERY (self)); + g_return_if_fail (self->priv->pagination_type == + GDATA_QUERY_PAGINATION_URIS); + + g_free (self->priv->next_uri); + self->priv->next_uri = g_strdup (next_uri); +} + +gboolean +_gdata_query_is_finished (GDataQuery *self) +{ + g_return_val_if_fail (GDATA_IS_QUERY (self), FALSE); + + switch (self->priv->pagination_type) { + case GDATA_QUERY_PAGINATION_INDEXED: + return FALSE; + case GDATA_QUERY_PAGINATION_URIS: + return (self->priv->next_uri == NULL && self->priv->use_next_page); + case GDATA_QUERY_PAGINATION_TOKENS: + return (self->priv->next_page_token == NULL && self->priv->use_next_page); + default: + g_assert_not_reached (); + } +} + +void +_gdata_query_set_previous_uri (GDataQuery *self, const gchar *previous_uri) +{ + g_return_if_fail (GDATA_IS_QUERY (self)); + g_return_if_fail (self->priv->pagination_type == + GDATA_QUERY_PAGINATION_URIS); + + g_free (self->priv->previous_uri); + self->priv->previous_uri = g_strdup (previous_uri); +} + +/** + * gdata_query_next_page: + * @self: a #GDataQuery + * + * Changes the state of the #GDataQuery such that when gdata_query_get_query_uri() is next called, it will build the + * query URI for the next page in the result set. + * + * Ideally, the URI of the next page is retrieved from a feed automatically when gdata_service_query() is called, but + * gdata_query_next_page() will fall back to using #GDataQuery:start-index to emulate true pagination if this fails. + * + * You <emphasis>should not</emphasis> implement pagination manually using #GDataQuery:start-index. + */ +void +gdata_query_next_page (GDataQuery *self) +{ + GDataQueryPrivate *priv = self->priv; + + g_return_if_fail (GDATA_IS_QUERY (self)); + + switch (self->priv->pagination_type) { + case GDATA_QUERY_PAGINATION_INDEXED: + if (priv->start_index == 0) + priv->start_index++; + priv->start_index += priv->max_results; + break; + case GDATA_QUERY_PAGINATION_URIS: + case GDATA_QUERY_PAGINATION_TOKENS: + priv->use_next_page = TRUE; + priv->use_previous_page = FALSE; + break; + default: + g_assert_not_reached (); + } + + /* Our current ETag will no longer be relevant */ + gdata_query_set_etag (self, NULL); +} + +/** + * gdata_query_previous_page: + * @self: a #GDataQuery + * + * Changes the state of the #GDataQuery such that when gdata_query_get_query_uri() is next called, it will build the + * query URI for the previous page in the result set. + * + * See the documentation for gdata_query_next_page() for an explanation of how query URIs from the feeds are used to this end. + * + * Return value: %TRUE if there is a previous page and it has been switched to, %FALSE otherwise + */ +gboolean +gdata_query_previous_page (GDataQuery *self) +{ + GDataQueryPrivate *priv = self->priv; + gboolean retval; + + g_return_val_if_fail (GDATA_IS_QUERY (self), FALSE); + + switch (self->priv->pagination_type) { + case GDATA_QUERY_PAGINATION_INDEXED: + if (priv->start_index <= priv->max_results) { + retval = FALSE; + } else { + priv->start_index -= priv->max_results; + if (priv->start_index == 1) + priv->start_index--; + retval = TRUE; + } + break; + case GDATA_QUERY_PAGINATION_URIS: + if (priv->previous_uri != NULL) { + priv->use_next_page = FALSE; + priv->use_previous_page = TRUE; + retval = TRUE; + } else { + retval = FALSE; + } + break; + case GDATA_QUERY_PAGINATION_TOKENS: + /* There are no previous page tokens, unfortunately. */ + retval = FALSE; + break; + default: + g_assert_not_reached (); + } + + if (retval) { + /* Our current ETag will no longer be relevant */ + gdata_query_set_etag (self, NULL); + } + + return retval; +} diff --git a/gdata/gdata-query.h b/gdata/gdata-query.h new file mode 100644 index 0000000..f80cc8c --- /dev/null +++ b/gdata/gdata-query.h @@ -0,0 +1,102 @@ +/* -*- Mode: C; indent-tabs-mode: t; c-basic-offset: 8; tab-width: 8 -*- */ +/* + * GData Client + * Copyright (C) Philip Withnall 2009–2010 <philip@tecnocode.co.uk> + * + * GData Client is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * GData Client is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with GData Client. If not, see <http://www.gnu.org/licenses/>. + */ + +#ifndef GDATA_QUERY_H +#define GDATA_QUERY_H + +#include <glib.h> +#include <glib-object.h> + +G_BEGIN_DECLS + +#define GDATA_TYPE_QUERY (gdata_query_get_type ()) +#define GDATA_QUERY(o) (G_TYPE_CHECK_INSTANCE_CAST ((o), GDATA_TYPE_QUERY, GDataQuery)) +#define GDATA_QUERY_CLASS(k) (G_TYPE_CHECK_CLASS_CAST((k), GDATA_TYPE_QUERY, GDataQueryClass)) +#define GDATA_IS_QUERY(o) (G_TYPE_CHECK_INSTANCE_TYPE ((o), GDATA_TYPE_QUERY)) +#define GDATA_IS_QUERY_CLASS(k) (G_TYPE_CHECK_CLASS_TYPE ((k), GDATA_TYPE_QUERY)) +#define GDATA_QUERY_GET_CLASS(o) (G_TYPE_INSTANCE_GET_CLASS ((o), GDATA_TYPE_QUERY, GDataQueryClass)) + +typedef struct _GDataQueryPrivate GDataQueryPrivate; + +/** + * GDataQuery: + * + * All the fields in the #GDataQuery structure are private and should never be accessed directly. + */ +typedef struct { + GObject parent; + GDataQueryPrivate *priv; +} GDataQuery; + +/** + * GDataQueryClass: + * + * All the fields in the #GDataQueryClass structure are private and should never be accessed directly. + */ +typedef struct { + /*< private >*/ + GObjectClass parent; + + void (*get_query_uri) (GDataQuery *self, const gchar *feed_uri, GString *query_uri, gboolean *params_started); + + /*< private >*/ + /* Padding for future expansion */ + void (*_g_reserved0) (void); + void (*_g_reserved1) (void); + void (*_g_reserved2) (void); + void (*_g_reserved3) (void); + void (*_g_reserved4) (void); + void (*_g_reserved5) (void); +} GDataQueryClass; + +GType gdata_query_get_type (void) G_GNUC_CONST; + +GDataQuery *gdata_query_new (const gchar *q) G_GNUC_WARN_UNUSED_RESULT G_GNUC_MALLOC; +GDataQuery *gdata_query_new_with_limits (const gchar *q, guint start_index, guint max_results) G_GNUC_WARN_UNUSED_RESULT G_GNUC_MALLOC; + +gchar *gdata_query_get_query_uri (GDataQuery *self, const gchar *feed_uri) G_GNUC_WARN_UNUSED_RESULT G_GNUC_MALLOC; +void gdata_query_next_page (GDataQuery *self); +gboolean gdata_query_previous_page (GDataQuery *self); + +const gchar *gdata_query_get_q (GDataQuery *self) G_GNUC_PURE; +void gdata_query_set_q (GDataQuery *self, const gchar *q); +const gchar *gdata_query_get_categories (GDataQuery *self) G_GNUC_PURE; +void gdata_query_set_categories (GDataQuery *self, const gchar *categories); +const gchar *gdata_query_get_author (GDataQuery *self) G_GNUC_PURE; +void gdata_query_set_author (GDataQuery *self, const gchar *author); +gint64 gdata_query_get_updated_min (GDataQuery *self); +void gdata_query_set_updated_min (GDataQuery *self, gint64 updated_min); +gint64 gdata_query_get_updated_max (GDataQuery *self); +void gdata_query_set_updated_max (GDataQuery *self, gint64 updated_max); +gint64 gdata_query_get_published_min (GDataQuery *self); +void gdata_query_set_published_min (GDataQuery *self, gint64 published_min); +gint64 gdata_query_get_published_max (GDataQuery *self); +void gdata_query_set_published_max (GDataQuery *self, gint64 published_max); +guint gdata_query_get_start_index (GDataQuery *self) G_GNUC_PURE; +void gdata_query_set_start_index (GDataQuery *self, guint start_index); +gboolean gdata_query_is_strict (GDataQuery *self) G_GNUC_PURE; +void gdata_query_set_is_strict (GDataQuery *self, gboolean is_strict); +guint gdata_query_get_max_results (GDataQuery *self) G_GNUC_PURE; +void gdata_query_set_max_results (GDataQuery *self, guint max_results); +const gchar *gdata_query_get_etag (GDataQuery *self) G_GNUC_PURE; +void gdata_query_set_etag (GDataQuery *self, const gchar *etag); + +G_END_DECLS + +#endif /* !GDATA_QUERY_H */ diff --git a/gdata/gdata-service.c b/gdata/gdata-service.c new file mode 100644 index 0000000..3597b13 --- /dev/null +++ b/gdata/gdata-service.c @@ -0,0 +1,2499 @@ +/* -*- Mode: C; indent-tabs-mode: t; c-basic-offset: 8; tab-width: 8 -*- */ +/* + * GData Client + * Copyright (C) Philip Withnall 2008, 2009, 2010, 2014 <philip@tecnocode.co.uk> + * + * GData Client is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * GData Client is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with GData Client. If not, see <http://www.gnu.org/licenses/>. + */ + +/** + * SECTION:gdata-service + * @short_description: GData service object + * @stability: Stable + * @include: gdata/gdata-service.h + * + * #GDataService represents a GData API service, typically a website using the GData API, such as YouTube or Google Calendar. One + * #GDataService instance is required to issue queries to the service, handle insertions, updates and deletions, and generally + * communicate with the online service. + * + * If operations performed on a #GDataService need authorization (such as uploading a video to YouTube or querying the user's personal calendar on + * Google Calendar), the service needs a #GDataAuthorizer instance set as #GDataService:authorizer. Once the user is appropriately authenticated and + * authorized by the #GDataAuthorizer implementation (see the documentation for #GDataAuthorizer for details on how this is achieved for specific + * implementations), all operations will be automatically authorized. + * + * Note that it's not always necessary to supply a #GDataAuthorizer instance to a #GDataService. If the only operations to be performed on the + * #GDataService don't need authorization (e.g. they only query public information), setting up a #GDataAuthorizer is just extra overhead. See the + * documentation for the operations on individual #GDataService subclasses to see which need authorization and which don't. + */ + +#include <config.h> +#include <glib.h> +#include <glib/gi18n-lib.h> +#include <libsoup/soup.h> +#include <string.h> +#include <stdarg.h> + +#ifdef HAVE_GNOME +#define GCR_API_SUBJECT_TO_CHANGE +#include <gcr/gcr-base.h> +#endif /* HAVE_GNOME */ + +#include "gdata-service.h" +#include "gdata-private.h" +#include "gdata-client-login-authorizer.h" +#include "gdata-marshal.h" +#include "gdata-types.h" + +GQuark +gdata_service_error_quark (void) +{ + return g_quark_from_static_string ("gdata-service-error-quark"); +} + +static void gdata_service_dispose (GObject *object); +static void gdata_service_finalize (GObject *object); +static void gdata_service_get_property (GObject *object, guint property_id, GValue *value, GParamSpec *pspec); +static void gdata_service_set_property (GObject *object, guint property_id, const GValue *value, GParamSpec *pspec); +static void real_append_query_headers (GDataService *self, GDataAuthorizationDomain *domain, SoupMessage *message); +static void real_parse_error_response (GDataService *self, GDataOperationType operation_type, guint status, const gchar *reason_phrase, + const gchar *response_body, gint length, GError **error); +static GDataFeed * +real_parse_feed (GDataService *self, + GDataAuthorizationDomain *domain, + GDataQuery *query, + GType entry_type, + SoupMessage *message, + GCancellable *cancellable, + GDataQueryProgressCallback progress_callback, + gpointer progress_user_data, + GError **error); +static void notify_proxy_uri_cb (GObject *gobject, GParamSpec *pspec, GObject *self); +static void notify_timeout_cb (GObject *gobject, GParamSpec *pspec, GObject *self); +static void debug_handler (const char *log_domain, GLogLevelFlags log_level, const char *message, gpointer user_data); +static void soup_log_printer (SoupLogger *logger, SoupLoggerLogLevel level, char direction, const char *data, gpointer user_data); + +static GDataFeed *__gdata_service_query (GDataService *self, GDataAuthorizationDomain *domain, const gchar *feed_uri, GDataQuery *query, + GType entry_type, GCancellable *cancellable, GDataQueryProgressCallback progress_callback, + gpointer progress_user_data, GError **error); + +static SoupURI *_get_proxy_uri (GDataService *self); +static void _set_proxy_uri (GDataService *self, SoupURI *proxy_uri); + +struct _GDataServicePrivate { + SoupSession *session; + gchar *locale; + GDataAuthorizer *authorizer; + GProxyResolver *proxy_resolver; +}; + +enum { + PROP_PROXY_URI = 1, + PROP_TIMEOUT, + PROP_LOCALE, + PROP_AUTHORIZER, + PROP_PROXY_RESOLVER, +}; + +G_DEFINE_TYPE (GDataService, gdata_service, G_TYPE_OBJECT) + +static void +gdata_service_class_init (GDataServiceClass *klass) +{ + GObjectClass *gobject_class = G_OBJECT_CLASS (klass); + + g_type_class_add_private (klass, sizeof (GDataServicePrivate)); + + gobject_class->set_property = gdata_service_set_property; + gobject_class->get_property = gdata_service_get_property; + gobject_class->dispose = gdata_service_dispose; + gobject_class->finalize = gdata_service_finalize; + + klass->api_version = "2"; + klass->feed_type = GDATA_TYPE_FEED; + klass->append_query_headers = real_append_query_headers; + klass->parse_error_response = real_parse_error_response; + klass->parse_feed = real_parse_feed; + klass->get_authorization_domains = NULL; /* equivalent to returning an empty list of domains */ + + /** + * GDataService:proxy-uri: + * + * The proxy URI used internally for all network requests. + * + * Note that if a #GDataAuthorizer is being used with this #GDataService, the authorizer might also need its proxy URI setting. + * + * Since: 0.2.0 + * Deprecated: 0.15.0: Use #GDataService:proxy-resolver instead, which gives more flexibility over the proxy used. + */ + g_object_class_install_property (gobject_class, PROP_PROXY_URI, + g_param_spec_boxed ("proxy-uri", + "Proxy URI", "The proxy URI used internally for all network requests.", + SOUP_TYPE_URI, + G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)); + + /** + * GDataService:timeout: + * + * A timeout, in seconds, for network operations. If the timeout is exceeded, the operation will be cancelled and + * %GDATA_SERVICE_ERROR_NETWORK_ERROR will be returned. + * + * If the timeout is <code class="literal">0</code>, operations will never time out. + * + * Note that if a #GDataAuthorizer is being used with this #GDataService, the authorizer might also need its timeout setting. + * + * Since: 0.7.0 + */ + g_object_class_install_property (gobject_class, PROP_TIMEOUT, + g_param_spec_uint ("timeout", + "Timeout", "A timeout, in seconds, for network operations.", + 0, G_MAXUINT, 0, + G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)); + + /** + * GDataService:locale: + * + * The locale to use for network requests, in Unix locale format. (e.g. "en_GB", "cs", "de_DE".) Use %NULL for the default "C" locale + * (typically "en_US"). + * + * Typically, this locale will be used by the server-side software to localise results, such as by translating category names, or by choosing + * geographically relevant search results. This will vary from service to service. + * + * The server-side behaviour is undefined if it doesn't support a given locale. + * + * Since: 0.7.0 + */ + g_object_class_install_property (gobject_class, PROP_LOCALE, + g_param_spec_string ("locale", + "Locale", "The locale to use for network requests, in Unix locale format.", + NULL, + G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)); + + /** + * GDataService:authorizer: + * + * An object which implements #GDataAuthorizer. This should have previously been authenticated authorized against this service type (and + * potentially other service types). The service will use the authorizer to add an authorization token to each request it performs. + * + * Your application should call methods on the #GDataAuthorizer object itself in order to authenticate with the Google accounts service and + * authorize against this service type. See the documentation for the particular #GDataAuthorizer implementation being used for more details. + * + * The authorizer for a service can be changed at runtime for a different #GDataAuthorizer object or %NULL without affecting ongoing requests + * and operations. + * + * Note that it's only necessary to set an authorizer on the service if your application is going to make requests of the service which + * require authorization. For example, listing the current most popular videos on YouTube does not require authorization, but uploading a + * video to YouTube does. It's an unnecessary overhead to require the user to authorize against a service when not strictly required. + * + * Since: 0.9.0 + */ + g_object_class_install_property (gobject_class, PROP_AUTHORIZER, + g_param_spec_object ("authorizer", + "Authorizer", "An authorizer object to provide an authorization token for each request.", + GDATA_TYPE_AUTHORIZER, + G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)); + + /** + * GDataService:proxy-resolver: + * + * The #GProxyResolver used to determine a proxy URI. Setting this will clear the #GDataService:proxy-uri property. + * + * Since: 0.15.0 + */ + g_object_class_install_property (gobject_class, PROP_PROXY_RESOLVER, + g_param_spec_object ("proxy-resolver", + "Proxy Resolver", "A GProxyResolver used to determine a proxy URI.", + G_TYPE_PROXY_RESOLVER, + G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)); +} + +static void +gdata_service_init (GDataService *self) +{ + self->priv = G_TYPE_INSTANCE_GET_PRIVATE (self, GDATA_TYPE_SERVICE, GDataServicePrivate); + self->priv->session = _gdata_service_build_session (); + + /* Log handling for all message types except debug */ + g_log_set_handler (G_LOG_DOMAIN, G_LOG_LEVEL_CRITICAL | G_LOG_LEVEL_ERROR | G_LOG_LEVEL_INFO | G_LOG_LEVEL_MESSAGE | G_LOG_LEVEL_WARNING, (GLogFunc) debug_handler, self); + + /* Proxy the SoupSession's proxy-uri and timeout properties */ + g_signal_connect (self->priv->session, "notify::proxy-uri", (GCallback) notify_proxy_uri_cb, self); + g_signal_connect (self->priv->session, "notify::timeout", (GCallback) notify_timeout_cb, self); + + /* Keep our GProxyResolver synchronized with SoupSession's. */ + g_object_bind_property (self->priv->session, "proxy-resolver", self, "proxy-resolver", G_BINDING_BIDIRECTIONAL | G_BINDING_SYNC_CREATE); +} + +static void +gdata_service_dispose (GObject *object) +{ + GDataServicePrivate *priv = GDATA_SERVICE (object)->priv; + + if (priv->authorizer != NULL) + g_object_unref (priv->authorizer); + priv->authorizer = NULL; + + if (priv->session != NULL) + g_object_unref (priv->session); + priv->session = NULL; + + g_clear_object (&priv->proxy_resolver); + + /* Chain up to the parent class */ + G_OBJECT_CLASS (gdata_service_parent_class)->dispose (object); +} + +static void +gdata_service_finalize (GObject *object) +{ + GDataServicePrivate *priv = GDATA_SERVICE (object)->priv; + + g_free (priv->locale); + + /* Chain up to the parent class */ + G_OBJECT_CLASS (gdata_service_parent_class)->finalize (object); +} + +static void +gdata_service_get_property (GObject *object, guint property_id, GValue *value, GParamSpec *pspec) +{ + GDataServicePrivate *priv = GDATA_SERVICE (object)->priv; + + switch (property_id) { + case PROP_PROXY_URI: + g_value_set_boxed (value, _get_proxy_uri (GDATA_SERVICE (object))); + break; + case PROP_TIMEOUT: + g_value_set_uint (value, gdata_service_get_timeout (GDATA_SERVICE (object))); + break; + case PROP_LOCALE: + g_value_set_string (value, priv->locale); + break; + case PROP_AUTHORIZER: + g_value_set_object (value, priv->authorizer); + break; + case PROP_PROXY_RESOLVER: + g_value_set_object (value, priv->proxy_resolver); + break; + default: + /* We don't have any other property... */ + G_OBJECT_WARN_INVALID_PROPERTY_ID (object, property_id, pspec); + break; + } +} + +static void +gdata_service_set_property (GObject *object, guint property_id, const GValue *value, GParamSpec *pspec) +{ + switch (property_id) { + case PROP_PROXY_URI: + _set_proxy_uri (GDATA_SERVICE (object), g_value_get_boxed (value)); + break; + case PROP_TIMEOUT: + gdata_service_set_timeout (GDATA_SERVICE (object), g_value_get_uint (value)); + break; + case PROP_LOCALE: + gdata_service_set_locale (GDATA_SERVICE (object), g_value_get_string (value)); + break; + case PROP_AUTHORIZER: + gdata_service_set_authorizer (GDATA_SERVICE (object), g_value_get_object (value)); + break; + case PROP_PROXY_RESOLVER: + gdata_service_set_proxy_resolver (GDATA_SERVICE (object), g_value_get_object (value)); + break; + default: + /* We don't have any other property... */ + G_OBJECT_WARN_INVALID_PROPERTY_ID (object, property_id, pspec); + break; + } +} + +static void +real_append_query_headers (GDataService *self, GDataAuthorizationDomain *domain, SoupMessage *message) +{ + g_assert (message != NULL); + + /* Set the authorisation header */ + if (self->priv->authorizer != NULL) { + gdata_authorizer_process_request (self->priv->authorizer, domain, message); + + if (domain != NULL) { + /* Store the authorisation domain on the message so that we can access it again after refreshing authorisation if necessary. + * See _gdata_service_send_message(). */ + g_object_set_data_full (G_OBJECT (message), "gdata-authorization-domain", g_object_ref (domain), + (GDestroyNotify) g_object_unref); + } + } + + /* Set the GData-Version header to tell it we want to use the v2 API */ + soup_message_headers_append (message->request_headers, "GData-Version", GDATA_SERVICE_GET_CLASS (self)->api_version); + + /* Set the locale, if it's been set for the service */ + if (self->priv->locale != NULL) + soup_message_headers_append (message->request_headers, "Accept-Language", self->priv->locale); +} + +static void +real_parse_error_response (GDataService *self, GDataOperationType operation_type, guint status, const gchar *reason_phrase, + const gchar *response_body, gint length, GError **error) +{ + /* We prefer to include the @response_body in the error message, but if it's empty, fall back to the @reason_phrase */ + if (response_body == NULL || *response_body == '\0') + response_body = reason_phrase; + + /* See: http://code.google.com/apis/gdata/docs/2.0/reference.html#HTTPStatusCodes */ + switch (status) { + case SOUP_STATUS_CANT_RESOLVE: + case SOUP_STATUS_CANT_CONNECT: + case SOUP_STATUS_SSL_FAILED: + case SOUP_STATUS_IO_ERROR: + g_set_error (error, GDATA_SERVICE_ERROR, GDATA_SERVICE_ERROR_NETWORK_ERROR, + _("Cannot connect to the service’s server.")); + return; + case SOUP_STATUS_CANT_RESOLVE_PROXY: + case SOUP_STATUS_CANT_CONNECT_PROXY: + g_set_error (error, GDATA_SERVICE_ERROR, GDATA_SERVICE_ERROR_PROXY_ERROR, + _("Cannot connect to the proxy server.")); + return; + case SOUP_STATUS_MALFORMED: + case SOUP_STATUS_BAD_REQUEST: /* 400 */ + g_set_error (error, GDATA_SERVICE_ERROR, GDATA_SERVICE_ERROR_PROTOCOL_ERROR, + /* Translators: the parameter is an error message returned by the server. */ + _("Invalid request URI or header, or unsupported nonstandard parameter: %s"), response_body); + return; + case SOUP_STATUS_UNAUTHORIZED: /* 401 */ + case SOUP_STATUS_FORBIDDEN: /* 403 */ + g_set_error (error, GDATA_SERVICE_ERROR, GDATA_SERVICE_ERROR_AUTHENTICATION_REQUIRED, + /* Translators: the parameter is an error message returned by the server. */ + _("Authentication required: %s"), response_body); + return; + case SOUP_STATUS_NOT_FOUND: /* 404 */ + g_set_error (error, GDATA_SERVICE_ERROR, GDATA_SERVICE_ERROR_NOT_FOUND, + /* Translators: the parameter is an error message returned by the server. */ + _("The requested resource was not found: %s"), response_body); + return; + case SOUP_STATUS_CONFLICT: /* 409 */ + case SOUP_STATUS_PRECONDITION_FAILED: /* 412 */ + g_set_error (error, GDATA_SERVICE_ERROR, GDATA_SERVICE_ERROR_CONFLICT, + /* Translators: the parameter is an error message returned by the server. */ + _("The entry has been modified since it was downloaded: %s"), response_body); + return; + case SOUP_STATUS_INTERNAL_SERVER_ERROR: /* 500 */ + default: + /* We'll fall back to generic errors, below */ + break; + } + + /* If the error hasn't been handled already, throw a generic error */ + switch (operation_type) { + case GDATA_OPERATION_AUTHENTICATION: + g_set_error (error, GDATA_SERVICE_ERROR, GDATA_SERVICE_ERROR_PROTOCOL_ERROR, + /* Translators: the first parameter is an HTTP status, + * and the second is an error message returned by the server. */ + _("Error code %u when authenticating: %s"), status, response_body); + break; + case GDATA_OPERATION_QUERY: + g_set_error (error, GDATA_SERVICE_ERROR, GDATA_SERVICE_ERROR_PROTOCOL_ERROR, + /* Translators: the first parameter is an HTTP status, + * and the second is an error message returned by the server. */ + _("Error code %u when querying: %s"), status, response_body); + break; + case GDATA_OPERATION_INSERTION: + g_set_error (error, GDATA_SERVICE_ERROR, GDATA_SERVICE_ERROR_PROTOCOL_ERROR, + /* Translators: the first parameter is an HTTP status, + * and the second is an error message returned by the server. */ + _("Error code %u when inserting an entry: %s"), status, response_body); + break; + case GDATA_OPERATION_UPDATE: + g_set_error (error, GDATA_SERVICE_ERROR, GDATA_SERVICE_ERROR_PROTOCOL_ERROR, + /* Translators: the first parameter is an HTTP status, + * and the second is an error message returned by the server. */ + _("Error code %u when updating an entry: %s"), status, response_body); + break; + case GDATA_OPERATION_DELETION: + g_set_error (error, GDATA_SERVICE_ERROR, GDATA_SERVICE_ERROR_PROTOCOL_ERROR, + /* Translators: the first parameter is an HTTP status, + * and the second is an error message returned by the server. */ + _("Error code %u when deleting an entry: %s"), status, response_body); + break; + case GDATA_OPERATION_DOWNLOAD: + g_set_error (error, GDATA_SERVICE_ERROR, GDATA_SERVICE_ERROR_PROTOCOL_ERROR, + /* Translators: the first parameter is an HTTP status, + * and the second is an error message returned by the server. */ + _("Error code %u when downloading: %s"), status, response_body); + break; + case GDATA_OPERATION_UPLOAD: + g_set_error (error, GDATA_SERVICE_ERROR, GDATA_SERVICE_ERROR_PROTOCOL_ERROR, + /* Translators: the first parameter is an HTTP status, + * and the second is an error message returned by the server. */ + _("Error code %u when uploading: %s"), status, response_body); + break; + case GDATA_OPERATION_BATCH: + g_set_error (error, GDATA_SERVICE_ERROR, GDATA_SERVICE_ERROR_WITH_BATCH_OPERATION, + /* Translators: the first parameter is a HTTP status, + * and the second is an error message returned by the server. */ + _("Error code %u when running a batch operation: %s"), status, response_body); + break; + default: + /* We should not be called with anything other than the above operation types */ + g_assert_not_reached (); + } +} + +/** + * gdata_service_is_authorized: + * @self: a #GDataService + * + * Determines whether the service is authorized for all the #GDataAuthorizationDomains it belongs to (as returned by + * gdata_service_get_authorization_domains()). If the service's #GDataService:authorizer is %NULL, %FALSE is always returned. + * + * This is basically a convenience method for checking that the service's #GDataAuthorizer is authorized for all the service's + * #GDataAuthorizationDomains. + * + * Return value: %TRUE if the service is authorized for all its domains, %FALSE otherwise + * + * Since: 0.9.0 + */ +gboolean +gdata_service_is_authorized (GDataService *self) +{ + GList *domains, *i; + gboolean authorised = TRUE; + + g_return_val_if_fail (GDATA_IS_SERVICE (self), FALSE); + + /* If we don't have an authoriser set, we can't be authorised */ + if (self->priv->authorizer == NULL) { + return FALSE; + } + + domains = gdata_service_get_authorization_domains (G_OBJECT_TYPE (self)); + + /* Find any domains which we're not authorised for */ + for (i = domains; i != NULL; i = i->next) { + if (gdata_authorizer_is_authorized_for_domain (self->priv->authorizer, GDATA_AUTHORIZATION_DOMAIN (i->data)) == FALSE) { + authorised = FALSE; + break; + } + } + + g_list_free (domains); + + return authorised; +} + +/** + * gdata_service_get_authorizer: + * @self: a #GDataService + * + * Gets the #GDataAuthorizer object currently in use by the service. See the documentation for #GDataService:authorizer for more details. + * + * Return value: (transfer none): the authorizer object for this service, or %NULL + * + * Since: 0.9.0 + */ +GDataAuthorizer * +gdata_service_get_authorizer (GDataService *self) +{ + g_return_val_if_fail (GDATA_IS_SERVICE (self), NULL); + + return self->priv->authorizer; +} + +/** + * gdata_service_set_authorizer: + * @self: a #GDataService + * @authorizer: a new authorizer object for the service, or %NULL + * + * Sets #GDataService:authorizer to @authorizer. This may be %NULL if the service will only make requests in future which don't require authorization. + * See the documentation for #GDataService:authorizer for more information. + * + * Since: 0.9.0 + */ +void +gdata_service_set_authorizer (GDataService *self, GDataAuthorizer *authorizer) +{ + GDataServicePrivate *priv = self->priv; + + g_return_if_fail (GDATA_IS_SERVICE (self)); + g_return_if_fail (authorizer == NULL || GDATA_IS_AUTHORIZER (authorizer)); + + if (priv->authorizer != NULL) { + g_object_unref (priv->authorizer); + } + + priv->authorizer = authorizer; + + if (priv->authorizer != NULL) { + g_object_ref (priv->authorizer); + } + + g_object_notify (G_OBJECT (self), "authorizer"); +} + +/** + * gdata_service_get_authorization_domains: + * @service_type: the #GType of the #GDataService subclass to retrieve the authorization domains for + * + * Retrieves the full list of #GDataAuthorizationDomains which relate to the specified @service_type. All the + * #GDataAuthorizationDomains are unique and interned, so can be compared with other domains by simple pointer comparison. + * + * Note that in addition to this method, #GDataService subclasses may expose some or all of their authorization domains individually by means of + * individual accessor functions. + * + * Return value: (transfer container) (element-type GDataAuthorizationDomain): an unordered list of #GDataAuthorizationDomains; free with + * g_list_free() + * + * Since: 0.9.0 + */ +GList * +gdata_service_get_authorization_domains (GType service_type) +{ + GDataServiceClass *klass; + GList *domains = NULL; + + g_return_val_if_fail (g_type_is_a (service_type, GDATA_TYPE_SERVICE), NULL); + + klass = GDATA_SERVICE_CLASS (g_type_class_ref (service_type)); + if (klass->get_authorization_domains != NULL) { + domains = klass->get_authorization_domains (); + } + g_type_class_unref (klass); + + return domains; +} + +SoupMessage * +_gdata_service_build_message (GDataService *self, GDataAuthorizationDomain *domain, const gchar *method, const gchar *uri, + const gchar *etag, gboolean etag_if_match) +{ + SoupMessage *message; + GDataServiceClass *klass; + SoupURI *_uri; + + /* Create the message. Allow changing the HTTPS port just for testing, + * but require that the URI is always HTTPS for privacy. */ + _uri = soup_uri_new (uri); + soup_uri_set_port (_uri, _gdata_service_get_https_port ()); + g_assert_cmpstr (soup_uri_get_scheme (_uri), ==, SOUP_URI_SCHEME_HTTPS); + message = soup_message_new_from_uri (method, _uri); + soup_uri_free (_uri); + + /* Make sure subclasses set their headers */ + klass = GDATA_SERVICE_GET_CLASS (self); + if (klass->append_query_headers != NULL) + klass->append_query_headers (self, domain, message); + + /* Append the ETag header if possible */ + if (etag != NULL) + soup_message_headers_append (message->request_headers, (etag_if_match == TRUE) ? "If-Match" : "If-None-Match", etag); + + return message; +} + +typedef struct { + GMutex mutex; /* mutex to prevent cancellation before the message has been added to the session's message queue */ + SoupSession *session; + SoupMessage *message; +} MessageData; + +static void +message_cancel_cb (GCancellable *cancellable, MessageData *data) +{ + g_mutex_lock (&(data->mutex)); + soup_session_cancel_message (data->session, data->message, SOUP_STATUS_CANCELLED); + g_mutex_unlock (&(data->mutex)); +} + +static void +message_request_queued_cb (SoupSession *session, SoupMessage *message, MessageData *data) +{ + if (message == data->message) { + g_mutex_unlock (&(data->mutex)); + } +} + +/* Synchronously send @message via @service, handling asynchronous cancellation as best we can. If @cancellable has been cancelled before we start + * network activity, return without doing any network activity. Otherwise, if @cancellable is cancelled (from another thread) after network activity + * has started, we wait until the message has been queued by the session, then cancel the network activity and return as soon as possible. + * + * If cancellation has been handled, @error is guaranteed to be set to %G_IO_ERROR_CANCELLED. Otherwise, @error is guaranteed to be unset. */ +void +_gdata_service_actually_send_message (SoupSession *session, SoupMessage *message, GCancellable *cancellable, GError **error) +{ + MessageData data; + gulong cancel_signal = 0, request_queued_signal = 0; + + /* Hold references to the session and message so they can't be freed by other threads. For example, if the SoupSession was freed by another + * thread while we were making a request, the request would be unexpectedly cancelled. See bgo#650835 for an example of this breaking things. + */ + g_object_ref (session); + g_object_ref (message); + + /* Listen for cancellation */ + if (cancellable != NULL) { + g_mutex_init (&(data.mutex)); + data.session = session; + data.message = message; + + cancel_signal = g_cancellable_connect (cancellable, (GCallback) message_cancel_cb, &data, NULL); + request_queued_signal = g_signal_connect (session, "request-queued", (GCallback) message_request_queued_cb, &data); + + /* We lock this mutex until the message has been queued by the session (i.e. it's unlocked in the request-queued callback), and require + * the mutex to be held to cancel the message. Consequently, if the message is cancelled (in another thread) any time between this lock + * and the request being queued, the cancellation will wait until the request has been queued before taking effect. + * This is a little ugly, but is the only way I can think of to avoid a race condition between calling soup_session_cancel_message() + * and soup_session_send_message(), as the former doesn't have any effect until the request has been queued, and once the latter has + * returned, all network activity has been finished so cancellation is pointless. */ + g_mutex_lock (&(data.mutex)); + } + + /* Only send the message if it hasn't already been cancelled. There is no race condition here for the above reasons: if the cancellable has + * been cancelled, it's because it was cancelled before we called g_cancellable_connect(). + * + * Otherwise, manually set the message's status code to SOUP_STATUS_CANCELLED, as the message was cancelled before even being queued to be + * sent. */ + if (cancellable == NULL || g_cancellable_is_cancelled (cancellable) == FALSE) + soup_session_send_message (session, message); + else { + if (cancellable != NULL) { + g_mutex_unlock (&data.mutex); + } + + soup_message_set_status (message, SOUP_STATUS_CANCELLED); + } + + /* Clean up the cancellation code */ + if (cancellable != NULL) { + g_signal_handler_disconnect (session, request_queued_signal); + + if (cancel_signal != 0) + g_cancellable_disconnect (cancellable, cancel_signal); + + g_mutex_clear (&(data.mutex)); + } + + /* Set the cancellation error if applicable. We can't assume that our GCancellable has been cancelled just because the message has; + * libsoup may internally cancel messages if, for example, the proxy URI of the SoupSession is changed. + * libsoup also sometimes seems to return a SOUP_STATUS_IO_ERROR when we cancel a message, even though we've specified SOUP_STATUS_CANCELLED + * at cancellation time. Ho Hum. */ + g_assert (message->status_code != SOUP_STATUS_NONE); + + if (message->status_code == SOUP_STATUS_CANCELLED || + ((message->status_code == SOUP_STATUS_IO_ERROR || message->status_code == SOUP_STATUS_SSL_FAILED || + message->status_code == SOUP_STATUS_CANT_CONNECT || message->status_code == SOUP_STATUS_CANT_RESOLVE) && + cancellable != NULL && g_cancellable_is_cancelled (cancellable) == TRUE)) { + /* We hackily create and cancel a new GCancellable so that we can set the error using it and therefore save ourselves a translatable + * string and the associated maintenance. */ + GCancellable *error_cancellable = g_cancellable_new (); + g_cancellable_cancel (error_cancellable); + g_assert (g_cancellable_set_error_if_cancelled (error_cancellable, error) == TRUE); + g_object_unref (error_cancellable); + + /* As per the above comment, force the status to be SOUP_STATUS_CANCELLED. */ + soup_message_set_status (message, SOUP_STATUS_CANCELLED); + } + + /* Free things */ + g_object_unref (message); + g_object_unref (session); +} + +guint +_gdata_service_send_message (GDataService *self, SoupMessage *message, GCancellable *cancellable, GError **error) +{ + /* Based on code from evolution-data-server's libgdata: + * Ebby Wiselyn <ebbywiselyn@gmail.com> + * Jason Willis <zenbrother@gmail.com> + * + * Copyright (C) 1999-2008 Novell, Inc. (www.novell.com) + */ + + soup_message_set_flags (message, SOUP_MESSAGE_NO_REDIRECT); + _gdata_service_actually_send_message (self->priv->session, message, cancellable, error); + soup_message_set_flags (message, 0); + + /* Handle redirections specially so we don't lose our custom headers when making the second request */ + if (SOUP_STATUS_IS_REDIRECTION (message->status_code)) { + SoupURI *new_uri; + const gchar *new_location; + + new_location = soup_message_headers_get_one (message->response_headers, "Location"); + g_return_val_if_fail (new_location != NULL, SOUP_STATUS_NONE); + + new_uri = soup_uri_new_with_base (soup_message_get_uri (message), new_location); + if (new_uri == NULL) { + gchar *uri_string = soup_uri_to_string (new_uri, FALSE); + g_set_error (error, GDATA_SERVICE_ERROR, GDATA_SERVICE_ERROR_PROTOCOL_ERROR, + /* Translators: the parameter is the URI which is invalid. */ + _("Invalid redirect URI: %s"), uri_string); + g_free (uri_string); + return SOUP_STATUS_NONE; + } + + /* Allow overriding the URI for testing. */ + soup_uri_set_port (new_uri, _gdata_service_get_https_port ()); + + soup_message_set_uri (message, new_uri); + soup_uri_free (new_uri); + + /* Send the message again */ + _gdata_service_actually_send_message (self->priv->session, message, cancellable, error); + } + + /* Not authorised, or authorisation has expired. If we were authorised in the first place, attempt to refresh the authorisation and + * try sending the message again (but only once, so we don't get caught in an infinite loop of denied authorisation errors). + * + * Note that we have to re-process the message with the authoriser so that its authorisation headers get updated after the refresh + * (bgo#653535). */ + if (message->status_code == SOUP_STATUS_UNAUTHORIZED || + message->status_code == SOUP_STATUS_FORBIDDEN || + message->status_code == SOUP_STATUS_NOT_FOUND) { + GDataAuthorizer *authorizer = self->priv->authorizer; + + if (authorizer != NULL && gdata_authorizer_refresh_authorization (authorizer, cancellable, NULL) == TRUE) { + GDataAuthorizationDomain *domain; + + /* Re-process the request */ + domain = g_object_get_data (G_OBJECT (message), "gdata-authorization-domain"); + g_assert (domain == NULL || GDATA_IS_AUTHORIZATION_DOMAIN (domain)); + + gdata_authorizer_process_request (authorizer, domain, message); + + /* Send the message again */ + g_clear_error (error); + _gdata_service_actually_send_message (self->priv->session, message, cancellable, error); + } + } + + return message->status_code; +} + +typedef struct { + /* Input */ + GDataAuthorizationDomain *domain; + gchar *feed_uri; + GDataQuery *query; + GType entry_type; + + /* Output */ + GDataQueryProgressCallback progress_callback; + gpointer progress_user_data; + GDestroyNotify destroy_progress_user_data; +} QueryAsyncData; + +static void +query_async_data_free (QueryAsyncData *self) +{ + if (self->domain != NULL) + g_object_unref (self->domain); + + g_free (self->feed_uri); + if (self->query) + g_object_unref (self->query); + + g_slice_free (QueryAsyncData, self); +} + +static void +query_thread (GTask *task, gpointer source_object, gpointer task_data, GCancellable *cancellable) +{ + GDataService *service = GDATA_SERVICE (source_object); + g_autoptr(GError) error = NULL; + QueryAsyncData *data = task_data; + g_autoptr(GDataFeed) feed = NULL; + + /* Execute the query and return */ + feed = __gdata_service_query (service, data->domain, data->feed_uri, data->query, data->entry_type, cancellable, + data->progress_callback, data->progress_user_data, &error); + if (feed == NULL && error != NULL) + g_task_return_error (task, g_steal_pointer (&error)); + else + g_task_return_pointer (task, g_steal_pointer (&feed), g_object_unref); + + if (data->destroy_progress_user_data != NULL) { + data->destroy_progress_user_data (data->progress_user_data); + } +} + +/** + * gdata_service_query_async: + * @self: a #GDataService + * @domain: (allow-none): the #GDataAuthorizationDomain the query falls under, or %NULL + * @feed_uri: the feed URI to query, including the host name and protocol + * @query: (allow-none): a #GDataQuery with the query parameters, or %NULL + * @entry_type: a #GType for the #GDataEntrys to build from the XML + * @cancellable: (allow-none): optional #GCancellable object, or %NULL + * @progress_callback: (allow-none) (closure progress_user_data): a #GDataQueryProgressCallback to call when an entry is loaded, or %NULL + * @progress_user_data: (closure): data to pass to the @progress_callback function + * @destroy_progress_user_data: (allow-none): the function to call when @progress_callback will not be called any more, or %NULL. This function will be + * called with @progress_user_data as a parameter and can be used to free any memory allocated for it. + * @callback: a #GAsyncReadyCallback to call when the query is finished + * @user_data: (closure): data to pass to the @callback function + * + * Queries the service's @feed_uri feed to build a #GDataFeed. @self, @feed_uri and + * @query are all reffed/copied when this function is called, so can safely be freed after this function returns. + * + * For more details, see gdata_service_query(), which is the synchronous version of this function. + * + * When the operation is finished, @callback will be called. You can then call gdata_service_query_finish() + * to get the results of the operation. + * + * Since: 0.9.1 + */ +void +gdata_service_query_async (GDataService *self, GDataAuthorizationDomain *domain, const gchar *feed_uri, GDataQuery *query, GType entry_type, + GCancellable *cancellable, GDataQueryProgressCallback progress_callback, gpointer progress_user_data, + GDestroyNotify destroy_progress_user_data, GAsyncReadyCallback callback, gpointer user_data) +{ + g_autoptr(GTask) task = NULL; + QueryAsyncData *data; + + g_return_if_fail (GDATA_IS_SERVICE (self)); + g_return_if_fail (domain == NULL || GDATA_IS_AUTHORIZATION_DOMAIN (domain)); + g_return_if_fail (feed_uri != NULL); + g_return_if_fail (g_type_is_a (entry_type, GDATA_TYPE_ENTRY)); + g_return_if_fail (cancellable == NULL || G_IS_CANCELLABLE (cancellable)); + g_return_if_fail (callback != NULL); + + data = g_slice_new (QueryAsyncData); + data->domain = (domain != NULL) ? g_object_ref (domain) : NULL; + data->feed_uri = g_strdup (feed_uri); + data->query = (query != NULL) ? g_object_ref (query) : NULL; + data->entry_type = entry_type; + data->progress_callback = progress_callback; + data->progress_user_data = progress_user_data; + data->destroy_progress_user_data = destroy_progress_user_data; + + task = g_task_new (self, cancellable, callback, user_data); + g_task_set_source_tag (task, gdata_service_query_async); + g_task_set_task_data (task, g_steal_pointer (&data), (GDestroyNotify) query_async_data_free); + g_task_run_in_thread (task, query_thread); +} + +/** + * gdata_service_query_finish: + * @self: a #GDataService + * @async_result: a #GAsyncResult + * @error: a #GError, or %NULL + * + * Finishes an asynchronous query operation started with gdata_service_query_async(). + * + * Return value: (transfer full): a #GDataFeed of query results, or %NULL; unref with g_object_unref() + */ +GDataFeed * +gdata_service_query_finish (GDataService *self, GAsyncResult *async_result, GError **error) +{ + g_return_val_if_fail (GDATA_IS_SERVICE (self), NULL); + g_return_val_if_fail (G_IS_ASYNC_RESULT (async_result), NULL); + g_return_val_if_fail (error == NULL || *error == NULL, NULL); + g_return_val_if_fail (g_task_is_valid (async_result, self), NULL); + g_return_val_if_fail (g_async_result_is_tagged (async_result, gdata_service_query_async), NULL); + + return g_task_propagate_pointer (G_TASK (async_result), error); +} + +/* Does the bulk of the work of gdata_service_query. Split out because certain queries (such as that done by + * gdata_service_query_single_entry()) only return a single entry, and thus need special parsing code. */ +SoupMessage * +_gdata_service_query (GDataService *self, GDataAuthorizationDomain *domain, const gchar *feed_uri, GDataQuery *query, + GCancellable *cancellable, GError **error) +{ + SoupMessage *message; + guint status; + const gchar *etag = NULL; + + /* Append the ETag header if possible */ + if (query != NULL) + etag = gdata_query_get_etag (query); + + /* Build the message */ + if (query != NULL) { + gchar *query_uri = gdata_query_get_query_uri (query, feed_uri); + message = _gdata_service_build_message (self, domain, SOUP_METHOD_GET, query_uri, etag, FALSE); + g_free (query_uri); + } else { + message = _gdata_service_build_message (self, domain, SOUP_METHOD_GET, feed_uri, etag, FALSE); + } + + /* Note that cancellation only applies to network activity; not to the processing done afterwards */ + status = _gdata_service_send_message (self, message, cancellable, error); + + if (status == SOUP_STATUS_NOT_MODIFIED || status == SOUP_STATUS_CANCELLED) { + /* Not modified (ETag has worked), or cancelled (in which case the error has been set) */ + g_object_unref (message); + return NULL; + } else if (status != SOUP_STATUS_OK) { + /* Error */ + GDataServiceClass *klass = GDATA_SERVICE_GET_CLASS (self); + g_assert (klass->parse_error_response != NULL); + klass->parse_error_response (self, GDATA_OPERATION_QUERY, status, message->reason_phrase, message->response_body->data, + message->response_body->length, error); + g_object_unref (message); + return NULL; + } + + return message; +} + +static GDataFeed * +__gdata_service_query (GDataService *self, GDataAuthorizationDomain *domain, const gchar *feed_uri, GDataQuery *query, GType entry_type, + GCancellable *cancellable, GDataQueryProgressCallback progress_callback, gpointer progress_user_data, GError **error) +{ + GDataServiceClass *klass; + SoupMessage *message; + GDataFeed *feed; + + klass = GDATA_SERVICE_GET_CLASS (self); + + /* Are we off the end of the final page? */ + if (query != NULL && _gdata_query_is_finished (query)) { + GTimeVal updated; + + /* Build an empty dummy feed to signify the end of the list. */ + g_get_current_time (&updated); + return _gdata_feed_new (klass->feed_type, "Empty feed", "feed1", + updated.tv_sec); + } + + /* Send the request. */ + message = _gdata_service_query (self, domain, feed_uri, query, cancellable, error); + if (message == NULL) + return NULL; + + g_assert (message->response_body->data != NULL); + g_assert (klass->parse_feed != NULL); + + /* Parse the response. */ + feed = klass->parse_feed (self, domain, query, entry_type, + message, cancellable, progress_callback, + progress_user_data, error); + + g_object_unref (message); + + return feed; +} + +static GDataFeed * +real_parse_feed (GDataService *self, + GDataAuthorizationDomain *domain, + GDataQuery *query, + GType entry_type, + SoupMessage *message, + GCancellable *cancellable, + GDataQueryProgressCallback progress_callback, + gpointer progress_user_data, + GError **error) +{ + GDataServiceClass *klass; + GDataFeed *feed = NULL; + SoupMessageHeaders *headers; + const gchar *content_type; + + klass = GDATA_SERVICE_GET_CLASS (self); + headers = message->response_headers; + content_type = soup_message_headers_get_content_type (headers, NULL); + + if (content_type != NULL && strcmp (content_type, "application/json") == 0) { + /* Definitely JSON. */ + g_debug("JSON content type detected."); + feed = _gdata_feed_new_from_json (klass->feed_type, message->response_body->data, message->response_body->length, entry_type, + progress_callback, progress_user_data, error); + } else { + /* Potentially XML. Don't bother checking the Content-Type, since the parser + * will fail gracefully if the response body is not valid XML. */ + g_debug("XML content type detected."); + feed = _gdata_feed_new_from_xml (klass->feed_type, message->response_body->data, message->response_body->length, entry_type, + progress_callback, progress_user_data, error); + } + + /* Update the query with the feed's ETag */ + if (query != NULL && feed != NULL && gdata_feed_get_etag (feed) != NULL) + gdata_query_set_etag (query, gdata_feed_get_etag (feed)); + + /* Update the query with the next and previous URIs from the feed */ + if (query != NULL && feed != NULL) { + GDataLink *_link; + const gchar *token; + + _gdata_query_clear_pagination (query); + + /* Atom-style next and previous page links. */ + _link = gdata_feed_look_up_link (feed, "http://www.iana.org/assignments/relation/next"); + if (_link != NULL) + _gdata_query_set_next_uri (query, gdata_link_get_uri (_link)); + _link = gdata_feed_look_up_link (feed, "http://www.iana.org/assignments/relation/previous"); + if (_link != NULL) + _gdata_query_set_previous_uri (query, gdata_link_get_uri (_link)); + + /* JSON-style next page token. (There is no previous page + * token.) */ + token = gdata_feed_get_next_page_token (feed); + if (token != NULL) + _gdata_query_set_next_page_token (query, token); + } + + return feed; +} + +/** + * gdata_service_query: + * @self: a #GDataService + * @domain: (allow-none): the #GDataAuthorizationDomain the query falls under, or %NULL + * @feed_uri: the feed URI to query, including the host name and protocol + * @query: (allow-none): a #GDataQuery with the query parameters, or %NULL + * @entry_type: a #GType for the #GDataEntrys to build from the XML + * @cancellable: (allow-none): optional #GCancellable object, or %NULL + * @progress_callback: (allow-none) (scope call) (closure progress_user_data): a #GDataQueryProgressCallback to call when an entry is loaded, or %NULL + * @progress_user_data: (closure): data to pass to the @progress_callback function + * @error: a #GError, or %NULL + * + * Queries the service's @feed_uri feed to build a #GDataFeed. + * + * If @cancellable is not %NULL, then the operation can be cancelled by triggering the @cancellable object from another thread. + * If the operation was cancelled before or during network activity, the error %G_IO_ERROR_CANCELLED will be returned. Cancellation has no effect + * after network activity has finished, however, and the query will return successfully (or return an error sent by the server) if it is first + * cancelled after network activity has finished. See the <link linkend="cancellable-support">overview of cancellation</link> for + * more details. + * + * A %GDATA_SERVICE_ERROR_PROTOCOL_ERROR will be returned if the server indicates there is a problem with the query, but subclasses may override + * this and return their own errors. See their documentation for more details. + * + * For each entry in the response feed, @progress_callback will be called in the main thread. If there was an error parsing the XML response, + * a #GDataParserError will be returned. + * + * If the query is successful and the feed supports pagination, @query will be updated with the pagination URIs, and the next or previous page + * can then be loaded by calling gdata_query_next_page() or gdata_query_previous_page() before running the query again. + * + * If the #GDataQuery's ETag is set and it finds a match on the server, %NULL will be returned, but @error will remain unset. Otherwise, + * @query's ETag will be updated with the ETag from the returned feed, if available. + * + * Return value: (transfer full): a #GDataFeed of query results, or %NULL; unref with g_object_unref() + * + * Since: 0.9.0 + */ +GDataFeed * +gdata_service_query (GDataService *self, GDataAuthorizationDomain *domain, const gchar *feed_uri, GDataQuery *query, GType entry_type, + GCancellable *cancellable, GDataQueryProgressCallback progress_callback, gpointer progress_user_data, GError **error) +{ + g_return_val_if_fail (GDATA_IS_SERVICE (self), NULL); + g_return_val_if_fail (domain == NULL || GDATA_IS_AUTHORIZATION_DOMAIN (domain), NULL); + g_return_val_if_fail (feed_uri != NULL, NULL); + g_return_val_if_fail (g_type_is_a (entry_type, GDATA_TYPE_ENTRY), NULL); + g_return_val_if_fail (cancellable == NULL || G_IS_CANCELLABLE (cancellable), FALSE); + g_return_val_if_fail (error == NULL || *error == NULL, FALSE); + + return __gdata_service_query (self, domain, feed_uri, query, entry_type, cancellable, progress_callback, progress_user_data, error); +} + +/** + * gdata_service_query_single_entry: + * @self: a #GDataService + * @domain: (allow-none): the #GDataAuthorizationDomain the query falls under, or %NULL + * @entry_id: the entry ID of the desired entry + * @query: (allow-none): a #GDataQuery with the query parameters, or %NULL + * @entry_type: a #GType for the #GDataEntry to build from the XML + * @cancellable: (allow-none): a #GCancellable, or %NULL + * @error: a #GError, or %NULL + * + * Retrieves information about the single entry with the given @entry_id. @entry_id should be as returned by + * gdata_entry_get_id(). + * + * Parameters and errors are as for gdata_service_query(). Most of the properties of @query aren't relevant, and + * will cause a server-side error if used. The most useful property to use is #GDataQuery:etag, which will cause the + * server to not return anything if the entry hasn't been modified since it was given the specified ETag; thus saving + * bandwidth. If the server does not return anything for this reason, gdata_service_query_single_entry() will return + * %NULL, but will not set an error in @error. + * + * Return value: (transfer full): a #GDataEntry, or %NULL; unref with g_object_unref() + * + * Since: 0.9.0 + */ +GDataEntry * +gdata_service_query_single_entry (GDataService *self, GDataAuthorizationDomain *domain, const gchar *entry_id, GDataQuery *query, GType entry_type, + GCancellable *cancellable, GError **error) +{ + GDataEntryClass *klass; + GDataEntry *entry; + gchar *entry_uri; + SoupMessage *message; + SoupMessageHeaders *headers; + const gchar *content_type; + + g_return_val_if_fail (GDATA_IS_SERVICE (self), NULL); + g_return_val_if_fail (domain == NULL || GDATA_IS_AUTHORIZATION_DOMAIN (domain), NULL); + g_return_val_if_fail (entry_id != NULL, NULL); + g_return_val_if_fail (query == NULL || GDATA_IS_QUERY (query), NULL); + g_return_val_if_fail (g_type_is_a (entry_type, GDATA_TYPE_ENTRY) == TRUE, NULL); + g_return_val_if_fail (cancellable == NULL || G_IS_CANCELLABLE (cancellable), NULL); + g_return_val_if_fail (error == NULL || *error == NULL, NULL); + + /* Query for just the specified entry */ + klass = GDATA_ENTRY_CLASS (g_type_class_ref (entry_type)); + g_assert (klass->get_entry_uri != NULL); + + entry_uri = klass->get_entry_uri (entry_id); + message = _gdata_service_query (GDATA_SERVICE (self), domain, entry_uri, query, cancellable, error); + g_free (entry_uri); + + if (message == NULL) { + g_type_class_unref (klass); + return NULL; + } + + g_assert (message->response_body->data != NULL); + + headers = message->response_headers; + content_type = soup_message_headers_get_content_type (headers, NULL); + + if (g_strcmp0 (content_type, "application/json") == 0) { + entry = GDATA_ENTRY (gdata_parsable_new_from_json (entry_type, message->response_body->data, message->response_body->length, error)); + } else { + entry = GDATA_ENTRY (gdata_parsable_new_from_xml (entry_type, message->response_body->data, message->response_body->length, error)); + } + + g_object_unref (message); + g_type_class_unref (klass); + + return entry; +} + +typedef struct { + GDataAuthorizationDomain *domain; + gchar *entry_id; + GDataQuery *query; + GType entry_type; +} QuerySingleEntryAsyncData; + +static void +query_single_entry_async_data_free (QuerySingleEntryAsyncData *data) +{ + if (data->domain != NULL) + g_object_unref (data->domain); + + g_free (data->entry_id); + if (data->query != NULL) + g_object_unref (data->query); + g_slice_free (QuerySingleEntryAsyncData, data); +} + +static void +query_single_entry_thread (GTask *task, gpointer source_object, gpointer task_data, GCancellable *cancellable) +{ + GDataService *service = GDATA_SERVICE (source_object); + g_autoptr(GDataEntry) entry = NULL; + g_autoptr(GError) error = NULL; + QuerySingleEntryAsyncData *data = task_data; + + /* Execute the query and return */ + entry = gdata_service_query_single_entry (service, data->domain, data->entry_id, data->query, data->entry_type, cancellable, &error); + if (entry == NULL && error != NULL) + g_task_return_error (task, g_steal_pointer (&error)); + else + g_task_return_pointer (task, g_steal_pointer (&entry), g_object_unref); +} + +/** + * gdata_service_query_single_entry_async: + * @self: a #GDataService + * @domain: (allow-none): the #GDataAuthorizationDomain the query falls under, or %NULL + * @entry_id: the entry ID of the desired entry + * @query: (allow-none): a #GDataQuery with the query parameters, or %NULL + * @entry_type: a #GType for the #GDataEntry to build from the XML + * @cancellable: (allow-none): optional #GCancellable object, or %NULL + * @callback: a #GAsyncReadyCallback to call when the query is finished + * @user_data: (closure): data to pass to the @callback function + * + * Retrieves information about the single entry with the given @entry_id. @entry_id should be as returned by + * gdata_entry_get_id(). @self, @query and @entry_id are reffed/copied when this + * function is called, so can safely be freed after this function returns. + * + * For more details, see gdata_service_query_single_entry(), which is the synchronous version of this function. + * + * When the operation is finished, @callback will be called. You can then call gdata_service_query_single_entry_finish() + * to get the results of the operation. + * + * Since: 0.9.0 + */ +void +gdata_service_query_single_entry_async (GDataService *self, GDataAuthorizationDomain *domain, const gchar *entry_id, GDataQuery *query, + GType entry_type, GCancellable *cancellable, GAsyncReadyCallback callback, gpointer user_data) +{ + g_autoptr(GTask) task = NULL; + QuerySingleEntryAsyncData *data; + + g_return_if_fail (GDATA_IS_SERVICE (self)); + g_return_if_fail (domain == NULL || GDATA_IS_AUTHORIZATION_DOMAIN (domain)); + g_return_if_fail (entry_id != NULL); + g_return_if_fail (query == NULL || GDATA_IS_QUERY (query)); + g_return_if_fail (g_type_is_a (entry_type, GDATA_TYPE_ENTRY) == TRUE); + g_return_if_fail (cancellable == NULL || G_IS_CANCELLABLE (cancellable)); + g_return_if_fail (callback != NULL); + + data = g_slice_new (QuerySingleEntryAsyncData); + data->domain = (domain != NULL) ? g_object_ref (domain) : NULL; + data->query = (query != NULL) ? g_object_ref (query) : NULL; + data->entry_id = g_strdup (entry_id); + data->entry_type = entry_type; + + task = g_task_new (self, cancellable, callback, user_data); + g_task_set_source_tag (task, gdata_service_query_single_entry_async); + g_task_set_task_data (task, g_steal_pointer (&data), (GDestroyNotify) query_single_entry_async_data_free); + g_task_run_in_thread (task, query_single_entry_thread); +} + +/** + * gdata_service_query_single_entry_finish: + * @self: a #GDataService + * @async_result: a #GAsyncResult + * @error: a #GError, or %NULL + * + * Finishes an asynchronous query operation for a single entry, as started with gdata_service_query_single_entry_async(). + * + * Return value: (transfer full): a #GDataEntry, or %NULL; unref with g_object_unref() + * + * Since: 0.7.0 + */ +GDataEntry * +gdata_service_query_single_entry_finish (GDataService *self, GAsyncResult *async_result, GError **error) +{ + g_return_val_if_fail (GDATA_IS_SERVICE (self), NULL); + g_return_val_if_fail (G_IS_ASYNC_RESULT (async_result), NULL); + g_return_val_if_fail (error == NULL || *error == NULL, NULL); + g_return_val_if_fail (g_task_is_valid (async_result, self), NULL); + g_return_val_if_fail (g_async_result_is_tagged (async_result, gdata_service_query_single_entry_async), NULL); + + return g_task_propagate_pointer (G_TASK (async_result), error); +} + +typedef struct { + GDataAuthorizationDomain *domain; + gchar *upload_uri; + GDataEntry *entry; +} InsertEntryAsyncData; + +static void +insert_entry_async_data_free (InsertEntryAsyncData *self) +{ + if (self->domain != NULL) + g_object_unref (self->domain); + + g_free (self->upload_uri); + if (self->entry) + g_object_unref (self->entry); + + g_slice_free (InsertEntryAsyncData, self); +} + +static void +insert_entry_thread (GTask *task, gpointer source_object, gpointer task_data, GCancellable *cancellable) +{ + GDataService *service = GDATA_SERVICE (source_object); + g_autoptr(GDataEntry) updated_entry = NULL; + g_autoptr(GError) error = NULL; + InsertEntryAsyncData *data = task_data; + + /* Insert the entry and return */ + updated_entry = gdata_service_insert_entry (service, data->domain, data->upload_uri, data->entry, cancellable, &error); + if (updated_entry == NULL) + g_task_return_error (task, g_steal_pointer (&error)); + else + g_task_return_pointer (task, g_steal_pointer (&updated_entry), g_object_unref); +} + +/** + * gdata_service_insert_entry_async: + * @self: a #GDataService + * @domain: (allow-none): the #GDataAuthorizationDomain the insertion operation falls under, or %NULL + * @upload_uri: the URI to which the upload should be sent + * @entry: the #GDataEntry to insert + * @cancellable: (allow-none): optional #GCancellable object, or %NULL + * @callback: a #GAsyncReadyCallback to call when insertion is finished, or %NULL + * @user_data: (closure): data to pass to the @callback function + * + * Inserts @entry by uploading it to the online service at @upload_uri. @self, @upload_uri and + * @entry are all reffed/copied when this function is called, so can safely be freed after this function returns. + * + * For more details, see gdata_service_insert_entry(), which is the synchronous version of this function. + * + * When the operation is finished, @callback will be called. You can then call gdata_service_insert_entry_finish() + * to get the results of the operation. + * + * Since: 0.9.0 + */ +void +gdata_service_insert_entry_async (GDataService *self, GDataAuthorizationDomain *domain, const gchar *upload_uri, GDataEntry *entry, + GCancellable *cancellable, GAsyncReadyCallback callback, gpointer user_data) +{ + g_autoptr(GTask) task = NULL; + InsertEntryAsyncData *data; + + g_return_if_fail (GDATA_IS_SERVICE (self)); + g_return_if_fail (domain == NULL || GDATA_IS_AUTHORIZATION_DOMAIN (domain)); + g_return_if_fail (upload_uri != NULL); + g_return_if_fail (GDATA_IS_ENTRY (entry)); + g_return_if_fail (cancellable == NULL || G_IS_CANCELLABLE (cancellable)); + + data = g_slice_new (InsertEntryAsyncData); + data->domain = (domain != NULL) ? g_object_ref (domain) : NULL; + data->upload_uri = g_strdup (upload_uri); + data->entry = g_object_ref (entry); + + task = g_task_new (self, cancellable, callback, user_data); + g_task_set_source_tag (task, gdata_service_insert_entry_async); + g_task_set_task_data (task, g_steal_pointer (&data), (GDestroyNotify) insert_entry_async_data_free); + g_task_run_in_thread (task, insert_entry_thread); +} + +/** + * gdata_service_insert_entry_finish: + * @self: a #GDataService + * @async_result: a #GAsyncResult + * @error: a #GError, or %NULL + * + * Finishes an asynchronous entry insertion operation started with gdata_service_insert_entry_async(). + * + * Return value: (transfer full): an updated #GDataEntry, or %NULL; unref with g_object_unref() + * + * Since: 0.3.0 + */ +GDataEntry * +gdata_service_insert_entry_finish (GDataService *self, GAsyncResult *async_result, GError **error) +{ + g_return_val_if_fail (GDATA_IS_SERVICE (self), NULL); + g_return_val_if_fail (G_IS_ASYNC_RESULT (async_result), NULL); + g_return_val_if_fail (error == NULL || *error == NULL, NULL); + g_return_val_if_fail (g_task_is_valid (async_result, self), NULL); + g_return_val_if_fail (g_async_result_is_tagged (async_result, gdata_service_insert_entry_async), NULL); + + return g_task_propagate_pointer (G_TASK (async_result), error); +} + +/** + * gdata_service_insert_entry: + * @self: a #GDataService + * @domain: (allow-none): the #GDataAuthorizationDomain the insertion operation falls under, or %NULL + * @upload_uri: the URI to which the upload should be sent + * @entry: the #GDataEntry to insert + * @cancellable: (allow-none): optional #GCancellable object, or %NULL + * @error: a #GError, or %NULL + * + * Inserts @entry by uploading it to the online service at @upload_uri. For more information about the concept of inserting entries, see + * the <ulink type="http" url="http://code.google.com/apis/gdata/docs/2.0/basics.html#InsertingEntry">online documentation</ulink> for the GData + * protocol. + * + * The service will return an updated version of the entry, which is the return value of this function on success. + * + * If @cancellable is not %NULL, then the operation can be cancelled by triggering the @cancellable object from another thread. + * If the operation was cancelled before or during network activity, the error %G_IO_ERROR_CANCELLED will be returned. Cancellation has no effect + * after network activity has finished, however, and the insertion will return successfully (or return an error sent by the server) if it is first + * cancelled after network activity has finished. See the <link linkend="cancellable-support">overview of cancellation</link> for + * more details. + * + * If the entry is marked as already having been inserted a %GDATA_SERVICE_ERROR_ENTRY_ALREADY_INSERTED error will be returned immediately + * (there will be no network requests). + * + * If there is an error inserting the entry, a %GDATA_SERVICE_ERROR_PROTOCOL_ERROR error will be returned. Currently, subclasses + * <emphasis>cannot</emphasis> cannot override this or provide more specific errors. + * + * Return value: (transfer full): an updated #GDataEntry, or %NULL; unref with g_object_unref() + * + * Since: 0.9.0 + */ +GDataEntry * +gdata_service_insert_entry (GDataService *self, GDataAuthorizationDomain *domain, const gchar *upload_uri, GDataEntry *entry, + GCancellable *cancellable, GError **error) +{ + GDataEntry *updated_entry; + SoupMessage *message; + gchar *upload_data; + guint status; + GDataParsableClass *klass; + + g_return_val_if_fail (GDATA_IS_SERVICE (self), NULL); + g_return_val_if_fail (domain == NULL || GDATA_IS_AUTHORIZATION_DOMAIN (domain), NULL); + g_return_val_if_fail (upload_uri != NULL, NULL); + g_return_val_if_fail (GDATA_IS_ENTRY (entry), NULL); + g_return_val_if_fail (cancellable == NULL || G_IS_CANCELLABLE (cancellable), FALSE); + g_return_val_if_fail (error == NULL || *error == NULL, FALSE); + + if (gdata_entry_is_inserted (entry) == TRUE) { + g_set_error_literal (error, GDATA_SERVICE_ERROR, GDATA_SERVICE_ERROR_ENTRY_ALREADY_INSERTED, + _("The entry has already been inserted.")); + return NULL; + } + + message = _gdata_service_build_message (self, domain, SOUP_METHOD_POST, upload_uri, NULL, FALSE); + + /* Append the data */ + klass = GDATA_PARSABLE_GET_CLASS (entry); + g_assert (klass->get_content_type != NULL); + if (g_strcmp0 (klass->get_content_type (), "application/json") == 0) { + upload_data = gdata_parsable_get_json (GDATA_PARSABLE (entry)); + soup_message_set_request (message, "application/json", SOUP_MEMORY_TAKE, upload_data, strlen (upload_data)); + } else { + upload_data = gdata_parsable_get_xml (GDATA_PARSABLE (entry)); + soup_message_set_request (message, "application/atom+xml", SOUP_MEMORY_TAKE, upload_data, strlen (upload_data)); + } + + /* Send the message */ + status = _gdata_service_send_message (self, message, cancellable, error); + + if (status == SOUP_STATUS_NONE || status == SOUP_STATUS_CANCELLED) { + /* Redirect error or cancelled */ + g_object_unref (message); + return NULL; + } else if (status != SOUP_STATUS_CREATED && status != SOUP_STATUS_OK) { + /* Error: for XML APIs Google returns CREATED and for JSON it returns OK. */ + GDataServiceClass *service_klass = GDATA_SERVICE_GET_CLASS (self); + g_assert (service_klass->parse_error_response != NULL); + service_klass->parse_error_response (self, GDATA_OPERATION_INSERTION, status, message->reason_phrase, message->response_body->data, + message->response_body->length, error); + g_object_unref (message); + return NULL; + } + + /* Parse the XML or JSON according to GDataEntry type; create and return a new GDataEntry of the same type as @entry */ + g_assert (message->response_body->data != NULL); + if (g_strcmp0 (klass->get_content_type (), "application/json") == 0) { + updated_entry = GDATA_ENTRY (gdata_parsable_new_from_json (G_OBJECT_TYPE (entry), message->response_body->data, + message->response_body->length, error)); + } else { + updated_entry = GDATA_ENTRY (gdata_parsable_new_from_xml (G_OBJECT_TYPE (entry), message->response_body->data, + message->response_body->length, error)); + } + g_object_unref (message); + + return updated_entry; +} + +typedef struct { + GDataAuthorizationDomain *domain; + GDataEntry *entry; +} UpdateEntryAsyncData; + +static void +update_entry_async_data_free (UpdateEntryAsyncData *data) +{ + if (data->domain != NULL) + g_object_unref (data->domain); + + if (data->entry != NULL) + g_object_unref (data->entry); + + g_slice_free (UpdateEntryAsyncData, data); +} + +static void +update_entry_thread (GTask *task, gpointer source_object, gpointer task_data, GCancellable *cancellable) +{ + GDataService *service = GDATA_SERVICE (source_object); + g_autoptr(GDataEntry) updated_entry = NULL; + g_autoptr(GError) error = NULL; + UpdateEntryAsyncData *data = task_data; + + /* Update the entry and return */ + updated_entry = gdata_service_update_entry (service, data->domain, data->entry, cancellable, &error); + if (updated_entry == NULL) + g_task_return_error (task, g_steal_pointer (&error)); + else + g_task_return_pointer (task, g_steal_pointer (&updated_entry), g_object_unref); +} + +/** + * gdata_service_update_entry_async: + * @self: a #GDataService + * @domain: (allow-none): the #GDataAuthorizationDomain the update operation falls under, or %NULL + * @entry: the #GDataEntry to update + * @cancellable: (allow-none): optional #GCancellable object, or %NULL + * @callback: a #GAsyncReadyCallback to call when the update is finished, or %NULL + * @user_data: (closure): data to pass to the @callback function + * + * Updates @entry by PUTting it to its <literal>edit</literal> link's URI. @self and + * @entry are both reffed when this function is called, so can safely be unreffed after this function returns. + * + * For more details, see gdata_service_update_entry(), which is the synchronous version of this function. + * + * When the operation is finished, @callback will be called. You can then call gdata_service_update_entry_finish() + * to get the results of the operation. + * + * Since: 0.9.0 + */ +void +gdata_service_update_entry_async (GDataService *self, GDataAuthorizationDomain *domain, GDataEntry *entry, + GCancellable *cancellable, GAsyncReadyCallback callback, gpointer user_data) +{ + g_autoptr(GTask) task = NULL; + UpdateEntryAsyncData *data; + + g_return_if_fail (GDATA_IS_SERVICE (self)); + g_return_if_fail (domain == NULL || GDATA_IS_AUTHORIZATION_DOMAIN (domain)); + g_return_if_fail (GDATA_IS_ENTRY (entry)); + g_return_if_fail (cancellable == NULL || G_IS_CANCELLABLE (cancellable)); + + data = g_slice_new (UpdateEntryAsyncData); + data->domain = (domain != NULL) ? g_object_ref (domain) : NULL; + data->entry = g_object_ref (entry); + + task = g_task_new (task, cancellable, callback, user_data); + g_task_set_source_tag (task, gdata_service_update_entry_async); + g_task_set_task_data (task, g_steal_pointer (&data), (GDestroyNotify) update_entry_async_data_free); + g_task_run_in_thread (task, update_entry_thread); +} + +/** + * gdata_service_update_entry_finish: + * @self: a #GDataService + * @async_result: a #GAsyncResult + * @error: a #GError, or %NULL + * + * Finishes an asynchronous entry update operation started with gdata_service_update_entry_async(). + * + * Return value: (transfer full): an updated #GDataEntry, or %NULL; unref with g_object_unref() + * + * Since: 0.3.0 + */ +GDataEntry * +gdata_service_update_entry_finish (GDataService *self, GAsyncResult *async_result, GError **error) +{ + g_return_val_if_fail (GDATA_IS_SERVICE (self), NULL); + g_return_val_if_fail (G_IS_ASYNC_RESULT (async_result), NULL); + g_return_val_if_fail (error == NULL || *error == NULL, NULL); + g_return_val_if_fail (g_task_is_valid (async_result, self), NULL); + g_return_val_if_fail (g_async_result_is_tagged (async_result, gdata_service_update_entry_async), NULL); + + return g_task_propagate_pointer (G_TASK (async_result), error); +} + +/** + * gdata_service_update_entry: + * @self: a #GDataService + * @domain: (allow-none): the #GDataAuthorizationDomain the update operation falls under, or %NULL + * @entry: the #GDataEntry to update + * @cancellable: (allow-none): optional #GCancellable object, or %NULL + * @error: a #GError, or %NULL + * + * Updates @entry by PUTting it to its <literal>edit</literal> link's URI. For more information about the concept of updating entries, see + * the <ulink type="http" url="http://code.google.com/apis/gdata/docs/2.0/basics.html#UpdatingEntry">online documentation</ulink> for the GData + * protocol. + * + * The service will return an updated version of the entry, which is the return value of this function on success. + * + * If @cancellable is not %NULL, then the operation can be cancelled by triggering the @cancellable object from another thread. + * If the operation was cancelled before or during network activity, the error %G_IO_ERROR_CANCELLED will be returned. Cancellation has no effect + * after network activity has finished, however, and the update will return successfully (or return an error sent by the server) if it is first + * cancelled after network activity has finished. See the <link linkend="cancellable-support">overview of cancellation</link> for + * more details. + * + * If there is an error updating the entry, a %GDATA_SERVICE_ERROR_PROTOCOL_ERROR error will be returned. Currently, subclasses + * <emphasis>cannot</emphasis> cannot override this or provide more specific errors. + * + * Return value: (transfer full): an updated #GDataEntry, or %NULL; unref with g_object_unref() + * + * Since: 0.9.0 + */ +GDataEntry * +gdata_service_update_entry (GDataService *self, GDataAuthorizationDomain *domain, GDataEntry *entry, GCancellable *cancellable, GError **error) +{ + GDataEntry *updated_entry; + GDataLink *_link; + SoupMessage *message; + gchar *upload_data; + guint status; + GDataParsableClass *klass; + + g_return_val_if_fail (GDATA_IS_SERVICE (self), NULL); + g_return_val_if_fail (domain == NULL || GDATA_IS_AUTHORIZATION_DOMAIN (domain), NULL); + g_return_val_if_fail (GDATA_IS_ENTRY (entry), NULL); + g_return_val_if_fail (cancellable == NULL || G_IS_CANCELLABLE (cancellable), FALSE); + g_return_val_if_fail (error == NULL || *error == NULL, FALSE); + + /* Append the data */ + klass = GDATA_PARSABLE_GET_CLASS (entry); + g_assert (klass->get_content_type != NULL); + if (g_strcmp0 (klass->get_content_type (), "application/json") == 0) { + /* Get the edit URI */ + _link = gdata_entry_look_up_link (entry, GDATA_LINK_SELF); + g_assert (_link != NULL); + message = _gdata_service_build_message (self, domain, SOUP_METHOD_PUT, gdata_link_get_uri (_link), gdata_entry_get_etag (entry), TRUE); + upload_data = gdata_parsable_get_json (GDATA_PARSABLE (entry)); + soup_message_set_request (message, "application/json", SOUP_MEMORY_TAKE, upload_data, strlen (upload_data)); + } else { + /* Get the edit URI */ + _link = gdata_entry_look_up_link (entry, GDATA_LINK_EDIT); + g_assert (_link != NULL); + message = _gdata_service_build_message (self, domain, SOUP_METHOD_PUT, gdata_link_get_uri (_link), gdata_entry_get_etag (entry), TRUE); + upload_data = gdata_parsable_get_xml (GDATA_PARSABLE (entry)); + soup_message_set_request (message, "application/atom+xml", SOUP_MEMORY_TAKE, upload_data, strlen (upload_data)); + } + + /* Send the message */ + status = _gdata_service_send_message (self, message, cancellable, error); + + if (status == SOUP_STATUS_NONE || status == SOUP_STATUS_CANCELLED) { + /* Redirect error or cancelled */ + g_object_unref (message); + return NULL; + } else if (status != SOUP_STATUS_OK) { + /* Error */ + GDataServiceClass *service_klass = GDATA_SERVICE_GET_CLASS (self); + g_assert (service_klass->parse_error_response != NULL); + service_klass->parse_error_response (self, GDATA_OPERATION_UPDATE, status, message->reason_phrase, message->response_body->data, + message->response_body->length, error); + g_object_unref (message); + return NULL; + } + + /* Parse the XML; create and return a new GDataEntry of the same type as @entry */ + if (g_strcmp0 (klass->get_content_type (), "application/json") == 0) { + updated_entry = GDATA_ENTRY (gdata_parsable_new_from_json (G_OBJECT_TYPE (entry), message->response_body->data, + message->response_body->length, error)); + } else { + updated_entry = GDATA_ENTRY (gdata_parsable_new_from_xml (G_OBJECT_TYPE (entry), message->response_body->data, + message->response_body->length, error)); + } + g_object_unref (message); + + return updated_entry; +} + +typedef struct { + GDataAuthorizationDomain *domain; + GDataEntry *entry; +} DeleteEntryAsyncData; + +static void +delete_entry_async_data_free (DeleteEntryAsyncData *data) +{ + if (data->domain != NULL) + g_object_unref (data->domain); + + if (data->entry != NULL) + g_object_unref (data->entry); + + g_slice_free (DeleteEntryAsyncData, data); +} + +static void +delete_entry_thread (GTask *task, gpointer source_object, gpointer task_data, GCancellable *cancellable) +{ + GDataService *service = GDATA_SERVICE (source_object); + g_autoptr(GError) error = NULL; + DeleteEntryAsyncData *data = task_data; + + /* Delete the entry and return */ + if (!gdata_service_delete_entry (service, data->domain, data->entry, cancellable, &error)) + g_task_return_error (task, g_steal_pointer (&error)); + else + g_task_return_boolean (task, TRUE); +} + +/** + * gdata_service_delete_entry_async: + * @self: a #GDataService + * @domain: (allow-none): the #GDataAuthorizationDomain the deletion falls under, or %NULL + * @entry: the #GDataEntry to delete + * @cancellable: (allow-none): optional #GCancellable object, or %NULL + * @callback: a #GAsyncReadyCallback to call when deletion is finished, or %NULL + * @user_data: (closure): data to pass to the @callback function + * + * Deletes @entry from the server. @self and @entry are both reffed when this function is called, + * so can safely be unreffed after this function returns. + * + * For more details, see gdata_service_delete_entry(), which is the synchronous version of this function. + * + * When the operation is finished, @callback will be called. You can then call gdata_service_delete_entry_finish() + * to get the results of the operation. + * + * Since: 0.9.0 + */ +void +gdata_service_delete_entry_async (GDataService *self, GDataAuthorizationDomain *domain, GDataEntry *entry, + GCancellable *cancellable, GAsyncReadyCallback callback, gpointer user_data) +{ + g_autoptr(GTask) task = NULL; + DeleteEntryAsyncData *data; + + g_return_if_fail (GDATA_IS_SERVICE (self)); + g_return_if_fail (domain == NULL || GDATA_IS_AUTHORIZATION_DOMAIN (domain)); + g_return_if_fail (GDATA_IS_ENTRY (entry)); + g_return_if_fail (cancellable == NULL || G_IS_CANCELLABLE (cancellable)); + + data = g_slice_new (DeleteEntryAsyncData); + data->domain = (domain != NULL) ? g_object_ref (domain) : NULL; + data->entry = g_object_ref (entry); + + task = g_task_new (self, cancellable, callback, user_data); + g_task_set_source_tag (task, gdata_service_delete_entry_async); + g_task_set_task_data (task, g_steal_pointer (&data), (GDestroyNotify) delete_entry_async_data_free); + g_task_run_in_thread (task, delete_entry_thread); +} + +/** + * gdata_service_delete_entry_finish: + * @self: a #GDataService + * @async_result: a #GAsyncResult + * @error: a #GError, or %NULL + * + * Finishes an asynchronous entry deletion operation started with gdata_service_delete_entry_async(). + * + * Return value: %TRUE on success, %FALSE otherwise + * + * Since: 0.3.0 + */ +gboolean +gdata_service_delete_entry_finish (GDataService *self, GAsyncResult *async_result, GError **error) +{ + g_return_val_if_fail (GDATA_IS_SERVICE (self), FALSE); + g_return_val_if_fail (G_IS_ASYNC_RESULT (async_result), FALSE); + g_return_val_if_fail (error == NULL || *error == NULL, FALSE); + g_return_val_if_fail (g_task_is_valid (async_result, self), FALSE); + g_return_val_if_fail (g_async_result_is_tagged (async_result, gdata_service_delete_entry_async), FALSE); + + return g_task_propagate_boolean (G_TASK (async_result), error); +} + +/** + * gdata_service_delete_entry: + * @self: a #GDataService + * @domain: (allow-none): the #GDataAuthorizationDomain the deletion falls under, or %NULL + * @entry: the #GDataEntry to delete + * @cancellable: (allow-none): optional #GCancellable object, or %NULL + * @error: a #GError, or %NULL + * + * Deletes @entry from the server. For more information about the concept of deleting entries, see the + * <ulink type="http" url="http://code.google.com/apis/gdata/docs/2.0/basics.html#DeletingEntry">online documentation</ulink> for the GData + * protocol. + * + * If @cancellable is not %NULL, then the operation can be cancelled by triggering the @cancellable object from another thread. + * If the operation was cancelled before or during network activity, the error %G_IO_ERROR_CANCELLED will be returned. Cancellation has no effect + * after network activity has finished, however, and the deletion will return successfully (or return an error sent by the server) if it is first + * cancelled after network activity has finished. See the <link linkend="cancellable-support">overview of cancellation</link> for + * more details. + * + * If there is an error deleting the entry, a %GDATA_SERVICE_ERROR_PROTOCOL_ERROR error will be returned. Currently, subclasses + * <emphasis>cannot</emphasis> cannot override this or provide more specific errors. + * + * Return value: %TRUE on success, %FALSE otherwise + * + * Since: 0.9.0 + */ +gboolean +gdata_service_delete_entry (GDataService *self, GDataAuthorizationDomain *domain, GDataEntry *entry, GCancellable *cancellable, GError **error) +{ + GDataLink *_link; + SoupMessage *message; + guint status; + gchar *fixed_uri; + GDataParsableClass *klass; + + g_return_val_if_fail (GDATA_IS_SERVICE (self), FALSE); + g_return_val_if_fail (domain == NULL || GDATA_IS_AUTHORIZATION_DOMAIN (domain), FALSE); + g_return_val_if_fail (GDATA_IS_ENTRY (entry), FALSE); + g_return_val_if_fail (cancellable == NULL || G_IS_CANCELLABLE (cancellable), FALSE); + g_return_val_if_fail (error == NULL || *error == NULL, FALSE); + + /* Get the edit URI. We have to fix it to always use HTTPS as YouTube videos appear to incorrectly return a HTTP URI as their edit URI. */ + klass = GDATA_PARSABLE_GET_CLASS (entry); + g_assert (klass->get_content_type != NULL); + if (g_strcmp0 (klass->get_content_type (), "application/json") == 0) { + _link = gdata_entry_look_up_link (entry, GDATA_LINK_SELF); + } else { + _link = gdata_entry_look_up_link (entry, GDATA_LINK_EDIT); + } + g_assert (_link != NULL); + + fixed_uri = _gdata_service_fix_uri_scheme (gdata_link_get_uri (_link)); + message = _gdata_service_build_message (self, domain, SOUP_METHOD_DELETE, fixed_uri, gdata_entry_get_etag (entry), TRUE); + g_free (fixed_uri); + + /* Send the message */ + status = _gdata_service_send_message (self, message, cancellable, error); + + if (status == SOUP_STATUS_NONE || status == SOUP_STATUS_CANCELLED) { + /* Redirect error or cancelled */ + g_object_unref (message); + return FALSE; + } else if (status != SOUP_STATUS_OK && status != SOUP_STATUS_NO_CONTENT) { + /* Error */ + GDataServiceClass *service_klass = GDATA_SERVICE_GET_CLASS (self); + g_assert (service_klass->parse_error_response != NULL); + service_klass->parse_error_response (self, GDATA_OPERATION_DELETION, status, message->reason_phrase, message->response_body->data, + message->response_body->length, error); + g_object_unref (message); + return FALSE; + } + + g_object_unref (message); + + return TRUE; +} + +static void +notify_proxy_uri_cb (GObject *gobject, GParamSpec *pspec, GObject *self) +{ + g_object_notify (self, "proxy-uri"); +} + +/* Static function which isn't deprecated so we can continue using it internally. */ +static SoupURI * +_get_proxy_uri (GDataService *self) +{ + SoupURI *proxy_uri; + + g_return_val_if_fail (GDATA_IS_SERVICE (self), NULL); + + g_object_get (self->priv->session, SOUP_SESSION_PROXY_URI, &proxy_uri, NULL); + g_object_unref (proxy_uri); /* remove the ref added by g_object_get */ + + return proxy_uri; +} + +/** + * gdata_service_get_proxy_uri: + * @self: a #GDataService + * + * Gets the proxy URI on the #GDataService's #SoupSession. + * + * Return value: (transfer none): the proxy URI, or %NULL + * + * Since: 0.2.0 + * Deprecated: 0.15.0: Use gdata_service_get_proxy_resolver() instead, which gives more flexibility over the proxy used. + */ +SoupURI * +gdata_service_get_proxy_uri (GDataService *self) +{ + return _get_proxy_uri (self); +} + +/* Static function which isn't deprecated so we can continue using it internally. */ +static void +_set_proxy_uri (GDataService *self, SoupURI *proxy_uri) +{ + g_return_if_fail (GDATA_IS_SERVICE (self)); + g_object_set (self->priv->session, SOUP_SESSION_PROXY_URI, proxy_uri, NULL); + g_object_notify (G_OBJECT (self), "proxy-uri"); +} + +/** + * gdata_service_set_proxy_uri: + * @self: a #GDataService + * @proxy_uri: (allow-none): the proxy URI, or %NULL + * + * Sets the proxy URI on the #SoupSession used internally by the given #GDataService. + * This forces all requests through the given proxy. + * + * If @proxy_uri is %NULL, no proxy will be used. + * + * Note that if a #GDataAuthorizer is being used with this #GDataService, the authorizer might also need its proxy URI setting. + * + * Since: 0.2.0 + * Deprecated: 0.15.0: Use gdata_service_set_proxy_resolver() instead, which gives more flexibility over the proxy used. + */ +void +gdata_service_set_proxy_uri (GDataService *self, SoupURI *proxy_uri) +{ + _set_proxy_uri (self, proxy_uri); +} + +/** + * gdata_service_get_proxy_resolver: + * @self: a #GDataService + * + * Gets the #GProxyResolver on the #GDataService's #SoupSession. + * + * Return value: (transfer none) (allow-none): a #GProxyResolver, or %NULL + * + * Since: 0.15.0 + */ +GProxyResolver * +gdata_service_get_proxy_resolver (GDataService *self) +{ + g_return_val_if_fail (GDATA_IS_SERVICE (self), NULL); + + return self->priv->proxy_resolver; +} + +/** + * gdata_service_set_proxy_resolver: + * @self: a #GDataService + * @proxy_resolver: (allow-none): a #GProxyResolver, or %NULL + * + * Sets the #GProxyResolver on the #SoupSession used internally by the given #GDataService. + * + * Setting this will clear the #GDataService:proxy-uri property. + * + * Since: 0.15.0 + */ +void +gdata_service_set_proxy_resolver (GDataService *self, GProxyResolver *proxy_resolver) +{ + g_return_if_fail (GDATA_IS_SERVICE (self)); + g_return_if_fail (proxy_resolver == NULL || G_IS_PROXY_RESOLVER (proxy_resolver)); + + if (proxy_resolver != NULL) { + g_object_ref (proxy_resolver); + } + + g_clear_object (&self->priv->proxy_resolver); + self->priv->proxy_resolver = proxy_resolver; + + g_object_notify (G_OBJECT (self), "proxy-resolver"); +} + +static void +notify_timeout_cb (GObject *gobject, GParamSpec *pspec, GObject *self) +{ + g_object_notify (self, "timeout"); +} + +/** + * gdata_service_get_timeout: + * @self: a #GDataService + * + * Gets the #GDataService:timeout property; the network timeout, in seconds. + * + * Return value: the timeout, or <code class="literal">0</code> + * + * Since: 0.7.0 + */ +guint +gdata_service_get_timeout (GDataService *self) +{ + guint timeout; + + g_return_val_if_fail (GDATA_IS_SERVICE (self), 0); + + g_object_get (self->priv->session, SOUP_SESSION_TIMEOUT, &timeout, NULL); + + return timeout; +} + +/** + * gdata_service_set_timeout: + * @self: a #GDataService + * @timeout: the timeout, or <code class="literal">0</code> + * + * Sets the #GDataService:timeout property; the network timeout, in seconds. + * + * If @timeout is <code class="literal">0</code>, network operations will never time out. + * + * Note that if a #GDataAuthorizer is being used with this #GDataService, the authorizer might also need its timeout setting. + * + * Since: 0.7.0 + */ +void +gdata_service_set_timeout (GDataService *self, guint timeout) +{ + g_return_if_fail (GDATA_IS_SERVICE (self)); + g_object_set (self->priv->session, SOUP_SESSION_TIMEOUT, timeout, NULL); + g_object_notify (G_OBJECT (self), "timeout"); +} + +SoupSession * +_gdata_service_get_session (GDataService *self) +{ + g_return_val_if_fail (GDATA_IS_SERVICE (self), NULL); + return self->priv->session; +} + +/* + * _gdata_service_get_scheme: + * + * Returns the name of the scheme to use, which will always be <code class="literal">https</code>. The return type used to vary according to the + * environment variable <code class="literal">LIBGDATA_FORCE_HTTP</code>, but Google has since switched to using HTTPS exclusively. + * + * See <ulink type="http" url="http://googlecode.blogspot.com/2011/03/improving-security-of-google-apis-with.html">Improving the security of Google + * APIs with SSL</ulink>. + * + * Return value: the scheme to use (<code class="literal">https</code>) + * + * Since: 0.6.0 + */ +const gchar * +_gdata_service_get_scheme (void) +{ + return "https"; +} + +/* + * _gdata_service_build_uri: + * @format: a standard printf() format string + * @...: the arguments to insert in the output + * + * Builds a URI from the given @format string, replacing each <code class="literal">%%s</code> format placeholder with a URI-escaped version of the + * corresponding argument, and each <code class="literal">%%p</code> format placeholder with a non-escaped version of the corresponding argument. No + * other printf() format placeholders are supported at the moment except <code class="literal">%%d</code>, which prints a signed integer; and + * <code class="literal">%%</code>, which prints a literal percent symbol. + * + * The returned URI is guaranteed to use the scheme returned by _gdata_service_get_scheme(). The format string, once all the arguments have been + * inserted into it, must include a scheme, but it doesn't matter which one. + * + * Return value: a newly allocated URI string; free with g_free() + */ +gchar * +_gdata_service_build_uri (const gchar *format, ...) +{ + const gchar *p; + gchar *fixed_uri; + GString *uri; + va_list args; + + g_return_val_if_fail (format != NULL, NULL); + + /* Allocate a GString to build the URI in with at least as much space as the format string */ + uri = g_string_sized_new (strlen (format)); + + /* Build the URI */ + va_start (args, format); + + for (p = format; *p != '\0'; p++) { + if (*p != '%') { + g_string_append_c (uri, *p); + continue; + } + + switch(*++p) { + case 's': + g_string_append_uri_escaped (uri, va_arg (args, gchar*), NULL, TRUE); + break; + case 'p': + g_string_append (uri, va_arg (args, gchar*)); + break; + case 'd': + g_string_append_printf (uri, "%d", va_arg (args, gint)); + break; + case '%': + g_string_append_c (uri, '%'); + break; + default: + g_error ("Unrecognized format placeholder '%%%c' in format '%s'. This is a programmer error.", *p, format); + break; + } + } + + va_end (args); + + /* Fix the scheme to always be HTTPS */ + fixed_uri = _gdata_service_fix_uri_scheme (uri->str); + g_string_free (uri, TRUE); + + return fixed_uri; +} + +/** + * _gdata_service_fix_uri_scheme: + * @uri: an URI with either HTTP or HTTPS as the scheme + * + * Fixes the given URI to always have HTTPS as its scheme. + * + * Return value: (transfer full): the URI with HTTPS as its scheme + * + * Since: 0.9.0 + */ +gchar * +_gdata_service_fix_uri_scheme (const gchar *uri) +{ + g_return_val_if_fail (uri != NULL && *uri != '\0', NULL); + + /* Ensure we're using the correct scheme (HTTP or HTTPS) */ + if (g_str_has_prefix (uri, "https") == FALSE) { + gchar *fixed_uri, **pieces; + + pieces = g_strsplit (uri, ":", 2); + g_assert (pieces[0] != NULL && pieces[1] != NULL && pieces[2] == NULL); + + fixed_uri = g_strconcat ("https:", pieces[1], NULL); + + g_strfreev (pieces); + + return fixed_uri; + } + + return g_strdup (uri); +} + +/** + * _gdata_service_get_https_port: + * + * Gets the destination TCP/IP port number which libgdata should use for all outbound HTTPS traffic. + * This defaults to 443, but may be overridden using the <code class="literal">LIBGDATA_HTTPS_PORT</code> + * environment variable. This is intended to allow network traffic to be redirected to a local server for + * unit testing, with a listening port above 1024 so the tests don't need root privileges. + * + * The value returned by this function may change at any time (e.g. between unit tests), so callers must not cache the result. + * + * Return value: port number to use for HTTPS traffic + */ +guint +_gdata_service_get_https_port (void) +{ + const gchar *port_string; + + /* Allow changing the HTTPS port just for testing. */ + port_string = g_getenv ("LIBGDATA_HTTPS_PORT"); + if (port_string != NULL) { + const gchar *end; + + guint64 port = g_ascii_strtoull (port_string, (gchar **) &end, 10); + + if (port != 0 && *end == '\0') { + g_debug ("Overriding message port to %" G_GUINT64_FORMAT ".", port); + return port; + } + } + + /* Return the default. */ + return 443; +} + +/* + * debug_handler: + * + * GLib debug message handler, which is passed all messages from g_debug() calls, and decides whether to print them. + */ +static void +debug_handler (const char *log_domain, GLogLevelFlags log_level, const char *message, gpointer user_data) +{ + if (_gdata_service_get_log_level () != GDATA_LOG_NONE) + g_log_default_handler (log_domain, log_level, message, NULL); +} + +/* + * soup_log_printer: + * + * Log printer for the libsoup logging functionality, which just marshals all soup log output to the standard GLib logging framework + * (and thus to debug_handler(), above). + */ +static void +soup_log_printer (SoupLogger *logger, SoupLoggerLogLevel level, char direction, const char *data, gpointer user_data) +{ + gboolean filter_data; + gchar *_data = NULL; + + filter_data = (_gdata_service_get_log_level () > GDATA_LOG_NONE && _gdata_service_get_log_level () < GDATA_LOG_FULL_UNREDACTED) ? TRUE : FALSE; + + if (filter_data == TRUE) { + /* Filter out lines which look like they might contain usernames, passwords or auth. tokens. */ + if (direction == '>' && g_str_has_prefix (data, "Authorization: GoogleLogin ") == TRUE) { + _data = g_strdup ("Authorization: GoogleLogin <redacted>"); + } else if (direction == '>' && g_str_has_prefix (data, "Authorization: OAuth ") == TRUE) { + _data = g_strdup ("Authorization: OAuth <redacted>"); + } else if (direction == '<' && g_str_has_prefix (data, "Set-Cookie: ") == TRUE) { + _data = g_strdup ("Set-Cookie: <redacted>"); + } else if (direction == '<' && g_str_has_prefix (data, "Location: ") == TRUE) { + /* Looks like: + * "Location: https://www.google.com/calendar/feeds/default/owncalendars/full?gsessionid=sBjmp05m5i67exYA51XjDA". */ + SoupURI *uri; + gchar *_uri; + GHashTable *params; + + uri = soup_uri_new (data + strlen ("Location: ")); + + if (uri->query != NULL) { + params = soup_form_decode (uri->query); + + /* strdup()s are necessary because the hash table's set up to free keys. */ + if (g_hash_table_lookup (params, "gsessionid") != NULL) { + g_hash_table_insert (params, (gpointer) g_strdup ("gsessionid"), (gpointer) "<redacted>"); + } + + soup_uri_set_query_from_form (uri, params); + g_hash_table_destroy (params); + } + + _uri = soup_uri_to_string (uri, FALSE); + _data = g_strconcat ("Location: ", _uri, NULL); + g_free (_uri); + + soup_uri_free (uri); + } else if (direction == '<' && g_str_has_prefix (data, "SID=") == TRUE) { + _data = g_strdup ("SID=<redacted>"); + } else if (direction == '<' && g_str_has_prefix (data, "LSID=") == TRUE) { + _data = g_strdup ("LSID=<redacted>"); + } else if (direction == '<' && g_str_has_prefix (data, "Auth=") == TRUE) { + _data = g_strdup ("Auth=<redacted>"); + } else if (direction == '>' && g_str_has_prefix (data, "accountType=") == TRUE) { + /* Looks like: "> accountType=HOSTED%5FOR%5FGOOGLE&Email=[e-mail address]&Passwd=[plaintex password]" + "&service=[service name]&source=ytapi%2DGNOME%2Dlibgdata%2D444fubtt%2D0". */ + GHashTable *params = soup_form_decode (data); + + /* strdup()s are necessary because the hash table's set up to free keys. */ + if (g_hash_table_lookup (params, "Email") != NULL) { + g_hash_table_insert (params, (gpointer) g_strdup ("Email"), (gpointer) "<redacted>"); + } + if (g_hash_table_lookup (params, "Passwd") != NULL) { + g_hash_table_insert (params, (gpointer) g_strdup ("Passwd"), (gpointer) "<redacted>"); + } + + _data = soup_form_encode_hash (params); + + g_hash_table_destroy (params); + } else if (direction == '<' && g_str_has_prefix (data, "oauth_token=") == TRUE) { + /* Looks like: "< oauth_token=4%2FI-WU7sBzKk5GhGlQUF8a_TCZRnb7&oauth_token_secret=qTTTJg3no25auiiWFerzjW4I" + "&oauth_callback_confirmed=true". */ + GHashTable *params = soup_form_decode (data); + + /* strdup()s are necessary because the hash table's set up to free keys. */ + if (g_hash_table_lookup (params, "oauth_token") != NULL) { + g_hash_table_insert (params, (gpointer) g_strdup ("oauth_token"), (gpointer) "<redacted>"); + } + if (g_hash_table_lookup (params, "oauth_token_secret") != NULL) { + g_hash_table_insert (params, (gpointer) g_strdup ("oauth_token_secret"), (gpointer) "<redacted>"); + } + + _data = soup_form_encode_hash (params); + + g_hash_table_destroy (params); + } else if (direction == '>' && g_str_has_prefix (data, "X-GData-Key: key=") == TRUE) { + /* Looks like: "> X-GData-Key: key=[dev key in hex]". */ + _data = g_strdup ("X-GData-Key: key=<redacted>"); + } else { + /* Nothing to redact. */ + _data = g_strdup (data); + } + } else { + /* Don't dupe the string. */ + _data = (gchar*) data; + } + + /* Log the data. */ + g_debug ("%c %s", direction, _data); + + if (filter_data == TRUE) { + g_free (_data); + } +} + +/** + * _gdata_service_get_log_level: + * + * Returns the logging level for the library, currently set by an environment variable. + * + * Return value: the log level + * + * Since: 0.7.0 + */ +GDataLogLevel +_gdata_service_get_log_level (void) +{ + static int level = -1; + + if (level < 0) { + const gchar *envvar = g_getenv ("LIBGDATA_DEBUG"); + if (envvar != NULL) + level = atoi (envvar); + level = MIN (MAX (level, 0), GDATA_LOG_FULL_UNREDACTED); + } + + return level; +} + +/* Build a User-Agent value to send to the server. + * + * If we support gzip, we can request gzip from the server by both including + * the appropriate Accept-Encoding header and putting 'gzip' in the User-Agent + * header: + * - https://developers.google.com/drive/web/performance#gzip + * - http://googleappsdeveloper.blogspot.co.uk/2011/12/optimizing-bandwidth-usage-with-gzip.html + */ +static gchar * +build_user_agent (gboolean supports_gzip) +{ + if (supports_gzip) { + return g_strdup_printf ("libgdata/%s - gzip", VERSION); + } else { + return g_strdup_printf ("libgdata/%s", VERSION); + } +} + +/** + * _gdata_service_build_session: + * + * Build a new #SoupSession, enabling GNOME features if support has been compiled for them, and adding a log printer which is hooked into + * libgdata's logging functionality. + * + * Return value: a new #SoupSession; unref with g_object_unref() + * + * Since: 0.9.0 + */ +SoupSession * +_gdata_service_build_session (void) +{ + SoupSession *session; + gboolean ssl_strict = TRUE; + gchar *user_agent; + + /* Iff LIBGDATA_LAX_SSL_CERTIFICATES=1, relax SSL certificate validation to allow using invalid/unsigned certificates for testing. */ + if (g_strcmp0 (g_getenv ("LIBGDATA_LAX_SSL_CERTIFICATES"), "1") == 0) { + ssl_strict = FALSE; + } + + session = soup_session_new_with_options ("ssl-strict", ssl_strict, + "timeout", 0, + NULL); + + user_agent = build_user_agent (soup_session_has_feature (session, SOUP_TYPE_CONTENT_DECODER)); + g_object_set (session, "user-agent", user_agent, NULL); + g_free (user_agent); + + soup_session_add_feature_by_type (session, SOUP_TYPE_PROXY_RESOLVER_DEFAULT); + + /* Log all libsoup traffic if debugging's turned on */ + if (_gdata_service_get_log_level () > GDATA_LOG_MESSAGES) { + SoupLoggerLogLevel level; + SoupLogger *logger; + + switch (_gdata_service_get_log_level ()) { + case GDATA_LOG_FULL_UNREDACTED: + case GDATA_LOG_FULL: + level = SOUP_LOGGER_LOG_BODY; + break; + case GDATA_LOG_HEADERS: + level = SOUP_LOGGER_LOG_HEADERS; + break; + case GDATA_LOG_MESSAGES: + case GDATA_LOG_NONE: + default: + g_assert_not_reached (); + } + + logger = soup_logger_new (level, -1); + soup_logger_set_printer (logger, (SoupLoggerPrinter) soup_log_printer, NULL, NULL); + + soup_session_add_feature (session, SOUP_SESSION_FEATURE (logger)); + + g_object_unref (logger); + } + + return session; +} + +/** + * gdata_service_get_locale: + * @self: a #GDataService + * + * Returns the locale currently being used for network requests, or %NULL if the locale is the default. + * + * Return value: the current locale + * + * Since: 0.7.0 + */ +const gchar * +gdata_service_get_locale (GDataService *self) +{ + g_return_val_if_fail (GDATA_IS_SERVICE (self), NULL); + return self->priv->locale; +} + +/** + * gdata_service_set_locale: + * @self: a #GDataService + * @locale: (allow-none): the new locale in Unix locale format, or %NULL for the default locale + * + * Set the locale used for network requests to @locale, given in standard Unix locale format. See #GDataService:locale for more details. + * + * Note that while it's possible to change the locale after sending network requests, it is unsupported, as the server-side software may behave + * unexpectedly. The only supported use of this function is after creation of a service, but before any network requests are made. + * + * Since: 0.7.0 + */ +void +gdata_service_set_locale (GDataService *self, const gchar *locale) +{ + g_return_if_fail (GDATA_IS_SERVICE (self)); + + g_free (self->priv->locale); + self->priv->locale = g_strdup (locale); + g_object_notify (G_OBJECT (self), "locale"); +} + +/* + * _gdata_service_secure_strdup: + * @str: string (which may be in pageable memory) to be duplicated, or %NULL + * + * Duplicate a string into non-pageable memory (if libgdata has been compiled with HAVE_GNOME) or just fall back to g_strdup() (if libgdata hasn't). + * Passing %NULL to this function will cause %NULL to be returned. + * + * Strings allocated using this function must be freed using _gdata_service_secure_strfree(). + * + * Return value: non-pageable copy of @str, or %NULL + * Since: 0.11.0 + */ +GDataSecureString +_gdata_service_secure_strdup (const gchar *str) +{ +#ifdef HAVE_GNOME + return gcr_secure_memory_strdup (str); +#else /* if !HAVE_GNOME */ + return g_strdup (str); +#endif /* !HAVE_GNOME */ +} + +/* + * _gdata_service_secure_strndup: + * @str: string (which may be in pageable memory) to be duplicated, or %NULL + * @n_bytes: maximum number of bytes to copy from @str + * + * Duplicate at most @n_bytes bytes from @str into non-pageable memory. See _gdata_service_secure_strdup() for more information; this function is just + * a version of that with the same semantics as strndup(). + * + * Return value: non-pageable copy of at most the first @n_bytes bytes of @str, or %NULL + * Since: 0.11.0 + */ +GDataSecureString +_gdata_service_secure_strndup (const gchar *str, gsize n_bytes) +{ +#ifdef HAVE_GNOME + gsize str_len; + GDataSecureString duped_str; + + if (str == NULL) { + return NULL; + } + + str_len = MIN (strlen (str), n_bytes); + duped_str = (GDataSecureString) gcr_secure_memory_alloc (str_len + 1); + strncpy (duped_str, str, str_len); + *(duped_str + str_len) = '\0'; + + return duped_str; +#else /* if !HAVE_GNOME */ + return g_strndup (str, n_bytes); +#endif /* !HAVE_GNOME */ +} + +/* + * _gdata_service_secure_strfree: + * @str: a string to free, or %NULL + * + * Free a string which was allocated securely using _gdata_service_secure_strdup(). + * Passing %NULL to this function is safe. + * + * Since: 0.11.0 + */ +void +_gdata_service_secure_strfree (GDataSecureString str) +{ +#ifdef HAVE_GNOME + gcr_secure_memory_free (str); +#else /* if !HAVE_GNOME */ + /* Poor man's approximation to non-pageable memory: the best we can do is ensure that we don't leak it in free memory. + * This can't guarantee that it hasn't hit disk at some point, but does mean it can't hit disk in future. */ + if (str != NULL) { + memset (str, 0, strlen (str)); + } + + g_free (str); +#endif /* !HAVE_GNOME */ +} diff --git a/gdata/gdata-service.h b/gdata/gdata-service.h new file mode 100644 index 0000000..c518909 --- /dev/null +++ b/gdata/gdata-service.h @@ -0,0 +1,247 @@ +/* -*- Mode: C; indent-tabs-mode: t; c-basic-offset: 8; tab-width: 8 -*- */ +/* + * GData Client + * Copyright (C) Philip Withnall 2008, 2009, 2010, 2014 <philip@tecnocode.co.uk> + * + * GData Client is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * GData Client is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with GData Client. If not, see <http://www.gnu.org/licenses/>. + */ + +#ifndef GDATA_SERVICE_H +#define GDATA_SERVICE_H + +#include <glib.h> +#include <glib-object.h> +#include <libsoup/soup.h> + +#include <gdata/gdata-authorizer.h> +#include <gdata/gdata-feed.h> +#include <gdata/gdata-query.h> + +G_BEGIN_DECLS + +/** + * GDataOperationType: + * @GDATA_OPERATION_QUERY: a query + * @GDATA_OPERATION_INSERTION: an insertion of a #GDataEntry + * @GDATA_OPERATION_UPDATE: an update of a #GDataEntry + * @GDATA_OPERATION_DELETION: a deletion of a #GDataEntry + * @GDATA_OPERATION_DOWNLOAD: a download of a file + * @GDATA_OPERATION_UPLOAD: an upload of a file + * @GDATA_OPERATION_AUTHENTICATION: authentication with the service + * @GDATA_OPERATION_BATCH: a batch operation with #GDataBatchOperation + * + * Representations of the different operations performed by the library. + * + * Since: 0.6.0 + */ +typedef enum { + GDATA_OPERATION_QUERY = 1, + GDATA_OPERATION_INSERTION, + GDATA_OPERATION_UPDATE, + GDATA_OPERATION_DELETION, + GDATA_OPERATION_DOWNLOAD, + GDATA_OPERATION_UPLOAD, + GDATA_OPERATION_AUTHENTICATION, + GDATA_OPERATION_BATCH +} GDataOperationType; + +/** + * GDataServiceError: + * @GDATA_SERVICE_ERROR_UNAVAILABLE: The service is unavailable due to maintenance or other reasons (e.g. network errors at the server end) + * @GDATA_SERVICE_ERROR_PROTOCOL_ERROR: The client or server unexpectedly strayed from the protocol (fatal error) + * @GDATA_SERVICE_ERROR_ENTRY_ALREADY_INSERTED: An entry has already been inserted, and cannot be re-inserted + * @GDATA_SERVICE_ERROR_AUTHENTICATION_REQUIRED: The user attempted to do something which required authentication, and they weren't authenticated or + * didn't have authorization for the operation + * @GDATA_SERVICE_ERROR_NOT_FOUND: A requested resource (feed or entry) was not found on the server + * @GDATA_SERVICE_ERROR_CONFLICT: There was a conflict when updating an entry on the server; the server-side copy was modified between downloading + * and uploading the modified entry + * @GDATA_SERVICE_ERROR_FORBIDDEN: Generic error for a forbidden action (not due to having insufficient permissions) + * @GDATA_SERVICE_ERROR_BAD_QUERY_PARAMETER: A given query parameter was invalid for the query type + * @GDATA_SERVICE_ERROR_NETWORK_ERROR: The service is unavailable due to local network errors (e.g. no Internet connection) + * @GDATA_SERVICE_ERROR_PROXY_ERROR: The service is unavailable due to proxy network errors (e.g. proxy unreachable) + * @GDATA_SERVICE_ERROR_WITH_BATCH_OPERATION: Generic error when running a batch operation and the whole operation fails + * @GDATA_SERVICE_ERROR_API_QUOTA_EXCEEDED: The API request quota for this + * developer account has been exceeded for the current time period (e.g. day). + * Try again later. (Since: 0.16.0.) + * + * Error codes for #GDataService operations. + */ +typedef enum { + GDATA_SERVICE_ERROR_UNAVAILABLE = 1, + GDATA_SERVICE_ERROR_PROTOCOL_ERROR, + GDATA_SERVICE_ERROR_ENTRY_ALREADY_INSERTED, + GDATA_SERVICE_ERROR_AUTHENTICATION_REQUIRED, + GDATA_SERVICE_ERROR_NOT_FOUND, + GDATA_SERVICE_ERROR_CONFLICT, + GDATA_SERVICE_ERROR_FORBIDDEN, + GDATA_SERVICE_ERROR_BAD_QUERY_PARAMETER, + GDATA_SERVICE_ERROR_NETWORK_ERROR, + GDATA_SERVICE_ERROR_PROXY_ERROR, + GDATA_SERVICE_ERROR_WITH_BATCH_OPERATION, + GDATA_SERVICE_ERROR_API_QUOTA_EXCEEDED, +} GDataServiceError; + +/** + * GDataQueryProgressCallback: + * @entry: a new #GDataEntry + * @entry_key: the key of the entry (zero-based index of its position in the feed) + * @entry_count: the total number of entries in the feed + * @user_data: user data passed to the callback + * + * Callback function called for each #GDataEntry parsed in a #GDataFeed when loading the results of a query. + * + * It is called in the main thread, so there is no guarantee on the order in which the callbacks are executed, + * or whether they will be called in a timely manner. It is, however, guaranteed that they will all be called before + * the #GAsyncReadyCallback which signals the completion of the query is called. + */ +typedef void (*GDataQueryProgressCallback) (GDataEntry *entry, guint entry_key, guint entry_count, gpointer user_data); + +#define GDATA_TYPE_SERVICE (gdata_service_get_type ()) +#define GDATA_SERVICE(o) (G_TYPE_CHECK_INSTANCE_CAST ((o), GDATA_TYPE_SERVICE, GDataService)) +#define GDATA_SERVICE_CLASS(k) (G_TYPE_CHECK_CLASS_CAST((k), GDATA_TYPE_SERVICE, GDataServiceClass)) +#define GDATA_IS_SERVICE(o) (G_TYPE_CHECK_INSTANCE_TYPE ((o), GDATA_TYPE_SERVICE)) +#define GDATA_IS_SERVICE_CLASS(k) (G_TYPE_CHECK_CLASS_TYPE ((k), GDATA_TYPE_SERVICE)) +#define GDATA_SERVICE_GET_CLASS(o) (G_TYPE_INSTANCE_GET_CLASS ((o), GDATA_TYPE_SERVICE, GDataServiceClass)) + +#define GDATA_SERVICE_ERROR gdata_service_error_quark () + +typedef struct _GDataServicePrivate GDataServicePrivate; + +/** + * GDataService: + * + * All the fields in the #GDataService structure are private and should never be accessed directly. + */ +typedef struct { + GObject parent; + GDataServicePrivate *priv; +} GDataService; + +/** + * GDataServiceClass: + * @parent: the parent class + * @api_version: the version of the GData API used by the service (typically <code class="literal">2</code>) + * @feed_type: the #GType of the feed class (subclass of #GDataFeed) to use for query results from this service + * @append_query_headers: a function to allow subclasses to append their own headers to queries before they are submitted to the online service, + * using the given authorization domain; new in version 0.9.0 + * @parse_error_response: a function to parse error responses to queries from the online service. It should set the error + * from the status, reason phrase and response body it is passed. + * @get_authorization_domains: a function to return a newly-allocated list of all the #GDataAuthorizationDomains the service makes use of; + * while the list should be newly-allocated, the individual domains should not be; not implementing this function is equivalent to returning an + * empty list; new in version 0.9.0 + * @parse_feed: a function to parse feed responses to queries from the online + * service; new in version 0.17.0 + * + * The class structure for the #GDataService type. + * + * Since: 0.9.0 + */ +typedef struct { + GObjectClass parent; + + const gchar *api_version; + GType feed_type; + + void (*append_query_headers) (GDataService *self, GDataAuthorizationDomain *domain, SoupMessage *message); + void (*parse_error_response) (GDataService *self, GDataOperationType operation_type, guint status, const gchar *reason_phrase, + const gchar *response_body, gint length, GError **error); + GList *(*get_authorization_domains) (void); + GDataFeed *(*parse_feed) (GDataService *self, + GDataAuthorizationDomain *domain, + GDataQuery *query, + GType entry_type, + SoupMessage *message, + GCancellable *cancellable, + GDataQueryProgressCallback progress_callback, + gpointer progress_user_data, + GError **error); + + /*< private >*/ + /* Padding for future expansion */ + void (*_g_reserved1) (void); + void (*_g_reserved2) (void); + void (*_g_reserved3) (void); + void (*_g_reserved4) (void); + void (*_g_reserved5) (void); + void (*_g_reserved6) (void); + void (*_g_reserved7) (void); +} GDataServiceClass; + +G_DEFINE_AUTOPTR_CLEANUP_FUNC (GDataService, g_object_unref) + +GType gdata_service_get_type (void) G_GNUC_CONST; +GQuark gdata_service_error_quark (void) G_GNUC_CONST; + +GList *gdata_service_get_authorization_domains (GType service_type) G_GNUC_WARN_UNUSED_RESULT G_GNUC_MALLOC; +gboolean gdata_service_is_authorized (GDataService *self); + +GDataAuthorizer *gdata_service_get_authorizer (GDataService *self) G_GNUC_PURE; +void gdata_service_set_authorizer (GDataService *self, GDataAuthorizer *authorizer); + +#include <gdata/gdata-query.h> + +GDataFeed *gdata_service_query (GDataService *self, GDataAuthorizationDomain *domain, const gchar *feed_uri, GDataQuery *query, GType entry_type, + GCancellable *cancellable, + GDataQueryProgressCallback progress_callback, gpointer progress_user_data, + GError **error) G_GNUC_WARN_UNUSED_RESULT G_GNUC_MALLOC; +void gdata_service_query_async (GDataService *self, GDataAuthorizationDomain *domain, const gchar *feed_uri, GDataQuery *query, GType entry_type, + GCancellable *cancellable, + GDataQueryProgressCallback progress_callback, gpointer progress_user_data, GDestroyNotify destroy_progress_user_data, + GAsyncReadyCallback callback, gpointer user_data); +GDataFeed *gdata_service_query_finish (GDataService *self, GAsyncResult *async_result, GError **error) G_GNUC_WARN_UNUSED_RESULT G_GNUC_MALLOC; + +GDataEntry *gdata_service_query_single_entry (GDataService *self, GDataAuthorizationDomain *domain, const gchar *entry_id, GDataQuery *query, + GType entry_type, GCancellable *cancellable, GError **error) G_GNUC_WARN_UNUSED_RESULT G_GNUC_MALLOC; +void gdata_service_query_single_entry_async (GDataService *self, GDataAuthorizationDomain *domain, const gchar *entry_id, GDataQuery *query, + GType entry_type, GCancellable *cancellable, GAsyncReadyCallback callback, gpointer user_data); +GDataEntry *gdata_service_query_single_entry_finish (GDataService *self, GAsyncResult *async_result, + GError **error) G_GNUC_WARN_UNUSED_RESULT G_GNUC_MALLOC; + +GDataEntry *gdata_service_insert_entry (GDataService *self, GDataAuthorizationDomain *domain, const gchar *upload_uri, GDataEntry *entry, + GCancellable *cancellable, GError **error) G_GNUC_WARN_UNUSED_RESULT G_GNUC_MALLOC; +void gdata_service_insert_entry_async (GDataService *self, GDataAuthorizationDomain *domain, const gchar *upload_uri, GDataEntry *entry, + GCancellable *cancellable, GAsyncReadyCallback callback, gpointer user_data); +GDataEntry *gdata_service_insert_entry_finish (GDataService *self, GAsyncResult *async_result, + GError **error) G_GNUC_WARN_UNUSED_RESULT G_GNUC_MALLOC; + +GDataEntry *gdata_service_update_entry (GDataService *self, GDataAuthorizationDomain *domain, GDataEntry *entry, + GCancellable *cancellable, GError **error) G_GNUC_WARN_UNUSED_RESULT G_GNUC_MALLOC; +void gdata_service_update_entry_async (GDataService *self, GDataAuthorizationDomain *domain, GDataEntry *entry, GCancellable *cancellable, + GAsyncReadyCallback callback, gpointer user_data); +GDataEntry *gdata_service_update_entry_finish (GDataService *self, GAsyncResult *async_result, + GError **error) G_GNUC_WARN_UNUSED_RESULT G_GNUC_MALLOC; + +gboolean gdata_service_delete_entry (GDataService *self, GDataAuthorizationDomain *domain, GDataEntry *entry, + GCancellable *cancellable, GError **error); +void gdata_service_delete_entry_async (GDataService *self, GDataAuthorizationDomain *domain, GDataEntry *entry, GCancellable *cancellable, + GAsyncReadyCallback callback, gpointer user_data); +gboolean gdata_service_delete_entry_finish (GDataService *self, GAsyncResult *async_result, GError **error); + +#ifndef LIBGDATA_DISABLE_DEPRECATED +SoupURI *gdata_service_get_proxy_uri (GDataService *self) G_GNUC_PURE G_GNUC_DEPRECATED_FOR (gdata_service_get_proxy_resolver); +void gdata_service_set_proxy_uri (GDataService *self, SoupURI *proxy_uri) G_GNUC_DEPRECATED_FOR (gdata_service_set_proxy_resolver); +#endif /* !LIBGDATA_DISABLE_DEPRECATED */ + +GProxyResolver *gdata_service_get_proxy_resolver (GDataService *self) G_GNUC_PURE; +void gdata_service_set_proxy_resolver (GDataService *self, GProxyResolver *proxy_resolver); + +guint gdata_service_get_timeout (GDataService *self) G_GNUC_PURE; +void gdata_service_set_timeout (GDataService *self, guint timeout); + +const gchar *gdata_service_get_locale (GDataService *self) G_GNUC_PURE; +void gdata_service_set_locale (GDataService *self, const gchar *locale); + +G_END_DECLS + +#endif /* !GDATA_SERVICE_H */ diff --git a/gdata/gdata-types.c b/gdata/gdata-types.c new file mode 100644 index 0000000..fd36705 --- /dev/null +++ b/gdata/gdata-types.c @@ -0,0 +1,134 @@ +/* -*- Mode: C; indent-tabs-mode: t; c-basic-offset: 8; tab-width: 8 -*- */ +/* + * GData Client + * Copyright (C) Philip Withnall 2008-2009 <philip@tecnocode.co.uk> + * + * GData Client is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * GData Client is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with GData Client. If not, see <http://www.gnu.org/licenses/>. + */ + +/** + * SECTION:gdata-types + * @short_description: miscellaneous data types + * @stability: Stable + * @include: gdata/gdata-types.h + * + * The structures here are used haphazardly across the library, describing + * various small data types. + */ + +#include <glib.h> +#include <glib-object.h> +#include <string.h> +#include <stdlib.h> +#include <libsoup/soup.h> + +#include "gdata-types.h" + +static gpointer +gdata_color_copy (gpointer color) +{ + return g_memdup (color, sizeof (GDataColor)); +} + +GType +gdata_color_get_type (void) +{ + static GType type_id = 0; + + if (type_id == 0) { + type_id = g_boxed_type_register_static (g_intern_static_string ("GDataColor"), + (GBoxedCopyFunc) gdata_color_copy, + (GBoxedFreeFunc) g_free); + } + + return type_id; +} + +/** + * gdata_color_from_hexadecimal: + * @hexadecimal: a hexadecimal color string + * @color: (out caller-allocates): a #GDataColor + * + * Parses @hexadecimal and returns a #GDataColor describing it in @color. + * + * @hexadecimal should be in the form <literal>#<replaceable>rr</replaceable><replaceable>gg</replaceable><replaceable>bb</replaceable></literal>, + * where <replaceable>rr</replaceable> is a two-digit hexadecimal red intensity value, <replaceable>gg</replaceable> is green + * and <replaceable>bb</replaceable> is blue. The hash is optional. + * + * Return value: %TRUE on success, %FALSE otherwise + */ +gboolean +gdata_color_from_hexadecimal (const gchar *hexadecimal, GDataColor *color) +{ + gint temp; + + g_return_val_if_fail (hexadecimal != NULL, FALSE); + g_return_val_if_fail (color != NULL, FALSE); + + if (*hexadecimal == '#') + hexadecimal++; + if (strlen (hexadecimal) != 6) + return FALSE; + + /* Red */ + temp = g_ascii_xdigit_value (*(hexadecimal++)) * 16; + if (temp < 0) + return FALSE; + color->red = temp; + temp = g_ascii_xdigit_value (*(hexadecimal++)); + if (temp < 0) + return FALSE; + color->red += temp; + + /* Green */ + temp = g_ascii_xdigit_value (*(hexadecimal++)) * 16; + if (temp < 0) + return FALSE; + color->green = temp; + temp = g_ascii_xdigit_value (*(hexadecimal++)); + if (temp < 0) + return FALSE; + color->green += temp; + + /* Blue */ + temp = g_ascii_xdigit_value (*(hexadecimal++)) * 16; + if (temp < 0) + return FALSE; + color->blue = temp; + temp = g_ascii_xdigit_value (*(hexadecimal++)); + if (temp < 0) + return FALSE; + color->blue += temp; + + return TRUE; +} + +/** + * gdata_color_to_hexadecimal: + * @color: a #GDataColor + * + * Returns a string describing @color in hexadecimal form; in the form <literal>#<replaceable>rr</replaceable><replaceable>gg</replaceable> + * <replaceable>bb</replaceable></literal>, where <replaceable>rr</replaceable> is a two-digit hexadecimal red intensity value, + * <replaceable>gg</replaceable> is green and <replaceable>bb</replaceable> is blue. The hash is always present. + * + * Return value: the color string; free with g_free() + * + * Since: 0.3.0 + */ +gchar * +gdata_color_to_hexadecimal (const GDataColor *color) +{ + g_return_val_if_fail (color != NULL, NULL); + return g_strdup_printf ("#%02x%02x%02x", color->red, color->green, color->blue); +} diff --git a/gdata/gdata-types.h b/gdata/gdata-types.h new file mode 100644 index 0000000..8b7e68c --- /dev/null +++ b/gdata/gdata-types.h @@ -0,0 +1,50 @@ +/* -*- Mode: C; indent-tabs-mode: t; c-basic-offset: 8; tab-width: 8 -*- */ +/* + * GData Client + * Copyright (C) Philip Withnall 2008-2009 <philip@tecnocode.co.uk> + * + * GData Client is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * GData Client is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with GData Client. If not, see <http://www.gnu.org/licenses/>. + */ + +#include <glib.h> + +#ifndef GDATA_TYPES_H +#define GDATA_TYPES_H + +G_BEGIN_DECLS + +/** + * GDataColor: + * @red: red color intensity, from 0–255 + * @green: green color intensity, from 0–255 + * @blue: blue color intensity, from 0–255 + * + * Describes a color, such as used in the Google Calendar interface to + * differentiate calendars. + */ +typedef struct { + /*< public >*/ + guint16 red; + guint16 green; + guint16 blue; +} GDataColor; + +#define GDATA_TYPE_COLOR (gdata_color_get_type ()) +GType gdata_color_get_type (void) G_GNUC_CONST; +gboolean gdata_color_from_hexadecimal (const gchar *hexadecimal, GDataColor *color); +gchar *gdata_color_to_hexadecimal (const GDataColor *color) G_GNUC_WARN_UNUSED_RESULT G_GNUC_MALLOC; + +G_END_DECLS + +#endif /* !GDATA_TYPES_H */ diff --git a/gdata/gdata-upload-stream.c b/gdata/gdata-upload-stream.c new file mode 100644 index 0000000..85738fd --- /dev/null +++ b/gdata/gdata-upload-stream.c @@ -0,0 +1,1660 @@ +/* -*- Mode: C; indent-tabs-mode: t; c-basic-offset: 8; tab-width: 8 -*- */ +/* + * GData Client + * Copyright (C) Philip Withnall 2009 <philip@tecnocode.co.uk> + * + * GData Client is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * GData Client is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with GData Client. If not, see <http://www.gnu.org/licenses/>. + */ + +/** + * SECTION:gdata-upload-stream + * @short_description: GData upload stream object + * @stability: Stable + * @include: gdata/gdata-upload-stream.h + * + * #GDataUploadStream is a #GOutputStream subclass to allow uploading of files from GData services with authorization from a #GDataService under + * the given #GDataAuthorizationDomain. If authorization is not required to perform the upload, a #GDataAuthorizationDomain doesn't have to be + * specified. + * + * Once a #GDataUploadStream is instantiated with gdata_upload_stream_new(), the standard #GOutputStream API can be used on the stream to upload + * the file. Network communication may not actually begin until the first call to g_output_stream_write(), so having a #GDataUploadStream around is no + * guarantee that data is being uploaded. + * + * Uploads of a file, or a file with associated metadata (a #GDataEntry) should use #GDataUploadStream, but if you want to simply upload a single + * #GDataEntry, use gdata_service_insert_entry() instead. #GDataUploadStream is for large streaming uploads. + * + * Once an upload is complete, the server's response can be retrieved from the #GDataUploadStream using gdata_upload_stream_get_response(). In order + * for network communication to be guaranteed to have stopped (and thus the response definitely available), g_output_stream_close() must be called + * on the #GDataUploadStream first. Otherwise, gdata_upload_stream_get_response() may return saying that the operation is still in progress. + * + * If the server returns an error instead of a success response, the error will be returned by g_output_stream_close() as a #GDataServiceError. + * + * The entire upload operation can be cancelled using the #GCancellable instance provided to gdata_upload_stream_new(), or returned by + * gdata_upload_stream_get_cancellable(). Cancelling this at any time will cause all future #GOutputStream method calls to return + * %G_IO_ERROR_CANCELLED. If any #GOutputStream methods are in the process of being called, they will be cancelled and return %G_IO_ERROR_CANCELLED as + * soon as possible. + * + * Note that cancelling an individual method call (such as a call to g_output_stream_write()) using the #GCancellable parameter of the method will not + * cancel the upload as a whole — just that particular method call. In the case of g_output_stream_write(), this will cause it to return the number of + * bytes it has successfully written up to the point of cancellation (up to the requested number of bytes), or return a %G_IO_ERROR_CANCELLED if it + * had not managed to write any bytes to the network by that point. This is also the behaviour of g_output_stream_write() when the upload operation as + * a whole is cancelled. + * + * In the case of g_output_stream_close(), the call will return immediately if network activity hasn't yet started. If it has, the network activity + * will be cancelled, regardless of whether the call to g_output_stream_close() is cancelled. Cancelling a pending call to g_output_stream_close() + * (either using the method's #GCancellable, or by cancelling the upload stream as a whole) will cause it to stop waiting for the network activity to + * finish, and return %G_IO_ERROR_CANCELLED immediately. Network activity will continue to be shut down in the background. + * + * Any outstanding data is guaranteed to be written to the network successfully even if a call to g_output_stream_close() is cancelled. However, if + * the upload stream as a whole is cancelled using #GDataUploadStream:cancellable, no more data will be sent over the network, and the network + * connection will be closed immediately. i.e. #GDataUploadStream will do its best to instruct the server to cancel the upload and any associated + * server-side changes of state. + * + * If the server returns an error message (for example, if the user is not correctly authenticated/authorized or doesn't have suitable permissions + * to upload from the given URI), it will be returned as a #GDataServiceError by g_output_stream_close(). + * + * <example> + * <title>Uploading from a File + * + * GDataService *service; + * GDataAuthorizationDomain *domain; + * GCancellable *cancellable; + * GInputStream *input_stream; + * GOutputStream *upload_stream; + * GFile *file; + * GFileInfo *file_info; + * GError *error = NULL; + * + * /* Get the file to upload */ + * file = get_file_to_upload (); + * file_info = g_file_query_info (file, G_FILE_ATTRIBUTE_STANDARD_DISPLAY_NAME "," G_FILE_ATTRIBUTE_STANDARD_CONTENT_TYPE "," + * G_FILE_ATTRIBUTE_STANDARD_SIZE, + * G_FILE_QUERY_INFO_NONE, NULL, &error); + * + * if (file_info == NULL) { + * g_error ("Error getting file info: %s", error->message); + * g_error_free (error); + * g_object_unref (file); + * return; + * } + * + * input_stream = g_file_read (file, NULL, &error); + * g_object_unref (file); + * + * if (input_stream == NULL) { + * g_error ("Error getting file input stream: %s", error->message); + * g_error_free (error); + * g_object_unref (file_info); + * return; + * } + * + * /* Create the upload stream */ + * service = create_my_service (); + * domain = get_my_authorization_domain_from_service (service); + * cancellable = g_cancellable_new (); /* cancel this to cancel the entire upload operation */ + * upload_stream = gdata_upload_stream_new_resumable (service, domain, SOUP_METHOD_POST, upload_uri, NULL, + * g_file_info_get_display_name (file_info), g_file_info_get_content_type (file_info), + * g_file_info_get_size (file_info), cancellable); + * g_object_unref (file_info); + * + * /* Perform the upload asynchronously */ + * g_output_stream_splice_async (upload_stream, input_stream, G_OUTPUT_STREAM_SPLICE_CLOSE_SOURCE | G_OUTPUT_STREAM_SPLICE_CLOSE_TARGET, + * G_PRIORITY_DEFAULT, NULL, (GAsyncReadyCallback) upload_splice_cb, NULL); + * + * g_object_unref (upload_stream); + * g_object_unref (input_stream); + * g_object_unref (cancellable); + * g_object_unref (domain); + * g_object_unref (service); + * + * static void + * upload_splice_cb (GOutputStream *upload_stream, GAsyncResult *result, gpointer user_data) + * { + * gssize length; + * GError *error = NULL; + * + * g_output_stream_splice_finish (upload_stream, result, &error); + * + * if (error != NULL && g_error_matches (error, G_IO_ERROR, G_IO_ERROR_CANCELLED) == FALSE)) { + * /* Error upload the file; potentially an I/O error (GIOError), or an error response from the server + * * (GDataServiceError). */ + * g_error ("Error uploading file: %s", error->message); + * g_error_free (error); + * } + * + * /* If the upload was successful, carry on to parse the result. Note that this will normally be handled by methods like + * * gdata_youtube_service_finish_video_upload(), gdata_picasaweb_service_finish_file_upload() and + * * gdata_documents_service_finish_upload() */ + * parse_server_result (gdata_upload_stream_get_response (GDATA_UPLOAD_STREAM (upload_stream), &length), length); + * } + * + * + * + * Since: 0.5.0 + */ + +/* + * We have a network thread which does all the uploading work. We send the message encoded as chunks, but cannot use the SoupMessageBody as a + * data buffer, since it can only ever be touched by the network thread. Instead, we pass data to the network thread through a GDataBuffer, with + * the main thread pushing it on as and when write() is called. The network thread cannot block on popping data off the buffer, as it requests fixed- + * size chunks, and there's no way to notify it that we've reached EOF; so when it gets to popping the last chunk off the buffer, which may well be + * smaller than its chunk size, it would block for more data and therefore hang. Consequently, the network thread instead pops as much data as it can + * off the buffer, up to its chunk size, which is a non-blocking operation. + * + * The write() and close() operations on the output stream are synchronised with the network thread, so that the write() call only returns once the + * network thread has written at least as many bytes as were passed to the write() call, and the close() call only returns once all network activity + * has finished (including receiving the response from the server). Async versions of these calls are provided by GOutputStream. + * + * The number of bytes in the various buffers are recorded using: + * • message_bytes_outstanding: the number of bytes in the GDataBuffer which are waiting to be written to the SoupMessageBody + * • network_bytes_outstanding: the number of bytes which have been written to the SoupMessageBody, and are waiting to be written to the network + * • network_bytes_written: the total number of bytes which have been successfully written to the network + * + * Mutex locking order: + * 1. response_mutex + * 2. write_mutex + */ + +#include +#include +#include +#include + +#include "gdata-upload-stream.h" +#include "gdata-buffer.h" +#include "gdata-private.h" + +#define BOUNDARY_STRING "0003Z5W789deadbeefRTE456KlemsnoZV" +#define MAX_RESUMABLE_CHUNK_SIZE (512 * 1024) /* bytes = 512 KiB */ + +static void gdata_upload_stream_constructed (GObject *object); +static void gdata_upload_stream_dispose (GObject *object); +static void gdata_upload_stream_finalize (GObject *object); +static void gdata_upload_stream_get_property (GObject *object, guint property_id, GValue *value, GParamSpec *pspec); +static void gdata_upload_stream_set_property (GObject *object, guint property_id, const GValue *value, GParamSpec *pspec); + +static gssize gdata_upload_stream_write (GOutputStream *stream, const void *buffer, gsize count, GCancellable *cancellable, GError **error); +static gboolean gdata_upload_stream_flush (GOutputStream *stream, GCancellable *cancellable, GError **error); +static gboolean gdata_upload_stream_close (GOutputStream *stream, GCancellable *cancellable, GError **error); + +static void create_network_thread (GDataUploadStream *self, GError **error); + +typedef enum { + STATE_INITIAL_REQUEST, /* initial POST request to the resumable-create-media link (unused for non-resumable uploads) */ + STATE_DATA_REQUESTS, /* one or more subsequent PUT requests (only state used for non-resumable uploads) */ + STATE_FINISHED, /* finished successfully or in error */ +} UploadState; + +struct _GDataUploadStreamPrivate { + gchar *method; + gchar *upload_uri; + GDataService *service; + GDataAuthorizationDomain *authorization_domain; + GDataEntry *entry; + gchar *slug; + gchar *content_type; + goffset content_length; /* -1 for non-resumable uploads; 0 or greater for resumable ones */ + SoupSession *session; + SoupMessage *message; + GDataBuffer *buffer; + + GCancellable *cancellable; + GThread *network_thread; + + UploadState state; /* protected by write_mutex */ + GMutex write_mutex; /* mutex for write operations (specifically, write_finished) */ + /* This persists across all resumable upload chunks. Note that it doesn't count bytes from the entry XML. */ + gsize total_network_bytes_written; /* the number of bytes which have been written to the network in STATE_DATA_REQUESTS */ + + /* All of the following apply only to the current resumable upload chunk. */ + gsize message_bytes_outstanding; /* the number of bytes which have been written to the buffer but not libsoup (signalled by write_cond) */ + gsize network_bytes_outstanding; /* the number of bytes which have been written to libsoup but not the network (signalled by write_cond) */ + gsize network_bytes_written; /* the number of bytes which have been written to the network (signalled by write_cond) */ + gsize chunk_size; /* the size of the current chunk (in bytes); 0 iff content_length <= 0; must be <= MAX_RESUMABLE_CHUNK_SIZE */ + GCond write_cond; /* signalled when a chunk has been written (protected by write_mutex) */ + + GCond finished_cond; /* signalled when sending the message (and receiving the response) is finished (protected by response_mutex) */ + guint response_status; /* set once we finish receiving the response (SOUP_STATUS_NONE otherwise) (protected by response_mutex) */ + GError *response_error; /* error asynchronously set by the network thread, and picked up by the main thread when appropriate */ + GMutex response_mutex; /* mutex for ->response_error, ->response_status and ->finished_cond */ +}; + +enum { + PROP_SERVICE = 1, + PROP_UPLOAD_URI, + PROP_ENTRY, + PROP_SLUG, + PROP_CONTENT_TYPE, + PROP_METHOD, + PROP_CANCELLABLE, + PROP_AUTHORIZATION_DOMAIN, + PROP_CONTENT_LENGTH, +}; + +G_DEFINE_TYPE (GDataUploadStream, gdata_upload_stream, G_TYPE_OUTPUT_STREAM) + +static void +gdata_upload_stream_class_init (GDataUploadStreamClass *klass) +{ + GObjectClass *gobject_class = G_OBJECT_CLASS (klass); + GOutputStreamClass *stream_class = G_OUTPUT_STREAM_CLASS (klass); + + g_type_class_add_private (klass, sizeof (GDataUploadStreamPrivate)); + + gobject_class->constructed = gdata_upload_stream_constructed; + gobject_class->dispose = gdata_upload_stream_dispose; + gobject_class->finalize = gdata_upload_stream_finalize; + gobject_class->get_property = gdata_upload_stream_get_property; + gobject_class->set_property = gdata_upload_stream_set_property; + + /* We use the default implementations of the async functions, which just run + * our implementation of the sync function in a thread. */ + stream_class->write_fn = gdata_upload_stream_write; + stream_class->flush = gdata_upload_stream_flush; + stream_class->close_fn = gdata_upload_stream_close; + + /** + * GDataUploadStream:service: + * + * The service which is used to authorize the upload, and to which the upload relates. + * + * Since: 0.5.0 + */ + g_object_class_install_property (gobject_class, PROP_SERVICE, + g_param_spec_object ("service", + "Service", "The service which is used to authorize the upload.", + GDATA_TYPE_SERVICE, + G_PARAM_CONSTRUCT_ONLY | G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)); + + /** + * GDataUploadStream:authorization-domain: + * + * The authorization domain for the upload, against which the #GDataService:authorizer for the #GDataDownloadStream:service should be + * authorized. This may be %NULL if authorization is not needed for the upload. + * + * Since: 0.9.0 + */ + g_object_class_install_property (gobject_class, PROP_AUTHORIZATION_DOMAIN, + g_param_spec_object ("authorization-domain", + "Authorization domain", "The authorization domain for the upload.", + GDATA_TYPE_AUTHORIZATION_DOMAIN, + G_PARAM_CONSTRUCT_ONLY | G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)); + + /** + * GDataUploadStream:method: + * + * The HTTP request method to use when uploading the file. + * + * Since: 0.7.0 + */ + g_object_class_install_property (gobject_class, PROP_METHOD, + g_param_spec_string ("method", + "Method", "The HTTP request method to use when uploading the file.", + NULL, + G_PARAM_CONSTRUCT_ONLY | G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)); + + /** + * GDataUploadStream:upload-uri: + * + * The URI to upload the data and metadata to. This must be HTTPS. + * + * Since: 0.5.0 + */ + g_object_class_install_property (gobject_class, PROP_UPLOAD_URI, + g_param_spec_string ("upload-uri", + "Upload URI", "The URI to upload the data and metadata to.", + NULL, + G_PARAM_CONSTRUCT_ONLY | G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)); + + /** + * GDataUploadStream:entry: + * + * The entry used for metadata to upload. + * + * Since: 0.5.0 + */ + g_object_class_install_property (gobject_class, PROP_ENTRY, + g_param_spec_object ("entry", + "Entry", "The entry used for metadata to upload.", + GDATA_TYPE_ENTRY, + G_PARAM_CONSTRUCT_ONLY | G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)); + + /** + * GDataUploadStream:slug: + * + * The slug of the file being uploaded. This is usually the display name of the file (i.e. as returned by g_file_info_get_display_name()). + * + * Since: 0.5.0 + */ + g_object_class_install_property (gobject_class, PROP_SLUG, + g_param_spec_string ("slug", + "Slug", "The slug of the file being uploaded.", + NULL, + G_PARAM_CONSTRUCT_ONLY | G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)); + + /** + * GDataUploadStream:content-length: + * + * The content length (in bytes) of the file being uploaded (i.e. as returned by g_file_info_get_size()). Note that this does not include the + * length of the XML serialisation of #GDataUploadStream:entry, if set. + * + * If this is -1 the upload will be non-resumable; if it is non-negative, the upload will be resumable. + * + * Since: 0.13.0 + */ + g_object_class_install_property (gobject_class, PROP_CONTENT_LENGTH, + g_param_spec_int64 ("content-length", + "Content length", "The content length (in bytes) of the file being uploaded.", + -1, G_MAXINT64, -1, + G_PARAM_CONSTRUCT_ONLY | G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)); + + /** + * GDataUploadStream:content-type: + * + * The content type of the file being uploaded (i.e. as returned by g_file_info_get_content_type()). + * + * Since: 0.5.0 + */ + g_object_class_install_property (gobject_class, PROP_CONTENT_TYPE, + g_param_spec_string ("content-type", + "Content type", "The content type of the file being uploaded.", + NULL, + G_PARAM_CONSTRUCT_ONLY | G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)); + + /** + * GDataUploadStream:cancellable: + * + * An optional cancellable used to cancel the entire upload operation. If a #GCancellable instance isn't provided for this property at + * construction time (i.e. to gdata_upload_stream_new()), one will be created internally and can be retrieved using + * gdata_upload_stream_get_cancellable() and used to cancel the upload operation with g_cancellable_cancel() just as if it was passed to + * gdata_upload_stream_new(). + * + * If the upload operation is cancelled using this #GCancellable, any ongoing network activity will be stopped, and any pending or future calls + * to #GOutputStream API on the #GDataUploadStream will return %G_IO_ERROR_CANCELLED. Note that the #GCancellable objects which can be passed + * to individual #GOutputStream operations will not cancel the upload operation proper if cancelled — they will merely cancel that API call. + * The only way to cancel the upload operation completely is using #GDataUploadStream:cancellable. + * + * Since: 0.8.0 + */ + g_object_class_install_property (gobject_class, PROP_CANCELLABLE, + g_param_spec_object ("cancellable", + "Cancellable", "An optional cancellable used to cancel the entire upload operation.", + G_TYPE_CANCELLABLE, + G_PARAM_CONSTRUCT_ONLY | G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)); +} + +static void +gdata_upload_stream_init (GDataUploadStream *self) +{ + self->priv = G_TYPE_INSTANCE_GET_PRIVATE (self, GDATA_TYPE_UPLOAD_STREAM, GDataUploadStreamPrivate); + self->priv->buffer = gdata_buffer_new (); + g_mutex_init (&(self->priv->write_mutex)); + g_cond_init (&(self->priv->write_cond)); + g_cond_init (&(self->priv->finished_cond)); + g_mutex_init (&(self->priv->response_mutex)); +} + +static SoupMessage * +build_message (GDataUploadStream *self, const gchar *method, const gchar *upload_uri) +{ + SoupMessage *new_message; + SoupURI *_uri; + + /* Build the message */ + _uri = soup_uri_new (upload_uri); + soup_uri_set_port (_uri, _gdata_service_get_https_port ()); + new_message = soup_message_new_from_uri (method, _uri); + soup_uri_free (_uri); + + /* We don't want to accumulate chunks */ + soup_message_body_set_accumulate (new_message->request_body, FALSE); + + return new_message; +} + +static void +gdata_upload_stream_constructed (GObject *object) +{ + GDataUploadStreamPrivate *priv; + GDataServiceClass *service_klass; + SoupURI *uri = NULL; + + /* Chain up to the parent class */ + G_OBJECT_CLASS (gdata_upload_stream_parent_class)->constructed (object); + priv = GDATA_UPLOAD_STREAM (object)->priv; + + /* The upload URI must be HTTPS. */ + uri = soup_uri_new (priv->upload_uri); + g_assert_cmpstr (soup_uri_get_scheme (uri), ==, SOUP_URI_SCHEME_HTTPS); + soup_uri_free (uri); + + /* Create a #GCancellable for the entire upload operation if one wasn't specified for #GDataUploadStream:cancellable during construction */ + if (priv->cancellable == NULL) + priv->cancellable = g_cancellable_new (); + + /* Build the message */ + priv->message = build_message (GDATA_UPLOAD_STREAM (object), priv->method, priv->upload_uri); + + if (priv->slug != NULL) + soup_message_headers_append (priv->message->request_headers, "Slug", priv->slug); + + if (priv->content_length == -1) { + /* Non-resumable upload */ + soup_message_headers_set_encoding (priv->message->request_headers, SOUP_ENCODING_CHUNKED); + + /* The Content-Type should be multipart/related if we're also uploading the metadata (entry != NULL), + * and the given content_type otherwise. */ + if (priv->entry != NULL) { + gchar *first_part_header, *upload_data; + gchar *second_part_header; + GDataParsableClass *parsable_klass; + + parsable_klass = GDATA_PARSABLE_GET_CLASS (priv->entry); + g_assert (parsable_klass->get_content_type != NULL); + + soup_message_headers_set_content_type (priv->message->request_headers, "multipart/related; boundary=" BOUNDARY_STRING, NULL); + + if (g_strcmp0 (parsable_klass->get_content_type (), "application/json") == 0) { + upload_data = gdata_parsable_get_json (GDATA_PARSABLE (priv->entry)); + } else { + upload_data = gdata_parsable_get_xml (GDATA_PARSABLE (priv->entry)); + } + + /* Start by writing out the entry; then the thread has something to write to the network when it's created */ + first_part_header = g_strdup_printf ("--" BOUNDARY_STRING "\n" + "Content-Type: %s; charset=UTF-8\n\n", + parsable_klass->get_content_type ()); + second_part_header = g_strdup_printf ("\n--" BOUNDARY_STRING "\n" + "Content-Type: %s\n" + "Content-Transfer-Encoding: binary\n\n", + priv->content_type); + + /* Push the message parts onto the message body; we can skip the buffer, since the network thread hasn't yet been created, + * so we're the sole thread accessing the SoupMessage. */ + soup_message_body_append (priv->message->request_body, + SOUP_MEMORY_TAKE, + first_part_header, + strlen (first_part_header)); + soup_message_body_append (priv->message->request_body, + SOUP_MEMORY_TAKE, upload_data, + strlen (upload_data)); + soup_message_body_append (priv->message->request_body, + SOUP_MEMORY_TAKE, + second_part_header, + strlen (second_part_header)); + + first_part_header = NULL; + upload_data = NULL; + second_part_header = NULL; + + priv->network_bytes_outstanding = priv->message->request_body->length; + } else { + soup_message_headers_set_content_type (priv->message->request_headers, priv->content_type, NULL); + } + + /* Non-resumable uploads start with the data requests immediately. */ + priv->state = STATE_DATA_REQUESTS; + } else { + gchar *content_length_str; + + /* Resumable upload's initial request */ + soup_message_headers_set_encoding (priv->message->request_headers, SOUP_ENCODING_CONTENT_LENGTH); + soup_message_headers_replace (priv->message->request_headers, "X-Upload-Content-Type", priv->content_type); + + content_length_str = g_strdup_printf ("%" G_GOFFSET_FORMAT, priv->content_length); + soup_message_headers_replace (priv->message->request_headers, "X-Upload-Content-Length", content_length_str); + g_free (content_length_str); + + if (priv->entry != NULL) { + GDataParsableClass *parsable_klass; + gchar *content_type, *upload_data; + + parsable_klass = GDATA_PARSABLE_GET_CLASS (priv->entry); + g_assert (parsable_klass->get_content_type != NULL); + + if (g_strcmp0 (parsable_klass->get_content_type (), "application/json") == 0) { + upload_data = gdata_parsable_get_json (GDATA_PARSABLE (priv->entry)); + } else { + upload_data = gdata_parsable_get_xml (GDATA_PARSABLE (priv->entry)); + } + + content_type = g_strdup_printf ("%s; charset=UTF-8", + parsable_klass->get_content_type ()); + soup_message_headers_set_content_type (priv->message->request_headers, + content_type, + NULL); + g_free (content_type); + + soup_message_body_append (priv->message->request_body, + SOUP_MEMORY_TAKE, + upload_data, + strlen (upload_data)); + upload_data = NULL; + + priv->network_bytes_outstanding = priv->message->request_body->length; + } else { + soup_message_headers_set_content_length (priv->message->request_headers, 0); + } + + /* Resumable uploads always start with an initial request, which either contains the XML or is empty. */ + priv->state = STATE_INITIAL_REQUEST; + priv->chunk_size = MIN (priv->content_length, MAX_RESUMABLE_CHUNK_SIZE); + } + + /* Make sure the headers are set. HACK: This should actually be in build_message(), but we have to work around + * http://code.google.com/a/google.com/p/apps-api-issues/issues/detail?id=3033 in GDataDocumentsService's append_query_headers(). */ + service_klass = GDATA_SERVICE_GET_CLASS (priv->service); + if (service_klass->append_query_headers != NULL) { + service_klass->append_query_headers (priv->service, priv->authorization_domain, priv->message); + } + + /* If the entry exists and has an ETag, we assume we're updating the entry, so we can set the If-Match header */ + if (priv->entry != NULL && gdata_entry_get_etag (priv->entry) != NULL) + soup_message_headers_append (priv->message->request_headers, "If-Match", gdata_entry_get_etag (priv->entry)); + + /* Uploading doesn't actually start until the first call to write() */ +} + +static void +gdata_upload_stream_dispose (GObject *object) +{ + GDataUploadStreamPrivate *priv = GDATA_UPLOAD_STREAM (object)->priv; + + /* Close the stream before unreffing things like priv->service, which stops crashes like bgo#602156 if the stream is unreffed in the middle + * of network operations */ + g_output_stream_close (G_OUTPUT_STREAM (object), NULL, NULL); + + if (priv->cancellable != NULL) + g_object_unref (priv->cancellable); + priv->cancellable = NULL; + + if (priv->service != NULL) + g_object_unref (priv->service); + priv->service = NULL; + + if (priv->authorization_domain != NULL) + g_object_unref (priv->authorization_domain); + priv->authorization_domain = NULL; + + if (priv->message != NULL) + g_object_unref (priv->message); + priv->message = NULL; + + if (priv->entry != NULL) + g_object_unref (priv->entry); + priv->entry = NULL; + + /* Chain up to the parent class */ + G_OBJECT_CLASS (gdata_upload_stream_parent_class)->dispose (object); +} + +static void +gdata_upload_stream_finalize (GObject *object) +{ + GDataUploadStreamPrivate *priv = GDATA_UPLOAD_STREAM (object)->priv; + + g_mutex_clear (&(priv->response_mutex)); + g_cond_clear (&(priv->finished_cond)); + g_cond_clear (&(priv->write_cond)); + g_mutex_clear (&(priv->write_mutex)); + gdata_buffer_free (priv->buffer); + g_clear_error (&(priv->response_error)); + g_free (priv->upload_uri); + g_free (priv->method); + g_free (priv->slug); + g_free (priv->content_type); + + /* Chain up to the parent class */ + G_OBJECT_CLASS (gdata_upload_stream_parent_class)->finalize (object); +} + +static void +gdata_upload_stream_get_property (GObject *object, guint property_id, GValue *value, GParamSpec *pspec) +{ + GDataUploadStreamPrivate *priv = GDATA_UPLOAD_STREAM (object)->priv; + + switch (property_id) { + case PROP_SERVICE: + g_value_set_object (value, priv->service); + break; + case PROP_AUTHORIZATION_DOMAIN: + g_value_set_object (value, priv->authorization_domain); + break; + case PROP_METHOD: + g_value_set_string (value, priv->method); + break; + case PROP_UPLOAD_URI: + g_value_set_string (value, priv->upload_uri); + break; + case PROP_ENTRY: + g_value_set_object (value, priv->entry); + break; + case PROP_SLUG: + g_value_set_string (value, priv->slug); + break; + case PROP_CONTENT_TYPE: + g_value_set_string (value, priv->content_type); + break; + case PROP_CONTENT_LENGTH: + g_value_set_int64 (value, priv->content_length); + break; + case PROP_CANCELLABLE: + g_value_set_object (value, priv->cancellable); + break; + default: + /* We don't have any other property... */ + G_OBJECT_WARN_INVALID_PROPERTY_ID (object, property_id, pspec); + break; + } +} + +static void +gdata_upload_stream_set_property (GObject *object, guint property_id, const GValue *value, GParamSpec *pspec) +{ + GDataUploadStreamPrivate *priv = GDATA_UPLOAD_STREAM (object)->priv; + + switch (property_id) { + case PROP_SERVICE: + priv->service = g_value_dup_object (value); + priv->session = _gdata_service_get_session (priv->service); + break; + case PROP_AUTHORIZATION_DOMAIN: + priv->authorization_domain = g_value_dup_object (value); + break; + case PROP_METHOD: + priv->method = g_value_dup_string (value); + break; + case PROP_UPLOAD_URI: + priv->upload_uri = g_value_dup_string (value); + break; + case PROP_ENTRY: + priv->entry = g_value_dup_object (value); + break; + case PROP_SLUG: + priv->slug = g_value_dup_string (value); + break; + case PROP_CONTENT_TYPE: + priv->content_type = g_value_dup_string (value); + break; + case PROP_CONTENT_LENGTH: + priv->content_length = g_value_get_int64 (value); + break; + case PROP_CANCELLABLE: + /* Construction only */ + priv->cancellable = g_value_dup_object (value); + break; + default: + /* We don't have any other property... */ + G_OBJECT_WARN_INVALID_PROPERTY_ID (object, property_id, pspec); + break; + } +} + +typedef struct { + GDataUploadStream *upload_stream; + gboolean *cancelled; +} CancelledData; + +static void +write_cancelled_cb (GCancellable *cancellable, CancelledData *data) +{ + GDataUploadStreamPrivate *priv = data->upload_stream->priv; + + /* Signal the gdata_upload_stream_write() function that it should stop blocking and cancel */ + g_mutex_lock (&(priv->write_mutex)); + *(data->cancelled) = TRUE; + g_cond_signal (&(priv->write_cond)); + g_mutex_unlock (&(priv->write_mutex)); +} + +static gssize +gdata_upload_stream_write (GOutputStream *stream, const void *buffer, gsize count, GCancellable *cancellable, GError **error_out) +{ + GDataUploadStreamPrivate *priv = GDATA_UPLOAD_STREAM (stream)->priv; + gssize length_written = -1; + gulong cancelled_signal = 0, global_cancelled_signal = 0; + gboolean cancelled = FALSE; /* must only be touched with ->write_mutex held */ + gsize old_total_network_bytes_written; + CancelledData data; + GError *error = NULL; + + /* Listen for cancellation events */ + data.upload_stream = GDATA_UPLOAD_STREAM (stream); + data.cancelled = &cancelled; + + global_cancelled_signal = g_cancellable_connect (priv->cancellable, (GCallback) write_cancelled_cb, &data, NULL); + + if (cancellable != NULL) + cancelled_signal = g_cancellable_connect (cancellable, (GCallback) write_cancelled_cb, &data, NULL); + + /* Check for an error and return if necessary */ + g_mutex_lock (&(priv->write_mutex)); + + if (cancelled == TRUE) { + g_assert (g_cancellable_set_error_if_cancelled (cancellable, &error) == TRUE || + g_cancellable_set_error_if_cancelled (priv->cancellable, &error) == TRUE); + g_mutex_unlock (&(priv->write_mutex)); + + length_written = -1; + goto done; + } + + g_mutex_unlock (&(priv->write_mutex)); + + /* Increment the number of bytes outstanding for the new write, and keep a record of the old number written so we know if the write's + * finished before we reach write_cond. */ + old_total_network_bytes_written = priv->total_network_bytes_written; + priv->message_bytes_outstanding += count; + + /* Handle the more common case of the network thread already having been created first */ + if (priv->network_thread != NULL) { + /* Push the new data into the buffer */ + gdata_buffer_push_data (priv->buffer, buffer, count); + goto write; + } + + /* Write out the first chunk of data, so there's guaranteed to be something in the buffer */ + gdata_buffer_push_data (priv->buffer, buffer, count); + + /* Create the thread and let the writing commence! */ + create_network_thread (GDATA_UPLOAD_STREAM (stream), &error); + if (priv->network_thread == NULL) { + length_written = -1; + goto done; + } + +write: + g_mutex_lock (&(priv->write_mutex)); + + /* Wait for it to be written */ + while (priv->total_network_bytes_written - old_total_network_bytes_written < count && cancelled == FALSE && priv->state != STATE_FINISHED) { + g_cond_wait (&(priv->write_cond), &(priv->write_mutex)); + } + length_written = MIN (count, priv->total_network_bytes_written - old_total_network_bytes_written); + + /* Check for an error and return if necessary */ + if (cancelled == TRUE && length_written < 1) { + /* Cancellation. */ + g_assert (g_cancellable_set_error_if_cancelled (cancellable, &error) == TRUE || + g_cancellable_set_error_if_cancelled (priv->cancellable, &error) == TRUE); + length_written = -1; + } else if (priv->state == STATE_FINISHED && (length_written < 0 || (gsize) length_written < count)) { + /* Resumable upload error. */ + g_set_error (&error, G_IO_ERROR, G_IO_ERROR_FAILED, _("Error received from server after uploading a resumable upload chunk.")); + length_written = -1; + } + + g_mutex_unlock (&(priv->write_mutex)); + +done: + /* Disconnect from the cancelled signals. Note that we have to do this with @write_mutex not held, as g_cancellable_disconnect() blocks + * until any outstanding cancellation callbacks return, and they will block on @write_mutex. */ + if (cancelled_signal != 0) + g_cancellable_disconnect (cancellable, cancelled_signal); + if (global_cancelled_signal != 0) + g_cancellable_disconnect (priv->cancellable, global_cancelled_signal); + + g_assert (error != NULL || length_written > 0); + + if (error != NULL) { + g_propagate_error (error_out, error); + } + + return length_written; +} + +static void +flush_cancelled_cb (GCancellable *cancellable, CancelledData *data) +{ + GDataUploadStreamPrivate *priv = data->upload_stream->priv; + + /* Signal the gdata_upload_stream_flush() function that it should stop blocking and cancel */ + g_mutex_lock (&(priv->write_mutex)); + *(data->cancelled) = TRUE; + g_cond_signal (&(priv->write_cond)); + g_mutex_unlock (&(priv->write_mutex)); +} + +/* Block until ->network_bytes_outstanding reaches zero. Cancelling the cancellable passed to gdata_upload_stream_flush() breaks out of the wait(), + * but doesn't stop the network thread from continuing to write the remaining bytes to the network. + * The wrapper function, g_output_stream_flush(), calls g_output_stream_set_pending() before calling this function, and calls + * g_output_stream_clear_pending() afterwards, so we don't need to worry about other operations happening concurrently. We also don't need to worry + * about being called after the stream has been closed (though the network activity could finish before or during this function). */ +static gboolean +gdata_upload_stream_flush (GOutputStream *stream, GCancellable *cancellable, GError **error) +{ + GDataUploadStreamPrivate *priv = GDATA_UPLOAD_STREAM (stream)->priv; + gulong cancelled_signal = 0, global_cancelled_signal = 0; + gboolean cancelled = FALSE; /* must only be touched with ->write_mutex held */ + gboolean success = TRUE; + CancelledData data; + + /* Listen for cancellation events */ + data.upload_stream = GDATA_UPLOAD_STREAM (stream); + data.cancelled = &cancelled; + + global_cancelled_signal = g_cancellable_connect (priv->cancellable, (GCallback) flush_cancelled_cb, &data, NULL); + + if (cancellable != NULL) + cancelled_signal = g_cancellable_connect (cancellable, (GCallback) flush_cancelled_cb, &data, NULL); + + /* Create the thread if it hasn't been created already. This can happen if flush() is called immediately after creating the stream. */ + if (priv->network_thread == NULL) { + create_network_thread (GDATA_UPLOAD_STREAM (stream), error); + if (priv->network_thread == NULL) { + success = FALSE; + goto done; + } + } + + /* Start the flush operation proper */ + g_mutex_lock (&(priv->write_mutex)); + + /* Wait for all outstanding bytes to be written to the network */ + while (priv->network_bytes_outstanding > 0 && cancelled == FALSE && priv->state != STATE_FINISHED) { + g_cond_wait (&(priv->write_cond), &(priv->write_mutex)); + } + + /* Check for an error and return if necessary */ + if (cancelled == TRUE) { + g_assert (g_cancellable_set_error_if_cancelled (cancellable, error) == TRUE || + g_cancellable_set_error_if_cancelled (priv->cancellable, error) == TRUE); + success = FALSE; + } else if (priv->state == STATE_FINISHED && priv->network_bytes_outstanding > 0) { + /* Resumable upload error. */ + g_set_error (error, G_IO_ERROR, G_IO_ERROR_FAILED, _("Error received from server after uploading a resumable upload chunk.")); + success = FALSE; + } + + g_mutex_unlock (&(priv->write_mutex)); + +done: + /* Disconnect from the cancelled signals. Note that we have to do this without @write_mutex held, as g_cancellable_disconnect() blocks + * until any outstanding cancellation callbacks return, and they will block on @write_mutex. */ + if (cancelled_signal != 0) + g_cancellable_disconnect (cancellable, cancelled_signal); + if (global_cancelled_signal != 0) + g_cancellable_disconnect (priv->cancellable, global_cancelled_signal); + + return success; +} + +static void +close_cancelled_cb (GCancellable *cancellable, CancelledData *data) +{ + GDataUploadStreamPrivate *priv = data->upload_stream->priv; + + /* Signal the gdata_upload_stream_close() function that it should stop blocking and cancel */ + g_mutex_lock (&(priv->response_mutex)); + *(data->cancelled) = TRUE; + g_cond_signal (&(priv->finished_cond)); + g_mutex_unlock (&(priv->response_mutex)); +} + +/* It's guaranteed that we have set ->response_status and ->response_error and are done with *all* network activity before this returns, unless it's + * cancelled. This means that it's safe to call gdata_upload_stream_get_response() once a call to close() has returned without being cancelled. + * + * Even though calling g_output_stream_close() multiple times on this stream is guaranteed to call gdata_upload_stream_close() at most once, other + * GIO methods (notably g_output_stream_splice()) can call gdata_upload_stream_close() directly. Consequently, we need to be careful to be idempotent + * after the first call. + * + * If the network thread hasn't yet been started (i.e. gdata_upload_stream_write() hasn't been called at all yet), %TRUE will be returned immediately. + * + * If the global cancellable, ->cancellable, or @cancellable are cancelled before the call to gdata_upload_stream_close(), gdata_upload_stream_close() + * should return immediately with %G_IO_ERROR_CANCELLED. If they're cancelled during the call, gdata_upload_stream_close() should stop waiting for + * any outstanding data to be flushed to the network and return %G_IO_ERROR_CANCELLED (though the operation to finish off network activity and close + * the stream will still continue). + * + * If the call to gdata_upload_stream_close() is not cancelled by any #GCancellable, it will wait until all the data has been flushed to the network + * and a response has been received. At this point, ->response_status and ->response_error have been set (and won't ever change) and we can return + * either success or an error code. */ +static gboolean +gdata_upload_stream_close (GOutputStream *stream, GCancellable *cancellable, GError **error) +{ + GDataUploadStreamPrivate *priv = GDATA_UPLOAD_STREAM (stream)->priv; + gboolean success = TRUE; + gboolean cancelled = FALSE; /* must only be touched with ->response_mutex held */ + gulong cancelled_signal = 0, global_cancelled_signal = 0; + CancelledData data; + gboolean is_finished; + GError *child_error = NULL; + + /* If the operation was never started, return successfully immediately */ + if (priv->network_thread == NULL) + return TRUE; + + /* If we've already closed the stream, return G_IO_ERROR_CLOSED */ + g_mutex_lock (&(priv->response_mutex)); + + if (priv->response_status != SOUP_STATUS_NONE) { + g_mutex_unlock (&(priv->response_mutex)); + g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_CLOSED, _("Stream is already closed")); + return FALSE; + } + + g_mutex_unlock (&(priv->response_mutex)); + + /* Allow cancellation */ + data.upload_stream = GDATA_UPLOAD_STREAM (stream); + data.cancelled = &cancelled; + + global_cancelled_signal = g_cancellable_connect (priv->cancellable, (GCallback) close_cancelled_cb, &data, NULL); + + if (cancellable != NULL) + cancelled_signal = g_cancellable_connect (cancellable, (GCallback) close_cancelled_cb, &data, NULL); + + g_mutex_lock (&(priv->response_mutex)); + + g_mutex_lock (&(priv->write_mutex)); + is_finished = (priv->state == STATE_FINISHED); + g_mutex_unlock (&(priv->write_mutex)); + + /* If an operation is still in progress, the upload thread hasn't finished yet… */ + if (!is_finished) { + /* We've reached the end of the stream, so append the footer if the entire operation hasn't been cancelled. */ + if (priv->entry != NULL && g_cancellable_is_cancelled (priv->cancellable) == FALSE) { + const gchar *footer = "\n--" BOUNDARY_STRING "--"; + gsize footer_length = strlen (footer); + + gdata_buffer_push_data (priv->buffer, (const guint8*) footer, footer_length); + + g_mutex_lock (&(priv->write_mutex)); + priv->message_bytes_outstanding += footer_length; + g_mutex_unlock (&(priv->write_mutex)); + } + + /* Mark the buffer as having reached EOF, and the write operation will close in its own time */ + gdata_buffer_push_data (priv->buffer, NULL, 0); + + /* Wait for the signal that we've finished. Cancelling the call to gdata_upload_stream_close() will cause this wait to be aborted, + * but won't actually prevent the stream being closed (i.e. all it means is that the stream isn't guaranteed to have been closed by + * the time gdata_upload_stream_close() returns — whereas normally it would be). */ + if (cancelled == FALSE) { + g_cond_wait (&(priv->finished_cond), &(priv->response_mutex)); + } + } + + g_assert (priv->response_status == SOUP_STATUS_NONE); + g_assert (priv->response_error == NULL); + + g_mutex_lock (&(priv->write_mutex)); + is_finished = (priv->state == STATE_FINISHED); + g_mutex_unlock (&(priv->write_mutex)); + + /* Error handling */ + if (!is_finished && cancelled == TRUE) { + /* Cancelled? If ->state == STATE_FINISHED, the network activity finished before the gdata_upload_stream_close() operation was + * cancelled, so we don't need to return an error. */ + g_assert (g_cancellable_set_error_if_cancelled (cancellable, &child_error) == TRUE || + g_cancellable_set_error_if_cancelled (priv->cancellable, &child_error) == TRUE); + priv->response_status = SOUP_STATUS_CANCELLED; + success = FALSE; + } else if (SOUP_STATUS_IS_SUCCESSFUL (priv->message->status_code) == FALSE) { + GDataServiceClass *klass = GDATA_SERVICE_GET_CLASS (priv->service); + + /* Parse the error */ + g_assert (klass->parse_error_response != NULL); + klass->parse_error_response (priv->service, GDATA_OPERATION_UPLOAD, priv->message->status_code, priv->message->reason_phrase, + priv->message->response_body->data, priv->message->response_body->length, &child_error); + priv->response_status = priv->message->status_code; + success = FALSE; + } else { + /* Success! Set the response status */ + priv->response_status = priv->message->status_code; + } + + g_assert (priv->response_status != SOUP_STATUS_NONE && (SOUP_STATUS_IS_SUCCESSFUL (priv->response_status) || child_error != NULL)); + + g_mutex_unlock (&(priv->response_mutex)); + + /* Disconnect from the signal handler. Note that we have to do this with @response_mutex not held, as g_cancellable_disconnect() blocks + * until any outstanding cancellation callbacks return, and they will block on @response_mutex. */ + if (cancelled_signal != 0) + g_cancellable_disconnect (cancellable, cancelled_signal); + if (global_cancelled_signal != 0) + g_cancellable_disconnect (priv->cancellable, global_cancelled_signal); + + g_assert ((success == TRUE && child_error == NULL) || (success == FALSE && child_error != NULL)); + + if (child_error != NULL) + g_propagate_error (error, child_error); + + return success; +} + +/* In the network thread context, called just after writing the headers, or just after writing a chunk, to write the next chunk to libsoup. + * We don't let it return until we've finished pushing all the data into the buffer. + * This is due to http://bugzilla.gnome.org/show_bug.cgi?id=522147, which means that + * we can't use soup_session_(un)?pause_message() with a SoupSessionSync. + * If we don't return from this signal handler, the message is never paused, and thus + * Bad Things don't happen (due to the bug, messages can be paused, but not unpaused). + * Obviously this means that our memory usage will increase, and we'll eventually end + * up storing the entire request body in memory, but that's unavoidable at this point. */ +static void +write_next_chunk (GDataUploadStream *self, SoupMessage *message) +{ + #define CHUNK_SIZE 8192 /* 8KiB */ + + GDataUploadStreamPrivate *priv = self->priv; + gboolean has_network_bytes_outstanding, is_complete; + gsize length; + gboolean reached_eof = FALSE; + guint8 next_buffer[CHUNK_SIZE]; + + g_mutex_lock (&(priv->write_mutex)); + has_network_bytes_outstanding = (priv->network_bytes_outstanding > 0); + is_complete = (priv->state == STATE_INITIAL_REQUEST || + (priv->content_length != -1 && priv->network_bytes_written + priv->network_bytes_outstanding == priv->chunk_size)); + g_mutex_unlock (&(priv->write_mutex)); + + /* If there are still bytes in libsoup's buffer, don't block on getting new bytes into the stream. Also, if we're making the initial request + * of a resumable upload, don't push new data onto the network, since all of the XML was pushed into the buffer when we started. */ + if (has_network_bytes_outstanding) { + return; + } else if (is_complete) { + soup_message_body_complete (priv->message->request_body); + + return; + } + + /* Append the next chunk to the message body so it can join in the fun. + * Note that this call isn't necessarily blocking, and can return less than the CHUNK_SIZE. This is because + * we could deadlock if we block on getting CHUNK_SIZE bytes at the end of the stream. write() could + * easily be called with fewer bytes, but has no way to notify us that we've reached the end of the + * stream, so we'd happily block on receiving more bytes which weren't forthcoming. + * + * Note also that we can't block on this call with write_mutex locked, or we could get into a deadlock if the stream is flushed at the same + * time (in the case that we don't know the content length ahead of time). */ + if (priv->content_length == -1) { + /* Non-resumable upload. */ + length = gdata_buffer_pop_data_limited (priv->buffer, next_buffer, CHUNK_SIZE, &reached_eof); + } else { + /* Resumable upload. Ensure we don't exceed the chunk size. */ + length = gdata_buffer_pop_data_limited (priv->buffer, next_buffer, + MIN (CHUNK_SIZE, priv->chunk_size - (priv->network_bytes_written + + priv->network_bytes_outstanding)), &reached_eof); + } + + g_mutex_lock (&(priv->write_mutex)); + + priv->message_bytes_outstanding -= length; + priv->network_bytes_outstanding += length; + + /* Append whatever data was returned */ + if (length > 0) + soup_message_body_append (priv->message->request_body, SOUP_MEMORY_COPY, next_buffer, length); + + /* Finish off the request body if we've reached EOF (i.e. the stream has been closed), or if we're doing a resumable upload and we reach + * the maximum chunk size. */ + if (reached_eof == TRUE || + (priv->content_length != -1 && priv->network_bytes_written + priv->network_bytes_outstanding == priv->chunk_size)) { + g_assert (reached_eof == FALSE || priv->message_bytes_outstanding == 0); + + soup_message_body_complete (priv->message->request_body); + } + + g_mutex_unlock (&(priv->write_mutex)); +} + +static void +wrote_headers_cb (SoupMessage *message, GDataUploadStream *self) +{ + GDataUploadStreamPrivate *priv = self->priv; + + /* Signal the main thread that the headers have been written */ + g_mutex_lock (&(priv->write_mutex)); + g_cond_signal (&(priv->write_cond)); + g_mutex_unlock (&(priv->write_mutex)); + + /* Send the first chunk to libsoup */ + write_next_chunk (self, message); +} + +static void +wrote_body_data_cb (SoupMessage *message, SoupBuffer *buffer, GDataUploadStream *self) +{ + GDataUploadStreamPrivate *priv = self->priv; + + /* Signal the main thread that the chunk has been written */ + g_mutex_lock (&(priv->write_mutex)); + g_assert (priv->network_bytes_outstanding > 0); + priv->network_bytes_outstanding -= buffer->length; + priv->network_bytes_written += buffer->length; + + if (priv->state == STATE_DATA_REQUESTS) { + priv->total_network_bytes_written += buffer->length; + } + + g_cond_signal (&(priv->write_cond)); + g_mutex_unlock (&(priv->write_mutex)); + + /* Send the next chunk to libsoup */ + write_next_chunk (self, message); +} + +static gpointer +upload_thread (GDataUploadStream *self) +{ + GDataUploadStreamPrivate *priv = self->priv; + GDataAuthorizer *authorizer; + + g_assert (priv->cancellable != NULL); + + /* FIXME: Refresh authorization before sending message in order to prevent authorization errors during transfer. + * See: https://gitlab.gnome.org/GNOME/libgdata/issues/23 */ + authorizer = gdata_service_get_authorizer (priv->service); + if (authorizer) { + g_autoptr(GError) error = NULL; + + gdata_authorizer_refresh_authorization (authorizer, priv->cancellable, &error); + if (error != NULL) + g_debug ("Error returned when refreshing authorization: %s", error->message); + else + gdata_authorizer_process_request (authorizer, priv->authorization_domain, priv->message); + } + + while (TRUE) { + GDataServiceClass *klass; + gulong wrote_headers_signal, wrote_body_data_signal; + gchar *new_uri; + SoupMessage *new_message; + gsize next_chunk_length; + + /* Connect to the wrote-* signals so we can prepare the next chunk for transmission */ + wrote_headers_signal = g_signal_connect (priv->message, "wrote-headers", (GCallback) wrote_headers_cb, self); + wrote_body_data_signal = g_signal_connect (priv->message, "wrote-body-data", (GCallback) wrote_body_data_cb, self); + + _gdata_service_actually_send_message (priv->session, priv->message, priv->cancellable, NULL); + + g_mutex_lock (&(priv->write_mutex)); + + /* If this is a resumable upload, continue to the next chunk. If it's a non-resumable upload, we're done. We have several cases: + * • Non-resumable upload: + * - Content only: STATE_DATA_REQUESTS → STATE_FINISHED + * - Metadata only: not supported + * - Content and metadata: STATE_DATA_REQUESTS → STATE_FINISHED + * • Resumable upload: + * - Content only: + * * STATE_INITIAL_REQUEST → STATE_DATA_REQUESTS + * * STATE_DATA_REQUESTS → STATE_DATA_REQUESTS + * * STATE_DATA_REQUESTS → STATE_FINISHED + * - Metadata only: STATE_INITIAL_REQUEST → STATE_FINISHED + * - Content and metadata: + * * STATE_INITIAL_REQUEST → STATE_DATA_REQUESTS + * * STATE_DATA_REQUESTS → STATE_DATA_REQUESTS + * * STATE_DATA_REQUESTS → STATE_FINISHED + */ + switch (priv->state) { + case STATE_INITIAL_REQUEST: + /* We're either a content-only or a content-and-metadata resumable upload. */ + priv->state = STATE_DATA_REQUESTS; + + /* Check the response. On success it should be empty, status 200, with a Location header telling us where to upload + * next. If it's an error response, bail out and let the code in gdata_upload_stream_close() parse the error..*/ + if (!SOUP_STATUS_IS_SUCCESSFUL (priv->message->status_code)) { + goto finished; + } else if (priv->content_length == 0 && priv->message->status_code == SOUP_STATUS_CREATED) { + /* If this was a metadata-only upload, we're done. */ + goto finished; + } + + /* Fall out and prepare the next message */ + g_assert (priv->total_network_bytes_written == 0); /* haven't written any data yet */ + + break; + case STATE_DATA_REQUESTS: + /* Check the response. On completion it should contain the resulting entry's XML, status 201. On continuation it should + * be empty, status 308, with a Range header and potentially a Location header telling us what/where to upload next. + * If it's an error response, bail out and let the code in gdata_upload_stream_close() parse the error..*/ + if (priv->message->status_code == 308) { + /* Continuation: fall out and prepare the next message */ + g_assert (priv->content_length == -1 || priv->total_network_bytes_written < (gsize) priv->content_length); + } else if (SOUP_STATUS_IS_SUCCESSFUL (priv->message->status_code)) { + /* Completion. Check the server isn't misbehaving. */ + g_assert (priv->content_length == -1 || priv->total_network_bytes_written == (gsize) priv->content_length); + + goto finished; + } else { + /* Error */ + goto finished; + } + + /* Fall out and prepare the next message */ + g_assert (priv->total_network_bytes_written > 0); + + break; + case STATE_FINISHED: + default: + g_assert_not_reached (); + } + + /* Prepare the next message. */ + g_assert (priv->content_length != -1); + + next_chunk_length = MIN (priv->content_length - priv->total_network_bytes_written, MAX_RESUMABLE_CHUNK_SIZE); + + new_uri = g_strdup (soup_message_headers_get_one (priv->message->response_headers, "Location")); + if (new_uri == NULL) { + new_uri = soup_uri_to_string (soup_message_get_uri (priv->message), FALSE); + } + + new_message = build_message (self, SOUP_METHOD_PUT, new_uri); + + g_free (new_uri); + + soup_message_headers_set_encoding (new_message->request_headers, SOUP_ENCODING_CONTENT_LENGTH); + soup_message_headers_set_content_type (new_message->request_headers, priv->content_type, NULL); + soup_message_headers_set_content_length (new_message->request_headers, next_chunk_length); + soup_message_headers_set_content_range (new_message->request_headers, priv->total_network_bytes_written, + priv->total_network_bytes_written + next_chunk_length - 1, priv->content_length); + + /* Make sure the headers are set. HACK: This should actually be in build_message(), but we have to work around + * http://code.google.com/a/google.com/p/apps-api-issues/issues/detail?id=3033 in GDataDocumentsService's append_query_headers(). */ + klass = GDATA_SERVICE_GET_CLASS (priv->service); + if (klass->append_query_headers != NULL) { + klass->append_query_headers (priv->service, priv->authorization_domain, new_message); + } + + g_signal_handler_disconnect (priv->message, wrote_body_data_signal); + g_signal_handler_disconnect (priv->message, wrote_headers_signal); + + g_object_unref (priv->message); + priv->message = new_message; + + /* Reset various counters for the next upload. Note that message_bytes_outstanding may be > 0 at this point, since the client may + * have pushed some content into the buffer while we were waiting for the response to this request. */ + g_assert (priv->network_bytes_outstanding == 0); + priv->chunk_size = next_chunk_length; + priv->network_bytes_written = 0; + + /* Loop round and upload this chunk now. */ + g_mutex_unlock (&(priv->write_mutex)); + + continue; + +finished: + g_mutex_unlock (&(priv->write_mutex)); + + goto finished_outer; + } + +finished_outer: + /* Signal that the operation has finished (either successfully or in error). + * Also signal write_cond, just in case we errored out and finished sending in the middle of a write. */ + g_mutex_lock (&(priv->write_mutex)); + priv->state = STATE_FINISHED; + g_cond_signal (&(priv->write_cond)); + g_mutex_unlock (&(priv->write_mutex)); + + g_cond_signal (&(priv->finished_cond)); + + /* Referenced in create_network_thread(). */ + g_object_unref (self); + + return NULL; +} + +static void +create_network_thread (GDataUploadStream *self, GError **error) +{ + GDataUploadStreamPrivate *priv = self->priv; + + g_assert (priv->network_thread == NULL); + g_object_ref (self); /* ownership transferred to thread */ + priv->network_thread = g_thread_try_new ("upload-thread", (GThreadFunc) upload_thread, self, error); +} + +/** + * gdata_upload_stream_new: + * @service: a #GDataService + * @domain: (allow-none): the #GDataAuthorizationDomain to authorize the upload, or %NULL + * @method: the HTTP method to use + * @upload_uri: the URI to upload, which must be HTTPS + * @entry: (allow-none): the entry to upload as metadata, or %NULL + * @slug: the file's slug (filename) + * @content_type: the content type of the file being uploaded + * @cancellable: (allow-none): a #GCancellable for the entire upload stream, or %NULL + * + * Creates a new #GDataUploadStream, allowing a file to be uploaded from a GData service using standard #GOutputStream API. + * + * The HTTP method to use should be specified in @method, and will typically be either %SOUP_METHOD_POST (for insertions) or %SOUP_METHOD_PUT + * (for updates), according to the server and the @upload_uri. + * + * If @entry is specified, it will be attached to the upload as the entry to which the file being uploaded belongs. Otherwise, just the file + * written to the stream will be uploaded, and given a default entry as determined by the server. + * + * @slug and @content_type must be specified before the upload begins, as they describe the file being streamed. @slug is the filename given to the + * file, which will typically be stored on the server and made available when downloading the file again. @content_type must be the correct + * content type for the file, and should be in the service's list of acceptable content types. + * + * As well as the standard GIO errors, calls to the #GOutputStream API on a #GDataUploadStream can also return any relevant specific error from + * #GDataServiceError, or %GDATA_SERVICE_ERROR_PROTOCOL_ERROR in the general case. + * + * If a #GCancellable is provided in @cancellable, the upload operation may be cancelled at any time from another thread using g_cancellable_cancel(). + * In this case, any ongoing network activity will be stopped, and any pending or future calls to #GOutputStream API on the #GDataUploadStream will + * return %G_IO_ERROR_CANCELLED. Note that the #GCancellable objects which can be passed to individual #GOutputStream operations will not cancel the + * upload operation proper if cancelled — they will merely cancel that API call. The only way to cancel the upload operation completely is using this + * @cancellable. + * + * Note that network communication won't begin until the first call to g_output_stream_write() on the #GDataUploadStream. + * + * Return value: a new #GOutputStream, or %NULL; unref with g_object_unref() + * + * Since: 0.9.0 + */ +GOutputStream * +gdata_upload_stream_new (GDataService *service, GDataAuthorizationDomain *domain, const gchar *method, const gchar *upload_uri, GDataEntry *entry, + const gchar *slug, const gchar *content_type, GCancellable *cancellable) +{ + g_return_val_if_fail (GDATA_IS_SERVICE (service), NULL); + g_return_val_if_fail (domain == NULL || GDATA_IS_AUTHORIZATION_DOMAIN (domain), NULL); + g_return_val_if_fail (method != NULL, NULL); + g_return_val_if_fail (upload_uri != NULL, NULL); + g_return_val_if_fail (entry == NULL || GDATA_IS_ENTRY (entry), NULL); + g_return_val_if_fail (slug != NULL, NULL); + g_return_val_if_fail (content_type != NULL, NULL); + g_return_val_if_fail (cancellable == NULL || G_IS_CANCELLABLE (cancellable), NULL); + + /* Create the upload stream */ + return G_OUTPUT_STREAM (g_object_new (GDATA_TYPE_UPLOAD_STREAM, + "method", method, + "upload-uri", upload_uri, + "service", service, + "authorization-domain", domain, + "entry", entry, + "slug", slug, + "content-type", content_type, + "cancellable", cancellable, + NULL)); +} + +/** + * gdata_upload_stream_new_resumable: + * @service: a #GDataService + * @domain: (allow-none): the #GDataAuthorizationDomain to authorize the upload, or %NULL + * @method: the HTTP method to use + * @upload_uri: the URI to upload + * @entry: (allow-none): the entry to upload as metadata, or %NULL + * @slug: the file's slug (filename) + * @content_type: the content type of the file being uploaded + * @content_length: the size (in bytes) of the file being uploaded + * @cancellable: (allow-none): a #GCancellable for the entire upload stream, or %NULL + * + * Creates a new resumable #GDataUploadStream, allowing a file to be uploaded from a GData service using standard #GOutputStream API. The upload will + * use GData's resumable upload API, so should be more reliable than a normal upload (especially if the file is large). See the + * GData documentation on resumable uploads for more + * information. + * + * The HTTP method to use should be specified in @method, and will typically be either %SOUP_METHOD_POST (for insertions) or %SOUP_METHOD_PUT + * (for updates), according to the server and the @upload_uri. + * + * If @entry is specified, it will be attached to the upload as the entry to which the file being uploaded belongs. Otherwise, just the file + * written to the stream will be uploaded, and given a default entry as determined by the server. + * + * @slug, @content_type and @content_length must be specified before the upload begins, as they describe the file being streamed. @slug is the filename + * given to the file, which will typically be stored on the server and made available when downloading the file again. @content_type must be the + * correct content type for the file, and should be in the service's list of acceptable content types. @content_length must be the size of the file + * being uploaded (not including the XML for any associated #GDataEntry) in bytes. Zero is accepted if a metadata-only upload is being performed. + * + * As well as the standard GIO errors, calls to the #GOutputStream API on a #GDataUploadStream can also return any relevant specific error from + * #GDataServiceError, or %GDATA_SERVICE_ERROR_PROTOCOL_ERROR in the general case. + * + * If a #GCancellable is provided in @cancellable, the upload operation may be cancelled at any time from another thread using g_cancellable_cancel(). + * In this case, any ongoing network activity will be stopped, and any pending or future calls to #GOutputStream API on the #GDataUploadStream will + * return %G_IO_ERROR_CANCELLED. Note that the #GCancellable objects which can be passed to individual #GOutputStream operations will not cancel the + * upload operation proper if cancelled — they will merely cancel that API call. The only way to cancel the upload operation completely is using this + * @cancellable. + * + * Note that network communication won't begin until the first call to g_output_stream_write() on the #GDataUploadStream. + * + * Return value: a new #GOutputStream, or %NULL; unref with g_object_unref() + * + * Since: 0.13.0 + */ +GOutputStream * +gdata_upload_stream_new_resumable (GDataService *service, GDataAuthorizationDomain *domain, const gchar *method, const gchar *upload_uri, + GDataEntry *entry, const gchar *slug, const gchar *content_type, goffset content_length, GCancellable *cancellable) +{ + g_return_val_if_fail (GDATA_IS_SERVICE (service), NULL); + g_return_val_if_fail (domain == NULL || GDATA_IS_AUTHORIZATION_DOMAIN (domain), NULL); + g_return_val_if_fail (method != NULL, NULL); + g_return_val_if_fail (upload_uri != NULL, NULL); + g_return_val_if_fail (entry == NULL || GDATA_IS_ENTRY (entry), NULL); + g_return_val_if_fail (slug != NULL, NULL); + g_return_val_if_fail (content_type != NULL, NULL); + g_return_val_if_fail (content_length >= 0, NULL); + g_return_val_if_fail (cancellable == NULL || G_IS_CANCELLABLE (cancellable), NULL); + + /* Create the upload stream */ + return G_OUTPUT_STREAM (g_object_new (GDATA_TYPE_UPLOAD_STREAM, + "method", method, + "upload-uri", upload_uri, + "service", service, + "authorization-domain", domain, + "entry", entry, + "slug", slug, + "content-type", content_type, + "content-length", content_length, + "cancellable", cancellable, + NULL)); +} + +/** + * gdata_upload_stream_get_response: + * @self: a #GDataUploadStream + * @length: (allow-none) (out caller-allocates): return location for the length of the response, or %NULL + * + * Returns the server's response to the upload operation performed by the #GDataUploadStream. If the operation + * is still underway, or the server's response hasn't been received yet, %NULL is returned and @length is set to -1. + * + * If there was an error during the upload operation (but it is complete), %NULL is returned, and @length is set to 0. + * + * While it is safe to call this function from any thread at any time during the network operation, the only way to guarantee that the response has + * been set before calling this function is to have closed the #GDataUploadStream by calling g_output_stream_close() on it, without cancelling + * the close operation. Once the stream has been closed, all network communication is guaranteed to have finished. Note that if a call to + * g_output_stream_close() is cancelled, g_output_stream_is_closed() will immediately start to return %TRUE, even if the #GDataUploadStream is still + * attempting to flush the network buffers asynchronously — consequently, gdata_upload_stream_get_response() may still return %NULL and a @length of + * -1. The only reliable way to determine if the stream has been fully closed in this situation is to check the results + * of gdata_upload_stream_get_response(), rather than g_output_stream_is_closed(). + * + * Return value: the server's response to the upload, or %NULL + * + * Since: 0.5.0 + */ +const gchar * +gdata_upload_stream_get_response (GDataUploadStream *self, gssize *length) +{ + gssize _length; + const gchar *_response; + + g_return_val_if_fail (GDATA_IS_UPLOAD_STREAM (self), NULL); + + g_mutex_lock (&(self->priv->response_mutex)); + + if (self->priv->response_status == SOUP_STATUS_NONE) { + /* We can't touch the message until the network thread has finished using it, since it isn't threadsafe */ + _length = -1; + _response = NULL; + } else if (SOUP_STATUS_IS_SUCCESSFUL (self->priv->response_status) == FALSE) { + /* The response has been received, and was unsuccessful */ + _length = 0; + _response = NULL; + } else { + /* The response has been received, and was successful */ + _length = self->priv->message->response_body->length; + _response = self->priv->message->response_body->data; + } + + g_mutex_unlock (&(self->priv->response_mutex)); + + if (length != NULL) + *length = _length; + return _response; +} + +/** + * gdata_upload_stream_get_service: + * @self: a #GDataUploadStream + * + * Gets the service used to authorize the upload, as passed to gdata_upload_stream_new(). + * + * Return value: (transfer none): the #GDataService used to authorize the upload + * + * Since: 0.5.0 + */ +GDataService * +gdata_upload_stream_get_service (GDataUploadStream *self) +{ + g_return_val_if_fail (GDATA_IS_UPLOAD_STREAM (self), NULL); + return self->priv->service; +} + +/** + * gdata_upload_stream_get_authorization_domain: + * @self: a #GDataUploadStream + * + * Gets the authorization domain used to authorize the upload, as passed to gdata_upload_stream_new(). It may be %NULL if authorization is not + * needed for the upload. + * + * Return value: (transfer none) (allow-none): the #GDataAuthorizationDomain used to authorize the upload, or %NULL + * + * Since: 0.9.0 + */ +GDataAuthorizationDomain * +gdata_upload_stream_get_authorization_domain (GDataUploadStream *self) +{ + g_return_val_if_fail (GDATA_IS_UPLOAD_STREAM (self), NULL); + return self->priv->authorization_domain; +} + +/** + * gdata_upload_stream_get_method: + * @self: a #GDataUploadStream + * + * Gets the HTTP request method being used to upload the file, as passed to gdata_upload_stream_new(). + * + * Return value: the HTTP request method in use + * + * Since: 0.7.0 + */ +const gchar * +gdata_upload_stream_get_method (GDataUploadStream *self) +{ + g_return_val_if_fail (GDATA_IS_UPLOAD_STREAM (self), NULL); + return self->priv->method; +} + +/** + * gdata_upload_stream_get_upload_uri: + * @self: a #GDataUploadStream + * + * Gets the URI the file is being uploaded to, as passed to gdata_upload_stream_new(). + * + * Return value: the URI which the file is being uploaded to + * + * Since: 0.5.0 + */ +const gchar * +gdata_upload_stream_get_upload_uri (GDataUploadStream *self) +{ + g_return_val_if_fail (GDATA_IS_UPLOAD_STREAM (self), NULL); + return self->priv->upload_uri; +} + +/** + * gdata_upload_stream_get_entry: + * @self: a #GDataUploadStream + * + * Gets the entry being used to upload metadata, if one was passed to gdata_upload_stream_new(). + * + * Return value: (transfer none): the entry used for metadata, or %NULL + * + * Since: 0.5.0 + */ +GDataEntry * +gdata_upload_stream_get_entry (GDataUploadStream *self) +{ + g_return_val_if_fail (GDATA_IS_UPLOAD_STREAM (self), NULL); + return self->priv->entry; +} + +/** + * gdata_upload_stream_get_slug: + * @self: a #GDataUploadStream + * + * Gets the slug (filename) of the file being uploaded. + * + * Return value: the slug of the file being uploaded + * + * Since: 0.5.0 + */ +const gchar * +gdata_upload_stream_get_slug (GDataUploadStream *self) +{ + g_return_val_if_fail (GDATA_IS_UPLOAD_STREAM (self), NULL); + return self->priv->slug; +} + +/** + * gdata_upload_stream_get_content_type: + * @self: a #GDataUploadStream + * + * Gets the content type of the file being uploaded. + * + * Return value: the content type of the file being uploaded + * + * Since: 0.5.0 + */ +const gchar * +gdata_upload_stream_get_content_type (GDataUploadStream *self) +{ + g_return_val_if_fail (GDATA_IS_UPLOAD_STREAM (self), NULL); + return self->priv->content_type; +} + +/** + * gdata_upload_stream_get_content_length: + * @self: a #GDataUploadStream + * + * Gets the size (in bytes) of the file being uploaded. This will be -1 for a non-resumable upload, and zero or greater + * for a resumable upload. + * + * Return value: the size of the file being uploaded + * + * Since: 0.13.0 + */ +goffset +gdata_upload_stream_get_content_length (GDataUploadStream *self) +{ + g_return_val_if_fail (GDATA_IS_UPLOAD_STREAM (self), -1); + return self->priv->content_length; +} + +/** + * gdata_upload_stream_get_cancellable: + * @self: a #GDataUploadStream + * + * Gets the #GCancellable for the entire upload operation, #GDataUploadStream:cancellable. + * + * Return value: (transfer none): the #GCancellable for the entire upload operation + * + * Since: 0.8.0 + */ +GCancellable * +gdata_upload_stream_get_cancellable (GDataUploadStream *self) +{ + g_return_val_if_fail (GDATA_IS_UPLOAD_STREAM (self), NULL); + g_assert (self->priv->cancellable != NULL); + return self->priv->cancellable; +} diff --git a/gdata/gdata-upload-stream.h b/gdata/gdata-upload-stream.h new file mode 100644 index 0000000..d4a3c7b --- /dev/null +++ b/gdata/gdata-upload-stream.h @@ -0,0 +1,124 @@ +/* -*- Mode: C; indent-tabs-mode: t; c-basic-offset: 8; tab-width: 8 -*- */ +/* + * GData Client + * Copyright (C) Philip Withnall 2009 + * + * GData Client is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * GData Client is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with GData Client. If not, see . + */ + +#ifndef GDATA_UPLOAD_STREAM_H +#define GDATA_UPLOAD_STREAM_H + +#include +#include +#include + +#include +#include + +G_BEGIN_DECLS + +/** + * GDATA_LINK_RESUMABLE_CREATE_MEDIA: + * + * The relation type URI of the resumable upload location for resources attached to this resource. + * + * For more information, see the + * GData resumable upload protocol + * specification. + * + * Since: 0.13.0 + */ +#define GDATA_LINK_RESUMABLE_CREATE_MEDIA "http://schemas.google.com/g/2005#resumable-create-media" + +/** + * GDATA_LINK_RESUMABLE_EDIT_MEDIA: + * + * The relation type URI of the resumable update location for resources attached to this resource. + * + * For more information, see the + * GData resumable upload protocol + * specification. + * + * Since: 0.13.0 + */ +#define GDATA_LINK_RESUMABLE_EDIT_MEDIA "http://schemas.google.com/g/2005#resumable-edit-media" + +#define GDATA_TYPE_UPLOAD_STREAM (gdata_upload_stream_get_type ()) +#define GDATA_UPLOAD_STREAM(o) (G_TYPE_CHECK_INSTANCE_CAST ((o), GDATA_TYPE_UPLOAD_STREAM, GDataUploadStream)) +#define GDATA_UPLOAD_STREAM_CLASS(k) (G_TYPE_CHECK_CLASS_CAST((k), GDATA_TYPE_UPLOAD_STREAM, GDataUploadStreamClass)) +#define GDATA_IS_UPLOAD_STREAM(o) (G_TYPE_CHECK_INSTANCE_TYPE ((o), GDATA_TYPE_UPLOAD_STREAM)) +#define GDATA_IS_UPLOAD_STREAM_CLASS(k) (G_TYPE_CHECK_CLASS_TYPE ((k), GDATA_TYPE_UPLOAD_STREAM)) +#define GDATA_UPLOAD_STREAM_GET_CLASS(o) (G_TYPE_INSTANCE_GET_CLASS ((o), GDATA_TYPE_UPLOAD_STREAM, GDataUploadStreamClass)) + +typedef struct _GDataUploadStreamPrivate GDataUploadStreamPrivate; + +/** + * GDataUploadStream: + * + * All the fields in the #GDataUploadStream structure are private and should never be accessed directly. + * + * Since: 0.5.0 + */ +typedef struct { + GOutputStream parent; + GDataUploadStreamPrivate *priv; +} GDataUploadStream; + +/** + * GDataUploadStreamClass: + * + * All the fields in the #GDataUploadStreamClass structure are private and should never be accessed directly. + * + * Since: 0.5.0 + */ +typedef struct { + /*< private >*/ + GOutputStreamClass parent; + + /*< private >*/ + /* Padding for future expansion */ + void (*_g_reserved0) (void); + void (*_g_reserved1) (void); + void (*_g_reserved2) (void); + void (*_g_reserved3) (void); + void (*_g_reserved4) (void); + void (*_g_reserved5) (void); +} GDataUploadStreamClass; + +GType gdata_upload_stream_get_type (void) G_GNUC_CONST; +G_DEFINE_AUTOPTR_CLEANUP_FUNC (GDataUploadStream, g_object_unref) + +GOutputStream *gdata_upload_stream_new (GDataService *service, GDataAuthorizationDomain *domain, const gchar *method, const gchar *upload_uri, + GDataEntry *entry, const gchar *slug, const gchar *content_type, + GCancellable *cancellable) G_GNUC_WARN_UNUSED_RESULT G_GNUC_MALLOC; +GOutputStream *gdata_upload_stream_new_resumable (GDataService *service, GDataAuthorizationDomain *domain, const gchar *method, const gchar *upload_uri, + GDataEntry *entry, const gchar *slug, const gchar *content_type, goffset content_length, + GCancellable *cancellable) G_GNUC_WARN_UNUSED_RESULT G_GNUC_MALLOC; + +const gchar *gdata_upload_stream_get_response (GDataUploadStream *self, gssize *length); + +GDataService *gdata_upload_stream_get_service (GDataUploadStream *self) G_GNUC_PURE; +GDataAuthorizationDomain *gdata_upload_stream_get_authorization_domain (GDataUploadStream *self) G_GNUC_PURE; +const gchar *gdata_upload_stream_get_method (GDataUploadStream *self) G_GNUC_PURE; +const gchar *gdata_upload_stream_get_upload_uri (GDataUploadStream *self) G_GNUC_PURE; +GDataEntry *gdata_upload_stream_get_entry (GDataUploadStream *self) G_GNUC_PURE; +const gchar *gdata_upload_stream_get_slug (GDataUploadStream *self) G_GNUC_PURE; +const gchar *gdata_upload_stream_get_content_type (GDataUploadStream *self) G_GNUC_PURE; +goffset gdata_upload_stream_get_content_length (GDataUploadStream *self) G_GNUC_PURE; +GCancellable *gdata_upload_stream_get_cancellable (GDataUploadStream *self) G_GNUC_PURE; + +G_END_DECLS + +#endif /* !GDATA_UPLOAD_STREAM_H */ diff --git a/gdata/gdata-version.h.in b/gdata/gdata-version.h.in new file mode 100644 index 0000000..994032e --- /dev/null +++ b/gdata/gdata-version.h.in @@ -0,0 +1,80 @@ +/* -*- Mode: C; indent-tabs-mode: t; c-basic-offset: 8; tab-width: 8 -*- */ +/* + * GData Client + * Copyright (C) Holger Berndt 2011 + * + * GData Client is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * GData Client is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with GData Client. If not, see . + */ + +#ifndef GDATA_VERSION_H +#define GDATA_VERSION_H + +/** + * SECTION:gdata-version + * @Short_description: Macros to check the libgdata version + * @Title: Version Information + * + * libgdata provides compile-time version information. + * + * Since: 0.11.0 + */ + +/** + * GDATA_MAJOR_VERSION: + * + * Evaluates to the major version of the GData headers at compile time. + * (e.g. in libgdata version 1.2.3 this is 1). + * + * Since: 0.11.0 + */ +#define GDATA_MAJOR_VERSION (@GDATA_VERSION_MAJOR@) + +/** + * GDATA_MINOR_VERSION: + * + * Evaluates to the minor version of the GData headers at compile time. + * (e.g. in libgdata version 1.2.3 this is 2). + * + * Since: 0.11.0 + */ +#define GDATA_MINOR_VERSION (@GDATA_VERSION_MINOR@) + +/** + * GDATA_MICRO_VERSION: + * + * Evaluates to the micro version of the GData headers at compile time. + * (e.g. in libgdata version 1.2.3 this is 3). + * + * Since: 0.11.0 + */ +#define GDATA_MICRO_VERSION (@GDATA_VERSION_MICRO@) + +/** + * GDATA_CHECK_VERSION: + * @major: major version (e.g. 1 for version 1.2.3) + * @minor: minor version (e.g. 2 for version 1.2.3) + * @micro: micro version (e.g. 3 for version 1.2.3) + * + * Evaluates to %TRUE if the version of the GData header files + * is the same as or newer than the passed-in version. + * + * Since: 0.11.0 + */ +#define GDATA_CHECK_VERSION(major,minor,micro) \ + (GDATA_MAJOR_VERSION > (major) || \ + (GDATA_MAJOR_VERSION == (major) && GDATA_MINOR_VERSION > (minor)) || \ + (GDATA_MAJOR_VERSION == (major) && GDATA_MINOR_VERSION == (minor) && \ + GDATA_MICRO_VERSION >= (micro))) + +#endif /* !GDATA_VERSION_H */ diff --git a/gdata/gdata.h b/gdata/gdata.h new file mode 100644 index 0000000..a1ff6ec --- /dev/null +++ b/gdata/gdata.h @@ -0,0 +1,162 @@ +/* -*- Mode: C; indent-tabs-mode: t; c-basic-offset: 8; tab-width: 8 -*- */ +/* + * GData Client + * Copyright (C) Philip Withnall 2008-2009 + * + * GData Client is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * GData Client is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with GData Client. If not, see . + */ + +#ifndef GDATA_H +#define GDATA_H + +/* Core files */ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#ifdef GOA_API_IS_SUBJECT_TO_CHANGE +/* You need to define GOA_API_IS_SUBJECT_TO_CHANGE in order to use the GOA authoriser. */ +#include +#endif /* GOA_API_IS_SUBJECT_TO_CHANGE */ +#include +#include +#include + +/* Namespaces */ + +/* Atom */ +#include +#include +#include +#include + +/* APP */ +#include + +/* GData */ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +/* GContact */ +#include +#include +#include +#include +#include +#include +#include + +/* Media RSS */ +#include +#include +#include +#include +#include + +/* Services */ + +/* YouTube */ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +/* Google Calendar */ +#include +#include +#include +#include +#include +#include + +/* Google PicasaWeb */ +#include +#include +#include +#include +#include +#include +#include +#include + +/* Google Contacts */ +#include +#include +#include +#include + +/* Google Documents*/ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +/* Google Tasks */ +#include +#include +#include +#include + +/* Google Freebase */ +#include +#include +#include +#include +#include +#include +#include +#include + +#endif /* !GDATA_H */ diff --git a/gdata/georss/gdata-georss-where.c b/gdata/georss/gdata-georss-where.c new file mode 100644 index 0000000..8673c26 --- /dev/null +++ b/gdata/georss/gdata-georss-where.c @@ -0,0 +1,223 @@ +/* -*- Mode: C; indent-tabs-mode: t; c-basic-offset: 8; tab-width: 8 -*- */ +/* + * GData Client + * Copyright (C) Philip Withnall 2009 + * Copyright (C) Richard Schwarting 2009 + * + * GData Client is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * GData Client is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with GData Client. If not, see . + */ + +/* + * SECTION:gdata-georss-where + * @short_description: GeoRSS where element + * @stability: Stable + * @include: gdata/georss/gdata-georss-where.h + * + * #GDataGeoRSSWhere represents a "where" element from the + * GeoRSS specification. + * with PicasaWeb usage defined at + * PicasaWeb API reference. + * + * It is private API, since implementing classes are likely to proxy the properties and functions + * of #GDataGeoRSSWhere as appropriate; most entry types which implement #GDataGeoRSSWhere have no use + * for most of its properties, and it would be unnecessary and confusing to expose #GDataGeoRSSWhere itself. + * + * Since: 0.5.0 + */ + +#include +#include +#include + +#include "gdata-georss-where.h" +#include "gdata-parsable.h" +#include "gdata-parser.h" +#include "gdata-private.h" + +static gboolean parse_xml (GDataParsable *parsable, xmlDoc *doc, xmlNode *node, gpointer user_data, GError **error); +static void get_namespaces (GDataParsable *parsable, GHashTable *namespaces); +static void get_xml (GDataParsable *parsable, GString *xml_string); + +struct _GDataGeoRSSWherePrivate { + gdouble latitude; + gdouble longitude; +}; + +G_DEFINE_TYPE (GDataGeoRSSWhere, gdata_georss_where, GDATA_TYPE_PARSABLE) + +static void +gdata_georss_where_class_init (GDataGeoRSSWhereClass *klass) +{ + GDataParsableClass *parsable_class = GDATA_PARSABLE_CLASS (klass); + + g_type_class_add_private (klass, sizeof (GDataGeoRSSWherePrivate)); + + parsable_class->get_xml = get_xml; + parsable_class->parse_xml = parse_xml; + parsable_class->get_namespaces = get_namespaces; + parsable_class->element_name = "where"; + parsable_class->element_namespace = "georss"; +} + +static void +gdata_georss_where_init (GDataGeoRSSWhere *self) +{ + self->priv = G_TYPE_INSTANCE_GET_PRIVATE (self, GDATA_TYPE_GEORSS_WHERE, GDataGeoRSSWherePrivate); + + self->priv->latitude = G_MAXDOUBLE; + self->priv->longitude = G_MAXDOUBLE; +} + +static gboolean +parse_xml (GDataParsable *parsable, xmlDoc *doc, xmlNode *node, gpointer user_data, GError **error) +{ + GDataGeoRSSWhere *self = GDATA_GEORSS_WHERE (parsable); + + if (gdata_parser_is_namespace (node, "http://www.opengis.net/gml") == TRUE && + xmlStrcmp (node->name, (xmlChar*) "Point") == 0) { + /* gml:Point */ + gboolean found_pos = FALSE; + xmlNode *child; + + for (child = node->children; child != NULL; child = child->next) { + if (xmlStrcmp (child->name, (xmlChar*) "pos") == 0) { + xmlChar *pos = xmlNodeListGetString (doc, child->children, TRUE); + gchar *endptr; + + self->priv->latitude = g_ascii_strtod ((gchar*) pos, &endptr); + self->priv->longitude = g_ascii_strtod (endptr, NULL); + + xmlFree (pos); + found_pos = TRUE; + } else { + /* TODO: this logic copied from gdata-parsable.c. Re-evaluate this at some point in the future. + If GeoRSS and GML support were to be used more widely, it might due to implement GML objects. */ + xmlBuffer *buffer; + + /* Unhandled XML */ + buffer = xmlBufferCreate (); + xmlNodeDump (buffer, doc, child, 0, 0); + g_debug ("Unhandled XML in : %s", (gchar*) xmlBufferContent (buffer)); + xmlBufferFree (buffer); + } + } + + if (found_pos == FALSE) + return gdata_parser_error_required_element_missing ("pos", "gml:Point", error); + return TRUE; + } + + return GDATA_PARSABLE_CLASS (gdata_georss_where_parent_class)->parse_xml (parsable, doc, node, user_data, error); +} + +static void +get_xml (GDataParsable *parsable, GString *xml_string) +{ + GDataGeoRSSWherePrivate *priv = GDATA_GEORSS_WHERE (parsable)->priv; + gchar latitude_str[G_ASCII_DTOSTR_BUF_SIZE]; + gchar longitude_str[G_ASCII_DTOSTR_BUF_SIZE]; + + if (priv->latitude != G_MAXDOUBLE && priv->longitude != G_MAXDOUBLE) { + g_string_append_printf (xml_string, "%s %s", + g_ascii_dtostr (latitude_str, sizeof (latitude_str), priv->latitude), + g_ascii_dtostr (longitude_str, sizeof (longitude_str), priv->longitude)); + } +} + +static void +get_namespaces (GDataParsable *parsable, GHashTable *namespaces) +{ + g_hash_table_insert (namespaces, (gchar*) "georss", (gchar*) "http://www.georss.org/georss"); + g_hash_table_insert (namespaces, (gchar*) "gml", (gchar*) "http://www.opengis.net/gml"); +} + +/** + * gdata_georss_where_get_latitude: + * @self: a #GDataGeoRSSWhere + * + * Gets the #GDataGeoRSSWhere:latitude property. + * + * Return value: the latitude of this position, or %G_MAXDOUBLE if unknown + * + * Since: 0.5.0 + */ +gdouble +gdata_georss_where_get_latitude (GDataGeoRSSWhere *self) +{ + g_return_val_if_fail (GDATA_IS_GEORSS_WHERE (self), G_MAXDOUBLE); + return self->priv->latitude; +} + +/** + * gdata_georss_where_get_longitude: + * @self: a #GDataGeoRSSWhere + * + * Gets the #GDataGeoRSSWhere:longitude property. + * + * Return value: the longitude of this position, or %G_MAXDOUBLE if unknown + * + * Since: 0.5.0 + */ +gdouble +gdata_georss_where_get_longitude (GDataGeoRSSWhere *self) +{ + g_return_val_if_fail (GDATA_IS_GEORSS_WHERE (self), G_MAXDOUBLE); + return self->priv->longitude; +} + +/** + * gdata_georss_where_set_latitude: + * @self: a #GDataGeoRSSWhere + * @latitude: the new latitude coordinate, or %G_MAXDOUBLE + * + * Sets the #GDataGeoRSSWhere:latitude property to @latitude. + * + * Valid values range from -90.0 to 90.0 inclusive. + * Set @latitude to %G_MAXDOUBLE to unset it. + * + * Since: 0.5.0 + */ +void +gdata_georss_where_set_latitude (GDataGeoRSSWhere *self, gdouble latitude) +{ + g_return_if_fail (GDATA_IS_GEORSS_WHERE (self)); + + if (latitude < -90.0 || latitude > 90.0) + self->priv->latitude = G_MAXDOUBLE; + else + self->priv->latitude = latitude; +} + +/** + * gdata_georss_where_set_longitude: + * @self: a #GDataGeoRSSWhere + * @longitude: the new longitude coordinate, or %G_MAXDOUBLE + * + * Sets the #GDataGeoRSSWhere:longitude property to @longitude. + * + * Valid values range from -180.0 to 180.0 inclusive. + * Set @longitude to %G_MAXDOUBLE to unset it. + * + * Since: 0.5.0 + */ +void +gdata_georss_where_set_longitude (GDataGeoRSSWhere *self, gdouble longitude) +{ + g_return_if_fail (GDATA_IS_GEORSS_WHERE (self)); + + if (longitude < -180.0 || longitude > 180.0) + self->priv->longitude = G_MAXDOUBLE; + else + self->priv->longitude = longitude; +} diff --git a/gdata/georss/gdata-georss-where.h b/gdata/georss/gdata-georss-where.h new file mode 100644 index 0000000..a949bb0 --- /dev/null +++ b/gdata/georss/gdata-georss-where.h @@ -0,0 +1,77 @@ +/* -*- Mode: C; indent-tabs-mode: t; c-basic-offset: 8; tab-width: 8 -*- */ +/* + * GData Client + * Copyright (C) Richard Schwarting 2009 + * + * GData Client is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * GData Client is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with GData Client. If not, see . + */ + +#ifndef GDATA_GEORSS_WHERE_H +#define GDATA_GEORSS_WHERE_H + +#include +#include + +#include + +G_BEGIN_DECLS + +#define GDATA_TYPE_GEORSS_WHERE (gdata_georss_where_get_type ()) +#define GDATA_GEORSS_WHERE(o) (G_TYPE_CHECK_INSTANCE_CAST ((o), GDATA_TYPE_GEORSS_WHERE, GDataGeoRSSWhere)) +#define GDATA_GEORSS_WHERE_CLASS(k) (G_TYPE_CHECK_CLASS_CAST((k), GDATA_TYPE_GEORSS_WHERE, GDataGeoRSSWhereClass)) +#define GDATA_IS_GEORSS_WHERE(o) (G_TYPE_CHECK_INSTANCE_TYPE ((o), GDATA_TYPE_GEORSS_WHERE)) +#define GDATA_IS_GEORSS_WHERE_CLASS(k) (G_TYPE_CHECK_CLASS_TYPE ((k), GDATA_TYPE_GEORSS_WHERE)) +#define GDATA_GEORSS_WHERE_GET_CLASS(o) (G_TYPE_INSTANCE_GET_CLASS ((o), GDATA_TYPE_GEORSS_WHERE, GDataGeoRSSWhereClass)) + +typedef struct _GDataGeoRSSWherePrivate GDataGeoRSSWherePrivate; + +/** + * GDataGeoRSSWhere: + * + * All the fields in the #GDataGeoRSSWhere structure are private and should never be accessed directly. + * + * Since: 0.5.0 + */ +typedef struct { + GDataParsable parent; + GDataGeoRSSWherePrivate *priv; +} GDataGeoRSSWhere; + +/** + * GDataGeoRSSWhereClass: + * + * All the fields in the #GDataGeoRSSWhereClass structure are private and should never be accessed directly. + * + * Since: 0.5.0 + */ +typedef struct { + /*< private >*/ + GDataParsableClass parent; + + /*< private >*/ + /* Padding for future expansion */ + void (*_g_reserved0) (void); + void (*_g_reserved1) (void); +} GDataGeoRSSWhereClass; + +GType gdata_georss_where_get_type (void) G_GNUC_CONST; + +gdouble gdata_georss_where_get_latitude (GDataGeoRSSWhere *self) G_GNUC_PURE; +gdouble gdata_georss_where_get_longitude (GDataGeoRSSWhere *self) G_GNUC_PURE; +void gdata_georss_where_set_latitude (GDataGeoRSSWhere *self, gdouble latitude); +void gdata_georss_where_set_longitude (GDataGeoRSSWhere *self, gdouble longitude); + +G_END_DECLS + +#endif /* !GDATA_GEORSS_WHERE_H */ diff --git a/gdata/georss/meson.build b/gdata/georss/meson.build new file mode 100644 index 0000000..69c2ce3 --- /dev/null +++ b/gdata/georss/meson.build @@ -0,0 +1 @@ +sources += files('gdata-georss-where.c') diff --git a/gdata/media/gdata-media-category.c b/gdata/media/gdata-media-category.c new file mode 100644 index 0000000..da7e156 --- /dev/null +++ b/gdata/media/gdata-media-category.c @@ -0,0 +1,388 @@ +/* -*- Mode: C; indent-tabs-mode: t; c-basic-offset: 8; tab-width: 8 -*- */ +/* + * GData Client + * Copyright (C) Philip Withnall 2009–2010 + * + * GData Client is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * GData Client is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with GData Client. If not, see . + */ + +/** + * SECTION:gdata-media-category + * @short_description: Media RSS category element + * @stability: Stable + * @include: gdata/media/gdata-media-category.h + * + * #GDataMediaCategory represents a "category" element from the + * Media RSS specification. + * + * Since: 0.4.0 + */ + +#include +#include + +#include "gdata-media-category.h" +#include "gdata-parsable.h" +#include "gdata-parser.h" +#include "gdata-types.h" + +static void gdata_media_category_finalize (GObject *object); +static void gdata_media_category_get_property (GObject *object, guint property_id, GValue *value, GParamSpec *pspec); +static void gdata_media_category_set_property (GObject *object, guint property_id, const GValue *value, GParamSpec *pspec); +static gboolean pre_parse_xml (GDataParsable *parsable, xmlDoc *doc, xmlNode *root_node, gpointer user_data, GError **error); +static gboolean parse_xml (GDataParsable *parsable, xmlDoc *doc, xmlNode *node, gpointer user_data, GError **error); +static void pre_get_xml (GDataParsable *parsable, GString *xml_string); +static void get_xml (GDataParsable *parsable, GString *xml_string); +static void get_namespaces (GDataParsable *parsable, GHashTable *namespaces); + +struct _GDataMediaCategoryPrivate { + gchar *category; + gchar *scheme; + gchar *label; +}; + +enum { + PROP_CATEGORY = 1, + PROP_SCHEME, + PROP_LABEL +}; + +G_DEFINE_TYPE (GDataMediaCategory, gdata_media_category, GDATA_TYPE_PARSABLE) + +static void +gdata_media_category_class_init (GDataMediaCategoryClass *klass) +{ + GObjectClass *gobject_class = G_OBJECT_CLASS (klass); + GDataParsableClass *parsable_class = GDATA_PARSABLE_CLASS (klass); + + g_type_class_add_private (klass, sizeof (GDataMediaCategoryPrivate)); + + gobject_class->get_property = gdata_media_category_get_property; + gobject_class->set_property = gdata_media_category_set_property; + gobject_class->finalize = gdata_media_category_finalize; + + parsable_class->pre_parse_xml = pre_parse_xml; + parsable_class->parse_xml = parse_xml; + parsable_class->pre_get_xml = pre_get_xml; + parsable_class->get_xml = get_xml; + parsable_class->get_namespaces = get_namespaces; + parsable_class->element_name = "category"; + parsable_class->element_namespace = "media"; + + /** + * GDataMediaCategory:category: + * + * The category name. + * + * For more information, see the Media RSS specification. + * + * Since: 0.4.0 + */ + g_object_class_install_property (gobject_class, PROP_CATEGORY, + g_param_spec_string ("category", + "Category", "The category name.", + NULL, + G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)); + + /** + * GDataMediaCategory:scheme: + * + * A URI that identifies the categorization scheme. + * + * For more information, see the Media RSS specification. + * + * Since: 0.4.0 + */ + g_object_class_install_property (gobject_class, PROP_SCHEME, + g_param_spec_string ("scheme", + "Scheme", "A URI that identifies the categorization scheme.", + NULL, + G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)); + + /** + * GDataMediaCategory:label: + * + * A human-readable label that can be displayed in end-user applications. + * + * For more information, see the Media RSS specification. + * + * Since: 0.4.0 + */ + g_object_class_install_property (gobject_class, PROP_LABEL, + g_param_spec_string ("label", + "Label", "A human-readable label that can be displayed in end-user applications.", + NULL, + G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)); +} + +static void +gdata_media_category_init (GDataMediaCategory *self) +{ + self->priv = G_TYPE_INSTANCE_GET_PRIVATE (self, GDATA_TYPE_MEDIA_CATEGORY, GDataMediaCategoryPrivate); +} + +static void +gdata_media_category_finalize (GObject *object) +{ + GDataMediaCategoryPrivate *priv = GDATA_MEDIA_CATEGORY (object)->priv; + + g_free (priv->category); + g_free (priv->scheme); + g_free (priv->label); + + /* Chain up to the parent class */ + G_OBJECT_CLASS (gdata_media_category_parent_class)->finalize (object); +} + +static void +gdata_media_category_get_property (GObject *object, guint property_id, GValue *value, GParamSpec *pspec) +{ + GDataMediaCategoryPrivate *priv = GDATA_MEDIA_CATEGORY (object)->priv; + + switch (property_id) { + case PROP_CATEGORY: + g_value_set_string (value, priv->category); + break; + case PROP_SCHEME: + g_value_set_string (value, priv->scheme); + break; + case PROP_LABEL: + g_value_set_string (value, priv->label); + break; + default: + /* We don't have any other property... */ + G_OBJECT_WARN_INVALID_PROPERTY_ID (object, property_id, pspec); + break; + } +} + +static void +gdata_media_category_set_property (GObject *object, guint property_id, const GValue *value, GParamSpec *pspec) +{ + GDataMediaCategory *self = GDATA_MEDIA_CATEGORY (object); + + switch (property_id) { + case PROP_CATEGORY: + gdata_media_category_set_category (self, g_value_get_string (value)); + break; + case PROP_SCHEME: + gdata_media_category_set_scheme (self, g_value_get_string (value)); + break; + case PROP_LABEL: + gdata_media_category_set_label (self, g_value_get_string (value)); + break; + default: + /* We don't have any other property... */ + G_OBJECT_WARN_INVALID_PROPERTY_ID (object, property_id, pspec); + break; + } +} + +static gboolean +pre_parse_xml (GDataParsable *parsable, xmlDoc *doc, xmlNode *root_node, gpointer user_data, GError **error) +{ + GDataMediaCategoryPrivate *priv = GDATA_MEDIA_CATEGORY (parsable)->priv; + xmlChar *category, *scheme; + + category = xmlNodeListGetString (doc, root_node->children, TRUE); + if (category == NULL || *category == '\0') { + xmlFree (category); + return gdata_parser_error_required_content_missing (root_node, error); + } + + scheme = xmlGetProp (root_node, (xmlChar*) "scheme"); + if (scheme != NULL && *scheme == '\0') { + xmlFree (scheme); + xmlFree (category); + return gdata_parser_error_required_property_missing (root_node, "scheme", error); + } else if (scheme == NULL) { + /* Default */ + scheme = xmlStrdup ((xmlChar*) "http://video.search.yahoo.com/mrss/category_schema"); + } + + priv->category = (gchar*) category; + priv->scheme = (gchar*) scheme; + priv->label = (gchar*) xmlGetProp (root_node, (xmlChar*) "label"); + + return TRUE; +} + +static gboolean +parse_xml (GDataParsable *parsable, xmlDoc *doc, xmlNode *node, gpointer user_data, GError **error) +{ + /* Textual content's handled in pre_parse_xml */ + if (node->type != XML_ELEMENT_NODE) + return TRUE; + + return GDATA_PARSABLE_CLASS (gdata_media_category_parent_class)->parse_xml (parsable, doc, node, user_data, error); +} + +static void +pre_get_xml (GDataParsable *parsable, GString *xml_string) +{ + GDataMediaCategoryPrivate *priv = GDATA_MEDIA_CATEGORY (parsable)->priv; + + if (priv->scheme != NULL) + gdata_parser_string_append_escaped (xml_string, " scheme='", priv->scheme, "'"); + if (priv->label != NULL) + gdata_parser_string_append_escaped (xml_string, " label='", priv->label, "'"); +} + +static void +get_xml (GDataParsable *parsable, GString *xml_string) +{ + gdata_parser_string_append_escaped (xml_string, NULL, GDATA_MEDIA_CATEGORY (parsable)->priv->category, NULL); +} + +static void +get_namespaces (GDataParsable *parsable, GHashTable *namespaces) +{ + g_hash_table_insert (namespaces, (gchar*) "media", (gchar*) "http://search.yahoo.com/mrss/"); +} + +/** + * gdata_media_category_new: + * @category: a category describing the content + * @scheme: (allow-none): a URI identifying the categorisation scheme, or %NULL + * @label: (allow-none): a human-readable name for the category, or %NULL + * + * Creates a new #GDataMediaCategory. More information is available in the Media RSS specification. + * + * Return value: a new #GDataMediaCategory, or %NULL; unref with g_object_unref() + */ +GDataMediaCategory * +gdata_media_category_new (const gchar *category, const gchar *scheme, const gchar *label) +{ + g_return_val_if_fail (category != NULL && *category != '\0', NULL); + g_return_val_if_fail (scheme == NULL || *scheme != '\0', NULL); + return g_object_new (GDATA_TYPE_MEDIA_CATEGORY, "category", category, "scheme", scheme, "label", label, NULL); +} + +/** + * gdata_media_category_get_category: + * @self: a #GDataMediaCategory + * + * Gets the #GDataMediaCategory:category property. + * + * Return value: the actual category + * + * Since: 0.4.0 + */ +const gchar * +gdata_media_category_get_category (GDataMediaCategory *self) +{ + g_return_val_if_fail (GDATA_IS_MEDIA_CATEGORY (self), NULL); + return self->priv->category; +} + +/** + * gdata_media_category_set_category: + * @self: a #GDataMediaCategory + * @category: the new category + * + * Sets the #GDataMediaCategory:category property to @category. + * + * Since: 0.4.0 + */ +void +gdata_media_category_set_category (GDataMediaCategory *self, const gchar *category) +{ + g_return_if_fail (GDATA_IS_MEDIA_CATEGORY (self)); + g_return_if_fail (category != NULL && *category != '\0'); + + g_free (self->priv->category); + self->priv->category = g_strdup (category); + g_object_notify (G_OBJECT (self), "category"); +} + +/** + * gdata_media_category_get_scheme: + * @self: a #GDataMediaCategory + * + * Gets the #GDataMediaCategory:scheme property. + * + * Return value: the category's scheme, or %NULL + * + * Since: 0.4.0 + */ +const gchar * +gdata_media_category_get_scheme (GDataMediaCategory *self) +{ + g_return_val_if_fail (GDATA_IS_MEDIA_CATEGORY (self), NULL); + return self->priv->scheme; +} + +/** + * gdata_media_category_set_scheme: + * @self: a #GDataMediaCategory + * @scheme: (allow-none): the category's new scheme, or %NULL + * + * Sets the #GDataMediaCategory:scheme property to @scheme. + * + * Set @scheme to %NULL to unset the property. + * + * Since: 0.4.0 + */ +void +gdata_media_category_set_scheme (GDataMediaCategory *self, const gchar *scheme) +{ + g_return_if_fail (GDATA_IS_MEDIA_CATEGORY (self)); + g_return_if_fail (scheme == NULL || *scheme != '\0'); + + if (scheme == NULL) + scheme = "http://video.search.yahoo.com/mrss/category_schema"; + + g_free (self->priv->scheme); + self->priv->scheme = g_strdup (scheme); + g_object_notify (G_OBJECT (self), "scheme"); +} + +/** + * gdata_media_category_get_label: + * @self: a #GDataMediaCategory + * + * Gets the #GDataMediaCategory:label property. + * + * Return value: the category's label, or %NULL + * + * Since: 0.4.0 + */ +const gchar * +gdata_media_category_get_label (GDataMediaCategory *self) +{ + g_return_val_if_fail (GDATA_IS_MEDIA_CATEGORY (self), NULL); + return self->priv->label; +} + +/** + * gdata_media_category_set_label: + * @self: a #GDataMediaCategory + * @label: (allow-none): the category's new label, or %NULL + * + * Sets the #GDataMediaCategory:label property to @label. + * + * Set @label to %NULL to unset the property. + * + * Since: 0.4.0 + */ +void +gdata_media_category_set_label (GDataMediaCategory *self, const gchar *label) +{ + g_return_if_fail (GDATA_IS_MEDIA_CATEGORY (self)); + + g_free (self->priv->label); + self->priv->label = g_strdup (label); + g_object_notify (G_OBJECT (self), "label"); +} diff --git a/gdata/media/gdata-media-category.h b/gdata/media/gdata-media-category.h new file mode 100644 index 0000000..0715fe3 --- /dev/null +++ b/gdata/media/gdata-media-category.h @@ -0,0 +1,81 @@ +/* -*- Mode: C; indent-tabs-mode: t; c-basic-offset: 8; tab-width: 8 -*- */ +/* + * GData Client + * Copyright (C) Philip Withnall 2009 + * + * GData Client is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * GData Client is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with GData Client. If not, see . + */ + +#ifndef GDATA_MEDIA_CATEGORY_H +#define GDATA_MEDIA_CATEGORY_H + +#include +#include + +#include + +G_BEGIN_DECLS + +#define GDATA_TYPE_MEDIA_CATEGORY (gdata_media_category_get_type ()) +#define GDATA_MEDIA_CATEGORY(o) (G_TYPE_CHECK_INSTANCE_CAST ((o), GDATA_TYPE_MEDIA_CATEGORY, GDataMediaCategory)) +#define GDATA_MEDIA_CATEGORY_CLASS(k) (G_TYPE_CHECK_CLASS_CAST((k), GDATA_TYPE_MEDIA_CATEGORY, GDataMediaCategoryClass)) +#define GDATA_IS_MEDIA_CATEGORY(o) (G_TYPE_CHECK_INSTANCE_TYPE ((o), GDATA_TYPE_MEDIA_CATEGORY)) +#define GDATA_IS_MEDIA_CATEGORY_CLASS(k) (G_TYPE_CHECK_CLASS_TYPE ((k), GDATA_TYPE_MEDIA_CATEGORY)) +#define GDATA_MEDIA_CATEGORY_GET_CLASS(o) (G_TYPE_INSTANCE_GET_CLASS ((o), GDATA_TYPE_MEDIA_CATEGORY, GDataMediaCategoryClass)) + +typedef struct _GDataMediaCategoryPrivate GDataMediaCategoryPrivate; + +/** + * GDataMediaCategory: + * + * All the fields in the #GDataMediaCategory structure are private and should never be accessed directly. + */ +typedef struct { + GDataParsable parent; + GDataMediaCategoryPrivate *priv; +} GDataMediaCategory; + +/** + * GDataMediaCategoryClass: + * + * All the fields in the #GDataMediaCategoryClass structure are private and should never be accessed directly. + * + * Since: 0.4.0 + */ +typedef struct { + /*< private >*/ + GDataParsableClass parent; + + /*< private >*/ + /* Padding for future expansion */ + void (*_g_reserved0) (void); + void (*_g_reserved1) (void); +} GDataMediaCategoryClass; + +GType gdata_media_category_get_type (void) G_GNUC_CONST; + +GDataMediaCategory *gdata_media_category_new (const gchar *category, const gchar *scheme, const gchar *label) G_GNUC_WARN_UNUSED_RESULT G_GNUC_MALLOC; + +const gchar *gdata_media_category_get_category (GDataMediaCategory *self) G_GNUC_PURE; +void gdata_media_category_set_category (GDataMediaCategory *self, const gchar *category); + +const gchar *gdata_media_category_get_scheme (GDataMediaCategory *self) G_GNUC_PURE; +void gdata_media_category_set_scheme (GDataMediaCategory *self, const gchar *scheme); + +const gchar *gdata_media_category_get_label (GDataMediaCategory *self) G_GNUC_PURE; +void gdata_media_category_set_label (GDataMediaCategory *self, const gchar *label); + +G_END_DECLS + +#endif /* !GDATA_MEDIA_CATEGORY_H */ diff --git a/gdata/media/gdata-media-content.c b/gdata/media/gdata-media-content.c new file mode 100644 index 0000000..50a35d3 --- /dev/null +++ b/gdata/media/gdata-media-content.c @@ -0,0 +1,573 @@ +/* -*- Mode: C; indent-tabs-mode: t; c-basic-offset: 8; tab-width: 8 -*- */ +/* + * GData Client + * Copyright (C) Philip Withnall 2009–2010 + * + * GData Client is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * GData Client is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with GData Client. If not, see . + */ + +/** + * SECTION:gdata-media-content + * @short_description: Media RSS content element + * @stability: Stable + * @include: gdata/media/gdata-media-content.h + * + * #GDataMediaContent represents a "content" element from the + * Media RSS specification. + * + * The class only implements parsing, not XML output, at the moment. + * + * Since: 0.4.0 + */ + +#include +#include + +#include "gdata-media-content.h" +#include "gdata-download-stream.h" +#include "gdata-parsable.h" +#include "gdata-parser.h" +#include "gdata-media-enums.h" +#include "gdata-private.h" + +static void gdata_media_content_finalize (GObject *object); +static void gdata_media_content_get_property (GObject *object, guint property_id, GValue *value, GParamSpec *pspec); +static gboolean pre_parse_xml (GDataParsable *parsable, xmlDoc *doc, xmlNode *root_node, gpointer user_data, GError **error); +static void get_namespaces (GDataParsable *parsable, GHashTable *namespaces); + +struct _GDataMediaContentPrivate { + gchar *uri; + gsize filesize; + gchar *content_type; + GDataMediaMedium medium; + gboolean is_default; + GDataMediaExpression expression; + gint64 duration; + guint height; + guint width; + /* TODO: implement other properties from the Media RSS standard */ +}; + +enum { + PROP_URI = 1, + PROP_FILESIZE, + PROP_CONTENT_TYPE, + PROP_MEDIUM, + PROP_IS_DEFAULT, + PROP_EXPRESSION, + PROP_DURATION, + PROP_HEIGHT, + PROP_WIDTH +}; + +G_DEFINE_TYPE (GDataMediaContent, gdata_media_content, GDATA_TYPE_PARSABLE) + +static void +gdata_media_content_class_init (GDataMediaContentClass *klass) +{ + GObjectClass *gobject_class = G_OBJECT_CLASS (klass); + GDataParsableClass *parsable_class = GDATA_PARSABLE_CLASS (klass); + + g_type_class_add_private (klass, sizeof (GDataMediaContentPrivate)); + + gobject_class->get_property = gdata_media_content_get_property; + gobject_class->finalize = gdata_media_content_finalize; + + parsable_class->pre_parse_xml = pre_parse_xml; + parsable_class->get_namespaces = get_namespaces; + parsable_class->element_name = "content"; + parsable_class->element_namespace = "media"; + + /** + * GDataMediaContent:uri: + * + * The direct URI to the media object. + * + * For more information, see the Media RSS specification. + * + * Since: 0.4.0 + */ + g_object_class_install_property (gobject_class, PROP_URI, + g_param_spec_string ("uri", + "URI", "The direct URI to the media object.", + NULL, + G_PARAM_READABLE | G_PARAM_STATIC_STRINGS)); + + /** + * GDataMediaContent:filesize: + * + * The number of bytes of the media object. + * + * For more information, see the Media RSS specification. + * + * Since: 0.4.0 + */ + g_object_class_install_property (gobject_class, PROP_FILESIZE, + g_param_spec_ulong ("filesize", + "Filesize", "The number of bytes of the media object.", + 0, G_MAXULONG, 0, + G_PARAM_READABLE | G_PARAM_STATIC_STRINGS)); + + /** + * GDataMediaContent:content-type: + * + * The standard MIME type of the object. + * + * For more information, see the Media RSS specification. + * + * Since: 0.4.0 + */ + g_object_class_install_property (gobject_class, PROP_CONTENT_TYPE, + g_param_spec_string ("content-type", + "Content type", "The standard MIME type of the object.", + NULL, + G_PARAM_READABLE | G_PARAM_STATIC_STRINGS)); + + /** + * GDataMediaContent:medium: + * + * The type of object, complementing #GDataMediaContent:content-type. It allows the consuming application to make simpler decisions between + * different content objects, based on whether they're a video or audio stream, for example. + * + * For more information, see the Media RSS specification. + * + * Since: 0.4.0 + */ + g_object_class_install_property (gobject_class, PROP_MEDIUM, + g_param_spec_enum ("medium", + "Medium", "The type of object.", + GDATA_TYPE_MEDIA_MEDIUM, GDATA_MEDIA_UNKNOWN, + G_PARAM_READABLE | G_PARAM_STATIC_STRINGS)); + + /** + * GDataMediaContent:is-default: + * + * Determines if this is the default content for the media group. There should only be one default object per media group. + * + * For more information, see the Media RSS specification. + * + * Since: 0.4.0 + */ + g_object_class_install_property (gobject_class, PROP_IS_DEFAULT, + g_param_spec_boolean ("is-default", + "Default?", "Determines if this is the default content for the media group.", + FALSE, + G_PARAM_READABLE | G_PARAM_STATIC_STRINGS)); + + /** + * GDataMediaContent:expression: + * + * Determines if the object is a sample or the full version of the object, or even if it is a continuous stream. + * + * For more information, see the Media RSS specification. + * + * Since: 0.4.0 + */ + g_object_class_install_property (gobject_class, PROP_EXPRESSION, + g_param_spec_enum ("expression", + "Expression", "Determines if the object is a sample or the full version of the object.", + GDATA_TYPE_MEDIA_EXPRESSION, GDATA_MEDIA_EXPRESSION_FULL, + G_PARAM_READABLE | G_PARAM_STATIC_STRINGS)); + + /** + * GDataMediaContent:duration: + * + * The number of seconds for which the media object plays. + * + * For more information, see the Media RSS specification. + * + * Since: 0.4.0 + */ + g_object_class_install_property (gobject_class, PROP_DURATION, + g_param_spec_int64 ("duration", + "Duration", "The number of seconds for which the media object plays.", + 0, G_MAXINT64, 0, + G_PARAM_READABLE | G_PARAM_STATIC_STRINGS)); + + /** + * GDataMediaContent:height: + * + * The height of the media object. + * + * For more information, see the Media RSS specification. + * + * Since: 0.4.0 + */ + g_object_class_install_property (gobject_class, PROP_HEIGHT, + g_param_spec_uint ("height", + "Height", "The height of the media object.", + 0, G_MAXUINT, 0, + G_PARAM_READABLE | G_PARAM_STATIC_STRINGS)); + + /** + * GDataMediaContent:width: + * + * The width of the media object. + * + * For more information, see the Media RSS specification. + * + * Since: 0.4.0 + */ + g_object_class_install_property (gobject_class, PROP_WIDTH, + g_param_spec_uint ("width", + "Width", "The width of the media object.", + 0, G_MAXUINT, 0, + G_PARAM_READABLE | G_PARAM_STATIC_STRINGS)); +} + +static void +gdata_media_content_init (GDataMediaContent *self) +{ + self->priv = G_TYPE_INSTANCE_GET_PRIVATE (self, GDATA_TYPE_MEDIA_CONTENT, GDataMediaContentPrivate); +} + +static void +gdata_media_content_finalize (GObject *object) +{ + GDataMediaContentPrivate *priv = GDATA_MEDIA_CONTENT (object)->priv; + + g_free (priv->uri); + g_free (priv->content_type); + + /* Chain up to the parent class */ + G_OBJECT_CLASS (gdata_media_content_parent_class)->finalize (object); +} + +static void +gdata_media_content_get_property (GObject *object, guint property_id, GValue *value, GParamSpec *pspec) +{ + GDataMediaContentPrivate *priv = GDATA_MEDIA_CONTENT (object)->priv; + + switch (property_id) { + case PROP_URI: + g_value_set_string (value, priv->uri); + break; + case PROP_FILESIZE: + g_value_set_ulong (value, priv->filesize); + break; + case PROP_CONTENT_TYPE: + g_value_set_string (value, priv->content_type); + break; + case PROP_MEDIUM: + g_value_set_enum (value, priv->medium); + break; + case PROP_IS_DEFAULT: + g_value_set_boolean (value, priv->is_default); + break; + case PROP_EXPRESSION: + g_value_set_enum (value, priv->expression); + break; + case PROP_DURATION: + g_value_set_int64 (value, priv->duration); + break; + case PROP_HEIGHT: + g_value_set_uint (value, priv->height); + break; + case PROP_WIDTH: + g_value_set_uint (value, priv->width); + break; + default: + /* We don't have any other property... */ + G_OBJECT_WARN_INVALID_PROPERTY_ID (object, property_id, pspec); + break; + } +} + +static gboolean +pre_parse_xml (GDataParsable *parsable, xmlDoc *doc, xmlNode *root_node, gpointer user_data, GError **error) +{ + GDataMediaContentPrivate *priv = GDATA_MEDIA_CONTENT (parsable)->priv; + xmlChar *uri, *expression, *medium, *duration, *filesize, *height, *width; + gboolean is_default_bool; + GDataMediaExpression expression_enum; + GDataMediaMedium medium_enum; + guint height_uint, width_uint; + gint64 duration_int64; + gulong filesize_ulong; + + /* Parse isDefault */ + if (gdata_parser_boolean_from_property (root_node, "isDefault", &is_default_bool, 0, error) == FALSE) + return FALSE; + + /* Parse expression */ + expression = xmlGetProp (root_node, (xmlChar*) "expression"); + if (expression == NULL || xmlStrcmp (expression, (xmlChar*) "full") == 0) { + expression_enum = GDATA_MEDIA_EXPRESSION_FULL; + } else if (xmlStrcmp (expression, (xmlChar*) "sample") == 0) { + expression_enum = GDATA_MEDIA_EXPRESSION_SAMPLE; + } else if (xmlStrcmp (expression, (xmlChar*) "nonstop") == 0) { + expression_enum = GDATA_MEDIA_EXPRESSION_NONSTOP; + } else { + gdata_parser_error_unknown_property_value (root_node, "expression", (gchar*) expression, error); + xmlFree (expression); + return FALSE; + } + xmlFree (expression); + + /* Parse medium */ + medium = xmlGetProp (root_node, (xmlChar*) "medium"); + if (medium == NULL) { + medium_enum = GDATA_MEDIA_UNKNOWN; + } else if (xmlStrcmp (medium, (xmlChar*) "image") == 0) { + medium_enum = GDATA_MEDIA_IMAGE; + } else if (xmlStrcmp (medium, (xmlChar*) "audio") == 0) { + medium_enum = GDATA_MEDIA_AUDIO; + } else if (xmlStrcmp (medium, (xmlChar*) "video") == 0) { + medium_enum = GDATA_MEDIA_VIDEO; + } else if (xmlStrcmp (medium, (xmlChar*) "document") == 0) { + medium_enum = GDATA_MEDIA_DOCUMENT; + } else if (xmlStrcmp (medium, (xmlChar*) "executable") == 0) { + medium_enum = GDATA_MEDIA_EXECUTABLE; + } else { + gdata_parser_error_unknown_property_value (root_node, "medium", (gchar*) medium, error); + xmlFree (medium); + return FALSE; + } + xmlFree (medium); + + /* Parse duration */ + duration = xmlGetProp (root_node, (xmlChar*) "duration"); + duration_int64 = (duration == NULL) ? 0 : g_ascii_strtoll ((gchar*) duration, NULL, 10); + xmlFree (duration); + + /* Parse filesize */ + filesize = xmlGetProp (root_node, (xmlChar*) "fileSize"); + filesize_ulong = (filesize == NULL) ? 0 : g_ascii_strtoull ((gchar*) filesize, NULL, 10); + xmlFree (filesize); + + /* Parse height and width */ + height = xmlGetProp (root_node, (xmlChar*) "height"); + height_uint = (height == NULL) ? 0 : g_ascii_strtoull ((gchar*) height, NULL, 10); + xmlFree (height); + + width = xmlGetProp (root_node, (xmlChar*) "width"); + width_uint = (width == NULL) ? 0 : g_ascii_strtoull ((gchar*) width, NULL, 10); + xmlFree (width); + + /* Other properties */ + uri = xmlGetProp (root_node, (xmlChar*) "url"); + if (uri != NULL && *uri == '\0') { + xmlFree (uri); + return gdata_parser_error_required_property_missing (root_node, "url", error); + } + + priv->uri = (gchar*) uri; + priv->filesize = filesize_ulong; + priv->content_type = (gchar*) xmlGetProp (root_node, (xmlChar*) "type"); + priv->medium = medium_enum; + priv->is_default = is_default_bool; + priv->expression = expression_enum; + priv->duration = duration_int64; + priv->height = height_uint; + priv->width = width_uint; + + return TRUE; +} + +static void +get_namespaces (GDataParsable *parsable, GHashTable *namespaces) +{ + g_hash_table_insert (namespaces, (gchar*) "media", (gchar*) "http://search.yahoo.com/mrss/"); +} + +/** + * gdata_media_content_get_uri: + * @self: a #GDataMediaContent + * + * Gets the #GDataMediaContent:uri property. + * + * Return value: the content's URI + * + * Since: 0.4.0 + */ +const gchar * +gdata_media_content_get_uri (GDataMediaContent *self) +{ + g_return_val_if_fail (GDATA_IS_MEDIA_CONTENT (self), NULL); + return self->priv->uri; +} + +/** + * gdata_media_content_get_filesize: + * @self: a #GDataMediaContent + * + * Gets the #GDataMediaContent:filesize property. + * + * Return value: the number of bytes in the content, or 0 + * + * Since: 0.4.0 + */ +gsize +gdata_media_content_get_filesize (GDataMediaContent *self) +{ + g_return_val_if_fail (GDATA_IS_MEDIA_CONTENT (self), 0); + return self->priv->filesize; +} + +/** + * gdata_media_content_get_content_type: + * @self: a #GDataMediaContent + * + * Gets the #GDataMediaContent:content-type property. + * + * Return value: the content's content (MIME) type, or %NULL + * + * Since: 0.4.0 + */ +const gchar * +gdata_media_content_get_content_type (GDataMediaContent *self) +{ + g_return_val_if_fail (GDATA_IS_MEDIA_CONTENT (self), NULL); + return self->priv->content_type; +} + +/** + * gdata_media_content_get_medium: + * @self: a #GDataMediaContent + * + * Gets the #GDataMediaContent:medium property. + * + * Return value: the type of the content, or %GDATA_MEDIA_UNKNOWN + * + * Since: 0.4.0 + */ +GDataMediaMedium +gdata_media_content_get_medium (GDataMediaContent *self) +{ + g_return_val_if_fail (GDATA_IS_MEDIA_CONTENT (self), GDATA_MEDIA_UNKNOWN); + return self->priv->medium; +} + +/** + * gdata_media_content_is_default: + * @self: a #GDataMediaContent + * + * Gets the #GDataMediaContent:is-default property. + * + * Return value: %TRUE if the #GDataMediaContent is the default content for the media group, %FALSE otherwise + * + * Since: 0.4.0 + */ +gboolean +gdata_media_content_is_default (GDataMediaContent *self) +{ + g_return_val_if_fail (GDATA_IS_MEDIA_CONTENT (self), FALSE); + return self->priv->is_default; +} + +/** + * gdata_media_content_get_expression: + * @self: a #GDataMediaContent + * + * Gets the #GDataMediaContent:expression property. + * + * Return value: the content's expression, or %GDATA_MEDIA_EXPRESSION_FULL + * + * Since: 0.4.0 + */ +GDataMediaExpression +gdata_media_content_get_expression (GDataMediaContent *self) +{ + g_return_val_if_fail (GDATA_IS_MEDIA_CONTENT (self), GDATA_MEDIA_EXPRESSION_FULL); + return self->priv->expression; +} + +/** + * gdata_media_content_get_duration: + * @self: a #GDataMediaContent + * + * Gets the #GDataMediaContent:duration property. + * + * Return value: the content's duration in seconds, or 0 + * + * Since: 0.4.0 + */ +gint64 +gdata_media_content_get_duration (GDataMediaContent *self) +{ + g_return_val_if_fail (GDATA_IS_MEDIA_CONTENT (self), 0); + return self->priv->duration; +} + +/** + * gdata_media_content_get_height: + * @self: a #GDataMediaContent + * + * Gets the #GDataMediaContent:height property. + * + * Return value: the content's height in pixels, or 0 + * + * Since: 0.4.0 + */ +guint +gdata_media_content_get_height (GDataMediaContent *self) +{ + g_return_val_if_fail (GDATA_IS_MEDIA_CONTENT (self), 0); + return self->priv->height; +} + +/** + * gdata_media_content_get_width: + * @self: a #GDataMediaContent + * + * Gets the #GDataMediaContent:width property. + * + * Return value: the content's width in pixels, or 0 + * + * Since: 0.4.0 + */ +guint +gdata_media_content_get_width (GDataMediaContent *self) +{ + g_return_val_if_fail (GDATA_IS_MEDIA_CONTENT (self), 0); + return self->priv->width; +} + +/** + * gdata_media_content_download: + * @self: a #GDataMediaContent + * @service: the #GDataService + * @cancellable: (allow-none): a #GCancellable for the entire download stream, or %NULL + * @error: a #GError, or %NULL + * + * Downloads and returns a #GDataDownloadStream allowing the content represented by @self to be read. + * + * To get the content type of the downloaded data, gdata_download_stream_get_content_type() can be called on the returned #GDataDownloadStream. + * Calling gdata_download_stream_get_content_length() on the stream will not return a meaningful result, however, as the stream is encoded in chunks, + * rather than by content length. + * + * In order to cancel the download, a #GCancellable passed in to @cancellable must be cancelled using g_cancellable_cancel(). Cancelling the individual + * #GInputStream operations on the #GDataDownloadStream will not cancel the entire download; merely the read or close operation in question. See the + * #GDataDownloadStream:cancellable for more details. + * + * Return value: (transfer full): a #GDataDownloadStream to download the content with, or %NULL; unref with g_object_unref() + * + * Since: 0.8.0 + */ +GDataDownloadStream * +gdata_media_content_download (GDataMediaContent *self, GDataService *service, GCancellable *cancellable, GError **error) +{ + const gchar *src_uri; + + g_return_val_if_fail (GDATA_IS_MEDIA_CONTENT (self), NULL); + g_return_val_if_fail (GDATA_IS_SERVICE (service), NULL); + g_return_val_if_fail (cancellable == NULL || G_IS_CANCELLABLE (cancellable), NULL); + g_return_val_if_fail (error == NULL || *error == NULL, NULL); + + /* We keep a GError in the argument list so that we can add authentication errors, etc., in future if necessary */ + + /* Get the download URI and create a stream for it */ + src_uri = gdata_media_content_get_uri (self); + return GDATA_DOWNLOAD_STREAM (gdata_download_stream_new (service, NULL, src_uri, cancellable)); +} diff --git a/gdata/media/gdata-media-content.h b/gdata/media/gdata-media-content.h new file mode 100644 index 0000000..c7c4954 --- /dev/null +++ b/gdata/media/gdata-media-content.h @@ -0,0 +1,121 @@ +/* -*- Mode: C; indent-tabs-mode: t; c-basic-offset: 8; tab-width: 8 -*- */ +/* + * GData Client + * Copyright (C) Philip Withnall 2009–2010 + * + * GData Client is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * GData Client is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with GData Client. If not, see . + */ + +#ifndef GDATA_MEDIA_CONTENT_H +#define GDATA_MEDIA_CONTENT_H + +#include +#include + +#include +#include +#include + +G_BEGIN_DECLS + +/** + * GDataMediaExpression: + * @GDATA_MEDIA_EXPRESSION_SAMPLE: the media is a sample of a larger video + * @GDATA_MEDIA_EXPRESSION_FULL: the media is the full version + * @GDATA_MEDIA_EXPRESSION_NONSTOP: the media is a continuous stream + * + * An enum representing the possible values of #GDataMediaContent:expression. + */ +typedef enum { + GDATA_MEDIA_EXPRESSION_SAMPLE, + GDATA_MEDIA_EXPRESSION_FULL, + GDATA_MEDIA_EXPRESSION_NONSTOP +} GDataMediaExpression; + +/** + * GDataMediaMedium: + * @GDATA_MEDIA_UNKNOWN: the type of the media is unknown + * @GDATA_MEDIA_IMAGE: the media is an image + * @GDATA_MEDIA_AUDIO: the media is an audio stream + * @GDATA_MEDIA_VIDEO: the media is a video + * @GDATA_MEDIA_DOCUMENT: the media is another type of document + * @GDATA_MEDIA_EXECUTABLE: the media is an executable file + * + * An enum representing the possible values of #GDataMediaContent:medium. + * + * Since: 0.4.0 + */ +typedef enum { + GDATA_MEDIA_UNKNOWN, + GDATA_MEDIA_IMAGE, + GDATA_MEDIA_AUDIO, + GDATA_MEDIA_VIDEO, + GDATA_MEDIA_DOCUMENT, + GDATA_MEDIA_EXECUTABLE +} GDataMediaMedium; + +#define GDATA_TYPE_MEDIA_CONTENT (gdata_media_content_get_type ()) +#define GDATA_MEDIA_CONTENT(o) (G_TYPE_CHECK_INSTANCE_CAST ((o), GDATA_TYPE_MEDIA_CONTENT, GDataMediaContent)) +#define GDATA_MEDIA_CONTENT_CLASS(k) (G_TYPE_CHECK_CLASS_CAST((k), GDATA_TYPE_MEDIA_CONTENT, GDataMediaContentClass)) +#define GDATA_IS_MEDIA_CONTENT(o) (G_TYPE_CHECK_INSTANCE_TYPE ((o), GDATA_TYPE_MEDIA_CONTENT)) +#define GDATA_IS_MEDIA_CONTENT_CLASS(k) (G_TYPE_CHECK_CLASS_TYPE ((k), GDATA_TYPE_MEDIA_CONTENT)) +#define GDATA_MEDIA_CONTENT_GET_CLASS(o) (G_TYPE_INSTANCE_GET_CLASS ((o), GDATA_TYPE_MEDIA_CONTENT, GDataMediaContentClass)) + +typedef struct _GDataMediaContentPrivate GDataMediaContentPrivate; + +/** + * GDataMediaContent: + * + * All the fields in the #GDataMediaContent structure are private and should never be accessed directly. + */ +typedef struct { + GDataParsable parent; + GDataMediaContentPrivate *priv; +} GDataMediaContent; + +/** + * GDataMediaContentClass: + * + * All the fields in the #GDataMediaContentClass structure are private and should never be accessed directly. + * + * Since: 0.4.0 + */ +typedef struct { + /*< private >*/ + GDataParsableClass parent; + + /*< private >*/ + /* Padding for future expansion */ + void (*_g_reserved0) (void); + void (*_g_reserved1) (void); +} GDataMediaContentClass; + +GType gdata_media_content_get_type (void) G_GNUC_CONST; + +const gchar *gdata_media_content_get_uri (GDataMediaContent *self) G_GNUC_PURE; +gsize gdata_media_content_get_filesize (GDataMediaContent *self) G_GNUC_PURE; +const gchar *gdata_media_content_get_content_type (GDataMediaContent *self) G_GNUC_PURE; +GDataMediaMedium gdata_media_content_get_medium (GDataMediaContent *self) G_GNUC_PURE; +gboolean gdata_media_content_is_default (GDataMediaContent *self) G_GNUC_PURE; +GDataMediaExpression gdata_media_content_get_expression (GDataMediaContent *self) G_GNUC_PURE; +gint64 gdata_media_content_get_duration (GDataMediaContent *self) G_GNUC_PURE; +guint gdata_media_content_get_height (GDataMediaContent *self) G_GNUC_PURE; +guint gdata_media_content_get_width (GDataMediaContent *self) G_GNUC_PURE; + +GDataDownloadStream *gdata_media_content_download (GDataMediaContent *self, GDataService *service, GCancellable *cancellable, + GError **error) G_GNUC_WARN_UNUSED_RESULT G_GNUC_MALLOC; + +G_END_DECLS + +#endif /* !GDATA_MEDIA_CONTENT_H */ diff --git a/gdata/media/gdata-media-credit.c b/gdata/media/gdata-media-credit.c new file mode 100644 index 0000000..de20677 --- /dev/null +++ b/gdata/media/gdata-media-credit.c @@ -0,0 +1,268 @@ +/* -*- Mode: C; indent-tabs-mode: t; c-basic-offset: 8; tab-width: 8 -*- */ +/* + * GData Client + * Copyright (C) Philip Withnall 2009–2010 + * + * GData Client is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * GData Client is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with GData Client. If not, see . + */ + +/** + * SECTION:gdata-media-credit + * @short_description: Media RSS credit element + * @stability: Stable + * @include: gdata/media/gdata-media-credit.h + * + * #GDataMediaCredit represents a "credit" element from the + * Media RSS specification. + * + * The class only implements parsing, not XML output, at the moment. + * + * Since: 0.4.0 + */ + +#include +#include + +#include "gdata-media-credit.h" +#include "gdata-parsable.h" +#include "gdata-parser.h" +#include "gdata-types.h" + +static void gdata_media_credit_finalize (GObject *object); +static void gdata_media_credit_get_property (GObject *object, guint property_id, GValue *value, GParamSpec *pspec); +static gboolean pre_parse_xml (GDataParsable *parsable, xmlDoc *doc, xmlNode *root_node, gpointer user_data, GError **error); +static gboolean parse_xml (GDataParsable *parsable, xmlDoc *doc, xmlNode *node, gpointer user_data, GError **error); +static void get_namespaces (GDataParsable *parsable, GHashTable *namespaces); + +struct _GDataMediaCreditPrivate { + gchar *credit; + gchar *scheme; + gchar *role; +}; + +enum { + PROP_CREDIT = 1, + PROP_SCHEME, + PROP_ROLE +}; + +G_DEFINE_TYPE (GDataMediaCredit, gdata_media_credit, GDATA_TYPE_PARSABLE) + +static void +gdata_media_credit_class_init (GDataMediaCreditClass *klass) +{ + GObjectClass *gobject_class = G_OBJECT_CLASS (klass); + GDataParsableClass *parsable_class = GDATA_PARSABLE_CLASS (klass); + + g_type_class_add_private (klass, sizeof (GDataMediaCreditPrivate)); + + gobject_class->get_property = gdata_media_credit_get_property; + gobject_class->finalize = gdata_media_credit_finalize; + + parsable_class->pre_parse_xml = pre_parse_xml; + parsable_class->parse_xml = parse_xml; + parsable_class->get_namespaces = get_namespaces; + parsable_class->element_name = "credit"; + parsable_class->element_namespace = "media"; + + /** + * GDataMediaCredit:credit: + * + * The credited entity's name. + * + * For more information, see the Media RSS specification. + * + * Since: 0.4.0 + */ + g_object_class_install_property (gobject_class, PROP_CREDIT, + g_param_spec_string ("credit", + "Credit", "The credited entity's name.", + NULL, + G_PARAM_READABLE | G_PARAM_STATIC_STRINGS)); + + /** + * GDataMediaCredit:scheme: + * + * A URI that identifies the role scheme. + * + * For more information, see the Media RSS specification. + * + * Since: 0.4.0 + */ + g_object_class_install_property (gobject_class, PROP_SCHEME, + g_param_spec_string ("scheme", + "Scheme", "A URI that identifies the role scheme.", + NULL, + G_PARAM_READABLE | G_PARAM_STATIC_STRINGS)); + + /** + * GDataMediaCredit:role: + * + * The role the credited entity played in the production of the media. + * + * For more information, see the Media RSS specification. + * + * Since: 0.4.0 + */ + g_object_class_install_property (gobject_class, PROP_ROLE, + g_param_spec_string ("role", + "Role", "The role the credited entity played in the production of the media.", + NULL, + G_PARAM_READABLE | G_PARAM_STATIC_STRINGS)); +} + +static void +gdata_media_credit_init (GDataMediaCredit *self) +{ + self->priv = G_TYPE_INSTANCE_GET_PRIVATE (self, GDATA_TYPE_MEDIA_CREDIT, GDataMediaCreditPrivate); +} + +static void +gdata_media_credit_finalize (GObject *object) +{ + GDataMediaCreditPrivate *priv = GDATA_MEDIA_CREDIT (object)->priv; + + g_free (priv->credit); + g_free (priv->scheme); + g_free (priv->role); + + /* Chain up to the parent class */ + G_OBJECT_CLASS (gdata_media_credit_parent_class)->finalize (object); +} + +static void +gdata_media_credit_get_property (GObject *object, guint property_id, GValue *value, GParamSpec *pspec) +{ + GDataMediaCreditPrivate *priv = GDATA_MEDIA_CREDIT (object)->priv; + + switch (property_id) { + case PROP_CREDIT: + g_value_set_string (value, priv->credit); + break; + case PROP_SCHEME: + g_value_set_string (value, priv->scheme); + break; + case PROP_ROLE: + g_value_set_string (value, priv->role); + break; + default: + /* We don't have any other property... */ + G_OBJECT_WARN_INVALID_PROPERTY_ID (object, property_id, pspec); + break; + } +} + +static gboolean +pre_parse_xml (GDataParsable *parsable, xmlDoc *doc, xmlNode *root_node, gpointer user_data, GError **error) +{ + GDataMediaCreditPrivate *priv = GDATA_MEDIA_CREDIT (parsable)->priv; + xmlChar *credit; + gchar *scheme; + guint i; + + credit = xmlNodeListGetString (doc, root_node->children, TRUE); + if (credit == NULL || *credit == '\0') { + xmlFree (credit); + return gdata_parser_error_required_content_missing (root_node, error); + } + + scheme = (gchar*) xmlGetProp (root_node, (xmlChar*) "scheme"); + if (scheme != NULL && *scheme == '\0') { + g_free (scheme); + xmlFree (credit); + return gdata_parser_error_required_property_missing (root_node, "scheme", error); + } else if (scheme == NULL) { + /* Default */ + scheme = g_strdup ("urn:ebu"); + } + + priv->credit = (gchar*) credit; + priv->scheme = scheme; + priv->role = (gchar*) xmlGetProp (root_node, (xmlChar*) "role"); + + /* Convert the role to lower case */ + if (priv->role != NULL) { + for (i = 0; priv->role[i] != '\0'; i++) + priv->role[i] = g_ascii_tolower (priv->role[i]); + } + + return TRUE; +} + +static gboolean +parse_xml (GDataParsable *parsable, xmlDoc *doc, xmlNode *node, gpointer user_data, GError **error) +{ + /* Textual content's handled in pre_parse_xml */ + if (node->type != XML_ELEMENT_NODE) + return TRUE; + + return GDATA_PARSABLE_CLASS (gdata_media_credit_parent_class)->parse_xml (parsable, doc, node, user_data, error); +} + +static void +get_namespaces (GDataParsable *parsable, GHashTable *namespaces) +{ + g_hash_table_insert (namespaces, (gchar*) "media", (gchar*) "http://search.yahoo.com/mrss/"); +} + +/** + * gdata_media_credit_get_credit: + * @self: a #GDataMediaCredit + * + * Gets the #GDataMediaCredit:credit property. + * + * Return value: the name of the credited entity + * + * Since: 0.4.0 + */ +const gchar * +gdata_media_credit_get_credit (GDataMediaCredit *self) +{ + g_return_val_if_fail (GDATA_IS_MEDIA_CREDIT (self), NULL); + return self->priv->credit; +} + +/** + * gdata_media_credit_get_scheme: + * @self: a #GDataMediaCredit + * + * Gets the #GDataMediaCredit:scheme property. + * + * Return value: the credit's role scheme, or %NULL + * + * Since: 0.4.0 + */ +const gchar * +gdata_media_credit_get_scheme (GDataMediaCredit *self) +{ + g_return_val_if_fail (GDATA_IS_MEDIA_CREDIT (self), NULL); + return self->priv->scheme; +} + +/** + * gdata_media_credit_get_role: + * @self: a #GDataMediaCredit + * + * Gets the #GDataMediaCredit:role property. + * + * Return value: the credited entity's role, or %NULL + * + * Since: 0.4.0 + */ +const gchar * +gdata_media_credit_get_role (GDataMediaCredit *self) +{ + g_return_val_if_fail (GDATA_IS_MEDIA_CREDIT (self), NULL); + return self->priv->role; +} diff --git a/gdata/media/gdata-media-credit.h b/gdata/media/gdata-media-credit.h new file mode 100644 index 0000000..a8b054e --- /dev/null +++ b/gdata/media/gdata-media-credit.h @@ -0,0 +1,74 @@ +/* -*- Mode: C; indent-tabs-mode: t; c-basic-offset: 8; tab-width: 8 -*- */ +/* + * GData Client + * Copyright (C) Philip Withnall 2009 + * + * GData Client is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * GData Client is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with GData Client. If not, see . + */ + +#ifndef GDATA_MEDIA_CREDIT_H +#define GDATA_MEDIA_CREDIT_H + +#include +#include + +#include + +G_BEGIN_DECLS + +#define GDATA_TYPE_MEDIA_CREDIT (gdata_media_credit_get_type ()) +#define GDATA_MEDIA_CREDIT(o) (G_TYPE_CHECK_INSTANCE_CAST ((o), GDATA_TYPE_MEDIA_CREDIT, GDataMediaCredit)) +#define GDATA_MEDIA_CREDIT_CLASS(k) (G_TYPE_CHECK_CLASS_CAST((k), GDATA_TYPE_MEDIA_CREDIT, GDataMediaCreditClass)) +#define GDATA_IS_MEDIA_CREDIT(o) (G_TYPE_CHECK_INSTANCE_TYPE ((o), GDATA_TYPE_MEDIA_CREDIT)) +#define GDATA_IS_MEDIA_CREDIT_CLASS(k) (G_TYPE_CHECK_CLASS_TYPE ((k), GDATA_TYPE_MEDIA_CREDIT)) +#define GDATA_MEDIA_CREDIT_GET_CLASS(o) (G_TYPE_INSTANCE_GET_CLASS ((o), GDATA_TYPE_MEDIA_CREDIT, GDataMediaCreditClass)) + +typedef struct _GDataMediaCreditPrivate GDataMediaCreditPrivate; + +/** + * GDataMediaCredit: + * + * All the fields in the #GDataMediaCredit structure are private and should never be accessed directly. + */ +typedef struct { + GDataParsable parent; + GDataMediaCreditPrivate *priv; +} GDataMediaCredit; + +/** + * GDataMediaCreditClass: + * + * All the fields in the #GDataMediaCreditClass structure are private and should never be accessed directly. + * + * Since: 0.4.0 + */ +typedef struct { + /*< private >*/ + GDataParsableClass parent; + + /*< private >*/ + /* Padding for future expansion */ + void (*_g_reserved0) (void); + void (*_g_reserved1) (void); +} GDataMediaCreditClass; + +GType gdata_media_credit_get_type (void) G_GNUC_CONST; + +const gchar *gdata_media_credit_get_credit (GDataMediaCredit *self) G_GNUC_PURE; +const gchar *gdata_media_credit_get_scheme (GDataMediaCredit *self) G_GNUC_PURE; +const gchar *gdata_media_credit_get_role (GDataMediaCredit *self) G_GNUC_PURE; + +G_END_DECLS + +#endif /* !GDATA_MEDIA_CREDIT_H */ diff --git a/gdata/media/gdata-media-group.c b/gdata/media/gdata-media-group.c new file mode 100644 index 0000000..6d0db9b --- /dev/null +++ b/gdata/media/gdata-media-group.c @@ -0,0 +1,667 @@ +/* -*- Mode: C; indent-tabs-mode: t; c-basic-offset: 8; tab-width: 8 -*- */ +/* + * GData Client + * Copyright (C) Philip Withnall 2009–2010 + * + * GData Client is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * GData Client is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with GData Client. If not, see . + */ + +/* + * SECTION:gdata-media-group + * @short_description: Media RSS group element + * @stability: Stable + * @include: gdata/media/gdata-media-group.h + * + * #GDataMediaGroup represents a "group" element from the + * Media RSS specification. + * + * It is private API, since implementing classes are likely to proxy the properties and functions + * of #GDataMediaGroup as appropriate; most entry types which implement #GDataMediaGroup have no use + * for most of its properties, and it would be unnecessary and confusing to expose #GDataMediaGroup itself. + * + * For this reason, properties have not been implemented on #GDataMediaGroup (yet). + */ + +#include +#include +#include + +#include "gdata-media-group.h" +#include "gdata-parsable.h" +#include "gdata-parser.h" +#include "gdata-private.h" +#include "media/gdata-media-category.h" +#include "media/gdata-media-credit.h" +#include "media/gdata-media-thumbnail.h" + +static void gdata_media_group_dispose (GObject *object); +static void gdata_media_group_finalize (GObject *object); +static gboolean parse_xml (GDataParsable *parsable, xmlDoc *doc, xmlNode *node, gpointer user_data, GError **error); +static void get_xml (GDataParsable *parsable, GString *xml_string); +static void get_namespaces (GDataParsable *parsable, GHashTable *namespaces); + +struct _GDataMediaGroupPrivate { + gchar **keywords; + gchar *player_uri; + GHashTable *restricted_countries; + gchar *simple_rating; + gchar *mpaa_rating; + gchar *v_chip_rating; + GList *thumbnails; /* GDataMediaThumbnail */ + gchar *title; + GDataMediaCategory *category; + GList *contents; /* GDataMediaContent */ + GDataMediaCredit *credit; + gchar *description; +}; + +G_DEFINE_TYPE (GDataMediaGroup, gdata_media_group, GDATA_TYPE_PARSABLE) + +static void +gdata_media_group_class_init (GDataMediaGroupClass *klass) +{ + GObjectClass *gobject_class = G_OBJECT_CLASS (klass); + GDataParsableClass *parsable_class = GDATA_PARSABLE_CLASS (klass); + + g_type_class_add_private (klass, sizeof (GDataMediaGroupPrivate)); + + gobject_class->dispose = gdata_media_group_dispose; + gobject_class->finalize = gdata_media_group_finalize; + + parsable_class->parse_xml = parse_xml; + parsable_class->get_xml = get_xml; + parsable_class->get_namespaces = get_namespaces; + parsable_class->element_name = "group"; + parsable_class->element_namespace = "media"; +} + +static void +gdata_media_group_init (GDataMediaGroup *self) +{ + self->priv = G_TYPE_INSTANCE_GET_PRIVATE (self, GDATA_TYPE_MEDIA_GROUP, GDataMediaGroupPrivate); + self->priv->restricted_countries = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, NULL); +} + +static void +gdata_media_group_dispose (GObject *object) +{ + GDataMediaGroupPrivate *priv = GDATA_MEDIA_GROUP (object)->priv; + + if (priv->category != NULL) + g_object_unref (priv->category); + priv->category = NULL; + + if (priv->credit != NULL) + g_object_unref (priv->credit); + priv->credit = NULL; + + g_list_free_full (priv->contents, g_object_unref); + priv->contents = NULL; + + g_list_free_full (priv->thumbnails, g_object_unref); + priv->thumbnails = NULL; + + /* Chain up to the parent class */ + G_OBJECT_CLASS (gdata_media_group_parent_class)->dispose (object); +} + +static void +gdata_media_group_finalize (GObject *object) +{ + GDataMediaGroupPrivate *priv = GDATA_MEDIA_GROUP (object)->priv; + + g_strfreev (priv->keywords); + g_free (priv->player_uri); + g_free (priv->v_chip_rating); + g_free (priv->mpaa_rating); + g_free (priv->simple_rating); + g_hash_table_destroy (priv->restricted_countries); + g_free (priv->title); + g_free (priv->description); + + /* Chain up to the parent class */ + G_OBJECT_CLASS (gdata_media_group_parent_class)->finalize (object); +} + +static gboolean +parse_xml (GDataParsable *parsable, xmlDoc *doc, xmlNode *node, gpointer user_data, GError **error) +{ + gboolean success; + GDataMediaGroup *self = GDATA_MEDIA_GROUP (parsable); + + if (gdata_parser_is_namespace (node, "http://search.yahoo.com/mrss/") == TRUE) { + if (gdata_parser_string_from_element (node, "title", P_NONE, &(self->priv->title), &success, error) == TRUE || + gdata_parser_string_from_element (node, "description", P_NONE, &(self->priv->description), &success, error) == TRUE || + gdata_parser_object_from_element_setter (node, "category", P_REQUIRED, GDATA_TYPE_MEDIA_CATEGORY, + gdata_media_group_set_category, self, &success, error) == TRUE || + gdata_parser_object_from_element_setter (node, "content", P_REQUIRED, GDATA_TYPE_MEDIA_CONTENT, + _gdata_media_group_add_content, self, &success, error) == TRUE || + gdata_parser_object_from_element_setter (node, "thumbnail", P_REQUIRED, GDATA_TYPE_MEDIA_THUMBNAIL, + _gdata_media_group_add_thumbnail, self, &success, error) == TRUE || + gdata_parser_object_from_element (node, "credit", P_REQUIRED | P_NO_DUPES, GDATA_TYPE_MEDIA_CREDIT, + &(self->priv->credit), &success, error) == TRUE) { + return success; + } else if (xmlStrcmp (node->name, (xmlChar*) "keywords") == 0) { + /* media:keywords */ + guint i; + xmlChar *text = xmlNodeListGetString (node->doc, node->children, TRUE); + + g_strfreev (self->priv->keywords); + if (text == NULL) { + self->priv->keywords = NULL; + return TRUE; + } + + self->priv->keywords = g_strsplit ((gchar*) text, ",", -1); + xmlFree (text); + + for (i = 0; self->priv->keywords[i] != NULL; i++) { + gchar *comma, *start = self->priv->keywords[i]; + gchar *end = start + strlen (start); + + /* Strip any whitespace from the ends of the keyword */ + g_strstrip (start); + + /* Unescape any %2Cs in the keyword to commas in-place */ + while ((comma = g_strstr_len (start, -1, "%2C")) != NULL) { + /* Unescape the comma */ + *comma = ','; + + /* Move forwards, skipping the comma */ + comma++; + end -= 2; + + /* Shift the remainder of the string downwards */ + memmove (comma, comma + 2, end - comma); + *end = '\0'; + } + } + } else if (xmlStrcmp (node->name, (xmlChar*) "player") == 0) { + /* media:player */ + xmlChar *player_uri = xmlGetProp (node, (xmlChar*) "url"); + g_free (self->priv->player_uri); + self->priv->player_uri = (gchar*) player_uri; + } else if (xmlStrcmp (node->name, (xmlChar*) "rating") == 0) { + /* media:rating */ + xmlChar *scheme; + + /* The possible schemes are defined here: + * • http://video.search.yahoo.com/mrss + * • http://code.google.com/apis/youtube/2.0/reference.html#youtube_data_api_tag_media:rating + */ + scheme = xmlGetProp (node, (xmlChar*) "scheme"); + + if (scheme == NULL || xmlStrcmp (scheme, (xmlChar*) "urn:simple") == 0) { + /* Options: adult, nonadult */ + gdata_parser_string_from_element (node, "rating", P_REQUIRED | P_NON_EMPTY, &(self->priv->simple_rating), + &success, error); + } else if (xmlStrcmp (scheme, (xmlChar*) "urn:mpaa") == 0) { + /* Options: g, pg, pg-13, r, nc-17 */ + gdata_parser_string_from_element (node, "rating", P_REQUIRED | P_NON_EMPTY, &(self->priv->mpaa_rating), + &success, error); + } else if (xmlStrcmp (scheme, (xmlChar*) "urn:v-chip") == 0) { + /* Options: tv-y, tv-y7, tv-y7-fv, tv-g, tv-pg, tv-14, tv-ma */ + gdata_parser_string_from_element (node, "rating", P_REQUIRED | P_NON_EMPTY, &(self->priv->v_chip_rating), + &success, error); + } else if (xmlStrcmp (scheme, (xmlChar*) "http://gdata.youtube.com/schemas/2007#mediarating") == 0) { + /* No content, but we do get a list of countries. There's nothing like overloading the semantics of XML elements + * to brighten up one's day. */ + xmlChar *countries; + + countries = xmlGetProp (node, (xmlChar*) "country"); + + if (countries != NULL) { + gchar **country_list, **country; + + /* It's either a comma-separated list of countries, or the value "all" */ + country_list = g_strsplit ((const gchar*) countries, ",", -1); + xmlFree (countries); + + /* Add all the listed countries to the restricted countries table */ + for (country = country_list; *country != NULL; country++) { + g_hash_table_insert (self->priv->restricted_countries, *country, GUINT_TO_POINTER (TRUE)); + } + + g_free (country_list); + } else { + /* Assume it's restricted in all countries */ + g_hash_table_insert (self->priv->restricted_countries, g_strdup ("all"), GUINT_TO_POINTER (TRUE)); + } + + success = TRUE; + } else { + /* Error */ + gdata_parser_error_unknown_property_value (node, "scheme", (gchar*) scheme, error); + success = FALSE; + } + + xmlFree (scheme); + + return success; + } else if (xmlStrcmp (node->name, (xmlChar*) "restriction") == 0) { + /* media:restriction */ + xmlChar *type, *countries, *relationship; + gchar **country_list, **country; + gboolean relationship_bool; + + /* Check the type property is "country" */ + type = xmlGetProp (node, (xmlChar*) "type"); + if (xmlStrcmp (type, (xmlChar*) "country") != 0) { + gdata_parser_error_unknown_property_value (node, "type", (gchar*) type, error); + xmlFree (type); + return FALSE; + } + xmlFree (type); + + relationship = xmlGetProp (node, (xmlChar*) "relationship"); + if (xmlStrcmp (relationship, (xmlChar*) "allow") == 0) { + relationship_bool = FALSE; /* it's *not* a restricted country */ + } else if (xmlStrcmp (relationship, (xmlChar*) "deny") == 0) { + relationship_bool = TRUE; /* it *is* a restricted country */ + } else { + gdata_parser_error_unknown_property_value (node, "relationship", (gchar*) relationship, error); + xmlFree (relationship); + return FALSE; + } + xmlFree (relationship); + + countries = xmlNodeListGetString (doc, node->children, TRUE); + country_list = g_strsplit ((const gchar*) countries, " ", -1); + xmlFree (countries); + + /* Add "all" to the table, since it's an exception table */ + g_hash_table_insert (self->priv->restricted_countries, g_strdup ("all"), GUINT_TO_POINTER (!relationship_bool)); + + /* Add all the listed countries to the restricted countries table */ + for (country = country_list; *country != NULL; country++) + g_hash_table_insert (self->priv->restricted_countries, *country, GUINT_TO_POINTER (relationship_bool)); + g_free (country_list); + } else { + return GDATA_PARSABLE_CLASS (gdata_media_group_parent_class)->parse_xml (parsable, doc, node, user_data, error); + } + } else { + return GDATA_PARSABLE_CLASS (gdata_media_group_parent_class)->parse_xml (parsable, doc, node, user_data, error); + } + + return TRUE; +} + +static void +get_xml (GDataParsable *parsable, GString *xml_string) +{ + GDataMediaGroupPrivate *priv = GDATA_MEDIA_GROUP (parsable)->priv; + + /* Media category */ + if (priv->category != NULL) + _gdata_parsable_get_xml (GDATA_PARSABLE (priv->category), xml_string, FALSE); + + if (priv->title != NULL) + gdata_parser_string_append_escaped (xml_string, "", priv->title, ""); + + if (priv->description != NULL) + gdata_parser_string_append_escaped (xml_string, "", priv->description, ""); + + if (priv->keywords != NULL) { + guint i; + + g_string_append (xml_string, ""); + + /* Add each keyword to the text content, comma-separated from the previous one */ + for (i = 0; priv->keywords[i] != NULL; i++) { + const gchar *comma, *start = priv->keywords[i]; + + /* Delimit the previous keyword */ + if (i != 0) + g_string_append_c (xml_string, ','); + + /* Escape any commas in the keyword to %2C */ + while ((comma = g_utf8_strchr (start, -1, ',')) != NULL) { + /* Copy the span */ + gchar *span = g_strndup (start, comma - start); + gdata_parser_string_append_escaped (xml_string, NULL, span, NULL); + g_free (span); + + /* Add an escaped comma */ + g_string_append (xml_string, "%2C"); + + /* Move forwards, skipping the comma */ + start = comma + 1; + } + + /* Append the rest of the string (the entire string if there were no commas) */ + gdata_parser_string_append_escaped (xml_string, NULL, start, NULL); + } + + g_string_append (xml_string, ""); + } +} + +static void +get_namespaces (GDataParsable *parsable, GHashTable *namespaces) +{ + g_hash_table_insert (namespaces, (gchar*) "media", (gchar*) "http://search.yahoo.com/mrss/"); +} + +/** + * gdata_media_group_get_title: + * @self: a #GDataMediaGroup + * + * Gets the #GDataMediaGroup:title property. + * + * Return value: the group's title, or %NULL + * + * Since: 0.4.0 + */ +const gchar * +gdata_media_group_get_title (GDataMediaGroup *self) +{ + g_return_val_if_fail (GDATA_IS_MEDIA_GROUP (self), NULL); + return self->priv->title; +} + +/** + * gdata_media_group_set_title: + * @self: a #GDataMediaGroup + * @title: (allow-none): the group's new title, or %NULL + * + * Sets the #GDataMediaGroup:title property to @title. + * + * Set @title to %NULL to unset the property. + * + * Since: 0.4.0 + */ +void +gdata_media_group_set_title (GDataMediaGroup *self, const gchar *title) +{ + g_return_if_fail (GDATA_IS_MEDIA_GROUP (self)); + g_free (self->priv->title); + self->priv->title = g_strdup (title); +} + +/** + * gdata_media_group_get_description: + * @self: a #GDataMediaGroup + * + * Gets the #GDataMediaGroup:description property. + * + * Return value: the group's description, or %NULL + * + * Since: 0.4.0 + */ +const gchar * +gdata_media_group_get_description (GDataMediaGroup *self) +{ + g_return_val_if_fail (GDATA_IS_MEDIA_GROUP (self), NULL); + return self->priv->description; +} + +/** + * gdata_media_group_set_description: + * @self: a #GDataMediaGroup + * @description: (allow-none): the group's new description, or %NULL + * + * Sets the #GDataMediaGroup:description property to @description. + * + * Set @description to %NULL to unset the property. + * + * Since: 0.4.0 + */ +void +gdata_media_group_set_description (GDataMediaGroup *self, const gchar *description) +{ + g_return_if_fail (GDATA_IS_MEDIA_GROUP (self)); + g_free (self->priv->description); + self->priv->description = g_strdup (description); +} + +/** + * gdata_media_group_get_keywords: + * @self: a #GDataMediaGroup + * + * Gets the #GDataMediaGroup:keywords property. + * + * Return value: (array zero-terminated=1): a %NULL-terminated array of the group's keywords, or %NULL + * + * Since: 0.4.0 + */ +const gchar * const * +gdata_media_group_get_keywords (GDataMediaGroup *self) +{ + g_return_val_if_fail (GDATA_IS_MEDIA_GROUP (self), NULL); + return (const gchar * const *) self->priv->keywords; +} + +/** + * gdata_media_group_set_keywords: + * @self: a #GDataMediaGroup + * @keywords: (array zero-terminated=1) (allow-none): a %NULL-terminated array of the group's new keywords, or %NULL + * + * Sets the #GDataMediaGroup:keywords property to @keywords. + * + * Set @keywords to %NULL to unset the property. + * + * Since: 0.4.0 + */ +void +gdata_media_group_set_keywords (GDataMediaGroup *self, const gchar * const *keywords) +{ + g_return_if_fail (GDATA_IS_MEDIA_GROUP (self)); + g_strfreev (self->priv->keywords); + self->priv->keywords = g_strdupv ((gchar**) keywords); +} + +/** + * gdata_media_group_get_category: + * @self: a #GDataMediaGroup + * + * Gets the #GDataMediaGroup:category property. + * + * Return value: a #GDataMediaCategory giving the group's category, or %NULL + */ +GDataMediaCategory * +gdata_media_group_get_category (GDataMediaGroup *self) +{ + g_return_val_if_fail (GDATA_IS_MEDIA_GROUP (self), NULL); + return self->priv->category; +} + +/** + * gdata_media_group_set_category: + * @self: a #GDataMediaGroup + * @category: (allow-none): a new #GDataMediaCategory, or %NULL + * + * Sets the #GDataMediaGroup:category property to @category, and increments its reference count. + */ +void +gdata_media_group_set_category (GDataMediaGroup *self, GDataMediaCategory *category) +{ + g_return_if_fail (GDATA_IS_MEDIA_GROUP (self)); + g_return_if_fail (category == NULL || GDATA_IS_MEDIA_CATEGORY (category)); + + if (self->priv->category != NULL) + g_object_unref (self->priv->category); + self->priv->category = (category == NULL) ? NULL : g_object_ref (category); +} + +static gint +content_compare_cb (const GDataMediaContent *content, const gchar *type) +{ + return strcmp (gdata_media_content_get_content_type ((GDataMediaContent*) content), type); +} + +/** + * gdata_media_group_look_up_content: + * @self: a #GDataMediaGroup + * @type: the MIME type of the content desired + * + * Looks up a #GDataMediaContent from the group with the given MIME type. The group's list of contents is + * a list of URIs to various formats of the group content itself, such as the SWF URI or RTSP stream for a video. + * + * Return value: (transfer none): a #GDataMediaContent matching @type, or %NULL + */ +GDataMediaContent * +gdata_media_group_look_up_content (GDataMediaGroup *self, const gchar *type) +{ + GList *element; + + g_return_val_if_fail (GDATA_IS_MEDIA_GROUP (self), NULL); + g_return_val_if_fail (type != NULL, NULL); + + /* TODO: If type is required, and is unique, the contents can be stored in a hash table rather than a linked list */ + element = g_list_find_custom (self->priv->contents, type, (GCompareFunc) content_compare_cb); + if (element == NULL) + return NULL; + return GDATA_MEDIA_CONTENT (element->data); +} + +/** + * gdata_media_group_get_contents: + * @self: a #GDataMediaGroup + * + * Returns a list of #GDataMediaContents, giving the content enclosed by the group. + * + * Return value: (element-type GData.MediaContent) (transfer none): a #GList of #GDataMediaContents, or %NULL + */ +GList * +gdata_media_group_get_contents (GDataMediaGroup *self) +{ + g_return_val_if_fail (GDATA_IS_MEDIA_GROUP (self), NULL); + return self->priv->contents; +} + +void +_gdata_media_group_add_content (GDataMediaGroup *self, GDataMediaContent *content) +{ + g_return_if_fail (GDATA_IS_MEDIA_GROUP (self)); + g_return_if_fail (GDATA_IS_MEDIA_CONTENT (content)); + self->priv->contents = g_list_prepend (self->priv->contents, g_object_ref (content)); +} + +/** + * gdata_media_group_get_credit: + * @self: a #GDataMediaGroup + * + * Gets the #GDataMediaGroup:credit property. + * + * Return value: a #GDataMediaCredit giving information on whom to credit for the media group, or %NULL + */ +GDataMediaCredit * +gdata_media_group_get_credit (GDataMediaGroup *self) +{ + g_return_val_if_fail (GDATA_IS_MEDIA_GROUP (self), NULL); + return self->priv->credit; +} + +void +_gdata_media_group_set_credit (GDataMediaGroup *self, GDataMediaCredit *credit) +{ + g_return_if_fail (GDATA_IS_MEDIA_GROUP (self)); + g_return_if_fail (credit == NULL ||GDATA_IS_MEDIA_CREDIT (credit)); + + if (self->priv->credit != NULL) + g_object_unref (self->priv->credit); + self->priv->credit = g_object_ref (credit); +} + +/** + * gdata_media_group_get_media_group: + * @self: a #GDataMediaGroup + * + * Gets the #GDataMediaGroup:player-uri property. + * + * Return value: a URI where the media group is playable in a web browser, or %NULL + */ +const gchar * +gdata_media_group_get_player_uri (GDataMediaGroup *self) +{ + g_return_val_if_fail (GDATA_IS_MEDIA_GROUP (self), NULL); + return self->priv->player_uri; +} + +/** + * gdata_media_group_is_restricted_in_country: + * @self: a #GDataMediaGroup + * @country: an ISO 3166 two-letter country code to check + * + * Checks whether viewing of the media is restricted in @country, either by its content rating, or by the request of the producer. + * The return value from this function is purely informational, and no obligation is assumed. + * + * Return value: %TRUE if the media is restricted in @country, %FALSE otherwise + */ +gboolean +gdata_media_group_is_restricted_in_country (GDataMediaGroup *self, const gchar *country) +{ + g_return_val_if_fail (GDATA_IS_MEDIA_GROUP (self), FALSE); + g_return_val_if_fail (country != NULL && *country != '\0', FALSE); + + if (GPOINTER_TO_UINT (g_hash_table_lookup (self->priv->restricted_countries, country)) == TRUE) + return TRUE; + + return GPOINTER_TO_UINT (g_hash_table_lookup (self->priv->restricted_countries, "all")); +} + +/** + * gdata_media_group_get_media_rating: + * @self: a #GDataMediaGroup + * @rating_type: the type of rating to retrieve + * + * Returns the rating of the given type for the media, if one exists. For example, this could be a film rating awarded by the MPAA. + * The valid values for @rating_type are: simple, mpaa and + * v-chip. + * + * The rating values returned for each of these rating types are string as defined in the + * YouTube documentation and + * MRSS specification. + * + * Return value: rating for the given rating type, or %NULL if the media has no rating for that type (or the type is invalid) + */ +const gchar * +gdata_media_group_get_media_rating (GDataMediaGroup *self, const gchar *rating_type) +{ + g_return_val_if_fail (GDATA_IS_MEDIA_GROUP (self), NULL); + g_return_val_if_fail (rating_type != NULL && *rating_type != '\0', NULL); + + if (strcmp (rating_type, "simple") == 0) { + return self->priv->simple_rating; + } else if (strcmp (rating_type, "mpaa") == 0) { + return self->priv->mpaa_rating; + } else if (strcmp (rating_type, "v-chip") == 0) { + return self->priv->v_chip_rating; + } + + return NULL; +} + +/** + * gdata_media_group_get_thumbnails: + * @self: a #GDataMediaGroup + * + * Gets a list of the thumbnails available for the group. + * + * Return value: (element-type GData.MediaThumbnail) (transfer none): a #GList of #GDataMediaThumbnails, or %NULL + */ +GList * +gdata_media_group_get_thumbnails (GDataMediaGroup *self) +{ + g_return_val_if_fail (GDATA_IS_MEDIA_GROUP (self), NULL); + return self->priv->thumbnails; +} + +void +_gdata_media_group_add_thumbnail (GDataMediaGroup *self, GDataMediaThumbnail *thumbnail) +{ + g_return_if_fail (GDATA_IS_MEDIA_GROUP (self)); + g_return_if_fail (GDATA_IS_MEDIA_THUMBNAIL (thumbnail)); + self->priv->thumbnails = g_list_prepend (self->priv->thumbnails, g_object_ref (thumbnail)); +} diff --git a/gdata/media/gdata-media-group.h b/gdata/media/gdata-media-group.h new file mode 100644 index 0000000..0845ba1 --- /dev/null +++ b/gdata/media/gdata-media-group.h @@ -0,0 +1,93 @@ +/* -*- Mode: C; indent-tabs-mode: t; c-basic-offset: 8; tab-width: 8 -*- */ +/* + * GData Client + * Copyright (C) Philip Withnall 2009 + * + * GData Client is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * GData Client is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with GData Client. If not, see . + */ + +#ifndef GDATA_MEDIA_GROUP_H +#define GDATA_MEDIA_GROUP_H + +#include +#include + +#include +#include +#include +#include +#include + +G_BEGIN_DECLS + +#define GDATA_TYPE_MEDIA_GROUP (gdata_media_group_get_type ()) +#define GDATA_MEDIA_GROUP(o) (G_TYPE_CHECK_INSTANCE_CAST ((o), GDATA_TYPE_MEDIA_GROUP, GDataMediaGroup)) +#define GDATA_MEDIA_GROUP_CLASS(k) (G_TYPE_CHECK_CLASS_CAST((k), GDATA_TYPE_MEDIA_GROUP, GDataMediaGroupClass)) +#define GDATA_IS_MEDIA_GROUP(o) (G_TYPE_CHECK_INSTANCE_TYPE ((o), GDATA_TYPE_MEDIA_GROUP)) +#define GDATA_IS_MEDIA_GROUP_CLASS(k) (G_TYPE_CHECK_CLASS_TYPE ((k), GDATA_TYPE_MEDIA_GROUP)) +#define GDATA_MEDIA_GROUP_GET_CLASS(o) (G_TYPE_INSTANCE_GET_CLASS ((o), GDATA_TYPE_MEDIA_GROUP, GDataMediaGroupClass)) + +typedef struct _GDataMediaGroupPrivate GDataMediaGroupPrivate; + +/** + * GDataMediaGroup: + * + * All the fields in the #GDataMediaGroup structure are private and should never be accessed directly. + */ +typedef struct { + GDataParsable parent; + GDataMediaGroupPrivate *priv; +} GDataMediaGroup; + +/** + * GDataMediaGroupClass: + * + * All the fields in the #GDataMediaGroupClass structure are private and should never be accessed directly. + * + * Since: 0.4.0 + */ +typedef struct { + /*< private >*/ + GDataParsableClass parent; + + /*< private >*/ + /* Padding for future expansion */ + void (*_g_reserved0) (void); + void (*_g_reserved1) (void); +} GDataMediaGroupClass; + +GType gdata_media_group_get_type (void) G_GNUC_CONST; + +const gchar *gdata_media_group_get_title (GDataMediaGroup *self) G_GNUC_PURE; +void gdata_media_group_set_title (GDataMediaGroup *self, const gchar *title); +const gchar *gdata_media_group_get_description (GDataMediaGroup *self) G_GNUC_PURE; +void gdata_media_group_set_description (GDataMediaGroup *self, const gchar *description); +const gchar * const *gdata_media_group_get_keywords (GDataMediaGroup *self) G_GNUC_PURE; +void gdata_media_group_set_keywords (GDataMediaGroup *self, const gchar * const *keywords); +GDataMediaCategory *gdata_media_group_get_category (GDataMediaGroup *self) G_GNUC_PURE; +void gdata_media_group_set_category (GDataMediaGroup *self, GDataMediaCategory *category); +GDataMediaContent *gdata_media_group_look_up_content (GDataMediaGroup *self, const gchar *type) G_GNUC_PURE; +GList *gdata_media_group_get_contents (GDataMediaGroup *self) G_GNUC_PURE; +void _gdata_media_group_add_content (GDataMediaGroup *self, GDataMediaContent *content); +GDataMediaCredit *gdata_media_group_get_credit (GDataMediaGroup *self) G_GNUC_PURE; +void _gdata_media_group_set_credit (GDataMediaGroup *self, GDataMediaCredit *credit); +const gchar *gdata_media_group_get_player_uri (GDataMediaGroup *self) G_GNUC_PURE; +gboolean gdata_media_group_is_restricted_in_country (GDataMediaGroup *self, const gchar *country) G_GNUC_PURE; +const gchar *gdata_media_group_get_media_rating (GDataMediaGroup *self, const gchar *rating_type) G_GNUC_PURE; +GList *gdata_media_group_get_thumbnails (GDataMediaGroup *self) G_GNUC_PURE; +void _gdata_media_group_add_thumbnail (GDataMediaGroup *self, GDataMediaThumbnail *thumbnail); + +G_END_DECLS + +#endif /* !GDATA_MEDIA_GROUP_H */ diff --git a/gdata/media/gdata-media-thumbnail.c b/gdata/media/gdata-media-thumbnail.c new file mode 100644 index 0000000..e8b4806 --- /dev/null +++ b/gdata/media/gdata-media-thumbnail.c @@ -0,0 +1,434 @@ +/* -*- Mode: C; indent-tabs-mode: t; c-basic-offset: 8; tab-width: 8 -*- */ +/* + * GData Client + * Copyright (C) Philip Withnall 2009–2010 + * + * GData Client is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * GData Client is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with GData Client. If not, see . + */ + +/** + * SECTION:gdata-media-thumbnail + * @short_description: Media RSS thumbnail element + * @stability: Stable + * @include: gdata/media/gdata-media-thumbnail.h + * + * #GDataMediaThumbnail represents a "thumbnail" element from the + * Media RSS specification. + * + * The class only implements parsing, not XML output, at the moment. + */ + +#include +#include +#include + +#include "gdata-media-thumbnail.h" +#include "gdata-download-stream.h" +#include "gdata-parsable.h" +#include "gdata-parser.h" +#include "gdata-private.h" + +static void gdata_media_thumbnail_finalize (GObject *object); +static void gdata_media_thumbnail_get_property (GObject *object, guint property_id, GValue *value, GParamSpec *pspec); +static gboolean pre_parse_xml (GDataParsable *parsable, xmlDoc *doc, xmlNode *root_node, gpointer user_data, GError **error); +static void get_namespaces (GDataParsable *parsable, GHashTable *namespaces); +static gboolean +parse_json (GDataParsable *parsable, JsonReader *reader, gpointer user_data, + GError **error); + +struct _GDataMediaThumbnailPrivate { + gchar *uri; + guint height; + guint width; + gint64 time; +}; + +enum { + PROP_URI = 1, + PROP_HEIGHT, + PROP_WIDTH, + PROP_TIME +}; + +G_DEFINE_TYPE (GDataMediaThumbnail, gdata_media_thumbnail, GDATA_TYPE_PARSABLE) + +static void +gdata_media_thumbnail_class_init (GDataMediaThumbnailClass *klass) +{ + GObjectClass *gobject_class = G_OBJECT_CLASS (klass); + GDataParsableClass *parsable_class = GDATA_PARSABLE_CLASS (klass); + + g_type_class_add_private (klass, sizeof (GDataMediaThumbnailPrivate)); + + gobject_class->get_property = gdata_media_thumbnail_get_property; + gobject_class->finalize = gdata_media_thumbnail_finalize; + + parsable_class->pre_parse_xml = pre_parse_xml; + parsable_class->get_namespaces = get_namespaces; + parsable_class->parse_json = parse_json; + parsable_class->element_name = "thumbnail"; + parsable_class->element_namespace = "media"; + + /** + * GDataMediaThumbnail:uri: + * + * The URI of the thumbnail. + * + * For more information, see the Media RSS specification. + * + * Since: 0.4.0 + */ + g_object_class_install_property (gobject_class, PROP_URI, + g_param_spec_string ("uri", + "URI", "The URI of the thumbnail.", + NULL, + G_PARAM_READABLE | G_PARAM_STATIC_STRINGS)); + + /** + * GDataMediaThumbnail:height: + * + * The height of the thumbnail, in pixels. + * + * For more information, see the Media RSS specification. + * + * Since: 0.4.0 + */ + g_object_class_install_property (gobject_class, PROP_HEIGHT, + g_param_spec_uint ("height", + "Height", "The height of the thumbnail, in pixels.", + 0, G_MAXUINT, 0, + G_PARAM_READABLE | G_PARAM_STATIC_STRINGS)); + + /** + * GDataMediaThumbnail:width: + * + * The width of the thumbnail, in pixels. + * + * For more information, see the Media RSS specification. + * + * Since: 0.4.0 + */ + g_object_class_install_property (gobject_class, PROP_WIDTH, + g_param_spec_uint ("width", + "Width", "The width of the thumbnail, in pixels.", + 0, G_MAXUINT, 0, + G_PARAM_READABLE | G_PARAM_STATIC_STRINGS)); + + /** + * GDataMediaThumbnail:time: + * + * The time offset of the thumbnail in relation to the media object, in milliseconds. + * + * For more information, see the Media RSS specification. + * + * Since: 0.4.0 + */ + g_object_class_install_property (gobject_class, PROP_TIME, + g_param_spec_int64 ("time", + "Time", "The time offset of the thumbnail in relation to the media object, in ms.", + -1, G_MAXINT64, -1, + G_PARAM_READABLE | G_PARAM_STATIC_STRINGS)); +} + +static void +gdata_media_thumbnail_init (GDataMediaThumbnail *self) +{ + self->priv = G_TYPE_INSTANCE_GET_PRIVATE (self, GDATA_TYPE_MEDIA_THUMBNAIL, GDataMediaThumbnailPrivate); +} + +static void +gdata_media_thumbnail_finalize (GObject *object) +{ + GDataMediaThumbnailPrivate *priv = GDATA_MEDIA_THUMBNAIL (object)->priv; + + g_free (priv->uri); + + /* Chain up to the parent class */ + G_OBJECT_CLASS (gdata_media_thumbnail_parent_class)->finalize (object); +} + +static void +gdata_media_thumbnail_get_property (GObject *object, guint property_id, GValue *value, GParamSpec *pspec) +{ + GDataMediaThumbnailPrivate *priv = GDATA_MEDIA_THUMBNAIL (object)->priv; + + switch (property_id) { + case PROP_URI: + g_value_set_string (value, priv->uri); + break; + case PROP_HEIGHT: + g_value_set_uint (value, priv->height); + break; + case PROP_WIDTH: + g_value_set_uint (value, priv->width); + break; + case PROP_TIME: + g_value_set_int64 (value, priv->time); + break; + default: + /* We don't have any other property... */ + G_OBJECT_WARN_INVALID_PROPERTY_ID (object, property_id, pspec); + break; + } +} + +/* + * gdata_media_thumbnail_parse_time: + * @time_string: a time string to parse + * + * Parses a time string in (a subset of) NTP format into a number of milliseconds since the start of a media stream. + * + * For more information about NTP format, see RFC 2326 3.6 Normal Play Time. + * + * To build an NTP-format string, see gdata_media_thumbnail_build_time(). + * + * Return value: number of milliseconds since the start of a media stream + */ +static gint64 +parse_time (const gchar *time_string) +{ + guint hours, minutes; + gdouble seconds; + gchar *end_pointer; + + g_return_val_if_fail (time_string != NULL, 0); + + hours = g_ascii_strtoull (time_string, &end_pointer, 10); + if (end_pointer != time_string + 2) + return -1; + + minutes = g_ascii_strtoull (time_string + 3, &end_pointer, 10); + if (end_pointer != time_string + 5) + return -1; + + seconds = g_ascii_strtod (time_string + 6, &end_pointer); + if (end_pointer != time_string + strlen (time_string)) + return -1; + + return (gint64) ((seconds + minutes * 60 + hours * 3600) * 1000); +} + +/* + * gdata_media_thumbnail_build_time: + * @_time: a number of milliseconds since the start of a media stream + * + * Builds an NTP-format time string describing @_time milliseconds since the start + * of a media stream. + * + * Return value: an NTP-format string describing @_time; free with g_free() + */ +/*static gchar * +build_time (gint64 _time) +{ + guint hours, minutes; + gfloat seconds; + + hours = _time % 3600000; + _time -= hours * 3600000; + + minutes = _time % 60000; + _time -= minutes * 60000; + + seconds = _time / 1000.0; + + return g_strdup_printf ("%02u:%02u:%02f", hours, minutes, seconds); +}*/ + +static gboolean +pre_parse_xml (GDataParsable *parsable, xmlDoc *doc, xmlNode *root_node, gpointer user_data, GError **error) +{ + GDataMediaThumbnailPrivate *priv = GDATA_MEDIA_THUMBNAIL (parsable)->priv; + xmlChar *uri, *width, *height, *_time; + guint width_uint, height_uint; + gint64 time_int64; + + /* Get the width and height */ + width = xmlGetProp (root_node, (xmlChar*) "width"); + width_uint = (width == NULL) ? 0 : g_ascii_strtoull ((gchar*) width, NULL, 10); + xmlFree (width); + + height = xmlGetProp (root_node, (xmlChar*) "height"); + height_uint = (height == NULL) ? 0 : g_ascii_strtoull ((gchar*) height, NULL, 10); + xmlFree (height); + + /* Get and parse the time */ + _time = xmlGetProp (root_node, (xmlChar*) "time"); + if (_time == NULL) { + time_int64 = -1; + } else { + time_int64 = parse_time ((gchar*) _time); + if (time_int64 == -1) { + gdata_parser_error_unknown_property_value (root_node, "time", (gchar*) _time, error); + xmlFree (_time); + return FALSE; + } + xmlFree (_time); + } + + /* Get the URI */ + uri = xmlGetProp (root_node, (xmlChar*) "url"); + if (uri == NULL || *uri == '\0') { + xmlFree (uri); + return gdata_parser_error_required_property_missing (root_node, "url", error); + } + + priv->uri = (gchar*) uri; + priv->height = height_uint; + priv->width = width_uint; + priv->time = time_int64; + + return TRUE; +} + +static void +get_namespaces (GDataParsable *parsable, GHashTable *namespaces) +{ + g_hash_table_insert (namespaces, (gchar*) "media", (gchar*) "http://search.yahoo.com/mrss/"); +} + +/* Reference: + * https://developers.google.com/youtube/v3/docs/videos#snippet.thumbnails */ +static gboolean +parse_json (GDataParsable *parsable, JsonReader *reader, gpointer user_data, + GError **error) +{ + gboolean success; + gint64 width, height; + GDataMediaThumbnail *self = GDATA_MEDIA_THUMBNAIL (parsable); + GDataMediaThumbnailPrivate *priv = self->priv; + + if (gdata_parser_string_from_json_member (reader, "url", P_DEFAULT, + &priv->uri, &success, + error)) { + return success; + } else if (gdata_parser_int_from_json_member (reader, "width", + P_DEFAULT, &width, + &success, error)) { + priv->width = width; + return success; + } else if (gdata_parser_int_from_json_member (reader, "height", + P_DEFAULT, &height, + &success, error)) { + priv->height = height; + return success; + } else { + return GDATA_PARSABLE_CLASS (gdata_media_thumbnail_parent_class)->parse_json (parsable, reader, user_data, error); + } +} + +/** + * gdata_media_thumbnail_get_uri: + * @self: a #GDataMediaThumbnail + * + * Gets the #GDataMediaThumbnail:uri property. + * + * Return value: the thumbnail's URI + * + * Since: 0.4.0 + */ +const gchar * +gdata_media_thumbnail_get_uri (GDataMediaThumbnail *self) +{ + g_return_val_if_fail (GDATA_IS_MEDIA_THUMBNAIL (self), NULL); + return self->priv->uri; +} + +/** + * gdata_media_thumbnail_get_height: + * @self: a #GDataMediaThumbnail + * + * Gets the #GDataMediaThumbnail:height property. + * + * Return value: the thumbnail's height in pixels, or 0 + * + * Since: 0.4.0 + */ +guint +gdata_media_thumbnail_get_height (GDataMediaThumbnail *self) +{ + g_return_val_if_fail (GDATA_IS_MEDIA_THUMBNAIL (self), 0); + return self->priv->height; +} + +/** + * gdata_media_thumbnail_get_width: + * @self: a #GDataMediaThumbnail + * + * Gets the #GDataMediaThumbnail:width property. + * + * Return value: the thumbnail's width in pixels, or 0 + * + * Since: 0.4.0 + */ +guint +gdata_media_thumbnail_get_width (GDataMediaThumbnail *self) +{ + g_return_val_if_fail (GDATA_IS_MEDIA_THUMBNAIL (self), 0); + return self->priv->width; +} + +/** + * gdata_media_thumbnail_get_time: + * @self: a #GDataMediaThumbnail + * + * Gets the #GDataMediaThumbnail:time property. + * + * Return value: the thumbnail's time offset in the media, or -1 + * + * Since: 0.4.0 + */ +gint64 +gdata_media_thumbnail_get_time (GDataMediaThumbnail *self) +{ + g_return_val_if_fail (GDATA_IS_MEDIA_THUMBNAIL (self), -1); + return self->priv->time; +} + +/** + * gdata_media_thumbnail_download: + * @self: a #GDataMediaThumbnail + * @service: the #GDataService + * @cancellable: (allow-none): a #GCancellable for the entire download stream, or %NULL + * @error: a #GError, or %NULL + * + * Downloads and returns a #GDataDownloadStream allowing the thumbnail data represented by @self to be read. + * + * To get the content type of the downloaded data, gdata_download_stream_get_content_type() can be called on the returned #GDataDownloadStream. + * Calling gdata_download_stream_get_content_length() on the stream will not return a meaningful result, however, as the stream is encoded in chunks, + * rather than by content length. + * + * In order to cancel the download, a #GCancellable passed in to @cancellable must be cancelled using g_cancellable_cancel(). Cancelling the individual + * #GInputStream operations on the #GDataDownloadStream will not cancel the entire download; merely the read or close operation in question. See the + * #GDataDownloadStream:cancellable for more details. + * + * Return value: (transfer full): a #GDataDownloadStream to download the thumbnail with, or %NULL; unref with g_object_unref() + * + * Since: 0.8.0 + */ +GDataDownloadStream * +gdata_media_thumbnail_download (GDataMediaThumbnail *self, GDataService *service, GCancellable *cancellable, GError **error) +{ + const gchar *src_uri; + + g_return_val_if_fail (GDATA_IS_MEDIA_THUMBNAIL (self), NULL); + g_return_val_if_fail (GDATA_IS_SERVICE (service), NULL); + g_return_val_if_fail (cancellable == NULL || G_IS_CANCELLABLE (cancellable), NULL); + g_return_val_if_fail (error == NULL || *error == NULL, NULL); + + /* We keep a GError in the argument list so that we can add authentication errors, etc., in future if necessary */ + + /* Get the download URI and create a stream for it */ + src_uri = gdata_media_thumbnail_get_uri (self); + return GDATA_DOWNLOAD_STREAM (gdata_download_stream_new (service, NULL, src_uri, cancellable)); +} diff --git a/gdata/media/gdata-media-thumbnail.h b/gdata/media/gdata-media-thumbnail.h new file mode 100644 index 0000000..ee05c10 --- /dev/null +++ b/gdata/media/gdata-media-thumbnail.h @@ -0,0 +1,80 @@ +/* -*- Mode: C; indent-tabs-mode: t; c-basic-offset: 8; tab-width: 8 -*- */ +/* + * GData Client + * Copyright (C) Philip Withnall 2009 + * + * GData Client is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * GData Client is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with GData Client. If not, see . + */ + +#ifndef GDATA_MEDIA_THUMBNAIL_H +#define GDATA_MEDIA_THUMBNAIL_H + +#include +#include + +#include +#include +#include + +G_BEGIN_DECLS + +#define GDATA_TYPE_MEDIA_THUMBNAIL (gdata_media_thumbnail_get_type ()) +#define GDATA_MEDIA_THUMBNAIL(o) (G_TYPE_CHECK_INSTANCE_CAST ((o), GDATA_TYPE_MEDIA_THUMBNAIL, GDataMediaThumbnail)) +#define GDATA_MEDIA_THUMBNAIL_CLASS(k) (G_TYPE_CHECK_CLASS_CAST((k), GDATA_TYPE_MEDIA_THUMBNAIL, GDataMediaThumbnailClass)) +#define GDATA_IS_MEDIA_THUMBNAIL(o) (G_TYPE_CHECK_INSTANCE_TYPE ((o), GDATA_TYPE_MEDIA_THUMBNAIL)) +#define GDATA_IS_MEDIA_THUMBNAIL_CLASS(k) (G_TYPE_CHECK_CLASS_TYPE ((k), GDATA_TYPE_MEDIA_THUMBNAIL)) +#define GDATA_MEDIA_THUMBNAIL_GET_CLASS(o) (G_TYPE_INSTANCE_GET_CLASS ((o), GDATA_TYPE_MEDIA_THUMBNAIL, GDataMediaThumbnailClass)) + +typedef struct _GDataMediaThumbnailPrivate GDataMediaThumbnailPrivate; + +/** + * GDataMediaThumbnail: + * + * All the fields in the #GDataMediaThumbnail structure are private and should never be accessed directly. + */ +typedef struct { + GDataParsable parent; + GDataMediaThumbnailPrivate *priv; +} GDataMediaThumbnail; + +/** + * GDataMediaThumbnailClass: + * + * All the fields in the #GDataMediaThumbnailClass structure are private and should never be accessed directly. + * + * Since: 0.4.0 + */ +typedef struct { + /*< private >*/ + GDataParsableClass parent; + + /*< private >*/ + /* Padding for future expansion */ + void (*_g_reserved0) (void); + void (*_g_reserved1) (void); +} GDataMediaThumbnailClass; + +GType gdata_media_thumbnail_get_type (void) G_GNUC_CONST; + +const gchar *gdata_media_thumbnail_get_uri (GDataMediaThumbnail *self) G_GNUC_PURE; +guint gdata_media_thumbnail_get_height (GDataMediaThumbnail *self) G_GNUC_PURE; +guint gdata_media_thumbnail_get_width (GDataMediaThumbnail *self) G_GNUC_PURE; +gint64 gdata_media_thumbnail_get_time (GDataMediaThumbnail *self) G_GNUC_PURE; + +GDataDownloadStream *gdata_media_thumbnail_download (GDataMediaThumbnail *self, GDataService *service, GCancellable *cancellable, + GError **error) G_GNUC_WARN_UNUSED_RESULT G_GNUC_MALLOC; + +G_END_DECLS + +#endif /* !GDATA_MEDIA_THUMBNAIL_H */ diff --git a/gdata/media/meson.build b/gdata/media/meson.build new file mode 100644 index 0000000..eef13ff --- /dev/null +++ b/gdata/media/meson.build @@ -0,0 +1,53 @@ +incs += include_directories('.') + +include_subdir = gdata_include_subdir / 'media' + +headers = files( + 'gdata-media-category.h', + 'gdata-media-content.h', + 'gdata-media-credit.h', + 'gdata-media-thumbnail.h', +) + +install_headers( + headers, + subdir: include_subdir, +) + +gir_headers += headers + +sources += files( + 'gdata-media-category.c', + 'gdata-media-content.c', + 'gdata-media-credit.c', + 'gdata-media-group.c', + 'gdata-media-thumbnail.c', +) + +enums = 'gdata-media-enums' + +enums_in = gnome.mkenums_simple( + enums + '-in', + sources: headers, +) + +# FIXME: Work around the namespace being incorrectly detected +# by glib-mkenums. This needs to be fixed by changing the +# namespace in libgdata. See !6. +sources += custom_target( + enums + '.c', + input: enums_in[0], + output: enums + '.c', + command: enum_source_cmd, + capture: true, +) + +enum_headers += custom_target( + enums + '.h', + input: enums_in[1], + output: enums + '.h', + command: enum_header_cmd, + capture: true, + install: true, + install_dir: gdata_includedir / include_subdir, +) diff --git a/gdata/meson.build b/gdata/meson.build new file mode 100644 index 0000000..a42bae7 --- /dev/null +++ b/gdata/meson.build @@ -0,0 +1,205 @@ +gdata_inc_dir = include_directories('.') + +enum_headers = [] +gir_headers = [] + +sources = [] + +incs = [ + gdata_inc_dir, + top_inc_dir, +] + +subdir('app') +subdir('atom') +subdir('exif') +subdir('gcontact') +subdir('gd') +subdir('georss') +subdir('media') +subdir('services') + +headers = files( + 'gdata.h', + 'gdata-access-handler.h', + 'gdata-access-rule.h', + 'gdata-authorization-domain.h', + 'gdata-authorizer.h', + 'gdata-batch-operation.h', + 'gdata-batchable.h', + 'gdata-client-login-authorizer.h', + 'gdata-comment.h', + 'gdata-commentable.h', + 'gdata-comparable.h', + 'gdata-download-stream.h', + 'gdata-entry.h', + 'gdata-feed.h', + 'gdata-oauth1-authorizer.h', + 'gdata-oauth2-authorizer.h', + 'gdata-parsable.h', + 'gdata-query.h', + 'gdata-service.h', + 'gdata-types.h', + 'gdata-upload-stream.h', +) + +sources += files( + 'gdata-access-handler.c', + 'gdata-access-rule.c', + 'gdata-authorization-domain.c', + 'gdata-authorizer.c', + 'gdata-batch-feed.c', + 'gdata-batch-operation.c', + 'gdata-batchable.c', + 'gdata-buffer.c', + 'gdata-client-login-authorizer.c', + 'gdata-comment.c', + 'gdata-commentable.c', + 'gdata-comparable.c', + 'gdata-download-stream.c', + 'gdata-entry.c', + 'gdata-feed.c', + 'gdata-oauth1-authorizer.c', + 'gdata-oauth2-authorizer.c', + 'gdata-parsable.c', + 'gdata-parser.c', + 'gdata-query.c', + 'gdata-service.c', + 'gdata-types.c', + 'gdata-upload-stream.c', +) + +if enable_goa + headers += files('gdata-goa-authorizer.h') + sources += files('gdata-goa-authorizer.c') +endif + +install_headers( + headers, + subdir: gdata_include_subdir, +) + +version_conf = { + 'GDATA_VERSION_MAJOR': gdata_version_major, + 'GDATA_VERSION_MINOR': gdata_version_minor, + 'GDATA_VERSION_MICRO': gdata_version_micro, +} + +headers += configure_file( + input: 'gdata-version.h.in', + output: '@BASENAME@', + configuration: version_conf, + install: true, + install_dir: gdata_includedir / gdata_include_subdir, +) + +gir_headers += headers + +marshal = 'gdata-marshal' + +marshal_files = gnome.genmarshal( + marshal, + sources: marshal + '.list', + prefix: marshal.underscorify(), +) + +enums = 'gdata-enums' + +enums_in = gnome.mkenums_simple( + enums + '-in', + sources: headers, +) + +# FIXME: Work around the namespace being incorrectly detected +# by glib-mkenums. This needs to be fixed by changing the +# namespace in libgdata. See !6. +sources += custom_target( + enums + '.c', + input: enums_in[0], + output: enums + '.c', + command: enum_source_cmd, + capture: true, +) + +enum_headers += custom_target( + enums + '.h', + input: enums_in[1], + output: enums + '.h', + command: enum_header_cmd, + capture: true, + install: true, + install_dir: gdata_includedir / gdata_include_subdir, +) + +symbol_map = meson.current_source_dir() / 'symbol.map' +ldflags = cc.get_supported_link_arguments('-Wl,--version-script,' + symbol_map) + +libgdata_lib = shared_library( + 'gdata', + include_directories: incs, + sources: sources + enum_headers + marshal_files, + c_args: common_c_args + ['-DG_LOG_DOMAIN="@0@"'.format(gdata_name)], + dependencies: gdata_deps + gdata_private_deps, + link_args: ldflags, + link_depends: symbol_map, + install: true, + version: gdata_soversion, + gnu_symbol_visibility: 'default', +) + +libgdata_dep = declare_dependency( + sources: enum_headers, + include_directories: gdata_inc_dir, + dependencies: gdata_deps, + link_with: libgdata_lib, +) + +pkgconfig.generate( + name: 'libgdata', + description: 'GData client library', + subdirs: 'libgdata', + libraries: libgdata_lib, + requires: gdata_deps, + requires_private: gdata_private_deps, + filebase: 'libgdata', + version: gdata_version, + variables: [ + 'exec_prefix=${prefix}', + 'goa_enabled=' + goa_dep.found().to_string(), + ], +) + +if get_option('introspection') + gdata_gir_includes = ['GObject-2.0', 'libxml2-2.0', 'Soup-2.4', 'Json-1.0'] + gdata_vapi_deps = ['libxml-2.0', 'libsoup-2.4', 'json-glib-1.0'] + + if enable_goa + gdata_gir_includes += ['Goa-1.0'] + gdata_vapi_deps += ['goa-1.0'] + endif + + libgdata_gir = gnome.generate_gir( + libgdata_lib, + sources: sources + gir_headers + enum_headers, + nsversion: '@0@.@1@'.format(gdata_api_version_major, gdata_api_version_minor), + namespace: 'GData', + symbol_prefix: 'gdata', + includes: gdata_gir_includes, + header: 'gdata/gdata.h', + install: true, + export_packages: gdata_name, + ) + + if get_option('vapi') + libgdata_vapi = gnome.generate_vapi(gdata_name, + sources: libgdata_gir[0], + packages: gdata_vapi_deps, + install: true, + ) + endif +endif + + +if always_build_tests + subdir('tests') +endif diff --git a/gdata/services/calendar/gdata-calendar-access-rule.c b/gdata/services/calendar/gdata-calendar-access-rule.c new file mode 100644 index 0000000..98d6091 --- /dev/null +++ b/gdata/services/calendar/gdata-calendar-access-rule.c @@ -0,0 +1,277 @@ +/* -*- Mode: C; indent-tabs-mode: t; c-basic-offset: 8; tab-width: 8 -*- */ +/* + * GData Client + * Copyright (C) Philip Withnall 2015 + * + * GData Client is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * GData Client is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with GData Client. If not, see . + */ + +/** + * SECTION:gdata-calendar-access-rule + * @short_description: GData Calendar access rule object + * @stability: Stable + * @include: gdata/services/calendar/gdata-calendar-access-rule.h + * + * #GDataCalendarAccessRule is a subclass of #GDataAccessRule to represent an + * access rule affecting users of a shared calendar in Google Calendar. + * + * Since: 0.17.2 + */ + +#include +#include +#include +#include + +#include "gdata-access-rule.h" +#include "gdata-parser.h" +#include "gdata-types.h" +#include "gdata-private.h" +#include "gdata-calendar-access-rule.h" + +static gboolean +parse_json (GDataParsable *parsable, JsonReader *reader, gpointer user_data, + GError **error); +static gboolean +post_parse_json (GDataParsable *parsable, gpointer user_data, GError **error); +static void +get_json (GDataParsable *parsable, JsonBuilder *builder); +static const gchar * +get_content_type (void); + +G_DEFINE_TYPE (GDataCalendarAccessRule, gdata_calendar_access_rule, + GDATA_TYPE_ACCESS_RULE) + +static void +gdata_calendar_access_rule_class_init (GDataCalendarAccessRuleClass *klass) +{ + GDataParsableClass *parsable_class = GDATA_PARSABLE_CLASS (klass); + GDataEntryClass *entry_class = GDATA_ENTRY_CLASS (klass); + + parsable_class->parse_json = parse_json; + parsable_class->post_parse_json = post_parse_json; + parsable_class->get_json = get_json; + parsable_class->get_content_type = get_content_type; + + entry_class->kind_term = "calendar#aclRule"; +} + +static void +gdata_calendar_access_rule_init (GDataCalendarAccessRule *self) +{ + /* Nothing to do here. */ +} + +/* V3 reference: + * https://developers.google.com/google-apps/calendar/v3/reference/acl#role + * V2 reference is no longer available. + */ +const struct { + const gchar *v3; + const gchar *v2; +} role_pairs[] = { + { "none", "none" }, + { "freeBusyReader", "http://schemas.google.com/gCal/2005#freebusy" }, + { "reader", "http://schemas.google.com/gCal/2005#read" }, + { "writer", "http://schemas.google.com/gCal/2005#editor" }, + { "owner", "http://schemas.google.com/gCal/2005#owner" }, +}; + +static const gchar * +role_v3_to_v2 (const gchar *v3_role) +{ + guint i; + + for (i = 0; i < G_N_ELEMENTS (role_pairs); i++) { + if (g_strcmp0 (v3_role, role_pairs[i].v3) == 0) { + return role_pairs[i].v2; + } + } + + /* Fallback. */ + return v3_role; +} + +static const gchar * +role_v2_to_v3 (const gchar *v2_role) +{ + guint i; + + for (i = 0; i < G_N_ELEMENTS (role_pairs); i++) { + if (g_strcmp0 (v2_role, role_pairs[i].v2) == 0) { + return role_pairs[i].v3; + } + } + + /* Fallback. */ + return v2_role; +} + +static const gchar * +scope_type_v3_to_v2 (const gchar *v3_scope_type) +{ + /* Surprisingly, they have not changed from v2 to v3. */ + return v3_scope_type; +} + +static const gchar * +scope_type_v2_to_v3 (const gchar *v2_scope_type) +{ + /* Surprisingly, they have not changed from v2 to v3. */ + return v2_scope_type; +} + +static gboolean +parse_json (GDataParsable *parsable, JsonReader *reader, gpointer user_data, GError **error) +{ + gboolean success; + + if (g_strcmp0 (json_reader_get_member_name (reader), "role") == 0) { + gchar *role = NULL; /* owned */ + + g_assert (gdata_parser_string_from_json_member (reader, "role", + P_REQUIRED | + P_NON_EMPTY, + &role, &success, + error)); + + if (!success) { + return FALSE; + } + + gdata_access_rule_set_role (GDATA_ACCESS_RULE (parsable), + role_v3_to_v2 (role)); + g_free (role); + + return TRUE; + } else if (g_strcmp0 (json_reader_get_member_name (reader), + "scope") == 0) { + const gchar *scope_type; + const gchar *scope_value; + + /* Check this is an object. */ + if (!json_reader_is_object (reader)) { + return gdata_parser_error_required_json_content_missing (reader, + error); + } + + json_reader_read_member (reader, "type"); + scope_type = json_reader_get_string_value (reader); + json_reader_end_member (reader); + + json_reader_read_member (reader, "value"); + scope_value = json_reader_get_string_value (reader); + json_reader_end_member (reader); + + /* Scope type is required. */ + if (scope_type == NULL) { + return gdata_parser_error_required_json_content_missing (reader, + error); + } + + gdata_access_rule_set_scope (GDATA_ACCESS_RULE (parsable), + scope_type_v3_to_v2 (scope_type), + scope_value); + + return TRUE; + } + + return GDATA_PARSABLE_CLASS (gdata_calendar_access_rule_parent_class)->parse_json (parsable, reader, user_data, error); +} + +static gboolean +post_parse_json (GDataParsable *parsable, gpointer user_data, GError **error) +{ + /* Do _not_ chain up. */ + return TRUE; +} + +static void +get_json (GDataParsable *parsable, JsonBuilder *builder) +{ + GDataAccessRule *access_rule; + const gchar *id, *etag, *role, *scope_type, *scope_value; + + access_rule = GDATA_ACCESS_RULE (parsable); + + id = gdata_entry_get_id (GDATA_ENTRY (parsable)); + if (id != NULL) { + json_builder_set_member_name (builder, "id"); + json_builder_add_string_value (builder, id); + } + + json_builder_set_member_name (builder, "kind"); + json_builder_add_string_value (builder, "calendar#aclRule"); + + /* Add the ETag, if available. */ + etag = gdata_entry_get_etag (GDATA_ENTRY (parsable)); + if (etag != NULL) { + json_builder_set_member_name (builder, "etag"); + json_builder_add_string_value (builder, etag); + } + + role = gdata_access_rule_get_role (access_rule); + if (role != NULL) { + json_builder_set_member_name (builder, "role"); + json_builder_add_string_value (builder, role_v2_to_v3 (role)); + } + + gdata_access_rule_get_scope (access_rule, &scope_type, &scope_value); + if (scope_type != NULL || scope_value != NULL) { + json_builder_set_member_name (builder, "scope"); + json_builder_begin_object (builder); + + if (scope_type != NULL) { + json_builder_set_member_name (builder, "type"); + json_builder_add_string_value (builder, + scope_type_v2_to_v3 (scope_type)); + } + + if (scope_value != NULL) { + json_builder_set_member_name (builder, "value"); + json_builder_add_string_value (builder, scope_value); + } + + json_builder_end_object (builder); + } +} + +static const gchar * +get_content_type (void) +{ + return "application/json"; +} + +/** + * gdata_calendar_access_rule_new: + * @id: the access rule's ID, or %NULL + * + * Creates a new #GDataCalendarAccessRule with the given ID and default + * properties. + * + * Return value: (transfer full): a new #GDataCalendarAccessRule; unref with + * g_object_unref() + * + * Since: 0.17.2 + */ +GDataCalendarAccessRule * +gdata_calendar_access_rule_new (const gchar *id) +{ + GObject *retval = NULL; /* owned */ + + retval = g_object_new (GDATA_TYPE_CALENDAR_ACCESS_RULE, + "id", id, + NULL); + return GDATA_CALENDAR_ACCESS_RULE (retval); +} diff --git a/gdata/services/calendar/gdata-calendar-access-rule.h b/gdata/services/calendar/gdata-calendar-access-rule.h new file mode 100644 index 0000000..e80ec84 --- /dev/null +++ b/gdata/services/calendar/gdata-calendar-access-rule.h @@ -0,0 +1,125 @@ +/* -*- Mode: C; indent-tabs-mode: t; c-basic-offset: 8; tab-width: 8 -*- */ +/* + * GData Client + * Copyright (C) Philip Withnall 2015 + * + * GData Client is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * GData Client is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with GData Client. If not, see . + */ + +#ifndef GDATA_CALENDAR_ACCESS_RULE_H +#define GDATA_CALENDAR_ACCESS_RULE_H + +#include +#include + +#include + +G_BEGIN_DECLS + +/** + * GDATA_CALENDAR_ACCESS_ROLE_READ: + * + * The users specified by the #GDataCalendarAccessRule have read-only access to + * the calendar. + * + * Since: 0.7.0 + */ +#define GDATA_CALENDAR_ACCESS_ROLE_READ "http://schemas.google.com/gCal/2005#read" + +/** + * GDATA_CALENDAR_ACCESS_ROLE_FREE_BUSY: + * + * The users specified by the #GDataCalendarAccessRule can only see the + * free/busy information on the calendar; not event details. + * + * Since: 0.7.0 + */ +#define GDATA_CALENDAR_ACCESS_ROLE_FREE_BUSY "http://schemas.google.com/gCal/2005#freebusy" + +/** + * GDATA_CALENDAR_ACCESS_ROLE_EDITOR: + * + * The users specified by the #GDataCalendarAccessRule have full edit access to + * the calendar, except they can’t change the calendar’s access rules. + * + * Since: 0.7.0 + */ +#define GDATA_CALENDAR_ACCESS_ROLE_EDITOR "http://schemas.google.com/gCal/2005#editor" + +/** + * GDATA_CALENDAR_ACCESS_ROLE_OWNER: + * + * The users specified by the #GDataCalendarAccessRule have full owner access + * to the calendar. + * + * Since: 0.7.0 + */ +#define GDATA_CALENDAR_ACCESS_ROLE_OWNER "http://schemas.google.com/gCal/2005#owner" + +/** + * GDATA_CALENDAR_ACCESS_ROLE_ROOT: + * + * The users specified by the #GDataCalendarAccessRule have full administrator + * access to the calendar server. This is only available in Google Apps For + * Your Domain. + * + * Since: 0.7.0 + */ +#define GDATA_CALENDAR_ACCESS_ROLE_ROOT "http://schemas.google.com/gCal/2005#root" + +#define GDATA_TYPE_CALENDAR_ACCESS_RULE (gdata_calendar_access_rule_get_type ()) +#define GDATA_CALENDAR_ACCESS_RULE(o) (G_TYPE_CHECK_INSTANCE_CAST ((o), GDATA_TYPE_CALENDAR_ACCESS_RULE, GDataCalendarAccessRule)) +#define GDATA_CALENDAR_ACCESS_RULE_CLASS(k) (G_TYPE_CHECK_CLASS_CAST((k), GDATA_TYPE_CALENDAR_ACCESS_RULE, GDataCalendarAccessRuleClass)) +#define GDATA_IS_CALENDAR_ACCESS_RULE(o) (G_TYPE_CHECK_INSTANCE_TYPE ((o), GDATA_TYPE_CALENDAR_ACCESS_RULE)) +#define GDATA_IS_CALENDAR_ACCESS_RULE_CLASS(k) (G_TYPE_CHECK_CLASS_TYPE ((k), GDATA_TYPE_CALENDAR_ACCESS_RULE)) +#define GDATA_CALENDAR_ACCESS_RULE_GET_CLASS(o) (G_TYPE_INSTANCE_GET_CLASS ((o), GDATA_TYPE_CALENDAR_ACCESS_RULE, GDataCalendarAccessRuleClass)) + +/** + * GDataCalendarAccessRule: + * + * All the fields in the #GDataCalendarAccessRule structure are private and + * should never be accessed directly. + * + * Since: 0.17.2 + */ +typedef struct { + GDataAccessRule parent; +} GDataCalendarAccessRule; + +/** + * GDataCalendarAccessRuleClass: + * + * All the fields in the #GDataCalendarAccessRuleClass structure are private + * and should never be accessed directly. + * + * Since: 0.17.2 + */ +typedef struct { + /*< private >*/ + GDataAccessRuleClass parent; + + /*< private >*/ + /* Padding for future expansion */ + void (*_g_reserved0) (void); + void (*_g_reserved1) (void); +} GDataCalendarAccessRuleClass; + +GType gdata_calendar_access_rule_get_type (void) G_GNUC_CONST; + +GDataCalendarAccessRule * +gdata_calendar_access_rule_new (const gchar *id) G_GNUC_WARN_UNUSED_RESULT G_GNUC_MALLOC; + +G_END_DECLS + +#endif /* !GDATA_CALENDAR_ACCESS_RULE_H */ diff --git a/gdata/services/calendar/gdata-calendar-calendar.c b/gdata/services/calendar/gdata-calendar-calendar.c new file mode 100644 index 0000000..c781558 --- /dev/null +++ b/gdata/services/calendar/gdata-calendar-calendar.c @@ -0,0 +1,805 @@ +/* -*- Mode: C; indent-tabs-mode: t; c-basic-offset: 8; tab-width: 8 -*- */ +/* + * GData Client + * Copyright (C) Philip Withnall 2009, 2010, 2014, 2015 + * + * GData Client is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * GData Client is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with GData Client. If not, see . + */ + +/** + * SECTION:gdata-calendar-calendar + * @short_description: GData Calendar calendar object + * @stability: Stable + * @include: gdata/services/calendar/gdata-calendar-calendar.h + * + * #GDataCalendarCalendar is a subclass of #GDataEntry to represent a calendar from Google Calendar. + * + * #GDataCalendarCalendar implements #GDataAccessHandler, meaning the access rules to it can be modified using that interface. As well as the + * access roles defined for the base #GDataAccessRule (e.g. %GDATA_ACCESS_ROLE_NONE), #GDataCalendarCalendar has its own, such as + * %GDATA_CALENDAR_ACCESS_ROLE_EDITOR and %GDATA_CALENDAR_ACCESS_ROLE_FREE_BUSY. + * + * For more details of Google Calendar's GData API, see the + * online documentation. + * + * + * Listing Calendars + * + * GDataCalendarService *service; + * GDataFeed *feed; + * GList *i; + * GError *error = NULL; + * + * /* Create a service */ + * service = create_calendar_service (); + * + * /* Query for all of the calendars the currently authenticated user has access to, including those which they have read-only + * * access to. */ + * feed = gdata_calendar_service_query_all_calendars (service, NULL, NULL, NULL, NULL, &error); + * + * g_object_unref (service); + * + * if (error != NULL) { + * g_error ("Error querying for calendars: %s", error->message); + * g_error_free (error); + * return; + * } + * + * /* Iterate through the returned calendars and do something with them */ + * for (i = gdata_feed_get_entries (feed); i != NULL; i = i->next) { + * const gchar *access_level; + * gboolean has_write_access; + * GDataCalendarCalendar *calendar = GDATA_CALENDAR_CALENDAR (i->data); + * + * /* Determine whether we have write access to the calendar, or just read-only or free/busy access. Note that the access levels + * * are more detailed than this; see the documentation for gdata_calendar_calendar_get_access_level() for more information. */ + * access_level = gdata_calendar_calendar_get_access_level (calendar); + * has_write_access = (access_level != NULL && strcmp (access_level, GDATA_CALENDAR_ACCESS_ROLE_EDITOR) == 0) ? TRUE : FALSE; + * + * /* Do something with the calendar here, such as insert it into a UI */ + * } + * + * g_object_unref (feed); + * + * + */ + +#include +#include +#include +#include + +#include "gdata-calendar-calendar.h" +#include "gdata-private.h" +#include "gdata-service.h" +#include "gdata-parser.h" +#include "gdata-types.h" +#include "gdata-access-handler.h" +#include "gdata-calendar-service.h" +#include "gdata-calendar-access-rule.h" + +static void gdata_calendar_calendar_access_handler_init (GDataAccessHandlerIface *iface); +static void gdata_calendar_calendar_finalize (GObject *object); +static void gdata_calendar_calendar_get_property (GObject *object, guint property_id, GValue *value, GParamSpec *pspec); +static void gdata_calendar_calendar_set_property (GObject *object, guint property_id, const GValue *value, GParamSpec *pspec); +static void get_json (GDataParsable *parsable, JsonBuilder *builder); +static gboolean parse_json (GDataParsable *parsable, JsonReader *reader, gpointer user_data, GError **error); +static const gchar *get_content_type (void); + +struct _GDataCalendarCalendarPrivate { + gchar *timezone; + gboolean is_hidden; + GDataColor colour; + gboolean is_selected; + gchar *access_level; +}; + +enum { + PROP_TIMEZONE = 1, + PROP_TIMES_CLEANED, + PROP_IS_HIDDEN, + PROP_COLOR, + PROP_IS_SELECTED, + PROP_ACCESS_LEVEL, + PROP_EDITED, + PROP_ETAG, +}; + +G_DEFINE_TYPE_WITH_CODE (GDataCalendarCalendar, gdata_calendar_calendar, GDATA_TYPE_ENTRY, + G_IMPLEMENT_INTERFACE (GDATA_TYPE_ACCESS_HANDLER, gdata_calendar_calendar_access_handler_init)) + +static void +gdata_calendar_calendar_class_init (GDataCalendarCalendarClass *klass) +{ + GObjectClass *gobject_class = G_OBJECT_CLASS (klass); + GDataParsableClass *parsable_class = GDATA_PARSABLE_CLASS (klass); + GDataEntryClass *entry_class = GDATA_ENTRY_CLASS (klass); + + g_type_class_add_private (klass, sizeof (GDataCalendarCalendarPrivate)); + + gobject_class->set_property = gdata_calendar_calendar_set_property; + gobject_class->get_property = gdata_calendar_calendar_get_property; + gobject_class->finalize = gdata_calendar_calendar_finalize; + + parsable_class->parse_json = parse_json; + parsable_class->get_json = get_json; + parsable_class->get_content_type = get_content_type; + + entry_class->kind_term = "calendar#calendarListEntry"; + + /** + * GDataCalendarCalendar:timezone: + * + * The timezone in which the calendar's times are given. This is a timezone name in tz database notation: reference. + */ + g_object_class_install_property (gobject_class, PROP_TIMEZONE, + g_param_spec_string ("timezone", + "Timezone", "The timezone in which the calendar's times are given.", + NULL, + G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)); + + /** + * GDataCalendarCalendar:times-cleaned: + * + * The number of times the calendar has been cleared of events. + * + * Deprecated: 0.17.2: Unsupported by the online API any more. There + * is no replacement; this will always return + * 0. + */ + g_object_class_install_property (gobject_class, PROP_TIMES_CLEANED, + g_param_spec_uint ("times-cleaned", + "Times cleaned", "The number of times the calendar has been cleared of events.", + 0, G_MAXUINT, 0, + G_PARAM_DEPRECATED | + G_PARAM_READABLE | + G_PARAM_STATIC_STRINGS)); + + /** + * GDataCalendarCalendar:is-hidden: + * + * Indicates whether the calendar is visible. + * + * Since: 0.2.0 + */ + g_object_class_install_property (gobject_class, PROP_IS_HIDDEN, + g_param_spec_boolean ("is-hidden", + "Hidden?", "Indicates whether the calendar is visible.", + FALSE, + G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)); + + /** + * GDataCalendarCalendar:color: + * + * The background color used to highlight the calendar in the user’s + * browser. This used to be restricted to a limited set of colours, but + * since 0.17.2 may be any RGB colour. + */ + g_object_class_install_property (gobject_class, PROP_COLOR, + g_param_spec_boxed ("color", + "Color", "The background color used to highlight the calendar in the user's browser.", + GDATA_TYPE_COLOR, + G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)); + + /** + * GDataCalendarCalendar:is-selected: + * + * Indicates whether the calendar is selected. + * + * Since: 0.2.0 + */ + g_object_class_install_property (gobject_class, PROP_IS_SELECTED, + g_param_spec_boolean ("is-selected", + "Selected?", "Indicates whether the calendar is selected.", + FALSE, + G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)); + + /** + * GDataCalendarCalendar:access-level: + * + * Indicates the access level the current user has to the calendar. For example: %GDATA_CALENDAR_ACCESS_ROLE_READ or + * %GDATA_CALENDAR_ACCESS_ROLE_FREE_BUSY. The "current user" is the one authenticated against the service's #GDataService:authorizer, + * or the guest user. + */ + g_object_class_install_property (gobject_class, PROP_ACCESS_LEVEL, + g_param_spec_string ("access-level", + "Access level", "Indicates the access level the current user has to the calendar.", + NULL, + G_PARAM_READABLE | G_PARAM_STATIC_STRINGS)); + + /** + * GDataCalendarCalendar:edited: + * + * The last time the calendar was edited. If the calendar has not been edited yet, the content indicates the time it was created. + * + * For more information, see the + * Atom Publishing Protocol specification. + * + * Deprecated: 0.17.2: Unsupported by the online API any more. There + * is no replacement; this will always return -1. + */ + g_object_class_install_property (gobject_class, PROP_EDITED, + g_param_spec_int64 ("edited", + "Edited", "The last time the calendar was edited.", + -1, G_MAXINT64, -1, + G_PARAM_DEPRECATED | + G_PARAM_READABLE | + G_PARAM_STATIC_STRINGS)); + + /* Override the ETag property since ETags don't seem to be supported for calendars. */ + g_object_class_override_property (gobject_class, PROP_ETAG, "etag"); +} + +static gboolean +is_owner_rule (GDataAccessRule *rule) +{ + return (strcmp (gdata_access_rule_get_role (rule), GDATA_CALENDAR_ACCESS_ROLE_OWNER) == 0) ? TRUE : FALSE; +} + +static GDataAuthorizationDomain * +get_authorization_domain (GDataAccessHandler *self) +{ + return gdata_calendar_service_get_primary_authorization_domain (); +} + +static GDataFeed * +get_rules (GDataAccessHandler *self, + GDataService *service, + GCancellable *cancellable, + GDataQueryProgressCallback progress_callback, + gpointer progress_user_data, + GError **error) +{ + GDataAccessHandlerIface *iface; + GDataAuthorizationDomain *domain = NULL; + GDataFeed *feed; + GDataLink *_link; + SoupMessage *message; + GList/**/ *rules, *i; + const gchar *calendar_id; + + _link = gdata_entry_look_up_link (GDATA_ENTRY (self), + GDATA_LINK_ACCESS_CONTROL_LIST); + g_assert (_link != NULL); + + iface = GDATA_ACCESS_HANDLER_GET_IFACE (self); + if (iface->get_authorization_domain != NULL) { + domain = iface->get_authorization_domain (self); + } + + message = _gdata_service_query (service, domain, + gdata_link_get_uri (_link), NULL, + cancellable, error); + if (message == NULL) { + return NULL; + } + + g_assert (message->response_body->data != NULL); + + feed = _gdata_feed_new_from_json (GDATA_TYPE_FEED, + message->response_body->data, + message->response_body->length, + GDATA_TYPE_CALENDAR_ACCESS_RULE, + progress_callback, progress_user_data, + error); + + /* Set the self link on all the ACL rules so they can be deleted. + * Sigh. */ + rules = gdata_feed_get_entries (feed); + calendar_id = gdata_entry_get_id (GDATA_ENTRY (self)); + + for (i = rules; i != NULL; i = i->next) { + const gchar *id; + gchar *uri = NULL; /* owned */ + + /* Set the self link, which is needed for + * gdata_service_delete_entry(). Unfortunately, it needs the + * ACL ID _and_ the calendar ID. */ + id = gdata_entry_get_id (GDATA_ENTRY (i->data)); + + if (id == NULL || calendar_id == NULL) { + continue; + } + + uri = g_strconcat ("https://www.googleapis.com" + "/calendar/v3/calendars/", + calendar_id, "/acl/", id, NULL); + _link = gdata_link_new (uri, GDATA_LINK_SELF); + gdata_entry_add_link (GDATA_ENTRY (i->data), _link); + g_object_unref (_link); + g_free (uri); + } + + g_object_unref (message); + + return feed; +} + +static void +gdata_calendar_calendar_access_handler_init (GDataAccessHandlerIface *iface) +{ + iface->is_owner_rule = is_owner_rule; + iface->get_authorization_domain = get_authorization_domain; + iface->get_rules = get_rules; +} + +static void +gdata_calendar_calendar_init (GDataCalendarCalendar *self) +{ + self->priv = G_TYPE_INSTANCE_GET_PRIVATE (self, GDATA_TYPE_CALENDAR_CALENDAR, GDataCalendarCalendarPrivate); +} + +static void +gdata_calendar_calendar_finalize (GObject *object) +{ + GDataCalendarCalendarPrivate *priv = GDATA_CALENDAR_CALENDAR (object)->priv; + + g_free (priv->timezone); + g_free (priv->access_level); + + /* Chain up to the parent class */ + G_OBJECT_CLASS (gdata_calendar_calendar_parent_class)->finalize (object); +} + +static void +gdata_calendar_calendar_get_property (GObject *object, guint property_id, GValue *value, GParamSpec *pspec) +{ + GDataCalendarCalendar *self = GDATA_CALENDAR_CALENDAR (object); + GDataCalendarCalendarPrivate *priv = self->priv; + + switch (property_id) { + case PROP_TIMEZONE: + g_value_set_string (value, priv->timezone); + break; + case PROP_TIMES_CLEANED: + G_GNUC_BEGIN_IGNORE_DEPRECATIONS + g_value_set_uint (value, gdata_calendar_calendar_get_times_cleaned (self)); + G_GNUC_END_IGNORE_DEPRECATIONS + break; + case PROP_IS_HIDDEN: + g_value_set_boolean (value, priv->is_hidden); + break; + case PROP_COLOR: + g_value_set_boxed (value, &(priv->colour)); + break; + case PROP_IS_SELECTED: + g_value_set_boolean (value, priv->is_selected); + break; + case PROP_ACCESS_LEVEL: + g_value_set_string (value, priv->access_level); + break; + case PROP_EDITED: + G_GNUC_BEGIN_IGNORE_DEPRECATIONS + g_value_set_int64 (value, + gdata_calendar_calendar_get_edited (self)); + G_GNUC_END_IGNORE_DEPRECATIONS + break; + case PROP_ETAG: + /* Never return an ETag */ + g_value_set_string (value, NULL); + break; + default: + /* We don't have any other property... */ + G_OBJECT_WARN_INVALID_PROPERTY_ID (object, property_id, pspec); + break; + } +} + +static void +gdata_calendar_calendar_set_property (GObject *object, guint property_id, const GValue *value, GParamSpec *pspec) +{ + GDataCalendarCalendar *self = GDATA_CALENDAR_CALENDAR (object); + + switch (property_id) { + case PROP_TIMEZONE: + gdata_calendar_calendar_set_timezone (self, g_value_get_string (value)); + break; + case PROP_IS_HIDDEN: + gdata_calendar_calendar_set_is_hidden (self, g_value_get_boolean (value)); + break; + case PROP_COLOR: + gdata_calendar_calendar_set_color (self, g_value_get_boxed (value)); + break; + case PROP_IS_SELECTED: + gdata_calendar_calendar_set_is_selected (self, g_value_get_boolean (value)); + break; + case PROP_ETAG: + /* Never set an ETag (note that this doesn't stop it being set in GDataEntry due to XML parsing) */ + break; + default: + /* We don't have any other property... */ + G_OBJECT_WARN_INVALID_PROPERTY_ID (object, property_id, pspec); + break; + } +} + +static gboolean +parse_json (GDataParsable *parsable, JsonReader *reader, gpointer user_data, GError **error) +{ + gboolean success; + GDataCalendarCalendar *self = GDATA_CALENDAR_CALENDAR (parsable); + + /* FIXME: Unimplemented: + * - location + * - summaryOverride + * - colorId + * - foregroundColor + * - defaultReminders + * - notificationSettings + * - primary + * - deleted + */ + + if (gdata_parser_string_from_json_member (reader, "timeZone", P_DEFAULT, &self->priv->timezone, &success, error) || + gdata_parser_color_from_json_member (reader, "backgroundColor", P_DEFAULT, &self->priv->colour, &success, error) || + gdata_parser_boolean_from_json_member (reader, "hidden", P_DEFAULT, &self->priv->is_hidden, &success, error) || + gdata_parser_boolean_from_json_member (reader, "selected", P_DEFAULT, &self->priv->is_selected, &success, error)) { + return success; + } else if (g_strcmp0 (json_reader_get_member_name (reader), "summary") == 0) { + gchar *summary = NULL; + + g_assert (gdata_parser_string_from_json_member (reader, + "summary", + P_DEFAULT, + &summary, + &success, + error)); + + if (summary != NULL) { + gdata_entry_set_title (GDATA_ENTRY (parsable), summary); + } + + g_free (summary); + + return success; + } else if (g_strcmp0 (json_reader_get_member_name (reader), "description") == 0) { + gchar *description = NULL; + + g_assert (gdata_parser_string_from_json_member (reader, + "description", + P_DEFAULT, + &description, + &success, + error)); + + if (description != NULL) { + gdata_entry_set_summary (GDATA_ENTRY (parsable), + description); + } + + g_free (description); + + return success; + } else if (g_strcmp0 (json_reader_get_member_name (reader), "accessRole") == 0) { + gchar *access_role = NULL; + + g_assert (gdata_parser_string_from_json_member (reader, + "accessRole", + P_DEFAULT, + &access_role, + &success, + error)); + + if (access_role != NULL) { + const gchar *level; + + /* Convert from v3 format to v2. */ + if (g_strcmp0 (access_role, "freeBusyReader") == 0) { + level = GDATA_CALENDAR_ACCESS_ROLE_FREE_BUSY; + } else if (g_strcmp0 (access_role, "reader") == 0) { + level = GDATA_CALENDAR_ACCESS_ROLE_READ; + } else if (g_strcmp0 (access_role, "writer") == 0) { + level = GDATA_CALENDAR_ACCESS_ROLE_EDITOR; + } else if (g_strcmp0 (access_role, "owner") == 0) { + level = GDATA_CALENDAR_ACCESS_ROLE_OWNER; + } else { + level = access_role; + } + + self->priv->access_level = g_strdup (level); + } + + g_free (access_role); + + return success; + } else if (g_strcmp0 (json_reader_get_member_name (reader), "id") == 0) { + GDataLink *_link; + const gchar *id; + gchar *uri; + + id = json_reader_get_string_value (reader); + if (id != NULL && *id != '\0') { + /* Calendar entries don’t contain their own selfLink, + * so we have to add one manually. */ + uri = g_strconcat ("https://www.googleapis.com/calendar/v3/calendars/", id, NULL); + _link = gdata_link_new (uri, GDATA_LINK_SELF); + gdata_entry_add_link (GDATA_ENTRY (parsable), _link); + g_object_unref (_link); + g_free (uri); + + /* Similarly for the ACL link. */ + uri = g_strconcat ("https://www.googleapis.com" + "/calendar/v3/calendars/", id, + "/acl", NULL); + _link = gdata_link_new (uri, + GDATA_LINK_ACCESS_CONTROL_LIST); + gdata_entry_add_link (GDATA_ENTRY (parsable), _link); + g_object_unref (_link); + g_free (uri); + } + + return GDATA_PARSABLE_CLASS (gdata_calendar_calendar_parent_class)->parse_json (parsable, reader, user_data, error); + } else { + return GDATA_PARSABLE_CLASS (gdata_calendar_calendar_parent_class)->parse_json (parsable, reader, user_data, error); + } + + return TRUE; +} + +static void +get_json (GDataParsable *parsable, JsonBuilder *builder) +{ + const gchar *id, *etag, *title, *description; + gchar *colour; + GDataCalendarCalendarPrivate *priv = GDATA_CALENDAR_CALENDAR (parsable)->priv; + + id = gdata_entry_get_id (GDATA_ENTRY (parsable)); + if (id != NULL) { + json_builder_set_member_name (builder, "id"); + json_builder_add_string_value (builder, id); + } + + json_builder_set_member_name (builder, "kind"); + json_builder_add_string_value (builder, "calendar#calendar"); + + /* Add the ETag, if available. */ + etag = gdata_entry_get_etag (GDATA_ENTRY (parsable)); + if (etag != NULL) { + json_builder_set_member_name (builder, "etag"); + json_builder_add_string_value (builder, etag); + } + + /* Calendar labels titles as ‘summary’. */ + title = gdata_entry_get_title (GDATA_ENTRY (parsable)); + if (title != NULL) { + json_builder_set_member_name (builder, "summary"); + json_builder_add_string_value (builder, title); + } + + description = gdata_entry_get_summary (GDATA_ENTRY (parsable)); + if (description != NULL) { + json_builder_set_member_name (builder, "description"); + json_builder_add_string_value (builder, description); + } + + /* Add all the calendar-specific JSON */ + if (priv->timezone != NULL) { + json_builder_set_member_name (builder, "timeZone"); + json_builder_add_string_value (builder, priv->timezone); + } + + json_builder_set_member_name (builder, "hidden"); + json_builder_add_boolean_value (builder, priv->is_hidden); + + colour = gdata_color_to_hexadecimal (&priv->colour); + json_builder_set_member_name (builder, "backgroundColor"); + json_builder_add_string_value (builder, colour); + g_free (colour); + + json_builder_set_member_name (builder, "selected"); + json_builder_add_boolean_value (builder, priv->is_selected); +} + +static const gchar * +get_content_type (void) +{ + return "application/json"; +} + +/** + * gdata_calendar_calendar_new: + * @id: (allow-none): the calendar's ID, or %NULL + * + * Creates a new #GDataCalendarCalendar with the given ID and default properties. + * + * Return value: a new #GDataCalendarCalendar; unref with g_object_unref() + */ +GDataCalendarCalendar * +gdata_calendar_calendar_new (const gchar *id) +{ + return GDATA_CALENDAR_CALENDAR (g_object_new (GDATA_TYPE_CALENDAR_CALENDAR, "id", id, NULL)); +} + +/** + * gdata_calendar_calendar_get_timezone: + * @self: a #GDataCalendarCalendar + * + * Gets the #GDataCalendarCalendar:timezone property. + * + * Return value: the calendar's timezone, or %NULL + */ +const gchar * +gdata_calendar_calendar_get_timezone (GDataCalendarCalendar *self) +{ + g_return_val_if_fail (GDATA_IS_CALENDAR_CALENDAR (self), NULL); + return self->priv->timezone; +} + +/** + * gdata_calendar_calendar_set_timezone: + * @self: a #GDataCalendarCalendar + * @_timezone: (allow-none): a new timezone, or %NULL + * + * Sets the #GDataCalendarCalendar:timezone property to the new timezone, @_timezone. + * + * Set @_timezone to %NULL to unset the property in the calendar. + */ +void +gdata_calendar_calendar_set_timezone (GDataCalendarCalendar *self, const gchar *_timezone) +{ + /* Blame "timezone" in /usr/include/time.h:291 for the weird parameter naming */ + g_return_if_fail (GDATA_IS_CALENDAR_CALENDAR (self)); + + g_free (self->priv->timezone); + self->priv->timezone = g_strdup (_timezone); + g_object_notify (G_OBJECT (self), "timezone"); +} + +/** + * gdata_calendar_calendar_get_times_cleaned: + * @self: a #GDataCalendarCalendar + * + * Gets the #GDataCalendarCalendar:times-cleaned property. + * + * Return value: the number of times the calendar has been totally emptied + * Deprecated: 0.17.2: Unsupported by the online API any more. There is no + * replacement; this will always return 0. + */ +guint +gdata_calendar_calendar_get_times_cleaned (GDataCalendarCalendar *self) +{ + g_return_val_if_fail (GDATA_IS_CALENDAR_CALENDAR (self), 0); + return 0; +} + +/** + * gdata_calendar_calendar_is_hidden: + * @self: a #GDataCalendarCalendar + * + * Gets the #GDataCalendarCalendar:is-hidden property. + * + * Return value: %TRUE if the calendar is hidden, %FALSE otherwise + * + * Since: 0.2.0 + */ +gboolean +gdata_calendar_calendar_is_hidden (GDataCalendarCalendar *self) +{ + g_return_val_if_fail (GDATA_IS_CALENDAR_CALENDAR (self), 0); + return self->priv->is_hidden; +} + +/** + * gdata_calendar_calendar_set_is_hidden: + * @self: a #GDataCalendarCalendar + * @is_hidden: %TRUE to hide the calendar, %FALSE otherwise + * + * Sets the #GDataCalendarCalendar:is-hidden property to @is_hidden. + * + * Since: 0.2.0 + */ +void +gdata_calendar_calendar_set_is_hidden (GDataCalendarCalendar *self, gboolean is_hidden) +{ + g_return_if_fail (GDATA_IS_CALENDAR_CALENDAR (self)); + self->priv->is_hidden = is_hidden; + g_object_notify (G_OBJECT (self), "is-hidden"); +} + +/** + * gdata_calendar_calendar_get_color: + * @self: a #GDataCalendarCalendar + * @color: (out caller-allocates): a #GDataColor + * + * Gets the #GDataCalendarCalendar:color property and puts it in @color. + */ +void +gdata_calendar_calendar_get_color (GDataCalendarCalendar *self, GDataColor *color) +{ + g_return_if_fail (GDATA_IS_CALENDAR_CALENDAR (self)); + g_return_if_fail (color != NULL); + *color = self->priv->colour; +} + +/** + * gdata_calendar_calendar_set_color: + * @self: a #GDataCalendarCalendar + * @color: a new #GDataColor + * + * Sets the #GDataCalendarCalendar:color property to @color. + */ +void +gdata_calendar_calendar_set_color (GDataCalendarCalendar *self, const GDataColor *color) +{ + g_return_if_fail (GDATA_IS_CALENDAR_CALENDAR (self)); + g_return_if_fail (color != NULL); + self->priv->colour = *color; + g_object_notify (G_OBJECT (self), "color"); +} + +/** + * gdata_calendar_calendar_is_selected: + * @self: a #GDataCalendarCalendar + * + * Gets the #GDataCalendarCalendar:is-selected property. + * + * Return value: %TRUE if the calendar is selected, %FALSE otherwise + * + * Since: 0.2.0 + */ +gboolean +gdata_calendar_calendar_is_selected (GDataCalendarCalendar *self) +{ + g_return_val_if_fail (GDATA_IS_CALENDAR_CALENDAR (self), 0); + return self->priv->is_selected; +} + +/** + * gdata_calendar_calendar_set_is_selected: + * @self: a #GDataCalendarCalendar + * @is_selected: %TRUE to select the calendar, %FALSE otherwise + * + * Sets the #GDataCalendarCalendar:is-selected property to @is_selected. + * + * Since: 0.2.0 + */ +void +gdata_calendar_calendar_set_is_selected (GDataCalendarCalendar *self, gboolean is_selected) +{ + g_return_if_fail (GDATA_IS_CALENDAR_CALENDAR (self)); + self->priv->is_selected = is_selected; + g_object_notify (G_OBJECT (self), "is-selected"); +} + +/** + * gdata_calendar_calendar_get_access_level: + * @self: a #GDataCalendarCalendar + * + * Gets the #GDataCalendarCalendar:access-level property. + * + * Return value: the authenticated user's access level to the calendar, or %NULL + */ +const gchar * +gdata_calendar_calendar_get_access_level (GDataCalendarCalendar *self) +{ + g_return_val_if_fail (GDATA_IS_CALENDAR_CALENDAR (self), NULL); + return self->priv->access_level; +} + +/** + * gdata_calendar_calendar_get_edited: + * @self: a #GDataCalendarCalendar + * + * Gets the #GDataCalendarCalendar:edited property. If the property is unset, -1 will be returned. + * + * Return value: the UNIX timestamp for the time the calendar was last edited, or -1 + * Deprecated: 0.17.2: Unsupported by the online API any more. There is no + * replacement; this will always return -1. + */ +gint64 +gdata_calendar_calendar_get_edited (GDataCalendarCalendar *self) +{ + g_return_val_if_fail (GDATA_IS_CALENDAR_CALENDAR (self), -1); + return -1; +} diff --git a/gdata/services/calendar/gdata-calendar-calendar.h b/gdata/services/calendar/gdata-calendar-calendar.h new file mode 100644 index 0000000..ecb61d4 --- /dev/null +++ b/gdata/services/calendar/gdata-calendar-calendar.h @@ -0,0 +1,86 @@ +/* -*- Mode: C; indent-tabs-mode: t; c-basic-offset: 8; tab-width: 8 -*- */ +/* + * GData Client + * Copyright (C) Philip Withnall 2009, 2015 + * + * GData Client is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * GData Client is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with GData Client. If not, see . + */ + +#ifndef GDATA_CALENDAR_CALENDAR_H +#define GDATA_CALENDAR_CALENDAR_H + +#include +#include + +#include +#include + +G_BEGIN_DECLS + +#define GDATA_TYPE_CALENDAR_CALENDAR (gdata_calendar_calendar_get_type ()) +#define GDATA_CALENDAR_CALENDAR(o) (G_TYPE_CHECK_INSTANCE_CAST ((o), GDATA_TYPE_CALENDAR_CALENDAR, GDataCalendarCalendar)) +#define GDATA_CALENDAR_CALENDAR_CLASS(k) (G_TYPE_CHECK_CLASS_CAST((k), GDATA_TYPE_CALENDAR_CALENDAR, GDataCalendarCalendarClass)) +#define GDATA_IS_CALENDAR_CALENDAR(o) (G_TYPE_CHECK_INSTANCE_TYPE ((o), GDATA_TYPE_CALENDAR_CALENDAR)) +#define GDATA_IS_CALENDAR_CALENDAR_CLASS(k) (G_TYPE_CHECK_CLASS_TYPE ((k), GDATA_TYPE_CALENDAR_CALENDAR)) +#define GDATA_CALENDAR_CALENDAR_GET_CLASS(o) (G_TYPE_INSTANCE_GET_CLASS ((o), GDATA_TYPE_CALENDAR_CALENDAR, GDataCalendarCalendarClass)) + +typedef struct _GDataCalendarCalendarPrivate GDataCalendarCalendarPrivate; + +/** + * GDataCalendarCalendar: + * + * All the fields in the #GDataCalendarCalendar structure are private and should never be accessed directly. + */ +typedef struct { + GDataEntry parent; + GDataCalendarCalendarPrivate *priv; +} GDataCalendarCalendar; + +/** + * GDataCalendarCalendarClass: + * + * All the fields in the #GDataCalendarCalendarClass structure are private and should never be accessed directly. + */ +typedef struct { + /*< private >*/ + GDataEntryClass parent; + + /*< private >*/ + /* Padding for future expansion */ + void (*_g_reserved0) (void); + void (*_g_reserved1) (void); +} GDataCalendarCalendarClass; + +GType gdata_calendar_calendar_get_type (void) G_GNUC_CONST; + +GDataCalendarCalendar *gdata_calendar_calendar_new (const gchar *id) G_GNUC_WARN_UNUSED_RESULT G_GNUC_MALLOC; + +const gchar *gdata_calendar_calendar_get_timezone (GDataCalendarCalendar *self) G_GNUC_PURE; +void gdata_calendar_calendar_set_timezone (GDataCalendarCalendar *self, const gchar *_timezone); +gboolean gdata_calendar_calendar_is_hidden (GDataCalendarCalendar *self) G_GNUC_PURE; +void gdata_calendar_calendar_set_is_hidden (GDataCalendarCalendar *self, gboolean is_hidden); +void gdata_calendar_calendar_get_color (GDataCalendarCalendar *self, GDataColor *color); +void gdata_calendar_calendar_set_color (GDataCalendarCalendar *self, const GDataColor *color); +gboolean gdata_calendar_calendar_is_selected (GDataCalendarCalendar *self) G_GNUC_PURE; +void gdata_calendar_calendar_set_is_selected (GDataCalendarCalendar *self, gboolean is_selected); +const gchar *gdata_calendar_calendar_get_access_level (GDataCalendarCalendar *self) G_GNUC_PURE; + +#ifndef LIBGDATA_DISABLE_DEPRECATED +guint gdata_calendar_calendar_get_times_cleaned (GDataCalendarCalendar *self) G_GNUC_PURE G_GNUC_DEPRECATED; +gint64 gdata_calendar_calendar_get_edited (GDataCalendarCalendar *self) G_GNUC_DEPRECATED; +#endif /* !LIBGDATA_DISABLE_DEPRECATED */ + +G_END_DECLS + +#endif /* !GDATA_CALENDAR_CALENDAR_H */ diff --git a/gdata/services/calendar/gdata-calendar-event.c b/gdata/services/calendar/gdata-calendar-event.c new file mode 100644 index 0000000..d11f045 --- /dev/null +++ b/gdata/services/calendar/gdata-calendar-event.c @@ -0,0 +1,1815 @@ +/* -*- Mode: C; indent-tabs-mode: t; c-basic-offset: 8; tab-width: 8 -*- */ +/* + * GData Client + * Copyright (C) Philip Withnall 2009, 2010, 2014, 2015 + * + * GData Client is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * GData Client is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with GData Client. If not, see . + */ + +/** + * SECTION:gdata-calendar-event + * @short_description: GData Calendar event object + * @stability: Stable + * @include: gdata/services/calendar/gdata-calendar-event.h + * + * #GDataCalendarEvent is a subclass of #GDataEntry to represent an event on a calendar from Google Calendar. + * + * For more details of Google Calendar's GData API, see the + * + * online documentation. + * + * + * Adding a New Event to the Default Calendar + * + * GDataCalendarService *service; + * GDataCalendarEvent *event, *new_event; + * GDataGDWhere *where; + * GDataGDWho *who; + * GDataGDWhen *when; + * GTimeVal current_time; + * GError *error = NULL; + * + * /* Create a service */ + * service = create_calendar_service (); + * + * /* Create the new event */ + * event = gdata_calendar_event_new (NULL); + * + * gdata_entry_set_title (GDATA_ENTRY (event), "Event Title"); + * gdata_entry_set_content (GDATA_ENTRY (event), "Event description. This should be a few sentences long."); + * gdata_calendar_event_set_status (event, GDATA_GD_EVENT_STATUS_CONFIRMED); + * + * where = gdata_gd_where_new (NULL, "Description of the location", NULL); + * gdata_calendar_event_add_place (event, where); + * g_object_unref (where); + * + * who = gdata_gd_who_new (GDATA_GD_WHO_EVENT_ORGANIZER, "John Smith", "john.smith@gmail.com"); + * gdata_calendar_event_add_person (event, who); + * g_object_unref (who); + * + * g_get_current_time (¤t_time); + * when = gdata_gd_when_new (current_time.tv_sec, current_time.tv_sec + 3600, FALSE); + * gdata_calendar_event_add_time (event, when); + * g_object_unref (when); + * + * /* Insert the event in the calendar */ + * new_event = gdata_calendar_service_insert_event (service, event, NULL, &error); + * + * g_object_unref (event); + * g_object_unref (service); + * + * if (error != NULL) { + * g_error ("Error inserting event: %s", error->message); + * g_error_free (error); + * return NULL; + * } + * + * /* Do something with the new_event here, such as return it to the user or store its ID for later usage */ + * + * g_object_unref (new_event); + * + * + */ + +#include +#include +#include +#include + +#include "gdata-calendar-event.h" +#include "gdata-private.h" +#include "gdata-service.h" +#include "gdata-parser.h" +#include "gdata-types.h" +#include "gdata-comparable.h" + +static GObject *gdata_calendar_event_constructor (GType type, guint n_construct_params, GObjectConstructParam *construct_params); +static void gdata_calendar_event_dispose (GObject *object); +static void gdata_calendar_event_finalize (GObject *object); +static void gdata_calendar_event_get_property (GObject *object, guint property_id, GValue *value, GParamSpec *pspec); +static void gdata_calendar_event_set_property (GObject *object, guint property_id, const GValue *value, GParamSpec *pspec); +static void get_json (GDataParsable *parsable, JsonBuilder *builder); +static gboolean parse_json (GDataParsable *parsable, JsonReader *reader, gpointer user_data, GError **error); +static gboolean post_parse_json (GDataParsable *parsable, gpointer user_data, GError **error); +static const gchar *get_content_type (void); + +struct _GDataCalendarEventPrivate { + gint64 edited; + gchar *status; + gchar *visibility; + gchar *transparency; + gchar *uid; + gint64 sequence; + GList *times; /* GDataGDWhen */ + gboolean guests_can_modify; + gboolean guests_can_invite_others; + gboolean guests_can_see_guests; + gboolean anyone_can_add_self; + GList *people; /* GDataGDWho */ + GList *places; /* GDataGDWhere */ + gchar *recurrence; + gchar *original_event_id; + gchar *original_event_uri; + gchar *organiser_email; /* owned */ + + /* Parsing state. */ + struct { + gint64 start_time; + gint64 end_time; + gboolean seen_start; + gboolean seen_end; + gboolean start_is_date; + gboolean end_is_date; + } parser; +}; + +enum { + PROP_EDITED = 1, + PROP_STATUS, + PROP_VISIBILITY, + PROP_TRANSPARENCY, + PROP_UID, + PROP_SEQUENCE, + PROP_GUESTS_CAN_MODIFY, + PROP_GUESTS_CAN_INVITE_OTHERS, + PROP_GUESTS_CAN_SEE_GUESTS, + PROP_ANYONE_CAN_ADD_SELF, + PROP_RECURRENCE, + PROP_ORIGINAL_EVENT_ID, + PROP_ORIGINAL_EVENT_URI +}; + +G_DEFINE_TYPE (GDataCalendarEvent, gdata_calendar_event, GDATA_TYPE_ENTRY) + +static void +gdata_calendar_event_class_init (GDataCalendarEventClass *klass) +{ + GObjectClass *gobject_class = G_OBJECT_CLASS (klass); + GDataParsableClass *parsable_class = GDATA_PARSABLE_CLASS (klass); + GDataEntryClass *entry_class = GDATA_ENTRY_CLASS (klass); + + g_type_class_add_private (klass, sizeof (GDataCalendarEventPrivate)); + + gobject_class->constructor = gdata_calendar_event_constructor; + gobject_class->get_property = gdata_calendar_event_get_property; + gobject_class->set_property = gdata_calendar_event_set_property; + gobject_class->dispose = gdata_calendar_event_dispose; + gobject_class->finalize = gdata_calendar_event_finalize; + + parsable_class->parse_json = parse_json; + parsable_class->post_parse_json = post_parse_json; + parsable_class->get_json = get_json; + parsable_class->get_content_type = get_content_type; + + entry_class->kind_term = "calendar#event"; + + /** + * GDataCalendarEvent:edited: + * + * The last time the event was edited. If the event has not been edited yet, the content indicates the time it was created. + * + * For more information, see the + * Atom Publishing Protocol specification. + */ + g_object_class_install_property (gobject_class, PROP_EDITED, + g_param_spec_int64 ("edited", + "Edited", "The last time the event was edited.", + -1, G_MAXINT64, -1, + G_PARAM_READABLE | G_PARAM_STATIC_STRINGS)); + + /** + * GDataCalendarEvent:status: + * + * The scheduling status of the event. For example: %GDATA_GD_EVENT_STATUS_CANCELED or %GDATA_GD_EVENT_STATUS_CONFIRMED. + * + * For more information, see the + * GData specification. + * + * Since: 0.2.0 + */ + g_object_class_install_property (gobject_class, PROP_STATUS, + g_param_spec_string ("status", + "Status", "The scheduling status of the event.", + NULL, + G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)); + + /** + * GDataCalendarEvent:visibility: + * + * The event's visibility to calendar users. For example: %GDATA_GD_EVENT_VISIBILITY_PUBLIC or %GDATA_GD_EVENT_VISIBILITY_DEFAULT. + * + * For more information, see the + * GData specification. + */ + g_object_class_install_property (gobject_class, PROP_VISIBILITY, + g_param_spec_string ("visibility", + "Visibility", "The event's visibility to calendar users.", + NULL, + G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)); + + /** + * GDataCalendarEvent:transparency: + * + * How the event is marked as consuming time on a calendar. For example: %GDATA_GD_EVENT_TRANSPARENCY_OPAQUE or + * %GDATA_GD_EVENT_TRANSPARENCY_TRANSPARENT. + * + * For more information, see the + * GData specification. + */ + g_object_class_install_property (gobject_class, PROP_TRANSPARENCY, + g_param_spec_string ("transparency", + "Transparency", "How the event is marked as consuming time on a calendar.", + NULL, + G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)); + + /** + * GDataCalendarEvent:uid: + * + * The globally unique identifier (UID) of the event as defined in Section 4.8.4.7 of RFC 2445. + */ + g_object_class_install_property (gobject_class, PROP_UID, + g_param_spec_string ("uid", + "UID", "The globally unique identifier (UID) of the event.", + NULL, + G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)); + + /** + * GDataCalendarEvent:sequence: + * + * The revision sequence number of the event as defined in Section 4.8.7.4 of RFC 2445. + */ + g_object_class_install_property (gobject_class, PROP_SEQUENCE, + g_param_spec_uint ("sequence", + "Sequence", "The revision sequence number of the event.", + 0, G_MAXUINT, 0, + G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)); + + /** + * GDataCalendarEvent:guests-can-modify: + * + * Indicates whether attendees may modify the original event, so that changes are visible to organizers and other attendees. + * Otherwise, any changes made by attendees will be restricted to that attendee's calendar. + * + * For more information, see the + * + * GData specification. + */ + g_object_class_install_property (gobject_class, PROP_GUESTS_CAN_MODIFY, + g_param_spec_boolean ("guests-can-modify", + "Guests can modify", "Indicates whether attendees may modify the original event.", + FALSE, + G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)); + + /** + * GDataCalendarEvent:guests-can-invite-others: + * + * Indicates whether attendees may invite others to the event. + * + * For more information, see the GData specification. + */ + g_object_class_install_property (gobject_class, PROP_GUESTS_CAN_INVITE_OTHERS, + g_param_spec_boolean ("guests-can-invite-others", + "Guests can invite others", "Indicates whether attendees may invite others.", + FALSE, + G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)); + + /** + * GDataCalendarEvent:guests-can-see-guests: + * + * Indicates whether attendees can see other people invited to the event. + * + * For more information, see the + * + * GData specification. + */ + g_object_class_install_property (gobject_class, PROP_GUESTS_CAN_SEE_GUESTS, + g_param_spec_boolean ("guests-can-see-guests", + "Guests can see guests", "Indicates whether attendees can see other people invited.", + FALSE, + G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)); + + /** + * GDataCalendarEvent:anyone-can-add-self: + * + * Indicates whether anyone can invite themselves to the event, by adding themselves to the attendee list. + */ + g_object_class_install_property (gobject_class, PROP_ANYONE_CAN_ADD_SELF, + g_param_spec_boolean ("anyone-can-add-self", + "Anyone can add self", "Indicates whether anyone can invite themselves to the event.", + FALSE, + G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)); + + /** + * GDataCalendarEvent:recurrence: + * + * Represents the dates and times when a recurring event takes place. The returned string is in iCal format, as a list of properties. + * + * For more information, see the + * GData specification. + * + * Note: gdata_calendar_event_add_time() and gdata_calendar_event_set_recurrence() are mutually + * exclusive. See the documentation for gdata_calendar_event_add_time() for details. + * + * Since: 0.3.0 + */ + g_object_class_install_property (gobject_class, PROP_RECURRENCE, + g_param_spec_string ("recurrence", + "Recurrence", "Represents the dates and times when a recurring event takes place.", + NULL, + G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)); + + /** + * GDataCalendarEvent:original-event-id: + * + * The event ID for the original event, if this event is an exception to a recurring event. + * + * Since: 0.3.0 + */ + g_object_class_install_property (gobject_class, PROP_ORIGINAL_EVENT_ID, + g_param_spec_string ("original-event-id", + "Original event ID", "The event ID for the original event.", + NULL, + G_PARAM_READABLE | G_PARAM_STATIC_STRINGS)); + + /** + * GDataCalendarEvent:original-event-uri: + * + * The event URI for the original event, if this event is an exception to a recurring event. + * + * Since: 0.3.0 + */ + g_object_class_install_property (gobject_class, PROP_ORIGINAL_EVENT_URI, + g_param_spec_string ("original-event-uri", + "Original event URI", "The event URI for the original event.", + NULL, + G_PARAM_READABLE | G_PARAM_STATIC_STRINGS)); +} + +static void +gdata_calendar_event_init (GDataCalendarEvent *self) +{ + self->priv = G_TYPE_INSTANCE_GET_PRIVATE (self, GDATA_TYPE_CALENDAR_EVENT, GDataCalendarEventPrivate); + self->priv->edited = -1; +} + +static GObject * +gdata_calendar_event_constructor (GType type, guint n_construct_params, GObjectConstructParam *construct_params) +{ + GObject *object; + + /* Chain up to the parent class */ + object = G_OBJECT_CLASS (gdata_calendar_event_parent_class)->constructor (type, n_construct_params, construct_params); + + if (_gdata_parsable_is_constructed_from_xml (GDATA_PARSABLE (object)) == FALSE) { + GDataCalendarEventPrivate *priv = GDATA_CALENDAR_EVENT (object)->priv; + GTimeVal time_val; + + /* Set the edited property to the current time (creation time). We don't do this in *_init() since that would cause + * setting it from parse_xml() to fail (duplicate element). */ + g_get_current_time (&time_val); + priv->edited = time_val.tv_sec; + } + + return object; +} + +static void +gdata_calendar_event_dispose (GObject *object) +{ + GDataCalendarEventPrivate *priv = GDATA_CALENDAR_EVENT (object)->priv; + + g_list_free_full(priv->times, g_object_unref); + priv->times = NULL; + + g_list_free_full (priv->people, g_object_unref); + priv->people = NULL; + + g_list_free_full (priv->places, g_object_unref); + priv->places = NULL; + + /* Chain up to the parent class */ + G_OBJECT_CLASS (gdata_calendar_event_parent_class)->dispose (object); +} + +static void +gdata_calendar_event_finalize (GObject *object) +{ + GDataCalendarEventPrivate *priv = GDATA_CALENDAR_EVENT (object)->priv; + + g_free (priv->status); + g_free (priv->visibility); + g_free (priv->transparency); + g_free (priv->uid); + g_free (priv->recurrence); + g_free (priv->original_event_id); + g_free (priv->original_event_uri); + g_free (priv->organiser_email); + + /* Chain up to the parent class */ + G_OBJECT_CLASS (gdata_calendar_event_parent_class)->finalize (object); +} + +static void +gdata_calendar_event_get_property (GObject *object, guint property_id, GValue *value, GParamSpec *pspec) +{ + GDataCalendarEventPrivate *priv = GDATA_CALENDAR_EVENT (object)->priv; + + switch (property_id) { + case PROP_EDITED: + g_value_set_int64 (value, priv->edited); + break; + case PROP_STATUS: + g_value_set_string (value, priv->status); + break; + case PROP_VISIBILITY: + g_value_set_string (value, priv->visibility); + break; + case PROP_TRANSPARENCY: + g_value_set_string (value, priv->transparency); + break; + case PROP_UID: + g_value_set_string (value, priv->uid); + break; + case PROP_SEQUENCE: + g_value_set_uint (value, CLAMP (priv->sequence, 0, G_MAXUINT)); + break; + case PROP_GUESTS_CAN_MODIFY: + g_value_set_boolean (value, priv->guests_can_modify); + break; + case PROP_GUESTS_CAN_INVITE_OTHERS: + g_value_set_boolean (value, priv->guests_can_invite_others); + break; + case PROP_GUESTS_CAN_SEE_GUESTS: + g_value_set_boolean (value, priv->guests_can_see_guests); + break; + case PROP_ANYONE_CAN_ADD_SELF: + g_value_set_boolean (value, priv->anyone_can_add_self); + break; + case PROP_RECURRENCE: + g_value_set_string (value, priv->recurrence); + break; + case PROP_ORIGINAL_EVENT_ID: + g_value_set_string (value, priv->original_event_id); + break; + case PROP_ORIGINAL_EVENT_URI: + g_value_set_string (value, priv->original_event_uri); + break; + default: + /* We don't have any other property... */ + G_OBJECT_WARN_INVALID_PROPERTY_ID (object, property_id, pspec); + break; + } +} + +static void +gdata_calendar_event_set_property (GObject *object, guint property_id, const GValue *value, GParamSpec *pspec) +{ + GDataCalendarEvent *self = GDATA_CALENDAR_EVENT (object); + + switch (property_id) { + case PROP_STATUS: + gdata_calendar_event_set_status (self, g_value_get_string (value)); + break; + case PROP_VISIBILITY: + gdata_calendar_event_set_visibility (self, g_value_get_string (value)); + break; + case PROP_TRANSPARENCY: + gdata_calendar_event_set_transparency (self, g_value_get_string (value)); + break; + case PROP_UID: + gdata_calendar_event_set_uid (self, g_value_get_string (value)); + break; + case PROP_SEQUENCE: + gdata_calendar_event_set_sequence (self, g_value_get_uint (value)); + break; + case PROP_GUESTS_CAN_MODIFY: + gdata_calendar_event_set_guests_can_modify (self, g_value_get_boolean (value)); + break; + case PROP_GUESTS_CAN_INVITE_OTHERS: + gdata_calendar_event_set_guests_can_invite_others (self, g_value_get_boolean (value)); + break; + case PROP_GUESTS_CAN_SEE_GUESTS: + gdata_calendar_event_set_guests_can_see_guests (self, g_value_get_boolean (value)); + break; + case PROP_ANYONE_CAN_ADD_SELF: + gdata_calendar_event_set_anyone_can_add_self (self, g_value_get_boolean (value)); + break; + case PROP_RECURRENCE: + gdata_calendar_event_set_recurrence (self, g_value_get_string (value)); + break; + default: + /* We don't have any other property... */ + G_OBJECT_WARN_INVALID_PROPERTY_ID (object, property_id, pspec); + break; + } +} + +static gboolean +date_object_from_json (JsonReader *reader, + const gchar *member_name, + GDataParserOptions options, + gint64 *date_time_output, + gboolean *is_date_output, + gboolean *success, + GError **error) +{ + gint64 date_time; + gboolean is_date = FALSE; + gboolean found_member = FALSE; + + /* Check if there’s such an element */ + if (g_strcmp0 (json_reader_get_member_name (reader), member_name) != 0) { + return FALSE; + } + + /* Check that it’s an object. */ + if (!json_reader_is_object (reader)) { + const GError *child_error; + + /* Manufacture an error. */ + json_reader_read_member (reader, "dateTime"); + child_error = json_reader_get_error (reader); + g_assert (child_error != NULL); + *success = gdata_parser_error_from_json_error (reader, + child_error, + error); + json_reader_end_member (reader); + + return TRUE; + } + + /* Try to parse either the dateTime or date member. */ + if (json_reader_read_member (reader, "dateTime")) { + const gchar *date_string; + const GError *child_error; + GTimeVal time_val; + + date_string = json_reader_get_string_value (reader); + child_error = json_reader_get_error (reader); + + if (child_error != NULL) { + *success = gdata_parser_error_from_json_error (reader, + child_error, + error); + json_reader_end_member (reader); + return TRUE; + } + + if (!g_time_val_from_iso8601 (date_string, &time_val)) { + *success = gdata_parser_error_not_iso8601_format_json (reader, date_string, error); + json_reader_end_member (reader); + return TRUE; + } + + date_time = time_val.tv_sec; + is_date = FALSE; + found_member = TRUE; + } + json_reader_end_member (reader); + + if (json_reader_read_member (reader, "date")) { + const gchar *date_string; + const GError *child_error; + + date_string = json_reader_get_string_value (reader); + child_error = json_reader_get_error (reader); + + if (child_error != NULL) { + *success = gdata_parser_error_from_json_error (reader, + child_error, + error); + json_reader_end_member (reader); + return TRUE; + } + + if (!gdata_parser_int64_from_date (date_string, &date_time)) { + *success = gdata_parser_error_not_iso8601_format_json (reader, date_string, error); + json_reader_end_member (reader); + return TRUE; + } + + is_date = TRUE; + found_member = TRUE; + } + json_reader_end_member (reader); + + /* Ignore timeZone; it should be specified in dateTime. */ + if (!found_member) { + *success = gdata_parser_error_required_json_content_missing (reader, error); + return TRUE; + } + + *date_time_output = date_time; + *is_date_output = is_date; + *success = TRUE; + + return TRUE; +} + +/* Convert between v2 and v3 versions of various enum values. v2 uses a URI + * style with a constant prefix; v3 simply drops this prefix, and changes the + * spelling of ‘canceled’ to ‘cancelled’. */ +#define V2_PREFIX "http://schemas.google.com/g/2005#event." + +static gchar * +add_v2_prefix (const gchar *in) +{ + return g_strconcat (V2_PREFIX, in, NULL); +} + +static const gchar * +strip_v2_prefix (const gchar *uri) +{ + /* Convert to v3 format. */ + if (g_str_has_prefix (uri, V2_PREFIX)) { + return uri + strlen (V2_PREFIX); + } else { + return uri; + } +} + +static gboolean +parse_json (GDataParsable *parsable, JsonReader *reader, gpointer user_data, GError **error) +{ + gboolean success; + GDataCalendarEvent *self = GDATA_CALENDAR_EVENT (parsable); + GDataCalendarEventPrivate *priv = self->priv; + + /* FIXME: Currently unsupported: + * - htmlLink + * - colorId + * - endTimeUnspecified + * - originalStartTime + * - attendeesOmitted + * - extendedProperties + * - hangoutLink + * - gadget + * - privateCopy + * - locked + * - reminders + * - source + */ + + if (g_strcmp0 (json_reader_get_member_name (reader), "start") == 0) { + self->priv->parser.seen_start = TRUE; + } else if (g_strcmp0 (json_reader_get_member_name (reader), "end") == 0) { + self->priv->parser.seen_end = TRUE; + } + + if (gdata_parser_string_from_json_member (reader, "recurringEventId", P_DEFAULT, &self->priv->original_event_id, &success, error) || + gdata_parser_boolean_from_json_member (reader, "guestsCanModify", P_DEFAULT, &self->priv->guests_can_modify, &success, error) || + gdata_parser_boolean_from_json_member (reader, "guestsCanInviteOthers", P_DEFAULT, &self->priv->guests_can_invite_others, &success, error) || + gdata_parser_boolean_from_json_member (reader, "guestsCanSeeOtherGuests", P_DEFAULT, &self->priv->guests_can_see_guests, &success, error) || + gdata_parser_boolean_from_json_member (reader, "anyoneCanAddSelf", P_DEFAULT, &self->priv->anyone_can_add_self, &success, error) || + gdata_parser_string_from_json_member (reader, "iCalUID", P_DEFAULT, &self->priv->uid, &success, error) || + gdata_parser_int_from_json_member (reader, "sequence", P_DEFAULT, &self->priv->sequence, &success, error) || + gdata_parser_int64_time_from_json_member (reader, "updated", P_DEFAULT, &self->priv->edited, &success, error) || + date_object_from_json (reader, "start", P_DEFAULT, &self->priv->parser.start_time, &self->priv->parser.start_is_date, &success, error) || + date_object_from_json (reader, "end", P_DEFAULT, &self->priv->parser.end_time, &self->priv->parser.end_is_date, &success, error)) { + if (success) { + if (self->priv->edited != -1) { + _gdata_entry_set_updated (GDATA_ENTRY (parsable), + self->priv->edited); + } + + if (self->priv->original_event_id != NULL) { + g_free (self->priv->original_event_uri); + self->priv->original_event_uri = g_strconcat ("https://www.googleapis.com/calendar/v3/events/", + self->priv->original_event_id, NULL); + } + + if (self->priv->parser.seen_start && self->priv->parser.seen_end) { + GDataGDWhen *when; + + when = gdata_gd_when_new (self->priv->parser.start_time, + self->priv->parser.end_time, + self->priv->parser.start_is_date || + self->priv->parser.end_is_date); + self->priv->times = g_list_prepend (self->priv->times, when); /* transfer ownership */ + + self->priv->parser.seen_start = FALSE; + self->priv->parser.seen_end = FALSE; + } + } + + return success; + } else if (g_strcmp0 (json_reader_get_member_name (reader), "transparency") == 0) { + gchar *transparency = NULL; /* owned */ + + g_assert (gdata_parser_string_from_json_member (reader, + "transparency", + P_DEFAULT, + &transparency, + &success, + error)); + + if (success) { + priv->transparency = add_v2_prefix (transparency); + } + + g_free (transparency); + + return success; + } else if (g_strcmp0 (json_reader_get_member_name (reader), "visibility") == 0) { + gchar *visibility = NULL; /* owned */ + + g_assert (gdata_parser_string_from_json_member (reader, + "visibility", + P_DEFAULT, + &visibility, + &success, + error)); + + if (success) { + priv->visibility = add_v2_prefix (visibility); + } + + g_free (visibility); + + return success; + } else if (g_strcmp0 (json_reader_get_member_name (reader), "status") == 0) { + gchar *status = NULL; /* owned */ + + g_assert (gdata_parser_string_from_json_member (reader, + "status", + P_DEFAULT, + &status, + &success, + error)); + + if (success) { + if (g_strcmp0 (status, "cancelled") == 0) { + /* Those damned British Englishes. */ + priv->status = add_v2_prefix ("canceled"); + } else { + priv->status = add_v2_prefix (status); + } + } + + g_free (status); + + return success; + } else if (g_strcmp0 (json_reader_get_member_name (reader), "summary") == 0) { + const gchar *summary; + const GError *child_error = NULL; + + summary = json_reader_get_string_value (reader); + child_error = json_reader_get_error (reader); + + if (child_error != NULL) { + gdata_parser_error_from_json_error (reader, + child_error, error); + return FALSE; + } + + gdata_entry_set_title (GDATA_ENTRY (parsable), summary); + } else if (g_strcmp0 (json_reader_get_member_name (reader), "description") == 0) { + const gchar *description; + const GError *child_error = NULL; + + description = json_reader_get_string_value (reader); + child_error = json_reader_get_error (reader); + + if (child_error != NULL) { + gdata_parser_error_from_json_error (reader, + child_error, error); + return FALSE; + } + + gdata_entry_set_content (GDATA_ENTRY (parsable), description); + } else if (g_strcmp0 (json_reader_get_member_name (reader), "location") == 0) { + const gchar *location; + GDataGDWhere *where = NULL; /* owned */ + const GError *child_error = NULL; + + location = json_reader_get_string_value (reader); + child_error = json_reader_get_error (reader); + + if (child_error != NULL) { + gdata_parser_error_from_json_error (reader, + child_error, error); + return FALSE; + } + + where = gdata_gd_where_new (GDATA_GD_WHERE_EVENT, + location, NULL); + priv->places = g_list_prepend (priv->places, where); /* transfer ownership */ + } else if (g_strcmp0 (json_reader_get_member_name (reader), "created") == 0) { + gint64 created; + + g_assert (gdata_parser_int64_time_from_json_member (reader, + "created", + P_DEFAULT, + &created, + &success, + error)); + + if (success) { + _gdata_entry_set_published (GDATA_ENTRY (parsable), + created); + } + + return success; + } else if (g_strcmp0 (json_reader_get_member_name (reader), "recurrence") == 0) { + guint i, j; + GString *recurrence = NULL; /* owned */ + + /* In the JSON API, the recurrence is given as an array of + * strings, each giving an RFC 2445 property such as RRULE, + * EXRULE, RDATE or EXDATE. Concatenate them all to form a + * recurrence string as used in v2 of the API. */ + if (self->priv->recurrence != NULL) { + return gdata_parser_error_duplicate_json_element (reader, + error); + } + + recurrence = g_string_new (""); + + for (i = 0, j = json_reader_count_elements (reader); i < j; i++) { + const gchar *line; + const GError *child_error; + + json_reader_read_element (reader, i); + + line = json_reader_get_string_value (reader); + child_error = json_reader_get_error (reader); + if (child_error != NULL) { + gdata_parser_error_from_json_error (reader, child_error, error); + json_reader_end_element (reader); + return FALSE; + } + + g_string_append (recurrence, line); + g_string_append (recurrence, "\n"); + + json_reader_end_element (reader); + } + + g_assert (self->priv->recurrence == NULL); + self->priv->recurrence = g_string_free (recurrence, FALSE); + + return TRUE; + } else if (g_strcmp0 (json_reader_get_member_name (reader), "attendees") == 0) { + guint i, j; + + if (priv->people != NULL) { + return gdata_parser_error_duplicate_json_element (reader, + error); + } + + for (i = 0, j = json_reader_count_elements (reader); i < j; i++) { + GDataGDWho *who = NULL; /* owned */ + const gchar *email_address, *value_string; + const gchar *relation_type; + gboolean is_organizer, is_resource; + const GError *child_error; + + json_reader_read_element (reader, i); + + json_reader_read_member (reader, "responseStatus"); + child_error = json_reader_get_error (reader); + if (child_error != NULL) { + gdata_parser_error_from_json_error (reader, + child_error, + error); + json_reader_end_member (reader); + return FALSE; + } + json_reader_end_member (reader); + + json_reader_read_member (reader, "email"); + email_address = json_reader_get_string_value (reader); + json_reader_end_member (reader); + + json_reader_read_member (reader, "displayName"); + value_string = json_reader_get_string_value (reader); + json_reader_end_member (reader); + + json_reader_read_member (reader, "organizer"); + is_organizer = json_reader_get_boolean_value (reader); + json_reader_end_member (reader); + + json_reader_read_member (reader, "resource"); + is_resource = json_reader_get_boolean_value (reader); + json_reader_end_member (reader); + + /* FIXME: Currently unsupported: + * - id + * - self + * - optional (writeble) + * - responseStatus (writeble) + * - comment (writeble) + * - additionalGuests (writeble) + */ + + if (is_organizer) { + relation_type = GDATA_GD_WHO_EVENT_ORGANIZER; + } else if (!is_resource) { + relation_type = GDATA_GD_WHO_EVENT_ATTENDEE; + } else { + /* FIXME: Add support for resources. */ + relation_type = NULL; + } + + who = gdata_gd_who_new (relation_type, value_string, + email_address); + priv->people = g_list_prepend (priv->people, who); /* transfer ownership */ + + json_reader_end_element (reader); + } + } else if (g_strcmp0 (json_reader_get_member_name (reader), "organizer") == 0) { + /* This actually gives the parent calendar. Optional. */ + g_clear_pointer (&priv->organiser_email, g_free); + if (json_reader_read_member (reader, "email")) + priv->organiser_email = g_strdup (json_reader_get_string_value (reader)); + json_reader_end_member (reader); + + return TRUE; + } else if (g_strcmp0 (json_reader_get_member_name (reader), "creator") == 0) { + /* These are read-only and already handled as part of + * ‘attendees’, so ignore them. */ + return TRUE; + } else { + return GDATA_PARSABLE_CLASS (gdata_calendar_event_parent_class)->parse_json (parsable, reader, user_data, error); + } + + return TRUE; +} + +static gboolean +post_parse_json (GDataParsable *parsable, gpointer user_data, GError **error) +{ + GDataLink *_link = NULL; /* owned */ + const gchar *id, *calendar_id; + gchar *uri = NULL; /* owned */ + GDataCalendarEventPrivate *priv; + + priv = GDATA_CALENDAR_EVENT (parsable)->priv; + + /* Set the self link, which is needed for gdata_service_delete_entry(). + * Unfortunately, it needs the event ID _and_ the calendar ID — which + * is perversely only available as the organiser e-mail address. */ + id = gdata_entry_get_id (GDATA_ENTRY (parsable)); + calendar_id = priv->organiser_email; + + if (id == NULL || calendar_id == NULL) { + return TRUE; + } + + uri = g_strconcat ("https://www.googleapis.com/calendar/v3/calendars/", + calendar_id, "/events/", id, NULL); + _link = gdata_link_new (uri, GDATA_LINK_SELF); + gdata_entry_add_link (GDATA_ENTRY (parsable), _link); + g_object_unref (_link); + g_free (uri); + + return TRUE; +} + +static void +get_json (GDataParsable *parsable, JsonBuilder *builder) +{ + GList *l; + const gchar *id, *etag, *title, *description; + GDataGDWho *organiser_who = NULL; /* unowned */ + GDataCalendarEventPrivate *priv = GDATA_CALENDAR_EVENT (parsable)->priv; + + /* FIXME: Support: + * - colorId + * - attendeesOmitted + * - extendedProperties + * - gadget + * - reminders + * - source + */ + + id = gdata_entry_get_id (GDATA_ENTRY (parsable)); + if (id != NULL) { + json_builder_set_member_name (builder, "id"); + json_builder_add_string_value (builder, id); + } + + json_builder_set_member_name (builder, "kind"); + json_builder_add_string_value (builder, "calendar#event"); + + /* Add the ETag, if available. */ + etag = gdata_entry_get_etag (GDATA_ENTRY (parsable)); + if (etag != NULL) { + json_builder_set_member_name (builder, "etag"); + json_builder_add_string_value (builder, etag); + } + + /* Calendar labels titles as ‘summary’. */ + title = gdata_entry_get_title (GDATA_ENTRY (parsable)); + if (title != NULL) { + json_builder_set_member_name (builder, "summary"); + json_builder_add_string_value (builder, title); + } + + description = gdata_entry_get_content (GDATA_ENTRY (parsable)); + if (description != NULL) { + json_builder_set_member_name (builder, "description"); + json_builder_add_string_value (builder, description); + } + + /* Add all the calendar-specific JSON */ + json_builder_set_member_name (builder, "anyoneCanAddSelf"); + json_builder_add_boolean_value (builder, priv->anyone_can_add_self); + + json_builder_set_member_name (builder, "guestsCanInviteOthers"); + json_builder_add_boolean_value (builder, priv->guests_can_invite_others); + + json_builder_set_member_name (builder, "guestsCanModify"); + json_builder_add_boolean_value (builder, priv->guests_can_modify); + + json_builder_set_member_name (builder, "guestsCanSeeOtherGuests"); + json_builder_add_boolean_value (builder, priv->guests_can_see_guests); + + if (priv->transparency != NULL) { + json_builder_set_member_name (builder, "transparency"); + json_builder_add_string_value (builder, + strip_v2_prefix (priv->transparency)); + } + + if (priv->visibility != NULL) { + json_builder_set_member_name (builder, "visibility"); + json_builder_add_string_value (builder, + strip_v2_prefix (priv->visibility)); + } + + if (priv->uid != NULL) { + json_builder_set_member_name (builder, "iCalUID"); + json_builder_add_string_value (builder, priv->uid); + } + + if (priv->sequence > 0) { + json_builder_set_member_name (builder, "sequence"); + json_builder_add_int_value (builder, priv->sequence); + } + + if (priv->status != NULL) { + const gchar *status; + + /* Convert to v3 format. */ + status = strip_v2_prefix (priv->status); + if (g_strcmp0 (status, "canceled") == 0) { + status = "cancelled"; + } + + json_builder_set_member_name (builder, "status"); + json_builder_add_string_value (builder, status); + } + + if (priv->recurrence != NULL) { + gchar **parts; + guint i; + + json_builder_set_member_name (builder, "recurrence"); + json_builder_begin_array (builder); + + parts = g_strsplit (priv->recurrence, "\n", -1); + + for (i = 0; parts[i] != NULL; i++) { + json_builder_add_string_value (builder, parts[i]); + } + + g_strfreev (parts); + + json_builder_end_array (builder); + } + + if (priv->original_event_id != NULL) { + json_builder_set_member_name (builder, "recurringEventId"); + json_builder_add_string_value (builder, priv->original_event_id); + } + + /* Times. */ + for (l = priv->times; l != NULL; l = l->next) { + GDataGDWhen *when; /* unowned */ + gchar *val = NULL; /* owned */ + const gchar *member_name; + gint64 start_time, end_time; + + when = l->data; + + /* Start time. */ + start_time = gdata_gd_when_get_start_time (when); + json_builder_set_member_name (builder, "start"); + json_builder_begin_object (builder); + + if (gdata_gd_when_is_date (when)) { + member_name = "date"; + val = gdata_parser_date_from_int64 (start_time); + } else { + member_name = "dateTime"; + val = gdata_parser_int64_to_iso8601 (start_time); + } + + json_builder_set_member_name (builder, member_name); + json_builder_add_string_value (builder, val); + g_free (val); + + json_builder_set_member_name (builder, "timeZone"); + json_builder_add_string_value (builder, "UTC"); + + json_builder_end_object (builder); + + /* End time. */ + end_time = gdata_gd_when_get_end_time (when); + + if (end_time > -1) { + json_builder_set_member_name (builder, "end"); + json_builder_begin_object (builder); + + if (gdata_gd_when_is_date (when)) { + member_name = "date"; + val = gdata_parser_date_from_int64 (end_time); + } else { + member_name = "dateTime"; + val = gdata_parser_int64_to_iso8601 (end_time); + } + + json_builder_set_member_name (builder, member_name); + json_builder_add_string_value (builder, val); + g_free (val); + + json_builder_set_member_name (builder, "timeZone"); + json_builder_add_string_value (builder, "UTC"); + + json_builder_end_object (builder); + } else { + json_builder_set_member_name (builder, "endTimeUnspecified"); + json_builder_add_boolean_value (builder, TRUE); + } + + /* Only use the first time. :-( + * FIXME: There must be a better solution. */ + if (l->next != NULL) { + g_warning ("Ignoring secondary times; they are no " + "longer supported by the server-side API."); + break; + } + } + + /* Locations. */ + for (l = priv->places; l != NULL; l = l->next) { + GDataGDWhere *where; /* unowned */ + const gchar *location; + + where = l->data; + location = gdata_gd_where_get_value_string (where); + + json_builder_set_member_name (builder, "location"); + json_builder_add_string_value (builder, location); + + /* Only use the first location. :-( + * FIXME: There must be a better solution. */ + if (l->next != NULL) { + g_warning ("Ignoring secondary locations; they are no " + "longer supported by the server-side API."); + break; + } + } + + /* People. */ + json_builder_set_member_name (builder, "attendees"); + json_builder_begin_array (builder); + + for (l = priv->people; l != NULL; l = l->next) { + GDataGDWho *who; /* unowned */ + const gchar *display_name, *email_address; + + who = l->data; + + json_builder_begin_object (builder); + + display_name = gdata_gd_who_get_value_string (who); + if (display_name != NULL) { + json_builder_set_member_name (builder, "displayName"); + json_builder_add_string_value (builder, display_name); + } + + email_address = gdata_gd_who_get_email_address (who); + if (email_address != NULL) { + json_builder_set_member_name (builder, "email"); + json_builder_add_string_value (builder, email_address); + } + + if (g_strcmp0 (gdata_gd_who_get_relation_type (who), + GDATA_GD_WHO_EVENT_ORGANIZER) == 0) { + json_builder_set_member_name (builder, "organizer"); + json_builder_add_boolean_value (builder, TRUE); + + organiser_who = who; + } + + json_builder_end_object (builder); + } + + json_builder_end_array (builder); + + if (organiser_who != NULL) { + const gchar *display_name, *email_address; + + json_builder_set_member_name (builder, "organizer"); + json_builder_begin_object (builder); + + display_name = gdata_gd_who_get_value_string (organiser_who); + if (display_name != NULL) { + json_builder_set_member_name (builder, "displayName"); + json_builder_add_string_value (builder, display_name); + } + + email_address = gdata_gd_who_get_email_address (organiser_who); + if (email_address != NULL) { + json_builder_set_member_name (builder, "email"); + json_builder_add_string_value (builder, email_address); + } + + json_builder_end_object (builder); + } +} + +static const gchar * +get_content_type (void) +{ + return "application/json"; +} + +/** + * gdata_calendar_event_new: + * @id: (allow-none): the event's ID, or %NULL + * + * Creates a new #GDataCalendarEvent with the given ID and default properties. + * + * Return value: a new #GDataCalendarEvent; unref with g_object_unref() + */ +GDataCalendarEvent * +gdata_calendar_event_new (const gchar *id) +{ + return GDATA_CALENDAR_EVENT (g_object_new (GDATA_TYPE_CALENDAR_EVENT, "id", id, NULL)); +} + +/** + * gdata_calendar_event_get_edited: + * @self: a #GDataCalendarEvent + * + * Gets the #GDataCalendarEvent:edited property. If the property is unset, -1 will be returned. + * + * Return value: the UNIX timestamp for the time the event was last edited, or -1 + */ +gint64 +gdata_calendar_event_get_edited (GDataCalendarEvent *self) +{ + g_return_val_if_fail (GDATA_IS_CALENDAR_EVENT (self), -1); + return self->priv->edited; +} + +/** + * gdata_calendar_event_get_status: + * @self: a #GDataCalendarEvent + * + * Gets the #GDataCalendarEvent:status property. + * + * Return value: the event status, or %NULL + * + * Since: 0.2.0 + */ +const gchar * +gdata_calendar_event_get_status (GDataCalendarEvent *self) +{ + g_return_val_if_fail (GDATA_IS_CALENDAR_EVENT (self), NULL); + return self->priv->status; +} + +/** + * gdata_calendar_event_set_status: + * @self: a #GDataCalendarEvent + * @status: (allow-none): a new event status, or %NULL + * + * Sets the #GDataCalendarEvent:status property to the new status, @status. + * + * Set @status to %NULL to unset the property in the event. + * + * Since: 0.2.0 + */ +void +gdata_calendar_event_set_status (GDataCalendarEvent *self, const gchar *status) +{ + g_return_if_fail (GDATA_IS_CALENDAR_EVENT (self)); + + g_free (self->priv->status); + self->priv->status = g_strdup (status); + g_object_notify (G_OBJECT (self), "status"); +} + +/** + * gdata_calendar_event_get_visibility: + * @self: a #GDataCalendarEvent + * + * Gets the #GDataCalendarEvent:visibility property. + * + * Return value: the event visibility, or %NULL + */ +const gchar * +gdata_calendar_event_get_visibility (GDataCalendarEvent *self) +{ + g_return_val_if_fail (GDATA_IS_CALENDAR_EVENT (self), NULL); + return self->priv->visibility; +} + +/** + * gdata_calendar_event_set_visibility: + * @self: a #GDataCalendarEvent + * @visibility: (allow-none): a new event visibility, or %NULL + * + * Sets the #GDataCalendarEvent:visibility property to the new visibility, @visibility. + * + * Set @visibility to %NULL to unset the property in the event. + */ +void +gdata_calendar_event_set_visibility (GDataCalendarEvent *self, const gchar *visibility) +{ + g_return_if_fail (GDATA_IS_CALENDAR_EVENT (self)); + + g_free (self->priv->visibility); + self->priv->visibility = g_strdup (visibility); + g_object_notify (G_OBJECT (self), "visibility"); +} + +/** + * gdata_calendar_event_get_transparency: + * @self: a #GDataCalendarEvent + * + * Gets the #GDataCalendarEvent:transparency property. + * + * Return value: the event transparency, or %NULL + */ +const gchar * +gdata_calendar_event_get_transparency (GDataCalendarEvent *self) +{ + g_return_val_if_fail (GDATA_IS_CALENDAR_EVENT (self), NULL); + return self->priv->transparency; +} + +/** + * gdata_calendar_event_set_transparency: + * @self: a #GDataCalendarEvent + * @transparency: (allow-none): a new event transparency, or %NULL + * + * Sets the #GDataCalendarEvent:transparency property to the new transparency, @transparency. + * + * Set @transparency to %NULL to unset the property in the event. + */ +void +gdata_calendar_event_set_transparency (GDataCalendarEvent *self, const gchar *transparency) +{ + g_return_if_fail (GDATA_IS_CALENDAR_EVENT (self)); + + g_free (self->priv->transparency); + self->priv->transparency = g_strdup (transparency); + g_object_notify (G_OBJECT (self), "transparency"); +} + +/** + * gdata_calendar_event_get_uid: + * @self: a #GDataCalendarEvent + * + * Gets the #GDataCalendarEvent:uid property. + * + * Return value: the event's UID, or %NULL + */ +const gchar * +gdata_calendar_event_get_uid (GDataCalendarEvent *self) +{ + g_return_val_if_fail (GDATA_IS_CALENDAR_EVENT (self), NULL); + return self->priv->uid; +} + +/** + * gdata_calendar_event_set_uid: + * @self: a #GDataCalendarEvent + * @uid: (allow-none): a new event UID, or %NULL + * + * Sets the #GDataCalendarEvent:uid property to the new UID, @uid. + * + * Set @uid to %NULL to unset the property in the event. + */ +void +gdata_calendar_event_set_uid (GDataCalendarEvent *self, const gchar *uid) +{ + /* TODO: is modifying this allowed? */ + g_return_if_fail (GDATA_IS_CALENDAR_EVENT (self)); + + g_free (self->priv->uid); + self->priv->uid = g_strdup (uid); + g_object_notify (G_OBJECT (self), "uid"); +} + +/** + * gdata_calendar_event_get_sequence: + * @self: a #GDataCalendarEvent + * + * Gets the #GDataCalendarEvent:sequence property. + * + * Return value: the event's sequence number + */ +guint +gdata_calendar_event_get_sequence (GDataCalendarEvent *self) +{ + g_return_val_if_fail (GDATA_IS_CALENDAR_EVENT (self), 0); + return CLAMP (self->priv->sequence, 0, G_MAXUINT); +} + +/** + * gdata_calendar_event_set_sequence: + * @self: a #GDataCalendarEvent + * @sequence: a new sequence number, or 0 + * + * Sets the #GDataCalendarEvent:sequence property to the new sequence number, @sequence. + */ +void +gdata_calendar_event_set_sequence (GDataCalendarEvent *self, guint sequence) +{ + g_return_if_fail (GDATA_IS_CALENDAR_EVENT (self)); + self->priv->sequence = sequence; + g_object_notify (G_OBJECT (self), "sequence"); +} + +/** + * gdata_calendar_event_get_guests_can_modify: + * @self: a #GDataCalendarEvent + * + * Gets the #GDataCalendarEvent:guests-can-modify property. + * + * Return value: %TRUE if attendees can modify the original event, %FALSE otherwise + */ +gboolean +gdata_calendar_event_get_guests_can_modify (GDataCalendarEvent *self) +{ + g_return_val_if_fail (GDATA_IS_CALENDAR_EVENT (self), FALSE); + return self->priv->guests_can_modify; +} + +/** + * gdata_calendar_event_set_guests_can_modify: + * @self: a #GDataCalendarEvent + * @guests_can_modify: %TRUE if attendees can modify the original event, %FALSE otherwise + * + * Sets the #GDataCalendarEvent:guests-can-modify property to @guests_can_modify. + */ +void +gdata_calendar_event_set_guests_can_modify (GDataCalendarEvent *self, gboolean guests_can_modify) +{ + g_return_if_fail (GDATA_IS_CALENDAR_EVENT (self)); + self->priv->guests_can_modify = guests_can_modify; + g_object_notify (G_OBJECT (self), "guests-can-modify"); +} + +/** + * gdata_calendar_event_get_guests_can_invite_others: + * @self: a #GDataCalendarEvent + * + * Gets the #GDataCalendarEvent:guests-can-invite-others property. + * + * Return value: %TRUE if attendees can invite others to the event, %FALSE otherwise + */ +gboolean +gdata_calendar_event_get_guests_can_invite_others (GDataCalendarEvent *self) +{ + g_return_val_if_fail (GDATA_IS_CALENDAR_EVENT (self), FALSE); + return self->priv->guests_can_invite_others; +} + +/** + * gdata_calendar_event_set_guests_can_invite_others: + * @self: a #GDataCalendarEvent + * @guests_can_invite_others: %TRUE if attendees can invite others to the event, %FALSE otherwise + * + * Sets the #GDataCalendarEvent:guests-can-invite-others property to @guests_can_invite_others. + */ +void +gdata_calendar_event_set_guests_can_invite_others (GDataCalendarEvent *self, gboolean guests_can_invite_others) +{ + g_return_if_fail (GDATA_IS_CALENDAR_EVENT (self)); + self->priv->guests_can_invite_others = guests_can_invite_others; + g_object_notify (G_OBJECT (self), "guests-can-invite-others"); +} + +/** + * gdata_calendar_event_get_guests_can_see_guests: + * @self: a #GDataCalendarEvent + * + * Gets the #GDataCalendarEvent:guests-can-see-guests property. + * + * Return value: %TRUE if attendees can see who's attending the event, %FALSE otherwise + */ +gboolean +gdata_calendar_event_get_guests_can_see_guests (GDataCalendarEvent *self) +{ + g_return_val_if_fail (GDATA_IS_CALENDAR_EVENT (self), FALSE); + return self->priv->guests_can_see_guests; +} + +/** + * gdata_calendar_event_set_guests_can_see_guests: + * @self: a #GDataCalendarEvent + * @guests_can_see_guests: %TRUE if attendees can see who's attending the event, %FALSE otherwise + * + * Sets the #GDataCalendarEvent:guests-can-see-guests property to @guests_can_see_guests. + */ +void +gdata_calendar_event_set_guests_can_see_guests (GDataCalendarEvent *self, gboolean guests_can_see_guests) +{ + g_return_if_fail (GDATA_IS_CALENDAR_EVENT (self)); + self->priv->guests_can_see_guests = guests_can_see_guests; + g_object_notify (G_OBJECT (self), "guests-can-see-guests"); +} + +/** + * gdata_calendar_event_get_anyone_can_add_self: + * @self: a #GDataCalendarEvent + * + * Gets the #GDataCalendarEvent:anyone-can-add-self property. + * + * Return value: %TRUE if anyone can add themselves as an attendee to the event, %FALSE otherwise + */ +gboolean +gdata_calendar_event_get_anyone_can_add_self (GDataCalendarEvent *self) +{ + g_return_val_if_fail (GDATA_IS_CALENDAR_EVENT (self), FALSE); + return self->priv->anyone_can_add_self; +} + +/** + * gdata_calendar_event_set_anyone_can_add_self: + * @self: a #GDataCalendarEvent + * @anyone_can_add_self: %TRUE if anyone can add themselves as an attendee to the event, %FALSE otherwise + * + * Sets the #GDataCalendarEvent:anyone-can-add-self property to @anyone_can_add_self. + */ +void +gdata_calendar_event_set_anyone_can_add_self (GDataCalendarEvent *self, gboolean anyone_can_add_self) +{ + g_return_if_fail (GDATA_IS_CALENDAR_EVENT (self)); + self->priv->anyone_can_add_self = anyone_can_add_self; + g_object_notify (G_OBJECT (self), "anyone-can-add-self"); +} + +/** + * gdata_calendar_event_add_person: + * @self: a #GDataCalendarEvent + * @who: a #GDataGDWho to add + * + * Adds the person @who to the event as a guest (attendee, organiser, performer, etc.), and increments its reference count. + * + * Duplicate people will not be added to the list. + */ +void +gdata_calendar_event_add_person (GDataCalendarEvent *self, GDataGDWho *who) +{ + g_return_if_fail (GDATA_IS_CALENDAR_EVENT (self)); + g_return_if_fail (GDATA_IS_GD_WHO (who)); + + if (g_list_find_custom (self->priv->people, who, (GCompareFunc) gdata_comparable_compare) == NULL) + self->priv->people = g_list_append (self->priv->people, g_object_ref (who)); +} + +/** + * gdata_calendar_event_get_people: + * @self: a #GDataCalendarEvent + * + * Gets a list of the people attending the event. + * + * Return value: (element-type GData.GDWho) (transfer none): a #GList of #GDataGDWhos, or %NULL + * + * Since: 0.2.0 + */ +GList * +gdata_calendar_event_get_people (GDataCalendarEvent *self) +{ + g_return_val_if_fail (GDATA_IS_CALENDAR_EVENT (self), NULL); + return self->priv->people; +} + +/** + * gdata_calendar_event_add_place: + * @self: a #GDataCalendarEvent + * @where: a #GDataGDWhere to add + * + * Adds the place @where to the event as a location and increments its reference count. + * + * Duplicate places will not be added to the list. + */ +void +gdata_calendar_event_add_place (GDataCalendarEvent *self, GDataGDWhere *where) +{ + g_return_if_fail (GDATA_IS_CALENDAR_EVENT (self)); + g_return_if_fail (GDATA_IS_GD_WHERE (where)); + + if (g_list_find_custom (self->priv->places, where, (GCompareFunc) gdata_comparable_compare) == NULL) + self->priv->places = g_list_append (self->priv->places, g_object_ref (where)); +} + +/** + * gdata_calendar_event_get_places: + * @self: a #GDataCalendarEvent + * + * Gets a list of the locations associated with the event. + * + * Return value: (element-type GData.GDWhere) (transfer none): a #GList of #GDataGDWheres, or %NULL + * + * Since: 0.2.0 + */ +GList * +gdata_calendar_event_get_places (GDataCalendarEvent *self) +{ + g_return_val_if_fail (GDATA_IS_CALENDAR_EVENT (self), NULL); + return self->priv->places; +} + +/** + * gdata_calendar_event_add_time: + * @self: a #GDataCalendarEvent + * @when: a #GDataGDWhen to add + * + * Adds @when to the event as a time period when the event happens, and increments its reference count. + * + * Duplicate times will not be added to the list. + * + * Note: gdata_calendar_event_add_time() and gdata_calendar_event_set_recurrence() are mutually + * exclusive, as the server doesn't support positive exceptions to recurrence rules. If recurrences + * are required, use gdata_calendar_event_set_recurrence(). Note that this means reminders cannot + * be set for the event, as they are only supported by #GDataGDWhen. No checks are performed for + * these forbidden conditions, as to do so would break libgdata's API; if both a recurrence is set + * and a specific time is added, the server will return an error when the #GDataCalendarEvent is + * inserted using gdata_service_insert_entry(). + * + * Since: 0.2.0 + */ +void +gdata_calendar_event_add_time (GDataCalendarEvent *self, GDataGDWhen *when) +{ + g_return_if_fail (GDATA_IS_CALENDAR_EVENT (self)); + g_return_if_fail (GDATA_IS_GD_WHEN (when)); + + if (g_list_find_custom (self->priv->times, when, (GCompareFunc) gdata_comparable_compare) == NULL) + self->priv->times = g_list_append (self->priv->times, g_object_ref (when)); +} + +/** + * gdata_calendar_event_get_times: + * @self: a #GDataCalendarEvent + * + * Gets a list of the time periods associated with the event. + * + * Return value: (element-type GData.GDWhen) (transfer none): a #GList of #GDataGDWhens, or %NULL + * + * Since: 0.2.0 + */ +GList * +gdata_calendar_event_get_times (GDataCalendarEvent *self) +{ + g_return_val_if_fail (GDATA_IS_CALENDAR_EVENT (self), NULL); + return self->priv->times; +} + +/** + * gdata_calendar_event_get_primary_time: + * @self: a #GDataCalendarEvent + * @start_time: (out caller-allocates): a #gint64 for the start time, or %NULL + * @end_time: (out caller-allocates): a #gint64 for the end time, or %NULL + * @when: (out callee-allocates) (transfer none): a #GDataGDWhen for the primary time structure, or %NULL + * + * Gets the first time period associated with the event, conveniently returning just its start and + * end times if required. + * + * If there are no time periods, or more than one time period, associated with the event, %FALSE will + * be returned, and the parameters will remain unmodified. + * + * Return value: %TRUE if there is only one time period associated with the event, %FALSE otherwise + * + * Since: 0.2.0 + */ +gboolean +gdata_calendar_event_get_primary_time (GDataCalendarEvent *self, gint64 *start_time, gint64 *end_time, GDataGDWhen **when) +{ + GDataGDWhen *primary_when; + + g_return_val_if_fail (GDATA_IS_CALENDAR_EVENT (self), FALSE); + + if (self->priv->times == NULL || self->priv->times->next != NULL) + return FALSE; + + primary_when = GDATA_GD_WHEN (self->priv->times->data); + if (start_time != NULL) + *start_time = gdata_gd_when_get_start_time (primary_when); + if (end_time != NULL) + *end_time = gdata_gd_when_get_end_time (primary_when); + if (when != NULL) + *when = primary_when; + + return TRUE; +} + +/** + * gdata_calendar_event_get_recurrence: + * @self: a #GDataCalendarEvent + * + * Gets the #GDataCalendarEvent:recurrence property. + * + * Return value: the event recurrence patterns, or %NULL + * + * Since: 0.3.0 + */ +const gchar * +gdata_calendar_event_get_recurrence (GDataCalendarEvent *self) +{ + g_return_val_if_fail (GDATA_IS_CALENDAR_EVENT (self), NULL); + return self->priv->recurrence; +} + +/** + * gdata_calendar_event_set_recurrence: + * @self: a #GDataCalendarEvent + * @recurrence: (allow-none): a new event recurrence, or %NULL + * + * Sets the #GDataCalendarEvent:recurrence property to the new recurrence, @recurrence. + * + * Set @recurrence to %NULL to unset the property in the event. + * + * Note: gdata_calendar_event_add_time() and gdata_calendar_event_set_recurrence() are mutually + * exclusive. See the documentation for gdata_calendar_event_add_time() for details. + * + * Since: 0.3.0 + */ +void +gdata_calendar_event_set_recurrence (GDataCalendarEvent *self, const gchar *recurrence) +{ + g_return_if_fail (GDATA_IS_CALENDAR_EVENT (self)); + + g_free (self->priv->recurrence); + self->priv->recurrence = g_strdup (recurrence); + g_object_notify (G_OBJECT (self), "recurrence"); +} + +/** + * gdata_calendar_event_get_original_event_details: + * @self: a #GDataCalendarEvent + * @event_id: (out callee-allocates) (transfer full): return location for the original event's ID, or %NULL + * @event_uri: (out callee-allocates) (transfer full): return location for the original event's URI, or %NULL + * + * Gets details of the original event, if this event is an exception to a recurring event. The original + * event's ID and the URI of the event's XML are returned in @event_id and @event_uri, respectively. + * + * If this event is not an exception to a recurring event, @event_id and @event_uri will be set to %NULL. + * See gdata_calendar_event_is_exception() to determine more simply whether an event is an exception to a + * recurring event. + * + * If both @event_id and @event_uri are %NULL, this function is a no-op. Otherwise, they should both be + * freed with g_free(). + * + * Since: 0.3.0 + */ +void +gdata_calendar_event_get_original_event_details (GDataCalendarEvent *self, gchar **event_id, gchar **event_uri) +{ + g_return_if_fail (GDATA_IS_CALENDAR_EVENT (self)); + + if (event_id != NULL) + *event_id = g_strdup (self->priv->original_event_id); + if (event_uri != NULL) + *event_uri = g_strdup (self->priv->original_event_uri); +} + +/** + * gdata_calendar_event_is_exception: + * @self: a #GDataCalendarEvent + * + * Determines whether the event is an exception to a recurring event. If it is, details of the original event + * can be retrieved using gdata_calendar_event_get_original_event_details(). + * + * Return value: %TRUE if the event is an exception, %FALSE otherwise + * + * Since: 0.3.0 + */ +gboolean +gdata_calendar_event_is_exception (GDataCalendarEvent *self) +{ + g_return_val_if_fail (GDATA_IS_CALENDAR_EVENT (self), FALSE); + return (self->priv->original_event_id != NULL && self->priv->original_event_uri != NULL) ? TRUE : FALSE; +} diff --git a/gdata/services/calendar/gdata-calendar-event.h b/gdata/services/calendar/gdata-calendar-event.h new file mode 100644 index 0000000..c19ff50 --- /dev/null +++ b/gdata/services/calendar/gdata-calendar-event.h @@ -0,0 +1,105 @@ +/* -*- Mode: C; indent-tabs-mode: t; c-basic-offset: 8; tab-width: 8 -*- */ +/* + * GData Client + * Copyright (C) Philip Withnall 2009 + * + * GData Client is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * GData Client is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with GData Client. If not, see . + */ + +#ifndef GDATA_CALENDAR_EVENT_H +#define GDATA_CALENDAR_EVENT_H + +#include +#include + +#include +#include +#include +#include +#include + +G_BEGIN_DECLS + +#define GDATA_TYPE_CALENDAR_EVENT (gdata_calendar_event_get_type ()) +#define GDATA_CALENDAR_EVENT(o) (G_TYPE_CHECK_INSTANCE_CAST ((o), GDATA_TYPE_CALENDAR_EVENT, GDataCalendarEvent)) +#define GDATA_CALENDAR_EVENT_CLASS(k) (G_TYPE_CHECK_CLASS_CAST((k), GDATA_TYPE_CALENDAR_EVENT, GDataCalendarEventClass)) +#define GDATA_IS_CALENDAR_EVENT(o) (G_TYPE_CHECK_INSTANCE_TYPE ((o), GDATA_TYPE_CALENDAR_EVENT)) +#define GDATA_IS_CALENDAR_EVENT_CLASS(k) (G_TYPE_CHECK_CLASS_TYPE ((k), GDATA_TYPE_CALENDAR_EVENT)) +#define GDATA_CALENDAR_EVENT_GET_CLASS(o) (G_TYPE_INSTANCE_GET_CLASS ((o), GDATA_TYPE_CALENDAR_EVENT, GDataCalendarEventClass)) + +typedef struct _GDataCalendarEventPrivate GDataCalendarEventPrivate; + +/** + * GDataCalendarEvent: + * + * All the fields in the #GDataCalendarEvent structure are private and should never be accessed directly. + */ +typedef struct { + GDataEntry parent; + GDataCalendarEventPrivate *priv; +} GDataCalendarEvent; + +/** + * GDataCalendarEventClass: + * + * All the fields in the #GDataCalendarEventClass structure are private and should never be accessed directly. + */ +typedef struct { + /*< private >*/ + GDataEntryClass parent; + + /*< private >*/ + /* Padding for future expansion */ + void (*_g_reserved0) (void); + void (*_g_reserved1) (void); +} GDataCalendarEventClass; + +GType gdata_calendar_event_get_type (void) G_GNUC_CONST; + +GDataCalendarEvent *gdata_calendar_event_new (const gchar *id) G_GNUC_WARN_UNUSED_RESULT G_GNUC_MALLOC; + +gint64 gdata_calendar_event_get_edited (GDataCalendarEvent *self); +const gchar *gdata_calendar_event_get_status (GDataCalendarEvent *self) G_GNUC_PURE; +void gdata_calendar_event_set_status (GDataCalendarEvent *self, const gchar *status); +const gchar *gdata_calendar_event_get_visibility (GDataCalendarEvent *self) G_GNUC_PURE; +void gdata_calendar_event_set_visibility (GDataCalendarEvent *self, const gchar *visibility); +const gchar *gdata_calendar_event_get_transparency (GDataCalendarEvent *self) G_GNUC_PURE; +void gdata_calendar_event_set_transparency (GDataCalendarEvent *self, const gchar *transparency); +const gchar *gdata_calendar_event_get_uid (GDataCalendarEvent *self) G_GNUC_PURE; +void gdata_calendar_event_set_uid (GDataCalendarEvent *self, const gchar *uid); +guint gdata_calendar_event_get_sequence (GDataCalendarEvent *self) G_GNUC_PURE; +void gdata_calendar_event_set_sequence (GDataCalendarEvent *self, guint sequence); +gboolean gdata_calendar_event_get_guests_can_modify (GDataCalendarEvent *self) G_GNUC_PURE; +void gdata_calendar_event_set_guests_can_modify (GDataCalendarEvent *self, gboolean guests_can_modify); +gboolean gdata_calendar_event_get_guests_can_invite_others (GDataCalendarEvent *self) G_GNUC_PURE; +void gdata_calendar_event_set_guests_can_invite_others (GDataCalendarEvent *self, gboolean guests_can_invite_others); +gboolean gdata_calendar_event_get_guests_can_see_guests (GDataCalendarEvent *self) G_GNUC_PURE; +void gdata_calendar_event_set_guests_can_see_guests (GDataCalendarEvent *self, gboolean guests_can_see_guests); +gboolean gdata_calendar_event_get_anyone_can_add_self (GDataCalendarEvent *self) G_GNUC_PURE; +void gdata_calendar_event_set_anyone_can_add_self (GDataCalendarEvent *self, gboolean anyone_can_add_self); +void gdata_calendar_event_add_person (GDataCalendarEvent *self, GDataGDWho *who); +GList *gdata_calendar_event_get_people (GDataCalendarEvent *self) G_GNUC_PURE; +void gdata_calendar_event_add_place (GDataCalendarEvent *self, GDataGDWhere *where); +GList *gdata_calendar_event_get_places (GDataCalendarEvent *self) G_GNUC_PURE; +void gdata_calendar_event_add_time (GDataCalendarEvent *self, GDataGDWhen *when); +GList *gdata_calendar_event_get_times (GDataCalendarEvent *self) G_GNUC_PURE; +gboolean gdata_calendar_event_get_primary_time (GDataCalendarEvent *self, gint64 *start_time, gint64 *end_time, GDataGDWhen **when); +const gchar *gdata_calendar_event_get_recurrence (GDataCalendarEvent *self) G_GNUC_PURE; +void gdata_calendar_event_set_recurrence (GDataCalendarEvent *self, const gchar *recurrence); +void gdata_calendar_event_get_original_event_details (GDataCalendarEvent *self, gchar **event_id, gchar **event_uri); +gboolean gdata_calendar_event_is_exception (GDataCalendarEvent *self) G_GNUC_PURE; + +G_END_DECLS + +#endif /* !GDATA_CALENDAR_EVENT_H */ diff --git a/gdata/services/calendar/gdata-calendar-feed.c b/gdata/services/calendar/gdata-calendar-feed.c new file mode 100644 index 0000000..1a8ece3 --- /dev/null +++ b/gdata/services/calendar/gdata-calendar-feed.c @@ -0,0 +1,158 @@ +/* -*- Mode: C; indent-tabs-mode: t; c-basic-offset: 8; tab-width: 8 -*- */ +/* + * GData Client + * Copyright (C) Philip Withnall 2009, 2010, 2014, 2015 + * + * GData Client is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * GData Client is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with GData Client. If not, see . + */ + +/** + * SECTION:gdata-calendar-feed + * @short_description: GData Calendar feed object + * @stability: Stable + * @include: gdata/services/calendar/gdata-calendar-feed.h + * + * #GDataCalendarFeed is a subclass of #GDataFeed to represent a results feed from Google Calendar. It adds a couple of + * properties which are specific to the Google Calendar API. + */ + +#include +#include + +#include "gdata-calendar-feed.h" +#include "gdata-feed.h" +#include "gdata-private.h" + +static void gdata_calendar_feed_get_property (GObject *object, guint property_id, GValue *value, GParamSpec *pspec); + +enum { + PROP_TIMEZONE = 1, + PROP_TIMES_CLEANED +}; + +G_DEFINE_TYPE (GDataCalendarFeed, gdata_calendar_feed, GDATA_TYPE_FEED) + +static void +gdata_calendar_feed_class_init (GDataCalendarFeedClass *klass) +{ + GObjectClass *gobject_class = G_OBJECT_CLASS (klass); + + gobject_class->get_property = gdata_calendar_feed_get_property; + + /** + * GDataCalendarFeed:timezone: + * + * The timezone in which the feed's times are given. This is a timezone name in tz database notation: reference. + * + * Since: 0.3.0 + * Deprecated: 0.17.2: Unsupported by the online API any more. There + * is no replacement; this will always return %NULL. + */ + g_object_class_install_property (gobject_class, PROP_TIMEZONE, + g_param_spec_string ("timezone", + "Timezone", "The timezone in which the feed's times are given.", + NULL, + G_PARAM_DEPRECATED | + G_PARAM_READABLE | + G_PARAM_STATIC_STRINGS)); + + /** + * GDataCalendarFeed:times-cleaned: + * + * The number of times the feed has been completely cleared of entries. + * + * Since: 0.3.0 + * Deprecated: 0.17.2: Unsupported by the online API any more. There + * is no replacement; this will always return 0. + */ + g_object_class_install_property (gobject_class, PROP_TIMES_CLEANED, + g_param_spec_uint ("times-cleaned", + "Times cleaned", "The number of times the feed has been completely cleared of entries.", + 0, G_MAXUINT, 0, + G_PARAM_DEPRECATED | + G_PARAM_READABLE | + G_PARAM_STATIC_STRINGS)); +} + +static void +gdata_calendar_feed_init (GDataCalendarFeed *self) +{ + /* Nothing to see here. */ +} + +static void +gdata_calendar_feed_get_property (GObject *object, guint property_id, GValue *value, GParamSpec *pspec) +{ + GDataCalendarFeed *self = GDATA_CALENDAR_FEED (object); + + switch (property_id) { + case PROP_TIMEZONE: + G_GNUC_BEGIN_IGNORE_DEPRECATIONS + g_value_set_string (value, + gdata_calendar_feed_get_timezone (self)); + G_GNUC_END_IGNORE_DEPRECATIONS + break; + case PROP_TIMES_CLEANED: + G_GNUC_BEGIN_IGNORE_DEPRECATIONS + g_value_set_uint (value, + gdata_calendar_feed_get_times_cleaned (self)); + G_GNUC_END_IGNORE_DEPRECATIONS + break; + default: + /* We don't have any other property... */ + G_OBJECT_WARN_INVALID_PROPERTY_ID (object, property_id, pspec); + break; + } +} + +/** + * gdata_calendar_feed_get_timezone: + * @self: a #GDataCalendarFeed + * + * Gets the #GDataCalendarFeed:timezone property. + * + * Return value: the feed's timezone, or %NULL + * + * Since: 0.3.0 + * Deprecated: 0.17.2: Unsupported by the online API any more. There is no + * replacement; this will always return %NULL. + */ +const gchar * +gdata_calendar_feed_get_timezone (GDataCalendarFeed *self) +{ + /* Not supported any more by version 3 of the API. */ + g_return_val_if_fail (GDATA_IS_CALENDAR_FEED (self), NULL); + return NULL; +} + +/** + * gdata_calendar_feed_get_times_cleaned: + * @self: a #GDataCalendarFeed + * + * Gets the #GDataCalendarFeed:times-cleaned property. + * + * Return value: the number of times the feed has been totally emptied + * + * Since: 0.3.0 + * Deprecated: 0.17.2: Unsupported by the online API any more. There is no + * replacement; this will always return %NULL. + */ +guint +gdata_calendar_feed_get_times_cleaned (GDataCalendarFeed *self) +{ + /* Not supported any more by version 3 of the API. */ + g_return_val_if_fail (GDATA_IS_CALENDAR_FEED (self), 0); + return 0; +} diff --git a/gdata/services/calendar/gdata-calendar-feed.h b/gdata/services/calendar/gdata-calendar-feed.h new file mode 100644 index 0000000..43b6452 --- /dev/null +++ b/gdata/services/calendar/gdata-calendar-feed.h @@ -0,0 +1,78 @@ +/* -*- Mode: C; indent-tabs-mode: t; c-basic-offset: 8; tab-width: 8 -*- */ +/* + * GData Client + * Copyright (C) Philip Withnall 2009, 2015 + * + * GData Client is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * GData Client is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with GData Client. If not, see . + */ + +#ifndef GDATA_CALENDAR_FEED_H +#define GDATA_CALENDAR_FEED_H + +#include +#include + +#include +#include + +G_BEGIN_DECLS + +#define GDATA_TYPE_CALENDAR_FEED (gdata_calendar_feed_get_type ()) +#define GDATA_CALENDAR_FEED(o) (G_TYPE_CHECK_INSTANCE_CAST ((o), GDATA_TYPE_CALENDAR_FEED, GDataCalendarFeed)) +#define GDATA_CALENDAR_FEED_CLASS(k) (G_TYPE_CHECK_CLASS_CAST((k), GDATA_TYPE_CALENDAR_FEED, GDataCalendarFeedClass)) +#define GDATA_IS_CALENDAR_FEED(o) (G_TYPE_CHECK_INSTANCE_TYPE ((o), GDATA_TYPE_CALENDAR_FEED)) +#define GDATA_IS_CALENDAR_FEED_CLASS(k) (G_TYPE_CHECK_CLASS_TYPE ((k), GDATA_TYPE_CALENDAR_FEED)) +#define GDATA_CALENDAR_FEED_GET_CLASS(o) (G_TYPE_INSTANCE_GET_CLASS ((o), GDATA_TYPE_CALENDAR_FEED, GDataCalendarFeedClass)) + +typedef struct _GDataCalendarFeedPrivate GDataCalendarFeedPrivate; + +/** + * GDataCalendarFeed: + * + * All the fields in the #GDataCalendarFeed structure are private and should never be accessed directly. + * + * Since: 0.3.0 + */ +typedef struct { + GDataFeed parent; + GDataCalendarFeedPrivate *priv; +} GDataCalendarFeed; + +/** + * GDataCalendarFeedClass: + * + * All the fields in the #GDataCalendarFeedClass structure are private and should never be accessed directly. + * + * Since: 0.3.0 + */ +typedef struct { + /*< private >*/ + GDataFeedClass parent; + + /*< private >*/ + /* Padding for future expansion */ + void (*_g_reserved0) (void); + void (*_g_reserved1) (void); +} GDataCalendarFeedClass; + +GType gdata_calendar_feed_get_type (void); + +#ifndef LIBGDATA_DISABLE_DEPRECATED +const gchar *gdata_calendar_feed_get_timezone (GDataCalendarFeed *self) G_GNUC_PURE G_GNUC_DEPRECATED; +guint gdata_calendar_feed_get_times_cleaned (GDataCalendarFeed *self) G_GNUC_PURE G_GNUC_DEPRECATED; +#endif /* !LIBGDATA_DISABLE_DEPRECATED */ + +G_END_DECLS + +#endif /* !GDATA_CALENDAR_FEED_H */ diff --git a/gdata/services/calendar/gdata-calendar-query.c b/gdata/services/calendar/gdata-calendar-query.c new file mode 100644 index 0000000..a64960c --- /dev/null +++ b/gdata/services/calendar/gdata-calendar-query.c @@ -0,0 +1,974 @@ +/* -*- Mode: C; indent-tabs-mode: t; c-basic-offset: 8; tab-width: 8 -*- */ +/* + * GData Client + * Copyright (C) Philip Withnall 2009, 2010, 2017 + * + * GData Client is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * GData Client is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with GData Client. If not, see . + */ + +/** + * SECTION:gdata-calendar-query + * @short_description: GData Calendar query object + * @stability: Stable + * @include: gdata/services/calendar/gdata-calendar-query.h + * + * #GDataCalendarQuery represents a collection of query parameters specific to the Google Calendar service, which go above and beyond + * those catered for by #GDataQuery. + * + * For more information on the custom GData query parameters supported by #GDataCalendarQuery, see the online + * documentation. + * + * + * Querying for Events + * + * GDataCalendarService *service; + * GDataCalendarCalendar *calendar; + * GDataCalendarQuery *query; + * GDataFeed *feed; + * GTimeVal current_time; + * GList *i; + * GError *error = NULL; + * + * /* Create a service and find a calendar to query in */ + * service = create_calendar_service (); + * calendar = get_calendar (service); + * + * /* Create the query to use. We're going to query for events within the next week which match the search term "party", + * * ordered by last modification time (descending). */ + * g_get_current_time (¤t_time); + * query = gdata_calendar_query_new_with_limits ("party", current_time.tv_sec, current_time.tv_sec + 7 * 24 * 60 * 60); + * gdata_calendar_query_set_order_by (query, "lastmodified"); + * + * /* Execute the query */ + * feed = gdata_calendar_service_query_events (service, calendar, query, NULL, NULL, NULL, &error); + * + * g_object_unref (query); + * g_object_unref (calendar); + * g_object_unref (service); + * + * if (error != NULL) { + * g_error ("Error querying for events: %s", error->message); + * g_error_free (error); + * return; + * } + * + * /* Iterate through the returned events and do something with them */ + * for (i = gdata_feed_get_entries (feed); i != NULL; i = i->next) { + * GDataCalendarEvent *event = GDATA_CALENDAR_EVENT (i->data); + * + * /* Do something with the event here, such as insert it into a UI */ + * } + * + * g_object_unref (feed); + * + * + */ + +#include +#include +#include +#include + +#include "gdata-calendar-query.h" +#include "gdata-query.h" +#include "gdata-parser.h" +#include "gdata-private.h" + +static void gdata_calendar_query_finalize (GObject *object); +static void gdata_calendar_query_get_property (GObject *object, guint property_id, GValue *value, GParamSpec *pspec); +static void gdata_calendar_query_set_property (GObject *object, guint property_id, const GValue *value, GParamSpec *pspec); +static void get_query_uri (GDataQuery *self, const gchar *feed_uri, GString *query_uri, gboolean *params_started); + +struct _GDataCalendarQueryPrivate { + gboolean future_events; + gchar *order_by; /* TODO: #defined values */ + gint64 recurrence_expansion_start; + gint64 recurrence_expansion_end; + gboolean single_events; + gchar *sort_order; /* TODO: #defined values */ + gint64 start_min; /* UNIX timestamp, seconds */ + gint64 start_max; /* UNIX timestamp, seconds */ + gchar *timezone; + guint max_attendees; + gboolean show_deleted; +}; + +enum { + PROP_FUTURE_EVENTS = 1, + PROP_ORDER_BY, + PROP_RECURRENCE_EXPANSION_START, + PROP_RECURRENCE_EXPANSION_END, + PROP_SINGLE_EVENTS, + PROP_SORT_ORDER, + PROP_START_MIN, + PROP_START_MAX, + PROP_TIMEZONE, + PROP_MAX_ATTENDEES, + PROP_SHOW_DELETED, +}; + +G_DEFINE_TYPE (GDataCalendarQuery, gdata_calendar_query, GDATA_TYPE_QUERY) + +static void +gdata_calendar_query_class_init (GDataCalendarQueryClass *klass) +{ + GObjectClass *gobject_class = G_OBJECT_CLASS (klass); + GDataQueryClass *query_class = GDATA_QUERY_CLASS (klass); + + g_type_class_add_private (klass, sizeof (GDataCalendarQueryPrivate)); + + gobject_class->set_property = gdata_calendar_query_set_property; + gobject_class->get_property = gdata_calendar_query_get_property; + gobject_class->finalize = gdata_calendar_query_finalize; + + query_class->get_query_uri = get_query_uri; + + /** + * GDataCalendarQuery:future-events: + * + * A shortcut to request all events scheduled for the future. Overrides the + * #GDataCalendarQuery:recurrence-expansion-start, #GDataCalendarQuery:recurrence-expansion-end, + * #GDataCalendarQuery:start-min and #GDataCalendarQuery:start-max properties. + */ + g_object_class_install_property (gobject_class, PROP_FUTURE_EVENTS, + g_param_spec_boolean ("future-events", + "Future events?", "A shortcut to request all events scheduled for the future.", + FALSE, + G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)); + + /** + * GDataCalendarQuery:order-by: + * + * Specifies order of entries in a feed. Supported values are lastmodified and + * starttime. + */ + g_object_class_install_property (gobject_class, PROP_ORDER_BY, + g_param_spec_string ("order-by", + "Order by", "Specifies order of entries in a feed.", + NULL, + G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)); + + /** + * GDataCalendarQuery:recurrence-expansion-start: + * + * Specifies the beginning of the time period to expand recurring events for, inclusive. + * + * Deprecated: 0.17.7: Use #GDataCalendarQuery:single-events instead, as this is no longer supported on the server. + */ + g_object_class_install_property (gobject_class, PROP_RECURRENCE_EXPANSION_START, + g_param_spec_int64 ("recurrence-expansion-start", + "Recurrence expansion start", "Specifies start of period to expand recurrences for.", + -1, G_MAXINT64, -1, + G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS | G_PARAM_DEPRECATED)); + + /** + * GDataCalendarQuery:recurrence-expansion-end: + * + * Specifies the end of the time period to expand recurring events for, exclusive. + * + * Deprecated: 0.17.7: Use #GDataCalendarQuery:single-events instead, as this is no longer supported on the server. + */ + g_object_class_install_property (gobject_class, PROP_RECURRENCE_EXPANSION_END, + g_param_spec_int64 ("recurrence-expansion-end", + "Recurrence expansion end", "Specifies end of period to expand recurrences for.", + -1, G_MAXINT64, -1, + G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS | G_PARAM_DEPRECATED)); + + /** + * GDataCalendarQuery:single-events: + * + * Indicates whether recurring events should be expanded or represented as a single event. + */ + g_object_class_install_property (gobject_class, PROP_SINGLE_EVENTS, + g_param_spec_boolean ("single-events", + "Single events?", "Indicates whether recurring events should be expanded.", + FALSE, + G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)); + + /** + * GDataCalendarQuery:sort-order: + * + * Specifies direction of sorting. Supported values are ascending and + * descending. + * + * By default, results are returned in ascending order. + * + * Deprecated: 0.17.7: Manually sort the results after retrieving them, as this is no longer supported on the server. + */ + g_object_class_install_property (gobject_class, PROP_SORT_ORDER, + g_param_spec_string ("sort-order", + "Sort order", "Specifies direction of sorting.", + NULL, + G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS | G_PARAM_DEPRECATED)); + + /** + * GDataCalendarQuery:start-min: + * + * Together with #GDataCalendarQuery:start-max, creates a timespan such that only events within the timespan are returned. + * + * #GDataCalendarQuery:start-min is inclusive, while #GDataCalendarQuery:start-max is exclusive. Events that overlap the range are + * included. Both are specified in seconds since the UNIX epoch. + * + * If not specified, the default #GDataCalendarQuery:start-min is 1970-01-01. + */ + g_object_class_install_property (gobject_class, PROP_START_MIN, + g_param_spec_int64 ("start-min", + "Start min", "A timespan such that only events within the timespan are returned.", + -1, G_MAXINT64, -1, + G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)); + + /** + * GDataCalendarQuery:start-max: + * + * Together with #GDataCalendarQuery:start-min, creates a timespan such that only events within the timespan are returned + * + * #GDataCalendarQuery:start-min is inclusive, while #GDataCalendarQuery:start-max is exclusive. Events that overlap the range are + * included. Both are specified in seconds since the UNIX epoch. + * + * If not specified, the default #GDataCalendarQuery:start-max is 2031-01-01. + */ + g_object_class_install_property (gobject_class, PROP_START_MAX, + g_param_spec_int64 ("start-max", + "Start max", "A timespan such that only events within the timespan are returned.", + -1, G_MAXINT64, -1, + G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)); + + /** + * GDataCalendarQuery:timezone: + * + * The current timezone. If this is not specified, all times are returned in UTC. + * + * Since: 0.2.0 + */ + g_object_class_install_property (gobject_class, PROP_TIMEZONE, + g_param_spec_string ("timezone", + "Timezone", "The current timezone.", + NULL, + G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)); + + /** + * GDataCalendarQuery:max-attendees: + * + * Specifies the maximum number of attendees to list for an event. If the actual number of attendees for an event is greater than this value, + * only the current user and the event organiser are listed. + * + * Since: 0.9.1 + */ + g_object_class_install_property (gobject_class, PROP_MAX_ATTENDEES, + g_param_spec_uint ("max-attendees", + "Max attendee count", "Specifies the maximum number of attendees to list for an event.", + 0, G_MAXUINT, 0, + G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)); + + /** + * GDataCalendarQuery:show-deleted: + * + * Whether to include deleted/cancelled events in the query feed. Deleted events have their #GDataCalendarEvent:status property set to + * %GDATA_GD_EVENT_STATUS_CANCELED. They do not normally appear in query results. + * + * Since: 0.9.1 + */ + g_object_class_install_property (gobject_class, PROP_SHOW_DELETED, + g_param_spec_boolean ("show-deleted", + "Show deleted?", "Whether to include deleted/cancelled events in the query feed.", + FALSE, + G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)); +} + +static void +gdata_calendar_query_init (GDataCalendarQuery *self) +{ + self->priv = G_TYPE_INSTANCE_GET_PRIVATE (self, GDATA_TYPE_CALENDAR_QUERY, GDataCalendarQueryPrivate); + self->priv->recurrence_expansion_start = -1; + self->priv->recurrence_expansion_end = -1; + self->priv->start_min = -1; + self->priv->start_max = -1; + + _gdata_query_set_pagination_type (GDATA_QUERY (self), + GDATA_QUERY_PAGINATION_TOKENS); +} + +static void +gdata_calendar_query_finalize (GObject *object) +{ + GDataCalendarQueryPrivate *priv = GDATA_CALENDAR_QUERY (object)->priv; + + g_free (priv->order_by); + g_free (priv->sort_order); + g_free (priv->timezone); + + /* Chain up to the parent class */ + G_OBJECT_CLASS (gdata_calendar_query_parent_class)->finalize (object); +} + +static void +gdata_calendar_query_get_property (GObject *object, guint property_id, GValue *value, GParamSpec *pspec) +{ + GDataCalendarQueryPrivate *priv = GDATA_CALENDAR_QUERY (object)->priv; + + switch (property_id) { + case PROP_FUTURE_EVENTS: + g_value_set_boolean (value, priv->future_events); + break; + case PROP_ORDER_BY: + g_value_set_string (value, priv->order_by); + break; + case PROP_RECURRENCE_EXPANSION_START: + g_value_set_int64 (value, priv->recurrence_expansion_start); + break; + case PROP_RECURRENCE_EXPANSION_END: + g_value_set_int64 (value, priv->recurrence_expansion_end); + break; + case PROP_SINGLE_EVENTS: + g_value_set_boolean (value, priv->single_events); + break; + case PROP_SORT_ORDER: + g_value_set_string (value, priv->sort_order); + break; + case PROP_START_MIN: + g_value_set_int64 (value, priv->start_min); + break; + case PROP_START_MAX: + g_value_set_int64 (value, priv->start_max); + break; + case PROP_TIMEZONE: + g_value_set_string (value, priv->timezone); + break; + case PROP_MAX_ATTENDEES: + g_value_set_uint (value, priv->max_attendees); + break; + case PROP_SHOW_DELETED: + g_value_set_boolean (value, priv->show_deleted); + break; + default: + /* We don't have any other property... */ + G_OBJECT_WARN_INVALID_PROPERTY_ID (object, property_id, pspec); + break; + } +} + +static void +gdata_calendar_query_set_property (GObject *object, guint property_id, const GValue *value, GParamSpec *pspec) +{ + GDataCalendarQuery *self = GDATA_CALENDAR_QUERY (object); + + switch (property_id) { + case PROP_FUTURE_EVENTS: + gdata_calendar_query_set_future_events (self, g_value_get_boolean (value)); + break; + case PROP_ORDER_BY: + gdata_calendar_query_set_order_by (self, g_value_get_string (value)); + break; + case PROP_RECURRENCE_EXPANSION_START: +G_GNUC_BEGIN_IGNORE_DEPRECATIONS + gdata_calendar_query_set_recurrence_expansion_start (self, g_value_get_int64 (value)); +G_GNUC_END_IGNORE_DEPRECATIONS + break; + case PROP_RECURRENCE_EXPANSION_END: +G_GNUC_BEGIN_IGNORE_DEPRECATIONS + gdata_calendar_query_set_recurrence_expansion_end (self, g_value_get_int64 (value)); +G_GNUC_END_IGNORE_DEPRECATIONS + break; + case PROP_SINGLE_EVENTS: + gdata_calendar_query_set_single_events (self, g_value_get_boolean (value)); + break; + case PROP_SORT_ORDER: +G_GNUC_BEGIN_IGNORE_DEPRECATIONS + gdata_calendar_query_set_sort_order (self, g_value_get_string (value)); +G_GNUC_END_IGNORE_DEPRECATIONS + break; + case PROP_START_MIN: + gdata_calendar_query_set_start_min (self, g_value_get_int64 (value)); + break; + case PROP_START_MAX: + gdata_calendar_query_set_start_max (self, g_value_get_int64 (value)); + break; + case PROP_TIMEZONE: + gdata_calendar_query_set_timezone (self, g_value_get_string (value)); + break; + case PROP_MAX_ATTENDEES: + gdata_calendar_query_set_max_attendees (self, g_value_get_uint (value)); + break; + case PROP_SHOW_DELETED: + gdata_calendar_query_set_show_deleted (self, g_value_get_boolean (value)); + break; + default: + /* We don't have any other property... */ + G_OBJECT_WARN_INVALID_PROPERTY_ID (object, property_id, pspec); + break; + } +} + +/* Convert the v2 order-by values to the v3 orderBy values: + * - https://developers.google.com/google-apps/calendar/v3/reference/events/list#orderBy + * - There is no reference for v2 any more. + */ +static const gchar * +order_by_to_v3 (const gchar *order_by) +{ + if (g_strcmp0 (order_by, "lastmodified") == 0) + return "updated"; + else if (g_strcmp0 (order_by, "starttime") == 0) + return "startTime"; + else + return order_by; +} + +static void +get_query_uri (GDataQuery *self, const gchar *feed_uri, GString *query_uri, gboolean *params_started) +{ + GDataCalendarQueryPrivate *priv = GDATA_CALENDAR_QUERY (self)->priv; + + #define APPEND_SEP g_string_append_c (query_uri, (*params_started == FALSE) ? '?' : '&'); *params_started = TRUE; + + /* Chain up to the parent class */ + GDATA_QUERY_CLASS (gdata_calendar_query_parent_class)->get_query_uri (self, feed_uri, query_uri, params_started); + + if (gdata_query_get_max_results (GDATA_QUERY (self)) != 0) { + APPEND_SEP + g_string_append_printf (query_uri, "maxResults=%u", + gdata_query_get_max_results (GDATA_QUERY (self))); + } + + if (priv->order_by != NULL) { + APPEND_SEP + g_string_append (query_uri, "orderBy="); + g_string_append_uri_escaped (query_uri, + order_by_to_v3 (priv->order_by), NULL, FALSE); + } + + /* Convert the deprecated recurrence-expansion-* properties into single-events. */ + APPEND_SEP + if (priv->single_events == TRUE || + priv->recurrence_expansion_start >= 0 || + priv->recurrence_expansion_end >= 0) + g_string_append (query_uri, "singleEvents=true"); + else + g_string_append (query_uri, "singleEvents=false"); + + if (priv->start_min != -1) { + gchar *start_min; + gint64 start_min_time; + + if (priv->future_events) + start_min_time = g_get_real_time () / G_USEC_PER_SEC; + else + start_min_time = priv->start_min; + + APPEND_SEP + g_string_append (query_uri, "timeMin="); + start_min = gdata_parser_int64_to_iso8601 (start_min_time); + g_string_append (query_uri, start_min); + g_free (start_min); + } + + if (priv->start_max != -1 && !priv->future_events) { + gchar *start_max; + + APPEND_SEP + g_string_append (query_uri, "timeMax="); + start_max = gdata_parser_int64_to_iso8601 (priv->start_max); + g_string_append (query_uri, start_max); + g_free (start_max); + } + + if (priv->timezone != NULL) { + APPEND_SEP + g_string_append (query_uri, "timeZone="); + g_string_append_uri_escaped (query_uri, priv->timezone, NULL, FALSE); + } + + if (priv->max_attendees > 0) { + APPEND_SEP + g_string_append_printf (query_uri, "maxAttendees=%u", priv->max_attendees); + } + + APPEND_SEP + if (priv->show_deleted == TRUE) { + g_string_append (query_uri, "showDeleted=true"); + } else { + g_string_append (query_uri, "showDeleted=false"); + } +} + +/** + * gdata_calendar_query_new: + * @q: (allow-none): a query string, or %NULL + * + * Creates a new #GDataCalendarQuery with its #GDataQuery:q property set to @q. + * + * Return value: a new #GDataCalendarQuery + */ +GDataCalendarQuery * +gdata_calendar_query_new (const gchar *q) +{ + return g_object_new (GDATA_TYPE_CALENDAR_QUERY, "q", q, NULL); +} + +/** + * gdata_calendar_query_new_with_limits: + * @q: (allow-none): a query string, or %NULL + * @start_min: a starting time for the event period, or -1 + * @start_max: an ending time for the event period, or -1 + * + * Creates a new #GDataCalendarQuery with its #GDataQuery:q property set to @q, and the time limits @start_min and @start_max + * applied (both in seconds since the UNIX epoch). + * + * Return value: a new #GDataCalendarQuery + */ +GDataCalendarQuery * +gdata_calendar_query_new_with_limits (const gchar *q, gint64 start_min, gint64 start_max) +{ + return g_object_new (GDATA_TYPE_CALENDAR_QUERY, + "q", q, + "start-min", start_min, + "start-max", start_max, + NULL); +} + +/** + * gdata_calendar_query_get_future_events: + * @self: a #GDataCalendarQuery + * + * Gets the #GDataCalendarQuery:future-events property. + * + * Return value: the future events property + */ +gboolean +gdata_calendar_query_get_future_events (GDataCalendarQuery *self) +{ + g_return_val_if_fail (GDATA_IS_CALENDAR_QUERY (self), FALSE); + return self->priv->future_events; +} + +/** + * gdata_calendar_query_set_future_events: + * @self: a #GDataCalendarQuery + * @future_events: %TRUE to unconditionally show future events, %FALSE otherwise + * + * Sets the #GDataCalendarQuery:future-events property of the #GDataCalendarQuery to @future_events. + */ +void +gdata_calendar_query_set_future_events (GDataCalendarQuery *self, gboolean future_events) +{ + g_return_if_fail (GDATA_IS_CALENDAR_QUERY (self)); + self->priv->future_events = future_events; + g_object_notify (G_OBJECT (self), "future-events"); + + /* Our current ETag will no longer be relevant */ + gdata_query_set_etag (GDATA_QUERY (self), NULL); +} + +/** + * gdata_calendar_query_get_order_by: + * @self: a #GDataCalendarQuery + * + * Gets the #GDataCalendarQuery:order-by property. + * + * Return value: the order by property, or %NULL if it is unset + */ +const gchar * +gdata_calendar_query_get_order_by (GDataCalendarQuery *self) +{ + g_return_val_if_fail (GDATA_IS_CALENDAR_QUERY (self), NULL); + return self->priv->order_by; +} + +/** + * gdata_calendar_query_set_order_by: + * @self: a #GDataCalendarQuery + * @order_by: (allow-none): a new order by string, or %NULL + * + * Sets the #GDataCalendarQuery:order-by property of the #GDataCalendarQuery to the new order by string, @order_by. + * + * Set @order_by to %NULL to unset the property in the query URI. + */ +void +gdata_calendar_query_set_order_by (GDataCalendarQuery *self, const gchar *order_by) +{ + g_return_if_fail (GDATA_IS_CALENDAR_QUERY (self)); + + g_free (self->priv->order_by); + self->priv->order_by = g_strdup (order_by); + g_object_notify (G_OBJECT (self), "order-by"); + + /* Our current ETag will no longer be relevant */ + gdata_query_set_etag (GDATA_QUERY (self), NULL); +} + +/** + * gdata_calendar_query_get_recurrence_expansion_start: + * @self: a #GDataCalendarQuery + * + * Gets the #GDataCalendarQuery:recurrence-expansion-start property. If the property is unset, -1 will be returned. + * + * Return value: the UNIX timestamp for the recurrence-expansion-start property, or -1 + * Deprecated: 0.17.7: Use #GDataCalendarQuery:single-events instead, as this is no longer supported on the server. + */ +gint64 +gdata_calendar_query_get_recurrence_expansion_start (GDataCalendarQuery *self) +{ + g_return_val_if_fail (GDATA_IS_CALENDAR_QUERY (self), -1); + return self->priv->recurrence_expansion_start; +} + +/** + * gdata_calendar_query_set_recurrence_expansion_start: + * @self: a #GDataCalendarQuery + * @start: a new start time, or -1 + * + * Sets the #GDataCalendarQuery:recurrence-expansion-start property of the #GDataCalendarQuery + * to the new time/date, @start. + * + * Set @start to -1 to unset the property in the query URI. + * + * Deprecated: 0.17.7: Use #GDataCalendarQuery:single-events instead, as this is no longer supported on the server. + */ +void +gdata_calendar_query_set_recurrence_expansion_start (GDataCalendarQuery *self, gint64 start) +{ + g_return_if_fail (GDATA_IS_CALENDAR_QUERY (self)); + g_return_if_fail (start >= -1); + + self->priv->recurrence_expansion_start = start; + g_object_notify (G_OBJECT (self), "recurrence-expansion-start"); + + /* Our current ETag will no longer be relevant */ + gdata_query_set_etag (GDATA_QUERY (self), NULL); +} + +/** + * gdata_calendar_query_get_recurrence_expansion_end: + * @self: a #GDataCalendarQuery + * + * Gets the #GDataCalendarQuery:recurrence-expansion-end property. If the property is unset, -1 will be returned. + * + * Return value: the UNIX timestamp for the recurrence-expansion-end property, or -1 + * + * Deprecated: 0.17.7: Use #GDataCalendarQuery:single-events instead, as this is no longer supported on the server. + */ +gint64 +gdata_calendar_query_get_recurrence_expansion_end (GDataCalendarQuery *self) +{ + g_return_val_if_fail (GDATA_IS_CALENDAR_QUERY (self), -1 ); + return self->priv->recurrence_expansion_end; +} + +/** + * gdata_calendar_query_set_recurrence_expansion_end: + * @self: a #GDataCalendarQuery + * @end: a new end time, or -1 + * + * Sets the #GDataCalendarQuery:recurrence-expansion-end property of the #GDataCalendarQuery + * to the new time/date, @end. + * + * Set @end to -1 to unset the property in the query URI. + * + * Deprecated: 0.17.7: Use #GDataCalendarQuery:single-events instead, as this is no longer supported on the server. + */ +void +gdata_calendar_query_set_recurrence_expansion_end (GDataCalendarQuery *self, gint64 end) +{ + g_return_if_fail (GDATA_IS_CALENDAR_QUERY (self)); + g_return_if_fail (end >= -1); + + self->priv->recurrence_expansion_end = end; + g_object_notify (G_OBJECT (self), "recurrence-expansion-end"); + + /* Our current ETag will no longer be relevant */ + gdata_query_set_etag (GDATA_QUERY (self), NULL); +} + +/** + * gdata_calendar_query_get_single_events: + * @self: a #GDataCalendarQuery + * + * Gets the #GDataCalendarQuery:single-events property. + * + * Return value: the single events property + */ +gboolean +gdata_calendar_query_get_single_events (GDataCalendarQuery *self) +{ + g_return_val_if_fail (GDATA_IS_CALENDAR_QUERY (self), FALSE); + return self->priv->single_events; +} + +/** + * gdata_calendar_query_set_single_events: + * @self: a #GDataCalendarQuery + * @single_events: %TRUE to show recurring events as single events, %FALSE otherwise + * + * Sets the #GDataCalendarQuery:single-events property of the #GDataCalendarQuery to @single_events. + */ +void +gdata_calendar_query_set_single_events (GDataCalendarQuery *self, gboolean single_events) +{ + g_return_if_fail (GDATA_IS_CALENDAR_QUERY (self)); + self->priv->single_events = single_events; + g_object_notify (G_OBJECT (self), "single-events"); + + /* Our current ETag will no longer be relevant */ + gdata_query_set_etag (GDATA_QUERY (self), NULL); +} + +/** + * gdata_calendar_query_get_sort_order: + * @self: a #GDataCalendarQuery + * + * Gets the #GDataCalendarQuery:sort-order property. + * + * Return value: the sort order property, or %NULL if it is unset + * Deprecated: 0.17.7: Manually sort the results after retrieving them, as this is no longer supported on the server. + */ +const gchar * +gdata_calendar_query_get_sort_order (GDataCalendarQuery *self) +{ + g_return_val_if_fail (GDATA_IS_CALENDAR_QUERY (self), NULL); + return self->priv->sort_order; +} + +/** + * gdata_calendar_query_set_sort_order: + * @self: a #GDataCalendarQuery + * @sort_order: (allow-none): a new sort order string, or %NULL + * + * Sets the #GDataCalendarQuery:sort-order property of the #GDataCalendarQuery to the new sort order string, @sort_order. + * + * Set @sort_order to %NULL to unset the property in the query URI. + * + * Deprecated: 0.17.7: Manually sort the results after retrieving them, as this is no longer supported on the server. + */ +void +gdata_calendar_query_set_sort_order (GDataCalendarQuery *self, const gchar *sort_order) +{ + g_return_if_fail (GDATA_IS_CALENDAR_QUERY (self)); + + g_free (self->priv->sort_order); + self->priv->sort_order = g_strdup (sort_order); + g_object_notify (G_OBJECT (self), "sort-order"); + + /* Our current ETag will no longer be relevant */ + gdata_query_set_etag (GDATA_QUERY (self), NULL); +} + +/** + * gdata_calendar_query_get_start_min: + * @self: a #GDataCalendarQuery + * + * Gets the #GDataCalendarQuery:start-min property. If the property is unset, -1 will be returned. + * + * Return value: the UNIX timestamp (in seconds) for the start-min property, or -1 + */ +gint64 +gdata_calendar_query_get_start_min (GDataCalendarQuery *self) +{ + g_return_val_if_fail (GDATA_IS_CALENDAR_QUERY (self), -1); + return self->priv->start_min; +} + +/** + * gdata_calendar_query_set_start_min: + * @self: a #GDataCalendarQuery + * @start_min: a new minimum start time (in seconds since the UNIX epoch), or -1 + * + * Sets the #GDataCalendarQuery:start-min property of the #GDataCalendarQuery + * to the new time/date, @start_min. + * + * Set @start_min to -1 to unset the property in the query URI. + */ +void +gdata_calendar_query_set_start_min (GDataCalendarQuery *self, gint64 start_min) +{ + g_return_if_fail (GDATA_IS_CALENDAR_QUERY (self)); + g_return_if_fail (start_min >= -1); + + self->priv->start_min = start_min; + g_object_notify (G_OBJECT (self), "start-min"); + + /* Our current ETag will no longer be relevant */ + gdata_query_set_etag (GDATA_QUERY (self), NULL); +} + +/** + * gdata_calendar_query_get_start_max: + * @self: a #GDataCalendarQuery + * + * Gets the #GDataCalendarQuery:start-max property. If the property is unset, -1 will be returned. + * + * Return value: the UNIX timestamp (in seconds) for the start-max property, or -1 + */ +gint64 +gdata_calendar_query_get_start_max (GDataCalendarQuery *self) +{ + g_return_val_if_fail (GDATA_IS_CALENDAR_QUERY (self), -1); + return self->priv->start_max; +} + +/** + * gdata_calendar_query_set_start_max: + * @self: a #GDataCalendarQuery + * @start_max: a new maximum start time (in seconds since the UNIX epoch), or -1 + * + * Sets the #GDataCalendarQuery:start-max property of the #GDataCalendarQuery + * to the new time/date, @start_max. + * + * Set @start_max to -1 to unset the property in the query URI. + */ +void +gdata_calendar_query_set_start_max (GDataCalendarQuery *self, gint64 start_max) +{ + g_return_if_fail (GDATA_IS_CALENDAR_QUERY (self)); + g_return_if_fail (start_max >= -1); + + self->priv->start_max = start_max; + g_object_notify (G_OBJECT (self), "start-max"); + + /* Our current ETag will no longer be relevant */ + gdata_query_set_etag (GDATA_QUERY (self), NULL); +} + +/** + * gdata_calendar_query_get_timezone: + * @self: a #GDataCalendarQuery + * + * Gets the #GDataCalendarQuery:timezone property. + * + * Return value: the timezone property, or %NULL if it is unset + * + * Since: 0.2.0 + */ +const gchar * +gdata_calendar_query_get_timezone (GDataCalendarQuery *self) +{ + g_return_val_if_fail (GDATA_IS_CALENDAR_QUERY (self), NULL); + return self->priv->timezone; +} + +/** + * gdata_calendar_query_set_timezone: + * @self: a #GDataCalendarQuery + * @_timezone: (allow-none): a new timezone string, or %NULL + * + * Sets the #GDataCalendarQuery:timezone property of the #GDataCalendarQuery to the new timezone string, @timezone. + * + * Set @timezone to %NULL to unset the property in the query URI. + * + * Since: 0.2.0 + */ +void +gdata_calendar_query_set_timezone (GDataCalendarQuery *self, const gchar *_timezone) +{ + g_return_if_fail (GDATA_IS_CALENDAR_QUERY (self)); + + g_free (self->priv->timezone); + + /* Replace all spaces with underscores */ + if (_timezone != NULL) { + gchar *zone, *i; + + zone = g_strdup (_timezone); + for (i = zone; *i != '\0'; i++) { + if (*i == ' ') + *i = '_'; + } + self->priv->timezone = zone; + } else { + self->priv->timezone = NULL; + } + + g_object_notify (G_OBJECT (self), "timezone"); + + /* Our current ETag will no longer be relevant */ + gdata_query_set_etag (GDATA_QUERY (self), NULL); +} + +/** + * gdata_calendar_query_get_max_attendees: + * @self: a #GDataCalendarQuery + * + * Gets the #GDataCalendarQuery:max-attendees property. If the property is unset, 0 will be returned. + * + * Return value: the maximum number of attendees, or 0 + * + * Since: 0.9.1 + */ +guint +gdata_calendar_query_get_max_attendees (GDataCalendarQuery *self) +{ + g_return_val_if_fail (GDATA_IS_CALENDAR_QUERY (self), 0); + return self->priv->max_attendees; +} + +/** + * gdata_calendar_query_set_max_attendees: + * @self: a #GDataCalendarQuery + * @max_attendees: a new maximum attendee count, or 0 + * + * Sets the #GDataCalendarQuery:max-attendees property of the #GDataCalendarQuery to the new value, @max_attendees. + * + * Set @max_attendees to 0 to unset the property in the query URI. + * + * Since: 0.9.1 + */ +void +gdata_calendar_query_set_max_attendees (GDataCalendarQuery *self, guint max_attendees) +{ + g_return_if_fail (GDATA_IS_CALENDAR_QUERY (self)); + + self->priv->max_attendees = max_attendees; + g_object_notify (G_OBJECT (self), "max-attendees"); + + /* Our current ETag will no longer be relevant */ + gdata_query_set_etag (GDATA_QUERY (self), NULL); +} + +/** + * gdata_calendar_query_show_deleted: + * @self: a #GDataCalendarQuery + * + * Gets the #GDataCalendarQuery:show-deleted property. + * + * Return value: %TRUE if deleted/cancelled events should be shown, %FALSE otherwise + * + * Since: 0.9.1 + */ +gboolean +gdata_calendar_query_show_deleted (GDataCalendarQuery *self) +{ + g_return_val_if_fail (GDATA_IS_CALENDAR_QUERY (self), FALSE); + return self->priv->show_deleted; +} + +/** + * gdata_calendar_query_set_show_deleted: + * @self: a #GDataCalendarQuery + * @show_deleted: %TRUE to show deleted events, %FALSE otherwise + * + * Sets the #GDataCalendarQuery:show-deleted property of the #GDataCalendarQuery. + * + * Since: 0.9.1 + */ +void +gdata_calendar_query_set_show_deleted (GDataCalendarQuery *self, gboolean show_deleted) +{ + g_return_if_fail (GDATA_IS_CALENDAR_QUERY (self)); + + self->priv->show_deleted = show_deleted; + g_object_notify (G_OBJECT (self), "show-deleted"); + + /* Our current ETag will no longer be relevant */ + gdata_query_set_etag (GDATA_QUERY (self), NULL); +} diff --git a/gdata/services/calendar/gdata-calendar-query.h b/gdata/services/calendar/gdata-calendar-query.h new file mode 100644 index 0000000..0f3b32e --- /dev/null +++ b/gdata/services/calendar/gdata-calendar-query.h @@ -0,0 +1,99 @@ +/* -*- Mode: C; indent-tabs-mode: t; c-basic-offset: 8; tab-width: 8 -*- */ +/* + * GData Client + * Copyright (C) Philip Withnall 2009 + * + * GData Client is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * GData Client is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with GData Client. If not, see . + */ + +#ifndef GDATA_CALENDAR_QUERY_H +#define GDATA_CALENDAR_QUERY_H + +#include +#include + +#include +#include + +G_BEGIN_DECLS + +#define GDATA_TYPE_CALENDAR_QUERY (gdata_calendar_query_get_type ()) +#define GDATA_CALENDAR_QUERY(o) (G_TYPE_CHECK_INSTANCE_CAST ((o), GDATA_TYPE_CALENDAR_QUERY, GDataCalendarQuery)) +#define GDATA_CALENDAR_QUERY_CLASS(k) (G_TYPE_CHECK_CLASS_CAST((k), GDATA_TYPE_CALENDAR_QUERY, GDataCalendarQueryClass)) +#define GDATA_IS_CALENDAR_QUERY(o) (G_TYPE_CHECK_INSTANCE_TYPE ((o), GDATA_TYPE_CALENDAR_QUERY)) +#define GDATA_IS_CALENDAR_QUERY_CLASS(k) (G_TYPE_CHECK_CLASS_TYPE ((k), GDATA_TYPE_CALENDAR_QUERY)) +#define GDATA_CALENDAR_QUERY_GET_CLASS(o) (G_TYPE_INSTANCE_GET_CLASS ((o), GDATA_TYPE_CALENDAR_QUERY, GDataCalendarQueryClass)) + +typedef struct _GDataCalendarQueryPrivate GDataCalendarQueryPrivate; + +/** + * GDataCalendarQuery: + * + * All the fields in the #GDataCalendarQuery structure are private and should never be accessed directly. + */ +typedef struct { + GDataQuery parent; + GDataCalendarQueryPrivate *priv; +} GDataCalendarQuery; + +/** + * GDataCalendarQueryClass: + * + * All the fields in the #GDataCalendarQueryClass structure are private and should never be accessed directly. + */ +typedef struct { + /*< private >*/ + GDataQueryClass parent; + + /*< private >*/ + /* Padding for future expansion */ + void (*_g_reserved0) (void); + void (*_g_reserved1) (void); +} GDataCalendarQueryClass; + +GType gdata_calendar_query_get_type (void) G_GNUC_CONST; + +GDataCalendarQuery *gdata_calendar_query_new (const gchar *q) G_GNUC_WARN_UNUSED_RESULT G_GNUC_MALLOC; +GDataCalendarQuery *gdata_calendar_query_new_with_limits (const gchar *q, gint64 start_min, gint64 start_max) G_GNUC_WARN_UNUSED_RESULT G_GNUC_MALLOC; + +gboolean gdata_calendar_query_get_future_events (GDataCalendarQuery *self) G_GNUC_PURE; +void gdata_calendar_query_set_future_events (GDataCalendarQuery *self, gboolean future_events); +const gchar *gdata_calendar_query_get_order_by (GDataCalendarQuery *self) G_GNUC_PURE; +void gdata_calendar_query_set_order_by (GDataCalendarQuery *self, const gchar *order_by); +gboolean gdata_calendar_query_get_single_events (GDataCalendarQuery *self) G_GNUC_PURE; +void gdata_calendar_query_set_single_events (GDataCalendarQuery *self, gboolean single_events); +gint64 gdata_calendar_query_get_start_min (GDataCalendarQuery *self); +void gdata_calendar_query_set_start_min (GDataCalendarQuery *self, gint64 start_min); +gint64 gdata_calendar_query_get_start_max (GDataCalendarQuery *self); +void gdata_calendar_query_set_start_max (GDataCalendarQuery *self, gint64 start_max); +const gchar *gdata_calendar_query_get_timezone (GDataCalendarQuery *self) G_GNUC_PURE; +void gdata_calendar_query_set_timezone (GDataCalendarQuery *self, const gchar *_timezone); +guint gdata_calendar_query_get_max_attendees (GDataCalendarQuery *self) G_GNUC_PURE; +void gdata_calendar_query_set_max_attendees (GDataCalendarQuery *self, guint max_attendees); +gboolean gdata_calendar_query_show_deleted (GDataCalendarQuery *self) G_GNUC_PURE; +void gdata_calendar_query_set_show_deleted (GDataCalendarQuery *self, gboolean show_deleted); + +#ifndef LIBGDATA_DISABLE_DEPRECATED +gint64 gdata_calendar_query_get_recurrence_expansion_start (GDataCalendarQuery *self) G_GNUC_DEPRECATED_FOR (gdata_calendar_query_get_single_events); +void gdata_calendar_query_set_recurrence_expansion_start (GDataCalendarQuery *self, gint64 start) G_GNUC_DEPRECATED_FOR (gdata_calendar_query_set_single_events); +gint64 gdata_calendar_query_get_recurrence_expansion_end (GDataCalendarQuery *self) G_GNUC_DEPRECATED_FOR (gdata_calendar_query_get_single_events); +void gdata_calendar_query_set_recurrence_expansion_end (GDataCalendarQuery *self, gint64 end) G_GNUC_DEPRECATED_FOR (gdata_calendar_query_set_single_events); + +const gchar *gdata_calendar_query_get_sort_order (GDataCalendarQuery *self) G_GNUC_PURE G_GNUC_DEPRECATED; +void gdata_calendar_query_set_sort_order (GDataCalendarQuery *self, const gchar *sort_order) G_GNUC_DEPRECATED_FOR (g_list_sort); +#endif /* !LIBGDATA_DISABLE_DEPRECATED */ + +G_END_DECLS + +#endif /* !GDATA_CALENDAR_QUERY_H */ diff --git a/gdata/services/calendar/gdata-calendar-service.c b/gdata/services/calendar/gdata-calendar-service.c new file mode 100644 index 0000000..6763262 --- /dev/null +++ b/gdata/services/calendar/gdata-calendar-service.c @@ -0,0 +1,918 @@ +/* -*- Mode: C; indent-tabs-mode: t; c-basic-offset: 8; tab-width: 8 -*- */ +/* + * GData Client + * Copyright (C) Philip Withnall 2009, 2014, 2015 + * + * GData Client is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * GData Client is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with GData Client. If not, see . + */ + +/** + * SECTION:gdata-calendar-service + * @short_description: GData Calendar service object + * @stability: Stable + * @include: gdata/services/calendar/gdata-calendar-service.h + * + * #GDataCalendarService is a subclass of #GDataService for communicating with the GData API of Google Calendar. It supports querying + * for, inserting, editing and deleting events from calendars, as well as operations on the calendars themselves. + * + * For more details of Google Calendar's GData API, see the + * + * online documentation. + * + * Each calendar accessible through the service has an access control list (ACL) which defines the level of access to the calendar to each user, and + * which users the calendar is shared with. For more information about ACLs for calendars, see the + * online documentation on + * sharing calendars. + * + * + * Retrieving the Access Control List for a Calendar + * + * GDataCalendarService *service; + * GDataCalendarCalendar *calendar; + * GDataFeed *acl_feed; + * GDataAccessRule *rule, *new_rule; + * GDataLink *acl_link; + * GList *i; + * GError *error = NULL; + * + * /* Create a service and retrieve a calendar to work on */ + * service = create_calendar_service (); + * calendar = get_calendar (service); + * + * /* Query the service for the ACL for the given calendar */ + * acl_feed = gdata_access_handler_get_rules (GDATA_ACCESS_HANDLER (calendar), GDATA_SERVICE (service), NULL, NULL, NULL, &error); + * + * if (error != NULL) { + * g_error ("Error getting ACL feed for calendar: %s", error->message); + * g_error_free (error); + * g_object_unref (calendar); + * g_object_unref (service); + * return; + * } + * + * /* Iterate through the ACL */ + * for (i = gdata_feed_get_entries (acl_feed); i != NULL; i = i->next) { + * const gchar *scope_value; + * + * rule = GDATA_ACCESS_RULE (i->data); + * + * /* Do something with the access rule here. As an example, we update the rule applying to test@gmail.com and delete all + * * the other rules. We then insert another rule for example@gmail.com below. */ + * gdata_access_rule_get_scope (rule, NULL, &scope_value); + * if (scope_value != NULL && strcmp (scope_value, "test@gmail.com") == 0) { + * GDataAccessRule *updated_rule; + * + * /* Update the rule to make test@gmail.com an editor (full read/write access to the calendar, but they can't change + * * the ACL). */ + * gdata_access_rule_set_role (rule, GDATA_CALENDAR_ACCESS_ROLE_EDITOR); + * updated_rule = GDATA_ACCESS_RULE (gdata_service_update_entry (GDATA_SERVICE (service), GDATA_ENTRY (rule), NULL, &error)); + * + * if (error != NULL) { + * g_error ("Error updating access rule for %s: %s", scope_value, error->message); + * g_error_free (error); + * g_object_unref (acl_feed); + * g_object_unref (calendar); + * g_object_unref (service); + * return; + * } + * + * g_object_unref (updated_rule); + * } else { + * /* Delete any rule which doesn't apply to test@gmail.com */ + * gdata_service_delete_entry (GDATA_SERVICE (service), GDATA_ENTRY (rule), NULL, &error); + * + * if (error != NULL) { + * g_error ("Error deleting access rule for %s: %s", scope_value, error->message); + * g_error_free (error); + * g_object_unref (acl_feed); + * g_object_unref (calendar); + * g_object_unref (service); + * return; + * } + * } + * } + * + * g_object_unref (acl_feed); + * + * /* Create and insert a new access rule for example@gmail.com which allows them to view free/busy information for events in the + * * calendar, but doesn't allow them to view the full event details. */ + * rule = gdata_access_rule_new (NULL); + * gdata_access_rule_set_role (rule, GDATA_CALENDAR_ACCESS_ROLE_FREE_BUSY); + * gdata_access_rule_set_scope (rule, GDATA_ACCESS_SCOPE_USER, "example@gmail.com"); + * + * acl_link = gdata_entry_look_up_link (GDATA_ENTRY (calendar), GDATA_LINK_ACCESS_CONTROL_LIST); + * new_rule = GDATA_ACCESS_RULE (gdata_service_insert_entry (GDATA_SERVICE (service), gdata_link_get_uri (acl_link), GDATA_ENTRY (rule), + * NULL, &error)); + * + * g_object_unref (rule); + * g_object_unref (calendar); + * g_object_unref (service); + * + * if (error != NULL) { + * g_error ("Error inserting access rule: %s", error->message); + * g_error_free (error); + * return; + * } + * + * g_object_unref (acl_link); + * + * + * + * Before version 0.17.2, the Calendar service could be manipulated using + * batch operations. That is no longer supported, and any batch operations + * created on the calendar will fail. + */ + +#include +#include +#include +#include +#include + +#include "gdata-calendar-service.h" +#include "gdata-batchable.h" +#include "gdata-service.h" +#include "gdata-private.h" +#include "gdata-query.h" +#include "gdata-calendar-feed.h" + +/* Standards reference here: + * https://developers.google.com/google-apps/calendar/v3/reference/ */ + +static void +parse_error_response (GDataService *self, + GDataOperationType operation_type, + guint status, + const gchar *reason_phrase, + const gchar *response_body, + gint length, + GError **error); +static GList *get_authorization_domains (void); + +_GDATA_DEFINE_AUTHORIZATION_DOMAIN (calendar, "cl", "https://www.google.com/calendar/feeds/") +G_DEFINE_TYPE_WITH_CODE (GDataCalendarService, gdata_calendar_service, GDATA_TYPE_SERVICE, G_IMPLEMENT_INTERFACE (GDATA_TYPE_BATCHABLE, NULL)) + +static void +gdata_calendar_service_class_init (GDataCalendarServiceClass *klass) +{ + GDataServiceClass *service_class = GDATA_SERVICE_CLASS (klass); + service_class->feed_type = GDATA_TYPE_CALENDAR_FEED; + service_class->parse_error_response = parse_error_response; + service_class->get_authorization_domains = get_authorization_domains; +} + +static void +gdata_calendar_service_init (GDataCalendarService *self) +{ + /* Nothing to see here */ +} + +/* The error format used by the Google Calendar API doesn’t seem to be + * documented anywhere, which is a little frustrating. Here’s an example of it: + * { + * "error": { + * "errors": [ + * { + * "domain": "global", + * "reason": "parseError", + * "message": "Parse Error", + * } + * ], + * "code": 400, + * "message": "Parse Error" + * } + * } + * or: + * { + * "error": { + * "errors": [ + * { + * "domain": "global", + * "reason": "required", + * "message": "Missing end time." + * } + * ], + * "code": 400, + * "message": "Missing end time." + * } + * } + */ +static void +parse_error_response (GDataService *self, + GDataOperationType operation_type, + guint status, + const gchar *reason_phrase, + const gchar *response_body, + gint length, + GError **error) +{ + JsonParser *parser = NULL; /* owned */ + JsonReader *reader = NULL; /* owned */ + gint i; + GError *child_error = NULL; + + if (response_body == NULL) { + goto parent; + } + + if (length == -1) { + length = strlen (response_body); + } + + parser = json_parser_new (); + if (!json_parser_load_from_data (parser, response_body, length, + &child_error)) { + goto parent; + } + + reader = json_reader_new (json_parser_get_root (parser)); + + /* Check that the outermost node is an object. */ + if (!json_reader_is_object (reader)) { + goto parent; + } + + /* Grab the ‘error’ member, then its ‘errors’ member. */ + if (!json_reader_read_member (reader, "error") || + !json_reader_is_object (reader) || + !json_reader_read_member (reader, "errors") || + !json_reader_is_array (reader)) { + goto parent; + } + + /* Parse each of the errors. Return the first one, and print out any + * others. */ + for (i = 0; i < json_reader_count_elements (reader); i++) { + const gchar *domain, *reason, *message, *extended_help; + const gchar *location_type, *location; + + /* Parse the error. */ + if (!json_reader_read_element (reader, i) || + !json_reader_is_object (reader)) { + goto parent; + } + + json_reader_read_member (reader, "domain"); + domain = json_reader_get_string_value (reader); + json_reader_end_member (reader); + + json_reader_read_member (reader, "reason"); + reason = json_reader_get_string_value (reader); + json_reader_end_member (reader); + + json_reader_read_member (reader, "message"); + message = json_reader_get_string_value (reader); + json_reader_end_member (reader); + + json_reader_read_member (reader, "extendedHelp"); + extended_help = json_reader_get_string_value (reader); + json_reader_end_member (reader); + + json_reader_read_member (reader, "locationType"); + location_type = json_reader_get_string_value (reader); + json_reader_end_member (reader); + + json_reader_read_member (reader, "location"); + location = json_reader_get_string_value (reader); + json_reader_end_member (reader); + + /* End the error element. */ + json_reader_end_element (reader); + + /* Create an error message, but only for the first error */ + if (error == NULL || *error == NULL) { + if (g_strcmp0 (domain, "usageLimits") == 0 && + g_strcmp0 (reason, + "dailyLimitExceededUnreg") == 0) { + /* Daily Limit for Unauthenticated Use + * Exceeded. */ + g_set_error (error, GDATA_SERVICE_ERROR, + GDATA_SERVICE_ERROR_API_QUOTA_EXCEEDED, + _("You have made too many API " + "calls recently. Please wait a " + "few minutes and try again.")); + } else if (g_strcmp0 (domain, "global") == 0 && + g_strcmp0 (reason, "notFound") == 0) { + /* Calendar not found. */ + g_set_error (error, GDATA_SERVICE_ERROR, + GDATA_SERVICE_ERROR_NOT_FOUND, + /* Translators: the parameter is an + * error message returned by the + * server. */ + _("The requested resource was not found: %s"), + message); + } else if ((g_strcmp0 (domain, "global") == 0 && + g_strcmp0 (reason, "required") == 0) || + (g_strcmp0 (domain, "global") == 0 && + g_strcmp0 (reason, "conditionNotMet") == 0)) { + /* Client-side protocol error. */ + g_set_error (error, GDATA_SERVICE_ERROR, + GDATA_SERVICE_ERROR_PROTOCOL_ERROR, + /* Translators: the parameter is an + * error message returned by the + * server. */ + _("Invalid request URI or header, " + "or unsupported nonstandard " + "parameter: %s"), message); + } else if (g_strcmp0 (domain, "global") == 0 && + (g_strcmp0 (reason, "authError") == 0 || + g_strcmp0 (reason, "required") == 0)) { + /* Authentication problem */ + g_set_error (error, GDATA_SERVICE_ERROR, + GDATA_SERVICE_ERROR_AUTHENTICATION_REQUIRED, + _("You must be authenticated to " + "do this.")); + } else if (g_strcmp0 (domain, "global") == 0 && + g_strcmp0 (reason, "forbidden") == 0) { + g_set_error (error, GDATA_SERVICE_ERROR, + GDATA_SERVICE_ERROR_FORBIDDEN, + _("Access was denied by the user " + "or server.")); + } else { + /* Unknown or validation (protocol) error. Fall + * back to working off the HTTP status code. */ + g_warning ("Unknown error code ‘%s’ in domain " + "‘%s’ received with location type " + "‘%s’, location ‘%s’, extended help " + "‘%s’ and message ‘%s’.", + reason, domain, location_type, + location, extended_help, message); + + goto parent; + } + } else { + /* For all errors after the first, log the error in the + * terminal. */ + g_debug ("Error message received in response: domain " + "‘%s’, reason ‘%s’, extended help ‘%s’, " + "message ‘%s’, location type ‘%s’, location " + "‘%s’.", + domain, reason, extended_help, message, + location_type, location); + } + } + + /* End the ‘errors’ and ‘error’ members. */ + json_reader_end_element (reader); + json_reader_end_element (reader); + + g_clear_object (&reader); + g_clear_object (&parser); + + /* Ensure we’ve actually set an error message. */ + g_assert (error == NULL || *error != NULL); + + return; + +parent: + g_clear_object (&reader); + g_clear_object (&parser); + + /* Chain up to the parent class */ + GDATA_SERVICE_CLASS (gdata_calendar_service_parent_class)->parse_error_response (self, operation_type, status, reason_phrase, + response_body, length, error); +} + +static GList * +get_authorization_domains (void) +{ + return g_list_prepend (NULL, get_calendar_authorization_domain ()); +} + +/** + * gdata_calendar_service_new: + * @authorizer: (allow-none): a #GDataAuthorizer to authorize the service's requests, or %NULL + * + * Creates a new #GDataCalendarService using the given #GDataAuthorizer. If @authorizer is %NULL, all requests are made as an unauthenticated user. + * + * Return value: a new #GDataCalendarService, or %NULL; unref with g_object_unref() + * + * Since: 0.9.0 + */ +GDataCalendarService * +gdata_calendar_service_new (GDataAuthorizer *authorizer) +{ + g_return_val_if_fail (authorizer == NULL || GDATA_IS_AUTHORIZER (authorizer), NULL); + + return g_object_new (GDATA_TYPE_CALENDAR_SERVICE, + "authorizer", authorizer, + NULL); +} + +/** + * gdata_calendar_service_get_primary_authorization_domain: + * + * The primary #GDataAuthorizationDomain for interacting with Google Calendar. This will not normally need to be used, as it's used internally + * by the #GDataCalendarService methods. However, if using the plain #GDataService methods to implement custom queries or requests which libgdata + * does not support natively, then this domain may be needed to authorize the requests. + * + * The domain never changes, and is interned so that pointer comparison can be used to differentiate it from other authorization domains. + * + * Return value: (transfer none): the service's authorization domain + * + * Since: 0.9.0 + */ +GDataAuthorizationDomain * +gdata_calendar_service_get_primary_authorization_domain (void) +{ + return get_calendar_authorization_domain (); +} + +/** + * gdata_calendar_service_query_all_calendars: + * @self: a #GDataCalendarService + * @query: (allow-none): a #GDataQuery with the query parameters, or %NULL + * @cancellable: (allow-none): optional #GCancellable object, or %NULL + * @progress_callback: (allow-none) (scope call) (closure progress_user_data): a #GDataQueryProgressCallback to call when an entry is loaded, or %NULL + * @progress_user_data: (closure): data to pass to the @progress_callback function + * @error: a #GError, or %NULL + * + * Queries the service to return a list of all calendars from the authenticated account which match the given + * @query. It will return all calendars the user has read access to, including primary, secondary and imported + * calendars. + * + * For more details, see gdata_service_query(). + * + * Return value: (transfer full): a #GDataFeed of query results; unref with g_object_unref() + */ +GDataFeed * +gdata_calendar_service_query_all_calendars (GDataCalendarService *self, GDataQuery *query, GCancellable *cancellable, + GDataQueryProgressCallback progress_callback, gpointer progress_user_data, GError **error) +{ + GDataFeed *feed; + gchar *request_uri; + + g_return_val_if_fail (GDATA_IS_CALENDAR_SERVICE (self), NULL); + g_return_val_if_fail (query == NULL || GDATA_IS_QUERY (query), NULL); + g_return_val_if_fail (cancellable == NULL || G_IS_CANCELLABLE (cancellable), NULL); + g_return_val_if_fail (error == NULL || *error == NULL, NULL); + + /* Ensure we're authenticated first */ + if (gdata_authorizer_is_authorized_for_domain (gdata_service_get_authorizer (GDATA_SERVICE (self)), + get_calendar_authorization_domain ()) == FALSE) { + g_set_error_literal (error, GDATA_SERVICE_ERROR, GDATA_SERVICE_ERROR_AUTHENTICATION_REQUIRED, + _("You must be authenticated to query all calendars.")); + return NULL; + } + + request_uri = g_strconcat (_gdata_service_get_scheme (), "://www.googleapis.com/calendar/v3/users/me/calendarList", NULL); + feed = gdata_service_query (GDATA_SERVICE (self), get_calendar_authorization_domain (), request_uri, query, GDATA_TYPE_CALENDAR_CALENDAR, + cancellable, progress_callback, progress_user_data, error); + g_free (request_uri); + + return feed; +} + +/** + * gdata_calendar_service_query_all_calendars_async: + * @self: a #GDataCalendarService + * @query: (allow-none): a #GDataQuery with the query parameters, or %NULL + * @cancellable: (allow-none): optional #GCancellable object, or %NULL + * @progress_callback: (allow-none) (closure progress_user_data): a #GDataQueryProgressCallback to call when an entry is loaded, or %NULL + * @progress_user_data: (closure): data to pass to the @progress_callback function + * @destroy_progress_user_data: (allow-none): the function to call when @progress_callback will not be called any more, or %NULL. This function will be + * called with @progress_user_data as a parameter and can be used to free any memory allocated for it. + * @callback: a #GAsyncReadyCallback to call when authentication is finished + * @user_data: (closure): data to pass to the @callback function + * + * Queries the service to return a list of all calendars from the authenticated account which match the given + * @query. @self and @query are all reffed when this function is called, so can safely be unreffed after + * this function returns. + * + * For more details, see gdata_calendar_service_query_all_calendars(), which is the synchronous version of + * this function, and gdata_service_query_async(), which is the base asynchronous query function. + * + * Since: 0.9.1 + */ +void +gdata_calendar_service_query_all_calendars_async (GDataCalendarService *self, GDataQuery *query, GCancellable *cancellable, + GDataQueryProgressCallback progress_callback, gpointer progress_user_data, + GDestroyNotify destroy_progress_user_data, + GAsyncReadyCallback callback, gpointer user_data) +{ + gchar *request_uri; + + g_return_if_fail (GDATA_IS_CALENDAR_SERVICE (self)); + g_return_if_fail (query == NULL || GDATA_IS_QUERY (query)); + g_return_if_fail (cancellable == NULL || G_IS_CANCELLABLE (cancellable)); + g_return_if_fail (callback != NULL); + + /* Ensure we're authenticated first */ + if (gdata_authorizer_is_authorized_for_domain (gdata_service_get_authorizer (GDATA_SERVICE (self)), + get_calendar_authorization_domain ()) == FALSE) { + g_autoptr(GTask) task = NULL; + + task = g_task_new (self, cancellable, callback, user_data); + g_task_set_source_tag (task, gdata_service_query_async); + g_task_return_new_error (task, GDATA_SERVICE_ERROR, GDATA_SERVICE_ERROR_AUTHENTICATION_REQUIRED, "%s", + _("You must be authenticated to query all calendars.")); + + return; + } + + request_uri = g_strconcat (_gdata_service_get_scheme (), "://www.googleapis.com/calendar/v3/users/me/calendarList", NULL); + gdata_service_query_async (GDATA_SERVICE (self), get_calendar_authorization_domain (), request_uri, query, GDATA_TYPE_CALENDAR_CALENDAR, + cancellable, progress_callback, progress_user_data, destroy_progress_user_data, callback, user_data); + g_free (request_uri); +} + +/** + * gdata_calendar_service_query_own_calendars: + * @self: a #GDataCalendarService + * @query: (allow-none): a #GDataQuery with the query parameters, or %NULL + * @cancellable: (allow-none): optional #GCancellable object, or %NULL + * @progress_callback: (allow-none) (scope call) (closure progress_user_data): a #GDataQueryProgressCallback to call when an entry is loaded, or %NULL + * @progress_user_data: (closure): data to pass to the @progress_callback function + * @error: a #GError, or %NULL + * + * Queries the service to return a list of calendars from the authenticated account which match the given + * @query, and the authenticated user owns. (i.e. They have full read/write access to the calendar, as well + * as the ability to set permissions on the calendar.) + * + * For more details, see gdata_service_query(). + * + * Return value: (transfer full): a #GDataFeed of query results; unref with g_object_unref() + */ +GDataFeed * +gdata_calendar_service_query_own_calendars (GDataCalendarService *self, GDataQuery *query, GCancellable *cancellable, + GDataQueryProgressCallback progress_callback, gpointer progress_user_data, GError **error) +{ + GDataFeed *feed; + gchar *request_uri; + + g_return_val_if_fail (GDATA_IS_CALENDAR_SERVICE (self), NULL); + g_return_val_if_fail (query == NULL || GDATA_IS_QUERY (query), NULL); + g_return_val_if_fail (cancellable == NULL || G_IS_CANCELLABLE (cancellable), NULL); + g_return_val_if_fail (error == NULL || *error == NULL, NULL); + + /* Ensure we're authenticated first */ + if (gdata_authorizer_is_authorized_for_domain (gdata_service_get_authorizer (GDATA_SERVICE (self)), + get_calendar_authorization_domain ()) == FALSE) { + g_set_error_literal (error, GDATA_SERVICE_ERROR, GDATA_SERVICE_ERROR_AUTHENTICATION_REQUIRED, + _("You must be authenticated to query your own calendars.")); + return NULL; + } + + request_uri = g_strconcat (_gdata_service_get_scheme (), "://www.googleapis.com/calendar/v3/users/me/calendarList?minAccessRole=owner", NULL); + feed = gdata_service_query (GDATA_SERVICE (self), get_calendar_authorization_domain (), request_uri, query, GDATA_TYPE_CALENDAR_CALENDAR, + cancellable, progress_callback, progress_user_data, error); + g_free (request_uri); + + return feed; +} + +/** + * gdata_calendar_service_query_own_calendars_async: + * @self: a #GDataCalendarService + * @query: (allow-none): a #GDataQuery with the query parameters, or %NULL + * @cancellable: (allow-none): optional #GCancellable object, or %NULL + * @progress_callback: (allow-none) (closure progress_user_data): a #GDataQueryProgressCallback to call when an entry is loaded, or %NULL + * @progress_user_data: (closure): data to pass to the @progress_callback function + * @destroy_progress_user_data: (allow-none): the function to call when @progress_callback will not be called any more, or %NULL. This function will be + * called with @progress_user_data as a parameter and can be used to free any memory allocated for it. + * @callback: a #GAsyncReadyCallback to call when authentication is finished + * @user_data: (closure): data to pass to the @callback function + * + * Queries the service to return a list of calendars from the authenticated account which match the given + * @query, and the authenticated user owns. @self and @query are all reffed when this function is called, + * so can safely be unreffed after this function returns. + * + * For more details, see gdata_calendar_service_query_own_calendars(), which is the synchronous version of + * this function, and gdata_service_query_async(), which is the base asynchronous query function. + * + * Since: 0.9.1 + */ +void +gdata_calendar_service_query_own_calendars_async (GDataCalendarService *self, GDataQuery *query, GCancellable *cancellable, + GDataQueryProgressCallback progress_callback, gpointer progress_user_data, + GDestroyNotify destroy_progress_user_data, + GAsyncReadyCallback callback, gpointer user_data) +{ + gchar *request_uri; + + g_return_if_fail (GDATA_IS_CALENDAR_SERVICE (self)); + g_return_if_fail (query == NULL || GDATA_IS_QUERY (query)); + g_return_if_fail (cancellable == NULL || G_IS_CANCELLABLE (cancellable)); + g_return_if_fail (callback != NULL); + + /* Ensure we're authenticated first */ + if (gdata_authorizer_is_authorized_for_domain (gdata_service_get_authorizer (GDATA_SERVICE (self)), + get_calendar_authorization_domain ()) == FALSE) { + g_autoptr(GTask) task = NULL; + + task = g_task_new (self, cancellable, callback, user_data); + g_task_set_source_tag (task, gdata_service_query_async); + g_task_return_new_error (task, GDATA_SERVICE_ERROR, GDATA_SERVICE_ERROR_AUTHENTICATION_REQUIRED, "%s", + _("You must be authenticated to query your own calendars.")); + + return; + } + + request_uri = g_strconcat (_gdata_service_get_scheme (), "://www.googleapis.com/calendar/v3/users/me/calendarList?minAccessRole=owner", NULL); + gdata_service_query_async (GDATA_SERVICE (self), get_calendar_authorization_domain (), request_uri, query, GDATA_TYPE_CALENDAR_CALENDAR, + cancellable, progress_callback, progress_user_data, destroy_progress_user_data, callback, user_data); + g_free (request_uri); +} + +static gchar * +build_events_uri (GDataCalendarCalendar *calendar) +{ + GString *uri; + const gchar *calendar_id; + + calendar_id = (calendar != NULL) ? gdata_entry_get_id (GDATA_ENTRY (calendar)) : "default"; + + uri = g_string_new (_gdata_service_get_scheme ()); + g_string_append (uri, "://www.googleapis.com/calendar/v3/calendars/"); + g_string_append_uri_escaped (uri, calendar_id, NULL, FALSE); + g_string_append (uri, "/events"); + + return g_string_free (uri, FALSE); +} + +/** + * gdata_calendar_service_query_events: + * @self: a #GDataCalendarService + * @calendar: a #GDataCalendarCalendar + * @query: (allow-none): a #GDataQuery with the query parameters, or %NULL + * @cancellable: (allow-none): optional #GCancellable object, or %NULL + * @progress_callback: (allow-none) (scope call) (closure progress_user_data): a #GDataQueryProgressCallback to call when an entry is loaded, or %NULL + * @progress_user_data: (closure): data to pass to the @progress_callback function + * @error: a #GError, or %NULL + * + * Queries the service to return a list of events in the given @calendar, which match @query. + * + * For more details, see gdata_service_query(). + * + * Return value: (transfer full): a #GDataFeed of query results; unref with g_object_unref() + */ +GDataFeed * +gdata_calendar_service_query_events (GDataCalendarService *self, GDataCalendarCalendar *calendar, GDataQuery *query, GCancellable *cancellable, + GDataQueryProgressCallback progress_callback, gpointer progress_user_data, GError **error) +{ + gchar *request_uri; + GDataFeed *feed; + + g_return_val_if_fail (GDATA_IS_CALENDAR_SERVICE (self), NULL); + g_return_val_if_fail (GDATA_IS_CALENDAR_CALENDAR (calendar), NULL); + g_return_val_if_fail (query == NULL || GDATA_IS_QUERY (query), NULL); + g_return_val_if_fail (cancellable == NULL || G_IS_CANCELLABLE (cancellable), NULL); + g_return_val_if_fail (error == NULL || *error == NULL, NULL); + + /* Ensure we're authenticated first */ + if (gdata_authorizer_is_authorized_for_domain (gdata_service_get_authorizer (GDATA_SERVICE (self)), + get_calendar_authorization_domain ()) == FALSE) { + g_set_error_literal (error, GDATA_SERVICE_ERROR, GDATA_SERVICE_ERROR_AUTHENTICATION_REQUIRED, + _("You must be authenticated to query your own calendars.")); + return NULL; + } + + /* Execute the query. */ + request_uri = build_events_uri (calendar); + feed = gdata_service_query (GDATA_SERVICE (self), + get_calendar_authorization_domain (), + request_uri, query, + GDATA_TYPE_CALENDAR_EVENT, cancellable, + progress_callback, progress_user_data, + error); + g_free (request_uri); + + return feed; +} + +/** + * gdata_calendar_service_query_events_async: + * @self: a #GDataCalendarService + * @calendar: a #GDataCalendarCalendar + * @query: (allow-none): a #GDataQuery with the query parameters, or %NULL + * @cancellable: (allow-none): optional #GCancellable object, or %NULL + * @progress_callback: (allow-none) (closure progress_user_data): a #GDataQueryProgressCallback to call when an entry is loaded, or %NULL + * @progress_user_data: (closure): data to pass to the @progress_callback function + * @destroy_progress_user_data: (allow-none): the function to call when @progress_callback will not be called any more, or %NULL. This function will be + * called with @progress_user_data as a parameter and can be used to free any memory allocated for it. + * @callback: a #GAsyncReadyCallback to call when the query is finished + * @user_data: (closure): data to pass to the @callback function + * + * Queries the service to return a list of events in the given @calendar, which match @query. @self, @calendar and @query are all reffed when this + * function is called, so can safely be unreffed after this function returns. + * + * Get the results of the query using gdata_service_query_finish() in the @callback. + * + * For more details, see gdata_calendar_service_query_events(), which is the synchronous version of this function, and gdata_service_query_async(), + * which is the base asynchronous query function. + * + * Since: 0.9.1 + */ +void +gdata_calendar_service_query_events_async (GDataCalendarService *self, GDataCalendarCalendar *calendar, GDataQuery *query, GCancellable *cancellable, + GDataQueryProgressCallback progress_callback, gpointer progress_user_data, + GDestroyNotify destroy_progress_user_data, + GAsyncReadyCallback callback, gpointer user_data) +{ + gchar *request_uri; + + g_return_if_fail (GDATA_IS_CALENDAR_SERVICE (self)); + g_return_if_fail (GDATA_IS_CALENDAR_CALENDAR (calendar)); + g_return_if_fail (query == NULL || GDATA_IS_QUERY (query)); + g_return_if_fail (cancellable == NULL || G_IS_CANCELLABLE (cancellable)); + g_return_if_fail (callback != NULL); + + /* Ensure we're authenticated first */ + if (gdata_authorizer_is_authorized_for_domain (gdata_service_get_authorizer (GDATA_SERVICE (self)), + get_calendar_authorization_domain ()) == FALSE) { + g_autoptr(GTask) task = NULL; + + task = g_task_new (self, cancellable, callback, user_data); + g_task_set_source_tag (task, gdata_service_query_async); + g_task_return_new_error (task, GDATA_SERVICE_ERROR, GDATA_SERVICE_ERROR_AUTHENTICATION_REQUIRED, "%s", + _("You must be authenticated to query your own calendars.")); + + return; + } + + /* Execute the query. */ + request_uri = build_events_uri (calendar); + gdata_service_query_async (GDATA_SERVICE (self), + get_calendar_authorization_domain (), + request_uri, query, + GDATA_TYPE_CALENDAR_EVENT, cancellable, + progress_callback, progress_user_data, + destroy_progress_user_data, callback, + user_data); + g_free (request_uri); +} + +/** + * gdata_calendar_service_insert_event: + * @self: a #GDataCalendarService + * @event: the #GDataCalendarEvent to insert + * @cancellable: (allow-none): optional #GCancellable object, or %NULL + * @error: a #GError, or %NULL + * + * Inserts @event by uploading it to the online calendar service. + * + * For more details, see gdata_service_insert_entry(). + * + * Return value: (transfer full): an updated #GDataCalendarEvent, or %NULL; unref with g_object_unref() + * + * Since: 0.2.0 + * Deprecated: 0.17.2: Use gdata_calendar_service_insert_calendar_event() + * instead to be able to specify the calendar to add the event to; otherwise + * the default calendar will be used. + */ +GDataCalendarEvent * +gdata_calendar_service_insert_event (GDataCalendarService *self, GDataCalendarEvent *event, GCancellable *cancellable, GError **error) +{ + gchar *uri; + GDataEntry *entry; + + g_return_val_if_fail (GDATA_IS_CALENDAR_SERVICE (self), NULL); + g_return_val_if_fail (GDATA_IS_CALENDAR_EVENT (event), NULL); + g_return_val_if_fail (cancellable == NULL || G_IS_CANCELLABLE (cancellable), NULL); + g_return_val_if_fail (error == NULL || *error == NULL, NULL); + + uri = build_events_uri (NULL); + entry = gdata_service_insert_entry (GDATA_SERVICE (self), get_calendar_authorization_domain (), uri, GDATA_ENTRY (event), cancellable, error); + g_free (uri); + + return GDATA_CALENDAR_EVENT (entry); +} + +/** + * gdata_calendar_service_insert_calendar_event: + * @self: a #GDataCalendarService + * @calendar: the #GDataCalendarCalendar to insert the event into + * @event: the #GDataCalendarEvent to insert + * @cancellable: (allow-none): optional #GCancellable object, or %NULL + * @error: a #GError, or %NULL + * + * Inserts @event by uploading it to the online calendar service, adding it to + * the specified @calendar. + * + * For more details, see gdata_service_insert_entry(). + * + * Return value: (transfer full): an updated #GDataCalendarEvent, or %NULL; + * unref with g_object_unref() + * + * Since: 0.17.2 + */ +GDataCalendarEvent * +gdata_calendar_service_insert_calendar_event (GDataCalendarService *self, + GDataCalendarCalendar *calendar, + GDataCalendarEvent *event, + GCancellable *cancellable, + GError **error) +{ + gchar *uri; + GDataEntry *entry; + + g_return_val_if_fail (GDATA_IS_CALENDAR_SERVICE (self), NULL); + g_return_val_if_fail (GDATA_IS_CALENDAR_CALENDAR (calendar), NULL); + g_return_val_if_fail (GDATA_IS_CALENDAR_EVENT (event), NULL); + g_return_val_if_fail (cancellable == NULL || G_IS_CANCELLABLE (cancellable), NULL); + g_return_val_if_fail (error == NULL || *error == NULL, NULL); + + uri = build_events_uri (calendar); + entry = gdata_service_insert_entry (GDATA_SERVICE (self), + get_calendar_authorization_domain (), + uri, GDATA_ENTRY (event), + cancellable, error); + g_free (uri); + + return GDATA_CALENDAR_EVENT (entry); +} + +/** + * gdata_calendar_service_insert_event_async: + * @self: a #GDataCalendarService + * @event: the #GDataCalendarEvent to insert + * @cancellable: (allow-none): optional #GCancellable object, or %NULL + * @callback: a #GAsyncReadyCallback to call when insertion is finished + * @user_data: (closure): data to pass to the @callback function + * + * Inserts @event by uploading it to the online calendar service. @self and @event are both reffed when this function is called, so can safely be + * unreffed after this function returns. + * + * @callback should call gdata_service_insert_entry_finish() to obtain a #GDataCalendarEvent representing the inserted event and to check for possible + * errors. + * + * For more details, see gdata_calendar_service_insert_event(), which is the synchronous version of this function, and + * gdata_service_insert_entry_async(), which is the base asynchronous insertion function. + * + * Since: 0.8.0 + * Deprecated: 0.17.2: Use + * gdata_calendar_service_insert_calendar_event_async() instead to be able to + * specify the calendar to add the event to; otherwise the default calendar + * will be used. + */ +void +gdata_calendar_service_insert_event_async (GDataCalendarService *self, GDataCalendarEvent *event, GCancellable *cancellable, + GAsyncReadyCallback callback, gpointer user_data) +{ + gchar *uri; + + g_return_if_fail (GDATA_IS_CALENDAR_SERVICE (self)); + g_return_if_fail (GDATA_IS_CALENDAR_EVENT (event)); + g_return_if_fail (cancellable == NULL || G_IS_CANCELLABLE (cancellable)); + + uri = build_events_uri (NULL); + gdata_service_insert_entry_async (GDATA_SERVICE (self), get_calendar_authorization_domain (), uri, GDATA_ENTRY (event), cancellable, + callback, user_data); + g_free (uri); +} + +/** + * gdata_calendar_service_insert_calendar_event_async: + * @self: a #GDataCalendarService + * @calendar: the #GDataCalendarCalendar to insert the event into + * @event: the #GDataCalendarEvent to insert + * @cancellable: (allow-none): optional #GCancellable object, or %NULL + * @callback: a #GAsyncReadyCallback to call when insertion is finished + * @user_data: (closure): data to pass to the @callback function + * + * Inserts @event by uploading it to the online calendar service, adding it to + * the specified @calendar. @self and @event are both reffed when this function + * is called, so can safely be unreffed after this function returns. + * + * @callback should call gdata_service_insert_entry_finish() to obtain a + * #GDataCalendarEvent representing the inserted event and to check for possible + * errors. + * + * For more details, see gdata_calendar_service_insert_event(), which is the + * synchronous version of this function, and gdata_service_insert_entry_async(), + * which is the base asynchronous insertion function. + * + * Since: 0.17.2 + */ +void +gdata_calendar_service_insert_calendar_event_async (GDataCalendarService *self, + GDataCalendarCalendar *calendar, + GDataCalendarEvent *event, + GCancellable *cancellable, + GAsyncReadyCallback callback, + gpointer user_data) +{ + gchar *uri; + + g_return_if_fail (GDATA_IS_CALENDAR_SERVICE (self)); + g_return_if_fail (GDATA_IS_CALENDAR_EVENT (event)); + g_return_if_fail (cancellable == NULL || G_IS_CANCELLABLE (cancellable)); + + uri = build_events_uri (calendar); + gdata_service_insert_entry_async (GDATA_SERVICE (self), + get_calendar_authorization_domain (), + uri, GDATA_ENTRY (event), cancellable, + callback, user_data); + g_free (uri); +} diff --git a/gdata/services/calendar/gdata-calendar-service.h b/gdata/services/calendar/gdata-calendar-service.h new file mode 100644 index 0000000..7cb397d --- /dev/null +++ b/gdata/services/calendar/gdata-calendar-service.h @@ -0,0 +1,129 @@ +/* -*- Mode: C; indent-tabs-mode: t; c-basic-offset: 8; tab-width: 8 -*- */ +/* + * GData Client + * Copyright (C) Philip Withnall 2009, 2015 + * + * GData Client is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * GData Client is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with GData Client. If not, see . + */ + +#ifndef GDATA_CALENDAR_SERVICE_H +#define GDATA_CALENDAR_SERVICE_H + +#include +#include + +#include +#include +#include + +G_BEGIN_DECLS + +#define GDATA_TYPE_CALENDAR_SERVICE (gdata_calendar_service_get_type ()) +#define GDATA_CALENDAR_SERVICE(o) (G_TYPE_CHECK_INSTANCE_CAST ((o), GDATA_TYPE_CALENDAR_SERVICE, GDataCalendarService)) +#define GDATA_CALENDAR_SERVICE_CLASS(k) (G_TYPE_CHECK_CLASS_CAST((k), GDATA_TYPE_CALENDAR_SERVICE, GDataCalendarServiceClass)) +#define GDATA_IS_CALENDAR_SERVICE(o) (G_TYPE_CHECK_INSTANCE_TYPE ((o), GDATA_TYPE_CALENDAR_SERVICE)) +#define GDATA_IS_CALENDAR_SERVICE_CLASS(k) (G_TYPE_CHECK_CLASS_TYPE ((k), GDATA_TYPE_CALENDAR_SERVICE)) +#define GDATA_CALENDAR_SERVICE_GET_CLASS(o) (G_TYPE_INSTANCE_GET_CLASS ((o), GDATA_TYPE_CALENDAR_SERVICE, GDataCalendarServiceClass)) + +typedef struct _GDataCalendarServicePrivate GDataCalendarServicePrivate; + +/** + * GDataCalendarService: + * + * All the fields in the #GDataCalendarService structure are private and should never be accessed directly. + */ +typedef struct { + GDataService parent; +} GDataCalendarService; + +/** + * GDataCalendarServiceClass: + * + * All the fields in the #GDataCalendarServiceClass structure are private and should never be accessed directly. + */ +typedef struct { + /*< private >*/ + GDataServiceClass parent; + + /*< private >*/ + /* Padding for future expansion */ + void (*_g_reserved0) (void); + void (*_g_reserved1) (void); + void (*_g_reserved2) (void); + void (*_g_reserved3) (void); + void (*_g_reserved4) (void); + void (*_g_reserved5) (void); +} GDataCalendarServiceClass; + +GType gdata_calendar_service_get_type (void) G_GNUC_CONST; + +GDataCalendarService *gdata_calendar_service_new (GDataAuthorizer *authorizer) G_GNUC_WARN_UNUSED_RESULT G_GNUC_MALLOC; + +GDataAuthorizationDomain *gdata_calendar_service_get_primary_authorization_domain (void) G_GNUC_CONST; + +GDataFeed *gdata_calendar_service_query_all_calendars (GDataCalendarService *self, GDataQuery *query, GCancellable *cancellable, + GDataQueryProgressCallback progress_callback, gpointer progress_user_data, + GError **error) G_GNUC_WARN_UNUSED_RESULT G_GNUC_MALLOC; +void gdata_calendar_service_query_all_calendars_async (GDataCalendarService *self, GDataQuery *query, GCancellable *cancellable, + GDataQueryProgressCallback progress_callback, gpointer progress_user_data, + GDestroyNotify destroy_progress_user_data, GAsyncReadyCallback callback, gpointer user_data); + +GDataFeed *gdata_calendar_service_query_own_calendars (GDataCalendarService *self, GDataQuery *query, GCancellable *cancellable, + GDataQueryProgressCallback progress_callback, gpointer progress_user_data, + GError **error) G_GNUC_WARN_UNUSED_RESULT G_GNUC_MALLOC; +void gdata_calendar_service_query_own_calendars_async (GDataCalendarService *self, GDataQuery *query, GCancellable *cancellable, + GDataQueryProgressCallback progress_callback, gpointer progress_user_data, + GDestroyNotify destroy_progress_user_data, GAsyncReadyCallback callback, gpointer user_data); + +GDataFeed *gdata_calendar_service_query_events (GDataCalendarService *self, GDataCalendarCalendar *calendar, GDataQuery *query, + GCancellable *cancellable, GDataQueryProgressCallback progress_callback, gpointer progress_user_data, + GError **error) G_GNUC_WARN_UNUSED_RESULT G_GNUC_MALLOC; +void gdata_calendar_service_query_events_async (GDataCalendarService *self, GDataCalendarCalendar *calendar, GDataQuery *query, + GCancellable *cancellable, GDataQueryProgressCallback progress_callback, gpointer progress_user_data, + GDestroyNotify destroy_progress_user_data, GAsyncReadyCallback callback, gpointer user_data); + +#include + +#ifndef LIBGDATA_DISABLE_DEPRECATED +GDataCalendarEvent * +gdata_calendar_service_insert_event (GDataCalendarService *self, + GDataCalendarEvent *event, + GCancellable *cancellable, + GError **error) G_GNUC_WARN_UNUSED_RESULT G_GNUC_MALLOC G_GNUC_DEPRECATED_FOR(gdata_calendar_service_insert_calendar_event); +void +gdata_calendar_service_insert_event_async (GDataCalendarService *self, + GDataCalendarEvent *event, + GCancellable *cancellable, + GAsyncReadyCallback callback, + gpointer user_data) + G_GNUC_DEPRECATED_FOR (gdata_calendar_service_insert_calendar_event_async); +#endif /* !LIBGDATA_DISABLE_DEPRECATED */ + +GDataCalendarEvent * +gdata_calendar_service_insert_calendar_event (GDataCalendarService *self, + GDataCalendarCalendar *calendar, + GDataCalendarEvent *event, + GCancellable *cancellable, + GError **error) G_GNUC_WARN_UNUSED_RESULT G_GNUC_MALLOC; +void +gdata_calendar_service_insert_calendar_event_async (GDataCalendarService *self, + GDataCalendarCalendar *calendar, + GDataCalendarEvent *event, + GCancellable *cancellable, + GAsyncReadyCallback callback, + gpointer user_data); + +G_END_DECLS + +#endif /* !GDATA_CALENDAR_SERVICE_H */ diff --git a/gdata/services/calendar/meson.build b/gdata/services/calendar/meson.build new file mode 100644 index 0000000..5eaa816 --- /dev/null +++ b/gdata/services/calendar/meson.build @@ -0,0 +1,24 @@ +headers = files( + 'gdata-calendar-access-rule.h', + 'gdata-calendar-calendar.h', + 'gdata-calendar-event.h', + 'gdata-calendar-feed.h', + 'gdata-calendar-query.h', + 'gdata-calendar-service.h', +) + +install_headers( + headers, + subdir: gdata_include_subdir / 'services/calendar', +) + +gir_headers += headers + +sources += files( + 'gdata-calendar-access-rule.c', + 'gdata-calendar-calendar.c', + 'gdata-calendar-event.c', + 'gdata-calendar-feed.c', + 'gdata-calendar-query.c', + 'gdata-calendar-service.c', +) diff --git a/gdata/services/contacts/gdata-contacts-contact.c b/gdata/services/contacts/gdata-contacts-contact.c new file mode 100644 index 0000000..fc577f3 --- /dev/null +++ b/gdata/services/contacts/gdata-contacts-contact.c @@ -0,0 +1,3487 @@ +/* -*- Mode: C; indent-tabs-mode: t; c-basic-offset: 8; tab-width: 8 -*- */ +/* + * GData Client + * Copyright (C) Philip Withnall 2009, 2010, 2011 + * + * GData Client is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * GData Client is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with GData Client. If not, see . + */ + +/** + * SECTION:gdata-contacts-contact + * @short_description: GData Contacts contact object + * @stability: Stable + * @include: gdata/services/contacts/gdata-contacts-contact.h + * + * #GDataContactsContact is a subclass of #GDataEntry to represent a contact from a Google address book. + * + * For more details of Google Contacts' GData API, see the + * online documentation. + * + * In addition to all the standard properties available for a contact, #GDataContactsContact supports two kinds of additional property: extended + * properties and user-defined fields. Extended properties, set with gdata_contacts_contact_set_extended_property() and retrieved with + * gdata_contacts_contact_get_extended_property(), are provided as a method of storing client-specific data which shouldn't be seen or be editable + * by the user, such as IDs and cache times. User-defined fields, set with gdata_contacts_contact_set_user_defined_field() and retrieved with + * gdata_contacts_contact_get_user_defined_field(), store fields defined by the user, and editable by them in the interface (both the interface of + * the appliation using libgdata, and the Google Contacts web interface). + * + * + * Getting a Contact's Photo + * + * GDataContactsService *service; + * GDataContactsContact *contact; + * guint8 *data; + * gchar *content_type = NULL; + * gsize length = 0; + * GError *error = NULL; + * + * /* Create a service and return the contact whose photo we're getting. */ + * service = create_contacts_service (); + * contact = query_user_for_contact (service); + * + * /* Get the photo. This should almost always be done asynchronously. */ + * data = gdata_contacts_contact_get_photo (contact, service, &length, &content_type, NULL, &error); + * + * g_object_unref (contact); + * g_object_unref (service); + * + * if (error != NULL) { + * g_error ("Error getting a contact's photo: %s", error->message); + * g_error_free (error); + * return; + * } + * + * /* Do something with the photo, stored in data, length and content_type. */ + * + * g_free (content_type); + * g_free (data); + * + * + * + * + * Setting a Contact's Photo + * + * GDataContactsService *service; + * GDataContactsContact *contact; + * guint8 *data; + * gchar *content_type = NULL; + * gsize length = 0; + * GError *error = NULL; + * + * /* Create a service and return the contact whose photo we're getting, as well as the details of the new photo. */ + * service = create_contacts_service (); + * contact = query_user_for_contact (service); + * data = query_user_for_new_photo (contact, &content_type, &length); + * + * /* Set the photo. This should almost always be done asynchronously. To delete the photo, just pass NULL as the photo data. */ + * gdata_contacts_contact_set_photo (contact, service, data, length, content_type, NULL, &error); + * + * g_free (data); + * g_free (content_type); + * g_object_unref (contact); + * g_object_unref (service); + * + * if (error != NULL) { + * g_error ("Error setting a contact's photo: %s", error->message); + * g_error_free (error); + * return; + * } + * + * + * + * + * Updating a Contact's Details + * + * GDataContactsService *service; + * GDataContactsContact *contact, *updated_contact; + * GDataGDEmailAddress *email_address; + * GDataGDIMAddress *im_address; + * GError *error = NULL; + * + * /* Create a service and return the contact whose details we're updating. */ + * service = create_contacts_service (); + * contact = query_user_for_contact (service); + * + * /* Update the contact's details. We set their nickname to "Fat Tony", add a new e-mail address, and replace all their existing IM + * * addresses with a single new one. */ + * gdata_contacts_contact_set_nickname (contact, "Fat Tony"); + * + * email_address = gdata_gd_email_address_new ("tony@gmail.com", GDATA_GD_EMAIL_ADDRESS_HOME, NULL, FALSE); + * gdata_contacts_contact_add_email_address (contact, email_address); + * g_object_unref (email_address); + * + * gdata_contacts_contact_remove_all_im_addresses (contact); + * im_address = gdata_gd_im_address_new ("tony.work@gmail.com", GDATA_GD_IM_PROTOCOL_GOOGLE_TALK, GDATA_GD_IM_ADDRESS_WORK, NULL, TRUE); + * gdata_contacts_contact_add_im_address (contact, im_address); + * g_object_unref (im_address); + * + * /* Send the updated contact to the server */ + * updated_contact = GDATA_CONTACTS_CONTACT (gdata_service_update_entry (GDATA_SERVICE (service), GDATA_ENTRY (contact), NULL, &error)); + * + * g_object_unref (contact); + * g_object_unref (service); + * + * if (error != NULL) { + * g_error ("Error updating a contact's details: %s", error->message); + * g_error_free (error); + * return; + * } + * + * /* Do something with the updated contact, such as update them in the UI, or store their ID for future use. */ + * + * g_object_unref (updated_contact); + * + * + * + * Since: 0.2.0 + */ + +#include +#include +#include +#include +#include + +#include "gdata-contacts-contact.h" +#include "gdata-parser.h" +#include "gdata-types.h" +#include "gdata-private.h" +#include "gdata-comparable.h" + +/* The maximum number of extended properties the server allows us. See + * http://code.google.com/apis/contacts/docs/2.0/reference.html#ProjectionsAndExtended. + * When updating this, make sure to update the API documentation for gdata_contacts_contact_get_extended_property() + * and gdata_contacts_contact_set_extended_property(). */ +#define MAX_N_EXTENDED_PROPERTIES 10 + +static GObject *gdata_contacts_contact_constructor (GType type, guint n_construct_params, GObjectConstructParam *construct_params); +static void gdata_contacts_contact_dispose (GObject *object); +static void gdata_contacts_contact_finalize (GObject *object); +static void gdata_contacts_contact_get_property (GObject *object, guint property_id, GValue *value, GParamSpec *pspec); +static void gdata_contacts_contact_set_property (GObject *object, guint property_id, const GValue *value, GParamSpec *pspec); +static void get_xml (GDataParsable *parsable, GString *xml_string); +static gboolean parse_xml (GDataParsable *parsable, xmlDoc *doc, xmlNode *node, gpointer user_data, GError **error); +static void get_namespaces (GDataParsable *parsable, GHashTable *namespaces); +static gchar *get_entry_uri (const gchar *id) G_GNUC_WARN_UNUSED_RESULT; + +struct _GDataContactsContactPrivate { + gint64 edited; + GDataGDName *name; + GList *email_addresses; /* GDataGDEmailAddress */ + GList *im_addresses; /* GDataGDIMAddress */ + GList *phone_numbers; /* GDataGDPhoneNumber */ + GList *postal_addresses; /* GDataGDPostalAddress */ + GList *organizations; /* GDataGDOrganization */ + GHashTable *extended_properties; + GHashTable *user_defined_fields; + GHashTable *groups; + gboolean deleted; + gchar *photo_etag; + GList *jots; /* GDataGContactJot */ + gchar *nickname; + gchar *file_as; + GDate birthday; + gboolean birthday_has_year; /* contacts can choose to just give the month and day of their birth */ + GList *relations; /* GDataGContactRelation */ + GList *websites; /* GDataGContactWebsite */ + GList *events; /* GDataGContactEvent */ + GList *calendars; /* GDataGContactCalendar */ + GList *external_ids; /* GDataGContactExternalID */ + gchar *billing_information; + gchar *directory_server; + gchar *gender; + gchar *initials; + gchar *maiden_name; + gchar *mileage; + gchar *occupation; + gchar *priority; + gchar *sensitivity; + gchar *short_name; + gchar *subject; + GList *hobbies; /* gchar* */ + GList *languages; /* GDataGContactLanguage */ +}; + +enum { + PROP_EDITED = 1, + PROP_DELETED, + PROP_NAME, + PROP_NICKNAME, + PROP_BIRTHDAY, + PROP_BIRTHDAY_HAS_YEAR, + PROP_BILLING_INFORMATION, + PROP_DIRECTORY_SERVER, + PROP_GENDER, + PROP_INITIALS, + PROP_MAIDEN_NAME, + PROP_MILEAGE, + PROP_OCCUPATION, + PROP_PRIORITY, + PROP_SENSITIVITY, + PROP_SHORT_NAME, + PROP_SUBJECT, + PROP_PHOTO_ETAG, + PROP_FILE_AS, +}; + +G_DEFINE_TYPE (GDataContactsContact, gdata_contacts_contact, GDATA_TYPE_ENTRY) + +static void +gdata_contacts_contact_class_init (GDataContactsContactClass *klass) +{ + GObjectClass *gobject_class = G_OBJECT_CLASS (klass); + GDataParsableClass *parsable_class = GDATA_PARSABLE_CLASS (klass); + GDataEntryClass *entry_class = GDATA_ENTRY_CLASS (klass); + + g_type_class_add_private (klass, sizeof (GDataContactsContactPrivate)); + + gobject_class->constructor = gdata_contacts_contact_constructor; + gobject_class->get_property = gdata_contacts_contact_get_property; + gobject_class->set_property = gdata_contacts_contact_set_property; + gobject_class->dispose = gdata_contacts_contact_dispose; + gobject_class->finalize = gdata_contacts_contact_finalize; + + parsable_class->parse_xml = parse_xml; + parsable_class->get_xml = get_xml; + parsable_class->get_namespaces = get_namespaces; + + entry_class->get_entry_uri = get_entry_uri; + entry_class->kind_term = "http://schemas.google.com/contact/2008#contact"; + + /** + * GDataContactsContact:edited: + * + * The last time the contact was edited. If the contact has not been edited yet, the content indicates the time it was created. + * + * For more information, see the + * Atom Publishing Protocol specification. + * + * Since: 0.2.0 + */ + g_object_class_install_property (gobject_class, PROP_EDITED, + g_param_spec_int64 ("edited", + "Edited", "The last time the contact was edited.", + -1, G_MAXINT64, -1, + G_PARAM_READABLE | G_PARAM_STATIC_STRINGS)); + + /** + * GDataContactsContact:deleted: + * + * Whether the entry has been deleted. + * + * Since: 0.2.0 + */ + g_object_class_install_property (gobject_class, PROP_DELETED, + g_param_spec_boolean ("deleted", + "Deleted", "Whether the entry has been deleted.", + FALSE, + G_PARAM_READABLE | G_PARAM_STATIC_STRINGS)); + + /** + * GDataContactsContact:photo-etag: + * + * The ETag of the contact's photo, if the contact has a photo; %NULL otherwise. + * + * Since: 0.9.0 + */ + g_object_class_install_property (gobject_class, PROP_PHOTO_ETAG, + g_param_spec_string ("photo-etag", + "Photo ETag", "The ETag of the contact's photo.", + NULL, + G_PARAM_READABLE | G_PARAM_STATIC_STRINGS)); + + /** + * GDataContactsContact:name: + * + * The contact's name in a structured representation. + * + * Since: 0.5.0 + */ + g_object_class_install_property (gobject_class, PROP_NAME, + g_param_spec_object ("name", + "Name", "The contact's name in a structured representation.", + GDATA_TYPE_GD_NAME, + G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)); + + /** + * GDataContactsContact:nickname: + * + * The contact's chosen nickname. + * + * Since: 0.7.0 + */ + g_object_class_install_property (gobject_class, PROP_NICKNAME, + g_param_spec_string ("nickname", + "Nickname", "The contact's chosen nickname.", + NULL, + G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)); + + /** + * GDataContactsContact:file-as: + * + * The name to file the contact under for sorting purposes. + * + * Since: 0.11.0 + */ + g_object_class_install_property (gobject_class, PROP_FILE_AS, + g_param_spec_string ("file-as", + "File As", "The name to file the contact under for sorting purposes.", + NULL, + G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)); + + /** + * GDataContactsContact:birthday: + * + * The contact's birthday. + * + * Since: 0.7.0 + */ + g_object_class_install_property (gobject_class, PROP_BIRTHDAY, + g_param_spec_boxed ("birthday", + "Birthday", "The contact's birthday.", + G_TYPE_DATE, + G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)); + + /** + * GDataContactsContact:birthday-has-year: + * + * Whether the contact's birthday includes their year of birth. + * + * Since: 0.7.0 + */ + g_object_class_install_property (gobject_class, PROP_BIRTHDAY_HAS_YEAR, + g_param_spec_boolean ("birthday-has-year", + "Birthday has year?", "Whether the contact's birthday includes their year of birth.", + FALSE, + G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)); + + /** + * GDataContactsContact:billing-information: + * + * Billing information for the contact, such as their billing name and address. + * + * Since: 0.7.0 + */ + g_object_class_install_property (gobject_class, PROP_BILLING_INFORMATION, + g_param_spec_string ("billing-information", + "Billing information", "Billing information for the contact.", + NULL, + G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)); + + /** + * GDataContactsContact:directory-server: + * + * The name or address of a directory server associated with the contact. + * + * Since: 0.7.0 + */ + g_object_class_install_property (gobject_class, PROP_DIRECTORY_SERVER, + g_param_spec_string ("directory-server", + "Directory server", "The name or address of an associated directory server.", + NULL, + G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)); + + /** + * GDataContactsContact:gender: + * + * The gender of the contact. For example: %GDATA_CONTACTS_GENDER_MALE or %GDATA_CONTACTS_GENDER_FEMALE. + * + * Since: 0.7.0 + */ + g_object_class_install_property (gobject_class, PROP_GENDER, + g_param_spec_string ("gender", + "Gender", "The gender of the contact.", + NULL, + G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)); + + /** + * GDataContactsContact:initials: + * + * The initials of the contact. + * + * Since: 0.7.0 + */ + g_object_class_install_property (gobject_class, PROP_INITIALS, + g_param_spec_string ("initials", + "Initials", "The initials of the contact.", + NULL, + G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)); + + /** + * GDataContactsContact:maiden-name: + * + * The maiden name of the contact. + * + * Since: 0.7.0 + */ + g_object_class_install_property (gobject_class, PROP_MAIDEN_NAME, + g_param_spec_string ("maiden-name", + "Maiden name", "The maiden name of the contact.", + NULL, + G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)); + + /** + * GDataContactsContact:mileage: + * + * A mileage associated with the contact, such as one for reimbursement purposes. It can be in any format. + * + * Since: 0.7.0 + */ + g_object_class_install_property (gobject_class, PROP_MILEAGE, + g_param_spec_string ("mileage", + "Mileage", "A mileage associated with the contact.", + NULL, + G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)); + + /** + * GDataContactsContact:occupation: + * + * The contact's occupation. + * + * Since: 0.7.0 + */ + g_object_class_install_property (gobject_class, PROP_OCCUPATION, + g_param_spec_string ("occupation", + "Occupation", "The contact's occupation.", + NULL, + G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)); + + /** + * GDataContactsContact:priority: + * + * The contact's importance. For example: %GDATA_CONTACTS_PRIORITY_NORMAL or %GDATA_CONTACTS_PRIORITY_HIGH. + * + * Since: 0.7.0 + */ + g_object_class_install_property (gobject_class, PROP_PRIORITY, + g_param_spec_string ("priority", + "Priority", "The contact's importance.", + NULL, + G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)); + + /** + * GDataContactsContact:sensitivity: + * + * The sensitivity of the contact's data. For example: %GDATA_CONTACTS_SENSITIVITY_NORMAL or %GDATA_CONTACTS_SENSITIVITY_PRIVATE. + * + * Since: 0.7.0 + */ + g_object_class_install_property (gobject_class, PROP_SENSITIVITY, + g_param_spec_string ("sensitivity", + "Sensitivity", "The sensitivity of the contact's data.", + NULL, + G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)); + + /** + * GDataContactsContact:short-name: + * + * A short name for the contact. This should be used for contracted versions of the contact's actual name, + * whereas #GDataContactsContact:nickname should be used for nicknames. + * + * Since: 0.7.0 + */ + g_object_class_install_property (gobject_class, PROP_SHORT_NAME, + g_param_spec_string ("short-name", + "Short name", "A short name for the contact.", + NULL, + G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)); + + /** + * GDataContactsContact:subject: + * + * The subject of the contact. (i.e. The contact's relevance to the address book.) + * + * Since: 0.7.0 + */ + g_object_class_install_property (gobject_class, PROP_SUBJECT, + g_param_spec_string ("subject", + "Subject", "The subject of the contact.", + NULL, + G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)); +} + +static void notify_full_name_cb (GObject *gobject, GParamSpec *pspec, GDataContactsContact *self); + +static void +notify_title_cb (GObject *gobject, GParamSpec *pspec, GDataContactsContact *self) +{ + /* Update GDataGDName:full-name */ + g_signal_handlers_block_by_func (self->priv->name, notify_full_name_cb, self); + gdata_gd_name_set_full_name (self->priv->name, gdata_entry_get_title (GDATA_ENTRY (self))); + g_signal_handlers_unblock_by_func (self->priv->name, notify_full_name_cb, self); +} + +static void +notify_full_name_cb (GObject *gobject, GParamSpec *pspec, GDataContactsContact *self) +{ + /* Update GDataEntry:title */ + g_signal_handlers_block_by_func (self, notify_title_cb, self); + gdata_entry_set_title (GDATA_ENTRY (self), gdata_gd_name_get_full_name (self->priv->name)); + g_signal_handlers_unblock_by_func (self, notify_title_cb, self); +} + +static void +gdata_contacts_contact_init (GDataContactsContact *self) +{ + self->priv = G_TYPE_INSTANCE_GET_PRIVATE (self, GDATA_TYPE_CONTACTS_CONTACT, GDataContactsContactPrivate); + self->priv->extended_properties = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, g_free); + self->priv->user_defined_fields = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, g_free); + self->priv->groups = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, NULL); + self->priv->edited = -1; + + /* Create a default name, so the name's properties can be set for a blank contact */ + self->priv->name = gdata_gd_name_new (NULL, NULL); + + /* Listen to change notifications for the entry's title, since it's linked to GDataGDName:full-name */ + g_signal_connect (self, "notify::title", (GCallback) notify_title_cb, self); + g_signal_connect (self->priv->name, "notify::full-name", (GCallback) notify_full_name_cb, self); + + /* Initialise the contact's birthday to a sane but invalid date */ + g_date_clear (&(self->priv->birthday), 1); +} + +static GObject * +gdata_contacts_contact_constructor (GType type, guint n_construct_params, GObjectConstructParam *construct_params) +{ + GObject *object; + guint i; + + /* Find the "id" property and ensure it's sane */ + for (i = 0; i < n_construct_params; i++) { + GParamSpec *pspec = construct_params[i].pspec; + GValue *value = construct_params[i].value; + + if (strcmp (g_param_spec_get_name (pspec), "id") == 0) { + gchar *base, *id; + + id = g_value_dup_string (value); + + /* Fix the ID to refer to the full projection, rather than the base projection. */ + if (id != NULL) { + base = strstr (id, "/base/"); + if (base != NULL) + memcpy (base, "/full/", 6); + } + + g_value_take_string (value, id); + + break; + } + } + + /* Chain up to the parent class */ + object = G_OBJECT_CLASS (gdata_contacts_contact_parent_class)->constructor (type, n_construct_params, construct_params); + + if (_gdata_parsable_is_constructed_from_xml (GDATA_PARSABLE (object)) == FALSE) { + GDataContactsContactPrivate *priv = GDATA_CONTACTS_CONTACT (object)->priv; + GTimeVal time_val; + + /* Set the edited property to the current time (creation time). We don't do this in *_init() since that would cause + * setting it from parse_xml() to fail (duplicate element). */ + g_get_current_time (&time_val); + priv->edited = time_val.tv_sec; + } + + return object; +} + +static void +gdata_contacts_contact_dispose (GObject *object) +{ + GDataContactsContact *self = GDATA_CONTACTS_CONTACT (object); + + if (self->priv->name != NULL) + g_object_unref (self->priv->name); + self->priv->name = NULL; + + gdata_contacts_contact_remove_all_organizations (self); + gdata_contacts_contact_remove_all_email_addresses (self); + gdata_contacts_contact_remove_all_im_addresses (self); + gdata_contacts_contact_remove_all_postal_addresses (self); + gdata_contacts_contact_remove_all_phone_numbers (self); + gdata_contacts_contact_remove_all_jots (self); + gdata_contacts_contact_remove_all_relations (self); + gdata_contacts_contact_remove_all_websites (self); + gdata_contacts_contact_remove_all_events (self); + gdata_contacts_contact_remove_all_calendars (self); + gdata_contacts_contact_remove_all_external_ids (self); + gdata_contacts_contact_remove_all_languages (self); + + /* Chain up to the parent class */ + G_OBJECT_CLASS (gdata_contacts_contact_parent_class)->dispose (object); +} + +static void +gdata_contacts_contact_finalize (GObject *object) +{ + GDataContactsContactPrivate *priv = GDATA_CONTACTS_CONTACT (object)->priv; + + g_hash_table_destroy (priv->extended_properties); + g_hash_table_destroy (priv->user_defined_fields); + g_hash_table_destroy (priv->groups); + g_free (priv->photo_etag); + g_free (priv->nickname); + g_free (priv->file_as); + g_free (priv->billing_information); + g_free (priv->directory_server); + g_free (priv->gender); + g_free (priv->initials); + g_free (priv->maiden_name); + g_free (priv->mileage); + g_free (priv->occupation); + g_free (priv->priority); + g_free (priv->sensitivity); + g_free (priv->short_name); + g_free (priv->subject); + + g_list_free_full (priv->hobbies, g_free); + + /* Chain up to the parent class */ + G_OBJECT_CLASS (gdata_contacts_contact_parent_class)->finalize (object); +} + +static void +gdata_contacts_contact_get_property (GObject *object, guint property_id, GValue *value, GParamSpec *pspec) +{ + GDataContactsContactPrivate *priv = GDATA_CONTACTS_CONTACT (object)->priv; + + switch (property_id) { + case PROP_EDITED: + g_value_set_int64 (value, priv->edited); + break; + case PROP_DELETED: + g_value_set_boolean (value, priv->deleted); + break; + case PROP_PHOTO_ETAG: + g_value_set_string (value, priv->photo_etag); + break; + case PROP_NAME: + g_value_set_object (value, priv->name); + break; + case PROP_NICKNAME: + g_value_set_string (value, priv->nickname); + break; + case PROP_FILE_AS: + g_value_set_string (value, priv->file_as); + break; + case PROP_BIRTHDAY: + g_value_set_boxed (value, &(priv->birthday)); + break; + case PROP_BIRTHDAY_HAS_YEAR: + g_value_set_boolean (value, priv->birthday_has_year); + break; + case PROP_BILLING_INFORMATION: + g_value_set_string (value, priv->billing_information); + break; + case PROP_DIRECTORY_SERVER: + g_value_set_string (value, priv->directory_server); + break; + case PROP_GENDER: + g_value_set_string (value, priv->gender); + break; + case PROP_INITIALS: + g_value_set_string (value, priv->initials); + break; + case PROP_MAIDEN_NAME: + g_value_set_string (value, priv->maiden_name); + break; + case PROP_MILEAGE: + g_value_set_string (value, priv->mileage); + break; + case PROP_OCCUPATION: + g_value_set_string (value, priv->occupation); + break; + case PROP_PRIORITY: + g_value_set_string (value, priv->priority); + break; + case PROP_SENSITIVITY: + g_value_set_string (value, priv->sensitivity); + break; + case PROP_SHORT_NAME: + g_value_set_string (value, priv->short_name); + break; + case PROP_SUBJECT: + g_value_set_string (value, priv->subject); + break; + default: + /* We don't have any other property... */ + G_OBJECT_WARN_INVALID_PROPERTY_ID (object, property_id, pspec); + break; + } +} + +static void +gdata_contacts_contact_set_property (GObject *object, guint property_id, const GValue *value, GParamSpec *pspec) +{ + GDataContactsContact *self = GDATA_CONTACTS_CONTACT (object); + + switch (property_id) { + case PROP_NAME: + gdata_contacts_contact_set_name (self, g_value_get_object (value)); + break; + case PROP_NICKNAME: + gdata_contacts_contact_set_nickname (self, g_value_get_string (value)); + break; + case PROP_FILE_AS: + gdata_contacts_contact_set_file_as (self, g_value_get_string (value)); + break; + case PROP_BIRTHDAY: + gdata_contacts_contact_set_birthday (self, g_value_get_boxed (value), self->priv->birthday_has_year); + break; + case PROP_BIRTHDAY_HAS_YEAR: + gdata_contacts_contact_set_birthday (self, &(self->priv->birthday), g_value_get_boolean (value)); + break; + case PROP_BILLING_INFORMATION: + gdata_contacts_contact_set_billing_information (self, g_value_get_string (value)); + break; + case PROP_DIRECTORY_SERVER: + gdata_contacts_contact_set_directory_server (self, g_value_get_string (value)); + break; + case PROP_GENDER: + gdata_contacts_contact_set_gender (self, g_value_get_string (value)); + break; + case PROP_INITIALS: + gdata_contacts_contact_set_initials (self, g_value_get_string (value)); + break; + case PROP_MAIDEN_NAME: + gdata_contacts_contact_set_maiden_name (self, g_value_get_string (value)); + break; + case PROP_MILEAGE: + gdata_contacts_contact_set_mileage (self, g_value_get_string (value)); + break; + case PROP_OCCUPATION: + gdata_contacts_contact_set_occupation (self, g_value_get_string (value)); + break; + case PROP_PRIORITY: + gdata_contacts_contact_set_priority (self, g_value_get_string (value)); + break; + case PROP_SENSITIVITY: + gdata_contacts_contact_set_sensitivity (self, g_value_get_string (value)); + break; + case PROP_SHORT_NAME: + gdata_contacts_contact_set_short_name (self, g_value_get_string (value)); + break; + case PROP_SUBJECT: + gdata_contacts_contact_set_subject (self, g_value_get_string (value)); + break; + default: + /* We don't have any other property... */ + G_OBJECT_WARN_INVALID_PROPERTY_ID (object, property_id, pspec); + break; + } +} + +static gboolean +parse_xml (GDataParsable *parsable, xmlDoc *doc, xmlNode *node, gpointer user_data, GError **error) +{ + gboolean success; + GDataContactsContact *self = GDATA_CONTACTS_CONTACT (parsable); + + if (gdata_parser_is_namespace (node, "http://www.w3.org/2007/app") == TRUE && + gdata_parser_int64_time_from_element (node, "edited", P_REQUIRED | P_NO_DUPES, &(self->priv->edited), &success, error) == TRUE) { + return success; + } else if (gdata_parser_is_namespace (node, "http://www.w3.org/2005/Atom") == TRUE && xmlStrcmp (node->name, (xmlChar*) "id") == 0) { + /* We have to override parsing to fix the projection. Modify it in-place so that the parser in GDataEntry will pick up + * the changes. This fixes bugs caused by referring to contacts by the base projection, rather than the full projection; + * such as http://code.google.com/p/gdata-issues/issues/detail?id=2129. */ + gchar *base; + gchar *id = (gchar*) xmlNodeListGetString (doc, node->children, TRUE); + + if (id != NULL) { + base = strstr (id, "/base/"); + if (base != NULL) { + memcpy (base, "/full/", 6); + xmlNodeSetContent (node, (xmlChar*) id); + } + } + + xmlFree (id); + + return GDATA_PARSABLE_CLASS (gdata_contacts_contact_parent_class)->parse_xml (parsable, doc, node, user_data, error); + } else if (gdata_parser_is_namespace (node, "http://schemas.google.com/g/2005") == TRUE) { + if (gdata_parser_object_from_element_setter (node, "im", P_REQUIRED, GDATA_TYPE_GD_IM_ADDRESS, + gdata_contacts_contact_add_im_address, self, &success, error) == TRUE || + gdata_parser_object_from_element_setter (node, "phoneNumber", P_REQUIRED, GDATA_TYPE_GD_PHONE_NUMBER, + gdata_contacts_contact_add_phone_number, self, &success, error) == TRUE || + gdata_parser_object_from_element_setter (node, "structuredPostalAddress", P_REQUIRED, GDATA_TYPE_GD_POSTAL_ADDRESS, + gdata_contacts_contact_add_postal_address, self, &success, error) == TRUE || + gdata_parser_object_from_element_setter (node, "organization", P_REQUIRED, GDATA_TYPE_GD_ORGANIZATION, + gdata_contacts_contact_add_organization, self, &success, error) == TRUE || + gdata_parser_object_from_element (node, "name", P_REQUIRED, GDATA_TYPE_GD_NAME, &(self->priv->name), &success, error) == TRUE) { + return success; + } else if (xmlStrcmp (node->name, (xmlChar*) "email") == 0) { + /* gd:email */ + GDataParsable *_parsable; + xmlChar *address; + + /* Check its address attribute is non-empty. Empty address attributes are apparently allowed, and make the + * gd:email element a no-op. See: https://bugzilla.gnome.org/show_bug.cgi?id=734863 */ + address = xmlGetProp (node, (xmlChar *) "address"); + if (address == NULL) { + return gdata_parser_error_required_property_missing (node, "address", error); + } else if (*address == '\0') { + xmlFree (address); + success = TRUE; + return TRUE; + } + + xmlFree (address); + + /* Parse the e-mail address. */ + _parsable = _gdata_parsable_new_from_xml_node (GDATA_TYPE_GD_EMAIL_ADDRESS, node->doc, node, NULL, error); + if (_parsable == NULL) { + /* The error has already been set by _gdata_parsable_new_from_xml_node() */ + success = FALSE; + return TRUE; + } + + /* Success! */ + gdata_contacts_contact_add_email_address (self, GDATA_GD_EMAIL_ADDRESS (_parsable)); + g_object_unref (_parsable); + success = TRUE; + + return TRUE; + } else if (xmlStrcmp (node->name, (xmlChar*) "extendedProperty") == 0) { + /* gd:extendedProperty */ + xmlChar *name, *value; + xmlBuffer *buffer = NULL; + + name = xmlGetProp (node, (xmlChar*) "name"); + if (name == NULL) + return gdata_parser_error_required_property_missing (node, "name", error); + + /* Get either the value property, or the element's content */ + value = xmlGetProp (node, (xmlChar*) "value"); + if (value == NULL) { + xmlNode *child_node; + + /* Use the element's content instead (arbitrary XML) */ + buffer = xmlBufferCreate (); + for (child_node = node->children; child_node != NULL; child_node = child_node->next) + xmlNodeDump (buffer, doc, child_node, 0, 0); + value = (xmlChar*) xmlBufferContent (buffer); + } + + gdata_contacts_contact_set_extended_property (self, (gchar*) name, (gchar*) value); + + xmlFree (name); + if (buffer != NULL) + xmlBufferFree (buffer); + else + xmlFree (value); + } else if (xmlStrcmp (node->name, (xmlChar*) "deleted") == 0) { + /* gd:deleted */ + self->priv->deleted = TRUE; + } else { + return GDATA_PARSABLE_CLASS (gdata_contacts_contact_parent_class)->parse_xml (parsable, doc, node, user_data, error); + } + } else if (gdata_parser_is_namespace (node, "http://schemas.google.com/contact/2008") == TRUE) { + if (gdata_parser_object_from_element_setter (node, "jot", P_REQUIRED, GDATA_TYPE_GCONTACT_JOT, + gdata_contacts_contact_add_jot, self, &success, error) == TRUE || + gdata_parser_object_from_element_setter (node, "relation", P_REQUIRED, GDATA_TYPE_GCONTACT_RELATION, + gdata_contacts_contact_add_relation, self, &success, error) == TRUE || + gdata_parser_object_from_element_setter (node, "event", P_REQUIRED, GDATA_TYPE_GCONTACT_EVENT, + gdata_contacts_contact_add_event, self, &success, error) == TRUE || + gdata_parser_object_from_element_setter (node, "website", P_IGNORE_ERROR, GDATA_TYPE_GCONTACT_WEBSITE, + gdata_contacts_contact_add_website, self, &success, error) == TRUE || + gdata_parser_object_from_element_setter (node, "calendarLink", P_REQUIRED, GDATA_TYPE_GCONTACT_CALENDAR, + gdata_contacts_contact_add_calendar, self, &success, error) == TRUE || + gdata_parser_object_from_element_setter (node, "externalId", P_REQUIRED, GDATA_TYPE_GCONTACT_EXTERNAL_ID, + gdata_contacts_contact_add_external_id, self, &success, error) == TRUE || + gdata_parser_object_from_element_setter (node, "language", P_REQUIRED, GDATA_TYPE_GCONTACT_LANGUAGE, + gdata_contacts_contact_add_language, self, &success, error) == TRUE || + gdata_parser_string_from_element (node, "nickname", P_REQUIRED | P_NO_DUPES, &(self->priv->nickname), &success, error) == TRUE || + gdata_parser_string_from_element (node, "fileAs", P_REQUIRED | P_NO_DUPES, &(self->priv->file_as), &success, error) == TRUE || + gdata_parser_string_from_element (node, "billingInformation", P_REQUIRED | P_NO_DUPES | P_NON_EMPTY, + &(self->priv->billing_information), &success, error) == TRUE || + gdata_parser_string_from_element (node, "directoryServer", P_REQUIRED | P_NO_DUPES | P_NON_EMPTY, + &(self->priv->directory_server), &success, error) == TRUE || + gdata_parser_string_from_element (node, "initials", P_REQUIRED | P_NO_DUPES, &(self->priv->initials), &success, error) == TRUE || + gdata_parser_string_from_element (node, "maidenName", P_REQUIRED | P_NO_DUPES, + &(self->priv->maiden_name), &success, error) == TRUE || + gdata_parser_string_from_element (node, "mileage", P_REQUIRED | P_NO_DUPES, &(self->priv->mileage), &success, error) == TRUE || + gdata_parser_string_from_element (node, "occupation", P_REQUIRED | P_NO_DUPES, + &(self->priv->occupation), &success, error) == TRUE || + gdata_parser_string_from_element (node, "shortName", P_REQUIRED | P_NO_DUPES, + &(self->priv->short_name), &success, error) == TRUE || + gdata_parser_string_from_element (node, "subject", P_REQUIRED | P_NO_DUPES, &(self->priv->subject), &success, error) == TRUE) { + return success; + } else if (xmlStrcmp (node->name, (xmlChar*) "gender") == 0) { + /* gContact:gender */ + xmlChar *value; + + if (self->priv->gender != NULL) + return gdata_parser_error_duplicate_element (node, error); + + value = xmlGetProp (node, (xmlChar*) "value"); + if (value == NULL || *value == '\0') { + xmlFree (value); + return gdata_parser_error_required_content_missing (node, error); + } + + self->priv->gender = (gchar*) value; + } else if (xmlStrcmp (node->name, (xmlChar*) "hobby") == 0) { + /* gContact:hobby */ + xmlChar *hobby; + + hobby = xmlNodeListGetString (doc, node->children, TRUE); + if (hobby == NULL || *hobby == '\0') { + xmlFree (hobby); + return gdata_parser_error_required_content_missing (node, error); + } + + gdata_contacts_contact_add_hobby (self, (gchar*) hobby); + xmlFree (hobby); + } else if (xmlStrcmp (node->name, (xmlChar*) "userDefinedField") == 0) { + /* gContact:userDefinedField */ + xmlChar *name, *value; + + /* Note that while we require the property to be present, we don't require it to be non-empty. See bgo#648058 */ + name = xmlGetProp (node, (xmlChar*) "key"); + if (name == NULL) { + return gdata_parser_error_required_property_missing (node, "key", error); + } + + /* Get either the value property, or the element's content */ + value = xmlGetProp (node, (xmlChar*) "value"); + if (value == NULL) { + xmlFree (name); + return gdata_parser_error_required_property_missing (node, "value", error); + } + + gdata_contacts_contact_set_user_defined_field (self, (gchar*) name, (gchar*) value); + + xmlFree (name); + xmlFree (value); + } else if (xmlStrcmp (node->name, (xmlChar*) "priority") == 0) { + /* gContact:priority */ + xmlChar *rel; + + if (self->priv->priority != NULL) + return gdata_parser_error_duplicate_element (node, error); + + rel = xmlGetProp (node, (xmlChar*) "rel"); + if (rel == NULL || *rel == '\0') { + xmlFree (rel); + return gdata_parser_error_required_content_missing (node, error); + } + + self->priv->priority = (gchar*) rel; + } else if (xmlStrcmp (node->name, (xmlChar*) "sensitivity") == 0) { + /* gContact:sensitivity */ + xmlChar *rel; + + if (self->priv->sensitivity != NULL) + return gdata_parser_error_duplicate_element (node, error); + + rel = xmlGetProp (node, (xmlChar*) "rel"); + if (rel == NULL || *rel == '\0') { + xmlFree (rel); + return gdata_parser_error_required_content_missing (node, error); + } + + self->priv->sensitivity = (gchar*) rel; + } else if (xmlStrcmp (node->name, (xmlChar*) "groupMembershipInfo") == 0) { + /* gContact:groupMembershipInfo */ + xmlChar *href; + gboolean deleted_bool; + + href = xmlGetProp (node, (xmlChar*) "href"); + if (href == NULL) + return gdata_parser_error_required_property_missing (node, "href", error); + + /* Has it been deleted? */ + if (gdata_parser_boolean_from_property (node, "deleted", &deleted_bool, 0, error) == FALSE) { + xmlFree (href); + return FALSE; + } + + /* Insert it into the hash table */ + g_hash_table_insert (self->priv->groups, (gchar*) href, GUINT_TO_POINTER (deleted_bool)); + } else if (xmlStrcmp (node->name, (xmlChar*) "birthday") == 0) { + /* gContact:birthday */ + xmlChar *birthday; + guint length = 0, year = 666, month, day; + + if (g_date_valid (&(self->priv->birthday)) == TRUE) + return gdata_parser_error_duplicate_element (node, error); + + birthday = xmlGetProp (node, (xmlChar*) "when"); + if (birthday == NULL) + return gdata_parser_error_required_property_missing (node, "when", error); + length = strlen ((char*) birthday); + + /* Try parsing the two possible formats: YYYY-MM-DD and --MM-DD */ + if (((length == 10 && sscanf ((char*) birthday, "%4u-%2u-%2u", &year, &month, &day) == 3) || + (length == 7 && sscanf ((char*) birthday, "--%2u-%2u", &month, &day) == 2)) && + g_date_valid_dmy (day, month, year) == TRUE) { + /* Store the values in the GDate */ + g_date_set_dmy (&(self->priv->birthday), day, month, year); + self->priv->birthday_has_year = (length == 10) ? TRUE : FALSE; + xmlFree (birthday); + } else { + /* Parsing failed */ + gdata_parser_error_not_iso8601_format (node, (gchar*) birthday, error); + xmlFree (birthday); + return FALSE; + } + } else { + return GDATA_PARSABLE_CLASS (gdata_contacts_contact_parent_class)->parse_xml (parsable, doc, node, user_data, error); + } + } else { + /* If we haven't yet found a photo, check to see if it's a photo element */ + if (self->priv->photo_etag == NULL && xmlStrcmp (node->name, (xmlChar*) "link") == 0) { + xmlChar *rel = xmlGetProp (node, (xmlChar*) "rel"); + if (xmlStrcmp (rel, (xmlChar*) "http://schemas.google.com/contacts/2008/rel#photo") == 0) { + /* It's the photo link (http://code.google.com/apis/contacts/docs/2.0/reference.html#Photos), whose ETag we should + * note down, then pass onto the parent class to parse properly */ + self->priv->photo_etag = (gchar*) xmlGetProp (node, (xmlChar*) "etag"); + } + xmlFree (rel); + } + + return GDATA_PARSABLE_CLASS (gdata_contacts_contact_parent_class)->parse_xml (parsable, doc, node, user_data, error); + } + + return TRUE; +} + +static void +get_child_xml (GList *list, GString *xml_string) +{ + GList *i; + + for (i = list; i != NULL; i = i->next) + _gdata_parsable_get_xml (GDATA_PARSABLE (i->data), xml_string, FALSE); +} + +static void +get_extended_property_xml_cb (const gchar *name, const gchar *value, GString *xml_string) +{ + /* Note that the value *isn't* escaped (see http://code.google.com/apis/gdata/docs/2.0/elements.html#gdExtendedProperty) */ + gdata_parser_string_append_escaped (xml_string, ""); + g_string_append_printf (xml_string, "%s", value); +} + +static void +get_user_defined_field_xml_cb (const gchar *name, const gchar *value, GString *xml_string) +{ + gdata_parser_string_append_escaped (xml_string, ""); +} + +static void +get_group_xml_cb (const gchar *href, gpointer deleted, GString *xml_string) +{ + gchar *full_pos, *uri = g_strdup (href); + + /* The service API sometimes stubbornly insists on using the "full" view instead of the "base" view, which we have + * to fix, or it complains about an invalid group ID. */ + full_pos = strstr (uri, "/full/"); + if (full_pos != NULL) + memcpy ((char*) full_pos, "/base/", 6); + + gdata_parser_string_append_escaped (xml_string, ""); + + g_free (uri); +} + +static void +get_hobby_xml_cb (const gchar *hobby, GString *xml_string) +{ + gdata_parser_string_append_escaped (xml_string, "", hobby, ""); +} + +static void +get_xml (GDataParsable *parsable, GString *xml_string) +{ + GDataContactsContactPrivate *priv = GDATA_CONTACTS_CONTACT (parsable)->priv; + + /* Chain up to the parent class */ + GDATA_PARSABLE_CLASS (gdata_contacts_contact_parent_class)->get_xml (parsable, xml_string); + + /* Name */ + _gdata_parsable_get_xml (GDATA_PARSABLE (priv->name), xml_string, FALSE); + + /* Lists of stuff */ + get_child_xml (priv->email_addresses, xml_string); + get_child_xml (priv->im_addresses, xml_string); + get_child_xml (priv->phone_numbers, xml_string); + get_child_xml (priv->postal_addresses, xml_string); + get_child_xml (priv->organizations, xml_string); + get_child_xml (priv->jots, xml_string); + get_child_xml (priv->relations, xml_string); + get_child_xml (priv->websites, xml_string); + get_child_xml (priv->events, xml_string); + get_child_xml (priv->calendars, xml_string); + get_child_xml (priv->external_ids, xml_string); + get_child_xml (priv->languages, xml_string); + + /* Extended properties */ + g_hash_table_foreach (priv->extended_properties, (GHFunc) get_extended_property_xml_cb, xml_string); + + /* User defined fields */ + g_hash_table_foreach (priv->user_defined_fields, (GHFunc) get_user_defined_field_xml_cb, xml_string); + + /* Group membership info */ + g_hash_table_foreach (priv->groups, (GHFunc) get_group_xml_cb, xml_string); + + /* Hobbies */ + g_list_foreach (priv->hobbies, (GFunc) get_hobby_xml_cb, xml_string); + + /* gContact:nickname */ + if (priv->nickname != NULL) + gdata_parser_string_append_escaped (xml_string, "", priv->nickname, ""); + + /* gContact:fileAs */ + if (priv->file_as != NULL) { + gdata_parser_string_append_escaped (xml_string, "", priv->file_as, ""); + } + + /* gContact:birthday */ + if (g_date_valid (&(priv->birthday)) == TRUE) { + if (priv->birthday_has_year == TRUE) { + g_string_append_printf (xml_string, "", + g_date_get_year (&(priv->birthday)), + g_date_get_month (&(priv->birthday)), + g_date_get_day (&(priv->birthday))); + } else { + g_string_append_printf (xml_string, "", + g_date_get_month (&(priv->birthday)), + g_date_get_day (&(priv->birthday))); + } + } + + /* gContact:billingInformation */ + if (priv->billing_information != NULL) { + gdata_parser_string_append_escaped (xml_string, + "", priv->billing_information, ""); + } + + /* gContact:directoryServer */ + if (priv->directory_server != NULL) + gdata_parser_string_append_escaped (xml_string, "", priv->directory_server, ""); + + /* gContact:gender */ + if (priv->gender != NULL) + gdata_parser_string_append_escaped (xml_string, ""); + + /* gContact:initials */ + if (priv->initials != NULL) + gdata_parser_string_append_escaped (xml_string, "", priv->initials, ""); + + /* gContact:maidenName */ + if (priv->maiden_name != NULL) + gdata_parser_string_append_escaped (xml_string, "", priv->maiden_name, ""); + + /* gContact:mileage */ + if (priv->mileage != NULL) + gdata_parser_string_append_escaped (xml_string, "", priv->mileage, ""); + + /* gContact:occupation */ + if (priv->occupation != NULL) + gdata_parser_string_append_escaped (xml_string, "", priv->occupation, ""); + + /* gContact:priority */ + if (priv->priority != NULL) + gdata_parser_string_append_escaped (xml_string, ""); + + /* gContact:sensitivity */ + if (priv->sensitivity != NULL) + gdata_parser_string_append_escaped (xml_string, ""); + + /* gContact:shortName */ + if (priv->short_name != NULL) + gdata_parser_string_append_escaped (xml_string, "", priv->short_name, ""); + + /* gContact:subject */ + if (priv->subject != NULL) + gdata_parser_string_append_escaped (xml_string, "", priv->subject, ""); + + /* TODO: + * - Finish supporting all tags + */ +} + +static void +get_namespaces (GDataParsable *parsable, GHashTable *namespaces) +{ + /* Chain up to the parent class */ + GDATA_PARSABLE_CLASS (gdata_contacts_contact_parent_class)->get_namespaces (parsable, namespaces); + + g_hash_table_insert (namespaces, (gchar*) "gd", (gchar*) "http://schemas.google.com/g/2005"); + g_hash_table_insert (namespaces, (gchar*) "gContact", (gchar*) "http://schemas.google.com/contact/2008"); + g_hash_table_insert (namespaces, (gchar*) "app", (gchar*) "http://www.w3.org/2007/app"); +} + +static gchar * +get_entry_uri (const gchar *id) +{ + const gchar *base_pos; + gchar *uri; + + /* Ensure it uses the HTTPS protocol */ + if (g_str_has_prefix (id, "http://") == TRUE) { + guint id_length = strlen (id); + + uri = g_malloc (id_length + 2); + strcpy (uri, "https://"); + strcpy (uri + strlen ("https://"), id + strlen ("http://")); + } else { + uri = g_strdup (id); + } + + /* The service API sometimes stubbornly insists on using the "base" view instead of the "full" view, which we have + * to fix, or our extended attributes are never visible */ + base_pos = strstr (uri, "/base/"); + if (base_pos != NULL) + memcpy ((char*) base_pos, "/full/", 6); + + return uri; +} + +/** + * gdata_contacts_contact_new: + * @id: (allow-none): the contact's ID, or %NULL + * + * Creates a new #GDataContactsContact with the given ID and default properties. + * + * Return value: a new #GDataContactsContact; unref with g_object_unref() + * + * Since: 0.2.0 + */ +GDataContactsContact * +gdata_contacts_contact_new (const gchar *id) +{ + return GDATA_CONTACTS_CONTACT (g_object_new (GDATA_TYPE_CONTACTS_CONTACT, "id", id, NULL)); +} + +/** + * gdata_contacts_contact_get_edited: + * @self: a #GDataContactsContact + * + * Gets the #GDataContactsContact:edited property. If the property is unset, -1 will be returned. + * + * Return value: the UNIX timestamp for the time the contact was last edited, or -1 + * + * Since: 0.2.0 + */ +gint64 +gdata_contacts_contact_get_edited (GDataContactsContact *self) +{ + g_return_val_if_fail (GDATA_IS_CONTACTS_CONTACT (self), -1); + return self->priv->edited; +} + +/** + * gdata_contacts_contact_get_name: + * @self: a #GDataContactsContact + * + * Gets the #GDataContactsContact:name property. + * + * Return value: (transfer none): the contact's name, or %NULL + * + * Since: 0.5.0 + */ +GDataGDName * +gdata_contacts_contact_get_name (GDataContactsContact *self) +{ + g_return_val_if_fail (GDATA_IS_CONTACTS_CONTACT (self), NULL); + return self->priv->name; +} + +/** + * gdata_contacts_contact_set_name: + * @self: a #GDataContactsContact + * @name: the new #GDataGDName + * + * Sets the #GDataContactsContact:name property to @name, and increments its reference count. + * + * @name must not be %NULL, though all its properties may be %NULL. + * + * Since: 0.7.0 + */ +void +gdata_contacts_contact_set_name (GDataContactsContact *self, GDataGDName *name) +{ + g_return_if_fail (GDATA_IS_CONTACTS_CONTACT (self)); + g_return_if_fail (GDATA_IS_GD_NAME (name)); + + if (self->priv->name != NULL) + g_object_unref (self->priv->name); + self->priv->name = g_object_ref (name); + g_object_notify (G_OBJECT (self), "name"); + + /* Notify the change in #GDataGDName:full-name explicitly, so that our #GDataEntry:title gets updated */ + notify_full_name_cb (G_OBJECT (name), NULL, self); +} + +/** + * gdata_contacts_contact_get_nickname: + * @self: a #GDataContactsContact + * + * Gets the #GDataContactsContact:nickname property. + * + * Return value: the contact's nickname, or %NULL + * + * Since: 0.7.0 + */ +const gchar * +gdata_contacts_contact_get_nickname (GDataContactsContact *self) +{ + g_return_val_if_fail (GDATA_IS_CONTACTS_CONTACT (self), NULL); + return self->priv->nickname; +} + +/** + * gdata_contacts_contact_set_nickname: + * @self: a #GDataContactsContact + * @nickname: (allow-none): the new nickname, or %NULL + * + * Sets the #GDataContactsContact:nickname property to @nickname. + * + * If @nickname is %NULL, the contact's nickname will be removed. + * + * Since: 0.7.0 + */ +void +gdata_contacts_contact_set_nickname (GDataContactsContact *self, const gchar *nickname) +{ + g_return_if_fail (GDATA_IS_CONTACTS_CONTACT (self)); + + g_free (self->priv->nickname); + self->priv->nickname = g_strdup (nickname); + g_object_notify (G_OBJECT (self), "nickname"); +} + +/** + * gdata_contacts_contact_get_file_as: + * @self: a #GDataContactsContact + * + * Gets the #GDataContactsContact:file-as property. + * + * Return value: the name the contact's filed under, or %NULL + * + * Since: 0.11.0 + */ +const gchar * +gdata_contacts_contact_get_file_as (GDataContactsContact *self) +{ + g_return_val_if_fail (GDATA_IS_CONTACTS_CONTACT (self), NULL); + return self->priv->file_as; +} + +/** + * gdata_contacts_contact_set_file_as: + * @self: a #GDataContactsContact + * @file_as: (allow-none): the new name to file the contact under, or %NULL + * + * Sets the #GDataContactsContact:file-as property to @file_as. + * + * If @file_as is %NULL, the contact will be filed under their full name. + * + * Since: 0.7.0 + */ +void +gdata_contacts_contact_set_file_as (GDataContactsContact *self, const gchar *file_as) +{ + g_return_if_fail (GDATA_IS_CONTACTS_CONTACT (self)); + + g_free (self->priv->file_as); + self->priv->file_as = g_strdup (file_as); + g_object_notify (G_OBJECT (self), "file-as"); +} + +/** + * gdata_contacts_contact_get_birthday: + * @self: a #GDataContactsContact + * @birthday: (allow-none) (out caller-allocates): return location for the birthday, or %NULL + * + * Gets the #GDataContactsContact:birthday and #GDataContactsContact:birthday-has-year properties. If @birthday is non-%NULL, + * #GDataContactsContact:birthday is returned in it. The function returns the value of #GDataContactsContact:birthday-has-year, + * which specifies whether the year in @birthday is meaningful. Contacts may not have the year of their birth set, in which + * case, the function would return %FALSE, and the year in @birthday should be ignored. + * + * Return value: whether the contact's birthday has the year set + * + * Since: 0.7.0 + */ +gboolean +gdata_contacts_contact_get_birthday (GDataContactsContact *self, GDate *birthday) +{ + g_return_val_if_fail (GDATA_IS_CONTACTS_CONTACT (self), FALSE); + + if (birthday != NULL) + *birthday = self->priv->birthday; + return self->priv->birthday_has_year; +} + +/** + * gdata_contacts_contact_set_birthday: + * @self: a #GDataContactsContact + * @birthday: (allow-none): the new birthday, or %NULL + * @birthday_has_year: %TRUE if @birthday's year is relevant, %FALSE otherwise + * + * Sets the #GDataContactsContact:birthday property to @birthday and the #GDataContactsContact:birthday-has-year property to @birthday_has_year. + * See gdata_contacts_contact_get_birthday() for an explanation of the interaction between these two properties. + * + * If @birthday is %NULL, the contact's birthday will be removed. + * + * Since: 0.7.0 + */ +void +gdata_contacts_contact_set_birthday (GDataContactsContact *self, GDate *birthday, gboolean birthday_has_year) +{ + g_return_if_fail (GDATA_IS_CONTACTS_CONTACT (self)); + g_return_if_fail (birthday == NULL || g_date_valid (birthday)); + + if (birthday != NULL) + self->priv->birthday = *birthday; + else + g_date_clear (&(self->priv->birthday), 1); + + self->priv->birthday_has_year = birthday_has_year; + + g_object_freeze_notify (G_OBJECT (self)); + g_object_notify (G_OBJECT (self), "birthday"); + g_object_notify (G_OBJECT (self), "birthday-has-year"); + g_object_thaw_notify (G_OBJECT (self)); +} + +/** + * gdata_contacts_contact_get_billing_information: + * @self: a #GDataContactsContact + * + * Gets the #GDataContactsContact:billing-information property. + * + * Return value: the contact's billing information, or %NULL + * + * Since: 0.7.0 + */ +const gchar * +gdata_contacts_contact_get_billing_information (GDataContactsContact *self) +{ + g_return_val_if_fail (GDATA_IS_CONTACTS_CONTACT (self), NULL); + return self->priv->billing_information; +} + +/** + * gdata_contacts_contact_set_billing_information: + * @self: a #GDataContactsContact + * @billing_information: (allow-none): the new billing information for the contact, or %NULL + * + * Sets the #GDataContactsContact:billing-information property to @billing_information. + * + * If @billing_information is %NULL, the contact's billing information will be removed. + * + * Since: 0.7.0 + */ +void +gdata_contacts_contact_set_billing_information (GDataContactsContact *self, const gchar *billing_information) +{ + g_return_if_fail (GDATA_IS_CONTACTS_CONTACT (self)); + g_return_if_fail (billing_information == NULL || *billing_information != '\0'); + + g_free (self->priv->billing_information); + self->priv->billing_information = g_strdup (billing_information); + g_object_notify (G_OBJECT (self), "billing-information"); +} + +/** + * gdata_contacts_contact_get_directory_server: + * @self: a #GDataContactsContact + * + * Gets the #GDataContactsContact:directory-server property. + * + * Return value: the name or address of a directory server associated with the contact, or %NULL + * + * Since: 0.7.0 + */ +const gchar * +gdata_contacts_contact_get_directory_server (GDataContactsContact *self) +{ + g_return_val_if_fail (GDATA_IS_CONTACTS_CONTACT (self), NULL); + return self->priv->directory_server; +} + +/** + * gdata_contacts_contact_set_directory_server: + * @self: a #GDataContactsContact + * @directory_server: (allow-none): the new name or address of a directory server associated with the contact, or %NULL + * + * Sets the #GDataContactsContact:directory-server property to @directory_server. + * + * If @directory_server is %NULL, the contact's directory server will be removed. + * + * Since: 0.7.0 + */ +void +gdata_contacts_contact_set_directory_server (GDataContactsContact *self, const gchar *directory_server) +{ + g_return_if_fail (GDATA_IS_CONTACTS_CONTACT (self)); + g_return_if_fail (directory_server == NULL || *directory_server != '\0'); + + g_free (self->priv->directory_server); + self->priv->directory_server = g_strdup (directory_server); + g_object_notify (G_OBJECT (self), "directory-server"); +} + +/** + * gdata_contacts_contact_get_gender: + * @self: a #GDataContactsContact + * + * Gets the #GDataContactsContact:gender property. + * + * Return value: the gender of the contact, or %NULL + * + * Since: 0.7.0 + */ +const gchar * +gdata_contacts_contact_get_gender (GDataContactsContact *self) +{ + g_return_val_if_fail (GDATA_IS_CONTACTS_CONTACT (self), NULL); + return self->priv->gender; +} + +/** + * gdata_contacts_contact_set_gender: + * @self: a #GDataContactsContact + * @gender: (allow-none): the new gender of the contact, or %NULL + * + * Sets the #GDataContactsContact:gender property to @gender. + * + * If @gender is %NULL, the contact's gender will be removed. + * + * Since: 0.7.0 + */ +void +gdata_contacts_contact_set_gender (GDataContactsContact *self, const gchar *gender) +{ + g_return_if_fail (GDATA_IS_CONTACTS_CONTACT (self)); + g_return_if_fail (gender == NULL || *gender != '\0'); + + g_free (self->priv->gender); + self->priv->gender = g_strdup (gender); + g_object_notify (G_OBJECT (self), "gender"); +} + +/** + * gdata_contacts_contact_get_initials: + * @self: a #GDataContactsContact + * + * Gets the #GDataContactsContact:initials property. + * + * Return value: the initials of the contact, or %NULL + * + * Since: 0.7.0 + */ +const gchar * +gdata_contacts_contact_get_initials (GDataContactsContact *self) +{ + g_return_val_if_fail (GDATA_IS_CONTACTS_CONTACT (self), NULL); + return self->priv->initials; +} + +/** + * gdata_contacts_contact_set_initials: + * @self: a #GDataContactsContact + * @initials: (allow-none): the new initials of the contact, or %NULL + * + * Sets the #GDataContactsContact:initials property to @initials. + * + * If @initials is %NULL, the contact's initials will be removed. + * + * Since: 0.7.0 + */ +void +gdata_contacts_contact_set_initials (GDataContactsContact *self, const gchar *initials) +{ + g_return_if_fail (GDATA_IS_CONTACTS_CONTACT (self)); + + g_free (self->priv->initials); + self->priv->initials = g_strdup (initials); + g_object_notify (G_OBJECT (self), "initials"); +} + +/** + * gdata_contacts_contact_get_maiden_name: + * @self: a #GDataContactsContact + * + * Gets the #GDataContactsContact:maiden-name property. + * + * Return value: the maiden name of the contact, or %NULL + * + * Since: 0.7.0 + */ +const gchar * +gdata_contacts_contact_get_maiden_name (GDataContactsContact *self) +{ + g_return_val_if_fail (GDATA_IS_CONTACTS_CONTACT (self), NULL); + return self->priv->maiden_name; +} + +/** + * gdata_contacts_contact_set_maiden_name: + * @self: a #GDataContactsContact + * @maiden_name: (allow-none): the new maiden name of the contact, or %NULL + * + * Sets the #GDataContactsContact:maiden-name property to @maiden_name. + * + * If @maiden_name is %NULL, the contact's maiden name will be removed. + * + * Since: 0.7.0 + */ +void +gdata_contacts_contact_set_maiden_name (GDataContactsContact *self, const gchar *maiden_name) +{ + g_return_if_fail (GDATA_IS_CONTACTS_CONTACT (self)); + + g_free (self->priv->maiden_name); + self->priv->maiden_name = g_strdup (maiden_name); + g_object_notify (G_OBJECT (self), "maiden-name"); +} + +/** + * gdata_contacts_contact_get_mileage: + * @self: a #GDataContactsContact + * + * Gets the #GDataContactsContact:mileage property. + * + * Return value: a mileage associated with the contact, or %NULL + * + * Since: 0.7.0 + */ +const gchar * +gdata_contacts_contact_get_mileage (GDataContactsContact *self) +{ + g_return_val_if_fail (GDATA_IS_CONTACTS_CONTACT (self), NULL); + return self->priv->mileage; +} + +/** + * gdata_contacts_contact_set_mileage: + * @self: a #GDataContactsContact + * @mileage: (allow-none): the new mileage associated with the contact, or %NULL + * + * Sets the #GDataContactsContact:mileage property to @mileage. + * + * If @mileage is %NULL, the contact's mileage will be removed. + * + * Since: 0.7.0 + */ +void +gdata_contacts_contact_set_mileage (GDataContactsContact *self, const gchar *mileage) +{ + g_return_if_fail (GDATA_IS_CONTACTS_CONTACT (self)); + + g_free (self->priv->mileage); + self->priv->mileage = g_strdup (mileage); + g_object_notify (G_OBJECT (self), "mileage"); +} + +/** + * gdata_contacts_contact_get_occupation: + * @self: a #GDataContactsContact + * + * Gets the #GDataContactsContact:occupation property. + * + * Return value: the contact's occupation, or %NULL + * + * Since: 0.7.0 + */ +const gchar * +gdata_contacts_contact_get_occupation (GDataContactsContact *self) +{ + g_return_val_if_fail (GDATA_IS_CONTACTS_CONTACT (self), NULL); + return self->priv->occupation; +} + +/** + * gdata_contacts_contact_set_occupation: + * @self: a #GDataContactsContact + * @occupation: (allow-none): the contact's new occupation, or %NULL + * + * Sets the #GDataContactsContact:occupation property to @occupation. + * + * If @occupation is %NULL, the contact's occupation will be removed. + * + * Since: 0.7.0 + */ +void +gdata_contacts_contact_set_occupation (GDataContactsContact *self, const gchar *occupation) +{ + g_return_if_fail (GDATA_IS_CONTACTS_CONTACT (self)); + + g_free (self->priv->occupation); + self->priv->occupation = g_strdup (occupation); + g_object_notify (G_OBJECT (self), "occupation"); +} + +/** + * gdata_contacts_contact_get_priority: + * @self: a #GDataContactsContact + * + * Gets the #GDataContactsContact:priority property. + * + * Return value: the contact's priority, or %NULL + * + * Since: 0.7.0 + */ +const gchar * +gdata_contacts_contact_get_priority (GDataContactsContact *self) +{ + g_return_val_if_fail (GDATA_IS_CONTACTS_CONTACT (self), NULL); + return self->priv->priority; +} + +/** + * gdata_contacts_contact_set_priority: + * @self: a #GDataContactsContact + * @priority: (allow-none): the contact's new priority, or %NULL + * + * Sets the #GDataContactsContact:priority property to @priority. + * + * If @priority is %NULL, the contact's priority will be removed. + * + * Since: 0.7.0 + */ +void +gdata_contacts_contact_set_priority (GDataContactsContact *self, const gchar *priority) +{ + g_return_if_fail (GDATA_IS_CONTACTS_CONTACT (self)); + g_return_if_fail (priority == NULL || *priority != '\0'); + + g_free (self->priv->priority); + self->priv->priority = g_strdup (priority); + g_object_notify (G_OBJECT (self), "priority"); +} + +/** + * gdata_contacts_contact_get_sensitivity: + * @self: a #GDataContactsContact + * + * Gets the #GDataContactsContact:sensitivity property. + * + * Return value: the contact's sensitivity, or %NULL + * + * Since: 0.7.0 + */ +const gchar * +gdata_contacts_contact_get_sensitivity (GDataContactsContact *self) +{ + g_return_val_if_fail (GDATA_IS_CONTACTS_CONTACT (self), NULL); + return self->priv->sensitivity; +} + +/** + * gdata_contacts_contact_set_sensitivity: + * @self: a #GDataContactsContact + * @sensitivity: (allow-none): the contact's new sensitivity, or %NULL + * + * Sets the #GDataContactsContact:sensitivity property to @sensitivity. + * + * If @sensitivity is %NULL, the contact's sensitivity will be removed. + * + * Since: 0.7.0 + */ +void +gdata_contacts_contact_set_sensitivity (GDataContactsContact *self, const gchar *sensitivity) +{ + g_return_if_fail (GDATA_IS_CONTACTS_CONTACT (self)); + g_return_if_fail (sensitivity == NULL || *sensitivity != '\0'); + + g_free (self->priv->sensitivity); + self->priv->sensitivity = g_strdup (sensitivity); + g_object_notify (G_OBJECT (self), "sensitivity"); +} + +/** + * gdata_contacts_contact_get_short_name: + * @self: a #GDataContactsContact + * + * Gets the #GDataContactsContact:short-name property. + * + * Return value: the contact's short name, or %NULL + * + * Since: 0.7.0 + */ +const gchar * +gdata_contacts_contact_get_short_name (GDataContactsContact *self) +{ + g_return_val_if_fail (GDATA_IS_CONTACTS_CONTACT (self), NULL); + return self->priv->short_name; +} + +/** + * gdata_contacts_contact_set_short_name: + * @self: a #GDataContactsContact + * @short_name: (allow-none): the contact's new short name, or %NULL + * + * Sets the #GDataContactsContact:short-name property to @short_name. + * + * If @short_name is %NULL, the contact's short name will be removed. + * + * Since: 0.7.0 + */ +void +gdata_contacts_contact_set_short_name (GDataContactsContact *self, const gchar *short_name) +{ + g_return_if_fail (GDATA_IS_CONTACTS_CONTACT (self)); + + g_free (self->priv->short_name); + self->priv->short_name = g_strdup (short_name); + g_object_notify (G_OBJECT (self), "short-name"); +} + +/** + * gdata_contacts_contact_get_subject: + * @self: a #GDataContactsContact + * + * Gets the #GDataContactsContact:subject property. + * + * Return value: the contact's subject, or %NULL + * + * Since: 0.7.0 + */ +const gchar * +gdata_contacts_contact_get_subject (GDataContactsContact *self) +{ + g_return_val_if_fail (GDATA_IS_CONTACTS_CONTACT (self), NULL); + return self->priv->subject; +} + +/** + * gdata_contacts_contact_set_subject: + * @self: a #GDataContactsContact + * @subject: (allow-none): the contact's new subject, or %NULL + * + * Sets the #GDataContactsContact:subject property to @subject. + * + * If @subject is %NULL, the contact's subject will be removed. + * + * Since: 0.7.0 + */ +void +gdata_contacts_contact_set_subject (GDataContactsContact *self, const gchar *subject) +{ + g_return_if_fail (GDATA_IS_CONTACTS_CONTACT (self)); + + g_free (self->priv->subject); + self->priv->subject = g_strdup (subject); + g_object_notify (G_OBJECT (self), "subject"); +} + +/** + * gdata_contacts_contact_add_email_address: + * @self: a #GDataContactsContact + * @email_address: a #GDataGDEmailAddress to add + * + * Adds an e-mail address to the contact's list of e-mail addresses and increments its reference count. + * + * Note that only one e-mail address per contact may be marked as "primary". Insertion and update operations + * (with gdata_contacts_service_insert_contact()) will return an error if more than one e-mail address + * is marked as primary. + * + * Duplicate e-mail addresses will not be added to the list. + * + * Since: 0.2.0 + */ +void +gdata_contacts_contact_add_email_address (GDataContactsContact *self, GDataGDEmailAddress *email_address) +{ + g_return_if_fail (GDATA_IS_CONTACTS_CONTACT (self)); + g_return_if_fail (GDATA_IS_GD_EMAIL_ADDRESS (email_address)); + + if (g_list_find_custom (self->priv->email_addresses, email_address, (GCompareFunc) gdata_comparable_compare) == NULL) + self->priv->email_addresses = g_list_append (self->priv->email_addresses, g_object_ref (email_address)); +} + +/** + * gdata_contacts_contact_get_email_addresses: + * @self: a #GDataContactsContact + * + * Gets a list of the e-mail addresses owned by the contact. + * + * Return value: (element-type GData.GDEmailAddress) (transfer none): a #GList of #GDataGDEmailAddresses, or %NULL + * + * Since: 0.2.0 + */ +GList * +gdata_contacts_contact_get_email_addresses (GDataContactsContact *self) +{ + g_return_val_if_fail (GDATA_IS_CONTACTS_CONTACT (self), NULL); + return self->priv->email_addresses; +} + +/** + * gdata_contacts_contact_get_primary_email_address: + * @self: a #GDataContactsContact + * + * Gets the contact's primary e-mail address, if one exists. + * + * Return value: (transfer none): a #GDataGDEmailAddress, or %NULL + * + * Since: 0.2.0 + */ +GDataGDEmailAddress * +gdata_contacts_contact_get_primary_email_address (GDataContactsContact *self) +{ + GList *i; + + g_return_val_if_fail (GDATA_IS_CONTACTS_CONTACT (self), NULL); + + for (i = self->priv->email_addresses; i != NULL; i = i->next) { + if (gdata_gd_email_address_is_primary (GDATA_GD_EMAIL_ADDRESS (i->data)) == TRUE) + return GDATA_GD_EMAIL_ADDRESS (i->data); + } + + return NULL; +} + +/** + * gdata_contacts_contact_remove_all_email_addresses: + * @self: a #GDataContactsContact + * + * Removes all e-mail addresses from the contact. + * + * Since: 0.4.0 + */ +void +gdata_contacts_contact_remove_all_email_addresses (GDataContactsContact *self) +{ + GDataContactsContactPrivate *priv = self->priv; + + g_return_if_fail (GDATA_IS_CONTACTS_CONTACT (self)); + + g_list_free_full (priv->email_addresses, g_object_unref); + priv->email_addresses = NULL; +} + +/** + * gdata_contacts_contact_add_im_address: + * @self: a #GDataContactsContact + * @im_address: a #GDataGDIMAddress to add + * + * Adds an IM (instant messaging) address to the contact's list of IM addresses and increments its reference count. + * + * Note that only one IM address per contact may be marked as "primary". Insertion and update operations + * (with gdata_contacts_service_insert_contact()) will return an error if more than one IM address + * is marked as primary. + * + * Duplicate IM addresses will not be added to the list. + * + * Since: 0.2.0 + */ +void +gdata_contacts_contact_add_im_address (GDataContactsContact *self, GDataGDIMAddress *im_address) +{ + g_return_if_fail (GDATA_IS_CONTACTS_CONTACT (self)); + g_return_if_fail (GDATA_IS_GD_IM_ADDRESS (im_address)); + + if (g_list_find_custom (self->priv->im_addresses, im_address, (GCompareFunc) gdata_comparable_compare) == NULL) + self->priv->im_addresses = g_list_append (self->priv->im_addresses, g_object_ref (im_address)); +} + +/** + * gdata_contacts_contact_get_im_addresses: + * @self: a #GDataContactsContact + * + * Gets a list of the IM addresses owned by the contact. + * + * Return value: (element-type GData.GDIMAddress) (transfer none): a #GList of #GDataGDIMAddresses, or %NULL + * + * Since: 0.2.0 + */ +GList * +gdata_contacts_contact_get_im_addresses (GDataContactsContact *self) +{ + g_return_val_if_fail (GDATA_IS_CONTACTS_CONTACT (self), NULL); + return self->priv->im_addresses; +} + +/** + * gdata_contacts_contact_get_primary_im_address: + * @self: a #GDataContactsContact + * + * Gets the contact's primary IM address, if one exists. + * + * Return value: (transfer none): a #GDataGDIMAddress, or %NULL + * + * Since: 0.2.0 + */ +GDataGDIMAddress * +gdata_contacts_contact_get_primary_im_address (GDataContactsContact *self) +{ + GList *i; + + g_return_val_if_fail (GDATA_IS_CONTACTS_CONTACT (self), NULL); + + for (i = self->priv->im_addresses; i != NULL; i = i->next) { + if (gdata_gd_im_address_is_primary (GDATA_GD_IM_ADDRESS (i->data)) == TRUE) + return GDATA_GD_IM_ADDRESS (i->data); + } + + return NULL; +} + +/** + * gdata_contacts_contact_remove_all_im_addresses: + * @self: a #GDataContactsContact + * + * Removes all IM addresses from the contact. + * + * Since: 0.4.0 + */ +void +gdata_contacts_contact_remove_all_im_addresses (GDataContactsContact *self) +{ + GDataContactsContactPrivate *priv = self->priv; + + g_return_if_fail (GDATA_IS_CONTACTS_CONTACT (self)); + + g_list_free_full (priv->im_addresses, g_object_unref); + priv->im_addresses = NULL; +} + +/** + * gdata_contacts_contact_add_phone_number: + * @self: a #GDataContactsContact + * @phone_number: a #GDataGDPhoneNumber to add + * + * Adds a phone number to the contact's list of phone numbers and increments its reference count + * + * Note that only one phone number per contact may be marked as "primary". Insertion and update operations + * (with gdata_contacts_service_insert_contact()) will return an error if more than one phone number + * is marked as primary. + * + * Duplicate phone numbers will not be added to the list. + * + * Since: 0.2.0 + */ +void +gdata_contacts_contact_add_phone_number (GDataContactsContact *self, GDataGDPhoneNumber *phone_number) +{ + g_return_if_fail (GDATA_IS_CONTACTS_CONTACT (self)); + g_return_if_fail (GDATA_IS_GD_PHONE_NUMBER (phone_number)); + + if (g_list_find_custom (self->priv->phone_numbers, phone_number, (GCompareFunc) gdata_comparable_compare) == NULL) + self->priv->phone_numbers = g_list_append (self->priv->phone_numbers, g_object_ref (phone_number)); +} + +/** + * gdata_contacts_contact_get_phone_numbers: + * @self: a #GDataContactsContact + * + * Gets a list of the phone numbers owned by the contact. + * + * Return value: (element-type GData.GDPhoneNumber) (transfer none): a #GList of #GDataGDPhoneNumbers, or %NULL + * + * Since: 0.2.0 + */ +GList * +gdata_contacts_contact_get_phone_numbers (GDataContactsContact *self) +{ + g_return_val_if_fail (GDATA_IS_CONTACTS_CONTACT (self), NULL); + return self->priv->phone_numbers; +} + +/** + * gdata_contacts_contact_get_primary_phone_number: + * @self: a #GDataContactsContact + * + * Gets the contact's primary phone number, if one exists. + * + * Return value: (transfer none): a #GDataGDPhoneNumber, or %NULL + * + * Since: 0.2.0 + */ +GDataGDPhoneNumber * +gdata_contacts_contact_get_primary_phone_number (GDataContactsContact *self) +{ + GList *i; + + g_return_val_if_fail (GDATA_IS_CONTACTS_CONTACT (self), NULL); + + for (i = self->priv->phone_numbers; i != NULL; i = i->next) { + if (gdata_gd_phone_number_is_primary (GDATA_GD_PHONE_NUMBER (i->data)) == TRUE) + return GDATA_GD_PHONE_NUMBER (i->data); + } + + return NULL; +} + +/** + * gdata_contacts_contact_remove_all_phone_numbers: + * @self: a #GDataContactsContact + * + * Removes all phone numbers from the contact. + * + * Since: 0.4.0 + */ +void +gdata_contacts_contact_remove_all_phone_numbers (GDataContactsContact *self) +{ + GDataContactsContactPrivate *priv = self->priv; + + g_return_if_fail (GDATA_IS_CONTACTS_CONTACT (self)); + + g_list_free_full (priv->phone_numbers, g_object_unref); + priv->phone_numbers = NULL; +} + +/** + * gdata_contacts_contact_add_postal_address: + * @self: a #GDataContactsContact + * @postal_address: a #GDataGDPostalAddress to add + * + * Adds a postal address to the contact's list of postal addresses and increments its reference count. + * + * Note that only one postal address per contact may be marked as "primary". Insertion and update operations + * (with gdata_contacts_service_insert_contact()) will return an error if more than one postal address + * is marked as primary. + * + * Duplicate postal addresses will not be added to the list. + * + * Since: 0.2.0 + */ +void +gdata_contacts_contact_add_postal_address (GDataContactsContact *self, GDataGDPostalAddress *postal_address) +{ + g_return_if_fail (GDATA_IS_CONTACTS_CONTACT (self)); + g_return_if_fail (GDATA_IS_GD_POSTAL_ADDRESS (postal_address)); + + if (g_list_find_custom (self->priv->postal_addresses, postal_address, (GCompareFunc) gdata_comparable_compare) == NULL) + self->priv->postal_addresses = g_list_append (self->priv->postal_addresses, g_object_ref (postal_address)); +} + +/** + * gdata_contacts_contact_get_postal_addresses: + * @self: a #GDataContactsContact + * + * Gets a list of the postal addresses owned by the contact. + * + * Return value: (element-type GData.GDPostalAddress) (transfer none): a #GList of #GDataGDPostalAddresses, or %NULL + * + * Since: 0.2.0 + */ +GList * +gdata_contacts_contact_get_postal_addresses (GDataContactsContact *self) +{ + g_return_val_if_fail (GDATA_IS_CONTACTS_CONTACT (self), NULL); + return self->priv->postal_addresses; +} + +/** + * gdata_contacts_contact_get_primary_postal_address: + * @self: a #GDataContactsContact + * + * Gets the contact's primary postal address, if one exists. + * + * Return value: (transfer none): a #GDataGDPostalAddress, or %NULL + * + * Since: 0.2.0 + */ +GDataGDPostalAddress * +gdata_contacts_contact_get_primary_postal_address (GDataContactsContact *self) +{ + GList *i; + + g_return_val_if_fail (GDATA_IS_CONTACTS_CONTACT (self), NULL); + + for (i = self->priv->postal_addresses; i != NULL; i = i->next) { + if (gdata_gd_postal_address_is_primary (GDATA_GD_POSTAL_ADDRESS (i->data)) == TRUE) + return GDATA_GD_POSTAL_ADDRESS (i->data); + } + + return NULL; +} + +/** + * gdata_contacts_contact_remove_all_postal_addresses: + * @self: a #GDataContactsContact + * + * Removes all postal addresses from the contact. + * + * Since: 0.4.0 + */ +void +gdata_contacts_contact_remove_all_postal_addresses (GDataContactsContact *self) +{ + GDataContactsContactPrivate *priv = self->priv; + + g_return_if_fail (GDATA_IS_CONTACTS_CONTACT (self)); + + g_list_free_full (priv->postal_addresses, g_object_unref); + priv->postal_addresses = NULL; +} + +/** + * gdata_contacts_contact_add_organization: + * @self: a #GDataContactsContact + * @organization: a #GDataGDOrganization to add + * + * Adds an organization to the contact's list of organizations (e.g. employers) and increments its reference count. + * + * Note that only one organization per contact may be marked as "primary". Insertion and update operations + * (with gdata_contacts_service_insert_contact()) will return an error if more than one organization + * is marked as primary. + * + * Duplicate organizations will not be added to the list. + * + * Since: 0.2.0 + */ +void +gdata_contacts_contact_add_organization (GDataContactsContact *self, GDataGDOrganization *organization) +{ + g_return_if_fail (GDATA_IS_CONTACTS_CONTACT (self)); + g_return_if_fail (organization != NULL); + + if (g_list_find_custom (self->priv->organizations, organization, (GCompareFunc) gdata_comparable_compare) == NULL) + self->priv->organizations = g_list_append (self->priv->organizations, g_object_ref (organization)); +} + +/** + * gdata_contacts_contact_get_organizations: + * @self: a #GDataContactsContact + * + * Gets a list of the organizations to which the contact belongs. + * + * Return value: (element-type GData.GDOrganization) (transfer none): a #GList of #GDataGDOrganizations, or %NULL + * + * Since: 0.2.0 + */ +GList * +gdata_contacts_contact_get_organizations (GDataContactsContact *self) +{ + g_return_val_if_fail (GDATA_IS_CONTACTS_CONTACT (self), NULL); + return self->priv->organizations; +} + +/** + * gdata_contacts_contact_get_primary_organization: + * @self: a #GDataContactsContact + * + * Gets the contact's primary organization, if one exists. + * + * Return value: (transfer none): a #GDataGDOrganization, or %NULL + * + * Since: 0.2.0 + */ +GDataGDOrganization * +gdata_contacts_contact_get_primary_organization (GDataContactsContact *self) +{ + GList *i; + + g_return_val_if_fail (GDATA_IS_CONTACTS_CONTACT (self), NULL); + + for (i = self->priv->organizations; i != NULL; i = i->next) { + if (gdata_gd_organization_is_primary (GDATA_GD_ORGANIZATION (i->data)) == TRUE) + return GDATA_GD_ORGANIZATION (i->data); + } + + return NULL; +} + +/** + * gdata_contacts_contact_remove_all_organizations: + * @self: a #GDataContactsContact + * + * Removes all organizations from the contact. + * + * Since: 0.4.0 + */ +void +gdata_contacts_contact_remove_all_organizations (GDataContactsContact *self) +{ + GDataContactsContactPrivate *priv = self->priv; + + g_return_if_fail (GDATA_IS_CONTACTS_CONTACT (self)); + + g_list_free_full (priv->organizations, g_object_unref); + priv->organizations = NULL; +} + +/** + * gdata_contacts_contact_add_jot: + * @self: a #GDataContactsContact + * @jot: a #GDataGContactJot to add + * + * Adds a jot to the contact's list of jots and increments its reference count. + * + * Duplicate jots will be added to the list, and multiple jots with the same relation type can be added to a single contact. + * + * Since: 0.7.0 + */ +void +gdata_contacts_contact_add_jot (GDataContactsContact *self, GDataGContactJot *jot) +{ + g_return_if_fail (GDATA_IS_CONTACTS_CONTACT (self)); + g_return_if_fail (GDATA_IS_GCONTACT_JOT (jot)); + + self->priv->jots = g_list_append (self->priv->jots, g_object_ref (jot)); +} + +/** + * gdata_contacts_contact_get_jots: + * @self: a #GDataContactsContact + * + * Gets a list of the jots attached to the contact. + * + * Return value: (element-type GData.GContactJot) (transfer none): a #GList of #GDataGContactJots, or %NULL + * + * Since: 0.7.0 + */ +GList * +gdata_contacts_contact_get_jots (GDataContactsContact *self) +{ + g_return_val_if_fail (GDATA_IS_CONTACTS_CONTACT (self), NULL); + return self->priv->jots; +} + +/** + * gdata_contacts_contact_remove_all_jots: + * @self: a #GDataContactsContact + * + * Removes all jots from the contact. + * + * Since: 0.7.0 + */ +void +gdata_contacts_contact_remove_all_jots (GDataContactsContact *self) +{ + GDataContactsContactPrivate *priv = self->priv; + + g_return_if_fail (GDATA_IS_CONTACTS_CONTACT (self)); + + g_list_free_full (priv->jots, g_object_unref); + priv->jots = NULL; +} + +/** + * gdata_contacts_contact_add_relation: + * @self: a #GDataContactsContact + * @relation: a #GDataGContactRelation to add + * + * Adds a relation to the contact's list of relations and increments its reference count. + * + * Duplicate relations will be added to the list, and multiple relations with the same relation type can be added to a single contact. + * Though it may not make sense for some relation types to be repeated, adding them is allowed. + * + * Since: 0.7.0 + */ +void +gdata_contacts_contact_add_relation (GDataContactsContact *self, GDataGContactRelation *relation) +{ + g_return_if_fail (GDATA_IS_CONTACTS_CONTACT (self)); + g_return_if_fail (GDATA_IS_GCONTACT_RELATION (relation)); + + self->priv->relations = g_list_append (self->priv->relations, g_object_ref (relation)); +} + +/** + * gdata_contacts_contact_get_relations: + * @self: a #GDataContactsContact + * + * Gets a list of the relations of the contact. + * + * Return value: (element-type GData.GContactRelation) (transfer none): a #GList of #GDataGContactRelations, or %NULL + * + * Since: 0.7.0 + */ +GList * +gdata_contacts_contact_get_relations (GDataContactsContact *self) +{ + g_return_val_if_fail (GDATA_IS_CONTACTS_CONTACT (self), NULL); + return self->priv->relations; +} + +/** + * gdata_contacts_contact_remove_all_relations: + * @self: a #GDataContactsContact + * + * Removes all relations from the contact. + * + * Since: 0.7.0 + */ +void +gdata_contacts_contact_remove_all_relations (GDataContactsContact *self) +{ + GDataContactsContactPrivate *priv = self->priv; + + g_return_if_fail (GDATA_IS_CONTACTS_CONTACT (self)); + + g_list_free_full (priv->relations, g_object_unref); + priv->relations = NULL; +} + +/** + * gdata_contacts_contact_add_website: + * @self: a #GDataContactsContact + * @website: a #GDataGContactWebsite to add + * + * Adds a website to the contact's list of websites and increments its reference count. + * + * Duplicate websites will not be added to the list, though the same URI may appear in several #GDataGContactWebsites with different + * relation types or labels. + * + * Since: 0.7.0 + */ +void +gdata_contacts_contact_add_website (GDataContactsContact *self, GDataGContactWebsite *website) +{ + g_return_if_fail (GDATA_IS_CONTACTS_CONTACT (self)); + g_return_if_fail (GDATA_IS_GCONTACT_WEBSITE (website)); + + if (g_list_find_custom (self->priv->websites, website, (GCompareFunc) gdata_comparable_compare) == NULL) + self->priv->websites = g_list_append (self->priv->websites, g_object_ref (website)); +} + +/** + * gdata_contacts_contact_get_websites: + * @self: a #GDataContactsContact + * + * Gets a list of the websites of the contact. + * + * Return value: (element-type GData.GContactWebsite) (transfer none): a #GList of #GDataGContactWebsites, or %NULL + * + * Since: 0.7.0 + */ +GList * +gdata_contacts_contact_get_websites (GDataContactsContact *self) +{ + g_return_val_if_fail (GDATA_IS_CONTACTS_CONTACT (self), NULL); + return self->priv->websites; +} + +/** + * gdata_contacts_contact_get_primary_website: + * @self: a #GDataContactsContact + * + * Gets the contact's primary website, if one exists. + * + * Return value: (transfer none): a #GDataGContactWebsite, or %NULL + * + * Since: 0.7.0 + */ +GDataGContactWebsite * +gdata_contacts_contact_get_primary_website (GDataContactsContact *self) +{ + GList *i; + + g_return_val_if_fail (GDATA_IS_CONTACTS_CONTACT (self), NULL); + + for (i = self->priv->websites; i != NULL; i = i->next) { + if (gdata_gcontact_website_is_primary (GDATA_GCONTACT_WEBSITE (i->data)) == TRUE) + return GDATA_GCONTACT_WEBSITE (i->data); + } + + return NULL; +} + +/** + * gdata_contacts_contact_remove_all_websites: + * @self: a #GDataContactsContact + * + * Removes all websites from the contact. + * + * Since: 0.7.0 + */ +void +gdata_contacts_contact_remove_all_websites (GDataContactsContact *self) +{ + GDataContactsContactPrivate *priv = self->priv; + + g_return_if_fail (GDATA_IS_CONTACTS_CONTACT (self)); + + g_list_free_full (priv->websites, g_object_unref); + priv->websites = NULL; +} + +/** + * gdata_contacts_contact_add_event: + * @self: a #GDataContactsContact + * @event: a #GDataGContactEvent to add + * + * Adds an event to the contact's list of events and increments its reference count. + * + * Duplicate events will be added to the list, and multiple events with the same event type can be added to a single contact. + * Though it may not make sense for some event types to be repeated, adding them is allowed. + * + * Since: 0.7.0 + */ +void +gdata_contacts_contact_add_event (GDataContactsContact *self, GDataGContactEvent *event) +{ + g_return_if_fail (GDATA_IS_CONTACTS_CONTACT (self)); + g_return_if_fail (GDATA_IS_GCONTACT_EVENT (event)); + + self->priv->events = g_list_append (self->priv->events, g_object_ref (event)); +} + +/** + * gdata_contacts_contact_get_events: + * @self: a #GDataContactsContact + * + * Gets a list of the events of the contact. + * + * Return value: (element-type GData.GContactEvent) (transfer none): a #GList of #GDataGContactEvents, or %NULL + * + * Since: 0.7.0 + */ +GList * +gdata_contacts_contact_get_events (GDataContactsContact *self) +{ + g_return_val_if_fail (GDATA_IS_CONTACTS_CONTACT (self), NULL); + return self->priv->events; +} + +/** + * gdata_contacts_contact_remove_all_events: + * @self: a #GDataContactsContact + * + * Removes all events from the contact. + * + * Since: 0.7.0 + */ +void +gdata_contacts_contact_remove_all_events (GDataContactsContact *self) +{ + GDataContactsContactPrivate *priv = self->priv; + + g_return_if_fail (GDATA_IS_CONTACTS_CONTACT (self)); + + g_list_free_full (priv->events, g_object_unref); + priv->events = NULL; +} + +/** + * gdata_contacts_contact_add_calendar: + * @self: a #GDataContactsContact + * @calendar: a #GDataGContactCalendar to add + * + * Adds a calendar to the contact's list of calendars and increments its reference count. + * + * Duplicate calendars will not be added to the list, though the same URI may appear in several #GDataGContactCalendars with different + * relation types or labels. + * + * Since: 0.7.0 + */ +void +gdata_contacts_contact_add_calendar (GDataContactsContact *self, GDataGContactCalendar *calendar) +{ + g_return_if_fail (GDATA_IS_CONTACTS_CONTACT (self)); + g_return_if_fail (GDATA_IS_GCONTACT_CALENDAR (calendar)); + + if (g_list_find_custom (self->priv->calendars, calendar, (GCompareFunc) gdata_comparable_compare) == NULL) + self->priv->calendars = g_list_append (self->priv->calendars, g_object_ref (calendar)); +} + +/** + * gdata_contacts_contact_get_calendars: + * @self: a #GDataContactsContact + * + * Gets a list of the calendars of the contact. + * + * Return value: (element-type GData.GContactCalendar) (transfer none): a #GList of #GDataGContactCalendars, or %NULL + * + * Since: 0.7.0 + */ +GList * +gdata_contacts_contact_get_calendars (GDataContactsContact *self) +{ + g_return_val_if_fail (GDATA_IS_CONTACTS_CONTACT (self), NULL); + return self->priv->calendars; +} + +/** + * gdata_contacts_contact_get_primary_calendar: + * @self: a #GDataContactsContact + * + * Gets the contact's primary calendar, if one exists. + * + * Return value: (transfer none): a #GDataGContactCalendar, or %NULL + * + * Since: 0.7.0 + */ +GDataGContactCalendar * +gdata_contacts_contact_get_primary_calendar (GDataContactsContact *self) +{ + GList *i; + + g_return_val_if_fail (GDATA_IS_CONTACTS_CONTACT (self), NULL); + + for (i = self->priv->calendars; i != NULL; i = i->next) { + if (gdata_gcontact_calendar_is_primary (GDATA_GCONTACT_CALENDAR (i->data)) == TRUE) + return GDATA_GCONTACT_CALENDAR (i->data); + } + + return NULL; +} + +/** + * gdata_contacts_contact_remove_all_calendars: + * @self: a #GDataContactsContact + * + * Removes all calendars from the contact. + * + * Since: 0.7.0 + */ +void +gdata_contacts_contact_remove_all_calendars (GDataContactsContact *self) +{ + GDataContactsContactPrivate *priv = self->priv; + + g_return_if_fail (GDATA_IS_CONTACTS_CONTACT (self)); + + g_list_free_full (priv->calendars, g_object_unref); + priv->calendars = NULL; +} + +/** + * gdata_contacts_contact_add_external_id: + * @self: a #GDataContactsContact + * @external_id: a #GDataGContactExternalID to add + * + * Adds an external ID to the contact's list of external IDs and increments its reference count. + * + * Duplicate IDs will not be added to the list. + * + * Since: 0.7.0 + */ +void +gdata_contacts_contact_add_external_id (GDataContactsContact *self, GDataGContactExternalID *external_id) +{ + g_return_if_fail (GDATA_IS_CONTACTS_CONTACT (self)); + g_return_if_fail (GDATA_IS_GCONTACT_EXTERNAL_ID (external_id)); + + if (g_list_find_custom (self->priv->external_ids, external_id, (GCompareFunc) gdata_comparable_compare) == NULL) + self->priv->external_ids = g_list_append (self->priv->external_ids, g_object_ref (external_id)); +} + +/** + * gdata_contacts_contact_get_external_ids: + * @self: a #GDataContactsContact + * + * Gets a list of the external IDs of the contact. + * + * Return value: (element-type GData.GContactExternalID) (transfer none): a #GList of #GDataGContactExternalIDs, or %NULL + * + * Since: 0.7.0 + */ +GList * +gdata_contacts_contact_get_external_ids (GDataContactsContact *self) +{ + g_return_val_if_fail (GDATA_IS_CONTACTS_CONTACT (self), NULL); + return self->priv->external_ids; +} + +/** + * gdata_contacts_contact_remove_all_external_ids: + * @self: a #GDataContactsContact + * + * Removes all external IDs from the contact. + * + * Since: 0.7.0 + */ +void +gdata_contacts_contact_remove_all_external_ids (GDataContactsContact *self) +{ + GDataContactsContactPrivate *priv = self->priv; + + g_return_if_fail (GDATA_IS_CONTACTS_CONTACT (self)); + + g_list_free_full (priv->external_ids, g_object_unref); + priv->external_ids = NULL; +} + +/** + * gdata_contacts_contact_add_hobby: + * @self: a #GDataContactsContact + * @hobby: a hobby to add + * + * Adds a hobby to the contact's list of hobbies, copying it in the process. + * + * Duplicate hobbies will not be added to the list. + * + * Since: 0.7.0 + */ +void +gdata_contacts_contact_add_hobby (GDataContactsContact *self, const gchar *hobby) +{ + g_return_if_fail (GDATA_IS_CONTACTS_CONTACT (self)); + g_return_if_fail (hobby != NULL && *hobby != '\0'); + + if (g_list_find_custom (self->priv->hobbies, hobby, (GCompareFunc) g_strcmp0) == NULL) + self->priv->hobbies = g_list_append (self->priv->hobbies, g_strdup (hobby)); +} + +/** + * gdata_contacts_contact_get_hobbies: + * @self: a #GDataContactsContact + * + * Gets a list of the hobbies of the contact. + * + * Return value: (element-type utf8) (transfer none): a #GList of hobby strings, or %NULL + * + * Since: 0.7.0 + */ +GList * +gdata_contacts_contact_get_hobbies (GDataContactsContact *self) +{ + g_return_val_if_fail (GDATA_IS_CONTACTS_CONTACT (self), NULL); + return self->priv->hobbies; +} + +/** + * gdata_contacts_contact_remove_all_hobbies: + * @self: a #GDataContactsContact + * + * Removes all hobbies from the contact. + * + * Since: 0.7.0 + */ +void +gdata_contacts_contact_remove_all_hobbies (GDataContactsContact *self) +{ + GDataContactsContactPrivate *priv = self->priv; + + g_return_if_fail (GDATA_IS_CONTACTS_CONTACT (self)); + + g_list_free_full (priv->hobbies, g_free); + priv->hobbies = NULL; +} + +/** + * gdata_contacts_contact_add_language: + * @self: a #GDataContactsContact + * @language: a #GDataGContactLanguage to add + * + * Adds a language to the contact's list of languages and increments its reference count. + * + * Duplicate languages will not be added to the list. + * + * Since: 0.7.0 + */ +void +gdata_contacts_contact_add_language (GDataContactsContact *self, GDataGContactLanguage *language) +{ + g_return_if_fail (GDATA_IS_CONTACTS_CONTACT (self)); + g_return_if_fail (GDATA_IS_GCONTACT_LANGUAGE (language)); + + if (g_list_find_custom (self->priv->languages, language, (GCompareFunc) gdata_comparable_compare) == NULL) + self->priv->languages = g_list_append (self->priv->languages, g_object_ref (language)); +} + +/** + * gdata_contacts_contact_get_languages: + * @self: a #GDataContactsContact + * + * Gets a list of the languages of the contact. + * + * Return value: (element-type GData.GContactLanguage) (transfer none): a #GList of #GDataGContactLanguages, or %NULL + * + * Since: 0.7.0 + */ +GList * +gdata_contacts_contact_get_languages (GDataContactsContact *self) +{ + g_return_val_if_fail (GDATA_IS_CONTACTS_CONTACT (self), NULL); + return self->priv->languages; +} + +/** + * gdata_contacts_contact_remove_all_languages: + * @self: a #GDataContactsContact + * + * Removes all languages from the contact. + * + * Since: 0.7.0 + */ +void +gdata_contacts_contact_remove_all_languages (GDataContactsContact *self) +{ + GDataContactsContactPrivate *priv = self->priv; + + g_return_if_fail (GDATA_IS_CONTACTS_CONTACT (self)); + + g_list_free_full (priv->languages, g_object_unref); + priv->languages = NULL; +} + +/** + * gdata_contacts_contact_get_extended_property: + * @self: a #GDataContactsContact + * @name: the property name; an arbitrary, unique string + * + * Gets the value of an extended property of the contact. Each contact can have up to 10 client-set extended + * properties to store data of the client's choosing. + * + * Return value: the property's value, or %NULL + * + * Since: 0.2.0 + */ +const gchar * +gdata_contacts_contact_get_extended_property (GDataContactsContact *self, const gchar *name) +{ + g_return_val_if_fail (GDATA_IS_CONTACTS_CONTACT (self), NULL); + g_return_val_if_fail (name != NULL && *name != '\0', NULL); + return g_hash_table_lookup (self->priv->extended_properties, name); +} + +/** + * gdata_contacts_contact_get_extended_properties: + * @self: a #GDataContactsContact + * + * Gets the full list of extended properties of the contact; a hash table mapping property name to value. + * + * Return value: (transfer none): a #GHashTable of extended properties + * + * Since: 0.4.0 + */ +GHashTable * +gdata_contacts_contact_get_extended_properties (GDataContactsContact *self) +{ + g_return_val_if_fail (GDATA_IS_CONTACTS_CONTACT (self), NULL); + return self->priv->extended_properties; +} + +/** + * gdata_contacts_contact_set_extended_property: + * @self: a #GDataContactsContact + * @name: the property name; an arbitrary, unique string + * @value: (allow-none): the property value, or %NULL + * + * Sets the value of a contact's extended property. Extended property names are unique (but of the client's choosing), + * and reusing the same property name will result in the old value of that property being overwritten. + * + * To unset a property, set @value to %NULL or an empty string. + * + * A contact may have up to 10 extended properties, and each should be reasonably small (i.e. not a photo or ringtone). + * For more information, see the online documentation. + * %FALSE will be returned if you attempt to add more than 10 extended properties. + * + * Return value: %TRUE if the property was updated or deleted successfully, %FALSE otherwise + * + * Since: 0.2.0 + */ +gboolean +gdata_contacts_contact_set_extended_property (GDataContactsContact *self, const gchar *name, const gchar *value) +{ + GHashTable *extended_properties = self->priv->extended_properties; + + g_return_val_if_fail (GDATA_IS_CONTACTS_CONTACT (self), FALSE); + g_return_val_if_fail (name != NULL && *name != '\0', FALSE); + + if (value == NULL || *value == '\0') { + /* Removing a property */ + g_hash_table_remove (extended_properties, name); + return TRUE; + } + + /* We can't add more than MAX_N_EXTENDED_PROPERTIES */ + if (g_hash_table_lookup (extended_properties, name) == NULL && + g_hash_table_size (extended_properties) >= MAX_N_EXTENDED_PROPERTIES) + return FALSE; + + /* Updating an existing property or adding a new one */ + g_hash_table_insert (extended_properties, g_strdup (name), g_strdup (value)); + + return TRUE; +} + +/** + * gdata_contacts_contact_get_user_defined_field: + * @self: a #GDataContactsContact + * @name: the field name; an arbitrary, case-sensitive, unique string + * + * Gets the value of a user-defined field of the contact. User-defined fields are settable by the user through the Google Contacts web interface, + * in contrast to extended properties, which are visible and settable only through the GData interface. + * + * The @name of the field may not be %NULL, but may be an empty string. + * + * Return value: the field's value, or %NULL + * + * Since: 0.7.0 + */ +const gchar * +gdata_contacts_contact_get_user_defined_field (GDataContactsContact *self, const gchar *name) +{ + g_return_val_if_fail (GDATA_IS_CONTACTS_CONTACT (self), NULL); + g_return_val_if_fail (name != NULL, NULL); + return g_hash_table_lookup (self->priv->user_defined_fields, name); +} + +/** + * gdata_contacts_contact_get_user_defined_fields: + * @self: a #GDataContactsContact + * + * Gets the full list of user-defined fields of the contact; a hash table mapping field name to value. + * + * Return value: (transfer none): a #GHashTable of user-defined fields + * + * Since: 0.7.0 + */ +GHashTable * +gdata_contacts_contact_get_user_defined_fields (GDataContactsContact *self) +{ + g_return_val_if_fail (GDATA_IS_CONTACTS_CONTACT (self), NULL); + return self->priv->user_defined_fields; +} + +/** + * gdata_contacts_contact_set_user_defined_field: + * @self: a #GDataContactsContact + * @name: the field name; an arbitrary, case-sensitive, unique string + * @value: (allow-none): the field value, or %NULL + * + * Sets the value of a contact's user-defined field. User-defined field names are unique (but of the client's choosing), + * and reusing the same field name will result in the old value of that field being overwritten. + * + * The @name of the field may not be %NULL, but may be an empty string. + * + * To unset a field, set @value to %NULL. + * + * Since: 0.7.0 + */ +void +gdata_contacts_contact_set_user_defined_field (GDataContactsContact *self, const gchar *name, const gchar *value) +{ + g_return_if_fail (GDATA_IS_CONTACTS_CONTACT (self)); + g_return_if_fail (name != NULL); + + if (value == NULL) { + /* Removing a field */ + g_hash_table_remove (self->priv->user_defined_fields, name); + } else { + /* Updating an existing field or adding a new one */ + g_hash_table_insert (self->priv->user_defined_fields, g_strdup (name), g_strdup (value)); + } +} + +/** + * gdata_contacts_contact_add_group: + * @self: a #GDataContactsContact + * @href: the group's ID URI + * + * Adds the contact to the given group. @href should be a URI. + * + * Since: 0.2.0 + */ +void +gdata_contacts_contact_add_group (GDataContactsContact *self, const gchar *href) +{ + g_return_if_fail (GDATA_IS_CONTACTS_CONTACT (self)); + g_return_if_fail (href != NULL); + g_hash_table_insert (self->priv->groups, g_strdup (href), GUINT_TO_POINTER (FALSE)); +} + +/** + * gdata_contacts_contact_remove_group: + * @self: a #GDataContactsContact + * @href: the group's ID URI + * + * Removes the contact from the given group. @href should be a URI. + * + * Since: 0.2.0 + */ +void +gdata_contacts_contact_remove_group (GDataContactsContact *self, const gchar *href) +{ + g_return_if_fail (GDATA_IS_CONTACTS_CONTACT (self)); + g_return_if_fail (href != NULL); + g_hash_table_remove (self->priv->groups, href); +} + +/** + * gdata_contacts_contact_is_group_deleted: + * @self: a #GDataContactsContact + * @href: the group's ID URI + * + * Returns whether the contact has recently been removed from the given group on the server. This + * will always return %FALSE unless #GDataContactsQuery:show-deleted has been set to + * %TRUE for the query which returned the contact. + * + * If you've just removed a contact from a group locally using gdata_contacts_contact_remove_group(), %FALSE will still be returned by this function, + * as the change hasn't been sent to the server. + * + * Return value: %TRUE if the contact has recently been removed from the group, %FALSE otherwise + * + * Since: 0.2.0 + */ +gboolean +gdata_contacts_contact_is_group_deleted (GDataContactsContact *self, const gchar *href) +{ + g_return_val_if_fail (GDATA_IS_CONTACTS_CONTACT (self), FALSE); + g_return_val_if_fail (href != NULL, FALSE); + return GPOINTER_TO_UINT (g_hash_table_lookup (self->priv->groups, href)); +} + +/** + * gdata_contacts_contact_get_groups: + * @self: a #GDataContactsContact + * + * Gets a list of the groups to which the contact belongs. + * + * Return value: (element-type utf8) (transfer container): a #GList of constant group ID URIs, or %NULL; free with g_list_free() + * + * Since: 0.2.0 + */ +GList * +gdata_contacts_contact_get_groups (GDataContactsContact *self) +{ + GHashTableIter iter; + const gchar *href; + gpointer value; + GList *groups = NULL; + + g_return_val_if_fail (GDATA_IS_CONTACTS_CONTACT (self), NULL); + + g_hash_table_iter_init (&iter, self->priv->groups); + while (g_hash_table_iter_next (&iter, (gpointer*) &href, &value) == TRUE) { + /* Add the group to the list as long as it hasn't been deleted */ + if (GPOINTER_TO_UINT (value) == FALSE) + groups = g_list_prepend (groups, (gpointer) href); + } + + return g_list_reverse (groups); +} + +/** + * gdata_contacts_contact_is_deleted: + * @self: a #GDataContactsContact + * + * Returns whether the contact has recently been deleted. This will always return + * %FALSE unless #GDataContactsQuery:show-deleted has been set to + * %TRUE for the query which returned the contact; then this function will return + * %TRUE only if the contact has been deleted. + * + * If a contact has been deleted, no other information is available about it. This + * is designed to allow contacts to be deleted from local address books using + * incremental updates from the server (e.g. with #GDataQuery:updated-min and + * #GDataContactsQuery:show-deleted). + * + * Return value: %TRUE if the contact has been deleted, %FALSE otherwise + * + * Since: 0.2.0 + */ +gboolean +gdata_contacts_contact_is_deleted (GDataContactsContact *self) +{ + g_return_val_if_fail (GDATA_IS_CONTACTS_CONTACT (self), FALSE); + return self->priv->deleted; +} + +/** + * gdata_contacts_contact_get_photo_etag: + * @self: a #GDataContactsContact + * + * Returns the ETag for the contact's attached photo, if it exists. If it does exist, the contact's photo can be retrieved using + * gdata_contacts_contact_get_photo(). If it doesn't exist, %NULL will be returned, and the contact doesn't have a photo (so calling + * gdata_contacts_contact_get_photo() will also return %NULL) + * + * Return value: the contact's photo's ETag if it exists, %NULL otherwise + * + * Since: 0.9.0 + */ +const gchar * +gdata_contacts_contact_get_photo_etag (GDataContactsContact *self) +{ + g_return_val_if_fail (GDATA_IS_CONTACTS_CONTACT (self), NULL); + return self->priv->photo_etag; +} + +/** + * gdata_contacts_contact_get_photo: + * @self: a #GDataContactsContact + * @service: a #GDataContactsService + * @length: (out caller-allocates): return location for the image length, in bytes + * @content_type: (out callee-allocates) (transfer full) (allow-none): return location for the image's content type, or %NULL; free with g_free() + * @cancellable: (allow-none): optional #GCancellable object, or %NULL + * @error: a #GError, or %NULL + * + * Downloads and returns the contact's photo, if they have one. If the contact doesn't + * have a photo (i.e. gdata_contacts_contact_get_photo_etag() returns %NULL), %NULL is returned, but + * no error is set in @error. + * + * If @cancellable is not %NULL, then the operation can be cancelled by triggering the @cancellable object from another thread. + * If the operation was cancelled, the error %G_IO_ERROR_CANCELLED will be returned. + * + * If there is an error getting the photo, a %GDATA_SERVICE_ERROR_PROTOCOL_ERROR error will be returned. + * + * Return value: (transfer full) (array length=length): the image data, or %NULL; free with g_free() + * + * Since: 0.8.0 + */ +guint8 * +gdata_contacts_contact_get_photo (GDataContactsContact *self, GDataContactsService *service, gsize *length, gchar **content_type, + GCancellable *cancellable, GError **error) +{ + GDataLink *_link; + SoupMessage *message; + guint status; + guint8 *data; + + g_return_val_if_fail (GDATA_IS_CONTACTS_CONTACT (self), NULL); + g_return_val_if_fail (GDATA_IS_CONTACTS_SERVICE (service), NULL); + g_return_val_if_fail (length != NULL, NULL); + g_return_val_if_fail (cancellable == NULL || G_IS_CANCELLABLE (cancellable), NULL); + g_return_val_if_fail (error == NULL || *error == NULL, NULL); + + /* Return if there is no photo */ + if (gdata_contacts_contact_get_photo_etag (self) == NULL) + return NULL; + + /* Get the photo URI */ + /* TODO: ETag support */ + _link = gdata_entry_look_up_link (GDATA_ENTRY (self), "http://schemas.google.com/contacts/2008/rel#photo"); + g_assert (_link != NULL); + message = _gdata_service_build_message (GDATA_SERVICE (service), gdata_contacts_service_get_primary_authorization_domain (), + SOUP_METHOD_GET, gdata_link_get_uri (_link), NULL, FALSE); + + /* Send the message */ + status = _gdata_service_send_message (GDATA_SERVICE (service), message, cancellable, error); + + if (status == SOUP_STATUS_NONE || status == SOUP_STATUS_CANCELLED) { + /* Redirect error or cancelled */ + g_object_unref (message); + return NULL; + } else if (status != SOUP_STATUS_OK) { + /* Error */ + GDataServiceClass *klass = GDATA_SERVICE_GET_CLASS (service); + g_assert (klass->parse_error_response != NULL); + klass->parse_error_response (GDATA_SERVICE (service), GDATA_OPERATION_DOWNLOAD, status, message->reason_phrase, + message->response_body->data, message->response_body->length, error); + g_object_unref (message); + return NULL; + } + + g_assert (message->response_body->data != NULL); + + /* Sort out the return values */ + if (content_type != NULL) + *content_type = g_strdup (soup_message_headers_get_content_type (message->response_headers, NULL)); + *length = message->response_body->length; + data = g_memdup (message->response_body->data, message->response_body->length); + + /* Update the stored photo ETag */ + g_free (self->priv->photo_etag); + self->priv->photo_etag = g_strdup (soup_message_headers_get_one (message->response_headers, "ETag")); + g_object_unref (message); + + return data; +} + +typedef struct { + GDataContactsService *service; + guint8 *data; + gsize length; + gchar *content_type; +} PhotoData; + +static void +photo_data_free (PhotoData *data) +{ + if (data->service != NULL) + g_object_unref (data->service); + g_free (data->data); + g_free (data->content_type); + g_slice_free (PhotoData, data); +} + +G_DEFINE_AUTOPTR_CLEANUP_FUNC (PhotoData, photo_data_free) + +static void +get_photo_thread (GTask *task, gpointer source_object, gpointer task_data, GCancellable *cancellable) +{ + GDataContactsContact *contact = GDATA_CONTACTS_CONTACT (source_object); + GDataContactsService *service = GDATA_CONTACTS_SERVICE (task_data); + g_autoptr(PhotoData) data = NULL; + g_autoptr(GError) error = NULL; + + /* Input and output */ + data = g_slice_new0 (PhotoData); + + /* Get the photo */ + data->data = gdata_contacts_contact_get_photo (contact, service, &(data->length), &(data->content_type), cancellable, &error); + if (error != NULL) + g_task_return_error (task, g_steal_pointer (&error)); + else + g_task_return_pointer (task, g_steal_pointer (&data), (GDestroyNotify) photo_data_free); +} + +/** + * gdata_contacts_contact_get_photo_async: + * @self: a #GDataContactsContact + * @service: a #GDataContactsService + * @cancellable: (allow-none): optional #GCancellable object, or %NULL + * @callback: a #GAsyncReadyCallback to call when the photo has been retrieved, or %NULL + * @user_data: (closure): data to pass to the @callback function + * + * Downloads and returns the contact's photo, if they have one, asynchronously. @self and @service are both reffed when this function is called, so + * can safely be unreffed after this function returns. + * + * When the operation is finished, @callback will be called. You can then call gdata_contacts_contact_get_photo_finish() to get the results of the + * operation. + * + * For more details, see gdata_contacts_contact_get_photo(), which is the synchronous version of this function. + * + * If @cancellable is not %NULL, then the operation can be cancelled by triggering the @cancellable object from another thread. + * If the operation was cancelled, the error %G_IO_ERROR_CANCELLED will be returned by gdata_contacts_contact_get_photo_finish(). + * + * If there is an error getting the photo, a %GDATA_SERVICE_ERROR_PROTOCOL_ERROR error will be returned by gdata_contacts_contact_get_photo_finish(). + * + * Since: 0.8.0 + */ +void +gdata_contacts_contact_get_photo_async (GDataContactsContact *self, GDataContactsService *service, GCancellable *cancellable, + GAsyncReadyCallback callback, gpointer user_data) +{ + g_autoptr(GTask) task = NULL; + + g_return_if_fail (GDATA_IS_CONTACTS_CONTACT (self)); + g_return_if_fail (GDATA_IS_CONTACTS_SERVICE (service)); + g_return_if_fail (cancellable == NULL || G_IS_CANCELLABLE (cancellable)); + g_return_if_fail (callback != NULL); + + task = g_task_new (self, cancellable, callback, user_data); + g_task_set_source_tag (task, gdata_contacts_contact_get_photo_async); + g_task_set_task_data (task, g_object_ref (service), (GDestroyNotify) g_object_unref); + g_task_run_in_thread (task, get_photo_thread); +} + +/** + * gdata_contacts_contact_get_photo_finish: + * @self: a #GDataContactsContact + * @async_result: a #GAsyncResult + * @length: (out caller-allocates): return location for the image length, in bytes + * @content_type: (out callee-allocates) (transfer full) (allow-none): return location for the image's content type, or %NULL; free with g_free() + * @error: a #GError, or %NULL + * + * Finishes an asynchronous contact photo retrieval operation started with gdata_contacts_contact_get_photo_async(). If the contact doesn't have a + * photo (i.e. gdata_contacts_contact_get_photo_etag() returns %NULL), %NULL is returned, but no error is set in @error. + * + * If there is an error getting the photo, a %GDATA_SERVICE_ERROR_PROTOCOL_ERROR error will be returned. @length will be set to + * 0 and @content_type will be set to %NULL. + * + * Return value: (transfer full) (array length=length): the image data, or %NULL; free with g_free() + * + * Since: 0.8.0 + */ +guint8 * +gdata_contacts_contact_get_photo_finish (GDataContactsContact *self, GAsyncResult *async_result, gsize *length, gchar **content_type, GError **error) +{ + g_autoptr(PhotoData) data = NULL; + + g_return_val_if_fail (GDATA_IS_CONTACTS_CONTACT (self), NULL); + g_return_val_if_fail (G_IS_ASYNC_RESULT (async_result), NULL); + g_return_val_if_fail (length != NULL, NULL); + g_return_val_if_fail (error == NULL || *error == NULL, NULL); + g_return_val_if_fail (g_task_is_valid (async_result, self), NULL); + g_return_val_if_fail (g_async_result_is_tagged (async_result, gdata_contacts_contact_get_photo_async), NULL); + + data = g_task_propagate_pointer (G_TASK (async_result), error); + if (data == NULL) { + /* Error */ + *length = 0; + + if (content_type != NULL) { + *content_type = NULL; + } + + return NULL; + } + + /* Return the photo (steal the data from the PhotoData struct so we don't have to copy it again) */ + *length = data->length; + if (content_type != NULL) + *content_type = g_steal_pointer (&data->content_type); + + return g_steal_pointer (&data->data); +} + +/** + * gdata_contacts_contact_set_photo: + * @self: a #GDataContactsContact + * @service: a #GDataContactsService + * @data: (allow-none): the image data, or %NULL + * @length: the image length, in bytes + * @content_type: (allow-none): the content type of the image, or %NULL + * @cancellable: (allow-none): optional #GCancellable object, or %NULL + * @error: a #GError, or %NULL + * + * Sets the contact's photo to @data or, if @data is %NULL, deletes the contact's photo. @content_type must be specified if @data is non-%NULL. + * + * If @cancellable is not %NULL, then the operation can be cancelled by triggering the @cancellable object from another thread. + * If the operation was cancelled, the error %G_IO_ERROR_CANCELLED will be returned. + * + * If there is an error setting the photo, a %GDATA_SERVICE_ERROR_PROTOCOL_ERROR error will be returned. + * + * Return value: %TRUE on success, %FALSE otherwise + * + * Since: 0.8.0 + */ +gboolean +gdata_contacts_contact_set_photo (GDataContactsContact *self, GDataContactsService *service, const guint8 *data, gsize length, + const gchar *content_type, GCancellable *cancellable, GError **error) +{ + GDataLink *_link; + SoupMessage *message; + guint status; + gboolean deleting_photo = FALSE; + const gchar *etag; + + g_return_val_if_fail (GDATA_IS_CONTACTS_CONTACT (self), FALSE); + g_return_val_if_fail (GDATA_IS_CONTACTS_SERVICE (service), FALSE); + g_return_val_if_fail (data == NULL || content_type != NULL, FALSE); + g_return_val_if_fail (cancellable == NULL || G_IS_CANCELLABLE (cancellable), FALSE); + g_return_val_if_fail (error == NULL || *error == NULL, FALSE); + + if (self->priv->photo_etag != NULL && data == NULL) + deleting_photo = TRUE; + + /* Get the photo URI */ + _link = gdata_entry_look_up_link (GDATA_ENTRY (self), "http://schemas.google.com/contacts/2008/rel#photo"); + g_assert (_link != NULL); + + /* We always have to set an If-Match header. */ + etag = self->priv->photo_etag; + if (etag == NULL || *etag == '\0') { + etag = "*"; + } + + message = _gdata_service_build_message (GDATA_SERVICE (service), gdata_contacts_service_get_primary_authorization_domain (), + (deleting_photo == TRUE) ? SOUP_METHOD_DELETE : SOUP_METHOD_PUT, + gdata_link_get_uri (_link), etag, TRUE); + + /* Append the data */ + if (deleting_photo == FALSE) + soup_message_set_request (message, content_type, SOUP_MEMORY_STATIC, (gchar*) data, length); + + /* Send the message */ + status = _gdata_service_send_message (GDATA_SERVICE (service), message, cancellable, error); + + if (status == SOUP_STATUS_NONE || status == SOUP_STATUS_CANCELLED) { + /* Redirect error or cancelled */ + g_object_unref (message); + return FALSE; + } else if (status != SOUP_STATUS_OK) { + /* Error */ + GDataServiceClass *klass = GDATA_SERVICE_GET_CLASS (service); + g_assert (klass->parse_error_response != NULL); + klass->parse_error_response (GDATA_SERVICE (service), GDATA_OPERATION_UPLOAD, status, message->reason_phrase, + message->response_body->data, message->response_body->length, error); + g_object_unref (message); + return FALSE; + } + + /* Update the stored photo ETag */ + g_free (self->priv->photo_etag); + self->priv->photo_etag = g_strdup (soup_message_headers_get_one (message->response_headers, "ETag")); + g_object_notify (G_OBJECT (self), "photo-etag"); + + g_object_unref (message); + + return TRUE; +} + +static void +set_photo_thread (GTask *task, gpointer source_object, gpointer task_data, GCancellable *cancellable) +{ + GDataContactsContact *contact = GDATA_CONTACTS_CONTACT (source_object); + PhotoData *data = task_data; + g_autoptr(GError) error = NULL; + + /* Set the photo */ + if (!gdata_contacts_contact_set_photo (contact, data->service, data->data, data->length, data->content_type, cancellable, &error)) + g_task_return_error (task, g_steal_pointer (&error)); + else + g_task_return_boolean (task, TRUE); +} + +/** + * gdata_contacts_contact_set_photo_async: + * @self: a #GDataContactsContact + * @service: a #GDataContactsService + * @data: (allow-none): the image data, or %NULL + * @length: the image length, in bytes + * @content_type: (allow-none): the content type of the image, or %NULL + * @cancellable: (allow-none): optional #GCancellable object, or %NULL + * @callback: a #GAsyncReadyCallback to call when the photo has been set, or %NULL + * @user_data: (closure): data to pass to the @callback function + * + * Sets the contact's photo to @data or, if @data is %NULL, deletes the contact's photo. @content_type must be specified if @data is non-%NULL. @self, + * @service, @data and @content_type are all reffed and copied when this function is called, so can safely be unreffed after this function returns. + * + * When the operation is finished, @callback will be called. You can then call gdata_contacts_contact_set_photo_finish() to get the results of the + * operation. + * + * For more details, see gdata_contacts_contact_set_photo(), which is the synchronous version of this function. + * + * If @cancellable is not %NULL, then the operation can be cancelled by triggering the @cancellable object from another thread. + * If the operation was cancelled, the error %G_IO_ERROR_CANCELLED will be returned by gdata_contacts_contact_set_photo_finish(). + * + * If there is an error setting the photo, a %GDATA_SERVICE_ERROR_PROTOCOL_ERROR error will be returned by gdata_contacts_contact_set_photo_finish(). + * + * Since: 0.8.0 + */ +void +gdata_contacts_contact_set_photo_async (GDataContactsContact *self, GDataContactsService *service, const guint8 *data, gsize length, + const gchar *content_type, GCancellable *cancellable, GAsyncReadyCallback callback, gpointer user_data) +{ + g_autoptr(GTask) task = NULL; + g_autoptr(PhotoData) photo_data = NULL; + + g_return_if_fail (GDATA_IS_CONTACTS_CONTACT (self)); + g_return_if_fail (GDATA_IS_CONTACTS_SERVICE (service)); + g_return_if_fail (data == NULL || content_type != NULL); + g_return_if_fail (cancellable == NULL || G_IS_CANCELLABLE (cancellable)); + + /* Prepare the data to be passed to the thread */ + photo_data = g_slice_new (PhotoData); + photo_data->service = g_object_ref (service); + photo_data->data = g_memdup (data, length); + photo_data->length = length; + photo_data->content_type = g_strdup (content_type); + + task = g_task_new (self, cancellable, callback, user_data); + g_task_set_source_tag (task, gdata_contacts_contact_set_photo_async); + g_task_set_task_data (task, g_steal_pointer (&photo_data), (GDestroyNotify) photo_data_free); + g_task_run_in_thread (task, set_photo_thread); +} + +/** + * gdata_contacts_contact_set_photo_finish: + * @self: a #GDataContactsContact + * @async_result: a #GAsyncResult + * @error: a #GError, or %NULL + * + * Finishes an asynchronous contact photo setting operation started with gdata_contacts_contact_set_photo_async(). + * + * If there is an error setting the photo, a %GDATA_SERVICE_ERROR_PROTOCOL_ERROR error will be returned. + * + * Return value: %TRUE on success, %FALSE otherwise + * + * Since: 0.8.0 + */ +gboolean +gdata_contacts_contact_set_photo_finish (GDataContactsContact *self, GAsyncResult *async_result, GError **error) +{ + g_return_val_if_fail (GDATA_IS_CONTACTS_CONTACT (self), FALSE); + g_return_val_if_fail (G_IS_ASYNC_RESULT (async_result), FALSE); + g_return_val_if_fail (error == NULL || *error == NULL, FALSE); + g_return_val_if_fail (g_task_is_valid (async_result, self), FALSE); + g_return_val_if_fail (g_async_result_is_tagged (async_result, gdata_contacts_contact_set_photo_async), FALSE); + + return g_task_propagate_boolean (G_TASK (async_result), error); +} diff --git a/gdata/services/contacts/gdata-contacts-contact.h b/gdata/services/contacts/gdata-contacts-contact.h new file mode 100644 index 0000000..b84daa7 --- /dev/null +++ b/gdata/services/contacts/gdata-contacts-contact.h @@ -0,0 +1,305 @@ +/* -*- Mode: C; indent-tabs-mode: t; c-basic-offset: 8; tab-width: 8 -*- */ +/* + * GData Client + * Copyright (C) Philip Withnall 2009, 2010, 2011 + * + * GData Client is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * GData Client is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with GData Client. If not, see . + */ + +#ifndef GDATA_CONTACTS_CONTACT_H +#define GDATA_CONTACTS_CONTACT_H + +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +G_BEGIN_DECLS + +/** + * GDATA_CONTACTS_GENDER_MALE: + * + * The contact is male. + * + * Since: 0.7.0 + */ +#define GDATA_CONTACTS_GENDER_MALE "male" + +/** + * GDATA_CONTACTS_GENDER_FEMALE: + * + * The contact is female. + * + * Since: 0.7.0 + */ +#define GDATA_CONTACTS_GENDER_FEMALE "female" + +/** + * GDATA_CONTACTS_PRIORITY_LOW: + * + * The contact is of low importance. + * + * Since: 0.7.0 + */ +#define GDATA_CONTACTS_PRIORITY_LOW "low" + +/** + * GDATA_CONTACTS_PRIORITY_NORMAL: + * + * The contact is of normal importance. + * + * Since: 0.7.0 + */ +#define GDATA_CONTACTS_PRIORITY_NORMAL "normal" + +/** + * GDATA_CONTACTS_PRIORITY_HIGH: + * + * The contact is of high importance. + * + * Since: 0.7.0 + */ +#define GDATA_CONTACTS_PRIORITY_HIGH "high" + +/** + * GDATA_CONTACTS_SENSITIVITY_CONFIDENTIAL: + * + * The contact's data is confidential. + * + * Since: 0.7.0 + */ +#define GDATA_CONTACTS_SENSITIVITY_CONFIDENTIAL "confidential" + +/** + * GDATA_CONTACTS_SENSITIVITY_NORMAL: + * + * The contact's data is of normal sensitivity. + * + * Since: 0.7.0 + */ +#define GDATA_CONTACTS_SENSITIVITY_NORMAL "normal" + +/** + * GDATA_CONTACTS_SENSITIVITY_PERSONAL: + * + * The contact's data is personal. + * + * Since: 0.7.0 + */ +#define GDATA_CONTACTS_SENSITIVITY_PERSONAL "personal" + +/** + * GDATA_CONTACTS_SENSITIVITY_PRIVATE: + * + * The contact's data is private. + * + * Since: 0.7.0 + */ +#define GDATA_CONTACTS_SENSITIVITY_PRIVATE "private" + +#define GDATA_TYPE_CONTACTS_CONTACT (gdata_contacts_contact_get_type ()) +#define GDATA_CONTACTS_CONTACT(o) (G_TYPE_CHECK_INSTANCE_CAST ((o), GDATA_TYPE_CONTACTS_CONTACT, GDataContactsContact)) +#define GDATA_CONTACTS_CONTACT_CLASS(k) (G_TYPE_CHECK_CLASS_CAST((k), GDATA_TYPE_CONTACTS_CONTACT, GDataContactsContactClass)) +#define GDATA_IS_CONTACTS_CONTACT(o) (G_TYPE_CHECK_INSTANCE_TYPE ((o), GDATA_TYPE_CONTACTS_CONTACT)) +#define GDATA_IS_CONTACTS_CONTACT_CLASS(k) (G_TYPE_CHECK_CLASS_TYPE ((k), GDATA_TYPE_CONTACTS_CONTACT)) +#define GDATA_CONTACTS_CONTACT_GET_CLASS(o) (G_TYPE_INSTANCE_GET_CLASS ((o), GDATA_TYPE_CONTACTS_CONTACT, GDataContactsContactClass)) + +typedef struct _GDataContactsContactPrivate GDataContactsContactPrivate; + +/** + * GDataContactsContact: + * + * All the fields in the #GDataContactsContact structure are private and should never be accessed directly. + * + * Since: 0.2.0 + */ +typedef struct { + GDataEntry parent; + GDataContactsContactPrivate *priv; +} GDataContactsContact; + +/** + * GDataContactsContactClass: + * + * All the fields in the #GDataContactsContactClass structure are private and should never be accessed directly. + * + * Since: 0.2.0 + */ +typedef struct { + /*< private >*/ + GDataEntryClass parent; + + /*< private >*/ + /* Padding for future expansion */ + void (*_g_reserved0) (void); + void (*_g_reserved1) (void); +} GDataContactsContactClass; + +GType gdata_contacts_contact_get_type (void) G_GNUC_CONST; + +GDataContactsContact *gdata_contacts_contact_new (const gchar *id) G_GNUC_WARN_UNUSED_RESULT G_GNUC_MALLOC; + +gint64 gdata_contacts_contact_get_edited (GDataContactsContact *self); +gboolean gdata_contacts_contact_is_deleted (GDataContactsContact *self) G_GNUC_PURE; + +GDataGDName *gdata_contacts_contact_get_name (GDataContactsContact *self) G_GNUC_PURE; +void gdata_contacts_contact_set_name (GDataContactsContact *self, GDataGDName *name); + +const gchar *gdata_contacts_contact_get_nickname (GDataContactsContact *self) G_GNUC_PURE; +void gdata_contacts_contact_set_nickname (GDataContactsContact *self, const gchar *nickname); + +const gchar *gdata_contacts_contact_get_file_as (GDataContactsContact *self) G_GNUC_PURE; +void gdata_contacts_contact_set_file_as (GDataContactsContact *self, const gchar *file_as); + +gboolean gdata_contacts_contact_get_birthday (GDataContactsContact *self, GDate *birthday) G_GNUC_PURE; +void gdata_contacts_contact_set_birthday (GDataContactsContact *self, GDate *birthday, gboolean birthday_has_year); + +const gchar *gdata_contacts_contact_get_billing_information (GDataContactsContact *self) G_GNUC_PURE; +void gdata_contacts_contact_set_billing_information (GDataContactsContact *self, const gchar *billing_information); + +const gchar *gdata_contacts_contact_get_directory_server (GDataContactsContact *self) G_GNUC_PURE; +void gdata_contacts_contact_set_directory_server (GDataContactsContact *self, const gchar *directory_server); + +const gchar *gdata_contacts_contact_get_gender (GDataContactsContact *self) G_GNUC_PURE; +void gdata_contacts_contact_set_gender (GDataContactsContact *self, const gchar *gender); + +const gchar *gdata_contacts_contact_get_initials (GDataContactsContact *self) G_GNUC_PURE; +void gdata_contacts_contact_set_initials (GDataContactsContact *self, const gchar *initials); + +const gchar *gdata_contacts_contact_get_maiden_name (GDataContactsContact *self) G_GNUC_PURE; +void gdata_contacts_contact_set_maiden_name (GDataContactsContact *self, const gchar *maiden_name); + +const gchar *gdata_contacts_contact_get_mileage (GDataContactsContact *self) G_GNUC_PURE; +void gdata_contacts_contact_set_mileage (GDataContactsContact *self, const gchar *mileage); + +const gchar *gdata_contacts_contact_get_occupation (GDataContactsContact *self) G_GNUC_PURE; +void gdata_contacts_contact_set_occupation (GDataContactsContact *self, const gchar *occupation); + +const gchar *gdata_contacts_contact_get_priority (GDataContactsContact *self) G_GNUC_PURE; +void gdata_contacts_contact_set_priority (GDataContactsContact *self, const gchar *priority); + +const gchar *gdata_contacts_contact_get_sensitivity (GDataContactsContact *self) G_GNUC_PURE; +void gdata_contacts_contact_set_sensitivity (GDataContactsContact *self, const gchar *sensitivity); + +const gchar *gdata_contacts_contact_get_short_name (GDataContactsContact *self) G_GNUC_PURE; +void gdata_contacts_contact_set_short_name (GDataContactsContact *self, const gchar *short_name); + +const gchar *gdata_contacts_contact_get_subject (GDataContactsContact *self) G_GNUC_PURE; +void gdata_contacts_contact_set_subject (GDataContactsContact *self, const gchar *subject); + +void gdata_contacts_contact_add_email_address (GDataContactsContact *self, GDataGDEmailAddress *email_address); +GList *gdata_contacts_contact_get_email_addresses (GDataContactsContact *self) G_GNUC_PURE; +GDataGDEmailAddress *gdata_contacts_contact_get_primary_email_address (GDataContactsContact *self) G_GNUC_PURE; +void gdata_contacts_contact_remove_all_email_addresses (GDataContactsContact *self); + +void gdata_contacts_contact_add_im_address (GDataContactsContact *self, GDataGDIMAddress *im_address); +GList *gdata_contacts_contact_get_im_addresses (GDataContactsContact *self) G_GNUC_PURE; +GDataGDIMAddress *gdata_contacts_contact_get_primary_im_address (GDataContactsContact *self) G_GNUC_PURE; +void gdata_contacts_contact_remove_all_im_addresses (GDataContactsContact *self); + +void gdata_contacts_contact_add_phone_number (GDataContactsContact *self, GDataGDPhoneNumber *phone_number); +GList *gdata_contacts_contact_get_phone_numbers (GDataContactsContact *self) G_GNUC_PURE; +GDataGDPhoneNumber *gdata_contacts_contact_get_primary_phone_number (GDataContactsContact *self) G_GNUC_PURE; +void gdata_contacts_contact_remove_all_phone_numbers (GDataContactsContact *self); + +void gdata_contacts_contact_add_postal_address (GDataContactsContact *self, GDataGDPostalAddress *postal_address); +GList *gdata_contacts_contact_get_postal_addresses (GDataContactsContact *self) G_GNUC_PURE; +GDataGDPostalAddress *gdata_contacts_contact_get_primary_postal_address (GDataContactsContact *self) G_GNUC_PURE; +void gdata_contacts_contact_remove_all_postal_addresses (GDataContactsContact *self); + +void gdata_contacts_contact_add_organization (GDataContactsContact *self, GDataGDOrganization *organization); +GList *gdata_contacts_contact_get_organizations (GDataContactsContact *self) G_GNUC_PURE; +GDataGDOrganization *gdata_contacts_contact_get_primary_organization (GDataContactsContact *self) G_GNUC_PURE; +void gdata_contacts_contact_remove_all_organizations (GDataContactsContact *self); + +void gdata_contacts_contact_add_jot (GDataContactsContact *self, GDataGContactJot *jot); +GList *gdata_contacts_contact_get_jots (GDataContactsContact *self) G_GNUC_PURE; +void gdata_contacts_contact_remove_all_jots (GDataContactsContact *self); + +void gdata_contacts_contact_add_relation (GDataContactsContact *self, GDataGContactRelation *relation); +GList *gdata_contacts_contact_get_relations (GDataContactsContact *self) G_GNUC_PURE; +void gdata_contacts_contact_remove_all_relations (GDataContactsContact *self); + +void gdata_contacts_contact_add_website (GDataContactsContact *self, GDataGContactWebsite *website); +GList *gdata_contacts_contact_get_websites (GDataContactsContact *self) G_GNUC_PURE; +GDataGContactWebsite *gdata_contacts_contact_get_primary_website (GDataContactsContact *self) G_GNUC_PURE; +void gdata_contacts_contact_remove_all_websites (GDataContactsContact *self); + +void gdata_contacts_contact_add_event (GDataContactsContact *self, GDataGContactEvent *event); +GList *gdata_contacts_contact_get_events (GDataContactsContact *self) G_GNUC_PURE; +void gdata_contacts_contact_remove_all_events (GDataContactsContact *self); + +void gdata_contacts_contact_add_calendar (GDataContactsContact *self, GDataGContactCalendar *calendar); +GList *gdata_contacts_contact_get_calendars (GDataContactsContact *self) G_GNUC_PURE; +GDataGContactCalendar *gdata_contacts_contact_get_primary_calendar (GDataContactsContact *self) G_GNUC_PURE; +void gdata_contacts_contact_remove_all_calendars (GDataContactsContact *self); + +void gdata_contacts_contact_add_external_id (GDataContactsContact *self, GDataGContactExternalID *external_id); +GList *gdata_contacts_contact_get_external_ids (GDataContactsContact *self) G_GNUC_PURE; +void gdata_contacts_contact_remove_all_external_ids (GDataContactsContact *self); + +void gdata_contacts_contact_add_hobby (GDataContactsContact *self, const gchar *hobby); +GList *gdata_contacts_contact_get_hobbies (GDataContactsContact *self) G_GNUC_PURE; +void gdata_contacts_contact_remove_all_hobbies (GDataContactsContact *self); + +void gdata_contacts_contact_add_language (GDataContactsContact *self, GDataGContactLanguage *language); +GList *gdata_contacts_contact_get_languages (GDataContactsContact *self) G_GNUC_PURE; +void gdata_contacts_contact_remove_all_languages (GDataContactsContact *self); + +const gchar *gdata_contacts_contact_get_extended_property (GDataContactsContact *self, const gchar *name) G_GNUC_PURE; +GHashTable *gdata_contacts_contact_get_extended_properties (GDataContactsContact *self) G_GNUC_PURE; +gboolean gdata_contacts_contact_set_extended_property (GDataContactsContact *self, const gchar *name, const gchar *value); + +const gchar *gdata_contacts_contact_get_user_defined_field (GDataContactsContact *self, const gchar *name) G_GNUC_PURE; +GHashTable *gdata_contacts_contact_get_user_defined_fields (GDataContactsContact *self) G_GNUC_PURE; +void gdata_contacts_contact_set_user_defined_field (GDataContactsContact *self, const gchar *name, const gchar *value); + +void gdata_contacts_contact_add_group (GDataContactsContact *self, const gchar *href); +void gdata_contacts_contact_remove_group (GDataContactsContact *self, const gchar *href); +gboolean gdata_contacts_contact_is_group_deleted (GDataContactsContact *self, const gchar *href) G_GNUC_PURE; +GList *gdata_contacts_contact_get_groups (GDataContactsContact *self) G_GNUC_WARN_UNUSED_RESULT G_GNUC_MALLOC; + +#include + +const gchar *gdata_contacts_contact_get_photo_etag (GDataContactsContact *self) G_GNUC_PURE; + +guint8 *gdata_contacts_contact_get_photo (GDataContactsContact *self, GDataContactsService *service, gsize *length, gchar **content_type, + GCancellable *cancellable, GError **error) G_GNUC_WARN_UNUSED_RESULT G_GNUC_MALLOC; +void gdata_contacts_contact_get_photo_async (GDataContactsContact *self, GDataContactsService *service, GCancellable *cancellable, + GAsyncReadyCallback callback, gpointer user_data); +guint8 *gdata_contacts_contact_get_photo_finish (GDataContactsContact *self, GAsyncResult *async_result, gsize *length, gchar **content_type, + GError **error) G_GNUC_WARN_UNUSED_RESULT G_GNUC_MALLOC; + +gboolean gdata_contacts_contact_set_photo (GDataContactsContact *self, GDataContactsService *service, const guint8 *data, gsize length, + const gchar *content_type, GCancellable *cancellable, GError **error); +void gdata_contacts_contact_set_photo_async (GDataContactsContact *self, GDataContactsService *service, const guint8 *data, gsize length, + const gchar *content_type, GCancellable *cancellable, GAsyncReadyCallback callback, gpointer user_data); +gboolean gdata_contacts_contact_set_photo_finish (GDataContactsContact *self, GAsyncResult *async_result, GError **error); + +G_END_DECLS + +#endif /* !GDATA_CONTACTS_CONTACT_H */ diff --git a/gdata/services/contacts/gdata-contacts-group.c b/gdata/services/contacts/gdata-contacts-group.c new file mode 100644 index 0000000..d8ab4a4 --- /dev/null +++ b/gdata/services/contacts/gdata-contacts-group.c @@ -0,0 +1,601 @@ +/* -*- Mode: C; indent-tabs-mode: t; c-basic-offset: 8; tab-width: 8 -*- */ +/* + * GData Client + * Copyright (C) Philip Withnall 2010 + * + * GData Client is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * GData Client is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with GData Client. If not, see . + */ + +/** + * SECTION:gdata-contacts-group + * @short_description: GData Contacts group object + * @stability: Stable + * @include: gdata/services/contacts/gdata-contacts-group.h + * + * #GDataContactsGroup is a subclass of #GDataEntry to represent a group from a Google address book. + * + * For more details of Google Contacts' GData API, see the + * online documentation. + * + * The user-set name of the group is stored in the #GDataEntry:title property, retrievable using gdata_entry_get_title(). Note that for system groups + * (see #GDataContactsGroup:system-group-id), this group name is provided by Google, and is not localised. Clients should provide their own localised + * group names for the system groups. + * + * In addition to all the standard properties available for a group, #GDataContactsGroup supports an additional kind of property: extended + * properties. Extended properties, set with gdata_contacts_group_set_extended_property() and retrieved with + * gdata_contacts_group_get_extended_property(), are provided as a method of storing client-specific data which shouldn't be seen or be editable + * by the user, such as IDs and cache times. + * + * + * Adding a New Group + * + * GDataContactsService *service; + * GDataContactsGroup *group, *updated_group; + * GDataContactsContact *contact, *updated_contact; + * GError *error = NULL; + * + * /* Create a service and return a contact to add to the new group. */ + * service = create_contacts_service (); + * contact = query_user_for_contact (service); + * + * /* Create the new group */ + * group = gdata_contacts_group_new (NULL); + * gdata_entry_set_title (GDATA_ENTRY (group), "Group Name"); + * + * /* Insert the group on the server */ + * updated_group = gdata_contacts_service_insert_group (service, group, NULL, &error); + * + * g_object_unref (group); + * + * if (error != NULL) { + * g_error ("Error adding a group: %s", error->message); + * g_error_free (error); + * g_object_unref (contact); + * g_object_unref (service); + * return; + * } + * + * /* Add the contact to the new group. */ + * gdata_contacts_contact_add_group (contact, gdata_entry_get_id (GDATA_ENTRY (updated_group))); + * + * g_object_unref (updated_group); + * + * /* Update the contact on the server */ + * updated_contact = GDATA_CONTACTS_CONTACT (gdata_service_update_entry (GDATA_SERVICE (service), GDATA_ENTRY (contact), NULL, &error)); + * + * g_object_unref (contact); + * g_object_unref (service); + * + * if (error != NULL) { + * g_error ("Error updating contact: %s", error->message); + * g_error_free (error); + * return; + * } + * + * /* Do something with the updated contact, such as update them in the UI, or store their ID for future use. */ + * + * g_object_unref (updated_contact); + * + * + * + * Since: 0.7.0 + */ + +#include +#include +#include +#include +#include + +#include "gdata-contacts-group.h" +#include "gdata-parser.h" +#include "gdata-types.h" +#include "gdata-private.h" + +/* The maximum number of extended properties the server allows us. See + * http://code.google.com/apis/contacts/docs/3.0/reference.html#ProjectionsAndExtended. + * When updating this, make sure to update the API documentation for gdata_contacts_group_get_extended_property() and + * gdata_contacts_group_set_extended_property(). */ +#define MAX_N_EXTENDED_PROPERTIES 10 + +static GObject *gdata_contacts_group_constructor (GType type, guint n_construct_params, GObjectConstructParam *construct_params); +static void gdata_contacts_group_get_property (GObject *object, guint property_id, GValue *value, GParamSpec *pspec); +static void gdata_contacts_group_finalize (GObject *object); +static void get_xml (GDataParsable *parsable, GString *xml_string); +static gboolean parse_xml (GDataParsable *parsable, xmlDoc *doc, xmlNode *node, gpointer user_data, GError **error); +static void get_namespaces (GDataParsable *parsable, GHashTable *namespaces); +static gchar *get_entry_uri (const gchar *id) G_GNUC_WARN_UNUSED_RESULT; + +struct _GDataContactsGroupPrivate { + gint64 edited; + GHashTable *extended_properties; + gboolean deleted; + gchar *system_group_id; +}; + +enum { + PROP_EDITED = 1, + PROP_DELETED, + PROP_SYSTEM_GROUP_ID +}; + +G_DEFINE_TYPE (GDataContactsGroup, gdata_contacts_group, GDATA_TYPE_ENTRY) + +static void +gdata_contacts_group_class_init (GDataContactsGroupClass *klass) +{ + GObjectClass *gobject_class = G_OBJECT_CLASS (klass); + GDataParsableClass *parsable_class = GDATA_PARSABLE_CLASS (klass); + GDataEntryClass *entry_class = GDATA_ENTRY_CLASS (klass); + + g_type_class_add_private (klass, sizeof (GDataContactsGroupPrivate)); + + gobject_class->constructor = gdata_contacts_group_constructor; + gobject_class->get_property = gdata_contacts_group_get_property; + gobject_class->finalize = gdata_contacts_group_finalize; + + parsable_class->parse_xml = parse_xml; + parsable_class->get_xml = get_xml; + parsable_class->get_namespaces = get_namespaces; + + entry_class->get_entry_uri = get_entry_uri; + entry_class->kind_term = "http://schemas.google.com/contact/2008#group"; + + /** + * GDataContactsGroup:edited: + * + * The last time the group was edited. If the group has not been edited yet, the content indicates the time it was created. + * + * For more information, see the + * Atom Publishing Protocol specification. + * + * Since: 0.7.0 + */ + g_object_class_install_property (gobject_class, PROP_EDITED, + g_param_spec_int64 ("edited", + "Edited", "The last time the group was edited.", + -1, G_MAXINT64, -1, + G_PARAM_READABLE | G_PARAM_STATIC_STRINGS)); + + /** + * GDataContactsGroup:deleted: + * + * Whether the entry has been deleted. + * + * Since: 0.7.0 + */ + g_object_class_install_property (gobject_class, PROP_DELETED, + g_param_spec_boolean ("deleted", + "Deleted", "Whether the entry has been deleted.", + FALSE, + G_PARAM_READABLE | G_PARAM_STATIC_STRINGS)); + + /** + * GDataContactsGroup:system-group-id: + * + * The system group ID for this group, if it's a system group. If the group is not a system group, this is %NULL. Otherwise, it is one of the + * four system group IDs: %GDATA_CONTACTS_GROUP_CONTACTS, %GDATA_CONTACTS_GROUP_FRIENDS, %GDATA_CONTACTS_GROUP_FAMILY and + * %GDATA_CONTACTS_GROUP_COWORKERS. + * + * If this is non-%NULL, the group name stored in #GDataEntry:title will not be localised, so clients should provide localised group names of + * their own for each of the system groups. Whether a group is a system group should be detected solely on the basis of the value of this + * property, not by comparing the group name (#GDataEntry:title) or entry ID (#GDataEntry:id). The entry ID is not the same as the system + * group ID. + * + * Since: 0.7.0 + */ + g_object_class_install_property (gobject_class, PROP_SYSTEM_GROUP_ID, + g_param_spec_string ("system-group-id", + "System group ID", "The system group ID for this group, if it's a system group.", + NULL, + G_PARAM_READABLE | G_PARAM_STATIC_STRINGS)); +} + +static void notify_content_cb (GObject *gobject, GParamSpec *pspec, GDataContactsGroup *self); + +static void +notify_title_cb (GObject *gobject, GParamSpec *pspec, GDataContactsGroup *self) +{ + /* Update GDataEntry:content */ + g_signal_handlers_block_by_func (self, notify_content_cb, self); + gdata_entry_set_content (GDATA_ENTRY (self), gdata_entry_get_title (GDATA_ENTRY (self))); + g_signal_handlers_unblock_by_func (self, notify_content_cb, self); +} + +static void +notify_content_cb (GObject *gobject, GParamSpec *pspec, GDataContactsGroup *self) +{ + /* Update GDataEntry:title */ + g_signal_handlers_block_by_func (self, notify_title_cb, self); + gdata_entry_set_title (GDATA_ENTRY (self), gdata_entry_get_content (GDATA_ENTRY (self))); + g_signal_handlers_unblock_by_func (self, notify_title_cb, self); +} + +static void +gdata_contacts_group_init (GDataContactsGroup *self) +{ + self->priv = G_TYPE_INSTANCE_GET_PRIVATE (self, GDATA_TYPE_CONTACTS_GROUP, GDataContactsGroupPrivate); + self->priv->extended_properties = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, g_free); + self->priv->edited = -1; + + /* Listen to change notifications for the entry's title and content, since they're linked */ + g_signal_connect (self, "notify::title", (GCallback) notify_title_cb, self); + g_signal_connect (self, "notify::content", (GCallback) notify_content_cb, self); +} + +static GObject * +gdata_contacts_group_constructor (GType type, guint n_construct_params, GObjectConstructParam *construct_params) +{ + GObject *object; + guint i; + + /* Find the "id" property and ensure it's sane */ + for (i = 0; i < n_construct_params; i++) { + GParamSpec *pspec = construct_params[i].pspec; + GValue *value = construct_params[i].value; + + if (strcmp (g_param_spec_get_name (pspec), "id") == 0) { + gchar *base, *id; + + id = g_value_dup_string (value); + + /* Fix the ID to refer to the full projection, rather than the base projection. */ + if (id != NULL) { + base = strstr (id, "/base/"); + if (base != NULL) + memcpy (base, "/full/", 6); + } + + g_value_take_string (value, id); + + break; + } + } + + /* Chain up to the parent class */ + object = G_OBJECT_CLASS (gdata_contacts_group_parent_class)->constructor (type, n_construct_params, construct_params); + + if (_gdata_parsable_is_constructed_from_xml (GDATA_PARSABLE (object)) == FALSE) { + GDataContactsGroupPrivate *priv = GDATA_CONTACTS_GROUP (object)->priv; + GTimeVal time_val; + + /* Set the edited property to the current time (creation time). We don't do this in *_init() since that would cause setting it from + * parse_xml() to fail (duplicate element). */ + g_get_current_time (&time_val); + priv->edited = time_val.tv_sec; + } + + return object; +} + +static void +gdata_contacts_group_get_property (GObject *object, guint property_id, GValue *value, GParamSpec *pspec) +{ + GDataContactsGroupPrivate *priv = GDATA_CONTACTS_GROUP (object)->priv; + + switch (property_id) { + case PROP_EDITED: + g_value_set_int64 (value, priv->edited); + break; + case PROP_DELETED: + g_value_set_boolean (value, priv->deleted); + break; + case PROP_SYSTEM_GROUP_ID: + g_value_set_string (value, priv->system_group_id); + break; + default: + /* We don't have any other property... */ + G_OBJECT_WARN_INVALID_PROPERTY_ID (object, property_id, pspec); + break; + } +} + +static void +gdata_contacts_group_finalize (GObject *object) +{ + GDataContactsGroupPrivate *priv = GDATA_CONTACTS_GROUP (object)->priv; + + g_hash_table_destroy (priv->extended_properties); + g_free (priv->system_group_id); + + /* Chain up to the parent class */ + G_OBJECT_CLASS (gdata_contacts_group_parent_class)->finalize (object); +} + +static gboolean +parse_xml (GDataParsable *parsable, xmlDoc *doc, xmlNode *node, gpointer user_data, GError **error) +{ + gboolean success; + GDataContactsGroup *self = GDATA_CONTACTS_GROUP (parsable); + + if (gdata_parser_is_namespace (node, "http://www.w3.org/2007/app") == TRUE && + gdata_parser_int64_time_from_element (node, "edited", P_REQUIRED | P_NO_DUPES, &(self->priv->edited), &success, error) == TRUE) { + return success; + } else if (gdata_parser_is_namespace (node, "http://www.w3.org/2005/Atom") == TRUE && xmlStrcmp (node->name, (xmlChar*) "id") == 0) { + /* We have to override parsing to fix the projection. Modify it in-place so that the parser in GDataEntry will pick up the + * changes. This fixes bugs caused by referring to contacts by the base projection, rather than the full projection; such as + * http://code.google.com/p/gdata-issues/issues/detail?id=2129. */ + gchar *base; + gchar *id = (gchar*) xmlNodeListGetString (doc, node->children, TRUE); + + if (id != NULL) { + base = strstr (id, "/base/"); + if (base != NULL) { + memcpy (base, "/full/", 6); + xmlNodeSetContent (node, (xmlChar*) id); + } + } + + xmlFree (id); + + return GDATA_PARSABLE_CLASS (gdata_contacts_group_parent_class)->parse_xml (parsable, doc, node, user_data, error); + } else if (gdata_parser_is_namespace (node, "http://schemas.google.com/g/2005") == TRUE) { + if (xmlStrcmp (node->name, (xmlChar*) "extendedProperty") == 0) { + /* gd:extendedProperty */ + xmlChar *name, *value; + xmlBuffer *buffer = NULL; + + name = xmlGetProp (node, (xmlChar*) "name"); + if (name == NULL) + return gdata_parser_error_required_property_missing (node, "name", error); + + /* Get either the value property, or the element's content */ + value = xmlGetProp (node, (xmlChar*) "value"); + if (value == NULL) { + xmlNode *child_node; + + /* Use the element's content instead (arbitrary XML) */ + buffer = xmlBufferCreate (); + for (child_node = node->children; child_node != NULL; child_node = child_node->next) + xmlNodeDump (buffer, doc, child_node, 0, 0); + value = (xmlChar*) xmlBufferContent (buffer); + } + + gdata_contacts_group_set_extended_property (self, (gchar*) name, (gchar*) value); + + xmlFree (name); + if (buffer != NULL) + xmlBufferFree (buffer); + else + xmlFree (value); + } else if (xmlStrcmp (node->name, (xmlChar*) "deleted") == 0) { + /* gd:deleted */ + if (self->priv->deleted == TRUE) + return gdata_parser_error_duplicate_element (node, error); + + self->priv->deleted = TRUE; + } else { + return GDATA_PARSABLE_CLASS (gdata_contacts_group_parent_class)->parse_xml (parsable, doc, node, user_data, error); + } + } else if (gdata_parser_is_namespace (node, "http://schemas.google.com/contact/2008") == TRUE) { + if (xmlStrcmp (node->name, (xmlChar*) "systemGroup") == 0) { + /* gContact:systemGroup */ + xmlChar *value; + + if (self->priv->system_group_id != NULL) + return gdata_parser_error_duplicate_element (node, error); + + value = xmlGetProp (node, (xmlChar*) "id"); + if (value == NULL || *value == '\0') { + xmlFree (value); + return gdata_parser_error_required_property_missing (node, "id", error); + } + + self->priv->system_group_id = (gchar*) value; + } else { + return GDATA_PARSABLE_CLASS (gdata_contacts_group_parent_class)->parse_xml (parsable, doc, node, user_data, error); + } + } else { + return GDATA_PARSABLE_CLASS (gdata_contacts_group_parent_class)->parse_xml (parsable, doc, node, user_data, error); + } + + return TRUE; +} + +static void +get_extended_property_xml_cb (const gchar *name, const gchar *value, GString *xml_string) +{ + /* Note that the value *isn't* escaped (see http://code.google.com/apis/gdata/docs/2.0/elements.html#gdExtendedProperty) */ + gdata_parser_string_append_escaped (xml_string, ""); + g_string_append_printf (xml_string, "%s", value); +} + +static void +get_xml (GDataParsable *parsable, GString *xml_string) +{ + GDataContactsGroupPrivate *priv = GDATA_CONTACTS_GROUP (parsable)->priv; + + /* Chain up to the parent class */ + GDATA_PARSABLE_CLASS (gdata_contacts_group_parent_class)->get_xml (parsable, xml_string); + + /* Extended properties */ + g_hash_table_foreach (priv->extended_properties, (GHFunc) get_extended_property_xml_cb, xml_string); +} + +static void +get_namespaces (GDataParsable *parsable, GHashTable *namespaces) +{ + /* Chain up to the parent class */ + GDATA_PARSABLE_CLASS (gdata_contacts_group_parent_class)->get_namespaces (parsable, namespaces); + + g_hash_table_insert (namespaces, (gchar*) "gd", (gchar*) "http://schemas.google.com/g/2005"); + g_hash_table_insert (namespaces, (gchar*) "gContact", (gchar*) "http://schemas.google.com/contact/2008"); + g_hash_table_insert (namespaces, (gchar*) "app", (gchar*) "http://www.w3.org/2007/app"); +} + +static gchar * +get_entry_uri (const gchar *id) +{ + const gchar *base_pos; + gchar *uri = g_strdup (id); + + /* The service API sometimes stubbornly insists on using the "base" view instead of the "full" view, which we have to fix, or our extended + * attributes are never visible */ + base_pos = strstr (uri, "/base/"); + if (base_pos != NULL) + memcpy ((char*) base_pos, "/full/", 6); + + return uri; +} + +/** + * gdata_contacts_group_new: + * @id: (allow-none): the group's ID, or %NULL + * + * Creates a new #GDataContactsGroup with the given ID and default properties. + * + * Return value: a new #GDataContactsGroup; unref with g_object_unref() + * + * Since: 0.7.0 + */ +GDataContactsGroup * +gdata_contacts_group_new (const gchar *id) +{ + return GDATA_CONTACTS_GROUP (g_object_new (GDATA_TYPE_CONTACTS_GROUP, "id", id, NULL)); +} + +/** + * gdata_contacts_group_get_edited: + * @self: a #GDataContactsGroup + * + * Gets the #GDataContactsGroup:edited property. If the property is unset, -1 will be returned. + * + * Return value: the UNIX timestamp for the time the file was last edited, or -1 + * + * Since: 0.7.0 + */ +gint64 +gdata_contacts_group_get_edited (GDataContactsGroup *self) +{ + g_return_val_if_fail (GDATA_IS_CONTACTS_GROUP (self), -1); + return self->priv->edited; +} + +/** + * gdata_contacts_group_get_system_group_id: + * @self: a #GDataContactsGroup + * + * Gets the #GDataContactsGroup:system-group-id property. If the group is not a system group, %NULL will be returned. + * + * Return value: the group's system group ID, or %NULL + * + * Since: 0.7.0 + */ +const gchar * +gdata_contacts_group_get_system_group_id (GDataContactsGroup *self) +{ + g_return_val_if_fail (GDATA_IS_CONTACTS_GROUP (self), NULL); + return self->priv->system_group_id; +} + +/** + * gdata_contacts_group_get_extended_property: + * @self: a #GDataContactsGroup + * @name: the property name; an arbitrary, unique string + * + * Gets the value of an extended property of the group. Each group can have up to 10 client-set extended properties to store data of the client's + * choosing. + * + * Return value: the property's value, or %NULL + * + * Since: 0.7.0 + */ +const gchar * +gdata_contacts_group_get_extended_property (GDataContactsGroup *self, const gchar *name) +{ + g_return_val_if_fail (GDATA_IS_CONTACTS_GROUP (self), NULL); + g_return_val_if_fail (name != NULL && *name != '\0', NULL); + return g_hash_table_lookup (self->priv->extended_properties, name); +} + +/** + * gdata_contacts_group_get_extended_properties: + * @self: a #GDataContactsGroup + * + * Gets the full list of extended properties of the group; a hash table mapping property name to value. + * + * Return value: (transfer none): a #GHashTable of extended properties + * + * Since: 0.7.0 + */ +GHashTable * +gdata_contacts_group_get_extended_properties (GDataContactsGroup *self) +{ + g_return_val_if_fail (GDATA_IS_CONTACTS_GROUP (self), NULL); + return self->priv->extended_properties; +} + +/** + * gdata_contacts_group_set_extended_property: + * @self: a #GDataContactsGroup + * @name: the property name; an arbitrary, unique string + * @value: (allow-none): the property value, or %NULL + * + * Sets the value of a group's extended property. Extended property names are unique (but of the client's choosing), and reusing the same property + * name will result in the old value of that property being overwritten. + * + * To unset a property, set @value to %NULL or an empty string. + * + * A group may have up to 10 extended properties, and each should be reasonably small (i.e. not a photo or ringtone). For more information, see the + * online documentation. + * %FALSE will be returned if you attempt to add more than 10 extended properties. + * + * Return value: %TRUE if the property was updated or deleted successfully, %FALSE otherwise + * + * Since: 0.7.0 + */ +gboolean +gdata_contacts_group_set_extended_property (GDataContactsGroup *self, const gchar *name, const gchar *value) +{ + GHashTable *extended_properties = self->priv->extended_properties; + + g_return_val_if_fail (GDATA_IS_CONTACTS_GROUP (self), FALSE); + g_return_val_if_fail (name != NULL && *name != '\0', FALSE); + + if (value == NULL || *value == '\0') { + /* Removing a property */ + g_hash_table_remove (extended_properties, name); + return TRUE; + } + + /* We can't add more than MAX_N_EXTENDED_PROPERTIES */ + if (g_hash_table_lookup (extended_properties, name) == NULL && g_hash_table_size (extended_properties) >= MAX_N_EXTENDED_PROPERTIES) + return FALSE; + + /* Updating an existing property or adding a new one */ + g_hash_table_insert (extended_properties, g_strdup (name), g_strdup (value)); + + return TRUE; +} + +/** + * gdata_contacts_group_is_deleted: + * @self: a #GDataContactsGroup + * + * Returns whether the group has recently been deleted. This will always return %FALSE unless #GDataContactsQuery:show-deleted has been set to %TRUE + * for the query which returned the group; then this function will return %TRUE only if the group has been deleted. + * + * If a group has been deleted, no other information is available about it. This is designed to allow groups to be deleted from local address + * books using incremental updates from the server (e.g. with #GDataQuery:updated-min and #GDataContactsQuery:show-deleted). + * + * Return value: %TRUE if the group has been deleted, %FALSE otherwise + * + * Since: 0.7.0 + */ +gboolean +gdata_contacts_group_is_deleted (GDataContactsGroup *self) +{ + g_return_val_if_fail (GDATA_IS_CONTACTS_GROUP (self), FALSE); + return self->priv->deleted; +} diff --git a/gdata/services/contacts/gdata-contacts-group.h b/gdata/services/contacts/gdata-contacts-group.h new file mode 100644 index 0000000..b8deaed --- /dev/null +++ b/gdata/services/contacts/gdata-contacts-group.h @@ -0,0 +1,118 @@ +/* -*- Mode: C; indent-tabs-mode: t; c-basic-offset: 8; tab-width: 8 -*- */ +/* + * GData Client + * Copyright (C) Philip Withnall 2010 + * + * GData Client is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * GData Client is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with GData Client. If not, see . + */ + +#ifndef GDATA_CONTACTS_GROUP_H +#define GDATA_CONTACTS_GROUP_H + +#include +#include + +#include + +G_BEGIN_DECLS + +/** + * GDATA_CONTACTS_GROUP_CONTACTS: + * + * The system group ID for the "My Contacts" system group. + * + * Since: 0.7.0 + */ +#define GDATA_CONTACTS_GROUP_CONTACTS "Contacts" + +/** + * GDATA_CONTACTS_GROUP_FRIENDS: + * + * The system group ID for the "Friends" system group. + * + * Since: 0.7.0 + */ +#define GDATA_CONTACTS_GROUP_FRIENDS "Friends" + +/** + * GDATA_CONTACTS_GROUP_FAMILY: + * + * The system group ID for the "Family" system group. + * + * Since: 0.7.0 + */ +#define GDATA_CONTACTS_GROUP_FAMILY "Family" + +/** + * GDATA_CONTACTS_GROUP_COWORKERS: + * + * The system group ID for the "Coworkers" system group. + * + * Since: 0.7.0 + */ +#define GDATA_CONTACTS_GROUP_COWORKERS "Coworkers" + +#define GDATA_TYPE_CONTACTS_GROUP (gdata_contacts_group_get_type ()) +#define GDATA_CONTACTS_GROUP(o) (G_TYPE_CHECK_INSTANCE_CAST ((o), GDATA_TYPE_CONTACTS_GROUP, GDataContactsGroup)) +#define GDATA_CONTACTS_GROUP_CLASS(k) (G_TYPE_CHECK_CLASS_CAST((k), GDATA_TYPE_CONTACTS_GROUP, GDataContactsGroupClass)) +#define GDATA_IS_CONTACTS_GROUP(o) (G_TYPE_CHECK_INSTANCE_TYPE ((o), GDATA_TYPE_CONTACTS_GROUP)) +#define GDATA_IS_CONTACTS_GROUP_CLASS(k) (G_TYPE_CHECK_CLASS_TYPE ((k), GDATA_TYPE_CONTACTS_GROUP)) +#define GDATA_CONTACTS_GROUP_GET_CLASS(o) (G_TYPE_INSTANCE_GET_CLASS ((o), GDATA_TYPE_CONTACTS_GROUP, GDataContactsGroupClass)) + +typedef struct _GDataContactsGroupPrivate GDataContactsGroupPrivate; + +/** + * GDataContactsGroup: + * + * All the fields in the #GDataContactsGroup structure are private and should never be accessed directly. + * + * Since: 0.7.0 + */ +typedef struct { + GDataEntry parent; + GDataContactsGroupPrivate *priv; +} GDataContactsGroup; + +/** + * GDataContactsGroupClass: + * + * All the fields in the #GDataContactsGroupClass structure are private and should never be accessed directly. + * + * Since: 0.7.0 + */ +typedef struct { + /*< private >*/ + GDataEntryClass parent; + + /*< private >*/ + /* Padding for future expansion */ + void (*_g_reserved0) (void); + void (*_g_reserved1) (void); +} GDataContactsGroupClass; + +GType gdata_contacts_group_get_type (void) G_GNUC_CONST; + +GDataContactsGroup *gdata_contacts_group_new (const gchar *id) G_GNUC_WARN_UNUSED_RESULT G_GNUC_MALLOC; + +gint64 gdata_contacts_group_get_edited (GDataContactsGroup *self); +gboolean gdata_contacts_group_is_deleted (GDataContactsGroup *self) G_GNUC_PURE; +const gchar *gdata_contacts_group_get_system_group_id (GDataContactsGroup *self) G_GNUC_PURE; + +const gchar *gdata_contacts_group_get_extended_property (GDataContactsGroup *self, const gchar *name) G_GNUC_PURE; +GHashTable *gdata_contacts_group_get_extended_properties (GDataContactsGroup *self) G_GNUC_PURE; +gboolean gdata_contacts_group_set_extended_property (GDataContactsGroup *self, const gchar *name, const gchar *value); + +G_END_DECLS + +#endif /* !GDATA_CONTACTS_GROUP_H */ diff --git a/gdata/services/contacts/gdata-contacts-query.c b/gdata/services/contacts/gdata-contacts-query.c new file mode 100644 index 0000000..3f3fab5 --- /dev/null +++ b/gdata/services/contacts/gdata-contacts-query.c @@ -0,0 +1,488 @@ +/* -*- Mode: C; indent-tabs-mode: t; c-basic-offset: 8; tab-width: 8 -*- */ +/* + * GData Client + * Copyright (C) Philip Withnall 2009–2010 + * + * GData Client is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * GData Client is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with GData Client. If not, see . + */ + +/** + * SECTION:gdata-contacts-query + * @short_description: GData Contacts query object + * @stability: Stable + * @include: gdata/services/contacts/gdata-contacts-query.h + * + * #GDataContactsQuery represents a collection of query parameters specific to the Google Contacts service, which go above and beyond + * those catered for by #GDataQuery. + * + * For more information on the custom GData query parameters supported by #GDataContactsQuery, see the online documentation. + * + * + * Querying for Contacts + * + * GDataContactsService *service; + * gchar *group_id; + * GDataContactsQuery *query; + * GDataFeed *feed; + * GList *i; + * GError *error = NULL; + * + * /* Create a service and return the group we're querying within. */ + * service = create_contacts_service (); + * group_id = query_user_for_group (service); + * + * /* Create the query to use. We're going to query for contacts which match the search term "John" within a given group, + * * including deleted contacts. The group is specified by its ID. */ + * query = gdata_contacts_query_new ("John"); + * gdata_contacts_query_set_show_deleted (query, TRUE); + * gdata_contacts_query_set_group (query, group_id); + * + * g_free (group_id); + * + * /* Execute the query */ + * feed = gdata_contacts_service_query_contacts (service, query, NULL, NULL, NULL, &error); + * + * g_object_unref (query); + * g_object_unref (service); + * + * if (error != NULL) { + * g_error ("Error querying for contacts: %s", error->message); + * g_error_free (error); + * return; + * } + * + * /* Iterate through the returned contacts and do something with them */ + * for (i = gdata_feed_get_entries (feed); i != NULL; i = i->next) { + * GDataContactsContact *contact = GDATA_CONTACTS_CONTACT (i->data); + * + * /* Do something with the contact here, such as insert it into a UI */ + * } + * + * g_object_unref (feed); + * + * + * + * Since: 0.2.0 + */ + +#include +#include +#include +#include + +#include "gdata-contacts-query.h" +#include "gdata-query.h" +#include "gdata-private.h" + +static void gdata_contacts_query_finalize (GObject *object); +static void gdata_contacts_query_get_property (GObject *object, guint property_id, GValue *value, GParamSpec *pspec); +static void gdata_contacts_query_set_property (GObject *object, guint property_id, const GValue *value, GParamSpec *pspec); +static void get_query_uri (GDataQuery *self, const gchar *feed_uri, GString *query_uri, gboolean *params_started); + +struct _GDataContactsQueryPrivate { + gchar *order_by; /* TODO: #defined values */ + gboolean show_deleted; + gchar *sort_order; /* TODO: #defined values */ + gchar *group; +}; + +enum { + PROP_ORDER_BY = 1, + PROP_SHOW_DELETED, + PROP_SORT_ORDER, + PROP_GROUP +}; + +G_DEFINE_TYPE (GDataContactsQuery, gdata_contacts_query, GDATA_TYPE_QUERY) + +static void +gdata_contacts_query_class_init (GDataContactsQueryClass *klass) +{ + GObjectClass *gobject_class = G_OBJECT_CLASS (klass); + GDataQueryClass *query_class = GDATA_QUERY_CLASS (klass); + + g_type_class_add_private (klass, sizeof (GDataContactsQueryPrivate)); + + gobject_class->set_property = gdata_contacts_query_set_property; + gobject_class->get_property = gdata_contacts_query_get_property; + gobject_class->finalize = gdata_contacts_query_finalize; + + query_class->get_query_uri = get_query_uri; + + /** + * GDataContactsQuery:order-by: + * + * Sorting criterion. The only supported value is lastmodified. + * + * Since: 0.2.0 + */ + g_object_class_install_property (gobject_class, PROP_ORDER_BY, + g_param_spec_string ("order-by", + "Order by", "Sorting criterion.", + NULL, + G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)); + + /** + * GDataContactsQuery:show-deleted: + * + * Whether to include deleted contacts in the query feed. Deleted contacts return %TRUE + * from gdata_contacts_contact_is_deleted(), and have no other information. They do not + * normally appear in query results. + * + * Since: 0.2.0 + */ + g_object_class_install_property (gobject_class, PROP_SHOW_DELETED, + g_param_spec_boolean ("show-deleted", + "Show deleted?", "Whether to include deleted contacts in the query feed.", + FALSE, + G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)); + + /** + * GDataContactsQuery:sort-order: + * + * Sorting order direction. Can be either ascending or descending. + * + * Since: 0.2.0 + */ + g_object_class_install_property (gobject_class, PROP_SORT_ORDER, + g_param_spec_string ("sort-order", + "Sort order", "Sorting order direction.", + NULL, + G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)); + + /** + * GDataContactsQuery:group: + * + * Constrains the results to only those belonging to the group specified. The value of this parameter + * should be a group ID URI. + * + * Since: 0.2.0 + */ + g_object_class_install_property (gobject_class, PROP_GROUP, + g_param_spec_string ("group", + "Group", "Constrains the results to only those belonging to the group specified.", + NULL, + G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)); +} + +static void +gdata_contacts_query_init (GDataContactsQuery *self) +{ + self->priv = G_TYPE_INSTANCE_GET_PRIVATE (self, GDATA_TYPE_CONTACTS_QUERY, GDataContactsQueryPrivate); + + /* https://developers.google.com/google-apps/contacts/v3/reference#contacts-query-parameters-reference + * indicates that the Contacts service uses index pagination, but all + * the results include next/previous URIs, so use those instead. + * (We have to — the #GDataService code will use them unconditionally.) */ + _gdata_query_set_pagination_type (GDATA_QUERY (self), + GDATA_QUERY_PAGINATION_URIS); +} + +static void +gdata_contacts_query_finalize (GObject *object) +{ + GDataContactsQueryPrivate *priv = GDATA_CONTACTS_QUERY (object)->priv; + + g_free (priv->order_by); + g_free (priv->sort_order); + g_free (priv->group); + + /* Chain up to the parent class */ + G_OBJECT_CLASS (gdata_contacts_query_parent_class)->finalize (object); +} + +static void +gdata_contacts_query_get_property (GObject *object, guint property_id, GValue *value, GParamSpec *pspec) +{ + GDataContactsQueryPrivate *priv = GDATA_CONTACTS_QUERY (object)->priv; + + switch (property_id) { + case PROP_ORDER_BY: + g_value_set_string (value, priv->order_by); + break; + case PROP_SHOW_DELETED: + g_value_set_boolean (value, priv->show_deleted); + break; + case PROP_SORT_ORDER: + g_value_set_string (value, priv->sort_order); + break; + case PROP_GROUP: + g_value_set_string (value, priv->group); + break; + default: + /* We don't have any other property... */ + G_OBJECT_WARN_INVALID_PROPERTY_ID (object, property_id, pspec); + break; + } +} + +static void +gdata_contacts_query_set_property (GObject *object, guint property_id, const GValue *value, GParamSpec *pspec) +{ + GDataContactsQuery *self = GDATA_CONTACTS_QUERY (object); + + switch (property_id) { + case PROP_ORDER_BY: + gdata_contacts_query_set_order_by (self, g_value_get_string (value)); + break; + case PROP_SHOW_DELETED: + gdata_contacts_query_set_show_deleted (self, g_value_get_boolean (value)); + break; + case PROP_SORT_ORDER: + gdata_contacts_query_set_sort_order (self, g_value_get_string (value)); + break; + case PROP_GROUP: + gdata_contacts_query_set_group (self, g_value_get_string (value)); + break; + default: + /* We don't have any other property... */ + G_OBJECT_WARN_INVALID_PROPERTY_ID (object, property_id, pspec); + break; + } +} + +static void +get_query_uri (GDataQuery *self, const gchar *feed_uri, GString *query_uri, gboolean *params_started) +{ + GDataContactsQueryPrivate *priv = GDATA_CONTACTS_QUERY (self)->priv; + + #define APPEND_SEP g_string_append_c (query_uri, (*params_started == FALSE) ? '?' : '&'); *params_started = TRUE; + + /* Chain up to the parent class */ + GDATA_QUERY_CLASS (gdata_contacts_query_parent_class)->get_query_uri (self, feed_uri, query_uri, params_started); + + if (priv->order_by != NULL) { + APPEND_SEP + g_string_append (query_uri, "orderby="); + g_string_append_uri_escaped (query_uri, priv->order_by, NULL, FALSE); + } + + APPEND_SEP + if (priv->show_deleted == TRUE) + g_string_append (query_uri, "showdeleted=true"); + else + g_string_append (query_uri, "showdeleted=false"); + + if (priv->sort_order != NULL) { + APPEND_SEP + g_string_append (query_uri, "sortorder="); + g_string_append_uri_escaped (query_uri, priv->sort_order, NULL, FALSE); + } + + if (priv->group != NULL) { + APPEND_SEP + g_string_append (query_uri, "group="); + g_string_append_uri_escaped (query_uri, priv->group, NULL, FALSE); + } +} + +/** + * gdata_contacts_query_new: + * @q: (allow-none): a query string, or %NULL + * + * Creates a new #GDataContactsQuery with its #GDataQuery:q property set to @q. + * + * Return value: a new #GDataContactsQuery + * + * Since: 0.2.0 + */ +GDataContactsQuery * +gdata_contacts_query_new (const gchar *q) +{ + return g_object_new (GDATA_TYPE_CONTACTS_QUERY, "q", q, NULL); +} + +/** + * gdata_contacts_query_new_with_limits: + * @q: (allow-none): a query string, or %NULL + * @start_index: a one-based start index for the results, or 0 + * @max_results: the maximum number of results to return, or 0 + * + * Creates a new #GDataContactsQuery with its #GDataQuery:q property set to @q, and the limits @start_index and @max_results + * applied. + * + * Return value: a new #GDataContactsQuery + * + * Since: 0.2.0 + */ +GDataContactsQuery * +gdata_contacts_query_new_with_limits (const gchar *q, guint start_index, guint max_results) +{ + return g_object_new (GDATA_TYPE_CONTACTS_QUERY, + "q", q, + "start-index", start_index, + "max-results", max_results, + NULL); +} + +/** + * gdata_contacts_query_get_order_by: + * @self: a #GDataContactsQuery + * + * Gets the #GDataContactsQuery:order-by property. + * + * Return value: the order by property, or %NULL if it is unset + * + * Since: 0.2.0 + */ +const gchar * +gdata_contacts_query_get_order_by (GDataContactsQuery *self) +{ + g_return_val_if_fail (GDATA_IS_CONTACTS_QUERY (self), NULL); + return self->priv->order_by; +} + +/** + * gdata_contacts_query_set_order_by: + * @self: a #GDataContactsQuery + * @order_by: (allow-none): a new order by string, or %NULL + * + * Sets the #GDataContactsQuery:order-by property of the #GDataContactsQuery to the new order by string, @order_by. + * + * Set @order_by to %NULL to unset the property in the query URI. + * + * Since: 0.2.0 + */ +void +gdata_contacts_query_set_order_by (GDataContactsQuery *self, const gchar *order_by) +{ + g_return_if_fail (GDATA_IS_CONTACTS_QUERY (self)); + + g_free (self->priv->order_by); + self->priv->order_by = g_strdup (order_by); + g_object_notify (G_OBJECT (self), "order-by"); + + /* Our current ETag will no longer be relevant */ + gdata_query_set_etag (GDATA_QUERY (self), NULL); +} + +/** + * gdata_contacts_query_show_deleted: + * @self: a #GDataContactsQuery + * + * Gets the #GDataContactsQuery:show-deleted property. + * + * Return value: %TRUE if deleted contacts should be shown, %FALSE otherwise + * + * Since: 0.2.0 + */ +gboolean +gdata_contacts_query_show_deleted (GDataContactsQuery *self) +{ + g_return_val_if_fail (GDATA_IS_CONTACTS_QUERY (self), FALSE); + return self->priv->show_deleted; +} + +/** + * gdata_contacts_query_set_show_deleted: + * @self: a #GDataContactsQuery + * @show_deleted: %TRUE to show deleted contacts, %FALSE otherwise + * + * Sets the #GDataContactsQuery:show-deleted property of the #GDataContactsQuery. + * + * Since: 0.2.0 + */ +void +gdata_contacts_query_set_show_deleted (GDataContactsQuery *self, gboolean show_deleted) +{ + g_return_if_fail (GDATA_IS_CONTACTS_QUERY (self)); + self->priv->show_deleted = show_deleted; + g_object_notify (G_OBJECT (self), "show-deleted"); + + /* Our current ETag will no longer be relevant */ + gdata_query_set_etag (GDATA_QUERY (self), NULL); +} + +/** + * gdata_contacts_query_get_sort_order: + * @self: a #GDataContactsQuery + * + * Gets the #GDataContactsQuery:sort-order property. + * + * Return value: the sort order property, or %NULL if it is unset + * + * Since: 0.2.0 + */ +const gchar * +gdata_contacts_query_get_sort_order (GDataContactsQuery *self) +{ + g_return_val_if_fail (GDATA_IS_CONTACTS_QUERY (self), NULL); + return self->priv->sort_order; +} + +/** + * gdata_contacts_query_set_sort_order: + * @self: a #GDataContactsQuery + * @sort_order: (allow-none): a new sort order string, or %NULL + * + * Sets the #GDataContactsQuery:sort-order property of the #GDataContactsQuery to the new sort order string, @sort_order. + * + * Set @sort_order to %NULL to unset the property in the query URI. + * + * Since: 0.2.0 + */ +void +gdata_contacts_query_set_sort_order (GDataContactsQuery *self, const gchar *sort_order) +{ + g_return_if_fail (GDATA_IS_CONTACTS_QUERY (self)); + + g_free (self->priv->sort_order); + self->priv->sort_order = g_strdup (sort_order); + g_object_notify (G_OBJECT (self), "sort-order"); + + /* Our current ETag will no longer be relevant */ + gdata_query_set_etag (GDATA_QUERY (self), NULL); +} + +/** + * gdata_contacts_query_get_group: + * @self: a #GDataContactsQuery + * + * Gets the #GDataContactsQuery:group property. + * + * Return value: the group property, or %NULL if it is unset + * + * Since: 0.2.0 + */ +const gchar * +gdata_contacts_query_get_group (GDataContactsQuery *self) +{ + g_return_val_if_fail (GDATA_IS_CONTACTS_QUERY (self), NULL); + return self->priv->group; +} + +/** + * gdata_contacts_query_set_group: + * @self: a #GDataContactsQuery + * @group: (allow-none): a new group ID URI, or %NULL + * + * Sets the #GDataContactsQuery:group property of the #GDataContactsQuery to the new group ID URI, @group. + * + * Set @group to %NULL to unset the property in the query URI. + * + * Since: 0.2.0 + */ +void +gdata_contacts_query_set_group (GDataContactsQuery *self, const gchar *group) +{ + g_return_if_fail (GDATA_IS_CONTACTS_QUERY (self)); + + g_free (self->priv->group); + self->priv->group = g_strdup (group); + g_object_notify (G_OBJECT (self), "group"); + + /* Our current ETag will no longer be relevant */ + gdata_query_set_etag (GDATA_QUERY (self), NULL); +} diff --git a/gdata/services/contacts/gdata-contacts-query.h b/gdata/services/contacts/gdata-contacts-query.h new file mode 100644 index 0000000..f215645 --- /dev/null +++ b/gdata/services/contacts/gdata-contacts-query.h @@ -0,0 +1,85 @@ +/* -*- Mode: C; indent-tabs-mode: t; c-basic-offset: 8; tab-width: 8 -*- */ +/* + * GData Client + * Copyright (C) Philip Withnall 2009–2010 + * + * GData Client is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * GData Client is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with GData Client. If not, see . + */ + +#ifndef GDATA_CONTACTS_QUERY_H +#define GDATA_CONTACTS_QUERY_H + +#include +#include + +#include + +G_BEGIN_DECLS + +#define GDATA_TYPE_CONTACTS_QUERY (gdata_contacts_query_get_type ()) +#define GDATA_CONTACTS_QUERY(o) (G_TYPE_CHECK_INSTANCE_CAST ((o), GDATA_TYPE_CONTACTS_QUERY, GDataContactsQuery)) +#define GDATA_CONTACTS_QUERY_CLASS(k) (G_TYPE_CHECK_CLASS_CAST((k), GDATA_TYPE_CONTACTS_QUERY, GDataContactsQueryClass)) +#define GDATA_IS_CONTACTS_QUERY(o) (G_TYPE_CHECK_INSTANCE_TYPE ((o), GDATA_TYPE_CONTACTS_QUERY)) +#define GDATA_IS_CONTACTS_QUERY_CLASS(k) (G_TYPE_CHECK_CLASS_TYPE ((k), GDATA_TYPE_CONTACTS_QUERY)) +#define GDATA_CONTACTS_QUERY_GET_CLASS(o) (G_TYPE_INSTANCE_GET_CLASS ((o), GDATA_TYPE_CONTACTS_QUERY, GDataContactsQueryClass)) + +typedef struct _GDataContactsQueryPrivate GDataContactsQueryPrivate; + +/** + * GDataContactsQuery: + * + * All the fields in the #GDataContactsQuery structure are private and should never be accessed directly. + * + * Since: 0.2.0 + */ +typedef struct { + GDataQuery parent; + GDataContactsQueryPrivate *priv; +} GDataContactsQuery; + +/** + * GDataContactsQueryClass: + * + * All the fields in the #GDataContactsQueryClass structure are private and should never be accessed directly. + * + * Since: 0.2.0 + */ +typedef struct { + /*< private >*/ + GDataQueryClass parent; + + /*< private >*/ + /* Padding for future expansion */ + void (*_g_reserved0) (void); + void (*_g_reserved1) (void); +} GDataContactsQueryClass; + +GType gdata_contacts_query_get_type (void) G_GNUC_CONST; + +GDataContactsQuery *gdata_contacts_query_new (const gchar *q) G_GNUC_WARN_UNUSED_RESULT G_GNUC_MALLOC; +GDataContactsQuery *gdata_contacts_query_new_with_limits (const gchar *q, guint start_index, + guint max_results) G_GNUC_WARN_UNUSED_RESULT G_GNUC_MALLOC; + +const gchar *gdata_contacts_query_get_order_by (GDataContactsQuery *self) G_GNUC_PURE; +void gdata_contacts_query_set_order_by (GDataContactsQuery *self, const gchar *order_by); +gboolean gdata_contacts_query_show_deleted (GDataContactsQuery *self) G_GNUC_PURE; +void gdata_contacts_query_set_show_deleted (GDataContactsQuery *self, gboolean show_deleted); +const gchar *gdata_contacts_query_get_sort_order (GDataContactsQuery *self) G_GNUC_PURE; +void gdata_contacts_query_set_sort_order (GDataContactsQuery *self, const gchar *sort_order); +const gchar *gdata_contacts_query_get_group (GDataContactsQuery *self) G_GNUC_PURE; +void gdata_contacts_query_set_group (GDataContactsQuery *self, const gchar *group); + +G_END_DECLS + +#endif /* !GDATA_CONTACTS_QUERY_H */ diff --git a/gdata/services/contacts/gdata-contacts-service.c b/gdata/services/contacts/gdata-contacts-service.c new file mode 100644 index 0000000..62d7c32 --- /dev/null +++ b/gdata/services/contacts/gdata-contacts-service.c @@ -0,0 +1,568 @@ +/* -*- Mode: C; indent-tabs-mode: t; c-basic-offset: 8; tab-width: 8 -*- */ +/* + * GData Client + * Copyright (C) Philip Withnall 2009 + * + * GData Client is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * GData Client is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with GData Client. If not, see . + */ + +/** + * SECTION:gdata-contacts-service + * @short_description: GData Contacts service object + * @stability: Stable + * @include: gdata/services/contacts/gdata-contacts-service.h + * + * #GDataContactsService is a subclass of #GDataService for communicating with the GData API of Google Contacts. It supports querying + * for, inserting, editing and deleting contacts from a Google address book. + * + * For more details of Google Contacts' GData API, see the + * online documentation. + * + * + * Querying for Groups + * + * GDataContactsService *service; + * GDataFeed *feed; + * GList *i; + * GError *error = NULL; + * + * /* Create a service */ + * service = create_contacts_service (); + * + * /* Query for groups */ + * feed = gdata_contacts_service_query_groups (service, NULL, NULL, NULL, NULL, &error); + * + * g_object_unref (service); + * + * if (error != NULL) { + * g_error ("Error querying for groups: %s", error->message); + * g_error_free (error); + * return; + * } + * + * /* Iterate through the returned groups and do something with them */ + * for (i = gdata_feed_get_entries (feed); i != NULL; i = i->next) { + * const gchar *system_group_id, *group_name; + * gboolean is_system_group; + * GDataContactsGroup *group = GDATA_CONTACTS_GROUP (i->data); + * + * /* Determine whether the group's a system group. If so, you should use the system group ID to provide your application's own + * * translations of the group name, as it's not translated. */ + * system_group_id = gdata_contacts_group_get_system_group_id (group); + * is_system_group = (system_group_id != NULL) ? TRUE : FALSE; + * group_name = (is_system_group == TRUE) ? get_group_name_for_system_group_id (system_group_id) + * : gdata_entry_get_title (GDATA_ENTRY (group)); + * + * /* Do something with the group here, such as insert it into a UI. Note that system groups are not allowed to be deleted, + * * so you may want to make certain parts of your UI insensitive accordingly if the group is a system group. */ + * } + * + * g_object_unref (feed); + * + * + * + * The Contacts service can be manipulated using batch operations, too. See the + * online documentation on batch + * operations for more information. + * + * + * Performing a Batch Operation on Contacts + * + * GDataContactsService *service; + * GDataBatchOperation *operation; + * GDataFeed *feed; + * GDataLink *batch_link; + * GList *i; + * GError *error = NULL; + * + * /* Create a service */ + * service = create_contacts_service (); + * + * /* Create the batch operation; this requires that we have done a query first so that we can get the batch link */ + * feed = do_some_query (service); + * batch_link = gdata_feed_look_up_link (feed, GDATA_LINK_BATCH); + * operation = gdata_batchable_create_operation (GDATA_BATCHABLE (service), gdata_link_get_uri (batch_link)); + * g_object_unref (feed); + * + * gdata_batch_operation_add_query (operation, contact_entry_id_to_query, GDATA_TYPE_CONTACTS_CONTACT, + * (GDataBatchOperationCallback) batch_query_cb, user_data); + * gdata_batch_operation_add_insertion (operation, new_entry, (GDataBatchOperationCallback) batch_insertion_cb, user_data); + * gdata_batch_operation_add_update (operation, old_entry, (GDataBatchOperationCallback) batch_update_cb, user_data); + * gdata_batch_operation_add_deletion (operation, entry_to_delete, (GDataBatchOperationCallback) batch_deletion_cb, user_data); + * + * /* Run the batch operation and handle the results in the various callbacks */ + * gdata_test_batch_operation_run (operation, NULL, &error); + * + * g_object_unref (operation); + * g_object_unref (service); + * + * if (error != NULL) { + * g_error ("Error running batch operation: %s", error->message); + * g_error_free (error); + * return; + * } + * + * static void + * batch_query_cb (guint operation_id, GDataBatchOperationType operation_type, GDataEntry *entry, GError *error, gpointer user_data) + * { + * /* operation_type == GDATA_BATCH_OPERATION_QUERY */ + * /* Reference and do something with the returned entry. */ + * } + * + * static void + * batch_insertion_cb (guint operation_id, GDataBatchOperationType operation_type, GDataEntry *entry, GError *error, gpointer user_data) + * { + * /* operation_type == GDATA_BATCH_OPERATION_INSERTION */ + * /* Reference and do something with the returned entry. */ + * } + * + * static void + * batch_update_cb (guint operation_id, GDataBatchOperationType operation_type, GDataEntry *entry, GError *error, gpointer user_data) + * { + * /* operation_type == GDATA_BATCH_OPERATION_UPDATE */ + * /* Reference and do something with the returned entry. */ + * } + * + * static void + * batch_deletion_cb (guint operation_id, GDataBatchOperationType operation_type, GDataEntry *entry, GError *error, gpointer user_data) + * { + * /* operation_type == GDATA_BATCH_OPERATION_DELETION, entry == NULL */ + * } + * + * + * + * Since: 0.2.0 + */ + +#include +#include +#include +#include +#include + +#include "gdata-contacts-service.h" +#include "gdata-batchable.h" +#include "gdata-service.h" +#include "gdata-private.h" +#include "gdata-query.h" + +static GList *get_authorization_domains (void); + +_GDATA_DEFINE_AUTHORIZATION_DOMAIN (contacts, "cp", "https://www.google.com/m8/feeds/") +G_DEFINE_TYPE_WITH_CODE (GDataContactsService, gdata_contacts_service, GDATA_TYPE_SERVICE, + G_IMPLEMENT_INTERFACE (GDATA_TYPE_BATCHABLE, NULL)) + +static void +gdata_contacts_service_class_init (GDataContactsServiceClass *klass) +{ + GDataServiceClass *service_class = GDATA_SERVICE_CLASS (klass); + service_class->api_version = "3"; + service_class->get_authorization_domains = get_authorization_domains; +} + +static void +gdata_contacts_service_init (GDataContactsService *self) +{ + /* Nothing to see here */ +} + +static GList * +get_authorization_domains (void) +{ + return g_list_prepend (NULL, get_contacts_authorization_domain ()); +} + +/** + * gdata_contacts_service_new: + * @authorizer: (allow-none): a #GDataAuthorizer to authorize the service's requests, or %NULL + * + * Creates a new #GDataContactsService using the given #GDataAuthorizer. If @authorizer is %NULL, all requests are made as an unauthenticated user. + * + * Return value: a new #GDataContactsService, or %NULL; unref with g_object_unref() + * + * Since: 0.9.0 + */ +GDataContactsService * +gdata_contacts_service_new (GDataAuthorizer *authorizer) +{ + g_return_val_if_fail (authorizer == NULL || GDATA_IS_AUTHORIZER (authorizer), NULL); + + return g_object_new (GDATA_TYPE_CONTACTS_SERVICE, + "authorizer", authorizer, + NULL); +} + +/** + * gdata_contacts_service_get_primary_authorization_domain: + * + * The primary #GDataAuthorizationDomain for interacting with Google Contacts. This will not normally need to be used, as it's used internally + * by the #GDataContactsService methods. However, if using the plain #GDataService methods to implement custom queries or requests which libgdata + * does not support natively, then this domain may be needed to authorize the requests. + * + * The domain never changes, and is interned so that pointer comparison can be used to differentiate it from other authorization domains. + * + * Return value: (transfer none): the service's authorization domain + * + * Since: 0.9.0 + */ +GDataAuthorizationDomain * +gdata_contacts_service_get_primary_authorization_domain (void) +{ + return get_contacts_authorization_domain (); +} + +/** + * gdata_contacts_service_query_contacts: + * @self: a #GDataContactsService + * @query: (allow-none): a #GDataQuery with the query parameters, or %NULL + * @cancellable: (allow-none): optional #GCancellable object, or %NULL + * @progress_callback: (allow-none) (scope call) (closure progress_user_data): a #GDataQueryProgressCallback to call when an entry is loaded, or %NULL + * @progress_user_data: (closure): data to pass to the @progress_callback function + * @error: a #GError, or %NULL + * + * Queries the service to return a list of contacts matching the given @query. + * + * For more details, see gdata_service_query(). + * + * Return value: (transfer full): a #GDataFeed of query results; unref with g_object_unref() + * + * Since: 0.2.0 + */ +GDataFeed * +gdata_contacts_service_query_contacts (GDataContactsService *self, GDataQuery *query, GCancellable *cancellable, + GDataQueryProgressCallback progress_callback, gpointer progress_user_data, GError **error) +{ + GDataFeed *feed; + gchar *request_uri; + + g_return_val_if_fail (GDATA_IS_CONTACTS_SERVICE (self), NULL); + g_return_val_if_fail (query == NULL || GDATA_IS_QUERY (query), NULL); + g_return_val_if_fail (cancellable == NULL || G_IS_CANCELLABLE (cancellable), NULL); + g_return_val_if_fail (error == NULL || *error == NULL, NULL); + + /* Ensure we're authenticated first */ + if (gdata_authorizer_is_authorized_for_domain (gdata_service_get_authorizer (GDATA_SERVICE (self)), + get_contacts_authorization_domain ()) == FALSE) { + g_set_error_literal (error, GDATA_SERVICE_ERROR, GDATA_SERVICE_ERROR_AUTHENTICATION_REQUIRED, + _("You must be authenticated to query contacts.")); + return NULL; + } + + request_uri = g_strconcat (_gdata_service_get_scheme (), "://www.google.com/m8/feeds/contacts/default/full", NULL); + feed = gdata_service_query (GDATA_SERVICE (self), get_contacts_authorization_domain (), request_uri, GDATA_QUERY (query), + GDATA_TYPE_CONTACTS_CONTACT, cancellable, progress_callback, progress_user_data, error); + g_free (request_uri); + + return feed; +} + +/** + * gdata_contacts_service_query_contacts_async: + * @self: a #GDataContactsService + * @query: (allow-none): a #GDataQuery with the query parameters, or %NULL + * @cancellable: (allow-none): optional #GCancellable object, or %NULL + * @progress_callback: (allow-none) (closure progress_user_data): a #GDataQueryProgressCallback to call when an entry is loaded, or %NULL + * @progress_user_data: (closure): data to pass to the @progress_callback function + * @destroy_progress_user_data: (allow-none): the function to call when @progress_callback will not be called any more, or %NULL. This function will be + * called with @progress_user_data as a parameter and can be used to free any memory allocated for it. + * @callback: a #GAsyncReadyCallback to call when the query is finished + * @user_data: (closure): data to pass to the @callback function + * + * Queries the service to return a list of contacts matching the given @query. @self and + * @query are all reffed when this function is called, so can safely be unreffed after this function returns. + * + * For more details, see gdata_contacts_service_query_contacts(), which is the synchronous version of this function, + * and gdata_service_query_async(), which is the base asynchronous query function. + * + * Since: 0.9.1 + */ +void +gdata_contacts_service_query_contacts_async (GDataContactsService *self, GDataQuery *query, GCancellable *cancellable, + GDataQueryProgressCallback progress_callback, gpointer progress_user_data, + GDestroyNotify destroy_progress_user_data, + GAsyncReadyCallback callback, gpointer user_data) +{ + gchar *request_uri; + + g_return_if_fail (GDATA_IS_CONTACTS_SERVICE (self)); + g_return_if_fail (query == NULL || GDATA_IS_QUERY (query)); + g_return_if_fail (cancellable == NULL || G_IS_CANCELLABLE (cancellable)); + g_return_if_fail (callback != NULL); + + /* Ensure we're authenticated first */ + if (gdata_authorizer_is_authorized_for_domain (gdata_service_get_authorizer (GDATA_SERVICE (self)), + get_contacts_authorization_domain ()) == FALSE) { + g_autoptr(GTask) task = NULL; + + task = g_task_new (self, cancellable, callback, user_data); + g_task_set_source_tag (task, gdata_service_query_async); + g_task_return_new_error (task, GDATA_SERVICE_ERROR, GDATA_SERVICE_ERROR_AUTHENTICATION_REQUIRED, "%s", + _("You must be authenticated to query contacts.")); + + return; + } + + request_uri = g_strconcat (_gdata_service_get_scheme (), "://www.google.com/m8/feeds/contacts/default/full", NULL); + gdata_service_query_async (GDATA_SERVICE (self), get_contacts_authorization_domain (), request_uri, GDATA_QUERY (query), + GDATA_TYPE_CONTACTS_CONTACT, cancellable, progress_callback, progress_user_data, + destroy_progress_user_data, callback, user_data); + g_free (request_uri); +} + +/** + * gdata_contacts_service_insert_contact: + * @self: a #GDataContactsService + * @contact: the #GDataContactsContact to insert + * @cancellable: (allow-none): optional #GCancellable object, or %NULL + * @error: a #GError, or %NULL + * + * Inserts @contact by uploading it to the online contacts service. + * + * For more details, see gdata_service_insert_entry(). + * + * Return value: (transfer full): an updated #GDataContactsContact, or %NULL; unref with g_object_unref() + * + * Since: 0.2.0 + */ +GDataContactsContact * +gdata_contacts_service_insert_contact (GDataContactsService *self, GDataContactsContact *contact, GCancellable *cancellable, GError **error) +{ + gchar *uri; + GDataEntry *entry; + + g_return_val_if_fail (GDATA_IS_CONTACTS_SERVICE (self), NULL); + g_return_val_if_fail (GDATA_IS_CONTACTS_CONTACT (contact), NULL); + g_return_val_if_fail (cancellable == NULL || G_IS_CANCELLABLE (cancellable), NULL); + g_return_val_if_fail (error == NULL || *error == NULL, NULL); + + uri = g_strconcat (_gdata_service_get_scheme (), "://www.google.com/m8/feeds/contacts/default/full", NULL); + entry = gdata_service_insert_entry (GDATA_SERVICE (self), get_contacts_authorization_domain (), uri, GDATA_ENTRY (contact), cancellable, + error); + g_free (uri); + + return GDATA_CONTACTS_CONTACT (entry); +} + +/** + * gdata_contacts_service_insert_contact_async: + * @self: a #GDataContactsService + * @contact: the #GDataContactsContact to insert + * @cancellable: (allow-none): optional #GCancellable object, or %NULL + * @callback: a #GAsyncReadyCallback to call when insertion is finished + * @user_data: (closure): data to pass to the @callback function + * + * Inserts @contact by uploading it to the online contacts service. @self and @contact are both reffed when this function is called, so can safely be + * unreffed after this function returns. + * + * @callback should call gdata_service_insert_entry_finish() to obtain a #GDataContactsContact representing the inserted contact and to check for + * possible errors. + * + * For more details, see gdata_contacts_service_insert_contact(), which is the synchronous version of this function, + * and gdata_service_insert_entry_async(), which is the base asynchronous insertion function. + * + * Since: 0.7.0 + */ +void +gdata_contacts_service_insert_contact_async (GDataContactsService *self, GDataContactsContact *contact, GCancellable *cancellable, + GAsyncReadyCallback callback, gpointer user_data) +{ + gchar *uri; + + g_return_if_fail (GDATA_IS_CONTACTS_SERVICE (self)); + g_return_if_fail (GDATA_IS_CONTACTS_CONTACT (contact)); + g_return_if_fail (cancellable == NULL || G_IS_CANCELLABLE (cancellable)); + + uri = g_strconcat (_gdata_service_get_scheme (), "://www.google.com/m8/feeds/contacts/default/full", NULL); + gdata_service_insert_entry_async (GDATA_SERVICE (self), get_contacts_authorization_domain (), uri, GDATA_ENTRY (contact), cancellable, + callback, user_data); + g_free (uri); +} + +/** + * gdata_contacts_service_query_groups: + * @self: a #GDataContactsService + * @query: (allow-none): a #GDataQuery with the query parameters, or %NULL + * @cancellable: (allow-none): optional #GCancellable object, or %NULL + * @progress_callback: (allow-none) (scope call) (closure progress_user_data): a #GDataQueryProgressCallback to call when an entry is loaded, or %NULL + * @progress_user_data: (closure): data to pass to the @progress_callback function + * @error: a #GError, or %NULL + * + * Queries the service to return a list of groups matching the given @query. + * + * For more details, see gdata_service_query(). + * + * Return value: (transfer full): a #GDataFeed of query results; unref with g_object_unref() + * + * Since: 0.7.0 + */ +GDataFeed * +gdata_contacts_service_query_groups (GDataContactsService *self, GDataQuery *query, GCancellable *cancellable, + GDataQueryProgressCallback progress_callback, gpointer progress_user_data, GError **error) +{ + GDataFeed *feed; + gchar *request_uri; + + g_return_val_if_fail (GDATA_IS_CONTACTS_SERVICE (self), NULL); + g_return_val_if_fail (query == NULL || GDATA_IS_QUERY (query), NULL); + g_return_val_if_fail (cancellable == NULL || G_IS_CANCELLABLE (cancellable), NULL); + g_return_val_if_fail (error == NULL || *error == NULL, NULL); + + /* Ensure we're authenticated first */ + if (gdata_authorizer_is_authorized_for_domain (gdata_service_get_authorizer (GDATA_SERVICE (self)), + get_contacts_authorization_domain ()) == FALSE) { + g_set_error_literal (error, GDATA_SERVICE_ERROR, GDATA_SERVICE_ERROR_AUTHENTICATION_REQUIRED, + _("You must be authenticated to query contact groups.")); + return NULL; + } + + request_uri = g_strconcat (_gdata_service_get_scheme (), "://www.google.com/m8/feeds/groups/default/full", NULL); + feed = gdata_service_query (GDATA_SERVICE (self), get_contacts_authorization_domain (), request_uri, GDATA_QUERY (query), + GDATA_TYPE_CONTACTS_GROUP, cancellable, progress_callback, progress_user_data, error); + g_free (request_uri); + + return feed; +} + +/** + * gdata_contacts_service_query_groups_async: + * @self: a #GDataContactsService + * @query: (allow-none): a #GDataQuery with the query parameters, or %NULL + * @cancellable: (allow-none): optional #GCancellable object, or %NULL + * @progress_callback: (allow-none) (closure progress_user_data): a #GDataQueryProgressCallback to call when an entry is loaded, or %NULL + * @progress_user_data: (closure): data to pass to the @progress_callback function + * @destroy_progress_user_data: (allow-none): the function to call when @progress_callback will not be called any more, or %NULL. This function will be + * called with @progress_user_data as a parameter and can be used to free any memory allocated for it. + * @callback: a #GAsyncReadyCallback to call when the query is finished + * @user_data: (closure): data to pass to the @callback function + * + * Queries the service to return a list of groups matching the given @query. @self and @query are all reffed when this function is called, so can + * safely be unreffed after this function returns. + * + * For more details, see gdata_contacts_service_query_groups(), which is the synchronous version of this function, and gdata_service_query_async(), + * which is the base asynchronous query function. + * + * Since: 0.9.1 + */ +void +gdata_contacts_service_query_groups_async (GDataContactsService *self, GDataQuery *query, GCancellable *cancellable, + GDataQueryProgressCallback progress_callback, gpointer progress_user_data, + GDestroyNotify destroy_progress_user_data, + GAsyncReadyCallback callback, gpointer user_data) +{ + gchar *request_uri; + + g_return_if_fail (GDATA_IS_CONTACTS_SERVICE (self)); + g_return_if_fail (query == NULL || GDATA_IS_QUERY (query)); + g_return_if_fail (cancellable == NULL || G_IS_CANCELLABLE (cancellable)); + g_return_if_fail (callback != NULL); + + /* Ensure we're authenticated first */ + if (gdata_authorizer_is_authorized_for_domain (gdata_service_get_authorizer (GDATA_SERVICE (self)), + get_contacts_authorization_domain ()) == FALSE) { + g_autoptr(GTask) task = NULL; + + task = g_task_new (self, cancellable, callback, user_data); + g_task_set_source_tag (task, gdata_service_query_async); + g_task_return_new_error (task, GDATA_SERVICE_ERROR, GDATA_SERVICE_ERROR_AUTHENTICATION_REQUIRED, "%s", + _("You must be authenticated to query contact groups.")); + + return; + } + + request_uri = g_strconcat (_gdata_service_get_scheme (), "://www.google.com/m8/feeds/groups/default/full", NULL); + gdata_service_query_async (GDATA_SERVICE (self), get_contacts_authorization_domain (), request_uri, GDATA_QUERY (query), + GDATA_TYPE_CONTACTS_GROUP, cancellable, progress_callback, progress_user_data, + destroy_progress_user_data, callback, user_data); + g_free (request_uri); +} + +/** + * gdata_contacts_service_insert_group: + * @self: a #GDataContactsService + * @group: a #GDataContactsGroup to create on the server + * @cancellable: (allow-none): optional #GCancellable object, or %NULL + * @error: a #GError, or %NULL + * + * Inserts a new contact group described by @group. The user must be authenticated to use this function. + * + * Return value: (transfer full): the inserted #GDataContactsGroup; unref with g_object_unref() + * + * Since: 0.7.0 + */ +GDataContactsGroup * +gdata_contacts_service_insert_group (GDataContactsService *self, GDataContactsGroup *group, GCancellable *cancellable, GError **error) +{ + gchar *request_uri; + GDataEntry *new_group; + + g_return_val_if_fail (GDATA_IS_CONTACTS_SERVICE (self), NULL); + g_return_val_if_fail (GDATA_IS_CONTACTS_GROUP (group), NULL); + g_return_val_if_fail (cancellable == NULL || G_IS_CANCELLABLE (cancellable), NULL); + g_return_val_if_fail (error == NULL || *error == NULL, NULL); + + if (gdata_entry_is_inserted (GDATA_ENTRY (group)) == TRUE) { + g_set_error_literal (error, GDATA_SERVICE_ERROR, GDATA_SERVICE_ERROR_ENTRY_ALREADY_INSERTED, + _("The group has already been inserted.")); + return NULL; + } + + if (gdata_authorizer_is_authorized_for_domain (gdata_service_get_authorizer (GDATA_SERVICE (self)), + get_contacts_authorization_domain ()) == FALSE) { + g_set_error_literal (error, GDATA_SERVICE_ERROR, GDATA_SERVICE_ERROR_AUTHENTICATION_REQUIRED, + _("You must be authenticated to insert a group.")); + return NULL; + } + + request_uri = g_strconcat (_gdata_service_get_scheme (), "://www.google.com/m8/feeds/groups/default/full", NULL); + new_group = gdata_service_insert_entry (GDATA_SERVICE (self), get_contacts_authorization_domain (), request_uri, GDATA_ENTRY (group), + cancellable, error); + g_free (request_uri); + + return GDATA_CONTACTS_GROUP (new_group); +} + +/** + * gdata_contacts_service_insert_group_async: + * @self: a #GDataContactsService + * @group: the #GDataContactsGroup to insert + * @cancellable: (allow-none): optional #GCancellable object, or %NULL + * @callback: a #GAsyncReadyCallback to call when insertion is finished + * @user_data: (closure): data to pass to the @callback function + * + * Inserts a new contact group described by @group. The user must be authenticated to use this function. @self and @group are both reffed when this + * function is called, so can safely be unreffed after this function returns. + * + * @callback should call gdata_service_insert_entry_finish() to obtain a #GDataContactsGroup representing the inserted group and to check for possible + * errors. + * + * For more details, see gdata_contacts_service_insert_group(), which is the synchronous version of this function, and + * gdata_service_insert_entry_async(), which is the base asynchronous insertion function. + * + * Since: 0.7.0 + */ +void +gdata_contacts_service_insert_group_async (GDataContactsService *self, GDataContactsGroup *group, GCancellable *cancellable, + GAsyncReadyCallback callback, gpointer user_data) +{ + gchar *request_uri; + + g_return_if_fail (GDATA_IS_CONTACTS_SERVICE (self)); + g_return_if_fail (GDATA_IS_CONTACTS_GROUP (group)); + g_return_if_fail (cancellable == NULL || G_IS_CANCELLABLE (cancellable)); + + request_uri = g_strconcat (_gdata_service_get_scheme (), "://www.google.com/m8/feeds/groups/default/full", NULL); + gdata_service_insert_entry_async (GDATA_SERVICE (self), get_contacts_authorization_domain (), request_uri, GDATA_ENTRY (group), cancellable, + callback, user_data); + g_free (request_uri); +} diff --git a/gdata/services/contacts/gdata-contacts-service.h b/gdata/services/contacts/gdata-contacts-service.h new file mode 100644 index 0000000..100e38d --- /dev/null +++ b/gdata/services/contacts/gdata-contacts-service.h @@ -0,0 +1,110 @@ +/* -*- Mode: C; indent-tabs-mode: t; c-basic-offset: 8; tab-width: 8 -*- */ +/* + * GData Client + * Copyright (C) Philip Withnall 2009–2010 + * + * GData Client is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * GData Client is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with GData Client. If not, see . + */ + +#ifndef GDATA_CONTACTS_SERVICE_H +#define GDATA_CONTACTS_SERVICE_H + +#include +#include + +#include +#include + +G_BEGIN_DECLS + +#define GDATA_TYPE_CONTACTS_SERVICE (gdata_contacts_service_get_type ()) +#define GDATA_CONTACTS_SERVICE(o) (G_TYPE_CHECK_INSTANCE_CAST ((o), GDATA_TYPE_CONTACTS_SERVICE, GDataContactsService)) +#define GDATA_CONTACTS_SERVICE_CLASS(k) (G_TYPE_CHECK_CLASS_CAST((k), GDATA_TYPE_CONTACTS_SERVICE, GDataContactsServiceClass)) +#define GDATA_IS_CONTACTS_SERVICE(o) (G_TYPE_CHECK_INSTANCE_TYPE ((o), GDATA_TYPE_CONTACTS_SERVICE)) +#define GDATA_IS_CONTACTS_SERVICE_CLASS(k) (G_TYPE_CHECK_CLASS_TYPE ((k), GDATA_TYPE_CONTACTS_SERVICE)) +#define GDATA_CONTACTS_SERVICE_GET_CLASS(o) (G_TYPE_INSTANCE_GET_CLASS ((o), GDATA_TYPE_CONTACTS_SERVICE, GDataContactsServiceClass)) + +typedef struct _GDataContactsServicePrivate GDataContactsServicePrivate; + +/** + * GDataContactsService: + * + * All the fields in the #GDataContactsService structure are private and should never be accessed directly. + * + * Since: 0.2.0 + */ +typedef struct { + GDataService parent; +} GDataContactsService; + +/** + * GDataContactsServiceClass: + * + * All the fields in the #GDataContactsServiceClass structure are private and should never be accessed directly. + * + * Since: 0.2.0 + */ +typedef struct { + /*< private >*/ + GDataServiceClass parent; + + /*< private >*/ + /* Padding for future expansion */ + void (*_g_reserved0) (void); + void (*_g_reserved1) (void); + void (*_g_reserved2) (void); + void (*_g_reserved3) (void); + void (*_g_reserved4) (void); + void (*_g_reserved5) (void); +} GDataContactsServiceClass; + +GType gdata_contacts_service_get_type (void) G_GNUC_CONST; + +GDataContactsService *gdata_contacts_service_new (GDataAuthorizer *authorizer) G_GNUC_WARN_UNUSED_RESULT G_GNUC_MALLOC; + +GDataAuthorizationDomain *gdata_contacts_service_get_primary_authorization_domain (void) G_GNUC_CONST; + +GDataFeed *gdata_contacts_service_query_contacts (GDataContactsService *self, GDataQuery *query, GCancellable *cancellable, + GDataQueryProgressCallback progress_callback, gpointer progress_user_data, + GError **error) G_GNUC_WARN_UNUSED_RESULT G_GNUC_MALLOC; +void gdata_contacts_service_query_contacts_async (GDataContactsService *self, GDataQuery *query, GCancellable *cancellable, + GDataQueryProgressCallback progress_callback, gpointer progress_user_data, + GDestroyNotify destroy_progress_user_data, + GAsyncReadyCallback callback, gpointer user_data); + +#include + +GDataContactsContact *gdata_contacts_service_insert_contact (GDataContactsService *self, GDataContactsContact *contact, + GCancellable *cancellable, GError **error) G_GNUC_WARN_UNUSED_RESULT G_GNUC_MALLOC; +void gdata_contacts_service_insert_contact_async (GDataContactsService *self, GDataContactsContact *contact, GCancellable *cancellable, + GAsyncReadyCallback callback, gpointer user_data); + +#include + +GDataFeed *gdata_contacts_service_query_groups (GDataContactsService *self, GDataQuery *query, GCancellable *cancellable, + GDataQueryProgressCallback progress_callback, gpointer progress_user_data, + GError **error) G_GNUC_WARN_UNUSED_RESULT G_GNUC_MALLOC; +void gdata_contacts_service_query_groups_async (GDataContactsService *self, GDataQuery *query, GCancellable *cancellable, + GDataQueryProgressCallback progress_callback, gpointer progress_user_data, + GDestroyNotify destroy_progress_user_data, + GAsyncReadyCallback callback, gpointer user_data); + +GDataContactsGroup *gdata_contacts_service_insert_group (GDataContactsService *self, GDataContactsGroup *group, + GCancellable *cancellable, GError **error) G_GNUC_WARN_UNUSED_RESULT G_GNUC_MALLOC; +void gdata_contacts_service_insert_group_async (GDataContactsService *self, GDataContactsGroup *group, GCancellable *cancellable, + GAsyncReadyCallback callback, gpointer user_data); + +G_END_DECLS + +#endif /* !GDATA_CONTACTS_SERVICE_H */ diff --git a/gdata/services/contacts/meson.build b/gdata/services/contacts/meson.build new file mode 100644 index 0000000..1627a7e --- /dev/null +++ b/gdata/services/contacts/meson.build @@ -0,0 +1,20 @@ +headers = files( + 'gdata-contacts-contact.h', + 'gdata-contacts-group.h', + 'gdata-contacts-query.h', + 'gdata-contacts-service.h', +) + +install_headers( + headers, + subdir: gdata_include_subdir / 'services/contacts', +) + +gir_headers += headers + +sources += files( + 'gdata-contacts-contact.c', + 'gdata-contacts-group.c', + 'gdata-contacts-query.c', + 'gdata-contacts-service.c', +) diff --git a/gdata/services/documents/gdata-documents-access-rule.c b/gdata/services/documents/gdata-documents-access-rule.c new file mode 100644 index 0000000..ba5398b --- /dev/null +++ b/gdata/services/documents/gdata-documents-access-rule.c @@ -0,0 +1,230 @@ +/* -*- Mode: C; indent-tabs-mode: t; c-basic-offset: 8; tab-width: 8 -*- */ +/* + * GData Client + * Copyright (C) Red Hat, Inc. 2015 + * + * GData Client is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * GData Client is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with GData Client. If not, see . + */ + +/** + * SECTION:gdata-documents-access-rule + * @short_description: GData Documents access rule object + * @stability: Stable + * @include: gdata/services/documents/gdata-documents-access-rule.h + * + * #GDataDocumentsAccessRule is a subclass of #GDataAccessRule to represent an + * access rule affecting users of a Google Documents entry. + * + * Since: 0.17.2 + */ + +#include +#include +#include + +#include "gdata-documents-access-rule.h" +#include "gdata-parser.h" +#include "gdata-private.h" + +static void gdata_documents_access_rule_finalize (GObject *object); +static gboolean parse_json (GDataParsable *parsable, JsonReader *reader, gpointer user_data, GError **error); +static gboolean post_parse_json (GDataParsable *parsable, gpointer user_data, GError **error); +static const gchar *get_content_type (void); +static void get_json (GDataParsable *parsable, JsonBuilder *builder); + +typedef struct { + gchar *domain; + gchar *email; + gchar *scope_type; +} GDataDocumentsAccessRulePrivate; + +G_DEFINE_TYPE_WITH_PRIVATE (GDataDocumentsAccessRule, gdata_documents_access_rule, GDATA_TYPE_ACCESS_RULE) + +static void +gdata_documents_access_rule_class_init (GDataDocumentsAccessRuleClass *klass) +{ + GObjectClass *gobject_class = G_OBJECT_CLASS (klass); + GDataParsableClass *parsable_class = GDATA_PARSABLE_CLASS (klass); + + gobject_class->finalize = gdata_documents_access_rule_finalize; + parsable_class->parse_json = parse_json; + parsable_class->post_parse_json = post_parse_json; + parsable_class->get_content_type = get_content_type; + parsable_class->get_json = get_json; +} + +static void +gdata_documents_access_rule_init (GDataDocumentsAccessRule *self) +{ + /* Nothing to do here. */ +} + +static void +gdata_documents_access_rule_finalize (GObject *object) +{ + GDataDocumentsAccessRulePrivate *priv; + + priv = gdata_documents_access_rule_get_instance_private (GDATA_DOCUMENTS_ACCESS_RULE (object)); + + g_free (priv->domain); + g_free (priv->email); + g_free (priv->scope_type); + + /* Chain up to the parent class */ + G_OBJECT_CLASS (gdata_documents_access_rule_parent_class)->finalize (object); +} + +static gboolean +parse_json (GDataParsable *parsable, JsonReader *reader, gpointer user_data, GError **error) +{ + GDataDocumentsAccessRulePrivate *priv; + gboolean success; + gchar *key = NULL; + gchar *role = NULL; + gchar *scope_type = NULL; + + priv = gdata_documents_access_rule_get_instance_private (GDATA_DOCUMENTS_ACCESS_RULE (parsable)); + + /* JSON format: https://developers.google.com/drive/v2/reference/permissions */ + + if (gdata_parser_string_from_json_member (reader, "emailAddress", P_REQUIRED | P_NON_EMPTY, &(priv->email), &success, error) == TRUE || + gdata_parser_string_from_json_member (reader, "domain", P_REQUIRED | P_NON_EMPTY, &(priv->domain), &success, error) == TRUE) { + return success; + } else if (gdata_parser_string_from_json_member (reader, "authKey", P_REQUIRED | P_NON_EMPTY, &key, &success, error) == TRUE) { + if (success && key != NULL && key[0] != '\0') + _gdata_access_rule_set_key (GDATA_ACCESS_RULE (parsable), key); + + g_free (key); + return success; + } else if (gdata_parser_string_from_json_member (reader, "role", P_REQUIRED | P_NON_EMPTY, &role, &success, error) == TRUE) { + if (success && role != NULL && role[0] != '\0') + gdata_access_rule_set_role (GDATA_ACCESS_RULE (parsable), role); + + g_free (role); + return success; + } else if (gdata_parser_string_from_json_member (reader, "type", P_REQUIRED | P_NON_EMPTY, &scope_type, &success, error) == TRUE) { + if (g_strcmp0 (scope_type, "anyone") == 0) { + priv->scope_type = g_strdup (GDATA_ACCESS_SCOPE_DEFAULT); + } else { + priv->scope_type = scope_type; + scope_type = NULL; + } + + g_free (scope_type); + return success; + } + + return GDATA_PARSABLE_CLASS (gdata_documents_access_rule_parent_class)->parse_json (parsable, reader, user_data, error); +} + +static gboolean +post_parse_json (GDataParsable *parsable, gpointer user_data, GError **error) +{ + GDataDocumentsAccessRulePrivate *priv; + + priv = gdata_documents_access_rule_get_instance_private (GDATA_DOCUMENTS_ACCESS_RULE (parsable)); + + if (g_strcmp0 (priv->scope_type, GDATA_ACCESS_SCOPE_DEFAULT) == 0) { + gdata_access_rule_set_scope (GDATA_ACCESS_RULE (parsable), priv->scope_type, NULL); + } else if (g_strcmp0 (priv->scope_type, "group") == 0 || g_strcmp0 (priv->scope_type, GDATA_ACCESS_SCOPE_USER) == 0) { + if (priv->email == NULL || priv->email[0] == '\0') { + g_set_error (error, GDATA_PARSER_ERROR, GDATA_PARSER_ERROR_PARSING_STRING, + /* Translators: the parameter is an error message */ + _("Error parsing JSON: %s"), + "Permission type ‘group’ or ‘user’ needs an ‘emailAddress’ property."); + return FALSE; + } else { + gdata_access_rule_set_scope (GDATA_ACCESS_RULE (parsable), priv->scope_type, priv->email); + } + } else if (g_strcmp0 (priv->scope_type, GDATA_ACCESS_SCOPE_DOMAIN) == 0) { + if (priv->domain == NULL || priv->domain[0] == '\0') { + g_set_error (error, GDATA_PARSER_ERROR, GDATA_PARSER_ERROR_PARSING_STRING, + /* Translators: the parameter is an error message */ + _("Error parsing JSON: %s"), + "Permission type ‘domain’ needs a ‘domain’ property."); + return FALSE; + } else { + gdata_access_rule_set_scope (GDATA_ACCESS_RULE (parsable), priv->scope_type, priv->domain); + } + } + + return TRUE; +} + +static const gchar * +get_content_type (void) +{ + return "application/json"; +} + +static void +get_json (GDataParsable *parsable, JsonBuilder *builder) +{ + const gchar *key; + const gchar *role; + const gchar *scope_type; + const gchar *scope_value; + + GDATA_PARSABLE_CLASS (gdata_documents_access_rule_parent_class)->get_json (parsable, builder); + + key = gdata_access_rule_get_key (GDATA_ACCESS_RULE (parsable)); + if (key != NULL && key[0] != '\0') { + json_builder_set_member_name (builder, "authKey"); + json_builder_add_string_value (builder, key); + } + + role = gdata_access_rule_get_role (GDATA_ACCESS_RULE (parsable)); + if (role != NULL && role[0] != '\0') { + json_builder_set_member_name (builder, "role"); + json_builder_add_string_value (builder, role); + } + + gdata_access_rule_get_scope (GDATA_ACCESS_RULE (parsable), &scope_type, &scope_value); + + if (scope_type != NULL && scope_type[0] != '\0') { + if (g_strcmp0 (scope_type, GDATA_ACCESS_SCOPE_DEFAULT) == 0) + scope_type = "anyone"; + + json_builder_set_member_name (builder, "type"); + json_builder_add_string_value (builder, scope_type); + } + + if (scope_value != NULL && scope_value[0] != '\0') { + json_builder_set_member_name (builder, "value"); + json_builder_add_string_value (builder, scope_value); + } +} + +/** + * gdata_documents_access_rule_new: + * @id: the access rule's ID, or %NULL + * + * Creates a new #GDataDocumentsAccessRule with the given ID and default + * properties. + * + * Return value: (transfer full): a new #GDataDocumentsAccessRule; unref with + * g_object_unref() + * + * Since: 0.17.2 + */ +GDataDocumentsAccessRule * +gdata_documents_access_rule_new (const gchar *id) +{ + GObject *retval = NULL; /* owned */ + + retval = g_object_new (GDATA_TYPE_DOCUMENTS_ACCESS_RULE, + "id", id, + NULL); + return GDATA_DOCUMENTS_ACCESS_RULE (retval); +} diff --git a/gdata/services/documents/gdata-documents-access-rule.h b/gdata/services/documents/gdata-documents-access-rule.h new file mode 100644 index 0000000..fc78e95 --- /dev/null +++ b/gdata/services/documents/gdata-documents-access-rule.h @@ -0,0 +1,75 @@ +/* -*- Mode: C; indent-tabs-mode: t; c-basic-offset: 8; tab-width: 8 -*- */ +/* + * GData Client + * Copyright (C) Red Hat, Inc. 2015 + * + * GData Client is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * GData Client is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with GData Client. If not, see . + */ + +#ifndef GDATA_DOCUMENTS_ACCESS_RULE_H +#define GDATA_DOCUMENTS_ACCESS_RULE_H + +#include +#include + +#include + +G_BEGIN_DECLS + +#define GDATA_TYPE_DOCUMENTS_ACCESS_RULE (gdata_documents_access_rule_get_type ()) +#define GDATA_DOCUMENTS_ACCESS_RULE(o) (G_TYPE_CHECK_INSTANCE_CAST ((o), GDATA_TYPE_DOCUMENTS_ACCESS_RULE, GDataDocumentsAccessRule)) +#define GDATA_DOCUMENTS_ACCESS_RULE_CLASS(k) (G_TYPE_CHECK_CLASS_CAST((k), GDATA_TYPE_DOCUMENTS_ACCESS_RULE, GDataDocumentsAccessRuleClass)) +#define GDATA_IS_DOCUMENTS_ACCESS_RULE(o) (G_TYPE_CHECK_INSTANCE_TYPE ((o), GDATA_TYPE_DOCUMENTS_ACCESS_RULE)) +#define GDATA_IS_DOCUMENTS_ACCESS_RULE_CLASS(k) (G_TYPE_CHECK_CLASS_TYPE ((k), GDATA_TYPE_DOCUMENTS_ACCESS_RULE)) +#define GDATA_DOCUMENTS_ACCESS_RULE_GET_CLASS(o) (G_TYPE_INSTANCE_GET_CLASS ((o), GDATA_TYPE_DOCUMENTS_ACCESS_RULE, GDataDocumentsAccessRuleClass)) + +/** + * GDataDocumentsAccessRule: + * + * All the fields in the #GDataDocumentsAccessRule structure are private and + * should never be accessed directly. + * + * Since: 0.17.2 + */ +typedef struct { + GDataAccessRule parent; +} GDataDocumentsAccessRule; + +/** + * GDataDocumentsAccessRuleClass: + * + * All the fields in the #GDataDocumentsAccessRuleClass structure are private + * and should never be accessed directly. + * + * Since: 0.17.2 + */ +typedef struct { + /*< private >*/ + GDataAccessRuleClass parent; + + /*< private >*/ + /* Padding for future expansion */ + void (*_g_reserved0) (void); + void (*_g_reserved1) (void); +} GDataDocumentsAccessRuleClass; + +GType gdata_documents_access_rule_get_type (void) G_GNUC_CONST; +G_DEFINE_AUTOPTR_CLEANUP_FUNC (GDataDocumentsAccessRule, g_object_unref) + +GDataDocumentsAccessRule * +gdata_documents_access_rule_new (const gchar *id) G_GNUC_WARN_UNUSED_RESULT G_GNUC_MALLOC; + +G_END_DECLS + +#endif /* !GDATA_DOCUMENTS_ACCESS_RULE_H */ diff --git a/gdata/services/documents/gdata-documents-document.c b/gdata/services/documents/gdata-documents-document.c new file mode 100644 index 0000000..f5d94cd --- /dev/null +++ b/gdata/services/documents/gdata-documents-document.c @@ -0,0 +1,556 @@ +/* -*- Mode: C; indent-tabs-mode: t; c-basic-offset: 8; tab-width: 8 -*- */ +/* + * GData Client + * Copyright (C) Philip Withnall 2010 + * Copyright (C) Red Hat, Inc. 2015, 2017 + * + * GData Client is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * GData Client is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with GData Client. If not, see . + */ + +/** + * SECTION:gdata-documents-document + * @short_description: GData documents document object + * @stability: Stable + * @include: gdata/services/documents/gdata-documents-document.h + * + * #GDataDocumentsDocument is a subclass of #GDataDocumentsEntry to represent an arbitrary Google Drive document (i.e. an arbitrary file which + * isn't a Google Documents presentation, text document, PDF, drawing or spreadsheet). It is subclassed by #GDataDocumentsPresentation, #GDataDocumentsText, + * #GDataDocumentsPdf, #GDataDocumentsDrawing and #GDataDocumentsSpreadsheet, which represent those specific types of Google Document, respectively. + * + * #GDataDocumentsDocument used to be abstract, but was made instantiable in version 0.13.0 to allow for arbitrary file uploads. This can be achieved + * by setting #GDataDocumentsUploadQuery:convert to %FALSE when making an upload using gdata_documents_service_upload_document_resumable(). See the + * documentation for #GDataDocumentsUploadQuery for an example. + * + * It should be noted that #GDataDocumentsDocument should only be used to represent arbitrary files; its subclasses should be used any time a standard + * Google Document (spreadsheet, text document, presentation, etc.) is to be represented. + * + * For more details of Google Drive’s GData API, see the + * online documentation. + * + * + * Downloading a Document + * + * GDataDocumentsService *service; + * GDataDocumentsDocument *document; + * GFile *destination_file; + * const gchar *download_format; + * GDataDownloadStream *download_stream; + * GFileOutputStream *output_stream; + * GError *error = NULL; + * + * /* Create a service and retrieve the document to download and the file and format to save the download in */ + * service = create_youtube_service (); + * document = get_document_to_download (service); + * destination_file = query_user_for_destination_file (document); + * download_format = query_user_for_download_format (document); + * + * /* Create the download stream */ + * download_stream = gdata_documents_document_download (document, service, download_format, NULL, &error); + * + * g_object_unref (document); + * g_object_unref (service); + * + * if (error != NULL) { + * g_error ("Error creating download stream: %s", error->message); + * g_error_free (error); + * g_object_unref (destination_file); + * return; + * } + * + * /* Create the file output stream */ + * output_stream = g_file_replace (destination_file, NULL, FALSE, G_FILE_CREATE_REPLACE_DESTINATION, NULL, &error); + * + * g_object_unref (destination_file); + * + * if (error != NULL) { + * g_error ("Error creating destination file: %s", error->message); + * g_error_free (error); + * g_object_unref (download_stream); + * return; + * } + * + * /* Download the document. This should almost always be done asynchronously. */ + * g_output_stream_splice (G_OUTPUT_STREAM (output_stream), G_INPUT_STREAM (download_stream), + * G_OUTPUT_STREAM_SPLICE_CLOSE_SOURCE | G_OUTPUT_STREAM_SPLICE_CLOSE_TARGET, NULL, &error); + * + * g_object_unref (output_stream); + * g_object_unref (download_stream); + * + * if (error != NULL) { + * g_error ("Error downloading document: %s", error->message); + * g_error_free (error); + * return; + * } + * + * + * + * Each document accessible through the service has an access control list (ACL) which defines the level of access to the document to each user, and + * which users the document is shared with. For more information about ACLs for documents, see the online + * documentation on sharing documents. + * + * + * Retrieving the Access Control List for a Document + * + * GDataDocumentsService *service; + * GDataDocumentsDocument *document; + * GDataFeed *acl_feed; + * GDataAccessRule *rule, *new_rule; + * GDataLink *acl_link; + * GList *i; + * GError *error = NULL; + * + * /* Create a service and retrieve a document to work on */ + * service = create_documents_service (); + * document = get_document (service); + * + * /* Query the service for the ACL for the given document */ + * acl_feed = gdata_access_handler_get_rules (GDATA_ACCESS_HANDLER (document), GDATA_SERVICE (service), NULL, NULL, NULL, &error); + * + * if (error != NULL) { + * g_error ("Error getting ACL feed for document: %s", error->message); + * g_error_free (error); + * g_object_unref (document); + * g_object_unref (service); + * return; + * } + * + * /* Iterate through the ACL */ + * for (i = gdata_feed_get_entries (acl_feed); i != NULL; i = i->next) { + * const gchar *scope_value; + * + * rule = GDATA_ACCESS_RULE (i->data); + * + * /* Do something with the access rule here. As an example, we update the rule applying to test@gmail.com and delete all + * * the other rules. We then insert another rule for example@gmail.com below. */ + * gdata_access_rule_get_scope (rule, NULL, &scope_value); + * if (scope_value != NULL && strcmp (scope_value, "test@gmail.com") == 0) { + * GDataAccessRule *updated_rule; + * + * /* Update the rule to make test@gmail.com a writer (full read/write access to the document, but they can't change + * * the ACL or delete the document). */ + * gdata_access_rule_set_role (rule, GDATA_DOCUMENTS_ACCESS_ROLE_WRITER); + * updated_rule = GDATA_ACCESS_RULE (gdata_service_update_entry (GDATA_SERVICE (service), GDATA_ENTRY (rule), NULL, &error)); + * + * if (error != NULL) { + * g_error ("Error updating access rule for %s: %s", scope_value, error->message); + * g_error_free (error); + * g_object_unref (acl_feed); + * g_object_unref (document); + * g_object_unref (service); + * return; + * } + * + * g_object_unref (updated_rule); + * } else { + * /* Delete any rule which doesn't apply to test@gmail.com */ + * gdata_service_delete_entry (GDATA_SERVICE (service), GDATA_ENTRY (rule), NULL, &error); + * + * if (error != NULL) { + * g_error ("Error deleting access rule for %s: %s", scope_value, error->message); + * g_error_free (error); + * g_object_unref (acl_feed); + * g_object_unref (document); + * g_object_unref (service); + * return; + * } + * } + * } + * + * g_object_unref (acl_feed); + * + * /* Create and insert a new access rule for example@gmail.com which allows them read-only access to the document. */ + * rule = gdata_access_rule_new (NULL); + * gdata_access_rule_set_role (rule, GDATA_DOCUMENTS_ACCESS_ROLE_READER); + * gdata_access_rule_set_scope (rule, GDATA_ACCESS_SCOPE_USER, "example@gmail.com"); + * + * acl_link = gdata_entry_look_up_link (GDATA_ENTRY (document), GDATA_LINK_ACCESS_CONTROL_LIST); + * new_rule = GDATA_ACCESS_RULE (gdata_service_insert_entry (GDATA_SERVICE (service), gdata_link_get_uri (acl_link), GDATA_ENTRY (rule), + * NULL, &error)); + * + * g_object_unref (rule); + * g_object_unref (document); + * g_object_unref (service); + * + * if (error != NULL) { + * g_error ("Error inserting access rule: %s", error->message); + * g_error_free (error); + * return; + * } + * + * g_object_unref (acl_link); + * + * + * + * Since: 0.7.0 + */ + +#include +#include +#include + +#include "gdata-documents-document.h" +#include "gdata-documents-drawing.h" +#include "gdata-documents-entry.h" +#include "gdata-documents-entry-private.h" +#include "gdata-documents-presentation.h" +#include "gdata-documents-spreadsheet.h" +#include "gdata-documents-text.h" +#include "gdata-documents-utils.h" +#include "gdata-download-stream.h" +#include "gdata-private.h" +#include "gdata-service.h" + +static void gdata_documents_document_finalize (GObject *object); +static gboolean parse_json (GDataParsable *parsable, JsonReader *reader, gpointer user_data, GError **error); +static gboolean post_parse_json (GDataParsable *parsable, gpointer user_data, GError **error); + +struct _GDataDocumentsDocumentPrivate { + GHashTable *export_links; /* owned string → owned string */ +}; + +G_DEFINE_TYPE (GDataDocumentsDocument, gdata_documents_document, GDATA_TYPE_DOCUMENTS_ENTRY) + +static void +gdata_documents_document_class_init (GDataDocumentsDocumentClass *klass) +{ + GObjectClass *gobject_class = G_OBJECT_CLASS (klass); + GDataParsableClass *parsable_class = GDATA_PARSABLE_CLASS (klass); + GDataEntryClass *entry_class = GDATA_ENTRY_CLASS (klass); + + g_type_class_add_private (klass, sizeof (GDataDocumentsDocumentPrivate)); + + gobject_class->finalize = gdata_documents_document_finalize; + parsable_class->parse_json = parse_json; + parsable_class->post_parse_json = post_parse_json; + entry_class->kind_term = "http://schemas.google.com/docs/2007#file"; +} + +static void +gdata_documents_document_init (GDataDocumentsDocument *self) +{ + self->priv = G_TYPE_INSTANCE_GET_PRIVATE (self, GDATA_TYPE_DOCUMENTS_DOCUMENT, GDataDocumentsDocumentPrivate); + self->priv->export_links = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, g_free); +} + +static void +gdata_documents_document_finalize (GObject *object) +{ + GDataDocumentsDocumentPrivate *priv = GDATA_DOCUMENTS_DOCUMENT (object)->priv; + + g_hash_table_unref (priv->export_links); + + G_OBJECT_CLASS (gdata_documents_document_parent_class)->finalize (object); +} + +static gboolean +parse_json (GDataParsable *parsable, JsonReader *reader, gpointer user_data, GError **error) +{ + GDataDocumentsDocumentPrivate *priv = GDATA_DOCUMENTS_DOCUMENT (parsable)->priv; + gboolean success; + gchar *content_uri = NULL; + gchar *thumbnail_uri = NULL; + + /* JSON format: https://developers.google.com/drive/v2/reference/files */ + + if (gdata_parser_string_from_json_member (reader, "downloadUrl", P_DEFAULT, &content_uri, &success, error) == TRUE) { + if (success && content_uri != NULL && content_uri[0] != '\0') + gdata_entry_set_content_uri (GDATA_ENTRY (parsable), content_uri); + g_free (content_uri); + return success; + } else if (gdata_parser_string_from_json_member (reader, "thumbnailLink", P_DEFAULT, &thumbnail_uri, &success, error) == TRUE) { + if (success && thumbnail_uri != NULL && thumbnail_uri[0] != '\0') { + GDataLink *_link; + + _link = gdata_link_new (thumbnail_uri, "http://schemas.google.com/docs/2007/thumbnail"); + gdata_entry_add_link (GDATA_ENTRY (parsable), _link); + g_object_unref (_link); + } + + g_free (thumbnail_uri); + return success; + } else if (g_strcmp0 (json_reader_get_member_name (reader), "exportLinks") == 0) { + guint i, members; + + if (json_reader_is_object (reader) == FALSE) { + g_set_error (error, GDATA_PARSER_ERROR, GDATA_PARSER_ERROR_PARSING_STRING, + /* Translators: the parameter is an error message */ + _("Error parsing JSON: %s"), + "JSON node ‘exportLinks’ is not an object."); + return FALSE; + } + + for (i = 0, members = (guint) json_reader_count_members (reader); i < members; i++) { + const gchar *format; + gchar *uri = NULL; + + json_reader_read_element (reader, i); + + format = json_reader_get_member_name (reader); + + g_assert (gdata_parser_string_from_json_member (reader, format, P_REQUIRED | P_NON_EMPTY, &uri, &success, NULL)); + if (success) { + g_hash_table_insert (priv->export_links, g_strdup (format), uri); + uri = NULL; + } + + json_reader_end_element (reader); + g_free (uri); + } + + return TRUE; + } + + return GDATA_PARSABLE_CLASS (gdata_documents_document_parent_class)->parse_json (parsable, reader, user_data, error); +} + +static gboolean +post_parse_json (GDataParsable *parsable, gpointer user_data, GError **error) +{ + const gchar *id; + gchar *resource_id; + + id = gdata_entry_get_id (GDATA_ENTRY (parsable)); + + /* Since the document-id is identical to GDataEntry:id, which is parsed by the parent class, we can't + * create the resource-id while parsing. */ + resource_id = g_strconcat ("document:", id, NULL); + _gdata_documents_entry_set_resource_id (GDATA_DOCUMENTS_ENTRY (parsable), resource_id); + + g_free (resource_id); + return GDATA_PARSABLE_CLASS (gdata_documents_document_parent_class)->post_parse_json (parsable, user_data, error); +} + +/** + * gdata_documents_document_new: + * @id: (allow-none): the entry's ID (not the document ID), or %NULL + * + * Creates a new #GDataDocumentsDocument with the given entry ID (#GDataEntry:id). + * + * Return value: (transfer full): a new #GDataDocumentsDocument, or %NULL; unref with g_object_unref() + * + * Since: 0.13.0 + */ +GDataDocumentsDocument * +gdata_documents_document_new (const gchar *id) +{ + return GDATA_DOCUMENTS_DOCUMENT (g_object_new (GDATA_TYPE_DOCUMENTS_DOCUMENT, "id", id, NULL)); +} + +/** + * gdata_documents_document_download: + * @self: a #GDataDocumentsDocument + * @service: a #GDataDocumentsService + * @export_format: the format in which the document should be exported + * @cancellable: (allow-none): a #GCancellable for the entire download stream, or %NULL + * @error: a #GError, or %NULL + * + * Downloads and returns the document file represented by the #GDataDocumentsDocument. If the document doesn't exist, %NULL is returned, but no error + * is set in @error. + * + * @export_format should be the file extension of the desired output format for the document, from the list accepted by Google Documents. For example: + * %GDATA_DOCUMENTS_PRESENTATION_PDF, %GDATA_DOCUMENTS_SPREADSHEET_ODS or %GDATA_DOCUMENTS_TEXT_ODT. + * + * If @self is a #GDataDocumentsSpreadsheet, only the first grid, or sheet, in the spreadsheet will be downloaded for some export formats. To download + * a specific a specific grid, use gdata_documents_spreadsheet_get_download_uri() with #GDataDownloadStream to download the grid manually. See the + * GData protocol + * specification for more information. + * + * To get the content type of the downloaded file, gdata_download_stream_get_content_type() can be called on the returned #GDataDownloadStream. + * Calling gdata_download_stream_get_content_length() on the stream will not return a meaningful result, however, as the stream is encoded in chunks, + * rather than by content length. + * + * In order to cancel the download, a #GCancellable passed in to @cancellable must be cancelled using g_cancellable_cancel(). Cancelling the individual + * #GInputStream operations on the #GDataDownloadStream will not cancel the entire download; merely the read or close operation in question. See the + * #GDataDownloadStream:cancellable for more details. + * + * If the given @export_format is unrecognised or not supported for this document, %GDATA_SERVICE_ERROR_NOT_FOUND will be returned. + * + * If @service isn't authenticated, a %GDATA_SERVICE_ERROR_AUTHENTICATION_REQUIRED will be returned. + * + * If there is an error getting the document, a %GDATA_SERVICE_ERROR_PROTOCOL_ERROR error will be returned. + * + * Return value: (transfer full): a #GDataDownloadStream to download the document with, or %NULL; unref with g_object_unref() + * + * Since: 0.8.0 + */ +GDataDownloadStream * +gdata_documents_document_download (GDataDocumentsDocument *self, GDataDocumentsService *service, const gchar *export_format, GCancellable *cancellable, + GError **error) +{ + gchar *download_uri; + GDataAuthorizationDomain *domain; + GDataDownloadStream *download_stream; + + g_return_val_if_fail (GDATA_IS_DOCUMENTS_DOCUMENT (self), NULL); + g_return_val_if_fail (GDATA_IS_SERVICE (service), NULL); + g_return_val_if_fail (export_format != NULL && *export_format != '\0', NULL); + g_return_val_if_fail (cancellable == NULL || G_IS_CANCELLABLE (cancellable), NULL); + g_return_val_if_fail (error == NULL || *error == NULL, NULL); + + /* If we're downloading a spreadsheet we have to use a different authorization domain. */ + if (GDATA_IS_DOCUMENTS_SPREADSHEET (self)) { + domain = gdata_documents_service_get_spreadsheet_authorization_domain (); + } else { + domain = gdata_documents_service_get_primary_authorization_domain (); + } + + /* Ensure we're authenticated first */ + if (gdata_authorizer_is_authorized_for_domain (gdata_service_get_authorizer (GDATA_SERVICE (service)), domain) == FALSE) { + g_set_error_literal (error, GDATA_SERVICE_ERROR, GDATA_SERVICE_ERROR_AUTHENTICATION_REQUIRED, + _("You must be authenticated to download documents.")); + return NULL; + } + + /* Get the download URI and create a stream for it */ + download_uri = gdata_documents_document_get_download_uri (self, export_format); + + if (download_uri == NULL) { + g_set_error (error, GDATA_SERVICE_ERROR, GDATA_SERVICE_ERROR_NOT_FOUND, + _("Unknown or unsupported document export format ‘%s’."), export_format); + return NULL; + } + + download_stream = GDATA_DOWNLOAD_STREAM (gdata_download_stream_new (GDATA_SERVICE (service), domain, download_uri, cancellable)); + g_free (download_uri); + + return download_stream; +} + +/** + * gdata_documents_document_get_download_uri: + * @self: a #GDataDocumentsDocument + * @export_format: the format in which the document should be exported when downloaded + * + * Builds and returns the download URI for the given #GDataDocumentsDocument in the desired format. Note that directly downloading the document using + * this URI isn't possible, as authentication is required. You should instead use gdata_download_stream_new() with the URI, and use the resulting + * #GInputStream. + * + * @export_format should be the file extension of the desired output format for the document, from the list accepted by Google Documents. For example: + * %GDATA_DOCUMENTS_PRESENTATION_PDF, %GDATA_DOCUMENTS_SPREADSHEET_ODS or %GDATA_DOCUMENTS_TEXT_ODT. + * + * If the @export_format is not recognised or not supported for this document, %NULL is returned. + * + * Return value: (nullable): the download URI, or %NULL; free with g_free() + * + * Since: 0.7.0 + */ +gchar * +gdata_documents_document_get_download_uri (GDataDocumentsDocument *self, const gchar *export_format) +{ + const gchar *format; + const gchar *mime_type; + + g_return_val_if_fail (GDATA_IS_DOCUMENTS_DOCUMENT (self), NULL); + g_return_val_if_fail (export_format != NULL && *export_format != '\0', NULL); + + if (g_strcmp0 (export_format, "html") == 0) + format = "text/html"; + else if (g_strcmp0 (export_format, "jpeg") == 0) + format = "image/jpeg"; + else if (g_strcmp0 (export_format, "pdf") == 0) + format = "application/pdf"; + else if (g_strcmp0 (export_format, "png") == 0) + format = "image/png"; + else if (g_strcmp0 (export_format, "txt") == 0) + format = "text/plain"; + else if (g_strcmp0 (export_format, GDATA_DOCUMENTS_DRAWING_SVG) == 0) + format = "image/svg+xml"; + else if (g_strcmp0 (export_format, GDATA_DOCUMENTS_PRESENTATION_PPT) == 0) + format = "application/vnd.openxmlformats-officedocument.presentationml.presentation"; + else if (g_strcmp0 (export_format, GDATA_DOCUMENTS_SPREADSHEET_CSV) == 0) + format = "text/csv"; + else if (g_strcmp0 (export_format, GDATA_DOCUMENTS_SPREADSHEET_ODS) == 0) + format = "application/x-vnd.oasis.opendocument.spreadsheet"; + else if (g_strcmp0 (export_format, GDATA_DOCUMENTS_SPREADSHEET_XLS) == 0) + format = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"; + else if (g_strcmp0 (export_format, GDATA_DOCUMENTS_TEXT_ODT) == 0) + format = "application/vnd.oasis.opendocument.text"; + else if (g_strcmp0 (export_format, GDATA_DOCUMENTS_TEXT_RTF) == 0) + format = "application/rtf"; + else + format = export_format; + + /* We use the exportLinks JSON member to do the format conversion during download. Unfortunately, there + * won't be any hits if the export format matches the original MIME type. We resort to downloadUrl in + * those cases. + */ + mime_type = gdata_documents_utils_get_content_type (GDATA_DOCUMENTS_ENTRY (self)); + if (g_content_type_equals (mime_type, format)) + return g_strdup (gdata_entry_get_content_uri (GDATA_ENTRY (self))); + + return g_strdup (g_hash_table_lookup (self->priv->export_links, format)); +} + +/** + * gdata_documents_document_get_thumbnail_uri: + * @self: a #GDataDocumentsDocument + * + * Gets the URI of the thumbnail for the #GDataDocumentsDocument. If no thumbnail exists for the document, %NULL will be returned. + * + * The thumbnail may then be downloaded using a #GDataDownloadStream. + * + * + * Downloading a Document Thumbnail + * + * GDataDocumentsService *service; + * const gchar *thumbnail_uri; + * GCancellable *cancellable; + * GdkPixbuf *pixbuf; + * GError *error = NULL; + * + * service = get_my_documents_service (); + * thumbnail_uri = gdata_documents_document_get_thumbnail_uri (my_document); + * cancellable = g_cancellable_new (); + * + * /* Prepare a download stream */ + * download_stream = GDATA_DOWNLOAD_STREAM (gdata_download_stream_new (GDATA_SERVICE (service), NULL, thumbnail_uri, cancellable)); + * + * /* Download into a new GdkPixbuf. This can be cancelled using 'cancellable'. */ + * pixbuf = gdk_pixbuf_new_from_stream (G_INPUT_STREAM (download_stream), NULL, &error); + * + * if (error != NULL) { + * /* Handle the error. */ + * g_error_free (error); + * } + * + * g_object_unref (download_stream); + * g_object_unref (cancellable); + * + * /* Do something with the GdkPixbuf. */ + * + * g_object_unref (pixbuf); + * + * + * + * Return value: (allow-none): the URI of the document's thumbnail, or %NULL + * + * Since: 0.13.1 + */ +const gchar * +gdata_documents_document_get_thumbnail_uri (GDataDocumentsDocument *self) +{ + GDataLink *thumbnail_link; + + g_return_val_if_fail (GDATA_IS_DOCUMENTS_DOCUMENT (self), NULL); + + /* Get the thumbnail URI (if it exists). */ + thumbnail_link = gdata_entry_look_up_link (GDATA_ENTRY (self), "http://schemas.google.com/docs/2007/thumbnail"); + + if (thumbnail_link == NULL) { + return NULL; + } + + return gdata_link_get_uri (thumbnail_link); +} diff --git a/gdata/services/documents/gdata-documents-document.h b/gdata/services/documents/gdata-documents-document.h new file mode 100644 index 0000000..675d56d --- /dev/null +++ b/gdata/services/documents/gdata-documents-document.h @@ -0,0 +1,84 @@ +/* -*- Mode: C; indent-tabs-mode: t; c-basic-offset: 8; tab-width: 8 -*- */ +/* + * GData Client + * Copyright (C) Philip Withnall 2010 + * + * GData Client is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * GData Client is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with GData Client. If not, see . + */ + +#ifndef GDATA_DOCUMENTS_DOCUMENT_H +#define GDATA_DOCUMENTS_DOCUMENT_H + +#include +#include + +#include +#include + +G_BEGIN_DECLS + +#define GDATA_TYPE_DOCUMENTS_DOCUMENT (gdata_documents_document_get_type ()) +#define GDATA_DOCUMENTS_DOCUMENT(o) (G_TYPE_CHECK_INSTANCE_CAST ((o), GDATA_TYPE_DOCUMENTS_DOCUMENT, GDataDocumentsDocument)) +#define GDATA_DOCUMENTS_DOCUMENT_CLASS(k) (G_TYPE_CHECK_CLASS_CAST((k), GDATA_TYPE_DOCUMENTS_DOCUMENT, GDataDocumentsDocumentClass)) +#define GDATA_IS_DOCUMENTS_DOCUMENT(o) (G_TYPE_CHECK_INSTANCE_TYPE ((o), GDATA_TYPE_DOCUMENTS_DOCUMENT)) +#define GDATA_IS_DOCUMENTS_DOCUMENT_CLASS(k) (G_TYPE_CHECK_CLASS_TYPE ((k), GDATA_TYPE_DOCUMENTS_DOCUMENT)) +#define GDATA_DOCUMENTS_DOCUMENT_GET_CLASS(o) (G_TYPE_INSTANCE_GET_CLASS ((o), GDATA_TYPE_DOCUMENTS_DOCUMENT, GDataDocumentsDocumentClass)) + +typedef struct _GDataDocumentsDocumentPrivate GDataDocumentsDocumentPrivate; + +/** + * GDataDocumentsDocument: + * + * All the fields in the #GDataDocumentsDocument structure are private and should never be accessed directly. + * + * Since: 0.7.0 + */ +typedef struct { + GDataDocumentsEntry parent; + GDataDocumentsDocumentPrivate *priv; +} GDataDocumentsDocument; + +/** + * GDataDocumentsDocumentClass: + * + * All the fields in the #GDataDocumentsDocumentClass structure are private and should never be accessed directly. + * + * Since: 0.7.0 + */ +typedef struct { + /*< private >*/ + GDataDocumentsEntryClass parent; + + /*< private >*/ + /* Padding for future expansion */ + void (*_g_reserved0) (void); + void (*_g_reserved1) (void); +} GDataDocumentsDocumentClass; + +GType gdata_documents_document_get_type (void) G_GNUC_CONST; +G_DEFINE_AUTOPTR_CLEANUP_FUNC (GDataDocumentsDocument, g_object_unref) + +GDataDocumentsDocument *gdata_documents_document_new (const gchar *id) G_GNUC_WARN_UNUSED_RESULT G_GNUC_MALLOC; + +#include + +GDataDownloadStream *gdata_documents_document_download (GDataDocumentsDocument *self, GDataDocumentsService *service, const gchar *export_format, + GCancellable *cancellable, GError **error) G_GNUC_WARN_UNUSED_RESULT G_GNUC_MALLOC; +gchar *gdata_documents_document_get_download_uri (GDataDocumentsDocument *self, const gchar *export_format) G_GNUC_WARN_UNUSED_RESULT G_GNUC_MALLOC; + +const gchar *gdata_documents_document_get_thumbnail_uri (GDataDocumentsDocument *self) G_GNUC_PURE; + +G_END_DECLS + +#endif /* !GDATA_DOCUMENTS_DOCUMENT_H */ diff --git a/gdata/services/documents/gdata-documents-drawing.c b/gdata/services/documents/gdata-documents-drawing.c new file mode 100644 index 0000000..4e0423d --- /dev/null +++ b/gdata/services/documents/gdata-documents-drawing.c @@ -0,0 +1,88 @@ +/* -*- Mode: C; indent-tabs-mode: t; c-basic-offset: 8; tab-width: 8 -*- */ +/* + * GData Client + * Copyright (C) Thibault Saunier 2009 + * Copyright (C) Philip Withnall 2010 + * Copyright (C) Cosimo Cecchi 2012 + * Copyright (C) Red Hat, Inc. 2016 + * + * GData Client is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * GData Client is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with GData Client. If not, see . + */ + +/** + * SECTION:gdata-documents-drawing + * @short_description: GData Documents drawing object + * @stability: Stable + * @include: gdata/services/documents/gdata-documents-drawing.h + * + * #GDataDocumentsDrawing is a subclass of #GDataDocumentsDocument to represent a drawing document from Google Documents. + * + * For more details of Google Drive's GData API, see the + * online documentation. + * + * Since: 0.13.1 + */ + +#include +#include + +#include "gdata-documents-drawing.h" +#include "gdata-documents-utils.h" +#include "gdata-parser.h" +#include "gdata-private.h" + +static void gdata_documents_drawing_constructed (GObject *object); + +G_DEFINE_TYPE (GDataDocumentsDrawing, gdata_documents_drawing, GDATA_TYPE_DOCUMENTS_DOCUMENT) + +static void +gdata_documents_drawing_class_init (GDataDocumentsDrawingClass *klass) +{ + GObjectClass *gobject_class = G_OBJECT_CLASS (klass); + GDataEntryClass *entry_class = GDATA_ENTRY_CLASS (klass); + + gobject_class->constructed = gdata_documents_drawing_constructed; + entry_class->kind_term = "http://schemas.google.com/docs/2007#drawing"; +} + +static void +gdata_documents_drawing_init (GDataDocumentsDrawing *self) +{ + /* Why am I writing it? */ +} + +static void +gdata_documents_drawing_constructed (GObject *object) +{ + G_OBJECT_CLASS (gdata_documents_drawing_parent_class)->constructed (object); + + if (!_gdata_parsable_is_constructed_from_xml (GDATA_PARSABLE (object))) + gdata_documents_utils_add_content_type (GDATA_DOCUMENTS_ENTRY (object), "application/vnd.google-apps.drawing"); +} + +/** + * gdata_documents_drawing_new: + * @id: (allow-none): the entry's ID (not the document ID of the drawing document), or %NULL + * + * Creates a new #GDataDocumentsDrawing with the given entry ID (#GDataEntry:id). + * + * Return value: (transfer full): a new #GDataDocumentsDrawing, or %NULL; unref with g_object_unref() + * + * Since: 0.13.1 + */ +GDataDocumentsDrawing * +gdata_documents_drawing_new (const gchar *id) +{ + return GDATA_DOCUMENTS_DRAWING (g_object_new (GDATA_TYPE_DOCUMENTS_DRAWING, "id", id, NULL)); +} diff --git a/gdata/services/documents/gdata-documents-drawing.h b/gdata/services/documents/gdata-documents-drawing.h new file mode 100644 index 0000000..d3e2014 --- /dev/null +++ b/gdata/services/documents/gdata-documents-drawing.h @@ -0,0 +1,130 @@ +/* -*- Mode: C; indent-tabs-mode: t; c-basic-offset: 8; tab-width: 8 -*- */ +/* + * GData Client + * Copyright (C) Thibault Saunier 2009 + * Copyright (C) Philip Withnall 2010 + * Copyright (C) Cosimo Cecchi 2012 + * + * GData Client is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * GData Client is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with GData Client. If not, see . + */ + +#ifndef GDATA_DOCUMENTS_DRAWING_H +#define GDATA_DOCUMENTS_DRAWING_H + +#include +#include + +#include + +G_BEGIN_DECLS + +/** + * GDATA_DOCUMENTS_DRAWING_JPEG: + * + * The export format for JPEG image format. + * + * For more information, see the + * + * GData protocol specification. + * + * Since: 0.13.1 + */ +#define GDATA_DOCUMENTS_DRAWING_JPEG "jpeg" + +/** + * GDATA_DOCUMENTS_DRAWING_PDF: + * + * The export format for Portable Document Format (PDF). + * + * For more information, see the + * + * GData protocol specification. + * + * Since: 0.13.1 + */ +#define GDATA_DOCUMENTS_DRAWING_PDF "pdf" + +/** + * GDATA_DOCUMENTS_DRAWING_PNG: + * + * The export format for Portable Network Graphics (PNG) image format. + * + * For more information, see the + * + * GData protocol specification. + * + * Since: 0.13.1 + */ +#define GDATA_DOCUMENTS_DRAWING_PNG "png" + +/** + * GDATA_DOCUMENTS_DRAWING_SVG: + * + * The export format for Scalable Vector Graphics (SVG) image format. + * + * For more information, see the + * + * GData protocol specification. + * + * Since: 0.13.1 + */ +#define GDATA_DOCUMENTS_DRAWING_SVG "svg" + + +#define GDATA_TYPE_DOCUMENTS_DRAWING (gdata_documents_drawing_get_type ()) +#define GDATA_DOCUMENTS_DRAWING(o) (G_TYPE_CHECK_INSTANCE_CAST ((o), GDATA_TYPE_DOCUMENTS_DRAWING, GDataDocumentsDrawing)) +#define GDATA_DOCUMENTS_DRAWING_CLASS(k) (G_TYPE_CHECK_CLASS_CAST((k), GDATA_TYPE_DOCUMENTS_DRAWING, GDataDocumentsDrawingClass)) +#define GDATA_IS_DOCUMENTS_DRAWING(o) (G_TYPE_CHECK_INSTANCE_TYPE ((o), GDATA_TYPE_DOCUMENTS_DRAWING)) +#define GDATA_IS_DOCUMENTS_DRAWING_CLASS(k) (G_TYPE_CHECK_CLASS_TYPE ((k), GDATA_TYPE_DOCUMENTS_DRAWING)) +#define GDATA_DOCUMENTS_DRAWING_GET_CLASS(o) (G_TYPE_INSTANCE_GET_CLASS ((o), GDATA_TYPE_DOCUMENTS_DRAWING, GDataDocumentsDrawingClass)) + +typedef struct _GDataDocumentsDrawingPrivate GDataDocumentsDrawingPrivate; + +/** + * GDataDocumentsDrawing: + * + * All the fields in the #GDataDocumentsDrawing structure are private and should never be accessed directly. + * + * Since: 0.13.1 + */ +typedef struct { + GDataDocumentsDocument parent; + GDataDocumentsDrawingPrivate *priv; +} GDataDocumentsDrawing; + +/** + * GDataDocumentsDrawingClass: + * + * All the fields in the #GDataDocumentsDrawingClass structure are private and should never be accessed directly. + * + * Since: 0.13.1 + */ +typedef struct { + /*< private >*/ + GDataDocumentsDocumentClass parent; + + /*< private >*/ + /* Padding for future expansion */ + void (*_g_reserved0) (void); + void (*_g_reserved1) (void); +} GDataDocumentsDrawingClass; + +GType gdata_documents_drawing_get_type (void) G_GNUC_CONST; +G_DEFINE_AUTOPTR_CLEANUP_FUNC (GDataDocumentsDrawing, g_object_unref) + +GDataDocumentsDrawing *gdata_documents_drawing_new (const gchar *id) G_GNUC_WARN_UNUSED_RESULT G_GNUC_MALLOC; + +G_END_DECLS + +#endif /* !GDATA_DOCUMENTS_DRAWING_H */ diff --git a/gdata/services/documents/gdata-documents-entry-private.h b/gdata/services/documents/gdata-documents-entry-private.h new file mode 100644 index 0000000..af92e73 --- /dev/null +++ b/gdata/services/documents/gdata-documents-entry-private.h @@ -0,0 +1,33 @@ +/* -*- Mode: C; indent-tabs-mode: t; c-basic-offset: 8; tab-width: 8 -*- */ +/* + * GData Client + * Copyright (C) Red Hat, Inc. 2017 + * + * GData Client is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * GData Client is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with GData Client. If not, see . + */ + +#ifndef GDATA_DOCUMENTS_ENTRY_PRIVATE_H +#define GDATA_DOCUMENTS_ENTRY_PRIVATE_H + +#include + +#include + +G_BEGIN_DECLS + +G_GNUC_INTERNAL void _gdata_documents_entry_set_resource_id (GDataDocumentsEntry *self, const gchar *resource_id); + +G_END_DECLS + +#endif /* !GDATA_DOCUMENTS_ENTRY_PRIVATE_H */ diff --git a/gdata/services/documents/gdata-documents-entry.c b/gdata/services/documents/gdata-documents-entry.c new file mode 100644 index 0000000..f16cfcd --- /dev/null +++ b/gdata/services/documents/gdata-documents-entry.c @@ -0,0 +1,1421 @@ +/* -*- Mode: C; indent-tabs-mode: t; c-basic-offset: 8; tab-width: 8 -*- */ +/* + * GData Client + * Copyright (C) Thibault Saunier 2009 + * Copyright (C) Red Hat, Inc. 2015, 2016 + * + * GData Client is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * GData Client is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with GData Client. If not, see . + */ + +/** + * SECTION:gdata-documents-entry + * @short_description: GData document object abstract class + * @stability: Stable + * @include: gdata/services/documents/gdata-documents-entry.h + * + * #GDataDocumentsEntry is a subclass of #GDataEntry to represent a Google Drive entry, which is then further subclassed + * to give specific document types. + * + * #GDataDocumentsEntry implements #GDataAccessHandler, meaning the access rules to it can be modified using that interface. As well as the + * access roles defined for the base #GDataAccessRule (e.g. %GDATA_ACCESS_ROLE_NONE), #GDataDocumentsEntry has its own, such as + * %GDATA_DOCUMENTS_ACCESS_ROLE_OWNER and %GDATA_DOCUMENTS_ACCESS_ROLE_READER. + * + * Documents can (confusingly) be referenced by three different types of IDs: their entry ID, their resource ID and their document ID (untyped resource + * ID). Each is a substring of the previous ones (i.e. the entry ID contains the resource ID, which in turn contains the document ID). The resource ID + * and document ID should almost always be considered as internal, and thus entry IDs (#GDataEntry:id) should normally be used to uniquely identify + * documents. For more information, see #GDataDocumentsEntry:resource-id. + * + * For more details of Google Drive's GData API, see the + * online documentation. + * + * + * Moving an Entry Between Folders + * + * GDataDocumentsService *service; + * GDataDocumentsEntry *entry, *intermediate_entry, *updated_entry; + * GDataDocumentsFolder *old_folder, *new_folder; + * GError *error = NULL; + * + * /* Create a service */ + * service = create_documents_service (); + * + * /* Get the entry, the folder it's being moved out of, and the folder it's being moved into. The entry can either be a document or + * * another folder, allowing hierarchies of folders to be constructed. */ + * entry = query_user_for_entry (service); + * old_folder = query_user_for_old_folder (service); + * new_folder = query_user_for_new_folder (service); + * + * /* Add the entry to the new folder */ + * intermediate_entry = gdata_documents_service_add_entry_to_folder (service, entry, new_folder, NULL, &error); + * + * g_object_unref (entry); + * g_object_unref (new_folder); + * + * if (error != NULL) { + * g_error ("Error adding entry to new folder: %s", error->message); + * g_error_free (error); + * g_object_unref (old_folder); + * g_object_unref (service); + * return; + * } + * + * /* Remove the entry from the old folder */ + * updated_entry = gdata_documents_service_remove_entry_from_folder (service, intermediate_entry, old_folder, NULL, &error); + * + * g_object_unref (intermediate_entry); + * g_object_unref (old_folder); + * g_object_unref (service); + * + * if (error != NULL) { + * /* Note that you might want to attempt to remove the intermediate_entry from the new_folder in this error case, so that + * * the operation is aborted cleanly. */ + * g_error ("Error removing entry from previous folder: %s", error->message); + * g_error_free (error); + * return; + * } + * + * /* Do something with the updated entry */ + * + * g_object_unref (updated_entry); + * + * + * + * Since: 0.4.0 + */ + +#include +#include +#include + +#include "gdata-comparable.h" +#include "gdata-documents-entry.h" +#include "gdata-documents-entry-private.h" +#include "gdata-parser.h" +#include "gdata-types.h" +#include "gdata-private.h" +#include "gdata-access-handler.h" +#include "gdata-documents-access-rule.h" +#include "gdata-documents-service.h" + +#include "gdata-documents-spreadsheet.h" +#include "gdata-documents-presentation.h" +#include "gdata-documents-text.h" +#include "gdata-documents-folder.h" +#include "gdata-documents-utils.h" + +static void gdata_documents_entry_access_handler_init (GDataAccessHandlerIface *iface); +static void gdata_documents_entry_finalize (GObject *object); +static void gdata_entry_dispose (GObject *object); +static const gchar *get_content_type (void); +static void get_namespaces (GDataParsable *parsable, GHashTable *namespaces); +static void gdata_documents_entry_get_property (GObject *object, guint property_id, GValue *value, GParamSpec *pspec); +static void gdata_documents_entry_set_property (GObject *object, guint property_id, const GValue *value, GParamSpec *pspec); +static gboolean parse_json (GDataParsable *parsable, JsonReader *reader, gpointer user_data, GError **error); +static gboolean post_parse_json (GDataParsable *parsable, gpointer user_data, GError **error); +static void get_json (GDataParsable *parsable, JsonBuilder *builder); +static gchar *get_entry_uri (const gchar *id); + +struct _GDataDocumentsEntryPrivate { + gint64 last_viewed; + gchar *resource_id; + gboolean writers_can_invite; + gboolean is_deleted; + GDataAuthor *last_modified_by; + goffset quota_used; /* bytes */ + goffset file_size; /* bytes */ + GList *properties; /* GDataDocumentsProperty */ +}; + +enum { + PROP_EDITED = 1, + PROP_LAST_VIEWED, + PROP_DOCUMENT_ID, + PROP_LAST_MODIFIED_BY, + PROP_IS_DELETED, + PROP_WRITERS_CAN_INVITE, + PROP_RESOURCE_ID, + PROP_QUOTA_USED, + PROP_FILE_SIZE, +}; + +G_DEFINE_ABSTRACT_TYPE_WITH_CODE (GDataDocumentsEntry, gdata_documents_entry, GDATA_TYPE_ENTRY, + G_IMPLEMENT_INTERFACE (GDATA_TYPE_ACCESS_HANDLER, gdata_documents_entry_access_handler_init)) + +static void +gdata_documents_entry_class_init (GDataDocumentsEntryClass *klass) +{ + GObjectClass *gobject_class = G_OBJECT_CLASS (klass); + GDataParsableClass *parsable_class = GDATA_PARSABLE_CLASS (klass); + GDataEntryClass *entry_class = GDATA_ENTRY_CLASS (klass); + + g_type_class_add_private (klass, sizeof (GDataDocumentsEntryPrivate)); + + gobject_class->get_property = gdata_documents_entry_get_property; + gobject_class->set_property = gdata_documents_entry_set_property; + gobject_class->finalize = gdata_documents_entry_finalize; + gobject_class->dispose = gdata_entry_dispose; + + parsable_class->parse_json = parse_json; + parsable_class->post_parse_json = post_parse_json; + parsable_class->get_content_type = get_content_type; + parsable_class->get_json = get_json; + parsable_class->get_namespaces = get_namespaces; + + entry_class->get_entry_uri = get_entry_uri; + + /** + * GDataDocumentsEntry:edited: + * + * The last time the document was edited. If the document has not been edited yet, the content indicates the time it was created. + * + * Since: 0.4.0 + * Deprecated: 0.17.0: This is identical to #GDataEntry:updated. + */ + g_object_class_install_property (gobject_class, PROP_EDITED, + g_param_spec_int64 ("edited", + "Edited", "The last time the document was edited.", + -1, G_MAXINT64, -1, + G_PARAM_READABLE | G_PARAM_STATIC_STRINGS | G_PARAM_DEPRECATED)); + + /** + * GDataDocumentsEntry:last-viewed: + * + * The last time the document was viewed. + * + * Since: 0.4.0 + */ + g_object_class_install_property (gobject_class, PROP_LAST_VIEWED, + g_param_spec_int64 ("last-viewed", + "Last viewed", "The last time the document was viewed.", + -1, G_MAXINT64, -1, + G_PARAM_READABLE | G_PARAM_STATIC_STRINGS)); + + /** + * GDataDocumentsEntry:writers-can-invite: + * + * Indicates whether the document entry writers can invite others to edit the document. + * + * Since: 0.4.0 + */ + g_object_class_install_property (gobject_class, PROP_WRITERS_CAN_INVITE, + g_param_spec_boolean ("writers-can-invite", + "Writers can invite?", "Indicates whether writers can invite others to edit.", + FALSE, + G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)); + + /** + * GDataDocumentsEntry:is-deleted: + * + * Indicates whether the document entry has been deleted (moved to the trash). Deleted documents will only + * appear in query results if the #GDataDocumentsQuery:show-deleted property is %TRUE. + * + * Since: 0.5.0 + */ + g_object_class_install_property (gobject_class, PROP_IS_DELETED, + g_param_spec_boolean ("is-deleted", + "Deleted?", "Indicates whether the document entry has been deleted.", + FALSE, + G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)); + + /** + * GDataDocumentsEntry:resource-id: + * + * The resource ID of the document. This should not normally need to be used in client code, and is mostly for internal use. To uniquely + * identify a given document or folder, use its #GDataEntry:id. + * + * Resource IDs have the form: + * document|drawing|pdf|spreadsheet|presentation|folder:untyped resource ID; whereas + * entry IDs have the form: + * https://docs.google.com/feeds/id/resource ID in version 3 of the API. + * + * For more information, see the + * Google Documents + * API reference. + * + * Since: 0.11.0 + */ + g_object_class_install_property (gobject_class, PROP_RESOURCE_ID, + g_param_spec_string ("resource-id", + "Resource ID", "The resource ID of the document.", + NULL, + G_PARAM_READABLE | G_PARAM_STATIC_STRINGS)); + + /** + * GDataDocumentsEntry:document-id: + * + * The document ID of the document, which is different from its entry ID (GDataEntry:id). The + * online GData + * Documentation refers to these as “untyped resource IDs”. + * + * Since: 0.4.0 + * Deprecated: 0.11.0: This a substring of the #GDataDocumentsEntry:resource-id, which is more general and should be used instead. + */ + g_object_class_install_property (gobject_class, PROP_DOCUMENT_ID, + g_param_spec_string ("document-id", + "Document ID", "The document ID of the document.", + NULL, + G_PARAM_READABLE | G_PARAM_STATIC_STRINGS | G_PARAM_DEPRECATED)); + + /** + * GDataDocumentsEntry:last-modified-by: + * + * Indicates the author of the last modification. + * + * Since: 0.4.0 + */ + g_object_class_install_property (gobject_class, PROP_LAST_MODIFIED_BY, + g_param_spec_object ("last-modified-by", + "Last modified by", "Indicates the author of the last modification.", + GDATA_TYPE_AUTHOR, + G_PARAM_READABLE | G_PARAM_STATIC_STRINGS)); + + /** + * GDataDocumentsEntry:quota-used: + * + * The amount of user quota the document is occupying. Currently, only arbitrary files consume file space quota (whereas standard document + * formats, such as #GDataDocumentsText, #GDataDocumentsSpreadsheet and #GDataDocumentsFolder don't). Measured in bytes. + * + * This property will be 0 for documents which aren't consuming any quota. + * + * Since: 0.13.0 + */ + g_object_class_install_property (gobject_class, PROP_QUOTA_USED, + g_param_spec_int64 ("quota-used", + "Quota used", "The amount of user quota the document is occupying.", + 0, G_MAXINT64, 0, + G_PARAM_READABLE | G_PARAM_STATIC_STRINGS)); + + /** + * GDataDocumentsEntry:file-size: + * + * The size of the document. This is only set for non-document files. + * Standard formats, such as #GDataDocumentsText, + * #GDataDocumentsSpreadsheet and #GDataDocumentsFolder are not binary + * data and so have no size. Measured in bytes. + * + * Since: 0.17.7 + */ + g_object_class_install_property (gobject_class, PROP_FILE_SIZE, + g_param_spec_int64 ("file-size", + "File size", "The size of the document.", + 0, G_MAXINT64, 0, + G_PARAM_READABLE | G_PARAM_STATIC_STRINGS)); +} + +static gboolean +is_owner_rule (GDataAccessRule *rule) +{ + return (strcmp (gdata_access_rule_get_role (rule), GDATA_DOCUMENTS_ACCESS_ROLE_OWNER) == 0) ? TRUE : FALSE; +} + +static GDataAuthorizationDomain * +get_authorization_domain (GDataAccessHandler *self) +{ + return gdata_documents_service_get_primary_authorization_domain (); +} + +static GDataFeed * +get_rules (GDataAccessHandler *self, + GDataService *service, + GCancellable *cancellable, + GDataQueryProgressCallback progress_callback, + gpointer progress_user_data, + GError **error) +{ + GDataAccessHandlerIface *iface; + GDataAuthorizationDomain *domain = NULL; + GDataFeed *feed; + GDataLink *_link; + SoupMessage *message; + + _link = gdata_entry_look_up_link (GDATA_ENTRY (self), GDATA_LINK_ACCESS_CONTROL_LIST); + g_assert (_link != NULL); + + iface = GDATA_ACCESS_HANDLER_GET_IFACE (self); + if (iface->get_authorization_domain != NULL) { + domain = iface->get_authorization_domain (self); + } + + message = _gdata_service_query (service, domain, gdata_link_get_uri (_link), NULL, cancellable, error); + if (message == NULL) { + return NULL; + } + + g_assert (message->response_body->data != NULL); + + feed = _gdata_feed_new_from_json (GDATA_TYPE_FEED, message->response_body->data, message->response_body->length, GDATA_TYPE_DOCUMENTS_ACCESS_RULE, + progress_callback, progress_user_data, error); + + g_object_unref (message); + + return feed; +} + +static void +gdata_documents_entry_access_handler_init (GDataAccessHandlerIface *iface) +{ + iface->is_owner_rule = is_owner_rule; + iface->get_authorization_domain = get_authorization_domain; + iface->get_rules = get_rules; +} + +static void +gdata_documents_entry_init (GDataDocumentsEntry *self) +{ + self->priv = G_TYPE_INSTANCE_GET_PRIVATE (self, GDATA_TYPE_DOCUMENTS_ENTRY, GDataDocumentsEntryPrivate); + self->priv->last_viewed = -1; +} + +static void +gdata_entry_dispose (GObject *object) +{ + GDataDocumentsEntryPrivate *priv = GDATA_DOCUMENTS_ENTRY (object)->priv; + + if (priv->last_modified_by != NULL) + g_object_unref (priv->last_modified_by); + priv->last_modified_by = NULL; + + g_list_free_full (priv->properties, g_object_unref); + priv->properties = NULL; + + /* Chain up to the parent class */ + G_OBJECT_CLASS (gdata_documents_entry_parent_class)->dispose (object); +} + +static void +gdata_documents_entry_finalize (GObject *object) +{ + GDataDocumentsEntryPrivate *priv = GDATA_DOCUMENTS_ENTRY (object)->priv; + + g_free (priv->resource_id); + + /* Chain up to the parent class */ + G_OBJECT_CLASS (gdata_documents_entry_parent_class)->finalize (object); +} + +static void +gdata_documents_entry_get_property (GObject *object, guint property_id, GValue *value, GParamSpec *pspec) +{ + GDataDocumentsEntryPrivate *priv = GDATA_DOCUMENTS_ENTRY (object)->priv; + + switch (property_id) { + case PROP_RESOURCE_ID: + g_value_set_string (value, priv->resource_id); + break; + case PROP_DOCUMENT_ID: + g_value_set_string (value, gdata_entry_get_id (GDATA_ENTRY (object))); + break; + case PROP_WRITERS_CAN_INVITE: + g_value_set_boolean (value, priv->writers_can_invite); + break; + case PROP_IS_DELETED: + g_value_set_boolean (value, priv->is_deleted); + break; + case PROP_EDITED: + g_value_set_int64 (value, gdata_entry_get_updated (GDATA_ENTRY (object))); + break; + case PROP_LAST_VIEWED: + g_value_set_int64 (value, priv->last_viewed); + break; + case PROP_LAST_MODIFIED_BY: + g_value_set_object (value, priv->last_modified_by); + break; + case PROP_QUOTA_USED: + g_value_set_int64 (value, priv->quota_used); + break; + case PROP_FILE_SIZE: + g_value_set_int64 (value, priv->file_size); + break; + default: + /* We don't have any other property... */ + G_OBJECT_WARN_INVALID_PROPERTY_ID (object, property_id, pspec); + break; + } +} + +static void +gdata_documents_entry_set_property (GObject *object, guint property_id, const GValue *value, GParamSpec *pspec) +{ + GDataDocumentsEntry *self = GDATA_DOCUMENTS_ENTRY (object); + + switch (property_id) { + case PROP_WRITERS_CAN_INVITE: + gdata_documents_entry_set_writers_can_invite (self, g_value_get_boolean (value)); + break; + case PROP_QUOTA_USED: + case PROP_FILE_SIZE: + /* Read only. */ + default: + /* We don't have any other property... */ + G_OBJECT_WARN_INVALID_PROPERTY_ID (object, property_id, pspec); + break; + } +} + +static void +get_key_value_and_visibility (JsonReader *reader, gchar **out_key, gchar **out_value, gchar **out_visibility, GError **error) +{ + g_autoptr(GError) child_error = NULL; + g_autofree gchar *key = NULL; + g_autofree gchar *value = NULL; + g_autofree gchar *visibility = NULL; + gboolean success = FALSE; + guint i, members; + + for (i = 0, members = (guint) json_reader_count_members (reader); i < members; i++) { + json_reader_read_element (reader, i); + + if (gdata_parser_string_from_json_member (reader, "key", P_REQUIRED | P_NON_EMPTY, &key, &success, &child_error) == TRUE) { + if (!success && child_error != NULL) { + g_propagate_prefixed_error (error, g_steal_pointer (&child_error), + /* Translators: the parameter is an error message */ + _("Error parsing JSON: %s"), + "Failed to find ‘key’."); + json_reader_end_element (reader); + return; + } + } + + if (gdata_parser_string_from_json_member (reader, "visibility", P_REQUIRED | P_NON_EMPTY, &visibility, &success, &child_error) == TRUE) { + if (!success && child_error != NULL) { + g_propagate_prefixed_error (error, g_steal_pointer (&child_error), + /* Translators: the parameter is an error message */ + _("Error parsing JSON: %s"), + "Failed to find ‘visibility’."); + json_reader_end_element (reader); + return; + } + } + + /* A Property can have a value field to be an empty string */ + if (gdata_parser_string_from_json_member (reader, "value", P_DEFAULT, &value, &success, &child_error) == TRUE) { + if (!success && child_error != NULL) { + g_propagate_prefixed_error (error, g_steal_pointer (&child_error), + /* Translators: the parameter is an error message */ + _("Error parsing JSON: %s"), + "Failed to find ‘value’."); + json_reader_end_element (reader); + return; + } + } + + json_reader_end_element (reader); + } + + if (out_key != NULL) { + *out_key = g_steal_pointer (&key); + } + + if (out_visibility != NULL) { + *out_visibility = g_steal_pointer (&visibility); + } + + if (out_value != NULL) { + *out_value = g_steal_pointer (&value); + } +} + +static void +get_kind_email_and_name (JsonReader *reader, gchar **out_kind, gchar **out_email, gchar **out_name, GError **error) +{ + GError *child_error = NULL; + gboolean success; + gchar *email = NULL; + gchar *kind = NULL; + gchar *name = NULL; + guint i, members; + + for (i = 0, members = (guint) json_reader_count_members (reader); i < members; i++) { + json_reader_read_element (reader, i); + + if (gdata_parser_string_from_json_member (reader, "kind", P_REQUIRED | P_NON_EMPTY, &kind, &success, &child_error) == TRUE) { + if (!success && child_error != NULL) { + g_propagate_prefixed_error (error, child_error, + /* Translators: the parameter is an error message */ + _("Error parsing JSON: %s"), + "Failed to find ‘kind’."); + json_reader_end_element (reader); + goto out; + } + } + + if (gdata_parser_string_from_json_member (reader, "displayName", P_REQUIRED | P_NON_EMPTY, &name, &success, &child_error) == TRUE) { + if (!success && child_error != NULL) { + g_propagate_prefixed_error (error, child_error, + /* Translators: the parameter is an error message */ + _("Error parsing JSON: %s"), + "Failed to find ‘displayName’."); + json_reader_end_element (reader); + goto out; + } + } + + if (gdata_parser_string_from_json_member (reader, "emailAddress", P_DEFAULT, &email, &success, &child_error) == TRUE) { + if (!success && child_error != NULL) { + g_propagate_prefixed_error (error, child_error, + /* Translators: the parameter is an error message */ + _("Error parsing JSON: %s"), + "Failed to find ‘emailAddress’."); + json_reader_end_element (reader); + goto out; + } + } + + json_reader_end_element (reader); + } + + if (out_kind != NULL) { + *out_kind = kind; + kind = NULL; + } + + if (out_email != NULL) { + *out_email = email; + email = NULL; + } + + if (out_name != NULL) { + *out_name = name; + name = NULL; + } + + out: + g_free (kind); + g_free (email); + g_free (name); +} + +static void +get_kind_and_parent_link (JsonReader *reader, gchar **out_kind, gchar **out_parent_link, GError **error) +{ + GError *child_error = NULL; + gboolean success; + gchar *kind = NULL; + gchar *parent_link = NULL; + guint i, members; + + for (i = 0, members = (guint) json_reader_count_members (reader); i < members; i++) { + json_reader_read_element (reader, i); + + if (gdata_parser_string_from_json_member (reader, "kind", P_REQUIRED | P_NON_EMPTY, &kind, &success, &child_error) == TRUE) { + if (!success && child_error != NULL) { + g_propagate_prefixed_error (error, child_error, + /* Translators: the parameter is an error message */ + _("Error parsing JSON: %s"), + "Failed to find ‘kind’."); + json_reader_end_element (reader); + goto out; + } + } + + if (gdata_parser_string_from_json_member (reader, "parentLink", P_REQUIRED | P_NON_EMPTY, &parent_link, &success, &child_error) == TRUE) { + if (!success && child_error != NULL) { + g_propagate_prefixed_error (error, child_error, + /* Translators: the parameter is an error message */ + _("Error parsing JSON: %s"), + "Failed to find ‘parentLink’."); + json_reader_end_element (reader); + goto out; + } + } + + json_reader_end_element (reader); + } + + if (out_kind != NULL) { + *out_kind = kind; + kind = NULL; + } + + if (out_parent_link != NULL) { + *out_parent_link = parent_link; + parent_link = NULL; + } + + out: + g_free (kind); + g_free (parent_link); +} + +static gboolean +parse_json (GDataParsable *parsable, JsonReader *reader, gpointer user_data, GError **error) +{ + GDataDocumentsEntryPrivate *priv = GDATA_DOCUMENTS_ENTRY (parsable)->priv; + GDataCategory *category; + GError *child_error = NULL; + gboolean shared; + gboolean success = TRUE; + gchar *alternate_uri = NULL; + gchar *kind = NULL; + gchar *mime_type = NULL; + gchar *quota_used = NULL; + gchar *file_size = NULL; + gint64 published; + gint64 updated; + + /* JSON format: https://developers.google.com/drive/v2/reference/files */ + + if (gdata_parser_string_from_json_member (reader, "alternateLink", P_DEFAULT, &alternate_uri, &success, error) == TRUE) { + if (success && alternate_uri != NULL && alternate_uri[0] != '\0') { + GDataLink *_link; + + _link = gdata_link_new (alternate_uri, GDATA_LINK_ALTERNATE); + gdata_entry_add_link (GDATA_ENTRY (parsable), _link); + g_object_unref (_link); + } + + g_free (alternate_uri); + return success; + } else if (gdata_parser_string_from_json_member (reader, "mimeType", P_DEFAULT, &mime_type, &success, error) == TRUE) { + if (success) + gdata_documents_utils_add_content_type (GDATA_DOCUMENTS_ENTRY (parsable), mime_type); + g_free (mime_type); + return success; + } else if (gdata_parser_int64_time_from_json_member (reader, "lastViewedByMeDate", P_DEFAULT, &(priv->last_viewed), &success, error) == TRUE || + gdata_parser_string_from_json_member (reader, "kind", P_REQUIRED | P_NON_EMPTY, &kind, &success, error) == TRUE) { + g_free (kind); + return success; + } else if (gdata_parser_int64_time_from_json_member (reader, "createdDate", P_DEFAULT, &published, &success, error) == TRUE) { + if (success) + _gdata_entry_set_published (GDATA_ENTRY (parsable), published); + return success; + } else if (gdata_parser_int64_time_from_json_member (reader, "modifiedDate", P_DEFAULT, &updated, &success, error) == TRUE) { + if (success) + _gdata_entry_set_updated (GDATA_ENTRY (parsable), updated); + return success; + } else if (gdata_parser_string_from_json_member (reader, "quotaBytesUsed", P_DEFAULT, "a_used, &success, error) == TRUE) { + gchar *end_ptr; + guint64 val; + + /* Even though ‘quotaBytesUsed’ is documented as long, + * it is actually a string in the JSON. + */ + val = g_ascii_strtoull (quota_used, &end_ptr, 10); + if (*end_ptr == '\0') + priv->quota_used = (goffset) val; + g_free (quota_used); + return success; + } else if (gdata_parser_string_from_json_member (reader, "fileSize", P_DEFAULT, &file_size, &success, error) == TRUE) { + gchar *end_ptr; + guint64 val; + + /* like 'quotaBytesUsed', 'fileSize' is also a string + * in the JSON. + */ + val = g_ascii_strtoull (file_size, &end_ptr, 10); + if (*end_ptr == '\0') + priv->file_size = (goffset) val; + g_free (file_size); + return success; + } else if (gdata_parser_boolean_from_json_member (reader, "shared", P_DEFAULT, &shared, &success, error) == TRUE) { + if (success && shared) { + category = gdata_category_new ("http://schemas.google.com/g/2005/labels#shared", GDATA_CATEGORY_SCHEMA_LABELS, "shared"); + gdata_entry_add_category (GDATA_ENTRY (parsable), category); + g_object_unref (category); + } + return success; + } else if (g_strcmp0 (json_reader_get_member_name (reader), "labels") == 0) { + guint i, members; + + if (json_reader_is_object (reader) == FALSE) { + g_set_error (error, GDATA_SERVICE_ERROR, GDATA_SERVICE_ERROR_PROTOCOL_ERROR, + /* Translators: the parameter is an error message */ + _("Error parsing JSON: %s"), + "JSON node ‘labels’ is not an object."); + return FALSE; + } + + for (i = 0, members = (guint) json_reader_count_members (reader); i < members; i++) { + gboolean starred; + gboolean viewed; + + json_reader_read_element (reader, i); + + gdata_parser_boolean_from_json_member (reader, "starred", P_DEFAULT, &starred, &success, NULL); + if (success && starred) { + category = gdata_category_new (GDATA_CATEGORY_SCHEMA_LABELS_STARRED, GDATA_CATEGORY_SCHEMA_LABELS, "starred"); + gdata_entry_add_category (GDATA_ENTRY (parsable), category); + g_object_unref (category); + } + + gdata_parser_boolean_from_json_member (reader, "viewed", P_DEFAULT, &viewed, &success, NULL); + if (success && viewed) { + category = gdata_category_new ("http://schemas.google.com/g/2005/labels#viewed", GDATA_CATEGORY_SCHEMA_LABELS, "viewed"); + gdata_entry_add_category (GDATA_ENTRY (parsable), category); + g_object_unref (category); + } + + json_reader_end_element (reader); + } + + return TRUE; + } else if (g_strcmp0 (json_reader_get_member_name (reader), "owners") == 0) { + guint i, elements; + + if (json_reader_is_array (reader) == FALSE) { + g_set_error (error, GDATA_SERVICE_ERROR, GDATA_SERVICE_ERROR_PROTOCOL_ERROR, + /* Translators: the parameter is an error message */ + _("Error parsing JSON: %s"), + "JSON node ‘owners’ is not an array."); + return FALSE; + } + + /* Loop through the elements array. */ + for (i = 0, elements = json_reader_count_elements (reader); success && i < elements; i++) { + gchar *email = NULL; + gchar *name = NULL; + + json_reader_read_element (reader, i); + + if (json_reader_is_object (reader) == FALSE) { + g_set_error (error, GDATA_SERVICE_ERROR, GDATA_SERVICE_ERROR_PROTOCOL_ERROR, + /* Translators: the parameter is an error message */ + _("Error parsing JSON: %s"), + "JSON node inside ‘owners’ is not an object."); + success = FALSE; + goto continue_owners; + } + + get_kind_email_and_name (reader, &kind, &email, &name, &child_error); + if (child_error != NULL) { + g_propagate_error (error, child_error); + success = FALSE; + goto continue_owners; + } + if (name == NULL || name[0] == '\0') { + g_set_error (error, GDATA_SERVICE_ERROR, GDATA_SERVICE_ERROR_PROTOCOL_ERROR, + /* Translators: the parameter is an error message */ + _("Error parsing JSON: %s"), + "Failed to find ‘displayName’."); + success = FALSE; + goto continue_owners; + } + + if (g_strcmp0 (kind, "drive#user") == 0) { + GDataAuthor *author; + + author = gdata_author_new (name, NULL, email); + gdata_entry_add_author (GDATA_ENTRY (parsable), author); + g_object_unref (author); + } else { + g_warning ("%s authors are not handled yet", kind); + } + + continue_owners: + g_free (email); + g_free (kind); + g_free (name); + json_reader_end_element (reader); + } + + return success; + } else if (g_strcmp0 (json_reader_get_member_name (reader), "parents") == 0) { + guint i, elements; + + if (json_reader_is_array (reader) == FALSE) { + g_set_error (error, GDATA_SERVICE_ERROR, GDATA_SERVICE_ERROR_PROTOCOL_ERROR, + /* Translators: the parameter is an error message */ + _("Error parsing JSON: %s"), + "JSON node ‘parents’ is not an array."); + return FALSE; + } + + /* Loop through the elements array. */ + for (i = 0, elements = (guint) json_reader_count_elements (reader); success && i < elements; i++) { + GDataLink *_link = NULL; + const gchar *relation_type = NULL; + gchar *uri = NULL; + + json_reader_read_element (reader, i); + + if (json_reader_is_object (reader) == FALSE) { + g_set_error (error, GDATA_SERVICE_ERROR, GDATA_SERVICE_ERROR_PROTOCOL_ERROR, + /* Translators: the parameter is an error message */ + _("Error parsing JSON: %s"), + "JSON node inside ‘parents’ is not an object."); + success = FALSE; + goto continue_parents; + } + + get_kind_and_parent_link (reader, &kind, &uri, &child_error); + if (child_error != NULL) { + g_propagate_error (error, child_error); + success = FALSE; + goto continue_parents; + } + + if (g_strcmp0 (kind, "drive#parentReference") == 0) { + relation_type = GDATA_LINK_PARENT; + } else { + g_warning ("%s parents are not handled yet", kind); + } + + if (relation_type == NULL) + goto continue_parents; + + _link = gdata_link_new (uri, relation_type); + gdata_entry_add_link (GDATA_ENTRY (parsable), _link); + + continue_parents: + g_clear_object (&_link); + g_free (kind); + g_free (uri); + json_reader_end_element (reader); + } + + return success; + } else if (g_strcmp0 (json_reader_get_member_name (reader), "properties") == 0) { + guint i, elements; + + if (!json_reader_is_array (reader)) { + g_set_error (error, GDATA_SERVICE_ERROR, GDATA_SERVICE_ERROR_PROTOCOL_ERROR, + /* Translators: the parameter is an error message */ + _("Error parsing JSON: %s"), + "JSON node ‘properties’ is not an array."); + return FALSE; + } + + /* Loop through the properties array. */ + for (i = 0, elements = (guint) json_reader_count_elements (reader); success && i < elements; i++) { + g_autofree gchar *key = NULL; + g_autofree gchar *value = NULL; + g_autofree gchar *visibility = NULL; + g_autoptr(GDataDocumentsProperty) property = NULL; + + json_reader_read_element (reader, i); + + if (!json_reader_is_object (reader)) { + g_set_error (error, GDATA_SERVICE_ERROR, GDATA_SERVICE_ERROR_PROTOCOL_ERROR, + /* Translators: the parameter is an error message */ + _("Error parsing JSON: %s"), + "JSON node inside ‘properties’ is not an object."); + success = FALSE; + goto continue_properties; + } + + get_key_value_and_visibility (reader, &key, &value, &visibility, &child_error); + + if (child_error != NULL) { + g_propagate_error (error, child_error); + success = FALSE; + goto continue_properties; + } + + if (g_strcmp0 (visibility, GDATA_DOCUMENTS_PROPERTY_VISIBILITY_PUBLIC) && + g_strcmp0 (visibility, GDATA_DOCUMENTS_PROPERTY_VISIBILITY_PRIVATE)) { + g_set_error (error, GDATA_SERVICE_ERROR, GDATA_SERVICE_ERROR_PROTOCOL_ERROR, + /* Translators: the parameter is the invalid value of visibility variable */ + _("Invalid visibility: unrecognized value ‘%s’"), + visibility); + success = FALSE; + goto continue_properties; + } + + g_assert (key != NULL); + + property = gdata_documents_property_new (key); + gdata_documents_property_set_visibility (property, visibility); + gdata_documents_property_set_value (property, value); + + gdata_documents_entry_add_documents_property (GDATA_DOCUMENTS_ENTRY (parsable), property); + + continue_properties: + json_reader_end_element (reader); + } + + return success; + } + + return GDATA_PARSABLE_CLASS (gdata_documents_entry_parent_class)->parse_json (parsable, reader, user_data, error); +} + +static gboolean +post_parse_json (GDataParsable *parsable, gpointer user_data, GError **error) +{ + GDataLink *_link; + const gchar *id; + gchar *uri; + + id = gdata_entry_get_id (GDATA_ENTRY (parsable)); + + /* gdata_access_handler_get_rules requires the presence of a GDATA_LINK_ACCESS_CONTROL_LIST link with the + * right URI. */ + uri = g_strconcat ("https://www.googleapis.com/drive/v2/files/", id, "/permissions", NULL); + _link = gdata_link_new (uri, GDATA_LINK_ACCESS_CONTROL_LIST); + gdata_entry_add_link (GDATA_ENTRY (parsable), _link); + g_free (uri); + g_object_unref (_link); + + return TRUE; +} + +static const gchar * +get_content_type (void) +{ + return "application/json"; +} + +static void +get_json (GDataParsable *parsable, JsonBuilder *builder) +{ + GList *i; + GList *parent_folders_list, *documents_properties_list; + const gchar *mime_type; + + GDATA_PARSABLE_CLASS (gdata_documents_entry_parent_class)->get_json (parsable, builder); + + /* Inserting files: https://developers.google.com/drive/v2/reference/files/insert */ + + mime_type = gdata_documents_utils_get_content_type (GDATA_DOCUMENTS_ENTRY (parsable)); + if (mime_type != NULL) { + json_builder_set_member_name (builder, "mimeType"); + json_builder_add_string_value (builder, mime_type); + } + + /* Upload to a folder: https://developers.google.com/drive/v2/web/folder */ + + json_builder_set_member_name (builder, "parents"); + json_builder_begin_array (builder); + + parent_folders_list = gdata_entry_look_up_links (GDATA_ENTRY (parsable), GDATA_LINK_PARENT); + for (i = parent_folders_list; i != NULL; i = i->next) { + GDataLink *_link = GDATA_LINK (i->data); + const gchar *id; + + id = gdata_documents_utils_get_id_from_link (_link); + if (id != NULL) { + json_builder_begin_object (builder); + json_builder_set_member_name (builder, "kind"); + json_builder_add_string_value (builder, "drive#fileLink"); + json_builder_set_member_name (builder, "id"); + json_builder_add_string_value (builder, id); + json_builder_end_object (builder); + } + } + + json_builder_end_array (builder); + + g_list_free (parent_folders_list); + + /* Set all the properties */ + json_builder_set_member_name (builder, "properties"); + json_builder_begin_array (builder); + + documents_properties_list = gdata_documents_entry_get_document_properties (GDATA_DOCUMENTS_ENTRY (parsable)); + for (i = documents_properties_list; i != NULL; i = i->next) { + GDataDocumentsProperty *property = GDATA_DOCUMENTS_PROPERTY (i->data); + const gchar *key = NULL; + const gchar *value = NULL; + const gchar *visibility = NULL; + + if (property != NULL) { + key = gdata_documents_property_get_key (property); + value = gdata_documents_property_get_value (property); + visibility = gdata_documents_property_get_visibility (property); + + json_builder_begin_object (builder); + + json_builder_set_member_name (builder, "key"); + json_builder_add_string_value (builder, key); + + json_builder_set_member_name (builder, "visibility"); + json_builder_add_string_value (builder, visibility); + + json_builder_set_member_name (builder, "value"); + if (value == NULL) { + json_builder_add_null_value (builder); + } else { + json_builder_add_string_value (builder, value); + } + + json_builder_end_object (builder); + } + } + + json_builder_end_array (builder); +} + +static void +get_namespaces (GDataParsable *parsable, GHashTable *namespaces) +{ + /* Chain up to the parent class */ + GDATA_PARSABLE_CLASS (gdata_documents_entry_parent_class)->get_namespaces (parsable, namespaces); + + g_hash_table_insert (namespaces, (gchar*) "docs", (gchar*) "http://schemas.google.com/docs/2007"); +} + +static gchar * +get_entry_uri (const gchar *id) +{ + return g_strconcat ("https://www.googleapis.com/drive/v2/files/", id, NULL); +} + +/** + * gdata_documents_entry_get_edited: + * @self: a #GDataDocumentsEntry + * + * Gets the #GDataDocumentsEntry:edited property. If the property is unset, -1 will be returned. + * + * Return value: the UNIX timestamp for the time the document was last edited, or -1 + * + * Since: 0.4.0 + * Deprecated: 0.17.0: Use gdata_entry_get_updated() instead. See #GDataDocumentsEntry:edited. + */ +gint64 +gdata_documents_entry_get_edited (GDataDocumentsEntry *self) +{ + g_return_val_if_fail (GDATA_IS_DOCUMENTS_ENTRY (self), -1); + return gdata_entry_get_updated (GDATA_ENTRY (self)); +} + +/** + * gdata_documents_entry_get_last_viewed: + * @self: a #GDataDocumentsEntry + * + * Gets the #GDataDocumentsEntry:last-viewed property. If the property is unset, -1 will be returned. + * + * Return value: the UNIX timestamp for the time the document was last viewed, or -1 + * + * Since: 0.4.0 + */ +gint64 +gdata_documents_entry_get_last_viewed (GDataDocumentsEntry *self) +{ + g_return_val_if_fail (GDATA_IS_DOCUMENTS_ENTRY (self), -1); + return self->priv->last_viewed; +} + +/** + * gdata_documents_entry_get_path: + * @self: a #GDataDocumentsEntry + * + * Builds a path for the #GDataDocumentsEntry, starting from a root node and traversing the folders containing the document, then ending with the + * document's ID. + * + * An example path would be: /folder_id1/folder_id2/document_id. + * + * Note: the path is based on the entry/document IDs of the folders (#GDataEntry:id) and document (#GDataDocumentsEntry:document-id), + * and not the entries' human-readable names (#GDataEntry:title). + * + * Return value: the folder hierarchy path containing the document, or %NULL; free with g_free() + * + * Since: 0.4.0 + */ +gchar * +gdata_documents_entry_get_path (GDataDocumentsEntry *self) +{ + GList *element, *parent_folders_list = NULL; + GString *path; + const gchar *id; + + g_return_val_if_fail (GDATA_IS_DOCUMENTS_ENTRY (self), NULL); + + path = g_string_new ("/"); + parent_folders_list = gdata_entry_look_up_links (GDATA_ENTRY (self), GDATA_LINK_PARENT); + + /* We check all the folders contained that are parents of the GDataDocumentsEntry */ + for (element = parent_folders_list; element != NULL; element = element->next) { + guint i; + gchar *folder_id = NULL; + gchar **link_href_cut = g_strsplit (gdata_link_get_uri (GDATA_LINK (element->data)), "/", 0); + + /* Extract the folder ID from the folder URI, which is of the form: + * http://docs.google.com/feeds/documents/private/full/folder%3Afolder_id + * We want the "folder_id" bit. */ + for (i = 0;; i++) { + gchar **path_cut = NULL; + + if (link_href_cut[i] == NULL) + break; + + path_cut = g_strsplit (link_href_cut[i], "%3A", 2); + if (*path_cut != NULL) { + if (strcmp (path_cut[0], "folder") == 0){ + folder_id = g_strdup (path_cut[1]); + g_strfreev (path_cut); + break; + } + } + g_strfreev (path_cut); + } + g_strfreev (link_href_cut); + g_assert (folder_id != NULL); + + /* Append the folder ID to our path */ + g_string_append (path, folder_id); + g_string_append_c (path, '/'); + g_free (folder_id); + } + + /* Append the entry ID */ + id = gdata_entry_get_id (GDATA_ENTRY (self)); + g_string_append (path, id); + + return g_string_free (path, FALSE); +} + +/** + * gdata_documents_entry_get_document_id: + * @self: a #GDataDocumentsEntry + * + * Gets the #GDataDocumentsEntry:document-id property. The + * online GData Documentation + * refers to these as “untyped resource IDs”. + * + * Return value: the document's document ID + * + * Since: 0.4.0 + * Deprecated: 0.11.0: Use gdata_documents_entry_get_resource_id() instead. See #GDataDocumentsEntry:document-id. + */ +const gchar * +gdata_documents_entry_get_document_id (GDataDocumentsEntry *self ) +{ + g_return_val_if_fail (GDATA_IS_DOCUMENTS_ENTRY (self), NULL); + return gdata_entry_get_id (GDATA_ENTRY (self)); +} + +/** + * gdata_documents_entry_get_resource_id: + * @self: a #GDataDocumentsEntry + * + * Gets the #GDataDocumentsEntry:resource-id property. + * + * Return value: the document's resource ID + * + * Since: 0.11.0 + */ +const gchar * +gdata_documents_entry_get_resource_id (GDataDocumentsEntry *self) +{ + g_return_val_if_fail (GDATA_IS_DOCUMENTS_ENTRY (self), NULL); + return self->priv->resource_id; +} + +void +_gdata_documents_entry_set_resource_id (GDataDocumentsEntry *self, const gchar *resource_id) +{ + g_return_if_fail (GDATA_IS_DOCUMENTS_ENTRY (self)); + g_return_if_fail (resource_id != NULL && resource_id[0] != '\0'); + + if (g_strcmp0 (resource_id, self->priv->resource_id) == 0) + return; + + g_free (self->priv->resource_id); + self->priv->resource_id = g_strdup (resource_id); + + g_object_notify (G_OBJECT (self), "resource-id"); +} + +/** + * gdata_documents_entry_set_writers_can_invite: + * @self: a #GDataDocumentsEntry + * @writers_can_invite: %TRUE if writers can invite other people to edit the document, %FALSE otherwise + * + * Sets the #GDataDocumentsEntry:writers-can-invite property to @writers_can_invite. + * + * Since: 0.4.0 + */ +void +gdata_documents_entry_set_writers_can_invite (GDataDocumentsEntry *self, gboolean writers_can_invite) +{ + g_return_if_fail (GDATA_IS_DOCUMENTS_ENTRY (self)); + self->priv->writers_can_invite = writers_can_invite; + g_object_notify (G_OBJECT (self), "writers-can-invite"); +} + +/** + * gdata_documents_entry_writers_can_invite: + * @self: a #GDataDocumentsEntry + * + * Gets the #GDataDocumentsEntry:writers-can-invite property. + * + * Return value: %TRUE if writers can invite other people to edit the document, %FALSE otherwise + * + * Since: 0.4.0 + */ +gboolean +gdata_documents_entry_writers_can_invite (GDataDocumentsEntry *self) +{ + g_return_val_if_fail (GDATA_IS_DOCUMENTS_ENTRY (self ), FALSE); + return self->priv->writers_can_invite; +} + +/** + * gdata_documents_entry_get_last_modified_by: + * @self: a #GDataDocumentsEntry + * + * Gets the #GDataDocumentsEntry:last-modified-by property. + * + * Return value: (transfer none): the author who last modified the document + * + * Since: 0.4.0 + */ +GDataAuthor * +gdata_documents_entry_get_last_modified_by (GDataDocumentsEntry *self) +{ + g_return_val_if_fail (GDATA_IS_DOCUMENTS_ENTRY (self), NULL); + return self->priv->last_modified_by; +} + +/** + * gdata_documents_entry_get_quota_used: + * @self: a #GDataDocumentsEntry + * + * Gets the #GDataDocumentsEntry:quota-used property. + * + * Return value: the number of quota bytes used by the document + * + * Since: 0.13.0 + */ +goffset +gdata_documents_entry_get_quota_used (GDataDocumentsEntry *self) +{ + g_return_val_if_fail (GDATA_IS_DOCUMENTS_ENTRY (self), 0); + + return self->priv->quota_used; +} + +/** + * gdata_documents_entry_get_file_size: + * @self: a #GDataDocumentsEntry + * + * Gets the #GDataDocumentsEntry:file-size property. + * + * Return value: the size of the document in bytes + * + * Since: 0.17.7 + */ +goffset +gdata_documents_entry_get_file_size (GDataDocumentsEntry *self) +{ + g_return_val_if_fail (GDATA_IS_DOCUMENTS_ENTRY (self), 0); + + return self->priv->file_size; +} + +/** + * gdata_documents_entry_is_deleted: + * @self: a #GDataDocumentsEntry + * + * Gets the #GDataDocumentsEntry:is-deleted property. + * + * Return value: %TRUE if the document has been deleted, %FALSE otherwise + * + * Since: 0.5.0 + */ +gboolean +gdata_documents_entry_is_deleted (GDataDocumentsEntry *self) +{ + g_return_val_if_fail (GDATA_IS_DOCUMENTS_ENTRY (self), FALSE); + return self->priv->is_deleted; +} + + +/** + * gdata_documents_entry_get_document_properties: + * @self: a #GDataDocumentsEntry + * + * Gets a list of the #GDataDocumentsPropertys for this entry. + * + * Return value: (transfer none) (element-type GDataDocumentsProperty): a #GList of pointers to #GDataDocumentsPropertys + * + * Since: 0.17.11 + */ +GList * +gdata_documents_entry_get_document_properties (GDataDocumentsEntry *self) +{ + g_return_val_if_fail (GDATA_IS_DOCUMENTS_ENTRY (self), NULL); + return self->priv->properties; +} + +/** + * gdata_documents_entry_add_documents_property: + * @self: a #GDataDocumentsEntry + * @property: a #GDataDocumentsProperty + * + * Inserts/updates @property on "properties" list in @self. Since, a GDataDocumentsProperty is uniquely identified by #GDataDocumentsProperty:key and #GDataDocumentsProperty:visibility, if no such property exists in the "properties" list, then a @property will be appended to the list after incrementing the reference count. + * + * In case that there already exists a @property in "properties", the #GDataDocumentsProperty inside the list will be updated to @property. Note that #GDataDocumentsProperty:value has no role in determining the uniqueness of a #GDataDocumentsProperty. + * + * The changes made by this function will be local only and you need to explicitly update @self by calling gdata_service_update_entry(). + * + * Return value: %TRUE if the @property doesn't exist in the "properties" list, or that #GDataDocumentsProperty:value of @property has been set to %NULL by a call to gdata_documents_entry_remove_documents_property(). %FALSE if @property exists in "properties" list, or in the case that @self or @property aren't of proper types. + * + * Since: 0.17.11 + */ +gboolean +gdata_documents_entry_add_documents_property (GDataDocumentsEntry *self, GDataDocumentsProperty *property) { + GList *l = NULL; + gboolean ret_val = TRUE; + + g_return_val_if_fail (GDATA_IS_DOCUMENTS_ENTRY (self), FALSE); + g_return_val_if_fail (GDATA_IS_DOCUMENTS_PROPERTY (property), FALSE); + + l = g_list_find_custom (self->priv->properties, property, (GCompareFunc) gdata_comparable_compare); + + if (l == NULL) { + self->priv->properties = g_list_prepend (self->priv->properties, g_object_ref (property)); + } else { + GDataDocumentsProperty *_prop = GDATA_DOCUMENTS_PROPERTY (l->data); + if (gdata_documents_property_get_value (_prop) != NULL) + ret_val = FALSE; + gdata_documents_property_set_value (_prop, gdata_documents_property_get_value (property)); + } + + return ret_val; +} + +/** + * gdata_documents_entry_remove_documents_property: + * @self: a #GDataDocumentsEntry + * @property: a #GDataDocumentsProperty + * + * The property specified by @property will be removed from the "properties" list on @self. + * + * Only #GDataDocumentsProperty:key and #GDataDocumentsProperty:visibility will be used to find @property in "properties" list. #GDataDocumentsProperty:value has no role in determining the uniqueness of a #GDataDocumentsProperty. + * + * The changes made by this function will be local only and you need to explicitly update @self by calling gdata_service_update_entry(). + * + * Return value: %TRUE if @property has been successfully removed from "properties" list on @self, %FALSE otherwise. + * + * Since: 0.17.11 + */ +gboolean +gdata_documents_entry_remove_documents_property (GDataDocumentsEntry *self, GDataDocumentsProperty *property) { + GList *l; + + g_return_val_if_fail (GDATA_IS_DOCUMENTS_ENTRY (self), FALSE); + g_return_val_if_fail (GDATA_IS_DOCUMENTS_PROPERTY (property), FALSE); + + l = g_list_find_custom (self->priv->properties, property, (GCompareFunc) gdata_comparable_compare); + + if (l == NULL) { + return FALSE; + } + + /* Google Drive has this weird behaviour that setting the properties + * array to empty with file/update method doesn't empties the array. + * For eg. Suppose we initially did an update with properties array + * with value [1, 2, 3]. If we again update the properties array with + * [1, 5, 6], the final resulting properties array will be [1, 2, 3, 5, + * 6] meaning that the values get appended on subsequent updates. + * + * The way to counter this is to set the "value" field in the Property + * Resource to NULL, which removes that Property Resource from the + * properties array. + */ + gdata_documents_property_set_value ((GDataDocumentsProperty *) l->data, NULL); + + return TRUE; +} diff --git a/gdata/services/documents/gdata-documents-entry.h b/gdata/services/documents/gdata-documents-entry.h new file mode 100644 index 0000000..558b91d --- /dev/null +++ b/gdata/services/documents/gdata-documents-entry.h @@ -0,0 +1,130 @@ +/* -*- Mode: C; indent-tabs-mode: t; c-basic-offset: 8; tab-width: 8 -*- */ +/* + * GData Client + * Copyright (C) Thibault Saunier 2009 + * + * GData Client is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * GData Client is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with GData Client. If not, see . + */ + +#ifndef GDATA_DOCUMENTS_ENTRY_H +#define GDATA_DOCUMENTS_ENTRY_H + +#include +#include + +#include +#include +#include +#include + +G_BEGIN_DECLS + +/** + * GDATA_DOCUMENTS_ACCESS_ROLE_OWNER: + * + * The users specified by the #GDataAccessRule have full owner access to the document. This allows them to modify the access rules and delete + * the document, amongst other things. + * + * Since: 0.7.0 + */ +#define GDATA_DOCUMENTS_ACCESS_ROLE_OWNER "owner" + +/** + * GDATA_DOCUMENTS_ACCESS_ROLE_WRITER: + * + * The users specified by the #GDataAccessRule have write access to the document. They cannot modify the access rules or delete the document. + * + * Since: 0.7.0 + */ +#define GDATA_DOCUMENTS_ACCESS_ROLE_WRITER "writer" + +/** + * GDATA_DOCUMENTS_ACCESS_ROLE_READER: + * + * The users specified by the #GDataAccessRule have read-only access to the document. + * + * Since: 0.7.0 + */ +#define GDATA_DOCUMENTS_ACCESS_ROLE_READER "reader" + +#define GDATA_TYPE_DOCUMENTS_ENTRY (gdata_documents_entry_get_type ()) +#define GDATA_DOCUMENTS_ENTRY(o) (G_TYPE_CHECK_INSTANCE_CAST ((o), GDATA_TYPE_DOCUMENTS_ENTRY, GDataDocumentsEntry)) +#define GDATA_DOCUMENTS_ENTRY_CLASS(k) (G_TYPE_CHECK_CLASS_CAST((k), GDATA_TYPE_DOCUMENTS_ENTRY, GDataDocumentsEntryClass)) +#define GDATA_IS_DOCUMENTS_ENTRY(o) (G_TYPE_CHECK_INSTANCE_TYPE ((o), GDATA_TYPE_DOCUMENTS_ENTRY)) +#define GDATA_IS_DOCUMENTS_ENTRY_CLASS(k) (G_TYPE_CHECK_CLASS_TYPE ((k), GDATA_TYPE_DOCUMENTS_ENTRY)) +#define GDATA_DOCUMENTS_ENTRY_GET_CLASS(o) (G_TYPE_INSTANCE_GET_CLASS ((o), GDATA_TYPE_DOCUMENTS_ENTRY, GDataDocumentsEntryClass)) + +typedef struct _GDataDocumentsEntryPrivate GDataDocumentsEntryPrivate; + +/** + * GDataDocumentsEntry: + * + * All the fields in the #GDataDocumentsEntry structure are private and should never be accessed directly. + * + * Since: 0.4.0 + */ +typedef struct { + GDataEntry parent; + GDataDocumentsEntryPrivate *priv; +} GDataDocumentsEntry; + +/** + * GDataDocumentsEntryClass: + * + * All the fields in the #GDataDocumentsEntryClass structure are private and should never be accessed directly. + * + * Since: 0.4.0 + */ +typedef struct { + /*< private >*/ + GDataEntryClass parent; + + /*< private >*/ + /* Padding for future expansion */ + void (*_g_reserved0) (void); + void (*_g_reserved1) (void); +} GDataDocumentsEntryClass; + +GType gdata_documents_entry_get_type (void) G_GNUC_CONST; +G_DEFINE_AUTOPTR_CLEANUP_FUNC (GDataDocumentsEntry, g_object_unref) + +gchar *gdata_documents_entry_get_path (GDataDocumentsEntry *self) G_GNUC_WARN_UNUSED_RESULT G_GNUC_MALLOC; + +const gchar *gdata_documents_entry_get_resource_id (GDataDocumentsEntry *self) G_GNUC_PURE; + +#ifndef LIBGDATA_DISABLE_DEPRECATED +const gchar *gdata_documents_entry_get_document_id (GDataDocumentsEntry *self) G_GNUC_PURE G_GNUC_DEPRECATED_FOR(gdata_documents_entry_get_resource_id); +gint64 gdata_documents_entry_get_edited (GDataDocumentsEntry *self) G_GNUC_DEPRECATED_FOR(gdata_entry_get_updated); +#endif /* !LIBGDATA_DISABLE_DEPRECATED */ + +gint64 gdata_documents_entry_get_last_viewed (GDataDocumentsEntry *self); + +void gdata_documents_entry_set_writers_can_invite (GDataDocumentsEntry *self, gboolean writers_can_invite); +gboolean gdata_documents_entry_writers_can_invite (GDataDocumentsEntry *self) G_GNUC_PURE; + +GDataAuthor *gdata_documents_entry_get_last_modified_by (GDataDocumentsEntry *self) G_GNUC_PURE; + +goffset gdata_documents_entry_get_quota_used (GDataDocumentsEntry *self) G_GNUC_PURE; +goffset gdata_documents_entry_get_file_size (GDataDocumentsEntry *self) G_GNUC_PURE; + +gboolean gdata_documents_entry_is_deleted (GDataDocumentsEntry *self) G_GNUC_PURE; + +GList *gdata_documents_entry_get_document_properties (GDataDocumentsEntry *self); + +gboolean gdata_documents_entry_add_documents_property (GDataDocumentsEntry *self, GDataDocumentsProperty *property); +gboolean gdata_documents_entry_remove_documents_property (GDataDocumentsEntry *self, GDataDocumentsProperty *property); + +G_END_DECLS + +#endif /* !GDATA_DOCUMENTS_ENTRY_H */ diff --git a/gdata/services/documents/gdata-documents-feed.c b/gdata/services/documents/gdata-documents-feed.c new file mode 100644 index 0000000..3637097 --- /dev/null +++ b/gdata/services/documents/gdata-documents-feed.c @@ -0,0 +1,185 @@ +/* -*- Mode: C; indent-tabs-mode: t; c-basic-offset: 8; tab-width: 8 -*- */ +/* + * GData Client + * Copyright (C) Thibault Saunier 2009 + * Copyright (C) Philip Withnall 2010 + * Copyright (C) Red Hat, Inc. 2015 + * + * GData Client is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * GData Client is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with GData Client. If not, see . + */ + +/** + * SECTION:gdata-documents-feed + * @short_description: GData documents feed object + * @stability: Stable + * @include: gdata/services/documents/gdata-documents-feed.h + * + * #GDataDocumentsFeed is a list of entries (#GDataDocumentsEntry subclasses) returned as the result of a query to a #GDataDocumentsService, + * or given as the input to another operation on the online service. + * + * Each #GDataDocumentsEntry represents a single object on the Google Documents online service, such as a text document, presentation document, + * spreadsheet document or a folder, and the #GDataDocumentsFeed represents a collection of those objects. + * + * Since: 0.4.0 + */ + +#include +#include +#include +#include + +#include "gdata-documents-feed.h" +#include "gdata-documents-utils.h" +#include "gdata-types.h" +#include "gdata-private.h" +#include "gdata-service.h" + +static gboolean parse_json (GDataParsable *parsable, JsonReader *reader, gpointer user_data, GError **error); + +G_DEFINE_TYPE (GDataDocumentsFeed, gdata_documents_feed, GDATA_TYPE_FEED) + +static void +gdata_documents_feed_class_init (GDataDocumentsFeedClass *klass) +{ + GDataParsableClass *parsable_class = GDATA_PARSABLE_CLASS (klass); + parsable_class->parse_json = parse_json; +} + +static void +gdata_documents_feed_init (GDataDocumentsFeed *self) +{ + /* Why am I writing it? */ +} + +static void +get_kind_and_mime_type (JsonReader *reader, gchar **out_kind, gchar **out_mime_type, GError **error) +{ + GError *child_error = NULL; + gboolean success; + gchar *kind = NULL; + gchar *mime_type = NULL; + guint i, members; + + for (i = 0, members = (guint) json_reader_count_members (reader); i < members; i++) { + json_reader_read_element (reader, i); + + if (gdata_parser_string_from_json_member (reader, "kind", P_REQUIRED | P_NON_EMPTY, &kind, &success, &child_error) == TRUE) { + if (!success && child_error != NULL) { + g_propagate_prefixed_error (error, child_error, + /* Translators: the parameter is an error message */ + _("Error parsing JSON: %s"), + "Failed to find ‘kind’."); + json_reader_end_element (reader); + goto out; + } + } + + if (gdata_parser_string_from_json_member (reader, "mimeType", P_DEFAULT, &mime_type, &success, &child_error) == TRUE) { + if (!success && child_error != NULL) { + g_propagate_prefixed_error (error, child_error, + /* Translators: the parameter is an error message */ + _("Error parsing JSON: %s"), + "Failed to find ‘mimeType’."); + json_reader_end_element (reader); + goto out; + } + } + + json_reader_end_element (reader); + } + + if (out_kind != NULL) { + *out_kind = kind; + kind = NULL; + } + + if (out_mime_type != NULL) { + *out_mime_type = mime_type; + mime_type = NULL; + } + + out: + g_free (kind); + g_free (mime_type); +} + +static gboolean +parse_json (GDataParsable *parsable, JsonReader *reader, gpointer user_data, GError **error) +{ + /* JSON format: https://developers.google.com/drive/v2/reference/files/list */ + + if (g_strcmp0 (json_reader_get_member_name (reader), "items") == 0) { + gboolean success = TRUE; + guint i, elements; + + if (json_reader_is_array (reader) == FALSE) { + g_set_error (error, GDATA_SERVICE_ERROR, GDATA_SERVICE_ERROR_PROTOCOL_ERROR, + /* Translators: the parameter is an error message */ + _("Error parsing JSON: %s"), + "JSON node ‘items’ is not an array."); + return FALSE; + } + + /* Loop through the elements array. */ + for (i = 0, elements = (guint) json_reader_count_elements (reader); success && i < elements; i++) { + GDataEntry *entry = NULL; + GError *child_error = NULL; + GType entry_type = G_TYPE_INVALID; + gchar *kind = NULL; + gchar *mime_type = NULL; + + json_reader_read_element (reader, i); + + if (json_reader_is_object (reader) == FALSE) { + g_set_error (error, GDATA_SERVICE_ERROR, GDATA_SERVICE_ERROR_PROTOCOL_ERROR, + /* Translators: the parameter is an error message */ + _("Error parsing JSON: %s"), + "JSON node inside ‘items’ is not an object"); + success = FALSE; + goto continuation; + } + + get_kind_and_mime_type (reader, &kind, &mime_type, &child_error); + if (child_error != NULL) { + g_propagate_error (error, child_error); + success = FALSE; + goto continuation; + } + + if (g_strcmp0 (kind, "drive#file") == 0) { + entry_type = gdata_documents_utils_get_type_from_content_type (mime_type); + } else { + g_warning ("%s files are not handled yet", kind); + } + + if (entry_type == G_TYPE_INVALID) + goto continuation; + + entry = GDATA_ENTRY (_gdata_parsable_new_from_json_node (entry_type, reader, NULL, error)); + /* Call the progress callback in the main thread */ + _gdata_feed_call_progress_callback (GDATA_FEED (parsable), user_data, entry); + _gdata_feed_add_entry (GDATA_FEED (parsable), entry); + + continuation: + g_clear_object (&entry); + g_free (kind); + g_free (mime_type); + json_reader_end_element (reader); + } + + return success; + } + + return GDATA_PARSABLE_CLASS (gdata_documents_feed_parent_class)->parse_json (parsable, reader, user_data, error); +} diff --git a/gdata/services/documents/gdata-documents-feed.h b/gdata/services/documents/gdata-documents-feed.h new file mode 100644 index 0000000..22f1fec --- /dev/null +++ b/gdata/services/documents/gdata-documents-feed.h @@ -0,0 +1,73 @@ +/* -*- Mode: C; indent-tabs-mode: t; c-basic-offset: 8; tab-width: 8 -*- */ +/* + * GData Client + * Copyright (C) Thibault Saunier . + */ + +#ifndef GDATA_DOCUMENTS_FEED_H +#define GDATA_DOCUMENTS_FEED_H + +#include +#include +#include + +G_BEGIN_DECLS + +#define GDATA_TYPE_DOCUMENTS_FEED (gdata_documents_feed_get_type ()) +#define GDATA_DOCUMENTS_FEED(o) (G_TYPE_CHECK_INSTANCE_CAST ((o), GDATA_TYPE_DOCUMENTS_FEED, GDataDocumentsFeed)) +#define GDATA_DOCUMENTS_FEED_CLASS(k) (G_TYPE_CHECK_CLASS_CAST((k), GDATA_TYPE_DOCUMENTS_FEED, GDataDocumentsFeedClass)) +#define GDATA_IS_DOCUMENTS_FEED(o) (G_TYPE_CHECK_INSTANCE_TYPE ((o), GDATA_TYPE_DOCUMENTS_FEED)) +#define GDATA_IS_DOCUMENTS_FEED_CLASS(k) (G_TYPE_CHECK_CLASS_TYPE ((k), GDATA_TYPE_DOCUMENTS_FEED)) +#define GDATA_DOCUMENTS_FEED_GET_CLASS(o) (G_TYPE_INSTANCE_GET_CLASS ((o), GDATA_TYPE_DOCUMENTS_FEED, GDataDocumentsFeedClass)) + +typedef struct _GDataDocumentsFeedPrivate GDataDocumentsFeedPrivate; + +/** + * GDataDocumentsFeed: + * + * All the fields in the #GDataDocumentsFeed structure are private and should never be accessed directly. + * + * Since: 0.4.0 + */ +typedef struct { + /*< private >*/ + GDataFeed parent; + GDataDocumentsFeedPrivate *priv; +} GDataDocumentsFeed; + +/** + * GDataDocumentsFeedClass: + * + * All the fields in the #GDataDocumentsFeedClass structure are private and should never be accessed directly. + * + * Since: 0.4.0 + */ +typedef struct { + /*< private >*/ + GDataFeedClass parent; + + /*< private >*/ + /* Padding for future expansion */ + void (*_g_reserved0) (void); + void (*_g_reserved1) (void); +} GDataDocumentsFeedClass; + +GType gdata_documents_feed_get_type (void) G_GNUC_CONST; +G_DEFINE_AUTOPTR_CLEANUP_FUNC (GDataDocumentsFeed, g_object_unref) + +G_END_DECLS + +#endif /* !GDATA_DOCUMENTS_FEED_H */ diff --git a/gdata/services/documents/gdata-documents-folder.c b/gdata/services/documents/gdata-documents-folder.c new file mode 100644 index 0000000..bd59a20 --- /dev/null +++ b/gdata/services/documents/gdata-documents-folder.c @@ -0,0 +1,157 @@ +/* -*- Mode: C; indent-tabs-mode: t; c-basic-offset: 8; tab-width: 8 -*- */ +/* + * GData Client + * Copyright (C) Thibault Saunier 2009 + * Copyright (C) Philip Withnall 2010 + * Copyright (C) Red Hat, Inc. 2015, 2016, 2017 + * + * GData Client is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * GData Client is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with GData Client. If not, see . + */ + +/** + * SECTION:gdata-documents-folder + * @short_description: GData documents folder object + * @stability: Stable + * @include: gdata/services/documents/gdata-documents-folder.h + * + * #GDataDocumentsFolder is a subclass of #GDataDocumentsEntry to represent a folder from Google Documents. + * + * For more details of Google Drive's GData API, see the + * online documentation. + * + * + * Adding a Folder + * + * GDataAuthorizationDomain *domain; + * GDataDocumentsService *service; + * GDataDocumentsFolder *folder, *new_folder, *parent_folder; + * GError *error = NULL; + * + * domain = gdata_documents_service_get_primary_authorization_domain (); + * + * /* Create a service */ + * service = create_documents_service (); + * + * parent_folder = GDATA_DOCUMENTS_FOLDER (gdata_service_query_single_entry (GDATA_SERVICE (service), domain, "root", NULL, + * GDATA_TYPE_DOCUMENTS_FOLDER, NULL, &error)); + * if (error != NULL) { + * g_error ("Error getting root folder"); + * g_error_free (error); + * return; + * } + * + * /* Create the new folder */ + * folder = gdata_documents_folder_new (NULL); + * gdata_entry_set_title (GDATA_ENTRY (folder), "Folder Name"); + * + * /* Insert the folder */ + * new_folder = GDATA_DOCUMENTS_FOLDER (gdata_documents_service_add_entry_to_folder (GDATA_SERVICE (service), GDATA_DOCUMENTS_ENTRY (folder), + * parent_folder, NULL, &error)); + * + * g_object_unref (folder); + * g_object_unref (parent_folder); + * g_object_unref (service); + * + * if (error != NULL) { + * g_error ("Error inserting new folder: %s", error->message); + * g_error_free (error); + * return; + * } + * + * /* Do something with the new folder, such as store its ID for future use */ + * + * g_object_unref (new_folder); + * + * + * + * Since: 0.4.0 + */ + +#include +#include +#include +#include +#include + +#include "gdata-documents-entry-private.h" +#include "gdata-documents-folder.h" +#include "gdata-documents-utils.h" +#include "gdata-parser.h" +#include "gdata-types.h" +#include "gdata-private.h" + +static void gdata_documents_folder_constructed (GObject *object); +static gboolean post_parse_json (GDataParsable *parsable, gpointer user_data, GError **error); + +G_DEFINE_TYPE (GDataDocumentsFolder, gdata_documents_folder, GDATA_TYPE_DOCUMENTS_ENTRY) + +static void +gdata_documents_folder_class_init (GDataDocumentsFolderClass *klass) +{ + GObjectClass *gobject_class = G_OBJECT_CLASS (klass); + GDataParsableClass *parsable_class = GDATA_PARSABLE_CLASS (klass); + GDataEntryClass *entry_class = GDATA_ENTRY_CLASS (klass); + + gobject_class->constructed = gdata_documents_folder_constructed; + parsable_class->post_parse_json = post_parse_json; + entry_class->kind_term = "http://schemas.google.com/docs/2007#folder"; +} + +static void +gdata_documents_folder_init (GDataDocumentsFolder *self) +{ + /* Why am I writing it? */ +} + +static void +gdata_documents_folder_constructed (GObject *object) +{ + G_OBJECT_CLASS (gdata_documents_folder_parent_class)->constructed (object); + + if (!_gdata_parsable_is_constructed_from_xml (GDATA_PARSABLE (object))) + gdata_documents_utils_add_content_type (GDATA_DOCUMENTS_ENTRY (object), "application/vnd.google-apps.folder"); +} + +static gboolean +post_parse_json (GDataParsable *parsable, gpointer user_data, GError **error) +{ + const gchar *id; + gchar *resource_id; + + id = gdata_entry_get_id (GDATA_ENTRY (parsable)); + + /* Since the document-id is identical to GDataEntry:id, which is parsed by the parent class, we can't + * create the resource-id while parsing. */ + resource_id = g_strconcat ("folder:", id, NULL); + _gdata_documents_entry_set_resource_id (GDATA_DOCUMENTS_ENTRY (parsable), resource_id); + + g_free (resource_id); + return GDATA_PARSABLE_CLASS (gdata_documents_folder_parent_class)->post_parse_json (parsable, user_data, error); +} + +/** + * gdata_documents_folder_new: + * @id: (allow-none): the entry's ID (not the document ID of the folder), or %NULL + * + * Creates a new #GDataDocumentsFolder with the given entry ID (#GDataEntry:id). + * + * Return value: a new #GDataDocumentsFolder, or %NULL; unref with g_object_unref() + * + * Since: 0.4.0 + */ +GDataDocumentsFolder * +gdata_documents_folder_new (const gchar *id) +{ + return GDATA_DOCUMENTS_FOLDER (g_object_new (GDATA_TYPE_DOCUMENTS_FOLDER, "id", id, NULL)); +} diff --git a/gdata/services/documents/gdata-documents-folder.h b/gdata/services/documents/gdata-documents-folder.h new file mode 100644 index 0000000..9949c99 --- /dev/null +++ b/gdata/services/documents/gdata-documents-folder.h @@ -0,0 +1,76 @@ +/* -*- Mode: C; indent-tabs-mode: t; c-basic-offset: 8; tab-width: 8 -*- */ +/* + * GData Client + * Copyright (C) Thibault Saunier 2009 + * + * GData Client is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * GData Client is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with GData Client. If not, see . + */ + +#ifndef GDATA_DOCUMENTS_FOLDER_H +#define GDATA_DOCUMENTS_FOLDER_H + +#include +#include + +#include +#include + +G_BEGIN_DECLS + +#define GDATA_TYPE_DOCUMENTS_FOLDER (gdata_documents_folder_get_type ()) +#define GDATA_DOCUMENTS_FOLDER(o) (G_TYPE_CHECK_INSTANCE_CAST ((o), GDATA_TYPE_DOCUMENTS_FOLDER, GDataDocumentsFolder)) +#define GDATA_DOCUMENTS_FOLDER_CLASS(k) (G_TYPE_CHECK_CLASS_CAST((k), GDATA_TYPE_DOCUMENTS_FOLDER, GDataDocumentsFolderClass)) +#define GDATA_IS_DOCUMENTS_FOLDER(o) (G_TYPE_CHECK_INSTANCE_TYPE ((o), GDATA_TYPE_DOCUMENTS_FOLDER)) +#define GDATA_IS_DOCUMENTS_FOLDER_CLASS(k) (G_TYPE_CHECK_CLASS_TYPE ((k), GDATA_TYPE_DOCUMENTS_FOLDER)) +#define GDATA_DOCUMENTS_FOLDER_GET_CLASS(o) (G_TYPE_INSTANCE_GET_CLASS ((o), GDATA_TYPE_DOCUMENTS_FOLDER, GDataDocumentsFolderClass)) + +typedef struct _GDataDocumentsFolderPrivate GDataDocumentsFolderPrivate; + +/** + * GDataDocumentsFolder: + * + * All the fields in the #GDataDocumentsFolder structure are private and should never be accessed directly. + * + * Since: 0.4.0 + */ +typedef struct { + GDataDocumentsEntry parent; + GDataDocumentsFolderPrivate *priv; +} GDataDocumentsFolder; + +/** + * GDataDocumentsFolderClass: + * + * All the fields in the #GDataDocumentsFolderClass structure are private and should never be accessed directly. + * + * Since: 0.4.0 + */ +typedef struct { + /*< private >*/ + GDataDocumentsEntryClass parent; + + /*< private >*/ + /* Padding for future expansion */ + void (*_g_reserved0) (void); + void (*_g_reserved1) (void); +} GDataDocumentsFolderClass; + +GType gdata_documents_folder_get_type (void) G_GNUC_CONST; +G_DEFINE_AUTOPTR_CLEANUP_FUNC (GDataDocumentsFolder, g_object_unref) + +GDataDocumentsFolder *gdata_documents_folder_new (const gchar *id) G_GNUC_WARN_UNUSED_RESULT G_GNUC_MALLOC; + +G_END_DECLS + +#endif /* !GDATA_DOCUMENTS_FOLDER_H */ diff --git a/gdata/services/documents/gdata-documents-metadata.c b/gdata/services/documents/gdata-documents-metadata.c new file mode 100644 index 0000000..f587af5 --- /dev/null +++ b/gdata/services/documents/gdata-documents-metadata.c @@ -0,0 +1,230 @@ +/* -*- Mode: C; indent-tabs-mode: t; c-basic-offset: 8; tab-width: 8 -*- */ +/* + * GData Client + * Copyright (C) Michael Terry 2017 + * + * GData Client is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * GData Client is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with GData Client. If not, see . + */ + +/** + * SECTION:gdata-documents-metadata + * @short_description: GData document service metadata class + * @stability: Stable + * @include: gdata/services/documents/gdata-documents-metadata.h + * + * #GDataDocumentsMetadata is a subclass of #GDataParsable to represent Google Drive service metadata. + * + * For more details of Google Documents' GData API, see the + * online documentation. + * + * Since: 0.17.9 + */ + +#include +#include +#include +#include + +#include "gdata-documents-metadata.h" +#include "gdata-parser.h" +#include "gdata-types.h" + +static const gchar *get_content_type (void); +static void gdata_documents_metadata_get_property (GObject *object, guint property_id, GValue *value, GParamSpec *pspec); +static void gdata_documents_metadata_set_property (GObject *object, guint property_id, const GValue *value, GParamSpec *pspec); +static gboolean parse_json (GDataParsable *parsable, JsonReader *reader, gpointer user_data, GError **error); + +struct _GDataDocumentsMetadataPrivate { + goffset quota_total; /* bytes */ + goffset quota_used; /* bytes */ + gboolean quota_unlimited; +}; + +enum { + PROP_QUOTA_TOTAL = 1, + PROP_QUOTA_USED, +}; + +G_DEFINE_TYPE (GDataDocumentsMetadata, gdata_documents_metadata, GDATA_TYPE_PARSABLE) + +static void +gdata_documents_metadata_class_init (GDataDocumentsMetadataClass *klass) +{ + GObjectClass *gobject_class = G_OBJECT_CLASS (klass); + GDataParsableClass *parsable_class = GDATA_PARSABLE_CLASS (klass); + + g_type_class_add_private (klass, sizeof (GDataDocumentsMetadataPrivate)); + + gobject_class->get_property = gdata_documents_metadata_get_property; + gobject_class->set_property = gdata_documents_metadata_set_property; + + parsable_class->parse_json = parse_json; + parsable_class->get_content_type = get_content_type; + + /** + * GDataDocumentsMetadata:quota-total: + * + * The user quota limit across all services. Measured in bytes. + * + * Since: 0.17.9 + */ + g_object_class_install_property (gobject_class, PROP_QUOTA_TOTAL, + g_param_spec_int64 ("quota-total", + "Quota total", "The user quota limit across all services.", + -1, G_MAXINT64, 0, + G_PARAM_READABLE | G_PARAM_STATIC_STRINGS)); + + /** + * GDataDocumentsMetadata:quota-used: + * + * The amount of user quota used up across all services. Measured in bytes. + * + * Since: 0.17.9 + */ + g_object_class_install_property (gobject_class, PROP_QUOTA_USED, + g_param_spec_int64 ("quota-used", + "Quota used", "The amount of user quota used up across all services.", + 0, G_MAXINT64, 0, + G_PARAM_READABLE | G_PARAM_STATIC_STRINGS)); +} + +static void +gdata_documents_metadata_init (GDataDocumentsMetadata *self) +{ + self->priv = G_TYPE_INSTANCE_GET_PRIVATE (self, GDATA_TYPE_DOCUMENTS_METADATA, GDataDocumentsMetadataPrivate); +} + +static void +gdata_documents_metadata_get_property (GObject *object, guint property_id, GValue *value, GParamSpec *pspec) +{ + GDataDocumentsMetadata *self = GDATA_DOCUMENTS_METADATA (object); + + switch (property_id) { + case PROP_QUOTA_TOTAL: + g_value_set_int64 (value, gdata_documents_metadata_get_quota_total (self)); + break; + case PROP_QUOTA_USED: + g_value_set_int64 (value, gdata_documents_metadata_get_quota_used (self)); + break; + default: + /* We don't have any other property... */ + G_OBJECT_WARN_INVALID_PROPERTY_ID (object, property_id, pspec); + break; + } +} + +static void +gdata_documents_metadata_set_property (GObject *object, guint property_id, const GValue *value, GParamSpec *pspec) +{ + switch (property_id) { + case PROP_QUOTA_TOTAL: + case PROP_QUOTA_USED: + /* Read only. */ + default: + /* We don't have any other property... */ + G_OBJECT_WARN_INVALID_PROPERTY_ID (object, property_id, pspec); + break; + } +} + +static gboolean +parse_json (GDataParsable *parsable, JsonReader *reader, gpointer user_data, GError **error) +{ + GDataDocumentsMetadataPrivate *priv = GDATA_DOCUMENTS_METADATA (parsable)->priv; + gboolean success = TRUE; + gchar *quota_total = NULL; + gchar *quota_used = NULL; + gchar *quota_type = NULL; + + /* JSON format: https://developers.google.com/drive/v2/reference/about */ + + if (gdata_parser_string_from_json_member (reader, "quotaBytesTotal", P_DEFAULT, "a_total, &success, error) == TRUE) { + gchar *end_ptr; + guint64 val; + + /* Even though ‘quotaBytesTotal’ is documented as long, + * it is actually a string in the JSON. + */ + val = g_ascii_strtoull (quota_total, &end_ptr, 10); + if (*end_ptr == '\0') + priv->quota_total = (goffset) val; + g_free (quota_total); + return success; + } else if (gdata_parser_string_from_json_member (reader, "quotaBytesUsedAggregate", P_DEFAULT, "a_used, &success, error) == TRUE) { + gchar *end_ptr; + guint64 val; + + /* Even though ‘quotaBytesUsedAggregate’ is documented as long, + * it is actually a string in the JSON. + */ + val = g_ascii_strtoull (quota_used, &end_ptr, 10); + if (*end_ptr == '\0') + priv->quota_used = (goffset) val; + g_free (quota_used); + return success; + } else if (gdata_parser_string_from_json_member (reader, "quotaType", P_DEFAULT, "a_type, &success, error) == TRUE) { + if (g_strcmp0 (quota_type, "UNLIMITED") == 0) + priv->quota_unlimited = TRUE; + g_free (quota_type); + return success; + } + + return GDATA_PARSABLE_CLASS (gdata_documents_metadata_parent_class)->parse_json (parsable, reader, user_data, error); +} + +static const gchar * +get_content_type (void) +{ + return "application/json"; +} + +/** + * gdata_documents_metadata_get_quota_total: + * @self: a #GDataDocumentsMetadata + * + * Gets the #GDataDocumentsMetadata:quota-total property. + * + * Return value: the number of quota bytes available in total. Returns -1 if + * there is no quota limit. + * + * Since: 0.17.9 + */ +goffset +gdata_documents_metadata_get_quota_total (GDataDocumentsMetadata *self) +{ + g_return_val_if_fail (GDATA_IS_DOCUMENTS_METADATA (self), 0); + + if (self->priv->quota_unlimited) + return -1; + else + return self->priv->quota_total; +} + +/** + * gdata_documents_metadata_get_quota_used: + * @self: a #GDataDocumentsMetadata + * + * Gets the #GDataDocumentsMetadata:quota-used property. + * + * Return value: the number of quota bytes used by the documents service + * + * Since: 0.17.9 + */ +goffset +gdata_documents_metadata_get_quota_used (GDataDocumentsMetadata *self) +{ + g_return_val_if_fail (GDATA_IS_DOCUMENTS_METADATA (self), 0); + + return self->priv->quota_used; +} diff --git a/gdata/services/documents/gdata-documents-metadata.h b/gdata/services/documents/gdata-documents-metadata.h new file mode 100644 index 0000000..c9c8d4a --- /dev/null +++ b/gdata/services/documents/gdata-documents-metadata.h @@ -0,0 +1,77 @@ +/* -*- Mode: C; indent-tabs-mode: t; c-basic-offset: 8; tab-width: 8 -*- */ +/* + * GData Client + * Copyright (C) Michael Terry 2017 + * + * GData Client is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * GData Client is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with GData Client. If not, see . + */ + +#ifndef GDATA_DOCUMENTS_METADATA_H +#define GDATA_DOCUMENTS_METADATA_H + +#include +#include + +#include + +G_BEGIN_DECLS + + +#define GDATA_TYPE_DOCUMENTS_METADATA (gdata_documents_metadata_get_type ()) +#define GDATA_DOCUMENTS_METADATA(o) (G_TYPE_CHECK_INSTANCE_CAST ((o), GDATA_TYPE_DOCUMENTS_METADATA, GDataDocumentsMetadata)) +#define GDATA_DOCUMENTS_METADATA_CLASS(k) (G_TYPE_CHECK_CLASS_CAST((k), GDATA_TYPE_DOCUMENTS_METADATA, GDataDocumentsMetadataClass)) +#define GDATA_IS_DOCUMENTS_METADATA(o) (G_TYPE_CHECK_INSTANCE_TYPE ((o), GDATA_TYPE_DOCUMENTS_METADATA)) +#define GDATA_IS_DOCUMENTS_METADATA_CLASS(k) (G_TYPE_CHECK_CLASS_TYPE ((k), GDATA_TYPE_DOCUMENTS_METADATA)) +#define GDATA_DOCUMENTS_METADATA_GET_CLASS(o) (G_TYPE_INSTANCE_GET_CLASS ((o), GDATA_TYPE_DOCUMENTS_METADATA, GDataDocumentsMetadataClass)) + +typedef struct _GDataDocumentsMetadataPrivate GDataDocumentsMetadataPrivate; + +/** + * GDataDocumentsMetadata: + * + * All the fields in the #GDataDocumentsMetadata structure are private and should never be accessed directly. + * + * Since: 0.17.9 + */ +typedef struct { + GDataParsable parent; + GDataDocumentsMetadataPrivate *priv; +} GDataDocumentsMetadata; + +/** + * GDataDocumentsMetadataClass: + * + * All the fields in the #GDataDocumentsMetadataClass structure are private and should never be accessed directly. + * + * Since: 0.17.9 + */ +typedef struct { + /*< private >*/ + GDataParsableClass parent; + + /*< private >*/ + /* Padding for future expansion */ + void (*_g_reserved0) (void); + void (*_g_reserved1) (void); +} GDataDocumentsMetadataClass; + +GType gdata_documents_metadata_get_type (void) G_GNUC_CONST; +G_DEFINE_AUTOPTR_CLEANUP_FUNC (GDataDocumentsMetadata, g_object_unref) + +goffset gdata_documents_metadata_get_quota_total (GDataDocumentsMetadata *self) G_GNUC_PURE; +goffset gdata_documents_metadata_get_quota_used (GDataDocumentsMetadata *self) G_GNUC_PURE; + +G_END_DECLS + +#endif /* !GDATA_DOCUMENTS_METADATA_H */ diff --git a/gdata/services/documents/gdata-documents-pdf.c b/gdata/services/documents/gdata-documents-pdf.c new file mode 100644 index 0000000..d4d2528 --- /dev/null +++ b/gdata/services/documents/gdata-documents-pdf.c @@ -0,0 +1,88 @@ +/* -*- Mode: C; indent-tabs-mode: t; c-basic-offset: 8; tab-width: 8 -*- */ +/* + * GData Client + * Copyright (C) Thibault Saunier 2009 + * Copyright (C) Philip Withnall 2010 + * Copyright (C) Cosimo Cecchi 2012 + * Copyright (C) Red Hat, Inc. 2016 + * + * GData Client is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * GData Client is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with GData Client. If not, see . + */ + +/** + * SECTION:gdata-documents-pdf + * @short_description: GData Documents pdf object + * @stability: Stable + * @include: gdata/services/documents/gdata-documents-pdf.h + * + * #GDataDocumentsPdf is a subclass of #GDataDocumentsDocument to represent a PDF document from Google Documents. + * + * For more details of Google Drive's GData API, see the + * online documentation. + * + * Since: 0.13.3 + */ + +#include +#include + +#include "gdata-documents-pdf.h" +#include "gdata-documents-utils.h" +#include "gdata-parser.h" +#include "gdata-private.h" + +static void gdata_documents_pdf_constructed (GObject *object); + +G_DEFINE_TYPE (GDataDocumentsPdf, gdata_documents_pdf, GDATA_TYPE_DOCUMENTS_DOCUMENT) + +static void +gdata_documents_pdf_class_init (GDataDocumentsPdfClass *klass) +{ + GObjectClass *gobject_class = G_OBJECT_CLASS (klass); + GDataEntryClass *entry_class = GDATA_ENTRY_CLASS (klass); + + gobject_class->constructed = gdata_documents_pdf_constructed; + entry_class->kind_term = "http://schemas.google.com/docs/2007#pdf"; +} + +static void +gdata_documents_pdf_init (GDataDocumentsPdf *self) +{ + /* Why am I writing it? */ +} + +static void +gdata_documents_pdf_constructed (GObject *object) +{ + G_OBJECT_CLASS (gdata_documents_pdf_parent_class)->constructed (object); + + if (!_gdata_parsable_is_constructed_from_xml (GDATA_PARSABLE (object))) + gdata_documents_utils_add_content_type (GDATA_DOCUMENTS_ENTRY (object), "application/pdf"); +} + +/** + * gdata_documents_pdf_new: + * @id: (allow-none): the entry's ID (not the document ID of the pdf document), or %NULL + * + * Creates a new #GDataDocumentsPdf with the given entry ID (#GDataEntry:id). + * + * Return value: (transfer full): a new #GDataDocumentsPdf, or %NULL; unref with g_object_unref() + * + * Since: 0.13.3 + */ +GDataDocumentsPdf * +gdata_documents_pdf_new (const gchar *id) +{ + return GDATA_DOCUMENTS_PDF (g_object_new (GDATA_TYPE_DOCUMENTS_PDF, "id", id, NULL)); +} diff --git a/gdata/services/documents/gdata-documents-pdf.h b/gdata/services/documents/gdata-documents-pdf.h new file mode 100644 index 0000000..701a137 --- /dev/null +++ b/gdata/services/documents/gdata-documents-pdf.h @@ -0,0 +1,77 @@ +/* -*- Mode: C; indent-tabs-mode: t; c-basic-offset: 8; tab-width: 8 -*- */ +/* + * GData Client + * Copyright (C) Thibault Saunier 2009 + * Copyright (C) Philip Withnall 2010 + * Copyright (C) Cosimo Cecchi 2012 + * + * GData Client is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * GData Client is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with GData Client. If not, see . + */ + +#ifndef GDATA_DOCUMENTS_PDF_H +#define GDATA_DOCUMENTS_PDF_H + +#include +#include + +#include + +G_BEGIN_DECLS + +#define GDATA_TYPE_DOCUMENTS_PDF (gdata_documents_pdf_get_type ()) +#define GDATA_DOCUMENTS_PDF(o) (G_TYPE_CHECK_INSTANCE_CAST ((o), GDATA_TYPE_DOCUMENTS_PDF, GDataDocumentsPdf)) +#define GDATA_DOCUMENTS_PDF_CLASS(k) (G_TYPE_CHECK_CLASS_CAST((k), GDATA_TYPE_DOCUMENTS_PDF, GDataDocumentsPdfClass)) +#define GDATA_IS_DOCUMENTS_PDF(o) (G_TYPE_CHECK_INSTANCE_TYPE ((o), GDATA_TYPE_DOCUMENTS_PDF)) +#define GDATA_IS_DOCUMENTS_PDF_CLASS(k) (G_TYPE_CHECK_CLASS_TYPE ((k), GDATA_TYPE_DOCUMENTS_PDF)) +#define GDATA_DOCUMENTS_PDF_GET_CLASS(o) (G_TYPE_INSTANCE_GET_CLASS ((o), GDATA_TYPE_DOCUMENTS_PDF, GDataDocumentsPdfClass)) + +typedef struct _GDataDocumentsPdfPrivate GDataDocumentsPdfPrivate; + +/** + * GDataDocumentsPdf: + * + * All the fields in the #GDataDocumentsPdf structure are private and should never be accessed directly. + * + * Since: 0.13.3 + */ +typedef struct { + GDataDocumentsDocument parent; + GDataDocumentsPdfPrivate *priv; +} GDataDocumentsPdf; + +/** + * GDataDocumentsPdfClass: + * + * All the fields in the #GDataDocumentsPdfClass structure are private and should never be accessed directly. + * + * Since: 0.13.3 + */ +typedef struct { + /*< private >*/ + GDataDocumentsDocumentClass parent; + + /*< private >*/ + /* Padding for future expansion */ + void (*_g_reserved0) (void); + void (*_g_reserved1) (void); +} GDataDocumentsPdfClass; + +GType gdata_documents_pdf_get_type (void) G_GNUC_CONST; +G_DEFINE_AUTOPTR_CLEANUP_FUNC (GDataDocumentsPdf, g_object_unref) + +GDataDocumentsPdf *gdata_documents_pdf_new (const gchar *id) G_GNUC_WARN_UNUSED_RESULT G_GNUC_MALLOC; + +G_END_DECLS + +#endif /* !GDATA_DOCUMENTS_PDF_H */ diff --git a/gdata/services/documents/gdata-documents-presentation.c b/gdata/services/documents/gdata-documents-presentation.c new file mode 100644 index 0000000..9031a61 --- /dev/null +++ b/gdata/services/documents/gdata-documents-presentation.c @@ -0,0 +1,87 @@ +/* -*- Mode: C; indent-tabs-mode: t; c-basic-offset: 8; tab-width: 8 -*- */ +/* + * GData Client + * Copyright (C) Thibault Saunier 2009 + * Copyright (C) Philip Withnall 2010 + * Copyright (C) Red Hat, Inc. 2016 + * + * GData Client is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * GData Client is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with GData Client. If not, see . + */ + +/** + * SECTION:gdata-documents-presentation + * @short_description: GData documents presentation object + * @stability: Stable + * @include: gdata/services/documents/gdata-documents-presentation.h + * + * #GDataDocumentsPresentation is a subclass of #GDataDocumentsDocument to represent a Google Documents presentation. + * + * For more details of Google Drive's GData API, see the + * online documentation. + * + * Since: 0.4.0 + */ + +#include +#include + +#include "gdata-documents-presentation.h" +#include "gdata-documents-utils.h" +#include "gdata-parser.h" +#include "gdata-private.h" + +static void gdata_documents_presentation_constructed (GObject *object); + +G_DEFINE_TYPE (GDataDocumentsPresentation, gdata_documents_presentation, GDATA_TYPE_DOCUMENTS_DOCUMENT) + +static void +gdata_documents_presentation_class_init (GDataDocumentsPresentationClass *klass) +{ + GObjectClass *gobject_class = G_OBJECT_CLASS (klass); + GDataEntryClass *entry_class = GDATA_ENTRY_CLASS (klass); + + gobject_class->constructed = gdata_documents_presentation_constructed; + entry_class->kind_term = "http://schemas.google.com/docs/2007#presentation"; +} + +static void +gdata_documents_presentation_init (GDataDocumentsPresentation *self) +{ + /* Why am I writing it? */ +} + +static void +gdata_documents_presentation_constructed (GObject *object) +{ + G_OBJECT_CLASS (gdata_documents_presentation_parent_class)->constructed (object); + + if (!_gdata_parsable_is_constructed_from_xml (GDATA_PARSABLE (object))) + gdata_documents_utils_add_content_type (GDATA_DOCUMENTS_ENTRY (object), "application/vnd.google-apps.presentation"); +} + +/** + * gdata_documents_presentation_new: + * @id: (allow-none): the entry's ID (not the document ID of the presentation), or %NULL + * + * Creates a new #GDataDocumentsPresentation with the given entry ID (#GDataEntry:id). + * + * Return value: (transfer full): a new #GDataDocumentsPresentation, or %NULL; unref with g_object_unref() + * + * Since: 0.4.0 + */ +GDataDocumentsPresentation * +gdata_documents_presentation_new (const gchar *id) +{ + return GDATA_DOCUMENTS_PRESENTATION (g_object_new (GDATA_TYPE_DOCUMENTS_PRESENTATION, "id", id, NULL)); +} diff --git a/gdata/services/documents/gdata-documents-presentation.h b/gdata/services/documents/gdata-documents-presentation.h new file mode 100644 index 0000000..5ab4b65 --- /dev/null +++ b/gdata/services/documents/gdata-documents-presentation.h @@ -0,0 +1,147 @@ +/* -*- Mode: C; indent-tabs-mode: t; c-basic-offset: 8; tab-width: 8 -*- */ +/* + * GData Client + * Copyright (C) Thibault Saunier 2009 + * + * GData Client is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * GData Client is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with GData Client. If not, see . + */ + +#ifndef GDATA_DOCUMENTS_PRESENTATION_H +#define GDATA_DOCUMENTS_PRESENTATION_H + +#include +#include + +#include + +G_BEGIN_DECLS + +/** + * GDATA_DOCUMENTS_PRESENTATION_PDF: + * + * The export format for Portable Document Format (PDF). + * + * For more information, see the + * + * GData protocol specification. + * + * Since: 0.7.0 + */ +#define GDATA_DOCUMENTS_PRESENTATION_PDF "pdf" + +/** + * GDATA_DOCUMENTS_PRESENTATION_PNG: + * + * The export format for Portable Network Graphics (PNG) image format. + * + * For more information, see the + * + * GData protocol specification. + * + * Since: 0.7.0 + */ +#define GDATA_DOCUMENTS_PRESENTATION_PNG "png" + +/** + * GDATA_DOCUMENTS_PRESENTATION_PPT: + * + * The export format for Microsoft PowerPoint (PPT) format. + * + * For more information, see the + * + * GData protocol specification. + * + * Since: 0.7.0 + */ +#define GDATA_DOCUMENTS_PRESENTATION_PPT "ppt" + +/** + * GDATA_DOCUMENTS_PRESENTATION_SWF: + * + * The export format for Adobe Flash (SWF) format. + * + * For more information, see the + * + * GData protocol specification. + * + * Since: 0.7.0 + * Deprecated: SWF export has been deprecated in the protocol due to low demand for it; PDF export (using %GDATA_DOCUMENTS_PRESENTATION_PDF) is + * recommended instead. (Since: 0.11.0.) + */ +#ifndef LIBGDATA_DISABLE_DEPRECATED +#define GDATA_DOCUMENTS_PRESENTATION_SWF "swf" +#endif /* !LIBGDATA_DISABLE_DEPRECATED */ + +/** + * GDATA_DOCUMENTS_PRESENTATION_TXT: + * + * The export format for plain text format. + * + * For more information, see the + * + * GData protocol specification. + * + * Since: 0.7.0 + */ +#define GDATA_DOCUMENTS_PRESENTATION_TXT "txt" + +#define GDATA_TYPE_DOCUMENTS_PRESENTATION (gdata_documents_presentation_get_type ()) +#define GDATA_DOCUMENTS_PRESENTATION(o) (G_TYPE_CHECK_INSTANCE_CAST ((o), GDATA_TYPE_DOCUMENTS_PRESENTATION, \ + GDataDocumentsPresentation)) +#define GDATA_DOCUMENTS_PRESENTATION_CLASS(k) (G_TYPE_CHECK_CLASS_CAST((k), GDATA_TYPE_DOCUMENTS_PRESENTATION, \ + GDataDocumentsPresentationClass)) +#define GDATA_IS_DOCUMENTS_PRESENTATION(o) (G_TYPE_CHECK_INSTANCE_TYPE ((o), GDATA_TYPE_DOCUMENTS_PRESENTATION)) +#define GDATA_IS_DOCUMENTS_PRESENTATION_CLASS(k) (G_TYPE_CHECK_CLASS_TYPE ((k), GDATA_TYPE_DOCUMENTS_PRESENTATION)) +#define GDATA_DOCUMENTS_PRESENTATION_GET_CLASS(o) (G_TYPE_INSTANCE_GET_CLASS ((o), GDATA_TYPE_DOCUMENTS_PRESENTATION, \ + GDataDocumentsPresentationClass)) + +typedef struct _GDataDocumentsPresentationPrivate GDataDocumentsPresentationPrivate; + +/** + * GDataDocumentsPresentation: + * + * All the fields in the #GDataDocumentsPresentation structure are private and should never be accessed directly. + * + * Since: 0.4.0 + */ +typedef struct { + GDataDocumentsDocument parent; + GDataDocumentsPresentationPrivate *priv; +} GDataDocumentsPresentation; + +/** + * GDataDocumentsPresentationClass: + * + * All the fields in the #GDataDocumentsPresentationClass structure are private and should never be accessed directly. + * + * Since: 0.4.0 + */ +typedef struct { + /*< private >*/ + GDataDocumentsDocumentClass parent; + + /*< private >*/ + /* Padding for future expansion */ + void (*_g_reserved0) (void); + void (*_g_reserved1) (void); +} GDataDocumentsPresentationClass; + +GType gdata_documents_presentation_get_type (void) G_GNUC_CONST; +G_DEFINE_AUTOPTR_CLEANUP_FUNC (GDataDocumentsPresentation, g_object_unref) + +GDataDocumentsPresentation *gdata_documents_presentation_new (const gchar *id) G_GNUC_WARN_UNUSED_RESULT G_GNUC_MALLOC; + +G_END_DECLS + +#endif /* !GDATA_DOCUMENTS_PRESENTATION_H */ diff --git a/gdata/services/documents/gdata-documents-property.c b/gdata/services/documents/gdata-documents-property.c new file mode 100644 index 0000000..c1d497d --- /dev/null +++ b/gdata/services/documents/gdata-documents-property.c @@ -0,0 +1,472 @@ +/* -*- Mode: C; indent-tabs-mode: t; c-basic-offset: 8; tab-width: 8 -*- */ +/* + * GData Client + * Copyright (C) Mayank Sharma + * + * GData Client is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * GData Client is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with GData Client. If not, see . + */ + +/** + * SECTION:gdata-documents-property + * @short_description: GData Documents property object + * @stability: Unstable + * @include: gdata/gdata-property.h + * + * #GDataDocumentsProperty is a subclass of #GDataParsable and represents a Google Drive Property Resource on a file object. + * + * It allows applications to store additional metadata on a file, such as tags, IDs from other data stores, viewing preferences etc. Properties can be used to share metadata between applications, for example, in a workflow application. + * + * Each #GDataDocumentsProperty is characterized by a key-value pair (where value is optional, and takes empty string "" by default) and a visibility parameter. The visibility can take values "PUBLIC" for public properties and "PRIVATE" for private properties (default). Private properties are accessible only by the application which set them, but public properties can be read/written by other applications as well. + * + * Since: 0.17.11 + */ + +#include +#include +#include + +#include "gdata-documents-property.h" +#include "gdata-parser.h" +#include "gdata-comparable.h" + +static void gdata_documents_property_comparable_init (GDataComparableIface *iface); +static void gdata_documents_property_finalize (GObject *object); +static void gdata_documents_property_get_property (GObject *object, guint property_id, GValue *value, GParamSpec *pspec); +static void gdata_documents_property_set_property (GObject *object, guint property_id, const GValue *value, GParamSpec *pspec); + +static void _gdata_documents_property_set_key (GDataDocumentsProperty *self, const gchar *key); +static void _gdata_documents_property_set_etag (GDataDocumentsProperty *self, const gchar *etag); + +static gboolean parse_json (GDataParsable *parsable, JsonReader *reader, gpointer user_data, GError **error); +static void get_json (GDataParsable *parsable, JsonBuilder *builder); + +struct _GDataDocumentsPropertyPrivate { + gchar *key; + gchar *etag; + gchar *value; /* default - empty string ("") */ + gchar *visibility; /* default - "PRIVATE" */ +}; + +enum { + PROP_KEY = 1, + PROP_ETAG, + PROP_VALUE, + PROP_VISIBILITY +}; + +G_DEFINE_TYPE_WITH_CODE (GDataDocumentsProperty, gdata_documents_property, GDATA_TYPE_PARSABLE, + G_IMPLEMENT_INTERFACE (GDATA_TYPE_COMPARABLE, gdata_documents_property_comparable_init)) + +static void +gdata_documents_property_class_init (GDataDocumentsPropertyClass *klass) +{ + GObjectClass *gobject_class = G_OBJECT_CLASS (klass); + GDataParsableClass *parsable_class = GDATA_PARSABLE_CLASS (klass); + + g_type_class_add_private (klass, sizeof (GDataDocumentsPropertyPrivate)); + + gobject_class->set_property = gdata_documents_property_set_property; + gobject_class->get_property = gdata_documents_property_get_property; + gobject_class->finalize = gdata_documents_property_finalize; + + parsable_class->parse_json = parse_json; + parsable_class->get_json = get_json; + parsable_class->element_name = "property"; + + /** + * GDataDocumentsProperty:key: + * + * The key of this property. + * + * For more information, see the Properties Resource + * + * Since: 0.17.11 + */ + g_object_class_install_property (gobject_class, PROP_KEY, + g_param_spec_string ("key", + "Key", "The key of this property.", + NULL, + G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)); + + /** + * GDataDocumentsProperty:etag: + * + * ETag of the property. + * + * For more information, see the Properties Resource + * + * Since: 0.17.11 + */ + g_object_class_install_property (gobject_class, PROP_ETAG, + g_param_spec_string ("etag", + "ETag", "ETag of the property.", + NULL, + G_PARAM_READWRITE | G_PARAM_CONSTRUCT_ONLY | G_PARAM_STATIC_STRINGS)); + + /** + * GDataDocumentsProperty:value: + * + * The value of this property. By default, it takes the an empty string (""). + * + * For more information, see the Properties Resource + * + * Since: 0.17.11 + */ + g_object_class_install_property (gobject_class, PROP_VALUE, + g_param_spec_string ("value", + "Value", "The value of this property.", + NULL, + G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)); + + /** + * GDataDocumentsProperty:visibility: + * + * The visibility status of this property. The default value of + * visibility is PRIVATE on a Drive Properties Resource object, + * hence #GDataDocumentsProperty:visibility is %GDATA_DOCUMENTS_PROPERTY_VISIBILITY_PRIVATE + * by default. A private property restricts its visibility to only the app which created it. + * + * For more information, see the Properties Resource + * + * Since: 0.17.11 + */ + g_object_class_install_property (gobject_class, PROP_VISIBILITY, + g_param_spec_string ("visibility", + "Visibility", "The visibility of this property.", + NULL, + G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)); +} + +static gint +compare_with (GDataComparable *self, GDataComparable *other) +{ + + GDataDocumentsPropertyPrivate *a = ((GDataDocumentsProperty*) self)->priv, *b = ((GDataDocumentsProperty*) other)->priv; + + if (g_strcmp0 (a->key, b->key) == 0 && g_strcmp0 (a->visibility, b->visibility) == 0) + return 0; + return 1; +} + +static gboolean +parse_json (GDataParsable *parsable, JsonReader *reader, gpointer user_data, GError **error) +{ + gchar *output_val = NULL; + gboolean success = TRUE, is_key_parsed = FALSE; + + if (gdata_parser_string_from_json_member (reader, "key", P_DEFAULT, &output_val, &success, error) == TRUE) { + if (success && output_val != NULL && output_val[0] != '\0') { + _gdata_documents_property_set_key (GDATA_DOCUMENTS_PROPERTY (parsable), output_val); + } + + is_key_parsed = TRUE; + } else if (gdata_parser_string_from_json_member (reader, "etag", P_DEFAULT, &output_val, &success, error) == TRUE) { + if (success && output_val != NULL && output_val[0] != '\0') { + _gdata_documents_property_set_etag (GDATA_DOCUMENTS_PROPERTY (parsable), output_val); + } + + is_key_parsed = TRUE; + } else if (gdata_parser_string_from_json_member (reader, "value", P_DEFAULT, &output_val, &success, error) == TRUE) { + + /* A Property can have a value field to be an empty string, but + * never NULL */ + if (success && output_val != NULL) { + gdata_documents_property_set_value (GDATA_DOCUMENTS_PROPERTY (parsable), output_val); + } + + is_key_parsed = TRUE; + } else if (gdata_parser_string_from_json_member (reader, "visibility", P_REQUIRED | P_NON_EMPTY, &output_val, &success, error) == TRUE) { + gdata_documents_property_set_visibility (GDATA_DOCUMENTS_PROPERTY (parsable), output_val); + + is_key_parsed = TRUE; + } + + if (is_key_parsed) { + g_free (output_val); + return success; + } + + /* Chain up to the parent class */ + return GDATA_PARSABLE_CLASS (gdata_documents_property_parent_class)->parse_json (parsable, reader, user_data, error); +} + +static void +get_json (GDataParsable *parsable, JsonBuilder *builder) +{ + + GDataDocumentsPropertyPrivate *priv = GDATA_DOCUMENTS_PROPERTY (parsable)->priv; + + /* Add all the Property specific JSON members */ + g_assert (priv->key != NULL); + json_builder_set_member_name (builder, "key"); + json_builder_add_string_value (builder, priv->key); + + if (gdata_documents_property_get_etag (GDATA_DOCUMENTS_PROPERTY (parsable)) != NULL) { + json_builder_set_member_name (builder, "etag"); + json_builder_add_string_value (builder, priv->etag); + } + + /* Setting the "value" field of a Property Resource deletes that Property Resource */ + json_builder_set_member_name (builder, "value"); + json_builder_add_string_value (builder, priv->value); + + json_builder_set_member_name (builder, "visibility"); + json_builder_add_string_value (builder, priv->visibility); +} + +static void +gdata_documents_property_comparable_init (GDataComparableIface *iface) +{ + iface->compare_with = compare_with; +} + +static void +gdata_documents_property_init (GDataDocumentsProperty *self) +{ + self->priv = G_TYPE_INSTANCE_GET_PRIVATE (self, GDATA_TYPE_DOCUMENTS_PROPERTY, GDataDocumentsPropertyPrivate); + + /* Google Drive sets the default value of a Property Resource to be an empty string (""), + * and visibility is %GDATA_DOCUMENTS_PROPERTY_VISIBILITY_PRIVATE by default */ + self->priv->value = g_strdup (""); + self->priv->visibility = g_strdup (GDATA_DOCUMENTS_PROPERTY_VISIBILITY_PRIVATE); +} + +static void +gdata_documents_property_finalize (GObject *object) +{ + GDataDocumentsPropertyPrivate *priv = GDATA_DOCUMENTS_PROPERTY (object)->priv; + + g_free (priv->key); + g_free (priv->etag); + g_free (priv->value); + g_free (priv->visibility); + + /* Chain up to the parent class */ + G_OBJECT_CLASS (gdata_documents_property_parent_class)->finalize (object); +} + +static void +gdata_documents_property_get_property (GObject *object, guint property_id, GValue *value, GParamSpec *pspec) +{ + GDataDocumentsPropertyPrivate *priv = GDATA_DOCUMENTS_PROPERTY (object)->priv; + + switch (property_id) { + case PROP_KEY: + g_value_set_string (value, priv->key); + break; + case PROP_ETAG: + g_value_set_string (value, priv->etag); + break; + case PROP_VALUE: + g_value_set_string (value, priv->value); + break; + case PROP_VISIBILITY: + g_value_set_string (value, priv->visibility); + break; + default: + /* We don't have any other property... */ + G_OBJECT_WARN_INVALID_PROPERTY_ID (object, property_id, pspec); + break; + } +} + +static void +gdata_documents_property_set_property (GObject *object, guint property_id, const GValue *value, GParamSpec *pspec) +{ + GDataDocumentsProperty *self = GDATA_DOCUMENTS_PROPERTY (object); + + switch (property_id) { + case PROP_KEY: + _gdata_documents_property_set_key (self, g_value_get_string (value)); + break; + case PROP_ETAG: + _gdata_documents_property_set_etag (self, g_value_get_string (value)); + break; + case PROP_VALUE: + gdata_documents_property_set_value (self, g_value_get_string (value)); + break; + case PROP_VISIBILITY: + gdata_documents_property_set_visibility (self, g_value_get_string (value)); + break; + default: + /* We don't have any other property... */ + G_OBJECT_WARN_INVALID_PROPERTY_ID (object, property_id, pspec); + break; + } +} + +/** + * gdata_documents_property_new: + * @key: the property's key + * + * Creates a new #GDataEntry with the given ID and default properties. + * + * Return value: (transfer full): a new #GDataDocumentsProperty; unref with g_object_unref() + * + * Since: 0.17.11 + */ +GDataDocumentsProperty * +gdata_documents_property_new (const gchar *key) +{ + /* GDataDocumentsProperty must have a non NULL key at initialization time, + * rest of the properties can be NULL or take their default values. */ + g_return_val_if_fail (key != NULL && key[0] != '\0', NULL); + + return GDATA_DOCUMENTS_PROPERTY (g_object_new (GDATA_TYPE_DOCUMENTS_PROPERTY, "key", key, NULL)); +} + +/** + * gdata_documents_property_get_key: + * @self: a #GDataDocumentsProperty + * + * Returns the key of the property. This will never be %NULL or an empty string (""). + * + * Return value: (transfer none): the property's key + * + * Since: 0.17.11 + */ +const gchar * +gdata_documents_property_get_key (GDataDocumentsProperty *self) +{ + g_return_val_if_fail (GDATA_IS_DOCUMENTS_PROPERTY (self), NULL); + return self->priv->key; +} + +static void +_gdata_documents_property_set_key (GDataDocumentsProperty *self, const gchar *key) +{ + /* This is a READ-ONLY PROPERTY */ + g_return_if_fail (GDATA_IS_DOCUMENTS_PROPERTY (self)); + g_return_if_fail (key != NULL && *key != '\0'); + + g_free (self->priv->key); + self->priv->key = g_strdup (key); + + g_object_notify (G_OBJECT (self), "key"); +} + +/** + * gdata_documents_property_get_etag: + * @self: a #GDataDocumentsProperty + * + * Returns the ETag of the property. + * + * Return value: (transfer none): the property's ETag. The ETag will never be empty; it's either %NULL or a valid ETag. + * + * Since: 0.17.11 + */ +const gchar * +gdata_documents_property_get_etag (GDataDocumentsProperty *self) +{ + g_return_val_if_fail (GDATA_IS_DOCUMENTS_PROPERTY (self), NULL); + return self->priv->etag; +} + +static void +_gdata_documents_property_set_etag (GDataDocumentsProperty *self, const gchar *etag) +{ + g_return_if_fail (GDATA_IS_DOCUMENTS_PROPERTY (self)); + + if (g_strcmp0 (self->priv->etag, etag) != 0) { + g_free (self->priv->etag); + self->priv->etag = g_strdup (etag); + g_object_notify (G_OBJECT (self), "etag"); + } +} + +/** + * gdata_documents_property_get_value: + * @self: a #GDataDocumentsProperty + * + * Returns the value of the property. + * + * In the case that this value is %NULL, the Property Resource corresponding to @self will be deleted from the properties array on a file's metadata, whereas in the case that it's empty string (""), it will be set as it is. + * + * Return value: (nullable): the property's value. This can be %NULL or empty. + * + * Since: 0.17.11 + */ +const gchar * +gdata_documents_property_get_value (GDataDocumentsProperty *self) +{ + g_return_val_if_fail (GDATA_IS_DOCUMENTS_PROPERTY (self), NULL); + return self->priv->value; +} + +/** + * gdata_documents_property_set_value: + * @self: a #GDataDocumentsProperty + * @value: (allow-none): the new value of the property + * + * Sets #GDataDocumentsProperty:value to @value, corresponding to the key. + * + * In the case that @value is %NULL, the Property Resource corresponding to @self will be deleted from the properties array on a file's metadata, whereas in the case that it's empty string (""), it will be set as it is. + * + * Since: 0.17.11 + */ +void +gdata_documents_property_set_value (GDataDocumentsProperty *self, const gchar *value) +{ + g_return_if_fail (GDATA_IS_DOCUMENTS_PROPERTY (self)); + + if (g_strcmp0 (self->priv->value, value) != 0) { + g_free (self->priv->value); + self->priv->value = g_strdup (value); + g_object_notify (G_OBJECT (self), "value"); + } +} + +/** + * gdata_documents_property_get_visibility: + * @self: a #GDataDocumentsProperty + * + * Returns the visibility status of the property. + * + * Return value: %GDATA_DOCUMENTS_PROPERTY_VISIBILITY_PUBLIC if the #GDataDocumentsProperty is publicly visible to other + * apps, %GDATA_DOCUMENTS_PROPERTY_VISIBILITY_PRIVATE if the #GDataDocumentsProperty is restricted to the application which + * created it. + * + * Since: 0.17.11 + */ +const gchar * +gdata_documents_property_get_visibility (GDataDocumentsProperty *self) +{ + g_return_val_if_fail (GDATA_IS_DOCUMENTS_PROPERTY (self), NULL); + return self->priv->visibility; +} + +/** + * gdata_documents_property_set_visibility: + * @self: a #GDataDocumentsProperty + * @visibility: the new visibility status of the property + * + * Sets #GDataDocumentsProperty:visibility to %GDATA_DOCUMENTS_PROPERTY_VISIBILITY_PUBLIC for + * public properties and %GDATA_DOCUMENTS_PROPERTY_VISIBILITY_PRIVATE for + * private properties (default). + * + * Since: 0.17.11 + */ +void +gdata_documents_property_set_visibility (GDataDocumentsProperty *self, const gchar *visibility) +{ + g_return_if_fail (GDATA_IS_DOCUMENTS_PROPERTY (self)); + g_return_if_fail (g_strcmp0 (visibility, GDATA_DOCUMENTS_PROPERTY_VISIBILITY_PUBLIC) == 0 || + g_strcmp0 (visibility, GDATA_DOCUMENTS_PROPERTY_VISIBILITY_PRIVATE) == 0); + + if (g_strcmp0 (self->priv->visibility, visibility) != 0) { + g_free (self->priv->visibility); + self->priv->visibility = g_strdup (visibility); + g_object_notify (G_OBJECT (self), "visibility"); + } +} diff --git a/gdata/services/documents/gdata-documents-property.h b/gdata/services/documents/gdata-documents-property.h new file mode 100644 index 0000000..1539130 --- /dev/null +++ b/gdata/services/documents/gdata-documents-property.h @@ -0,0 +1,106 @@ +/* -*- Mode: C; indent-tabs-mode: t; c-basic-offset: 8; tab-width: 8 -*- */ +/* + * GData Client + * Copyright (C) Mayank Sharma + * + * GData Client is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * GData Client is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with GData Client. If not, see . + */ + +#ifndef GDATA_DOCUMENTS_PROPERTY_H +#define GDATA_DOCUMENTS_PROPERTY_H + +#include +#include + +#include + +G_BEGIN_DECLS + +/** + * GDATA_DOCUMENTS_PROPERTY_VISIBILITY_PUBLIC: + * + * The #GDataDocumentsProperty having the visibility set to TRUE corresponds to having the visibility property + * on a Drive Property Resource + * set to "PUBLIC". This makes the Property Resource visible to other apps. + * + * Since: 0.17.11 + */ +#define GDATA_DOCUMENTS_PROPERTY_VISIBILITY_PUBLIC "PUBLIC" + +/** + * GDATA_DOCUMENTS_PROPERTY_VISIBILITY_PRIVATE: + * + * The #GDataDocumentsProperty having the visibility set to FALSE (default) corresponds to having the visibility property on a Drive Property Resource + * set to "PRIVATE". This makes the Property Resource accessible only by the app that created it. + * + * Since: 0.17.11 + */ +#define GDATA_DOCUMENTS_PROPERTY_VISIBILITY_PRIVATE "PRIVATE" + +#define GDATA_TYPE_DOCUMENTS_PROPERTY (gdata_documents_property_get_type ()) +#define GDATA_DOCUMENTS_PROPERTY(o) (G_TYPE_CHECK_INSTANCE_CAST ((o), GDATA_TYPE_DOCUMENTS_PROPERTY, GDataDocumentsProperty)) +#define GDATA_DOCUMENTS_PROPERTY_CLASS(k) (G_TYPE_CHECK_CLASS_CAST((k), GDATA_TYPE_DOCUMENTS_PROPERTY, GDataDocumentsPropertyClass)) +#define GDATA_IS_DOCUMENTS_PROPERTY(o) (G_TYPE_CHECK_INSTANCE_TYPE ((o), GDATA_TYPE_DOCUMENTS_PROPERTY)) +#define GDATA_IS_DOCUMENTS_PROPERTY_CLASS(k) (G_TYPE_CHECK_CLASS_TYPE ((k), GDATA_TYPE_DOCUMENTS_PROPERTY)) +#define GDATA_DOCUMENTS_PROPERTY_GET_CLASS(o) (G_TYPE_INSTANCE_GET_CLASS ((o), GDATA_TYPE_DOCUMENTS_PROPERTY, GDataDocumentsPropertyClass)) + +typedef struct _GDataDocumentsPropertyPrivate GDataDocumentsPropertyPrivate; + +/** + * GDataDocumentsProperty: + * + * All the fields in the #GDataDocumentsProperty structure are private and should never be accessed directly. + * + * Since: 0.17.11 + */ +typedef struct { + GDataParsable parent; + GDataDocumentsPropertyPrivate *priv; +} GDataDocumentsProperty; + +/** + * GDataDocumentsPropertyClass: + * + * All the fields in the #GDataDocumentsPropertyClass structure are private and should never be accessed directly. + * + * Since: 0.17.11 + */ +typedef struct { + /*< private >*/ + GDataParsableClass parent; + + /*< private >*/ + /* Padding for future expansion */ + void (*_g_reserved0) (void); + void (*_g_reserved1) (void); +} GDataDocumentsPropertyClass; + +GType gdata_documents_property_get_type (void) G_GNUC_CONST; +G_DEFINE_AUTOPTR_CLEANUP_FUNC (GDataDocumentsProperty, g_object_unref) + +GDataDocumentsProperty *gdata_documents_property_new (const gchar *key) G_GNUC_WARN_UNUSED_RESULT G_GNUC_MALLOC; + +const gchar *gdata_documents_property_get_key (GDataDocumentsProperty *self) G_GNUC_PURE; + +const gchar *gdata_documents_property_get_etag (GDataDocumentsProperty *self) G_GNUC_PURE; + +const gchar *gdata_documents_property_get_value (GDataDocumentsProperty *self) G_GNUC_PURE; +void gdata_documents_property_set_value (GDataDocumentsProperty *self, const gchar *value); + +const gchar *gdata_documents_property_get_visibility (GDataDocumentsProperty *self) G_GNUC_PURE; +void gdata_documents_property_set_visibility (GDataDocumentsProperty *self, const gchar *visibility); + +G_END_DECLS + +#endif /* !GDATA_DOCUMENTS_PROPERTY_H */ diff --git a/gdata/services/documents/gdata-documents-query.c b/gdata/services/documents/gdata-documents-query.c new file mode 100644 index 0000000..6070c1b --- /dev/null +++ b/gdata/services/documents/gdata-documents-query.c @@ -0,0 +1,709 @@ +/* -*- Mode: C; indent-tabs-mode: t; c-basic-offset: 8; tab-width: 8 -*- */ +/* + * GData Client + * Copyright (C) Thibault Saunier 2009 + * Copyright (C) Philip Withnall 2010 + * Copyright (C) Red Hat, Inc. 2015 + * + * GData Client is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * GData Client is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with GData Client. If not, see . + */ + +/** + * SECTION:gdata-documents-query + * @short_description: GData Documents query object + * @stability: Stable + * @include: gdata/services/documents/gdata-documents-query.h + * + * #GDataDocumentsQuery represents a collection of query parameters specific to the Google Documents service, which go above and beyond + * those catered for by #GDataQuery. + * + * For more information on the custom GData query parameters supported by #GDataDocumentsQuery, see the online documentation. + * + * + * Querying for Documents + * + * GDataDocumentsService *service; + * GDataDocumentsQuery *query; + * GDataFeed *feed; + * GTimeVal current_time; + * GList *i; + * GError *error = NULL; + * + * /* Create a service */ + * service = create_documents_service (); + * + * /* Create the query to use. We're going to query for the last 10 documents modified by example@gmail.com in the past week, including + * * deleted documents. */ + * query = gdata_documents_query_new_with_limits (NULL, 0, 10); + * + * gdata_documents_query_add_collaborator (query, "example@gmail.com"); + * gdata_documents_query_set_show_deleted (query, TRUE); + * + * g_get_current_time (¤t_time); + * gdata_query_set_updated_min (GDATA_QUERY (query), current_time.tv_sec - 7 * 24 * 60 * 60); + * gdata_query_set_updated_max (GDATA_QUERY (query), current_time.tv_sec); + * + * /* Execute the query */ + * feed = gdata_documents_service_query_documents (service, query, NULL, NULL, NULL, &error); + * + * g_object_unref (query); + * g_object_unref (service); + * + * if (error != NULL) { + * g_error ("Error querying for documents: %s", error->message); + * g_error_free (error); + * return; + * } + * + * /* Iterate through the returned documents and do something with them */ + * for (i = gdata_feed_get_entries (feed); i != NULL; i = i->next) { + * GDataDocumentsDocument *document = GDATA_DOCUMENTS_DOCUMENT (i->data); + * + * /* Do something with the document here, such as insert it into a UI */ + * } + * + * g_object_unref (feed); + * + * + * + * Since: 0.4.0 + */ + +#include +#include +#include +#include + +#include "gd/gdata-gd-email-address.h" +#include "gdata-documents-query.h" +#include "gdata-private.h" +#include "gdata-query.h" + +#include +#include +#include +#include + +static void gdata_documents_query_dispose (GObject *object); +static void gdata_documents_query_finalize (GObject *object); +static void gdata_documents_query_get_property (GObject *object, guint property_id, GValue *value, GParamSpec *pspec); +static void gdata_documents_query_set_property (GObject *object, guint property_id, const GValue *value, GParamSpec *pspec); +static void get_query_uri (GDataQuery *self, const gchar *feed_uri, GString *query_uri, gboolean *params_started); + +struct _GDataDocumentsQueryPrivate { + gboolean show_deleted; + gboolean show_folders; + gboolean exact_title; + gchar *folder_id; + gchar *title; + GList *collaborator_addresses; /* GDataGDEmailAddress */ + GList *reader_addresses; /* GDataGDEmailAddress */ +}; + +enum { + PROP_SHOW_DELETED = 1, + PROP_SHOW_FOLDERS, + PROP_EXACT_TITLE, + PROP_FOLDER_ID, + PROP_TITLE +}; + +G_DEFINE_TYPE (GDataDocumentsQuery, gdata_documents_query, GDATA_TYPE_QUERY) + +static void +gdata_documents_query_class_init (GDataDocumentsQueryClass *klass) +{ + GObjectClass *gobject_class = G_OBJECT_CLASS (klass); + GDataQueryClass *query_class = GDATA_QUERY_CLASS (klass); + + g_type_class_add_private (klass, sizeof (GDataDocumentsQueryPrivate)); + + gobject_class->get_property = gdata_documents_query_get_property; + gobject_class->set_property = gdata_documents_query_set_property; + gobject_class->dispose = gdata_documents_query_dispose; + gobject_class->finalize = gdata_documents_query_finalize; + + query_class->get_query_uri = get_query_uri; + + /** + * GDataDocumentsQuery:show-deleted: + * + * A shortcut to request all documents that have been deleted. + * + * Since: 0.4.0 + */ + g_object_class_install_property (gobject_class, PROP_SHOW_DELETED, + g_param_spec_boolean ("show-deleted", + "Show deleted?", "A shortcut to request all documents that have been deleted.", + FALSE, + G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)); + + /** + * GDataDocumentsQuery:show-folders: + * + * Specifies if the request also returns folders. + * + * Since: 0.4.0 + */ + g_object_class_install_property (gobject_class, PROP_SHOW_FOLDERS, + g_param_spec_boolean ("show-folders", + "Show folders?", "Specifies if the request also returns folders.", + FALSE, + G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)); + + /** + * GDataDocumentsQuery:exact-title: + * + * Specifies whether the query should search for an exact title match for the #GDataDocumentsQuery:title parameter. + * + * Since: 0.4.0 + */ + g_object_class_install_property (gobject_class, PROP_EXACT_TITLE, + g_param_spec_boolean ("exact-title", + "Exact title?", "Specifies whether the query should search for an exact title match.", + FALSE, + G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)); + + /** + * GDataDocumentsQuery:folder-id: + * + * Specifies the ID of the folder in which to search. + * + * Since: 0.4.0 + */ + g_object_class_install_property (gobject_class, PROP_FOLDER_ID, + g_param_spec_string ("folder-id", + "Folder ID", "Specifies the ID of the folder in which to search.", + NULL, + G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)); + + /** + * GDataDocumentsQuery:title: + * + * A title (or title fragment) to be searched for. If #GDataDocumentsQuery:exact-title is %TRUE, an exact + * title match will be searched for, otherwise substring matches will also be returned. + * + * Since: 0.4.0 + */ + g_object_class_install_property (gobject_class, PROP_TITLE, + g_param_spec_string ("title", + "Title", "A title (or title fragment) to be searched for.", + NULL, + G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)); +} + +static void +gdata_documents_query_init (GDataDocumentsQuery *self) +{ + self->priv = G_TYPE_INSTANCE_GET_PRIVATE (self, GDATA_TYPE_DOCUMENTS_QUERY, GDataDocumentsQueryPrivate); + + /* https://developers.google.com/drive/v3/reference/files/list#q */ + _gdata_query_set_pagination_type (GDATA_QUERY (self), + GDATA_QUERY_PAGINATION_TOKENS); +} + +static void +gdata_documents_query_dispose (GObject *object) +{ + GList *i; + GDataDocumentsQueryPrivate *priv = GDATA_DOCUMENTS_QUERY (object)->priv; + + for (i = priv->collaborator_addresses; i != NULL; i = i->next) + g_object_unref (i->data); + g_list_free (priv->collaborator_addresses); + priv->collaborator_addresses = NULL; + + for (i = priv->reader_addresses; i != NULL; i = i->next) + g_object_unref (i->data); + g_list_free (priv->reader_addresses); + priv->reader_addresses = NULL; + + G_OBJECT_CLASS (gdata_documents_query_parent_class)->dispose (object); +} + +static void +gdata_documents_query_finalize (GObject *object) +{ + GDataDocumentsQueryPrivate *priv = GDATA_DOCUMENTS_QUERY (object)->priv; + + g_free (priv->folder_id); + g_free (priv->title); + + G_OBJECT_CLASS (gdata_documents_query_parent_class)->finalize (object); +} + +static void +gdata_documents_query_get_property (GObject *object, guint property_id, GValue *value, GParamSpec *pspec) +{ + GDataDocumentsQueryPrivate *priv = GDATA_DOCUMENTS_QUERY (object)->priv; + + switch (property_id) { + case PROP_SHOW_DELETED: + g_value_set_boolean (value, priv->show_deleted); + break; + case PROP_SHOW_FOLDERS: + g_value_set_boolean (value, priv->show_folders); + break; + case PROP_FOLDER_ID: + g_value_set_string (value, priv->folder_id); + break; + case PROP_EXACT_TITLE: + g_value_set_boolean (value, priv->exact_title); + break; + case PROP_TITLE: + g_value_set_string (value, priv->title); + break; + default: + /* We don't have any other property... */ + G_OBJECT_WARN_INVALID_PROPERTY_ID (object, property_id, pspec); + break; + } +} + +static void +gdata_documents_query_set_property (GObject *object, guint property_id, const GValue *value, GParamSpec *pspec) +{ + GDataDocumentsQuery *self = GDATA_DOCUMENTS_QUERY (object); + + switch (property_id) { + case PROP_SHOW_DELETED: + gdata_documents_query_set_show_deleted (self, g_value_get_boolean (value)); + break; + case PROP_SHOW_FOLDERS: + gdata_documents_query_set_show_folders (self, g_value_get_boolean (value)); + break; + case PROP_FOLDER_ID: + gdata_documents_query_set_folder_id (self, g_value_get_string (value)); + break; + case PROP_EXACT_TITLE: + self->priv->exact_title = g_value_get_boolean (value); + break; + case PROP_TITLE: + gdata_documents_query_set_title (self, g_value_get_string (value), TRUE); + break; + default: + /* We don't have any other property... */ + G_OBJECT_WARN_INVALID_PROPERTY_ID (object, property_id, pspec); + break; + } +} + +static void +get_query_uri (GDataQuery *self, const gchar *feed_uri, GString *query_uri, gboolean *params_started) +{ + GDataDocumentsQueryPrivate *priv = GDATA_DOCUMENTS_QUERY (self)->priv; + guint max_results; + + #define APPEND_SEP g_string_append_c (query_uri, (*params_started == FALSE) ? '?' : '&'); *params_started = TRUE; + + if (priv->folder_id != NULL) { + g_string_append (query_uri, "/folder%3A"); + g_string_append_uri_escaped (query_uri, priv->folder_id, NULL, FALSE); + } + + /* Search parameters: https://developers.google.com/drive/web/search-parameters */ + + _gdata_query_clear_q_internal (self); + + if (priv->collaborator_addresses != NULL) { + GList *i; + GString *str; + + str = g_string_new (NULL); + + for (i = priv->collaborator_addresses; i != NULL; i = i->next) { + GDataGDEmailAddress *email_address = GDATA_GD_EMAIL_ADDRESS (i->data); + const gchar *address; + + address = gdata_gd_email_address_get_address (email_address); + g_string_append_printf (str, "'%s' in writers", address); + if (i->next != NULL) + g_string_append (str, " or "); + } + + _gdata_query_add_q_internal (self, str->str); + g_string_free (str, TRUE); + } + + if (priv->reader_addresses != NULL) { + GList *i; + GString *str; + + str = g_string_new (NULL); + + for (i = priv->reader_addresses; i != NULL; i = i->next) { + GDataGDEmailAddress *email_address = GDATA_GD_EMAIL_ADDRESS (i->data); + const gchar *address; + + address = gdata_gd_email_address_get_address (email_address); + g_string_append_printf (str, "'%s' in readers", address); + if (i->next != NULL) + g_string_append (str, " or "); + } + + _gdata_query_add_q_internal (self, str->str); + g_string_free (str, TRUE); + } + + if (priv->show_deleted == TRUE) + _gdata_query_add_q_internal (self, "trashed=true"); + else + _gdata_query_add_q_internal (self, "trashed=false"); + + if (priv->show_folders == FALSE) + _gdata_query_add_q_internal (self, "mimeType!='application/vnd.google-apps.folder'"); + + if (priv->title != NULL) { + GString *title_query; + const gchar *ptr, *ptr_end; + + title_query = g_string_new ("title"); + if (priv->exact_title) { + g_string_append_c (title_query, '='); + } else { + g_string_append (title_query, " contains "); + } + g_string_append_c (title_query, '\''); + + for (ptr = priv->title; ptr != NULL; ptr = ptr_end) { + /* Escape any "'" and "\" found in the title with a "\" */ + ptr_end = strpbrk (ptr, "\'\\"); + if (ptr_end == NULL) { + g_string_append (title_query, ptr); + } else { + g_string_append_len (title_query, ptr, ptr_end - ptr); + g_string_append_c (title_query, '\\'); + g_string_append_c (title_query, *ptr_end); + } + } + + g_string_append_c (title_query, '\''); + _gdata_query_add_q_internal (self, title_query->str); + g_string_free (title_query, TRUE); + } + + /* Chain up to the parent class */ + GDATA_QUERY_CLASS (gdata_documents_query_parent_class)->get_query_uri (self, feed_uri, query_uri, params_started); + + /* https://developers.google.com/drive/v2/reference/files/list */ + max_results = gdata_query_get_max_results (self); + if (max_results > 0) { + APPEND_SEP + max_results = max_results > 1000 ? 1000 : max_results; + g_string_append_printf (query_uri, "maxResults=%u", max_results); + } +} + +/** + * gdata_documents_query_new: + * @q: (allow-none): a query string, or %NULL + * + * Creates a new #GDataDocumentsQuery with its #GDataQuery:q property set to @q. + * + * Return value: a new #GDataDocumentsQuery + * + * Since: 0.4.0 + */ +GDataDocumentsQuery * +gdata_documents_query_new (const gchar *q) +{ + return g_object_new (GDATA_TYPE_DOCUMENTS_QUERY, "q", q, NULL); +} + +/** + * gdata_documents_query_new_with_limits: + * @q: (allow-none): a query string, or %NULL + * @start_index: a one-based start index for the results, or 0 + * @max_results: the maximum number of results to return, or 0 + * + * Creates a new #GDataDocumentsQuery with its #GDataQuery:q property set to @q, and the limits @start_index and @max_results + * applied. + * + * Return value: a new #GDataDocumentsQuery + * + * Since: 0.4.0 + */ +GDataDocumentsQuery * +gdata_documents_query_new_with_limits (const gchar *q, guint start_index, guint max_results) +{ + return g_object_new (GDATA_TYPE_DOCUMENTS_QUERY, + "q", q, + "start-index", start_index, + "max-results", max_results, + NULL); +} + +/** + * gdata_documents_query_show_deleted: + * @self: a #GDataDocumentsQuery + * + * Gets the #GDataDocumentsQuery:show_deleted property. + * + * Return value: %TRUE if the request should return deleted entries, %FALSE otherwise + * + * Since: 0.4.0 + */ +gboolean +gdata_documents_query_show_deleted (GDataDocumentsQuery *self) +{ + g_return_val_if_fail (GDATA_IS_DOCUMENTS_QUERY (self), FALSE); + return self->priv->show_deleted; +} + +/** + * gdata_documents_query_set_show_deleted: + * @self: a #GDataDocumentsQuery + * @show_deleted: %TRUE if the request should return deleted entries, %FALSE otherwise + * + * Sets the #GDataDocumentsQuery:show_deleted property to @show_deleted. + * + * Since: 0.4.0 + */ +void +gdata_documents_query_set_show_deleted (GDataDocumentsQuery *self, gboolean show_deleted) +{ + g_return_if_fail (GDATA_IS_DOCUMENTS_QUERY (self)); + self->priv->show_deleted = show_deleted; + g_object_notify (G_OBJECT (self), "show-deleted"); + + /* Our current ETag will no longer be relevant */ + gdata_query_set_etag (GDATA_QUERY (self), NULL); +} + +/** + * gdata_documents_query_show_folders: + * @self: a #GDataDocumentsQuery + * + * Gets the #GDataDocumentsQuery:show-folders property. + * + * Return value: %TRUE if the request should return folders, %FALSE otherwise + * + * Since: 0.4.0 + */ +gboolean +gdata_documents_query_show_folders (GDataDocumentsQuery *self) +{ + g_return_val_if_fail (GDATA_IS_DOCUMENTS_QUERY (self), FALSE); + return self->priv->show_folders; +} + +/** + * gdata_documents_query_set_show_folders: + * @self: a #GDataDocumentsQuery + * @show_folders: %TRUE if the request should return folders, %FALSE otherwise + * + * Sets the #GDataDocumentsQuery:show-folders property to show_folders. + * + * Since: 0.4.0 + */ +void +gdata_documents_query_set_show_folders (GDataDocumentsQuery *self, gboolean show_folders) +{ + g_return_if_fail (GDATA_IS_DOCUMENTS_QUERY (self)); + self->priv->show_folders = show_folders; + g_object_notify (G_OBJECT (self), "show-folders"); + + /* Our current ETag will no longer be relevant */ + gdata_query_set_etag (GDATA_QUERY (self), NULL); +} + +/** + * gdata_documents_query_get_folder_id: + * @self: a #GDataDocumentsQuery + * + * Gets the #GDataDocumentsQuery:folder-id property. + * + * Return value: the ID of the folder to be queried, or %NULL + * + * Since: 0.4.0 + */ +const gchar * +gdata_documents_query_get_folder_id (GDataDocumentsQuery *self) +{ + g_return_val_if_fail (GDATA_IS_DOCUMENTS_QUERY (self), NULL); + return self->priv->folder_id; +} + +/** + * gdata_documents_query_set_folder_id: + * @self: a #GDataDocumentsQuery + * @folder_id: (allow-none): the ID of the folder to be queried, or %NULL + * + * Sets the #GDataDocumentsQuery:folder-id property to @folder_id. + * + * Set @folder_id to %NULL to unset the property in the query URI. + * + * Since: 0.4.0 + */ +void +gdata_documents_query_set_folder_id (GDataDocumentsQuery *self, const gchar *folder_id) +{ + g_return_if_fail (GDATA_IS_DOCUMENTS_QUERY (self)); + + g_free (self->priv->folder_id); + self->priv->folder_id = g_strdup (folder_id); + g_object_notify (G_OBJECT (self), "folder-id"); + + /* Our current ETag will no longer be relevant */ + gdata_query_set_etag (GDATA_QUERY (self), NULL); +} + +/** + * gdata_documents_query_get_title: + * @self: a #GDataDocumentsQuery + * + * Gets the #GDataDocumentsQuery:title property. + * + * Return value: the title (or title fragment) being queried for, or %NULL + * + * Since: 0.4.0 + */ +const gchar * +gdata_documents_query_get_title (GDataDocumentsQuery *self) +{ + g_return_val_if_fail (GDATA_IS_DOCUMENTS_QUERY (self), NULL); + return self->priv->title; +} + +/** + * gdata_documents_query_get_exact_title: + * @self: a #GDataDocumentsQuery + * + * Gets the #GDataDocumentsQuery:exact-title property. + * + * Return value: %TRUE if the query matches the exact title of documents with #GDataDocumentsQuery:title, %FALSE otherwise + * + * Since: 0.4.0 + */ +gboolean +gdata_documents_query_get_exact_title (GDataDocumentsQuery *self) +{ + g_return_val_if_fail (GDATA_IS_DOCUMENTS_QUERY (self), FALSE); + return self->priv->exact_title; +} + +/** + * gdata_documents_query_set_title: + * @self: a #GDataDocumentsQuery + * @title: (allow-none): the title (or title fragment) to query for, or %NULL + * @exact_title: %TRUE if the query should match the exact @title, %FALSE otherwise + * + * Sets the #GDataDocumentsQuery:title property to @title. + * + * Set @title to %NULL to unset the property in the query URI. + * + * Since: 0.4.0 + */ +void +gdata_documents_query_set_title (GDataDocumentsQuery *self, const gchar *title, gboolean exact_title) +{ + g_return_if_fail (GDATA_IS_DOCUMENTS_QUERY (self)); + + g_free (self->priv->title); + self->priv->title = g_strdup (title); + self->priv->exact_title = exact_title; + + g_object_freeze_notify (G_OBJECT (self)); + g_object_notify (G_OBJECT (self), "exact-title"); + g_object_notify (G_OBJECT (self), "title"); + g_object_thaw_notify (G_OBJECT (self)); + + /* Our current ETag will no longer be relevant */ + gdata_query_set_etag (GDATA_QUERY (self), NULL); +} + +/** + * gdata_documents_query_get_collaborator_addresses: + * @self: a #GDataDocumentsQuery + * + * Gets a list of #GDataGDEmailAddresses of the document collaborators whose documents will be queried. + * + * Return value: (element-type GData.GDEmailAddress) (transfer none): a list of #GDataGDEmailAddresses of the collaborators concerned by the + * query, or %NULL + * + * Since: 0.4.0 + */ +GList * +gdata_documents_query_get_collaborator_addresses (GDataDocumentsQuery *self) +{ + g_return_val_if_fail (GDATA_IS_DOCUMENTS_QUERY (self), NULL); + return self->priv->collaborator_addresses; +} + +/** + * gdata_documents_query_get_reader_addresses: + * @self: a #GDataDocumentsQuery + * + * Gets a list of #GDataGDEmailAddresses of the document readers whose documents will be queried. + * + * Return value: (element-type GData.GDEmailAddress) (transfer none): a list of #GDataGDEmailAddresses of the readers concerned by the query, + * or %NULL + * + * Since: 0.4.0 + */ +GList * +gdata_documents_query_get_reader_addresses (GDataDocumentsQuery *self) +{ + g_return_val_if_fail (GDATA_IS_DOCUMENTS_QUERY (self), NULL); + return self->priv->reader_addresses; +} + +/** + * gdata_documents_query_add_reader: + * @self: a #GDataDocumentsQuery + * @email_address: the e-mail address of the reader to add + * + * Add @email_address as a #GDataGDEmailAddress to the list of readers, the documents readable by whom will be queried. + * + * Since: 0.4.0 + */ +void +gdata_documents_query_add_reader (GDataDocumentsQuery *self, const gchar *email_address) +{ + GDataGDEmailAddress *address; + + g_return_if_fail (GDATA_IS_DOCUMENTS_QUERY (self)); + g_return_if_fail (email_address != NULL && *email_address != '\0'); + + address = gdata_gd_email_address_new (email_address, "reader", NULL, FALSE); + self->priv->reader_addresses = g_list_append (self->priv->reader_addresses, address); + + /* Our current ETag will no longer be relevant */ + gdata_query_set_etag (GDATA_QUERY (self), NULL); +} + +/** + * gdata_documents_query_add_collaborator: + * @self: a #GDataDocumentsQuery + * @email_address: the e-mail address of the collaborator to add + * + * Add @email_address as a #GDataGDEmailAddress to the list of collaborators whose edited documents will be queried. + * + * Since: 0.4.0 + */ +void +gdata_documents_query_add_collaborator (GDataDocumentsQuery *self, const gchar *email_address) +{ + GDataGDEmailAddress *address; + + g_return_if_fail (GDATA_IS_DOCUMENTS_QUERY (self)); + g_return_if_fail (email_address != NULL && *email_address != '\0'); + + address = gdata_gd_email_address_new (email_address, "collaborator", NULL, FALSE); + self->priv->collaborator_addresses = g_list_append (self->priv->collaborator_addresses, address); + + /* Our current ETag will no longer be relevant */ + gdata_query_set_etag (GDATA_QUERY (self), NULL); +} diff --git a/gdata/services/documents/gdata-documents-query.h b/gdata/services/documents/gdata-documents-query.h new file mode 100644 index 0000000..dfe369c --- /dev/null +++ b/gdata/services/documents/gdata-documents-query.h @@ -0,0 +1,93 @@ +/* -*- Mode: C; indent-tabs-mode: t; c-basic-offset: 8; tab-width: 8 -*- */ +/* + * GData Client + * Copyright (C) Thibault Saunier 2009 + * + * GData Client is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * GData Client is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with GData Client. If not, see . + */ + +#ifndef GDATA_DOCUMENTS_QUERY_H +#define GDATA_DOCUMENTS_QUERY_H + +#include +#include + +#include +#include + +G_BEGIN_DECLS + +#define GDATA_TYPE_DOCUMENTS_QUERY (gdata_documents_query_get_type ()) +#define GDATA_DOCUMENTS_QUERY(o) (G_TYPE_CHECK_INSTANCE_CAST ((o), GDATA_TYPE_DOCUMENTS_QUERY, GDataDocumentsQuery)) +#define GDATA_DOCUMENTS_QUERY_CLASS(k) (G_TYPE_CHECK_CLASS_CAST((k), GDATA_TYPE_DOCUMENTS_QUERY, GDataDocumentsQueryClass)) +#define GDATA_IS_DOCUMENTS_QUERY(o) (G_TYPE_CHECK_INSTANCE_TYPE ((o), GDATA_TYPE_DOCUMENTS_QUERY)) +#define GDATA_IS_DOCUMENTS_QUERY_CLASS(k) (G_TYPE_CHECK_CLASS_TYPE ((k), GDATA_TYPE_DOCUMENTS_QUERY)) +#define GDATA_DOCUMENTS_QUERY_GET_CLASS(o) (G_TYPE_INSTANCE_GET_CLASS ((o), GDATA_TYPE_DOCUMENTS_QUERY, GDataDocumentsQueryClass)) + +typedef struct _GDataDocumentsQueryPrivate GDataDocumentsQueryPrivate; + +/** + * GDataDocumentsQuery: + * + * All the fields in the #GDataDocumentsQuery structure are private and should never be accessed directly. + * + * Since: 0.4.0 + */ +typedef struct { + GDataQuery parent; + GDataDocumentsQueryPrivate *priv; +} GDataDocumentsQuery; + +/** + * GDataDocumentsQueryClass: + * + * All the fields in the #GDataDocumentsQueryClass structure are private and should never be accessed directly. + * + * Since: 0.4.0 + */ +typedef struct { + /*< private >*/ + GDataQueryClass parent; + GDataDocumentsQueryPrivate *priv; + + /*< private >*/ + /* Padding for future expansion */ + void (*_g_reserved0) (void); + void (*_g_reserved1) (void); +} GDataDocumentsQueryClass; + +GType gdata_documents_query_get_type (void) G_GNUC_CONST; +G_DEFINE_AUTOPTR_CLEANUP_FUNC (GDataDocumentsQuery, g_object_unref) + +GDataDocumentsQuery *gdata_documents_query_new (const gchar *q) G_GNUC_WARN_UNUSED_RESULT G_GNUC_MALLOC; +GDataDocumentsQuery *gdata_documents_query_new_with_limits (const gchar *q, + guint start_index, guint max_results) G_GNUC_WARN_UNUSED_RESULT G_GNUC_MALLOC; + +gboolean gdata_documents_query_show_deleted (GDataDocumentsQuery *self) G_GNUC_PURE; +void gdata_documents_query_set_show_deleted (GDataDocumentsQuery *self, gboolean show_deleted); +gboolean gdata_documents_query_show_folders (GDataDocumentsQuery *self) G_GNUC_PURE; +void gdata_documents_query_set_show_folders (GDataDocumentsQuery *self, gboolean show_folders); +const gchar *gdata_documents_query_get_folder_id (GDataDocumentsQuery *self) G_GNUC_PURE; +void gdata_documents_query_set_folder_id (GDataDocumentsQuery *self, const gchar *folder_id); +const gchar *gdata_documents_query_get_title (GDataDocumentsQuery *self) G_GNUC_PURE; +gboolean gdata_documents_query_get_exact_title (GDataDocumentsQuery *self) G_GNUC_PURE; +void gdata_documents_query_set_title (GDataDocumentsQuery *self, const gchar *title, gboolean exact_title); +GList *gdata_documents_query_get_collaborator_addresses (GDataDocumentsQuery *self) G_GNUC_PURE; +GList *gdata_documents_query_get_reader_addresses (GDataDocumentsQuery *self) G_GNUC_PURE; +void gdata_documents_query_add_reader (GDataDocumentsQuery *self, const gchar *email_address); +void gdata_documents_query_add_collaborator (GDataDocumentsQuery *self, const gchar *email_address); + +G_END_DECLS + +#endif /* !GDATA_DOCUMENTS_QUERY_H */ diff --git a/gdata/services/documents/gdata-documents-service.c b/gdata/services/documents/gdata-documents-service.c new file mode 100644 index 0000000..93bc8f7 --- /dev/null +++ b/gdata/services/documents/gdata-documents-service.c @@ -0,0 +1,1628 @@ +/* -*- Mode: C; indent-tabs-mode: t; c-basic-offset: 8; tab-width: 8 -*- */ +/* + * GData Client + * Copyright (C) Thibault Saunier 2009 + * Copyright (C) Philip Withnall 2010, 2014 + * Copyright (C) Red Hat, Inc. 2015, 2016 + * + * GData Client is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * GData Client is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with GData Client. If not, see . + */ + +/** + * SECTION:gdata-documents-service + * @short_description: GData Documents service object + * @stability: Stable + * @include: gdata/services/documents/gdata-documents-service.h + * + * #GDataDocumentsService is a subclass of #GDataService for communicating with the GData API of Google Drive. It supports querying + * for, inserting, editing and deleting documents, as well as a folder hierarchy. + * The API is named ‘documents’ rather than ‘drive’ as it used to use the Google + * Documents API, which has since been deprecated. + * + * For more details of Google Drive's GData API, see the + * + * online documentation. + * + * Fore more details about the spreadsheet downloads handling, see the + * + * online explanation about the problem. + * + * + * Uploading a Document from Disk + * + * GDataDocumentsService *service; + * GDataDocumentsDocument *document, *uploaded_document; + * GFile *document_file; + * GDataDocumentsFolder *destination_folder; + * GFileInfo *file_info; + * const gchar *slug, *content_type; + * GFileInputStream *file_stream; + * GDataUploadStream *upload_stream; + * GError *error = NULL; + * + * /* Create a service */ + * service = create_documents_service (); + * + * /* Get the document file to upload and the folder to upload it into */ + * document_file = g_file_new_for_path ("document.odt"); + * destination_folder = query_user_for_destination_folder (service); + * + * /* Get the file's display name and content type */ + * file_info = g_file_query_info (document_file, G_FILE_ATTRIBUTE_STANDARD_DISPLAY_NAME "," G_FILE_ATTRIBUTE_STANDARD_CONTENT_TYPE, + * G_FILE_QUERY_INFO_NONE, NULL, &error); + * + * if (error != NULL) { + * g_error ("Error getting document file information: %s", error->message); + * g_error_free (error); + * g_object_unref (destination_folder); + * g_object_unref (document_file); + * g_object_unref (service); + * return; + * } + * + * slug = g_file_info_get_display_name (file_info); + * content_type = g_file_info_get_content_type (file_info); + * + * /* Get an input stream for the file */ + * file_stream = g_file_read (document_file, NULL, &error); + * + * g_object_unref (document_file); + * + * if (error != NULL) { + * g_error ("Error getting document file stream: %s", error->message); + * g_error_free (error); + * g_object_unref (file_info); + * g_object_unref (destination_folder); + * g_object_unref (service); + * return; + * } + * + * /* Create the document metadata to upload */ + * document = gdata_documents_text_new (NULL); + * gdata_entry_set_title (GDATA_ENTRY (document), "Document Title"); + * + * /* Get an upload stream for the document */ + * upload_stream = gdata_documents_service_upload_document (service, document, slug, content_type, destination_folder, NULL, &error); + * + * g_object_unref (document); + * g_object_unref (file_info); + * g_object_unref (destination_folder); + * + * if (error != NULL) { + * g_error ("Error getting upload stream: %s", error->message); + * g_error_free (error); + * g_object_unref (file_stream); + * g_object_unref (service); + * return; + * } + * + * /* Upload the document. This is a blocking operation, and should normally be done asynchronously. */ + * g_output_stream_splice (G_OUTPUT_STREAM (upload_stream), G_INPUT_STREAM (file_stream), + * G_OUTPUT_STREAM_SPLICE_CLOSE_SOURCE | G_OUTPUT_STREAM_SPLICE_CLOSE_TARGET, NULL, &error); + * + * g_object_unref (file_stream); + * + * if (error != NULL) { + * g_error ("Error splicing streams: %s", error->message); + * g_error_free (error); + * g_object_unref (upload_stream); + * g_object_unref (service); + * return; + * } + * + * /* Finish off the upload by parsing the returned updated document metadata entry */ + * uploaded_document = gdata_documents_service_finish_upload (service, upload_stream, &error); + * + * g_object_unref (upload_stream); + * g_object_unref (service); + * + * if (error != NULL) { + * g_error ("Error uploading document: %s", error->message); + * g_error_free (error); + * return; + * } + * + * /* Do something with the uploaded document */ + * + * g_object_unref (uploaded_document); + * + * + * + * The Drive service can be manipulated using batch operations, too. See the + * online documentation on batch + * operations for more information. + * + * + * Performing a Batch Operation on Documents + * + * GDataDocumentsService *service; + * GDataBatchOperation *operation; + * GDataFeed *feed; + * GDataLink *batch_link; + * GList *i; + * GError *error = NULL; + * + * /* Create a service */ + * service = create_documents_service (); + * + * /* Create the batch operation; this requires that we have done a query first so that we can get the batch link */ + * feed = do_some_query (service); + * batch_link = gdata_feed_look_up_link (feed, GDATA_LINK_BATCH); + * operation = gdata_batchable_create_operation (GDATA_BATCHABLE (service), gdata_link_get_uri (batch_link)); + * g_object_unref (feed); + * + * gdata_batch_operation_add_query (operation, presentation_entry_id_to_query, GDATA_TYPE_DOCUMENTS_PRESENTATION, + * (GDataBatchOperationCallback) batch_query_cb, user_data); + * gdata_batch_operation_add_insertion (operation, new_entry, (GDataBatchOperationCallback) batch_insertion_cb, user_data); + * gdata_batch_operation_add_update (operation, old_entry, (GDataBatchOperationCallback) batch_update_cb, user_data); + * gdata_batch_operation_add_deletion (operation, entry_to_delete, (GDataBatchOperationCallback) batch_deletion_cb, user_data); + * + * /* Run the batch operation and handle the results in the various callbacks */ + * gdata_test_batch_operation_run (operation, NULL, &error); + * + * g_object_unref (operation); + * g_object_unref (service); + * + * if (error != NULL) { + * g_error ("Error running batch operation: %s", error->message); + * g_error_free (error); + * return; + * } + * + * static void + * batch_query_cb (guint operation_id, GDataBatchOperationType operation_type, GDataEntry *entry, GError *error, gpointer user_data) + * { + * /* operation_type == GDATA_BATCH_OPERATION_QUERY */ + * /* Reference and do something with the returned entry. */ + * } + * + * static void + * batch_insertion_cb (guint operation_id, GDataBatchOperationType operation_type, GDataEntry *entry, GError *error, gpointer user_data) + * { + * /* operation_type == GDATA_BATCH_OPERATION_INSERTION */ + * /* Reference and do something with the returned entry. */ + * } + * + * static void + * batch_update_cb (guint operation_id, GDataBatchOperationType operation_type, GDataEntry *entry, GError *error, gpointer user_data) + * { + * /* operation_type == GDATA_BATCH_OPERATION_UPDATE */ + * /* Reference and do something with the returned entry. */ + * } + * + * static void + * batch_deletion_cb (guint operation_id, GDataBatchOperationType operation_type, GDataEntry *entry, GError *error, gpointer user_data) + * { + * /* operation_type == GDATA_BATCH_OPERATION_DELETION, entry == NULL */ + * } + * + * + * + * Starred documents are denoted by being in the %GDATA_CATEGORY_SCHEMA_LABELS_STARRED category of the %GDATA_CATEGORY_SCHEMA_LABELS schema. Documents + * can be starred or unstarred simply by adding or removing this category from them and updating the document: + * + * + * Starring a Document + * + * GDataDocumentsService *service; + * GDataDocumentsEntry *document, *updated_document; + * GDataCategory *starred_category; + * GError *error = NULL; + * + * /* Create a service and retrieve the document to be starred */ + * service = create_documents_service (); + * document = get_document_to_be_starred (service); + * + * /* Add the “starred” category to the document */ + * starred_category = gdata_category_new (GDATA_CATEGORY_SCHEMA_LABELS_STARRED, GDATA_CATEGORY_SCHEMA_LABELS, "starred"); + * gdata_entry_add_category (GDATA_ENTRY (document), starred_category); + * g_object_unref (starred_category); + * + * /* Propagate the updated document to the server */ + * updated_document = GDATA_DOCUMENTS_ENTRY (gdata_service_update_entry (GDATA_SERVICE (service), + * gdata_documents_service_get_primary_authorization_domain (), + * GDATA_ENTRY (document), NULL, &error)); + * + * g_object_unref (document); + * g_object_unref (service); + * + * if (error != NULL) { + * g_error ("Error starring document: %s", error->message); + * g_error_free (error); + * return; + * } + * + * /* Do something with the newly-starred document, like update it in the UI */ + * + * g_object_unref (updated_document); + * + * + * + * Since: 0.4.0 + */ + +#include +#include +#include +#include +#include + +#include "gdata-documents-property.h" +#include "gdata-documents-service.h" +#include "gdata-documents-utils.h" +#include "gdata-batchable.h" +#include "gdata-service.h" +#include "gdata-private.h" +#include "gdata-upload-stream.h" + +GQuark +gdata_documents_service_error_quark (void) +{ + return g_quark_from_static_string ("gdata-documents-service-error-quark"); +} + +static void append_query_headers (GDataService *self, GDataAuthorizationDomain *domain, SoupMessage *message); +static GList *get_authorization_domains (void); +static gchar *_get_upload_uri_for_query_and_folder (GDataDocumentsUploadQuery *query, + GDataDocumentsFolder *folder) G_GNUC_WARN_UNUSED_RESULT G_GNUC_MALLOC; + +_GDATA_DEFINE_AUTHORIZATION_DOMAIN (documents, "writely", "https://www.googleapis.com/auth/drive") +_GDATA_DEFINE_AUTHORIZATION_DOMAIN (spreadsheets, "wise", "https://spreadsheets.google.com/feeds/") +G_DEFINE_TYPE_WITH_CODE (GDataDocumentsService, gdata_documents_service, GDATA_TYPE_SERVICE, G_IMPLEMENT_INTERFACE (GDATA_TYPE_BATCHABLE, NULL)) + +static void +gdata_documents_service_class_init (GDataDocumentsServiceClass *klass) +{ + GDataServiceClass *service_class = GDATA_SERVICE_CLASS (klass); + service_class->feed_type = GDATA_TYPE_DOCUMENTS_FEED; + + service_class->append_query_headers = append_query_headers; + service_class->get_authorization_domains = get_authorization_domains; + + service_class->api_version = "3"; +} + +static void +gdata_documents_service_init (GDataDocumentsService *self) +{ + /* Nothing to see here */ +} + +static void +append_query_headers (GDataService *self, GDataAuthorizationDomain *domain, SoupMessage *message) +{ + g_assert (message != NULL); + + if (message->method == SOUP_METHOD_POST && soup_message_headers_get_one (message->request_headers, "X-Upload-Content-Length") == NULL) { + gchar *upload_uri; + const gchar *v3_pos; + + upload_uri = soup_uri_to_string (soup_message_get_uri (message), FALSE); + v3_pos = strstr (upload_uri, "://docs.google.com/feeds/upload/create-session/default/private/full"); + + if (v3_pos != NULL) { + gchar *v2_upload_uri; + SoupURI *_v2_upload_uri; + + /* Content length header for resumable uploads. Only set it if this looks like the initial request of a resumable upload, and + * if no content length has been set previously. + * This allows methods like gdata_service_insert_entry() (which aren't resumable-upload-aware) to continue working for creating + * documents with metadata only, by simulating the initial request of a resumable upload as described here: + * https://developers.google.com/google-apps/documents-list/#creating_a_new_document_or_file_with_metadata_only */ + soup_message_headers_replace (message->request_headers, "X-Upload-Content-Length", "0"); + + /* Also set the encoding to be content length encoding. */ + soup_message_headers_set_encoding (message->request_headers, SOUP_ENCODING_CONTENT_LENGTH); + + /* HACK: Work around http://code.google.com/a/google.com/p/apps-api-issues/issues/detail?id=3033 by changing the upload URI + * to the v2 API's upload URI. Grrr. */ + v2_upload_uri = g_strconcat (_gdata_service_get_scheme (), "://docs.google.com/feeds/default/private/full", + v3_pos + strlen ("://docs.google.com/feeds/upload/create-session/default/private/full"), NULL); + _v2_upload_uri = soup_uri_new (v2_upload_uri); + soup_message_set_uri (message, _v2_upload_uri); + soup_uri_free (_v2_upload_uri); + g_free (v2_upload_uri); + } + + g_free (upload_uri); + } + + /* Chain up to the parent class */ + GDATA_SERVICE_CLASS (gdata_documents_service_parent_class)->append_query_headers (self, domain, message); +} + +static GList * +get_authorization_domains (void) +{ + GList *authorization_domains = NULL; + + authorization_domains = g_list_prepend (authorization_domains, get_documents_authorization_domain ()); + authorization_domains = g_list_prepend (authorization_domains, get_spreadsheets_authorization_domain ()); + + return authorization_domains; +} + +/** + * gdata_documents_service_new: + * @authorizer: (allow-none): a #GDataAuthorizer to authorize the service's requests, or %NULL + * + * Creates a new #GDataDocumentsService using the given #GDataAuthorizer. If @authorizer is %NULL, all requests are made as an unauthenticated user. + * + * Return value: a new #GDataDocumentsService, or %NULL; unref with g_object_unref() + * + * Since: 0.9.0 + */ +GDataDocumentsService * +gdata_documents_service_new (GDataAuthorizer *authorizer) +{ + g_return_val_if_fail (authorizer == NULL || GDATA_IS_AUTHORIZER (authorizer), NULL); + + return g_object_new (GDATA_TYPE_DOCUMENTS_SERVICE, + "authorizer", authorizer, + NULL); +} + +/** + * gdata_documents_service_get_primary_authorization_domain: + * + * The primary #GDataAuthorizationDomain for interacting with Google Documents. This will not normally need to be used, as it's used internally + * by the #GDataDocumentsService methods. However, if using the plain #GDataService methods to implement custom queries or requests which libgdata + * does not support natively, then this domain may be needed to authorize the requests. + * + * The domain never changes, and is interned so that pointer comparison can be used to differentiate it from other authorization domains. + * + * Return value: (transfer none): the service's authorization domain + * + * Since: 0.9.0 + */ +GDataAuthorizationDomain * +gdata_documents_service_get_primary_authorization_domain (void) +{ + return get_documents_authorization_domain (); +} + +/** + * gdata_documents_service_get_spreadsheet_authorization_domain: + * + * The #GDataAuthorizationDomain for interacting with spreadsheet data. This will not normally need to be used, as it's automatically used internally + * by the #GDataDocumentsService methods. However, if using the plain #GDataService methods to implement custom queries or requests which libgdata + * does not support natively, then this domain may be needed to authorize the requests which pertain to the Google Spreadsheets Data API, such as + * requests to download or upload spreadsheet documents. + * + * The domain never changes, and is interned so that pointer comparison can be used to differentiate it from other authorization domains. + * + * Return value: (transfer none): the service's authorization domain + * + * Since: 0.9.0 + */ +GDataAuthorizationDomain * +gdata_documents_service_get_spreadsheet_authorization_domain (void) +{ + return get_spreadsheets_authorization_domain (); +} + +/** + * gdata_documents_service_get_metadata: + * @self: a #GDataDocumentsService + * @cancellable: (allow-none): optional #GCancellable object, or %NULL + * @error: a #GError, or %NULL + * + * Gets a #GDataDocumentsMetadata object containing metadata about the documents + * service itself, like how large the user quota is. + * + * Return value: (transfer full): the service's metadata object; unref with g_object_unref() + * + * Since: 0.17.9 + */ +GDataDocumentsMetadata * +gdata_documents_service_get_metadata (GDataDocumentsService *self, GCancellable *cancellable, GError **error) +{ + GDataDocumentsMetadata *metadata; + const gchar *uri = "https://www.googleapis.com/drive/v2/about"; + SoupMessage *message; + guint status; + + g_return_val_if_fail (GDATA_IS_DOCUMENTS_SERVICE (self), NULL); + g_return_val_if_fail (cancellable == NULL || G_IS_CANCELLABLE (cancellable), NULL); + g_return_val_if_fail (error == NULL || *error == NULL, NULL); + + message = _gdata_service_build_message (GDATA_SERVICE (self), get_documents_authorization_domain (), SOUP_METHOD_GET, uri, NULL, FALSE); + + /* Send the message */ + status = _gdata_service_send_message (GDATA_SERVICE (self), message, cancellable, error); + + if (status == SOUP_STATUS_NONE || status == SOUP_STATUS_CANCELLED) { + /* Redirect error or cancelled */ + g_object_unref (message); + return NULL; + } else if (status != SOUP_STATUS_OK) { + /* Error */ + GDataServiceClass *klass = GDATA_SERVICE_GET_CLASS (self); + g_assert (klass->parse_error_response != NULL); + klass->parse_error_response (GDATA_SERVICE (self), GDATA_OPERATION_QUERY, status, message->reason_phrase, message->response_body->data, + message->response_body->length, error); + g_object_unref (message); + return NULL; + } + + /* Parse the JSON; and update the entry */ + g_assert (message->response_body->data != NULL); + metadata = GDATA_DOCUMENTS_METADATA (gdata_parsable_new_from_json (GDATA_TYPE_DOCUMENTS_METADATA, message->response_body->data, message->response_body->length, + error)); + g_object_unref (message); + + return metadata; +} + +static void +get_metadata_thread (GTask *task, gpointer source_object, gpointer task_data, GCancellable *cancellable) +{ + GDataDocumentsService *service = GDATA_DOCUMENTS_SERVICE (source_object); + g_autoptr(GDataDocumentsMetadata) metadata = NULL; + g_autoptr(GError) error = NULL; + + /* Copy the metadata and return */ + metadata = gdata_documents_service_get_metadata (service, cancellable, &error); + if (error != NULL) + g_task_return_error (task, g_steal_pointer (&error)); + else + g_task_return_pointer (task, g_steal_pointer (&metadata), g_object_unref); +} + +/** + * gdata_documents_service_get_metadata_async: + * @self: a #GDataDocumentsService + * @cancellable: (allow-none): optional #GCancellable object, or %NULL + * @callback: a #GAsyncReadyCallback to call when the operation is finished, or %NULL + * @user_data: (closure): data to pass to the @callback function + * + * Gets a #GDataDocumentsMetadata object containing metadata about the documents + * service itself, like how large the user quota is. + * + * For more details, see gdata_documents_service_get_metadata(), which is the synchronous version of this function. + * + * When the operation is finished, @callback will be called. You can then call gdata_documents_service_get_metadata_finish() to get the results + * of the operation. + * + * Since: 0.17.9 + */ +void +gdata_documents_service_get_metadata_async (GDataDocumentsService *self, GCancellable *cancellable, + GAsyncReadyCallback callback, gpointer user_data) +{ + g_autoptr(GTask) task = NULL; + + g_return_if_fail (GDATA_IS_DOCUMENTS_SERVICE (self)); + g_return_if_fail (cancellable == NULL || G_IS_CANCELLABLE (cancellable)); + + task = g_task_new (self, cancellable, callback, user_data); + g_task_set_source_tag (task, gdata_documents_service_get_metadata_async); + g_task_run_in_thread (task, get_metadata_thread); +} + +/** + * gdata_documents_service_get_metadata_finish: + * @self: a #GDataDocumentsService + * @async_result: a #GAsyncResult + * @error: a #GError, or %NULL + * + * Finish an asynchronous operation to get a #GDataDocumentsMetadata started with gdata_documents_service_get_metadata_async(). + * + * Return value: (transfer full): the service's metadata object; unref with g_object_unref() + * + * Since: 0.17.9 + */ +GDataDocumentsMetadata * +gdata_documents_service_get_metadata_finish (GDataDocumentsService *self, GAsyncResult *async_result, GError **error) +{ + g_return_val_if_fail (GDATA_IS_DOCUMENTS_SERVICE (self), NULL); + g_return_val_if_fail (G_IS_ASYNC_RESULT (async_result), NULL); + g_return_val_if_fail (error == NULL || *error == NULL, NULL); + g_return_val_if_fail (g_task_is_valid (async_result, self), NULL); + g_return_val_if_fail (g_async_result_is_tagged (async_result, gdata_documents_service_get_metadata_async), NULL); + + return g_task_propagate_pointer (G_TASK (async_result), error); +} + +static gchar * +_query_documents_build_request_uri (GDataDocumentsQuery *query) +{ + /* If we want to query for documents contained in a folder, the URI is different. + * The "/[folder:id]" suffix is added by the GDataQuery later. */ + return g_strdup ("https://www.googleapis.com/drive/v2/files"); +} + +/** + * gdata_documents_service_query_documents: + * @self: a #GDataDocumentsService + * @query: (allow-none): a #GDataDocumentsQuery with the query parameters, or %NULL + * @cancellable: (allow-none): optional #GCancellable object, or %NULL + * @progress_callback: (allow-none) (scope call) (closure progress_user_data): a #GDataQueryProgressCallback to call when an entry is loaded, or %NULL + * @progress_user_data: (closure): data to pass to the @progress_callback function + * @error: a #GError, or %NULL + * + * Queries the service to return a list of documents matching the given @query. Note that @query has to be a #GDataDocumentsQuery, rather than just + * a #GDataQuery, as it uses the folder ID specified in #GDataDocumentsQuery:folder-id. + * + * For more details, see gdata_service_query(). + * + * Return value: (transfer full): a #GDataDocumentsFeed of query results; unref with g_object_unref() + * + * Since: 0.4.0 + */ +GDataDocumentsFeed * +gdata_documents_service_query_documents (GDataDocumentsService *self, GDataDocumentsQuery *query, GCancellable *cancellable, + GDataQueryProgressCallback progress_callback, gpointer progress_user_data, + GError **error) +{ + GDataFeed *feed; + gchar *request_uri; + + g_return_val_if_fail (GDATA_IS_DOCUMENTS_SERVICE (self), NULL); + g_return_val_if_fail (query == NULL || GDATA_IS_DOCUMENTS_QUERY (query), NULL); + g_return_val_if_fail (cancellable == NULL || G_IS_CANCELLABLE (cancellable), NULL); + g_return_val_if_fail (error == NULL || *error == NULL, NULL); + + /* Ensure we're authenticated first */ + if (gdata_authorizer_is_authorized_for_domain (gdata_service_get_authorizer (GDATA_SERVICE (self)), + get_documents_authorization_domain ()) == FALSE) { + g_set_error_literal (error, GDATA_SERVICE_ERROR, GDATA_SERVICE_ERROR_AUTHENTICATION_REQUIRED, + _("You must be authenticated to query documents.")); + return NULL; + } + + request_uri = _query_documents_build_request_uri (query); + feed = gdata_service_query (GDATA_SERVICE (self), get_documents_authorization_domain (), request_uri, GDATA_QUERY (query), + GDATA_TYPE_DOCUMENTS_ENTRY, cancellable, progress_callback, progress_user_data, error); + g_free (request_uri); + + return GDATA_DOCUMENTS_FEED (feed); +} + +/** + * gdata_documents_service_query_documents_async: + * @self: a #GDataDocumentsService + * @query: (allow-none): a #GDataDocumentsQuery with the query parameters, or %NULL + * @cancellable: (allow-none): optional #GCancellable object, or %NULL + * @progress_callback: (allow-none) (closure progress_user_data): a #GDataQueryProgressCallback to call when an entry is loaded, or %NULL + * @progress_user_data: (closure): data to pass to the @progress_callback function + * @destroy_progress_user_data: (allow-none): the function to call when @progress_callback will not be called any more, or %NULL. This function will be + * called with @progress_user_data as a parameter and can be used to free any memory allocated for it. + * @callback: a #GAsyncReadyCallback to call when authentication is finished + * @user_data: (closure): data to pass to the @callback function + * + * Queries the service to return a list of documents matching the given @query. @self and + * @query are both reffed when this function is called, so can safely be unreffed after this function returns. + * + * For more details, see gdata_documents_service_query_documents(), which is the synchronous version of this function, + * and gdata_service_query_async(), which is the base asynchronous query function. + * + * Since: 0.9.1 + */ +void +gdata_documents_service_query_documents_async (GDataDocumentsService *self, GDataDocumentsQuery *query, GCancellable *cancellable, + GDataQueryProgressCallback progress_callback, gpointer progress_user_data, + GDestroyNotify destroy_progress_user_data, + GAsyncReadyCallback callback, gpointer user_data) +{ + gchar *request_uri; + + g_return_if_fail (GDATA_IS_DOCUMENTS_SERVICE (self)); + g_return_if_fail (query == NULL || GDATA_IS_DOCUMENTS_QUERY (query)); + g_return_if_fail (cancellable == NULL || G_IS_CANCELLABLE (cancellable)); + g_return_if_fail (callback != NULL); + + /* Ensure we're authenticated first */ + if (gdata_authorizer_is_authorized_for_domain (gdata_service_get_authorizer (GDATA_SERVICE (self)), + get_documents_authorization_domain ()) == FALSE) { + g_autoptr(GTask) task = NULL; + + task = g_task_new (self, cancellable, callback, user_data); + g_task_set_source_tag (task, gdata_service_query_async); + g_task_return_new_error (task, GDATA_SERVICE_ERROR, GDATA_SERVICE_ERROR_AUTHENTICATION_REQUIRED, "%s", + _("You must be authenticated to query documents.")); + + return; + } + + request_uri = _query_documents_build_request_uri (query); + gdata_service_query_async (GDATA_SERVICE (self), get_documents_authorization_domain (), request_uri, GDATA_QUERY (query), + GDATA_TYPE_DOCUMENTS_ENTRY, cancellable, progress_callback, progress_user_data, + destroy_progress_user_data, callback, user_data); + g_free (request_uri); +} + +static void +add_folder_link_to_entry (GDataDocumentsEntry *entry, GDataDocumentsFolder *folder) +{ + GDataLink *_link; + const gchar *id; + gchar *uri; + + /* HACK: Build the GDataLink:uri from the ID by adding the prefix. */ + id = gdata_entry_get_id (GDATA_ENTRY (folder)); + uri = g_strconcat (GDATA_DOCUMENTS_URI_PREFIX, id, NULL); + _link = gdata_link_new (uri, GDATA_LINK_PARENT); + gdata_entry_add_link (GDATA_ENTRY (entry), _link); + g_object_unref (_link); + g_free (uri); +} + +static GDataUploadStream * +upload_update_document (GDataDocumentsService *self, GDataDocumentsDocument *document, const gchar *slug, const gchar *content_type, + GDataDocumentsFolder *folder, goffset content_length, const gchar *method, const gchar *upload_uri, + GCancellable *cancellable) +{ + /* HACK: Corrects a bug on spreadsheet content types handling + * The content type for ODF spreadsheets is "application/vnd.oasis.opendocument.spreadsheet" for my ODF spreadsheet; + * but Google Documents' spreadsheet service is waiting for "application/x-vnd.oasis.opendocument.spreadsheet" + * and nothing else. + * Bug filed with Google: http://code.google.com/p/gdata-issues/issues/detail?id=1127 */ + if (strcmp (content_type, "application/vnd.oasis.opendocument.spreadsheet") == 0) + content_type = "application/x-vnd.oasis.opendocument.spreadsheet"; + + if (folder != NULL) + add_folder_link_to_entry (GDATA_DOCUMENTS_ENTRY (document), folder); + + /* We need streaming file I/O: GDataUploadStream */ + if (content_length == -1) { + /* Non-resumable upload. */ + return GDATA_UPLOAD_STREAM (gdata_upload_stream_new (GDATA_SERVICE (self), get_documents_authorization_domain (), method, upload_uri, + GDATA_ENTRY (document), slug, content_type, cancellable)); + } else { + /* Resumable upload. */ + return GDATA_UPLOAD_STREAM (gdata_upload_stream_new_resumable (GDATA_SERVICE (self), get_documents_authorization_domain (), method, + upload_uri, GDATA_ENTRY (document), slug, content_type, content_length, + cancellable)); + } +} + +static gboolean +_upload_checks (GDataDocumentsService *self, GDataDocumentsDocument *document, GError **error) +{ + if (gdata_authorizer_is_authorized_for_domain (gdata_service_get_authorizer (GDATA_SERVICE (self)), + get_documents_authorization_domain ()) == FALSE) { + g_set_error_literal (error, GDATA_SERVICE_ERROR, GDATA_SERVICE_ERROR_AUTHENTICATION_REQUIRED, + _("You must be authenticated to upload documents.")); + return FALSE; + } + + if (document != NULL && gdata_entry_is_inserted (GDATA_ENTRY (document)) == TRUE) { + g_set_error_literal (error, GDATA_SERVICE_ERROR, GDATA_SERVICE_ERROR_ENTRY_ALREADY_INSERTED, + _("The document has already been uploaded.")); + return FALSE; + } + + return TRUE; +} + +/** + * gdata_documents_service_upload_document: + * @self: an authenticated #GDataDocumentsService + * @document: (allow-none): the #GDataDocumentsDocument to insert, or %NULL + * @slug: the filename to give to the uploaded document + * @content_type: the content type of the uploaded data + * @folder: (allow-none): the folder to which the document should be uploaded, or %NULL + * @cancellable: (allow-none): a #GCancellable for the entire upload stream, or %NULL + * @error: a #GError, or %NULL + * + * Uploads a document to Google Documents, using the properties from @document and the document data written to the resulting #GDataUploadStream. If + * the document data does not need to be provided at the moment, just the metadata, use gdata_service_insert_entry() instead (e.g. in the case of + * creating a new, empty file to be edited at a later date). + * + * This performs a non-resumable upload, unlike gdata_documents_service_upload_document(). This means that errors during transmission will cause the + * upload to fail, and the entire document will have to be re-uploaded. It is recommended that gdata_documents_service_upload_document_resumable() + * be used instead. + * + * If @document is %NULL, only the document data will be uploaded. The new document entry will be named using @slug, and will have default metadata. + * + * The stream returned by this function should be written to using the standard #GOutputStream methods, asynchronously or synchronously. Once the stream + * is closed (using g_output_stream_close()), gdata_documents_service_finish_upload() should be called on it to parse and return the updated + * #GDataDocumentsDocument for the document. This must be done, as @document isn't updated in-place. + * + * In order to cancel the upload, a #GCancellable passed in to @cancellable must be cancelled using g_cancellable_cancel(). Cancelling the individual + * #GOutputStream operations on the #GDataUploadStream will not cancel the entire upload; merely the write or close operation in question. See the + * #GDataUploadStream:cancellable for more details. + * + * Any upload errors will be thrown by the stream methods, and may come from the #GDataServiceError domain. + * + * Return value: (transfer full): a #GDataUploadStream to write the document data to, or %NULL; unref with g_object_unref() + * + * Since: 0.8.0 + */ +GDataUploadStream * +gdata_documents_service_upload_document (GDataDocumentsService *self, GDataDocumentsDocument *document, const gchar *slug, const gchar *content_type, + GDataDocumentsFolder *folder, GCancellable *cancellable, GError **error) +{ + GDataUploadStream *upload_stream; + gchar *upload_uri; + gchar *upload_uri_prefix; + + g_return_val_if_fail (GDATA_IS_DOCUMENTS_SERVICE (self), NULL); + g_return_val_if_fail (document == NULL || GDATA_IS_DOCUMENTS_DOCUMENT (document), NULL); + g_return_val_if_fail (slug != NULL && *slug != '\0', NULL); + g_return_val_if_fail (content_type != NULL && *content_type != '\0', NULL); + g_return_val_if_fail (folder == NULL || GDATA_IS_DOCUMENTS_FOLDER (folder), NULL); + g_return_val_if_fail (cancellable == NULL || G_IS_CANCELLABLE (cancellable), NULL); + g_return_val_if_fail (error == NULL || *error == NULL, NULL); + + if (_upload_checks (self, document, error) == FALSE) { + return NULL; + } + + upload_uri_prefix = gdata_documents_service_get_upload_uri (folder); + upload_uri = g_strconcat (upload_uri_prefix, "?uploadType=multipart", NULL); + upload_stream = upload_update_document (self, document, slug, content_type, folder, -1, SOUP_METHOD_POST, upload_uri, cancellable); + g_free (upload_uri); + g_free (upload_uri_prefix); + + return upload_stream; +} + +/** + * gdata_documents_service_upload_document_resumable: + * @self: an authenticated #GDataDocumentsService + * @document: (allow-none): the #GDataDocumentsDocument to insert, or %NULL + * @slug: the filename to give to the uploaded document + * @content_type: the content type of the uploaded data + * @content_length: the size (in bytes) of the file being uploaded + * @query: (allow-none): a query specifying parameters for the upload, or %NULL + * @cancellable: (allow-none): a #GCancellable for the entire upload stream, or %NULL + * @error: a #GError, or %NULL + * + * Uploads a document to Google Documents, using the properties from @document and the document data written to the resulting #GDataUploadStream. If + * the document data does not need to be provided at the moment, just the metadata, use gdata_service_insert_entry() instead (e.g. in the case of + * creating a new, empty file to be edited at a later date). + * + * Unlike gdata_documents_service_upload_document(), this method performs a + * resumable upload which allows for correction of + * transmission errors without re-uploading the entire file. Use of this method is preferred over gdata_documents_service_upload_document(). + * + * If @document is %NULL, only the document data will be uploaded. The new document entry will be named using @slug, and will have default metadata. + * + * If non-%NULL, the @query specifies parameters for the upload, such as a #GDataDocumentsFolder to upload the document into; and whether to treat + * the document as an opaque file, or convert it to a standard format. If @query is %NULL, the document will be uploaded into the root folder, and + * automatically converted to a standard format. No OCR or automatic language translation will be performed by default. + * + * If @query is non-%NULL and #GDataDocumentsUploadQuery:convert is %FALSE, @document must be an instance of #GDataDocumentsDocument. Otherwise, + * @document must be a subclass of it, such as #GDataDocumentsPresentation. + * + * The stream returned by this function should be written to using the standard #GOutputStream methods, asynchronously or synchronously. Once the stream + * is closed (using g_output_stream_close()), gdata_documents_service_finish_upload() should be called on it to parse and return the updated + * #GDataDocumentsDocument for the document. This must be done, as @document isn't updated in-place. + * + * In order to cancel the upload, a #GCancellable passed in to @cancellable must be cancelled using g_cancellable_cancel(). Cancelling the individual + * #GOutputStream operations on the #GDataUploadStream will not cancel the entire upload; merely the write or close operation in question. See the + * #GDataUploadStream:cancellable for more details. + * + * Any upload errors will be thrown by the stream methods, and may come from the #GDataServiceError domain. + * + * Return value: (transfer full): a #GDataUploadStream to write the document data to, or %NULL; unref with g_object_unref() + * + * Since: 0.13.0 + */ +GDataUploadStream * +gdata_documents_service_upload_document_resumable (GDataDocumentsService *self, GDataDocumentsDocument *document, const gchar *slug, + const gchar *content_type, goffset content_length, GDataDocumentsUploadQuery *query, + GCancellable *cancellable, GError **error) +{ + GDataUploadStream *upload_stream; + gchar *upload_uri; + + g_return_val_if_fail (GDATA_IS_DOCUMENTS_SERVICE (self), NULL); + g_return_val_if_fail (document == NULL || GDATA_IS_DOCUMENTS_DOCUMENT (document), NULL); + g_return_val_if_fail (slug != NULL && *slug != '\0', NULL); + g_return_val_if_fail (content_type != NULL && *content_type != '\0', NULL); + g_return_val_if_fail (query == NULL || GDATA_IS_DOCUMENTS_UPLOAD_QUERY (query), NULL); + g_return_val_if_fail (cancellable == NULL || G_IS_CANCELLABLE (cancellable), NULL); + g_return_val_if_fail (error == NULL || *error == NULL, NULL); + + if (_upload_checks (self, document, error) == FALSE) { + return NULL; + } + + upload_uri = _get_upload_uri_for_query_and_folder (query, NULL); + upload_stream = upload_update_document (self, document, slug, content_type, NULL, content_length, SOUP_METHOD_POST, upload_uri, cancellable); + g_free (upload_uri); + + return upload_stream; +} + +static gboolean +_update_checks (GDataDocumentsService *self, GError **error) +{ + if (gdata_authorizer_is_authorized_for_domain (gdata_service_get_authorizer (GDATA_SERVICE (self)), + get_documents_authorization_domain ()) == FALSE) { + g_set_error_literal (error, GDATA_SERVICE_ERROR, GDATA_SERVICE_ERROR_AUTHENTICATION_REQUIRED, + _("You must be authenticated to update documents.")); + return FALSE; + } + + return TRUE; +} + +/** + * gdata_documents_service_update_document: + * @self: a #GDataDocumentsService + * @document: the #GDataDocumentsDocument to update + * @slug: the filename to give to the uploaded document + * @content_type: the content type of the uploaded data + * @cancellable: (allow-none): a #GCancellable for the entire upload stream, or %NULL + * @error: a #GError, or %NULL + * + * Update the document using the properties from @document and the document data written to the resulting #GDataUploadStream. If the document data does + * not need to be changed, just the metadata, use gdata_service_update_entry() instead. + * + * This performs a non-resumable upload, unlike gdata_documents_service_update_document(). This means that errors during transmission will cause the + * upload to fail, and the entire document will have to be re-uploaded. It is recommended that gdata_documents_service_update_document_resumable() + * be used instead. + * + * The stream returned by this function should be written to using the standard #GOutputStream methods, asynchronously or synchronously. Once the stream + * is closed (using g_output_stream_close()), gdata_documents_service_finish_upload() should be called on it to parse and return the updated + * #GDataDocumentsDocument for the document. This must be done, as @document isn't updated in-place. + * + * In order to cancel the update, a #GCancellable passed in to @cancellable must be cancelled using g_cancellable_cancel(). Cancelling the individual + * #GOutputStream operations on the #GDataUploadStream will not cancel the entire update; merely the write or close operation in question. See the + * #GDataUploadStream:cancellable for more details. + * + * Any upload errors will be thrown by the stream methods, and may come from the #GDataServiceError domain. + * + * For more information, see gdata_service_update_entry(). + * + * Return value: (transfer full): a #GDataUploadStream to write the document data to; unref with g_object_unref() + * + * Since: 0.8.0 + */ +GDataUploadStream * +gdata_documents_service_update_document (GDataDocumentsService *self, GDataDocumentsDocument *document, const gchar *slug, const gchar *content_type, + GCancellable *cancellable, GError **error) +{ + GDataUploadStream *update_stream; + const gchar *id; + gchar *update_uri; + gchar *update_uri_prefix; + + g_return_val_if_fail (GDATA_IS_DOCUMENTS_SERVICE (self), NULL); + g_return_val_if_fail (GDATA_IS_DOCUMENTS_DOCUMENT (document), NULL); + g_return_val_if_fail (slug != NULL && *slug != '\0', NULL); + g_return_val_if_fail (content_type != NULL && *content_type != '\0', NULL); + g_return_val_if_fail (cancellable == NULL || G_IS_CANCELLABLE (cancellable), NULL); + g_return_val_if_fail (error == NULL || *error == NULL, NULL); + + if (_update_checks (self, error) == FALSE) { + return NULL; + } + + update_uri_prefix = gdata_documents_service_get_upload_uri (NULL); + id = gdata_entry_get_id (GDATA_ENTRY (document)); + update_uri = g_strconcat (update_uri_prefix, "/", id, "?uploadType=multipart", NULL); + update_stream = upload_update_document (self, document, slug, content_type, NULL, -1, SOUP_METHOD_PUT, update_uri, cancellable); + g_free (update_uri); + g_free (update_uri_prefix); + + return update_stream; +} + +/** + * gdata_documents_service_update_document_resumable: + * @self: a #GDataDocumentsService + * @document: the #GDataDocumentsDocument to update + * @slug: the filename to give to the uploaded document + * @content_type: the content type of the uploaded data + * @content_length: the size (in bytes) of the file being uploaded + * @cancellable: (allow-none): a #GCancellable for the entire upload stream, or %NULL + * @error: a #GError, or %NULL + * + * Update the document using the properties from @document and the document data written to the resulting #GDataUploadStream. If the document data does + * not need to be changed, just the metadata, use gdata_service_update_entry() instead. + * + * Unlike gdata_documents_service_update_document(), this method performs a + * resumable upload which allows for correction of + * transmission errors without re-uploading the entire file. Use of this method is preferred over gdata_documents_service_update_document(). + * + * The stream returned by this function should be written to using the standard #GOutputStream methods, asynchronously or synchronously. Once the stream + * is closed (using g_output_stream_close()), gdata_documents_service_finish_upload() should be called on it to parse and return the updated + * #GDataDocumentsDocument for the document. This must be done, as @document isn't updated in-place. + * + * In order to cancel the update, a #GCancellable passed in to @cancellable must be cancelled using g_cancellable_cancel(). Cancelling the individual + * #GOutputStream operations on the #GDataUploadStream will not cancel the entire update; merely the write or close operation in question. See the + * #GDataUploadStream:cancellable for more details. + * + * Any upload errors will be thrown by the stream methods, and may come from the #GDataServiceError domain. + * + * For more information, see gdata_service_update_entry(). + * + * Return value: (transfer full): a #GDataUploadStream to write the document data to; unref with g_object_unref() + * + * Since: 0.13.0 + */ +GDataUploadStream * +gdata_documents_service_update_document_resumable (GDataDocumentsService *self, GDataDocumentsDocument *document, const gchar *slug, + const gchar *content_type, goffset content_length, GCancellable *cancellable, GError **error) +{ + GDataLink *update_link; + + g_return_val_if_fail (GDATA_IS_DOCUMENTS_SERVICE (self), NULL); + g_return_val_if_fail (GDATA_IS_DOCUMENTS_DOCUMENT (document), NULL); + g_return_val_if_fail (slug != NULL && *slug != '\0', NULL); + g_return_val_if_fail (content_type != NULL && *content_type != '\0', NULL); + g_return_val_if_fail (cancellable == NULL || G_IS_CANCELLABLE (cancellable), NULL); + g_return_val_if_fail (error == NULL || *error == NULL, NULL); + + if (_update_checks (self, error) == FALSE) { + return NULL; + } + + update_link = gdata_entry_look_up_link (GDATA_ENTRY (document), GDATA_LINK_RESUMABLE_EDIT_MEDIA); + g_assert (update_link != NULL); + + return upload_update_document (self, document, slug, content_type, NULL, content_length, SOUP_METHOD_PUT, gdata_link_get_uri (update_link), + cancellable); +} + +/** + * gdata_documents_service_finish_upload: + * @self: a #GDataDocumentsService + * @upload_stream: the #GDataUploadStream from the operation + * @error: a #GError, or %NULL + * + * Finish off a document upload or update operation started by gdata_documents_service_upload_document() or gdata_documents_service_update_document(), + * parsing the result and returning the new or updated #GDataDocumentsDocument. + * + * If an error occurred during the upload or update operation, it will have been returned during the operation (e.g. by g_output_stream_splice() or one + * of the other stream methods). In such a case, %NULL will be returned but @error will remain unset. @error is only set in the case that the server + * indicates that the operation was successful, but an error is encountered in parsing the result sent by the server. + * + * In the case that no #GDataDocumentsDocument was passed (to gdata_documents_service_upload_document() or gdata_documents_service_update_document()) + * when starting the operation, %GDATA_DOCUMENTS_SERVICE_ERROR_INVALID_CONTENT_TYPE will be thrown in @error if the content type of the uploaded data + * could not be mapped to a document type with which to interpret the response from the server. + * + * Return value: (transfer full): the new or updated #GDataDocumentsDocument, or %NULL; unref with g_object_unref() + * + * Since: 0.8.0 + */ +GDataDocumentsDocument * +gdata_documents_service_finish_upload (GDataDocumentsService *self, GDataUploadStream *upload_stream, GError **error) +{ + const gchar *content_type; + const gchar *response_body; + gssize response_length; + GType new_document_type = G_TYPE_INVALID; + + /* Get and parse the response from the server */ + response_body = gdata_upload_stream_get_response (upload_stream, &response_length); + if (response_body == NULL || response_length == 0) { + /* Error will have been set by the upload stream. */ + return NULL; + } + + content_type = gdata_upload_stream_get_content_type (upload_stream); + new_document_type = gdata_documents_utils_get_type_from_content_type (content_type); + + if (g_type_is_a (new_document_type, GDATA_TYPE_DOCUMENTS_DOCUMENT) == FALSE) { + g_set_error (error, GDATA_DOCUMENTS_SERVICE_ERROR, GDATA_DOCUMENTS_SERVICE_ERROR_INVALID_CONTENT_TYPE, + _("The content type of the supplied document (‘%s’) could not be recognized."), + content_type); + return NULL; + } + + return GDATA_DOCUMENTS_DOCUMENT (gdata_parsable_new_from_json (new_document_type, response_body, (gint) response_length, error)); +} + +/** + * gdata_documents_service_copy_document: + * @self: an authenticated #GDataDocumentsService + * @document: the #GDataDocumentsDocument to copy + * @cancellable: (allow-none): optional #GCancellable object, or %NULL + * @error: a #GError, or %NULL + * + * Copy the given @document, producing a duplicate document in the same folder and returning its #GDataDocumentsDocument. + * + * Errors from #GDataServiceError can be returned for exceptional conditions, as determined by the server. + * + * Return value: (transfer full): the duplicate #GDataDocumentsDocument, or %NULL; unref with g_object_unref() + * + * Since: 0.13.1 + */ +GDataDocumentsDocument * +gdata_documents_service_copy_document (GDataDocumentsService *self, GDataDocumentsDocument *document, GCancellable *cancellable, GError **error) +{ + GDataDocumentsDocument *new_document; + GDataEntry *parent = NULL; + GList *i; + GList *parent_folders_list; + const gchar *parent_id = NULL; + + g_return_val_if_fail (GDATA_IS_DOCUMENTS_SERVICE (self), NULL); + g_return_val_if_fail (GDATA_IS_DOCUMENTS_DOCUMENT (document), NULL); + g_return_val_if_fail (cancellable == NULL || G_IS_CANCELLABLE (cancellable), NULL); + g_return_val_if_fail (error == NULL || *error == NULL, NULL); + + if (gdata_authorizer_is_authorized_for_domain (gdata_service_get_authorizer (GDATA_SERVICE (self)), + get_documents_authorization_domain ()) == FALSE) { + g_set_error_literal (error, GDATA_SERVICE_ERROR, GDATA_SERVICE_ERROR_AUTHENTICATION_REQUIRED, + _("You must be authenticated to copy documents.")); + return NULL; + } + + parent_folders_list = gdata_entry_look_up_links (GDATA_ENTRY (document), GDATA_LINK_PARENT); + for (i = parent_folders_list; i != NULL; i = i->next) { + GDataLink *_link = GDATA_LINK (i->data); + const gchar *id; + + id = gdata_documents_utils_get_id_from_link (_link); + if (id != NULL) { + parent_id = id; + break; + } + } + + g_list_free (parent_folders_list); + + if (parent_id == NULL) { + g_set_error_literal (error, GDATA_SERVICE_ERROR, GDATA_SERVICE_ERROR_NOT_FOUND, _("Parent folder not found")); + return NULL; + } + + parent = gdata_service_query_single_entry (GDATA_SERVICE (self), get_documents_authorization_domain (), parent_id, NULL, GDATA_TYPE_DOCUMENTS_FOLDER, cancellable, error); + if (parent == NULL) + return NULL; + + new_document = GDATA_DOCUMENTS_DOCUMENT (gdata_documents_service_add_entry_to_folder (self, GDATA_DOCUMENTS_ENTRY (document), GDATA_DOCUMENTS_FOLDER (parent), cancellable, error)); + g_object_unref (parent); + + return new_document; +} + +static void +copy_document_thread (GTask *task, gpointer source_object, gpointer task_data, GCancellable *cancellable) +{ + GDataDocumentsService *service = GDATA_DOCUMENTS_SERVICE (source_object); + GDataDocumentsDocument *document = task_data; + g_autoptr(GDataDocumentsDocument) new_document = NULL; + g_autoptr(GError) error = NULL; + + /* Copy the document and return */ + new_document = gdata_documents_service_copy_document (service, document, cancellable, &error); + if (error != NULL) + g_task_return_error (task, g_steal_pointer (&error)); + else + g_task_return_pointer (task, g_steal_pointer (&new_document), g_object_unref); +} + +/** + * gdata_documents_service_copy_document_async: + * @self: a #GDataDocumentsService + * @document: the #GDataDocumentsDocument to copy + * @cancellable: (allow-none): optional #GCancellable object, or %NULL + * @callback: a #GAsyncReadyCallback to call when the operation is finished, or %NULL + * @user_data: (closure): data to pass to the @callback function + * + * Copy the given @document, producing a duplicate document in the same folder and returning its #GDataDocumentsDocument. @self and @document are + * both reffed when this function is called, so can safely be unreffed after this function returns. + * + * For more details, see gdata_documents_service_copy_document(), which is the synchronous version of this function. + * + * When the operation is finished, @callback will be called. You can then call gdata_documents_service_copy_document_finish() to get the results + * of the operation. + * + * Since: 0.13.1 + */ +void +gdata_documents_service_copy_document_async (GDataDocumentsService *self, GDataDocumentsDocument *document, GCancellable *cancellable, + GAsyncReadyCallback callback, gpointer user_data) +{ + g_autoptr(GTask) task = NULL; + + g_return_if_fail (GDATA_IS_DOCUMENTS_SERVICE (self)); + g_return_if_fail (GDATA_IS_DOCUMENTS_DOCUMENT (document)); + g_return_if_fail (cancellable == NULL || G_IS_CANCELLABLE (cancellable)); + + task = g_task_new (self, cancellable, callback, user_data); + g_task_set_source_tag (task, gdata_documents_service_copy_document_async); + g_task_set_task_data (task, g_object_ref (document), (GDestroyNotify) g_object_unref); + g_task_run_in_thread (task, copy_document_thread); +} + +/** + * gdata_documents_service_copy_document_finish: + * @self: a #GDataDocumentsService + * @async_result: a #GAsyncResult + * @error: a #GError, or %NULL + * + * Finish an asynchronous operation to copy a #GDataDocumentsDocument started with gdata_documents_service_copy_document_async(). + * + * Return value: (transfer full): the duplicate #GDataDocumentsDocument, or %NULL; unref with g_object_unref() + * + * Since: 0.13.1 + */ +GDataDocumentsDocument * +gdata_documents_service_copy_document_finish (GDataDocumentsService *self, GAsyncResult *async_result, GError **error) +{ + g_return_val_if_fail (GDATA_IS_DOCUMENTS_SERVICE (self), NULL); + g_return_val_if_fail (G_IS_ASYNC_RESULT (async_result), NULL); + g_return_val_if_fail (error == NULL || *error == NULL, NULL); + g_return_val_if_fail (g_task_is_valid (async_result, self), NULL); + g_return_val_if_fail (g_async_result_is_tagged (async_result, gdata_documents_service_copy_document_async), NULL); + + return g_task_propagate_pointer (G_TASK (async_result), error); +} + +/** + * gdata_documents_service_add_entry_to_folder: + * @self: an authenticated #GDataDocumentsService + * @entry: the #GDataDocumentsEntry to copy + * @folder: the #GDataDocumentsFolder to copy @entry into + * @cancellable: (allow-none): optional #GCancellable object, or %NULL + * @error: a #GError, or %NULL + * + * Add the given @entry to the specified @folder, and return an updated #GDataDocumentsEntry for @entry. If the @entry is already in another folder, + * a copy will be added to the new folder. The copy and original will have different IDs. Note that @entry can't be a #GDataDocumentsFolder that + * already exists on the server. It can be a new #GDataDocumentsFolder, or a #GDataDocumentsDocument that is either new or already present on the + * server. + * + * Errors from #GDataServiceError can be returned for exceptional conditions, as determined by the server. + * + * Return value: (transfer full): an updated #GDataDocumentsEntry, or %NULL; unref with g_object_unref() + * + * Since: 0.8.0 + */ +GDataDocumentsEntry * +gdata_documents_service_add_entry_to_folder (GDataDocumentsService *self, GDataDocumentsEntry *entry, GDataDocumentsFolder *folder, + GCancellable *cancellable, GError **error) +{ + GDataDocumentsEntry *new_entry; + GDataDocumentsEntry *local_entry; + GDataOperationType operation_type; + GType entry_type; + const gchar *content_type; + const gchar *etag; + const gchar *title; + const gchar *uri_prefix = "https://www.googleapis.com/drive/v2/files"; + gchar *upload_data; + gchar *uri; + SoupMessage *message; + guint status; + GList *l; + + g_return_val_if_fail (GDATA_IS_DOCUMENTS_SERVICE (self), NULL); + g_return_val_if_fail (GDATA_IS_DOCUMENTS_ENTRY (entry), NULL); + g_return_val_if_fail (GDATA_IS_DOCUMENTS_FOLDER (folder), NULL); + g_return_val_if_fail (cancellable == NULL || G_IS_CANCELLABLE (cancellable), NULL); + g_return_val_if_fail (error == NULL || *error == NULL, NULL); + + if (gdata_authorizer_is_authorized_for_domain (gdata_service_get_authorizer (GDATA_SERVICE (self)), + get_documents_authorization_domain ()) == FALSE) { + g_set_error_literal (error, GDATA_SERVICE_ERROR, GDATA_SERVICE_ERROR_AUTHENTICATION_REQUIRED, + _("You must be authenticated to insert or move documents and folders.")); + return NULL; + } + + if (gdata_entry_is_inserted (GDATA_ENTRY (entry)) == TRUE) { + const gchar *id; + + id = gdata_entry_get_id (GDATA_ENTRY (entry)); + uri = g_strconcat (uri_prefix, "/", id, "/copy", NULL); + operation_type = GDATA_OPERATION_UPDATE; + } else { + uri = g_strdup (uri_prefix); + operation_type = GDATA_OPERATION_INSERTION; + } + + entry_type = G_OBJECT_TYPE (entry); + content_type = gdata_documents_utils_get_content_type (entry); + etag = gdata_entry_get_etag (GDATA_ENTRY (entry)); + title = gdata_entry_get_title (GDATA_ENTRY (entry)); + local_entry = g_object_new (entry_type, "etag", etag, "title", title, NULL); + gdata_documents_utils_add_content_type (local_entry, content_type); + add_folder_link_to_entry (local_entry, folder); + + for (l = gdata_documents_entry_get_document_properties (entry); l != NULL; l = l->next) { + GDataDocumentsProperty *old_prop; + g_autoptr(GDataDocumentsProperty) new_prop = NULL; + + old_prop = GDATA_DOCUMENTS_PROPERTY (l->data); + + new_prop = gdata_documents_property_new (gdata_documents_property_get_key (old_prop)); + gdata_documents_property_set_value (new_prop, gdata_documents_property_get_value (old_prop)); + gdata_documents_property_set_visibility (new_prop, gdata_documents_property_get_visibility (old_prop)); + gdata_documents_entry_add_documents_property (local_entry, new_prop); + } + + message = _gdata_service_build_message (GDATA_SERVICE (self), get_documents_authorization_domain (), SOUP_METHOD_POST, uri, NULL, FALSE); + g_free (uri); + + /* Append the data */ + upload_data = gdata_parsable_get_json (GDATA_PARSABLE (local_entry)); + soup_message_set_request (message, "application/json", SOUP_MEMORY_TAKE, upload_data, strlen (upload_data)); + g_object_unref (local_entry); + + /* Send the message */ + status = _gdata_service_send_message (GDATA_SERVICE (self), message, cancellable, error); + + if (status == SOUP_STATUS_NONE || status == SOUP_STATUS_CANCELLED) { + /* Redirect error or cancelled */ + g_object_unref (message); + return NULL; + } else if (status != SOUP_STATUS_OK) { + /* Error */ + GDataServiceClass *klass = GDATA_SERVICE_GET_CLASS (self); + g_assert (klass->parse_error_response != NULL); + klass->parse_error_response (GDATA_SERVICE (self), operation_type, status, message->reason_phrase, message->response_body->data, + message->response_body->length, error); + g_object_unref (message); + return NULL; + } + + /* Parse the JSON; and update the entry */ + g_assert (message->response_body->data != NULL); + new_entry = GDATA_DOCUMENTS_ENTRY (gdata_parsable_new_from_json (entry_type, message->response_body->data, message->response_body->length, + error)); + g_object_unref (message); + + return new_entry; +} + +typedef struct { + GDataDocumentsEntry *entry; + GDataDocumentsFolder *folder; +} AddEntryToFolderData; + +static void +add_entry_to_folder_data_free (AddEntryToFolderData *data) +{ + g_object_unref (data->entry); + g_object_unref (data->folder); + g_slice_free (AddEntryToFolderData, data); +} + +static void +add_entry_to_folder_thread (GTask *task, gpointer source_object, gpointer task_data, GCancellable *cancellable) +{ + GDataDocumentsService *service = GDATA_DOCUMENTS_SERVICE (source_object); + g_autoptr(GDataDocumentsEntry) updated_entry = NULL; + AddEntryToFolderData *data = task_data; + g_autoptr(GError) error = NULL; + + /* Add the entry to the folder and return */ + updated_entry = gdata_documents_service_add_entry_to_folder (service, data->entry, data->folder, cancellable, &error); + if (error != NULL) + g_task_return_error (task, g_steal_pointer (&error)); + else + g_task_return_pointer (task, g_steal_pointer (&updated_entry), (GDestroyNotify) g_object_unref); +} + +/** + * gdata_documents_service_add_entry_to_folder_async: + * @self: a #GDataDocumentsService + * @entry: the #GDataDocumentsEntry to add to @folder + * @folder: the #GDataDocumentsFolder to add @entry to + * @cancellable: (allow-none): optional #GCancellable object, or %NULL + * @callback: a #GAsyncReadyCallback to call when the operation is finished, or %NULL + * @user_data: (closure): data to pass to the @callback function + * + * Add the given @entry to the specified @folder. @self, @entry and @folder are all reffed when this function is called, so can safely be unreffed + * after this function returns. + * + * For more details, see gdata_documents_service_add_entry_to_folder(), which is the synchronous version of this function. + * + * When the operation is finished, @callback will be called. You can then call gdata_documents_service_add_entry_to_folder_finish() to get the results + * of the operation. + * + * Since: 0.8.0 + */ +void +gdata_documents_service_add_entry_to_folder_async (GDataDocumentsService *self, GDataDocumentsEntry *entry, GDataDocumentsFolder *folder, + GCancellable *cancellable, GAsyncReadyCallback callback, gpointer user_data) +{ + g_autoptr(GTask) task = NULL; + AddEntryToFolderData *data; + + g_return_if_fail (GDATA_IS_DOCUMENTS_SERVICE (self)); + g_return_if_fail (GDATA_IS_DOCUMENTS_ENTRY (entry)); + g_return_if_fail (GDATA_IS_DOCUMENTS_FOLDER (folder)); + g_return_if_fail (cancellable == NULL || G_IS_CANCELLABLE (cancellable)); + + data = g_slice_new (AddEntryToFolderData); + data->entry = g_object_ref (entry); + data->folder = g_object_ref (folder); + + task = g_task_new (self, cancellable, callback, user_data); + g_task_set_source_tag (task, gdata_documents_service_add_entry_to_folder_async); + g_task_set_task_data (task, g_steal_pointer (&data), (GDestroyNotify) add_entry_to_folder_data_free); + g_task_run_in_thread (task, add_entry_to_folder_thread); +} + +/** + * gdata_documents_service_add_entry_to_folder_finish: + * @self: a #GDataDocumentsService + * @async_result: a #GAsyncResult + * @error: a #GError, or %NULL + * + * Finish an asynchronous operation to add a #GDataDocumentsEntry to a folder started with gdata_documents_service_add_entry_to_folder_async(). + * + * Return value: (transfer full): an updated #GDataDocumentsEntry, or %NULL; unref with g_object_unref() + * + * Since: 0.8.0 + */ +GDataDocumentsEntry * +gdata_documents_service_add_entry_to_folder_finish (GDataDocumentsService *self, GAsyncResult *async_result, GError **error) +{ + g_return_val_if_fail (GDATA_IS_DOCUMENTS_SERVICE (self), NULL); + g_return_val_if_fail (G_IS_ASYNC_RESULT (async_result), NULL); + g_return_val_if_fail (error == NULL || *error == NULL, NULL); + g_return_val_if_fail (g_task_is_valid (async_result, self), NULL); + g_return_val_if_fail (g_async_result_is_tagged (async_result, gdata_documents_service_add_entry_to_folder_async), NULL); + + return g_task_propagate_pointer (G_TASK (async_result), error); +} + +/** + * gdata_documents_service_remove_entry_from_folder: + * @self: a #GDataDocumentsService + * @entry: the #GDataDocumentsEntry to remove + * @folder: the #GDataDocumentsFolder from which we should remove @entry + * @cancellable: (allow-none): optional #GCancellable object, or %NULL + * @error: a #GError, or %NULL + * + * Remove the given @entry from @folder, and return an updated #GDataDocumentsEntry for @entry. @entry will remain a member of any other folders it's + * currently in. Note that @entry can be either a #GDataDocumentsDocument or a #GDataDocumentsFolder. + * + * Errors from #GDataServiceError can be returned for exceptional conditions, as determined by the server. + * + * Return value: (transfer full): an updated #GDataDocumentsEntry, or %NULL; unref with g_object_unref() + * + * Since: 0.8.0 + */ +GDataDocumentsEntry * +gdata_documents_service_remove_entry_from_folder (GDataDocumentsService *self, GDataDocumentsEntry *entry, GDataDocumentsFolder *folder, + GCancellable *cancellable, GError **error) +{ + const gchar *folder_id; + GList *i; + GList *parent_folders_list; + GDataLink *folder_link = NULL, *file_link = NULL; + GDataParsableClass *klass; + GDataAuthorizationDomain *domain; + gchar *fixed_uri, *modified_uri; + guint status; + gboolean req_status = TRUE; + SoupMessage *message; + + g_return_val_if_fail (GDATA_IS_DOCUMENTS_SERVICE (self), NULL); + g_return_val_if_fail (GDATA_IS_DOCUMENTS_ENTRY (entry), NULL); + g_return_val_if_fail (GDATA_IS_DOCUMENTS_FOLDER (folder), NULL); + g_return_val_if_fail (cancellable == NULL || G_IS_CANCELLABLE (cancellable), NULL); + g_return_val_if_fail (error == NULL || *error == NULL, NULL); + + if (gdata_authorizer_is_authorized_for_domain (gdata_service_get_authorizer (GDATA_SERVICE (self)), + get_documents_authorization_domain ()) == FALSE) { + g_set_error_literal (error, GDATA_SERVICE_ERROR, GDATA_SERVICE_ERROR_AUTHENTICATION_REQUIRED, + _("You must be authenticated to move documents and folders.")); + return NULL; + } + + domain = gdata_documents_service_get_primary_authorization_domain(); + + folder_id = gdata_entry_get_id (GDATA_ENTRY (folder)); + g_assert (folder_id != NULL); + + parent_folders_list = gdata_entry_look_up_links (GDATA_ENTRY (entry), GDATA_LINK_PARENT); + for (i = parent_folders_list; i != NULL; i = i->next) { + GDataLink *_link = GDATA_LINK (i->data); + const gchar *id; + + id = gdata_documents_utils_get_id_from_link (_link); + if (g_strcmp0 (folder_id, id) == 0) { + folder_link = _link; + break; + } + } + + g_list_free (parent_folders_list); + + if (folder_link == NULL) { + g_set_error_literal (error, + GDATA_SERVICE_ERROR, + GDATA_SERVICE_ERROR_NOT_FOUND, + _("Parent folder not found")); + return NULL; + } + + klass = GDATA_PARSABLE_GET_CLASS (entry); + + g_assert (klass->get_content_type != NULL); + if (g_strcmp0 (klass->get_content_type (), "application/json") == 0) { + file_link = gdata_entry_look_up_link (GDATA_ENTRY (entry), GDATA_LINK_SELF); + } else { + file_link = gdata_entry_look_up_link (GDATA_ENTRY (entry), GDATA_LINK_EDIT); + } + g_debug ("Link = %s", gdata_link_get_uri(file_link)); + g_assert (file_link != NULL); + + fixed_uri = _gdata_service_fix_uri_scheme (gdata_link_get_uri (file_link)); + modified_uri = g_strconcat (fixed_uri, "/parents/", folder_id, NULL); + + message = _gdata_service_build_message (GDATA_SERVICE (self), + domain, + SOUP_METHOD_DELETE, + modified_uri, + gdata_entry_get_etag (GDATA_ENTRY (entry)), + TRUE); + g_free (fixed_uri); + g_free (modified_uri); + + /* Send the message */ + status = _gdata_service_send_message (GDATA_SERVICE (self), message, cancellable, error); + + if (status == SOUP_STATUS_NONE || status == SOUP_STATUS_CANCELLED) { + /* Redirect error or cancelled */ + g_object_unref (message); + return NULL; + } else if (status != SOUP_STATUS_OK && status != SOUP_STATUS_NO_CONTENT) { + /* Error */ + GDataServiceClass *service_klass = GDATA_SERVICE_GET_CLASS (self); + g_assert (service_klass->parse_error_response != NULL); + service_klass->parse_error_response (GDATA_SERVICE (self), + GDATA_OPERATION_DELETION, + status, + message->reason_phrase, + message->response_body->data, + message->response_body->length, + error); + req_status = FALSE; + } + + g_object_unref (message); + + if (req_status) { + /* Remove parent link from File's Data Entry */ + gdata_entry_remove_link (GDATA_ENTRY (entry), folder_link); + g_object_ref (entry); + return entry; + } else { + return NULL; + } +} + +typedef struct { + GDataDocumentsEntry *entry; + GDataDocumentsFolder *folder; +} RemoveEntryFromFolderData; + +static void +remove_entry_from_folder_data_free (RemoveEntryFromFolderData *data) +{ + g_object_unref (data->entry); + g_object_unref (data->folder); + g_slice_free (RemoveEntryFromFolderData, data); +} + +static void +remove_entry_from_folder_thread (GTask *task, gpointer source_object, gpointer task_data, GCancellable *cancellable) +{ + GDataDocumentsService *service = GDATA_DOCUMENTS_SERVICE (source_object); + g_autoptr(GDataDocumentsEntry) updated_entry = NULL; + RemoveEntryFromFolderData *data = task_data; + g_autoptr(GError) error = NULL; + + /* Remove the entry from the folder and return */ + updated_entry = gdata_documents_service_remove_entry_from_folder (service, data->entry, data->folder, cancellable, &error); + if (error != NULL) + g_task_return_error (task, g_steal_pointer (&error)); + else + g_task_return_pointer (task, g_steal_pointer (&updated_entry), g_object_unref); +} + +/** + * gdata_documents_service_remove_entry_from_folder_async: + * @self: a #GDataDocumentsService + * @entry: the #GDataDocumentsEntry to remove from @folder + * @folder: the #GDataDocumentsFolder to remove @entry from + * @cancellable: (allow-none): optional #GCancellable object, or %NULL + * @callback: a #GAsyncReadyCallback to call when the operation is finished, or %NULL + * @user_data: (closure): data to pass to the @callback function + * + * Remove the given @entry from the specified @folder. @self, @entry and @folder are all reffed when this function is called, so can safely be unreffed + * after this function returns. + * + * For more details, see gdata_documents_service_remove_entry_from_folder(), which is the synchronous version of this function. + * + * When the operation is finished, @callback will be called. You can then call gdata_documents_service_remove_entry_from_folder_finish() to get the + * results of the operation. + * + * Since: 0.8.0 + */ +void +gdata_documents_service_remove_entry_from_folder_async (GDataDocumentsService *self, GDataDocumentsEntry *entry, GDataDocumentsFolder *folder, + GCancellable *cancellable, GAsyncReadyCallback callback, gpointer user_data) +{ + g_autoptr(GTask) task = NULL; + RemoveEntryFromFolderData *data; + + g_return_if_fail (GDATA_IS_DOCUMENTS_SERVICE (self)); + g_return_if_fail (GDATA_IS_DOCUMENTS_ENTRY (entry)); + g_return_if_fail (GDATA_IS_DOCUMENTS_FOLDER (folder)); + g_return_if_fail (cancellable == NULL || G_IS_CANCELLABLE (cancellable)); + + data = g_slice_new (RemoveEntryFromFolderData); + data->entry = g_object_ref (entry); + data->folder = g_object_ref (folder); + + task = g_task_new (self, cancellable, callback, user_data); + g_task_set_source_tag (task, gdata_documents_service_remove_entry_from_folder_async); + g_task_set_task_data (task, g_steal_pointer (&data), (GDestroyNotify) remove_entry_from_folder_data_free); + g_task_run_in_thread (task, remove_entry_from_folder_thread); +} + +/** + * gdata_documents_service_remove_entry_from_folder_finish: + * @self: a #GDataDocumentsService + * @async_result: a #GAsyncResult + * @error: a #GError, or %NULL + * + * Finish an asynchronous operation to remove a #GDataDocumentsEntry from a folder started with + * gdata_documents_service_remove_entry_from_folder_async(). + * + * Return value: (transfer full): an updated #GDataDocumentsEntry, or %NULL; unref with g_object_unref() + * + * Since: 0.8.0 + */ +GDataDocumentsEntry * +gdata_documents_service_remove_entry_from_folder_finish (GDataDocumentsService *self, GAsyncResult *async_result, GError **error) +{ + g_return_val_if_fail (GDATA_IS_DOCUMENTS_SERVICE (self), NULL); + g_return_val_if_fail (G_IS_ASYNC_RESULT (async_result), NULL); + g_return_val_if_fail (error == NULL || *error == NULL, NULL); + g_return_val_if_fail (g_task_is_valid (async_result, self), NULL); + g_return_val_if_fail (g_async_result_is_tagged (async_result, gdata_documents_service_remove_entry_from_folder_async), NULL); + + return g_task_propagate_pointer (G_TASK (async_result), error); +} + +/* NOTE: query may be NULL. */ +static gchar * +_get_upload_uri_for_query_and_folder (GDataDocumentsUploadQuery *query, GDataDocumentsFolder *folder) +{ + if (query == NULL) { + query = gdata_documents_upload_query_new (); + } + + if (folder != NULL) { + gdata_documents_upload_query_set_folder (query, folder); + } + + return gdata_documents_upload_query_build_uri (query); +} + +/** + * gdata_documents_service_get_upload_uri: + * @folder: (allow-none): the #GDataDocumentsFolder into which to upload the document, or %NULL + * + * Gets the upload URI for documents for the service. + * + * If @folder is %NULL, the URI will be the one to upload documents to the "root" folder. + * + * Return value: the URI permitting the upload of documents to @folder, or %NULL; free with g_free() + * + * Since: 0.5.0 + */ +gchar * +gdata_documents_service_get_upload_uri (GDataDocumentsFolder *folder) +{ + g_return_val_if_fail (folder == NULL || GDATA_IS_DOCUMENTS_FOLDER (folder), NULL); + + /* Upload URI: https://developers.google.com/drive/web/manage-uploads */ + return g_strdup ("https://www.googleapis.com/upload/drive/v2/files"); +} diff --git a/gdata/services/documents/gdata-documents-service.h b/gdata/services/documents/gdata-documents-service.h new file mode 100644 index 0000000..ab2ea7e --- /dev/null +++ b/gdata/services/documents/gdata-documents-service.h @@ -0,0 +1,163 @@ +/* -*- Mode: C; indent-tabs-mode: t; c-basic-offset: 8; tab-width: 8 -*- */ +/* + * GData Client + * Copyright (C) Thibault Saunier 2009 + * + * GData Client is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * GData Client is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with GData Client. If not, see . + */ + +#ifndef GDATA_DOCUMENTS_SERVICE_H +#define GDATA_DOCUMENTS_SERVICE_H + +#include +#include +#include +#include +#include +#include +#include +#include + +G_BEGIN_DECLS + +/** + * GDataDocumentsServiceError: + * @GDATA_DOCUMENTS_SERVICE_ERROR_INVALID_CONTENT_TYPE: the content type of a provided file was invalid + * + * Error codes for #GDataDocumentsService operations. + * + * Since: 0.4.0 + */ +typedef enum { + GDATA_DOCUMENTS_SERVICE_ERROR_INVALID_CONTENT_TYPE +} GDataDocumentsServiceError; + +#define GDATA_TYPE_DOCUMENTS_SERVICE (gdata_documents_service_get_type ()) +#define GDATA_DOCUMENTS_SERVICE(o) (G_TYPE_CHECK_INSTANCE_CAST ((o), GDATA_TYPE_DOCUMENTS_SERVICE, GDataDocumentsService)) +#define GDATA_DOCUMENTS_SERVICE_CLASS(k) (G_TYPE_CHECK_CLASS_CAST((k), GDATA_TYPE_DOCUMENTS_SERVICE, GDataDocumentsServiceClass)) +#define GDATA_IS_DOCUMENTS_SERVICE(o) (G_TYPE_CHECK_INSTANCE_TYPE ((o), GDATA_TYPE_DOCUMENTS_SERVICE)) +#define GDATA_IS_DOCUMENTS_SERVICE_CLASS(k) (G_TYPE_CHECK_CLASS_TYPE ((k), GDATA_TYPE_DOCUMENTS_SERVICE)) +#define GDATA_DOCUMENTS_SERVICE_GET_CLASS(o) (G_TYPE_INSTANCE_GET_CLASS ((o), GDATA_TYPE_DOCUMENTS_SERVICE, GDataDocumentsServiceClass)) + +#define GDATA_DOCUMENTS_SERVICE_ERROR gdata_documents_service_error_quark () + +typedef struct _GDataDocumentsServicePrivate GDataDocumentsServicePrivate; + +/** + * GDataDocumentsService: + * + * All the fields in the #GDataDocumentsService structure are private and should never be accessed directly. + * + * Since: 0.4.0 + */ +typedef struct { + GDataService parent; + GDataDocumentsServicePrivate *priv; +} GDataDocumentsService; + +/** + * GDataDocumentsServiceClass: + * + * All the fields in the #GDataDocumentsServiceClass structure are private and should never be accessed directly. + * + * Since: 0.4.0 + */ +typedef struct { + /*< private >*/ + GDataServiceClass parent; + + /*< private >*/ + /* Padding for future expansion */ + void (*_g_reserved0) (void); + void (*_g_reserved1) (void); + void (*_g_reserved2) (void); + void (*_g_reserved3) (void); + void (*_g_reserved4) (void); + void (*_g_reserved5) (void); +} GDataDocumentsServiceClass; + +GType gdata_documents_service_get_type (void) G_GNUC_CONST; +GQuark gdata_documents_service_error_quark (void) G_GNUC_CONST; + +G_DEFINE_AUTOPTR_CLEANUP_FUNC (GDataDocumentsService, g_object_unref) + +GDataDocumentsService *gdata_documents_service_new (GDataAuthorizer *authorizer) G_GNUC_WARN_UNUSED_RESULT G_GNUC_MALLOC; + +GDataAuthorizationDomain *gdata_documents_service_get_primary_authorization_domain (void) G_GNUC_CONST; +GDataAuthorizationDomain *gdata_documents_service_get_spreadsheet_authorization_domain (void) G_GNUC_CONST; + +GDataDocumentsMetadata *gdata_documents_service_get_metadata (GDataDocumentsService *self, GCancellable *cancellable, + GError **error) G_GNUC_WARN_UNUSED_RESULT G_GNUC_MALLOC; +void gdata_documents_service_get_metadata_async (GDataDocumentsService *self, GCancellable *cancellable, + GAsyncReadyCallback callback, gpointer user_data); +GDataDocumentsMetadata *gdata_documents_service_get_metadata_finish (GDataDocumentsService *self, GAsyncResult *async_result, + GError **error) G_GNUC_WARN_UNUSED_RESULT G_GNUC_MALLOC; + +GDataDocumentsFeed *gdata_documents_service_query_documents (GDataDocumentsService *self, GDataDocumentsQuery *query, GCancellable *cancellable, + GDataQueryProgressCallback progress_callback, gpointer progress_user_data, + GError **error) G_GNUC_WARN_UNUSED_RESULT G_GNUC_MALLOC; +void gdata_documents_service_query_documents_async (GDataDocumentsService *self, GDataDocumentsQuery *query, GCancellable *cancellable, + GDataQueryProgressCallback progress_callback, gpointer progress_user_data, + GDestroyNotify destroy_progress_user_data, + GAsyncReadyCallback callback, gpointer user_data); + +#include +#include +#include + +GDataUploadStream *gdata_documents_service_upload_document (GDataDocumentsService *self, GDataDocumentsDocument *document, const gchar *slug, + const gchar *content_type, GDataDocumentsFolder *folder, + GCancellable *cancellable, GError **error) G_GNUC_WARN_UNUSED_RESULT G_GNUC_MALLOC; +GDataUploadStream *gdata_documents_service_upload_document_resumable (GDataDocumentsService *self, GDataDocumentsDocument *document, const gchar *slug, + const gchar *content_type, goffset content_length, + GDataDocumentsUploadQuery *query, + GCancellable *cancellable, GError **error) G_GNUC_WARN_UNUSED_RESULT G_GNUC_MALLOC; + +GDataUploadStream *gdata_documents_service_update_document (GDataDocumentsService *self, GDataDocumentsDocument *document, const gchar *slug, + const gchar *content_type, GCancellable *cancellable, + GError **error) G_GNUC_WARN_UNUSED_RESULT G_GNUC_MALLOC; +GDataUploadStream *gdata_documents_service_update_document_resumable (GDataDocumentsService *self, GDataDocumentsDocument *document, const gchar *slug, + const gchar *content_type, goffset content_length, GCancellable *cancellable, + GError **error) G_GNUC_WARN_UNUSED_RESULT G_GNUC_MALLOC; + +GDataDocumentsDocument *gdata_documents_service_finish_upload (GDataDocumentsService *self, GDataUploadStream *upload_stream, + GError **error) G_GNUC_WARN_UNUSED_RESULT G_GNUC_MALLOC; + +GDataDocumentsDocument *gdata_documents_service_copy_document (GDataDocumentsService *self, GDataDocumentsDocument *document, + GCancellable *cancellable, GError **error) G_GNUC_WARN_UNUSED_RESULT G_GNUC_MALLOC; +void gdata_documents_service_copy_document_async (GDataDocumentsService *self, GDataDocumentsDocument *document, GCancellable *cancellable, + GAsyncReadyCallback callback, gpointer user_data); +GDataDocumentsDocument *gdata_documents_service_copy_document_finish (GDataDocumentsService *self, GAsyncResult *async_result, + GError **error) G_GNUC_WARN_UNUSED_RESULT G_GNUC_MALLOC; + +GDataDocumentsEntry *gdata_documents_service_add_entry_to_folder (GDataDocumentsService *self, GDataDocumentsEntry *entry, + GDataDocumentsFolder *folder, GCancellable *cancellable, + GError **error) G_GNUC_WARN_UNUSED_RESULT G_GNUC_MALLOC; +void gdata_documents_service_add_entry_to_folder_async (GDataDocumentsService *self, GDataDocumentsEntry *entry, GDataDocumentsFolder *folder, + GCancellable *cancellable, GAsyncReadyCallback callback, gpointer user_data); +GDataDocumentsEntry *gdata_documents_service_add_entry_to_folder_finish (GDataDocumentsService *self, GAsyncResult *async_result, + GError **error) G_GNUC_WARN_UNUSED_RESULT G_GNUC_MALLOC; + +GDataDocumentsEntry *gdata_documents_service_remove_entry_from_folder (GDataDocumentsService *self, GDataDocumentsEntry *entry, + GDataDocumentsFolder *folder, GCancellable *cancellable, + GError **error) G_GNUC_WARN_UNUSED_RESULT G_GNUC_MALLOC; +void gdata_documents_service_remove_entry_from_folder_async (GDataDocumentsService *self, GDataDocumentsEntry *entry, GDataDocumentsFolder *folder, + GCancellable *cancellable, GAsyncReadyCallback callback, gpointer user_data); +GDataDocumentsEntry *gdata_documents_service_remove_entry_from_folder_finish (GDataDocumentsService *self, GAsyncResult *async_result, + GError **error) G_GNUC_WARN_UNUSED_RESULT G_GNUC_MALLOC; + +gchar *gdata_documents_service_get_upload_uri (GDataDocumentsFolder *folder) G_GNUC_WARN_UNUSED_RESULT G_GNUC_MALLOC; + +G_END_DECLS +#endif /* !GDATA_DOCUMENTS_SERVICE_H */ diff --git a/gdata/services/documents/gdata-documents-spreadsheet.c b/gdata/services/documents/gdata-documents-spreadsheet.c new file mode 100644 index 0000000..767689a --- /dev/null +++ b/gdata/services/documents/gdata-documents-spreadsheet.c @@ -0,0 +1,189 @@ +/* -*- Mode: C; indent-tabs-mode: t; c-basic-offset: 8; tab-width: 8 -*- */ +/* + * GData Client + * Copyright (C) Thibault Saunier 2009 + * Copyright (C) Philip Withnall 2010 + * Copyright (C) Red Hat, Inc. 2016 + * + * GData Client is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * GData Client is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with GData Client. If not, see . + */ + +/** + * SECTION:gdata-documents-spreadsheet + * @short_description: GData Documents spreadsheet object + * @stability: Stable + * @include: gdata/services/documents/gdata-documents-spreadsheet.h + * + * #GDataDocumentsSpreadsheet is a subclass of #GDataDocumentsDocument to represent a spreadsheet from Google Documents. + * + * For more details of Google Drive's GData API, see the + * online documentation. + * + * + * Downloading a Specific Sheet of a Spreadsheet + * + * GDataDocumentsService *service; + * GDataDocumentsSpreadsheet *spreadsheet; + * GFile *destination_file; + * guint gid; + * gchar *download_uri; + * GDataDownloadStream *download_stream; + * GFileOutputStream *output_stream; + * GError *error = NULL; + * + * /* Create a service and retrieve the spreadsheet and sheet index (GID) to download and the file to save the download in */ + * service = create_youtube_service (); + * spreadsheet = get_document_to_download (service); + * destination_file = query_user_for_destination_file (spreadsheet); + * gid = query_user_for_gid (spreadsheet); + * + * /* Create the download stream */ + * download_uri = gdata_documents_spreadsheet_get_download_uri (spreadsheet, GDATA_DOCUMENTS_SPREADSHEET_CSV, gid); + * download_stream = GDATA_DOWNLOAD_STREAM (gdata_download_stream_new (service, gdata_documents_service_get_spreadsheet_authorization_domain (), + * download_uri, NULL)); + * g_free (download_uri); + * + * g_object_unref (spreadsheet); + * g_object_unref (service); + * + * /* Create the file output stream */ + * output_stream = g_file_replace (destination_file, NULL, FALSE, G_FILE_CREATE_REPLACE_DESTINATION, NULL, &error); + * + * g_object_unref (destination_file); + * + * if (error != NULL) { + * g_error ("Error creating destination file: %s", error->message); + * g_error_free (error); + * g_object_unref (download_stream); + * return; + * } + * + * /* Download the document. This should almost always be done asynchronously. */ + * g_output_stream_splice (G_OUTPUT_STREAM (output_stream), G_INPUT_STREAM (download_stream), + * G_OUTPUT_STREAM_SPLICE_CLOSE_SOURCE | G_OUTPUT_STREAM_SPLICE_CLOSE_TARGET, NULL, &error); + * + * g_object_unref (output_stream); + * g_object_unref (download_stream); + * + * if (error != NULL) { + * g_error ("Error downloading spreadsheet: %s", error->message); + * g_error_free (error); + * return; + * } + * + * + * + * Since: 0.4.0 + */ + +#include +#include +#include +#include +#include + +#include "gdata-documents-spreadsheet.h" +#include "gdata-documents-utils.h" +#include "gdata-parser.h" +#include "gdata-private.h" + +static void gdata_documents_spreadsheet_constructed (GObject *object); + +G_DEFINE_TYPE (GDataDocumentsSpreadsheet, gdata_documents_spreadsheet, GDATA_TYPE_DOCUMENTS_DOCUMENT) + +static void +gdata_documents_spreadsheet_class_init (GDataDocumentsSpreadsheetClass *klass) +{ + GObjectClass *gobject_class = G_OBJECT_CLASS (klass); + GDataEntryClass *entry_class = GDATA_ENTRY_CLASS (klass); + + gobject_class->constructed = gdata_documents_spreadsheet_constructed; + entry_class->kind_term = "http://schemas.google.com/docs/2007#spreadsheet"; +} + +static void +gdata_documents_spreadsheet_init (GDataDocumentsSpreadsheet *self) +{ + /* Why am I writing it? */ +} + +static void +gdata_documents_spreadsheet_constructed (GObject *object) +{ + G_OBJECT_CLASS (gdata_documents_spreadsheet_parent_class)->constructed (object); + + if (!_gdata_parsable_is_constructed_from_xml (GDATA_PARSABLE (object))) + gdata_documents_utils_add_content_type (GDATA_DOCUMENTS_ENTRY (object), "application/vnd.google-apps.spreadsheet"); +} + +/** + * gdata_documents_spreadsheet_new: + * @id: (allow-none): the entry's ID (not the document ID of the spreadsheet), or %NULL + * + * Creates a new #GDataDocumentsSpreadsheet with the given entry ID (#GDataEntry:id). + * + * Return value: (transfer full): a new #GDataDocumentsSpreadsheet, or %NULL; unref with g_object_unref() + * + * Since: 0.4.0 + */ +GDataDocumentsSpreadsheet * +gdata_documents_spreadsheet_new (const gchar *id) +{ + return GDATA_DOCUMENTS_SPREADSHEET (g_object_new (GDATA_TYPE_DOCUMENTS_SPREADSHEET, "id", id, NULL)); +} + +/** + * gdata_documents_spreadsheet_get_download_uri: + * @self: a #GDataDocumentsSpreadsheet + * @export_format: the format in which the spreadsheet should be exported when downloaded + * @gid: the 0-based sheet ID to download, or -1 + * + * Builds and returns the download URI for the given #GDataDocumentsSpreadsheet in the desired format. Note that directly downloading + * the document using this URI isn't possible, as authentication is required. You should instead use gdata_download_stream_new() with + * the URI, and use the resulting #GInputStream. + * + * When requesting a "csv", "tsv", "pdf" or + * "html" file you may specify an additional parameter called @gid which indicates which grid, or sheet, you wish to get + * (the index is 0-based, so GID 1 actually refers to the second sheet on a given + * spreadsheet). + * + * Return value: the download URI; free with g_free() + * + * Since: 0.5.0 + */ +gchar * +gdata_documents_spreadsheet_get_download_uri (GDataDocumentsSpreadsheet *self, const gchar *export_format, gint gid) +{ + const gchar *resource_id, *document_id; + + g_return_val_if_fail (GDATA_IS_DOCUMENTS_SPREADSHEET (self), NULL); + g_return_val_if_fail (export_format != NULL && *export_format != '\0', NULL); + g_return_val_if_fail (gid >= -1, NULL); + + /* Extract the document ID from the resource ID. */ + resource_id = gdata_documents_entry_get_resource_id (GDATA_DOCUMENTS_ENTRY (self)); + g_assert (resource_id != NULL); + + document_id = g_utf8_strchr (resource_id, -1, ':'); + g_assert (document_id != NULL); + document_id++; /* skip over the colon */ + + if (gid != -1) { + return _gdata_service_build_uri ("http://spreadsheets.google.com/feeds/download/spreadsheets/Export?key=%s&exportFormat=%s&gid=%d", + document_id, export_format, gid); + } else { + return _gdata_service_build_uri ("http://spreadsheets.google.com/feeds/download/spreadsheets/Export?key=%s&exportFormat=%s", + document_id, export_format); + } +} diff --git a/gdata/services/documents/gdata-documents-spreadsheet.h b/gdata/services/documents/gdata-documents-spreadsheet.h new file mode 100644 index 0000000..438e93f --- /dev/null +++ b/gdata/services/documents/gdata-documents-spreadsheet.h @@ -0,0 +1,159 @@ +/* -*- Mode: C; indent-tabs-mode: t; c-basic-offset: 8; tab-width: 8 -*- */ +/* + * GData Client + * Copyright (C) Thibault Saunier 2009 + * + * GData Client is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * GData Client is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with GData Client. If not, see . + */ + +#ifndef GDATA_DOCUMENTS_SPREADSHEET_H +#define GDATA_DOCUMENTS_SPREADSHEET_H + +#include +#include + +#include + +G_BEGIN_DECLS + +/** + * GDATA_DOCUMENTS_SPREADSHEET_CSV: + * + * The export format for Comma-Separated Values (CSV) format. + * + * For more information, see the + * + * GData protocol specification. + * + * Since: 0.7.0 + */ +#define GDATA_DOCUMENTS_SPREADSHEET_CSV "csv" + +/** + * GDATA_DOCUMENTS_SPREADSHEET_ODS: + * + * The export format for OpenDocument Spreadsheet (ODS) format. + * + * For more information, see the + * + * GData protocol specification. + * + * Since: 0.7.0 + */ +#define GDATA_DOCUMENTS_SPREADSHEET_ODS "ods" + +/** + * GDATA_DOCUMENTS_SPREADSHEET_PDF: + * + * The export format for Portable Document Format (PDF). + * + * For more information, see the + * + * GData protocol specification. + * + * Since: 0.7.0 + */ +#define GDATA_DOCUMENTS_SPREADSHEET_PDF "pdf" + +/** + * GDATA_DOCUMENTS_SPREADSHEET_TSV: + * + * The export format for Tab-Separated Values (TSV) format. + * + * For more information, see the + * + * GData protocol specification. + * + * Since: 0.7.0 + */ +#define GDATA_DOCUMENTS_SPREADSHEET_TSV "tsv" + +/** + * GDATA_DOCUMENTS_SPREADSHEET_XLS: + * + * The export format for Microsoft Excel spreadsheet (XLS) format. + * + * For more information, see the + * + * GData protocol specification. + * + * Since: 0.7.0 + */ +#define GDATA_DOCUMENTS_SPREADSHEET_XLS "xls" + +/** + * GDATA_DOCUMENTS_SPREADSHEET_HTML: + * + * The export format for HyperText Markup Language (HTML) format. + * + * For more information, see the + * + * GData protocol specification. + * + * Since: 0.7.0 + */ +#define GDATA_DOCUMENTS_SPREADSHEET_HTML "html" + +#define GDATA_TYPE_DOCUMENTS_SPREADSHEET (gdata_documents_spreadsheet_get_type ()) +#define GDATA_DOCUMENTS_SPREADSHEET(o) (G_TYPE_CHECK_INSTANCE_CAST ((o), GDATA_TYPE_DOCUMENTS_SPREADSHEET, \ + GDataDocumentsSpreadsheet)) +#define GDATA_DOCUMENTS_SPREADSHEET_CLASS(k) (G_TYPE_CHECK_CLASS_CAST((k), GDATA_TYPE_DOCUMENTS_SPREADSHEET, \ + GDataDocumentsSpreadsheetClass)) +#define GDATA_IS_DOCUMENTS_SPREADSHEET(o) (G_TYPE_CHECK_INSTANCE_TYPE ((o), GDATA_TYPE_DOCUMENTS_SPREADSHEET)) +#define GDATA_IS_DOCUMENTS_SPREADSHEET_CLASS(k) (G_TYPE_CHECK_CLASS_TYPE ((k), GDATA_TYPE_DOCUMENTS_SPREADSHEET)) +#define GDATA_DOCUMENTS_SPREADSHEET_GET_CLASS(o) (G_TYPE_INSTANCE_GET_CLASS ((o), GDATA_TYPE_DOCUMENTS_SPREADSHEET, \ + GDataDocumentsSpreadsheetClass)) + +typedef struct _GDataDocumentsSpreadsheetPrivate GDataDocumentsSpreadsheetPrivate; + +/** + * GDataDocumentsSpreadsheet: + * + * All the fields in the #GDataDocumentsSpreadsheet structure are private and should never be accessed directly. + * + * Since: 0.4.0 + */ +typedef struct { + GDataDocumentsDocument parent; + GDataDocumentsSpreadsheetPrivate *priv; +} GDataDocumentsSpreadsheet; + +/** + * GDataDocumentsSpreadsheetClass: + * + * All the fields in the #GDataDocumentsSpreadsheetClass structure are private and should never be accessed directly. + * + * Since: 0.4.0 + */ +typedef struct { + /*< private >*/ + GDataDocumentsDocumentClass parent; + + /*< private >*/ + /* Padding for future expansion */ + void (*_g_reserved0) (void); + void (*_g_reserved1) (void); +} GDataDocumentsSpreadsheetClass; + +GType gdata_documents_spreadsheet_get_type (void) G_GNUC_CONST; +G_DEFINE_AUTOPTR_CLEANUP_FUNC (GDataDocumentsSpreadsheet, g_object_unref) + +GDataDocumentsSpreadsheet *gdata_documents_spreadsheet_new (const gchar *id) G_GNUC_WARN_UNUSED_RESULT G_GNUC_MALLOC; + +gchar *gdata_documents_spreadsheet_get_download_uri (GDataDocumentsSpreadsheet *self, const gchar *export_format, + gint gid) G_GNUC_WARN_UNUSED_RESULT G_GNUC_MALLOC; + +G_END_DECLS + +#endif /* !GDATA_DOCUMENTS_SPREADSHEET_H */ diff --git a/gdata/services/documents/gdata-documents-text.c b/gdata/services/documents/gdata-documents-text.c new file mode 100644 index 0000000..3041506 --- /dev/null +++ b/gdata/services/documents/gdata-documents-text.c @@ -0,0 +1,87 @@ +/* -*- Mode: C; indent-tabs-mode: t; c-basic-offset: 8; tab-width: 8 -*- */ +/* + * GData Client + * Copyright (C) Thibault Saunier 2009 + * Copyright (C) Philip Withnall 2010 + * Copyright (C) Red Hat, Inc. 2016 + * + * GData Client is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * GData Client is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with GData Client. If not, see . + */ + +/** + * SECTION:gdata-documents-text + * @short_description: GData Documents text object + * @stability: Stable + * @include: gdata/services/documents/gdata-documents-text.h + * + * #GDataDocumentsText is a subclass of #GDataDocumentsDocument to represent a text document from Google Documents. + * + * For more details of Google Drive's GData API, see the + * online documentation. + * + * Since: 0.4.0 + */ + +#include +#include + +#include "gdata-documents-text.h" +#include "gdata-documents-utils.h" +#include "gdata-parser.h" +#include "gdata-private.h" + +static void gdata_documents_text_constructed (GObject *object); + +G_DEFINE_TYPE (GDataDocumentsText, gdata_documents_text, GDATA_TYPE_DOCUMENTS_DOCUMENT) + +static void +gdata_documents_text_class_init (GDataDocumentsTextClass *klass) +{ + GObjectClass *gobject_class = G_OBJECT_CLASS (klass); + GDataEntryClass *entry_class = GDATA_ENTRY_CLASS (klass); + + gobject_class->constructed = gdata_documents_text_constructed; + entry_class->kind_term = "http://schemas.google.com/docs/2007#document"; +} + +static void +gdata_documents_text_init (GDataDocumentsText *self) +{ + /* Why am I writing it? */ +} + +static void +gdata_documents_text_constructed (GObject *object) +{ + G_OBJECT_CLASS (gdata_documents_text_parent_class)->constructed (object); + + if (!_gdata_parsable_is_constructed_from_xml (GDATA_PARSABLE (object))) + gdata_documents_utils_add_content_type (GDATA_DOCUMENTS_ENTRY (object), "application/vnd.google-apps.document"); +} + +/** + * gdata_documents_text_new: + * @id: (allow-none): the entry's ID (not the document ID of the text document), or %NULL + * + * Creates a new #GDataDocumentsText with the given entry ID (#GDataEntry:id). + * + * Return value: (transfer full): a new #GDataDocumentsText, or %NULL; unref with g_object_unref() + * + * Since: 0.4.0 + */ +GDataDocumentsText * +gdata_documents_text_new (const gchar *id) +{ + return GDATA_DOCUMENTS_TEXT (g_object_new (GDATA_TYPE_DOCUMENTS_TEXT, "id", id, NULL)); +} diff --git a/gdata/services/documents/gdata-documents-text.h b/gdata/services/documents/gdata-documents-text.h new file mode 100644 index 0000000..4645524 --- /dev/null +++ b/gdata/services/documents/gdata-documents-text.h @@ -0,0 +1,192 @@ +/* -*- Mode: C; indent-tabs-mode: t; c-basic-offset: 8; tab-width: 8 -*- */ +/* + * GData Client + * Copyright (C) Thibault Saunier 2009 + * + * GData Client is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * GData Client is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with GData Client. If not, see . + */ + +#ifndef GDATA_DOCUMENTS_TEXT_H +#define GDATA_DOCUMENTS_TEXT_H + +#include +#include + +#include + +G_BEGIN_DECLS + +/** + * GDATA_DOCUMENTS_TEXT_DOC: + * + * The export format for Microsoft Word (DOC) format. + * + * For more information, see the + * + * GData protocol specification. + * + * Since: 0.7.0 + */ +#define GDATA_DOCUMENTS_TEXT_DOC "doc" + +/** + * GDATA_DOCUMENTS_TEXT_HTML: + * + * The export format for HyperText Markup Language (HTML) format. + * + * For more information, see the + * + * GData protocol specification. + * + * Since: 0.7.0 + */ +#define GDATA_DOCUMENTS_TEXT_HTML "html" + +/** + * GDATA_DOCUMENTS_TEXT_JPEG: + * + * The export format for JPEG image format. + * + * For more information, see the + * + * GData protocol specification. + * + * Since: 0.13.0 + */ +#define GDATA_DOCUMENTS_TEXT_JPEG "jpeg" + +/** + * GDATA_DOCUMENTS_TEXT_ODT: + * + * The export format for OpenDocument Text (ODT) format. + * + * For more information, see the + * + * GData protocol specification. + * + * Since: 0.7.0 + */ +#define GDATA_DOCUMENTS_TEXT_ODT "odt" + +/** + * GDATA_DOCUMENTS_TEXT_PDF: + * + * The export format for Portable Document Format (PDF). + * + * For more information, see the + * + * GData protocol specification. + * + * Since: 0.7.0 + */ +#define GDATA_DOCUMENTS_TEXT_PDF "pdf" + +/** + * GDATA_DOCUMENTS_TEXT_PNG: + * + * The export format for Portable Network Graphics (PNG) image format. + * + * For more information, see the + * + * GData protocol specification. + * + * Since: 0.7.0 + */ +#define GDATA_DOCUMENTS_TEXT_PNG "png" + +/** + * GDATA_DOCUMENTS_TEXT_RTF: + * + * The export format for Rich Text Format (RTF). + * + * For more information, see the + * + * GData protocol specification. + * + * Since: 0.7.0 + */ +#define GDATA_DOCUMENTS_TEXT_RTF "rtf" + +/** + * GDATA_DOCUMENTS_TEXT_TXT: + * + * The export format for plain text format. + * + * For more information, see the + * + * GData protocol specification. + * + * Since: 0.7.0 + */ +#define GDATA_DOCUMENTS_TEXT_TXT "txt" + +/** + * GDATA_DOCUMENTS_TEXT_ZIP: + * + * The export format for a ZIP archive containing images and exported HTML. + * + * For more information, see the + * + * GData protocol specification. + * + * Since: 0.7.0 + */ +#define GDATA_DOCUMENTS_TEXT_ZIP "zip" + +#define GDATA_TYPE_DOCUMENTS_TEXT (gdata_documents_text_get_type ()) +#define GDATA_DOCUMENTS_TEXT(o) (G_TYPE_CHECK_INSTANCE_CAST ((o), GDATA_TYPE_DOCUMENTS_TEXT, GDataDocumentsText)) +#define GDATA_DOCUMENTS_TEXT_CLASS(k) (G_TYPE_CHECK_CLASS_CAST((k), GDATA_TYPE_DOCUMENTS_TEXT, GDataDocumentsTextClass)) +#define GDATA_IS_DOCUMENTS_TEXT(o) (G_TYPE_CHECK_INSTANCE_TYPE ((o), GDATA_TYPE_DOCUMENTS_TEXT)) +#define GDATA_IS_DOCUMENTS_TEXT_CLASS(k) (G_TYPE_CHECK_CLASS_TYPE ((k), GDATA_TYPE_DOCUMENTS_TEXT)) +#define GDATA_DOCUMENTS_TEXT_GET_CLASS(o) (G_TYPE_INSTANCE_GET_CLASS ((o), GDATA_TYPE_DOCUMENTS_TEXT, GDataDocumentsTextClass)) + +typedef struct _GDataDocumentsTextPrivate GDataDocumentsTextPrivate; + +/** + * GDataDocumentsText: + * + * All the fields in the #GDataDocumentsText structure are private and should never be accessed directly. + * + * Since: 0.4.0 + */ +typedef struct { + GDataDocumentsDocument parent; + GDataDocumentsTextPrivate *priv; +} GDataDocumentsText; + +/** + * GDataDocumentsTextClass: + * + * All the fields in the #GDataDocumentsTextClass structure are private and should never be accessed directly. + * + * Since: 0.4.0 + */ +typedef struct { + /*< private >*/ + GDataDocumentsDocumentClass parent; + + /*< private >*/ + /* Padding for future expansion */ + void (*_g_reserved0) (void); + void (*_g_reserved1) (void); +} GDataDocumentsTextClass; + +GType gdata_documents_text_get_type (void) G_GNUC_CONST; +G_DEFINE_AUTOPTR_CLEANUP_FUNC (GDataDocumentsText, g_object_unref) + +GDataDocumentsText *gdata_documents_text_new (const gchar *id) G_GNUC_WARN_UNUSED_RESULT G_GNUC_MALLOC; + +G_END_DECLS + +#endif /* !GDATA_DOCUMENTS_TEXT_H */ diff --git a/gdata/services/documents/gdata-documents-upload-query.c b/gdata/services/documents/gdata-documents-upload-query.c new file mode 100644 index 0000000..383db17 --- /dev/null +++ b/gdata/services/documents/gdata-documents-upload-query.c @@ -0,0 +1,423 @@ +/* -*- Mode: C; indent-tabs-mode: t; c-basic-offset: 8; tab-width: 8 -*- */ +/* + * GData Client + * Copyright (C) Philip Withnall 2012 + * + * GData Client is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * GData Client is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with GData Client. If not, see . + */ + +/** + * SECTION:gdata-documents-upload-query + * @short_description: GData Documents upload query object + * @stability: Stable + * @include: gdata/services/documents/gdata-documents-upload-query.h + * + * #GDataDocumentsUploadQuery is a collection of parameters for document uploads to Google Documents, allowing various options to be set when uploading + * a document for the first time. For example, the destination folder for the uploaded document may be specified; or whether to automatically convert + * the document to a common format. + * + * #GDataDocumentsUploadQuery is designed as an object (rather than a fixed struct or set of function arguments) to allow for easy additions of new + * Google Documents features in the future. + * + * + * Uploading an Arbitrary File from Disk + * + * GDataDocumentsService *service; + * GDataDocumentsDocument *document, *uploaded_document; + * GFile *arbitrary_file; + * GFileInfo *file_info; + * const gchar *slug, *content_type; + * goffset file_size; + * GDataDocumentsUploadQuery *upload_query; + * GFileInputStream *file_stream; + * GDataUploadStream *upload_stream; + * GError *error = NULL; + * + * /* Create a service. */ + * service = create_documents_service (); + * + * /* Get the file to upload. */ + * arbitrary_file = g_file_new_for_path ("arbitrary-file.bin"); + * + * /* Get the file's display name, content type and size. */ + * file_info = g_file_query_info (arbitrary_file, G_FILE_ATTRIBUTE_STANDARD_DISPLAY_NAME "," G_FILE_ATTRIBUTE_STANDARD_CONTENT_TYPE "," + * G_FILE_ATTRIBUTE_STANDARD_SIZE, G_FILE_QUERY_INFO_NONE, NULL, &error); + * + * if (error != NULL) { + * g_error ("Error getting arbitrary file information: %s", error->message); + * g_error_free (error); + * g_object_unref (arbitrary_file); + * g_object_unref (service); + * return; + * } + * + * slug = g_file_info_get_display_name (file_info); + * content_type = g_file_info_get_content_type (file_info); + * file_size = g_file_info_get_size (file_info); + * + * /* Get an input stream for the file. */ + * file_stream = g_file_read (arbitrary_file, NULL, &error); + * + * g_object_unref (arbitrary_file); + * + * if (error != NULL) { + * g_error ("Error getting arbitrary file stream: %s", error->message); + * g_error_free (error); + * g_object_unref (file_info); + * g_object_unref (service); + * return; + * } + * + * /* Create the file metadata to upload. */ + * document = gdata_documents_document_new (NULL); + * gdata_entry_set_title (GDATA_ENTRY (document), "Title for My Arbitrary File"); + * + * /* Build the upload query and set the upload to not be converted to a standard format. */ + * upload_query = gdata_documents_upload_query_new (); + * gdata_documents_upload_query_set_convert (upload_query, FALSE); + * + * /* Get an upload stream for the file. */ + * upload_stream = gdata_documents_service_upload_document_resumable (service, document, slug, content_type, file_size, upload_query, NULL, &error); + * + * g_object_unref (upload_query); + * g_object_unref (document); + * g_object_unref (file_info); + * + * if (error != NULL) { + * g_error ("Error getting upload stream: %s", error->message); + * g_error_free (error); + * g_object_unref (file_stream); + * g_object_unref (service); + * return; + * } + * + * /* Upload the document. This is a blocking operation, and should normally be done asynchronously. */ + * g_output_stream_splice (G_OUTPUT_STREAM (upload_stream), G_INPUT_STREAM (file_stream), + * G_OUTPUT_STREAM_SPLICE_CLOSE_SOURCE | G_OUTPUT_STREAM_SPLICE_CLOSE_TARGET, NULL, &error); + * + * g_object_unref (file_stream); + * + * if (error != NULL) { + * g_error ("Error splicing streams: %s", error->message); + * g_error_free (error); + * g_object_unref (upload_stream); + * g_object_unref (service); + * return; + * } + * + * /* Finish off the upload by parsing the returned updated document metadata entry. */ + * uploaded_document = gdata_documents_service_finish_upload (service, upload_stream, &error); + * + * g_object_unref (upload_stream); + * g_object_unref (service); + * + * if (error != NULL) { + * g_error ("Error uploading file: %s", error->message); + * g_error_free (error); + * return; + * } + * + * /* Do something with the uploaded document. */ + * + * g_object_unref (uploaded_document); + * + * + * + * Since: 0.13.0 + */ + +#include + +#include "gdata-documents-upload-query.h" +#include "gdata-private.h" +#include "gdata-upload-stream.h" + +static void gdata_documents_upload_query_dispose (GObject *object); +static void gdata_documents_upload_query_get_property (GObject *object, guint property_id, GValue *value, GParamSpec *pspec); +static void gdata_documents_upload_query_set_property (GObject *object, guint property_id, const GValue *value, GParamSpec *pspec); + +struct _GDataDocumentsUploadQueryPrivate { + GDataDocumentsFolder *folder; + gboolean convert; +}; + +enum { + PROP_FOLDER = 1, + PROP_CONVERT, +}; + +G_DEFINE_TYPE (GDataDocumentsUploadQuery, gdata_documents_upload_query, G_TYPE_OBJECT) + +static void +gdata_documents_upload_query_class_init (GDataDocumentsUploadQueryClass *klass) +{ + GObjectClass *gobject_class = G_OBJECT_CLASS (klass); + + g_type_class_add_private (klass, sizeof (GDataDocumentsUploadQueryPrivate)); + + gobject_class->get_property = gdata_documents_upload_query_get_property; + gobject_class->set_property = gdata_documents_upload_query_set_property; + gobject_class->dispose = gdata_documents_upload_query_dispose; + + /** + * GDataDocumentsUploadQuery:folder: + * + * Folder to upload the document into. If this is %NULL, the document will be uploaded into the root folder. + * + * Since: 0.13.0 + */ + g_object_class_install_property (gobject_class, PROP_FOLDER, + g_param_spec_object ("folder", + "Folder", "Folder to upload the document into.", + GDATA_TYPE_DOCUMENTS_FOLDER, + G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)); + + /** + * GDataDocumentsUploadQuery:convert: + * + * %TRUE to automatically convert the uploaded document into a standard format (such as a text document, spreadsheet, presentation, etc.). + * %FALSE to upload the document without converting it; this allows for arbitrary files to be uploaded to Google Documents. + * + * For more information, see the + * online documentation. + * + * Note that uploading with this property set to %FALSE will only have an effect when using gdata_documents_service_update_document_resumable() + * and not gdata_documents_service_update_document(). Additionally, the #GDataDocumentsDocument passed to + * gdata_documents_service_update_document_resumable() must be a #GDataDocumentsDocument if this property is %FALSE, and a subclass of it + * otherwise. + * + * Since: 0.13.0 + */ + g_object_class_install_property (gobject_class, PROP_CONVERT, + g_param_spec_boolean ("convert", + "Convert?", "Whether to automatically convert uploaded documents into a standard format.", + TRUE, + G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)); +} + +static void +gdata_documents_upload_query_init (GDataDocumentsUploadQuery *self) +{ + self->priv = G_TYPE_INSTANCE_GET_PRIVATE (self, GDATA_TYPE_DOCUMENTS_UPLOAD_QUERY, GDataDocumentsUploadQueryPrivate); + self->priv->convert = TRUE; +} + +static void +gdata_documents_upload_query_dispose (GObject *object) +{ + GDataDocumentsUploadQueryPrivate *priv = GDATA_DOCUMENTS_UPLOAD_QUERY (object)->priv; + + g_clear_object (&priv->folder); + + /* Chain up to the parent class */ + G_OBJECT_CLASS (gdata_documents_upload_query_parent_class)->dispose (object); +} + +static void +gdata_documents_upload_query_get_property (GObject *object, guint property_id, GValue *value, GParamSpec *pspec) +{ + GDataDocumentsUploadQueryPrivate *priv = GDATA_DOCUMENTS_UPLOAD_QUERY (object)->priv; + + switch (property_id) { + case PROP_FOLDER: + g_value_set_object (value, priv->folder); + break; + case PROP_CONVERT: + g_value_set_boolean (value, priv->convert); + break; + default: + /* We don't have any other property... */ + G_OBJECT_WARN_INVALID_PROPERTY_ID (object, property_id, pspec); + break; + } +} + +static void +gdata_documents_upload_query_set_property (GObject *object, guint property_id, const GValue *value, GParamSpec *pspec) +{ + GDataDocumentsUploadQuery *self = GDATA_DOCUMENTS_UPLOAD_QUERY (object); + + switch (property_id) { + case PROP_FOLDER: + gdata_documents_upload_query_set_folder (self, g_value_get_object (value)); + break; + case PROP_CONVERT: + gdata_documents_upload_query_set_convert (self, g_value_get_boolean (value)); + break; + default: + /* We don't have any other property... */ + G_OBJECT_WARN_INVALID_PROPERTY_ID (object, property_id, pspec); + break; + } +} + +/** + * gdata_documents_upload_query_new: + * + * Constructs a new empty #GDataDocumentsUploadQuery. + * + * Return value: (transfer full): a new #GDataDocumentsUploadQuery; unref with g_object_unref() + * + * Since: 0.13.0 + */ +GDataDocumentsUploadQuery * +gdata_documents_upload_query_new (void) +{ + return g_object_new (GDATA_TYPE_DOCUMENTS_UPLOAD_QUERY, NULL); +} + +/** + * gdata_documents_upload_query_build_uri: + * @self: a #GDataDocumentsUploadQuery + * + * Builds an upload URI suitable for passing to gdata_upload_stream_new_resumable() in order to upload a document to Google Documents as described in + * the + * + * online documentation. + * + * Return value: (transfer full): a complete upload URI; free with g_free() + * + * Since: 0.13.0 + */ +gchar * +gdata_documents_upload_query_build_uri (GDataDocumentsUploadQuery *self) +{ + gchar *base_uri; + GString *upload_uri; + GDataDocumentsUploadQueryPrivate *priv; + + g_return_val_if_fail (GDATA_IS_DOCUMENTS_UPLOAD_QUERY (self), NULL); + + priv = self->priv; + + /* Construct the base URI. */ + if (priv->folder != NULL) { + GDataLink *upload_link; + + /* Get the folder's upload URI. */ + upload_link = gdata_entry_look_up_link (GDATA_ENTRY (priv->folder), GDATA_LINK_RESUMABLE_CREATE_MEDIA); + + if (upload_link == NULL) { + /* Fall back to building a URI manually. */ + base_uri = _gdata_service_build_uri ("%s://docs.google.com/feeds/upload/create-session/default/private/full/%s/contents", + _gdata_service_get_scheme (), + gdata_documents_entry_get_resource_id (GDATA_DOCUMENTS_ENTRY (priv->folder))); + } else { + base_uri = g_strdup (gdata_link_get_uri (upload_link)); + } + } else { + base_uri = g_strconcat (_gdata_service_get_scheme (), "://docs.google.com/feeds/upload/create-session/default/private/full", NULL); + } + + /* Document format conversion. See: https://developers.google.com/google-apps/documents-list/#creating_or_uploading_files */ + upload_uri = g_string_new (base_uri); + g_free (base_uri); + + if (priv->convert == TRUE) { + /* Convert documents to standard formats on upload. */ + g_string_append (upload_uri, "?convert=true"); + } else { + /* Don't convert them — this permits uploading of arbitrary files. */ + g_string_append (upload_uri, "?convert=false"); + } + + return g_string_free (upload_uri, FALSE); +} + +/** + * gdata_documents_upload_query_get_folder: + * @self: a #GDataDocumentsUploadQuery + * + * Gets #GDataDocumentsUploadQuery:folder. + * + * Return value: (allow-none) (transfer none): the folder to upload into, or %NULL + * + * Since: 0.13.0 + */ +GDataDocumentsFolder * +gdata_documents_upload_query_get_folder (GDataDocumentsUploadQuery *self) +{ + g_return_val_if_fail (GDATA_IS_DOCUMENTS_UPLOAD_QUERY (self), NULL); + + return self->priv->folder; +} + +/** + * gdata_documents_upload_query_set_folder: + * @self: a #GDataDocumentsUploadQuery + * @folder: (allow-none) (transfer none): a new folder to upload into, or %NULL + * + * Sets #GDataDocumentsUploadQuery:folder to @folder. + * + * Since: 0.13.0 + */ +void +gdata_documents_upload_query_set_folder (GDataDocumentsUploadQuery *self, GDataDocumentsFolder *folder) +{ + g_return_if_fail (GDATA_IS_DOCUMENTS_UPLOAD_QUERY (self)); + g_return_if_fail (folder == NULL || GDATA_IS_DOCUMENTS_FOLDER (folder)); + + if (folder == self->priv->folder) { + return; + } + + if (folder != NULL) { + g_object_ref (folder); + } + + g_clear_object (&self->priv->folder); + self->priv->folder = folder; + + g_object_notify (G_OBJECT (self), "folder"); +} + +/** + * gdata_documents_upload_query_get_convert: + * @self: a #GDataDocumentsUploadQuery + * + * Gets #GDataDocumentsUploadQuery:convert. + * + * Return value: %TRUE to convert documents to common formats, %FALSE to upload them unmodified + * + * Since: 0.13.0 + */ +gboolean +gdata_documents_upload_query_get_convert (GDataDocumentsUploadQuery *self) +{ + g_return_val_if_fail (GDATA_IS_DOCUMENTS_UPLOAD_QUERY (self), TRUE); + + return self->priv->convert; +} + +/** + * gdata_documents_upload_query_set_convert: + * @self: a #GDataDocumentsUploadQuery + * @convert: %TRUE to convert documents to common formats, %FALSE to upload them unmodified + * + * Sets #GDataDocumentsUploadQuery:convert to @convert. + * + * Since: 0.13.0 + */ +void +gdata_documents_upload_query_set_convert (GDataDocumentsUploadQuery *self, gboolean convert) +{ + g_return_if_fail (GDATA_IS_DOCUMENTS_UPLOAD_QUERY (self)); + + if (convert == self->priv->convert) { + return; + } + + self->priv->convert = convert; + g_object_notify (G_OBJECT (self), "convert"); +} diff --git a/gdata/services/documents/gdata-documents-upload-query.h b/gdata/services/documents/gdata-documents-upload-query.h new file mode 100644 index 0000000..30582e9 --- /dev/null +++ b/gdata/services/documents/gdata-documents-upload-query.h @@ -0,0 +1,84 @@ +/* -*- Mode: C; indent-tabs-mode: t; c-basic-offset: 8; tab-width: 8 -*- */ +/* + * GData Client + * Copyright (C) Philip Withnall 2012 + * + * GData Client is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * GData Client is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with GData Client. If not, see . + */ + +#ifndef GDATA_DOCUMENTS_UPLOAD_QUERY_H +#define GDATA_DOCUMENTS_UPLOAD_QUERY_H + +#include +#include + +#include + +G_BEGIN_DECLS + +#define GDATA_TYPE_DOCUMENTS_UPLOAD_QUERY (gdata_documents_upload_query_get_type ()) +#define GDATA_DOCUMENTS_UPLOAD_QUERY(o) (G_TYPE_CHECK_INSTANCE_CAST ((o), GDATA_TYPE_DOCUMENTS_UPLOAD_QUERY, GDataDocumentsUploadQuery)) +#define GDATA_DOCUMENTS_UPLOAD_QUERY_CLASS(k) (G_TYPE_CHECK_CLASS_CAST((k), GDATA_TYPE_DOCUMENTS_UPLOAD_QUERY, GDataDocumentsUploadQueryClass)) +#define GDATA_IS_DOCUMENTS_UPLOAD_QUERY(o) (G_TYPE_CHECK_INSTANCE_TYPE ((o), GDATA_TYPE_DOCUMENTS_UPLOAD_QUERY)) +#define GDATA_IS_DOCUMENTS_UPLOAD_QUERY_CLASS(k) (G_TYPE_CHECK_CLASS_TYPE ((k), GDATA_TYPE_DOCUMENTS_UPLOAD_QUERY)) +#define GDATA_DOCUMENTS_UPLOAD_QUERY_GET_CLASS(o) \ + (G_TYPE_INSTANCE_GET_CLASS ((o), GDATA_TYPE_DOCUMENTS_UPLOAD_QUERY, GDataDocumentsUploadQueryClass)) + +typedef struct _GDataDocumentsUploadQueryPrivate GDataDocumentsUploadQueryPrivate; + +/** + * GDataDocumentsUploadQuery: + * + * All the fields in the #GDataDocumentsUploadQuery structure are private and should never be accessed directly. + * + * Since: 0.13.0 + */ +typedef struct { + GObject parent; + GDataDocumentsUploadQueryPrivate *priv; +} GDataDocumentsUploadQuery; + +/** + * GDataDocumentsUploadQueryClass: + * + * All the fields in the #GDataDocumentsUploadQueryClass structure are private and should never be accessed directly. + * + * Since: 0.13.0 + */ +typedef struct { + /*< private >*/ + GObjectClass parent; + + /*< private >*/ + /* Padding for future expansion */ + void (*_g_reserved0) (void); + void (*_g_reserved1) (void); +} GDataDocumentsUploadQueryClass; + +GType gdata_documents_upload_query_get_type (void) G_GNUC_CONST; +G_DEFINE_AUTOPTR_CLEANUP_FUNC (GDataDocumentsUploadQuery, g_object_unref) + +GDataDocumentsUploadQuery *gdata_documents_upload_query_new (void) G_GNUC_WARN_UNUSED_RESULT G_GNUC_MALLOC; + +gchar *gdata_documents_upload_query_build_uri (GDataDocumentsUploadQuery *self) G_GNUC_WARN_UNUSED_RESULT G_GNUC_MALLOC; + +GDataDocumentsFolder *gdata_documents_upload_query_get_folder (GDataDocumentsUploadQuery *self) G_GNUC_PURE; +void gdata_documents_upload_query_set_folder (GDataDocumentsUploadQuery *self, GDataDocumentsFolder *folder); + +gboolean gdata_documents_upload_query_get_convert (GDataDocumentsUploadQuery *self) G_GNUC_PURE; +void gdata_documents_upload_query_set_convert (GDataDocumentsUploadQuery *self, gboolean convert); + +G_END_DECLS + +#endif /* !GDATA_DOCUMENTS_UPLOAD_QUERY_H */ diff --git a/gdata/services/documents/gdata-documents-utils.c b/gdata/services/documents/gdata-documents-utils.c new file mode 100644 index 0000000..b2e19d5 --- /dev/null +++ b/gdata/services/documents/gdata-documents-utils.c @@ -0,0 +1,154 @@ +/* -*- Mode: C; indent-tabs-mode: t; c-basic-offset: 8; tab-width: 8 -*- */ +/* + * GData Client + * Copyright (C) Red Hat, Inc. 2015, 2016 + * + * GData Client is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * GData Client is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with GData Client. If not, see . + */ + +#include + +#include "gdata-documents-spreadsheet.h" +#include "gdata-documents-text.h" +#include "gdata-documents-presentation.h" +#include "gdata-documents-folder.h" +#include "gdata-documents-drawing.h" +#include "gdata-documents-pdf.h" +#include "gdata-documents-utils.h" + +/* + * gdata_documents_utils_add_content_type: + * @entry: a #GDataDocumentsEntry + * @content_type: the new entry content-type + * + * Adds a #GDataCategory representing @content_type to @entry. + * + * Since: 0.17.7 + */ +void +gdata_documents_utils_add_content_type (GDataDocumentsEntry *entry, const gchar *content_type) +{ + GDataCategory *category; + GDataEntryClass *klass = GDATA_ENTRY_GET_CLASS (entry); + + if (content_type == NULL || content_type[0] == '\0') + return; + + category = gdata_category_new (klass->kind_term, "http://schemas.google.com/g/2005#kind", content_type); + gdata_entry_add_category (GDATA_ENTRY (entry), category); + g_object_unref (category); +} + +/* + * gdata_documents_utils_get_type_from_content_type: + * @content_type: the content type + * + * Maps @content_type to a #GType representing a #GDataDocumentsEntry + * sub-class. + * + * Return value: a #GType corresponding to @content_type + * + * Since: 0.17.2 + */ +GType +gdata_documents_utils_get_type_from_content_type (const gchar *content_type) +{ + GType retval; + + /* MIME types: https://developers.google.com/drive/web/mime-types */ + + if (g_strcmp0 (content_type, "application/vnd.google-apps.folder") == 0) { + retval = GDATA_TYPE_DOCUMENTS_FOLDER; + } else if (g_strcmp0 (content_type, "application/pdf") == 0) { + retval = GDATA_TYPE_DOCUMENTS_PDF; + } else if (g_strcmp0 (content_type, "application/vnd.google-apps.document") == 0) { + retval = GDATA_TYPE_DOCUMENTS_TEXT; + } else if (g_strcmp0 (content_type, "application/vnd.google-apps.drawing") == 0) { + retval = GDATA_TYPE_DOCUMENTS_DRAWING; + } else if (g_strcmp0 (content_type, "application/vnd.google-apps.presentation") == 0) { + retval = GDATA_TYPE_DOCUMENTS_PRESENTATION; + } else if (g_strcmp0 (content_type, "application/vnd.google-apps.spreadsheet") == 0) { + retval = GDATA_TYPE_DOCUMENTS_SPREADSHEET; + } else { + retval = GDATA_TYPE_DOCUMENTS_DOCUMENT; + } + + return retval; +} + +/* + * gdata_documents_utils_get_content_type: + * @entry: a #GDataDocumentsEntry + * + * Returns the content type of @entry, if any. + * + * Return value: (nullable): content type of @entry, %NULL otherwise + * + * Since: 0.17.5 + */ +const gchar * +gdata_documents_utils_get_content_type (GDataDocumentsEntry *entry) +{ + GList *categories; + GList *i; + const gchar *retval = NULL; + + categories = gdata_entry_get_categories (GDATA_ENTRY (entry)); + for (i = categories; i != NULL; i = i->next) { + GDataCategory *category = GDATA_CATEGORY (i->data); + const gchar *label; + const gchar *scheme; + + label = gdata_category_get_label (category); + scheme = gdata_category_get_scheme (category); + if (label != NULL && label[0] != '\0' && g_strcmp0 (scheme, "http://schemas.google.com/g/2005#kind") == 0) { + retval = label; + break; + } + } + + return retval; +} + +/* + * gdata_documents_utils_get_id_from_link: + * @_link: a #GDataLink + * + * Returns the ID, if any, of the #GDataEntry pointed to by @_link. + * + * Return value: (nullable): ID of @_link, %NULL otherwise + * + * Since: 0.17.9 + */ +const gchar * +gdata_documents_utils_get_id_from_link (GDataLink *_link) +{ + const gchar *retval = NULL; + const gchar *uri; + + /* HACK: Extract the ID from the GDataLink:uri by removing the prefix. Ignore links which + * don't have the prefix. */ + uri = gdata_link_get_uri (_link); + if (g_str_has_prefix (uri, GDATA_DOCUMENTS_URI_PREFIX)) { + const gchar *id; + gsize uri_prefix_len; + + uri_prefix_len = strlen (GDATA_DOCUMENTS_URI_PREFIX); + id = uri + uri_prefix_len; + if (id[0] != '\0') + retval = id; + } + + return retval; +} diff --git a/gdata/services/documents/gdata-documents-utils.h b/gdata/services/documents/gdata-documents-utils.h new file mode 100644 index 0000000..48625d0 --- /dev/null +++ b/gdata/services/documents/gdata-documents-utils.h @@ -0,0 +1,43 @@ +/* -*- Mode: C; indent-tabs-mode: t; c-basic-offset: 8; tab-width: 8 -*- */ +/* + * GData Client + * Copyright (C) Red Hat, Inc. 2015, 2016 + * + * GData Client is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * GData Client is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with GData Client. If not, see . + */ + +#ifndef GDATA_DOCUMENTS_UTILS_H +#define GDATA_DOCUMENTS_UTILS_H + +#include +#include + +#include + +G_BEGIN_DECLS + +/* HACK: Used to convert GDataLink:uri to ID and vice-versa. */ +#define GDATA_DOCUMENTS_URI_PREFIX "https://www.googleapis.com/drive/v2/files/" + +G_GNUC_INTERNAL void gdata_documents_utils_add_content_type (GDataDocumentsEntry *entry, const gchar *content_type); + +G_GNUC_INTERNAL GType gdata_documents_utils_get_type_from_content_type (const gchar *content_type); + +G_GNUC_INTERNAL const gchar *gdata_documents_utils_get_content_type (GDataDocumentsEntry *entry); + +G_GNUC_INTERNAL const gchar *gdata_documents_utils_get_id_from_link (GDataLink *_link); + +G_END_DECLS + +#endif /* !GDATA_DOCUMENTS_UTILS_H */ diff --git a/gdata/services/documents/meson.build b/gdata/services/documents/meson.build new file mode 100644 index 0000000..a098483 --- /dev/null +++ b/gdata/services/documents/meson.build @@ -0,0 +1,75 @@ +incs += include_directories('.') + +include_subdir = gdata_include_subdir / 'services/documents' + +headers = files( + 'gdata-documents-access-rule.h', + 'gdata-documents-document.h', + 'gdata-documents-drawing.h', + 'gdata-documents-entry.h', + 'gdata-documents-feed.h', + 'gdata-documents-folder.h', + 'gdata-documents-metadata.h', + 'gdata-documents-pdf.h', + 'gdata-documents-presentation.h', + 'gdata-documents-property.h', + 'gdata-documents-query.h', + 'gdata-documents-service.h', + 'gdata-documents-spreadsheet.h', + 'gdata-documents-text.h', + 'gdata-documents-upload-query.h', +) + +install_headers( + headers, + subdir: include_subdir, +) + +gir_headers += headers + +sources += files( + 'gdata-documents-access-rule.c', + 'gdata-documents-document.c', + 'gdata-documents-drawing.c', + 'gdata-documents-entry.c', + 'gdata-documents-feed.c', + 'gdata-documents-folder.c', + 'gdata-documents-metadata.c', + 'gdata-documents-pdf.c', + 'gdata-documents-presentation.c', + 'gdata-documents-property.c', + 'gdata-documents-query.c', + 'gdata-documents-service.c', + 'gdata-documents-spreadsheet.c', + 'gdata-documents-text.c', + 'gdata-documents-upload-query.c', + 'gdata-documents-utils.c', +) + +enums = 'gdata-documents-enums' + +# FIXME: Work around the namespace being incorrectly detected +# by glib-mkenums. This needs to be fixed by changing the +# namespace in libgdata. See !6. +enums_in = gnome.mkenums_simple( + enums + '-in', + sources: headers, +) + +sources += custom_target( + enums + '.c', + input: enums_in[0], + output: enums + '.c', + command: enum_source_cmd, + capture: true, +) + +enum_headers += custom_target( + enums + '.h', + input: enums_in[1], + output: enums + '.h', + command: enum_header_cmd, + capture: true, + install: true, + install_dir: gdata_includedir / include_subdir, +) diff --git a/gdata/services/freebase/gdata-freebase-query.c b/gdata/services/freebase/gdata-freebase-query.c new file mode 100644 index 0000000..8ec8314 --- /dev/null +++ b/gdata/services/freebase/gdata-freebase-query.c @@ -0,0 +1,259 @@ +/* -*- Mode: C; indent-tabs-mode: t; c-basic-offset: 8; tab-width: 8 -*- */ +/* + * GData Client + * Copyright (C) 2014 Carlos Garnacho + * + * GData Client is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * GData Client is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with GData Client. If not, see . + */ + +/** + * SECTION:gdata-freebase-query + * @short_description: GData Freebase query object + * @stability: Stable + * @include: gdata/services/freebase/gdata-freebase-query.h + * + * #GDataFreebaseQuery represents a MQL query specific to the Google Freebase service. + * + * This implementation of #GDataQuery respects the gdata_query_set_max_results() call. + * + * For more details of Google Freebase API, see the + * online documentation. + * + * Since: 0.15.1 + * Deprecated: 0.17.7: Google Freebase has been permanently shut down. + */ + +#include +#include +#include +#include +#include + +#include "gdata-freebase-query.h" +#include "gdata-query.h" +#include "gdata-parser.h" +#include "gdata-private.h" + +G_GNUC_BEGIN_IGNORE_DEPRECATIONS + +static void gdata_freebase_query_finalize (GObject *self); +static void gdata_freebase_query_set_property (GObject *self, guint prop_id, const GValue *value, GParamSpec *pspec); +static void gdata_freebase_query_get_property (GObject *self, guint prop_id, GValue *value, GParamSpec *pspec); +static void get_query_uri (GDataQuery *self, const gchar *feed_uri, GString *query_uri, gboolean *params_started); + +struct _GDataFreebaseQueryPrivate { + /* These params are here not in GDataQuery due of differently named query params for JSON protocols therefore need for different parse_uri */ + GVariant *variant; + JsonNode *query_node; +}; + +enum { + PROP_VARIANT = 1, +}; + +G_DEFINE_TYPE (GDataFreebaseQuery, gdata_freebase_query, GDATA_TYPE_QUERY) + +static void +gdata_freebase_query_class_init (GDataFreebaseQueryClass *klass) +{ + GObjectClass *gobject_class = G_OBJECT_CLASS (klass); + GDataQueryClass *query_class = GDATA_QUERY_CLASS (klass); + + g_type_class_add_private (klass, sizeof (GDataFreebaseQueryPrivate)); + + gobject_class->finalize = gdata_freebase_query_finalize; + gobject_class->set_property = gdata_freebase_query_set_property; + gobject_class->get_property = gdata_freebase_query_get_property; + + query_class->get_query_uri = get_query_uri; + + /** + * GDataFreebaseQuery:variant: + * + * Variant containing the MQL query. The variant is a very generic container of type "a{smv}", + * containing (possibly nested) Freebase schema types and values. + * + * Since: 0.15.1 + * Deprecated: 0.17.7: Google Freebase has been permanently shut down. + */ + g_object_class_install_property (gobject_class, PROP_VARIANT, + g_param_spec_variant ("variant", + "Variant", + "Variant to construct the query from.", + G_VARIANT_TYPE ("a{smv}"), NULL, + G_PARAM_CONSTRUCT_ONLY | G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS | + G_PARAM_DEPRECATED)); +} + +static void +gdata_freebase_query_init (GDataFreebaseQuery *self) +{ + self->priv = G_TYPE_INSTANCE_GET_PRIVATE (self, GDATA_TYPE_FREEBASE_QUERY, GDataFreebaseQueryPrivate); + + /* https://developers.google.com/freebase/v1/search#cursor */ + _gdata_query_set_pagination_type (GDATA_QUERY (self), + GDATA_QUERY_PAGINATION_INDEXED); +} + +static void +gdata_freebase_query_finalize (GObject *self) +{ + GDataFreebaseQueryPrivate *priv = GDATA_FREEBASE_QUERY (self)->priv; + + if (priv->variant != NULL) + g_variant_unref (priv->variant); + if (priv->query_node != NULL) + json_node_free (priv->query_node); + /* Chain up to the parent class */ + G_OBJECT_CLASS (gdata_freebase_query_parent_class)->finalize (self); +} + +static void +gdata_freebase_query_set_property (GObject *self, guint prop_id, const GValue *value, GParamSpec *pspec) +{ + GDataFreebaseQueryPrivate *priv = GDATA_FREEBASE_QUERY (self)->priv; + + switch (prop_id) { + case PROP_VARIANT: + priv->variant = g_value_get_variant (value); + if (priv->variant) + priv->query_node = json_gvariant_serialize (priv->variant); + break; + default: + G_OBJECT_WARN_INVALID_PROPERTY_ID (self, prop_id, pspec); + break; + } +} + +static void +gdata_freebase_query_get_property (GObject *self, guint prop_id, GValue *value, GParamSpec *pspec) +{ + GDataFreebaseQueryPrivate *priv = GDATA_FREEBASE_QUERY (self)->priv; + + switch (prop_id) { + case PROP_VARIANT: + g_value_set_variant (value, priv->variant); + break; + default: + G_OBJECT_WARN_INVALID_PROPERTY_ID (self, prop_id, pspec); + break; + } +} + +static void +get_query_uri (GDataQuery *self, const gchar *feed_uri, GString *query_uri, gboolean *params_started) +{ + GDataFreebaseQueryPrivate *priv = GDATA_FREEBASE_QUERY (self)->priv; + const gchar *query; + +#define APPEND_SEP g_string_append_c (query_uri, (*params_started == FALSE) ? '?' : '&'); *params_started = TRUE; + + query = gdata_query_get_q (self); + + if (query != NULL) { + APPEND_SEP; + g_string_append (query_uri, "query="); + g_string_append (query_uri, query); + } else if (priv->query_node != NULL) { + JsonGenerator *generator; + JsonNode *copy; + gchar *json; + guint limit; + + copy = json_node_copy (priv->query_node); + + limit = gdata_query_get_max_results (self); + + if (limit > 0) { + JsonNode *limit_node; + JsonObject *object; + + limit_node = json_node_new (JSON_NODE_VALUE); + json_node_set_int (limit_node, limit); + + object = json_node_get_object (copy); + json_object_set_member (object, "limit", limit_node); + } + + generator = json_generator_new (); + json_generator_set_root (generator, copy); + json = json_generator_to_data (generator, NULL); + g_object_unref (generator); + + APPEND_SEP; + g_string_append (query_uri, "query="); + g_string_append (query_uri, json); + g_free (json); + } + + /* We don't chain up with parent class get_query_uri because it uses + * GData protocol parameters and they aren't compatible with newest API family + */ +#undef APPEND_SEP +} + +/** + * gdata_freebase_query_new: + * @mql: a MQL query string + * + * Creates a new #GDataFreebaseQuery with the MQL query provided in @mql. MQL + * is a JSON-based query language, analogous to SPARQL. To learn more about MQL, + * see the + * MQL overview and + * cookbook. + * + * For detailed information on Freebase schemas, The "Schema" + * section on the main site allows for natural search and navigation through the multiple data properties and domains. + * + * Return value: (transfer full): a new #GDataFreebaseQuery + * + * Since: 0.15.1 + * Deprecated: 0.17.7: Google Freebase has been permanently shut down. + */ +GDataFreebaseQuery * +gdata_freebase_query_new (const gchar *mql) +{ + g_return_val_if_fail (mql != NULL, NULL); + + return g_object_new (GDATA_TYPE_FREEBASE_QUERY, "q", mql, NULL); +} + +/** + * gdata_freebase_query_new_from_variant: + * @variant: a variant containing the MQL query structure + * + * Creates a new #GDataFreebaseQuery with the MQL query provided in a serialized form as @variant + * of type "a{smv}" containing the JSON data tree of a MQL query. One convenient way + * to build the variant is using json_gvariant_serialize() from a #JsonNode. For more information + * about MQL, see gdata_freebase_query_new(). + * + * #GDataFreebaseQuery takes ownership on @variant, if it has a floating reference, it will be sunk. + * Otherwise an extra reference will be added. + * + * Return value: (transfer full): a new #GDataFreebaseQuery + * + * Since: 0.15.1 + * Deprecated: 0.17.7: Google Freebase has been permanently shut down. + */ +GDataFreebaseQuery * +gdata_freebase_query_new_from_variant (GVariant *variant) +{ + g_return_val_if_fail (variant != NULL, NULL); + + return g_object_new (GDATA_TYPE_FREEBASE_QUERY, + "variant", g_variant_ref_sink (variant), + NULL); +} + +G_GNUC_END_IGNORE_DEPRECATIONS diff --git a/gdata/services/freebase/gdata-freebase-query.h b/gdata/services/freebase/gdata-freebase-query.h new file mode 100644 index 0000000..28c1070 --- /dev/null +++ b/gdata/services/freebase/gdata-freebase-query.h @@ -0,0 +1,81 @@ +/* -*- Mode: C; indent-tabs-mode: t; c-basic-offset: 8; tab-width: 8 -*- */ +/* + * GData Client + * Copyright (C) 2014 Carlos Garnacho + * + * GData Client is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * GData Client is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with GData Client. If not, see . + */ + +#ifndef GDATA_FREEBASE_QUERY_H +#define GDATA_FREEBASE_QUERY_H + +#include +#include + +#include +#include + +G_BEGIN_DECLS + +#ifndef LIBGDATA_DISABLE_DEPRECATED + +#define GDATA_TYPE_FREEBASE_QUERY (gdata_freebase_query_get_type ()) +#define GDATA_FREEBASE_QUERY(o) (G_TYPE_CHECK_INSTANCE_CAST ((o), GDATA_TYPE_FREEBASE_QUERY, GDataFreebaseQuery)) +#define GDATA_FREEBASE_QUERY_CLASS(k) (G_TYPE_CHECK_CLASS_CAST((k), GDATA_TYPE_FREEBASE_QUERY, GDataFreebaseQueryClass)) +#define GDATA_IS_FREEBASE_QUERY(o) (G_TYPE_CHECK_INSTANCE_TYPE ((o), GDATA_TYPE_FREEBASE_QUERY)) +#define GDATA_IS_FREEBASE_QUERY_CLASS(k) (G_TYPE_CHECK_CLASS_TYPE ((k), GDATA_TYPE_FREEBASE_QUERY)) +#define GDATA_FREEBASE_QUERY_GET_CLASS(o) (G_TYPE_INSTANCE_GET_CLASS ((o), GDATA_TYPE_FREEBASE_QUERY, GDataFreebaseQueryClass)) + +typedef struct _GDataFreebaseQueryPrivate GDataFreebaseQueryPrivate; + +/** + * GDataFreebaseQuery: + * + * All the fields in the #GDataFreebaseQuery structure are private and should never be accessed directly. + * + * Since: 0.15.1 + */ +typedef struct { + GDataQuery parent; + /*< private >*/ + GDataFreebaseQueryPrivate *priv; +} GDataFreebaseQuery; + +/** + * GDataFreebaseQueryClass: + * + * All the fields in the #GDataFreebaseQueryClass structure are private and should never be accessed directly. + * + * Since: 0.15.1 + */ +typedef struct { + /*< private >*/ + GDataQueryClass parent; + + /*< private >*/ + /* Padding for future expansion */ + void (*_g_reserved0) (void); + void (*_g_reserved1) (void); +} GDataFreebaseQueryClass; + +GType gdata_freebase_query_get_type (void) G_GNUC_CONST G_GNUC_DEPRECATED; + +GDataFreebaseQuery *gdata_freebase_query_new (const gchar *mql) G_GNUC_WARN_UNUSED_RESULT G_GNUC_MALLOC G_GNUC_DEPRECATED; +GDataFreebaseQuery *gdata_freebase_query_new_from_variant (GVariant *variant) G_GNUC_WARN_UNUSED_RESULT G_GNUC_MALLOC G_GNUC_DEPRECATED; + +#endif /* !LIBGDATA_DISABLE_DEPRECATED */ + +G_END_DECLS + +#endif /* !GDATA_FREEBASE_QUERY_H */ diff --git a/gdata/services/freebase/gdata-freebase-result.c b/gdata/services/freebase/gdata-freebase-result.c new file mode 100644 index 0000000..56c9022 --- /dev/null +++ b/gdata/services/freebase/gdata-freebase-result.c @@ -0,0 +1,205 @@ +/* -*- Mode: C; indent-tabs-mode: t; c-basic-offset: 8; tab-width: 8 -*- */ +/* + * GData Client + * Copyright (C) 2014 Carlos Garnacho + * + * GData Client is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * GData Client is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with GData Client. If not, see . + */ + +/** + * SECTION:gdata-freebase-result + * @short_description: GData Freebase result object + * @stability: Stable + * @include: gdata/services/freebase/gdata-freebase-result.h + * + * #GDataFreebaseResult is a subclass of #GDataEntry to represent the result of a Google Freebase MQL query. + * + * For more details of Google Freebase API, see the + * online documentation. + * + * Since: 0.15.1 + * Deprecated: 0.17.7: Google Freebase has been permanently shut down. + */ + +#include +#include +#include +#include + +#include "gdata-freebase-result.h" +#include "gdata-private.h" +#include "gdata-types.h" + +G_GNUC_BEGIN_IGNORE_DEPRECATIONS + +#define URLBASE "https://www.googleapis.com/freebase/v1/" + +enum { + PROP_VARIANT = 1 +}; + +struct _GDataFreebaseResultPrivate { + GVariant *result; +}; + +static void gdata_freebase_result_finalize (GObject *self); +static void gdata_freebase_result_get_property (GObject *self, guint prop_id, GValue *value, GParamSpec *pspec); +static gboolean parse_json (GDataParsable *parsable, JsonReader *reader, gpointer user_data, GError **error); +static const gchar *get_content_type (void); +static gchar *get_entry_uri (const gchar *id); + +G_DEFINE_TYPE (GDataFreebaseResult, gdata_freebase_result, GDATA_TYPE_ENTRY) + +static void +gdata_freebase_result_class_init (GDataFreebaseResultClass *klass) +{ + GDataParsableClass *parsable_class = GDATA_PARSABLE_CLASS (klass); + GDataEntryClass *entry_class = GDATA_ENTRY_CLASS (klass); + GObjectClass *gobject_class = G_OBJECT_CLASS (klass); + + g_type_class_add_private (klass, sizeof (GDataFreebaseResultPrivate)); + + gobject_class->finalize = gdata_freebase_result_finalize; + gobject_class->get_property = gdata_freebase_result_get_property; + + parsable_class->parse_json = parse_json; + parsable_class->get_content_type = get_content_type; + entry_class->get_entry_uri = get_entry_uri; + + /** + * GDataFreebaseResult:variant: + * + * Variant containing the MQL result. The variant is a very generic container of type "a{smv}", + * containing (possibly nested) Freebase schema types and values. + * + * Since: 0.15.1 + * Deprecated: 0.17.7: Google Freebase has been permanently shut down. + */ + g_object_class_install_property (gobject_class, PROP_VARIANT, + g_param_spec_variant ("variant", + "Variant", "Variant holding the raw result.", + G_VARIANT_TYPE ("a{smv}"), NULL, + G_PARAM_READABLE | G_PARAM_STATIC_STRINGS | + G_PARAM_DEPRECATED)); +} + +static void +gdata_freebase_result_init (GDataFreebaseResult *self) +{ + self->priv = G_TYPE_INSTANCE_GET_PRIVATE (self, GDATA_TYPE_FREEBASE_RESULT, GDataFreebaseResultPrivate); +} + +static void +gdata_freebase_result_finalize (GObject *self) +{ + GDataFreebaseResultPrivate *priv = GDATA_FREEBASE_RESULT (self)->priv; + + if (priv->result != NULL) + g_variant_unref (priv->result); + + G_OBJECT_CLASS (gdata_freebase_result_parent_class)->finalize (self); +} + +static void +gdata_freebase_result_get_property (GObject *self, guint prop_id, GValue *value, GParamSpec *pspec) +{ + GDataFreebaseResultPrivate *priv = GDATA_FREEBASE_RESULT (self)->priv; + + switch (prop_id) { + case PROP_VARIANT: + g_value_set_variant (value, priv->result); + break; + default: + G_OBJECT_WARN_INVALID_PROPERTY_ID (self, prop_id, pspec); + break; + } +} + +static gboolean +parse_json (GDataParsable *parsable, JsonReader *reader, gpointer user_data, GError **error) +{ + GDataFreebaseResultPrivate *priv = GDATA_FREEBASE_RESULT (parsable)->priv; + JsonNode *root, *node; + JsonObject *object; + + if (g_strcmp0 (json_reader_get_member_name (reader), "result") != 0) + return TRUE; + + g_object_get (reader, "root", &root, NULL); + object = json_node_get_object (root); + node = json_object_get_member (object, "result"); + + priv->result = g_variant_ref_sink (json_gvariant_deserialize (node, NULL, error)); + json_node_free (root); + + return (priv->result != NULL); +} + +static const gchar * +get_content_type (void) +{ + return "application/json"; +} + +static gchar * +get_entry_uri (const gchar *id) +{ + /* https://www.googleapis.com/freebase/v1/mqlread interface */ + return g_strconcat (URLBASE, id, NULL); +} + +/** + * gdata_freebase_result_new: + * + * Creates a new #GDataFreebaseResult. + * + * Return value: (transfer full): a new #GDataFreebaseResult; unref with g_object_unref() + * + * Since: 0.15.1 + * Deprecated: 0.17.7: Google Freebase has been permanently shut down. + */ +GDataFreebaseResult * +gdata_freebase_result_new (void) +{ + return g_object_new (GDATA_TYPE_FREEBASE_RESULT, NULL); +} + +/** + * gdata_freebase_result_dup_variant: + * @self: a #GDataFreebaseResult + * + * Gets the result serialized as a #GVariant of type "a{smv}", containing the JSON + * data tree. This variant can be alternatively processed through json_gvariant_serialize(). + * + * Returns: (allow-none) (transfer full): the serialized result, or %NULL; unref with g_variant_unref() + * + * Since: 0.15.1 + * Deprecated: 0.17.7: Google Freebase has been permanently shut down. + */ +GVariant * +gdata_freebase_result_dup_variant (GDataFreebaseResult *self) +{ + GDataFreebaseResultPrivate *priv; + + g_return_val_if_fail (GDATA_IS_FREEBASE_RESULT (self), NULL); + + priv = self->priv; + + if (priv->result == NULL) + return NULL; + + return g_variant_ref (priv->result); +} + +G_GNUC_END_IGNORE_DEPRECATIONS diff --git a/gdata/services/freebase/gdata-freebase-result.h b/gdata/services/freebase/gdata-freebase-result.h new file mode 100644 index 0000000..1f4950c --- /dev/null +++ b/gdata/services/freebase/gdata-freebase-result.h @@ -0,0 +1,81 @@ +/* -*- Mode: C; indent-tabs-mode: t; c-basic-offset: 8; tab-width: 8 -*- */ +/* + * GData Client + * Copyright (C) 2014 Carlos Garnacho + * + * GData Client is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * GData Client is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with GData Client. If not, see . + */ + +#ifndef GDATA_FREEBASE_RESULT_H +#define GDATA_FREEBASE_RESULT_H + +#include +#include + +#include +#include + +G_BEGIN_DECLS + +#ifndef LIBGDATA_DISABLE_DEPRECATED + +#define GDATA_TYPE_FREEBASE_RESULT (gdata_freebase_result_get_type ()) +#define GDATA_FREEBASE_RESULT(o) (G_TYPE_CHECK_INSTANCE_CAST ((o), GDATA_TYPE_FREEBASE_RESULT, GDataFreebaseResult)) +#define GDATA_FREEBASE_RESULT_CLASS(k) (G_TYPE_CHECK_CLASS_CAST((k), GDATA_TYPE_FREEBASE_RESULT, GDataFreebaseResultClass)) +#define GDATA_IS_FREEBASE_RESULT(o) (G_TYPE_CHECK_INSTANCE_TYPE ((o), GDATA_TYPE_FREEBASE_RESULT)) +#define GDATA_IS_FREEBASE_RESULT_CLASS(k) (G_TYPE_CHECK_CLASS_TYPE ((k), GDATA_TYPE_FREEBASE_RESULT)) +#define GDATA_FREEBASE_RESULT_GET_CLASS(o) (G_TYPE_INSTANCE_GET_CLASS ((o), GDATA_TYPE_FREEBASE_RESULT, GDataFreebaseResultClass)) + +typedef struct _GDataFreebaseResultPrivate GDataFreebaseResultPrivate; + +/** + * GDataFreebaseResult: + * + * All the fields in the #GDataFreebaseResult structure are private and should never be accessed directly. + * + * Since: 0.15.1 + */ +typedef struct { + GDataEntry parent; + GDataFreebaseResultPrivate *priv; +} GDataFreebaseResult; + +/** + * GDataFreebaseResultClass: + * + * All the fields in the #GDataFreebaseResultClass structure are private and should never be accessed directly. + * + * Since: 0.15.1 + */ + +typedef struct { + /*< private >*/ + GDataEntryClass parent; + + /*< private >*/ + /* Padding for future expansion */ + void (*_g_reserved0) (void); + void (*_g_reserved1) (void); +} GDataFreebaseResultClass; + +GType gdata_freebase_result_get_type (void) G_GNUC_CONST G_GNUC_DEPRECATED; + +GDataFreebaseResult *gdata_freebase_result_new (void) G_GNUC_WARN_UNUSED_RESULT G_GNUC_MALLOC G_GNUC_DEPRECATED; +GVariant *gdata_freebase_result_dup_variant (GDataFreebaseResult *self) G_GNUC_WARN_UNUSED_RESULT G_GNUC_DEPRECATED; + +#endif /* !LIBGDATA_DISABLE_DEPRECATED */ + +G_END_DECLS + +#endif /* !GDATA_FREEBASE_RESULT_H */ diff --git a/gdata/services/freebase/gdata-freebase-search-query.c b/gdata/services/freebase/gdata-freebase-search-query.c new file mode 100644 index 0000000..fc09a2d --- /dev/null +++ b/gdata/services/freebase/gdata-freebase-search-query.c @@ -0,0 +1,626 @@ +/* -*- Mode: C; indent-tabs-mode: t; c-basic-offset: 8; tab-width: 8 -*- */ +/* + * GData Client + * Copyright (C) 2014 Carlos Garnacho + * + * GData Client is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * GData Client is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with GData Client. If not, see . + */ + +/** + * SECTION:gdata-freebase-search-query + * @short_description: GData Freebase query object + * @stability: Stable + * @include: gdata/services/freebase/gdata-freebase-query.h + * + * #GDataFreebaseQuery represents a collection of query parameters specific to the Google Freebase service. + * a #GDataFreebaseQuery is built on top of a search term, further filters can be set on the search query + * through gdata_freebase_search_query_add_filter() or gdata_freebase_search_query_add_location(). The filters + * can be nested in sublevels, created through gdata_freebase_search_query_open_filter() + * and gdata_freebase_search_query_close_filter(). + * + * For more details of Google Freebase API, see the + * online documentation. + * + * Since: 0.15.1 + * Deprecated: 0.17.7: Google Freebase has been permanently shut down. + */ + +#include +#include +#include +#include +#include + +#include "gdata-freebase-search-query.h" +#include "gdata-query.h" +#include "gdata-parser.h" + +G_GNUC_BEGIN_IGNORE_DEPRECATIONS + +static void gdata_freebase_search_query_finalize (GObject *self); +static void gdata_freebase_search_query_set_property (GObject *self, guint prop_id, const GValue *value, GParamSpec *pspec); +static void gdata_freebase_search_query_get_property (GObject *self, guint prop_id, GValue *value, GParamSpec *pspec); +static void get_query_uri (GDataQuery *self, const gchar *feed_uri, GString *query_uri, gboolean *params_started); + +typedef enum { + NODE_CONTAINER, + NODE_VALUE, + NODE_LOCATION +} FilterNodeType; + +typedef union { + FilterNodeType type; + + struct { + FilterNodeType type; + GDataFreebaseSearchFilterType filter_type; + GPtrArray *child_nodes; /* Contains owned FilterNode structs */ + } container; + + struct { + FilterNodeType type; + gchar *property; + gchar *value; + } value; + + struct { + FilterNodeType type; + guint64 radius; + gdouble lat; + gdouble lon; + } location; +} FilterNode; + +struct _GDataFreebaseSearchQueryPrivate { + FilterNode *filter; + GList *filter_stack; /* Contains unowned FilterNode structs */ + + gchar *lang; + guint stemmed : 1; +}; + +enum { + PROP_LANGUAGE = 1, + PROP_STEMMED +}; + +G_DEFINE_TYPE (GDataFreebaseSearchQuery, gdata_freebase_search_query, GDATA_TYPE_QUERY) + +static void +gdata_freebase_search_query_class_init (GDataFreebaseSearchQueryClass *klass) +{ + GObjectClass *gobject_class = G_OBJECT_CLASS (klass); + GDataQueryClass *query_class = GDATA_QUERY_CLASS (klass); + + g_type_class_add_private (klass, sizeof (GDataFreebaseSearchQueryPrivate)); + + gobject_class->finalize = gdata_freebase_search_query_finalize; + gobject_class->set_property = gdata_freebase_search_query_set_property; + gobject_class->get_property = gdata_freebase_search_query_get_property; + + query_class->get_query_uri = get_query_uri; + + /** + * GDataFreebaseSearchQuery:language: + * + * Language used for search results, in ISO-639-1 format. + * + * Since: 0.15.1 + * Deprecated: 0.17.7: Google Freebase has been permanently shut down. + */ + g_object_class_install_property (gobject_class, PROP_LANGUAGE, + g_param_spec_string ("language", + "Language used for results", + "Language in ISO-639-1 format.", + NULL, + G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS | + G_PARAM_DEPRECATED)); + /** + * GDataFreebaseSearchQuery:stemmed: + * + * Whether word stemming should happen on the search terms. If this property is enabled, + * words like eg. "natural", "naturally" or "nature" would be all reduced to the root "natur" + * for search purposes. + * + * Since: 0.15.1 + * Deprecated: 0.17.7: Google Freebase has been permanently shut down. + */ + g_object_class_install_property (gobject_class, PROP_STEMMED, + g_param_spec_boolean ("stemmed", + "Stem search terms", + "Whether the search terms should be stemmed", + FALSE, + G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS | + G_PARAM_DEPRECATED)); +} + +static void +gdata_freebase_search_query_init (GDataFreebaseSearchQuery *self) +{ + self->priv = G_TYPE_INSTANCE_GET_PRIVATE (self, GDATA_TYPE_FREEBASE_SEARCH_QUERY, GDataFreebaseSearchQueryPrivate); +} + +static void +_free_filter_node (FilterNode *node) +{ + switch (node->type) { + case NODE_CONTAINER: + g_ptr_array_unref (node->container.child_nodes); + break; + case NODE_VALUE: + g_free (node->value.property); + g_free (node->value.value); + break; + case NODE_LOCATION: + default: + break; + } + + g_slice_free (FilterNode, node); +} + +static void +gdata_freebase_search_query_finalize (GObject *self) +{ + GDataFreebaseSearchQueryPrivate *priv = GDATA_FREEBASE_SEARCH_QUERY (self)->priv; + + g_free (priv->lang); + g_list_free (priv->filter_stack); + + if (priv->filter != NULL) + _free_filter_node (priv->filter); + + /* Chain up to the parent class */ + G_OBJECT_CLASS (gdata_freebase_search_query_parent_class)->finalize (self); +} + +static void +gdata_freebase_search_query_set_property (GObject *self, guint prop_id, const GValue *value, GParamSpec *pspec) +{ + GDataFreebaseSearchQuery *query = GDATA_FREEBASE_SEARCH_QUERY (self); + + switch (prop_id) { + case PROP_LANGUAGE: + gdata_freebase_search_query_set_language (query, g_value_get_string (value)); + break; + case PROP_STEMMED: + gdata_freebase_search_query_set_stemmed (query, g_value_get_boolean (value)); + break; + default: + G_OBJECT_WARN_INVALID_PROPERTY_ID (self, prop_id, pspec); + break; + } +} + +static void +gdata_freebase_search_query_get_property (GObject *self, guint prop_id, GValue *value, GParamSpec *pspec) +{ + GDataFreebaseSearchQueryPrivate *priv = GDATA_FREEBASE_SEARCH_QUERY (self)->priv; + + switch (prop_id) { + case PROP_LANGUAGE: + g_value_set_string (value, priv->lang); + break; + case PROP_STEMMED: + g_value_set_boolean (value, priv->stemmed); + break; + default: + G_OBJECT_WARN_INVALID_PROPERTY_ID (self, prop_id, pspec); + break; + } +} + +static void +build_filter_string (FilterNode *node, + GString *str) +{ + switch (node->type) { + case NODE_CONTAINER: + { + /* Array matches GDataFreebaseSearchFilterType */ + const gchar *type_str[] = { "all", "any", "not" }; + guint i; + + g_assert (/* node->container.filter_type >= 0 && */ + node->container.filter_type < G_N_ELEMENTS (type_str)); + + g_string_append_printf (str, "(%s", type_str[node->container.filter_type]); + + for (i = 0; i < node->container.child_nodes->len; i++) + build_filter_string (g_ptr_array_index (node->container.child_nodes, i), str); + + g_string_append (str, ")"); + break; + } + case NODE_VALUE: + { + gchar *escaped; + + escaped = g_strescape (node->value.value, NULL); + g_string_append_printf (str, " %s:\"%s\"", node->value.property, escaped); + g_free (escaped); + break; + } + case NODE_LOCATION: + { + gchar lon_str[G_ASCII_DTOSTR_BUF_SIZE], lat_str[G_ASCII_DTOSTR_BUF_SIZE]; + + g_ascii_formatd (lon_str, G_ASCII_DTOSTR_BUF_SIZE, "%.4f", node->location.lon); + g_ascii_formatd (lat_str, G_ASCII_DTOSTR_BUF_SIZE, "%.4f", node->location.lat); + g_string_append_printf (str, "(within radius:%" G_GUINT64_FORMAT "m lon:%s lat:%s)", + node->location.radius, lon_str, lat_str); + break; + } + default: + g_assert_not_reached (); + break; + } +} + +static void +get_query_uri (GDataQuery *self, const gchar *feed_uri, GString *query_uri, gboolean *params_started) +{ + GDataFreebaseSearchQueryPrivate *priv = GDATA_FREEBASE_SEARCH_QUERY (self)->priv; + const gchar *query, *lang = NULL; + gint64 updated_max; + guint cur, limit; + +#define APPEND_SEP g_string_append_c (query_uri, (*params_started == FALSE) ? '?' : '&'); *params_started = TRUE; + + query = gdata_query_get_q (self); + + if (query != NULL) { + APPEND_SEP; + g_string_append (query_uri, "query="); + g_string_append (query_uri, query); + } + + if (priv->filter != NULL) { + GString *str = g_string_new (NULL); + + build_filter_string (priv->filter, str); + + APPEND_SEP; + g_string_append (query_uri, "filter="); + g_string_append (query_uri, str->str); + g_string_free (str, TRUE); + } + + updated_max = gdata_query_get_updated_max (self); + + if (updated_max != -1) { + gchar *date_str; + + date_str = gdata_parser_int64_to_iso8601 (updated_max); + + APPEND_SEP; + g_string_append (query_uri, "as_of_time="); + g_string_append (query_uri, date_str); + g_free (date_str); + } + + if (priv->lang != NULL) { + lang = priv->lang; + } else { + const gchar * const *user_languages; + GString *lang_str = NULL; + gint i; + + user_languages = g_get_language_names (); + + for (i = 0; user_languages[i] != NULL; i++) { + if (strlen (user_languages[i]) != 2) + continue; + + if (!lang_str) + lang_str = g_string_new (user_languages[i]); + else + g_string_append_printf (lang_str, ",%s", user_languages[i]); + } + + lang = g_string_free (lang_str, FALSE); + } + + APPEND_SEP; + g_string_append (query_uri, "lang="); + g_string_append (query_uri, lang); + + if (priv->stemmed) { + APPEND_SEP; + g_string_append (query_uri, "stemmed=true"); + } + + cur = gdata_query_get_start_index (self); + + if (cur > 0) { + APPEND_SEP; + g_string_append_printf (query_uri, "cursor=%d", cur); + } + + limit = gdata_query_get_max_results (self); + + if (limit > 0) { + APPEND_SEP; + g_string_append_printf (query_uri, "limit=%d", limit); + } + + /* We don't chain up with parent class get_query_uri because it uses + * GData protocol parameters and they aren't compatible with newest API family + */ +#undef APPEND_SEP +} + +/** + * gdata_freebase_search_query_new: + * @search_terms: string to search for + * + * Creates a new #GDataFreebaseSearchQuery prepared to search for Freebase elements that + * match the given @search_terms. Further filters on the query can be set through + * gdata_freebase_search_query_add_filter() or gdata_freebase_search_query_add_location(). + * + * Return value: (transfer full): a new #GDataFreebaseSearchQuery; unref with g_object_unref() + * + * Since: 0.15.1 + * Deprecated: 0.17.7: Google Freebase has been permanently shut down. + */ +GDataFreebaseSearchQuery * +gdata_freebase_search_query_new (const gchar *search_terms) +{ + g_return_val_if_fail (search_terms != NULL, NULL); + return g_object_new (GDATA_TYPE_FREEBASE_SEARCH_QUERY, "q", search_terms, NULL); +} + +/** + * gdata_freebase_search_query_open_filter: + * @self: a #GDataFreebaseSearchQuery + * @filter_type: filter type + * + * Opens a container of filter rules, those are applied according to the behavior specified by @filter_type. + * Every call to this function must be paired by a call to gdata_freebase_search_query_close_filter(). + * + * Since: 0.15.1 + * Deprecated: 0.17.7: Google Freebase has been permanently shut down. + */ +void +gdata_freebase_search_query_open_filter (GDataFreebaseSearchQuery *self, GDataFreebaseSearchFilterType filter_type) +{ + GDataFreebaseSearchQueryPrivate *priv; + FilterNode *current_node, *node; + + g_return_if_fail (GDATA_IS_FREEBASE_SEARCH_QUERY (self)); + + priv = GDATA_FREEBASE_SEARCH_QUERY (self)->priv; + + node = g_slice_new0 (FilterNode); + node->type = NODE_CONTAINER; + node->container.filter_type = filter_type; + node->container.child_nodes = g_ptr_array_new_with_free_func ((GDestroyNotify) _free_filter_node); + + if (priv->filter_stack != NULL) { + current_node = priv->filter_stack->data; + g_ptr_array_add (current_node->container.child_nodes, node); + } else if (priv->filter == NULL) { + priv->filter = node; + } else { + g_assert_not_reached (); + } + + priv->filter_stack = g_list_prepend (priv->filter_stack, node); +} + +/** + * gdata_freebase_search_query_close_filter: + * @self: a #GDataFreebaseSearchQuery + * + * Closes a filter level. + * + * Since: 0.15.1 + * Deprecated: 0.17.7: Google Freebase has been permanently shut down. + */ +void +gdata_freebase_search_query_close_filter (GDataFreebaseSearchQuery *self) +{ + GDataFreebaseSearchQueryPrivate *priv; + + g_return_if_fail (GDATA_IS_FREEBASE_SEARCH_QUERY (self)); + + priv = GDATA_FREEBASE_SEARCH_QUERY (self)->priv; + + if (priv->filter_stack == NULL) + g_assert_not_reached (); + + priv->filter_stack = g_list_delete_link (priv->filter_stack, priv->filter_stack); +} + +/** + * gdata_freebase_search_query_add_filter: + * @self: a #GDataFreebaseSearchQuery + * @property: Freebase property ID + * @value: match string + * + * Adds a property filter to the query. property filters are always nested in + * containers, opened and closed through gdata_freebase_search_query_open_filter() + * and gdata_freebase_search_query_close_filter(). + * + * Since: 0.15.1 + * Deprecated: 0.17.7: Google Freebase has been permanently shut down. + */ +void +gdata_freebase_search_query_add_filter (GDataFreebaseSearchQuery *self, const gchar *property, const gchar *value) +{ + GDataFreebaseSearchQueryPrivate *priv; + FilterNode *current_node, *node; + + g_return_if_fail (GDATA_IS_FREEBASE_SEARCH_QUERY (self)); + g_return_if_fail (property != NULL && value != NULL); + + priv = GDATA_FREEBASE_SEARCH_QUERY (self)->priv; + + if (priv->filter_stack == NULL) { + g_critical ("A filter container must be opened before through " + "gdata_freebase_search_query_open_filter()"); + g_assert_not_reached (); + } + + node = g_slice_new0 (FilterNode); + node->type = NODE_VALUE; + node->value.property = g_strdup (property); + node->value.value = g_strdup (value); + + current_node = priv->filter_stack->data; + g_ptr_array_add (current_node->container.child_nodes, node); +} + +/** + * gdata_freebase_search_query_add_location: + * @self: a #GDataFreebaseSearchQuery + * @radius: radius in meters + * @lat: latitude + * @lon: longitude + * + * Adds a geolocation filter to the query. location filters are always nested in + * containers, opened and closed through gdata_freebase_search_query_open_filter() + * and gdata_freebase_search_query_close_filter(). + * + * Since: 0.15.1 + * Deprecated: 0.17.7: Google Freebase has been permanently shut down. + */ +void +gdata_freebase_search_query_add_location (GDataFreebaseSearchQuery *self, guint64 radius, gdouble lat, gdouble lon) +{ + GDataFreebaseSearchQueryPrivate *priv = GDATA_FREEBASE_SEARCH_QUERY (self)->priv; + FilterNode *current_node, *node; + + g_return_if_fail (GDATA_IS_FREEBASE_SEARCH_QUERY (self)); + + if (priv->filter_stack == NULL) { + g_critical ("A filter container must be opened before through " + "gdata_freebase_search_query_open_filter()"); + g_assert_not_reached (); + } + + node = g_slice_new0 (FilterNode); + node->type = NODE_LOCATION; + node->location.radius = radius; + node->location.lat = lat; + node->location.lon = lon; + + current_node = priv->filter_stack->data; + g_ptr_array_add (current_node->container.child_nodes, node); +} + +/** + * gdata_freebase_search_query_set_language: + * @self: a #GDataFreebaseSearchQuery + * @lang: (allow-none): Language used on the search terms and results, in ISO-639-1 format, or %NULL to unset. + * + * Sets the language used, both on the search terms and the results. If unset, + * the locale preferences will be respected. + * + * Since: 0.15.1 + * Deprecated: 0.17.7: Google Freebase has been permanently shut down. + */ +void +gdata_freebase_search_query_set_language (GDataFreebaseSearchQuery *self, + const gchar *lang) +{ + GDataFreebaseSearchQueryPrivate *priv; + + g_return_if_fail (GDATA_IS_FREEBASE_SEARCH_QUERY (self)); + g_return_if_fail (!lang || strlen (lang) == 2); + + priv = self->priv; + + if (g_strcmp0 (priv->lang, lang) == 0) + return; + + g_free (priv->lang); + priv->lang = g_strdup (lang); + g_object_notify (G_OBJECT (self), "language"); +} + +/** + * gdata_freebase_search_query_get_language: + * @self: a #GDataFreebaseSearchQuery + * + * Gets the language set on the search query, or %NULL if unset. + * + * Return value: (allow-none): The language used on the query. + * + * Since: 0.15.1 + * Deprecated: 0.17.7: Google Freebase has been permanently shut down. + */ +const gchar * +gdata_freebase_search_query_get_language (GDataFreebaseSearchQuery *self) +{ + GDataFreebaseSearchQueryPrivate *priv; + + g_return_val_if_fail (GDATA_IS_FREEBASE_SEARCH_QUERY (self), NULL); + + priv = self->priv; + return priv->lang; +} + +/** + * gdata_freebase_search_query_set_stemmed: + * @self: a #GDataFreebaseSearchQuery + * @stemmed: %TRUE to perform stemming on the search results + * + * Sets whether stemming is performed on the provided search terms. If @stemmed is %TRUE, + * words like eg. "natural", "naturally" or "nature" would be all reduced to the root "natur" + * for search purposes. + * + * Since: 0.15.1 + * Deprecated: 0.17.7: Google Freebase has been permanently shut down. + */ +void +gdata_freebase_search_query_set_stemmed (GDataFreebaseSearchQuery *self, + gboolean stemmed) +{ + GDataFreebaseSearchQueryPrivate *priv; + + g_return_if_fail (GDATA_IS_FREEBASE_SEARCH_QUERY (self)); + + priv = self->priv; + + if (priv->stemmed == stemmed) + return; + + priv->stemmed = stemmed; + g_object_notify (G_OBJECT (self), "stemmed"); +} + +/** + * gdata_freebase_search_query_get_stemmed: + * @self: a #GDataFreebaseSearchQuery + * + * Returns whether the #GDataFreebaseSearchQuery will perform stemming on the search terms. + * + * Return value: %TRUE if the #GDataFreebaseSearchQuery performs stemming + * + * Since: 0.15.1 + * Deprecated: 0.17.7: Google Freebase has been permanently shut down. + */ +gboolean +gdata_freebase_search_query_get_stemmed (GDataFreebaseSearchQuery *self) +{ + GDataFreebaseSearchQueryPrivate *priv; + + g_return_val_if_fail (GDATA_IS_FREEBASE_SEARCH_QUERY (self), FALSE); + + priv = self->priv; + return priv->stemmed; +} + +G_GNUC_END_IGNORE_DEPRECATIONS diff --git a/gdata/services/freebase/gdata-freebase-search-query.h b/gdata/services/freebase/gdata-freebase-search-query.h new file mode 100644 index 0000000..7c7927b --- /dev/null +++ b/gdata/services/freebase/gdata-freebase-search-query.h @@ -0,0 +1,106 @@ +/* -*- Mode: C; indent-tabs-mode: t; c-basic-offset: 8; tab-width: 8 -*- */ +/* + * GData Client + * Copyright (C) 2014 Carlos Garnacho + * + * GData Client is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * GData Client is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with GData Client. If not, see . + */ + +#ifndef GDATA_FREEBASE_SEARCH_QUERY_H +#define GDATA_FREEBASE_SEARCH_QUERY_H + +#include +#include + +#include +#include + +G_BEGIN_DECLS + +#ifndef LIBGDATA_DISABLE_DEPRECATED + +#define GDATA_TYPE_FREEBASE_SEARCH_QUERY (gdata_freebase_search_query_get_type ()) +#define GDATA_FREEBASE_SEARCH_QUERY(o) (G_TYPE_CHECK_INSTANCE_CAST ((o), GDATA_TYPE_FREEBASE_SEARCH_QUERY, GDataFreebaseSearchQuery)) +#define GDATA_FREEBASE_SEARCH_QUERY_CLASS(k) (G_TYPE_CHECK_CLASS_CAST((k), GDATA_TYPE_FREEBASE_SEARCH_QUERY, GDataFreebaseSearchQueryClass)) +#define GDATA_IS_FREEBASE_SEARCH_QUERY(o) (G_TYPE_CHECK_INSTANCE_TYPE ((o), GDATA_TYPE_FREEBASE_SEARCH_QUERY)) +#define GDATA_IS_FREEBASE_SEARCH_QUERY_CLASS(k) (G_TYPE_CHECK_CLASS_TYPE ((k), GDATA_TYPE_FREEBASE_SEARCH_QUERY)) +#define GDATA_FREEBASE_SEARCH_QUERY_GET_CLASS(o) (G_TYPE_INSTANCE_GET_CLASS ((o), GDATA_TYPE_FREEBASE_SEARCH_QUERY, GDataFreebaseSearchQueryClass)) + +typedef struct _GDataFreebaseSearchQueryPrivate GDataFreebaseSearchQueryPrivate; + +/** + * GDataFreebaseSearchFilterType: + * @GDATA_FREEBASE_SEARCH_FILTER_ALL: all enclosed elements must match, logically an AND + * @GDATA_FREEBASE_SEARCH_FILTER_ANY: any of the enclosed elements must match, logically an OR + * @GDATA_FREEBASE_SEARCH_FILTER_NOT: the match is inverted. + * + * Search filter container types. + * + * Since: 0.15.1 + */ +typedef enum { + GDATA_FREEBASE_SEARCH_FILTER_ALL, + GDATA_FREEBASE_SEARCH_FILTER_ANY, + GDATA_FREEBASE_SEARCH_FILTER_NOT +} GDataFreebaseSearchFilterType; + +/** + * GDataFreebaseSearchQuery: + * + * All the fields in the #GDataFreebaseSearchQuery structure are private and should never be accessed directly. + * + * Since: 0.15.1 + */ +typedef struct { + GDataQuery parent; + GDataFreebaseSearchQueryPrivate *priv; +} GDataFreebaseSearchQuery; + +/** + * GDataFreebaseSearchQueryClass: + * + * All the fields in the #GDataFreebaseSearchQueryClass structure are private and should never be accessed directly. + * + * Since: 0.15.1 + */ +typedef struct { + /*< private >*/ + GDataQueryClass parent; + + /*< private >*/ + /* Padding for future expansion */ + void (*_g_reserved0) (void); + void (*_g_reserved1) (void); +} GDataFreebaseSearchQueryClass; + +GType gdata_freebase_search_query_get_type (void) G_GNUC_CONST G_GNUC_DEPRECATED; + +GDataFreebaseSearchQuery *gdata_freebase_search_query_new (const gchar *search_terms) G_GNUC_WARN_UNUSED_RESULT G_GNUC_MALLOC G_GNUC_DEPRECATED; + +void gdata_freebase_search_query_open_filter (GDataFreebaseSearchQuery *self, GDataFreebaseSearchFilterType filter_type) G_GNUC_DEPRECATED; +void gdata_freebase_search_query_close_filter (GDataFreebaseSearchQuery *self) G_GNUC_DEPRECATED; +void gdata_freebase_search_query_add_filter (GDataFreebaseSearchQuery *self, const gchar *property, const gchar *value) G_GNUC_DEPRECATED; +void gdata_freebase_search_query_add_location (GDataFreebaseSearchQuery *self, guint64 radius, gdouble lat, gdouble lon) G_GNUC_DEPRECATED; + +void gdata_freebase_search_query_set_language (GDataFreebaseSearchQuery *self, const gchar *lang) G_GNUC_DEPRECATED; +const gchar * gdata_freebase_search_query_get_language (GDataFreebaseSearchQuery *self) G_GNUC_DEPRECATED; + +void gdata_freebase_search_query_set_stemmed (GDataFreebaseSearchQuery *self, gboolean stemmed) G_GNUC_DEPRECATED; +gboolean gdata_freebase_search_query_get_stemmed (GDataFreebaseSearchQuery *self) G_GNUC_DEPRECATED; + +#endif /* !LIBGDATA_DISABLE_DEPRECATED */ + +G_END_DECLS + +#endif /* !GDATA_FREEBASE_SEARCH_QUERY_H */ diff --git a/gdata/services/freebase/gdata-freebase-search-result.c b/gdata/services/freebase/gdata-freebase-search-result.c new file mode 100644 index 0000000..c36ad1c --- /dev/null +++ b/gdata/services/freebase/gdata-freebase-search-result.c @@ -0,0 +1,432 @@ +/* -*- Mode: C; indent-tabs-mode: t; c-basic-offset: 8; tab-width: 8 -*- */ +/* + * GData Client + * Copyright (C) 2014 Carlos Garnacho + * + * GData Client is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * GData Client is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with GData Client. If not, see . + */ + +/** + * SECTION:gdata-freebase-search-result + * @short_description: GData Freebase search result object + * @stability: Stable + * @include: gdata/services/freebase/gdata-freebase-result.h + * + * #GDataFreebaseSearchResult is a subclass of #GDataEntry to represent the result of a Freebase search query. + * + * For more details of Google Freebase API, see the + * online documentation. + * + * Since: 0.15.1 + * Deprecated: 0.17.7: Google Freebase has been permanently shut down. + */ + +#include +#include +#include +#include + +#include "gdata-freebase-search-result.h" +#include "gdata-private.h" +#include "gdata-types.h" + +G_GNUC_BEGIN_IGNORE_DEPRECATIONS + +#define URLBASE "https://www.googleapis.com/freebase/v1" + +struct _GDataFreebaseSearchResultItem { + gchar *mid; + gchar *id; + gchar *name; + gchar *lang; + gchar *notable_id; + gchar *notable_name; + gdouble score; +}; + +struct _GDataFreebaseSearchResultPrivate { + GPtrArray *items; /* contains owned GDataFreebaseSearchResultItem structs */ + guint total_hits; +}; + +static void gdata_freebase_search_result_finalize (GObject *self); +static gboolean parse_json (GDataParsable *parsable, JsonReader *reader, gpointer user_data, GError **error); +static GDataFreebaseSearchResultItem * item_copy (const GDataFreebaseSearchResultItem *item); +static void item_free (GDataFreebaseSearchResultItem *item); + +G_DEFINE_BOXED_TYPE (GDataFreebaseSearchResultItem, gdata_freebase_search_result_item, item_copy, item_free) + +G_DEFINE_TYPE (GDataFreebaseSearchResult, gdata_freebase_search_result, GDATA_TYPE_FREEBASE_RESULT) + +static void +gdata_freebase_search_result_class_init (GDataFreebaseSearchResultClass *klass) +{ + GDataParsableClass *parsable_class = GDATA_PARSABLE_CLASS (klass); + GObjectClass *gobject_class = G_OBJECT_CLASS (klass); + + g_type_class_add_private (klass, sizeof (GDataFreebaseSearchResultPrivate)); + + gobject_class->finalize = gdata_freebase_search_result_finalize; + parsable_class->parse_json = parse_json; +} + +static GDataFreebaseSearchResultItem * +item_new (void) +{ + return g_slice_new0 (GDataFreebaseSearchResultItem); +} + +static void +item_free (GDataFreebaseSearchResultItem *item) +{ + g_free (item->mid); + g_free (item->id); + g_free (item->name); + g_free (item->lang); + g_free (item->notable_id); + g_free (item->notable_name); + g_slice_free (GDataFreebaseSearchResultItem, item); +} + +static GDataFreebaseSearchResultItem * +item_copy (const GDataFreebaseSearchResultItem *item) +{ + GDataFreebaseSearchResultItem *copy; + + copy = item_new (); + copy->mid = g_strdup (item->mid); + copy->id = g_strdup (item->id); + copy->name = g_strdup (item->name); + copy->lang = g_strdup (item->lang); + copy->notable_id = g_strdup (item->notable_id); + copy->notable_name = g_strdup (item->notable_name); + copy->score = item->score; + + return copy; +} + +static void +gdata_freebase_search_result_init (GDataFreebaseSearchResult *self) +{ + self->priv = G_TYPE_INSTANCE_GET_PRIVATE (self, GDATA_TYPE_FREEBASE_SEARCH_RESULT, GDataFreebaseSearchResultPrivate); + self->priv->items = g_ptr_array_new_with_free_func ((GDestroyNotify) item_free); +} + +static void +gdata_freebase_search_result_finalize (GObject *self) +{ + GDataFreebaseSearchResultPrivate *priv = GDATA_FREEBASE_SEARCH_RESULT (self)->priv; + + g_ptr_array_unref (priv->items); + + G_OBJECT_CLASS (gdata_freebase_search_result_parent_class)->finalize (self); +} + +static gboolean +parse_json (GDataParsable *parsable, JsonReader *reader, gpointer user_data, GError **error) +{ + GDataFreebaseSearchResultPrivate *priv = GDATA_FREEBASE_SEARCH_RESULT (parsable)->priv; + const GError *inner_error = NULL; + const gchar *member_name; + gint count, i; + + GDATA_PARSABLE_CLASS (gdata_freebase_search_result_parent_class)->parse_json (parsable, reader, user_data, error); + +#define ITEM_SET_STRING(id,field,mandatory) \ + json_reader_read_member (reader, #id); \ + item->field = g_strdup (json_reader_get_string_value (reader)); \ + if (mandatory) { \ + inner_error = json_reader_get_error (reader); \ + if (inner_error != NULL) goto item_error; \ + } \ + json_reader_end_member (reader); + +#define ITEM_SET_DOUBLE(id,field) \ + json_reader_read_member (reader, #id); \ + item->field = json_reader_get_double_value (reader); \ + inner_error = json_reader_get_error (reader); \ + if (inner_error != NULL) goto item_error; \ + json_reader_end_member (reader); + + member_name = json_reader_get_member_name (reader); + + if (member_name == NULL) + return FALSE; + + if (strcmp (member_name, "hits") == 0) { + priv->total_hits = json_reader_get_int_value (reader); + return TRUE; + } else if (strcmp (member_name, "result") != 0) { + /* Avoid anything else besides hits/result */ + return TRUE; + } + + if (!json_reader_is_array (reader)) + return FALSE; + + count = json_reader_count_elements (reader); + + for (i = 0; i < count; i++) { + GDataFreebaseSearchResultItem *item; + + item = item_new (); + json_reader_read_element (reader, i); + + ITEM_SET_STRING (mid, mid, TRUE); + ITEM_SET_STRING (id, id, FALSE); + ITEM_SET_STRING (name, name, TRUE); + ITEM_SET_STRING (lang, lang, FALSE); + ITEM_SET_DOUBLE (score, score); + + /* Read "notable" */ + json_reader_read_member (reader, "notable"); + + if (json_reader_get_error (reader) == NULL) { + ITEM_SET_STRING (id, notable_id, TRUE); + ITEM_SET_STRING (name, notable_name, TRUE); + } + + json_reader_end_member (reader); + json_reader_end_element (reader); + + g_ptr_array_add (priv->items, item); + continue; + + item_error: + item_free (item); + gdata_parser_error_required_json_content_missing (reader, error); + return FALSE; + } + +#undef ITEM_SET_DOUBLE +#undef ITEM_SET_STRING + + return TRUE; +} + +/** + * gdata_freebase_search_result_new: + * + * Creates a new #GDataFreebaseSearchResult with the given ID and default properties. + * + * Return value: (transfer full): a new #GDataFreebaseSearchResult; unref with g_object_unref() + * + * Since: 0.15.1 + * Deprecated: 0.17.7: Google Freebase has been permanently shut down. + */ +GDataFreebaseSearchResult * +gdata_freebase_search_result_new (void) +{ + return g_object_new (GDATA_TYPE_FREEBASE_SEARCH_RESULT, NULL); +} + +/** + * gdata_freebase_search_result_get_num_items: + * @self: a #GDataFreebaseSearchResult + * + * Returns the number of items contained in this result. + * + * Returns: The number of items + * + * Since: 0.15.1 + * Deprecated: 0.17.7: Google Freebase has been permanently shut down. + */ +guint +gdata_freebase_search_result_get_num_items (GDataFreebaseSearchResult *self) +{ + g_return_val_if_fail (GDATA_IS_FREEBASE_SEARCH_RESULT (self), 0); + + return self->priv->items->len; +} + +/** + * gdata_freebase_search_result_get_total_hits: + * @self: a #GDataFreebaseSearchResult + * + * Returns the total number of hits found for the search query. + * + * Returns: the total number of hits. + * + * Since: 0.15.1 + * Deprecated: 0.17.7: Google Freebase has been permanently shut down. + */ +guint +gdata_freebase_search_result_get_total_hits (GDataFreebaseSearchResult *self) +{ + g_return_val_if_fail (GDATA_IS_FREEBASE_SEARCH_RESULT (self), 0); + + return self->priv->total_hits; +} + +/** + * gdata_freebase_search_result_get_item: + * @self: a #GDataFreebaseSearchResult + * @i: number of item to retrieve + * + * Gets an item from the search result. + * + * Returns: (transfer none) (allow-none): a search result item, or %NULL on invalid item. + * + * Since: 0.15.1 + * Deprecated: 0.17.7: Google Freebase has been permanently shut down. + */ +const GDataFreebaseSearchResultItem * +gdata_freebase_search_result_get_item (GDataFreebaseSearchResult *self, guint i) +{ + GDataFreebaseSearchResultPrivate *priv; + + g_return_val_if_fail (GDATA_IS_FREEBASE_SEARCH_RESULT (self), NULL); + + priv = self->priv; + g_return_val_if_fail (i < priv->items->len, NULL); + + return g_ptr_array_index (priv->items, i); +} + +/** + * gdata_freebase_search_result_item_get_mid: + * @item: a #GDataFreebaseSearchResultItem + * + * Returns the machine-encoded ID (MID) of the search result item. Elements may + * have a single MID, as opposed to the potentially multiple Freebase IDs that + * may point to it. MIDs are usable interchangeably with Freebase IDs. + * + * Returns: (transfer none): The result item MID. + * + * Since: 0.15.1 + * Deprecated: 0.17.7: Google Freebase has been permanently shut down. + */ +const gchar * +gdata_freebase_search_result_item_get_mid (const GDataFreebaseSearchResultItem *item) +{ + g_return_val_if_fail (item != NULL, NULL); + return item->mid; +} + +/** + * gdata_freebase_search_result_item_get_id: + * @item: a #GDataFreebaseSearchResultItem + * + * Returns the Freebase ID of the search result item. + * + * Returns: (transfer none): The search result item Freebase ID. + * + * Since: 0.15.1 + * Deprecated: 0.17.7: Google Freebase has been permanently shut down. + */ +const gchar * +gdata_freebase_search_result_item_get_id (const GDataFreebaseSearchResultItem *item) +{ + g_return_val_if_fail (item != NULL, NULL); + + if (item->id != NULL) + return item->id; + + return item->mid; +} + +/** + * gdata_freebase_search_result_item_get_name: + * @item: a #GDataFreebaseSearchResultItem + * + * Returns the human readable name of the search result item. + * + * Returns: (transfer none): The human readable name of the item. + * + * Since: 0.15.1 + * Deprecated: 0.17.7: Google Freebase has been permanently shut down. + */ +const gchar * +gdata_freebase_search_result_item_get_name (const GDataFreebaseSearchResultItem *item) +{ + g_return_val_if_fail (item != NULL, NULL); + return item->name; +} + +/** + * gdata_freebase_search_result_item_get_language: + * @item: a #GDataFreebaseSearchResultItem + * + * Gets the language of this search result item, in ISO-639-1 format. + * + * Returns: (transfer none): The language of the search result item. + * + * Since: 0.15.1 + * Deprecated: 0.17.7: Google Freebase has been permanently shut down. + */ +const gchar * +gdata_freebase_search_result_item_get_language (const GDataFreebaseSearchResultItem *item) +{ + g_return_val_if_fail (item != NULL, NULL); + return item->lang; +} + +/** + * gdata_freebase_search_result_item_get_notable_id: + * @item: a #GDataFreebaseSearchResultItem + * + * If this search result item is notable in an specific topic, this function + * returns the Freebase ID of this topic. + * + * Returns: (transfer none) (allow-none): The topic the result item is most notable of, or %NULL. + * + * Since: 0.15.1 + * Deprecated: 0.17.7: Google Freebase has been permanently shut down. + */ +const gchar * +gdata_freebase_search_result_item_get_notable_id (const GDataFreebaseSearchResultItem *item) +{ + g_return_val_if_fail (item != NULL, NULL); + return item->notable_id; +} + +/** + * gdata_freebase_search_result_item_get_notable_name: + * @item: a #GDataFreebaseSearchResultItem + * + * If this search result item is notable in an specific topic, this function + * returns the human readable name of this topic. + * + * Returns: (transfer none) (allow-none): The human readable topic name, or %NULL + * + * Since: 0.15.1 + * Deprecated: 0.17.7: Google Freebase has been permanently shut down. + */ +const gchar * +gdata_freebase_search_result_item_get_notable_name (const GDataFreebaseSearchResultItem *item) +{ + g_return_val_if_fail (item != NULL, NULL); + return item->notable_name; +} + +/** + * gdata_freebase_search_result_item_get_score: + * @item: a #GDataFreebaseSearchResultItem + * + * Returns the score of this search result item. The higher, the more relevant this + * item seems, given the search terms. + * + * Returns: the result item score. + * + * Since: 0.15.1 + * Deprecated: 0.17.7: Google Freebase has been permanently shut down. + */ +gdouble +gdata_freebase_search_result_item_get_score (const GDataFreebaseSearchResultItem *item) +{ + g_return_val_if_fail (item != NULL, 0.0); + return item->score; +} + +G_GNUC_END_IGNORE_DEPRECATIONS diff --git a/gdata/services/freebase/gdata-freebase-search-result.h b/gdata/services/freebase/gdata-freebase-search-result.h new file mode 100644 index 0000000..299bc9b --- /dev/null +++ b/gdata/services/freebase/gdata-freebase-search-result.h @@ -0,0 +1,104 @@ +/* -*- Mode: C; indent-tabs-mode: t; c-basic-offset: 8; tab-width: 8 -*- */ +/* + * GData Client + * Copyright (C) 2014 Carlos Garnacho + * + * GData Client is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * GData Client is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with GData Client. If not, see . + */ + +#ifndef GDATA_FREEBASE_SEARCH_RESULT_H +#define GDATA_FREEBASE_SEARCH_RESULT_H + +#include +#include + +#include +#include "gdata-freebase-result.h" + +G_BEGIN_DECLS + +#ifndef LIBGDATA_DISABLE_DEPRECATED + +#define GDATA_TYPE_FREEBASE_SEARCH_RESULT_ITEM (gdata_freebase_search_result_item_get_type ()) +#define GDATA_TYPE_FREEBASE_SEARCH_RESULT (gdata_freebase_search_result_get_type ()) +#define GDATA_FREEBASE_SEARCH_RESULT(o) (G_TYPE_CHECK_INSTANCE_CAST ((o), GDATA_TYPE_FREEBASE_SEARCH_RESULT, GDataFreebaseSearchResult)) +#define GDATA_FREEBASE_SEARCH_RESULT_CLASS(k) (G_TYPE_CHECK_CLASS_CAST((k), GDATA_TYPE_FREEBASE_SEARCH_RESULT, GDataFreebaseSearchResultClass)) +#define GDATA_IS_FREEBASE_SEARCH_RESULT(o) (G_TYPE_CHECK_INSTANCE_TYPE ((o), GDATA_TYPE_FREEBASE_SEARCH_RESULT)) +#define GDATA_IS_FREEBASE_SEARCH_RESULT_CLASS(k) (G_TYPE_CHECK_CLASS_TYPE ((k), GDATA_TYPE_FREEBASE_SEARCH_RESULT)) +#define GDATA_FREEBASE_SEARCH_RESULT_GET_CLASS(o) (G_TYPE_INSTANCE_GET_CLASS ((o), GDATA_TYPE_FREEBASE_SEARCH_RESULT, GDataFreebaseSearchResultClass)) + +typedef struct _GDataFreebaseSearchResultPrivate GDataFreebaseSearchResultPrivate; + +/** + * GDataFreebaseSearchResultItem: + * + * Opaque struct holding data for a single search result item. + * + * Since: 0.15.1 + */ +typedef struct _GDataFreebaseSearchResultItem GDataFreebaseSearchResultItem; + +/** + * GDataFreebaseSearchResult: + * + * All the fields in the #GDataFreebaseSearchResult structure are private and should never be accessed directly. + * + * Since: 0.15.1 + */ +typedef struct { + GDataFreebaseResult parent; + GDataFreebaseSearchResultPrivate *priv; +} GDataFreebaseSearchResult; + +/** + * GDataFreebaseSearchResultClass: + * + * All the fields in the #GDataFreebaseSearchResultClass structure are private and should never be accessed directly. + * + * Since: 0.15.1 + */ + +typedef struct { + /*< private >*/ + GDataFreebaseResultClass parent; + + /*< private >*/ + /* Padding for future expansion */ + void (*_g_reserved0) (void); + void (*_g_reserved1) (void); +} GDataFreebaseSearchResultClass; + +GType gdata_freebase_search_result_item_get_type (void) G_GNUC_CONST G_GNUC_DEPRECATED; +GType gdata_freebase_search_result_get_type (void) G_GNUC_CONST G_GNUC_DEPRECATED; + +GDataFreebaseSearchResult *gdata_freebase_search_result_new (void) G_GNUC_WARN_UNUSED_RESULT G_GNUC_MALLOC G_GNUC_DEPRECATED; + +guint gdata_freebase_search_result_get_num_items (GDataFreebaseSearchResult *self) G_GNUC_DEPRECATED; +guint gdata_freebase_search_result_get_total_hits (GDataFreebaseSearchResult *self) G_GNUC_DEPRECATED; + +const GDataFreebaseSearchResultItem *gdata_freebase_search_result_get_item (GDataFreebaseSearchResult *self, guint i) G_GNUC_DEPRECATED; + +const gchar *gdata_freebase_search_result_item_get_mid (const GDataFreebaseSearchResultItem *item) G_GNUC_DEPRECATED; +const gchar *gdata_freebase_search_result_item_get_id (const GDataFreebaseSearchResultItem *item) G_GNUC_DEPRECATED; +const gchar *gdata_freebase_search_result_item_get_name (const GDataFreebaseSearchResultItem *item) G_GNUC_DEPRECATED; +const gchar *gdata_freebase_search_result_item_get_language (const GDataFreebaseSearchResultItem *item) G_GNUC_DEPRECATED; +const gchar *gdata_freebase_search_result_item_get_notable_id (const GDataFreebaseSearchResultItem *item) G_GNUC_DEPRECATED; +const gchar *gdata_freebase_search_result_item_get_notable_name (const GDataFreebaseSearchResultItem *item) G_GNUC_DEPRECATED; +gdouble gdata_freebase_search_result_item_get_score (const GDataFreebaseSearchResultItem *item) G_GNUC_DEPRECATED; + +#endif /* !LIBGDATA_DISABLE_DEPRECATED */ + +G_END_DECLS + +#endif /* !GDATA_FREEBASE_SEARCH_RESULT_H */ diff --git a/gdata/services/freebase/gdata-freebase-service.c b/gdata/services/freebase/gdata-freebase-service.c new file mode 100644 index 0000000..df1b925 --- /dev/null +++ b/gdata/services/freebase/gdata-freebase-service.c @@ -0,0 +1,509 @@ +/* -*- Mode: C; indent-tabs-mode: t; c-basic-offset: 8; tab-width: 8 -*- */ +/* + * GData Client + * Copyright (C) 2014 Carlos Garnacho + * + * GData Client is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * GData Client is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with GData Client. If not, see . + */ + +/** + * SECTION:gdata-freebase-service + * @short_description: GData Freebase service object + * @stability: Stable + * @include: gdata/services/freebase/gdata-freebase-service.h + * + * #GDataFreebaseService is a subclass of #GDataService for communicating with the Google Freebase API. It supports queries + * in MQL format, that allows highly flexible queries on any topic. MQL is a JSON based query language, MQL requests consist + * of a mix of defined and empty values for types in the Freebase schema, those "placeholder" values will be filled in on the + * reply. For more information and examples, see the + * MQL overview page. + * + * For more details of Google Freebase API, see the + * online documentation. + * + * Since August 2016, [Google has retired Freebase](https://developers.google.com/freebase/), + * so all of these APIs will return an error if used; and should be considered + * deprecated. + * + * Since: 0.15.1 + * Deprecated: 0.17.7: Google Freebase has been permanently shut down. + */ + +#include +#include +#include +#include + +#include "gdata-freebase-service.h" +#include "gdata-freebase-result.h" +#include "gdata-freebase-search-result.h" +#include "gdata-service.h" +#include "gdata-private.h" +#include "gdata-query.h" +#include "gdata-feed.h" + +G_GNUC_BEGIN_IGNORE_DEPRECATIONS + +/* Standards reference at https://developers.google.com/freebase/v1/ */ + +#define URLBASE "://www.googleapis.com/freebase/v1" +#define IMAGE_URI_PREFIX "https://usercontent.googleapis.com/freebase/v1/image" + +enum { + PROP_DEVELOPER_KEY = 1 +}; + +struct _GDataFreebaseServicePrivate { + gchar *developer_key; +}; + +static void gdata_freebase_service_set_property (GObject *self, guint prop_id, const GValue *value, GParamSpec *pspec); +static void gdata_freebase_service_get_property (GObject *self, guint prop_id, GValue *value, GParamSpec *pspec); +static void gdata_freebase_service_finalize (GObject *self); +static void append_query_headers (GDataService *self, GDataAuthorizationDomain *domain, SoupMessage *message); +static GList *get_authorization_domains (void); + +_GDATA_DEFINE_AUTHORIZATION_DOMAIN (freebase, "freebase", "https://www.googleapis.com/auth/freebase.readonly") + +G_DEFINE_TYPE (GDataFreebaseService, gdata_freebase_service, GDATA_TYPE_SERVICE) + +static void +gdata_freebase_service_class_init (GDataFreebaseServiceClass *klass) +{ + GObjectClass *gobject_class = G_OBJECT_CLASS (klass); + GDataServiceClass *service_class = GDATA_SERVICE_CLASS (klass); + + g_type_class_add_private (klass, sizeof (GDataFreebaseServicePrivate)); + + gobject_class->set_property = gdata_freebase_service_set_property; + gobject_class->get_property = gdata_freebase_service_get_property; + gobject_class->finalize = gdata_freebase_service_finalize; + + service_class->append_query_headers = append_query_headers; + service_class->get_authorization_domains = get_authorization_domains; + + /** + * GDataFreebaseService:developer-key: + * + * The developer key your application has registered with the Freebase API. For more information, see the online documentation. + * + * Since: 0.15.1 + * Deprecated: 0.17.7: Google Freebase has been permanently shut down. + */ + g_object_class_install_property (gobject_class, PROP_DEVELOPER_KEY, + g_param_spec_string ("developer-key", + "Developer key", "Your Freebase developer API key.", + NULL, + G_PARAM_CONSTRUCT_ONLY | G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS | + G_PARAM_DEPRECATED)); +} + +static void +gdata_freebase_service_init (GDataFreebaseService *self) +{ + self->priv = G_TYPE_INSTANCE_GET_PRIVATE (self, GDATA_TYPE_FREEBASE_SERVICE, GDataFreebaseServicePrivate); +} + +static void +append_query_headers (GDataService *self, GDataAuthorizationDomain *domain, SoupMessage *message) +{ + GDataFreebaseServicePrivate *priv = GDATA_FREEBASE_SERVICE (self)->priv; + const gchar *query; + GString *new_query; + SoupURI *uri; + + g_assert (message != NULL); + + if (priv->developer_key) { + uri = soup_message_get_uri (message); + query = soup_uri_get_query (uri); + + /* Set the key on every request, as per + * https://developers.google.com/freebase/v1/parameters + */ + if (query) { + new_query = g_string_new (query); + + g_string_append (new_query, "&key="); + g_string_append_uri_escaped (new_query, priv->developer_key, NULL, FALSE); + + soup_uri_set_query (uri, new_query->str); + g_string_free (new_query, TRUE); + } + } + + /* Chain up to the parent class */ + GDATA_SERVICE_CLASS (gdata_freebase_service_parent_class)->append_query_headers (self, domain, message); +} + +static GList * +get_authorization_domains (void) +{ + return g_list_prepend (NULL, get_freebase_authorization_domain ()); +} + +static void +gdata_freebase_service_set_property (GObject *self, guint prop_id, const GValue *value, GParamSpec *pspec) +{ + GDataFreebaseServicePrivate *priv = GDATA_FREEBASE_SERVICE (self)->priv; + + switch (prop_id) { + case PROP_DEVELOPER_KEY: + priv->developer_key = g_value_dup_string (value); + break; + default: + G_OBJECT_WARN_INVALID_PROPERTY_ID (self, prop_id, pspec); + break; + } +} + +static void +gdata_freebase_service_get_property (GObject *self, guint prop_id, GValue *value, GParamSpec *pspec) +{ + GDataFreebaseServicePrivate *priv = GDATA_FREEBASE_SERVICE (self)->priv; + + switch (prop_id) { + case PROP_DEVELOPER_KEY: + g_value_set_string (value, priv->developer_key); + break; + default: + G_OBJECT_WARN_INVALID_PROPERTY_ID (self, prop_id, pspec); + break; + } +} + +static void +gdata_freebase_service_finalize (GObject *self) +{ + GDataFreebaseServicePrivate *priv = GDATA_FREEBASE_SERVICE (self)->priv; + + g_free (priv->developer_key); + + G_OBJECT_CLASS (gdata_freebase_service_parent_class)->finalize (self); +} + +/** + * gdata_freebase_service_new: + * @developer_key: (allow-none): developer key to use the API, or %NULL + * @authorizer: (allow-none): a #GDataAuthorizer to authorize the service's requests, or %NULL + * + * Creates a new #GDataFreebaseService using the given #GDataAuthorizer. If @authorizer is %NULL, all requests are made as an unauthenticated user. + * Having both @developer_key and @authorizer set to %NULL is allowed, but this should be reserved for debugging situations, as there is a certain + * key-less quota for those purposes. If this service is used on any code intended to be deployed, one or both of @developer_key and @authorizer + * should be non-%NULL and valid. + * + * Return value: (transfer full): a new #GDataFreebaseService; unref with g_object_unref() + * + * Since: 0.15.1 + * Deprecated: 0.17.7: Google Freebase has been permanently shut down. + */ +GDataFreebaseService * +gdata_freebase_service_new (const gchar *developer_key, GDataAuthorizer *authorizer) +{ + g_return_val_if_fail (authorizer == NULL || GDATA_IS_AUTHORIZER (authorizer), NULL); + + return g_object_new (GDATA_TYPE_FREEBASE_SERVICE, + "developer-key", developer_key, + "authorizer", authorizer, + NULL); +} + +/** + * gdata_freebase_service_get_primary_authorization_domain: + * + * The primary #GDataAuthorizationDomain for interacting with Freebase. This will not normally need to be used, as it's used internally + * by the #GDataFreebaseService methods. However, if using the plain #GDataService methods to implement custom queries or requests which libgdata + * does not support natively, then this domain may be needed to authorize the requests. + * + * The domain never changes, and is interned so that pointer comparison can be used to differentiate it from other authorization domains. + * + * Return value: (transfer none): the service's authorization domain + * + * Since: 0.15.1 + * Deprecated: 0.17.7: Google Freebase has been permanently shut down. + */ +GDataAuthorizationDomain * +gdata_freebase_service_get_primary_authorization_domain (void) +{ + return get_freebase_authorization_domain (); +} + +/** + * gdata_freebase_service_query: + * @self: a #GDataFreebaseService + * @query: a #GDataFreebaseQuery with the MQL query + * @cancellable: (allow-none): optional #GCancellable object, or %NULL + * @error: (allow-none): a #GError, or %NULL + * + * Performs a MQL query on the service, you can find out more about MQL in the online MQL documentation. + * + * Return value: (transfer full): a #GDataFreebaseResult containing the query result; unref with g_object_unref() + * + * Since: 0.15.1 + * Deprecated: 0.17.7: Google Freebase has been permanently shut down. + */ +GDataFreebaseResult * +gdata_freebase_service_query (GDataFreebaseService *self, GDataFreebaseQuery *query, + GCancellable *cancellable, GError **error) +{ + GDataEntry *entry; + + g_return_val_if_fail (GDATA_IS_FREEBASE_SERVICE (self), NULL); + g_return_val_if_fail (GDATA_IS_FREEBASE_QUERY (query), NULL); + g_return_val_if_fail (cancellable == NULL || G_IS_CANCELLABLE (cancellable), NULL); + g_return_val_if_fail (error == NULL || *error == NULL, NULL); + + entry = gdata_service_query_single_entry (GDATA_SERVICE (self), get_freebase_authorization_domain (), "mqlread", + GDATA_QUERY (query), GDATA_TYPE_FREEBASE_RESULT, cancellable, error); + if (entry == NULL) + return NULL; + + return GDATA_FREEBASE_RESULT (entry); +} + +/** + * gdata_freebase_service_query_async: + * @self: a #GDataFreebaseService + * @query: a #GDataFreebaseQuery with the MQL query + * @cancellable: (allow-none): optional #GCancellable object, or %NULL + * @callback: a #GAsyncReadyCallback to call when authentication is finished + * @user_data: (closure): data to pass to the @callback function + * + * Performs a MQL query on the service. @self and @query are all reffed when this function is called, so can safely + * be unreffed after this function returns. When the query is replied, or fails, @callback will be executed, and + * the result can be obtained through gdata_service_query_single_entry_finish(). + * + * For more details, see gdata_freebase_service_query(), which is the synchronous version of + * this function. + * + * Since: 0.15.1 + * Deprecated: 0.17.7: Google Freebase has been permanently shut down. + */ +void +gdata_freebase_service_query_async (GDataFreebaseService *self, GDataFreebaseQuery *query, GCancellable *cancellable, + GAsyncReadyCallback callback, gpointer user_data) +{ + g_return_if_fail (GDATA_IS_FREEBASE_SERVICE (self)); + g_return_if_fail (GDATA_IS_FREEBASE_QUERY (query)); + g_return_if_fail (cancellable == NULL || G_IS_CANCELLABLE (cancellable)); + g_return_if_fail (callback != NULL); + + gdata_service_query_single_entry_async (GDATA_SERVICE (self), get_freebase_authorization_domain (), "mqlread", + GDATA_QUERY (query), GDATA_TYPE_FREEBASE_RESULT, cancellable, callback, user_data); +} + +/** + * gdata_freebase_service_get_topic: + * @self: a #GDataFreebaseService + * @query: a #GDataFreebaseTopicQuery containing the topic ID + * @cancellable: (allow-none): optional #GCancellable object, or %NULL + * @error: (allow-none): a #GError, or %NULL + * + * Queries information about a topic, identified through a Freebase ID. You can find out more about topic queries in the + * online documentation. + * + * Return value: (transfer full): a #GDataFreebaseTopicResult containing information about the topic; unref with g_object_unref() + * + * Since: 0.15.1 + * Deprecated: 0.17.7: Google Freebase has been permanently shut down. + */ +GDataFreebaseTopicResult * +gdata_freebase_service_get_topic (GDataFreebaseService *self, GDataFreebaseTopicQuery *query, GCancellable *cancellable, GError **error) +{ + GDataEntry *entry; + + g_return_val_if_fail (GDATA_IS_FREEBASE_SERVICE (self), NULL); + g_return_val_if_fail (GDATA_IS_FREEBASE_TOPIC_QUERY (query), NULL); + g_return_val_if_fail (cancellable == NULL || G_IS_CANCELLABLE (cancellable), NULL); + g_return_val_if_fail (error == NULL || *error == NULL, NULL); + + entry = gdata_service_query_single_entry (GDATA_SERVICE (self), get_freebase_authorization_domain (), "topic", + GDATA_QUERY (query), GDATA_TYPE_FREEBASE_TOPIC_RESULT, cancellable, error); + if (entry == NULL) + return NULL; + + return GDATA_FREEBASE_TOPIC_RESULT (entry); +} + +/** + * gdata_freebase_service_get_topic_async: + * @self: a #GDataFreebaseService + * @query: a #GDataFreebaseQuery with the MQL query + * @cancellable: (allow-none): optional #GCancellable object, or %NULL + * @callback: a #GAsyncReadyCallback to call when authentication is finished + * @user_data: (closure): data to pass to the @callback function + * + * Queries information about a topic, identified through a Freebase ID. @self and @query are all reffed when this + * function is called, so can safely be unreffed after this function returns. When the query is replied, or fails, + * @callback will be executed, and the result can be obtained through gdata_service_query_single_entry_finish(). + * + * For more details, see gdata_freebase_service_get_topic(), which is the synchronous version of + * this function. + * + * Since: 0.15.1 + * Deprecated: 0.17.7: Google Freebase has been permanently shut down. + */ +void +gdata_freebase_service_get_topic_async (GDataFreebaseService *self, GDataFreebaseTopicQuery *query, + GCancellable *cancellable, GAsyncReadyCallback callback, gpointer user_data) +{ + g_return_if_fail (GDATA_IS_FREEBASE_SERVICE (self)); + g_return_if_fail (GDATA_IS_FREEBASE_TOPIC_QUERY (query)); + g_return_if_fail (cancellable == NULL || G_IS_CANCELLABLE (cancellable)); + g_return_if_fail (callback != NULL); + + gdata_service_query_single_entry_async (GDATA_SERVICE (self), get_freebase_authorization_domain (), "topic", + GDATA_QUERY (query), GDATA_TYPE_FREEBASE_TOPIC_RESULT, cancellable, callback, user_data); +} + +/** + * gdata_freebase_service_search: + * @self: a #GDataFreebaseService + * @query: a #GDataFreebaseSearchQuery containing the topic ID + * @cancellable: (allow-none): optional #GCancellable object, or %NULL + * @error: (allow-none): a #GError, or %NULL + * + * Performs a search for any given search term, filters can be set on @query to narrow down the results. The results returned + * are ordered by relevance. You can find out more about topic queries in the + * online documentation. + * + * Return value: (transfer full): a #GDataFreebaseSearchResult containing the results for the given search query; unref with g_object_unref() + * + * Since: 0.15.1 + * Deprecated: 0.17.7: Google Freebase has been permanently shut down. + */ +GDataFreebaseSearchResult * +gdata_freebase_service_search (GDataFreebaseService *self, GDataFreebaseSearchQuery *query, GCancellable *cancellable, GError **error) +{ + GDataEntry *entry; + + g_return_val_if_fail (GDATA_IS_FREEBASE_SERVICE (self), NULL); + g_return_val_if_fail (GDATA_IS_FREEBASE_SEARCH_QUERY (query), NULL); + g_return_val_if_fail (cancellable == NULL || G_IS_CANCELLABLE (cancellable), NULL); + g_return_val_if_fail (error == NULL || *error == NULL, NULL); + + entry = gdata_service_query_single_entry (GDATA_SERVICE (self), get_freebase_authorization_domain (), "search", + GDATA_QUERY (query), GDATA_TYPE_FREEBASE_SEARCH_RESULT, cancellable, error); + if (entry == NULL) + return NULL; + + return GDATA_FREEBASE_SEARCH_RESULT (entry); +} + +/** + * gdata_freebase_service_search_async: + * @self: a #GDataFreebaseService + * @query: a #GDataFreebaseQuery with the MQL query + * @cancellable: (allow-none): optional #GCancellable object, or %NULL + * @callback: a #GAsyncReadyCallback to call when authentication is finished + * @user_data: (closure): data to pass to the @callback function + * + * Performs a search for any given search term. @self and @query are all reffed when this + * function is called, so can safely be unreffed after this function returns. + * + * For more details, see gdata_freebase_service_search(), which is the synchronous version of + * this function. + * + * Since: 0.15.1 + * Deprecated: 0.17.7: Google Freebase has been permanently shut down. + */ +void +gdata_freebase_service_search_async (GDataFreebaseService *self, GDataFreebaseSearchQuery *query, + GCancellable *cancellable, GAsyncReadyCallback callback, gpointer user_data) +{ + g_return_if_fail (GDATA_IS_FREEBASE_SERVICE (self)); + g_return_if_fail (GDATA_IS_FREEBASE_SEARCH_QUERY (query)); + g_return_if_fail (cancellable == NULL || G_IS_CANCELLABLE (cancellable)); + g_return_if_fail (callback != NULL); + + gdata_service_query_single_entry_async (GDATA_SERVICE (self), get_freebase_authorization_domain (), "search", + GDATA_QUERY (query), GDATA_TYPE_FREEBASE_SEARCH_RESULT, cancellable, callback, user_data); +} + +static gchar * +compose_image_uri (GDataFreebaseTopicValue *value, guint max_width, guint max_height) +{ + GString *uri = g_string_new (IMAGE_URI_PREFIX); + const GDataFreebaseTopicObject *object; + gboolean first = TRUE; + + object = gdata_freebase_topic_value_get_object (value); + g_assert (object != NULL); + + g_string_append (uri, gdata_freebase_topic_object_get_id (object)); + +#define APPEND_SEP g_string_append_c (uri, first ? '?' : '&'); first = FALSE; + + if (max_width > 0) { + APPEND_SEP; + g_string_append_printf (uri, "maxwidth=%d", max_width); + } + + if (max_height > 0) { + APPEND_SEP; + g_string_append_printf (uri, "maxheight=%d", max_height); + } +#undef APPEND_SEP + + return g_string_free (uri, FALSE); +} + +/** + * gdata_freebase_service_get_image: + * @self: a #GDataFreebaseService + * @value: a #GDataFreebaseTopicValue from a topic result + * @cancellable: (allow-none): optional #GCancellable object, or %NULL + * @max_width: maximum width of the image returned, or 0 + * @max_height: maximum height of the image returned, or 0 + * @error: (allow-none): a #GError, or %NULL + * + * Creates an input stream to an image object returned in a topic query. If @max_width and @max_height + * are unspecified (i.e. set to 0), the image returned will be the smallest available. + * + * Return value: (transfer full): a #GInputStream opened to the image; unref with g_object_unref() + * + * Since: 0.15.1 + * Deprecated: 0.17.7: Google Freebase has been permanently shut down. + */ +GInputStream * +gdata_freebase_service_get_image (GDataFreebaseService *self, GDataFreebaseTopicValue *value, + GCancellable *cancellable, guint max_width, guint max_height, GError **error) +{ + GInputStream *stream; + gchar *uri; + + g_return_val_if_fail (GDATA_IS_FREEBASE_SERVICE (self), NULL); + g_return_val_if_fail (cancellable == NULL || G_IS_CANCELLABLE (cancellable), NULL); + g_return_val_if_fail (value != NULL, NULL); + g_return_val_if_fail (!error || !*error, NULL); + g_return_val_if_fail (max_width < 4096 && max_height < 4096, NULL); + + if (!gdata_freebase_topic_value_is_image (value)) { + g_set_error (error, + GDATA_SERVICE_ERROR, + GDATA_SERVICE_ERROR_BAD_QUERY_PARAMETER, + _("Property ‘%s’ does not hold an image"), + gdata_freebase_topic_value_get_property (value)); + return NULL; + } + + uri = compose_image_uri (value, max_width, max_height); + stream = gdata_download_stream_new (GDATA_SERVICE (self), get_freebase_authorization_domain (), uri, cancellable); + g_free (uri); + + return stream; +} + +G_GNUC_END_IGNORE_DEPRECATIONS diff --git a/gdata/services/freebase/gdata-freebase-service.h b/gdata/services/freebase/gdata-freebase-service.h new file mode 100644 index 0000000..1897c15 --- /dev/null +++ b/gdata/services/freebase/gdata-freebase-service.h @@ -0,0 +1,111 @@ +/* -*- Mode: C; indent-tabs-mode: t; c-basic-offset: 8; tab-width: 8 -*- */ +/* + * GData Client + * Copyright (C) 2014 Carlos Garnacho + * + * GData Client is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * GData Client is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with GData Client. If not, see . + */ + +#ifndef GDATA_FREEBASE_SERVICE_H +#define GDATA_FREEBASE_SERVICE_H + +#include +#include +#include + +#include +#include +#include "gdata-freebase-query.h" +#include "gdata-freebase-result.h" +#include "gdata-freebase-search-query.h" +#include "gdata-freebase-search-result.h" +#include "gdata-freebase-topic-query.h" +#include "gdata-freebase-topic-result.h" + +G_BEGIN_DECLS + +#ifndef LIBGDATA_DISABLE_DEPRECATED + +#define GDATA_TYPE_FREEBASE_SERVICE (gdata_freebase_service_get_type ()) +#define GDATA_FREEBASE_SERVICE(o) (G_TYPE_CHECK_INSTANCE_CAST ((o), GDATA_TYPE_FREEBASE_SERVICE, GDataFreebaseService)) +#define GDATA_FREEBASE_SERVICE_CLASS(k) (G_TYPE_CHECK_CLASS_CAST((k), GDATA_TYPE_FREEBASE_SERVICE, GDataFreebaseServiceClass)) +#define GDATA_IS_FREEBASE_SERVICE(o) (G_TYPE_CHECK_INSTANCE_TYPE ((o), GDATA_TYPE_FREEBASE_SERVICE)) +#define GDATA_IS_FREEBASE_SERVICE_CLASS(k) (G_TYPE_CHECK_CLASS_TYPE ((k), GDATA_TYPE_FREEBASE_SERVICE)) +#define GDATA_FREEBASE_SERVICE_GET_CLASS(o) (G_TYPE_INSTANCE_GET_CLASS ((o), GDATA_TYPE_FREEBASE_SERVICE, GDataFreebaseServiceClass)) + +typedef struct _GDataFreebaseServicePrivate GDataFreebaseServicePrivate; + +/** + * GDataFreebaseService: + * + * All the fields in the #GDataFreebaseService structure are private and should never be accessed directly. + * + * Since: 0.15.1 + */ +typedef struct { + GDataService parent; + /*< private >*/ + GDataFreebaseServicePrivate *priv; +} GDataFreebaseService; + +/** + * GDataFreebaseServiceClass: + * + * All the fields in the #GDataFreebaseServiceClass structure are private and should never be accessed directly. + * + * Since: 0.15.1 + */ +typedef struct { + /*< private >*/ + GDataServiceClass parent; + + /*< private >*/ + /* Padding for future expansion */ + void (*_g_reserved0) (void); + void (*_g_reserved1) (void); + void (*_g_reserved2) (void); + void (*_g_reserved3) (void); + void (*_g_reserved4) (void); + void (*_g_reserved5) (void); +} GDataFreebaseServiceClass; + +GType gdata_freebase_service_get_type (void) G_GNUC_CONST G_GNUC_DEPRECATED; + +GDataFreebaseService *gdata_freebase_service_new (const gchar *developer_key, GDataAuthorizer *authorizer) G_GNUC_WARN_UNUSED_RESULT G_GNUC_MALLOC G_GNUC_DEPRECATED; + +GDataAuthorizationDomain *gdata_freebase_service_get_primary_authorization_domain (void) G_GNUC_CONST G_GNUC_DEPRECATED; + +GDataFreebaseResult *gdata_freebase_service_query (GDataFreebaseService *self, GDataFreebaseQuery *query, + GCancellable *cancellable, GError **error) G_GNUC_WARN_UNUSED_RESULT G_GNUC_MALLOC G_GNUC_DEPRECATED; +void gdata_freebase_service_query_async (GDataFreebaseService *self, GDataFreebaseQuery *query, + GCancellable *cancellable, GAsyncReadyCallback callback, gpointer user_data) G_GNUC_DEPRECATED; + +GDataFreebaseTopicResult *gdata_freebase_service_get_topic (GDataFreebaseService *self, GDataFreebaseTopicQuery *query, + GCancellable *cancellable, GError **error) G_GNUC_WARN_UNUSED_RESULT G_GNUC_MALLOC G_GNUC_DEPRECATED; +void gdata_freebase_service_get_topic_async (GDataFreebaseService *self, GDataFreebaseTopicQuery *query, + GCancellable *cancellable, GAsyncReadyCallback callback, gpointer user_data) G_GNUC_DEPRECATED; + +GDataFreebaseSearchResult *gdata_freebase_service_search (GDataFreebaseService *self, GDataFreebaseSearchQuery *query, + GCancellable *cancellable, GError **error) G_GNUC_WARN_UNUSED_RESULT G_GNUC_MALLOC G_GNUC_DEPRECATED; +void gdata_freebase_service_search_async (GDataFreebaseService *self, GDataFreebaseSearchQuery *query, + GCancellable *cancellable, GAsyncReadyCallback callback, gpointer user_data) G_GNUC_DEPRECATED; + +GInputStream *gdata_freebase_service_get_image (GDataFreebaseService *self, GDataFreebaseTopicValue *value, + GCancellable *cancellable, guint max_width, guint max_height, GError **error) G_GNUC_WARN_UNUSED_RESULT G_GNUC_MALLOC G_GNUC_DEPRECATED; + +#endif /* !LIBGDATA_DISABLE_DEPRECATED */ + +G_END_DECLS + +#endif /* !GDATA_FREEBASE_SERVICE_H */ diff --git a/gdata/services/freebase/gdata-freebase-topic-query.c b/gdata/services/freebase/gdata-freebase-topic-query.c new file mode 100644 index 0000000..05740ba --- /dev/null +++ b/gdata/services/freebase/gdata-freebase-topic-query.c @@ -0,0 +1,351 @@ +/* -*- Mode: C; indent-tabs-mode: t; c-basic-offset: 8; tab-width: 8 -*- */ +/* + * GData Client + * Copyright (C) 2014 Carlos Garnacho + * + * GData Client is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * GData Client is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with GData Client. If not, see . + */ + +/** + * SECTION:gdata-freebase-topic-query + * @short_description: GData Freebase topic query object + * @stability: Stable + * @include: gdata/services/freebase/gdata-freebase-topic-query.h + * + * #GDataFreebaseTopicQuery represents a Freebase topic query. The topic query happens on a single Freebase ID, + * given in gdata_freebase_topic_query_new(), the reply returns all known information in Freebase for that given ID. + * For more documentation and examples, see the + * Topic response API documentation + * + * This implementation of #GDataQuery respects the gdata_query_set_max_results() and gdata_query_set_updated_max() calls. + * + * For more details of Google Freebase API, see the + * online documentation. + * + * Since: 0.15.1 + * Deprecated: 0.17.7: Google Freebase has been permanently shut down. + */ + +#include +#include +#include +#include +#include + +#include "gdata-freebase-topic-query.h" +#include "gdata-query.h" +#include "gdata-parser.h" + +G_GNUC_BEGIN_IGNORE_DEPRECATIONS + +static void gdata_freebase_topic_query_finalize (GObject *self); +static void gdata_freebase_topic_query_set_property (GObject *self, guint prop_id, const GValue *value, GParamSpec *pspec); +static void gdata_freebase_topic_query_get_property (GObject *self, guint prop_id, GValue *value, GParamSpec *pspec); +static void get_query_uri (GDataQuery *self, const gchar *feed_uri, GString *query_uri, gboolean *params_started); + +struct _GDataFreebaseTopicQueryPrivate { + gchar *lang; + gchar **filter; +}; + +enum { + PROP_LANGUAGE = 1, + PROP_FILTER +}; + +G_DEFINE_TYPE (GDataFreebaseTopicQuery, gdata_freebase_topic_query, GDATA_TYPE_QUERY) + +static void +gdata_freebase_topic_query_class_init (GDataFreebaseTopicQueryClass *klass) +{ + GObjectClass *gobject_class = G_OBJECT_CLASS (klass); + GDataQueryClass *query_class = GDATA_QUERY_CLASS (klass); + + g_type_class_add_private (klass, sizeof (GDataFreebaseTopicQueryPrivate)); + + gobject_class->finalize = gdata_freebase_topic_query_finalize; + gobject_class->set_property = gdata_freebase_topic_query_set_property; + gobject_class->get_property = gdata_freebase_topic_query_get_property; + + query_class->get_query_uri = get_query_uri; + + /** + * GDataFreebaseTopicQuery:language: + * + * Language used for topic values in the result, in ISO-639-1 format. + * + * Since: 0.15.1 + * Deprecated: 0.17.7: Google Freebase has been permanently shut down. + */ + g_object_class_install_property (gobject_class, PROP_LANGUAGE, + g_param_spec_string ("language", + "Language used for results", + "Language in ISO-639-1 format.", + NULL, + G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS | + G_PARAM_DEPRECATED)); + + /** + * GDataFreebaseTopicQuery:filter: + * + * Array of properties (eg. "/common/topic/description", or "/computer/software/first_released"), or property + * domains (eg. "/common/topic", or "/computer") to be used as filter. + * + * Since: 0.15.1 + * Deprecated: 0.17.7: Google Freebase has been permanently shut down. + */ + g_object_class_install_property (gobject_class, PROP_FILTER, + g_param_spec_boxed ("filter", + "Filter", + "Property domain to be used as filter", + G_TYPE_STRV, + G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)); +} + +static void +gdata_freebase_topic_query_init (GDataFreebaseTopicQuery *self) +{ + self->priv = G_TYPE_INSTANCE_GET_PRIVATE (self, GDATA_TYPE_FREEBASE_TOPIC_QUERY, GDataFreebaseTopicQueryPrivate); +} + +static void +gdata_freebase_topic_query_finalize (GObject *self) +{ + GDataFreebaseTopicQueryPrivate *priv = GDATA_FREEBASE_TOPIC_QUERY (self)->priv; + + g_free (priv->lang); + g_free (priv->filter); + + /* Chain up to the parent class */ + G_OBJECT_CLASS (gdata_freebase_topic_query_parent_class)->finalize (self); +} + +static void +gdata_freebase_topic_query_set_property (GObject *self, guint prop_id, const GValue *value, GParamSpec *pspec) +{ + GDataFreebaseTopicQuery *query = GDATA_FREEBASE_TOPIC_QUERY (self); + + switch (prop_id) { + case PROP_LANGUAGE: + gdata_freebase_topic_query_set_language (query, g_value_get_string (value)); + break; + case PROP_FILTER: + gdata_freebase_topic_query_set_filter (query, g_value_get_boxed (value)); + break; + default: + G_OBJECT_WARN_INVALID_PROPERTY_ID (self, prop_id, pspec); + break; + } +} + +static void +gdata_freebase_topic_query_get_property (GObject *self, guint prop_id, GValue *value, GParamSpec *pspec) +{ + GDataFreebaseTopicQueryPrivate *priv = GDATA_FREEBASE_TOPIC_QUERY (self)->priv; + + switch (prop_id) { + case PROP_LANGUAGE: + g_value_set_string (value, priv->lang); + break; + case PROP_FILTER: + g_value_set_boxed (value, priv->filter); + break; + default: + G_OBJECT_WARN_INVALID_PROPERTY_ID (self, prop_id, pspec); + break; + } +} + +static void +get_query_uri (GDataQuery *self, const gchar *feed_uri, GString *query_uri, gboolean *params_started) +{ + GDataFreebaseTopicQueryPrivate *priv = GDATA_FREEBASE_TOPIC_QUERY (self)->priv; + const gchar *lang = NULL; + gint64 updated_max; + guint limit; + + g_string_append (query_uri, gdata_query_get_q (self)); + +#define APPEND_SEP g_string_append_c (query_uri, (*params_started == FALSE) ? '?' : '&'); *params_started = TRUE; + + if (priv->lang != NULL) { + lang = priv->lang; + } else { + const gchar * const *user_languages; + guint i; + + user_languages = g_get_language_names (); + + /* Pick the first user language */ + for (i = 0; user_languages[i] != NULL; i++) { + if (strlen (user_languages[i]) == 2) { + lang = user_languages[i]; + break; + } + } + } + + APPEND_SEP; + g_string_append (query_uri, "lang="); + g_string_append (query_uri, lang); + + if (priv->filter) { + guint i; + + for (i = 0; priv->filter[i] != NULL; i++) { + APPEND_SEP; + g_string_append (query_uri, "filter="); + g_string_append (query_uri, priv->filter[i]); + } + } + + updated_max = gdata_query_get_updated_max (self); + + if (updated_max > -1) { + APPEND_SEP; + g_string_append_printf (query_uri, "dateline=%" G_GINT64_FORMAT, updated_max); + } + + limit = gdata_query_get_max_results (self); + + if (limit > 0) { + APPEND_SEP; + g_string_append_printf (query_uri, "limit=%d", limit); + } + + /* We don't chain up with parent class get_query_uri because it uses + * GData protocol parameters and they aren't compatible with newest API family + */ +#undef APPEND_SEP +} + +/** + * gdata_freebase_topic_query_new: + * @id: a Freebase ID or MID + * + * Creates a new #GDataFreebaseTopicQuery for the given Freebase ID. Those can be + * obtained programmatically through gdata_freebase_search_result_item_get_id() or + * embedded in the result of a gdata_freebase_service_query() call. + * + * Return value: (transfer full): a new #GDataFreebaseTopicQuery + * + * Since: 0.15.1 + * Deprecated: 0.17.7: Google Freebase has been permanently shut down. + */ +GDataFreebaseTopicQuery * +gdata_freebase_topic_query_new (const gchar *id) +{ + g_return_val_if_fail (id != NULL, NULL); + return g_object_new (GDATA_TYPE_FREEBASE_TOPIC_QUERY, "q", id, NULL); +} + +/** + * gdata_freebase_topic_query_set_language: + * @self: a #GDataFreebaseTopicQuery + * @lang: (allow-none): language used on the topic query, in ISO-639-1 format, or %NULL to unset the language + * + * Sets the language used in the topic query. If unset, + * the locale preferences will be respected. + * + * Since: 0.15.1 + * Deprecated: 0.17.7: Google Freebase has been permanently shut down. + */ +void +gdata_freebase_topic_query_set_language (GDataFreebaseTopicQuery *self, + const gchar *lang) +{ + GDataFreebaseTopicQueryPrivate *priv; + + g_return_if_fail (GDATA_IS_FREEBASE_TOPIC_QUERY (self)); + g_return_if_fail (lang == NULL || strlen (lang) == 2); + + priv = self->priv; + + if (g_strcmp0 (priv->lang, lang) == 0) + return; + + g_free (priv->lang); + priv->lang = g_strdup (lang); + g_object_notify (G_OBJECT (self), "language"); +} + +/** + * gdata_freebase_topic_query_get_language: + * @self: a #GDataFreebaseTopicQuery + * + * Gets the language set on the topic query, or %NULL if unset. + * + * Return value: (allow-none): The language used on the query. + * + * Since: 0.15.1 + * Deprecated: 0.17.7: Google Freebase has been permanently shut down. + */ +const gchar * +gdata_freebase_topic_query_get_language (GDataFreebaseTopicQuery *self) +{ + g_return_val_if_fail (GDATA_IS_FREEBASE_TOPIC_QUERY (self), NULL); + + return self->priv->lang; +} + +/** + * gdata_freebase_topic_query_set_filter: + * @self: a #GDataFreebaseTopicQuery + * @filter: (array zero-terminated=1) (allow-none): %NULL-terminated array of filter strings, or %NULL to unset + * + * Sets a filter on the properties to be returned by the #GDataFreebaseTopicQuery, a filter string usually contains either + * a specific property (eg. "/common/topic/description", or "/computer/software/first_released"), or a property domain + * (eg. "/common/topic", or "/computer"), all properties pertaining to the domain will be returned through the + * #GDataFreebaseTopicResult in the latter case. Other special strings can be passed as filter strings, those are documented + * in the Topic API overview + * + * If multiple filter strings are set, the result will contain all information necessary to satisfy each of those individually. + * If no filter is set, the "commons" special value will be implicitly assumed, which returns a reasonably complete data set. + * + * Since: 0.15.1 + * Deprecated: 0.17.7: Google Freebase has been permanently shut down. + */ +void +gdata_freebase_topic_query_set_filter (GDataFreebaseTopicQuery *self, const gchar * const *filter) +{ + GDataFreebaseTopicQueryPrivate *priv; + + g_return_if_fail (GDATA_IS_FREEBASE_TOPIC_QUERY (self)); + priv = self->priv; + + g_strfreev (priv->filter); + priv->filter = g_strdupv ((gchar **) filter); + g_object_notify (G_OBJECT (self), "filter"); +} + +/** + * gdata_freebase_topic_query_get_filter: + * @self: a #GDataFreebaseTopicQuery + * + * Gets the filter set on the topic query, or %NULL if unset. + * + * Return value: (array zero-terminated=1) (transfer none) (allow-none): The filter used on the query. + * + * Since: 0.15.1 + * Deprecated: 0.17.7: Google Freebase has been permanently shut down. + */ +const gchar * const * +gdata_freebase_topic_query_get_filter (GDataFreebaseTopicQuery *self) +{ + g_return_val_if_fail (GDATA_IS_FREEBASE_TOPIC_QUERY (self), NULL); + + return (const gchar * const *) self->priv->filter; +} + +G_GNUC_END_IGNORE_DEPRECATIONS diff --git a/gdata/services/freebase/gdata-freebase-topic-query.h b/gdata/services/freebase/gdata-freebase-topic-query.h new file mode 100644 index 0000000..4d20a98 --- /dev/null +++ b/gdata/services/freebase/gdata-freebase-topic-query.h @@ -0,0 +1,84 @@ +/* -*- Mode: C; indent-tabs-mode: t; c-basic-offset: 8; tab-width: 8 -*- */ +/* + * GData Client + * Copyright (C) 2014 Carlos Garnacho + * + * GData Client is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * GData Client is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with GData Client. If not, see . + */ + +#ifndef GDATA_FREEBASE_TOPIC_QUERY_H +#define GDATA_FREEBASE_TOPIC_QUERY_H + +#include +#include + +#include +#include + +G_BEGIN_DECLS + +#ifndef LIBGDATA_DISABLE_DEPRECATED + +#define GDATA_TYPE_FREEBASE_TOPIC_QUERY (gdata_freebase_topic_query_get_type ()) +#define GDATA_FREEBASE_TOPIC_QUERY(o) (G_TYPE_CHECK_INSTANCE_CAST ((o), GDATA_TYPE_FREEBASE_TOPIC_QUERY, GDataFreebaseTopicQuery)) +#define GDATA_FREEBASE_TOPIC_QUERY_CLASS(k) (G_TYPE_CHECK_CLASS_CAST((k), GDATA_TYPE_FREEBASE_TOPIC_QUERY, GDataFreebaseTopicQueryClass)) +#define GDATA_IS_FREEBASE_TOPIC_QUERY(o) (G_TYPE_CHECK_INSTANCE_TYPE ((o), GDATA_TYPE_FREEBASE_TOPIC_QUERY)) +#define GDATA_IS_FREEBASE_TOPIC_QUERY_CLASS(k) (G_TYPE_CHECK_CLASS_TYPE ((k), GDATA_TYPE_FREEBASE_TOPIC_QUERY)) +#define GDATA_FREEBASE_TOPIC_QUERY_GET_CLASS(o) (G_TYPE_INSTANCE_GET_CLASS ((o), GDATA_TYPE_FREEBASE_TOPIC_QUERY, GDataFreebaseTopicQueryClass)) + +typedef struct _GDataFreebaseTopicQueryPrivate GDataFreebaseTopicQueryPrivate; + +/** + * GDataFreebaseTopicQuery: + * + * All the fields in the #GDataFreebaseTopicQuery structure are private and should never be accessed directly. + * + * Since: 0.15.1 + */ +typedef struct { + GDataQuery parent; + GDataFreebaseTopicQueryPrivate *priv; +} GDataFreebaseTopicQuery; + +/** + * GDataFreebaseTopicQueryClass: + * + * All the fields in the #GDataFreebaseTopicQueryClass structure are private and should never be accessed directly. + * + * Since: 0.15.1 + */ +typedef struct { + /*< private >*/ + GDataQueryClass parent; + + /*< private >*/ + /* Padding for future expansion */ + void (*_g_reserved0) (void); + void (*_g_reserved1) (void); +} GDataFreebaseTopicQueryClass; + +GType gdata_freebase_topic_query_get_type (void) G_GNUC_CONST G_GNUC_DEPRECATED; + +GDataFreebaseTopicQuery *gdata_freebase_topic_query_new (const gchar *id) G_GNUC_WARN_UNUSED_RESULT G_GNUC_MALLOC G_GNUC_DEPRECATED; +void gdata_freebase_topic_query_set_language (GDataFreebaseTopicQuery *self, const gchar *lang) G_GNUC_DEPRECATED; +const gchar *gdata_freebase_topic_query_get_language (GDataFreebaseTopicQuery *self) G_GNUC_DEPRECATED; + +void gdata_freebase_topic_query_set_filter (GDataFreebaseTopicQuery *self, const gchar * const *filter) G_GNUC_DEPRECATED; +const gchar * const *gdata_freebase_topic_query_get_filter (GDataFreebaseTopicQuery *self) G_GNUC_DEPRECATED; + +#endif /* !LIBGDATA_DISABLE_DEPRECATED */ + +G_END_DECLS + +#endif /* !GDATA_FREEBASE_TOPIC_QUERY_H */ diff --git a/gdata/services/freebase/gdata-freebase-topic-result.c b/gdata/services/freebase/gdata-freebase-topic-result.c new file mode 100644 index 0000000..1796efc --- /dev/null +++ b/gdata/services/freebase/gdata-freebase-topic-result.c @@ -0,0 +1,1047 @@ +/* -*- Mode: C; indent-tabs-mode: t; c-basic-offset: 8; tab-width: 8 -*- */ +/* + * GData Client + * Copyright (C) 2014 Carlos Garnacho + * + * GData Client is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * GData Client is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with GData Client. If not, see . + */ + +/** + * SECTION:gdata-freebase-topic-result + * @short_description: GData Freebase topic result object + * @stability: Stable + * @include: gdata/services/freebase/gdata-freebase-topic-result.h + * + * #GDataFreebaseTopicResult is a subclass of #GDataFreebaseResult that contains all or a subset of the information + * contained in Freebase about the Freebase ID given to the #GDataFreebaseTopicQuery. + * + * For more details of Google Freebase API, see the + * online documentation. + * + * Since: 0.15.1 + * Deprecated: 0.17.7: Google Freebase has been permanently shut down. + */ + +typedef struct _GDataFreebaseTopicValueArray GDataFreebaseTopicValueArray; + +#include +#include +#include +#include + +#include "gdata-freebase-topic-result.h" +#include "gdata-download-stream.h" +#include "gdata-private.h" +#include "gdata-types.h" + +G_GNUC_BEGIN_IGNORE_DEPRECATIONS + +typedef enum { + TYPE_NONE, + TYPE_BOOL, + TYPE_INT, + TYPE_DOUBLE, + TYPE_STRING, + TYPE_DATETIME, + TYPE_COMPOUND, + TYPE_OBJECT, + TYPE_KEY, + TYPE_URI +} TopicValueType; + +/* Wraps a compound object, either the main object returned by the result, or a + * complex object within the result values (events are at least composed of + * location and time at least, for example). + */ +struct _GDataFreebaseTopicObject { + gchar *id; + GHashTable *values; /* Hashtable of property->GDataFreebaseTopicValueArray */ + volatile gint ref_count; +}; + +/* Wraps an array of values, single-valued properties will contain an array with a single value here */ +struct _GDataFreebaseTopicValueArray { + TopicValueType type; + GPtrArray *values; + guint64 hits; /* Total number of hits, as opposed to values->len */ +}; + +/* Wraps a single value in the topic result, may be either simple (numbers, strings, Freebase IDs...), + * or nested compound types (contained by a GDataFreebaseTopicObject, which is what the value would + * contain in that case). + */ +struct _GDataFreebaseTopicValue { + gchar *property; + gchar *text; + gchar *lang; + gchar *creator; + gint64 timestamp; + GValue value; + volatile gint ref_count; +}; + +struct _GDataFreebaseTopicResultPrivate { + GDataFreebaseTopicObject *object; +}; + +static void gdata_freebase_topic_result_finalize (GObject *self); +static gboolean parse_json (GDataParsable *parsable, JsonReader *reader, gpointer user_data, GError **error); +static GDataFreebaseTopicObject *object_new (const gchar *id); +static void value_free (GDataFreebaseTopicValue *object); +static gboolean reader_get_properties (JsonReader *reader, GDataFreebaseTopicObject *object, GError **error); + +G_DEFINE_BOXED_TYPE (GDataFreebaseTopicObject, gdata_freebase_topic_object, gdata_freebase_topic_object_ref, gdata_freebase_topic_object_unref) +G_DEFINE_BOXED_TYPE (GDataFreebaseTopicValue, gdata_freebase_topic_value, gdata_freebase_topic_value_ref, gdata_freebase_topic_value_unref) +G_DEFINE_TYPE (GDataFreebaseTopicResult, gdata_freebase_topic_result, GDATA_TYPE_FREEBASE_RESULT) + +static void +gdata_freebase_topic_result_class_init (GDataFreebaseTopicResultClass *klass) +{ + GDataParsableClass *parsable_class = GDATA_PARSABLE_CLASS (klass); + GObjectClass *gobject_class = G_OBJECT_CLASS (klass); + + g_type_class_add_private (klass, sizeof (GDataFreebaseTopicResultPrivate)); + + gobject_class->finalize = gdata_freebase_topic_result_finalize; + parsable_class->parse_json = parse_json; +} + +static void +gdata_freebase_topic_result_init (GDataFreebaseTopicResult *self) +{ + self->priv = G_TYPE_INSTANCE_GET_PRIVATE (self, GDATA_TYPE_FREEBASE_TOPIC_RESULT, GDataFreebaseTopicResultPrivate); +} + +static void +gdata_freebase_topic_result_finalize (GObject *self) +{ + GDataFreebaseTopicResultPrivate *priv = GDATA_FREEBASE_TOPIC_RESULT (self)->priv; + + gdata_freebase_topic_object_unref (priv->object); + + G_OBJECT_CLASS (gdata_freebase_topic_result_parent_class)->finalize (self); +} + +static GDataFreebaseTopicValueArray * +value_array_new (TopicValueType type, guint64 hits) +{ + GDataFreebaseTopicValueArray *array; + + array = g_slice_new0 (GDataFreebaseTopicValueArray); + array->values = g_ptr_array_new_with_free_func ((GDestroyNotify) gdata_freebase_topic_value_unref); + array->type = type; + array->hits = hits; + + return array; +} + +/* Takes ownership on @value */ +static void +value_array_add (GDataFreebaseTopicValueArray *array, GDataFreebaseTopicValue *value) +{ + g_ptr_array_add (array->values, value); +} + +static void +value_array_free (GDataFreebaseTopicValueArray *array) +{ + g_ptr_array_unref (array->values); + g_slice_free (GDataFreebaseTopicValueArray, array); +} + +static guint64 +reader_get_item_count (JsonReader *reader) +{ + gint64 count; + + json_reader_read_member (reader, "count"); + count = json_reader_get_int_value (reader); + json_reader_end_member (reader); + + return (guint64) count; +} + +static guint +reader_get_value_type (JsonReader *reader, const gchar *property, GError **error) +{ + TopicValueType type = TYPE_NONE; + const GError *reader_error; + const gchar *valuestr; + + json_reader_read_member (reader, "valuetype"); + valuestr = json_reader_get_string_value (reader); + + reader_error = json_reader_get_error (reader); + + if (reader_error != NULL) { + if (error != NULL && *error == NULL) + *error = g_error_copy (reader_error); + } else { + if (strcmp (valuestr, "key") == 0) + type = TYPE_KEY; + else if (strcmp (valuestr, "uri") == 0) + type = TYPE_URI; + else if (strcmp (valuestr, "compound") == 0) + type = TYPE_COMPOUND; + else if (strcmp (valuestr, "object") == 0) + type = TYPE_OBJECT; + else if (strcmp (valuestr, "float") == 0) + type = TYPE_DOUBLE; + else if (strcmp (valuestr, "string") == 0) + type = TYPE_STRING; + else if (strcmp (valuestr, "int") == 0) + type = TYPE_INT; + else if (strcmp (valuestr, "bool") == 0) + type = TYPE_BOOL; + else if (strcmp (valuestr, "datetime") == 0) + type = TYPE_DATETIME; + else + gdata_parser_error_required_json_content_missing (reader, error); + } + + json_reader_end_member (reader); + return type; +} + +static void +value_free (GDataFreebaseTopicValue *value) +{ + if (G_IS_VALUE (&value->value)) + g_value_unset (&value->value); + g_free (value->text); + g_free (value->lang); + g_free (value->creator); + g_free (value->property); + g_slice_free (GDataFreebaseTopicValue, value); +} + +/* Parsing functions to create GDataFreebaseTopicValues, and arrays of those */ +static gchar * +reader_dup_member_string (JsonReader *reader, const gchar *member, GError **error) +{ + const GError *reader_error; + gchar *str; + + if (error != NULL && *error != NULL) + return NULL; + + json_reader_read_member (reader, member); + str = g_strdup (json_reader_get_string_value (reader)); + reader_error = json_reader_get_error (reader); + + if (reader_error != NULL) { + g_free (str); + str = NULL; + + if (error != NULL) + *error = g_error_copy (reader_error); + } + + json_reader_end_member (reader); + + return str; +} + +static gint64 +reader_parse_timestamp (JsonReader *reader, const gchar *member, GError **error) +{ + const GError *reader_error; + const gchar *date_str; + gint64 timestamp = -1; + + if (error != NULL && *error != NULL) + return -1; + + json_reader_read_member (reader, member); + date_str = json_reader_get_string_value (reader); + reader_error = json_reader_get_error (reader); + + if (reader_error != NULL) { + if (error != NULL) + *error = g_error_copy (reader_error); + } else if (date_str) { + if (!gdata_parser_int64_from_iso8601 (date_str, ×tamp)) + timestamp = -1; + } + + json_reader_end_member (reader); + + return timestamp; +} + +static gboolean +reader_fill_simple_gvalue (JsonReader *reader, TopicValueType type, GValue *value) +{ + gboolean retval = TRUE; + gint64 datetime; + + json_reader_read_member (reader, "value"); + + if (json_reader_get_error (reader) != NULL) { + json_reader_end_member (reader); + return FALSE; + } + + switch (type) { + case TYPE_BOOL: + case TYPE_INT: + case TYPE_DOUBLE: + case TYPE_STRING: + json_node_get_value (json_reader_get_value (reader), value); + break; + case TYPE_DATETIME: + if (gdata_parser_int64_from_iso8601 (json_reader_get_string_value (reader), &datetime) || + gdata_parser_int64_from_date (json_reader_get_string_value (reader), &datetime)) { + g_value_init (value, G_TYPE_INT64); + g_value_set_int64 (value, datetime); + } else { + retval = FALSE; + } + + break; + case TYPE_NONE: + case TYPE_COMPOUND: + case TYPE_OBJECT: + case TYPE_KEY: + case TYPE_URI: + default: + retval = FALSE; + } + + json_reader_end_member (reader); + return retval; +} + +static GDataFreebaseTopicObject * +reader_create_object (JsonReader *reader, TopicValueType type) +{ + GDataFreebaseTopicObject *object; + + if (type != TYPE_OBJECT && type != TYPE_COMPOUND) + return NULL; + + json_reader_read_member (reader, "id"); + + if (json_reader_get_error (reader) != NULL) { + json_reader_end_member (reader); + return NULL; + } + + object = object_new (json_reader_get_string_value (reader)); + json_reader_end_member (reader); + + return object; +} + +static gboolean +reader_fill_object_gvalue (JsonReader *reader, TopicValueType type, GValue *value) +{ + GDataFreebaseTopicObject *object; + + if (type != TYPE_OBJECT) + return FALSE; + + object = reader_create_object (reader, type); + + if (object != NULL) { + g_value_init (value, GDATA_TYPE_FREEBASE_TOPIC_OBJECT); + g_value_take_boxed (value, object); + } + + return (object != NULL); +} + +static gboolean +reader_fill_compound_gvalue (JsonReader *reader, TopicValueType type, GValue *value, GError **error) +{ + GDataFreebaseTopicObject *object; + + if (type != TYPE_COMPOUND) + return FALSE; + + object = reader_create_object (reader, type); + + if (object == NULL) + return FALSE; + + json_reader_read_member (reader, "property"); + + if (json_reader_get_error (reader) != NULL) { + json_reader_end_member (reader); + gdata_freebase_topic_object_unref (object); + return FALSE; + } + + reader_get_properties (reader, object, error); + json_reader_end_member (reader); + + g_value_init (value, GDATA_TYPE_FREEBASE_TOPIC_OBJECT); + g_value_take_boxed (value, object); + return TRUE; +} + +static GDataFreebaseTopicValue * +reader_create_value (JsonReader *reader, const gchar *property, TopicValueType type, GError **error) +{ + GDataFreebaseTopicValue *value; + + value = g_slice_new0 (GDataFreebaseTopicValue); + + value->ref_count = 1; + value->property = g_strdup (property); + value->text = reader_dup_member_string (reader, "text", error); + value->lang = reader_dup_member_string (reader, "lang", error); + + /* Not all parsed nodes are meant to contain creator/timestamp tags, + * do not pass error to those, so parsing continues. + */ + value->creator = reader_dup_member_string (reader, "creator", NULL); + value->timestamp = reader_parse_timestamp (reader, "timestamp", NULL); + + if (reader_fill_simple_gvalue (reader, type, &value->value) || + reader_fill_object_gvalue (reader, type, &value->value) || + reader_fill_compound_gvalue (reader, type, &value->value, error)) + return value; + + value_free (value); + return NULL; +} + +static GDataFreebaseTopicValueArray * +reader_create_value_array (JsonReader *reader, const gchar *property, GError **error) +{ + GDataFreebaseTopicValueArray *array; + GDataFreebaseTopicValue *value; + TopicValueType type; + guint64 count, i; + + count = reader_get_item_count (reader); + + if (count <= 0) + return NULL; + + type = reader_get_value_type (reader, property, error); + + if (type == TYPE_NONE || type == TYPE_URI || type == TYPE_KEY) + return NULL; + + array = value_array_new (type, count); + + json_reader_read_member (reader, "values"); + count = json_reader_count_elements (reader); + + for (i = 0; i < count; i++) { + json_reader_read_element (reader, i); + value = reader_create_value (reader, property, type, error); + json_reader_end_element (reader); + + if (value != NULL) + value_array_add (array, value); + } + + json_reader_end_member (reader); + + return array; +} + +static GDataFreebaseTopicObject * +object_new (const gchar *id) +{ + GDataFreebaseTopicObject *object; + + object = g_slice_new0 (GDataFreebaseTopicObject); + object->id = g_strdup (id); + object->ref_count = 1; + object->values = g_hash_table_new_full (g_str_hash, g_str_equal, + (GDestroyNotify) g_free, + (GDestroyNotify) value_array_free); + return object; +} + +/* Takes ownership on @array */ +static void +object_add_value (GDataFreebaseTopicObject *object, const gchar *property, GDataFreebaseTopicValueArray *array) +{ + g_return_if_fail (object != NULL); + g_return_if_fail (property != NULL); + g_return_if_fail (array != NULL); + g_hash_table_replace (object->values, g_strdup (property), array); +} + +static gboolean +reader_get_properties (JsonReader *reader, GDataFreebaseTopicObject *object, GError **error) +{ + GDataFreebaseTopicValueArray *array; + gboolean retval = TRUE; + gint count, i; + + count = json_reader_count_members (reader); + + for (i = 0; i < count; i++) { + GError *inner_error = NULL; + const gchar *name; + gchar *property; + + json_reader_read_element (reader, i); + property = g_strdup (json_reader_get_member_name (reader)); + name = property; + + /* Reverse properties start with !, display those as + * regular properties, and skip that char + */ + if (name[0] == '!') + name++; + + /* All Freebase properties and IDs start with '/' */ + if (name[0] != '/') + continue; + + /* Parse the value for this property, possibly with nested contents */ + array = reader_create_value_array (reader, name, &inner_error); + json_reader_end_element (reader); + + if (inner_error != NULL) { + g_propagate_error (error, inner_error); + retval = FALSE; + break; + } else if (array != NULL) { + /* Takes ownership of array */ + object_add_value (object, name, array); + } + + g_free (property); + } + + return retval; +} + +static gboolean +parse_json (GDataParsable *parsable, JsonReader *reader, gpointer user_data, GError **error) +{ + GDataFreebaseTopicResultPrivate *priv = GDATA_FREEBASE_TOPIC_RESULT (parsable)->priv; + const gchar *member_name; + + GDATA_PARSABLE_CLASS (gdata_freebase_topic_result_parent_class)->parse_json (parsable, reader, user_data, error); + + member_name = json_reader_get_member_name (reader); + + if (member_name == NULL) + return FALSE; + + if (strcmp (member_name, "id") == 0) { + /* We only expect one member containing information */ + g_assert (priv->object == NULL); + priv->object = object_new (json_reader_get_string_value (reader)); + } else if (strcmp (member_name, "property") == 0) { + reader_get_properties (reader, priv->object, error); + } else { + return FALSE; + } + + return TRUE; +} + +/** + * gdata_freebase_topic_result_new: + * + * Creates a new #GDataFreebaseTopicResult with the given ID and default properties. + * + * Return value: (transfer full): a new #GDataFreebaseTopicResult; unref with g_object_unref() + * + * Since: 0.15.1 + * Deprecated: 0.17.7: Google Freebase has been permanently shut down. + */ +GDataFreebaseTopicResult * +gdata_freebase_topic_result_new (void) +{ + return g_object_new (GDATA_TYPE_FREEBASE_TOPIC_RESULT, NULL); +} + +/** + * gdata_freebase_topic_result_dup_object: + * @self: a #GDataFreebaseTopicResult + * + * Returns a reference to the root #GDataFreebaseTopicObject containing the + * topic query results. + * + * Returns: (transfer full): A new reference on the result object, unref with + * gdata_freebase_topic_object_unref() + * + * Since: 0.15.1 + * Deprecated: 0.17.7: Google Freebase has been permanently shut down. + */ +GDataFreebaseTopicObject * +gdata_freebase_topic_result_dup_object (GDataFreebaseTopicResult *self) +{ + g_return_val_if_fail (GDATA_IS_FREEBASE_TOPIC_RESULT (self), NULL); + + return gdata_freebase_topic_object_ref (self->priv->object); +} + +/** + * gdata_freebase_topic_object_ref: + * @object: a #GDataFreebaseTopicObject + * + * Creates and returns a new reference on @object. + * + * Returns: (transfer full): @object, with an extra reference. + * + * Since: 0.15.1 + * Deprecated: 0.17.7: Google Freebase has been permanently shut down. + */ +GDataFreebaseTopicObject * +gdata_freebase_topic_object_ref (GDataFreebaseTopicObject *object) +{ + g_return_val_if_fail (object != NULL, NULL); + + g_atomic_int_inc (&object->ref_count); + return object; +} + +/** + * gdata_freebase_topic_object_unref: + * @object: (transfer full): a #GDataFreebaseTopicResult + * + * Removes a reference from @object. If the reference count drops to 0, + * the object is freed. + * + * Since: 0.15.1 + * Deprecated: 0.17.7: Google Freebase has been permanently shut down. + */ +void +gdata_freebase_topic_object_unref (GDataFreebaseTopicObject *object) +{ + g_return_if_fail (object != NULL); + + if (g_atomic_int_dec_and_test (&object->ref_count)) { + g_hash_table_unref (object->values); + g_free (object->id); + g_slice_free (GDataFreebaseTopicObject, object); + } +} + +/** + * gdata_freebase_topic_object_list_properties: + * @object: a #GDataFreebaseTopicObject + * + * Returns the list of Freebase properties described by @object. + * + * Returns: (transfer container) (element-type gchar*): An array of property names, free with g_ptr_array_unref(). + * + * Since: 0.15.1 +Deprecated: 0.17.7: Google Freebase has been permanently shut down. + */ +GPtrArray * +gdata_freebase_topic_object_list_properties (const GDataFreebaseTopicObject *object) +{ + GPtrArray *properties; + GHashTableIter iter; + gchar *property; + + g_return_val_if_fail (object != NULL, NULL); + + properties = g_ptr_array_new (); + g_hash_table_iter_init (&iter, object->values); + + while (g_hash_table_iter_next (&iter, (gpointer *) &property, NULL)) + g_ptr_array_add (properties, property); + + return properties; +} + +/** + * gdata_freebase_topic_object_get_property_count: + * @object: a #GDataFreebaseTopicObject + * @property: a property name contained in @object + * + * Returns the number of values that @object holds for the given @property. If @object + * contains no information about @property, 0 is returned. + * + * Returns: The number of values contained for @property + * + * Since: 0.15.1 + * Deprecated: 0.17.7: Google Freebase has been permanently shut down. + */ +guint64 +gdata_freebase_topic_object_get_property_count (const GDataFreebaseTopicObject *object, const gchar *property) +{ + GDataFreebaseTopicValueArray *array; + + g_return_val_if_fail (object != NULL, 0); + g_return_val_if_fail (property != NULL, 0); + array = g_hash_table_lookup (object->values, property); + + if (array == NULL) + return 0; + + return array->values->len; +} + +/** + * gdata_freebase_topic_object_get_property_hits: + * @object: a #GDataFreebaseTopicObject + * @property: a property name contained in @object + * + * Returns the total number of hits that the Freebase database stores + * for this object, this number either equals or is greater than + * gdata_freebase_topic_object_get_property_count(), the query limit + * can be controlled through gdata_query_set_max_results() on the topic + * query. + * + * If @object contains no information about @property, 0 is returned. + * + * Returns: the total number of hits for this property + * + * Since: 0.15.1 + * Deprecated: 0.17.7: Google Freebase has been permanently shut down. + */ +guint64 +gdata_freebase_topic_object_get_property_hits (const GDataFreebaseTopicObject *object, const gchar *property) +{ + GDataFreebaseTopicValueArray *array; + + g_return_val_if_fail (object != NULL, 0); + g_return_val_if_fail (property != NULL, 0); + array = g_hash_table_lookup (object->values, property); + + if (array == NULL) + return 0; + + return array->hits; +} + +/** + * gdata_freebase_topic_object_get_property_value: + * @object: a #GDataFreebaseTopicObject + * @property: a property name contained in @object + * @item: item number to retrieve from @property + * + * Gets the value that @object stores for this @property/@item pair, as a generic + * #GDataFreebaseTopicValue. If @object contains no information about @property, + * or @item is outside the [0..gdata_freebase_topic_object_get_property_count() - 1] + * range, %NULL is returned. + * + * Returns: (allow-none) (transfer none): the value for this property/item + * + * Since: 0.15.1 + * Deprecated: 0.17.7: Google Freebase has been permanently shut down. + */ +GDataFreebaseTopicValue * +gdata_freebase_topic_object_get_property_value (const GDataFreebaseTopicObject *object, const gchar *property, gint64 item) +{ + GDataFreebaseTopicValueArray *array; + + g_return_val_if_fail (object != NULL, NULL); + g_return_val_if_fail (property != NULL, NULL); + array = g_hash_table_lookup (object->values, property); + + if (array == NULL) + return NULL; + + if (item < 0 || item >= array->values->len) + return NULL; + + return g_ptr_array_index (array->values, item); +} + +/** + * gdata_freebase_topic_object_get_id: + * @object: a #GDataFreebaseTopicObject + * + * Gets the Freebase ID for this specific object. + * + * Returns: (transfer none): the Freebase ID of this object + * + * Since: 0.15.1 + * Deprecated: 0.17.7: Google Freebase has been permanently shut down. + */ +const gchar * +gdata_freebase_topic_object_get_id (const GDataFreebaseTopicObject *object) +{ + g_return_val_if_fail (object != NULL, NULL); + return object->id; +} + +/** + * gdata_freebase_topic_value_ref: + * @value: a #GDataFreebaseTopicValue + * + * Creates and returns a new reference on @value. + * + * Returns: (transfer full): @value, with an extra reference. + * + * Since: 0.15.1 + * Deprecated: 0.17.7: Google Freebase has been permanently shut down. + */ +GDataFreebaseTopicValue * +gdata_freebase_topic_value_ref (GDataFreebaseTopicValue *value) +{ + g_return_val_if_fail (value != NULL, NULL); + + g_atomic_int_inc (&value->ref_count); + return value; +} + +/** + * gdata_freebase_topic_value_unref: + * @value: (transfer full): a #GDataFreebaseTopicValue + * + * Removes a reference from @value. If the reference count drops to 0, + * the object is freed. + * + * Since: 0.15.1 + * Deprecated: 0.17.7: Google Freebase has been permanently shut down. + */ +void +gdata_freebase_topic_value_unref (GDataFreebaseTopicValue *value) +{ + g_return_if_fail (value != NULL); + + if (g_atomic_int_dec_and_test (&value->ref_count)) + value_free (value); +} + +/** + * gdata_freebase_topic_value_get_property: + * @value: a #GDataFreebaseTopicValue + * + * Returns the property name that this value describes + * + * Returns: the property name of @value + * + * Since: 0.15.1 + * Deprecated: 0.17.7: Google Freebase has been permanently shut down. + */ +const gchar * +gdata_freebase_topic_value_get_property (GDataFreebaseTopicValue *value) +{ + g_return_val_if_fail (value != NULL, NULL); + return value->property; +} + +/** + * gdata_freebase_topic_value_get_text: + * @value: a #GDataFreebaseTopicValue + * + * Returns a textual representation of this value, this is either + * the value contained transformed to a string, or a concatenation + * of subvalues for compound types. + * + * Returns: a textual representation of @value + * + * Since: 0.15.1 + * Deprecated: 0.17.7: Google Freebase has been permanently shut down. + */ +const gchar * +gdata_freebase_topic_value_get_text (GDataFreebaseTopicValue *value) +{ + g_return_val_if_fail (value != NULL, NULL); + return value->text; +} + +/** + * gdata_freebase_topic_value_get_language: + * @value: a #GDataFreebaseTopicValue + * + * Returns the language used in the content of @value + * + * Returns: the language @value is written in + * + * Since: 0.15.1 + * Deprecated: 0.17.7: Google Freebase has been permanently shut down. + */ +const gchar * +gdata_freebase_topic_value_get_language (GDataFreebaseTopicValue *value) +{ + g_return_val_if_fail (value != NULL, NULL); + return value->lang; +} + +/** + * gdata_freebase_topic_value_get_creator: + * @value: a #GDataFreebaseTopicValue + * + * Returns the Freebase ID of the user that created this value. + * + * Returns: the creator of this value, as a Freebase ID + * + * Since: 0.15.1 + * Deprecated: 0.17.7: Google Freebase has been permanently shut down. + */ +const gchar * +gdata_freebase_topic_value_get_creator (GDataFreebaseTopicValue *value) +{ + g_return_val_if_fail (value != NULL, NULL); + return value->creator; +} + +/** + * gdata_freebase_topic_value_get_timestamp: + * @value: #GDataFreebaseTopicValue + * + * Returns the time at which this value was created in the Freebase database. + * It's a UNIX timestamp in seconds since the epoch. If @value has no timestamp, + * -1 will be returned. + * + * Returns: The creation time of @value, or -1 + * + * Since: 0.15.1 + * Deprecated: 0.17.7: Google Freebase has been permanently shut down. + */ +gint64 +gdata_freebase_topic_value_get_timestamp (GDataFreebaseTopicValue *value) +{ + g_return_val_if_fail (value != NULL, 0); + return value->timestamp; +} + +/** + * gdata_freebase_topic_value_get_value_type: + * @value: a #GDataFreebaseTopicValue + * + * Returns the #GType of the real value held in @value. + * + * Returns: the #GType of the contained value + * + * Since: 0.15.1 + * Deprecated: 0.17.7: Google Freebase has been permanently shut down. + */ +GType +gdata_freebase_topic_value_get_value_type (GDataFreebaseTopicValue *value) +{ + g_return_val_if_fail (value != NULL, G_TYPE_INVALID); + return G_VALUE_TYPE (&value->value); +} + +/** + * gdata_freebase_topic_value_copy_value: + * @value: a #GDataFreebaseTopicValue + * @gvalue: (out caller-allocates) (transfer full): an empty #GValue + * + * Copies in @gvalue the value held in @value. the #GValue must be later freed through g_value_unset() + * + * Since: 0.15.1 + * Deprecated: 0.17.7: Google Freebase has been permanently shut down. + */ +void +gdata_freebase_topic_value_copy_value (GDataFreebaseTopicValue *value, GValue *gvalue) +{ + g_return_if_fail (value != NULL); + + g_value_copy (&value->value, gvalue); +} + +/** + * gdata_freebase_topic_value_get_int: + * @value: a #GDataFreebaseTopicValue + * + * Returns a #gint64 value held in @value. It is only valid to call this if the #GType is a %G_TYPE_INT64 + * + * Returns: the #gint64 value + * + * Since: 0.15.1 + * Deprecated: 0.17.7: Google Freebase has been permanently shut down. + */ +gint64 +gdata_freebase_topic_value_get_int (GDataFreebaseTopicValue *value) +{ + g_return_val_if_fail (value != NULL, 0); + g_return_val_if_fail (G_VALUE_HOLDS_INT64 (&value->value), 0); + + return g_value_get_int64 (&value->value); +} + +/** + * gdata_freebase_topic_value_get_double: + * @value: a #GDataFreebaseTopicValue + * + * Returns a #gdouble value held in @value. It is only valid to call this if the #GType is a %G_TYPE_DOUBLE + * + * Returns: the #gdouble value + * + * Since: 0.15.1 + * Deprecated: 0.17.7: Google Freebase has been permanently shut down. + */ +gdouble +gdata_freebase_topic_value_get_double (GDataFreebaseTopicValue *value) +{ + g_return_val_if_fail (value != NULL, 0); + g_return_val_if_fail (G_VALUE_HOLDS_DOUBLE (&value->value), 0); + + return g_value_get_double (&value->value); +} + +/** + * gdata_freebase_topic_value_get_string: + * @value: a #GDataFreebaseTopicValue + * + * Returns a string value held in @value. It is only valid to call this if the #GType is a %G_TYPE_STRING + * + * Returns: the string value + * + * Since: 0.15.1 + * Deprecated: 0.17.7: Google Freebase has been permanently shut down. + */ +const gchar * +gdata_freebase_topic_value_get_string (GDataFreebaseTopicValue *value) +{ + g_return_val_if_fail (value != NULL, NULL); + g_return_val_if_fail (G_VALUE_HOLDS_STRING (&value->value), NULL); + + return g_value_get_string (&value->value); +} + +/** + * gdata_freebase_topic_value_get_object: + * @value: a #GDataFreebaseTopicValue + * + * Returns a compound/complex object held in @value. It is only valid to call this if the #GType is a + * %GDATA_TYPE_FREEBASE_TOPIC_OBJECT. + * + * Returns: (transfer none): the compound value as a #GDataFreebaseTopicObject + * + * Since: 0.15.1 + * Deprecated: 0.17.7: Google Freebase has been permanently shut down. + */ +const GDataFreebaseTopicObject * +gdata_freebase_topic_value_get_object (GDataFreebaseTopicValue *value) +{ + g_return_val_if_fail (value != NULL, NULL); + g_return_val_if_fail (G_VALUE_HOLDS (&value->value, GDATA_TYPE_FREEBASE_TOPIC_OBJECT), NULL); + + return g_value_get_boxed (&value->value); +} + +/** + * gdata_freebase_topic_value_is_image: + * @value: a #GDataFreebaseTopicValue + * + * Returns true if @value holds a freebase image object, on such values it + * will be valid to call gdata_freebase_service_get_image() to get a stream + * to the image itself. + * + * Returns: Whether @value holds a Freebase image object + * + * Since: 0.15.1 + * Deprecated: 0.17.7: Google Freebase has been permanently shut down. + */ +gboolean +gdata_freebase_topic_value_is_image (GDataFreebaseTopicValue *value) +{ + g_return_val_if_fail (value != NULL, FALSE); + + return (strcmp (value->property, "/common/topic/image") == 0); +} + +G_GNUC_END_IGNORE_DEPRECATIONS diff --git a/gdata/services/freebase/gdata-freebase-topic-result.h b/gdata/services/freebase/gdata-freebase-topic-result.h new file mode 100644 index 0000000..34b73e2 --- /dev/null +++ b/gdata/services/freebase/gdata-freebase-topic-result.h @@ -0,0 +1,135 @@ +/* -*- Mode: C; indent-tabs-mode: t; c-basic-offset: 8; tab-width: 8 -*- */ +/* + * GData Client + * Copyright (C) 2014 Carlos Garnacho + * + * GData Client is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * GData Client is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with GData Client. If not, see . + */ + +#ifndef GDATA_FREEBASE_TOPIC_RESULT_H +#define GDATA_FREEBASE_TOPIC_RESULT_H + +#include +#include + +#include +#include "gdata-freebase-result.h" + +G_BEGIN_DECLS + +#ifndef LIBGDATA_DISABLE_DEPRECATED + +#define GDATA_TYPE_FREEBASE_TOPIC_OBJECT (gdata_freebase_topic_object_get_type ()) +#define GDATA_TYPE_FREEBASE_TOPIC_VALUE (gdata_freebase_topic_value_get_type ()) +#define GDATA_TYPE_FREEBASE_TOPIC_RESULT (gdata_freebase_topic_result_get_type ()) +#define GDATA_FREEBASE_TOPIC_RESULT(o) (G_TYPE_CHECK_INSTANCE_CAST ((o), GDATA_TYPE_FREEBASE_TOPIC_RESULT, GDataFreebaseTopicResult)) +#define GDATA_FREEBASE_TOPIC_RESULT_CLASS(k) (G_TYPE_CHECK_CLASS_CAST((k), GDATA_TYPE_FREEBASE_TOPIC_RESULT, GDataFreebaseTopicResultClass)) +#define GDATA_IS_FREEBASE_TOPIC_RESULT(o) (G_TYPE_CHECK_INSTANCE_TYPE ((o), GDATA_TYPE_FREEBASE_TOPIC_RESULT)) +#define GDATA_IS_FREEBASE_TOPIC_RESULT_CLASS(k) (G_TYPE_CHECK_CLASS_TYPE ((k), GDATA_TYPE_FREEBASE_TOPIC_RESULT)) +#define GDATA_FREEBASE_TOPIC_RESULT_GET_CLASS(o) (G_TYPE_INSTANCE_GET_CLASS ((o), GDATA_TYPE_FREEBASE_TOPIC_RESULT, GDataFreebaseTopicResultClass)) + +typedef struct _GDataFreebaseTopicResultPrivate GDataFreebaseTopicResultPrivate; + +/** + * GDataFreebaseTopicObject: + * + * Opaque struct containing a Freebase topic object. This object may contain one or more + * #GDataFreebaseTopicValue structs, which may in turn contain nested #GDataFreebaseTopicObject + * structs to express complex data. + * + * Since: 0.15.1 + */ +typedef struct _GDataFreebaseTopicObject GDataFreebaseTopicObject; + +/** + * GDataFreebaseTopicValue: + * + * Opaque struct containing a value of a Freebase topic object. This struct may contain a simple + * value (integers, doubles, strings...) or complex values, expressed through a #GDataFreebaseTopicObject. + * + * Since: 0.15.1 + */ +typedef struct _GDataFreebaseTopicValue GDataFreebaseTopicValue; + +/** + * GDataFreebaseTopicResult: + * + * All the fields in the #GDataFreebaseTopicResult structure are private and should never be accessed directly. + * + * Since: 0.15.1 + */ +typedef struct { + GDataFreebaseResult parent; + GDataFreebaseTopicResultPrivate *priv; +} GDataFreebaseTopicResult; + +/** + * GDataFreebaseTopicResultClass: + * + * All the fields in the #GDataFreebaseTopicResultClass structure are private and should never be accessed directly. + * + * Since: 0.15.1 + */ +typedef struct { + /*< private >*/ + GDataFreebaseResultClass parent; + + /*< private >*/ + /* Padding for future expansion */ + void (*_g_reserved0) (void); + void (*_g_reserved1) (void); +} GDataFreebaseTopicResultClass; + +GType gdata_freebase_topic_object_get_type (void) G_GNUC_CONST G_GNUC_DEPRECATED; +GType gdata_freebase_topic_value_get_type (void) G_GNUC_CONST G_GNUC_DEPRECATED; +GType gdata_freebase_topic_result_get_type (void) G_GNUC_CONST G_GNUC_DEPRECATED; + +GDataFreebaseTopicResult *gdata_freebase_topic_result_new (void) G_GNUC_WARN_UNUSED_RESULT G_GNUC_MALLOC G_GNUC_DEPRECATED; + +GDataFreebaseTopicObject *gdata_freebase_topic_result_dup_object (GDataFreebaseTopicResult *self) G_GNUC_DEPRECATED; + +GDataFreebaseTopicObject *gdata_freebase_topic_object_ref (GDataFreebaseTopicObject *object) G_GNUC_DEPRECATED; +void gdata_freebase_topic_object_unref (GDataFreebaseTopicObject *object) G_GNUC_DEPRECATED; + +GPtrArray *gdata_freebase_topic_object_list_properties (const GDataFreebaseTopicObject *object) G_GNUC_DEPRECATED; + +const gchar *gdata_freebase_topic_object_get_id (const GDataFreebaseTopicObject *object) G_GNUC_DEPRECATED; +guint64 gdata_freebase_topic_object_get_property_count (const GDataFreebaseTopicObject *object, const gchar *property) G_GNUC_DEPRECATED; +guint64 gdata_freebase_topic_object_get_property_hits (const GDataFreebaseTopicObject *object, const gchar *property) G_GNUC_DEPRECATED; +GDataFreebaseTopicValue *gdata_freebase_topic_object_get_property_value (const GDataFreebaseTopicObject *object, const gchar *property, gint64 item) G_GNUC_DEPRECATED; + +GDataFreebaseTopicValue *gdata_freebase_topic_value_ref (GDataFreebaseTopicValue *value) G_GNUC_DEPRECATED; +void gdata_freebase_topic_value_unref (GDataFreebaseTopicValue *value) G_GNUC_DEPRECATED; + +const gchar *gdata_freebase_topic_value_get_property (GDataFreebaseTopicValue *value) G_GNUC_DEPRECATED; + +const gchar *gdata_freebase_topic_value_get_text (GDataFreebaseTopicValue *value) G_GNUC_DEPRECATED; +const gchar *gdata_freebase_topic_value_get_language (GDataFreebaseTopicValue *value) G_GNUC_DEPRECATED; +const gchar *gdata_freebase_topic_value_get_creator (GDataFreebaseTopicValue *value) G_GNUC_DEPRECATED; +gint64 gdata_freebase_topic_value_get_timestamp (GDataFreebaseTopicValue *value) G_GNUC_DEPRECATED; +GType gdata_freebase_topic_value_get_value_type (GDataFreebaseTopicValue *value) G_GNUC_DEPRECATED; +void gdata_freebase_topic_value_copy_value (GDataFreebaseTopicValue *value, GValue *gvalue) G_GNUC_DEPRECATED; + +gint64 gdata_freebase_topic_value_get_int (GDataFreebaseTopicValue *value) G_GNUC_DEPRECATED; +gdouble gdata_freebase_topic_value_get_double (GDataFreebaseTopicValue *value) G_GNUC_DEPRECATED; +const gchar *gdata_freebase_topic_value_get_string (GDataFreebaseTopicValue *value) G_GNUC_DEPRECATED; +const GDataFreebaseTopicObject *gdata_freebase_topic_value_get_object (GDataFreebaseTopicValue *value) G_GNUC_DEPRECATED; + +gboolean gdata_freebase_topic_value_is_image (GDataFreebaseTopicValue *value) G_GNUC_DEPRECATED; + +#endif /* !LIBGDATA_DISABLE_DEPRECATED */ + +G_END_DECLS + +#endif /* !GDATA_FREEBASE_TOPIC_RESULT_H */ diff --git a/gdata/services/freebase/meson.build b/gdata/services/freebase/meson.build new file mode 100644 index 0000000..7ed419a --- /dev/null +++ b/gdata/services/freebase/meson.build @@ -0,0 +1,58 @@ +incs += include_directories('.') + +include_subdir = gdata_include_subdir / 'services/freebase' + +headers = files( + 'gdata-freebase-query.h', + 'gdata-freebase-result.h', + 'gdata-freebase-search-query.h', + 'gdata-freebase-search-result.h', + 'gdata-freebase-service.h', + 'gdata-freebase-topic-query.h', + 'gdata-freebase-topic-result.h', +) + +install_headers( + headers, + subdir: include_subdir, +) + +gir_headers += headers + +sources += files( + 'gdata-freebase-query.c', + 'gdata-freebase-result.c', + 'gdata-freebase-search-query.c', + 'gdata-freebase-search-result.c', + 'gdata-freebase-service.c', + 'gdata-freebase-topic-query.c', + 'gdata-freebase-topic-result.c', +) + +enums = 'gdata-freebase-enums' + +enums_in = gnome.mkenums_simple( + enums + '-in', + sources: headers, +) + +# FIXME: Work around the namespace being incorrectly detected +# by glib-mkenums. This needs to be fixed by changing the +# namespace in libgdata. See !6. +sources += custom_target( + enums + '.c', + input: enums_in[0], + output: enums + '.c', + command: enum_source_cmd, + capture: true, +) + +enum_headers += custom_target( + enums + '.h', + input: enums_in[1], + output: enums + '.h', + command: enum_header_cmd, + capture: true, + install: true, + install_dir: gdata_includedir / include_subdir, +) diff --git a/gdata/services/meson.build b/gdata/services/meson.build new file mode 100644 index 0000000..f9879c7 --- /dev/null +++ b/gdata/services/meson.build @@ -0,0 +1,7 @@ +subdir('calendar') +subdir('contacts') +subdir('documents') +subdir('freebase') +subdir('picasaweb') +subdir('tasks') +subdir('youtube') diff --git a/gdata/services/picasaweb/gdata-picasaweb-album.c b/gdata/services/picasaweb/gdata-picasaweb-album.c new file mode 100644 index 0000000..cb55c04 --- /dev/null +++ b/gdata/services/picasaweb/gdata-picasaweb-album.c @@ -0,0 +1,1268 @@ +/* -*- Mode: C; indent-tabs-mode: t; c-basic-offset: 8; tab-width: 8 -*- */ +/* + * GData Client + * Copyright (C) Richard Schwarting 2009 + * Copyright (C) Philip Withnall 2009–2010 + * + * GData Client is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * GData Client is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with GData Client. If not, see . + */ + +/** + * SECTION:gdata-picasaweb-album + * @short_description: GData PicasaWeb album object + * @stability: Stable + * @include: gdata/services/picasaweb/gdata-picasaweb-album.h + * + * #GDataPicasaWebAlbum is a subclass of #GDataEntry to represent an album from Google PicasaWeb. + * + * For more details of Google PicasaWeb's GData API, see the + * online documentation. + * + * + * Getting Basic Album Data + * + * GDataFeed *album_feed; + * GList *album_entries; + * + * /* Query for a feed of GDataPicasaWebAlbums owned by user "libgdata.picasaweb" */ + * album_feed = gdata_picasaweb_service_query_all_albums (service, NULL, "libgdata.picasaweb", NULL, NULL, NULL, NULL); + * + * /* Get a list of GDataPicasaWebAlbums from the query's feed */ + * for (album_entries = gdata_feed_get_entries (album_feed); album_entries != NULL; album_entries = album_entries->next) { + * GDataPicasaWebAlbum *album; + * guint num_photos; + * const gchar *owner_nickname, *title, *summary; + * gint64 timestamp; + * GList *thumbnails; + * + * album = GDATA_PICASAWEB_ALBUM (album_entries->data); + * + * /* Get various bits of information about the album */ + * num_photos = gdata_picasaweb_album_get_num_photos (album); + * owner_nickname = gdata_picasaweb_album_get_nickname (album); + * title = gdata_entry_get_title (GDATA_ENTRY (album)); + * summary = gdata_entry_get_summary (GDATA_ENTRY (album)); + * /* Get the day the album was shot on or, if not set, when it was uploaded. This is in milliseconds since the epoch. */ + * timestamp = gdata_picasaweb_album_get_timestamp (album); + * + * for (thumbnails = gdata_picasaweb_album_get_thumbnails (album); thumbnails != NULL; thumbnails = thumbnails->next) { + * GDataMediaThumbnail *thumbnail; + * GDataDownloadStream *download_stream; + * GdkPixbuf *pixbuf; + * + * thumbnail = GDATA_MEDIA_THUMBNAIL (thumbnails->data); + * /* Do something fun with the thumbnails, like download and display them. We could just as easily download them into + * * files using g_file_create() and g_output_stream_splice(), rather than create GdkPixbufs directly from them. + * * Note that this is a blocking operation. */ + * download_stream = gdata_media_thumbnail_download (thumbnail, GDATA_SERVICE (service), NULL, NULL); + * pixbuf = gdk_pixbuf_new_from_stream (G_INPUT_STREAM (download_stream), NULL, NULL); + * g_object_unref (download_stream); + * /* ... */ + * g_object_unref (pixbuf); + * } + * + * /* Do something worthwhile with your album data */ + * } + * + * g_object_unref (album_feed); + * + * + * + * Since: 0.4.0 + */ + +/* TODO: support the album cover/icon ? I think this is already done with the thumbnails, but we don't set it yet :( */ + +#include +#include +#include +#include +#include + +#include "gdata-picasaweb-album.h" +#include "gdata-private.h" +#include "gdata-service.h" +#include "gdata-parsable.h" +#include "gdata-parser.h" +#include "gdata-types.h" +#include "media/gdata-media-group.h" +#include "gdata-picasaweb-enums.h" +#include "georss/gdata-georss-where.h" + +static GObject *gdata_picasaweb_album_constructor (GType type, guint n_construct_params, GObjectConstructParam *construct_params); +static void gdata_picasaweb_album_dispose (GObject *object); +static void gdata_picasaweb_album_finalize (GObject *object); +static void gdata_picasaweb_album_get_property (GObject *object, guint property_id, GValue *value, GParamSpec *pspec); +static void gdata_picasaweb_album_set_property (GObject *object, guint property_id, const GValue *value, GParamSpec *pspec); +static void get_xml (GDataParsable *parsable, GString *xml_string); +static gboolean parse_xml (GDataParsable *parsable, xmlDoc *doc, xmlNode *node, gpointer user_data, GError **error); +static void get_namespaces (GDataParsable *parsable, GHashTable *namespaces); + +struct _GDataPicasaWebAlbumPrivate { + gchar *album_id; + gchar *user; + gchar *nickname; + gint64 edited; + gchar *location; + GDataPicasaWebVisibility visibility; + gint64 timestamp; /* in milliseconds! */ + guint num_photos; + guint num_photos_remaining; + glong bytes_used; + gboolean is_commenting_enabled; + guint comment_count; + + /* media:group */ + GDataMediaGroup *media_group; + /* georss:where */ + GDataGeoRSSWhere *georss_where; +}; + +enum { + PROP_USER = 1, + PROP_NICKNAME, + PROP_EDITED, + PROP_LOCATION, + PROP_VISIBILITY, + PROP_TIMESTAMP, + PROP_NUM_PHOTOS, + PROP_NUM_PHOTOS_REMAINING, + PROP_BYTES_USED, + PROP_IS_COMMENTING_ENABLED, + PROP_COMMENT_COUNT, + PROP_TAGS, + PROP_LATITUDE, + PROP_LONGITUDE, + PROP_ALBUM_ID +}; + +G_DEFINE_TYPE (GDataPicasaWebAlbum, gdata_picasaweb_album, GDATA_TYPE_ENTRY) + +static void +gdata_picasaweb_album_class_init (GDataPicasaWebAlbumClass *klass) +{ + GObjectClass *gobject_class = G_OBJECT_CLASS (klass); + GDataParsableClass *parsable_class = GDATA_PARSABLE_CLASS (klass); + GDataEntryClass *entry_class = GDATA_ENTRY_CLASS (klass); + + g_type_class_add_private (klass, sizeof (GDataPicasaWebAlbumPrivate)); + + gobject_class->constructor = gdata_picasaweb_album_constructor; + gobject_class->get_property = gdata_picasaweb_album_get_property; + gobject_class->set_property = gdata_picasaweb_album_set_property; + gobject_class->dispose = gdata_picasaweb_album_dispose; + gobject_class->finalize = gdata_picasaweb_album_finalize; + + parsable_class->parse_xml = parse_xml; + parsable_class->get_xml = get_xml; + parsable_class->get_namespaces = get_namespaces; + + entry_class->kind_term = "http://schemas.google.com/photos/2007#album"; + + /** + * GDataPicasaWebAlbum:album-id: + * + * The ID of the album. This is a substring of the ID returned by gdata_entry_get_id() for #GDataPicasaWebAlbums; for example, + * if gdata_entry_get_id() returned "http://picasaweb.google.com/data/entry/user/libgdata.picasaweb/albumid/5328889949261497249" for a + * particular #GDataPicasaWebAlbum, the #GDataPicasaWebAlbum:album-id property would be "5328889949261497249". + * + * For more information, see the + * gphoto specification. + * + * Since: 0.7.0 + */ + g_object_class_install_property (gobject_class, PROP_ALBUM_ID, + g_param_spec_string ("album-id", + "Album ID", "The ID of the album.", + NULL, + G_PARAM_READWRITE | G_PARAM_CONSTRUCT_ONLY | G_PARAM_STATIC_STRINGS)); + + /** + * GDataPicasaWebAlbum:user: + * + * The username of the album owner. + * + * For more information, see the + * gphoto specification. + * + * Since: 0.4.0 + */ + g_object_class_install_property (gobject_class, PROP_USER, + g_param_spec_string ("user", + "User", "The username of the album owner.", + NULL, + G_PARAM_READABLE | G_PARAM_STATIC_STRINGS)); + + /** + * GDataPicasaWebAlbum:nickname: + * + * The user's nickname. This is a user-specified value that should be used when referring to the user by name. + * + * For more information, see the + * gphoto specification. + * + * Since: 0.4.0 + */ + g_object_class_install_property (gobject_class, PROP_NICKNAME, + g_param_spec_string ("nickname", + "Nickname", "The user's nickname.", + NULL, + G_PARAM_READABLE | G_PARAM_STATIC_STRINGS)); + + /** + * GDataPicasaWebAlbum:edited: + * + * The time this album was last edited. If the album has not been edited yet, the content indicates the time it was created. + * + * For more information, see the + * Atom Publishing Protocol specification. + * + * Since: 0.4.0 + */ + g_object_class_install_property (gobject_class, PROP_EDITED, + g_param_spec_int64 ("edited", + "Edited", "The time this album was last edited.", + -1, G_MAXINT64, -1, + G_PARAM_READABLE | G_PARAM_STATIC_STRINGS)); + + /** + * GDataPicasaWebAlbum:location: + * + * The user-specified location associated with the album. A place name. + * + * For more information, see the + * gphoto specification. + * + * Since: 0.4.0 + */ + g_object_class_install_property (gobject_class, PROP_LOCATION, + g_param_spec_string ("location", + "Location", "The user-specified location associated with the album.", + NULL, + G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)); + + /** + * GDataPicasaWebAlbum:visibility: + * + * The visibility (or access rights) of the album. + * + * For more information, see the + * gphoto specification. + * + * Since: 0.4.0 + */ + g_object_class_install_property (gobject_class, PROP_VISIBILITY, + g_param_spec_enum ("visibility", + "Visibility", "The visibility (or access rights) of the album.", + GDATA_TYPE_PICASAWEB_VISIBILITY, GDATA_PICASAWEB_PRIVATE, + G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)); + + /** + * GDataPicasaWebAlbum:timestamp: + * + * The timestamp of when the album occurred, settable by the user. This a UNIX timestamp in milliseconds (not seconds) since the epoch. + * + * For more information, see the + * gphoto specification. + * + * Since: 0.4.0 + */ + g_object_class_install_property (gobject_class, PROP_TIMESTAMP, + g_param_spec_int64 ("timestamp", + "Timestamp", "The timestamp of when the album occurred, settable by the user.", + -1, G_MAXINT64, -1, + G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)); + + /* TODO: Change to photo-count? */ + /** + * GDataPicasaWebAlbum:num-photos: + * + * The number of photos and videos in the album. + * + * For more information, see the + * gphoto specification. + * + * Since: 0.4.0 + */ + g_object_class_install_property (gobject_class, PROP_NUM_PHOTOS, + g_param_spec_uint ("num-photos", + "Number of photos", "The number of photos and videos in the album.", + 0, G_MAXUINT, 0, + G_PARAM_READABLE | G_PARAM_STATIC_STRINGS)); + + /* TODO: Change to remaining-photos-count? */ + /** + * GDataPicasaWebAlbum:num-photos-remaining: + * + * The number of photos and videos that can still be uploaded to this album. + * This doesn't account for quota, just a hardcoded maximum number per album set by Google. + * + * For more information, see the + * gphoto specification. + * + * Since: 0.4.0 + */ + g_object_class_install_property (gobject_class, PROP_NUM_PHOTOS_REMAINING, + g_param_spec_uint ("num-photos-remaining", + "Number of photo spaces remaining", "The number of files spaces still free for uploads.", + 0, G_MAXUINT, 0, + G_PARAM_READABLE | G_PARAM_STATIC_STRINGS)); + + /** + * GDataPicasaWebAlbum:bytes-used: + * + * The number of bytes consumed by this album and its contents. Note that this is only set if the authenticated user is the owner of the + * album; it's otherwise -1. + * + * For more information, see the + * gphoto specification. + * + * Since: 0.4.0 + */ + g_object_class_install_property (gobject_class, PROP_BYTES_USED, + g_param_spec_long ("bytes-used", + "Number of bytes used", "The number of bytes consumed by this album and its contents.", + -1, G_MAXLONG, -1, + G_PARAM_READABLE | G_PARAM_STATIC_STRINGS)); + + /** + * GDataPicasaWebAlbum:commenting-enabled: + * + * Whether commenting is enabled for this album. + * + * Since: 0.4.0 + */ + g_object_class_install_property (gobject_class, PROP_IS_COMMENTING_ENABLED, + g_param_spec_boolean ("is-commenting-enabled", + "Commenting enabled?", "Whether commenting is enabled for this album.", + FALSE, + G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)); + + /** + * GDataPicasaWebAlbum:comment-count: + * + * The number of comments on the album. + * + * For more information, see the + * gphoto specification. + * + * Since: 0.4.0 + */ + g_object_class_install_property (gobject_class, PROP_COMMENT_COUNT, + g_param_spec_uint ("comment-count", + "Comment count", "The number of comments on the album.", + 0, G_MAXUINT, 0, + G_PARAM_READABLE | G_PARAM_STATIC_STRINGS)); + + /** + * GDataPicasaWebAlbum:tags: + * + * A %NULL-terminated array of tags associated with the album; all the tags associated with the individual photos in the album. + * + * For more information, see the + * Media RSS specification. + * + * Since: 0.4.0 + */ + g_object_class_install_property (gobject_class, PROP_TAGS, + g_param_spec_boxed ("tags", + "Tags", "A NULL-terminated array of tags associated with the album", + G_TYPE_STRV, + G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)); + + /** + * GDataPicasaWebAlbum:latitude: + * + * The location as a latitude coordinate associated with this album. Valid latitudes range from -90.0 + * to 90.0 inclusive. + * + * For more information, see the + * GeoRSS specification. + * + * Since: 0.5.0 + */ + g_object_class_install_property (gobject_class, PROP_LATITUDE, + g_param_spec_double ("latitude", + "Latitude", "The location as a latitude coordinate associated with this album.", + -90.0, 90.0, 0.0, + G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)); + + /** + * GDataPicasaWebAlbum:longitude: + * + * The location as a longitude coordinate associated with this album. Valid longitudes range from -180.0 + * to 180.0 inclusive. + * + * For more information, see the + * GeoRSS specification. + * + * Since: 0.5.0 + */ + g_object_class_install_property (gobject_class, PROP_LONGITUDE, + g_param_spec_double ("longitude", + "Longitude", "The location as a longitude coordinate associated with this album.", + -180.0, 180.0, 0.0, + G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)); +} + +static void +notify_title_cb (GDataPicasaWebAlbum *self, GParamSpec *pspec, gpointer user_data) +{ + /* Update our media:group title */ + if (self->priv->media_group != NULL) + gdata_media_group_set_title (self->priv->media_group, gdata_entry_get_title (GDATA_ENTRY (self))); +} + +static void +notify_summary_cb (GDataPicasaWebAlbum *self, GParamSpec *pspec, gpointer user_data) +{ + /* Update our media:group description */ + if (self->priv->media_group != NULL) + gdata_media_group_set_description (self->priv->media_group, gdata_entry_get_summary (GDATA_ENTRY (self))); +} + +static void notify_visibility_cb (GDataPicasaWebAlbum *self, GParamSpec *pspec, gpointer user_data); + +static void +notify_rights_cb (GDataPicasaWebAlbum *self, GParamSpec *pspec, gpointer user_data) +{ + const gchar *rights = gdata_entry_get_rights (GDATA_ENTRY (self)); + + /* Update our gphoto:visibility */ + g_signal_handlers_block_by_func (self, notify_visibility_cb, NULL); + + if (rights == NULL || strcmp (rights, "public") == 0) { + gdata_picasaweb_album_set_visibility (self, GDATA_PICASAWEB_PUBLIC); + } else if (strcmp (rights, "private") == 0) { + gdata_picasaweb_album_set_visibility (self, GDATA_PICASAWEB_PRIVATE); + } else { + /* Print out a warning and leave the visibility as it is */ + g_warning ("Unknown or value: %s", rights); + } + + g_signal_handlers_unblock_by_func (self, notify_visibility_cb, NULL); +} + +static void +notify_visibility_cb (GDataPicasaWebAlbum *self, GParamSpec *pspec, gpointer user_data) +{ + /* Update our GDataEntry's atom:rights */ + g_signal_handlers_block_by_func (self, notify_rights_cb, NULL); + + switch (self->priv->visibility) { + case GDATA_PICASAWEB_PUBLIC: + gdata_entry_set_rights (GDATA_ENTRY (self), "public"); + break; + case GDATA_PICASAWEB_PRIVATE: + gdata_entry_set_rights (GDATA_ENTRY (self), "private"); + break; + default: + g_assert_not_reached (); + } + + g_signal_handlers_unblock_by_func (self, notify_rights_cb, NULL); +} + +static void +gdata_picasaweb_album_init (GDataPicasaWebAlbum *self) +{ + self->priv = G_TYPE_INSTANCE_GET_PRIVATE (self, GDATA_TYPE_PICASAWEB_ALBUM, GDataPicasaWebAlbumPrivate); + self->priv->media_group = g_object_new (GDATA_TYPE_MEDIA_GROUP, NULL); + self->priv->georss_where = g_object_new (GDATA_TYPE_GEORSS_WHERE, NULL); + self->priv->edited = -1; + self->priv->timestamp = -1; + + /* Set the initial visibility */ + self->priv->visibility = GDATA_PICASAWEB_PRIVATE; + gdata_entry_set_rights (GDATA_ENTRY (self), "private"); + + /* Connect to the notify::title signal from GDataEntry so our media:group title can be kept in sync + * (the title of an album is duplicated in atom:title and media:group/media:title) */ + g_signal_connect (GDATA_ENTRY (self), "notify::title", G_CALLBACK (notify_title_cb), NULL); + /* Connect to the notify::description signal from GDataEntry so our media:group description can be kept in sync + * (the description of an album is duplicated in atom:summary and media:group/media:description) */ + g_signal_connect (GDATA_ENTRY (self), "notify::summary", G_CALLBACK (notify_summary_cb), NULL); + /* Connect to the notify::rights signal from GDataEntry so our gphoto:visibility can be kept in sync (and vice-versa) + * (visibility settings are duplicated in atom:rights and gphoto:visibility) */ + g_signal_connect (GDATA_ENTRY (self), "notify::rights", G_CALLBACK (notify_rights_cb), NULL); + g_signal_connect (self, "notify::visibility", G_CALLBACK (notify_visibility_cb), NULL); +} + +static GObject * +gdata_picasaweb_album_constructor (GType type, guint n_construct_params, GObjectConstructParam *construct_params) +{ + GObject *object; + + /* Chain up to the parent class */ + object = G_OBJECT_CLASS (gdata_picasaweb_album_parent_class)->constructor (type, n_construct_params, construct_params); + + if (_gdata_parsable_is_constructed_from_xml (GDATA_PARSABLE (object)) == FALSE) { + GDataPicasaWebAlbumPrivate *priv = GDATA_PICASAWEB_ALBUM (object)->priv; + GTimeVal time_val; + + /* Set the edited and timestamp properties to the current time (creation time). bgo#599140 + * We don't do this in *_init() since that would cause setting it from parse_xml() to fail (duplicate element). */ + g_get_current_time (&time_val); + priv->timestamp = (gint64) time_val.tv_sec * 1000; + priv->edited = time_val.tv_sec; + } + + return object; +} + +static void +gdata_picasaweb_album_dispose (GObject *object) +{ + GDataPicasaWebAlbumPrivate *priv = GDATA_PICASAWEB_ALBUM (object)->priv; + + if (priv->media_group != NULL) + g_object_unref (priv->media_group); + priv->media_group = NULL; + + if (priv->georss_where != NULL) + g_object_unref (priv->georss_where); + priv->georss_where = NULL; + + /* Chain up to the parent class */ + G_OBJECT_CLASS (gdata_picasaweb_album_parent_class)->dispose (object); +} + +static void +gdata_picasaweb_album_finalize (GObject *object) +{ + GDataPicasaWebAlbumPrivate *priv = GDATA_PICASAWEB_ALBUM (object)->priv; + + g_free (priv->album_id); + g_free (priv->user); + g_free (priv->nickname); + g_free (priv->location); + + /* Chain up to the parent class */ + G_OBJECT_CLASS (gdata_picasaweb_album_parent_class)->finalize (object); +} + +static void +gdata_picasaweb_album_get_property (GObject *object, guint property_id, GValue *value, GParamSpec *pspec) +{ + GDataPicasaWebAlbumPrivate *priv = GDATA_PICASAWEB_ALBUM (object)->priv; + + switch (property_id) { + case PROP_ALBUM_ID: + g_value_set_string (value, priv->album_id); + break; + case PROP_USER: + g_value_set_string (value, priv->user); + break; + case PROP_NICKNAME: + g_value_set_string (value, priv->nickname); + break; + case PROP_EDITED: + g_value_set_int64 (value, priv->edited); + break; + case PROP_LOCATION: + g_value_set_string (value, priv->location); + break; + case PROP_VISIBILITY: + g_value_set_enum (value, priv->visibility); + break; + case PROP_TIMESTAMP: + g_value_set_int64 (value, priv->timestamp); + break; + case PROP_NUM_PHOTOS: + g_value_set_uint (value, priv->num_photos); + break; + case PROP_NUM_PHOTOS_REMAINING: + g_value_set_uint (value, priv->num_photos_remaining); + break; + case PROP_BYTES_USED: + g_value_set_long (value, priv->bytes_used); + break; + case PROP_IS_COMMENTING_ENABLED: + g_value_set_boolean (value, priv->is_commenting_enabled); + break; + case PROP_COMMENT_COUNT: + g_value_set_uint (value, priv->comment_count); + break; + case PROP_TAGS: + g_value_set_boxed (value, gdata_media_group_get_keywords (priv->media_group)); + break; + case PROP_LATITUDE: + g_value_set_double (value, gdata_georss_where_get_latitude (priv->georss_where)); + break; + case PROP_LONGITUDE: + g_value_set_double (value, gdata_georss_where_get_longitude (priv->georss_where)); + break; + default: + /* We don't have any other property... */ + G_OBJECT_WARN_INVALID_PROPERTY_ID (object, property_id, pspec); + break; + } +} + +static void +gdata_picasaweb_album_set_property (GObject *object, guint property_id, const GValue *value, GParamSpec *pspec) +{ + GDataPicasaWebAlbum *self = GDATA_PICASAWEB_ALBUM (object); + + switch (property_id) { + case PROP_ALBUM_ID: + /* Construct only */ + g_free (self->priv->album_id); + self->priv->album_id = g_value_dup_string (value); + break; + case PROP_LOCATION: + gdata_picasaweb_album_set_location (self, g_value_get_string (value)); + break; + case PROP_VISIBILITY: + gdata_picasaweb_album_set_visibility (self, g_value_get_enum (value)); + break; + case PROP_TIMESTAMP: + gdata_picasaweb_album_set_timestamp (self, g_value_get_int64 (value)); + break; + case PROP_IS_COMMENTING_ENABLED: + gdata_picasaweb_album_set_is_commenting_enabled (self, g_value_get_boolean (value)); + break; + case PROP_TAGS: + gdata_picasaweb_album_set_tags (self, g_value_get_boxed (value)); + break; + case PROP_LATITUDE: + gdata_picasaweb_album_set_coordinates (self, g_value_get_double (value), + gdata_georss_where_get_longitude (self->priv->georss_where)); + break; + case PROP_LONGITUDE: + gdata_picasaweb_album_set_coordinates (self, gdata_georss_where_get_latitude (self->priv->georss_where), + g_value_get_double (value)); + break; + default: + /* We don't have any other property... */ + G_OBJECT_WARN_INVALID_PROPERTY_ID (object, property_id, pspec); + break; + } +} + +static gboolean +parse_xml (GDataParsable *parsable, xmlDoc *doc, xmlNode *node, gpointer user_data, GError **error) +{ + gboolean success; + GDataPicasaWebAlbum *self = GDATA_PICASAWEB_ALBUM (parsable); + + /* TODO: media:group should also be P_NO_DUPES, but we can't, as priv->media_group has to be pre-populated + * in order for things like gdata_picasaweb_album_get_tags() to work. */ + if (gdata_parser_is_namespace (node, "http://www.w3.org/2007/app") == TRUE && + gdata_parser_int64_time_from_element (node, "edited", P_REQUIRED | P_NO_DUPES, &(self->priv->edited), &success, error) == TRUE) { + return success; + } else if (gdata_parser_is_namespace (node, "http://search.yahoo.com/mrss/") == TRUE && + gdata_parser_object_from_element (node, "group", P_REQUIRED, GDATA_TYPE_MEDIA_GROUP, + &(self->priv->media_group), &success, error) == TRUE) { + return success; + } else if (gdata_parser_is_namespace (node, "http://www.georss.org/georss") == TRUE && + gdata_parser_object_from_element (node, "where", P_REQUIRED, GDATA_TYPE_GEORSS_WHERE, + &(self->priv->georss_where), &success, error) == TRUE) { + return success; + } else if (gdata_parser_is_namespace (node, "http://schemas.google.com/photos/2007") == TRUE) { + if (gdata_parser_string_from_element (node, "user", P_REQUIRED | P_NON_EMPTY, &(self->priv->user), &success, error) == TRUE || + gdata_parser_string_from_element (node, "nickname", P_REQUIRED | P_NON_EMPTY, &(self->priv->nickname), &success, error) == TRUE || + gdata_parser_string_from_element (node, "location", P_NONE, &(self->priv->location), &success, error) == TRUE || + gdata_parser_string_from_element (node, "id", P_REQUIRED | P_NON_EMPTY | P_NO_DUPES, + &(self->priv->album_id), &success, error) == TRUE) { + return success; + } else if (xmlStrcmp (node->name, (xmlChar*) "access") == 0) { + /* gphoto:access */ + xmlChar *access_level = xmlNodeListGetString (doc, node->children, TRUE); + if (xmlStrcmp (access_level, (xmlChar*) "public") == 0) { + gdata_picasaweb_album_set_visibility (self, GDATA_PICASAWEB_PUBLIC); + } else if (xmlStrcmp (access_level, (xmlChar*) "private") == 0 || + xmlStrcmp (access_level, (xmlChar*) "protected") == 0) { + gdata_picasaweb_album_set_visibility (self, GDATA_PICASAWEB_PRIVATE); + } else { + gdata_parser_error_unknown_content (node, (gchar*) access_level, error); + xmlFree (access_level); + return FALSE; + } + xmlFree (access_level); + } else if (xmlStrcmp (node->name, (xmlChar*) "timestamp") == 0) { + /* gphoto:timestamp */ + xmlChar *timestamp_str; + guint64 milliseconds; + + timestamp_str = xmlNodeListGetString (doc, node->children, TRUE); + milliseconds = g_ascii_strtoull ((gchar*) timestamp_str, NULL, 10); + xmlFree (timestamp_str); + + gdata_picasaweb_album_set_timestamp (self, (gint64) milliseconds); + } else if (xmlStrcmp (node->name, (xmlChar*) "numphotos") == 0) { + /* gphoto:numphotos */ + xmlChar *num_photos = xmlNodeListGetString (doc, node->children, TRUE); + if (num_photos == NULL || *num_photos == '\0') { + xmlFree (num_photos); + return gdata_parser_error_required_content_missing (node, error); + } + + self->priv->num_photos = g_ascii_strtoull ((char*) num_photos, NULL, 10); + xmlFree (num_photos); + } else if (xmlStrcmp (node->name, (xmlChar*) "numphotosremaining") == 0) { + /* gphoto:numphotosremaining */ + xmlChar *num_photos_remaining = xmlNodeListGetString (doc, node->children, TRUE); + if (num_photos_remaining == NULL || *num_photos_remaining == '\0') { + xmlFree (num_photos_remaining); + return gdata_parser_error_required_content_missing (node, error); + } + + self->priv->num_photos_remaining = g_ascii_strtoull ((char*) num_photos_remaining, NULL, 10); + xmlFree (num_photos_remaining); + } else if (xmlStrcmp (node->name, (xmlChar*) "bytesUsed") == 0) { + /* gphoto:bytesUsed */ + xmlChar *bytes_used = xmlNodeListGetString (doc, node->children, TRUE); + if (bytes_used == NULL || *bytes_used == '\0') { + xmlFree (bytes_used); + return gdata_parser_error_required_content_missing (node, error); + } + + self->priv->bytes_used = g_ascii_strtoll ((char*) bytes_used, NULL, 10); + xmlFree (bytes_used); + } else if (xmlStrcmp (node->name, (xmlChar*) "commentingEnabled") == 0) { + /* gphoto:commentingEnabled */ + xmlChar *commenting_enabled = xmlNodeListGetString (doc, node->children, TRUE); + if (commenting_enabled == NULL || *commenting_enabled == '\0') { + xmlFree (commenting_enabled); + return gdata_parser_error_required_content_missing (node, error); + } + + gdata_picasaweb_album_set_is_commenting_enabled (self, + (xmlStrcmp (commenting_enabled, (xmlChar*) "true") == 0) ? TRUE : FALSE); + xmlFree (commenting_enabled); + } else if (xmlStrcmp (node->name, (xmlChar*) "commentCount") == 0) { + /* gphoto:commentCount */ + xmlChar *comment_count = xmlNodeListGetString (doc, node->children, TRUE); + if (comment_count == NULL || *comment_count == '\0') { + xmlFree (comment_count); + return gdata_parser_error_required_content_missing (node, error); + } + + self->priv->comment_count = g_ascii_strtoull ((char*) comment_count, NULL, 10); + xmlFree (comment_count); + } else { + return GDATA_PARSABLE_CLASS (gdata_picasaweb_album_parent_class)->parse_xml (parsable, doc, node, user_data, error); + } + } else { + return GDATA_PARSABLE_CLASS (gdata_picasaweb_album_parent_class)->parse_xml (parsable, doc, node, user_data, error); + } + + return TRUE; +} + +static void +get_xml (GDataParsable *parsable, GString *xml_string) +{ + GDataPicasaWebAlbumPrivate *priv = GDATA_PICASAWEB_ALBUM (parsable)->priv; + + /* Chain up to the parent class */ + GDATA_PARSABLE_CLASS (gdata_picasaweb_album_parent_class)->get_xml (parsable, xml_string); + + /* Add all the album-specific XML */ + if (priv->album_id != NULL) + gdata_parser_string_append_escaped (xml_string, "", priv->album_id, ""); + + if (priv->location != NULL) + gdata_parser_string_append_escaped (xml_string, "", priv->location, ""); + + switch (priv->visibility) { + case GDATA_PICASAWEB_PUBLIC: + g_string_append (xml_string, "public"); + break; + case GDATA_PICASAWEB_PRIVATE: + g_string_append (xml_string, "private"); + break; + default: + g_assert_not_reached (); + } + + if (priv->timestamp != -1) { + /* in milliseconds */ + g_string_append_printf (xml_string, "%" G_GINT64_FORMAT "", priv->timestamp); + } + + if (priv->is_commenting_enabled == FALSE) + g_string_append (xml_string, "false"); + else + g_string_append (xml_string, "true"); + + /* media:group */ + _gdata_parsable_get_xml (GDATA_PARSABLE (priv->media_group), xml_string, FALSE); + + /* georss:where */ + if (priv->georss_where != NULL && gdata_georss_where_get_latitude (priv->georss_where) != G_MAXDOUBLE && + gdata_georss_where_get_longitude (priv->georss_where) != G_MAXDOUBLE) { + _gdata_parsable_get_xml (GDATA_PARSABLE (priv->georss_where), xml_string, FALSE); + } + + /* TODO: + * - Finish supporting all tags + * - Check all tags here are valid for insertions and updates + */ +} + +static void +get_namespaces (GDataParsable *parsable, GHashTable *namespaces) +{ + GDataPicasaWebAlbumPrivate *priv = GDATA_PICASAWEB_ALBUM (parsable)->priv; + + /* Chain up to the parent class */ + GDATA_PARSABLE_CLASS (gdata_picasaweb_album_parent_class)->get_namespaces (parsable, namespaces); + + g_hash_table_insert (namespaces, (gchar*) "gphoto", (gchar*) "http://schemas.google.com/photos/2007"); + g_hash_table_insert (namespaces, (gchar*) "app", (gchar*) "http://www.w3.org/2007/app"); + + /* Add the media:group namespaces */ + GDATA_PARSABLE_GET_CLASS (priv->media_group)->get_namespaces (GDATA_PARSABLE (priv->media_group), namespaces); + /* Add the georss:where namespaces */ + GDATA_PARSABLE_GET_CLASS (priv->georss_where)->get_namespaces (GDATA_PARSABLE (priv->georss_where), namespaces); +} + +/** + * gdata_picasaweb_album_new: + * @id: (allow-none): the album's entry ID, or %NULL + * + * Creates a new #GDataPicasaWebAlbum with the given ID and default properties. @id is the ID which would be returned by gdata_entry_get_id(), + * not gdata_picasaweb_album_get_id(). + * + * If @id is not %NULL and can't be parsed to extract an album ID, %NULL will be returned. + * + * Return value: a new #GDataPicasaWebAlbum, or %NULL; unref with g_object_unref() + * + * Since: 0.4.0 + */ +GDataPicasaWebAlbum * +gdata_picasaweb_album_new (const gchar *id) +{ + const gchar *album_id = NULL, *i; + + if (id != NULL) { + album_id = g_strrstr (id, "/"); + if (album_id == NULL) + return NULL; + album_id++; /* skip the slash */ + + /* Ensure the @album_id is entirely numeric */ + for (i = album_id; *i != '\0'; i = g_utf8_next_char (i)) { + if (g_unichar_isdigit (g_utf8_get_char (i)) == FALSE) + return NULL; + } + } + + return GDATA_PICASAWEB_ALBUM (g_object_new (GDATA_TYPE_PICASAWEB_ALBUM, "id", id, "album-id", album_id, NULL)); +} + +/** + * gdata_picasaweb_album_get_id: + * @self: a #GDataPicasaWebAlbum + * + * Gets the #GDataPicasaWebAlbum:album-id property. + * + * Return value: the album's ID + * + * Since: 0.7.0 + */ +const gchar * +gdata_picasaweb_album_get_id (GDataPicasaWebAlbum *self) +{ + g_return_val_if_fail (GDATA_IS_PICASAWEB_ALBUM (self), NULL); + return self->priv->album_id; +} + +/** + * gdata_picasaweb_album_get_user: + * @self: a #GDataPicasaWebAlbum + * + * Gets the #GDataPicasaWebAlbum:user property. + * + * Return value: the album owner's username + * + * Since: 0.4.0 + */ +const gchar * +gdata_picasaweb_album_get_user (GDataPicasaWebAlbum *self) +{ + g_return_val_if_fail (GDATA_IS_PICASAWEB_ALBUM (self), NULL); + return self->priv->user; +} + +/** + * gdata_picasaweb_album_get_nickname: + * @self: a #GDataPicasaWebAlbum + * + * Gets the #GDataPicasaWebAlbum:nickname property. + * + * Return value: the album owner's nickname + * + * Since: 0.4.0 + */ +const gchar * +gdata_picasaweb_album_get_nickname (GDataPicasaWebAlbum *self) +{ + g_return_val_if_fail (GDATA_IS_PICASAWEB_ALBUM (self), NULL); + return self->priv->nickname; +} + +/** + * gdata_picasaweb_album_get_edited: + * @self: a #GDataPicasaWebAlbum + * + * Gets the #GDataPicasaWebAlbum:edited property. If the property is unset, -1 will be returned. + * + * Return value: the UNIX timestamp for the time the album was last edited, or -1 + * + * Since: 0.4.0 + */ +gint64 +gdata_picasaweb_album_get_edited (GDataPicasaWebAlbum *self) +{ + g_return_val_if_fail (GDATA_IS_PICASAWEB_ALBUM (self), -1); + return self->priv->edited; +} + +/** + * gdata_picasaweb_album_get_location: + * @self: a #GDataPicasaWebAlbum + * + * Gets the #GDataPicasaWebAlbum:location property. + * + * Return value: the album's location, or %NULL + * + * Since: 0.4.0 + */ +const gchar * +gdata_picasaweb_album_get_location (GDataPicasaWebAlbum *self) +{ + g_return_val_if_fail (GDATA_IS_PICASAWEB_ALBUM (self), NULL); + return self->priv->location; +} + +/** + * gdata_picasaweb_album_set_location: + * @self: a #GDataPicasaWebAlbum + * @location: (allow-none): the new album location, or %NULL + * + * Sets the #GDataPicasaWebAlbum:location property to @location. + * + * Set @location to %NULL to unset the property. + * + * Since: 0.4.0 + */ +void +gdata_picasaweb_album_set_location (GDataPicasaWebAlbum *self, const gchar *location) +{ + g_return_if_fail (GDATA_IS_PICASAWEB_ALBUM (self)); + + g_free (self->priv->location); + self->priv->location = g_strdup (location); + g_object_notify (G_OBJECT (self), "location"); +} + +/** + * gdata_picasaweb_album_get_visibility: + * @self: a #GDataPicasaWebAlbum + * + * Gets the #GDataPicasaWebAlbum:visibility property. + * + * Return value: the album's visibility level + * + * Since: 0.4.0 + */ +GDataPicasaWebVisibility +gdata_picasaweb_album_get_visibility (GDataPicasaWebAlbum *self) +{ + g_return_val_if_fail (GDATA_IS_PICASAWEB_ALBUM (self), GDATA_PICASAWEB_PUBLIC); + return self->priv->visibility; +} + +/** + * gdata_picasaweb_album_set_visibility: + * @self: a #GDataPicasaWebAlbum + * @visibility: the new album visibility level + * + * Sets the #GDataPicasaWebAlbum:visibility property to @visibility. + * + * Since: 0.4.0 + */ +void +gdata_picasaweb_album_set_visibility (GDataPicasaWebAlbum *self, GDataPicasaWebVisibility visibility) +{ + g_return_if_fail (GDATA_IS_PICASAWEB_ALBUM (self)); + + self->priv->visibility = visibility; + g_object_notify (G_OBJECT (self), "visibility"); +} + +/** + * gdata_picasaweb_album_get_timestamp: + * @self: a #GDataPicasaWebAlbum + * + * Gets the #GDataPicasaWebAlbum:timestamp property. This value usually holds either the date that best corresponds to the album of photos, or to the + * day it was uploaded. It's a UNIX timestamp in milliseconds (not seconds) since the epoch. If the property is unset, -1 + * will be returned. + * + * Return value: the UNIX timestamp for the timestamp property in milliseconds, or -1 + * + * Since: 0.4.0 + */ +gint64 +gdata_picasaweb_album_get_timestamp (GDataPicasaWebAlbum *self) +{ + g_return_val_if_fail (GDATA_IS_PICASAWEB_ALBUM (self), -1); + return self->priv->timestamp; +} + +/** + * gdata_picasaweb_album_set_timestamp: + * @self: a #GDataPicasaWebAlbum + * @timestamp: a UNIX timestamp, or -1 + * + * Sets the #GDataPicasaWebAlbum:timestamp property from @timestamp. This should be a UNIX timestamp in milliseconds (not seconds) since the epoch. + * + * Set @timestamp to -1 to unset the property. + * + * Since: 0.4.0 + */ +void +gdata_picasaweb_album_set_timestamp (GDataPicasaWebAlbum *self, gint64 timestamp) +{ + g_return_if_fail (GDATA_IS_PICASAWEB_ALBUM (self)); + g_return_if_fail (timestamp >= -1); + + self->priv->timestamp = timestamp; + g_object_notify (G_OBJECT (self), "timestamp"); +} + +/** + * gdata_picasaweb_album_get_num_photos: + * @self: a #GDataPicasaWebAlbum + * + * Gets the #GDataPicasaWebAlbum:num-photos property. + * + * Return value: the number of photos currently in the album + * + * Since: 0.4.0 + */ +guint +gdata_picasaweb_album_get_num_photos (GDataPicasaWebAlbum *self) +{ + g_return_val_if_fail (GDATA_IS_PICASAWEB_ALBUM (self), 0); + return self->priv->num_photos; +} + +/** + * gdata_picasaweb_album_get_num_photos_remaining: + * @self: a #GDataPicasaWebAlbum + * + * Gets the #GDataPicasaWebAlbum:num-photos-remaining property. + * + * Return value: the number of photos that can still be uploaded to the album + * + * Since: 0.4.0 + */ +guint +gdata_picasaweb_album_get_num_photos_remaining (GDataPicasaWebAlbum *self) +{ + g_return_val_if_fail (GDATA_IS_PICASAWEB_ALBUM (self), 0); + return self->priv->num_photos_remaining; +} + +/** + * gdata_picasaweb_album_get_bytes_used: + * @self: a #GDataPicasaWebAlbum + * + * Gets the #GDataPicasaWebAlbum:bytes-used property. It will return -1 if the current authenticated + * user is not the owner of the album. + * + * Return value: the number of bytes used by the album and its contents, or -1 + * + * Since: 0.4.0 + */ +glong +gdata_picasaweb_album_get_bytes_used (GDataPicasaWebAlbum *self) +{ + g_return_val_if_fail (GDATA_IS_PICASAWEB_ALBUM (self), -1); + return self->priv->bytes_used; +} + +/** + * gdata_picasaweb_album_is_commenting_enabled: + * @self: a #GDataPicasaWebAlbum + * + * Gets the #GDataPicasaWebAlbum:is-commenting-enabled property. + * + * Return value: %TRUE if commenting is enabled for the album, %FALSE otherwise + * + * Since: 0.4.0 + */ +gboolean +gdata_picasaweb_album_is_commenting_enabled (GDataPicasaWebAlbum *self) +{ + g_return_val_if_fail (GDATA_IS_PICASAWEB_ALBUM (self), FALSE); + return self->priv->is_commenting_enabled; +} + +/** + * gdata_picasaweb_album_set_is_commenting_enabled: + * @self: a #GDataPicasaWebAlbum + * @is_commenting_enabled: %TRUE if commenting should be enabled for the album, %FALSE otherwise + * + * Sets the #GDataPicasaWebAlbum:is-commenting-enabled property to @is_commenting_enabled. + * + * Since: 0.4.0 + */ +void +gdata_picasaweb_album_set_is_commenting_enabled (GDataPicasaWebAlbum *self, gboolean is_commenting_enabled) +{ + g_return_if_fail (GDATA_IS_PICASAWEB_ALBUM (self)); + self->priv->is_commenting_enabled = is_commenting_enabled; + g_object_notify (G_OBJECT (self), "is-commenting-enabled"); +} + +/** + * gdata_picasaweb_album_get_comment_count: + * @self: a #GDataPicasaWebAlbum + * + * Gets the #GDataPicasaWebAlbum:comment-count property. + * + * Return value: the number of comments on the album + * + * Since: 0.4.0 + */ +guint +gdata_picasaweb_album_get_comment_count (GDataPicasaWebAlbum *self) +{ + g_return_val_if_fail (GDATA_IS_PICASAWEB_ALBUM (self), 0); + return self->priv->comment_count; +} + +/** + * gdata_picasaweb_album_get_tags: + * @self: a #GDataPicasaWebAlbum + * + * Gets the #GDataPicasaWebAlbum:tags property. + * + * Return value: (array zero-terminated=1) (transfer none): a %NULL-terminated array of tags associated with all the photos in the album, or %NULL + * + * Since: 0.4.0 + */ +const gchar * const * +gdata_picasaweb_album_get_tags (GDataPicasaWebAlbum *self) +{ + g_return_val_if_fail (GDATA_IS_PICASAWEB_ALBUM (self), NULL); + return gdata_media_group_get_keywords (self->priv->media_group); +} + +/** + * gdata_picasaweb_album_set_tags: + * @self: a #GDataPicasaWebAlbum + * @tags: (array zero-terminated=1) (allow-none): the new %NULL-terminated array of tags, or %NULL + * + * Sets the #GDataPicasaWebAlbum:tags property to @tags. + * + * Set @tags to %NULL to unset the album's tag list. + * + * Since: 0.4.0 + */ +void +gdata_picasaweb_album_set_tags (GDataPicasaWebAlbum *self, const gchar * const *tags) +{ + g_return_if_fail (GDATA_IS_PICASAWEB_ALBUM (self)); + + gdata_media_group_set_keywords (self->priv->media_group, tags); + g_object_notify (G_OBJECT (self), "tags"); +} + +/** + * gdata_picasaweb_album_get_contents: + * @self: a #GDataPicasaWebAlbum + * + * Returns a list of media content, such as the cover image for the album. + * + * Return value: (element-type GData.MediaContent) (transfer none): a #GList of #GDataMediaContent items + * + * Since: 0.4.0 + */ +GList * +gdata_picasaweb_album_get_contents (GDataPicasaWebAlbum *self) +{ + g_return_val_if_fail (GDATA_IS_PICASAWEB_ALBUM (self), NULL); + return gdata_media_group_get_contents (self->priv->media_group); +} + +/** + * gdata_picasaweb_album_get_thumbnails: + * @self: a #GDataPicasaWebAlbum + * + * Returns a list of thumbnails, often at different sizes, for this album. + * + * Return value: (element-type GData.MediaThumbnail) (transfer none): a #GList of #GDataMediaThumbnails, or %NULL + * + * Since: 0.4.0 + */ +GList * +gdata_picasaweb_album_get_thumbnails (GDataPicasaWebAlbum *self) +{ + g_return_val_if_fail (GDATA_IS_PICASAWEB_ALBUM (self), NULL); + return gdata_media_group_get_thumbnails (self->priv->media_group); +} + +/** + * gdata_picasaweb_album_get_coordinates: + * @self: a #GDataPicasaWebAlbum + * @latitude: (out caller-allocates) (allow-none): return location for the latitude, or %NULL + * @longitude: (out caller-allocates) (allow-none): return location for the longitude, or %NULL + * + * Gets the #GDataPicasaWebAlbum:latitude and #GDataPicasaWebAlbum:longitude properties, + * setting the out parameters to them. If either latitude or longitude is %NULL, that parameter will not be set. + * If the coordinates are unset, @latitude and @longitude will be set to %G_MAXDOUBLE. + * + * Since: 0.5.0 + */ +void +gdata_picasaweb_album_get_coordinates (GDataPicasaWebAlbum *self, gdouble *latitude, gdouble *longitude) +{ + g_return_if_fail (GDATA_IS_PICASAWEB_ALBUM (self)); + + if (latitude != NULL) + *latitude = gdata_georss_where_get_latitude (self->priv->georss_where); + if (longitude != NULL) + *longitude = gdata_georss_where_get_longitude (self->priv->georss_where); +} + +/** + * gdata_picasaweb_album_set_coordinates: + * @self: a #GDataPicasaWebAlbum + * @latitude: the album's new latitude coordinate, or %G_MAXDOUBLE + * @longitude: the album's new longitude coordinate, or %G_MAXDOUBLE + * + * Sets the #GDataPicasaWebAlbum:latitude and #GDataPicasaWebAlbum:longitude properties to + * @latitude and @longitude respectively. + * + * Since: 0.5.0 + */ +void +gdata_picasaweb_album_set_coordinates (GDataPicasaWebAlbum *self, gdouble latitude, gdouble longitude) +{ + g_return_if_fail (GDATA_IS_PICASAWEB_ALBUM (self)); + + gdata_georss_where_set_latitude (self->priv->georss_where, latitude); + gdata_georss_where_set_longitude (self->priv->georss_where, longitude); + + g_object_freeze_notify (G_OBJECT (self)); + g_object_notify (G_OBJECT (self), "latitude"); + g_object_notify (G_OBJECT (self), "longitude"); + g_object_thaw_notify (G_OBJECT (self)); +} diff --git a/gdata/services/picasaweb/gdata-picasaweb-album.h b/gdata/services/picasaweb/gdata-picasaweb-album.h new file mode 100644 index 0000000..005560b --- /dev/null +++ b/gdata/services/picasaweb/gdata-picasaweb-album.h @@ -0,0 +1,114 @@ +/* -*- Mode: C; indent-tabs-mode: t; c-basic-offset: 8; tab-width: 8 -*- */ +/* + * GData Client + * Copyright (C) Richard Schwarting 2009 + * Copyright (C) Philip Withnall 2009 + * + * GData Client is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * GData Client is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with GData Client. If not, see . + */ + +#ifndef GDATA_PICASWEB_ALBUM_H +#define GDATA_PICASWEB_ALBUM_H + +#include +#include + +#include + +G_BEGIN_DECLS + +/** + * GDataPicasaWebVisibility: + * @GDATA_PICASAWEB_PUBLIC: the album is visible to everyone, regardless of whether they're authenticated + * @GDATA_PICASAWEB_PRIVATE: the album is visible only to authenticated users in an allowlist + * + * Visibility statuses available for albums on PicasaWeb. For more information, see the + * online documentation. + * + * Since: 0.4.0 + */ +typedef enum { + GDATA_PICASAWEB_PUBLIC = 1, + GDATA_PICASAWEB_PRIVATE +} GDataPicasaWebVisibility; + +#define GDATA_TYPE_PICASAWEB_ALBUM (gdata_picasaweb_album_get_type ()) +#define GDATA_PICASAWEB_ALBUM(o) (G_TYPE_CHECK_INSTANCE_CAST ((o), GDATA_TYPE_PICASAWEB_ALBUM, GDataPicasaWebAlbum)) +#define GDATA_PICASAWEB_ALBUM_CLASS(k) (G_TYPE_CHECK_CLASS_CAST((k), GDATA_TYPE_PICASAWEB_ALBUM, GDataPicasaWebAlbumClass)) +#define GDATA_IS_PICASAWEB_ALBUM(o) (G_TYPE_CHECK_INSTANCE_TYPE ((o), GDATA_TYPE_PICASAWEB_ALBUM)) +#define GDATA_IS_PICASAWEB_ALBUM_CLASS(k) (G_TYPE_CHECK_CLASS_TYPE ((k), GDATA_TYPE_PICASAWEB_ALBUM)) +#define GDATA_PICASAWEB_ALBUM_GET_CLASS(o) (G_TYPE_INSTANCE_GET_CLASS ((o), GDATA_TYPE_PICASAWEB_ALBUM, GDataPicasaWebAlbumClass)) + +typedef struct _GDataPicasaWebAlbumPrivate GDataPicasaWebAlbumPrivate; + +/** + * GDataPicasaWebAlbum: + * + * All the fields in the #GDataPicasaWebAlbum structure are private and should never be accessed directly. + * + * Since: 0.4.0 + */ +typedef struct { + GDataEntry parent; + GDataPicasaWebAlbumPrivate *priv; +} GDataPicasaWebAlbum; + +/** + * GDataPicasaWebAlbumClass: + * + * All the fields in the #GDataPicasaWebAlbumClass structure are private and should never be accessed directly. + * + * Since: 0.4.0 + */ +typedef struct { + /*< private >*/ + GDataEntryClass parent; + + /*< private >*/ + /* Padding for future expansion */ + void (*_g_reserved0) (void); + void (*_g_reserved1) (void); +} GDataPicasaWebAlbumClass; + +GType gdata_picasaweb_album_get_type (void) G_GNUC_CONST; +G_DEFINE_AUTOPTR_CLEANUP_FUNC (GDataPicasaWebAlbum, g_object_unref) + +GDataPicasaWebAlbum *gdata_picasaweb_album_new (const gchar *id) G_GNUC_WARN_UNUSED_RESULT G_GNUC_MALLOC; + +const gchar *gdata_picasaweb_album_get_id (GDataPicasaWebAlbum *self) G_GNUC_PURE; +const gchar *gdata_picasaweb_album_get_user (GDataPicasaWebAlbum *self) G_GNUC_PURE; +const gchar *gdata_picasaweb_album_get_nickname (GDataPicasaWebAlbum *self) G_GNUC_PURE; +gint64 gdata_picasaweb_album_get_edited (GDataPicasaWebAlbum *self); +const gchar *gdata_picasaweb_album_get_location (GDataPicasaWebAlbum *self) G_GNUC_PURE; +void gdata_picasaweb_album_set_location (GDataPicasaWebAlbum *self, const gchar *location); +GDataPicasaWebVisibility gdata_picasaweb_album_get_visibility (GDataPicasaWebAlbum *self) G_GNUC_PURE; +void gdata_picasaweb_album_set_visibility (GDataPicasaWebAlbum *self, GDataPicasaWebVisibility visibility); +gint64 gdata_picasaweb_album_get_timestamp (GDataPicasaWebAlbum *self); +void gdata_picasaweb_album_set_timestamp (GDataPicasaWebAlbum *self, gint64 timestamp); +guint gdata_picasaweb_album_get_num_photos (GDataPicasaWebAlbum *self) G_GNUC_PURE; +guint gdata_picasaweb_album_get_num_photos_remaining (GDataPicasaWebAlbum *self) G_GNUC_PURE; +glong gdata_picasaweb_album_get_bytes_used (GDataPicasaWebAlbum *self) G_GNUC_PURE; +gboolean gdata_picasaweb_album_is_commenting_enabled (GDataPicasaWebAlbum *self) G_GNUC_PURE; +void gdata_picasaweb_album_set_is_commenting_enabled (GDataPicasaWebAlbum *self, gboolean is_commenting_enabled); +guint gdata_picasaweb_album_get_comment_count (GDataPicasaWebAlbum *self) G_GNUC_PURE; +const gchar * const *gdata_picasaweb_album_get_tags (GDataPicasaWebAlbum *self) G_GNUC_PURE; +void gdata_picasaweb_album_set_tags (GDataPicasaWebAlbum *self, const gchar * const *tags); +GList *gdata_picasaweb_album_get_contents (GDataPicasaWebAlbum *self) G_GNUC_PURE; +GList *gdata_picasaweb_album_get_thumbnails (GDataPicasaWebAlbum *self) G_GNUC_PURE; +void gdata_picasaweb_album_get_coordinates (GDataPicasaWebAlbum *self, gdouble *latitude, gdouble *longitude); +void gdata_picasaweb_album_set_coordinates (GDataPicasaWebAlbum *self, gdouble latitude, gdouble longitude); + +G_END_DECLS + +#endif /* !GDATA_PICASAWEB_ALBUM_H */ diff --git a/gdata/services/picasaweb/gdata-picasaweb-comment.c b/gdata/services/picasaweb/gdata-picasaweb-comment.c new file mode 100644 index 0000000..bb8b8ee --- /dev/null +++ b/gdata/services/picasaweb/gdata-picasaweb-comment.c @@ -0,0 +1,114 @@ +/* -*- Mode: C; indent-tabs-mode: t; c-basic-offset: 8; tab-width: 8 -*- */ +/* + * GData Client + * Copyright (C) Philip Withnall 2011 + * + * GData Client is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * GData Client is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with GData Client. If not, see . + */ + +/** + * SECTION:gdata-picasaweb-comment + * @short_description: GData PicasaWeb comment object + * @stability: Stable + * @include: gdata/services/picasaweb/gdata-picasaweb-comment.h + * + * #GDataPicasaWebComment is a subclass of #GDataComment to represent a comment on a #GDataPicasaWebFile. It is returned by the #GDataCommentable + * interface implementation on #GDataPicasaWebFile. + * + * It's possible to query for, add and delete #GDataPicasaWebComments from #GDataPicasaWebFiles. + * + * Since: 0.10.0 + */ + +#include +#include + +#include "gdata-picasaweb-comment.h" + +static void gdata_picasaweb_comment_get_property (GObject *object, guint property_id, GValue *value, GParamSpec *pspec); +static void gdata_picasaweb_comment_set_property (GObject *object, guint property_id, const GValue *value, GParamSpec *pspec); + +enum { + PROP_ETAG = 1, +}; + +G_DEFINE_TYPE (GDataPicasaWebComment, gdata_picasaweb_comment, GDATA_TYPE_COMMENT) + +static void +gdata_picasaweb_comment_class_init (GDataPicasaWebCommentClass *klass) +{ + GObjectClass *gobject_class = G_OBJECT_CLASS (klass); + GDataEntryClass *entry_class = GDATA_ENTRY_CLASS (klass); + + gobject_class->get_property = gdata_picasaweb_comment_get_property; + gobject_class->set_property = gdata_picasaweb_comment_set_property; + + entry_class->kind_term = "http://schemas.google.com/photos/2007#comment"; + + /* Override the ETag property since ETags don't seem to be supported for PicasaWeb comments. */ + g_object_class_override_property (gobject_class, PROP_ETAG, "etag"); +} + +static void +gdata_picasaweb_comment_init (GDataPicasaWebComment *self) +{ + /* Nothing to see here. */ +} + +static void +gdata_picasaweb_comment_get_property (GObject *object, guint property_id, GValue *value, GParamSpec *pspec) +{ + switch (property_id) { + case PROP_ETAG: + /* Never return an ETag */ + g_value_set_string (value, NULL); + break; + default: + /* We don't have any other property... */ + G_OBJECT_WARN_INVALID_PROPERTY_ID (object, property_id, pspec); + break; + } +} + +static void +gdata_picasaweb_comment_set_property (GObject *object, guint property_id, const GValue *value, GParamSpec *pspec) +{ + switch (property_id) { + case PROP_ETAG: + /* Never set an ETag (note that this doesn't stop it being set in GDataEntry due to XML parsing) */ + break; + default: + /* We don't have any other property... */ + G_OBJECT_WARN_INVALID_PROPERTY_ID (object, property_id, pspec); + break; + } +} + +/** + * gdata_picasaweb_comment_new: + * @id: the comment's ID, or %NULL + * + * Creates a new #GDataPicasaWebComment with the given ID and default properties. + * + * Return value: a new #GDataPicasaWebComment; unref with g_object_unref() + * + * Since: 0.10.0 + */ +GDataPicasaWebComment * +gdata_picasaweb_comment_new (const gchar *id) +{ + return GDATA_PICASAWEB_COMMENT (g_object_new (GDATA_TYPE_PICASAWEB_COMMENT, + "id", id, + NULL)); +} diff --git a/gdata/services/picasaweb/gdata-picasaweb-comment.h b/gdata/services/picasaweb/gdata-picasaweb-comment.h new file mode 100644 index 0000000..af48a3c --- /dev/null +++ b/gdata/services/picasaweb/gdata-picasaweb-comment.h @@ -0,0 +1,75 @@ +/* -*- Mode: C; indent-tabs-mode: t; c-basic-offset: 8; tab-width: 8 -*- */ +/* + * GData Client + * Copyright (C) Philip Withnall 2011 + * + * GData Client is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * GData Client is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with GData Client. If not, see . + */ + +#ifndef GDATA_PICASAWEB_COMMENT_H +#define GDATA_PICASAWEB_COMMENT_H + +#include +#include + +#include + +G_BEGIN_DECLS + +#define GDATA_TYPE_PICASAWEB_COMMENT (gdata_picasaweb_comment_get_type ()) +#define GDATA_PICASAWEB_COMMENT(o) (G_TYPE_CHECK_INSTANCE_CAST ((o), GDATA_TYPE_PICASAWEB_COMMENT, GDataPicasaWebComment)) +#define GDATA_PICASAWEB_COMMENT_CLASS(k) (G_TYPE_CHECK_CLASS_CAST((k), GDATA_TYPE_PICASAWEB_COMMENT, GDataPicasaWebCommentClass)) +#define GDATA_IS_PICASAWEB_COMMENT(o) (G_TYPE_CHECK_INSTANCE_TYPE ((o), GDATA_TYPE_PICASAWEB_COMMENT)) +#define GDATA_IS_PICASAWEB_COMMENT_CLASS(k) (G_TYPE_CHECK_CLASS_TYPE ((k), GDATA_TYPE_PICASAWEB_COMMENT)) +#define GDATA_PICASAWEB_COMMENT_GET_CLASS(o) (G_TYPE_INSTANCE_GET_CLASS ((o), GDATA_TYPE_PICASAWEB_COMMENT, GDataPicasaWebCommentClass)) + +typedef struct _GDataPicasaWebCommentPrivate GDataPicasaWebCommentPrivate; + +/** + * GDataPicasaWebComment: + * + * All the fields in the #GDataPicasaWebComment structure are private and should never be accessed directly. + * + * Since: 0.10.0 + */ +typedef struct { + GDataComment parent; + GDataPicasaWebCommentPrivate *priv; +} GDataPicasaWebComment; + +/** + * GDataPicasaWebCommentClass: + * + * All the fields in the #GDataPicasaWebCommentClass structure are private and should never be accessed directly. + * + * Since: 0.10.0 + */ +typedef struct { + /*< private >*/ + GDataCommentClass parent; + + /*< private >*/ + /* Padding for future expansion */ + void (*_g_reserved0) (void); + void (*_g_reserved1) (void); +} GDataPicasaWebCommentClass; + +GType gdata_picasaweb_comment_get_type (void) G_GNUC_CONST; +G_DEFINE_AUTOPTR_CLEANUP_FUNC (GDataPicasaWebComment, g_object_unref) + +GDataPicasaWebComment *gdata_picasaweb_comment_new (const gchar *id) G_GNUC_WARN_UNUSED_RESULT G_GNUC_MALLOC; + +G_END_DECLS + +#endif /* !GDATA_PICASAWEB_COMMENT_H */ diff --git a/gdata/services/picasaweb/gdata-picasaweb-feed.c b/gdata/services/picasaweb/gdata-picasaweb-feed.c new file mode 100644 index 0000000..d3c1d01 --- /dev/null +++ b/gdata/services/picasaweb/gdata-picasaweb-feed.c @@ -0,0 +1,91 @@ +/* -*- Mode: C; indent-tabs-mode: t; c-basic-offset: 8; tab-width: 8 -*- */ +/* + * GData Client + * Copyright (C) Philip Withnall 2009 + * Copyright (C) Richard Schwarting 2009–2010 + * + * GData Client is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * GData Client is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with GData Client. If not, see . + */ + +/** + * SECTION:gdata-picasaweb-feed + * @short_description: GData PicasaWeb Feed object + * @stability: Stable + * @include: gdata/services/picasaweb/gdata-picasaweb-feed.h + * + * #GDataPicasaWebFeed is a subclass of #GDataFeed to represent properties for a PicasaWeb feed. It adds a couple of + * properties which are specific to the Google PicasaWeb API. + * + * Since: 0.6.0 + */ + +#include +#include + +#include "gdata-picasaweb-feed.h" +#include "gdata-feed.h" +#include "gdata-private.h" + +static gboolean parse_xml (GDataParsable *parsable, xmlDoc *doc, xmlNode *node, gpointer user_data, GError **error); + +G_DEFINE_TYPE (GDataPicasaWebFeed, gdata_picasaweb_feed, GDATA_TYPE_FEED) + +static void +gdata_picasaweb_feed_class_init (GDataPicasaWebFeedClass *klass) +{ + GDataParsableClass *parsable_class = GDATA_PARSABLE_CLASS (klass); + parsable_class->parse_xml = parse_xml; +} + +static void +gdata_picasaweb_feed_init (GDataPicasaWebFeed *self) +{ + /* Nothing to see here */ +} + +static gboolean +parse_xml (GDataParsable *parsable, xmlDoc *doc, xmlNode *node, gpointer user_data, GError **error) +{ + if (gdata_parser_is_namespace (node, "http://schemas.google.com/photos/2007") == TRUE) { + if (xmlStrcmp (node->name, (xmlChar*) "user") == 0 || + xmlStrcmp (node->name, (xmlChar*) "nickname") == 0 || + xmlStrcmp (node->name, (xmlChar*) "quotacurrent") == 0 || + xmlStrcmp (node->name, (xmlChar*) "quotalimit") == 0 || + xmlStrcmp (node->name, (xmlChar*) "maxPhotosPerAlbum") == 0 || + xmlStrcmp (node->name, (xmlChar*) "thumbnail") == 0 || + xmlStrcmp (node->name, (xmlChar*) "allowDownloads") == 0 || + xmlStrcmp (node->name, (xmlChar*) "allowPrints") == 0 || + xmlStrcmp (node->name, (xmlChar*) "id") == 0 || + xmlStrcmp (node->name, (xmlChar*) "rights") == 0 || + xmlStrcmp (node->name, (xmlChar*) "location") == 0 || + xmlStrcmp (node->name, (xmlChar*) "access") == 0 || + xmlStrcmp (node->name, (xmlChar*) "timestamp") == 0 || + xmlStrcmp (node->name, (xmlChar*) "numphotos") == 0 || + xmlStrcmp (node->name, (xmlChar*) "numphotosremaining") == 0 || + xmlStrcmp (node->name, (xmlChar*) "bytesUsed") == 0) { + /* From user's feed of album entries. Redundant with user entry represented by #GDataPicasaWebUser. + * Capturing and ignoring. See bgo #589858. */ + } else { + return GDATA_PARSABLE_CLASS (gdata_picasaweb_feed_parent_class)->parse_xml (parsable, doc, node, user_data, error); + } + } else if (gdata_parser_is_namespace (node, "http://www.georss.org/georss") == TRUE && xmlStrcmp (node->name, (xmlChar*) "where") == 0) { + /* From user's feed of album entries. Redundant with user entry represented by #GDataPicasaWebUser. + * Capturing and ignoring. See bgo #589858. */ + } else { + return GDATA_PARSABLE_CLASS (gdata_picasaweb_feed_parent_class)->parse_xml (parsable, doc, node, user_data, error); + } + + return TRUE; +} + diff --git a/gdata/services/picasaweb/gdata-picasaweb-feed.h b/gdata/services/picasaweb/gdata-picasaweb-feed.h new file mode 100644 index 0000000..14a8688 --- /dev/null +++ b/gdata/services/picasaweb/gdata-picasaweb-feed.h @@ -0,0 +1,73 @@ +/* -*- Mode: C; indent-tabs-mode: t; c-basic-offset: 8; tab-width: 8 -*- */ +/* + * GData Client + * Copyright (C) Philip Withnall 2009 + * Copyright (C) Richard Schwarting 2009 + * + * GData Client is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * GData Client is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with GData Client. If not, see . + */ + +#ifndef GDATA_PICASAWEB_FEED_H +#define GDATA_PICASAWEB_FEED_H + +#include +#include + +#include + +G_BEGIN_DECLS + +#define GDATA_TYPE_PICASAWEB_FEED (gdata_picasaweb_feed_get_type ()) +#define GDATA_PICASAWEB_FEED(o) (G_TYPE_CHECK_INSTANCE_CAST ((o), GDATA_TYPE_PICASAWEB_FEED, GDataPicasaWebFeed)) +#define GDATA_PICASAWEB_FEED_CLASS(k) (G_TYPE_CHECK_CLASS_CAST((k), GDATA_TYPE_PICASAWEB_FEED, GDataPicasaWebFeedClass)) +#define GDATA_IS_PICASAWEB_FEED(o) (G_TYPE_CHECK_INSTANCE_TYPE ((o), GDATA_TYPE_PICASAWEB_FEED)) +#define GDATA_IS_PICASAWEB_FEED_CLASS(k) (G_TYPE_CHECK_CLASS_TYPE ((k), GDATA_TYPE_PICASAWEB_FEED)) +#define GDATA_PICASAWEB_FEED_GET_CLASS(o) (G_TYPE_INSTANCE_GET_CLASS ((o), GDATA_TYPE_PICASAWEB_FEED, GDataPicasaWebFeedClass)) + +/** + * GDataPicasaWebFeed: + * + * All the fields in the #GDataPicasaWebFeed structure are private and should never be accessed directly. + * + * Since: 0.6.0 + */ +typedef struct { + GDataFeed parent; + /*< private >*/ + gpointer padding1; /* reserved for private struct */ +} GDataPicasaWebFeed; + +/** + * GDataPicasaWebFeedClass: + * + * All the fields in the #GDataPicasaWebFeedClass structure are private and should never be accessed directly. + * + * Since: 0.6.0 + */ +typedef struct { + /*< private >*/ + GDataFeedClass parent; + + /*< private >*/ + /* Padding for future expansion */ + void (*_g_reserved0) (void); + void (*_g_reserved1) (void); +} GDataPicasaWebFeedClass; + +GType gdata_picasaweb_feed_get_type (void) G_GNUC_CONST; +G_DEFINE_AUTOPTR_CLEANUP_FUNC (GDataPicasaWebFeed, g_object_unref) + +G_END_DECLS + +#endif /* !GDATA_PICASAWEB_FEED_H */ diff --git a/gdata/services/picasaweb/gdata-picasaweb-file.c b/gdata/services/picasaweb/gdata-picasaweb-file.c new file mode 100644 index 0000000..d669d08 --- /dev/null +++ b/gdata/services/picasaweb/gdata-picasaweb-file.c @@ -0,0 +1,1801 @@ +/* -*- Mode: C; indent-tabs-mode: t; c-basic-offset: 8; tab-width: 8 -*- */ +/* + * GData Client + * Copyright (C) Richard Schwarting 2009 + * Copyright (C) Philip Withnall 2009–2010 + * + * GData Client is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * GData Client is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with GData Client. If not, see . + */ + +/** + * SECTION:gdata-picasaweb-file + * @short_description: GData PicasaWeb file object + * @stability: Stable + * @include: gdata/services/picasaweb/gdata-picasaweb-file.h + * + * #GDataPicasaWebFile is a subclass of #GDataEntry to represent a file (photo or video) in an album on Google PicasaWeb. + * + * #GDataPicasaWebFile implements #GDataCommentable, allowing comments on files to be queried using gdata_commentable_query_comments(), new + * comments to be added to files using gdata_commentable_insert_comment() and existing comments to be deleted from files using + * gdata_commentable_delete_comment(). + * + * For more details of Google PicasaWeb's GData API, see the + * online documentation. + * + * + * Getting Basic Photo Data + * + * GDataFeed *photo_feed; + * GList *photo_entries; + * + * /* Query for a feed of GDataPicasaWebFiles belonging to the given GDataPicasaWebAlbum album */ + * photo_feed = gdata_picasaweb_service_query_files (service, album, NULL, NULL, NULL, NULL, NULL); + * + * /* Get a list of GDataPicasaWebFiles from the query's feed */ + * for (photo_entries = gdata_feed_get_entries (photo_feed); photo_entries != NULL; photo_entries = photo_entries->next) { + * GDataPicasaWebFile *photo; + * guint height, width; + * gsize file_size; + * gint64 timestamp; + * const gchar *title, *summary; + * GList *contents; + * + * photo = GDATA_PICASAWEB_FILE (photo_entries->data); + * + * /* Get various bits of information about the photo */ + * height = gdata_picasaweb_file_get_height (photo); + * width = gdata_picasaweb_file_get_width (photo); + * file_size = gdata_picasaweb_file_get_size (photo); + * timestamp = gdata_picasaweb_file_get_timestamp (photo); + * title = gdata_entry_get_title (GDATA_ENTRY (photo)); + * summary = gdata_entry_get_summary (GDATA_ENTRY (photo)); + * + * /* Obtain the image data at various sizes */ + * for (contents = gdata_picasaweb_file_get_contents (photo); contents != NULL; contents = contents->next) { + * GDataMediaContent *content; + * GDataDownloadStream *download_stream; + * GFileOutputStream *file_stream; + * GFile *new_file; + * + * content = GDATA_MEDIA_CONTENT (contents->data); + * /* Do something fun with the actual images, like download them to a file. + * * Note that this is a blocking operation. */ + * download_stream = gdata_media_content_download (content, GDATA_SERVICE (service), NULL, NULL); + * new_file = g_file_new_for_path (file_path); + * file_stream = g_file_create (new_file, G_FILE_CREATE_NONE, NULL, NULL); + * g_output_stream_splice (G_OUTPUT_STREAM (file_stream), G_INPUT_STREAM (download_stream), + * G_OUTPUT_STREAM_SPLICE_CLOSE_SOURCE | G_OUTPUT_STREAM_SPLICE_CLOSE_TARGET, NULL, NULL); + * g_object_unref (file_stream); + * g_object_unref (download_stream); + * /* ... */ + * g_object_unref (new_file); + * } + * + * /* Do something worthwhile with your image data */ + * } + * + * g_object_unref (photo_feed); + * + * + * + * Since: 0.4.0 + */ + +#include +#include +#include +#include +#include + +#include "gdata-picasaweb-file.h" +#include "gdata-private.h" +#include "gdata-service.h" +#include "gdata-parser.h" +#include "gdata-types.h" +#include "media/gdata-media-group.h" +#include "exif/gdata-exif-tags.h" +#include "georss/gdata-georss-where.h" +#include "gd/gdata-gd-feed-link.h" +#include "gdata-commentable.h" +#include "gdata-picasaweb-comment.h" +#include "gdata-picasaweb-service.h" + +static GObject *gdata_picasaweb_file_constructor (GType type, guint n_construct_params, GObjectConstructParam *construct_params); +static void gdata_picasaweb_file_dispose (GObject *object); +static void gdata_picasaweb_file_finalize (GObject *object); +static void gdata_picasaweb_file_get_property (GObject *object, guint property_id, GValue *value, GParamSpec *pspec); +static void gdata_picasaweb_file_set_property (GObject *object, guint property_id, const GValue *value, GParamSpec *pspec); +static void get_xml (GDataParsable *parsable, GString *xml_string); +static gboolean parse_xml (GDataParsable *parsable, xmlDoc *doc, xmlNode *node, gpointer user_data, GError **error); +static void get_namespaces (GDataParsable *parsable, GHashTable *namespaces); +static gchar *get_entry_uri (const gchar *id) G_GNUC_WARN_UNUSED_RESULT; +GDataAuthorizationDomain *get_authorization_domain (GDataCommentable *self) G_GNUC_CONST; +static gchar *get_query_comments_uri (GDataCommentable *self) G_GNUC_MALLOC G_GNUC_WARN_UNUSED_RESULT; +static gchar *get_insert_comment_uri (GDataCommentable *self, GDataComment *comment_) G_GNUC_MALLOC G_GNUC_WARN_UNUSED_RESULT; +static gboolean is_comment_deletable (GDataCommentable *self, GDataComment *comment_); +static void gdata_picasaweb_file_commentable_init (GDataCommentableInterface *iface); + +struct _GDataPicasaWebFilePrivate { + gchar *file_id; + gint64 edited; + gchar *version; + gchar *album_id; + guint width; + guint height; + gsize size; + gchar *checksum; + gint64 timestamp; /* in milliseconds! */ + gboolean is_commenting_enabled; + guint comment_count; + guint rotation; + gchar *video_status; + + /* media:group */ + GDataMediaGroup *media_group; + /* exif:tags */ + GDataExifTags *exif_tags; + /* georss:where */ + GDataGeoRSSWhere *georss_where; +}; + +enum { + PROP_EDITED = 1, + PROP_VERSION, + PROP_ALBUM_ID, + PROP_WIDTH, + PROP_HEIGHT, + PROP_SIZE, + PROP_CHECKSUM, + PROP_TIMESTAMP, + PROP_IS_COMMENTING_ENABLED, + PROP_COMMENT_COUNT, + PROP_ROTATION, + PROP_VIDEO_STATUS, + PROP_CREDIT, + PROP_CAPTION, + PROP_TAGS, + PROP_DISTANCE, + PROP_EXPOSURE, + PROP_FLASH, + PROP_FOCAL_LENGTH, + PROP_FSTOP, + PROP_IMAGE_UNIQUE_ID, + PROP_ISO, + PROP_MAKE, + PROP_MODEL, + PROP_LATITUDE, + PROP_LONGITUDE, + PROP_FILE_ID +}; + +G_DEFINE_TYPE_WITH_CODE (GDataPicasaWebFile, gdata_picasaweb_file, GDATA_TYPE_ENTRY, + G_IMPLEMENT_INTERFACE (GDATA_TYPE_COMMENTABLE, gdata_picasaweb_file_commentable_init)) + +static void +gdata_picasaweb_file_class_init (GDataPicasaWebFileClass *klass) +{ + GObjectClass *gobject_class = G_OBJECT_CLASS (klass); + GDataParsableClass *parsable_class = GDATA_PARSABLE_CLASS (klass); + GDataEntryClass *entry_class = GDATA_ENTRY_CLASS (klass); + + g_type_class_add_private (klass, sizeof (GDataPicasaWebFilePrivate)); + + gobject_class->constructor = gdata_picasaweb_file_constructor; + gobject_class->get_property = gdata_picasaweb_file_get_property; + gobject_class->set_property = gdata_picasaweb_file_set_property; + gobject_class->dispose = gdata_picasaweb_file_dispose; + gobject_class->finalize = gdata_picasaweb_file_finalize; + + parsable_class->get_xml = get_xml; + parsable_class->parse_xml = parse_xml; + parsable_class->get_namespaces = get_namespaces; + + entry_class->get_entry_uri = get_entry_uri; + entry_class->kind_term = "http://schemas.google.com/photos/2007#photo"; + + /** + * GDataPicasaWebFile:file-id: + * + * The ID of the file. This is a substring of the ID returned by gdata_entry_get_id() for #GDataPicasaWebFiles; for example, + * if gdata_entry_get_id() returned + * "http://picasaweb.google.com/data/entry/user/libgdata.picasaweb/albumid/5328889949261497249/photoid/5328890138794566386" for a + * particular #GDataPicasaWebFile, the #GDataPicasaWebFile:file-id property would be "5328890138794566386". + * + * For more information, see the + * gphoto specification. + * + * Since: 0.7.0 + */ + g_object_class_install_property (gobject_class, PROP_FILE_ID, + g_param_spec_string ("file-id", + "File ID", "The ID of the file.", + NULL, + G_PARAM_READWRITE | G_PARAM_CONSTRUCT_ONLY | G_PARAM_STATIC_STRINGS)); + + /** + * GDataPicasaWebFile:version: + * + * The version number of the file. Version numbers are based on modification time, so they don't increment linearly. + * + * For more information, see the + * gphoto specification. + * + * Since: 0.4.0 + */ + g_object_class_install_property (gobject_class, PROP_VERSION, + g_param_spec_string ("version", + "Version", "The version number of the file.", + NULL, + G_PARAM_READWRITE | G_PARAM_CONSTRUCT_ONLY | G_PARAM_STATIC_STRINGS)); + + /** + * GDataPicasaWebFile:album-id: + * + * The ID for the file's album. This is in the same form as returned by gdata_picasaweb_album_get_id(). + * + * For more information, see the + * gphoto specification. + * + * Since: 0.4.0 + */ + g_object_class_install_property (gobject_class, PROP_ALBUM_ID, + g_param_spec_string ("album-id", + "Album ID", "The ID for the file's album.", + NULL, + G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)); + + /** + * GDataPicasaWebFile:checksum: + * + * A checksum of the file, useful for duplicate detection. + * + * For more information, see the + * gphoto specification. + * + * Since: 0.4.0 + */ + g_object_class_install_property (gobject_class, PROP_CHECKSUM, + g_param_spec_string ("checksum", + "Checksum", "A checksum of the file, useful for duplicate detection.", + NULL, + G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)); + + /** + * GDataPicasaWebFile:video-status: + * + * The status of the file, if it is a video. For example: %GDATA_PICASAWEB_VIDEO_STATUS_PENDING or %GDATA_PICASAWEB_VIDEO_STATUS_FAILED. + * + * For more information, see the + * gphoto specification. + * + * Since: 0.4.0 + */ + g_object_class_install_property (gobject_class, PROP_VIDEO_STATUS, + g_param_spec_string ("video-status", + "Video Status", "The status of the file, if it is a video.", + NULL, + G_PARAM_READABLE | G_PARAM_STATIC_STRINGS)); + + /** + * GDataPicasaWebFile:width: + * + * The width of the photo or video, in pixels. + * + * For more information, see the + * gphoto specification. + * + * Since: 0.4.0 + */ + g_object_class_install_property (gobject_class, PROP_WIDTH, + g_param_spec_uint ("width", + "Width", "The width of the photo or video, in pixels.", + 0, G_MAXUINT, 0, + G_PARAM_READABLE | G_PARAM_STATIC_STRINGS)); + + /** + * GDataPicasaWebFile:height: + * + * The height of the photo or video, in pixels. + * + * For more information, see the + * gphoto specification. + * + * Since: 0.4.0 + */ + g_object_class_install_property (gobject_class, PROP_HEIGHT, + g_param_spec_uint ("height", + "Height", "The height of the photo or video, in pixels.", + 0, G_MAXUINT, 0, + G_PARAM_READABLE | G_PARAM_STATIC_STRINGS)); + + /** + * GDataPicasaWebFile:size: + * + * The size of the file, in bytes. + * + * For more information, see the + * gphoto specification. + * + * Since: 0.4.0 + */ + g_object_class_install_property (gobject_class, PROP_SIZE, + g_param_spec_ulong ("size", + "Size", "The size of the file, in bytes.", + 0, G_MAXULONG, 0, + G_PARAM_READABLE | G_PARAM_STATIC_STRINGS)); + + /** + * GDataPicasaWebFile:edited: + * + * The time this file was last edited. If the file has not been edited yet, the content indicates the time it was created. + * + * For more information, see the + * Atom Publishing Protocol specification. + * + * Since: 0.4.0 + */ + g_object_class_install_property (gobject_class, PROP_EDITED, + g_param_spec_int64 ("edited", + "Edited", "The time this file was last edited.", + -1, G_MAXINT64, -1, + G_PARAM_READABLE | G_PARAM_STATIC_STRINGS)); + + /** + * GDataPicasaWebFile:timestamp: + * + * The time the file was purportedly taken. This a UNIX timestamp in milliseconds (not seconds) since the epoch. + * + * For more information, see the + * gphoto specification. + * + * Since: 0.4.0 + */ + g_object_class_install_property (gobject_class, PROP_TIMESTAMP, + g_param_spec_int64 ("timestamp", + "Timestamp", "The time the file was purportedly taken.", + -1, G_MAXINT64, -1, + G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)); + + /** + * GDataPicasaWebFile:comment-count: + * + * The number of comments on the file. + * + * For more information, see the + * gphoto specification. + * + * Since: 0.4.0 + */ + g_object_class_install_property (gobject_class, PROP_COMMENT_COUNT, + g_param_spec_uint ("comment-count", + "Comment Count", "The number of comments on the file.", + 0, G_MAXUINT, 0, + G_PARAM_READABLE | G_PARAM_STATIC_STRINGS)); + + /** + * GDataPicasaWebFile:rotation: + * + * The rotation of the photo, in degrees. This will only be non-zero for files which are pending rotation, and haven't yet been + * permanently modified. For files which have already been rotated, this will be 0. + * + * For more information, see the + * gphoto specification. + * + * Since: 0.4.0 + */ + g_object_class_install_property (gobject_class, PROP_ROTATION, + g_param_spec_uint ("rotation", + "Rotation", "The rotation of the photo, in degrees.", + 0, 359, 0, + G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)); + + /** + * GDataPicasaWebFile:is-commenting-enabled: + * + * Whether commenting is enabled for this file. + * + * Since: 0.4.0 + */ + g_object_class_install_property (gobject_class, PROP_IS_COMMENTING_ENABLED, + g_param_spec_boolean ("is-commenting-enabled", + "Commenting enabled?", "Indicates whether comments are enabled.", + TRUE, + G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)); + + /** + * GDataPicasaWebFile:credit: + * + * The nickname of the user credited with this file. + * + * For more information, see the Media RSS + * specification. + * + * Since: 0.4.0 + */ + g_object_class_install_property (gobject_class, PROP_CREDIT, + g_param_spec_string ("credit", + "Credit", "The nickname of the user credited with this file.", + NULL, + G_PARAM_READABLE | G_PARAM_STATIC_STRINGS)); + + /** + * GDataPicasaWebFile:caption: + * + * The file's descriptive caption. + * + * Since: 0.4.0 + */ + g_object_class_install_property (gobject_class, PROP_CAPTION, + g_param_spec_string ("caption", + "Caption", "The file's descriptive caption.", + NULL, + G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)); + + /** + * GDataPicasaWebFile:tags: + * + * A %NULL-terminated array of tags associated with the file. + * + * For more information, see the + * Media RSS specification. + * + * Since: 0.4.0 + */ + g_object_class_install_property (gobject_class, PROP_TAGS, + g_param_spec_boxed ("tags", + "Tags", "A NULL-terminated array of tags associated with the file.", + G_TYPE_STRV, + G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)); + + /** + * GDataPicasaWebFile:distance: + * + * The distance to the subject reported in the image's EXIF. + * + * For more information, see the + * EXIF element reference. + * + * Since: 0.5.0 + */ + g_object_class_install_property (gobject_class, PROP_DISTANCE, + g_param_spec_double ("distance", + "Distance", "The distance to the subject.", + -1.0, G_MAXDOUBLE, -1.0, + G_PARAM_READABLE | G_PARAM_STATIC_STRINGS)); + + /** + * GDataPicasaWebFile:exposure: + * + * The exposure time. + * + * For more information, see the + * EXIF element reference. + * + * Since: 0.5.0 + */ + g_object_class_install_property (gobject_class, PROP_EXPOSURE, + g_param_spec_double ("exposure", + "Exposure", "The exposure time.", + 0.0, G_MAXDOUBLE, 0.0, + G_PARAM_READABLE | G_PARAM_STATIC_STRINGS)); + + /** + * GDataPicasaWebFile:flash: + * + * Indicates whether the flash was used. + * + * For more information, see the + * EXIF element reference. + * + * Since: 0.5.0 + */ + g_object_class_install_property (gobject_class, PROP_FLASH, + g_param_spec_boolean ("flash", + "Flash", "Indicates whether the flash was used.", + FALSE, + G_PARAM_READABLE | G_PARAM_STATIC_STRINGS)); + + /** + * GDataPicasaWebFile:focal-length: + * + * The focal length for the shot. + * + * For more information, see the + * EXIF element reference. + * + * Since: 0.5.0 + */ + g_object_class_install_property (gobject_class, PROP_FOCAL_LENGTH, + g_param_spec_double ("focal-length", + "Focal Length", "The focal length used in the shot.", + -1.0, G_MAXDOUBLE, -1.0, + G_PARAM_READABLE | G_PARAM_STATIC_STRINGS)); + + /* TODO: Rename to f-stop */ + /** + * GDataPicasaWebFile:fstop: + * + * The F-stop value. + * + * For more information, see the + * EXIF element reference. + * + * Since: 0.5.0 + */ + g_object_class_install_property (gobject_class, PROP_FSTOP, + g_param_spec_double ("fstop", + "F-stop", "The F-stop used.", + 0.0, G_MAXDOUBLE, 0.0, + G_PARAM_READABLE | G_PARAM_STATIC_STRINGS)); + + /** + * GDataPicasaWebFile:image-unique-id: + * + * An unique ID for the image found in the EXIF. + * + * For more information, see the + * EXIF element reference. + * + * Since: 0.5.0 + */ + g_object_class_install_property (gobject_class, PROP_IMAGE_UNIQUE_ID, + g_param_spec_string ("image-unique-id", + "Image Unique ID", "An unique ID for the image.", + NULL, + G_PARAM_READABLE | G_PARAM_STATIC_STRINGS)); + + /** + * GDataPicasaWebFile:iso: + * + * The ISO speed. + * + * For more information, see the + * EXIF element reference and ISO 5800:1987. + * + * Since: 0.5.0 + */ + g_object_class_install_property (gobject_class, PROP_ISO, + g_param_spec_long ("iso", + "ISO", "The ISO speed.", + -1, G_MAXLONG, -1, + G_PARAM_READABLE | G_PARAM_STATIC_STRINGS)); + + /** + * GDataPicasaWebFile:make: + * + * The name of the manufacturer of the camera. + * + * For more information, see the + * EXIF element reference. + * + * Since: 0.5.0 + */ + g_object_class_install_property (gobject_class, PROP_MAKE, + g_param_spec_string ("make", + "Make", "The name of the manufacturer.", + NULL, + G_PARAM_READABLE | G_PARAM_STATIC_STRINGS)); + + /** + * GDataPicasaWebFile:model: + * + * The model of the camera. + * + * For more information, see the + * EXIF element reference. + * + * Since: 0.5.0 + */ + g_object_class_install_property (gobject_class, PROP_MODEL, + g_param_spec_string ("model", + "Model", "The model of the camera.", + NULL, + G_PARAM_READABLE | G_PARAM_STATIC_STRINGS)); + + /** + * GDataPicasaWebFile:latitude: + * + * The location as a latitude coordinate associated with this file. Valid latitudes range from -90.0 + * to 90.0 inclusive. + * + * For more information, see the + * GeoRSS specification. + * + * Since: 0.5.0 + */ + g_object_class_install_property (gobject_class, PROP_LATITUDE, + g_param_spec_double ("latitude", + "Latitude", "The location as a latitude coordinate associated with this file.", + -90.0, 90.0, 0.0, + G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)); + + /** + * GDataPicasaWebFile:longitude: + * + * The location as a longitude coordinate associated with this file. Valid longitudes range from -180.0 + * to 180.0 inclusive. + * + * For more information, see the + * GeoRSS specification. + * + * Since: 0.5.0 + */ + g_object_class_install_property (gobject_class, PROP_LONGITUDE, + g_param_spec_double ("longitude", + "Longitude", "The location as a longitude coordinate associated with this file.", + -180.0, 180.0, 0.0, + G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)); +} + +static void +gdata_picasaweb_file_commentable_init (GDataCommentableInterface *iface) +{ + iface->comment_type = GDATA_TYPE_PICASAWEB_COMMENT; + iface->get_authorization_domain = get_authorization_domain; + iface->get_query_comments_uri = get_query_comments_uri; + iface->get_insert_comment_uri = get_insert_comment_uri; + iface->is_comment_deletable = is_comment_deletable; +} + +static void +notify_title_cb (GDataPicasaWebFile *self, GParamSpec *pspec, gpointer user_data) +{ + /* Keep the atom:title and media:group/media:title in sync */ + if (self->priv->media_group != NULL) + gdata_media_group_set_title (self->priv->media_group, gdata_entry_get_title (GDATA_ENTRY (self))); +} + +static void +notify_summary_cb (GDataPicasaWebFile *self, GParamSpec *pspec, gpointer user_data) +{ + /* Keep the atom:summary and media:group/media:description in sync */ + if (self->priv->media_group != NULL) + gdata_media_group_set_description (self->priv->media_group, gdata_entry_get_summary (GDATA_ENTRY (self))); +} + +static void +gdata_picasaweb_file_init (GDataPicasaWebFile *self) +{ + self->priv = G_TYPE_INSTANCE_GET_PRIVATE (self, GDATA_TYPE_PICASAWEB_FILE, GDataPicasaWebFilePrivate); + self->priv->media_group = g_object_new (GDATA_TYPE_MEDIA_GROUP, NULL); + self->priv->exif_tags = g_object_new (GDATA_TYPE_EXIF_TAGS, NULL); + self->priv->georss_where = g_object_new (GDATA_TYPE_GEORSS_WHERE, NULL); + self->priv->is_commenting_enabled = TRUE; + self->priv->edited = -1; + self->priv->timestamp = -1; + + /* We need to keep atom:title (the canonical title for the file) in sync with media:group/media:title */ + g_signal_connect (self, "notify::title", G_CALLBACK (notify_title_cb), NULL); + /* atom:summary (the canonical summary/caption for the file) in sync with media:group/media:description */ + g_signal_connect (self, "notify::summary", G_CALLBACK (notify_summary_cb), NULL); +} + +static GObject * +gdata_picasaweb_file_constructor (GType type, guint n_construct_params, GObjectConstructParam *construct_params) +{ + GObject *object; + + /* Chain up to the parent class */ + object = G_OBJECT_CLASS (gdata_picasaweb_file_parent_class)->constructor (type, n_construct_params, construct_params); + + if (_gdata_parsable_is_constructed_from_xml (GDATA_PARSABLE (object)) == FALSE) { + GDataPicasaWebFilePrivate *priv = GDATA_PICASAWEB_FILE (object)->priv; + GTimeVal time_val; + + /* Set the edited and timestamp properties to the current time (creation time). bgo#599140 + * We don't do this in *_init() since that would cause setting it from parse_xml() to fail (duplicate element). */ + g_get_current_time (&time_val); + priv->timestamp = (gint64) time_val.tv_sec * 1000; + priv->edited = time_val.tv_sec; + } + + return object; +} + +static void +gdata_picasaweb_file_dispose (GObject *object) +{ + GDataPicasaWebFilePrivate *priv = GDATA_PICASAWEB_FILE (object)->priv; + + if (priv->media_group != NULL) + g_object_unref (priv->media_group); + priv->media_group = NULL; + + if (priv->exif_tags != NULL) + g_object_unref (priv->exif_tags); + priv->exif_tags = NULL; + + if (priv->georss_where != NULL) + g_object_unref (priv->georss_where); + priv->georss_where = NULL; + + /* Chain up to the parent class */ + G_OBJECT_CLASS (gdata_picasaweb_file_parent_class)->dispose (object); +} + +static void +gdata_picasaweb_file_finalize (GObject *object) +{ + GDataPicasaWebFilePrivate *priv = GDATA_PICASAWEB_FILE (object)->priv; + + g_free (priv->file_id); + g_free (priv->version); + g_free (priv->album_id); + g_free (priv->checksum); + g_free (priv->video_status); + + /* Chain up to the parent class */ + G_OBJECT_CLASS (gdata_picasaweb_file_parent_class)->finalize (object); +} + +static void +gdata_picasaweb_file_get_property (GObject *object, guint property_id, GValue *value, GParamSpec *pspec) +{ + GDataPicasaWebFilePrivate *priv = GDATA_PICASAWEB_FILE (object)->priv; + + switch (property_id) { + case PROP_FILE_ID: + g_value_set_string (value, priv->file_id); + break; + case PROP_EDITED: + g_value_set_int64 (value, priv->edited); + break; + case PROP_VERSION: + g_value_set_string (value, priv->version); + break; + case PROP_ALBUM_ID: + g_value_set_string (value, priv->album_id); + break; + case PROP_WIDTH: + g_value_set_uint (value, priv->width); + break; + case PROP_HEIGHT: + g_value_set_uint (value, priv->height); + break; + case PROP_SIZE: + g_value_set_ulong (value, priv->size); + break; + case PROP_CHECKSUM: + g_value_set_string (value, priv->checksum); + break; + case PROP_TIMESTAMP: + g_value_set_int64 (value, priv->timestamp); + break; + case PROP_IS_COMMENTING_ENABLED: + g_value_set_boolean (value, priv->is_commenting_enabled); + break; + case PROP_COMMENT_COUNT: + g_value_set_uint (value, priv->comment_count); + break; + case PROP_ROTATION: + g_value_set_uint (value, priv->rotation); + break; + case PROP_VIDEO_STATUS: + g_value_set_string (value, priv->video_status); + break; + case PROP_CREDIT: { + GDataMediaCredit *credit = gdata_media_group_get_credit (priv->media_group); + g_value_set_string (value, gdata_media_credit_get_credit (credit)); + break; } + case PROP_CAPTION: + g_value_set_string (value, gdata_entry_get_summary (GDATA_ENTRY (object))); + break; + case PROP_TAGS: + g_value_set_boxed (value, gdata_media_group_get_keywords (priv->media_group)); + break; + case PROP_DISTANCE: + g_value_set_double (value, gdata_exif_tags_get_distance (priv->exif_tags)); + break; + case PROP_EXPOSURE: + g_value_set_double (value, gdata_exif_tags_get_exposure (priv->exif_tags)); + break; + case PROP_FLASH: + g_value_set_boolean (value, gdata_exif_tags_get_flash (priv->exif_tags)); + break; + case PROP_FOCAL_LENGTH: + g_value_set_double (value, gdata_exif_tags_get_focal_length (priv->exif_tags)); + break; + case PROP_FSTOP: + g_value_set_double (value, gdata_exif_tags_get_fstop (priv->exif_tags)); + break; + case PROP_IMAGE_UNIQUE_ID: + g_value_set_string (value, gdata_exif_tags_get_image_unique_id (priv->exif_tags)); + break; + case PROP_ISO: + g_value_set_long (value, gdata_exif_tags_get_iso (priv->exif_tags)); + break; + case PROP_MAKE: + g_value_set_string (value, gdata_exif_tags_get_make (priv->exif_tags)); + break; + case PROP_MODEL: + g_value_set_string (value, gdata_exif_tags_get_model (priv->exif_tags)); + break; + case PROP_LATITUDE: + g_value_set_double (value, gdata_georss_where_get_latitude (priv->georss_where)); + break; + case PROP_LONGITUDE: + g_value_set_double (value, gdata_georss_where_get_longitude (priv->georss_where)); + break; + default: + /* We don't have any other property... */ + G_OBJECT_WARN_INVALID_PROPERTY_ID (object, property_id, pspec); + break; + } +} + +static void +gdata_picasaweb_file_set_property (GObject *object, guint property_id, const GValue *value, GParamSpec *pspec) +{ + GDataPicasaWebFile *self = GDATA_PICASAWEB_FILE (object); + + switch (property_id) { + case PROP_FILE_ID: + /* Construct only */ + g_free (self->priv->file_id); + self->priv->file_id = g_value_dup_string (value); + break; + case PROP_VERSION: + /* Construct only */ + g_free (self->priv->version); + self->priv->version = g_value_dup_string (value); + break; + case PROP_ALBUM_ID: + /* TODO: do we allow this to change albums? I think that's how pictures are moved. */ + gdata_picasaweb_file_set_album_id (self, g_value_get_string (value)); + break; + case PROP_CHECKSUM: + gdata_picasaweb_file_set_checksum (self, g_value_get_string (value)); + break; + case PROP_TIMESTAMP: + gdata_picasaweb_file_set_timestamp (self, g_value_get_int64 (value)); + break; + case PROP_IS_COMMENTING_ENABLED: /* TODO I don't think we can change this on a per file basis */ + gdata_picasaweb_file_set_is_commenting_enabled (self, g_value_get_boolean (value)); + break; + case PROP_ROTATION: + gdata_picasaweb_file_set_rotation (self, g_value_get_uint (value)); + break; + case PROP_CAPTION: + gdata_picasaweb_file_set_caption (self, g_value_get_string (value)); + break; + case PROP_TAGS: + gdata_picasaweb_file_set_tags (self, g_value_get_boxed (value)); + break; + case PROP_LATITUDE: + gdata_picasaweb_file_set_coordinates (self, g_value_get_double (value), + gdata_georss_where_get_longitude (self->priv->georss_where)); + break; + case PROP_LONGITUDE: + gdata_picasaweb_file_set_coordinates (self, gdata_georss_where_get_latitude (self->priv->georss_where), + g_value_get_double (value)); + break; + default: + /* We don't have any other property... */ + G_OBJECT_WARN_INVALID_PROPERTY_ID (object, property_id, pspec); + break; + } +} + +static gboolean +parse_xml (GDataParsable *parsable, xmlDoc *doc, xmlNode *node, gpointer user_data, GError **error) +{ + gboolean success; + GDataPicasaWebFile *self = GDATA_PICASAWEB_FILE (parsable); + + /* TODO: media:group should also be P_NO_DUPES, but we can't, as priv->media_group has to be pre-populated + * in order for things like gdata_picasaweb_file_set_description() to work. */ + if (gdata_parser_is_namespace (node, "http://www.w3.org/2007/app") == TRUE && + gdata_parser_int64_time_from_element (node, "edited", P_REQUIRED | P_NO_DUPES, &(self->priv->edited), &success, error) == TRUE) { + return success; + } else if (gdata_parser_is_namespace (node, "http://search.yahoo.com/mrss/") == TRUE && + gdata_parser_object_from_element (node, "group", P_REQUIRED, GDATA_TYPE_MEDIA_GROUP, + &(self->priv->media_group), &success, error) == TRUE) { + return success; + } else if (gdata_parser_is_namespace (node, "http://www.georss.org/georss") == TRUE && + gdata_parser_object_from_element (node, "where", P_REQUIRED, GDATA_TYPE_GEORSS_WHERE, + &(self->priv->georss_where), &success, error) == TRUE) { + return success; + } else if (gdata_parser_is_namespace (node, "http://schemas.google.com/photos/exif/2007") == TRUE && + gdata_parser_object_from_element (node, "tags", P_REQUIRED, GDATA_TYPE_EXIF_TAGS, + &(self->priv->exif_tags), &success, error) == TRUE) { + return success; + } else if (gdata_parser_is_namespace (node, "http://schemas.google.com/photos/2007") == TRUE) { + if (gdata_parser_string_from_element (node, "videostatus", P_NO_DUPES, &(self->priv->video_status), &success, error) == TRUE || + gdata_parser_string_from_element (node, "imageVersion", P_NONE, &(self->priv->version), &success, error) == TRUE || + gdata_parser_string_from_element (node, "albumid", P_NONE, &(self->priv->album_id), &success, error) == TRUE || + gdata_parser_string_from_element (node, "checksum", P_NONE, &(self->priv->checksum), &success, error) == TRUE || + gdata_parser_string_from_element (node, "id", P_REQUIRED | P_NON_EMPTY | P_NO_DUPES, + &(self->priv->file_id), &success, error) == TRUE) { + return success; + } else if (xmlStrcmp (node->name, (xmlChar*) "width") == 0) { + /* gphoto:width */ + xmlChar *width = xmlNodeListGetString (doc, node->children, TRUE); + self->priv->width = g_ascii_strtoull ((gchar*) width, NULL, 10); + xmlFree (width); + } else if (xmlStrcmp (node->name, (xmlChar*) "height") == 0) { + /* gphoto:height */ + xmlChar *height = xmlNodeListGetString (doc, node->children, TRUE); + self->priv->height = g_ascii_strtoull ((gchar*) height, NULL, 10); + xmlFree (height); + } else if (xmlStrcmp (node->name, (xmlChar*) "size") == 0) { + /* gphoto:size */ + xmlChar *size = xmlNodeListGetString (doc, node->children, TRUE); + self->priv->size = g_ascii_strtoull ((gchar*) size, NULL, 10); + xmlFree (size); + } else if (xmlStrcmp (node->name, (xmlChar*) "timestamp") == 0) { + /* gphoto:timestamp */ + xmlChar *timestamp_str; + guint64 milliseconds; + + timestamp_str = xmlNodeListGetString (doc, node->children, TRUE); + milliseconds = g_ascii_strtoull ((gchar*) timestamp_str, NULL, 10); + xmlFree (timestamp_str); + + gdata_picasaweb_file_set_timestamp (self, (gint64) milliseconds); + } else if (xmlStrcmp (node->name, (xmlChar*) "commentingEnabled") == 0) { + /* gphoto:commentingEnabled */ + xmlChar *is_commenting_enabled = xmlNodeListGetString (doc, node->children, TRUE); + if (is_commenting_enabled == NULL) + return gdata_parser_error_required_content_missing (node, error); + self->priv->is_commenting_enabled = (xmlStrcmp (is_commenting_enabled, (xmlChar*) "true") == 0 ? TRUE : FALSE); + xmlFree (is_commenting_enabled); + } else if (xmlStrcmp (node->name, (xmlChar*) "commentCount") == 0) { + /* gphoto:commentCount */ + xmlChar *comment_count = xmlNodeListGetString (doc, node->children, TRUE); + self->priv->comment_count = g_ascii_strtoull ((gchar*) comment_count, NULL, 10); + xmlFree (comment_count); + } else if (xmlStrcmp (node->name, (xmlChar*) "access") == 0) { + /* gphoto:access */ + /* Visibility is already obtained through the album. When PicasaWeb supports per-file access restrictions, + * we'll expose this property. Until then, we'll catch this to suppress the Unhandled XML warning. + * See https://bugzilla.gnome.org/show_bug.cgi?id=589858 */ + } else if (xmlStrcmp (node->name, (xmlChar*) "rotation") == 0) { + /* gphoto:rotation */ + xmlChar *rotation = xmlNodeListGetString (doc, node->children, TRUE); + gdata_picasaweb_file_set_rotation (self, g_ascii_strtoull ((gchar*) rotation, NULL, 10)); + xmlFree (rotation); + } else { + return GDATA_PARSABLE_CLASS (gdata_picasaweb_file_parent_class)->parse_xml (parsable, doc, node, user_data, error); + } + } else { + return GDATA_PARSABLE_CLASS (gdata_picasaweb_file_parent_class)->parse_xml (parsable, doc, node, user_data, error); + } + + return TRUE; +} + +static void +get_xml (GDataParsable *parsable, GString *xml_string) +{ + GDataPicasaWebFilePrivate *priv = GDATA_PICASAWEB_FILE (parsable)->priv; + + /* Chain up to the parent class */ + GDATA_PARSABLE_CLASS (gdata_picasaweb_file_parent_class)->get_xml (parsable, xml_string); + + /* Add all the PicasaWeb-specific XML */ + if (priv->file_id != NULL) + gdata_parser_string_append_escaped (xml_string, "", priv->file_id, ""); + + if (priv->version != NULL) + gdata_parser_string_append_escaped (xml_string, "", priv->version, ""); + + if (priv->album_id != NULL) + gdata_parser_string_append_escaped (xml_string, "", priv->album_id, ""); + + if (priv->checksum != NULL) + gdata_parser_string_append_escaped (xml_string, "", priv->checksum, ""); + + if (priv->timestamp != -1) { + /* timestamp is in milliseconds */ + g_string_append_printf (xml_string, "%" G_GINT64_FORMAT "", priv->timestamp); + } + + if (priv->is_commenting_enabled == TRUE) + g_string_append (xml_string, "true"); + else + g_string_append (xml_string, "false"); + + if (priv->rotation > 0) + g_string_append_printf (xml_string, "%u", priv->rotation); + + /* media:group */ + _gdata_parsable_get_xml (GDATA_PARSABLE (priv->media_group), xml_string, FALSE); + + /* georss:where */ + if (priv->georss_where != NULL && gdata_georss_where_get_latitude (priv->georss_where) != G_MAXDOUBLE && + gdata_georss_where_get_longitude (priv->georss_where) != G_MAXDOUBLE) { + _gdata_parsable_get_xml (GDATA_PARSABLE (priv->georss_where), xml_string, FALSE); + } + + /* TODO: + * - Finish supporting all tags + * - Check all tags here are valid for insertions and updates + */ +} + +static void +get_namespaces (GDataParsable *parsable, GHashTable *namespaces) +{ + GDataPicasaWebFilePrivate *priv = GDATA_PICASAWEB_FILE (parsable)->priv; + + /* Chain up to the parent class */ + GDATA_PARSABLE_CLASS (gdata_picasaweb_file_parent_class)->get_namespaces (parsable, namespaces); + + g_hash_table_insert (namespaces, (gchar*) "gphoto", (gchar*) "http://schemas.google.com/photos/2007"); + g_hash_table_insert (namespaces, (gchar*) "app", (gchar*) "http://www.w3.org/2007/app"); + + /* Add the media:group namespaces */ + GDATA_PARSABLE_GET_CLASS (priv->media_group)->get_namespaces (GDATA_PARSABLE (priv->media_group), namespaces); + /* Add the exif:tags namespaces */ + GDATA_PARSABLE_GET_CLASS (priv->exif_tags)->get_namespaces (GDATA_PARSABLE (priv->exif_tags), namespaces); + /* Add the georss:where namespaces */ + GDATA_PARSABLE_GET_CLASS (priv->georss_where)->get_namespaces (GDATA_PARSABLE (priv->georss_where), namespaces); +} + +static gchar * +get_entry_uri (const gchar *id) +{ + /* For files, the ID is of the form: "http://picasaweb.google.com/data/entry/user/liz/albumid/albumID/photoid/photoID" + * whereas the URI is of the form: "http://picasaweb.google.com/data/entry/api/user/liz/albumid/albumID/photoid/photoID" */ + gchar **parts, *uri; + + parts = g_strsplit (id, "/entry/user/", 2); + g_assert (parts[0] != NULL && parts[1] != NULL && parts[2] == NULL); + uri = g_strconcat (parts[0], "/entry/api/user/", parts[1], NULL); + g_strfreev (parts); + + return uri; +} + +GDataAuthorizationDomain * +get_authorization_domain (GDataCommentable *self) +{ + return gdata_picasaweb_service_get_primary_authorization_domain (); +} + +static gchar * +get_query_comments_uri (GDataCommentable *self) +{ + GDataLink *_link; + SoupURI *uri; + GHashTable *query; + gchar *output_uri; + + /* Get the feed link of the form: https://picasaweb.google.com/data/feed/api/user/[userID]/albumid/[albumID]/photoid/[photoID] */ + _link = gdata_entry_look_up_link (GDATA_ENTRY (self), "http://schemas.google.com/g/2005#feed"); + g_assert (_link != NULL); + + /* We're going to query the comments belonging to the photo, so add the comment kind. This link isn't available as a normal on + * photos. It's of the form: https://picasaweb.google.com/data/feed/api/user/[userID]/albumid/[albumID]/photoid/[photoID]?kind=comment */ + uri = soup_uri_new (gdata_link_get_uri (_link)); + query = soup_form_decode (uri->query); + + g_hash_table_replace (query, g_strdup ("kind"), (gchar*) "comment"); /* libsoup only specifies a destruction function for the key */ + soup_uri_set_query_from_form (uri, query); + output_uri = soup_uri_to_string (uri, FALSE); + + g_hash_table_destroy (query); + soup_uri_free (uri); + + return output_uri; +} + +static gchar * +get_insert_comment_uri (GDataCommentable *self, GDataComment *comment_) +{ + GDataLink *_link; + + _link = gdata_entry_look_up_link (GDATA_ENTRY (self), "http://schemas.google.com/g/2005#feed"); + g_assert (_link != NULL); + + return g_strdup (gdata_link_get_uri (_link)); +} + +static gboolean +is_comment_deletable (GDataCommentable *self, GDataComment *comment_) +{ + return (gdata_entry_look_up_link (GDATA_ENTRY (comment_), GDATA_LINK_EDIT) != NULL) ? TRUE : FALSE; +} + +/** + * gdata_picasaweb_file_new: + * @id: (allow-none): the file's ID, or %NULL + * + * Creates a new #GDataPicasaWebFile with the given ID and default properties. + * + * Return value: a new #GDataPicasaWebFile; unref with g_object_unref() + * + * Since: 0.4.0 + */ +GDataPicasaWebFile * +gdata_picasaweb_file_new (const gchar *id) +{ + const gchar *file_id = NULL, *i; + + if (id != NULL) { + file_id = g_strrstr (id, "/"); + if (file_id == NULL) + return NULL; + file_id++; /* skip the slash */ + + /* Ensure the @file_id is entirely numeric */ + for (i = file_id; *i != '\0'; i = g_utf8_next_char (i)) { + if (g_unichar_isdigit (g_utf8_get_char (i)) == FALSE) + return NULL; + } + } + + return GDATA_PICASAWEB_FILE (g_object_new (GDATA_TYPE_PICASAWEB_FILE, "id", id, "file-id", file_id, NULL)); +} + +/** + * gdata_picasaweb_file_get_id: + * @self: a #GDataPicasaWebFile + * + * Gets the #GDataPicasaWebFile:file-id property. + * + * Return value: the file's ID + * + * Since: 0.7.0 + */ +const gchar * +gdata_picasaweb_file_get_id (GDataPicasaWebFile *self) +{ + g_return_val_if_fail (GDATA_IS_PICASAWEB_FILE (self), NULL); + return self->priv->file_id; +} + +/** + * gdata_picasaweb_file_get_edited: + * @self: a #GDataPicasaWebFile + * + * Gets the #GDataPicasaWebFile:edited property. If the property is unset, -1 will be returned. + * + * Return value: the UNIX timestamp for the time the file was last edited, or -1 + * + * Since: 0.4.0 + */ +gint64 +gdata_picasaweb_file_get_edited (GDataPicasaWebFile *self) +{ + g_return_val_if_fail (GDATA_IS_PICASAWEB_FILE (self), -1); + return self->priv->edited; +} + +/** + * gdata_picasaweb_file_get_version: + * @self: a #GDataPicasaWebFile + * + * Gets the #GDataPicasaWebFile:version property. + * + * Return value: the file's version number, or %NULL + * + * Since: 0.4.0 + */ +const gchar * +gdata_picasaweb_file_get_version (GDataPicasaWebFile *self) +{ + g_return_val_if_fail (GDATA_IS_PICASAWEB_FILE (self), NULL); + return self->priv->version; +} + +/** + * gdata_picasaweb_file_get_album_id: + * @self: a #GDataPicasaWebFile + * + * Gets the #GDataPicasaWebFile:album-id property. This is in the same form as returned by gdata_picasaweb_album_get_id(). + * + * Return value: the ID of the album containing the #GDataPicasaWebFile + * + * Since: 0.4.0 + */ +const gchar * +gdata_picasaweb_file_get_album_id (GDataPicasaWebFile *self) +{ + g_return_val_if_fail (GDATA_IS_PICASAWEB_FILE (self), NULL); + return self->priv->album_id; +} + +/** + * gdata_picasaweb_file_set_album_id: + * @self: a #GDataPicasaWebFile + * @album_id: the ID of the new album for this file + * + * Sets the #GDataPicasaWebFile:album-id property, effectively moving the file to the album. + * + * Since: 0.4.0 + */ +void +gdata_picasaweb_file_set_album_id (GDataPicasaWebFile *self, const gchar *album_id) +{ + g_return_if_fail (GDATA_IS_PICASAWEB_FILE (self)); + g_return_if_fail (album_id != NULL && *album_id != '\0'); + + g_free (self->priv->album_id); + self->priv->album_id = g_strdup (album_id); + g_object_notify (G_OBJECT (self), "album-id"); +} + +/** + * gdata_picasaweb_file_get_width: + * @self: a #GDataPicasaWebFile + * + * Gets the #GDataPicasaWebFile:width property. + * + * Return value: the width of the image or video, in pixels + * + * Since: 0.4.0 + */ +guint +gdata_picasaweb_file_get_width (GDataPicasaWebFile *self) +{ + g_return_val_if_fail (GDATA_IS_PICASAWEB_FILE (self), 0); + return self->priv->width; +} + +/** + * gdata_picasaweb_file_get_height: + * @self: a #GDataPicasaWebFile + * + * Gets the #GDataPicasaWebFile:height property. + * + * Return value: the height of the image or video, in pixels + * + * Since: 0.4.0 + */ +guint +gdata_picasaweb_file_get_height (GDataPicasaWebFile *self) +{ + g_return_val_if_fail (GDATA_IS_PICASAWEB_FILE (self), 0); + return self->priv->height; +} + +/** + * gdata_picasaweb_file_get_size: + * @self: a #GDataPicasaWebFile + * + * Gets the #GDataPicasaWebFile:size property. + * + * Return value: the size of the file, in bytes + * + * Since: 0.4.0 + */ +gsize +gdata_picasaweb_file_get_size (GDataPicasaWebFile *self) +{ + g_return_val_if_fail (GDATA_IS_PICASAWEB_FILE (self), 0); + return self->priv->size; +} + +/** + * gdata_picasaweb_file_get_checksum: + * @self: a #GDataPicasaWebFile + * + * Gets the #GDataPicasaWebFile:checksum property. + * + * Return value: the checksum assigned to this file, or %NULL + * + * Since: 0.4.0 + */ +const gchar * +gdata_picasaweb_file_get_checksum (GDataPicasaWebFile *self) +{ + g_return_val_if_fail (GDATA_IS_PICASAWEB_FILE (self), NULL); + return self->priv->checksum; +} + +/** + * gdata_picasaweb_file_set_checksum: + * @self: a #GDataPicasaWebFile + * @checksum: (allow-none): the new checksum for this file, or %NULL + * + * Sets the #GDataPicasaWebFile:checksum property to @checksum. + * + * Set @checksum to %NULL to unset the property. + * + * Since: 0.4.0 + */ +void +gdata_picasaweb_file_set_checksum (GDataPicasaWebFile *self, const gchar *checksum) +{ + g_return_if_fail (GDATA_IS_PICASAWEB_FILE (self)); + + g_free (self->priv->checksum); + self->priv->checksum = g_strdup (checksum); + g_object_notify (G_OBJECT (self), "checksum"); +} + +/** + * gdata_picasaweb_file_get_timestamp: + * @self: a #GDataPicasaWebFile + * + * Gets the #GDataPicasaWebFile:timestamp property. It's a UNIX timestamp in milliseconds (not seconds) since the epoch. If the property is unset, + * -1 will be returned. + * + * Return value: the UNIX timestamp for the timestamp property in milliseconds, or -1 + * + * Since: 0.4.0 + */ +gint64 +gdata_picasaweb_file_get_timestamp (GDataPicasaWebFile *self) +{ + g_return_val_if_fail (GDATA_IS_PICASAWEB_FILE (self), -1); + return self->priv->timestamp; +} + +/** + * gdata_picasaweb_file_set_timestamp: + * @self: a #GDataPicasaWebFile + * @timestamp: a UNIX timestamp, or -1 + * + * Sets the #GDataPicasaWebFile:timestamp property from @timestamp. This should be a UNIX timestamp in milliseconds (not seconds) since the epoch. If + * @timestamp is -1, the property will be unset. + * + * Since: 0.4.0 + */ +void +gdata_picasaweb_file_set_timestamp (GDataPicasaWebFile *self, gint64 timestamp) +{ + /* RHSTODO: I think the timestamp value is just being + over-ridden by the file's actual EXIF time value; unless + we're setting this incorrectly here or in get_xml(); test that */ + /* RHSTODO: improve testing of setters in tests/picasa.c */ + + g_return_if_fail (GDATA_IS_PICASAWEB_FILE (self)); + g_return_if_fail (timestamp >= -1); + + self->priv->timestamp = timestamp; + g_object_notify (G_OBJECT (self), "timestamp"); +} + +/** + * gdata_picasaweb_file_is_commenting_enabled: + * @self: a #GDataPicasaWebFile + * + * Gets the #GDataPicasaWebFile:is-commenting-enabled property. + * + * Return value: %TRUE if commenting is enabled, %FALSE otherwise + * + * Since: 0.4.0 + */ +gboolean +gdata_picasaweb_file_is_commenting_enabled (GDataPicasaWebFile *self) +{ + g_return_val_if_fail (GDATA_IS_PICASAWEB_FILE (self), FALSE); + return self->priv->is_commenting_enabled; +} + +/** + * gdata_picasaweb_file_set_is_commenting_enabled: + * @self: a #GDataPicasaWebFile + * @is_commenting_enabled: %TRUE if commenting should be enabled for the file, %FALSE otherwise + * + * Sets the #GDataPicasaWebFile:is-commenting-enabled property to @is_commenting_enabled. + * + * Since: 0.4.0 + */ +void +gdata_picasaweb_file_set_is_commenting_enabled (GDataPicasaWebFile *self, gboolean is_commenting_enabled) +{ + g_return_if_fail (GDATA_IS_PICASAWEB_FILE (self)); + self->priv->is_commenting_enabled = is_commenting_enabled; + g_object_notify (G_OBJECT (self), "is-commenting-enabled"); +} + +/** + * gdata_picasaweb_file_get_comment_count: + * @self: a #GDataPicasaWebFile + * + * Gets the #GDataPicasaWebFile:comment-count property. + * + * Return value: the number of comments on the file + * + * Since: 0.4.0 + */ +guint +gdata_picasaweb_file_get_comment_count (GDataPicasaWebFile *self) +{ + g_return_val_if_fail (GDATA_IS_PICASAWEB_FILE (self), 0); + return self->priv->comment_count; +} + +/** + * gdata_picasaweb_file_get_rotation: + * @self: a #GDataPicasaWebFile + * + * Gets the #GDataPicasaWebFile:rotation property. + * + * Return value: the image's rotation, in degrees + * + * Since: 0.4.0 + */ +guint +gdata_picasaweb_file_get_rotation (GDataPicasaWebFile *self) +{ + g_return_val_if_fail (GDATA_IS_PICASAWEB_FILE (self), 0); + return self->priv->rotation; +} + +/** + * gdata_picasaweb_file_set_rotation: + * @self: a #GDataPicasaWebFile + * @rotation: the new rotation for the image, in degrees + * + * Sets the #GDataPicasaWebFile:rotation property to @rotation. + * + * The rotation is absolute, rather than cumulative, through successive calls to gdata_picasaweb_file_set_rotation(), + * so calling it with 90° then 20° will result in a final rotation of 20°. + * + * Since: 0.4.0 + */ +void +gdata_picasaweb_file_set_rotation (GDataPicasaWebFile *self, guint rotation) +{ + g_return_if_fail (GDATA_IS_PICASAWEB_FILE (self)); + self->priv->rotation = rotation % 360; + g_object_notify (G_OBJECT (self), "rotation"); +} + + +/** + * gdata_picasaweb_file_get_video_status: + * @self: a #GDataPicasaWebFile + * + * Gets the #GDataPicasaWebFile:video-status property. + * + * Return value: the status of this video ("pending", "ready", "final" or "failed"), or %NULL + * + * Since: 0.4.0 + */ +const gchar * +gdata_picasaweb_file_get_video_status (GDataPicasaWebFile *self) +{ + g_return_val_if_fail (GDATA_IS_PICASAWEB_FILE (self), NULL); + return self->priv->video_status; +} + +/** + * gdata_picasaweb_file_get_tags: + * @self: a #GDataPicasaWebFile + * + * Gets the #GDataPicasaWebFile:tags property. + * + * Return value: (array zero-terminated=1) (transfer none): a %NULL-terminated array of tags associated with the file, or %NULL + * + * Since: 0.4.0 + */ +const gchar * const * +gdata_picasaweb_file_get_tags (GDataPicasaWebFile *self) +{ + g_return_val_if_fail (GDATA_IS_PICASAWEB_FILE (self), NULL); + return gdata_media_group_get_keywords (self->priv->media_group); +} + +/** + * gdata_picasaweb_file_set_tags: + * @self: a #GDataPicasaWebFile + * @tags: (array zero-terminated=1) (allow-none): a new %NULL-terminated array of tags, or %NULL + * + * Sets the #GDataPicasaWebFile:tags property to @tags. + * + * Set @tags to %NULL to unset the property. + * + * Since: 0.4.0 + */ +void +gdata_picasaweb_file_set_tags (GDataPicasaWebFile *self, const gchar * const *tags) +{ + g_return_if_fail (GDATA_IS_PICASAWEB_FILE (self)); + + gdata_media_group_set_keywords (self->priv->media_group, tags); + g_object_notify (G_OBJECT (self), "tags"); +} + +/** + * gdata_picasaweb_file_get_credit: + * @self: a #GDataPicasaWebFile + * + * Gets the #GDataPicasaWebFile:credit property. + * + * Return value: the nickname of the user credited with this file + * + * Since: 0.4.0 + */ +const gchar * +gdata_picasaweb_file_get_credit (GDataPicasaWebFile *self) +{ + GDataMediaCredit *credit; + + g_return_val_if_fail (GDATA_IS_PICASAWEB_FILE (self), NULL); + + credit = gdata_media_group_get_credit (self->priv->media_group); + return (credit == NULL) ? NULL : gdata_media_credit_get_credit (credit); +} + +/** + * gdata_picasaweb_file_get_caption: + * @self: a #GDataPicasaWebFile + * + * Gets the #GDataPicasaWebFile:caption property. + * + * Return value: the file's descriptive caption, or %NULL + * + * Since: 0.4.0 + */ +const gchar * +gdata_picasaweb_file_get_caption (GDataPicasaWebFile *self) +{ + g_return_val_if_fail (GDATA_IS_PICASAWEB_FILE (self), NULL); + return gdata_entry_get_summary (GDATA_ENTRY (self)); +} + +/** + * gdata_picasaweb_file_set_caption: + * @self: a #GDataPicasaWebFile + * @caption: (allow-none): the file's new caption, or %NULL + * + * Sets the #GDataPicasaWebFile:caption property to @caption. + * + * Set @caption to %NULL to unset the file's caption. + * + * Since: 0.4.0 + */ +void +gdata_picasaweb_file_set_caption (GDataPicasaWebFile *self, const gchar *caption) +{ + g_return_if_fail (GDATA_IS_PICASAWEB_FILE (self)); + + gdata_entry_set_summary (GDATA_ENTRY (self), caption); + gdata_media_group_set_description (self->priv->media_group, caption); + g_object_notify (G_OBJECT (self), "caption"); +} + +/** + * gdata_picasaweb_file_get_contents: + * @self: a #GDataPicasaWebFile + * + * Returns a list of media content, e.g. the actual photo or video. + * + * Return value: (element-type GData.MediaContent) (transfer none): a #GList of #GDataMediaContent items + * + * Since: 0.4.0 + */ +GList * +gdata_picasaweb_file_get_contents (GDataPicasaWebFile *self) +{ + g_return_val_if_fail (GDATA_IS_PICASAWEB_FILE (self), NULL); + return gdata_media_group_get_contents (self->priv->media_group); +} + +/** + * gdata_picasaweb_file_get_thumbnails: + * @self: a #GDataPicasaWebFile + * + * Returns a list of thumbnails, often at different sizes, for this + * file. Currently, PicasaWeb usually returns three thumbnails, with + * widths in pixels of 72, 144, and 288. However, the thumbnail will + * not be larger than the actual image, so thumbnails may be smaller + * than the widths listed above. + * + * Return value: (element-type GData.MediaThumbnail) (transfer none): a #GList of #GDataMediaThumbnails, or %NULL + * + * Since: 0.4.0 + */ +GList * +gdata_picasaweb_file_get_thumbnails (GDataPicasaWebFile *self) +{ + g_return_val_if_fail (GDATA_IS_PICASAWEB_FILE (self), NULL); + return gdata_media_group_get_thumbnails (self->priv->media_group); +} + +/** + * gdata_picasaweb_file_get_distance: + * @self: a #GDataPicasaWebFile + * + * Gets the #GDataPicasaWebFile:distance property. + * + * Return value: the distance recorded in the photo's EXIF, or -1 if unknown + * + * Since: 0.5.0 + */ +gdouble +gdata_picasaweb_file_get_distance (GDataPicasaWebFile *self) +{ + g_return_val_if_fail (GDATA_IS_PICASAWEB_FILE (self), -1); + return gdata_exif_tags_get_distance (self->priv->exif_tags); +} + +/** + * gdata_picasaweb_file_get_exposure: + * @self: a #GDataPicasaWebFile + * + * Gets the #GDataPicasaWebFile:exposure property. + * + * Return value: the exposure value, or 0 if unknown + * + * Since: 0.5.0 + */ +gdouble +gdata_picasaweb_file_get_exposure (GDataPicasaWebFile *self) +{ + g_return_val_if_fail (GDATA_IS_PICASAWEB_FILE (self), 0); + return gdata_exif_tags_get_exposure (self->priv->exif_tags); +} + +/** + * gdata_picasaweb_file_get_flash: + * @self: a #GDataPicasaWebFile + * + * Gets the #GDataPicasaWebFile:flash property. + * + * Return value: %TRUE if flash was used, %FALSE otherwise + * + * Since: 0.5.0 + */ +gboolean +gdata_picasaweb_file_get_flash (GDataPicasaWebFile *self) +{ + g_return_val_if_fail (GDATA_IS_PICASAWEB_FILE (self), FALSE); + return gdata_exif_tags_get_flash (self->priv->exif_tags); +} + +/** + * gdata_picasaweb_file_get_focal_length: + * @self: a #GDataPicasaWebFile + * + * Gets the #GDataPicasaWebFile:focal-length property. + * + * Return value: the focal-length value, or -1 if unknown + * + * Since: 0.5.0 + */ +gdouble +gdata_picasaweb_file_get_focal_length (GDataPicasaWebFile *self) +{ + g_return_val_if_fail (GDATA_IS_PICASAWEB_FILE (self), -1); + return gdata_exif_tags_get_focal_length (self->priv->exif_tags); +} + +/** + * gdata_picasaweb_file_get_fstop: + * @self: a #GDataPicasaWebFile + * + * Gets the #GDataPicasaWebFile:fstop property. + * + * Return value: the F-stop value, or 0 if unknown + * + * Since: 0.5.0 + */ +gdouble +gdata_picasaweb_file_get_fstop (GDataPicasaWebFile *self) +{ + g_return_val_if_fail (GDATA_IS_PICASAWEB_FILE (self), 0); + return gdata_exif_tags_get_fstop (self->priv->exif_tags); +} + +/** + * gdata_picasaweb_file_get_image_unique_id: + * @self: a #GDataPicasaWebFile + * + * Gets the #GDataPicasaWebFile:image-unique-id property. + * + * Return value: the photo's unique EXIF identifier, or %NULL + * + * Since: 0.5.0 + */ +const gchar * +gdata_picasaweb_file_get_image_unique_id (GDataPicasaWebFile *self) +{ + g_return_val_if_fail (GDATA_IS_PICASAWEB_FILE (self), NULL); + return gdata_exif_tags_get_image_unique_id (self->priv->exif_tags); +} + +/** + * gdata_picasaweb_file_get_iso: + * @self: a #GDataPicasaWebFile + * + * Gets the #GDataPicasaWebFile:iso property. + * + * Return value: the ISO speed, or -1 if unknown + * + * Since: 0.5.0 + */ +gint +gdata_picasaweb_file_get_iso (GDataPicasaWebFile *self) +{ + g_return_val_if_fail (GDATA_IS_PICASAWEB_FILE (self), -1); + return gdata_exif_tags_get_iso (self->priv->exif_tags); +} + +/** + * gdata_picasaweb_file_get_make: + * @self: a #GDataPicasaWebFile + * + * Gets the #GDataPicasaWebFile:make property. + * + * Return value: the name of the manufacturer of the camera, or %NULL if unknown + * + * Since: 0.5.0 + */ +const gchar * +gdata_picasaweb_file_get_make (GDataPicasaWebFile *self) +{ + g_return_val_if_fail (GDATA_IS_PICASAWEB_FILE (self), NULL); + return gdata_exif_tags_get_make (self->priv->exif_tags); +} + +/** + * gdata_picasaweb_file_get_model: + * @self: a #GDataPicasaWebFile + * + * Gets the #GDataPicasaWebFile:model property. + * + * Return value: the model name of the camera, or %NULL if unknown + * + * Since: 0.5.0 + */ +const gchar * +gdata_picasaweb_file_get_model (GDataPicasaWebFile *self) +{ + g_return_val_if_fail (GDATA_IS_PICASAWEB_FILE (self), NULL); + return gdata_exif_tags_get_model (self->priv->exif_tags); +} + +/** + * gdata_picasaweb_file_get_coordinates: + * @self: a #GDataPicasaWebFile + * @latitude: (out caller-allocates) (allow-none): return location for the latitude, or %NULL + * @longitude: (out caller-allocates) (allow-none): return location for the longitude, or %NULL + * + * Gets the #GDataPicasaWebFile:latitude and #GDataPicasaWebFile:longitude properties, setting the out parameters to them. + * If either latitude or longitude is %NULL, that parameter will not be set. If the coordinates are unset, + * @latitude and @longitude will be set to %G_MAXDOUBLE. + * + * Since: 0.5.0 + */ +void +gdata_picasaweb_file_get_coordinates (GDataPicasaWebFile *self, gdouble *latitude, gdouble *longitude) +{ + g_return_if_fail (GDATA_IS_PICASAWEB_FILE (self)); + + if (latitude != NULL) + *latitude = gdata_georss_where_get_latitude (self->priv->georss_where); + if (longitude != NULL) + *longitude = gdata_georss_where_get_longitude (self->priv->georss_where); +} + +/** + * gdata_picasaweb_file_set_coordinates: + * @self: a #GDataPicasaWebFile + * @latitude: the file's new latitude coordinate, or %G_MAXDOUBLE + * @longitude: the file's new longitude coordinate, or %G_MAXDOUBLE + * + * Sets the #GDataPicasaWebFile:latitude and #GDataPicasaWebFile:longitude properties to + * @latitude and @longitude respectively. + * + * Since: 0.5.0 + */ +void +gdata_picasaweb_file_set_coordinates (GDataPicasaWebFile *self, gdouble latitude, gdouble longitude) +{ + g_return_if_fail (GDATA_IS_PICASAWEB_FILE (self)); + + gdata_georss_where_set_latitude (self->priv->georss_where, latitude); + gdata_georss_where_set_longitude (self->priv->georss_where, longitude); + + g_object_freeze_notify (G_OBJECT (self)); + g_object_notify (G_OBJECT (self), "latitude"); + g_object_notify (G_OBJECT (self), "longitude"); + g_object_thaw_notify (G_OBJECT (self)); +} diff --git a/gdata/services/picasaweb/gdata-picasaweb-file.h b/gdata/services/picasaweb/gdata-picasaweb-file.h new file mode 100644 index 0000000..1bd9f0f --- /dev/null +++ b/gdata/services/picasaweb/gdata-picasaweb-file.h @@ -0,0 +1,154 @@ +/* -*- Mode: C; indent-tabs-mode: t; c-basic-offset: 8; tab-width: 8 -*- */ +/* + * GData Client + * Copyright (C) Richard Schwarting 2009 + * Copyright (C) Philip Withnall 2009 + * + * GData Client is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * GData Client is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with GData Client. If not, see . + */ + +#ifndef GDATA_PICASAWEB_FILE_H +#define GDATA_PICASAWEB_FILE_H + +#include +#include + +#include +#include + +G_BEGIN_DECLS + +/** + * GDATA_PICASAWEB_VIDEO_STATUS_PENDING: + * + * The video is still being processed. + * + * Since: 0.7.0 + */ +#define GDATA_PICASAWEB_VIDEO_STATUS_PENDING "pending" + +/** + * GDATA_PICASAWEB_VIDEO_STATUS_READY: + * + * The video has been processed, but still needs thumbnailing. + * + * Since: 0.7.0 + */ +#define GDATA_PICASAWEB_VIDEO_STATUS_READY "ready" + +/** + * GDATA_PICASAWEB_VIDEO_STATUS_FINAL: + * + * The video has been processed and thumbnailed. + * + * Since: 0.7.0 + */ +#define GDATA_PICASAWEB_VIDEO_STATUS_FINAL "final" + +/** + * GDATA_PICASAWEB_VIDEO_STATUS_FAILED: + * + * There was an error while processing or thumbnailing the video and it should be deleted. + * + * Since: 0.7.0 + */ +#define GDATA_PICASAWEB_VIDEO_STATUS_FAILED "failed" + +#define GDATA_TYPE_PICASAWEB_FILE (gdata_picasaweb_file_get_type ()) +#define GDATA_PICASAWEB_FILE(o) (G_TYPE_CHECK_INSTANCE_CAST ((o), GDATA_TYPE_PICASAWEB_FILE, GDataPicasaWebFile)) +#define GDATA_PICASAWEB_FILE_CLASS(k) (G_TYPE_CHECK_CLASS_CAST((k), GDATA_TYPE_PICASAWEB_FILE, GDataPicasaWebFileClass)) +#define GDATA_IS_PICASAWEB_FILE(o) (G_TYPE_CHECK_INSTANCE_TYPE ((o), GDATA_TYPE_PICASAWEB_FILE)) +#define GDATA_IS_PICASAWEB_FILE_CLASS(k) (G_TYPE_CHECK_CLASS_TYPE ((k), GDATA_TYPE_PICASAWEB_FILE)) +#define GDATA_PICASAWEB_FILE_GET_CLASS(o) (G_TYPE_INSTANCE_GET_CLASS ((o), GDATA_TYPE_PICASAWEB_FILE, GDataPicasaWebFileClass)) + +typedef struct _GDataPicasaWebFilePrivate GDataPicasaWebFilePrivate; + +/** + * GDataPicasaWebFile: + * + * All the fields in the #GDataPicasaWebFile structure are private and should never be accessed directly. + * + * Since: 0.4.0 + */ +typedef struct { + GDataEntry parent; + GDataPicasaWebFilePrivate *priv; +} GDataPicasaWebFile; + +/** + * GDataPicasaWebFileClass: + * + * All the fields in the #GDataPicasaWebFileClass structure are private and should never be accessed directly. + * + * Since: 0.4.0 + */ +typedef struct { + /*< private >*/ + GDataEntryClass parent; + + /*< private >*/ + /* Padding for future expansion */ + void (*_g_reserved0) (void); + void (*_g_reserved1) (void); +} GDataPicasaWebFileClass; + +GType gdata_picasaweb_file_get_type (void) G_GNUC_CONST; +G_DEFINE_AUTOPTR_CLEANUP_FUNC (GDataPicasaWebFile, g_object_unref) + +GDataPicasaWebFile *gdata_picasaweb_file_new (const gchar *id) G_GNUC_WARN_UNUSED_RESULT G_GNUC_MALLOC; + +const gchar *gdata_picasaweb_file_get_id (GDataPicasaWebFile *self) G_GNUC_PURE; +gint64 gdata_picasaweb_file_get_edited (GDataPicasaWebFile *self); +const gchar *gdata_picasaweb_file_get_version (GDataPicasaWebFile *self) G_GNUC_PURE; +const gchar *gdata_picasaweb_file_get_album_id (GDataPicasaWebFile *self) G_GNUC_PURE; +/* TODO should we have a more obvious _move() API too? nah */ +void gdata_picasaweb_file_set_album_id (GDataPicasaWebFile *self, const gchar *album_id); +guint gdata_picasaweb_file_get_width (GDataPicasaWebFile *self) G_GNUC_PURE; +guint gdata_picasaweb_file_get_height (GDataPicasaWebFile *self) G_GNUC_PURE; +gsize gdata_picasaweb_file_get_size (GDataPicasaWebFile *self) G_GNUC_PURE; +const gchar *gdata_picasaweb_file_get_checksum (GDataPicasaWebFile *self) G_GNUC_PURE; +void gdata_picasaweb_file_set_checksum (GDataPicasaWebFile *self, const gchar *checksum); +gint64 gdata_picasaweb_file_get_timestamp (GDataPicasaWebFile *self); +void gdata_picasaweb_file_set_timestamp (GDataPicasaWebFile *self, gint64 timestamp); +gboolean gdata_picasaweb_file_is_commenting_enabled (GDataPicasaWebFile *self) G_GNUC_PURE; +void gdata_picasaweb_file_set_is_commenting_enabled (GDataPicasaWebFile *self, gboolean is_commenting_enabled); +guint gdata_picasaweb_file_get_comment_count (GDataPicasaWebFile *self) G_GNUC_PURE; +guint gdata_picasaweb_file_get_rotation (GDataPicasaWebFile *self) G_GNUC_PURE; +void gdata_picasaweb_file_set_rotation (GDataPicasaWebFile *self, guint rotation); +const gchar *gdata_picasaweb_file_get_video_status (GDataPicasaWebFile *self) G_GNUC_PURE; +const gchar * const *gdata_picasaweb_file_get_tags (GDataPicasaWebFile *self) G_GNUC_PURE; +void gdata_picasaweb_file_set_tags (GDataPicasaWebFile *self, const gchar * const *tags); +const gchar *gdata_picasaweb_file_get_credit (GDataPicasaWebFile *self) G_GNUC_PURE; +const gchar *gdata_picasaweb_file_get_caption (GDataPicasaWebFile *self) G_GNUC_PURE; +void gdata_picasaweb_file_set_caption (GDataPicasaWebFile *self, const gchar *caption); +GList *gdata_picasaweb_file_get_contents (GDataPicasaWebFile *self) G_GNUC_PURE; +GList *gdata_picasaweb_file_get_thumbnails (GDataPicasaWebFile *self) G_GNUC_PURE; +gdouble gdata_picasaweb_file_get_distance (GDataPicasaWebFile *self) G_GNUC_PURE; +gdouble gdata_picasaweb_file_get_exposure (GDataPicasaWebFile *self) G_GNUC_PURE; +gboolean gdata_picasaweb_file_get_flash (GDataPicasaWebFile *self) G_GNUC_PURE; +gdouble gdata_picasaweb_file_get_focal_length (GDataPicasaWebFile *self) G_GNUC_PURE; +gdouble gdata_picasaweb_file_get_fstop (GDataPicasaWebFile *self) G_GNUC_PURE; +const gchar *gdata_picasaweb_file_get_image_unique_id (GDataPicasaWebFile *self) G_GNUC_PURE; +gint gdata_picasaweb_file_get_iso (GDataPicasaWebFile *self) G_GNUC_PURE; +const gchar *gdata_picasaweb_file_get_make (GDataPicasaWebFile *self) G_GNUC_PURE; +const gchar *gdata_picasaweb_file_get_model (GDataPicasaWebFile *self) G_GNUC_PURE; +void gdata_picasaweb_file_get_coordinates (GDataPicasaWebFile *self, gdouble *latitude, gdouble *longitude); +void gdata_picasaweb_file_set_coordinates (GDataPicasaWebFile *self, gdouble latitude, gdouble longitude); + +/* TODO implement is video */ +/* TODO implement get comments */ + +G_END_DECLS + +#endif /* !GDATA_PICASAWEB_FILE_H */ diff --git a/gdata/services/picasaweb/gdata-picasaweb-query.c b/gdata/services/picasaweb/gdata-picasaweb-query.c new file mode 100644 index 0000000..5785157 --- /dev/null +++ b/gdata/services/picasaweb/gdata-picasaweb-query.c @@ -0,0 +1,608 @@ +/* -*- Mode: C; indent-tabs-mode: t; c-basic-offset: 8; tab-width: 8 -*- */ +/* + * GData Client + * Copyright (C) Richard Schwarting 2009 + * Copyright (C) Philip Withnall 2009–2010 + * + * GData Client is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * GData Client is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with GData Client. If not, see . + */ + +/** + * SECTION:gdata-picasaweb-query + * @short_description: GData PicasaWeb query object + * @stability: Stable + * @include: gdata/services/picasaweb/gdata-picasaweb-query.h + * + * #GDataPicasaWebQuery represents a collection of query parameters specific to the Google PicasaWeb service, which go above and beyond + * those catered for by #GDataQuery. + * + * For more information on the custom GData query parameters supported by #GDataPicasaWebQuery, see the online documentation. + * + * Since: 0.4.0 + */ + +#include +#include +#include +#include + +#include "gdata-picasaweb-query.h" +#include "gdata-query.h" +#include "gdata-picasaweb-enums.h" +#include "gdata-private.h" + +static void gdata_picasaweb_query_finalize (GObject *object); +static void gdata_picasaweb_query_get_property (GObject *object, guint property_id, GValue *value, GParamSpec *pspec); +static void gdata_picasaweb_query_set_property (GObject *object, guint property_id, const GValue *value, GParamSpec *pspec); +static void get_query_uri (GDataQuery *self, const gchar *feed_uri, GString *query_uri, gboolean *params_started); + +struct _GDataPicasaWebQueryPrivate { + GDataPicasaWebVisibility visibility; + gchar *thumbnail_size; + gchar *image_size; + gchar *tag; + gchar *location; + + struct { + gdouble north; + gdouble east; + gdouble south; + gdouble west; + } bounding_box; +}; + +enum { + PROP_VISIBILITY = 1, + PROP_THUMBNAIL_SIZE, + PROP_IMAGE_SIZE, + PROP_TAG, + PROP_LOCATION +}; + +G_DEFINE_TYPE (GDataPicasaWebQuery, gdata_picasaweb_query, GDATA_TYPE_QUERY) + +static void +gdata_picasaweb_query_class_init (GDataPicasaWebQueryClass *klass) +{ + GObjectClass *gobject_class = G_OBJECT_CLASS (klass); + GDataQueryClass *query_class = GDATA_QUERY_CLASS (klass); + + g_type_class_add_private (klass, sizeof (GDataPicasaWebQueryPrivate)); + + gobject_class->get_property = gdata_picasaweb_query_get_property; + gobject_class->set_property = gdata_picasaweb_query_set_property; + gobject_class->finalize = gdata_picasaweb_query_finalize; + + query_class->get_query_uri = get_query_uri; + + /** + * GDataPicasaWebQuery:visibility: + * + * Specifies which albums should be listed, in terms of their visibility (#GDataPicasaWebAlbum:visibility). + * + * Set the property to 0 to list all albums, regardless of their visibility. Otherwise, use values + * from #GDataPicasaWebVisibility. + * + * For more information, see the + * online documentation. + * + * Since: 0.4.0 + */ + g_object_class_install_property (gobject_class, PROP_VISIBILITY, + g_param_spec_int ("visibility", + "Visibility", "Specifies which albums should be listed, in terms of their visibility.", + 0, GDATA_PICASAWEB_PRIVATE, 0, + G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)); + + /** + * GDataPicasaWebQuery:thumbnail-size: + * + * A comma-separated list of thumbnail widths (in pixels) to return. Only certain sizes are allowed, and whether the thumbnail should be + * cropped or scaled can be specified; for more information, see the + * online documentation. + * + * Since: 0.4.0 + */ + g_object_class_install_property (gobject_class, PROP_THUMBNAIL_SIZE, + g_param_spec_string ("thumbnail-size", + "Thumbnail size", "A comma-separated list of thumbnail width (in pixels) to return.", + NULL, + G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)); + + /** + * GDataPicasaWebQuery:image-size: + * + * A comma-separated list of image sizes (width in pixels) to return. Only certain sizes are allowed, and whether the image should be + * cropped or scaled can be specified; for more information, see the + * online documentation. + * + * Since: 0.4.0 + */ + g_object_class_install_property (gobject_class, PROP_IMAGE_SIZE, + g_param_spec_string ("image-size", + "Image size", "A comma-separated list of image sizes (width in pixels) to return.", + NULL, + G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)); + + /** + * GDataPicasaWebQuery:tag: + * + * A tag which returned results must contain. + * + * Since: 0.4.0 + */ + g_object_class_install_property (gobject_class, PROP_TAG, + g_param_spec_string ("tag", + "Tag", "A tag which returned results must contain.", + NULL, + G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)); + + /** + * GDataPicasaWebQuery:location: + * + * A location to search for photos, e.g. "London". + * + * Since: 0.4.0 + */ + g_object_class_install_property (gobject_class, PROP_LOCATION, + g_param_spec_string ("location", + "Location", "A location to search for photos, e.g. \"London\".", + NULL, + G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)); +} + +static void +gdata_picasaweb_query_init (GDataPicasaWebQuery *self) +{ + self->priv = G_TYPE_INSTANCE_GET_PRIVATE (self, GDATA_TYPE_PICASAWEB_QUERY, GDataPicasaWebQueryPrivate); + + /* https://developers.google.com/picasa-web/docs/3.0/reference#Parameters */ + _gdata_query_set_pagination_type (GDATA_QUERY (self), + GDATA_QUERY_PAGINATION_INDEXED); +} + +static void +gdata_picasaweb_query_finalize (GObject *object) +{ + GDataPicasaWebQueryPrivate *priv = GDATA_PICASAWEB_QUERY (object)->priv; + + g_free (priv->thumbnail_size); + g_free (priv->image_size); + g_free (priv->tag); + g_free (priv->location); + + /* Chain up to the parent class */ + G_OBJECT_CLASS (gdata_picasaweb_query_parent_class)->finalize (object); +} + +static void +gdata_picasaweb_query_get_property (GObject *object, guint property_id, GValue *value, GParamSpec *pspec) +{ + GDataPicasaWebQueryPrivate *priv = GDATA_PICASAWEB_QUERY (object)->priv; + + switch (property_id) { + case PROP_VISIBILITY: + g_value_set_int (value, priv->visibility); + break; + case PROP_THUMBNAIL_SIZE: + g_value_set_string (value, priv->thumbnail_size); + break; + case PROP_IMAGE_SIZE: + g_value_set_string (value, priv->image_size); + break; + case PROP_TAG: + g_value_set_string (value, priv->tag); + break; + case PROP_LOCATION: + g_value_set_string (value, priv->location); + break; + default: + /* We don't have any other property... */ + G_OBJECT_WARN_INVALID_PROPERTY_ID (object, property_id, pspec); + break; + } +} + +static void +gdata_picasaweb_query_set_property (GObject *object, guint property_id, const GValue *value, GParamSpec *pspec) +{ + GDataPicasaWebQuery *self = GDATA_PICASAWEB_QUERY (object); + + switch (property_id) { + case PROP_VISIBILITY: + gdata_picasaweb_query_set_visibility (self, g_value_get_int (value)); + break; + case PROP_THUMBNAIL_SIZE: + gdata_picasaweb_query_set_thumbnail_size (self, g_value_get_string (value)); + break; + case PROP_IMAGE_SIZE: + gdata_picasaweb_query_set_image_size (self, g_value_get_string (value)); + break; + case PROP_TAG: + gdata_picasaweb_query_set_tag (self, g_value_get_string (value)); + break; + case PROP_LOCATION: + gdata_picasaweb_query_set_location (self, g_value_get_string (value)); + break; + default: + /* We don't have any other property... */ + G_OBJECT_WARN_INVALID_PROPERTY_ID (object, property_id, pspec); + break; + } +} + +static void +get_query_uri (GDataQuery *self, const gchar *feed_uri, GString *query_uri, gboolean *params_started) +{ + GDataPicasaWebQueryPrivate *priv = GDATA_PICASAWEB_QUERY (self)->priv; + + #define APPEND_SEP g_string_append_c (query_uri, (*params_started == FALSE) ? '?' : '&'); *params_started = TRUE; + + /* Chain up to the parent class */ + GDATA_QUERY_CLASS (gdata_picasaweb_query_parent_class)->get_query_uri (self, feed_uri, query_uri, params_started); + + APPEND_SEP + if (priv->visibility == 0) + ; // Appending nothing to retrieve all for authenticated users and just public albums for unauthenticated + else if (priv->visibility == GDATA_PICASAWEB_PUBLIC) + g_string_append (query_uri, "access=public"); + else if (priv->visibility == GDATA_PICASAWEB_PRIVATE) + g_string_append (query_uri, "access=private"); + else + g_assert_not_reached (); + + if (priv->thumbnail_size != NULL) { + APPEND_SEP + g_string_append (query_uri, "thumbsize="); + g_string_append_uri_escaped (query_uri, priv->thumbnail_size, NULL, FALSE); + } + + if (priv->image_size != NULL) { + APPEND_SEP + g_string_append (query_uri, "imgmax="); + g_string_append_uri_escaped (query_uri, priv->image_size, NULL, FALSE); + } + + if (priv->tag != NULL) { + APPEND_SEP + g_string_append (query_uri, "tag="); + g_string_append_uri_escaped (query_uri, priv->tag, NULL, FALSE); + } + + if (priv->bounding_box.north != priv->bounding_box.south && priv->bounding_box.east != priv->bounding_box.west) { + gchar west[G_ASCII_DTOSTR_BUF_SIZE], south[G_ASCII_DTOSTR_BUF_SIZE], east[G_ASCII_DTOSTR_BUF_SIZE], north[G_ASCII_DTOSTR_BUF_SIZE]; + + APPEND_SEP + g_string_append_printf (query_uri, "bbox=%s,%s,%s,%s", + g_ascii_dtostr (west, sizeof (west), priv->bounding_box.west), + g_ascii_dtostr (south, sizeof (south), priv->bounding_box.south), + g_ascii_dtostr (east, sizeof (east), priv->bounding_box.east), + g_ascii_dtostr (north, sizeof (north), priv->bounding_box.north)); + } + + if (priv->location != NULL) { + APPEND_SEP + g_string_append (query_uri, "l="); + g_string_append_uri_escaped (query_uri, priv->location, NULL, FALSE); + } +} + +/** + * gdata_picasaweb_query_new: + * @q: (allow-none): a query string, or %NULL + * + * Creates a new #GDataPicasaWebQuery with its #GDataQuery:q property set to @q. + * + * Note that when querying for albums with gdata_picasaweb_service_query_all_albums(), the @q parameter cannot be used. + * + * Return value: a new #GDataPicasaWebQuery + * + * Since: 0.4.0 + */ +GDataPicasaWebQuery * +gdata_picasaweb_query_new (const gchar *q) +{ + return g_object_new (GDATA_TYPE_PICASAWEB_QUERY, "q", q, NULL); +} + +/** + * gdata_picasaweb_query_new_with_limits: + * @q: (allow-none): a query string, or %NULL + * @start_index: the index of the first result to include, or 0 + * @max_results: the maximum number of results to include, or 0 + * + * Creates a #GDataPicasaWebQuery with its #GDataQuery:q property set to @q, returning @max_results starting from the @start_indexth result. + * + * Note that when querying for albums with gdata_picasaweb_service_query_all_albums(), the @q parameter cannot be used. + * + * This is useful for paging through results, but the result set between separate queries may change. So, if you use this to + * request the next ten results after a previous query, it may include some of the previously returned results if their order changed, or + * omit ones that would have otherwise been found in a earlier but larger query. + * + * Return value: a new #GDataPicasaWebQuery + * + * Since: 0.6.0 + */ +GDataPicasaWebQuery * +gdata_picasaweb_query_new_with_limits (const gchar *q, guint start_index, guint max_results) +{ + return g_object_new (GDATA_TYPE_PICASAWEB_QUERY, + "q", q, + "start-index", start_index, + "max-results", max_results, + NULL); +} + +/** + * gdata_picasaweb_query_get_visibility: + * @self: a #GDataPicasaWebQuery + * + * Gets the #GDataPicasaWebQuery:visibility property. + * + * Return value: the visibility of the objects to retrieve, or 0 to retrieve all objects + * + * Since: 0.4.0 + */ +GDataPicasaWebVisibility +gdata_picasaweb_query_get_visibility (GDataPicasaWebQuery *self) +{ + g_return_val_if_fail (GDATA_IS_PICASAWEB_QUERY (self), 0); + return self->priv->visibility; +} + +/** + * gdata_picasaweb_query_set_visibility: + * @self: a #GDataPicasaWebQuery + * @visibility: the visibility of the objects to retrieve, or 0 to retrieve all objects + * + * Sets the #GDataPicasaWebQuery:visibility property to @visibility. + * + * Since: 0.4.0 + */ +void +gdata_picasaweb_query_set_visibility (GDataPicasaWebQuery *self, GDataPicasaWebVisibility visibility) +{ + g_return_if_fail (GDATA_IS_PICASAWEB_QUERY (self)); + self->priv->visibility = visibility; + g_object_notify (G_OBJECT (self), "visibility"); + + /* Our current ETag will no longer be relevant */ + gdata_query_set_etag (GDATA_QUERY (self), NULL); +} + +/** + * gdata_picasaweb_query_get_thumbnail_size: + * @self: a #GDataPicasaWebQuery + * + * Gets the #GDataPicasaWebQuery:thumbnail-size property. + * + * Return value: a comma-separated list of thumbnail sizes to retrieve, or %NULL + * + * Since: 0.4.0 + */ +const gchar * +gdata_picasaweb_query_get_thumbnail_size (GDataPicasaWebQuery *self) +{ + g_return_val_if_fail (GDATA_IS_PICASAWEB_QUERY (self), NULL); + return self->priv->thumbnail_size; +} + +/** + * gdata_picasaweb_query_set_thumbnail_size: + * @self: a #GDataPicasaWebQuery + * @thumbnail_size: (allow-none): a comma-separated list of thumbnail sizes to retrieve, or %NULL + * + * Sets the #GDataPicasaWebQuery:thumbnail-size property to @thumbnail_size. + * + * Set @thumbnail_size to %NULL to unset the property. + * + * Since: 0.4.0 + */ +void +gdata_picasaweb_query_set_thumbnail_size (GDataPicasaWebQuery *self, const gchar *thumbnail_size) +{ + g_return_if_fail (GDATA_IS_PICASAWEB_QUERY (self)); + + g_free (self->priv->thumbnail_size); + self->priv->thumbnail_size = g_strdup (thumbnail_size); + g_object_notify (G_OBJECT (self), "thumbnail-size"); + + /* Our current ETag will no longer be relevant */ + gdata_query_set_etag (GDATA_QUERY (self), NULL); +} + +/** + * gdata_picasaweb_query_get_image_size: + * @self: a #GDataPicasaWebQuery + * + * Gets the #GDataPicasaWebQuery:image-size property. + * + * Return value: the currently set desired image size for retrieval, or %NULL + * + * Since: 0.4.0 + */ +const gchar * +gdata_picasaweb_query_get_image_size (GDataPicasaWebQuery *self) +{ + g_return_val_if_fail (GDATA_IS_PICASAWEB_QUERY (self), NULL); + return self->priv->image_size; +} + +/** + * gdata_picasaweb_query_set_image_size: + * @self: a #GDataPicasaWebQuery + * @image_size: (allow-none): the desired size of the image to be retrieved, or %NULL + * + * Sets the #GDataPicasaWebQuery:image-size property to @image_size. + * Valid sizes are described in the + * online documentation. + * + * Set @image_size to %NULL to unset the property. + * + * Since: 0.4.0 + */ +void +gdata_picasaweb_query_set_image_size (GDataPicasaWebQuery *self, const gchar *image_size) +{ + g_return_if_fail (GDATA_IS_PICASAWEB_QUERY (self)); + + g_free (self->priv->image_size); + self->priv->image_size = g_strdup (image_size); + g_object_notify (G_OBJECT (self), "image-size"); + + /* Our current ETag will no longer be relevant */ + gdata_query_set_etag (GDATA_QUERY (self), NULL); +} + +/** + * gdata_picasaweb_query_get_tag: + * @self: a #GDataPicasaWebQuery + * + * Gets the #GDataPicasaWebQuery:tag property. + * + * Return value: a tag which retrieved objects must have, or %NULL + * + * Since: 0.4.0 + */ +const gchar * +gdata_picasaweb_query_get_tag (GDataPicasaWebQuery *self) +{ + g_return_val_if_fail (GDATA_IS_PICASAWEB_QUERY (self), NULL); + return self->priv->tag; +} + +/** + * gdata_picasaweb_query_set_tag: + * @self: a #GDataPicasaWebQuery + * @tag: (allow-none): a tag which retrieved objects must have, or %NULL + * + * Sets the #GDataPicasaWebQuery:tag property to @tag. + * + * Set @tag to %NULL to unset the property. + * + * Since: 0.4.0 + */ +void +gdata_picasaweb_query_set_tag (GDataPicasaWebQuery *self, const gchar *tag) +{ + g_return_if_fail (GDATA_IS_PICASAWEB_QUERY (self)); + + g_free (self->priv->tag); + self->priv->tag = g_strdup (tag); + g_object_notify (G_OBJECT (self), "tag"); + + /* Our current ETag will no longer be relevant */ + gdata_query_set_etag (GDATA_QUERY (self), NULL); +} + +/** + * gdata_picasaweb_query_get_bounding_box: + * @self: a #GDataPicasaWebQuery + * @north: (out caller-allocates) (allow-none): return location for the latitude of the top of the box, or %NULL + * @east: (out caller-allocates) (allow-none): return location for the longitude of the right of the box, or %NULL + * @south: (out caller-allocates) (allow-none): return location for the latitude of the south of the box, or %NULL + * @west: (out caller-allocates) (allow-none): return location for the longitude of the left of the box, or %NULL + * + * Gets the latitudes and longitudes of a bounding box, inside which all the results must lie. + * + * Since: 0.4.0 + */ +void +gdata_picasaweb_query_get_bounding_box (GDataPicasaWebQuery *self, gdouble *north, gdouble *east, gdouble *south, gdouble *west) +{ + g_return_if_fail (GDATA_IS_PICASAWEB_QUERY (self)); + + if (north != NULL) + *north = self->priv->bounding_box.north; + if (east != NULL) + *east = self->priv->bounding_box.east; + if (south != NULL) + *south = self->priv->bounding_box.south; + if (west != NULL) + *west = self->priv->bounding_box.west; +} + +/** + * gdata_picasaweb_query_set_bounding_box: + * @self: a #GDataPicasaWebQuery + * @north: latitude of the top of the box + * @east: longitude of the right of the box + * @south: latitude of the bottom of the box + * @west: longitude of the left of the box + * + * Sets a bounding box, inside which all the returned results must lie. + * + * Set @north, @east, @south and @west to 0 to unset the property. + * + * Since: 0.4.0 + */ +void +gdata_picasaweb_query_set_bounding_box (GDataPicasaWebQuery *self, gdouble north, gdouble east, gdouble south, gdouble west) +{ + g_return_if_fail (GDATA_IS_PICASAWEB_QUERY (self)); + g_return_if_fail (north >= -90.0 && north <= 90.0); + g_return_if_fail (south >= -90.0 && south <= 90.0); + g_return_if_fail (east >= -180.0 && east <= 180.0); + g_return_if_fail (west >= -180.0 && west <= 180.0); + + self->priv->bounding_box.north = north; + self->priv->bounding_box.east = east; + self->priv->bounding_box.south = south; + self->priv->bounding_box.west = west; + + /* Our current ETag will no longer be relevant */ + gdata_query_set_etag (GDATA_QUERY (self), NULL); +} + +/** + * gdata_picasaweb_query_get_location: + * @self: a #GDataPicasaWebQuery + * + * Gets the #GDataPicasaWebQuery:location property. + * + * Return value: a location which returned objects must be near, or %NULL + * + * Since: 0.4.0 + */ +const gchar * +gdata_picasaweb_query_get_location (GDataPicasaWebQuery *self) +{ + g_return_val_if_fail (GDATA_IS_PICASAWEB_QUERY (self), NULL); + return self->priv->location; +} + +/** + * gdata_picasaweb_query_set_location: + * @self: a #GDataPicasaWebQuery + * @location: (allow-none): a location which returned objects must be near, or %NULL + * + * Sets the #GDataPicasaWebQuery:location property to @location. + * + * Set @location to %NULL to unset the property. + * + * Since: 0.4.0 + */ +void +gdata_picasaweb_query_set_location (GDataPicasaWebQuery *self, const gchar *location) +{ + g_return_if_fail (GDATA_IS_PICASAWEB_QUERY (self)); + + g_free (self->priv->location); + self->priv->location = g_strdup (location); + g_object_notify (G_OBJECT (self), "location"); + + /* Our current ETag will no longer be relevant */ + gdata_query_set_etag (GDATA_QUERY (self), NULL); +} diff --git a/gdata/services/picasaweb/gdata-picasaweb-query.h b/gdata/services/picasaweb/gdata-picasaweb-query.h new file mode 100644 index 0000000..8c9492f --- /dev/null +++ b/gdata/services/picasaweb/gdata-picasaweb-query.h @@ -0,0 +1,92 @@ +/* -*- Mode: C; indent-tabs-mode: t; c-basic-offset: 8; tab-width: 8 -*- */ +/* + * GData Client + * Copyright (C) Richard Schwarting 2009 + * Copyright (C) Philip Withnall 2009 + * + * GData Client is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * GData Client is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with GData Client. If not, see . + */ + +#ifndef GDATA_PICASAWEB_QUERY_H +#define GDATA_PICASAWEB_QUERY_H + +#include +#include + +#include +#include + +G_BEGIN_DECLS + +#define GDATA_TYPE_PICASAWEB_QUERY (gdata_picasaweb_query_get_type ()) +#define GDATA_PICASAWEB_QUERY(o) (G_TYPE_CHECK_INSTANCE_CAST ((o), GDATA_TYPE_PICASAWEB_QUERY, GDataPicasaWebQuery)) +#define GDATA_PICASAWEB_QUERY_CLASS(k) (G_TYPE_CHECK_CLASS_CAST((k), GDATA_TYPE_PICASAWEB_QUERY, GDataPicasawebQueryClass)) +#define GDATA_IS_PICASAWEB_QUERY(o) (G_TYPE_CHECK_INSTANCE_TYPE ((o), GDATA_TYPE_PICASAWEB_QUERY)) +#define GDATA_IS_PICASAWEB_QUERY_CLASS(k) (G_TYPE_CHECK_CLASS_TYPE ((k), GDATA_TYPE_PICASAWEB_QUERY)) +#define GDATA_PICASAWEB_QUERY_GET_CLASS(o) (G_TYPE_INSTANCE_GET_CLASS ((o), GDATA_TYPE_PICASAWEB_QUERY, GDataPicasawebQueryClass)) + +typedef struct _GDataPicasaWebQueryPrivate GDataPicasaWebQueryPrivate; + +/** + * GDataPicasaWebQuery: + * + * All the fields in the #GDataPicasaWebQuery structure are private and should never be accessed directly. + * + * Since: 0.4.0 + */ +typedef struct { + GDataQuery parent; + GDataPicasaWebQueryPrivate *priv; +} GDataPicasaWebQuery; + +/** + * GDataPicasaWebQueryClass: + * + * All the fields in the #GDataPicasaWebQueryClass structure are private and should never be accessed directly. + * + * Since: 0.4.0 + */ +typedef struct { + /*< private >*/ + GDataQueryClass parent; + + /*< private >*/ + /* Padding for future expansion */ + void (*_g_reserved0) (void); + void (*_g_reserved1) (void); +} GDataPicasaWebQueryClass; + +GType gdata_picasaweb_query_get_type (void) G_GNUC_CONST; +G_DEFINE_AUTOPTR_CLEANUP_FUNC (GDataPicasaWebQuery, g_object_unref) + +GDataPicasaWebQuery *gdata_picasaweb_query_new (const gchar *q) G_GNUC_WARN_UNUSED_RESULT G_GNUC_MALLOC; +GDataPicasaWebQuery *gdata_picasaweb_query_new_with_limits (const gchar *q, + guint start_index, guint max_results) G_GNUC_WARN_UNUSED_RESULT G_GNUC_MALLOC; + +GDataPicasaWebVisibility gdata_picasaweb_query_get_visibility (GDataPicasaWebQuery *self) G_GNUC_PURE; +void gdata_picasaweb_query_set_visibility (GDataPicasaWebQuery *self, GDataPicasaWebVisibility visibility); +const gchar *gdata_picasaweb_query_get_thumbnail_size (GDataPicasaWebQuery *self) G_GNUC_PURE; +void gdata_picasaweb_query_set_thumbnail_size (GDataPicasaWebQuery *self, const gchar *thumbnail_size); +const gchar *gdata_picasaweb_query_get_image_size (GDataPicasaWebQuery *self) G_GNUC_PURE; +void gdata_picasaweb_query_set_image_size (GDataPicasaWebQuery *self, const gchar *image_size); +const gchar *gdata_picasaweb_query_get_tag (GDataPicasaWebQuery *self) G_GNUC_PURE; +void gdata_picasaweb_query_set_tag (GDataPicasaWebQuery *self, const gchar *tag); +void gdata_picasaweb_query_get_bounding_box (GDataPicasaWebQuery *self, gdouble *north, gdouble *east, gdouble *south, gdouble *west); +void gdata_picasaweb_query_set_bounding_box (GDataPicasaWebQuery *self, gdouble north, gdouble east, gdouble south, gdouble west); +const gchar *gdata_picasaweb_query_get_location (GDataPicasaWebQuery *self) G_GNUC_PURE; +void gdata_picasaweb_query_set_location (GDataPicasaWebQuery *self, const gchar *location); + +G_END_DECLS + +#endif /* !GDATA_PICASAWEB_QUERY_H */ diff --git a/gdata/services/picasaweb/gdata-picasaweb-service.c b/gdata/services/picasaweb/gdata-picasaweb-service.c new file mode 100644 index 0000000..89dcd7a --- /dev/null +++ b/gdata/services/picasaweb/gdata-picasaweb-service.c @@ -0,0 +1,741 @@ +/* -*- Mode: C; indent-tabs-mode: t; c-basic-offset: 8; tab-width: 8 -*- */ +/* + * GData Client + * Copyright (C) Richard Schwarting 2009 + * Copyright (C) Philip Withnall 2009–2010 + * + * GData Client is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * GData Client is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with GData Client. If not, see . + */ + +/** + * SECTION:gdata-picasaweb-service + * @short_description: GData PicasaWeb service object + * @stability: Stable + * @include: gdata/services/picasaweb/gdata-picasaweb-service.h + * + * #GDataPicasaWebService is a subclass of #GDataService for communicating with the GData API of Google PicasaWeb. It supports querying for files + * and albums, and uploading files. + * + * For more details of PicasaWeb's GData API, see the + * online documentation. + * + * + * Authenticating and Creating a New Album + * + * GDataClientLoginAuthorizer *authorizer; + * GDataPicasaWebService *service; + * GDataPicasaWebAlbum *album, *inserted_album; + * + * /* Create a service object and authorize against the PicasaWeb service */ + * authorizer = gdata_client_login_authorizer_new ("companyName-applicationName-versionID", GDATA_TYPE_PICASAWEB_SERVICE); + * gdata_client_login_authorizer_authenticate (authorizer, username, password, NULL, NULL); + * service = gdata_picasaweb_service_new (GDATA_AUTHORIZER (authorizer)); + * + * /* Create a GDataPicasaWebAlbum entry for the new album, setting some information about it */ + * album = gdata_picasaweb_album_new (NULL); + * gdata_entry_set_title (GDATA_ENTRY (album), "Photos from the Rhine"); + * gdata_entry_set_summary (GDATA_ENTRY (album), "An album of our adventures on the great river."); + * gdata_picasaweb_album_set_location (album, "The Rhine, Germany"); + * + * /* Insert the new album on the server. Note that this is a blocking operation. */ + * inserted_album = gdata_picasaweb_service_insert_album (service, album, NULL, NULL); + * + * g_object_unref (album); + * g_object_unref (inserted_album); + * g_object_unref (service); + * g_object_unref (authorizer); + * + * + * + * + * Uploading a Photo or Video + * + * GDataPicasaWebFile *file_entry, *uploaded_file_entry; + * GDataUploadStream *upload_stream; + * GFile *file_data; + * GFileInfo *file_info; + * GFileInputStream *file_stream; + * + * /* Specify the GFile image on disk to upload */ + * file_data = g_file_new_for_path (path); + * + * /* Get the file information for the file being uploaded. If another data source was being used for the upload, it would have to + * * provide an appropriate slug and content type. Note that this is a blocking operation. */ + * file_info = g_file_query_info (file_data, G_FILE_ATTRIBUTE_STANDARD_DISPLAY_NAME "," G_FILE_ATTRIBUTE_STANDARD_CONTENT_TYPE, + * G_FILE_QUERY_INFO_NONE, NULL, NULL); + * + * /* Create a GDataPicasaWebFile entry for the image, setting a title and caption/summary */ + * file_entry = gdata_picasaweb_file_new (NULL); + * gdata_entry_set_title (GDATA_ENTRY (file_entry), "Black Cat"); + * gdata_entry_set_summary (GDATA_ENTRY (file_entry), "Photo of the world's most beautiful cat."); + * + * /* Create an upload stream for the file. This is non-blocking. */ + * upload_stream = gdata_picasaweb_service_upload_file (service, album, file_entry, g_file_info_get_display_name (file_info), + * g_file_info_get_content_type (file_info), NULL, NULL); + * g_object_unref (file_info); + * g_object_unref (file_entry); + * + * /* Prepare a file stream for the file to be uploaded. This is a blocking operation. */ + * file_stream = g_file_read (file_data, NULL, NULL); + * g_object_unref (file_data); + * + * /* Upload the file to the server. Note that this is a blocking operation. */ + * g_output_stream_splice (G_OUTPUT_STREAM (upload_stream), G_INPUT_STREAM (file_stream), + * G_OUTPUT_STREAM_SPLICE_CLOSE_SOURCE | G_OUTPUT_STREAM_SPLICE_CLOSE_TARGET, NULL, NULL); + * + * /* Parse the resulting updated entry. This is a non-blocking operation. */ + * uploaded_file_entry = gdata_picasaweb_service_finish_file_upload (service, upload_stream, NULL); + * g_object_unref (file_stream); + * g_object_unref (upload_stream); + * + * /* ... */ + * + * g_object_unref (uploaded_file_entry); + * + * + * + * + * Since: 0.4.0 + */ + +#include +#include +#include + +#include "gdata-service.h" +#include "gdata-picasaweb-service.h" +#include "gdata-private.h" +#include "gdata-parser.h" +#include "atom/gdata-link.h" +#include "gdata-upload-stream.h" +#include "gdata-picasaweb-feed.h" + +static GList *get_authorization_domains (void); + +_GDATA_DEFINE_AUTHORIZATION_DOMAIN (picasaweb, "lh2", "http://picasaweb.google.com/data/") +G_DEFINE_TYPE (GDataPicasaWebService, gdata_picasaweb_service, GDATA_TYPE_SERVICE) + +static void +gdata_picasaweb_service_class_init (GDataPicasaWebServiceClass *klass) +{ + GDataServiceClass *service_class = GDATA_SERVICE_CLASS (klass); + service_class->feed_type = GDATA_TYPE_PICASAWEB_FEED; + service_class->get_authorization_domains = get_authorization_domains; +} + +static void +gdata_picasaweb_service_init (GDataPicasaWebService *self) +{ + /* Nothing to see here */ +} + +static GList * +get_authorization_domains (void) +{ + return g_list_prepend (NULL, get_picasaweb_authorization_domain ()); +} + +/** + * gdata_picasaweb_service_new: + * @authorizer: (allow-none): a #GDataAuthorizer to authorize the service's requests, or %NULL + * + * Creates a new #GDataPicasaWebService using the given #GDataAuthorizer. If @authorizer is %NULL, all requests are made as an unauthenticated user. + * + * Return value: a new #GDataPicasaWebService, or %NULL; unref with g_object_unref() + * + * Since: 0.9.0 + */ +GDataPicasaWebService * +gdata_picasaweb_service_new (GDataAuthorizer *authorizer) +{ + g_return_val_if_fail (authorizer == NULL || GDATA_IS_AUTHORIZER (authorizer), NULL); + + return g_object_new (GDATA_TYPE_PICASAWEB_SERVICE, + "authorizer", authorizer, + NULL); +} + +/** + * gdata_picasaweb_service_get_primary_authorization_domain: + * + * The primary #GDataAuthorizationDomain for interacting with PicasaWeb. This will not normally need to be used, as it's used internally + * by the #GDataPicasaWebService methods. However, if using the plain #GDataService methods to implement custom queries or requests which libgdata + * does not support natively, then this domain may be needed to authorize the requests. + * + * The domain never changes, and is interned so that pointer comparison can be used to differentiate it from other authorization domains. + * + * Return value: (transfer none): the service's authorization domain + * + * Since: 0.9.0 + */ +GDataAuthorizationDomain * +gdata_picasaweb_service_get_primary_authorization_domain (void) +{ + return get_picasaweb_authorization_domain (); +} + +/* + * create_uri: + * @self: a #GDataPicasaWebService + * @username: (allow-none): the username to use, or %NULL to use the currently logged in user + * @type: the type of object to access: "entry" for a user, or "feed" for an album + * + * Builds a URI to use when querying for albums or a user. + * + * Return value: a constructed URI; free with g_free() + * + * Since: 0.4.0 + */ +static gchar * +create_uri (GDataPicasaWebService *self, const gchar *username, const gchar *type) +{ + if (username == NULL) { + /* Ensure we're authorized first */ + if (gdata_authorizer_is_authorized_for_domain (gdata_service_get_authorizer (GDATA_SERVICE (self)), + get_picasaweb_authorization_domain ()) == FALSE) { + return NULL; + } + + /* Querying Picasa albums for the "default" user when logged in returns the albums for the authenticated user */ + username = "default"; + } + + return _gdata_service_build_uri ("https://picasaweb.google.com/data/%s/api/user/%s", type, username); +} + +/** + * gdata_picasaweb_service_get_user: + * @self: a #GDataPicasaWebService + * @username: (allow-none): the username of the user whose information you wish to retrieve, or %NULL for the currently authenticated user. + * @cancellable: (allow-none): optional #GCancellable object, or %NULL + * @error: a #GError, or %NULL + * + * Queries the service to return the user specified by @username. + * + * Return value: (transfer full): a #GDataPicasaWebUser; unref with g_object_unref() + * + * Since: 0.6.0 + */ +GDataPicasaWebUser * +gdata_picasaweb_service_get_user (GDataPicasaWebService *self, const gchar *username, GCancellable *cancellable, GError **error) +{ + gchar *uri; + GDataParsable *user; + SoupMessage *message; + + g_return_val_if_fail (GDATA_IS_PICASAWEB_SERVICE (self), NULL); + g_return_val_if_fail (cancellable == NULL || G_IS_CANCELLABLE (cancellable), NULL); + g_return_val_if_fail (error == NULL || *error == NULL, NULL); + + uri = create_uri (self, username, "entry"); + if (uri == NULL) { + g_set_error_literal (error, GDATA_SERVICE_ERROR, GDATA_SERVICE_ERROR_AUTHENTICATION_REQUIRED, + _("You must specify a username or be authenticated to query a user.")); + return NULL; + } + + message = _gdata_service_query (GDATA_SERVICE (self), get_picasaweb_authorization_domain (), uri, NULL, cancellable, error); + g_free (uri); + + if (message == NULL) + return NULL; + + g_assert (message->response_body->data != NULL); + user = gdata_parsable_new_from_xml (GDATA_TYPE_PICASAWEB_USER, message->response_body->data, message->response_body->length, error); + g_object_unref (message); + + return GDATA_PICASAWEB_USER (user); +} + +static void +get_user_thread (GTask *task, gpointer source_object, gpointer task_data, GCancellable *cancellable) +{ + GDataPicasaWebService *service = GDATA_PICASAWEB_SERVICE (source_object); + const gchar *username = task_data; + g_autoptr(GDataPicasaWebUser) user = NULL; + g_autoptr(GError) error = NULL; + + /* Get the user and return */ + user = gdata_picasaweb_service_get_user (service, username, cancellable, &error); + + if (error != NULL) + g_task_return_error (task, g_steal_pointer (&error)); + else + g_task_return_pointer (task, g_steal_pointer (&user), g_object_unref); +} + +/** + * gdata_picasaweb_service_get_user_async: + * @self: a #GDataPicasaWebService + * @username: (allow-none): the username of the user whose information you wish to retrieve, or %NULL for the currently authenticated user + * @cancellable: (allow-none): optional #GCancellable object, or %NULL + * @callback: a #GAsyncReadyCallback to call when the query is finished + * @user_data: (closure): data to pass to the @callback function + * + * Queries the service to return the user specified by @username. + * + * For more details, see gdata_picasaweb_service_get_user() which is the synchronous version of this method. + * + * When the operation is finished, @callback will be called. You can then call gdata_picasaweb_service_get_user_finish() to get the results of the + * operation. + * + * Since: 0.9.1 + */ +void +gdata_picasaweb_service_get_user_async (GDataPicasaWebService *self, const gchar *username, GCancellable *cancellable, + GAsyncReadyCallback callback, gpointer user_data) +{ + g_autoptr(GTask) task = NULL; + + g_return_if_fail (GDATA_IS_PICASAWEB_SERVICE (self)); + g_return_if_fail (cancellable == NULL || G_IS_CANCELLABLE (cancellable)); + g_return_if_fail (callback != NULL); + + task = g_task_new (self, cancellable, callback, user_data); + g_task_set_source_tag (task, gdata_picasaweb_service_get_user_async); + g_task_set_task_data (task, g_strdup (username), (GDestroyNotify) g_free); + g_task_run_in_thread (task, get_user_thread); +} + +/** + * gdata_picasaweb_service_get_user_finish: + * @self: a #GDataPicasaWebService + * @result: a #GAsyncResult + * @error: a #GError, or %NULL + * + * Finishes an asynchronous user retrieval operation started with gdata_picasaweb_service_get_user_async(). + * + * Return value: (transfer full): a #GDataPicasaWebUser; unref with g_object_unref() + * + * Since: 0.9.1 + */ +GDataPicasaWebUser * +gdata_picasaweb_service_get_user_finish (GDataPicasaWebService *self, GAsyncResult *async_result, GError **error) +{ + g_return_val_if_fail (GDATA_IS_PICASAWEB_SERVICE (self), NULL); + g_return_val_if_fail (G_IS_ASYNC_RESULT (async_result), NULL); + g_return_val_if_fail (error == NULL || *error == NULL, NULL); + g_return_val_if_fail (g_task_is_valid (async_result, self), NULL); + g_return_val_if_fail (g_async_result_is_tagged (async_result, gdata_picasaweb_service_get_user_async), NULL); + + return g_task_propagate_pointer (G_TASK (async_result), error); +} + +/** + * gdata_picasaweb_service_query_all_albums: + * @self: a #GDataPicasaWebService + * @query: (allow-none): a #GDataQuery with the query parameters, or %NULL + * @username: (allow-none): the username of the user whose albums you wish to retrieve, or %NULL + * @cancellable: (allow-none): optional #GCancellable object, or %NULL + * @progress_callback: (allow-none) (scope call) (closure progress_user_data): a #GDataQueryProgressCallback to call when an entry is loaded, or %NULL + * @progress_user_data: (closure): data to pass to the @progress_callback function + * @error: a #GError, or %NULL + * + * Queries the service to return a list of all albums belonging to the specified @username which match the given + * @query. If a user is authenticated with the service, @username can be set as %NULL to return a list of albums belonging + * to the currently-authenticated user. + * + * Note that the #GDataQuery:q query parameter cannot be set on @query for album queries. + * + * For more details, see gdata_service_query(). + * + * Return value: (transfer full): a #GDataFeed of query results; unref with g_object_unref() + * + * Since: 0.4.0 + */ +GDataFeed * +gdata_picasaweb_service_query_all_albums (GDataPicasaWebService *self, GDataQuery *query, const gchar *username, GCancellable *cancellable, + GDataQueryProgressCallback progress_callback, gpointer progress_user_data, GError **error) +{ + gchar *uri; + GDataFeed *album_feed; + + g_return_val_if_fail (GDATA_IS_PICASAWEB_SERVICE (self), NULL); + g_return_val_if_fail (query == NULL || GDATA_IS_QUERY (query), NULL); + g_return_val_if_fail (cancellable == NULL || G_IS_CANCELLABLE (cancellable), NULL); + g_return_val_if_fail (error == NULL || *error == NULL, NULL); + + if (query != NULL && gdata_query_get_q (query) != NULL) { + /* Bug #593336 — Query parameter "q=..." isn't valid for album kinds */ + g_set_error_literal (error, GDATA_SERVICE_ERROR, GDATA_SERVICE_ERROR_BAD_QUERY_PARAMETER, + _("Query parameter not allowed for albums.")); + return NULL; + } + + uri = create_uri (self, username, "feed"); + if (uri == NULL) { + g_set_error_literal (error, GDATA_SERVICE_ERROR, GDATA_SERVICE_ERROR_AUTHENTICATION_REQUIRED, + _("You must specify a username or be authenticated to query all albums.")); + return NULL; + } + + /* Execute the query */ + album_feed = gdata_service_query (GDATA_SERVICE (self), get_picasaweb_authorization_domain (), uri, query, GDATA_TYPE_PICASAWEB_ALBUM, + cancellable, progress_callback, progress_user_data, error); + g_free (uri); + + return album_feed; +} + +/** + * gdata_picasaweb_service_query_all_albums_async: + * @self: a #GDataPicasaWebService + * @query: (allow-none): a #GDataQuery with the query parameters, or %NULL + * @username: (allow-none): the username of the user whose albums you wish to retrieve, or %NULL + * @cancellable: (allow-none): optional #GCancellable object, or %NULL + * @progress_callback: (allow-none) (closure progress_user_data): a #GDataQueryProgressCallback to call when an entry is loaded, or %NULL + * @progress_user_data: (closure): data to pass to the @progress_callback function + * @destroy_progress_user_data: (allow-none): the function to call when @progress_callback will not be called any more, or %NULL. This function will be + * called with @progress_user_data as a parameter and can be used to free any memory allocated for it. + * @callback: a #GAsyncReadyCallback to call when authentication is finished + * @user_data: (closure): data to pass to the @callback function + * + * Queries the service to return a list of all albums belonging to the specified @username which match the given + * @query. @self, @query and @username are all reffed/copied when this function is called, so can safely be unreffed/freed after + * this function returns. + * + * For more details, see gdata_picasaweb_service_query_all_albums(), which is the synchronous version of + * this function, and gdata_service_query_async(), which is the base asynchronous query function. + * + * Since: 0.9.1 + */ +void +gdata_picasaweb_service_query_all_albums_async (GDataPicasaWebService *self, GDataQuery *query, const gchar *username, + GCancellable *cancellable, GDataQueryProgressCallback progress_callback, gpointer progress_user_data, + GDestroyNotify destroy_progress_user_data, GAsyncReadyCallback callback, gpointer user_data) +{ + gchar *uri; + + g_return_if_fail (GDATA_IS_PICASAWEB_SERVICE (self)); + g_return_if_fail (query == NULL || GDATA_IS_QUERY (query)); + g_return_if_fail (cancellable == NULL || G_IS_CANCELLABLE (cancellable)); + g_return_if_fail (callback != NULL); + + if (query != NULL && gdata_query_get_q (query) != NULL) { + /* Bug #593336 — Query parameter "q=..." isn't valid for album kinds */ + g_autoptr(GTask) task = NULL; + + task = g_task_new (self, cancellable, callback, user_data); + g_task_set_source_tag (task, gdata_service_query_async); + g_task_return_new_error (task, GDATA_SERVICE_ERROR, GDATA_SERVICE_ERROR_BAD_QUERY_PARAMETER, "%s", + _("Query parameter not allowed for albums.")); + + return; + } + + uri = create_uri (self, username, "feed"); + if (uri == NULL) { + g_autoptr(GTask) task = NULL; + + task = g_task_new (self, cancellable, callback, user_data); + g_task_set_source_tag (task, gdata_service_query_async); + g_task_return_new_error (task, GDATA_SERVICE_ERROR, GDATA_SERVICE_ERROR_AUTHENTICATION_REQUIRED, "%s", + _("You must specify a username or be authenticated to query all albums.")); + + return; + } + + /* Schedule the async query */ + gdata_service_query_async (GDATA_SERVICE (self), get_picasaweb_authorization_domain (), uri, query, GDATA_TYPE_PICASAWEB_ALBUM, cancellable, + progress_callback, progress_user_data, destroy_progress_user_data, callback, user_data); + g_free (uri); +} + +static const gchar * +get_query_files_uri (GDataPicasaWebAlbum *album, GError **error) +{ + if (album != NULL) { + GDataLink *_link = gdata_entry_look_up_link (GDATA_ENTRY (album), "http://schemas.google.com/g/2005#feed"); + if (_link == NULL) { + /* Error */ + g_set_error_literal (error, GDATA_SERVICE_ERROR, GDATA_SERVICE_ERROR_PROTOCOL_ERROR, + _("The album did not have a feed link.")); + return NULL; + } + + return gdata_link_get_uri (_link); + } else { + /* Default URI */ + return "https://picasaweb.google.com/data/feed/api/user/default/albumid/default"; + } +} + +/** + * gdata_picasaweb_service_query_files: + * @self: a #GDataPicasaWebService + * @album: (allow-none): a #GDataPicasaWebAlbum from which to retrieve the files, or %NULL + * @query: (allow-none): a #GDataQuery with the query parameters, or %NULL + * @cancellable: (allow-none): optional #GCancellable object, or %NULL + * @progress_callback: (allow-none) (scope call) (closure progress_user_data): a #GDataQueryProgressCallback to call when an entry is loaded, or %NULL + * @progress_user_data: (closure): data to pass to the @progress_callback function + * @error: a #GError, or %NULL + * + * Queries the specified @album for a list of the files which match the given @query. If @album is %NULL and a user is + * authenticated with the service, the user's default album will be queried. + * + * For more details, see gdata_service_query(). + * + * Return value: (transfer full): a #GDataFeed of query results; unref with g_object_unref() + * + * Since: 0.4.0 + */ +GDataFeed * +gdata_picasaweb_service_query_files (GDataPicasaWebService *self, GDataPicasaWebAlbum *album, GDataQuery *query, GCancellable *cancellable, + GDataQueryProgressCallback progress_callback, gpointer progress_user_data, GError **error) +{ + const gchar *uri; + + g_return_val_if_fail (GDATA_IS_PICASAWEB_SERVICE (self), NULL); + g_return_val_if_fail (album == NULL || GDATA_IS_PICASAWEB_ALBUM (album), NULL); + g_return_val_if_fail (query == NULL || GDATA_IS_QUERY (query), NULL); + g_return_val_if_fail (cancellable == NULL || G_IS_CANCELLABLE (cancellable), NULL); + g_return_val_if_fail (error == NULL || *error == NULL, NULL); + + uri = get_query_files_uri (album, error); + if (uri == NULL) + return NULL; + + /* Execute the query */ + return gdata_service_query (GDATA_SERVICE (self), get_picasaweb_authorization_domain (), uri, GDATA_QUERY (query), GDATA_TYPE_PICASAWEB_FILE, + cancellable, progress_callback, progress_user_data, error); +} + +/** + * gdata_picasaweb_service_query_files_async: + * @self: a #GDataPicasaWebService + * @album: (allow-none): a #GDataPicasaWebAlbum from which to retrieve the files, or %NULL + * @query: (allow-none): a #GDataQuery with the query parameters, or %NULL + * @cancellable: (allow-none): optional #GCancellable object, or %NULL + * @progress_callback: (allow-none) (closure progress_user_data): a #GDataQueryProgressCallback to call when an entry is loaded, or %NULL + * @progress_user_data: (closure): data to pass to the @progress_callback function + * @destroy_progress_user_data: (allow-none): the function to call when @progress_callback will not be called any more, or %NULL. This function will be + * called with @progress_user_data as a parameter and can be used to free any memory allocated for it. + * @callback: a #GAsyncReadyCallback to call when the query is finished + * @user_data: (closure): data to pass to the @callback function + * + * Queries the specified @album for a list of the files which match the given @query. If @album is %NULL and a user is authenticated with the service, + * the user's default album will be queried. @self, @album and @query are all reffed when this function is called, so can safely be unreffed after + * this function returns. + * + * For more details, see gdata_picasaweb_service_query_files(), which is the synchronous version of this function, and gdata_service_query_async(), + * which is the base asynchronous query function. + * + * Since: 0.9.1 + */ +void +gdata_picasaweb_service_query_files_async (GDataPicasaWebService *self, GDataPicasaWebAlbum *album, GDataQuery *query, GCancellable *cancellable, + GDataQueryProgressCallback progress_callback, gpointer progress_user_data, + GDestroyNotify destroy_progress_user_data, GAsyncReadyCallback callback, gpointer user_data) +{ + const gchar *request_uri; + GError *child_error = NULL; + + g_return_if_fail (GDATA_IS_PICASAWEB_SERVICE (self)); + g_return_if_fail (album == NULL || GDATA_IS_PICASAWEB_ALBUM (album)); + g_return_if_fail (query == NULL || GDATA_IS_QUERY (query)); + g_return_if_fail (cancellable == NULL || G_IS_CANCELLABLE (cancellable)); + g_return_if_fail (callback != NULL); + + request_uri = get_query_files_uri (album, &child_error); + if (request_uri == NULL) { + g_task_report_error (self, callback, user_data, gdata_service_query_async, g_steal_pointer (&child_error)); + return; + } + + gdata_service_query_async (GDATA_SERVICE (self), get_picasaweb_authorization_domain (), request_uri, GDATA_QUERY (query), + GDATA_TYPE_PICASAWEB_FILE, cancellable, progress_callback, progress_user_data, destroy_progress_user_data, + callback, user_data); +} + +/** + * gdata_picasaweb_service_upload_file: + * @self: a #GDataPicasaWebService + * @album: (allow-none): a #GDataPicasaWebAlbum into which to insert the file, or %NULL + * @file_entry: a #GDataPicasaWebFile to insert + * @slug: the filename to give to the uploaded file + * @content_type: the content type of the uploaded data + * @cancellable: (allow-none): a #GCancellable for the entire upload stream, or %NULL + * @error: a #GError, or %NULL + * + * Uploads a file (photo or video) to the given PicasaWeb @album, using the metadata from @file and the file data written to the resulting + * #GDataUploadStream. If @album is %NULL, the file will be uploaded to the currently-authenticated user's "Drop Box" album. A user must be + * authenticated to use this function. + * + * If @file has already been inserted, a %GDATA_SERVICE_ERROR_ENTRY_ALREADY_INSERTED error will be returned. + * + * If no user is authenticated with the service, %GDATA_SERVICE_ERROR_AUTHENTICATION_REQUIRED will be returned. It is recommended to retry the + * upload after refreshing the authorization tokens held by the associated #GDataAuthorizer using gdata_authorizer_refresh_authorization(). + * + * The stream returned by this function should be written to using the standard #GOutputStream methods, asynchronously or synchronously. Once the stream + * is closed (using g_output_stream_close()), gdata_picasaweb_service_finish_file_upload() should be called on it to parse and return the updated + * #GDataPicasaWebFile for the uploaded file. This must be done, as @file_entry isn't updated in-place. + * + * In order to cancel the upload, a #GCancellable passed in to @cancellable must be cancelled using g_cancellable_cancel(). Cancelling the individual + * #GOutputStream operations on the #GDataUploadStream will not cancel the entire upload; merely the write or close operation in question. See the + * #GDataUploadStream:cancellable for more details. + * + * Any upload errors will be thrown by the stream methods, and may come from the #GDataServiceError domain. + * + * Return value: (transfer full): a #GDataUploadStream to write the file data to, or %NULL; unref with g_object_unref() + * + * Since: 0.8.0 + */ +GDataUploadStream * +gdata_picasaweb_service_upload_file (GDataPicasaWebService *self, GDataPicasaWebAlbum *album, GDataPicasaWebFile *file_entry, const gchar *slug, + const gchar *content_type, GCancellable *cancellable, GError **error) +{ + const gchar *album_id = NULL; + GDataUploadStream *upload_stream; + gchar *upload_uri; + + g_return_val_if_fail (GDATA_IS_PICASAWEB_SERVICE (self), NULL); + g_return_val_if_fail (album == NULL || GDATA_IS_PICASAWEB_ALBUM (album), NULL); + g_return_val_if_fail (GDATA_IS_PICASAWEB_FILE (file_entry), NULL); + g_return_val_if_fail (slug != NULL && *slug != '\0', NULL); + g_return_val_if_fail (content_type != NULL && *content_type != '\0', NULL); + g_return_val_if_fail (cancellable == NULL || G_IS_CANCELLABLE (cancellable), NULL); + g_return_val_if_fail (error == NULL || *error == NULL, NULL); + + if (gdata_entry_is_inserted (GDATA_ENTRY (file_entry)) == TRUE) { + g_set_error_literal (error, GDATA_SERVICE_ERROR, GDATA_SERVICE_ERROR_ENTRY_ALREADY_INSERTED, + _("The entry has already been inserted.")); + return NULL; + } + + if (gdata_authorizer_is_authorized_for_domain (gdata_service_get_authorizer (GDATA_SERVICE (self)), + get_picasaweb_authorization_domain ()) == FALSE) { + g_set_error_literal (error, GDATA_SERVICE_ERROR, GDATA_SERVICE_ERROR_AUTHENTICATION_REQUIRED, + _("You must be authenticated to upload a file.")); + return NULL; + } + + /* PicasaWeb allows you to post to a default Dropbox */ + album_id = (album != NULL) ? gdata_picasaweb_album_get_id (album) : "default"; + + /* Build the upload URI and upload stream */ + upload_uri = _gdata_service_build_uri ("https://picasaweb.google.com/data/feed/api/user/default/albumid/%s", album_id); + upload_stream = GDATA_UPLOAD_STREAM (gdata_upload_stream_new (GDATA_SERVICE (self), get_picasaweb_authorization_domain (), SOUP_METHOD_POST, + upload_uri, GDATA_ENTRY (file_entry), slug, content_type, cancellable)); + g_free (upload_uri); + + return upload_stream; +} + +/** + * gdata_picasaweb_service_finish_file_upload: + * @self: a #GDataPicasaWebService + * @upload_stream: the #GDataUploadStream from the operation + * @error: a #GError, or %NULL + * + * Finish off a file upload operation started by gdata_picasaweb_service_upload_file(), parsing the result and returning the new #GDataPicasaWebFile. + * + * If an error occurred during the upload operation, it will have been returned during the operation (e.g. by g_output_stream_splice() or one + * of the other stream methods). In such a case, %NULL will be returned but @error will remain unset. @error is only set in the case that the server + * indicates that the operation was successful, but an error is encountered in parsing the result sent by the server. + * + * Return value: (transfer full): the new #GDataPicasaWebFile, or %NULL; unref with g_object_unref() + * + * Since: 0.8.0 + */ +GDataPicasaWebFile * +gdata_picasaweb_service_finish_file_upload (GDataPicasaWebService *self, GDataUploadStream *upload_stream, GError **error) +{ + const gchar *response_body; + gssize response_length; + + g_return_val_if_fail (GDATA_IS_PICASAWEB_SERVICE (self), NULL); + g_return_val_if_fail (GDATA_IS_UPLOAD_STREAM (upload_stream), NULL); + g_return_val_if_fail (error == NULL || *error == NULL, NULL); + + /* Get the response from the server */ + response_body = gdata_upload_stream_get_response (upload_stream, &response_length); + if (response_body == NULL || response_length == 0) + return NULL; + + /* Parse the response to produce a GDataPicasaWebFile */ + return GDATA_PICASAWEB_FILE (gdata_parsable_new_from_xml (GDATA_TYPE_PICASAWEB_FILE, response_body, (gint) response_length, error)); +} + +/** + * gdata_picasaweb_service_insert_album: + * @self: a #GDataPicasaWebService + * @album: a #GDataPicasaWebAlbum to create on the server + * @cancellable: (allow-none): optional #GCancellable object, or %NULL + * @error: a #GError, or %NULL + * + * Inserts a new album described by @album. A user must be + * authenticated to use this function. + * + * Return value: (transfer full): the inserted #GDataPicasaWebAlbum; unref with + * g_object_unref() + * + * Since: 0.6.0 + */ +GDataPicasaWebAlbum * +gdata_picasaweb_service_insert_album (GDataPicasaWebService *self, GDataPicasaWebAlbum *album, GCancellable *cancellable, GError **error) +{ + g_return_val_if_fail (GDATA_IS_PICASAWEB_SERVICE (self), NULL); + g_return_val_if_fail (GDATA_IS_PICASAWEB_ALBUM (album), NULL); + g_return_val_if_fail (cancellable == NULL || G_IS_CANCELLABLE (cancellable), NULL); + g_return_val_if_fail (error == NULL || *error == NULL, NULL); + + if (gdata_entry_is_inserted (GDATA_ENTRY (album)) == TRUE) { + g_set_error_literal (error, GDATA_SERVICE_ERROR, GDATA_SERVICE_ERROR_ENTRY_ALREADY_INSERTED, + _("The album has already been inserted.")); + return NULL; + } + + if (gdata_authorizer_is_authorized_for_domain (gdata_service_get_authorizer (GDATA_SERVICE (self)), + get_picasaweb_authorization_domain ()) == FALSE) { + g_set_error_literal (error, GDATA_SERVICE_ERROR, GDATA_SERVICE_ERROR_AUTHENTICATION_REQUIRED, + _("You must be authenticated to insert an album.")); + return NULL; + } + + return GDATA_PICASAWEB_ALBUM (gdata_service_insert_entry (GDATA_SERVICE (self), get_picasaweb_authorization_domain (), + "https://picasaweb.google.com/data/feed/api/user/default", + GDATA_ENTRY (album), cancellable, error)); +} + +/** + * gdata_picasaweb_service_insert_album_async: + * @self: a #GDataPicasaWebService + * @album: a #GDataPicasaWebAlbum to create on the server + * @cancellable: (allow-none): optional #GCancellable object, or %NULL + * @callback: a #GAsyncReadyCallback to call when insertion is finished + * @user_data: (closure): data to pass to the @callback function + * + * Inserts a new album described by @album. The user must be authenticated to use this function. @self and @album are both reffed when this function + * is called, so can safely be unreffed after this function returns. + * + * @callback should call gdata_service_insert_entry_finish() to obtain a #GDataPicasaWebAlbum representing the inserted album and to check for + * possible errors. + * + * For more details, see gdata_picasaweb_service_insert_album(), which is the synchronous version of this function, and + * gdata_service_insert_entry_async(), which is the base asynchronous insertion function. + * + * Since: 0.8.0 + */ +void +gdata_picasaweb_service_insert_album_async (GDataPicasaWebService *self, GDataPicasaWebAlbum *album, GCancellable *cancellable, + GAsyncReadyCallback callback, gpointer user_data) +{ + g_return_if_fail (GDATA_IS_PICASAWEB_SERVICE (self)); + g_return_if_fail (GDATA_IS_PICASAWEB_ALBUM (album)); + g_return_if_fail (cancellable == NULL || G_IS_CANCELLABLE (cancellable)); + + gdata_service_insert_entry_async (GDATA_SERVICE (self), get_picasaweb_authorization_domain (), + "https://picasaweb.google.com/data/feed/api/user/default", GDATA_ENTRY (album), cancellable, callback, + user_data); +} diff --git a/gdata/services/picasaweb/gdata-picasaweb-service.h b/gdata/services/picasaweb/gdata-picasaweb-service.h new file mode 100644 index 0000000..f144edb --- /dev/null +++ b/gdata/services/picasaweb/gdata-picasaweb-service.h @@ -0,0 +1,120 @@ +/* -*- Mode: C; indent-tabs-mode: t; c-basic-offset: 8; tab-width: 8 -*- */ +/* + * GData Client + * Copyright (C) Richard Schwarting 2009 + * Copyright (C) Philip Withnall 2009 + * + * GData Client is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * GData Client is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with GData Client. If not, see . + */ + +#ifndef GDATA_PICASAWEB_SERVICE_H +#define GDATA_PICASAWEB_SERVICE_H + +#include +#include + +#include +#include +#include +#include + +G_BEGIN_DECLS + +#define GDATA_TYPE_PICASAWEB_SERVICE (gdata_picasaweb_service_get_type ()) +#define GDATA_PICASAWEB_SERVICE(o) (G_TYPE_CHECK_INSTANCE_CAST ((o), GDATA_TYPE_PICASAWEB_SERVICE, GDataPicasaWebService)) +#define GDATA_PICASAWEB_SERVICE_CLASS(k) (G_TYPE_CHECK_CLASS_CAST((k), GDATA_TYPE_PICASAWEB_SERVICE, GDataPicasaWebServiceClass)) +#define GDATA_IS_PICASAWEB_SERVICE(o) (G_TYPE_CHECK_INSTANCE_TYPE ((o), GDATA_TYPE_PICASAWEB_SERVICE)) +#define GDATA_IS_PICASAWEB_SERVICE_CLASS(k) (G_TYPE_CHECK_CLASS_TYPE ((k), GDATA_TYPE_PICASAWEB_SERVICE)) +#define GDATA_PICASAWEB_SERVICE_GET_CLASS(o) (G_TYPE_INSTANCE_GET_CLASS ((o), GDATA_TYPE_PICASAWEB_SERVICE, GDataPicasaWebServiceClass)) + +/** + * GDataPicasaWebService: + * + * All the fields in the #GDataPicasaWebService structure are private and should never be accessed directly. + * + * Since: 0.4.0 + */ +typedef struct { + GDataService parent; +} GDataPicasaWebService; + +/** + * GDataPicasaWebServiceClass: + * + * All the fields in the #GDataPicasaWebServiceClass structure are private and should never be accessed directly. + * + * Since: 0.4.0 + */ +typedef struct { + /*< private >*/ + GDataServiceClass parent; + + /*< private >*/ + /* Padding for future expansion */ + void (*_g_reserved0) (void); + void (*_g_reserved1) (void); + void (*_g_reserved2) (void); + void (*_g_reserved3) (void); + void (*_g_reserved4) (void); + void (*_g_reserved5) (void); +} GDataPicasaWebServiceClass; + +GType gdata_picasaweb_service_get_type (void) G_GNUC_CONST; +G_DEFINE_AUTOPTR_CLEANUP_FUNC (GDataPicasaWebService, g_object_unref) + +GDataPicasaWebService *gdata_picasaweb_service_new (GDataAuthorizer *authorizer) G_GNUC_WARN_UNUSED_RESULT G_GNUC_MALLOC; + +GDataAuthorizationDomain *gdata_picasaweb_service_get_primary_authorization_domain (void) G_GNUC_CONST; + +#include + +GDataPicasaWebUser *gdata_picasaweb_service_get_user (GDataPicasaWebService *self, const gchar *username, + GCancellable *cancellable, GError **error) G_GNUC_WARN_UNUSED_RESULT G_GNUC_MALLOC; +void gdata_picasaweb_service_get_user_async (GDataPicasaWebService *self, const gchar *username, GCancellable *cancellable, + GAsyncReadyCallback callback, gpointer user_data); +GDataPicasaWebUser *gdata_picasaweb_service_get_user_finish (GDataPicasaWebService *self, GAsyncResult *result, + GError **error) G_GNUC_WARN_UNUSED_RESULT G_GNUC_MALLOC; + +GDataFeed *gdata_picasaweb_service_query_all_albums (GDataPicasaWebService *self, GDataQuery *query, const gchar *username, GCancellable *cancellable, + GDataQueryProgressCallback progress_callback, gpointer progress_user_data, + GError **error) G_GNUC_WARN_UNUSED_RESULT G_GNUC_MALLOC; +void gdata_picasaweb_service_query_all_albums_async (GDataPicasaWebService *self, GDataQuery *query, const gchar *username, GCancellable *cancellable, + GDataQueryProgressCallback progress_callback, gpointer progress_user_data, + GDestroyNotify destroy_progress_user_data, + GAsyncReadyCallback callback, gpointer user_data); + +GDataFeed *gdata_picasaweb_service_query_files (GDataPicasaWebService *self, GDataPicasaWebAlbum *album, GDataQuery *query, + GCancellable *cancellable, GDataQueryProgressCallback progress_callback, gpointer progress_user_data, + GError **error) G_GNUC_WARN_UNUSED_RESULT G_GNUC_MALLOC; +void gdata_picasaweb_service_query_files_async (GDataPicasaWebService *self, GDataPicasaWebAlbum *album, GDataQuery *query, GCancellable *cancellable, + GDataQueryProgressCallback progress_callback, gpointer progress_user_data, + GDestroyNotify destroy_progress_user_data, + GAsyncReadyCallback callback, gpointer user_data); + +#include + +GDataUploadStream *gdata_picasaweb_service_upload_file (GDataPicasaWebService *self, GDataPicasaWebAlbum *album, GDataPicasaWebFile *file_entry, + const gchar *slug, const gchar *content_type, GCancellable *cancellable, + GError **error) G_GNUC_WARN_UNUSED_RESULT G_GNUC_MALLOC; +GDataPicasaWebFile *gdata_picasaweb_service_finish_file_upload (GDataPicasaWebService *self, GDataUploadStream *upload_stream, + GError **error) G_GNUC_WARN_UNUSED_RESULT G_GNUC_MALLOC; + +GDataPicasaWebAlbum *gdata_picasaweb_service_insert_album (GDataPicasaWebService *self, GDataPicasaWebAlbum *album, GCancellable *cancellable, + GError **error) G_GNUC_WARN_UNUSED_RESULT G_GNUC_MALLOC; +void gdata_picasaweb_service_insert_album_async (GDataPicasaWebService *self, GDataPicasaWebAlbum *album, GCancellable *cancellable, + GAsyncReadyCallback callback, gpointer user_data); + +G_END_DECLS + +#endif /* !GDATA_PICASAWEB_SERVICE_H */ diff --git a/gdata/services/picasaweb/gdata-picasaweb-user.c b/gdata/services/picasaweb/gdata-picasaweb-user.c new file mode 100644 index 0000000..38db73f --- /dev/null +++ b/gdata/services/picasaweb/gdata-picasaweb-user.c @@ -0,0 +1,376 @@ +/* -*- Mode: C; indent-tabs-mode: t; c-basic-offset: 8; tab-width: 8 -*- */ +/* + * GData Client + * Copyright (C) Philip Withnall 2009–2010 + * Copyright (C) Richard Schwarting 2009 + * + * GData Client is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * GData Client is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with GData Client. If not, see . + */ + +/** + * SECTION:gdata-picasaweb-user + * @short_description: GData PicasaWeb User object + * @stability: Stable + * @include: gdata/services/picasaweb/gdata-picasaweb-user.h + * + * #GDataPicasaWebUser is a subclass of #GDataEntry to represent properties for a PicasaWeb user. It adds a couple of + * properties which are specific to the Google PicasaWeb API. + * + * Since: 0.6.0 + */ + +#include +#include + +#include "gdata-picasaweb-user.h" +#include "gdata-entry.h" +#include "gdata-private.h" + +static void gdata_picasaweb_user_finalize (GObject *object); +static void gdata_picasaweb_user_get_property (GObject *object, guint property_id, GValue *value, GParamSpec *pspec); +static gboolean parse_xml (GDataParsable *parsable, xmlDoc *doc, xmlNode *node, gpointer user_data, GError **error); +static void get_namespaces (GDataParsable *parsable, GHashTable *namespaces); + +struct _GDataPicasaWebUserPrivate { + gchar *user; + gchar *nickname; + gint64 quota_limit; + gint64 quota_current; + gint max_photos_per_album; + gchar *thumbnail_uri; +}; + +enum { + PROP_USER = 1, + PROP_NICKNAME, + PROP_QUOTA_LIMIT, + PROP_QUOTA_CURRENT, + PROP_MAX_PHOTOS_PER_ALBUM, + PROP_THUMBNAIL_URI +}; + +G_DEFINE_TYPE (GDataPicasaWebUser, gdata_picasaweb_user, GDATA_TYPE_ENTRY) + +static void +gdata_picasaweb_user_class_init (GDataPicasaWebUserClass *klass) +{ + GObjectClass *gobject_class = G_OBJECT_CLASS (klass); + GDataParsableClass *parsable_class = GDATA_PARSABLE_CLASS (klass); + GDataEntryClass *entry_class = GDATA_ENTRY_CLASS (klass); + + g_type_class_add_private (klass, sizeof (GDataPicasaWebUserPrivate)); + + gobject_class->get_property = gdata_picasaweb_user_get_property; + gobject_class->finalize = gdata_picasaweb_user_finalize; + + parsable_class->parse_xml = parse_xml; + parsable_class->get_namespaces = get_namespaces; + + entry_class->kind_term = "http://schemas.google.com/photos/2007#user"; + + /** + * GDataPicasaWebUser:user: + * + * The username of the user, as seen in feed URLs. + * http://code.google.com/apis/picasaweb/docs/2.0/reference.html#gphoto_user + * + * Since: 0.6.0 + */ + g_object_class_install_property (gobject_class, PROP_USER, + g_param_spec_string ("user", + "User", "The username of the user.", + NULL, + G_PARAM_READABLE | G_PARAM_STATIC_STRINGS)); + + /** + * GDataPicasaWebUser:nickname: + * + * The user's nickname. This is a user-specified value that should be used when referring to the user by name. + * http://code.google.com/apis/picasaweb/docs/2.0/reference.html#gphoto_nickname + * + * Since: 0.6.0 + */ + g_object_class_install_property (gobject_class, PROP_NICKNAME, + g_param_spec_string ("nickname", + "Nickname", "The user's nickname.", + NULL, + G_PARAM_READABLE | G_PARAM_STATIC_STRINGS)); + + /** + * GDataPicasaWebUser:quota-limit: + * + * The total amount of space, in bytes, available to the user. + * http://code.google.com/apis/picasaweb/docs/2.0/reference.html#gphoto_quotalimit + * + * If the #GDataPicasaWebUser does not represent the currently authenticated user, this will be -1. + * + * Since: 0.6.0 + */ + g_object_class_install_property (gobject_class, PROP_QUOTA_LIMIT, + g_param_spec_int64 ("quota-limit", + "Quota Limit", "The total amount of space, in bytes, available to the user.", + -1, G_MAXINT64, -1, + G_PARAM_READABLE | G_PARAM_STATIC_STRINGS)); + + /** + * GDataPicasaWebUser:quota-current: + * + * The current amount of space, in bytes, already used by the user. + * http://code.google.com/apis/picasaweb/docs/2.0/reference.html#gphoto_quotacurrent + * + * If the #GDataPicasaWebUser does not represent the currently authenticated user, this will be -1. + * + * Since: 0.6.0 + */ + g_object_class_install_property (gobject_class, PROP_QUOTA_CURRENT, + g_param_spec_int64 ("quota-current", + "Quota Current", "The current amount of space, in bytes, already used by the user.", + -1, G_MAXINT64, -1, + G_PARAM_READABLE | G_PARAM_STATIC_STRINGS)); + + /** + * GDataPicasaWebUser:max-photos-per-album: + * + * The maximum number of photos allowed in an album. + * http://code.google.com/apis/picasaweb/docs/2.0/reference.html#gphoto_maxPhotosPerAlbum + * + * If the #GDataPicasaWebUser does not represent the currently authenticated user, this will be -1. + * + * Since: 0.6.0 + */ + g_object_class_install_property (gobject_class, PROP_MAX_PHOTOS_PER_ALBUM, + g_param_spec_int ("max-photos-per-album", + "Max Photos Per Album", "The maximum number of photos allowed in an album.", + -1, G_MAXINT, -1, + G_PARAM_READABLE | G_PARAM_STATIC_STRINGS)); + + /** + * GDataPicasaWebUser:thumbnail-uri: + * + * The URI of a thumbnail-sized portrait of the user. + * http://code.google.com/apis/picasaweb/docs/2.0/reference.html#gphoto_thumbnail + * + * Since: 0.6.0 + */ + g_object_class_install_property (gobject_class, PROP_THUMBNAIL_URI, + g_param_spec_string ("thumbnail-uri", + "Thumbnail URI", "The URI of a thumbnail-sized portrait of the user.", + NULL, + G_PARAM_READABLE | G_PARAM_STATIC_STRINGS)); +} + +static void +gdata_picasaweb_user_init (GDataPicasaWebUser *self) +{ + self->priv = G_TYPE_INSTANCE_GET_PRIVATE (self, GDATA_TYPE_PICASAWEB_USER, GDataPicasaWebUserPrivate); + + /* Initialise the properties whose values we can theoretically not know */ + self->priv->quota_limit = self->priv->quota_current = self->priv->max_photos_per_album = -1; +} + +static void +gdata_picasaweb_user_finalize (GObject *object) +{ + GDataPicasaWebUserPrivate *priv = GDATA_PICASAWEB_USER (object)->priv; + + g_free (priv->user); + g_free (priv->nickname); + g_free (priv->thumbnail_uri); + + /* Chain up to the parent class */ + G_OBJECT_CLASS (gdata_picasaweb_user_parent_class)->finalize (object); +} + +static void +gdata_picasaweb_user_get_property (GObject *object, guint property_id, GValue *value, GParamSpec *pspec) +{ + GDataPicasaWebUserPrivate *priv = GDATA_PICASAWEB_USER (object)->priv; + + switch (property_id) { + case PROP_USER: + g_value_set_string (value, priv->user); + break; + case PROP_NICKNAME: + g_value_set_string (value, priv->nickname); + break; + case PROP_QUOTA_LIMIT: + g_value_set_int64 (value, priv->quota_limit); + break; + case PROP_QUOTA_CURRENT: + g_value_set_int64 (value, priv->quota_current); + break; + case PROP_MAX_PHOTOS_PER_ALBUM: + g_value_set_int (value, priv->max_photos_per_album); + break; + case PROP_THUMBNAIL_URI: + g_value_set_string (value, priv->thumbnail_uri); + break; + default: + /* We don't have any other property... */ + G_OBJECT_WARN_INVALID_PROPERTY_ID (object, property_id, pspec); + break; + } +} + +static gboolean +parse_xml (GDataParsable *parsable, xmlDoc *doc, xmlNode *node, gpointer user_data, GError **error) +{ + gboolean success; + GDataPicasaWebUser *self = GDATA_PICASAWEB_USER (parsable); + + if (gdata_parser_is_namespace (node, "http://schemas.google.com/photos/2007") == FALSE) + return GDATA_PARSABLE_CLASS (gdata_picasaweb_user_parent_class)->parse_xml (parsable, doc, node, user_data, error); + + if (gdata_parser_string_from_element (node, "user", P_REQUIRED | P_NON_EMPTY, &(self->priv->user), &success, error) == TRUE || + gdata_parser_string_from_element (node, "nickname", P_REQUIRED | P_NON_EMPTY, &(self->priv->nickname), &success, error) == TRUE || + gdata_parser_string_from_element (node, "thumbnail", P_REQUIRED | P_NON_EMPTY, &(self->priv->thumbnail_uri), &success, error) == TRUE || + gdata_parser_int64_from_element (node, "quotacurrent", P_REQUIRED | P_NO_DUPES, &(self->priv->quota_current), -1, &success, error) == TRUE || + gdata_parser_int64_from_element (node, "quotalimit", P_REQUIRED | P_NO_DUPES, &(self->priv->quota_limit), -1, &success, error) == TRUE) { + return success; + } else if (xmlStrcmp (node->name, (xmlChar*) "maxPhotosPerAlbum") == 0) { + /* gphoto:max-photos-per-album */ + xmlChar *max_photos_per_album = xmlNodeListGetString (doc, node->children, TRUE); + self->priv->max_photos_per_album = g_ascii_strtoll ((char*) max_photos_per_album, NULL, 10); + xmlFree (max_photos_per_album); + } else if (xmlStrcmp (node->name, (xmlChar*) "x-allowDownloads") == 0) { /* RHSTODO: see if this comes with the user */ + /* gphoto:allowDownloads */ + /* TODO: Not part of public API so we're capturing and ignoring for now. See bgo #589858. */ + } else if (xmlStrcmp (node->name, (xmlChar*) "x-allowPrints") == 0) { /* RHSTODO: see if this comes with the user */ + /* gphoto:allowPrints */ + /* TODO: Not part of public API so we're capturing and ignoring for now. See bgo #589858. */ + } else { + return GDATA_PARSABLE_CLASS (gdata_picasaweb_user_parent_class)->parse_xml (parsable, doc, node, user_data, error); + } + + return TRUE; +} + +static void +get_namespaces (GDataParsable *parsable, GHashTable *namespaces) +{ + /* Chain up to the parent class */ + GDATA_PARSABLE_CLASS (gdata_picasaweb_user_parent_class)->get_namespaces (parsable, namespaces); + + g_hash_table_insert (namespaces, (gchar*) "gphoto", (gchar*) "http://schemas.google.com/photos/2007"); +} + +/** + * gdata_picasaweb_user_get_user: + * @self: a #GDataPicasaWebUser + * + * Gets the #GDataPicasaWebUser:user property. + * + * Return value: the feed's user, or %NULL + * + * Since: 0.6.0 + */ +const gchar * +gdata_picasaweb_user_get_user (GDataPicasaWebUser *self) +{ + g_return_val_if_fail (GDATA_IS_PICASAWEB_USER (self), NULL); + return self->priv->user; +} + +/** + * gdata_picasaweb_user_get_nickname: + * @self: a #GDataPicasaWebUser + * + * Gets the #GDataPicasaWebUser:nickname property. + * + * Return value: the nickname of the feed's user's nickname, or %NULL + * + * Since: 0.6.0 + */ +const gchar * +gdata_picasaweb_user_get_nickname (GDataPicasaWebUser *self) +{ + g_return_val_if_fail (GDATA_IS_PICASAWEB_USER (self), NULL); + return self->priv->nickname; +} + +/** + * gdata_picasaweb_user_get_quota_limit: + * @self: a #GDataPicasaWebUser + * + * Gets the #GDataPicasaWebUser:quota-limit property. Note that + * this information is not available when accessing feeds which we + * haven't authenticated, and 0 is returned. + * + * Return value: the maximum capacity in bytes for this feed's account, or -1 + * + * Since: 0.6.0 + */ +gint64 +gdata_picasaweb_user_get_quota_limit (GDataPicasaWebUser *self) +{ + g_return_val_if_fail (GDATA_IS_PICASAWEB_USER (self), -1); + return self->priv->quota_limit; +} + +/** + * gdata_picasaweb_user_get_quota_current: + * @self: a #GDataPicasaWebUser + * + * Gets the #GDataPicasaWebUser:quota-current property. Note that + * this information is not available when accessing feeds which we + * haven't authenticated, and 0 is returned. + * + * Return value: the current number of bytes in use by this feed's account, or -1 + * + * Since: 0.6.0 + */ +gint64 +gdata_picasaweb_user_get_quota_current (GDataPicasaWebUser *self) +{ + g_return_val_if_fail (GDATA_IS_PICASAWEB_USER (self), -1); + return self->priv->quota_current; +} + +/** + * gdata_picasaweb_user_get_max_photos_per_album: + * @self: a #GDataPicasaWebUser + * + * Gets the #GDataPicasaWebUser:max-photos-per-album property. Note that + * this information is not available when accessing feeds which we + * haven't authenticated, and 0 is returned. + * + * Return value: the maximum number of photos an album for this account can hold, or -1 + * + * Since: 0.6.0 + */ +gint +gdata_picasaweb_user_get_max_photos_per_album (GDataPicasaWebUser *self) +{ + g_return_val_if_fail (GDATA_IS_PICASAWEB_USER (self), -1); + return self->priv->max_photos_per_album; +} + +/** + * gdata_picasaweb_user_get_thumbnail_uri: + * @self: a #GDataPicasaWebUser + * + * Gets the #GDataPicasaWebUser:thumbnail-uri property. + * + * Return value: the URI for the thumbnail of the account, or %NULL + * + * Since: 0.6.0 + */ +const gchar * +gdata_picasaweb_user_get_thumbnail_uri (GDataPicasaWebUser *self) +{ + g_return_val_if_fail (GDATA_IS_PICASAWEB_USER (self), NULL); + return self->priv->thumbnail_uri; +} + +/* TODO: in the future, see if we can change things like the user's nickname and thumbnail/avatar */ diff --git a/gdata/services/picasaweb/gdata-picasaweb-user.h b/gdata/services/picasaweb/gdata-picasaweb-user.h new file mode 100644 index 0000000..e8f6f11 --- /dev/null +++ b/gdata/services/picasaweb/gdata-picasaweb-user.h @@ -0,0 +1,82 @@ +/* -*- Mode: C; indent-tabs-mode: t; c-basic-offset: 8; tab-width: 8 -*- */ +/* + * GData Client + * Copyright (C) Philip Withnall 2009 + * Copyright (C) Richard Schwarting 2009 + * + * GData Client is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * GData Client is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with GData Client. If not, see . + */ + +#ifndef GDATA_PICASAWEB_USER_H +#define GDATA_PICASAWEB_USER_H + +#include +#include + +#include +#include + +G_BEGIN_DECLS + +#define GDATA_TYPE_PICASAWEB_USER (gdata_picasaweb_user_get_type ()) +#define GDATA_PICASAWEB_USER(o) (G_TYPE_CHECK_INSTANCE_CAST ((o), GDATA_TYPE_PICASAWEB_USER, GDataPicasaWebUser)) +#define GDATA_PICASAWEB_USER_CLASS(k) (G_TYPE_CHECK_CLASS_CAST((k), GDATA_TYPE_PICASAWEB_USER, GDataPicasaWebUserClass)) +#define GDATA_IS_PICASAWEB_USER(o) (G_TYPE_CHECK_INSTANCE_TYPE ((o), GDATA_TYPE_PICASAWEB_USER)) +#define GDATA_IS_PICASAWEB_USER_CLASS(k) (G_TYPE_CHECK_CLASS_TYPE ((k), GDATA_TYPE_PICASAWEB_USER)) +#define GDATA_PICASAWEB_USER_GET_CLASS(o) (G_TYPE_INSTANCE_GET_CLASS ((o), GDATA_TYPE_PICASAWEB_USER, GDataPicasaWebUserClass)) + +typedef struct _GDataPicasaWebUserPrivate GDataPicasaWebUserPrivate; + +/** + * GDataPicasaWebUser: + * + * All the fields in the #GDataPicasaWebUser structure are private and should never be accessed directly. + * + * Since: 0.6.0 + */ +typedef struct { + GDataEntry parent; + GDataPicasaWebUserPrivate *priv; +} GDataPicasaWebUser; + +/** + * GDataPicasaWebUserClass: + * + * All the fields in the #GDataPicasaWebUserClass structure are private and should never be accessed directly. + * + * Since: 0.6.0 + */ +typedef struct { + /*< private >*/ + GDataEntryClass parent; + + /*< private >*/ + /* Padding for future expansion */ + void (*_g_reserved0) (void); + void (*_g_reserved1) (void); +} GDataPicasaWebUserClass; + +GType gdata_picasaweb_user_get_type (void) G_GNUC_CONST; +G_DEFINE_AUTOPTR_CLEANUP_FUNC (GDataPicasaWebUser, g_object_unref) + +const gchar *gdata_picasaweb_user_get_user (GDataPicasaWebUser *self) G_GNUC_PURE; +const gchar *gdata_picasaweb_user_get_nickname (GDataPicasaWebUser *self) G_GNUC_PURE; +gint64 gdata_picasaweb_user_get_quota_limit (GDataPicasaWebUser *self) G_GNUC_PURE; +gint64 gdata_picasaweb_user_get_quota_current (GDataPicasaWebUser *self) G_GNUC_PURE; +gint gdata_picasaweb_user_get_max_photos_per_album (GDataPicasaWebUser *self) G_GNUC_PURE; +const gchar *gdata_picasaweb_user_get_thumbnail_uri (GDataPicasaWebUser *self) G_GNUC_PURE; + +G_END_DECLS + +#endif /* !GDATA_PICASAWEB_USER_H */ diff --git a/gdata/services/picasaweb/meson.build b/gdata/services/picasaweb/meson.build new file mode 100644 index 0000000..edab0ce --- /dev/null +++ b/gdata/services/picasaweb/meson.build @@ -0,0 +1,58 @@ +incs += include_directories('.') + +include_subdir = gdata_include_subdir / 'services/picasaweb' + +headers = files( + 'gdata-picasaweb-album.h', + 'gdata-picasaweb-comment.h', + 'gdata-picasaweb-feed.h', + 'gdata-picasaweb-file.h', + 'gdata-picasaweb-query.h', + 'gdata-picasaweb-service.h', + 'gdata-picasaweb-user.h', +) + +install_headers( + headers, + subdir: include_subdir, +) + +gir_headers += headers + +sources += files( + 'gdata-picasaweb-album.c', + 'gdata-picasaweb-comment.c', + 'gdata-picasaweb-feed.c', + 'gdata-picasaweb-file.c', + 'gdata-picasaweb-query.c', + 'gdata-picasaweb-service.c', + 'gdata-picasaweb-user.c', +) + +enums = 'gdata-picasaweb-enums' + +enums_in = gnome.mkenums_simple( + enums + '-in', + sources: headers, +) + +# FIXME: Work around the namespace being incorrectly detected +# by glib-mkenums. This needs to be fixed by changing the +# namespace in libgdata. See !6. +sources += custom_target( + enums + '.c', + input: enums_in[0], + output: enums + '.c', + command: [sed, '-e', 's/-in//', '-e', 's/g_data_picasa_web/gdata_picasaweb/', build_root / '@INPUT@'], + capture: true, +) + +enum_headers += custom_target( + enums + '.h', + input: enums_in[1], + output: enums + '.h', + command: [sed, '-e', 's/g_data_picasa_web/gdata_picasaweb/', '-e', 's/G_TYPE_DATA_PICASA_WEB/GDATA_TYPE_PICASAWEB/', build_root / '@INPUT@'], + capture: true, + install: true, + install_dir: gdata_includedir / include_subdir, +) diff --git a/gdata/services/tasks/gdata-tasks-query.c b/gdata/services/tasks/gdata-tasks-query.c new file mode 100644 index 0000000..627dc86 --- /dev/null +++ b/gdata/services/tasks/gdata-tasks-query.c @@ -0,0 +1,659 @@ +/* -*- Mode: C; indent-tabs-mode: t; c-basic-offset: 8; tab-width: 8 -*- */ +/* + * GData Client + * Copyright (C) Peteris Krisjanis 2013 + * + * GData Client is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * GData Client is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with GData Client. If not, see . + */ + +/** + * SECTION:gdata-tasks-query + * @short_description: GData Tasks query object + * @stability: Stable + * @include: gdata/services/tasks/gdata-tasks-query.h + * + * #GDataTasksQuery represents a collection of query parameters specific to the Google Tasks service, which go above and beyond + * those catered for by #GDataQuery. + * + * For more details of Google Tasks API, see the + * online documentation. + * + * Since: 0.15.0 + */ + +#include +#include +#include +#include + +#include "gdata-tasks-query.h" +#include "gdata-query.h" +#include "gdata-parser.h" +#include "gdata-private.h" + +static void gdata_tasks_query_finalize (GObject *object); +static void gdata_tasks_query_get_property (GObject *object, guint property_id, GValue *value, GParamSpec *pspec); +static void gdata_tasks_query_set_property (GObject *object, guint property_id, const GValue *value, GParamSpec *pspec); +static void get_query_uri (GDataQuery *self, const gchar *feed_uri, GString *query_uri, gboolean *params_started); + +struct _GDataTasksQueryPrivate { + gint64 completed_max; + gint64 completed_min; + gint64 due_max; + gint64 due_min; + gboolean show_completed; + gboolean show_deleted; + gboolean show_hidden; +}; + +enum { + PROP_COMPLETED_MAX = 1, + PROP_COMPLETED_MIN, + PROP_DUE_MAX, + PROP_DUE_MIN, + PROP_SHOW_COMPLETED, + PROP_SHOW_DELETED, + PROP_SHOW_HIDDEN, +}; + +G_DEFINE_TYPE (GDataTasksQuery, gdata_tasks_query, GDATA_TYPE_QUERY) + +static void +gdata_tasks_query_class_init (GDataTasksQueryClass *klass) +{ + GObjectClass *gobject_class = G_OBJECT_CLASS (klass); + GDataQueryClass *query_class = GDATA_QUERY_CLASS (klass); + + g_type_class_add_private (klass, sizeof (GDataTasksQueryPrivate)); + + gobject_class->set_property = gdata_tasks_query_set_property; + gobject_class->get_property = gdata_tasks_query_get_property; + gobject_class->finalize = gdata_tasks_query_finalize; + + query_class->get_query_uri = get_query_uri; + + /** + * GDataTasksQuery:completed-max: + * + * Upper bound for a task's completion date (as a RFC 3339 timestamp) to filter by. Optional. + * The default is not to filter by completion date. + * + * Since: 0.15.0 + */ + g_object_class_install_property (gobject_class, PROP_COMPLETED_MAX, + g_param_spec_int64 ("completed-max", + "Max task completion date", "Upper bound for a task's completion date to filter by.", + -1, G_MAXINT64, -1, + G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)); + + /** + * GDataTasksQuery:completed-min: + * + * Lower bound for a task's completion date (as a RFC 3339 timestamp) to filter by. Optional. + * The default is not to filter by completion date. + * + * Since: 0.15.0 + */ + g_object_class_install_property (gobject_class, PROP_COMPLETED_MIN, + g_param_spec_int64 ("completed-min", + "Min task completion date", "Lower bound for a task's completion date to filter by.", + -1, G_MAXINT64, -1, + G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)); + + /** + * GDataTasksQuery:due-max: + * + * Upper bound for a task's due date (as a RFC 3339 timestamp) to filter by. Optional. + * The default is not to filter by completion date. + * + * Since: 0.15.0 + */ + g_object_class_install_property (gobject_class, PROP_DUE_MAX, + g_param_spec_int64 ("due-max", + "Max task completion date", "Upper bound for a task's completion date to filter by.", + -1, G_MAXINT64, -1, + G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)); + + /** + * GDataTasksQuery:due-min: + * + * Lower bound for a task's due date (as a RFC 3339 timestamp) to filter by. Optional. + * The default is not to filter by completion date. + * Since: 0.15.0 + */ + g_object_class_install_property (gobject_class, PROP_DUE_MIN, + g_param_spec_int64 ("due-min", + "Min task completion date", "Lower bound for a task's completion date to filter by.", + -1, G_MAXINT64, -1, + G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)); + + /** + * GDataTasksQuery:show-completed: + * + * Flag indicating whether completed tasks are returned in the result. Optional. The default is %FALSE. + * + * Since: 0.15.0 + */ + g_object_class_install_property (gobject_class, PROP_SHOW_COMPLETED, + g_param_spec_boolean ("show-completed", + "Show completed tasks?", "Indicated whatever completed tasks are returned in the result.", + FALSE, + G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)); + + /** + * GDataTasksQuery:show-deleted: + * + * Flag indicating whether deleted tasks are returned in the result. Optional. The default is %FALSE. + * + * Since: 0.15.0 + */ + g_object_class_install_property (gobject_class, PROP_SHOW_DELETED, + g_param_spec_boolean ("show-deleted", + "Show deleted tasks?", "Indicated whatever deleted tasks are returned in the result.", + FALSE, + G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)); + + /** + * GDataTasksQuery:show-hidden: + * + * Flag indicating whether hidden tasks are returned in the result. Optional. The default is %FALSE. + * + * Since: 0.15.0 + */ + g_object_class_install_property (gobject_class, PROP_SHOW_HIDDEN, + g_param_spec_boolean ("show-hidden", + "Show hidden tasks?", "Indicated whatever hidden tasks are returned in the result.", + FALSE, + G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)); +} + +static void +gdata_tasks_query_init (GDataTasksQuery *self) +{ + self->priv = G_TYPE_INSTANCE_GET_PRIVATE (self, GDATA_TYPE_TASKS_QUERY, GDataTasksQueryPrivate); + self->priv->completed_min = -1; + self->priv->completed_max = -1; + self->priv->due_min = -1; + self->priv->due_max = -1; + + _gdata_query_set_pagination_type (GDATA_QUERY (self), + GDATA_QUERY_PAGINATION_TOKENS); +} + +static void +gdata_tasks_query_finalize (GObject *object) +{ + /* Chain up to the parent class */ + G_OBJECT_CLASS (gdata_tasks_query_parent_class)->finalize (object); +} + +static void +gdata_tasks_query_get_property (GObject *object, guint property_id, GValue *value, GParamSpec *pspec) +{ + GDataTasksQueryPrivate *priv = GDATA_TASKS_QUERY (object)->priv; + + switch (property_id) { + case PROP_COMPLETED_MAX: + g_value_set_int64 (value, priv->completed_max); + break; + case PROP_COMPLETED_MIN: + g_value_set_int64 (value, priv->completed_min); + break; + case PROP_DUE_MAX: + g_value_set_int64 (value, priv->due_max); + break; + case PROP_DUE_MIN: + g_value_set_int64 (value, priv->due_min); + break; + case PROP_SHOW_COMPLETED: + g_value_set_boolean (value, priv->show_completed); + break; + case PROP_SHOW_DELETED: + g_value_set_boolean (value, priv->show_deleted); + break; + case PROP_SHOW_HIDDEN: + g_value_set_boolean (value, priv->show_hidden); + break; + default: + /* We don't have any other property... */ + G_OBJECT_WARN_INVALID_PROPERTY_ID (object, property_id, pspec); + break; + } +} + +static void +gdata_tasks_query_set_property (GObject *object, guint property_id, const GValue *value, GParamSpec *pspec) +{ + GDataTasksQuery *self = GDATA_TASKS_QUERY (object); + + switch (property_id) { + case PROP_COMPLETED_MAX: + gdata_tasks_query_set_completed_max (self, g_value_get_int64 (value)); + break; + case PROP_COMPLETED_MIN: + gdata_tasks_query_set_completed_min (self, g_value_get_int64 (value)); + break; + case PROP_DUE_MAX: + gdata_tasks_query_set_due_max (self, g_value_get_int64 (value)); + break; + case PROP_DUE_MIN: + gdata_tasks_query_set_due_min (self, g_value_get_int64 (value)); + break; + case PROP_SHOW_COMPLETED: + gdata_tasks_query_set_show_completed (self, g_value_get_boolean (value)); + break; + case PROP_SHOW_DELETED: + gdata_tasks_query_set_show_deleted (self, g_value_get_boolean (value)); + break; + case PROP_SHOW_HIDDEN: + gdata_tasks_query_set_show_hidden (self, g_value_get_boolean (value)); + break; + default: + /* We don't have any other property... */ + G_OBJECT_WARN_INVALID_PROPERTY_ID (object, property_id, pspec); + break; + } +} + +static void +get_query_uri (GDataQuery *self, const gchar *feed_uri, GString *query_uri, gboolean *params_started) +{ + GDataTasksQueryPrivate *priv = GDATA_TASKS_QUERY (self)->priv; + + /* Chain up to the parent class. This adds a load of irrelevant query + * parameters, but they’re harmless. Importantly, it adds pagination + * support. */ + GDATA_QUERY_CLASS (gdata_tasks_query_parent_class)->get_query_uri (self, feed_uri, query_uri, params_started); + + #define APPEND_SEP g_string_append_c (query_uri, (*params_started == FALSE) ? '?' : '&'); *params_started = TRUE; + + if (gdata_query_get_max_results (GDATA_QUERY (self)) > 0) { + APPEND_SEP + g_string_append_printf (query_uri, "maxResults=%u", gdata_query_get_max_results (GDATA_QUERY (self))); + } + + if (gdata_query_get_updated_min (GDATA_QUERY (self)) != -1) { + gchar *updated_min; + + APPEND_SEP + g_string_append (query_uri, "updatedMin="); + updated_min = gdata_parser_int64_to_iso8601 (gdata_query_get_updated_min (GDATA_QUERY (self))); + g_string_append (query_uri, updated_min); + g_free (updated_min); + } + + if (priv->completed_min != -1) { + gchar *completed_min; + + APPEND_SEP + g_string_append (query_uri, "completedMin="); + completed_min = gdata_parser_int64_to_iso8601 (priv->completed_min); + g_string_append (query_uri, completed_min); + g_free (completed_min); + } + + if (priv->completed_max != -1) { + gchar *completed_max; + + APPEND_SEP + g_string_append (query_uri, "completedMax="); + completed_max = gdata_parser_int64_to_iso8601 (priv->completed_max); + g_string_append (query_uri, completed_max); + g_free (completed_max); + } + + if (priv->due_min != -1) { + gchar *due_min; + + APPEND_SEP + g_string_append (query_uri, "dueMin="); + due_min = gdata_parser_int64_to_iso8601 (priv->due_min); + g_string_append (query_uri, due_min); + g_free (due_min); + } + + if (priv->due_max != -1) { + gchar *due_max; + + APPEND_SEP + g_string_append (query_uri, "dueMax="); + due_max = gdata_parser_int64_to_iso8601 (priv->due_max); + g_string_append (query_uri, due_max); + g_free (due_max); + } + + APPEND_SEP + if (priv->show_completed == TRUE) { + g_string_append (query_uri, "showCompleted=true"); + } else { + g_string_append (query_uri, "showCompleted=false"); + } + + APPEND_SEP + if (priv->show_deleted == TRUE) { + g_string_append (query_uri, "showDeleted=true"); + } else { + g_string_append (query_uri, "showDeleted=false"); + } + + APPEND_SEP + if (priv->show_hidden == TRUE) { + g_string_append (query_uri, "showHidden=true"); + } else { + g_string_append (query_uri, "showHidden=false"); + } + + #undef APPEND_SEP +} + +/** + * gdata_tasks_query_new: + * @q: (allow-none): a query string, or %NULL + * + * Creates a new #GDataTasksQuery. @q is unused and must be set to %NULL. + * + * Return value: a new #GDataTasksQuery + * + * Since: 0.15.0 + */ +GDataTasksQuery * +gdata_tasks_query_new (const gchar *q) +{ + /* Ignore the q parameter, as it's not used in any of the queries and + * will cause errors. */ + return g_object_new (GDATA_TYPE_TASKS_QUERY, NULL); +} + +/** + * gdata_tasks_query_get_completed_max: + * @self: a #GDataTasksQuery + * + * Gets the #GDataTasksQuery:completed-max property. If the property is unset, -1 will be returned. + * + * Return value: the UNIX timestamp for the completed-max property, or -1 + * + * Since: 0.15.0 + */ +gint64 +gdata_tasks_query_get_completed_max (GDataTasksQuery *self) +{ + g_return_val_if_fail (GDATA_IS_TASKS_QUERY (self), -1); + return self->priv->completed_max; +} + +/** + * gdata_tasks_query_set_completed_max: + * @self: a #GDataTasksQuery + * @completed_max: upper bound for a task's completion date by UNIX timestamp, or -1 + * + * Sets the #GDataTasksQuery:completed-max property of the #GDataTasksQuery + * to the new time/date, @completed_max. + * + * Set @completed_max to -1 to unset the property in the query URI. + * + * Since: 0.15.0 + */ +void +gdata_tasks_query_set_completed_max (GDataTasksQuery *self, gint64 completed_max) +{ + g_return_if_fail (GDATA_IS_TASKS_QUERY (self)); + g_return_if_fail (completed_max >= -1); + + self->priv->completed_max = completed_max; + g_object_notify (G_OBJECT (self), "completed-max"); + + /* Our current ETag will no longer be relevant. */ + gdata_query_set_etag (GDATA_QUERY (self), NULL); +} + +/** + * gdata_tasks_query_get_completed_min: + * @self: a #GDataTasksQuery + * + * Gets the #GDataTasksQuery:completed-min property. If the property is unset, -1 will be returned. + * + * Return value: the UNIX timestamp for the completed-min property, or -1 + * + * Since: 0.15.0 + */ +gint64 +gdata_tasks_query_get_completed_min (GDataTasksQuery *self) +{ + g_return_val_if_fail (GDATA_IS_TASKS_QUERY (self), -1); + return self->priv->completed_min; +} + +/** + * gdata_tasks_query_set_completed_min: + * @self: a #GDataTasksQuery + * @completed_min: lower bound for a task's completion date by UNIX timestamp, or -1 + * + * Sets the #GDataTasksQuery:completed-min property of the #GDataTasksQuery + * to the new time/date, @completed_min. + * + * Set @completed_min to -1 to unset the property in the query URI. + * + * Since: 0.15.0 + */ +void +gdata_tasks_query_set_completed_min (GDataTasksQuery *self, gint64 completed_min) +{ + g_return_if_fail (GDATA_IS_TASKS_QUERY (self)); + g_return_if_fail (completed_min >= -1); + + self->priv->completed_min = completed_min; + g_object_notify (G_OBJECT (self), "completed-min"); + + /* Our current ETag will no longer be relevant. */ + gdata_query_set_etag (GDATA_QUERY (self), NULL); +} + +/** + * gdata_tasks_query_get_due_max: + * @self: a #GDataTasksQuery + * + * Gets the #GDataTasksQuery:due-max property. If the property is unset, -1 will be returned. + * + * Return value: the UNIX timestamp for the due-max property, or -1 + * + * Since: 0.15.0 + */ +gint64 +gdata_tasks_query_get_due_max (GDataTasksQuery *self) +{ + g_return_val_if_fail (GDATA_IS_TASKS_QUERY (self), -1); + return self->priv->due_max; +} + +/** + * gdata_tasks_query_set_due_max: + * @self: a #GDataTasksQuery + * @due_max: upper bound for a task's due date by UNIX timestamp, or -1 + * + * Sets the #GDataTasksQuery:due-max property of the #GDataTasksQuery + * to the new time/date, @due_max. + * + * Set @due_max to -1 to unset the property in the query URI. + * + * Since: 0.15.0 + */ +void +gdata_tasks_query_set_due_max (GDataTasksQuery *self, gint64 due_max) +{ + g_return_if_fail (GDATA_IS_TASKS_QUERY (self)); + g_return_if_fail (due_max >= -1); + + self->priv->due_max = due_max; + g_object_notify (G_OBJECT (self), "due-max"); + + /* Our current ETag will no longer be relevant. */ + gdata_query_set_etag (GDATA_QUERY (self), NULL); +} + + +/** + * gdata_tasks_query_get_due_min: + * @self: a #GDataTasksQuery + * + * Gets the #GDataTasksQuery:due-min property. If the property is unset, -1 will be returned. + * + * Return value: the UNIX timestamp for the due-min property, or -1 + * + * Since: 0.15.0 + */ +gint64 +gdata_tasks_query_get_due_min (GDataTasksQuery *self) +{ + g_return_val_if_fail (GDATA_IS_TASKS_QUERY (self), -1); + return self->priv->due_min; +} + +/** + * gdata_tasks_query_set_due_min: + * @self: a #GDataTasksQuery + * @due_min: lower bound for a task's due date by UNIX timestamp, or -1 + * + * Sets the #GDataTasksQuery:due-min property of the #GDataTasksQuery + * to the new time/date, @due_min. + * + * Set @due_min to -1 to unset the property in the query URI. + * + * Since: 0.15.0 + */ +void +gdata_tasks_query_set_due_min (GDataTasksQuery *self, gint64 due_min) +{ + g_return_if_fail (GDATA_IS_TASKS_QUERY (self)); + g_return_if_fail (due_min >= -1); + + self->priv->due_min = due_min; + g_object_notify (G_OBJECT (self), "due-min"); + + /* Our current ETag will no longer be relevant. */ + gdata_query_set_etag (GDATA_QUERY (self), NULL); +} + +/** + * gdata_tasks_query_get_show_completed: + * @self: a #GDataTasksQuery + * + * Gets the #GDataTasksQuery:show-completed property. + * + * Return value: the show-completed property + * + * Since: 0.15.0 + */ +gboolean +gdata_tasks_query_get_show_completed (GDataTasksQuery *self) +{ + g_return_val_if_fail (GDATA_IS_TASKS_QUERY (self), FALSE); + return self->priv->show_completed; +} + +/** + * gdata_tasks_query_set_show_completed: + * @self: a #GDataTasksQuery + * @show_completed: %TRUE to show completed tasks, %FALSE otherwise + * + * Sets the #GDataTasksQuery:show-completed property of the #GDataTasksQuery. + * + * Since: 0.15.0 + */ +void +gdata_tasks_query_set_show_completed (GDataTasksQuery *self, gboolean show_completed) +{ + g_return_if_fail (GDATA_IS_TASKS_QUERY (self)); + + self->priv->show_completed = show_completed; + g_object_notify (G_OBJECT (self), "show-completed"); + + /* Our current ETag will no longer be relevant. */ + gdata_query_set_etag (GDATA_QUERY (self), NULL); +} + +/** + * gdata_tasks_query_get_show_deleted: + * @self: a #GDataTasksQuery + * + * Gets the #GDataTasksQuery:show-deleted property. + * + * Return value: the show-deleted property + * + * Since: 0.15.0 + */ +gboolean +gdata_tasks_query_get_show_deleted (GDataTasksQuery *self) +{ + g_return_val_if_fail (GDATA_IS_TASKS_QUERY (self), FALSE); + return self->priv->show_deleted; +} + +/** + * gdata_tasks_query_set_show_deleted: + * @self: a #GDataTasksQuery + * @show_deleted: %TRUE to show deleted tasks, %FALSE otherwise + * + * Sets the #GDataTasksQuery:show-deleted property of the #GDataTasksQuery. + * + * Since: 0.15.0 + */ +void +gdata_tasks_query_set_show_deleted (GDataTasksQuery *self, gboolean show_deleted) +{ + g_return_if_fail (GDATA_IS_TASKS_QUERY (self)); + + self->priv->show_deleted = show_deleted; + g_object_notify (G_OBJECT (self), "show-deleted"); + + /* Our current ETag will no longer be relevant. */ + gdata_query_set_etag (GDATA_QUERY (self), NULL); +} + +/** + * gdata_tasks_query_get_show_hidden: + * @self: a #GDataTasksQuery + * + * Gets the #GDataTasksQuery:show-hidden property. + * + * Return value: the show-hidden property + * + * Since: 0.15.0 + */ +gboolean +gdata_tasks_query_get_show_hidden (GDataTasksQuery *self) +{ + g_return_val_if_fail (GDATA_IS_TASKS_QUERY (self), FALSE); + return self->priv->show_hidden; +} + +/** + * gdata_tasks_query_set_show_hidden: + * @self: a #GDataTasksQuery + * @show_hidden: %TRUE to show hidden tasks, %FALSE otherwise + * + * Sets the #GDataTasksQuery:show-hidden property of the #GDataTasksQuery. + * + * Since: 0.15.0 + */ +void +gdata_tasks_query_set_show_hidden (GDataTasksQuery *self, gboolean show_hidden) +{ + g_return_if_fail (GDATA_IS_TASKS_QUERY (self)); + + self->priv->show_hidden = show_hidden; + g_object_notify (G_OBJECT (self), "show-hidden"); + + /* Our current ETag will no longer be relevant. */ + gdata_query_set_etag (GDATA_QUERY (self), NULL); +} diff --git a/gdata/services/tasks/gdata-tasks-query.h b/gdata/services/tasks/gdata-tasks-query.h new file mode 100644 index 0000000..bb399d9 --- /dev/null +++ b/gdata/services/tasks/gdata-tasks-query.h @@ -0,0 +1,90 @@ +/* -*- Mode: C; indent-tabs-mode: t; c-basic-offset: 8; tab-width: 8 -*- */ +/* + * GData Client + * Copyright (C) Peteris Krisjanis 2013 + * + * GData Client is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * GData Client is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with GData Client. If not, see . + */ + +#ifndef GDATA_TASKS_QUERY_H +#define GDATA_TASKS_QUERY_H + +#include +#include + +#include +#include + +G_BEGIN_DECLS + +#define GDATA_TYPE_TASKS_QUERY (gdata_tasks_query_get_type ()) +#define GDATA_TASKS_QUERY(o) (G_TYPE_CHECK_INSTANCE_CAST ((o), GDATA_TYPE_TASKS_QUERY, GDataTasksQuery)) +#define GDATA_TASKS_QUERY_CLASS(k) (G_TYPE_CHECK_CLASS_CAST((k), GDATA_TYPE_TASKS_QUERY, GDataTasksQueryClass)) +#define GDATA_IS_TASKS_QUERY(o) (G_TYPE_CHECK_INSTANCE_TYPE ((o), GDATA_TYPE_TASKS_QUERY)) +#define GDATA_IS_TASKS_QUERY_CLASS(k) (G_TYPE_CHECK_CLASS_TYPE ((k), GDATA_TYPE_TASKS_QUERY)) +#define GDATA_TASKS_QUERY_GET_CLASS(o) (G_TYPE_INSTANCE_GET_CLASS ((o), GDATA_TYPE_TASKS_QUERY, GDataTasksQueryClass)) + +typedef struct _GDataTasksQueryPrivate GDataTasksQueryPrivate; + +/** + * GDataTasksQuery: + * + * All the fields in the #GDataTasksQuery structure are private and should never be accessed directly. + * + * Since: 0.15.0 + */ +typedef struct { + GDataQuery parent; + GDataTasksQueryPrivate *priv; +} GDataTasksQuery; + +/** + * GDataTasksQueryClass: + * + * All the fields in the #GDataTasksQueryClass structure are private and should never be accessed directly. + * + * Since: 0.15.0 + */ +typedef struct { + /*< private >*/ + GDataQueryClass parent; + + /*< private >*/ + /* Padding for future expansion */ + void (*_g_reserved0) (void); + void (*_g_reserved1) (void); +} GDataTasksQueryClass; + +GType gdata_tasks_query_get_type (void) G_GNUC_CONST; + +GDataTasksQuery *gdata_tasks_query_new (const gchar *q) G_GNUC_WARN_UNUSED_RESULT G_GNUC_MALLOC; + +gint64 gdata_tasks_query_get_completed_max (GDataTasksQuery *self) G_GNUC_PURE; +void gdata_tasks_query_set_completed_max (GDataTasksQuery *self, gint64 completed_max); +gint64 gdata_tasks_query_get_completed_min (GDataTasksQuery *self) G_GNUC_PURE; +void gdata_tasks_query_set_completed_min (GDataTasksQuery *self, gint64 completed_min); +gint64 gdata_tasks_query_get_due_max (GDataTasksQuery *self) G_GNUC_PURE; +void gdata_tasks_query_set_due_max (GDataTasksQuery *self, gint64 due_max); +gint64 gdata_tasks_query_get_due_min (GDataTasksQuery *self) G_GNUC_PURE; +void gdata_tasks_query_set_due_min (GDataTasksQuery *self, gint64 due_min); +gboolean gdata_tasks_query_get_show_completed (GDataTasksQuery *self) G_GNUC_PURE; +void gdata_tasks_query_set_show_completed (GDataTasksQuery *self, gboolean show_completed); +gboolean gdata_tasks_query_get_show_deleted (GDataTasksQuery *self) G_GNUC_PURE; +void gdata_tasks_query_set_show_deleted (GDataTasksQuery *self, gboolean show_deleted); +gboolean gdata_tasks_query_get_show_hidden (GDataTasksQuery *self) G_GNUC_PURE; +void gdata_tasks_query_set_show_hidden (GDataTasksQuery *self, gboolean show_hidden); + +G_END_DECLS + +#endif /* !GDATA_TASKS_QUERY_H */ diff --git a/gdata/services/tasks/gdata-tasks-service.c b/gdata/services/tasks/gdata-tasks-service.c new file mode 100644 index 0000000..4fcbb2c --- /dev/null +++ b/gdata/services/tasks/gdata-tasks-service.c @@ -0,0 +1,872 @@ +/* -*- Mode: C; indent-tabs-mode: t; c-basic-offset: 8; tab-width: 8 -*- */ +/* + * GData Client + * Copyright (C) Peteris Krisjanis 2013 + * + * GData Client is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * GData Client is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with GData Client. If not, see . + */ + +/** + * SECTION:gdata-tasks-service + * @short_description: GData Tasks service object + * @stability: Stable + * @include: gdata/services/tasks/gdata-tasks-service.h + * + * #GDataTasksService is a subclass of #GDataService for communicating with the API of Google Tasks. It supports querying + * for, inserting, editing and deleting tasks from tasklists, as well as operations on the tasklists themselves. + * + * For more details of Google Tasks API, see the + * online documentation. + * + * Since: 0.15.0 + */ + +#include +#include +#include +#include + +#include "gdata-tasks-service.h" +#include "gdata-service.h" +#include "gdata-private.h" +#include "gdata-query.h" +#include "gdata-feed.h" + +/* Standards reference here: https://developers.google.com/google-apps/tasks/v1/reference/ */ + +static void parse_error_response (GDataService *self, + GDataOperationType operation_type, + guint status, const gchar *reason_phrase, + const gchar *response_body, gint length, + GError **error); +static GList *get_authorization_domains (void); + +_GDATA_DEFINE_AUTHORIZATION_DOMAIN (tasks, "tasks", "https://www.googleapis.com/auth/tasks") +G_DEFINE_TYPE (GDataTasksService, gdata_tasks_service, GDATA_TYPE_SERVICE) + +static void +gdata_tasks_service_class_init (GDataTasksServiceClass *klass) +{ + GDataServiceClass *service_class = GDATA_SERVICE_CLASS (klass); + + service_class->feed_type = GDATA_TYPE_FEED; + + service_class->parse_error_response = parse_error_response; + service_class->get_authorization_domains = get_authorization_domains; +} + +static void +gdata_tasks_service_init (GDataTasksService *self) +{ + /* Nothing to see here */ +} + +/* The error format used by the Google Tasks API doesn’t seem to be documented + * anywhere, which is a little frustrating. Here’s an example of it: + * { + * "error": { + * "errors": [ + * { + * "domain": "usageLimits", + * "reason": "dailyLimitExceededUnreg", + * "message": "Daily Limit for Unauthenticated Use Exceeded.", + * "extendedHelp": "https://code.google.com/apis/console" + * } + * ], + * "code": 403, + * "message": "Daily Limit for Unauthenticated Use Exceeded." + * } + * } + * or: + * { + * "error": { + * "errors": [ + * { + * "domain": "global", + * "reason": "authError", + * "message": "Invalid Credentials", + * "locationType": "header", + * "location": "Authorization" + * } + * ], + * "code": 401, + * "message": "Invalid Credentials" + * } + * } + */ +static void +parse_error_response (GDataService *self, GDataOperationType operation_type, + guint status, const gchar *reason_phrase, + const gchar *response_body, gint length, GError **error) +{ + JsonParser *parser = NULL; /* owned */ + JsonReader *reader = NULL; /* owned */ + gint i; + GError *child_error = NULL; + + if (response_body == NULL) { + goto parent; + } + + if (length == -1) { + length = strlen (response_body); + } + + parser = json_parser_new (); + if (!json_parser_load_from_data (parser, response_body, length, + &child_error)) { + goto parent; + } + + reader = json_reader_new (json_parser_get_root (parser)); + + /* Check that the outermost node is an object. */ + if (!json_reader_is_object (reader)) { + goto parent; + } + + /* Grab the ‘error’ member, then its ‘errors’ member. */ + if (!json_reader_read_member (reader, "error") || + !json_reader_is_object (reader) || + !json_reader_read_member (reader, "errors") || + !json_reader_is_array (reader)) { + goto parent; + } + + /* Parse each of the errors. Return the first one, and print out any + * others. */ + for (i = 0; i < json_reader_count_elements (reader); i++) { + const gchar *domain, *reason, *message, *extended_help; + const gchar *location_type, *location; + + /* Parse the error. */ + if (!json_reader_read_element (reader, i) || + !json_reader_is_object (reader)) { + goto parent; + } + + json_reader_read_member (reader, "domain"); + domain = json_reader_get_string_value (reader); + json_reader_end_member (reader); + + json_reader_read_member (reader, "reason"); + reason = json_reader_get_string_value (reader); + json_reader_end_member (reader); + + json_reader_read_member (reader, "message"); + message = json_reader_get_string_value (reader); + json_reader_end_member (reader); + + json_reader_read_member (reader, "extendedHelp"); + extended_help = json_reader_get_string_value (reader); + json_reader_end_member (reader); + + json_reader_read_member (reader, "locationType"); + location_type = json_reader_get_string_value (reader); + json_reader_end_member (reader); + + json_reader_read_member (reader, "location"); + location = json_reader_get_string_value (reader); + json_reader_end_member (reader); + + /* End the error element. */ + json_reader_end_element (reader); + + /* Create an error message, but only for the first error */ + if (error == NULL || *error == NULL) { + if (g_strcmp0 (domain, "usageLimits") == 0 && + g_strcmp0 (reason, + "dailyLimitExceededUnreg") == 0) { + /* Daily Limit for Unauthenticated Use + * Exceeded. */ + g_set_error (error, GDATA_SERVICE_ERROR, + GDATA_SERVICE_ERROR_API_QUOTA_EXCEEDED, + _("You have made too many API " + "calls recently. Please wait a " + "few minutes and try again.")); + } else if (g_strcmp0 (domain, "global") == 0 && + (g_strcmp0 (reason, "authError") == 0 || + g_strcmp0 (reason, "required") == 0)) { + /* Authentication problem */ + g_set_error (error, GDATA_SERVICE_ERROR, + GDATA_SERVICE_ERROR_AUTHENTICATION_REQUIRED, + _("You must be authenticated to " + "do this.")); + } else { + /* Unknown or validation (protocol) error. Fall + * back to working off the HTTP status code. */ + g_warning ("Unknown error code ‘%s’ in domain " + "‘%s’ received with location type " + "‘%s’, location ‘%s’, extended help " + "‘%s’ and message ‘%s’.", + reason, domain, location_type, + location, extended_help, message); + + goto parent; + } + } else { + /* For all errors after the first, log the error in the + * terminal. */ + g_debug ("Error message received in response: domain " + "‘%s’, reason ‘%s’, extended help ‘%s’, " + "message ‘%s’, location type ‘%s’, location " + "‘%s’.", + domain, reason, extended_help, message, + location_type, location); + } + } + + /* End the ‘errors’ and ‘error’ members. */ + json_reader_end_element (reader); + json_reader_end_element (reader); + + g_clear_object (&reader); + g_clear_object (&parser); + + /* Ensure we’ve actually set an error message. */ + g_assert (error == NULL || *error != NULL); + + return; + +parent: + g_clear_object (&reader); + g_clear_object (&parser); + + /* Chain up to the parent class */ + GDATA_SERVICE_CLASS (gdata_tasks_service_parent_class)->parse_error_response (self, operation_type, status, reason_phrase, + response_body, length, error); +} + +static GList * +get_authorization_domains (void) +{ + return g_list_prepend (NULL, get_tasks_authorization_domain ()); +} + +/** + * gdata_tasks_service_new: + * @authorizer: (allow-none): a #GDataAuthorizer to authorize the service's requests, or %NULL + * + * Creates a new #GDataTasksService using the given #GDataAuthorizer. If @authorizer is %NULL, all requests are made as an unauthenticated user. + * + * Return value: a new #GDataTasksService, or %NULL; unref with g_object_unref() + * + * Since: 0.15.0 + */ +GDataTasksService * +gdata_tasks_service_new (GDataAuthorizer *authorizer) +{ + g_return_val_if_fail (authorizer == NULL || GDATA_IS_AUTHORIZER (authorizer), NULL); + + return g_object_new (GDATA_TYPE_TASKS_SERVICE, + "authorizer", authorizer, + NULL); +} + +/** + * gdata_tasks_service_get_primary_authorization_domain: + * + * The primary #GDataAuthorizationDomain for interacting with Google Tasks. This will not normally need to be used, as it's used internally + * by the #GDataTasksService methods. However, if using the plain #GDataService methods to implement custom queries or requests which libgdata + * does not support natively, then this domain may be needed to authorize the requests. + * + * The domain never changes, and is interned so that pointer comparison can be used to differentiate it from other authorization domains. + * + * Return value: (transfer none): the service's authorization domain + * + * Since: 0.15.0 + */ +GDataAuthorizationDomain * +gdata_tasks_service_get_primary_authorization_domain (void) +{ + return get_tasks_authorization_domain (); +} + +/** + * gdata_tasks_service_query_all_tasklists: + * @self: a #GDataTasksService + * @query: (allow-none): a #GDataQuery with the query parameters, or %NULL + * @cancellable: (allow-none): optional #GCancellable object, or %NULL + * @progress_callback: (allow-none) (scope call) (closure progress_user_data): a #GDataQueryProgressCallback to call when an entry is loaded, or %NULL + * @progress_user_data: (closure): data to pass to the @progress_callback function + * @error: (allow-none): a #GError, or %NULL + * + * Queries the service to return a list of all tasklists from the authenticated account which match the given + * @query. It will return all tasklists the user has read access to. + * + * For more details, see gdata_service_query(). + * + * Return value: (transfer full): a #GDataFeed of query results; unref with g_object_unref() + * + * Since: 0.15.0 + */ +GDataFeed * +gdata_tasks_service_query_all_tasklists (GDataTasksService *self, GDataQuery *query, GCancellable *cancellable, + GDataQueryProgressCallback progress_callback, gpointer progress_user_data, GError **error) +{ + GDataFeed *feed; + gchar *request_uri; + + g_return_val_if_fail (GDATA_IS_TASKS_SERVICE (self), NULL); + g_return_val_if_fail (query == NULL || GDATA_IS_QUERY (query), NULL); + g_return_val_if_fail (cancellable == NULL || G_IS_CANCELLABLE (cancellable), NULL); + g_return_val_if_fail (error == NULL || *error == NULL, NULL); + + /* Ensure we're authenticated first */ + if (gdata_authorizer_is_authorized_for_domain (gdata_service_get_authorizer (GDATA_SERVICE (self)), + get_tasks_authorization_domain ()) == FALSE) { + g_set_error_literal (error, GDATA_SERVICE_ERROR, GDATA_SERVICE_ERROR_AUTHENTICATION_REQUIRED, + _("You must be authenticated to query all tasklists.")); + return NULL; + } + + request_uri = g_strconcat (_gdata_service_get_scheme (), "://www.googleapis.com/tasks/v1/users/@me/lists", NULL); + feed = gdata_service_query (GDATA_SERVICE (self), get_tasks_authorization_domain (), request_uri, query, GDATA_TYPE_TASKS_TASKLIST, + cancellable, progress_callback, progress_user_data, error); + g_free (request_uri); + + return feed; +} + +/** + * gdata_tasks_service_query_all_tasklists_async: + * @self: a #GDataTasksService + * @query: (allow-none): a #GDataQuery with the query parameters, or %NULL + * @cancellable: (allow-none): optional #GCancellable object, or %NULL + * @progress_callback: (allow-none) (closure progress_user_data): a #GDataQueryProgressCallback to call when an entry is loaded, or %NULL + * @progress_user_data: (closure): data to pass to the @progress_callback function + * @destroy_progress_user_data: (allow-none): the function to call when @progress_callback will not be called any more, or %NULL. This function will be + * called with @progress_user_data as a parameter and can be used to free any memory allocated for it. + * @callback: a #GAsyncReadyCallback to call when authentication is finished + * @user_data: (closure): data to pass to the @callback function + * + * Queries the service to return a list of all tasklists from the authenticated account which match the given + * @query. @self and @query are all reffed when this function is called, so can safely be unreffed after + * this function returns. + * + * For more details, see gdata_tasks_service_query_all_tasklists(), which is the synchronous version of + * this function, and gdata_service_query_async(), which is the base asynchronous query function. + * + * Since: 0.15.0 + */ +void +gdata_tasks_service_query_all_tasklists_async (GDataTasksService *self, GDataQuery *query, GCancellable *cancellable, + GDataQueryProgressCallback progress_callback, gpointer progress_user_data, + GDestroyNotify destroy_progress_user_data, + GAsyncReadyCallback callback, gpointer user_data) +{ + gchar *request_uri; + + g_return_if_fail (GDATA_IS_TASKS_SERVICE (self)); + g_return_if_fail (query == NULL || GDATA_IS_QUERY (query)); + g_return_if_fail (cancellable == NULL || G_IS_CANCELLABLE (cancellable)); + g_return_if_fail (callback != NULL); + + /* Ensure we're authenticated first */ + if (gdata_authorizer_is_authorized_for_domain (gdata_service_get_authorizer (GDATA_SERVICE (self)), + get_tasks_authorization_domain ()) == FALSE) { + g_autoptr(GTask) task = NULL; + + task = g_task_new (self, cancellable, callback, user_data); + g_task_set_source_tag (task, gdata_service_query_async); + g_task_return_new_error (task, GDATA_SERVICE_ERROR, GDATA_SERVICE_ERROR_AUTHENTICATION_REQUIRED, "%s", + _("You must be authenticated to query all tasklists.")); + + return; + } + + request_uri = g_strconcat (_gdata_service_get_scheme (), "://www.googleapis.com/tasks/v1/users/@me/lists", NULL); + gdata_service_query_async (GDATA_SERVICE (self), get_tasks_authorization_domain (), request_uri, query, GDATA_TYPE_TASKS_TASKLIST, + cancellable, progress_callback, progress_user_data, destroy_progress_user_data, callback, user_data); + g_free (request_uri); +} + +/** + * gdata_tasks_service_query_tasks: + * @self: a #GDataTasksService + * @tasklist: a #GDataTasksTasklist + * @query: (allow-none): a #GDataQuery with the query parameters, or %NULL + * @cancellable: (allow-none): optional #GCancellable object, or %NULL + * @progress_callback: (allow-none) (scope call) (closure progress_user_data): a #GDataQueryProgressCallback to call when an entry is loaded, or %NULL + * @progress_user_data: (closure): data to pass to the @progress_callback function + * @error: (allow-none): a #GError, or %NULL + * + * Queries the service to return a list of tasks in the given @tasklist, which match @query. + * + * For more details, see gdata_service_query(). + * + * Return value: (transfer full): a #GDataFeed of query results; unref with g_object_unref() + * + * Since: 0.15.0 + */ +GDataFeed * +gdata_tasks_service_query_tasks (GDataTasksService *self, GDataTasksTasklist *tasklist, GDataQuery *query, GCancellable *cancellable, + GDataQueryProgressCallback progress_callback, gpointer progress_user_data, GError **error) +{ + gchar* request_uri; + GDataFeed *feed; + + g_return_val_if_fail (GDATA_IS_TASKS_SERVICE (self), NULL); + g_return_val_if_fail (GDATA_IS_TASKS_TASKLIST (tasklist), NULL); + g_return_val_if_fail (gdata_entry_get_id (GDATA_ENTRY (tasklist)) != NULL, NULL); + g_return_val_if_fail (query == NULL || GDATA_IS_QUERY (query), NULL); + g_return_val_if_fail (cancellable == NULL || G_IS_CANCELLABLE (cancellable), NULL); + g_return_val_if_fail (error == NULL || *error == NULL, NULL); + + /* Ensure we're authenticated first */ + if (gdata_authorizer_is_authorized_for_domain (gdata_service_get_authorizer (GDATA_SERVICE (self)), + get_tasks_authorization_domain ()) == FALSE) { + g_set_error_literal (error, GDATA_SERVICE_ERROR, GDATA_SERVICE_ERROR_AUTHENTICATION_REQUIRED, + _("You must be authenticated to query your own tasks.")); + return NULL; + } + + /* Should add /tasks as requested by API */ + request_uri = g_strconcat (_gdata_service_get_scheme (), "://www.googleapis.com/tasks/v1/lists/", gdata_entry_get_id (GDATA_ENTRY (tasklist)), "/tasks", NULL); + /* Execute the query */ + feed = gdata_service_query (GDATA_SERVICE (self), get_tasks_authorization_domain (), request_uri, query, GDATA_TYPE_TASKS_TASK, cancellable, + progress_callback, progress_user_data, error); + g_free (request_uri); + + return feed; +} + +/** + * gdata_tasks_service_query_tasks_async: + * @self: a #GDataTasksService + * @tasklist: a #GDataTasksTasklist + * @query: (allow-none): a #GDataQuery with the query parameters, or %NULL + * @cancellable: (allow-none): optional #GCancellable object, or %NULL + * @progress_callback: (allow-none) (closure progress_user_data): a #GDataQueryProgressCallback to call when an entry is loaded, or %NULL + * @progress_user_data: (closure): data to pass to the @progress_callback function + * @destroy_progress_user_data: (allow-none): the function to call when @progress_callback will not be called any more, or %NULL. This function will be + * called with @progress_user_data as a parameter and can be used to free any memory allocated for it. + * @callback: a #GAsyncReadyCallback to call when the query is finished + * @user_data: (closure): data to pass to the @callback function + * + * Queries the service to return a list of tasks in the given @tasklist, which match @query. @self, @tasklist and @query are all reffed when this + * function is called, so can safely be unreffed after this function returns. + * + * Get the results of the query using gdata_service_query_finish() in the @callback. + * + * For more details, see gdata_tasks_service_query_tasks(), which is the synchronous version of this function, and gdata_service_query_async(), + * which is the base asynchronous query function. + * + * Since: 0.15.0 + */ +void +gdata_tasks_service_query_tasks_async (GDataTasksService *self, GDataTasksTasklist *tasklist, GDataQuery *query, GCancellable *cancellable, + GDataQueryProgressCallback progress_callback, gpointer progress_user_data, + GDestroyNotify destroy_progress_user_data, + GAsyncReadyCallback callback, gpointer user_data) +{ + gchar *request_uri; + + g_return_if_fail (GDATA_IS_TASKS_SERVICE (self)); + g_return_if_fail (GDATA_IS_TASKS_TASKLIST (tasklist)); + g_return_if_fail (gdata_entry_get_id (GDATA_ENTRY (tasklist)) != NULL); + g_return_if_fail (query == NULL || GDATA_IS_QUERY (query)); + g_return_if_fail (cancellable == NULL || G_IS_CANCELLABLE (cancellable)); + g_return_if_fail (callback != NULL); + + /* Ensure we're authenticated first */ + if (gdata_authorizer_is_authorized_for_domain (gdata_service_get_authorizer (GDATA_SERVICE (self)), + get_tasks_authorization_domain ()) == FALSE) { + g_autoptr(GTask) task = NULL; + + task = g_task_new (self, cancellable, callback, user_data); + g_task_set_source_tag (task, gdata_service_query_async); + g_task_return_new_error (task, GDATA_SERVICE_ERROR, GDATA_SERVICE_ERROR_AUTHENTICATION_REQUIRED, "%s", + _("You must be authenticated to query your own tasks.")); + + return; + } + + /* Should add /tasks as requested by API */ + request_uri = g_strconcat (_gdata_service_get_scheme (), "://www.googleapis.com/tasks/v1/lists/", gdata_entry_get_id (GDATA_ENTRY (tasklist)), "/tasks", NULL); + /* Execute the query */ + gdata_service_query_async (GDATA_SERVICE (self), get_tasks_authorization_domain (), request_uri, query, GDATA_TYPE_TASKS_TASK, cancellable, + progress_callback, progress_user_data, destroy_progress_user_data, callback, user_data); + g_free (request_uri); +} + +/** + * gdata_tasks_service_insert_task: + * @self: a #GDataTasksService + * @task: the #GDataTasksTask to insert + * @tasklist: #GDataTasksTasklist to insert into + * @cancellable: (allow-none): optional #GCancellable object, or %NULL + * @error: (allow-none): a #GError, or %NULL + * + * Inserts @task by uploading it to the online tasks service into tasklist @tasklist. It is safe to unref @tasklist after function returns. + * + * For more details, see gdata_service_insert_entry(). + * + * Return value: (transfer full): an updated #GDataTasksTask, or %NULL; unref with g_object_unref() + * + * Since: 0.15.0 + */ +GDataTasksTask * +gdata_tasks_service_insert_task (GDataTasksService *self, GDataTasksTask *task, GDataTasksTasklist *tasklist, GCancellable *cancellable, GError **error) +{ + gchar *request_uri; + GDataEntry *entry; + + g_return_val_if_fail (GDATA_IS_TASKS_SERVICE (self), NULL); + g_return_val_if_fail (GDATA_IS_TASKS_TASK (task), NULL); + g_return_val_if_fail (GDATA_IS_TASKS_TASKLIST (tasklist), NULL); + g_return_val_if_fail (gdata_entry_get_id (GDATA_ENTRY (tasklist)) != NULL, NULL); + g_return_val_if_fail (cancellable == NULL || G_IS_CANCELLABLE (cancellable), NULL); + g_return_val_if_fail (error == NULL || *error == NULL, NULL); + + request_uri = g_strconcat (_gdata_service_get_scheme (), "://www.googleapis.com/tasks/v1/lists/", gdata_entry_get_id (GDATA_ENTRY (tasklist)), "/tasks", NULL); + entry = gdata_service_insert_entry (GDATA_SERVICE (self), get_tasks_authorization_domain (), request_uri, GDATA_ENTRY (task), cancellable, error); + g_free (request_uri); + + return GDATA_TASKS_TASK (entry); +} + +/** + * gdata_tasks_service_insert_task_async: + * @self: a #GDataTasksService + * @task: the #GDataTasksTask to insert + * @tasklist: #GDataTasksTasklist to insert into + * @cancellable: (allow-none): optional #GCancellable object, or %NULL + * @callback: a #GAsyncReadyCallback to call when insertion is finished + * @user_data: (closure): data to pass to the @callback function + * + * Inserts @task by uploading it to the online tasks service into tasklist @tasklist. @self, @task and @tasklist are all reffed when this function is called, so can safely be + * unreffed after this function returns. + * + * @callback should call gdata_service_insert_entry_finish() to obtain a #GDataTasksTask representing the inserted task and to check for possible + * errors. + * + * For more details, see gdata_tasks_service_insert_task(), which is the synchronous version of this function, and + * gdata_service_insert_entry_async(), which is the base asynchronous insertion function. + * + * Since: 0.15.0 + */ +void +gdata_tasks_service_insert_task_async (GDataTasksService *self, GDataTasksTask *task, GDataTasksTasklist *tasklist, GCancellable *cancellable, + GAsyncReadyCallback callback, gpointer user_data) +{ + gchar *request_uri; + + g_return_if_fail (GDATA_IS_TASKS_SERVICE (self)); + g_return_if_fail (GDATA_IS_TASKS_TASK (task)); + g_return_if_fail (GDATA_IS_TASKS_TASKLIST (tasklist)); + g_return_if_fail (gdata_entry_get_id (GDATA_ENTRY (tasklist)) != NULL); + g_return_if_fail (cancellable == NULL || G_IS_CANCELLABLE (cancellable)); + + request_uri = g_strconcat (_gdata_service_get_scheme (), "://www.googleapis.com/tasks/v1/lists/", gdata_entry_get_id (GDATA_ENTRY (tasklist)), "/tasks", NULL); + gdata_service_insert_entry_async (GDATA_SERVICE (self), get_tasks_authorization_domain (), request_uri, GDATA_ENTRY (task), cancellable, + callback, user_data); + g_free (request_uri); +} + +/** + * gdata_tasks_service_insert_tasklist: + * @self: a #GDataTasksService + * @tasklist: #GDataTasksTasklist to insert + * @cancellable: (allow-none): optional #GCancellable object, or %NULL + * @error: (allow-none): a #GError, or %NULL + * + * Inserts @tasklist by uploading it to the online tasks service. + * + * For more details, see gdata_service_insert_entry(). + * + * Return value: (transfer full): an updated #GDataTasksTasklist, or %NULL; unref with g_object_unref() + * + * Since: 0.15.0 + */ +GDataTasksTasklist * +gdata_tasks_service_insert_tasklist (GDataTasksService *self, GDataTasksTasklist *tasklist, GCancellable *cancellable, GError **error) +{ + gchar *request_uri; + GDataEntry *entry; + + g_return_val_if_fail (GDATA_IS_TASKS_SERVICE (self), NULL); + g_return_val_if_fail (GDATA_IS_TASKS_TASKLIST (tasklist), NULL); + g_return_val_if_fail (cancellable == NULL || G_IS_CANCELLABLE (cancellable), NULL); + g_return_val_if_fail (error == NULL || *error == NULL, NULL); + + request_uri = g_strconcat (_gdata_service_get_scheme (), "://www.googleapis.com/tasks/v1/users/@me/lists", NULL); + entry = gdata_service_insert_entry (GDATA_SERVICE (self), get_tasks_authorization_domain (), request_uri, GDATA_ENTRY (tasklist), cancellable, error); + g_free (request_uri); + + return GDATA_TASKS_TASKLIST (entry); +} + +/** + * gdata_tasks_service_insert_tasklist_async: + * @self: a #GDataTasksService + * @tasklist: #GDataTasksTasklist to insert + * @cancellable: (allow-none): optional #GCancellable object, or %NULL + * @callback: a #GAsyncReadyCallback to call when insertion is finished + * @user_data: (closure): data to pass to the @callback function + * + * Inserts @tasklist by uploading it to the online tasks service. @self and @tasklist are both reffed when this function is called, so can safely be + * unreffed after this function returns. + * + * @callback should call gdata_service_insert_entry_finish() to obtain a #GDataTasksTasklist representing the inserted tasklist and to check for possible + * errors. + * + * For more details, see gdata_tasks_service_insert_tasklist(), which is the synchronous version of this function, and + * gdata_service_insert_entry_async(), which is the base asynchronous insertion function. + * + * Since: 0.15.0 + */ +void +gdata_tasks_service_insert_tasklist_async (GDataTasksService *self, GDataTasksTasklist *tasklist, GCancellable *cancellable, + GAsyncReadyCallback callback, gpointer user_data) +{ + gchar *request_uri; + + g_return_if_fail (GDATA_IS_TASKS_SERVICE (self)); + g_return_if_fail (GDATA_IS_TASKS_TASKLIST (tasklist)); + g_return_if_fail (cancellable == NULL || G_IS_CANCELLABLE (cancellable)); + + request_uri = g_strconcat (_gdata_service_get_scheme (), "://www.googleapis.com/tasks/v1/users/@me/lists", NULL); + gdata_service_insert_entry_async (GDATA_SERVICE (self), get_tasks_authorization_domain (), request_uri, GDATA_ENTRY (tasklist), cancellable, + callback, user_data); + g_free (request_uri); +} + +/** + * gdata_tasks_service_delete_task: + * @self: a #GDataTasksService + * @task: the #GDataTasksTask to delete + * @cancellable: (allow-none): optional #GCancellable object, or %NULL + * @error: (allow-none): a #GError, or %NULL + * + * Delete @task from online tasks service. + * + * For more details, see gdata_service_delete_entry(). + * + * Return value: %TRUE on success, %FALSE otherwise + * + * Since: 0.15.0 + */ +gboolean +gdata_tasks_service_delete_task (GDataTasksService *self, GDataTasksTask *task, GCancellable *cancellable, GError **error) +{ + g_return_val_if_fail (GDATA_IS_TASKS_SERVICE (self), FALSE); + g_return_val_if_fail (GDATA_IS_TASKS_TASK (task), FALSE); + g_return_val_if_fail (cancellable == NULL || G_IS_CANCELLABLE (cancellable), FALSE); + g_return_val_if_fail (error == NULL || *error == NULL, FALSE); + + return gdata_service_delete_entry (GDATA_SERVICE (self), get_tasks_authorization_domain (), GDATA_ENTRY (task), cancellable, error); +} + +/** + * gdata_tasks_service_delete_task_async: + * @self: a #GDataTasksService + * @task: #GDataTasksTask to delete + * @cancellable: (allow-none): optional #GCancellable object, or %NULL + * @callback: a #GAsyncReadyCallback to call when insertion is finished + * @user_data: (closure): data to pass to the @callback function + * + * Deletes @task from online tasks service. @self and @task are both reffed when this function is called, so can safely be + * unreffed after this function returns. + * + * @callback should call gdata_service_delete_entry_finish() to finish deleting task and to check for possible + * errors. + * + * For more details, see gdata_tasks_service_delete_task(), which is the synchronous version of this function, and + * gdata_service_delete_entry_async(), which is the base asynchronous insertion function. + * + * Since: 0.15.0 + */ +void +gdata_tasks_service_delete_task_async (GDataTasksService *self, GDataTasksTask *task, GCancellable *cancellable, + GAsyncReadyCallback callback, gpointer user_data) +{ + g_return_if_fail (GDATA_IS_TASKS_SERVICE (self)); + g_return_if_fail (GDATA_IS_TASKS_TASK (task)); + g_return_if_fail (cancellable == NULL || G_IS_CANCELLABLE (cancellable)); + + gdata_service_delete_entry_async (GDATA_SERVICE (self), get_tasks_authorization_domain (), GDATA_ENTRY (task), cancellable, + callback, user_data); +} + +/** + * gdata_tasks_service_delete_tasklist: + * @self: a #GDataTasksService + * @tasklist: the #GDataTasksTasklist to delete + * @cancellable: (allow-none): optional #GCancellable object, or %NULL + * @error: (allow-none): a #GError, or %NULL + * + * Delete @tasklist from online tasks service. + * + * For more details, see gdata_service_delete_entry(). + * + * Return value: %TRUE on success, %FALSE otherwise + * + * Since: 0.15.0 + */ +gboolean +gdata_tasks_service_delete_tasklist (GDataTasksService *self, GDataTasksTasklist *tasklist, GCancellable *cancellable, GError **error) +{ + g_return_val_if_fail (GDATA_IS_TASKS_SERVICE (self), FALSE); + g_return_val_if_fail (GDATA_IS_TASKS_TASKLIST (tasklist), FALSE); + g_return_val_if_fail (cancellable == NULL || G_IS_CANCELLABLE (cancellable), FALSE); + g_return_val_if_fail (error == NULL || *error == NULL, FALSE); + + return gdata_service_delete_entry (GDATA_SERVICE (self), get_tasks_authorization_domain (), GDATA_ENTRY (tasklist), cancellable, error); +} + +/** + * gdata_tasks_service_delete_tasklist_async: + * @self: a #GDataTasksService + * @tasklist: #GDataTasksTasklist to delete + * @cancellable: (allow-none): optional #GCancellable object, or %NULL + * @callback: a #GAsyncReadyCallback to call when insertion is finished + * @user_data: (closure): data to pass to the @callback function + * + * Deletes @tasklist from online tasks service. @self and @tasklist are both reffed when this function is called, so can safely be + * unreffed after this function returns. + * + * @callback should call gdata_service_delete_entry_finish() to finish deleting tasklist and to check for possible + * errors. + * + * For more details, see gdata_tasks_service_delete_tasklist(), which is the synchronous version of this function, and + * gdata_service_delete_entry_async(), which is the base asynchronous insertion function. + * + * Since: 0.15.0 + */ +void +gdata_tasks_service_delete_tasklist_async (GDataTasksService *self, GDataTasksTasklist *tasklist, GCancellable *cancellable, + GAsyncReadyCallback callback, gpointer user_data) +{ + g_return_if_fail (GDATA_IS_TASKS_SERVICE (self)); + g_return_if_fail (GDATA_IS_TASKS_TASKLIST (tasklist)); + g_return_if_fail (cancellable == NULL || G_IS_CANCELLABLE (cancellable)); + + gdata_service_delete_entry_async (GDATA_SERVICE (self), get_tasks_authorization_domain (), GDATA_ENTRY (tasklist), cancellable, + callback, user_data); +} + +/** + * gdata_tasks_service_update_task: + * @self: a #GDataTasksService + * @task: the #GDataTasksTask to update + * @cancellable: (allow-none): optional #GCancellable object, or %NULL + * @error: (allow-none): a #GError, or %NULL + * + * Update @task in online tasks service. + * + * For more details, see gdata_service_update_entry(). + * + * Return value: (transfer full): an updated #GDataTasksTask, or %NULL; unref with g_object_unref() + * + * Since: 0.15.0 + */ +GDataTasksTask * +gdata_tasks_service_update_task (GDataTasksService *self, GDataTasksTask *task, GCancellable *cancellable, GError **error) +{ + g_return_val_if_fail (GDATA_IS_TASKS_SERVICE (self), NULL); + g_return_val_if_fail (GDATA_IS_TASKS_TASK (task), NULL); + g_return_val_if_fail (cancellable == NULL || G_IS_CANCELLABLE (cancellable), NULL); + g_return_val_if_fail (error == NULL || *error == NULL, NULL); + + return GDATA_TASKS_TASK (gdata_service_update_entry (GDATA_SERVICE (self), get_tasks_authorization_domain (), GDATA_ENTRY (task), cancellable, error)); +} + +/** + * gdata_tasks_service_update_task_async: + * @self: a #GDataTasksService + * @task: #GDataTasksTask to update + * @cancellable: (allow-none): optional #GCancellable object, or %NULL + * @callback: a #GAsyncReadyCallback to call when insertion is finished + * @user_data: (closure): data to pass to the @callback function + * + * Updates @task to online tasks service. @self and @task are both reffed when this function is called, so can safely be + * unreffed after this function returns. + * + * @callback should call gdata_service_update_entry_finish() to obtain a #GDataTasksTask representing the updated task and to check for possible + * errors. + * + * For more details, see gdata_tasks_service_update_task(), which is the synchronous version of this function, and + * gdata_service_update_entry_async(), which is the base asynchronous insertion function. + * + * Since: 0.15.0 + */ +void +gdata_tasks_service_update_task_async (GDataTasksService *self, GDataTasksTask *task, GCancellable *cancellable, + GAsyncReadyCallback callback, gpointer user_data) +{ + g_return_if_fail (GDATA_IS_TASKS_SERVICE (self)); + g_return_if_fail (GDATA_IS_TASKS_TASK (task)); + g_return_if_fail (cancellable == NULL || G_IS_CANCELLABLE (cancellable)); + + gdata_service_update_entry_async (GDATA_SERVICE (self), get_tasks_authorization_domain (), GDATA_ENTRY (task), cancellable, + callback, user_data); +} + +/** + * gdata_tasks_service_update_tasklist: + * @self: a #GDataTasksService + * @tasklist: the #GDataTasksTasklist to update + * @cancellable: (allow-none): optional #GCancellable object, or %NULL + * @error: (allow-none): a #GError, or %NULL + * + * Update @tasklist in online tasks service. + * + * For more details, see gdata_service_update_entry(). + * + * Return value: (transfer full): an updated #GDataTasksTasklist, or %NULL; unref with g_object_unref() + * + * Since: 0.15.0 + */ +GDataTasksTasklist * +gdata_tasks_service_update_tasklist (GDataTasksService *self, GDataTasksTasklist *tasklist, GCancellable *cancellable, GError **error) +{ + g_return_val_if_fail (GDATA_IS_TASKS_SERVICE (self), NULL); + g_return_val_if_fail (GDATA_IS_TASKS_TASKLIST (tasklist), NULL); + g_return_val_if_fail (cancellable == NULL || G_IS_CANCELLABLE (cancellable), NULL); + g_return_val_if_fail (error == NULL || *error == NULL, NULL); + + return GDATA_TASKS_TASKLIST (gdata_service_update_entry (GDATA_SERVICE (self), get_tasks_authorization_domain (), GDATA_ENTRY (tasklist), cancellable, error)); +} + +/** + * gdata_tasks_service_update_tasklist_async: + * @self: a #GDataTasksService + * @tasklist: #GDataTasksTasklist to update + * @cancellable: (allow-none): optional #GCancellable object, or %NULL + * @callback: a #GAsyncReadyCallback to call when insertion is finished + * @user_data: (closure): data to pass to the @callback function + * + * Updates @tasklist from online tasks service. @self and @tasklist are both reffed when this function is called, so can safely be + * unreffed after this function returns. + * + * @callback should call gdata_service_update_entry_finish() to obtain a #GDataTasksTasklist representing the updated task and to check for possible + * errors. + * + * For more details, see gdata_tasks_service_update_tasklist(), which is the synchronous version of this function, and + * gdata_service_update_entry_async(), which is the base asynchronous insertion function. + * + * Since: 0.15.0 + */ +void +gdata_tasks_service_update_tasklist_async (GDataTasksService *self, GDataTasksTasklist *tasklist, GCancellable *cancellable, + GAsyncReadyCallback callback, gpointer user_data) +{ + g_return_if_fail (GDATA_IS_TASKS_SERVICE (self)); + g_return_if_fail (GDATA_IS_TASKS_TASKLIST (tasklist)); + g_return_if_fail (cancellable == NULL || G_IS_CANCELLABLE (cancellable)); + + gdata_service_update_entry_async (GDATA_SERVICE (self), get_tasks_authorization_domain (), GDATA_ENTRY (tasklist), cancellable, + callback, user_data); +} diff --git a/gdata/services/tasks/gdata-tasks-service.h b/gdata/services/tasks/gdata-tasks-service.h new file mode 100644 index 0000000..625c217 --- /dev/null +++ b/gdata/services/tasks/gdata-tasks-service.h @@ -0,0 +1,115 @@ +/* -*- Mode: C; indent-tabs-mode: t; c-basic-offset: 8; tab-width: 8 -*- */ +/* + * GData Client + * Copyright (C) Peteris Krisjanis 2013 + * + * GData Client is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * GData Client is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with GData Client. If not, see . + */ + +#ifndef GDATA_TASKS_SERVICE_H +#define GDATA_TASKS_SERVICE_H + +#include +#include + +#include +#include +#include +#include + +G_BEGIN_DECLS + +#define GDATA_TYPE_TASKS_SERVICE (gdata_tasks_service_get_type ()) +#define GDATA_TASKS_SERVICE(o) (G_TYPE_CHECK_INSTANCE_CAST ((o), GDATA_TYPE_TASKS_SERVICE, GDataTasksService)) +#define GDATA_TASKS_SERVICE_CLASS(k) (G_TYPE_CHECK_CLASS_CAST((k), GDATA_TYPE_TASKS_SERVICE, GDataTasksServiceClass)) +#define GDATA_IS_TASKS_SERVICE(o) (G_TYPE_CHECK_INSTANCE_TYPE ((o), GDATA_TYPE_TASKS_SERVICE)) +#define GDATA_IS_TASKS_SERVICE_CLASS(k) (G_TYPE_CHECK_CLASS_TYPE ((k), GDATA_TYPE_TASKS_SERVICE)) +#define GDATA_TASKS_SERVICE_GET_CLASS(o) (G_TYPE_INSTANCE_GET_CLASS ((o), GDATA_TYPE_TASKS_SERVICE, GDataTasksServiceClass)) + +/** + * GDataTasksService: + * + * All the fields in the #GDataTasksService structure are private and should never be accessed directly. + * + * Since: 0.15.0 + */ +typedef struct { + GDataService parent; +} GDataTasksService; + +/** + * GDataTasksServiceClass: + * + * All the fields in the #GDataTasksServiceClass structure are private and should never be accessed directly. + * + * Since: 0.15.0 + */ +typedef struct { + /*< private >*/ + GDataServiceClass parent; + + /*< private >*/ + /* Padding for future expansion */ + void (*_g_reserved0) (void); + void (*_g_reserved1) (void); +} GDataTasksServiceClass; + +GType gdata_tasks_service_get_type (void) G_GNUC_CONST; + +GDataTasksService *gdata_tasks_service_new (GDataAuthorizer *authorizer) G_GNUC_WARN_UNUSED_RESULT G_GNUC_MALLOC; + +GDataAuthorizationDomain *gdata_tasks_service_get_primary_authorization_domain (void) G_GNUC_CONST; + +GDataFeed *gdata_tasks_service_query_all_tasklists (GDataTasksService *self, GDataQuery *query, GCancellable *cancellable, + GDataQueryProgressCallback progress_callback, gpointer progress_user_data, + GError **error) G_GNUC_WARN_UNUSED_RESULT G_GNUC_MALLOC; +void gdata_tasks_service_query_all_tasklists_async (GDataTasksService *self, GDataQuery *query, GCancellable *cancellable, + GDataQueryProgressCallback progress_callback, gpointer progress_user_data, + GDestroyNotify destroy_progress_user_data, GAsyncReadyCallback callback, gpointer user_data); + +GDataFeed *gdata_tasks_service_query_tasks (GDataTasksService *self, GDataTasksTasklist *tasklist, GDataQuery *query, + GCancellable *cancellable, GDataQueryProgressCallback progress_callback, gpointer progress_user_data, + GError **error) G_GNUC_WARN_UNUSED_RESULT G_GNUC_MALLOC; +void gdata_tasks_service_query_tasks_async (GDataTasksService *self, GDataTasksTasklist *tasklist, GDataQuery *query, + GCancellable *cancellable, GDataQueryProgressCallback progress_callback, gpointer progress_user_data, + GDestroyNotify destroy_progress_user_data, GAsyncReadyCallback callback, gpointer user_data); + +GDataTasksTask *gdata_tasks_service_insert_task (GDataTasksService *self, GDataTasksTask *task, GDataTasksTasklist *tasklist, + GCancellable *cancellable, GError **error) G_GNUC_MALLOC G_GNUC_WARN_UNUSED_RESULT; +void gdata_tasks_service_insert_task_async (GDataTasksService *self, GDataTasksTask *task, GDataTasksTasklist *tasklist, + GCancellable *cancellable, GAsyncReadyCallback callback, gpointer user_data); +GDataTasksTasklist *gdata_tasks_service_insert_tasklist (GDataTasksService *self, GDataTasksTasklist *tasklist, + GCancellable *cancellable, GError **error) G_GNUC_MALLOC G_GNUC_WARN_UNUSED_RESULT; +void gdata_tasks_service_insert_tasklist_async (GDataTasksService *self, GDataTasksTasklist *tasklist, + GCancellable *cancellable, GAsyncReadyCallback callback, gpointer user_data); +gboolean gdata_tasks_service_delete_task (GDataTasksService *self, GDataTasksTask *task, + GCancellable *cancellable, GError **error); +void gdata_tasks_service_delete_task_async (GDataTasksService *self, GDataTasksTask *task, + GCancellable *cancellable, GAsyncReadyCallback callback, gpointer user_data); +gboolean gdata_tasks_service_delete_tasklist (GDataTasksService *self, GDataTasksTasklist *tasklist, + GCancellable *cancellable, GError **error); +void gdata_tasks_service_delete_tasklist_async (GDataTasksService *self, GDataTasksTasklist *tasklist, + GCancellable *cancellable, GAsyncReadyCallback callback, gpointer user_data); +GDataTasksTask *gdata_tasks_service_update_task (GDataTasksService *self, GDataTasksTask *task, + GCancellable *cancellable, GError **error) G_GNUC_MALLOC G_GNUC_WARN_UNUSED_RESULT; +void gdata_tasks_service_update_task_async (GDataTasksService *self, GDataTasksTask *task, + GCancellable *cancellable, GAsyncReadyCallback callback, gpointer user_data); +GDataTasksTasklist *gdata_tasks_service_update_tasklist (GDataTasksService *self, GDataTasksTasklist *tasklist, + GCancellable *cancellable, GError **error) G_GNUC_MALLOC G_GNUC_WARN_UNUSED_RESULT; +void gdata_tasks_service_update_tasklist_async (GDataTasksService *self, GDataTasksTasklist *tasklist, + GCancellable *cancellable, GAsyncReadyCallback callback, gpointer user_data); + +G_END_DECLS + +#endif /* !GDATA_TASKS_SERVICE_H */ diff --git a/gdata/services/tasks/gdata-tasks-task.c b/gdata/services/tasks/gdata-tasks-task.c new file mode 100644 index 0000000..265dd13 --- /dev/null +++ b/gdata/services/tasks/gdata-tasks-task.c @@ -0,0 +1,697 @@ +/* -*- Mode: C; indent-tabs-mode: t; c-basic-offset: 8; tab-width: 8 -*- */ +/* + * GData Client + * Copyright (C) Peteris Krisjanis 2013 + * + * GData Client is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * GData Client is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with GData Client. If not, see . + */ + +/** + * SECTION:gdata-tasks-task + * @short_description: GData Tasks task object + * @stability: Stable + * @include: gdata/services/tasks/gdata-tasks-task.h + * + * #GDataTasksTask is a subclass of #GDataEntry to represent a task in a tasklist from Google Tasks. + * + * All functionality of Tasks is currently supported except + * links. + * + * For more details of Google Tasks API, see the + * online documentation. + * + * Since: 0.15.0 + */ + +#include +#include +#include +#include + +#include "gdata-tasks-task.h" +#include "gdata-private.h" +#include "gdata-service.h" +#include "gdata-parser.h" +#include "gdata-types.h" +#include "gdata-comparable.h" + +static void gdata_tasks_task_finalize (GObject *object); +static void gdata_tasks_task_get_property (GObject *object, guint property_id, GValue *value, GParamSpec *pspec); +static void gdata_tasks_task_set_property (GObject *object, guint property_id, const GValue *value, GParamSpec *pspec); +static void get_json (GDataParsable *parsable, JsonBuilder *builder); +static gboolean parse_json (GDataParsable *parsable, JsonReader *reader, gpointer user_data, GError **error); +static const gchar *get_content_type (void); + +struct _GDataTasksTaskPrivate { + gchar *parent; + gchar *position; + gchar *notes; + gchar *status; + gint64 due; + gint64 completed; + gboolean deleted; + gboolean hidden; +}; + +enum { + PROP_PARENT = 1, + PROP_POSITION, + PROP_NOTES, + PROP_STATUS, + PROP_DUE, + PROP_COMPLETED, + PROP_DELETED, + PROP_HIDDEN, +}; + +G_DEFINE_TYPE (GDataTasksTask, gdata_tasks_task, GDATA_TYPE_ENTRY) + +static void +gdata_tasks_task_class_init (GDataTasksTaskClass *klass) +{ + GObjectClass *gobject_class = G_OBJECT_CLASS (klass); + GDataParsableClass *parsable_class = GDATA_PARSABLE_CLASS (klass); + GDataEntryClass *entry_class = GDATA_ENTRY_CLASS (klass); + + g_type_class_add_private (klass, sizeof (GDataTasksTaskPrivate)); + + gobject_class->get_property = gdata_tasks_task_get_property; + gobject_class->set_property = gdata_tasks_task_set_property; + gobject_class->finalize = gdata_tasks_task_finalize; + + parsable_class->parse_json = parse_json; + parsable_class->get_json = get_json; + parsable_class->get_content_type = get_content_type; + + entry_class->kind_term = "tasks#task"; + + /** + * GDataTasksTask:parent: + * + * Parent task identifier. This field is omitted if it is a top-level task. + * + * Since 0.17.10, this property is writable. + * + * Since: 0.15.0 + */ + g_object_class_install_property (gobject_class, PROP_PARENT, + g_param_spec_string ("parent", + "Parent of task", "Identifier of parent task.", + NULL, + G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)); + + /** + * GDataTasksTask:position: + * + * String indicating the position of the task among its sibling tasks under the same parent task + * or at the top level. If this string is greater than another task's corresponding position string + * according to lexicographical ordering, the task is positioned after the other task under the same + * parent task (or at the top level). + * + * Since 0.17.10, this property is writable. + * + * Since: 0.15.0 + */ + g_object_class_install_property (gobject_class, PROP_POSITION, + g_param_spec_string ("position", + "Position of task", "Position of the task among sibling tasks using lexicographical order.", + NULL, + G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)); + + /** + * GDataTasksTask:notes: + * + * This is where the description of what needs to be done in the task is stored. + * + * Since: 0.15.0 + */ + g_object_class_install_property (gobject_class, PROP_NOTES, + g_param_spec_string ("notes", + "Notes of task", "Notes describing the task.", + NULL, + G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)); + + /** + * GDataTasksTask:status: + * + * Status of the task. This is either %GDATA_TASKS_STATUS_NEEDS_ACTION + * or %GDATA_TASKS_STATUS_COMPLETED. + * + * Since: 0.15.0 + */ + g_object_class_install_property (gobject_class, PROP_STATUS, + g_param_spec_string ("status", + "Status of task", "Status of the task.", + NULL, + G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)); + + /** + * GDataTasksTask:due: + * + * Due date of the task (as a RFC 3339 timestamp; seconds since the UNIX + * epoch). + * + * This field is -1 if the task has no due + * date assigned. + * + * Since: 0.15.0 + */ + g_object_class_install_property (gobject_class, PROP_DUE, + g_param_spec_int64 ("due", + "Due date of the task", "Due date of the task.", + -1, G_MAXINT64, -1, + G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)); + + /** + * GDataTasksTask:completed: + * + * Completion date of the task (as a RFC 3339 timestamp; seconds since + * the UNIX epoch). + * + * This field is -1 if the task has not + * been completed. + * + * Since: 0.15.0 + */ + g_object_class_install_property (gobject_class, PROP_COMPLETED, + g_param_spec_int64 ("completed", + "Completion date of task", "Completion date of the task.", + -1, G_MAXINT64, -1, + G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)); + + /** + * GDataTasksTask:is-deleted: + * + * Flag indicating whether the task has been deleted. The default is %FALSE. + * + * Since: 0.15.0 + */ + g_object_class_install_property (gobject_class, PROP_DELETED, + g_param_spec_boolean ("is-deleted", + "Deleted?", "Indicated whatever task is deleted.", + FALSE, + G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)); + + /** + * GDataTasksTask:is-hidden: + * + * Flag indicating whether the task is hidden. This is the case if the task + * had been marked completed when the task list was last cleared. + * The default is %FALSE. This field is read-only. + * + * Since: 0.15.0 + */ + g_object_class_install_property (gobject_class, PROP_HIDDEN, + g_param_spec_boolean ("is-hidden", + "Hidden?", "Indicated whatever task is hidden.", + FALSE, + G_PARAM_READABLE | G_PARAM_STATIC_STRINGS)); +} + +static void +gdata_tasks_task_init (GDataTasksTask *self) +{ + self->priv = G_TYPE_INSTANCE_GET_PRIVATE (self, GDATA_TYPE_TASKS_TASK, GDataTasksTaskPrivate); + self->priv->due = -1; + self->priv->completed = -1; +} + +static void +gdata_tasks_task_finalize (GObject *object) +{ + GDataTasksTaskPrivate *priv = GDATA_TASKS_TASK (object)->priv; + + g_free (priv->parent); + g_free (priv->position); + g_free (priv->notes); + g_free (priv->status); + + /* Chain up to the parent class */ + G_OBJECT_CLASS (gdata_tasks_task_parent_class)->finalize (object); +} + +static void +gdata_tasks_task_get_property (GObject *object, guint property_id, GValue *value, GParamSpec *pspec) +{ + GDataTasksTaskPrivate *priv = GDATA_TASKS_TASK (object)->priv; + + switch (property_id) { + case PROP_PARENT: + g_value_set_string (value, priv->parent); + break; + case PROP_POSITION: + g_value_set_string (value, priv->position); + break; + case PROP_NOTES: + g_value_set_string (value, priv->notes); + break; + case PROP_STATUS: + g_value_set_string (value, priv->status); + break; + case PROP_DUE: + g_value_set_int64 (value, priv->due); + break; + case PROP_COMPLETED: + g_value_set_int64 (value, priv->completed); + break; + case PROP_DELETED: + g_value_set_boolean (value, priv->deleted); + break; + case PROP_HIDDEN: + g_value_set_boolean (value, priv->hidden); + break; + default: + /* We don't have any other property... */ + G_OBJECT_WARN_INVALID_PROPERTY_ID (object, property_id, pspec); + break; + } +} + +static void +gdata_tasks_task_set_property (GObject *object, guint property_id, const GValue *value, GParamSpec *pspec) +{ + GDataTasksTask *self = GDATA_TASKS_TASK (object); + + switch (property_id) { + case PROP_NOTES: + gdata_tasks_task_set_notes (self, g_value_get_string (value)); + break; + case PROP_STATUS: + gdata_tasks_task_set_status (self, g_value_get_string (value)); + break; + case PROP_DUE: + gdata_tasks_task_set_due (self, g_value_get_int64 (value)); + break; + case PROP_COMPLETED: + gdata_tasks_task_set_completed (self, g_value_get_int64 (value)); + break; + case PROP_DELETED: + gdata_tasks_task_set_is_deleted (self, g_value_get_boolean (value)); + break; + case PROP_PARENT: + gdata_tasks_task_set_parent (self, g_value_get_string (value)); + break; + case PROP_POSITION: + gdata_tasks_task_set_position (self, g_value_get_string (value)); + break; + case PROP_HIDDEN: + /* Read-only */ + default: + /* We don't have any other property... */ + G_OBJECT_WARN_INVALID_PROPERTY_ID (object, property_id, pspec); + break; + } +} + +static gboolean +parse_json (GDataParsable *parsable, JsonReader *reader, gpointer user_data, GError **error) +{ + gboolean success; + GDataTasksTask *self = GDATA_TASKS_TASK (parsable); + + if (gdata_parser_string_from_json_member (reader, "parent", P_DEFAULT, &(self->priv->parent), &success, error) == TRUE || + gdata_parser_string_from_json_member (reader, "position", P_DEFAULT, &(self->priv->position), &success, error) == TRUE || + gdata_parser_string_from_json_member (reader, "notes", P_DEFAULT, &(self->priv->notes), &success, error) == TRUE || + gdata_parser_string_from_json_member (reader, "status", P_DEFAULT, &(self->priv->status), &success, error) == TRUE || + gdata_parser_int64_time_from_json_member (reader, "due", P_DEFAULT, &(self->priv->due), &success, error) == TRUE || + gdata_parser_int64_time_from_json_member (reader, "completed", P_DEFAULT, &(self->priv->completed), &success, error) == TRUE || + gdata_parser_boolean_from_json_member (reader, "deleted", P_DEFAULT, &(self->priv->deleted), &success, error) == TRUE || + gdata_parser_boolean_from_json_member (reader, "hidden", P_DEFAULT, &(self->priv->hidden), &success, error) == TRUE) { + return success; + } else { + return GDATA_PARSABLE_CLASS (gdata_tasks_task_parent_class)->parse_json (parsable, reader, user_data, error); + } + + return TRUE; +} + +static void +get_json (GDataParsable *parsable, JsonBuilder *builder) +{ + gchar *due; + gchar *completed; + + GDataTasksTaskPrivate *priv = GDATA_TASKS_TASK (parsable)->priv; + + /* Chain up to the parent class */ + GDATA_PARSABLE_CLASS (gdata_tasks_task_parent_class)->get_json (parsable, builder); + + /* Add all the task specific JSON */ + + if (priv->parent != NULL) { + json_builder_set_member_name (builder, "parent"); + json_builder_add_string_value (builder, priv->parent); + } + if (priv->position != NULL) { + json_builder_set_member_name (builder, "position"); + json_builder_add_string_value (builder, priv->position); + } + if (priv->notes != NULL) { + json_builder_set_member_name (builder, "notes"); + json_builder_add_string_value (builder, priv->notes); + } + if (priv->status != NULL) { + json_builder_set_member_name (builder, "status"); + json_builder_add_string_value (builder, priv->status); + } + if (priv->due != -1) { + due = gdata_parser_int64_to_iso8601 (priv->due); + json_builder_set_member_name (builder, "due"); + json_builder_add_string_value (builder, due); + g_free (due); + } + if (priv->completed != -1) { + completed = gdata_parser_int64_to_iso8601 (priv->completed); + json_builder_set_member_name (builder, "completed"); + json_builder_add_string_value (builder, completed); + g_free (completed); + } + + json_builder_set_member_name (builder, "deleted"); + json_builder_add_boolean_value (builder, priv->deleted); + + json_builder_set_member_name (builder, "hidden"); + json_builder_add_boolean_value (builder, priv->hidden); +} + +static const gchar * +get_content_type (void) +{ + return "application/json"; +} + +/** + * gdata_tasks_task_new: + * @id: (allow-none): the task's ID, or %NULL + * + * Creates a new #GDataTasksTask with the given ID and default properties. + * + * Return value: a new #GDataTasksTask; unref with g_object_unref() + * + * Since: 0.15.0 + */ +GDataTasksTask * +gdata_tasks_task_new (const gchar *id) +{ + return GDATA_TASKS_TASK (g_object_new (GDATA_TYPE_TASKS_TASK, "id", id, NULL)); +} + +/** + * gdata_tasks_task_get_parent: + * @self: a #GDataTasksTask + * + * Gets the #GDataTasksTask:parent property. + * + * Return value: (allow-none): the parent of the task, or %NULL + * + * Since: 0.15.0 + */ +const gchar * +gdata_tasks_task_get_parent (GDataTasksTask *self) +{ + g_return_val_if_fail (GDATA_IS_TASKS_TASK (self), NULL); + return self->priv->parent; +} + +/** + * gdata_tasks_task_set_parent: + * @self: a #GDataTasksTask + * @parent: (nullable): parent of the task + * + * Sets the #GDataTasksTask:parent property. + * + * Since: 0.17.10 + */ +void +gdata_tasks_task_set_parent (GDataTasksTask *self, const gchar *parent) +{ + gchar *local_parent; + g_return_if_fail (GDATA_IS_TASKS_TASK (self)); + + if (g_strcmp0 (self->priv->parent, parent) == 0) + return; + + local_parent = self->priv->parent; + self->priv->parent = g_strdup (parent); + g_free (local_parent); + g_object_notify (G_OBJECT (self), "parent"); +} + +/** + * gdata_tasks_task_get_position: + * @self: a #GDataTasksTask + * + * Gets the #GDataTasksTask:position property. + * + * Return value: (allow-none): the position of the task, or %NULL + * + * Since: 0.15.0 + */ +const gchar * +gdata_tasks_task_get_position (GDataTasksTask *self) +{ + g_return_val_if_fail (GDATA_IS_TASKS_TASK (self), NULL); + return self->priv->position; +} + +/** + * gdata_tasks_task_set_position: + * @self: a #GDataTasksTask + * @position: position of the task in the list + * + * Sets the #GDataTasksTask:position property. + * + * Since: 0.17.10 + */ +void +gdata_tasks_task_set_position (GDataTasksTask *self, const gchar *position) +{ + gchar *local_position; + g_return_if_fail (GDATA_IS_TASKS_TASK (self)); + + if (g_strcmp0 (self->priv->position, position) == 0) + return; + + local_position = self->priv->position; + self->priv->position = g_strdup (position); + g_free (local_position); + g_object_notify (G_OBJECT (self), "position"); +} + +/** + * gdata_tasks_task_get_notes: + * @self: a #GDataTasksTask + * + * Gets the #GDataTasksTask:notes property. + * + * Return value: (allow-none): notes of the task, or %NULL + * + * Since: 0.15.0 + */ +const gchar * +gdata_tasks_task_get_notes (GDataTasksTask *self) +{ + g_return_val_if_fail (GDATA_IS_TASKS_TASK (self), NULL); + return self->priv->notes; +} + +/** + * gdata_tasks_task_set_notes: + * @self: a #GDataTasksTask + * @notes: (allow-none): a new notes of the task, or %NULL + * + * Sets the #GDataTasksTask:notes property to the new notes, @notes. + * + * Set @notes to %NULL to unset the property in the task. + * + * Since: 0.15.0 + */ +void +gdata_tasks_task_set_notes (GDataTasksTask *self, const gchar *notes) +{ + gchar *local_notes; + g_return_if_fail (GDATA_IS_TASKS_TASK (self)); + + local_notes = self->priv->notes; + self->priv->notes = g_strdup (notes); + g_free (local_notes); + g_object_notify (G_OBJECT (self), "notes"); +} + +/** + * gdata_tasks_task_get_status: + * @self: a #GDataTasksTask + * + * Gets the #GDataTasksTask:status property. + * + * Return value: (allow-none): the status of the task, or %NULL + * + * Since: 0.15.0 + */ +const gchar * +gdata_tasks_task_get_status (GDataTasksTask *self) +{ + g_return_val_if_fail (GDATA_IS_TASKS_TASK (self), NULL); + return self->priv->status; +} + +/** + * gdata_tasks_task_set_status: + * @self: a #GDataTasksTask + * @status: (allow-none): a new status of the task, or %NULL + * + * Sets the #GDataTasksTask:status property to the new status, @status. + * + * Set @status to %NULL to unset the property in the task. + * + * Since: 0.15.0 + */ +void +gdata_tasks_task_set_status (GDataTasksTask *self, const gchar *status) +{ + gchar *local_status; + g_return_if_fail (GDATA_IS_TASKS_TASK (self)); + + local_status = self->priv->status; + self->priv->status = g_strdup (status); + g_free (local_status); + g_object_notify (G_OBJECT (self), "status"); +} + +/** + * gdata_tasks_task_get_due: + * @self: a #GDataTasksTask + * + * Gets the #GDataTasksTask:due property. If the property is unset, -1 will be returned. + * + * Return value: the due property, or -1 + * + * Since: 0.15.0 + */ +gint64 +gdata_tasks_task_get_due (GDataTasksTask *self) +{ + g_return_val_if_fail (GDATA_IS_TASKS_TASK (self), -1); + return self->priv->due; +} + +/** + * gdata_tasks_task_set_due: + * @self: a #GDataTasksTask + * @due: due time of the task, or -1 + * + * Sets the #GDataTasksTask:due property of the #GDataTasksTask to the new due time of the task, @due. + * + * Set @due to -1 to unset the property in the due time of the task + * + * Since: 0.15.0 + */ +void +gdata_tasks_task_set_due (GDataTasksTask *self, gint64 due) +{ + g_return_if_fail (GDATA_IS_TASKS_TASK (self)); + g_return_if_fail (due >= -1); + + self->priv->due = due; + g_object_notify (G_OBJECT (self), "due"); +} + +/** + * gdata_tasks_task_get_completed: + * @self: a #GDataTasksTask + * + * Gets the #GDataTasksTask:completed property. If the property is unset, -1 will be returned. + * + * Return value: the completed property, or -1 + * + * Since: 0.15.0 + */ +gint64 +gdata_tasks_task_get_completed (GDataTasksTask *self) +{ + g_return_val_if_fail (GDATA_IS_TASKS_TASK (self), -1); + return self->priv->completed; +} + +/** + * gdata_tasks_task_set_completed: + * @self: a #GDataTasksTask + * @completed: completion time of the task, or -1 + * + * Sets the #GDataTasksTask:completed property of the #GDataTasksTask to the new completion time of the task, @completed. + * + * Set @completed to -1 to unset the property in the completion time of the task + * + * Since: 0.15.0 + */ +void +gdata_tasks_task_set_completed (GDataTasksTask *self, gint64 completed) +{ + g_return_if_fail (GDATA_IS_TASKS_TASK (self)); + g_return_if_fail (completed >= -1); + + self->priv->completed = completed; + g_object_notify (G_OBJECT (self), "completed"); +} + +/** + * gdata_tasks_task_is_deleted: + * @self: a #GDataTasksTask + * + * Gets the #GDataTasksTask:is-deleted property. + * + * Return value: %TRUE if task is deleted, %FALSE otherwise + * + * Since: 0.15.0 + */ +gboolean +gdata_tasks_task_is_deleted (GDataTasksTask *self) +{ + g_return_val_if_fail (GDATA_IS_TASKS_TASK (self), FALSE); + return self->priv->deleted; +} + +/** + * gdata_tasks_task_set_is_deleted: + * @self: a #GDataTasksTask + * @deleted: %TRUE if task is deleted, %FALSE otherwise + * + * Sets the #GDataTasksTask:is-deleted property to @deleted. + * + * Since: 0.15.0 + */ +void +gdata_tasks_task_set_is_deleted (GDataTasksTask *self, gboolean deleted) +{ + g_return_if_fail (GDATA_IS_TASKS_TASK (self)); + self->priv->deleted = deleted; + g_object_notify (G_OBJECT (self), "is-deleted"); +} + +/** + * gdata_tasks_task_is_hidden: + * @self: a #GDataTasksTask + * + * Gets the #GDataTasksTask:is-hidden property. + * + * Return value: %TRUE if task is hidden, %FALSE otherwise + * + * Since: 0.15.0 + */ +gboolean +gdata_tasks_task_is_hidden (GDataTasksTask *self) +{ + g_return_val_if_fail (GDATA_IS_TASKS_TASK (self), FALSE); + return self->priv->hidden; +} diff --git a/gdata/services/tasks/gdata-tasks-task.h b/gdata/services/tasks/gdata-tasks-task.h new file mode 100644 index 0000000..2f28b9c --- /dev/null +++ b/gdata/services/tasks/gdata-tasks-task.h @@ -0,0 +1,118 @@ +/* -*- Mode: C; indent-tabs-mode: t; c-basic-offset: 8; tab-width: 8 -*- */ +/* + * GData Client + * Copyright (C) Peteris Krisjanis 2013 + * + * GData Client is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * GData Client is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with GData Client. If not, see . + */ + +#ifndef GDATA_TASKS_TASK_H +#define GDATA_TASKS_TASK_H + +#include +#include + +#include +#include + +G_BEGIN_DECLS + +/** + * GDATA_TASKS_STATUS_NEEDS_ACTION: + * + * A value for #GDataTasksTask:status indicating the task still needs action + * before it is complete. + * + * Reference: + * + * Google Tasks documentation. + * + * Since: 0.16.0 + */ +#define GDATA_TASKS_STATUS_NEEDS_ACTION "needsAction" + +/** + * GDATA_TASKS_STATUS_COMPLETED: + * + * A value for #GDataTasksTask:status indicating the task has been completed. + * + * Reference: + * + * Google Tasks documentation. + * + * Since: 0.16.0 + */ +#define GDATA_TASKS_STATUS_COMPLETED "completed" + +#define GDATA_TYPE_TASKS_TASK (gdata_tasks_task_get_type ()) +#define GDATA_TASKS_TASK(o) (G_TYPE_CHECK_INSTANCE_CAST ((o), GDATA_TYPE_TASKS_TASK, GDataTasksTask)) +#define GDATA_TASKS_TASK_CLASS(k) (G_TYPE_CHECK_CLASS_CAST((k), GDATA_TYPE_TASKS_TASK, GDataTasksTaskClass)) +#define GDATA_IS_TASKS_TASK(o) (G_TYPE_CHECK_INSTANCE_TYPE ((o), GDATA_TYPE_TASKS_TASK)) +#define GDATA_IS_TASKS_TASK_CLASS(k) (G_TYPE_CHECK_CLASS_TYPE ((k), GDATA_TYPE_TASKS_TASK)) +#define GDATA_TASKS_TASK_GET_CLASS(o) (G_TYPE_INSTANCE_GET_CLASS ((o), GDATA_TYPE_TASKS_TASK, GDataTasksTaskClass)) + +typedef struct _GDataTasksTaskPrivate GDataTasksTaskPrivate; + +/** + * GDataTasksTask: + * + * All the fields in the #GDataTasksTask structure are private and should never be accessed directly. + * + * Since: 0.15.0 + */ +typedef struct { + GDataEntry parent; + GDataTasksTaskPrivate *priv; +} GDataTasksTask; + +/** + * GDataTasksTaskClass: + * + * All the fields in the #GDataTasksTaskClass structure are private and should never be accessed directly. + * + * Since: 0.15.0 + */ +typedef struct { + /*< private >*/ + GDataEntryClass parent; + + /*< private >*/ + /* Padding for future expansion */ + void (*_g_reserved0) (void); + void (*_g_reserved1) (void); +} GDataTasksTaskClass; + +GType gdata_tasks_task_get_type (void) G_GNUC_CONST; + +GDataTasksTask *gdata_tasks_task_new (const gchar *id) G_GNUC_WARN_UNUSED_RESULT G_GNUC_MALLOC; + +const gchar *gdata_tasks_task_get_parent (GDataTasksTask *self) G_GNUC_PURE; +void gdata_tasks_task_set_parent (GDataTasksTask *self, const gchar *parent); +const gchar *gdata_tasks_task_get_position (GDataTasksTask *self) G_GNUC_PURE; +void gdata_tasks_task_set_position (GDataTasksTask *self, const gchar *position); +const gchar *gdata_tasks_task_get_notes (GDataTasksTask *self) G_GNUC_PURE; +void gdata_tasks_task_set_notes (GDataTasksTask *self, const gchar *notes); +const gchar *gdata_tasks_task_get_status (GDataTasksTask *self) G_GNUC_PURE; +void gdata_tasks_task_set_status (GDataTasksTask *self, const gchar *status); +gint64 gdata_tasks_task_get_due (GDataTasksTask *self) G_GNUC_PURE; +void gdata_tasks_task_set_due (GDataTasksTask *self, gint64 due); +gint64 gdata_tasks_task_get_completed (GDataTasksTask *self) G_GNUC_PURE; +void gdata_tasks_task_set_completed (GDataTasksTask *self, gint64 completed); +gboolean gdata_tasks_task_is_deleted (GDataTasksTask *self) G_GNUC_PURE; +void gdata_tasks_task_set_is_deleted (GDataTasksTask *self, gboolean deleted); +gboolean gdata_tasks_task_is_hidden (GDataTasksTask *self) G_GNUC_PURE; + +G_END_DECLS + +#endif /* !GDATA_TASKS_TASK_H */ diff --git a/gdata/services/tasks/gdata-tasks-tasklist.c b/gdata/services/tasks/gdata-tasks-tasklist.c new file mode 100644 index 0000000..1690c23 --- /dev/null +++ b/gdata/services/tasks/gdata-tasks-tasklist.c @@ -0,0 +1,84 @@ +/* -*- Mode: C; indent-tabs-mode: t; c-basic-offset: 8; tab-width: 8 -*- */ +/* + * GData Client + * Copyright (C) Peteris Krisjanis 2013 + * + * GData Client is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * GData Client is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with GData Client. If not, see . + */ + +/** + * SECTION:gdata-tasks-tasklist + * @short_description: GData Tasks tasklist object + * @stability: Stable + * @include: gdata/services/tasks/gdata-tasks-tasklist.h + * + * #GDataTasksTasklist is a subclass of #GDataEntry to represent a tasklist from Google Tasks. + * + * For more details of Google Tasks API, see the + * online documentation. + * + * Since: 0.15.0 + */ + +#include +#include +#include +#include + +#include "gdata-tasks-tasklist.h" +#include "gdata-private.h" +#include "gdata-types.h" + +static const gchar *get_content_type (void); + +G_DEFINE_TYPE (GDataTasksTasklist, gdata_tasks_tasklist, GDATA_TYPE_ENTRY) + +static void +gdata_tasks_tasklist_class_init (GDataTasksTasklistClass *klass) +{ + GDataParsableClass *parsable_class = GDATA_PARSABLE_CLASS (klass); + GDataEntryClass *entry_class = GDATA_ENTRY_CLASS (klass); + + parsable_class->get_content_type = get_content_type; + + entry_class->kind_term = "tasks#taskList"; +} + +static void +gdata_tasks_tasklist_init (GDataTasksTasklist *self) +{ + /* Empty */ +} + +static const gchar * +get_content_type (void) +{ + return "application/json"; +} + +/** + * gdata_tasks_tasklist_new: + * @id: (allow-none): the tasklist's ID, or %NULL + * + * Creates a new #GDataTasksTasklist with the given ID and default properties. + * + * Return value: (transfer full): a new #GDataTasksTasklist; unref with g_object_unref() + * + * Since: 0.15.0 + */ +GDataTasksTasklist * +gdata_tasks_tasklist_new (const gchar *id) +{ + return GDATA_TASKS_TASKLIST (g_object_new (GDATA_TYPE_TASKS_TASKLIST, "id", id, NULL)); +} diff --git a/gdata/services/tasks/gdata-tasks-tasklist.h b/gdata/services/tasks/gdata-tasks-tasklist.h new file mode 100644 index 0000000..ea0c1ca --- /dev/null +++ b/gdata/services/tasks/gdata-tasks-tasklist.h @@ -0,0 +1,73 @@ +/* -*- Mode: C; indent-tabs-mode: t; c-basic-offset: 8; tab-width: 8 -*- */ +/* + * GData Client + * Copyright (C) Peteris Krisjanis 2013 + * + * GData Client is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * GData Client is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with GData Client. If not, see . + */ + +#ifndef GDATA_TASKS_TASKLIST_H +#define GDATA_TASKS_TASKLIST_H + +#include +#include + +#include +#include + +G_BEGIN_DECLS + +#define GDATA_TYPE_TASKS_TASKLIST (gdata_tasks_tasklist_get_type ()) +#define GDATA_TASKS_TASKLIST(o) (G_TYPE_CHECK_INSTANCE_CAST ((o), GDATA_TYPE_TASKS_TASKLIST, GDataTasksTasklist)) +#define GDATA_TASKS_TASKLIST_CLASS(k) (G_TYPE_CHECK_CLASS_CAST((k), GDATA_TYPE_TASKS_TASKLIST, GDataTasksTasklistClass)) +#define GDATA_IS_TASKS_TASKLIST(o) (G_TYPE_CHECK_INSTANCE_TYPE ((o), GDATA_TYPE_TASKS_TASKLIST)) +#define GDATA_IS_TASKS_TASKLIST_CLASS(k) (G_TYPE_CHECK_CLASS_TYPE ((k), GDATA_TYPE_TASKS_TASKLIST)) +#define GDATA_TASKS_TASKLIST_GET_CLASS(o) (G_TYPE_INSTANCE_GET_CLASS ((o), GDATA_TYPE_TASKS_TASKLIST, GDataTasksTasklistClass)) + +/** + * GDataTasksTasklist: + * + * All the fields in the #GDataTasksTasklist structure are private and should never be accessed directly. + * + * Since: 0.15.0 + */ +typedef struct { + GDataEntry parent; +} GDataTasksTasklist; + +/** + * GDataTasksTasklistClass: + * + * All the fields in the #GDataTasksTasklistClass structure are private and should never be accessed directly. + * + * Since: 0.15.0 + */ + +typedef struct { + /*< private >*/ + GDataEntryClass parent; + + /*< private >*/ + /* Padding for future expansion */ + void (*_g_reserved0) (void); + void (*_g_reserved1) (void); +} GDataTasksTasklistClass; + +GType gdata_tasks_tasklist_get_type (void) G_GNUC_CONST; + +GDataTasksTasklist *gdata_tasks_tasklist_new (const gchar *id) G_GNUC_WARN_UNUSED_RESULT G_GNUC_MALLOC; + +G_END_DECLS + +#endif /* !GDATA_TASKS_TASKLIST_H */ diff --git a/gdata/services/tasks/meson.build b/gdata/services/tasks/meson.build new file mode 100644 index 0000000..76ad423 --- /dev/null +++ b/gdata/services/tasks/meson.build @@ -0,0 +1,20 @@ +headers = files( + 'gdata-tasks-query.h', + 'gdata-tasks-service.h', + 'gdata-tasks-task.h', + 'gdata-tasks-tasklist.h', +) + +install_headers( + headers, + subdir: gdata_include_subdir / 'services/tasks', +) + +gir_headers += headers + +sources += files( + 'gdata-tasks-query.c', + 'gdata-tasks-service.c', + 'gdata-tasks-task.c', + 'gdata-tasks-tasklist.c', +) diff --git a/gdata/services/youtube/gdata-youtube-category.c b/gdata/services/youtube/gdata-youtube-category.c new file mode 100644 index 0000000..20af910 --- /dev/null +++ b/gdata/services/youtube/gdata-youtube-category.c @@ -0,0 +1,242 @@ +/* -*- Mode: C; indent-tabs-mode: t; c-basic-offset: 8; tab-width: 8 -*- */ +/* + * GData Client + * Copyright (C) Philip Withnall 2010 + * + * GData Client is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * GData Client is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with GData Client. If not, see . + */ + +/** + * SECTION:gdata-youtube-category + * @short_description: YouTube category element + * @stability: Stable + * @include: gdata/services/youtube/gdata-youtube-category.h + * + * #GDataYouTubeCategory represents the YouTube-specific customizations to #GDataCategory. For more information, + * see the + * online documentation. + * + * Since: 0.7.0 + */ + +#include +#include +#include + +#include "gdata-youtube-category.h" +#include "gdata-parsable.h" +#include "gdata-parser.h" + +static void gdata_youtube_category_finalize (GObject *object); +static void gdata_youtube_category_get_property (GObject *object, guint property_id, GValue *value, GParamSpec *pspec); +static gboolean parse_xml (GDataParsable *parsable, xmlDoc *doc, xmlNode *node, gpointer user_data, GError **error); +static void get_namespaces (GDataParsable *parsable, GHashTable *namespaces); + +struct _GDataYouTubeCategoryPrivate { + gboolean assignable; + gchar **browsable_regions; + /*gboolean deprecated; --- "Categories that are neither assignable or browsable are deprecated and are identified as such using the + * tag." */ +}; + +enum { + PROP_IS_ASSIGNABLE = 1, + PROP_IS_DEPRECATED +}; + +G_DEFINE_TYPE (GDataYouTubeCategory, gdata_youtube_category, GDATA_TYPE_CATEGORY) + +static void +gdata_youtube_category_class_init (GDataYouTubeCategoryClass *klass) +{ + GObjectClass *gobject_class = G_OBJECT_CLASS (klass); + GDataParsableClass *parsable_class = GDATA_PARSABLE_CLASS (klass); + + g_type_class_add_private (klass, sizeof (GDataYouTubeCategoryPrivate)); + + gobject_class->get_property = gdata_youtube_category_get_property; + gobject_class->finalize = gdata_youtube_category_finalize; + + parsable_class->parse_xml = parse_xml; + parsable_class->get_namespaces = get_namespaces; + + /** + * GDataYouTubeCategory:is-assignable: + * + * Whether new videos can be added to the category. + * + * Since: 0.7.0 + */ + g_object_class_install_property (gobject_class, PROP_IS_ASSIGNABLE, + g_param_spec_boolean ("is-assignable", + "Assignable?", "Whether new videos can be added to the category.", + FALSE, + G_PARAM_READABLE | G_PARAM_STATIC_STRINGS)); + + /** + * GDataYouTubeCategory:is-deprecated: + * + * Whether the category is deprecated. + * + * Since: 0.7.0 + */ + g_object_class_install_property (gobject_class, PROP_IS_DEPRECATED, + g_param_spec_boolean ("is-deprecated", + "Deprecated?", "Whether the category is deprecated.", + TRUE, + G_PARAM_READABLE | G_PARAM_STATIC_STRINGS)); +} + +static void +gdata_youtube_category_init (GDataYouTubeCategory *self) +{ + self->priv = G_TYPE_INSTANCE_GET_PRIVATE (self, GDATA_TYPE_YOUTUBE_CATEGORY, GDataYouTubeCategoryPrivate); +} + +static void +gdata_youtube_category_finalize (GObject *object) +{ + GDataYouTubeCategoryPrivate *priv = GDATA_YOUTUBE_CATEGORY (object)->priv; + + g_strfreev (priv->browsable_regions); + + /* Chain up to the parent class */ + G_OBJECT_CLASS (gdata_youtube_category_parent_class)->finalize (object); +} + +static void +gdata_youtube_category_get_property (GObject *object, guint property_id, GValue *value, GParamSpec *pspec) +{ + GDataYouTubeCategoryPrivate *priv = GDATA_YOUTUBE_CATEGORY (object)->priv; + + switch (property_id) { + case PROP_IS_ASSIGNABLE: + g_value_set_boolean (value, priv->assignable); + break; + case PROP_IS_DEPRECATED: + g_value_set_boolean (value, (priv->assignable == FALSE && priv->browsable_regions == NULL) ? TRUE : FALSE); + break; + default: + /* We don't have any other property... */ + G_OBJECT_WARN_INVALID_PROPERTY_ID (object, property_id, pspec); + break; + } +} + +static gboolean +parse_xml (GDataParsable *parsable, xmlDoc *doc, xmlNode *node, gpointer user_data, GError **error) +{ + GDataYouTubeCategory *self = GDATA_YOUTUBE_CATEGORY (parsable); + + if (gdata_parser_is_namespace (node, "http://gdata.youtube.com/schemas/2007") == TRUE) { + if (xmlStrcmp (node->name, (xmlChar*) "assignable") == 0) { + /* yt:assignable */ + self->priv->assignable = TRUE; + } else if (xmlStrcmp (node->name, (xmlChar*) "deprecated") == 0) { + /* yt:deprecated */ + self->priv->assignable = FALSE; + g_strfreev (self->priv->browsable_regions); + self->priv->browsable_regions = NULL; + } else if (xmlStrcmp (node->name, (xmlChar*) "browsable") == 0) { + /* yt:browsable */ + xmlChar *regions; + + regions = xmlGetProp (node, (xmlChar*) "regions"); + if (regions == NULL) + return gdata_parser_error_required_property_missing (node, "regions", error); + + self->priv->browsable_regions = g_strsplit ((gchar*) regions, " ", -1); + xmlFree (regions); + } else { + return GDATA_PARSABLE_CLASS (gdata_youtube_category_parent_class)->parse_xml (parsable, doc, node, user_data, error); + } + } else { + return GDATA_PARSABLE_CLASS (gdata_youtube_category_parent_class)->parse_xml (parsable, doc, node, user_data, error); + } + + return TRUE; +} + +static void +get_namespaces (GDataParsable *parsable, GHashTable *namespaces) +{ + /* Chain up to the parent class */ + GDATA_PARSABLE_CLASS (gdata_youtube_category_parent_class)->get_namespaces (parsable, namespaces); + + g_hash_table_insert (namespaces, (gchar*) "youtube", (gchar*) "http://gdata.youtube.com/schemas/2007"); +} + +/** + * gdata_youtube_category_is_assignable: + * @self: a #GDataYouTubeCategory + * + * Gets the #GDataYouTubeCategory:is-assignable property. + * + * Return value: whether new videos can be assigned to the category + * + * Since: 0.7.0 + */ +gboolean +gdata_youtube_category_is_assignable (GDataYouTubeCategory *self) +{ + g_return_val_if_fail (GDATA_IS_YOUTUBE_CATEGORY (self), FALSE); + return self->priv->assignable; +} + +/** + * gdata_youtube_category_is_browsable: + * @self: a #GDataYouTubeCategory + * @region: a two-letter region ID + * + * Returns whether the category is browsable in the given @region. The list of supported region IDs is + * available online. + * + * Return value: whether the category is browsable in @region + * + * Since: 0.7.0 + */ +gboolean +gdata_youtube_category_is_browsable (GDataYouTubeCategory *self, const gchar *region) +{ + g_return_val_if_fail (GDATA_IS_YOUTUBE_CATEGORY (self), FALSE); + g_return_val_if_fail (region != NULL && *region != '\0', FALSE); + + if (self->priv->browsable_regions != NULL) { + guint i; + + for (i = 0; self->priv->browsable_regions[i] != NULL; i++) { + if (strcmp (self->priv->browsable_regions[i], region) == 0) + return TRUE; + } + } + + return FALSE; +} + +/** + * gdata_youtube_category_is_deprecated: + * @self: a #GDataYouTubeCategory + * + * Gets the #GDataYouTubeCategory:is-deprecated property. + * + * Return value: whether the category is deprecated + * + * Since: 0.7.0 + */ +gboolean +gdata_youtube_category_is_deprecated (GDataYouTubeCategory *self) +{ + g_return_val_if_fail (GDATA_IS_YOUTUBE_CATEGORY (self), TRUE); + return (self->priv->assignable == FALSE && self->priv->browsable_regions == NULL) ? TRUE : FALSE; +} diff --git a/gdata/services/youtube/gdata-youtube-category.h b/gdata/services/youtube/gdata-youtube-category.h new file mode 100644 index 0000000..7b10661 --- /dev/null +++ b/gdata/services/youtube/gdata-youtube-category.h @@ -0,0 +1,77 @@ +/* -*- Mode: C; indent-tabs-mode: t; c-basic-offset: 8; tab-width: 8 -*- */ +/* + * GData Client + * Copyright (C) Philip Withnall 2010 + * + * GData Client is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * GData Client is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with GData Client. If not, see . + */ + +#ifndef GDATA_YOUTUBE_CATEGORY_H +#define GDATA_YOUTUBE_CATEGORY_H + +#include +#include + +#include +#include + +G_BEGIN_DECLS + +#define GDATA_TYPE_YOUTUBE_CATEGORY (gdata_youtube_category_get_type ()) +#define GDATA_YOUTUBE_CATEGORY(o) (G_TYPE_CHECK_INSTANCE_CAST ((o), GDATA_TYPE_YOUTUBE_CATEGORY, GDataYouTubeCategory)) +#define GDATA_YOUTUBE_CATEGORY_CLASS(k) (G_TYPE_CHECK_CLASS_CAST((k), GDATA_TYPE_YOUTUBE_CATEGORY, GDataYouTubeCategoryClass)) +#define GDATA_IS_YOUTUBE_CATEGORY(o) (G_TYPE_CHECK_INSTANCE_TYPE ((o), GDATA_TYPE_YOUTUBE_CATEGORY)) +#define GDATA_IS_YOUTUBE_CATEGORY_CLASS(k) (G_TYPE_CHECK_CLASS_TYPE ((k), GDATA_TYPE_YOUTUBE_CATEGORY)) +#define GDATA_YOUTUBE_CATEGORY_GET_CLASS(o) (G_TYPE_INSTANCE_GET_CLASS ((o), GDATA_TYPE_YOUTUBE_CATEGORY, GDataYouTubeCategoryClass)) + +typedef struct _GDataYouTubeCategoryPrivate GDataYouTubeCategoryPrivate; + +/** + * GDataYouTubeCategory: + * + * All the fields in the #GDataYouTubeCategory structure are private and should never be accessed directly. + * + * Since: 0.7.0 + */ +typedef struct { + GDataCategory parent; + GDataYouTubeCategoryPrivate *priv; +} GDataYouTubeCategory; + +/** + * GDataYouTubeCategoryClass: + * + * All the fields in the #GDataYouTubeCategoryClass structure are private and should never be accessed directly. + * + * Since: 0.7.0 + */ +typedef struct { + /*< private >*/ + GDataCategoryClass parent; + + /*< private >*/ + /* Padding for future expansion */ + void (*_g_reserved0) (void); + void (*_g_reserved1) (void); +} GDataYouTubeCategoryClass; + +GType gdata_youtube_category_get_type (void) G_GNUC_CONST; + +gboolean gdata_youtube_category_is_assignable (GDataYouTubeCategory *self) G_GNUC_PURE; +gboolean gdata_youtube_category_is_browsable (GDataYouTubeCategory *self, const gchar *region) G_GNUC_PURE; +gboolean gdata_youtube_category_is_deprecated (GDataYouTubeCategory *self) G_GNUC_PURE; + +G_END_DECLS + +#endif /* !GDATA_YOUTUBE_CATEGORY_H */ diff --git a/gdata/services/youtube/gdata-youtube-comment.c b/gdata/services/youtube/gdata-youtube-comment.c new file mode 100644 index 0000000..1a19847 --- /dev/null +++ b/gdata/services/youtube/gdata-youtube-comment.c @@ -0,0 +1,576 @@ +/* -*- Mode: C; indent-tabs-mode: t; c-basic-offset: 8; tab-width: 8 -*- */ +/* + * GData Client + * Copyright (C) Philip Withnall 2011, 2015 + * + * GData Client is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * GData Client is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with GData Client. If not, see . + */ + +/** + * SECTION:gdata-youtube-comment + * @short_description: GData YouTube comment object + * @stability: Stable + * @include: gdata/services/youtube/gdata-youtube-comment.h + * + * #GDataYouTubeComment is a subclass of #GDataComment to represent a comment on a #GDataYouTubeVideo. It is returned by the #GDataCommentable + * interface implementation on #GDataYouTubeVideo. + * + * It's possible to query for and add #GDataYouTubeComments, but it is not possible to delete #GDataYouTubeComments from any video + * using the GData API. + * + * Comments on YouTube videos can be arranged in a hierarchy by their #GDataYouTubeComment:parent-comment-uris. If a + * #GDataYouTubeComment's parent comment URI is non-%NULL, it should match the %GDATA_LINK_SELF #GDataLink of another #GDataYouTubeComment on + * the same video (as retrieved using gdata_entry_look_up_link() on the comments). Comments with #GDataYouTubeComment:parent-comment-uri set to %NULL + * are top-level comments. + * + * Since: 0.10.0 + */ + +#include +#include + +#include "gdata-parser.h" +#include "gdata-private.h" +#include "gdata-youtube-comment.h" + +#define GDATA_LINK_PARENT_COMMENT_URI "http://gdata.youtube.com/schemas/2007#in-reply-to" + +static void gdata_youtube_comment_set_property (GObject *object, guint property_id, const GValue *value, GParamSpec *pspec); +static void gdata_youtube_comment_get_property (GObject *object, guint property_id, GValue *value, GParamSpec *pspec); +static void gdata_youtube_comment_finalize (GObject *object); +static gboolean parse_json (GDataParsable *parsable, JsonReader *reader, gpointer user_data, GError **error); +static void get_json (GDataParsable *parsable, JsonBuilder *builder); +static const gchar *get_content_type (void); + +struct _GDataYouTubeCommentPrivate { + gchar *channel_id; /* owned */ + gchar *video_id; /* owned */ + gboolean can_reply; +}; + +enum { + PROP_PARENT_COMMENT_URI = 1, +}; + +G_DEFINE_TYPE (GDataYouTubeComment, gdata_youtube_comment, GDATA_TYPE_COMMENT) + +static void +gdata_youtube_comment_class_init (GDataYouTubeCommentClass *klass) +{ + GObjectClass *gobject_class = G_OBJECT_CLASS (klass); + GDataParsableClass *parsable_class = GDATA_PARSABLE_CLASS (klass); + GDataEntryClass *entry_class = GDATA_ENTRY_CLASS (klass); + + g_type_class_add_private (klass, sizeof (GDataYouTubeCommentPrivate)); + + gobject_class->get_property = gdata_youtube_comment_get_property; + gobject_class->set_property = gdata_youtube_comment_set_property; + gobject_class->finalize = gdata_youtube_comment_finalize; + + parsable_class->parse_json = parse_json; + parsable_class->get_json = get_json; + parsable_class->get_content_type = get_content_type; + + entry_class->kind_term = "youtube#commentThread"; + + /** + * GDataYouTubeComment:parent-comment-uri: + * + * The URI of the parent comment to this one, or %NULL if this comment is a top-level comment. + * + * See the documentation for #GDataYouTubeComment for an explanation of the semantics of parent comment URIs. + * + * Since: 0.10.0 + */ + g_object_class_install_property (gobject_class, PROP_PARENT_COMMENT_URI, + g_param_spec_string ("parent-comment-uri", + "Parent comment URI", "The URI of the parent comment to this one.", + NULL, + G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)); +} + +static void +gdata_youtube_comment_init (GDataYouTubeComment *self) +{ + self->priv = G_TYPE_INSTANCE_GET_PRIVATE (self, GDATA_TYPE_YOUTUBE_COMMENT, GDataYouTubeCommentPrivate); +} + +static void +gdata_youtube_comment_get_property (GObject *object, guint property_id, GValue *value, GParamSpec *pspec) +{ + GDataYouTubeComment *self = GDATA_YOUTUBE_COMMENT (object); + + switch (property_id) { + case PROP_PARENT_COMMENT_URI: + g_value_set_string (value, gdata_youtube_comment_get_parent_comment_uri (self)); + break; + default: + /* We don't have any other property... */ + G_OBJECT_WARN_INVALID_PROPERTY_ID (object, property_id, pspec); + break; + } +} + +static void +gdata_youtube_comment_set_property (GObject *object, guint property_id, const GValue *value, GParamSpec *pspec) +{ + GDataYouTubeComment *self = GDATA_YOUTUBE_COMMENT (object); + + switch (property_id) { + case PROP_PARENT_COMMENT_URI: + gdata_youtube_comment_set_parent_comment_uri (self, g_value_get_string (value)); + break; + default: + /* We don't have any other property... */ + G_OBJECT_WARN_INVALID_PROPERTY_ID (object, property_id, pspec); + break; + } +} + +static void +gdata_youtube_comment_finalize (GObject *object) +{ + GDataYouTubeCommentPrivate *priv = GDATA_YOUTUBE_COMMENT (object)->priv; + + g_free (priv->channel_id); + g_free (priv->video_id); + + /* Chain up to the parent class */ + G_OBJECT_CLASS (gdata_youtube_comment_parent_class)->finalize (object); +} + +/* Reference: https://developers.google.com/youtube/v3/docs/comments#resource */ +static gboolean +parse_comment (GDataParsable *parsable, JsonReader *reader, GError **error) +{ + GDataYouTubeComment *self = GDATA_YOUTUBE_COMMENT (parsable); + const gchar *id, *etag, *parent_id, *author_name, *author_uri; + const gchar *published_at, *updated_at; + gint64 published, updated; + + /* Check this is an object. */ + if (!json_reader_is_object (reader)) { + return gdata_parser_error_required_json_content_missing (reader, error); + } + + /* id */ + json_reader_read_member (reader, "id"); + id = json_reader_get_string_value (reader); + json_reader_end_member (reader); + + /* Empty ID? */ + if (id == NULL || *id == '\0') { + return gdata_parser_error_required_json_content_missing (reader, error); + } + + _gdata_entry_set_id (GDATA_ENTRY (parsable), id); + + /* etag */ + json_reader_read_member (reader, "etag"); + etag = json_reader_get_string_value (reader); + json_reader_end_member (reader); + + /* Empty ETag? */ + if (etag != NULL && *id == '\0') { + return gdata_parser_error_required_json_content_missing (reader, error); + } + + _gdata_entry_set_etag (GDATA_ENTRY (parsable), etag); + + /* snippet */ + json_reader_read_member (reader, "snippet"); + + if (!json_reader_is_object (reader)) { + json_reader_end_member (reader); + return gdata_parser_error_required_json_content_missing (reader, error); + } + + json_reader_read_member (reader, "textDisplay"); + gdata_entry_set_content (GDATA_ENTRY (self), + json_reader_get_string_value (reader)); + json_reader_end_member (reader); + + json_reader_read_member (reader, "parentId"); + parent_id = json_reader_get_string_value (reader); + json_reader_end_member (reader); + + if (parent_id != NULL) { + gchar *uri = NULL; + + uri = _gdata_service_build_uri ("https://www.googleapis.com" + "/youtube/v3/comments" + "?part=snippet" + "&id=%s", parent_id); + gdata_youtube_comment_set_parent_comment_uri (self, uri); + g_free (uri); + } + + json_reader_read_member (reader, "authorDisplayName"); + author_name = json_reader_get_string_value (reader); + json_reader_end_member (reader); + + json_reader_read_member (reader, "authorChannelUrl"); + author_uri = json_reader_get_string_value (reader); + json_reader_end_member (reader); + + if (author_name != NULL && *author_name != '\0') { + GDataAuthor *author = NULL; + + author = gdata_author_new (author_name, author_uri, NULL); + gdata_entry_add_author (GDATA_ENTRY (self), author); + } + + json_reader_read_member (reader, "publishedAt"); + published_at = json_reader_get_string_value (reader); + json_reader_end_member (reader); + + if (published_at != NULL && + gdata_parser_int64_from_iso8601 (published_at, &published)) { + _gdata_entry_set_published (GDATA_ENTRY (self), published); + } else if (published_at != NULL) { + /* Error */ + gdata_parser_error_not_iso8601_format_json (reader, + published_at, + error); + json_reader_end_member (reader); + return FALSE; + } + + json_reader_read_member (reader, "updatedAt"); + updated_at = json_reader_get_string_value (reader); + json_reader_end_member (reader); + + if (updated_at != NULL && + gdata_parser_int64_from_iso8601 (updated_at, &updated)) { + _gdata_entry_set_updated (GDATA_ENTRY (self), updated); + } else if (updated_at != NULL) { + /* Error */ + gdata_parser_error_not_iso8601_format_json (reader, + updated_at, + error); + json_reader_end_member (reader); + return FALSE; + } + + /* FIXME: Implement: + * - channelId + * - videoId + * - textOriginal + * - canRate + * - viewerRating + * - likeCount + * - moderationStatus + * - authorProfileImageUrl + * - authorChannelId + * - authorGoogleplusProfileUrl + */ + + json_reader_end_member (reader); + + return TRUE; +} + +/* Reference: https://developers.google.com/youtube/v3/docs/commentThreads#resource */ +static gboolean +parse_json (GDataParsable *parsable, JsonReader *reader, gpointer user_data, GError **error) +{ + gboolean success; + GDataYouTubeComment *self = GDATA_YOUTUBE_COMMENT (parsable); + GDataYouTubeCommentPrivate *priv = self->priv; + + if (g_strcmp0 (json_reader_get_member_name (reader), "snippet") == 0) { + guint i; + + /* Check this is an object. */ + if (!json_reader_is_object (reader)) { + return gdata_parser_error_required_json_content_missing (reader, error); + } + + for (i = 0; i < (guint) json_reader_count_members (reader); i++) { + json_reader_read_element (reader, i); + + if (gdata_parser_string_from_json_member (reader, "channelId", P_DEFAULT, &priv->channel_id, &success, error) || + gdata_parser_string_from_json_member (reader, "videoId", P_DEFAULT, &priv->video_id, &success, error) || + gdata_parser_boolean_from_json_member (reader, "canReply", P_DEFAULT, &priv->can_reply, &success, error)) { + /* Fall through. */ + } else if (g_strcmp0 (json_reader_get_member_name (reader), "topLevelComment") == 0) { + success = parse_comment (parsable, reader, error); + } + + json_reader_end_element (reader); + + if (!success) { + return FALSE; + } + } + + return TRUE; + } else { + return GDATA_PARSABLE_CLASS (gdata_youtube_comment_parent_class)->parse_json (parsable, reader, user_data, error); + } + + return TRUE; +} + +/* Reference: https://developers.google.com/youtube/v3/docs/comments#resource */ +static void +get_comment (GDataParsable *parsable, JsonBuilder *builder) +{ + GDataYouTubeComment *self = GDATA_YOUTUBE_COMMENT (parsable); + GDataEntry *entry = GDATA_ENTRY (parsable); + GDataYouTubeCommentPrivate *priv = GDATA_YOUTUBE_COMMENT (parsable)->priv; + + json_builder_set_member_name (builder, "kind"); + json_builder_add_string_value (builder, "youtube#comment"); + + if (gdata_entry_get_etag (entry) != NULL) { + json_builder_set_member_name (builder, "etag"); + json_builder_add_string_value (builder, + gdata_entry_get_etag (entry)); + } + + if (gdata_entry_get_id (entry) != NULL) { + json_builder_set_member_name (builder, "id"); + json_builder_add_string_value (builder, + gdata_entry_get_id (entry)); + } + + json_builder_set_member_name (builder, "snippet"); + json_builder_begin_object (builder); + + if (priv->channel_id != NULL) { + json_builder_set_member_name (builder, "channelId"); + json_builder_add_string_value (builder, priv->channel_id); + } + + if (priv->video_id != NULL) { + json_builder_set_member_name (builder, "videoId"); + json_builder_add_string_value (builder, priv->video_id); + } + + /* Note we build textOriginal and parse textDisplay. */ + if (gdata_entry_get_content (entry) != NULL) { + json_builder_set_member_name (builder, "textOriginal"); + json_builder_add_string_value (builder, + gdata_entry_get_content (entry)); + } + + if (gdata_youtube_comment_get_parent_comment_uri (self) != NULL) { + json_builder_set_member_name (builder, "parentId"); + json_builder_add_string_value (builder, + gdata_youtube_comment_get_parent_comment_uri (self)); + } + + json_builder_end_object (builder); +} + +/* Reference: https://developers.google.com/youtube/v3/docs/commentThreads#resource + * + * Sort of. If creating a new top-level comment, we need to create a + * commentThread; otherwise we need to create a comment. */ +static void +get_json (GDataParsable *parsable, JsonBuilder *builder) +{ + GDataEntry *entry = GDATA_ENTRY (parsable); + GDataYouTubeCommentPrivate *priv = GDATA_YOUTUBE_COMMENT (parsable)->priv; + + /* Don’t chain up because it’s mostly irrelevant. */ + json_builder_set_member_name (builder, "kind"); + json_builder_add_string_value (builder, "youtube#commentThread"); + + if (gdata_entry_get_etag (entry) != NULL) { + json_builder_set_member_name (builder, "etag"); + json_builder_add_string_value (builder, + gdata_entry_get_etag (entry)); + } + + if (gdata_entry_get_id (entry) != NULL) { + json_builder_set_member_name (builder, "id"); + json_builder_add_string_value (builder, + gdata_entry_get_id (entry)); + } + + /* snippet object. */ + json_builder_set_member_name (builder, "snippet"); + json_builder_begin_object (builder); + + if (priv->channel_id != NULL) { + json_builder_set_member_name (builder, "channelId"); + json_builder_add_string_value (builder, priv->channel_id); + } + + if (priv->video_id != NULL) { + json_builder_set_member_name (builder, "videoId"); + json_builder_add_string_value (builder, priv->video_id); + } + + json_builder_set_member_name (builder, "topLevelComment"); + json_builder_begin_object (builder); + get_comment (parsable, builder); + json_builder_end_object (builder); + + json_builder_end_object (builder); +} + +static const gchar * +get_content_type (void) +{ + return "application/json"; +} + +/** + * gdata_youtube_comment_new: + * @id: the comment's ID, or %NULL + * + * Creates a new #GDataYouTubeComment with the given ID and default properties. + * + * Return value: a new #GDataYouTubeComment; unref with g_object_unref() + * + * Since: 0.10.0 + */ +GDataYouTubeComment * +gdata_youtube_comment_new (const gchar *id) +{ + return GDATA_YOUTUBE_COMMENT (g_object_new (GDATA_TYPE_YOUTUBE_COMMENT, + "id", id, + NULL)); +} + +/** + * gdata_youtube_comment_get_parent_comment_uri: + * @self: a #GDataYouTubeComment + * + * Gets the #GDataYouTubeComment:parent-comment-uri property. + * + * Return value: the parent comment URI, or %NULL + * + * Since: 0.10.0 + */ +const gchar * +gdata_youtube_comment_get_parent_comment_uri (GDataYouTubeComment *self) +{ + GDataLink *link_; + + g_return_val_if_fail (GDATA_IS_YOUTUBE_COMMENT (self), NULL); + + link_ = gdata_entry_look_up_link (GDATA_ENTRY (self), GDATA_LINK_PARENT_COMMENT_URI); + if (link_ == NULL) { + return NULL; + } + + return gdata_link_get_uri (link_); +} + +/** + * gdata_youtube_comment_set_parent_comment_uri: + * @self: a #GDataYouTubeComment + * @parent_comment_uri: a new parent comment URI, or %NULL + * + * Sets the #GDataYouTubeComment:parent-comment-uri property to @parent_comment_uri. + * + * Set @parent_comment_uri to %NULL to unset the #GDataYouTubeComment:parent-comment-uri property in the comment (i.e. make the comment a top-level + * comment). + * + * See the online + * documentation for more information. + * + * Since: 0.10.0 + */ +void +gdata_youtube_comment_set_parent_comment_uri (GDataYouTubeComment *self, const gchar *parent_comment_uri) +{ + GDataLink *link_; + + g_return_if_fail (GDATA_IS_YOUTUBE_COMMENT (self)); + g_return_if_fail (parent_comment_uri == NULL || *parent_comment_uri != '\0'); + + link_ = gdata_entry_look_up_link (GDATA_ENTRY (self), GDATA_LINK_PARENT_COMMENT_URI); + + if ((link_ == NULL && parent_comment_uri == NULL) || + (link_ != NULL && parent_comment_uri != NULL && g_strcmp0 (gdata_link_get_uri (link_), parent_comment_uri) == 0)) { + /* Nothing to do. */ + return; + } else if (link_ == NULL && parent_comment_uri != NULL) { + /* Add the new link. */ + link_ = gdata_link_new (parent_comment_uri, GDATA_LINK_PARENT_COMMENT_URI); + gdata_entry_add_link (GDATA_ENTRY (self), link_); + g_object_unref (link_); + } else if (link_ != NULL && parent_comment_uri == NULL) { + /* Remove the old link. */ + gdata_entry_remove_link (GDATA_ENTRY (self), link_); + } else if (link_ != NULL && parent_comment_uri != NULL) { + /* Update the existing link. */ + gdata_link_set_uri (link_, parent_comment_uri); + } + + g_object_notify (G_OBJECT (self), "parent-comment-uri"); +} + +G_GNUC_INTERNAL void +_gdata_youtube_comment_set_video_id (GDataYouTubeComment *self, + const gchar *video_id); +G_GNUC_INTERNAL void +_gdata_youtube_comment_set_channel_id (GDataYouTubeComment *self, + const gchar *channel_id); + +/** + * _gdata_youtube_comment_set_video_id: + * @self: a #GDataYouTubeComment + * @video_id: (nullable): the comment’s video ID, or %NULL + * + * Set the ID of the video the comment is attached to. This may be %NULL if the + * comment has not yet been inserted, or if it is just attached to a channel + * rather than a video. + * + * Since: 0.17.2 + */ +void +_gdata_youtube_comment_set_video_id (GDataYouTubeComment *self, + const gchar *video_id) +{ + GDataYouTubeCommentPrivate *priv; + + g_return_if_fail (GDATA_IS_YOUTUBE_COMMENT (self)); + g_return_if_fail (video_id == NULL || *video_id != '\0'); + + priv = self->priv; + + g_free (priv->video_id); + priv->video_id = g_strdup (video_id); +} + +/** + * _gdata_youtube_comment_set_channel_id: + * @self: a #GDataYouTubeComment + * @channel_id: (nullable): the comment’s channel ID, or %NULL + * + * Set the ID of the channel the comment is attached to. This may be %NULL if + * the comment has not yet been inserted, but must be set otherwise. + * + * Since: 0.17.2 + */ +void +_gdata_youtube_comment_set_channel_id (GDataYouTubeComment *self, + const gchar *channel_id) +{ + GDataYouTubeCommentPrivate *priv; + + g_return_if_fail (GDATA_IS_YOUTUBE_COMMENT (self)); + g_return_if_fail (channel_id == NULL || *channel_id != '\0'); + + priv = self->priv; + + g_free (priv->channel_id); + priv->channel_id = g_strdup (channel_id); +} diff --git a/gdata/services/youtube/gdata-youtube-comment.h b/gdata/services/youtube/gdata-youtube-comment.h new file mode 100644 index 0000000..f26bc27 --- /dev/null +++ b/gdata/services/youtube/gdata-youtube-comment.h @@ -0,0 +1,77 @@ +/* -*- Mode: C; indent-tabs-mode: t; c-basic-offset: 8; tab-width: 8 -*- */ +/* + * GData Client + * Copyright (C) Philip Withnall 2011 + * + * GData Client is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * GData Client is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with GData Client. If not, see . + */ + +#ifndef GDATA_YOUTUBE_COMMENT_H +#define GDATA_YOUTUBE_COMMENT_H + +#include +#include + +#include + +G_BEGIN_DECLS + +#define GDATA_TYPE_YOUTUBE_COMMENT (gdata_youtube_comment_get_type ()) +#define GDATA_YOUTUBE_COMMENT(o) (G_TYPE_CHECK_INSTANCE_CAST ((o), GDATA_TYPE_YOUTUBE_COMMENT, GDataYouTubeComment)) +#define GDATA_YOUTUBE_COMMENT_CLASS(k) (G_TYPE_CHECK_CLASS_CAST((k), GDATA_TYPE_YOUTUBE_COMMENT, GDataYouTubeCommentClass)) +#define GDATA_IS_YOUTUBE_COMMENT(o) (G_TYPE_CHECK_INSTANCE_TYPE ((o), GDATA_TYPE_YOUTUBE_COMMENT)) +#define GDATA_IS_YOUTUBE_COMMENT_CLASS(k) (G_TYPE_CHECK_CLASS_TYPE ((k), GDATA_TYPE_YOUTUBE_COMMENT)) +#define GDATA_YOUTUBE_COMMENT_GET_CLASS(o) (G_TYPE_INSTANCE_GET_CLASS ((o), GDATA_TYPE_YOUTUBE_COMMENT, GDataYouTubeCommentClass)) + +typedef struct _GDataYouTubeCommentPrivate GDataYouTubeCommentPrivate; + +/** + * GDataYouTubeComment: + * + * All the fields in the #GDataYouTubeComment structure are private and should never be accessed directly. + * + * Since: 0.10.0 + */ +typedef struct { + GDataComment parent; + GDataYouTubeCommentPrivate *priv; +} GDataYouTubeComment; + +/** + * GDataYouTubeCommentClass: + * + * All the fields in the #GDataYouTubeCommentClass structure are private and should never be accessed directly. + * + * Since: 0.10.0 + */ +typedef struct { + /*< private >*/ + GDataCommentClass parent; + + /*< private >*/ + /* Padding for future expansion */ + void (*_g_reserved0) (void); + void (*_g_reserved1) (void); +} GDataYouTubeCommentClass; + +GType gdata_youtube_comment_get_type (void) G_GNUC_CONST; + +GDataYouTubeComment *gdata_youtube_comment_new (const gchar *id) G_GNUC_WARN_UNUSED_RESULT G_GNUC_MALLOC; + +const gchar *gdata_youtube_comment_get_parent_comment_uri (GDataYouTubeComment *self) G_GNUC_PURE; +void gdata_youtube_comment_set_parent_comment_uri (GDataYouTubeComment *self, const gchar *parent_comment_uri); + +G_END_DECLS + +#endif /* !GDATA_YOUTUBE_COMMENT_H */ diff --git a/gdata/services/youtube/gdata-youtube-content.c b/gdata/services/youtube/gdata-youtube-content.c new file mode 100644 index 0000000..3b9126e --- /dev/null +++ b/gdata/services/youtube/gdata-youtube-content.c @@ -0,0 +1,157 @@ +/* -*- Mode: C; indent-tabs-mode: t; c-basic-offset: 8; tab-width: 8 -*- */ +/* + * GData Client + * Copyright (C) Philip Withnall 2009–2010, 2015 + * + * GData Client is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * GData Client is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with GData Client. If not, see . + */ + +/** + * SECTION:gdata-youtube-content + * @short_description: YouTube content element + * @stability: Stable + * @include: gdata/services/youtube/gdata-youtube-content.h + * + * #GDataYouTubeContent represents the YouTube-specific customizations to #GDataMediaContent. For more information, + * see the + * online documentation. + * + * Since: 0.4.0 + * Deprecated: 0.17.0: Accessing YouTube video content directly is no longer + * supported by Google. There is no replacement. + */ + +#include +#include + +#include "gdata-youtube-content.h" +#include "gdata-parsable.h" +#include "gdata-parser.h" +#include "gdata-youtube-enums.h" + +G_GNUC_BEGIN_IGNORE_DEPRECATIONS + +static void gdata_youtube_content_get_property (GObject *object, guint property_id, GValue *value, GParamSpec *pspec); +static gboolean pre_parse_xml (GDataParsable *parsable, xmlDoc *doc, xmlNode *root_node, gpointer user_data, GError **error); +static void get_namespaces (GDataParsable *parsable, GHashTable *namespaces); + +struct _GDataYouTubeContentPrivate { + GDataYouTubeFormat format; +}; + +enum { + PROP_FORMAT = 1 +}; + +G_DEFINE_TYPE (GDataYouTubeContent, gdata_youtube_content, GDATA_TYPE_MEDIA_CONTENT) + +static void +gdata_youtube_content_class_init (GDataYouTubeContentClass *klass) +{ + GObjectClass *gobject_class = G_OBJECT_CLASS (klass); + GDataParsableClass *parsable_class = GDATA_PARSABLE_CLASS (klass); + + g_type_class_add_private (klass, sizeof (GDataYouTubeContentPrivate)); + + gobject_class->get_property = gdata_youtube_content_get_property; + + parsable_class->pre_parse_xml = pre_parse_xml; + parsable_class->get_namespaces = get_namespaces; + + /** + * GDataYouTubeContent:format: + * + * The video format of the video object. + * + * For more information, see the + * + * YouTube documentation. + * + * Since: 0.4.0 + * Deprecated: 0.17.0: Accessing YouTube video content directly is + * no longer supported by Google. There is no replacement. + */ + g_object_class_install_property (gobject_class, PROP_FORMAT, + g_param_spec_enum ("format", + "Format", "The video format of the video object.", + GDATA_TYPE_YOUTUBE_FORMAT, GDATA_YOUTUBE_FORMAT_UNKNOWN, + G_PARAM_READABLE | G_PARAM_STATIC_STRINGS | + G_PARAM_DEPRECATED)); +} + +static void +gdata_youtube_content_init (GDataYouTubeContent *self) +{ + self->priv = G_TYPE_INSTANCE_GET_PRIVATE (self, GDATA_TYPE_YOUTUBE_CONTENT, GDataYouTubeContentPrivate); +} + +static void +gdata_youtube_content_get_property (GObject *object, guint property_id, GValue *value, GParamSpec *pspec) +{ + GDataYouTubeContentPrivate *priv = GDATA_YOUTUBE_CONTENT (object)->priv; + + switch (property_id) { + case PROP_FORMAT: + g_value_set_enum (value, priv->format); + break; + default: + /* We don't have any other property... */ + G_OBJECT_WARN_INVALID_PROPERTY_ID (object, property_id, pspec); + break; + } +} + +static gboolean +pre_parse_xml (GDataParsable *parsable, xmlDoc *doc, xmlNode *root_node, gpointer user_data, GError **error) +{ + xmlChar *format; + + /* Chain up to the parent class */ + GDATA_PARSABLE_CLASS (gdata_youtube_content_parent_class)->pre_parse_xml (parsable, doc, root_node, user_data, error); + + format = xmlGetProp (root_node, (xmlChar*) "format"); + GDATA_YOUTUBE_CONTENT (parsable)->priv->format = (format == NULL) ? GDATA_YOUTUBE_FORMAT_UNKNOWN : g_ascii_strtoull ((gchar*) format, NULL, 10); + + return TRUE; +} + +static void +get_namespaces (GDataParsable *parsable, GHashTable *namespaces) +{ + /* Chain up to the parent class */ + GDATA_PARSABLE_CLASS (gdata_youtube_content_parent_class)->get_namespaces (parsable, namespaces); + + g_hash_table_insert (namespaces, (gchar*) "youtube", (gchar*) "http://gdata.youtube.com/schemas/2007"); +} + +/** + * gdata_youtube_content_get_format: + * @self: a #GDataYouTubeContent + * + * Gets the #GDataYouTubeContent:format property. + * + * Return value: the video format, or %GDATA_YOUTUBE_FORMAT_UNKNOWN + * + * Since: 0.4.0 + * Deprecated: 0.17.0: Accessing YouTube video content directly is no longer + * supported by Google. There is no replacement. + */ +GDataYouTubeFormat +gdata_youtube_content_get_format (GDataYouTubeContent *self) +{ + g_return_val_if_fail (GDATA_IS_YOUTUBE_CONTENT (self), GDATA_YOUTUBE_FORMAT_UNKNOWN); + return self->priv->format; +} + +G_GNUC_END_IGNORE_DEPRECATIONS diff --git a/gdata/services/youtube/gdata-youtube-content.h b/gdata/services/youtube/gdata-youtube-content.h new file mode 100644 index 0000000..1a34d0d --- /dev/null +++ b/gdata/services/youtube/gdata-youtube-content.h @@ -0,0 +1,108 @@ +/* -*- Mode: C; indent-tabs-mode: t; c-basic-offset: 8; tab-width: 8 -*- */ +/* + * GData Client + * Copyright (C) Philip Withnall 2009–2010, 2015 + * + * GData Client is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * GData Client is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with GData Client. If not, see . + */ + +#ifndef GDATA_YOUTUBE_CONTENT_H +#define GDATA_YOUTUBE_CONTENT_H + +#include +#include + +#include +#include + +G_BEGIN_DECLS + +#ifndef LIBGDATA_DISABLE_DEPRECATED + +/** + * GDataYouTubeFormat: + * @GDATA_YOUTUBE_FORMAT_UNKNOWN: retrieve videos in all formats when querying the service + * @GDATA_YOUTUBE_FORMAT_RTSP_H263_AMR: RTSP streaming URI for mobile video playback; H.263 video (up to 176×144) and AMR audio + * @GDATA_YOUTUBE_FORMAT_HTTP_SWF: HTTP URI to the embeddable player (SWF) for this video + * @GDATA_YOUTUBE_FORMAT_RTSP_MPEG4_AAC: RTSP streaming URI for mobile video playback; MPEG-4 SP video (up to 176×144) and AAC audio + * + * Video formats available on YouTube. For more information, see the + * online documentation. + * + * Since: 0.3.0 + * Deprecated: 0.17.0: Accessing YouTube video content directly is no longer + * supported by Google. There is no replacement. + */ +typedef enum { + GDATA_YOUTUBE_FORMAT_UNKNOWN = 0, + GDATA_YOUTUBE_FORMAT_RTSP_H263_AMR = 1, + GDATA_YOUTUBE_FORMAT_HTTP_SWF = 5, + GDATA_YOUTUBE_FORMAT_RTSP_MPEG4_AAC = 6 +} GDataYouTubeFormat; + +#define GDATA_TYPE_YOUTUBE_CONTENT (gdata_youtube_content_get_type ()) +#define GDATA_YOUTUBE_CONTENT(o) (G_TYPE_CHECK_INSTANCE_CAST ((o), GDATA_TYPE_YOUTUBE_CONTENT, GDataYouTubeContent)) +#define GDATA_YOUTUBE_CONTENT_CLASS(k) (G_TYPE_CHECK_CLASS_CAST((k), GDATA_TYPE_YOUTUBE_CONTENT, GDataYouTubeContentClass)) +#define GDATA_IS_YOUTUBE_CONTENT(o) (G_TYPE_CHECK_INSTANCE_TYPE ((o), GDATA_TYPE_YOUTUBE_CONTENT)) +#define GDATA_IS_YOUTUBE_CONTENT_CLASS(k) (G_TYPE_CHECK_CLASS_TYPE ((k), GDATA_TYPE_YOUTUBE_CONTENT)) +#define GDATA_YOUTUBE_CONTENT_GET_CLASS(o) (G_TYPE_INSTANCE_GET_CLASS ((o), GDATA_TYPE_YOUTUBE_CONTENT, GDataYouTubeContentClass)) + +typedef struct _GDataYouTubeContentPrivate GDataYouTubeContentPrivate G_GNUC_DEPRECATED; + +/** + * GDataYouTubeContent: + * + * All the fields in the #GDataYouTubeContent structure are private and should never be accessed directly. + * + * Since: 0.4.0 + * Deprecated: 0.17.0: Accessing YouTube video content directly is no longer + * supported by Google. There is no replacement. + */ +typedef struct { + G_GNUC_BEGIN_IGNORE_DEPRECATIONS + GDataMediaContent parent; + GDataYouTubeContentPrivate *priv; + G_GNUC_END_IGNORE_DEPRECATIONS +} GDataYouTubeContent; + +/** + * GDataYouTubeContentClass: + * + * All the fields in the #GDataYouTubeContentClass structure are private and should never be accessed directly. + * + * Since: 0.4.0 + * Deprecated: 0.17.0: Accessing YouTube video content directly is no longer + * supported by Google. There is no replacement. + */ +typedef struct { + /*< private >*/ + GDataMediaContentClass parent; + + /*< private >*/ + /* Padding for future expansion */ + void (*_g_reserved0) (void); + void (*_g_reserved1) (void); +} GDataYouTubeContentClass; + +GType gdata_youtube_content_get_type (void) G_GNUC_CONST G_GNUC_DEPRECATED; + +G_GNUC_BEGIN_IGNORE_DEPRECATIONS +GDataYouTubeFormat gdata_youtube_content_get_format (GDataYouTubeContent *self) G_GNUC_PURE G_GNUC_DEPRECATED; +G_GNUC_END_IGNORE_DEPRECATIONS + +#endif /* !LIBGDATA_DISABLE_DEPRECATED */ + +G_END_DECLS + +#endif /* !GDATA_YOUTUBE_CONTENT_H */ diff --git a/gdata/services/youtube/gdata-youtube-credit.c b/gdata/services/youtube/gdata-youtube-credit.c new file mode 100644 index 0000000..b1b7f60 --- /dev/null +++ b/gdata/services/youtube/gdata-youtube-credit.c @@ -0,0 +1,179 @@ +/* -*- Mode: C; indent-tabs-mode: t; c-basic-offset: 8; tab-width: 8 -*- */ +/* + * GData Client + * Copyright (C) Philip Withnall 2009–2010, 2015 + * + * GData Client is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * GData Client is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with GData Client. If not, see . + */ + +/** + * SECTION:gdata-youtube-credit + * @short_description: YouTube credit element + * @stability: Stable + * @include: gdata/services/youtube/gdata-youtube-credit.h + * + * #GDataYouTubeCredit represents the YouTube-specific customizations to #GDataMediaCredit. For more information, + * see the + * online documentation. + * + * Since: 0.4.0 + * Deprecated: 0.17.0: This is no longer supported by Google. There is no + * replacement. + */ + +#include +#include + +#include "gdata-youtube-credit.h" +#include "gdata-parsable.h" +#include "gdata-parser.h" + +G_GNUC_BEGIN_IGNORE_DEPRECATIONS + +static void gdata_youtube_credit_finalize (GObject *object); +static void gdata_youtube_credit_get_property (GObject *object, guint property_id, GValue *value, GParamSpec *pspec); +static gboolean pre_parse_xml (GDataParsable *parsable, xmlDoc *doc, xmlNode *root_node, gpointer user_data, GError **error); +static void pre_get_xml (GDataParsable *parsable, GString *xml_string); +static void get_namespaces (GDataParsable *parsable, GHashTable *namespaces); + +struct _GDataYouTubeCreditPrivate { + gchar *entity_type; +}; + +enum { + PROP_ENTITY_TYPE = 1 +}; + +G_DEFINE_TYPE (GDataYouTubeCredit, gdata_youtube_credit, GDATA_TYPE_MEDIA_CREDIT) + +static void +gdata_youtube_credit_class_init (GDataYouTubeCreditClass *klass) +{ + GObjectClass *gobject_class = G_OBJECT_CLASS (klass); + GDataParsableClass *parsable_class = GDATA_PARSABLE_CLASS (klass); + + g_type_class_add_private (klass, sizeof (GDataYouTubeCreditPrivate)); + + gobject_class->get_property = gdata_youtube_credit_get_property; + gobject_class->finalize = gdata_youtube_credit_finalize; + + parsable_class->pre_parse_xml = pre_parse_xml; + parsable_class->pre_get_xml = pre_get_xml; + parsable_class->get_namespaces = get_namespaces; + + /** + * GDataYouTubeCredit:entity-type: + * + * The type of entity who is credited. Currently this can only be %GDATA_YOUTUBE_CREDIT_ENTITY_PARTNER, for a YouTube partner. + * + * For more information, see the + * + * YouTube documentation. + * + * Since: 0.4.0 + * Deprecated: 0.17.0: This is no longer supported by Google. There + * is no replacement. + */ + g_object_class_install_property (gobject_class, PROP_ENTITY_TYPE, + g_param_spec_string ("entity-type", + "Entity type", "The type of entity who is credited.", + NULL, + G_PARAM_READABLE | G_PARAM_STATIC_STRINGS | G_PARAM_DEPRECATED)); +} + +static void +gdata_youtube_credit_init (GDataYouTubeCredit *self) +{ + self->priv = G_TYPE_INSTANCE_GET_PRIVATE (self, GDATA_TYPE_YOUTUBE_CREDIT, GDataYouTubeCreditPrivate); +} + +static void +gdata_youtube_credit_finalize (GObject *object) +{ + GDataYouTubeCreditPrivate *priv = GDATA_YOUTUBE_CREDIT (object)->priv; + + g_free (priv->entity_type); + + /* Chain up to the parent class */ + G_OBJECT_CLASS (gdata_youtube_credit_parent_class)->finalize (object); +} + +static void +gdata_youtube_credit_get_property (GObject *object, guint property_id, GValue *value, GParamSpec *pspec) +{ + GDataYouTubeCreditPrivate *priv = GDATA_YOUTUBE_CREDIT (object)->priv; + + switch (property_id) { + case PROP_ENTITY_TYPE: + g_value_set_string (value, priv->entity_type); + break; + default: + /* We don't have any other property... */ + G_OBJECT_WARN_INVALID_PROPERTY_ID (object, property_id, pspec); + break; + } +} + +static gboolean +pre_parse_xml (GDataParsable *parsable, xmlDoc *doc, xmlNode *root_node, gpointer user_data, GError **error) +{ + /* Chain up to the parent class */ + GDATA_PARSABLE_CLASS (gdata_youtube_credit_parent_class)->pre_parse_xml (parsable, doc, root_node, user_data, error); + + GDATA_YOUTUBE_CREDIT (parsable)->priv->entity_type = (gchar*) xmlGetProp (root_node, (xmlChar*) "type"); + + return TRUE; +} + +static void +pre_get_xml (GDataParsable *parsable, GString *xml_string) +{ + GDataYouTubeCreditPrivate *priv = GDATA_YOUTUBE_CREDIT (parsable)->priv; + + /* Chain up to the parent class */ + GDATA_PARSABLE_CLASS (gdata_youtube_credit_parent_class)->pre_get_xml (parsable, xml_string); + + if (priv->entity_type != NULL) + gdata_parser_string_append_escaped (xml_string, " type='", priv->entity_type, "'"); +} + +static void +get_namespaces (GDataParsable *parsable, GHashTable *namespaces) +{ + /* Chain up to the parent class */ + GDATA_PARSABLE_CLASS (gdata_youtube_credit_parent_class)->get_namespaces (parsable, namespaces); + + g_hash_table_insert (namespaces, (gchar*) "youtube", (gchar*) "http://gdata.youtube.com/schemas/2007"); +} + +/** + * gdata_youtube_credit_get_entity_type: + * @self: a #GDataYouTubeCredit + * + * Gets the #GDataYouTubeCredit:entity-type property. + * + * Return value: the type of the credited user (e.g. %GDATA_YOUTUBE_CREDIT_ENTITY_PARTNER), or %NULL + * + * Since: 0.4.0 + * Deprecated: 0.17.0: This is no longer supported by Google. There is no + * replacement. + */ +const gchar * +gdata_youtube_credit_get_entity_type (GDataYouTubeCredit *self) +{ + g_return_val_if_fail (GDATA_IS_YOUTUBE_CREDIT (self), NULL); + return self->priv->entity_type; +} + +G_GNUC_END_IGNORE_DEPRECATIONS diff --git a/gdata/services/youtube/gdata-youtube-credit.h b/gdata/services/youtube/gdata-youtube-credit.h new file mode 100644 index 0000000..da31630 --- /dev/null +++ b/gdata/services/youtube/gdata-youtube-credit.h @@ -0,0 +1,97 @@ +/* -*- Mode: C; indent-tabs-mode: t; c-basic-offset: 8; tab-width: 8 -*- */ +/* + * GData Client + * Copyright (C) Philip Withnall 2009–2010, 2015 + * + * GData Client is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * GData Client is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with GData Client. If not, see . + */ + +#ifndef GDATA_YOUTUBE_CREDIT_H +#define GDATA_YOUTUBE_CREDIT_H + +#include +#include + +#include +#include + +G_BEGIN_DECLS + +#ifndef LIBGDATA_DISABLE_DEPRECATED + +/** + * GDATA_YOUTUBE_CREDIT_ENTITY_PARTNER: + * + * The credited entity is a YouTube partner. + * + * Since: 0.7.0 + * Deprecated: 0.17.0: This is no longer supported by Google. There is no + * replacement. + */ +#define GDATA_YOUTUBE_CREDIT_ENTITY_PARTNER "partner" + +#define GDATA_TYPE_YOUTUBE_CREDIT (gdata_youtube_credit_get_type ()) +#define GDATA_YOUTUBE_CREDIT(o) (G_TYPE_CHECK_INSTANCE_CAST ((o), GDATA_TYPE_YOUTUBE_CREDIT, GDataYouTubeCredit)) +#define GDATA_YOUTUBE_CREDIT_CLASS(k) (G_TYPE_CHECK_CLASS_CAST((k), GDATA_TYPE_YOUTUBE_CREDIT, GDataYouTubeCreditClass)) +#define GDATA_IS_YOUTUBE_CREDIT(o) (G_TYPE_CHECK_INSTANCE_TYPE ((o), GDATA_TYPE_YOUTUBE_CREDIT)) +#define GDATA_IS_YOUTUBE_CREDIT_CLASS(k) (G_TYPE_CHECK_CLASS_TYPE ((k), GDATA_TYPE_YOUTUBE_CREDIT)) +#define GDATA_YOUTUBE_CREDIT_GET_CLASS(o) (G_TYPE_INSTANCE_GET_CLASS ((o), GDATA_TYPE_YOUTUBE_CREDIT, GDataYouTubeCreditClass)) + +typedef struct _GDataYouTubeCreditPrivate GDataYouTubeCreditPrivate G_GNUC_DEPRECATED; + +/** + * GDataYouTubeCredit: + * + * All the fields in the #GDataYouTubeCredit structure are private and should never be accessed directly. + * + * Since: 0.4.0 + * Deprecated: 0.17.0: This is no longer supported by Google. There is no + * replacement. + */ +typedef struct { + G_GNUC_BEGIN_IGNORE_DEPRECATIONS + GDataMediaCredit parent; + GDataYouTubeCreditPrivate *priv; + G_GNUC_END_IGNORE_DEPRECATIONS +} GDataYouTubeCredit; + +/** + * GDataYouTubeCreditClass: + * + * All the fields in the #GDataYouTubeCreditClass structure are private and should never be accessed directly. + * + * Since: 0.4.0 + * Deprecated: 0.17.0: This is no longer supported by Google. There is no + * replacement. + */ +typedef struct { + /*< private >*/ + GDataMediaCreditClass parent; + + /*< private >*/ + /* Padding for future expansion */ + void (*_g_reserved0) (void); + void (*_g_reserved1) (void); +} GDataYouTubeCreditClass; + +G_GNUC_BEGIN_IGNORE_DEPRECATIONS +GType gdata_youtube_credit_get_type (void) G_GNUC_CONST G_GNUC_DEPRECATED; +const gchar *gdata_youtube_credit_get_entity_type (GDataYouTubeCredit *self) G_GNUC_PURE G_GNUC_DEPRECATED; +G_GNUC_END_IGNORE_DEPRECATIONS + +#endif /* !LIBGDATA_DISABLE_DEPRECATED */ + +G_END_DECLS + +#endif /* !GDATA_YOUTUBE_CREDIT_H */ diff --git a/gdata/services/youtube/gdata-youtube-feed.c b/gdata/services/youtube/gdata-youtube-feed.c new file mode 100644 index 0000000..82d2f5e --- /dev/null +++ b/gdata/services/youtube/gdata-youtube-feed.c @@ -0,0 +1,102 @@ +/* -*- Mode: C; indent-tabs-mode: t; c-basic-offset: 8; tab-width: 8 -*- */ +/* + * GData Client + * Copyright (C) Philip Withnall 2015 + * + * GData Client is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * GData Client is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with GData Client. If not, see . + */ + +/** + * SECTION:gdata-youtube-feed + * @short_description: GData YouTube feed object + * @stability: Stable + * @include: gdata/services/youtube/gdata-youtube-feed.h + * + * #GDataYouTubeFeed is a list of entries (#GDataYouTubeVideo subclasses) + * returned as the result of a query to a #GDataYouTubeService, or given as the + * input to another operation on the online service. + * + * Each #GDataYouTubeVideo represents a single video on YouTube, and the + * #GDataYouTubeFeed represents a collection of those objects. + * + * Since: 0.17.0 + */ + +#include +#include +#include +#include + +#include "gdata-youtube-feed.h" +#include "gdata-youtube-video.h" +#include "gdata-types.h" +#include "gdata-private.h" +#include "gdata-service.h" + +static gboolean +parse_json (GDataParsable *parsable, JsonReader *reader, gpointer user_data, + GError **error); + +G_DEFINE_TYPE (GDataYouTubeFeed, gdata_youtube_feed, GDATA_TYPE_FEED) + +static void +gdata_youtube_feed_class_init (GDataYouTubeFeedClass *klass) +{ + GDataParsableClass *parsable_class = GDATA_PARSABLE_CLASS (klass); + parsable_class->parse_json = parse_json; +} + +static void +gdata_youtube_feed_init (GDataYouTubeFeed *self) +{ + /* Move along now. */ +} + +static gboolean +parse_json (GDataParsable *parsable, JsonReader *reader, gpointer user_data, + GError **error) +{ + if (g_strcmp0 (json_reader_get_member_name (reader), "pageInfo") == 0) { + guint total_results, items_per_page; + const GError *child_error = NULL; + + /* Check this is an object. */ + if (!json_reader_is_object (reader)) { + return gdata_parser_error_required_json_content_missing (reader, error); + } + + /* https://developers.google.com/youtube/v3/docs/playlists/list/ */ + json_reader_read_member (reader, "totalResults"); + total_results = json_reader_get_int_value (reader); + json_reader_end_member (reader); + + json_reader_read_member (reader, "resultsPerPage"); + items_per_page = json_reader_get_int_value (reader); + json_reader_end_member (reader); + + child_error = json_reader_get_error (reader); + if (child_error != NULL) { + return gdata_parser_error_from_json_error (reader, + child_error, + error); + } + + _gdata_feed_set_page_info (GDATA_FEED (parsable), total_results, + items_per_page); + + return TRUE; + } else { + return GDATA_PARSABLE_CLASS (gdata_youtube_feed_parent_class)->parse_json (parsable, reader, user_data, error); + } +} diff --git a/gdata/services/youtube/gdata-youtube-feed.h b/gdata/services/youtube/gdata-youtube-feed.h new file mode 100644 index 0000000..e78c7c2 --- /dev/null +++ b/gdata/services/youtube/gdata-youtube-feed.h @@ -0,0 +1,74 @@ +/* -*- Mode: C; indent-tabs-mode: t; c-basic-offset: 8; tab-width: 8 -*- */ +/* + * GData Client + * Copyright (C) Philip Withnall 2015 + * + * GData Client is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * GData Client is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with GData Client. If not, see . + */ + +#ifndef GDATA_YOUTUBE_FEED_H +#define GDATA_YOUTUBE_FEED_H + +#include +#include +#include + +G_BEGIN_DECLS + +#define GDATA_TYPE_YOUTUBE_FEED (gdata_youtube_feed_get_type ()) +#define GDATA_YOUTUBE_FEED(o) (G_TYPE_CHECK_INSTANCE_CAST ((o), GDATA_TYPE_YOUTUBE_FEED, GDataYouTubeFeed)) +#define GDATA_YOUTUBE_FEED_CLASS(k) (G_TYPE_CHECK_CLASS_CAST((k), GDATA_TYPE_YOUTUBE_FEED, GDataYouTubeFeedClass)) +#define GDATA_IS_YOUTUBE_FEED(o) (G_TYPE_CHECK_INSTANCE_TYPE ((o), GDATA_TYPE_YOUTUBE_FEED)) +#define GDATA_IS_YOUTUBE_FEED_CLASS(k) (G_TYPE_CHECK_CLASS_TYPE ((k), GDATA_TYPE_YOUTUBE_FEED)) +#define GDATA_YOUTUBE_FEED_GET_CLASS(o) (G_TYPE_INSTANCE_GET_CLASS ((o), GDATA_TYPE_YOUTUBE_FEED, GDataYouTubeFeedClass)) + +typedef struct _GDataYouTubeFeedPrivate GDataYouTubeFeedPrivate; + +/** + * GDataYouTubeFeed: + * + * All the fields in the #GDataYouTubeFeed structure are private and should + * never be accessed directly. + * + * Since: 0.17.0 + */ +typedef struct { + /*< private >*/ + GDataFeed parent; + GDataYouTubeFeedPrivate *priv; +} GDataYouTubeFeed; + +/** + * GDataYouTubeFeedClass: + * + * All the fields in the #GDataYouTubeFeedClass structure are private and should + * never be accessed directly. + * + * Since: 0.17.0 + */ +typedef struct { + /*< private >*/ + GDataFeedClass parent; + + /*< private >*/ + /* Padding for future expansion */ + void (*_g_reserved0) (void); + void (*_g_reserved1) (void); +} GDataYouTubeFeedClass; + +GType gdata_youtube_feed_get_type (void) G_GNUC_CONST; + +G_END_DECLS + +#endif /* !GDATA_YOUTUBE_FEED_H */ diff --git a/gdata/services/youtube/gdata-youtube-query.c b/gdata/services/youtube/gdata-youtube-query.c new file mode 100644 index 0000000..99ae996 --- /dev/null +++ b/gdata/services/youtube/gdata-youtube-query.c @@ -0,0 +1,1127 @@ +/* -*- Mode: C; indent-tabs-mode: t; c-basic-offset: 8; tab-width: 8 -*- */ +/* + * GData Client + * Copyright (C) Philip Withnall 2009–2010 + * + * GData Client is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * GData Client is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with GData Client. If not, see . + */ + +/** + * SECTION:gdata-youtube-query + * @short_description: GData YouTube query object + * @stability: Stable + * @include: gdata/services/youtube/gdata-youtube-query.h + * + * #GDataYouTubeQuery represents a collection of query parameters specific to the YouTube service, which go above and beyond + * those catered for by #GDataQuery. + * + * With the transition to version 3 of the YouTube, the #GDataQuery:author and + * #GDataQuery:start-index properties are no longer supported, and their values + * will be ignored. Use gdata_query_next_page() instead of the + * #GDataQuery:start-index API. + * + * For more information on the custom GData query parameters supported by #GDataYouTubeQuery, see the online documentation. + * + * Since: 0.3.0 + */ + +#include +#include +#include +#include + +#include "gdata-youtube-query.h" +#include "gdata-query.h" +#include "gdata-youtube-content.h" +#include "gdata-private.h" + +static void gdata_youtube_query_finalize (GObject *object); +static void gdata_youtube_query_get_property (GObject *object, guint property_id, GValue *value, GParamSpec *pspec); +static void gdata_youtube_query_set_property (GObject *object, guint property_id, const GValue *value, GParamSpec *pspec); +static void get_query_uri (GDataQuery *self, const gchar *feed_uri, GString *query_uri, gboolean *params_started); + +struct _GDataYouTubeQueryPrivate { + G_GNUC_BEGIN_IGNORE_DEPRECATIONS + GDataYouTubeFormat format; + GDataYouTubeSortOrder sort_order; + GDataYouTubeUploader uploader; + G_GNUC_END_IGNORE_DEPRECATIONS + + gdouble latitude; + gdouble longitude; + gdouble location_radius; + gboolean has_location; + gchar *language; + gchar *order_by; + gchar *restriction; + GDataYouTubeSafeSearch safe_search; + GDataYouTubeAge age; + gchar *license; +}; + +enum { + PROP_FORMAT = 1, + PROP_LATITUDE, + PROP_LONGITUDE, + PROP_LOCATION_RADIUS, + PROP_HAS_LOCATION, + PROP_LANGUAGE, + PROP_ORDER_BY, + PROP_RESTRICTION, + PROP_SAFE_SEARCH, + PROP_SORT_ORDER, + PROP_AGE, + PROP_UPLOADER, + PROP_LICENSE, +}; + +G_DEFINE_TYPE (GDataYouTubeQuery, gdata_youtube_query, GDATA_TYPE_QUERY) + +static void +gdata_youtube_query_class_init (GDataYouTubeQueryClass *klass) +{ + GObjectClass *gobject_class = G_OBJECT_CLASS (klass); + GDataQueryClass *query_class = GDATA_QUERY_CLASS (klass); + + g_type_class_add_private (klass, sizeof (GDataYouTubeQueryPrivate)); + + gobject_class->set_property = gdata_youtube_query_set_property; + gobject_class->get_property = gdata_youtube_query_get_property; + gobject_class->finalize = gdata_youtube_query_finalize; + + query_class->get_query_uri = get_query_uri; + + /** + * GDataYouTubeQuery:format: + * + * Specifies that videos must be available in a particular video format. Use %GDATA_YOUTUBE_FORMAT_UNKNOWN to + * retrieve videos irrespective of their format availability. + * + * Since: 0.3.0 + * Deprecated: 0.17.0: No longer supported by Google. The value of + * this property will be unused in queries. There is no replacement. + */ + g_object_class_install_property (gobject_class, PROP_FORMAT, + g_param_spec_enum ("format", + "Format", "Specifies that videos must be available in a particular video format.", + GDATA_TYPE_YOUTUBE_FORMAT, GDATA_YOUTUBE_FORMAT_UNKNOWN, + G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS | + G_PARAM_DEPRECATED)); + + /** + * GDataYouTubeQuery:latitude: + * + * The latitude of a particular location of which videos should be found. This should be used in conjunction with + * #GDataYouTubeQuery:longitude; if either property is outside the valid range, neither will be used. Valid latitudes + * are between -90 and 900 degrees; any values of this property outside that range + * will unset the property in the query URI. + * + * If #GDataYouTubeQuery:location-radius is a non-0 value, this will define a circle from which videos should be + * found. + * + * As it is deprecated, the value of #GDataYouTubeQuery:has-location is + * ignored. + * + * For more information, see the online documentation. + * + * Since: 0.3.0 + */ + g_object_class_install_property (gobject_class, PROP_LATITUDE, + g_param_spec_double ("latitude", + "Latitude", "The latitude of a particular location of which videos should be found.", + -G_MAXDOUBLE, G_MAXDOUBLE, G_MAXDOUBLE, + G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)); + + /** + * GDataYouTubeQuery:longitude: + * + * The longitude of a particular location of which videos should be found. This should be used in conjunction with + * #GDataYouTubeQuery:latitude; if either property is outside the valid range, neither will be used. Valid longitudes + * are between -180 and 180 degrees; any values of this property outside that + * range will unset the property in the query URI. + * + * For more information, see the documentation for #GDataYouTubeQuery:latitude. + * + * Since: 0.3.0 + */ + g_object_class_install_property (gobject_class, PROP_LONGITUDE, + g_param_spec_double ("longitude", + "Longitude", "The longitude of a particular location of which videos should be found.", + -G_MAXDOUBLE, G_MAXDOUBLE, G_MAXDOUBLE, + G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)); + + /** + * GDataYouTubeQuery:location-radius: + * + * The radius, in metres, of a circle from within which videos should be returned. The circle is centred on the latitude and + * longitude given in #GDataYouTubeQuery:latitude and #GDataYouTubeQuery:longitude. + * + * Set this property to 0 to search for specific coordinates, rather than within a given radius. + * + * For more information, see the documentation for #GDataYouTubeQuery:latitude. + * + * Since: 0.3.0 + */ + g_object_class_install_property (gobject_class, PROP_LOCATION_RADIUS, + g_param_spec_double ("location-radius", + "Location radius", "The radius, in metres, of a circle to search within.", + 0.0, G_MAXDOUBLE, 0.0, + G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)); + + /** + * GDataYouTubeQuery:has-location: + * + * Whether to restrict search results to videos with specific coordinates associated with them. If used with a given + * #GDataYouTubeQuery:latitude and #GDataYouTubeQuery:longitude, only videos with specific coordinates (not those with merely + * a descriptive address) will be returned. If used without a latitude and longitude set, only videos with specific coordinates + * (regardless of those coordinates) will be returned. + * + * For more information, see the documentation for #GDataYouTubeQuery:latitude. + * + * Since: 0.3.0 + * Deprecated: 0.17.0: No longer supported by Google. The value of + * this property will be unused in queries. + */ + g_object_class_install_property (gobject_class, PROP_HAS_LOCATION, + g_param_spec_boolean ("has-location", + "Has location?", "Whether to restrict results to videos with specific coordinates.", + FALSE, + G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS | + G_PARAM_DEPRECATED)); + + /** + * GDataYouTubeQuery:language: + * + * Restricts the search to videos that have a title, description or keywords in a specified language. The language code should + * be a two-letter ISO 639-1 code; or you can use zh-Hans for simplified Chinese and zh-Hant + * for traditional Chinese. + * + * For more information, see the online documentation. + * + * Since: 0.3.0 + * Deprecated: 0.17.0: No longer supported by Google. The value of + * this property will be unused in queries. There is no replacement. + */ + g_object_class_install_property (gobject_class, PROP_LANGUAGE, + g_param_spec_string ("language", + "Language", "Restricts the search to videos described in the given language.", + NULL, + G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS | + G_PARAM_DEPRECATED)); + + /** + * GDataYouTubeQuery:order-by: + * + * Specifies the order of entries in a feed. Supported values are relevance, + * published, viewCount and rating. + * + * Additionally, results most relevant to a specific language can be returned by setting the property + * to relevance_lang_languageCode, where + * languageCode is an ISO 639-1 language code, as used in #GDataYouTubeQuery:language. + * + * For more information, see the online documentation. + * + * Since: 0.3.0 + */ + g_object_class_install_property (gobject_class, PROP_ORDER_BY, + g_param_spec_string ("order-by", + "Order by", "Specifies the order of entries in a feed.", + NULL, + G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)); + + /** + * GDataYouTubeQuery:restriction: + * + * An ISO 3166 two-letter country code that should be used to filter + * videos playable only in specific countries. + * + * Previously, this property could also accept the client’s IP address + * for country lookup. This feature is no longer supported by Google, + * and will result in an error from the server if used. Use a country + * code instead. + * + * For more information, see the online documentation. + * + * Since: 0.3.0 + */ + g_object_class_install_property (gobject_class, PROP_RESTRICTION, + g_param_spec_string ("restriction", + "Restriction", "The country code to filter videos playable only in specific countries.", + NULL, + G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)); + + /** + * GDataYouTubeQuery:safe-search: + * + * Whether the search results should include restricted content as well as standard content. + * + * For more information, see the online documentation. + * + * Since: 0.3.0 + */ + g_object_class_install_property (gobject_class, PROP_SAFE_SEARCH, + g_param_spec_enum ("safe-search", + "Safe search", "Whether the search results should include restricted content.", + GDATA_TYPE_YOUTUBE_SAFE_SEARCH, GDATA_YOUTUBE_SAFE_SEARCH_MODERATE, + G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)); + + /** + * GDataYouTubeQuery:sort-order: + * + * Specifies the direction of sorting. To use the default sort order, set the property to %GDATA_YOUTUBE_SORT_NONE. + * + * Since: 0.3.0 + * Deprecated: 0.17.0: No longer supported by Google. The value of + * this property will be unused in queries. There is no replacement. + */ + g_object_class_install_property (gobject_class, PROP_SORT_ORDER, + g_param_spec_enum ("sort-order", + "Sort order", "Specifies the direction of sorting.", + GDATA_TYPE_YOUTUBE_SORT_ORDER, GDATA_YOUTUBE_SORT_NONE, + G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS | + G_PARAM_DEPRECATED)); + + /** + * GDataYouTubeQuery:age: + * + * Restricts the search to videos uploaded within the specified time period. To retrieve videos irrespective of their + * age, set the property to %GDATA_YOUTUBE_AGE_ALL_TIME. + * + * Since: 0.3.0 + */ + g_object_class_install_property (gobject_class, PROP_AGE, + g_param_spec_enum ("age", + "Age", "Restricts the search to videos uploaded within the specified time period.", + GDATA_TYPE_YOUTUBE_AGE, GDATA_YOUTUBE_AGE_ALL_TIME, + G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)); + + /** + * GDataYouTubeQuery:uploader: + * + * Restricts the search to videos from the specified type of uploader. Currently, this can only be used to restrict + * searches to videos from YouTube partners. + * + * Since: 0.3.0 + * Deprecated: 0.17.0: No longer supported by Google. The value of + * this property will be unused in queries. There is no replacement. + */ + g_object_class_install_property (gobject_class, PROP_UPLOADER, + g_param_spec_enum ("uploader", + "Uploader", "Restricts the search to videos from the specified type of uploader.", + GDATA_TYPE_YOUTUBE_UPLOADER, GDATA_YOUTUBE_UPLOADER_ALL, + G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS | + G_PARAM_DEPRECATED)); + + /** + * GDataYouTubeQuery:license: + * + * The content license which should be used to filter search results. If set to, for example, %GDATA_YOUTUBE_LICENSE_CC, only videos which + * are Creative Commons licensed will be returned in search results. Set this to %NULL to return videos under any license. + * + * For more information, see the online documentation. + * + * Since: 0.11.0 + */ + g_object_class_install_property (gobject_class, PROP_LICENSE, + g_param_spec_string ("license", + "License", "The content license which should be used to filter search results.", + NULL, + G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)); + +} + +static void +gdata_youtube_query_init (GDataYouTubeQuery *self) +{ + self->priv = G_TYPE_INSTANCE_GET_PRIVATE (self, GDATA_TYPE_YOUTUBE_QUERY, GDataYouTubeQueryPrivate); + + self->priv->latitude = G_MAXDOUBLE; + self->priv->longitude = G_MAXDOUBLE; + + /* https://developers.google.com/youtube/v3/docs/search/list#pageToken */ + _gdata_query_set_pagination_type (GDATA_QUERY (self), + GDATA_QUERY_PAGINATION_TOKENS); +} + +static void +gdata_youtube_query_finalize (GObject *object) +{ + GDataYouTubeQueryPrivate *priv = GDATA_YOUTUBE_QUERY (object)->priv; + + g_free (priv->language); + g_free (priv->order_by); + g_free (priv->restriction); + g_free (priv->license); + + /* Chain up to the parent class */ + G_OBJECT_CLASS (gdata_youtube_query_parent_class)->finalize (object); +} + +static void +gdata_youtube_query_get_property (GObject *object, guint property_id, GValue *value, GParamSpec *pspec) +{ + GDataYouTubeQueryPrivate *priv = GDATA_YOUTUBE_QUERY (object)->priv; + + switch (property_id) { + case PROP_FORMAT: + g_value_set_enum (value, priv->format); + break; + case PROP_LATITUDE: + g_value_set_double (value, priv->latitude); + break; + case PROP_LONGITUDE: + g_value_set_double (value, priv->longitude); + break; + case PROP_LOCATION_RADIUS: + g_value_set_double (value, priv->location_radius); + break; + case PROP_HAS_LOCATION: + g_value_set_boolean (value, priv->has_location); + break; + case PROP_LANGUAGE: + g_value_set_string (value, priv->language); + break; + case PROP_ORDER_BY: + g_value_set_string (value, priv->order_by); + break; + case PROP_RESTRICTION: + g_value_set_string (value, priv->restriction); + break; + case PROP_SAFE_SEARCH: + g_value_set_enum (value, priv->safe_search); + break; + case PROP_SORT_ORDER: + g_value_set_enum (value, priv->sort_order); + break; + case PROP_AGE: + g_value_set_enum (value, priv->age); + break; + case PROP_UPLOADER: + g_value_set_enum (value, priv->uploader); + break; + case PROP_LICENSE: + g_value_set_string (value, priv->license); + break; + default: + /* We don't have any other property... */ + G_OBJECT_WARN_INVALID_PROPERTY_ID (object, property_id, pspec); + break; + } +} + +static void +gdata_youtube_query_set_property (GObject *object, guint property_id, const GValue *value, GParamSpec *pspec) +{ + GDataYouTubeQuery *self = GDATA_YOUTUBE_QUERY (object); + + switch (property_id) { + case PROP_FORMAT: + G_GNUC_BEGIN_IGNORE_DEPRECATIONS + gdata_youtube_query_set_format (self, g_value_get_enum (value)); + G_GNUC_END_IGNORE_DEPRECATIONS + break; + case PROP_LATITUDE: + self->priv->latitude = g_value_get_double (value); + break; + case PROP_LONGITUDE: + self->priv->longitude = g_value_get_double (value); + break; + case PROP_LOCATION_RADIUS: + self->priv->location_radius = g_value_get_double (value); + break; + case PROP_HAS_LOCATION: + self->priv->has_location = g_value_get_boolean (value); + break; + case PROP_LANGUAGE: + G_GNUC_BEGIN_IGNORE_DEPRECATIONS + gdata_youtube_query_set_language (self, g_value_get_string (value)); + G_GNUC_END_IGNORE_DEPRECATIONS + break; + case PROP_ORDER_BY: + gdata_youtube_query_set_order_by (self, g_value_get_string (value)); + break; + case PROP_RESTRICTION: + gdata_youtube_query_set_restriction (self, g_value_get_string (value)); + break; + case PROP_SAFE_SEARCH: + gdata_youtube_query_set_safe_search (self, g_value_get_enum (value)); + break; + case PROP_SORT_ORDER: + G_GNUC_BEGIN_IGNORE_DEPRECATIONS + gdata_youtube_query_set_sort_order (self, g_value_get_enum (value)); + G_GNUC_END_IGNORE_DEPRECATIONS + break; + case PROP_AGE: + gdata_youtube_query_set_age (self, g_value_get_enum (value)); + break; + case PROP_UPLOADER: + G_GNUC_BEGIN_IGNORE_DEPRECATIONS + gdata_youtube_query_set_uploader (self, g_value_get_enum (value)); + G_GNUC_END_IGNORE_DEPRECATIONS + break; + case PROP_LICENSE: + gdata_youtube_query_set_license (self, g_value_get_string (value)); + break; + default: + /* We don't have any other property... */ + G_OBJECT_WARN_INVALID_PROPERTY_ID (object, property_id, pspec); + break; + } +} + +/* Convert from a v2 order-by parameter value to a v3 order parameter value. + * Reference: + * v2: https://developers.google.com/youtube/2.0/developers_guide_protocol_api_query_parameters#orderbysp + * v3: https://developers.google.com/youtube/v3/docs/search/list#order + */ +static const gchar * +get_v3_order (const gchar *v2_order_by) +{ + const struct { + const gchar *v2_order_by; + const gchar *v3_order; + } mapping[] = { + { "relevance", "relevance" }, + { "published", "date" }, + { "viewCount", "viewCount" }, + { "rating", "rating" }, + }; + guint i; + + for (i = 0; i < G_N_ELEMENTS (mapping); i++) { + if (g_strcmp0 (v2_order_by, mapping[i].v2_order_by) == 0) { + return mapping[i].v3_order; + } + } + + /* Special case for ‘relevance_lang_*’. */ + if (g_str_has_prefix (v2_order_by, "relevance_lang_")) { + return "relevance"; + } + + return NULL; +} + +/* Convert from a v2 license parameter value to a v3 videoLicense parameter + * value. Reference: + * v2: https://developers.google.com/youtube/2.0/developers_guide_protocol_api_query_parameters#licensesp + * v3: https://developers.google.com/youtube/v3/docs/search/list#videoLicense + */ +static const gchar * +get_v3_video_license (const gchar *v2_license) +{ + if (g_strcmp0 (v2_license, "cc") == 0) { + return "creativeCommon"; + } else if (g_strcmp0 (v2_license, "youtube") == 0) { + return "youtube"; + } else { + return NULL; + } +} + +static void +get_query_uri (GDataQuery *self, const gchar *feed_uri, GString *query_uri, gboolean *params_started) +{ + GDataYouTubeQueryPrivate *priv = GDATA_YOUTUBE_QUERY (self)->priv; + + #define APPEND_SEP g_string_append_c (query_uri, (*params_started == FALSE) ? '?' : '&'); *params_started = TRUE; + + /* NOTE: We do not chain up because the parent class implements a lot + * of deprecated API. */ + + /* Categories */ + if (gdata_query_get_categories (self) != NULL) { + APPEND_SEP + g_string_append (query_uri, "videoCategoryId="); + g_string_append_uri_escaped (query_uri, + gdata_query_get_categories (self), + NULL, + FALSE); + } + + /* q param */ + if (gdata_query_get_q (self) != NULL) { + APPEND_SEP + g_string_append (query_uri, "q="); + g_string_append_uri_escaped (query_uri, + gdata_query_get_q (self), NULL, + FALSE); + } + + if (gdata_query_get_max_results (self) > 0) { + APPEND_SEP + g_string_append_printf (query_uri, "maxResults=%u", + gdata_query_get_max_results (self)); + } + + if (priv->age != GDATA_YOUTUBE_AGE_ALL_TIME) { + gchar *after; + GTimeVal tv = { 0, }; + + g_get_current_time (&tv); + + /* Squash the microseconds; they’re not useful. */ + tv.tv_usec = 0; + + switch (priv->age) { + case GDATA_YOUTUBE_AGE_TODAY: + tv.tv_sec -= 24 * 60 * 60; + break; + case GDATA_YOUTUBE_AGE_THIS_WEEK: + tv.tv_sec -= 7 * 24 * 60 * 60; + break; + case GDATA_YOUTUBE_AGE_THIS_MONTH: + tv.tv_sec -= 31 * 24 * 60 * 60; + break; + case GDATA_YOUTUBE_AGE_ALL_TIME: + default: + g_assert_not_reached (); + } + + APPEND_SEP + + after = g_time_val_to_iso8601 (&tv); + g_string_append_printf (query_uri, "publishedAfter=%s", after); + g_free (after); + } + + /* We don’t need to use APPEND_SEP below here, as this parameter is + * always included */ + APPEND_SEP + switch (priv->safe_search) { + case GDATA_YOUTUBE_SAFE_SEARCH_NONE: + g_string_append (query_uri, "safeSearch=none"); + break; + case GDATA_YOUTUBE_SAFE_SEARCH_MODERATE: + g_string_append (query_uri, "safeSearch=moderate"); + break; + case GDATA_YOUTUBE_SAFE_SEARCH_STRICT: + g_string_append (query_uri, "safeSearch=strict"); + break; + default: + g_assert_not_reached (); + } + + if (priv->latitude >= -90.0 && priv->latitude <= 90.0 && + priv->longitude >= -180.0 && priv->longitude <= 180.0) { + gchar latitude[G_ASCII_DTOSTR_BUF_SIZE]; + gchar longitude[G_ASCII_DTOSTR_BUF_SIZE]; + + g_string_append_printf (query_uri, "&location=%s,%s", + g_ascii_dtostr (latitude, + sizeof (latitude), + priv->latitude), + g_ascii_dtostr (longitude, + sizeof (longitude), + priv->longitude)); + + if (priv->location_radius >= 0.0) { + gchar radius[G_ASCII_DTOSTR_BUF_SIZE]; + g_string_append_printf (query_uri, "&locationRadius=%sm", + g_ascii_dtostr (radius, + sizeof (radius), + priv->location_radius)); + } + } + + if (priv->order_by != NULL) { + const gchar *v3_order_by = get_v3_order (priv->order_by); + + if (v3_order_by != NULL) { + g_string_append (query_uri, "&order="); + g_string_append_uri_escaped (query_uri, v3_order_by, + NULL, FALSE); + } + } + + if (priv->restriction != NULL) { + g_string_append (query_uri, "®ionCode="); + g_string_append_uri_escaped (query_uri, priv->restriction, NULL, FALSE); + } + + if (priv->license != NULL) { + const gchar *v3_video_license; + + v3_video_license = get_v3_video_license (priv->license); + + if (v3_video_license != NULL) { + g_string_append (query_uri, "&videoLicense="); + g_string_append_uri_escaped (query_uri, + v3_video_license, NULL, + FALSE); + } + } +} + +/** + * gdata_youtube_query_new: + * @q: (allow-none): a query string, or %NULL + * + * Creates a new #GDataYouTubeQuery with its #GDataQuery:q property set to @q. + * + * Return value: a new #GDataYouTubeQuery + * + * Since: 0.3.0 + */ +GDataYouTubeQuery * +gdata_youtube_query_new (const gchar *q) +{ + return g_object_new (GDATA_TYPE_YOUTUBE_QUERY, "q", q, NULL); +} + +G_GNUC_BEGIN_IGNORE_DEPRECATIONS + +/** + * gdata_youtube_query_get_format: + * @self: a #GDataYouTubeQuery + * + * Gets the #GDataYouTubeQuery:format property. + * + * Return value: the format property + * + * Since: 0.3.0 + * Deprecated: 0.17.0: No longer supported by Google. The value of + * this property will be unused in queries. There is no replacement. + */ +GDataYouTubeFormat +gdata_youtube_query_get_format (GDataYouTubeQuery *self) +{ + g_return_val_if_fail (GDATA_IS_YOUTUBE_QUERY (self), GDATA_YOUTUBE_FORMAT_UNKNOWN); + return self->priv->format; +} + +/** + * gdata_youtube_query_set_format: + * @self: a #GDataYouTubeQuery + * @format: the requested video format + * + * Sets the #GDataYouTubeQuery:format property of the #GDataYouTubeQuery to @format. + * + * Since: 0.3.0 + * Deprecated: 0.17.0: No longer supported by Google. The value of + * this property will be unused in queries. There is no replacement. + */ +void +gdata_youtube_query_set_format (GDataYouTubeQuery *self, GDataYouTubeFormat format) +{ + g_return_if_fail (GDATA_IS_YOUTUBE_QUERY (self)); + self->priv->format = format; + g_object_notify (G_OBJECT (self), "format"); + + /* Our current ETag will no longer be relevant */ + gdata_query_set_etag (GDATA_QUERY (self), NULL); +} + +G_GNUC_END_IGNORE_DEPRECATIONS + +/** + * gdata_youtube_query_get_location: + * @self: a #GDataYouTubeQuery + * @latitude: (out caller-allocates) (allow-none): a location in which to return the latitude, or %NULL + * @longitude: (out caller-allocates) (allow-none): a location in which to return the longitude, or %NULL + * @radius: (out caller-allocates) (allow-none): a location in which to return the location radius, or %NULL + * @has_location: (out caller-allocates) (allow-none): a location in which to return %TRUE if the query is searching for videos with a specific + * location, %FALSE otherwise, or %NULL + * + * Gets the location-based properties of the #GDataYouTubeQuery: #GDataYouTubeQuery:latitude, #GDataYouTubeQuery:longitude, + * #GDataYouTubeQuery:location-radius and #GDataYouTubeQuery:has-location. + * + * Since: 0.3.0 + */ +void +gdata_youtube_query_get_location (GDataYouTubeQuery *self, gdouble *latitude, gdouble *longitude, gdouble *radius, gboolean *has_location) +{ + g_return_if_fail (GDATA_IS_YOUTUBE_QUERY (self)); + + if (latitude != NULL) + *latitude = self->priv->latitude; + if (longitude != NULL) + *longitude = self->priv->longitude; + if (radius != NULL) + *radius = self->priv->location_radius; + if (has_location != NULL) + *has_location = self->priv->has_location; +} + +/** + * gdata_youtube_query_set_location: + * @self: a #GDataYouTubeQuery + * @latitude: the new latitude, or %G_MAXDOUBLE + * @longitude: the new longitude, or %G_MAXDOUBLE + * @radius: the new location radius, or 0 + * @has_location: %TRUE if the query is for videos with a specific location, %FALSE otherwise + * + * Sets the location-based properties of the #GDataYouTubeQuery: #GDataYouTubeQuery:latitude, #GDataYouTubeQuery:longitude, + * #GDataYouTubeQuery:location-radius and #GDataYouTubeQuery:has-location. + * + * Since: 0.3.0 + */ +void +gdata_youtube_query_set_location (GDataYouTubeQuery *self, gdouble latitude, gdouble longitude, gdouble radius, gboolean has_location) +{ + g_return_if_fail (GDATA_IS_YOUTUBE_QUERY (self)); + + self->priv->latitude = latitude; + self->priv->longitude = longitude; + self->priv->location_radius = radius; + self->priv->has_location = has_location; + + g_object_freeze_notify (G_OBJECT (self)); + g_object_notify (G_OBJECT (self), "latitude"); + g_object_notify (G_OBJECT (self), "longitude"); + g_object_notify (G_OBJECT (self), "location-radius"); + g_object_notify (G_OBJECT (self), "has-location"); + g_object_thaw_notify (G_OBJECT (self)); + + /* Our current ETag will no longer be relevant */ + gdata_query_set_etag (GDATA_QUERY (self), NULL); +} + +/** + * gdata_youtube_query_get_language: + * @self: a #GDataYouTubeQuery + * + * Gets the #GDataYouTubeQuery:language property. + * + * Return value: the language property, or %NULL if it is unset + * + * Since: 0.3.0 + * Deprecated: 0.17.0: No longer supported by Google. The value of + * this property will be unused in queries. There is no replacement. + */ +const gchar * +gdata_youtube_query_get_language (GDataYouTubeQuery *self) +{ + g_return_val_if_fail (GDATA_IS_YOUTUBE_QUERY (self), NULL); + return self->priv->language; +} + +/** + * gdata_youtube_query_set_language: + * @self: a #GDataYouTubeQuery + * @language: (allow-none): a new language name, or %NULL + * + * Sets the #GDataYouTubeQuery:language property of the #GDataYouTubeQuery to the new language, @language. + * + * Set @language to %NULL to unset the property in the query URI. + * + * Since: 0.3.0 + * Deprecated: 0.17.0: No longer supported by Google. The value of + * this property will be unused in queries. There is no replacement. + */ +void +gdata_youtube_query_set_language (GDataYouTubeQuery *self, const gchar *language) +{ + g_return_if_fail (GDATA_IS_YOUTUBE_QUERY (self)); + g_free (self->priv->language); + self->priv->language = g_strdup (language); + g_object_notify (G_OBJECT (self), "language"); + + /* Our current ETag will no longer be relevant */ + gdata_query_set_etag (GDATA_QUERY (self), NULL); +} + +/** + * gdata_youtube_query_get_order_by: + * @self: a #GDataYouTubeQuery + * + * Gets the #GDataYouTubeQuery:order-by property. + * + * Return value: the order by property, or %NULL if it is unset + * + * Since: 0.3.0 + */ +const gchar * +gdata_youtube_query_get_order_by (GDataYouTubeQuery *self) +{ + g_return_val_if_fail (GDATA_IS_YOUTUBE_QUERY (self), NULL); + return self->priv->order_by; +} + +/** + * gdata_youtube_query_set_order_by: + * @self: a #GDataYouTubeQuery + * @order_by: (allow-none): a new order by string, or %NULL + * + * Sets the #GDataYouTubeQuery:order-by property of the #GDataYouTubeQuery to the new order by string, @order_by. + * + * Set @order_by to %NULL to unset the property in the query URI. + * + * Since: 0.3.0 + */ +void +gdata_youtube_query_set_order_by (GDataYouTubeQuery *self, const gchar *order_by) +{ + g_return_if_fail (GDATA_IS_YOUTUBE_QUERY (self)); + + g_free (self->priv->order_by); + self->priv->order_by = g_strdup (order_by); + g_object_notify (G_OBJECT (self), "order-by"); + + /* Our current ETag will no longer be relevant */ + gdata_query_set_etag (GDATA_QUERY (self), NULL); +} + +/** + * gdata_youtube_query_get_restriction: + * @self: a #GDataYouTubeQuery + * + * Gets the #GDataYouTubeQuery:restriction property. + * + * Return value: the restriction property, or %NULL if it is unset + * + * Since: 0.3.0 + */ +const gchar * +gdata_youtube_query_get_restriction (GDataYouTubeQuery *self) +{ + g_return_val_if_fail (GDATA_IS_YOUTUBE_QUERY (self), NULL); + return self->priv->restriction; +} + +/** + * gdata_youtube_query_set_restriction: + * @self: a #GDataYouTubeQuery + * @restriction: (allow-none): a new restriction string, or %NULL + * + * Sets the #GDataYouTubeQuery:restriction property of the #GDataYouTubeQuery to the new restriction string, @restriction. + * + * Set @restriction to %NULL to unset the property in the query URI. + * + * Since: 0.3.0 + */ +void +gdata_youtube_query_set_restriction (GDataYouTubeQuery *self, const gchar *restriction) +{ + g_return_if_fail (GDATA_IS_YOUTUBE_QUERY (self)); + g_free (self->priv->restriction); + self->priv->restriction = g_strdup (restriction); + g_object_notify (G_OBJECT (self), "restriction"); + + /* Our current ETag will no longer be relevant */ + gdata_query_set_etag (GDATA_QUERY (self), NULL); +} + +/** + * gdata_youtube_query_get_safe_search: + * @self: a #GDataYouTubeQuery + * + * Gets the #GDataYouTubeQuery:safe-search property. + * + * Return value: the safe search property + * + * Since: 0.3.0 + */ +GDataYouTubeSafeSearch +gdata_youtube_query_get_safe_search (GDataYouTubeQuery *self) +{ + g_return_val_if_fail (GDATA_IS_YOUTUBE_QUERY (self), GDATA_YOUTUBE_SAFE_SEARCH_MODERATE); + return self->priv->safe_search; +} + +/** + * gdata_youtube_query_set_safe_search: + * @self: a #GDataYouTubeQuery + * @safe_search: a new safe search level + * + * Sets the #GDataYouTubeQuery:safe-search property of the #GDataYouTubeQuery to @safe_search. + * + * Since: 0.3.0 + */ +void +gdata_youtube_query_set_safe_search (GDataYouTubeQuery *self, GDataYouTubeSafeSearch safe_search) +{ + g_return_if_fail (GDATA_IS_YOUTUBE_QUERY (self)); + self->priv->safe_search = safe_search; + g_object_notify (G_OBJECT (self), "safe-search"); + + /* Our current ETag will no longer be relevant */ + gdata_query_set_etag (GDATA_QUERY (self), NULL); +} + +G_GNUC_BEGIN_IGNORE_DEPRECATIONS + +/** + * gdata_youtube_query_get_sort_order: + * @self: a #GDataYouTubeQuery + * + * Gets the #GDataYouTubeQuery:sort-order property. + * + * Return value: the sort order property + * + * Since: 0.3.0 + * Deprecated: 0.17.0: No longer supported by Google. The value of + * this property will be unused in queries. There is no replacement. + */ +GDataYouTubeSortOrder +gdata_youtube_query_get_sort_order (GDataYouTubeQuery *self) +{ + g_return_val_if_fail (GDATA_IS_YOUTUBE_QUERY (self), GDATA_YOUTUBE_SORT_NONE); + return self->priv->sort_order; +} + +/** + * gdata_youtube_query_set_sort_order: + * @self: a #GDataYouTubeQuery + * @sort_order: the new sort order + * + * Sets the #GDataYouTubeQuery:sort-order property of the #GDataYouTubeQuery to @sort_order. + * + * Set @sort_order to %GDATA_YOUTUBE_SORT_NONE to unset the property in the query URI. + * + * Since: 0.3.0 + * Deprecated: 0.17.0: No longer supported by Google. The value of + * this property will be unused in queries. There is no replacement. + */ +void +gdata_youtube_query_set_sort_order (GDataYouTubeQuery *self, GDataYouTubeSortOrder sort_order) +{ + g_return_if_fail (GDATA_IS_YOUTUBE_QUERY (self)); + self->priv->sort_order = sort_order; + g_object_notify (G_OBJECT (self), "sort-order"); + + /* Our current ETag will no longer be relevant */ + gdata_query_set_etag (GDATA_QUERY (self), NULL); +} + +G_GNUC_END_IGNORE_DEPRECATIONS + +/** + * gdata_youtube_query_get_age: + * @self: a #GDataYouTubeQuery + * + * Gets the #GDataYouTubeQuery:age property. + * + * Return value: the age property + * + * Since: 0.3.0 + */ +GDataYouTubeAge +gdata_youtube_query_get_age (GDataYouTubeQuery *self) +{ + g_return_val_if_fail (GDATA_IS_YOUTUBE_QUERY (self), GDATA_YOUTUBE_AGE_ALL_TIME); + return self->priv->age; +} + +/** + * gdata_youtube_query_set_age: + * @self: a #GDataYouTubeQuery + * @age: the new age + * + * Sets the #GDataYouTubeQuery:age property of the #GDataYouTubeQuery to @age. + * + * Since: 0.3.0 + */ +void +gdata_youtube_query_set_age (GDataYouTubeQuery *self, GDataYouTubeAge age) +{ + g_return_if_fail (GDATA_IS_YOUTUBE_QUERY (self)); + self->priv->age = age; + g_object_notify (G_OBJECT (self), "age"); + + /* Our current ETag will no longer be relevant */ + gdata_query_set_etag (GDATA_QUERY (self), NULL); +} + +G_GNUC_BEGIN_IGNORE_DEPRECATIONS + +/** + * gdata_youtube_query_get_uploader: + * @self: a #GDataYouTubeQuery + * + * Gets the #GDataYouTubeQuery:uploader property. + * + * Return value: the uploader property + * + * Since: 0.3.0 + * Deprecated: 0.17.0: No longer supported by Google. The value of + * this property will be unused in queries. There is no replacement. + */ +GDataYouTubeUploader +gdata_youtube_query_get_uploader (GDataYouTubeQuery *self) +{ + g_return_val_if_fail (GDATA_IS_YOUTUBE_QUERY (self), GDATA_YOUTUBE_UPLOADER_ALL); + return self->priv->uploader; +} + +/** + * gdata_youtube_query_set_uploader: + * @self: a #GDataYouTubeQuery + * @uploader: the new uploader + * + * Sets the #GDataYouTubeQuery:uploader property of the #GDataYouTubeQuery to @uploader. + * + * Since: 0.3.0 + * Deprecated: 0.17.0: No longer supported by Google. The value of + * this property will be unused in queries. There is no replacement. + */ +void +gdata_youtube_query_set_uploader (GDataYouTubeQuery *self, GDataYouTubeUploader uploader) +{ + g_return_if_fail (GDATA_IS_YOUTUBE_QUERY (self)); + self->priv->uploader = uploader; + g_object_notify (G_OBJECT (self), "uploader"); + + /* Our current ETag will no longer be relevant */ + gdata_query_set_etag (GDATA_QUERY (self), NULL); +} + +G_GNUC_END_IGNORE_DEPRECATIONS + +/** + * gdata_youtube_query_get_license: + * @self: a #GDataYouTubeQuery + * + * Gets the #GDataYouTubeQuery:license property. + * + * Return value: the license property, or %NULL if it is unset + * + * Since: 0.11.0 + */ +const gchar * +gdata_youtube_query_get_license (GDataYouTubeQuery *self) +{ + g_return_val_if_fail (GDATA_IS_YOUTUBE_QUERY (self), NULL); + return self->priv->license; +} + +/** + * gdata_youtube_query_set_license: + * @self: a #GDataYouTubeQuery + * @license: (allow-none): a new license value, or %NULL + * + * Sets the #GDataYouTubeQuery:license property of the #GDataYouTubeQuery to the new license value, @license. + * + * Set @license to %NULL to unset the property in the query URI. + * + * Since: 0.11.0 + */ +void +gdata_youtube_query_set_license (GDataYouTubeQuery *self, const gchar *license) +{ + g_return_if_fail (GDATA_IS_YOUTUBE_QUERY (self)); + g_free (self->priv->license); + self->priv->license = g_strdup (license); + g_object_notify (G_OBJECT (self), "license"); + + /* Our current ETag will no longer be relevant */ + gdata_query_set_etag (GDATA_QUERY (self), NULL); +} diff --git a/gdata/services/youtube/gdata-youtube-query.h b/gdata/services/youtube/gdata-youtube-query.h new file mode 100644 index 0000000..32924a1 --- /dev/null +++ b/gdata/services/youtube/gdata-youtube-query.h @@ -0,0 +1,197 @@ +/* -*- Mode: C; indent-tabs-mode: t; c-basic-offset: 8; tab-width: 8 -*- */ +/* + * GData Client + * Copyright (C) Philip Withnall 2009, 2015 + * + * GData Client is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * GData Client is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with GData Client. If not, see . + */ + +#ifndef GDATA_YOUTUBE_QUERY_H +#define GDATA_YOUTUBE_QUERY_H + +#include +#include + +#include +#include +#include +#include + +G_BEGIN_DECLS + +/** + * GDataYouTubeSafeSearch: + * @GDATA_YOUTUBE_SAFE_SEARCH_NONE: YouTube will not perform any filtering on the search result set + * @GDATA_YOUTUBE_SAFE_SEARCH_MODERATE: YouTube will filter some content from search results and, at the least, + * will filter content that is restricted in your locale + * @GDATA_YOUTUBE_SAFE_SEARCH_STRICT: YouTube will try to exclude all restricted content from the search result set + * + * Safe search levels for removing restricted entries from query results. For more information, see the + * online documentation. + * + * Since: 0.3.0 + */ +typedef enum { + GDATA_YOUTUBE_SAFE_SEARCH_NONE = 0, + GDATA_YOUTUBE_SAFE_SEARCH_MODERATE, + GDATA_YOUTUBE_SAFE_SEARCH_STRICT +} GDataYouTubeSafeSearch; + +#ifndef LIBGDATA_DISABLE_DEPRECATED +/** + * GDataYouTubeSortOrder: + * @GDATA_YOUTUBE_SORT_NONE: do not explicitly sort in any sense + * @GDATA_YOUTUBE_SORT_ASCENDING: sort results in ascending order of the order field + * @GDATA_YOUTUBE_SORT_DESCENDING: sort results in descending order of the order field + * + * Sort orders for the search results from queries. They specify the order of the designated order field. + * + * Since: 0.3.0 + * Deprecated: 0.17.0: No longer supported by Google. There is no + * replacement. + */ +typedef enum { + GDATA_YOUTUBE_SORT_NONE = 0, + GDATA_YOUTUBE_SORT_ASCENDING, + GDATA_YOUTUBE_SORT_DESCENDING +} GDataYouTubeSortOrder; +#endif /* !LIBGDATA_DISABLE_DEPRECATED */ + +/** + * GDataYouTubeAge: + * @GDATA_YOUTUBE_AGE_ALL_TIME: retrieve all videos, regardless of the date they were uploaded + * @GDATA_YOUTUBE_AGE_TODAY: retrieve only videos uploaded in the past day + * @GDATA_YOUTUBE_AGE_THIS_WEEK: retrieve only videos uploaded in the past week + * @GDATA_YOUTUBE_AGE_THIS_MONTH: retrieve only videos uploaded in the past month + * + * Video ages, allowing queries to be limited to videos uploaded in a recent time period. + * + * Since: 0.3.0 + */ +typedef enum { + GDATA_YOUTUBE_AGE_ALL_TIME = 0, + GDATA_YOUTUBE_AGE_TODAY, + GDATA_YOUTUBE_AGE_THIS_WEEK, + GDATA_YOUTUBE_AGE_THIS_MONTH +} GDataYouTubeAge; + +#ifndef LIBGDATA_DISABLE_DEPRECATED +/** + * GDataYouTubeUploader: + * @GDATA_YOUTUBE_UPLOADER_ALL: retrieve all videos, regardless of who uploaded them + * @GDATA_YOUTUBE_UPLOADER_PARTNER: retrieve only videos uploaded by YouTube partners + * + * Video uploaders, allowing queries to be limited to returning videos uploaded by YouTube partners. + * + * Since: 0.3.0 + * Deprecated: 0.17.0: No longer supported by Google. There is no + * replacement. + */ +typedef enum { + GDATA_YOUTUBE_UPLOADER_ALL = 0, + GDATA_YOUTUBE_UPLOADER_PARTNER +} GDataYouTubeUploader; +#endif /* !LIBGDATA_DISABLE_DEPRECATED */ + +/** + * GDATA_YOUTUBE_LICENSE_CC: + * + * Value for #GDataYouTubeQuery:license to restrict search results to only videos which are Creative Commons licensed. Specifically, the license + * is the Creative Commons Attribution 3.0 Unported license; see the + * YouTube Help for more information. + * + * Since: 0.11.0 + */ +#define GDATA_YOUTUBE_LICENSE_CC "cc" + +/** + * GDATA_YOUTUBE_LICENSE_STANDARD: + * + * Value for #GDataYouTubeQuery:license to restrict search results to only videos which are under the standard YouTube license. + * + * Since: 0.11.0 + */ +#define GDATA_YOUTUBE_LICENSE_STANDARD "youtube" + +#define GDATA_TYPE_YOUTUBE_QUERY (gdata_youtube_query_get_type ()) +#define GDATA_YOUTUBE_QUERY(o) (G_TYPE_CHECK_INSTANCE_CAST ((o), GDATA_TYPE_YOUTUBE_QUERY, GDataYouTubeQuery)) +#define GDATA_YOUTUBE_QUERY_CLASS(k) (G_TYPE_CHECK_CLASS_CAST((k), GDATA_TYPE_YOUTUBE_QUERY, GDataYouTubeQueryClass)) +#define GDATA_IS_YOUTUBE_QUERY(o) (G_TYPE_CHECK_INSTANCE_TYPE ((o), GDATA_TYPE_YOUTUBE_QUERY)) +#define GDATA_IS_YOUTUBE_QUERY_CLASS(k) (G_TYPE_CHECK_CLASS_TYPE ((k), GDATA_TYPE_YOUTUBE_QUERY)) +#define GDATA_YOUTUBE_QUERY_GET_CLASS(o) (G_TYPE_INSTANCE_GET_CLASS ((o), GDATA_TYPE_YOUTUBE_QUERY, GDataYouTubeQueryClass)) + +typedef struct _GDataYouTubeQueryPrivate GDataYouTubeQueryPrivate; + +/** + * GDataYouTubeQuery: + * + * All the fields in the #GDataYouTubeQuery structure are private and should never be accessed directly. + * + * Since: 0.3.0 + */ +typedef struct { + GDataQuery parent; + GDataYouTubeQueryPrivate *priv; +} GDataYouTubeQuery; + +/** + * GDataYouTubeQueryClass: + * + * All the fields in the #GDataYouTubeQueryClass structure are private and should never be accessed directly. + * + * Since: 0.3.0 + */ +typedef struct { + /*< private >*/ + GDataQueryClass parent; + + /*< private >*/ + /* Padding for future expansion */ + void (*_g_reserved0) (void); + void (*_g_reserved1) (void); +} GDataYouTubeQueryClass; + +GType gdata_youtube_query_get_type (void) G_GNUC_CONST; + +GDataYouTubeQuery *gdata_youtube_query_new (const gchar *q) G_GNUC_WARN_UNUSED_RESULT G_GNUC_MALLOC; + +void gdata_youtube_query_get_location (GDataYouTubeQuery *self, gdouble *latitude, gdouble *longitude, gdouble *radius, gboolean *has_location); +void gdata_youtube_query_set_location (GDataYouTubeQuery *self, gdouble latitude, gdouble longitude, gdouble radius, gboolean has_location); +const gchar *gdata_youtube_query_get_order_by (GDataYouTubeQuery *self) G_GNUC_PURE; +void gdata_youtube_query_set_order_by (GDataYouTubeQuery *self, const gchar *order_by); +const gchar *gdata_youtube_query_get_restriction (GDataYouTubeQuery *self) G_GNUC_PURE; +void gdata_youtube_query_set_restriction (GDataYouTubeQuery *self, const gchar *restriction); +GDataYouTubeSafeSearch gdata_youtube_query_get_safe_search (GDataYouTubeQuery *self) G_GNUC_PURE; +void gdata_youtube_query_set_safe_search (GDataYouTubeQuery *self, GDataYouTubeSafeSearch safe_search); +GDataYouTubeAge gdata_youtube_query_get_age (GDataYouTubeQuery *self) G_GNUC_PURE; +void gdata_youtube_query_set_age (GDataYouTubeQuery *self, GDataYouTubeAge age); +const gchar *gdata_youtube_query_get_license (GDataYouTubeQuery *self) G_GNUC_PURE; +void gdata_youtube_query_set_license (GDataYouTubeQuery *self, const gchar *license); + +#ifndef LIBGDATA_DISABLE_DEPRECATED +G_GNUC_BEGIN_IGNORE_DEPRECATIONS +GDataYouTubeFormat gdata_youtube_query_get_format (GDataYouTubeQuery *self) G_GNUC_PURE G_GNUC_DEPRECATED; +void gdata_youtube_query_set_format (GDataYouTubeQuery *self, GDataYouTubeFormat format) G_GNUC_DEPRECATED; +const gchar *gdata_youtube_query_get_language (GDataYouTubeQuery *self) G_GNUC_PURE G_GNUC_DEPRECATED; +void gdata_youtube_query_set_language (GDataYouTubeQuery *self, const gchar *language) G_GNUC_DEPRECATED; +GDataYouTubeSortOrder gdata_youtube_query_get_sort_order (GDataYouTubeQuery *self) G_GNUC_PURE G_GNUC_DEPRECATED; +void gdata_youtube_query_set_sort_order (GDataYouTubeQuery *self, GDataYouTubeSortOrder sort_order) G_GNUC_DEPRECATED; +GDataYouTubeUploader gdata_youtube_query_get_uploader (GDataYouTubeQuery *self) G_GNUC_PURE G_GNUC_DEPRECATED; +void gdata_youtube_query_set_uploader (GDataYouTubeQuery *self, GDataYouTubeUploader uploader) G_GNUC_DEPRECATED; +G_GNUC_END_IGNORE_DEPRECATIONS +#endif /* !LIBGDATA_DISABLE_DEPRECATED */ + +G_END_DECLS + +#endif /* !GDATA_YOUTUBE_QUERY_H */ diff --git a/gdata/services/youtube/gdata-youtube-service.c b/gdata/services/youtube/gdata-youtube-service.c new file mode 100644 index 0000000..89d44bb --- /dev/null +++ b/gdata/services/youtube/gdata-youtube-service.c @@ -0,0 +1,1229 @@ +/* -*- Mode: C; indent-tabs-mode: t; c-basic-offset: 8; tab-width: 8 -*- */ +/* + * GData Client + * Copyright (C) Philip Withnall 2008–2010, 2015 + * + * GData Client is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * GData Client is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with GData Client. If not, see . + */ + +/** + * SECTION:gdata-youtube-service + * @short_description: GData YouTube service object + * @stability: Stable + * @include: gdata/services/youtube/gdata-youtube-service.h + * + * #GDataYouTubeService is a subclass of #GDataService for communicating with the GData API of YouTube. It supports querying for and + * uploading videos using version 3 of the API. + * + * The YouTube API supports returning different sets of properties for + * #GDataYouTubeVideos depending on the specific query. For search results, only + * ‘snippet’ properties are returned (including #GDataEntry:title, + * #GDataEntry:summary and the set of thumbnails). For querying single videos, + * a more complete set of properties are returned — so use + * gdata_service_query_single_entry_async() to get further details on a video. + * + * For more details of YouTube's GData API, see the + * online documentation. + * + * + * Getting a Localized List of YouTube Categories + * + * GDataYouTubeService *service; + * GDataAPPCategories *app_categories; + * GList *categories, *i; + * + * /* Create a service and set its locale to Italian, which localizes the categories to Italian */ + * service = create_youtube_service (); + * gdata_service_set_locale (GDATA_SERVICE (service), "it"); + * + * /* Query the server for the current list of YouTube categories (in Italian) */ + * app_categories = gdata_youtube_service_get_categories (service, NULL, NULL); + * categories = gdata_app_categories_get_categories (app_categories); + * + * /* Iterate through the categories */ + * for (i = categories; i != NULL; i = i->next) { + * GDataYouTubeCategory *category = GDATA_YOUTUBE_CATEGORY (i->data); + * + * if (gdata_youtube_category_is_deprecated (category) == FALSE && gdata_youtube_category_is_browsable (category, "IT") == TRUE) { + * /* Do something with the category here, as it's not deprecated, and is browsable in the given region */ + * add_to_ui (gdata_category_get_term (GDATA_CATEGORY (category)), gdata_category_get_label (GDATA_CATEGORY (category))); + * } + * } + * + * g_object_unref (app_categories); + * g_object_unref (service); + * + * + * + * + * Uploading a Video from Disk + * + * GDataYouTubeService *service; + * GDataYouTubeVideo *video, *uploaded_video; + * GDataMediaCategory *category; + * const gchar * const tags[] = { "tag1", "tag2", NULL }; + * GFile *video_file; + * GFileInfo *file_info; + * const gchar *slug, *content_type; + * GFileInputStream *file_stream; + * GDataUploadStream *upload_stream; + * GError *error = NULL; + * + * /* Create a service */ + * service = create_youtube_service (); + * + * /* Get the video file to upload */ + * video_file = g_file_new_for_path ("sample.ogg"); + * + * /* Get the file's display name and content type */ + * file_info = g_file_query_info (video_file, G_FILE_ATTRIBUTE_STANDARD_DISPLAY_NAME "," G_FILE_ATTRIBUTE_STANDARD_CONTENT_TYPE, + * G_FILE_QUERY_INFO_NONE, NULL, &error); + * + * if (error != NULL) { + * g_error ("Error getting video file information: %s", error->message); + * g_error_free (error); + * g_object_unref (video_file); + * g_object_unref (service); + * return; + * } + * + * slug = g_file_info_get_display_name (file_info); + * content_type = g_file_info_get_content_type (file_info); + * + * /* Get an input stream for the file */ + * file_stream = g_file_read (video_file, NULL, &error); + * + * g_object_unref (video_file); + * + * if (error != NULL) { + * g_error ("Error getting video file stream: %s", error->message); + * g_error_free (error); + * g_object_unref (file_info); + * g_object_unref (service); + * return; + * } + * + * /* Create the video to upload */ + * video = gdata_youtube_video_new (NULL); + * + * gdata_entry_set_title (GDATA_ENTRY (video), "Video Title"); + * gdata_youtube_video_set_description (video, "Video description."); + * gdata_youtube_video_set_keywords (video, video_tags); + * + * category = gdata_media_category_new ("People", "http://gdata.youtube.com/schemas/2007/categories.cat", NULL); + * gdata_youtube_video_set_category (video, category); + * g_object_unref (category); + * + * /* Get an upload stream for the video */ + * upload_stream = gdata_youtube_service_upload_video (service, video, slug, content_type, NULL, &error); + * + * g_object_unref (video); + * g_object_unref (file_info); + * + * if (error != NULL) { + * g_error ("Error getting upload stream: %s", error->message); + * g_error_free (error); + * g_object_unref (file_stream); + * g_object_unref (service); + * return; + * } + * + * /* Upload the video. This is a blocking operation, and should normally be done asynchronously. */ + * g_output_stream_splice (G_OUTPUT_STREAM (upload_stream), G_INPUT_STREAM (file_stream), + * G_OUTPUT_STREAM_SPLICE_CLOSE_SOURCE | G_OUTPUT_STREAM_SPLICE_CLOSE_TARGET, NULL, &error); + * + * g_object_unref (file_stream); + * + * if (error != NULL) { + * g_error ("Error splicing streams: %s", error->message); + * g_error_free (error); + * g_object_unref (upload_stream); + * g_object_unref (service); + * return; + * } + * + * /* Finish off the upload by parsing the returned updated video entry */ + * uploaded_video = gdata_youtube_service_finish_video_upload (service, upload_stream, &error); + * + * g_object_unref (upload_stream); + * g_object_unref (service); + * + * if (error != NULL) { + * g_error ("Error uploading video: %s", error->message); + * g_error_free (error); + * return; + * } + * + * /* Do something with the uploaded video */ + * + * g_object_unref (uploaded_video); + * + * + * + * + * Querying for Videos from a Standard Feed + * + * GDataYouTubeService *service; + * GDataFeed *feed; + * GList *i; + * GError *error = NULL; + * + * /* Create a service */ + * service = create_youtube_service (); + * + * /* Query for the top page of videos in the most popular feed */ + * feed = gdata_youtube_service_query_standard_feed (service, GDATA_YOUTUBE_MOST_POPULAR_FEED, NULL, NULL, NULL, NULL, &error); + * + * g_object_unref (service); + * + * if (error != NULL) { + * g_error ("Error querying for most popular videos: %s", error->message); + * g_error_free (error); + * return; + * } + * + * /* Iterate through the videos */ + * for (i = gdata_feed_get_entries (feed); i != NULL; i = i->next) { + * GDataYouTubeVideo *video = GDATA_YOUTUBE_VIDEO (i->data); + * + * /* Do something with the video, like insert it into the UI */ + * } + * + * g_object_unref (feed); + * + * + * + * + * Querying for Videos using Search Terms + * + * GDataYouTubeService *service; + * GDataYouTubeQuery *query; + * GDataFeed *feed; + * GList *i; + * GError *error = NULL; + * + * /* Create a service */ + * service = create_youtube_service (); + * + * /* Build a query with the given search terms, also matching only videos which are CC-licensed */ + * query = gdata_youtube_query_new (my_space_separated_search_terms); + * gdata_youtube_query_set_license (query, GDATA_YOUTUBE_LICENSE_CC); + * + * /* Query for the videos matching the query parameters */ + * feed = gdata_youtube_service_query_videos (service, query, NULL, NULL, NULL, &error); + * + * g_object_unref (query); + * g_object_unref (service); + * + * if (error != NULL) { + * g_error ("Error querying for videos matching search terms ‘%s’: %s", my_space_separated_search_terms, error->message); + * g_error_free (error); + * return; + * } + * + * /* Iterate through the videos */ + * for (i = gdata_feed_get_entries (feed); i != NULL; i = i->next) { + * GDataYouTubeVideo *video = GDATA_YOUTUBE_VIDEO (i->data); + * + * /* Do something with the video, like insert it into the UI */ + * } + * + * g_object_unref (feed); + * + * + */ + +#include +#include +#include +#include +#include + +#include "gdata-youtube-service.h" +#include "gdata-youtube-feed.h" +#include "gdata-service.h" +#include "gdata-private.h" +#include "gdata-parser.h" +#include "atom/gdata-link.h" +#include "gdata-upload-stream.h" +#include "gdata-youtube-category.h" +#include "gdata-batchable.h" + +/* Standards reference here: https://developers.google.com/youtube/v3/docs/ */ + +GQuark +gdata_youtube_service_error_quark (void) +{ + return g_quark_from_static_string ("gdata-youtube-service-error-quark"); +} + +static void gdata_youtube_service_batchable_init (GDataBatchableIface *iface); +static void gdata_youtube_service_finalize (GObject *object); +static void gdata_youtube_service_get_property (GObject *object, guint property_id, GValue *value, GParamSpec *pspec); +static void gdata_youtube_service_set_property (GObject *object, guint property_id, const GValue *value, GParamSpec *pspec); +static void append_query_headers (GDataService *self, GDataAuthorizationDomain *domain, SoupMessage *message); +static void parse_error_response (GDataService *self, GDataOperationType operation_type, guint status, const gchar *reason_phrase, + const gchar *response_body, gint length, GError **error); + +static GList *get_authorization_domains (void); + +struct _GDataYouTubeServicePrivate { + gchar *developer_key; +}; + +enum { + PROP_DEVELOPER_KEY = 1 +}; + +/* Reference: https://developers.google.com/youtube/v3/guides/authentication */ +_GDATA_DEFINE_AUTHORIZATION_DOMAIN (youtube, "youtube", + "https://www.googleapis.com/auth/youtube") +_GDATA_DEFINE_AUTHORIZATION_DOMAIN (youtube_force_ssl, "youtube-force-ssl", + "https://www.googleapis.com/auth/youtube.force-ssl") +G_DEFINE_TYPE_WITH_CODE (GDataYouTubeService, gdata_youtube_service, GDATA_TYPE_SERVICE, + G_IMPLEMENT_INTERFACE (GDATA_TYPE_BATCHABLE, + gdata_youtube_service_batchable_init)) + +static void +gdata_youtube_service_class_init (GDataYouTubeServiceClass *klass) +{ + GObjectClass *gobject_class = G_OBJECT_CLASS (klass); + GDataServiceClass *service_class = GDATA_SERVICE_CLASS (klass); + + g_type_class_add_private (klass, sizeof (GDataYouTubeServicePrivate)); + + gobject_class->set_property = gdata_youtube_service_set_property; + gobject_class->get_property = gdata_youtube_service_get_property; + gobject_class->finalize = gdata_youtube_service_finalize; + + service_class->feed_type = GDATA_TYPE_YOUTUBE_FEED; + service_class->append_query_headers = append_query_headers; + service_class->parse_error_response = parse_error_response; + service_class->get_authorization_domains = get_authorization_domains; + + /** + * GDataYouTubeService:developer-key: + * + * The developer key your application has registered with the YouTube API. For more information, see the online documentation. + * + * With the port from v2 to v3 of the YouTube API in libgdata + * 0.17.0, it might be necessary to update your application’s + * developer key. + */ + g_object_class_install_property (gobject_class, PROP_DEVELOPER_KEY, + g_param_spec_string ("developer-key", + "Developer key", "Your YouTube developer API key.", + NULL, + G_PARAM_CONSTRUCT_ONLY | G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)); +} + +static gboolean +gdata_youtube_service_batchable_is_supported (GDataBatchOperationType operation_type) +{ + /* Batch operation support was removed with v3 of the API: + * https://developers.google.com/youtube/v3/guides/implementation/deprecated#Batch_Processing */ + return FALSE; +} + +static void +gdata_youtube_service_batchable_init (GDataBatchableIface *iface) +{ + iface->is_supported = gdata_youtube_service_batchable_is_supported; +} + +static void +gdata_youtube_service_init (GDataYouTubeService *self) +{ + self->priv = G_TYPE_INSTANCE_GET_PRIVATE (self, GDATA_TYPE_YOUTUBE_SERVICE, GDataYouTubeServicePrivate); +} + +static void +gdata_youtube_service_finalize (GObject *object) +{ + GDataYouTubeServicePrivate *priv = GDATA_YOUTUBE_SERVICE (object)->priv; + + g_free (priv->developer_key); + + /* Chain up to the parent class */ + G_OBJECT_CLASS (gdata_youtube_service_parent_class)->finalize (object); +} + +static void +gdata_youtube_service_get_property (GObject *object, guint property_id, GValue *value, GParamSpec *pspec) +{ + GDataYouTubeServicePrivate *priv = GDATA_YOUTUBE_SERVICE (object)->priv; + + switch (property_id) { + case PROP_DEVELOPER_KEY: + g_value_set_string (value, priv->developer_key); + break; + default: + /* We don't have any other property... */ + G_OBJECT_WARN_INVALID_PROPERTY_ID (object, property_id, pspec); + break; + } +} + +static void +gdata_youtube_service_set_property (GObject *object, guint property_id, const GValue *value, GParamSpec *pspec) +{ + GDataYouTubeServicePrivate *priv = GDATA_YOUTUBE_SERVICE (object)->priv; + + switch (property_id) { + case PROP_DEVELOPER_KEY: + priv->developer_key = g_value_dup_string (value); + break; + default: + /* We don't have any other property... */ + G_OBJECT_WARN_INVALID_PROPERTY_ID (object, property_id, pspec); + break; + } +} + +static void +append_query_headers (GDataService *self, GDataAuthorizationDomain *domain, + SoupMessage *message) +{ + GDataYouTubeServicePrivate *priv = GDATA_YOUTUBE_SERVICE (self)->priv; + + g_assert (message != NULL); + + if (priv->developer_key != NULL && + !gdata_authorizer_is_authorized_for_domain (gdata_service_get_authorizer (GDATA_SERVICE (self)), + get_youtube_authorization_domain ())) { + const gchar *query; + SoupURI *uri; + + uri = soup_message_get_uri (message); + query = soup_uri_get_query (uri); + + /* Set the key on every unauthorised request: + * https://developers.google.com/youtube/v3/docs/standard_parameters#key */ + if (query != NULL) { + GString *new_query; + + new_query = g_string_new (query); + + g_string_append (new_query, "&key="); + g_string_append_uri_escaped (new_query, + priv->developer_key, NULL, + FALSE); + + soup_uri_set_query (uri, new_query->str); + g_string_free (new_query, TRUE); + } + } + + /* Chain up to the parent class */ + GDATA_SERVICE_CLASS (gdata_youtube_service_parent_class)->append_query_headers (self, domain, message); +} + +/* Reference: https://developers.google.com/youtube/v3/docs/errors + * + * Example response: + * { + * "error": { + * "errors": [ + * { + * "domain": "youtube.parameter", + * "reason": "missingRequiredParameter", + * "message": "No filter selected.", + * "locationType": "parameter", + * "location": "" + * } + * ], + * "code": 400, + * "message": "No filter selected." + * } + * } + */ +/* FIXME: Factor this out into a common JSON error parser helper which simply + * takes a map of expected error codes. */ +static void +parse_error_response (GDataService *self, GDataOperationType operation_type, + guint status, const gchar *reason_phrase, + const gchar *response_body, gint length, GError **error) +{ + JsonParser *parser = NULL; /* owned */ + JsonReader *reader = NULL; /* owned */ + gint i; + GError *child_error = NULL; + + if (response_body == NULL) { + goto parent; + } + + if (length == -1) { + length = strlen (response_body); + } + + parser = json_parser_new (); + if (!json_parser_load_from_data (parser, response_body, length, + &child_error)) { + goto parent; + } + + reader = json_reader_new (json_parser_get_root (parser)); + + /* Check that the outermost node is an object. */ + if (!json_reader_is_object (reader)) { + goto parent; + } + + /* Grab the ‘error’ member, then its ‘errors’ member. */ + if (!json_reader_read_member (reader, "error") || + !json_reader_is_object (reader) || + !json_reader_read_member (reader, "errors") || + !json_reader_is_array (reader)) { + goto parent; + } + + /* Parse each of the errors. Return the first one, and print out any + * others. */ + for (i = 0; i < json_reader_count_elements (reader); i++) { + const gchar *domain, *reason, *message, *extended_help; + const gchar *location_type, *location; + + /* Parse the error. */ + if (!json_reader_read_element (reader, i) || + !json_reader_is_object (reader)) { + goto parent; + } + + json_reader_read_member (reader, "domain"); + domain = json_reader_get_string_value (reader); + json_reader_end_member (reader); + + json_reader_read_member (reader, "reason"); + reason = json_reader_get_string_value (reader); + json_reader_end_member (reader); + + json_reader_read_member (reader, "message"); + message = json_reader_get_string_value (reader); + json_reader_end_member (reader); + + json_reader_read_member (reader, "extendedHelp"); + extended_help = json_reader_get_string_value (reader); + json_reader_end_member (reader); + + json_reader_read_member (reader, "locationType"); + location_type = json_reader_get_string_value (reader); + json_reader_end_member (reader); + + json_reader_read_member (reader, "location"); + location = json_reader_get_string_value (reader); + json_reader_end_member (reader); + + /* End the error element. */ + json_reader_end_element (reader); + + /* Create an error message, but only for the first error */ + if (error == NULL || *error == NULL) { + if (g_strcmp0 (domain, "usageLimits") == 0 && + g_strcmp0 (reason, + "dailyLimitExceededUnreg") == 0) { + /* Daily Limit for Unauthenticated Use + * Exceeded. */ + g_set_error (error, GDATA_SERVICE_ERROR, + GDATA_SERVICE_ERROR_API_QUOTA_EXCEEDED, + _("You have made too many API " + "calls recently. Please wait a " + "few minutes and try again.")); + } else if (g_strcmp0 (reason, + "rateLimitExceeded") == 0) { + g_set_error (error, GDATA_YOUTUBE_SERVICE_ERROR, + GDATA_YOUTUBE_SERVICE_ERROR_ENTRY_QUOTA_EXCEEDED, + _("You have exceeded your entry " + "quota. Please delete some " + "entries and try again.")); + } else if (g_strcmp0 (domain, "global") == 0 && + (g_strcmp0 (reason, "authError") == 0 || + g_strcmp0 (reason, "required") == 0)) { + /* Authentication problem */ + g_set_error (error, GDATA_SERVICE_ERROR, + GDATA_SERVICE_ERROR_AUTHENTICATION_REQUIRED, + _("You must be authenticated to " + "do this.")); + } else if (g_strcmp0 (reason, + "youtubeSignupRequired") == 0) { + /* Tried to authenticate with a Google Account which hasn't yet had a YouTube channel created for it. */ + g_set_error (error, GDATA_YOUTUBE_SERVICE_ERROR, + GDATA_YOUTUBE_SERVICE_ERROR_CHANNEL_REQUIRED, + /* Translators: the parameter is a URI. */ + _("Your Google Account must be " + "associated with a YouTube " + "channel to do this. Visit %s " + "to create one."), + "https://www.youtube.com/create_channel"); + } else { + /* Unknown or validation (protocol) error. Fall + * back to working off the HTTP status code. */ + g_warning ("Unknown error code ‘%s’ in domain " + "‘%s’ received with location type " + "‘%s’, location ‘%s’, extended help " + "‘%s’ and message ‘%s’.", + reason, domain, location_type, + location, extended_help, message); + + goto parent; + } + } else { + /* For all errors after the first, log the error in the + * terminal. */ + g_debug ("Error message received in response: domain " + "‘%s’, reason ‘%s’, extended help ‘%s’, " + "message ‘%s’, location type ‘%s’, location " + "‘%s’.", + domain, reason, extended_help, message, + location_type, location); + } + } + + /* End the ‘errors’ and ‘error’ members. */ + json_reader_end_element (reader); + json_reader_end_element (reader); + + g_clear_object (&reader); + g_clear_object (&parser); + + /* Ensure we’ve actually set an error message. */ + g_assert (error == NULL || *error != NULL); + + return; + +parent: + g_clear_object (&reader); + g_clear_object (&parser); + + /* Chain up to the parent class */ + GDATA_SERVICE_CLASS (gdata_youtube_service_parent_class)->parse_error_response (self, operation_type, status, reason_phrase, + response_body, length, error); +} + +static GList * +get_authorization_domains (void) +{ + GList *authorization_domains = NULL; + + authorization_domains = g_list_prepend (authorization_domains, get_youtube_authorization_domain ()); + authorization_domains = g_list_prepend (authorization_domains, get_youtube_force_ssl_authorization_domain ()); + + return authorization_domains; +} + +/** + * gdata_youtube_service_new: + * @developer_key: your application's developer API key + * @authorizer: (allow-none): a #GDataAuthorizer to authorize the service's requests, or %NULL + * + * Creates a new #GDataYouTubeService using the given #GDataAuthorizer. If @authorizer is %NULL, all requests are made as an unauthenticated user. + * The @developer_key must be unique for your application, and as + * registered with Google. + * + * Return value: a new #GDataYouTubeService, or %NULL; unref with g_object_unref() + * + * Since: 0.9.0 + */ +GDataYouTubeService * +gdata_youtube_service_new (const gchar *developer_key, GDataAuthorizer *authorizer) +{ + g_return_val_if_fail (developer_key != NULL, NULL); + g_return_val_if_fail (authorizer == NULL || GDATA_IS_AUTHORIZER (authorizer), NULL); + + return g_object_new (GDATA_TYPE_YOUTUBE_SERVICE, + "developer-key", developer_key, + "authorizer", authorizer, + NULL); +} + +/** + * gdata_youtube_service_get_primary_authorization_domain: + * + * The primary #GDataAuthorizationDomain for interacting with YouTube. This will not normally need to be used, as it's used internally + * by the #GDataYouTubeService methods. However, if using the plain #GDataService methods to implement custom queries or requests which libgdata + * does not support natively, then this domain may be needed to authorize the requests. + * + * The domain never changes, and is interned so that pointer comparison can be used to differentiate it from other authorization domains. + * + * Return value: (transfer none): the service's authorization domain + * + * Since: 0.9.0 + */ +GDataAuthorizationDomain * +gdata_youtube_service_get_primary_authorization_domain (void) +{ + return get_youtube_authorization_domain (); +} + +static gchar * +standard_feed_type_to_feed_uri (GDataYouTubeStandardFeedType feed_type) +{ + switch (feed_type) { + case GDATA_YOUTUBE_MOST_POPULAR_FEED: + return _gdata_service_build_uri ("https://www.googleapis.com/youtube/v3/videos" + "?part=snippet" + "&chart=mostPopular"); + case GDATA_YOUTUBE_TOP_RATED_FEED: + case GDATA_YOUTUBE_TOP_FAVORITES_FEED: + case GDATA_YOUTUBE_MOST_VIEWED_FEED: + case GDATA_YOUTUBE_MOST_RECENT_FEED: + case GDATA_YOUTUBE_MOST_DISCUSSED_FEED: + case GDATA_YOUTUBE_MOST_LINKED_FEED: + case GDATA_YOUTUBE_MOST_RESPONDED_FEED: + case GDATA_YOUTUBE_RECENTLY_FEATURED_FEED: + case GDATA_YOUTUBE_WATCH_ON_MOBILE_FEED: { + gchar *date, *out; + GTimeVal tv; + + /* All feed types except MOST_POPULAR have been deprecated for + * a while, and fall back to MOST_POPULAR on the server anyway. + * See: https://developers.google.com/youtube/2.0/developers_guide_protocol_video_feeds#Standard_feeds */ + g_get_current_time (&tv); + tv.tv_sec -= 24 * 60 * 60; /* 1 day ago */ + date = g_time_val_to_iso8601 (&tv); + out = _gdata_service_build_uri ("https://www.googleapis.com/youtube/v3/videos" + "?part=snippet" + "&chart=mostPopular" + "&publishedAfter=%s", date); + g_free (date); + + return out; + } + default: + g_assert_not_reached (); + } +} + +/** + * gdata_youtube_service_query_standard_feed: + * @self: a #GDataYouTubeService + * @feed_type: the feed type to query, from #GDataYouTubeStandardFeedType + * @query: (allow-none): a #GDataQuery with the query parameters, or %NULL + * @cancellable: (allow-none): optional #GCancellable object, or %NULL + * @progress_callback: (allow-none) (scope call) (closure progress_user_data): a #GDataQueryProgressCallback to call when an entry is loaded, or %NULL + * @progress_user_data: (closure): data to pass to the @progress_callback function + * @error: a #GError, or %NULL + * + * Queries the service's standard @feed_type feed to build a #GDataFeed. + * + * Note that with the port from v2 to v3 of the YouTube API in libgdata + * 0.17.0, all feed types except %GDATA_YOUTUBE_MOST_POPULAR_FEED have been + * deprecated. Other feed types will now transparently return + * %GDATA_YOUTUBE_MOST_POPULAR_FEED, limited to the past 24 hours. + * + * Parameters and errors are as for gdata_service_query(). + * + * Return value: (transfer full): a #GDataFeed of query results, or %NULL; unref with g_object_unref() + */ +GDataFeed * +gdata_youtube_service_query_standard_feed (GDataYouTubeService *self, GDataYouTubeStandardFeedType feed_type, GDataQuery *query, + GCancellable *cancellable, GDataQueryProgressCallback progress_callback, gpointer progress_user_data, + GError **error) +{ + gchar *query_uri; + GDataFeed *feed; + + g_return_val_if_fail (GDATA_IS_YOUTUBE_SERVICE (self), NULL); + g_return_val_if_fail (query == NULL || GDATA_IS_QUERY (query), NULL); + g_return_val_if_fail (cancellable == NULL || G_IS_CANCELLABLE (cancellable), NULL); + g_return_val_if_fail (error == NULL || *error == NULL, NULL); + + /* TODO: Support the "time" parameter, as well as category- and region-specific feeds */ + query_uri = standard_feed_type_to_feed_uri (feed_type); + feed = gdata_service_query (GDATA_SERVICE (self), + get_youtube_authorization_domain (), + query_uri, query, GDATA_TYPE_YOUTUBE_VIDEO, + cancellable, progress_callback, + progress_user_data, error); + g_free (query_uri); + + return feed; +} + +/** + * gdata_youtube_service_query_standard_feed_async: + * @self: a #GDataService + * @feed_type: the feed type to query, from #GDataYouTubeStandardFeedType + * @query: (allow-none): a #GDataQuery with the query parameters, or %NULL + * @cancellable: (allow-none): optional #GCancellable object, or %NULL + * @progress_callback: (allow-none) (closure progress_user_data): a #GDataQueryProgressCallback to call when an entry is loaded, or %NULL + * @progress_user_data: (closure): data to pass to the @progress_callback function + * @destroy_progress_user_data: (allow-none): the function to call when @progress_callback will not be called any more, or %NULL. This function will be + * called with @progress_user_data as a parameter and can be used to free any memory allocated for it. + * @callback: a #GAsyncReadyCallback to call when authentication is finished + * @user_data: (closure): data to pass to the @callback function + * + * Queries the service's standard @feed_type feed to build a #GDataFeed. @self and + * @query are both reffed when this function is called, so can safely be freed after this function returns. + * + * For more details, see gdata_youtube_service_query_standard_feed(), which is the synchronous version of this function. + * + * When the operation is finished, @callback will be called. You can then call gdata_service_query_finish() + * to get the results of the operation. + * + * Since: 0.9.1 + */ +void +gdata_youtube_service_query_standard_feed_async (GDataYouTubeService *self, GDataYouTubeStandardFeedType feed_type, GDataQuery *query, + GCancellable *cancellable, GDataQueryProgressCallback progress_callback, gpointer progress_user_data, + GDestroyNotify destroy_progress_user_data, + GAsyncReadyCallback callback, gpointer user_data) +{ + gchar *query_uri; + + g_return_if_fail (GDATA_IS_YOUTUBE_SERVICE (self)); + g_return_if_fail (query == NULL || GDATA_IS_QUERY (query)); + g_return_if_fail (cancellable == NULL || G_IS_CANCELLABLE (cancellable)); + g_return_if_fail (callback != NULL); + + query_uri = standard_feed_type_to_feed_uri (feed_type); + gdata_service_query_async (GDATA_SERVICE (self), + get_youtube_authorization_domain (), + query_uri, query, GDATA_TYPE_YOUTUBE_VIDEO, + cancellable, progress_callback, + progress_user_data, + destroy_progress_user_data, callback, + user_data); + g_free (query_uri); +} + +/** + * gdata_youtube_service_query_videos: + * @self: a #GDataYouTubeService + * @query: (allow-none): a #GDataQuery with the query parameters, or %NULL + * @cancellable: (allow-none): optional #GCancellable object, or %NULL + * @progress_callback: (allow-none) (scope call) (closure progress_user_data): a #GDataQueryProgressCallback to call when an entry is loaded, or %NULL + * @progress_user_data: (closure): data to pass to the @progress_callback function + * @error: a #GError, or %NULL + * + * Queries the service for videos matching the parameters set on the #GDataQuery. This searches site-wide, and imposes no other restrictions or + * parameters on the query. + * + * Parameters and errors are as for gdata_service_query(). + * + * Return value: (transfer full): a #GDataFeed of query results, or %NULL; unref with g_object_unref() + */ +GDataFeed * +gdata_youtube_service_query_videos (GDataYouTubeService *self, GDataQuery *query, + GCancellable *cancellable, GDataQueryProgressCallback progress_callback, gpointer progress_user_data, + GError **error) +{ + g_return_val_if_fail (GDATA_IS_YOUTUBE_SERVICE (self), NULL); + g_return_val_if_fail (query == NULL || GDATA_IS_QUERY (query), NULL); + g_return_val_if_fail (cancellable == NULL || G_IS_CANCELLABLE (cancellable), NULL); + g_return_val_if_fail (error == NULL || *error == NULL, NULL); + + return gdata_service_query (GDATA_SERVICE (self), + get_youtube_authorization_domain (), + "https://www.googleapis.com/youtube/v3/search" + "?part=snippet" + "&type=video", + query, GDATA_TYPE_YOUTUBE_VIDEO, + cancellable, progress_callback, + progress_user_data, error); +} + +/** + * gdata_youtube_service_query_videos_async: + * @self: a #GDataService + * @query: (allow-none): a #GDataQuery with the query parameters, or %NULL + * @cancellable: (allow-none): optional #GCancellable object, or %NULL + * @progress_callback: (allow-none) (closure progress_user_data): a #GDataQueryProgressCallback to call when an entry is loaded, or %NULL + * @progress_user_data: (closure): data to pass to the @progress_callback function + * @destroy_progress_user_data: (allow-none): the function to call when @progress_callback will not be called any more, or %NULL. This function will be + * called with @progress_user_data as a parameter and can be used to free any memory allocated for it. + * @callback: a #GAsyncReadyCallback to call when authentication is finished + * @user_data: (closure): data to pass to the @callback function + * + * Queries the service for videos matching the parameters set on the #GDataQuery. This searches site-wide, and imposes no other restrictions or + * parameters on the query. @self and @query are both reffed when this function is called, so can safely be freed after this function returns. + * + * For more details, see gdata_youtube_service_query_videos(), which is the synchronous version of this function. + * + * When the operation is finished, @callback will be called. You can then call gdata_service_query_finish() + * to get the results of the operation. + * + * Since: 0.9.1 + */ +void +gdata_youtube_service_query_videos_async (GDataYouTubeService *self, GDataQuery *query, + GCancellable *cancellable, GDataQueryProgressCallback progress_callback, gpointer progress_user_data, + GDestroyNotify destroy_progress_user_data, + GAsyncReadyCallback callback, gpointer user_data) +{ + g_return_if_fail (GDATA_IS_YOUTUBE_SERVICE (self)); + g_return_if_fail (query == NULL || GDATA_IS_QUERY (query)); + g_return_if_fail (cancellable == NULL || G_IS_CANCELLABLE (cancellable)); + g_return_if_fail (callback != NULL); + + gdata_service_query_async (GDATA_SERVICE (self), + get_youtube_authorization_domain (), + "https://www.googleapis.com/youtube/v3/search" + "?part=snippet" + "&type=video", + query, GDATA_TYPE_YOUTUBE_VIDEO, cancellable, + progress_callback, progress_user_data, + destroy_progress_user_data, callback, + user_data); +} + +/** + * gdata_youtube_service_query_related: + * @self: a #GDataYouTubeService + * @video: a #GDataYouTubeVideo for which to find related videos + * @query: (allow-none): a #GDataQuery with the query parameters, or %NULL + * @cancellable: (allow-none): optional #GCancellable object, or %NULL + * @progress_callback: (allow-none) (scope call) (closure progress_user_data): a #GDataQueryProgressCallback to call when an entry is loaded, or %NULL + * @progress_user_data: (closure): data to pass to the @progress_callback function + * @error: a #GError, or %NULL + * + * Queries the service for videos related to @video. The algorithm determining which videos are related is on the server side. + * + * Parameters and other errors are as for gdata_service_query(). + * + * Return value: (transfer full): a #GDataFeed of query results; unref with g_object_unref() + */ +GDataFeed * +gdata_youtube_service_query_related (GDataYouTubeService *self, GDataYouTubeVideo *video, GDataQuery *query, + GCancellable *cancellable, GDataQueryProgressCallback progress_callback, gpointer progress_user_data, + GError **error) +{ + GDataFeed *feed; + gchar *uri; + + g_return_val_if_fail (GDATA_IS_YOUTUBE_SERVICE (self), NULL); + g_return_val_if_fail (GDATA_IS_YOUTUBE_VIDEO (video), NULL); + g_return_val_if_fail (query == NULL || GDATA_IS_QUERY (query), NULL); + g_return_val_if_fail (cancellable == NULL || G_IS_CANCELLABLE (cancellable), NULL); + g_return_val_if_fail (error == NULL || *error == NULL, NULL); + + /* Execute the query */ + uri = _gdata_service_build_uri ("https://www.googleapis.com/youtube/v3/search" + "?part=snippet" + "&type=video" + "&relatedToVideoId=%s", + gdata_entry_get_id (GDATA_ENTRY (video))); + feed = gdata_service_query (GDATA_SERVICE (self), + get_youtube_authorization_domain (), uri, + query, GDATA_TYPE_YOUTUBE_VIDEO, + cancellable, progress_callback, + progress_user_data, error); + g_free (uri); + + return feed; +} + +/** + * gdata_youtube_service_query_related_async: + * @self: a #GDataService + * @video: a #GDataYouTubeVideo for which to find related videos + * @query: (allow-none): a #GDataQuery with the query parameters, or %NULL + * @cancellable: (allow-none): optional #GCancellable object, or %NULL + * @progress_callback: (allow-none) (closure progress_user_data): a #GDataQueryProgressCallback to call when an entry is loaded, or %NULL + * @progress_user_data: (closure): data to pass to the @progress_callback function + * @destroy_progress_user_data: (allow-none): the function to call when @progress_callback will not be called any more, or %NULL. This function will be + * called with @progress_user_data as a parameter and can be used to free any memory allocated for it. + * @callback: a #GAsyncReadyCallback to call when authentication is finished + * @user_data: (closure): data to pass to the @callback function + * + * Queries the service for videos related to @video. The algorithm determining which videos are related is on the server side. + * @self and @query are both reffed when this function is called, so can safely be freed after this function returns. + * + * For more details, see gdata_youtube_service_query_related(), which is the synchronous version of this function. + * + * When the operation is finished, @callback will be called. You can then call gdata_service_query_finish() + * to get the results of the operation. + * + * Since: 0.9.1 + */ +void +gdata_youtube_service_query_related_async (GDataYouTubeService *self, GDataYouTubeVideo *video, GDataQuery *query, + GCancellable *cancellable, GDataQueryProgressCallback progress_callback, gpointer progress_user_data, + GDestroyNotify destroy_progress_user_data, + GAsyncReadyCallback callback, gpointer user_data) +{ + gchar *uri; + + g_return_if_fail (GDATA_IS_YOUTUBE_SERVICE (self)); + g_return_if_fail (GDATA_IS_YOUTUBE_VIDEO (video)); + g_return_if_fail (query == NULL || GDATA_IS_QUERY (query)); + g_return_if_fail (cancellable == NULL || G_IS_CANCELLABLE (cancellable)); + g_return_if_fail (callback != NULL); + + uri = _gdata_service_build_uri ("https://www.googleapis.com/youtube/v3/search" + "?part=snippet" + "&type=video" + "&relatedToVideoId=%s", + gdata_entry_get_id (GDATA_ENTRY (video))); + gdata_service_query_async (GDATA_SERVICE (self), + get_youtube_authorization_domain (), uri, + query, GDATA_TYPE_YOUTUBE_VIDEO, cancellable, + progress_callback, progress_user_data, + destroy_progress_user_data, callback, + user_data); + g_free (uri); +} + +/** + * gdata_youtube_service_upload_video: + * @self: a #GDataYouTubeService + * @video: a #GDataYouTubeVideo to insert + * @slug: the filename to give to the uploaded file + * @content_type: the content type of the uploaded data + * @cancellable: (allow-none): a #GCancellable for the entire upload stream, or %NULL + * @error: a #GError, or %NULL + * + * Uploads a video to YouTube, using the properties from @video and the file data written to the resulting #GDataUploadStream. + * + * If @video has already been inserted, a %GDATA_SERVICE_ERROR_ENTRY_ALREADY_INSERTED error will be returned. If no user is authenticated + * with the service, %GDATA_SERVICE_ERROR_AUTHENTICATION_REQUIRED will be returned. + * + * The stream returned by this function should be written to using the standard #GOutputStream methods, asynchronously or synchronously. Once the stream + * is closed (using g_output_stream_close()), gdata_youtube_service_finish_video_upload() should be called on it to parse and return the updated + * #GDataYouTubeVideo for the uploaded video. This must be done, as @video isn't updated in-place. + * + * In order to cancel the upload, a #GCancellable passed in to @cancellable must be cancelled using g_cancellable_cancel(). Cancelling the individual + * #GOutputStream operations on the #GDataUploadStream will not cancel the entire upload; merely the write or close operation in question. See the + * #GDataUploadStream:cancellable for more details. + * + * Any upload errors will be thrown by the stream methods, and may come from the #GDataServiceError domain. + * + * Return value: (transfer full): a #GDataUploadStream to write the video data to, or %NULL; unref with g_object_unref() + * + * Since: 0.8.0 + */ +GDataUploadStream * +gdata_youtube_service_upload_video (GDataYouTubeService *self, GDataYouTubeVideo *video, const gchar *slug, const gchar *content_type, + GCancellable *cancellable, GError **error) +{ + GOutputStream *stream = NULL; /* owned */ + + g_return_val_if_fail (GDATA_IS_YOUTUBE_SERVICE (self), NULL); + g_return_val_if_fail (GDATA_IS_YOUTUBE_VIDEO (video), NULL); + g_return_val_if_fail (slug != NULL && *slug != '\0', NULL); + g_return_val_if_fail (content_type != NULL && *content_type != '\0', NULL); + g_return_val_if_fail (cancellable == NULL || G_IS_CANCELLABLE (cancellable), NULL); + g_return_val_if_fail (error == NULL || *error == NULL, NULL); + + if (gdata_entry_is_inserted (GDATA_ENTRY (video)) == TRUE) { + g_set_error_literal (error, GDATA_SERVICE_ERROR, GDATA_SERVICE_ERROR_ENTRY_ALREADY_INSERTED, + _("The entry has already been inserted.")); + return NULL; + } + + /* FIXME: Could be more cunning about domains here; see scope on + * https://developers.google.com/youtube/v3/guides/authentication */ + if (gdata_authorizer_is_authorized_for_domain (gdata_service_get_authorizer (GDATA_SERVICE (self)), + get_youtube_authorization_domain ()) == FALSE) { + g_set_error_literal (error, GDATA_SERVICE_ERROR, GDATA_SERVICE_ERROR_AUTHENTICATION_REQUIRED, + _("You must be authenticated to upload a video.")); + return NULL; + } + + /* FIXME: Add support for resumable uploads. That means a new + * gdata_youtube_service_upload_video_resumable() method a la + * Documents. */ + stream = gdata_upload_stream_new (GDATA_SERVICE (self), + get_youtube_authorization_domain (), + SOUP_METHOD_POST, + "https://www.googleapis.com/upload/youtube/v3/videos" + "?part=snippet,status," + "recordingDetails", + GDATA_ENTRY (video), slug, + content_type, + cancellable); + + return GDATA_UPLOAD_STREAM (stream); +} + +/** + * gdata_youtube_service_finish_video_upload: + * @self: a #GDataYouTubeService + * @upload_stream: the #GDataUploadStream from the operation + * @error: a #GError, or %NULL + * + * Finish off a video upload operation started by gdata_youtube_service_upload_video(), parsing the result and returning the new #GDataYouTubeVideo. + * + * If an error occurred during the upload operation, it will have been returned during the operation (e.g. by g_output_stream_splice() or one + * of the other stream methods). In such a case, %NULL will be returned but @error will remain unset. @error is only set in the case that the server + * indicates that the operation was successful, but an error is encountered in parsing the result sent by the server. + * + * Return value: (transfer full): the new #GDataYouTubeVideo, or %NULL; unref with g_object_unref() + * + * Since: 0.8.0 + */ +GDataYouTubeVideo * +gdata_youtube_service_finish_video_upload (GDataYouTubeService *self, GDataUploadStream *upload_stream, GError **error) +{ + const gchar *response_body; + gssize response_length; + + g_return_val_if_fail (GDATA_IS_YOUTUBE_SERVICE (self), NULL); + g_return_val_if_fail (GDATA_IS_UPLOAD_STREAM (upload_stream), NULL); + g_return_val_if_fail (error == NULL || *error == NULL, NULL); + + /* Get the response from the server */ + response_body = gdata_upload_stream_get_response (upload_stream, &response_length); + if (response_body == NULL || response_length == 0) + return NULL; + + /* Parse the response to produce a GDataYouTubeVideo */ + return GDATA_YOUTUBE_VIDEO (gdata_parsable_new_from_json (GDATA_TYPE_YOUTUBE_VIDEO, + response_body, + (gint) response_length, + error)); +} + +/** + * gdata_youtube_service_get_developer_key: + * @self: a #GDataYouTubeService + * + * Gets the #GDataYouTubeService:developer-key property from the #GDataYouTubeService. + * + * Return value: the developer key property + */ +const gchar * +gdata_youtube_service_get_developer_key (GDataYouTubeService *self) +{ + g_return_val_if_fail (GDATA_IS_YOUTUBE_SERVICE (self), NULL); + return self->priv->developer_key; +} + +/** + * gdata_youtube_service_get_categories: + * @self: a #GDataYouTubeService + * @cancellable: (allow-none): a #GCancellable, or %NULL + * @error: a #GError, or %NULL + * + * Gets a list of the categories currently in use on YouTube. The returned #GDataAPPCategories contains a list of #GDataYouTubeCategorys which + * enumerate the current YouTube categories. + * + * The category labels (#GDataCategory:label) are localised based on the value of #GDataService:locale. + * + * Return value: (transfer full): a #GDataAPPCategories, or %NULL; unref with g_object_unref() + * + * Since: 0.7.0 + */ +GDataAPPCategories * +gdata_youtube_service_get_categories (GDataYouTubeService *self, GCancellable *cancellable, GError **error) +{ + const gchar *locale; + gchar *uri; + SoupMessage *message; + GDataAPPCategories *categories; + + g_return_val_if_fail (GDATA_IS_YOUTUBE_SERVICE (self), NULL); + g_return_val_if_fail (cancellable == NULL || G_IS_CANCELLABLE (cancellable), NULL); + g_return_val_if_fail (error == NULL || *error == NULL, NULL); + + /* Download the category list. Note that this is (service) + * locale-dependent, and a locale must always be specified. */ + locale = gdata_service_get_locale (GDATA_SERVICE (self)); + if (locale == NULL) { + locale = "US"; + } + + uri = _gdata_service_build_uri ("https://www.googleapis.com/youtube/v3/videoCategories" + "?part=snippet" + "®ionCode=%s", + locale); + message = _gdata_service_query (GDATA_SERVICE (self), + get_youtube_authorization_domain (), + uri, NULL, cancellable, error); + g_free (uri); + + if (message == NULL) + return NULL; + + g_assert (message->response_body->data != NULL); + categories = GDATA_APP_CATEGORIES (_gdata_parsable_new_from_json (GDATA_TYPE_APP_CATEGORIES, + message->response_body->data, + message->response_body->length, + GSIZE_TO_POINTER (GDATA_TYPE_YOUTUBE_CATEGORY), + error)); + g_object_unref (message); + + return categories; +} + +static void +get_categories_thread (GTask *task, gpointer source_object, gpointer task_data, GCancellable *cancellable) +{ + GDataYouTubeService *service = GDATA_YOUTUBE_SERVICE (source_object); + g_autoptr(GDataAPPCategories) categories = NULL; + g_autoptr(GError) error = NULL; + + /* Get the categories and return */ + categories = gdata_youtube_service_get_categories (service, cancellable, &error); + if (error != NULL) + g_task_return_error (task, g_steal_pointer (&error)); + else + g_task_return_pointer (task, g_steal_pointer (&categories), g_object_unref); +} + +/** + * gdata_youtube_service_get_categories_async: + * @self: a #GDataYouTubeService + * @cancellable: (allow-none): optional #GCancellable object, or %NULL + * @callback: a #GAsyncReadyCallback to call when the request is finished + * @user_data: (closure): data to pass to the @callback function + * + * Gets a list of the categories currently in use on YouTube. @self is reffed when this function is called, so can safely be unreffed after this + * function returns. + * + * For more details, see gdata_youtube_service_get_categories(), which is the synchronous version of this function. + * + * When the operation is finished, @callback will be called. You can then call gdata_youtube_service_get_categories_finish() to get the results of the + * operation. + * + * Since: 0.7.0 + */ +void +gdata_youtube_service_get_categories_async (GDataYouTubeService *self, GCancellable *cancellable, GAsyncReadyCallback callback, gpointer user_data) +{ + g_autoptr(GTask) task = NULL; + + g_return_if_fail (GDATA_IS_YOUTUBE_SERVICE (self)); + g_return_if_fail (cancellable == NULL || G_IS_CANCELLABLE (cancellable)); + g_return_if_fail (callback != NULL); + + task = g_task_new (self, cancellable, callback, user_data); + g_task_set_source_tag (task, gdata_youtube_service_get_categories_async); + g_task_run_in_thread (task, get_categories_thread); +} + +/** + * gdata_youtube_service_get_categories_finish: + * @self: a #GDataYouTubeService + * @async_result: a #GAsyncResult + * @error: a #GError, or %NULL + * + * Finishes an asynchronous request for a list of categories on YouTube, as started with gdata_youtube_service_get_categories_async(). + * + * Return value: (transfer full): a #GDataAPPCategories, or %NULL; unref with g_object_unref() + * + * Since: 0.7.0 + */ +GDataAPPCategories * +gdata_youtube_service_get_categories_finish (GDataYouTubeService *self, GAsyncResult *async_result, GError **error) +{ + g_return_val_if_fail (GDATA_IS_YOUTUBE_SERVICE (self), NULL); + g_return_val_if_fail (G_IS_ASYNC_RESULT (async_result), NULL); + g_return_val_if_fail (error == NULL || *error == NULL, NULL); + g_return_val_if_fail (g_task_is_valid (async_result, self), NULL); + g_return_val_if_fail (g_async_result_is_tagged (async_result, gdata_youtube_service_get_categories_async), NULL); + + return g_task_propagate_pointer (G_TASK (async_result), error); +} diff --git a/gdata/services/youtube/gdata-youtube-service.h b/gdata/services/youtube/gdata-youtube-service.h new file mode 100644 index 0000000..7471067 --- /dev/null +++ b/gdata/services/youtube/gdata-youtube-service.h @@ -0,0 +1,201 @@ +/* -*- Mode: C; indent-tabs-mode: t; c-basic-offset: 8; tab-width: 8 -*- */ +/* + * GData Client + * Copyright (C) Philip Withnall 2008-2009, 2015 + * + * GData Client is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * GData Client is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with GData Client. If not, see . + */ + +#ifndef GDATA_YOUTUBE_SERVICE_H +#define GDATA_YOUTUBE_SERVICE_H + +#include +#include +#include + +#include +#include +#include +#include + +G_BEGIN_DECLS + +/** + * GDataYouTubeStandardFeedType: + * @GDATA_YOUTUBE_TOP_RATED_FEED: This feed contains the most highly rated + * YouTube videos. Deprecated: 0.17.0: Google no longer supports this feed + * type, and it will return results equivalent to + * %GDATA_YOUTUBE_MOST_POPULAR_FEED. + * @GDATA_YOUTUBE_TOP_FAVORITES_FEED: This feed contains videos most frequently + * flagged as favorite videos. Deprecated: 0.17.0: Google no longer + * supports this feed type, and it will return results equivalent to + * %GDATA_YOUTUBE_MOST_POPULAR_FEED. + * @GDATA_YOUTUBE_MOST_VIEWED_FEED: This feed contains the most frequently + * watched YouTube videos. Deprecated: 0.17.0: Google no longer supports + * this feed type, and it will return results equivalent to + * %GDATA_YOUTUBE_MOST_POPULAR_FEED. + * @GDATA_YOUTUBE_MOST_POPULAR_FEED: This feed contains the most popular YouTube + * videos, selected using an algorithm that combines many different signals to + * determine overall popularity. As of version 0.17.0, this is the only + * supported feed type. + * @GDATA_YOUTUBE_MOST_RECENT_FEED: This feed contains the videos most recently + * submitted to YouTube. Deprecated: 0.17.0: Google no longer supports + * this feed type, and it will return results equivalent to + * %GDATA_YOUTUBE_MOST_POPULAR_FEED. + * @GDATA_YOUTUBE_MOST_DISCUSSED_FEED: This feed contains the YouTube videos + * that have received the most comments. Deprecated: 0.17.0: Google no + * longer supports this feed type, and it will return results equivalent to + * %GDATA_YOUTUBE_MOST_POPULAR_FEED. + * @GDATA_YOUTUBE_MOST_LINKED_FEED: This feed contains the YouTube videos that + * receive the most links from other websites. Deprecated: 0.17.0: Google + * no longer supports this feed type, and it will return results equivalent to + * %GDATA_YOUTUBE_MOST_POPULAR_FEED. + * @GDATA_YOUTUBE_MOST_RESPONDED_FEED: This feed contains YouTube videos that + * receive the most video responses. Deprecated: 0.17.0: Google no longer + * supports this feed type, and it will return results equivalent to + * %GDATA_YOUTUBE_MOST_POPULAR_FEED. + * @GDATA_YOUTUBE_RECENTLY_FEATURED_FEED: This feed contains videos recently + * featured on the YouTube home page or featured videos tab. Deprecated: + * 0.17.0: Google no longer supports this feed type, and it will return + * results equivalent to %GDATA_YOUTUBE_MOST_POPULAR_FEED. + * @GDATA_YOUTUBE_WATCH_ON_MOBILE_FEED: This feed contains videos suitable for + * playback on mobile devices. Deprecated: 0.17.0: Google no longer + * supports this feed type, and it will return results equivalent to + * %GDATA_YOUTUBE_MOST_POPULAR_FEED. + * + * Standard feed types for standard feed queries with + * gdata_youtube_service_query_standard_feed(). For more information, see the + * online + * documentation. + */ +typedef enum { + GDATA_YOUTUBE_TOP_RATED_FEED, + GDATA_YOUTUBE_TOP_FAVORITES_FEED, + GDATA_YOUTUBE_MOST_VIEWED_FEED, + GDATA_YOUTUBE_MOST_POPULAR_FEED, + GDATA_YOUTUBE_MOST_RECENT_FEED, + GDATA_YOUTUBE_MOST_DISCUSSED_FEED, + GDATA_YOUTUBE_MOST_LINKED_FEED, + GDATA_YOUTUBE_MOST_RESPONDED_FEED, + GDATA_YOUTUBE_RECENTLY_FEATURED_FEED, + GDATA_YOUTUBE_WATCH_ON_MOBILE_FEED +} GDataYouTubeStandardFeedType; + +/** + * GDataYouTubeServiceError: + * @GDATA_YOUTUBE_SERVICE_ERROR_API_QUOTA_EXCEEDED: the API request quota for this developer account has been exceeded + * @GDATA_YOUTUBE_SERVICE_ERROR_ENTRY_QUOTA_EXCEEDED: the entry (e.g. video) quota for this user account has been exceeded + * @GDATA_YOUTUBE_SERVICE_ERROR_CHANNEL_REQUIRED: the currently authenticated user doesn't have a YouTube channel, but the current action requires one; + * if this error is received, inform the user that they need a YouTube channel, and provide a link to + * https://www.youtube.com/create_channel + * + * Error codes for #GDataYouTubeService operations. + */ +typedef enum { + GDATA_YOUTUBE_SERVICE_ERROR_API_QUOTA_EXCEEDED, + GDATA_YOUTUBE_SERVICE_ERROR_ENTRY_QUOTA_EXCEEDED, + GDATA_YOUTUBE_SERVICE_ERROR_CHANNEL_REQUIRED, +} GDataYouTubeServiceError; + +#define GDATA_TYPE_YOUTUBE_SERVICE (gdata_youtube_service_get_type ()) +#define GDATA_YOUTUBE_SERVICE(o) (G_TYPE_CHECK_INSTANCE_CAST ((o), GDATA_TYPE_YOUTUBE_SERVICE, GDataYouTubeService)) +#define GDATA_YOUTUBE_SERVICE_CLASS(k) (G_TYPE_CHECK_CLASS_CAST((k), GDATA_TYPE_YOUTUBE_SERVICE, GDataYouTubeServiceClass)) +#define GDATA_IS_YOUTUBE_SERVICE(o) (G_TYPE_CHECK_INSTANCE_TYPE ((o), GDATA_TYPE_YOUTUBE_SERVICE)) +#define GDATA_IS_YOUTUBE_SERVICE_CLASS(k) (G_TYPE_CHECK_CLASS_TYPE ((k), GDATA_TYPE_YOUTUBE_SERVICE)) +#define GDATA_YOUTUBE_SERVICE_GET_CLASS(o) (G_TYPE_INSTANCE_GET_CLASS ((o), GDATA_TYPE_YOUTUBE_SERVICE, GDataYouTubeServiceClass)) + +#define GDATA_YOUTUBE_SERVICE_ERROR gdata_youtube_service_error_quark () + +typedef struct _GDataYouTubeServicePrivate GDataYouTubeServicePrivate; + +/** + * GDataYouTubeService: + * + * All the fields in the #GDataYouTubeService structure are private and should never be accessed directly. + */ +typedef struct { + GDataService parent; + GDataYouTubeServicePrivate *priv; +} GDataYouTubeService; + +/** + * GDataYouTubeServiceClass: + * + * All the fields in the #GDataYouTubeServiceClass structure are private and should never be accessed directly. + */ +typedef struct { + /*< private >*/ + GDataServiceClass parent; + + /*< private >*/ + /* Padding for future expansion */ + void (*_g_reserved0) (void); + void (*_g_reserved1) (void); + void (*_g_reserved2) (void); + void (*_g_reserved3) (void); + void (*_g_reserved4) (void); + void (*_g_reserved5) (void); +} GDataYouTubeServiceClass; + +GType gdata_youtube_service_get_type (void) G_GNUC_CONST; +GQuark gdata_youtube_service_error_quark (void) G_GNUC_CONST; + +GDataYouTubeService *gdata_youtube_service_new (const gchar *developer_key, GDataAuthorizer *authorizer) G_GNUC_WARN_UNUSED_RESULT G_GNUC_MALLOC; + +GDataAuthorizationDomain *gdata_youtube_service_get_primary_authorization_domain (void) G_GNUC_CONST; + +GDataFeed *gdata_youtube_service_query_standard_feed (GDataYouTubeService *self, GDataYouTubeStandardFeedType feed_type, GDataQuery *query, + GCancellable *cancellable, + GDataQueryProgressCallback progress_callback, gpointer progress_user_data, + GError **error) G_GNUC_WARN_UNUSED_RESULT G_GNUC_MALLOC; +void gdata_youtube_service_query_standard_feed_async (GDataYouTubeService *self, GDataYouTubeStandardFeedType feed_type, GDataQuery *query, + GCancellable *cancellable, + GDataQueryProgressCallback progress_callback, gpointer progress_user_data, + GDestroyNotify destroy_progress_user_data, + GAsyncReadyCallback callback, gpointer user_data); + +GDataFeed *gdata_youtube_service_query_videos (GDataYouTubeService *self, GDataQuery *query, + GCancellable *cancellable, GDataQueryProgressCallback progress_callback, gpointer progress_user_data, + GError **error) G_GNUC_WARN_UNUSED_RESULT G_GNUC_MALLOC; +void gdata_youtube_service_query_videos_async (GDataYouTubeService *self, GDataQuery *query, + GCancellable *cancellable, GDataQueryProgressCallback progress_callback, gpointer progress_user_data, + GDestroyNotify destroy_progress_user_data, + GAsyncReadyCallback callback, gpointer user_data); + +GDataFeed *gdata_youtube_service_query_related (GDataYouTubeService *self, GDataYouTubeVideo *video, GDataQuery *query, + GCancellable *cancellable, GDataQueryProgressCallback progress_callback, gpointer progress_user_data, + GError **error) G_GNUC_WARN_UNUSED_RESULT G_GNUC_MALLOC; +void gdata_youtube_service_query_related_async (GDataYouTubeService *self, GDataYouTubeVideo *video, GDataQuery *query, + GCancellable *cancellable, GDataQueryProgressCallback progress_callback, gpointer progress_user_data, + GDestroyNotify destroy_progress_user_data, + GAsyncReadyCallback callback, gpointer user_data); + +GDataUploadStream *gdata_youtube_service_upload_video (GDataYouTubeService *self, GDataYouTubeVideo *video, const gchar *slug, + const gchar *content_type, GCancellable *cancellable, + GError **error) G_GNUC_WARN_UNUSED_RESULT G_GNUC_MALLOC; +GDataYouTubeVideo *gdata_youtube_service_finish_video_upload (GDataYouTubeService *self, GDataUploadStream *upload_stream, + GError **error) G_GNUC_WARN_UNUSED_RESULT G_GNUC_MALLOC; + +const gchar *gdata_youtube_service_get_developer_key (GDataYouTubeService *self) G_GNUC_PURE; + +GDataAPPCategories *gdata_youtube_service_get_categories (GDataYouTubeService *self, GCancellable *cancellable, + GError **error) G_GNUC_WARN_UNUSED_RESULT G_GNUC_MALLOC; +void gdata_youtube_service_get_categories_async (GDataYouTubeService *self, GCancellable *cancellable, GAsyncReadyCallback callback, + gpointer user_data); +GDataAPPCategories *gdata_youtube_service_get_categories_finish (GDataYouTubeService *self, GAsyncResult *async_result, + GError **error) G_GNUC_WARN_UNUSED_RESULT G_GNUC_MALLOC; + +G_END_DECLS + +#endif /* !GDATA_YOUTUBE_SERVICE_H */ diff --git a/gdata/services/youtube/gdata-youtube-state.c b/gdata/services/youtube/gdata-youtube-state.c new file mode 100644 index 0000000..be1fa0f --- /dev/null +++ b/gdata/services/youtube/gdata-youtube-state.c @@ -0,0 +1,285 @@ +/* -*- Mode: C; indent-tabs-mode: t; c-basic-offset: 8; tab-width: 8 -*- */ +/* + * GData Client + * Copyright (C) Philip Withnall 2009–2010, 2015 + * + * GData Client is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * GData Client is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with GData Client. If not, see . + */ + +/** + * SECTION:gdata-youtube-state + * @short_description: YouTube state element + * @stability: Stable + * @include: gdata/services/youtube/gdata-youtube-state.h + * + * #GDataYouTubeState represents a "state" element from the + * YouTube namespace. + * + * Since: 0.4.0 + */ + +#include + +#include "gdata-youtube-state.h" +#include "gdata-parsable.h" + +static void gdata_youtube_state_finalize (GObject *object); +static void gdata_youtube_state_get_property (GObject *object, guint property_id, GValue *value, GParamSpec *pspec); +static void +gdata_youtube_state_set_property (GObject *object, + guint property_id, + const GValue *value, + GParamSpec *pspec); + +struct _GDataYouTubeStatePrivate { + gchar *name; + gchar *reason_code; + gchar *help_uri; + gchar *message; +}; + +enum { + PROP_NAME = 1, + PROP_REASON_CODE, + PROP_HELP_URI, + PROP_MESSAGE +}; + +G_DEFINE_TYPE (GDataYouTubeState, gdata_youtube_state, GDATA_TYPE_PARSABLE) + +static void +gdata_youtube_state_class_init (GDataYouTubeStateClass *klass) +{ + GObjectClass *gobject_class = G_OBJECT_CLASS (klass); + + g_type_class_add_private (klass, sizeof (GDataYouTubeStatePrivate)); + + gobject_class->get_property = gdata_youtube_state_get_property; + gobject_class->set_property = gdata_youtube_state_set_property; + gobject_class->finalize = gdata_youtube_state_finalize; + + /** + * GDataYouTubeState:name: + * + * The name of the status of the unpublished video. Valid values are: "processing", "restricted", "deleted", "rejected" and "failed". + * + * For more information, see the + * online documentation. + * + * Since: 0.4.0 + */ + g_object_class_install_property (gobject_class, PROP_NAME, + g_param_spec_string ("name", + "Name", "The name of the status of the unpublished video.", + NULL, + G_PARAM_CONSTRUCT_ONLY | + G_PARAM_READWRITE | + G_PARAM_STATIC_STRINGS)); + + /** + * GDataYouTubeState:reason-code: + * + * The reason code explaining why the video failed to upload. + * + * For more information, see the + * online documentation. + * + * Since: 0.4.0 + */ + g_object_class_install_property (gobject_class, PROP_REASON_CODE, + g_param_spec_string ("reason-code", + "Reason code", "The reason code explaining why the video failed to upload.", + NULL, + G_PARAM_CONSTRUCT_ONLY | + G_PARAM_READWRITE | + G_PARAM_STATIC_STRINGS)); + + /** + * GDataYouTubeState:help-uri: + * + * A URI for a YouTube Help Center page that may help the developer or the video owner to diagnose + * the reason that an upload failed or was rejected. + * + * For more information, see the + * online documentation. + * + * Since: 0.4.0 + */ + g_object_class_install_property (gobject_class, PROP_HELP_URI, + g_param_spec_string ("help-uri", + "Help URI", "A URI for a YouTube Help Center page.", + NULL, + G_PARAM_CONSTRUCT_ONLY | + G_PARAM_READWRITE | + G_PARAM_STATIC_STRINGS)); + + /** + * GDataYouTubeState:message: + * + * A human-readable description of why the video failed to upload. + * + * For more information, see the + * online documentation. + * + * Since: 0.4.0 + */ + g_object_class_install_property (gobject_class, PROP_MESSAGE, + g_param_spec_string ("message", + "Message", "A human-readable description of why the video failed to upload.", + NULL, + G_PARAM_CONSTRUCT_ONLY | + G_PARAM_READWRITE | + G_PARAM_STATIC_STRINGS)); +} + +static void +gdata_youtube_state_init (GDataYouTubeState *self) +{ + self->priv = G_TYPE_INSTANCE_GET_PRIVATE (self, GDATA_TYPE_YOUTUBE_STATE, GDataYouTubeStatePrivate); +} + +static void +gdata_youtube_state_finalize (GObject *object) +{ + GDataYouTubeStatePrivate *priv = GDATA_YOUTUBE_STATE (object)->priv; + + g_free (priv->name); + g_free (priv->reason_code); + g_free (priv->help_uri); + g_free (priv->message); + + /* Chain up to the parent class */ + G_OBJECT_CLASS (gdata_youtube_state_parent_class)->finalize (object); +} + +static void +gdata_youtube_state_get_property (GObject *object, guint property_id, GValue *value, GParamSpec *pspec) +{ + GDataYouTubeStatePrivate *priv = GDATA_YOUTUBE_STATE (object)->priv; + + switch (property_id) { + case PROP_NAME: + g_value_set_string (value, priv->name); + break; + case PROP_REASON_CODE: + g_value_set_string (value, priv->reason_code); + break; + case PROP_HELP_URI: + g_value_set_string (value, priv->help_uri); + break; + case PROP_MESSAGE: + g_value_set_string (value, priv->message); + break; + default: + /* We don't have any other property... */ + G_OBJECT_WARN_INVALID_PROPERTY_ID (object, property_id, pspec); + break; + } +} + +static void +gdata_youtube_state_set_property (GObject *object, + guint property_id, + const GValue *value, + GParamSpec *pspec) +{ + GDataYouTubeStatePrivate *priv = GDATA_YOUTUBE_STATE (object)->priv; + + switch (property_id) { + case PROP_NAME: + priv->name = g_value_dup_string (value); + break; + case PROP_REASON_CODE: + priv->reason_code = g_value_dup_string (value); + break; + case PROP_HELP_URI: + priv->help_uri = g_value_dup_string (value); + break; + case PROP_MESSAGE: + priv->message = g_value_dup_string (value); + break; + default: + /* We don't have any other property... */ + G_OBJECT_WARN_INVALID_PROPERTY_ID (object, property_id, pspec); + break; + } +} + +/** + * gdata_youtube_state_get_name: + * @self: a #GDataYouTubeState + * + * Gets the #GDataYouTubeState:name property. + * + * Return value: the status name + * + * Since: 0.4.0 + */ +const gchar * +gdata_youtube_state_get_name (GDataYouTubeState *self) +{ + g_return_val_if_fail (GDATA_IS_YOUTUBE_STATE (self), NULL); + return self->priv->name; +} + +/** + * gdata_youtube_state_get_reason_code: + * @self: a #GDataYouTubeState + * + * Gets the #GDataYouTubeState:reason-code property. + * + * Return value: the status reason code, or %NULL + * + * Since: 0.4.0 + */ +const gchar * +gdata_youtube_state_get_reason_code (GDataYouTubeState *self) +{ + g_return_val_if_fail (GDATA_IS_YOUTUBE_STATE (self), NULL); + return self->priv->reason_code; +} + +/** + * gdata_youtube_state_get_help_uri: + * @self: a #GDataYouTubeState + * + * Gets the #GDataYouTubeState:help-uri property. + * + * Return value: the help URI, or %NULL + * + * Since: 0.4.0 + */ +const gchar * +gdata_youtube_state_get_help_uri (GDataYouTubeState *self) +{ + g_return_val_if_fail (GDATA_IS_YOUTUBE_STATE (self), NULL); + return self->priv->help_uri; +} + +/** + * gdata_youtube_state_get_message: + * @self: a #GDataYouTubeState + * + * Gets the #GDataYouTubeState:message property. + * + * Return value: the status message, or %NULL + * + * Since: 0.4.0 + */ +const gchar * +gdata_youtube_state_get_message (GDataYouTubeState *self) +{ + g_return_val_if_fail (GDATA_IS_YOUTUBE_STATE (self), NULL); + return self->priv->message; +} diff --git a/gdata/services/youtube/gdata-youtube-state.h b/gdata/services/youtube/gdata-youtube-state.h new file mode 100644 index 0000000..a820e24 --- /dev/null +++ b/gdata/services/youtube/gdata-youtube-state.h @@ -0,0 +1,75 @@ +/* -*- Mode: C; indent-tabs-mode: t; c-basic-offset: 8; tab-width: 8 -*- */ +/* + * GData Client + * Copyright (C) Philip Withnall 2009 + * + * GData Client is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * GData Client is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with GData Client. If not, see . + */ + +#ifndef GDATA_YOUTUBE_STATE_H +#define GDATA_YOUTUBE_STATE_H + +#include +#include + +#include + +G_BEGIN_DECLS + +#define GDATA_TYPE_YOUTUBE_STATE (gdata_youtube_state_get_type ()) +#define GDATA_YOUTUBE_STATE(o) (G_TYPE_CHECK_INSTANCE_CAST ((o), GDATA_TYPE_YOUTUBE_STATE, GDataYouTubeState)) +#define GDATA_YOUTUBE_STATE_CLASS(k) (G_TYPE_CHECK_CLASS_CAST((k), GDATA_TYPE_YOUTUBE_STATE, GDataYouTubeStateClass)) +#define GDATA_IS_YOUTUBE_STATE(o) (G_TYPE_CHECK_INSTANCE_TYPE ((o), GDATA_TYPE_YOUTUBE_STATE)) +#define GDATA_IS_YOUTUBE_STATE_CLASS(k) (G_TYPE_CHECK_CLASS_TYPE ((k), GDATA_TYPE_YOUTUBE_STATE)) +#define GDATA_YOUTUBE_STATE_GET_CLASS(o) (G_TYPE_INSTANCE_GET_CLASS ((o), GDATA_TYPE_YOUTUBE_STATE, GDataYouTubeStateClass)) + +typedef struct _GDataYouTubeStatePrivate GDataYouTubeStatePrivate; + +/** + * GDataYouTubeState: + * + * All the fields in the #GDataYouTubeState structure are private and should never be accessed directly. + */ +typedef struct { + GDataParsable parent; + GDataYouTubeStatePrivate *priv; +} GDataYouTubeState; + +/** + * GDataYouTubeStateClass: + * + * All the fields in the #GDataYouTubeStateClass structure are private and should never be accessed directly. + * + * Since: 0.4.0 + */ +typedef struct { + /*< private >*/ + GDataParsableClass parent; + + /*< private >*/ + /* Padding for future expansion */ + void (*_g_reserved0) (void); + void (*_g_reserved1) (void); +} GDataYouTubeStateClass; + +GType gdata_youtube_state_get_type (void) G_GNUC_CONST; + +const gchar *gdata_youtube_state_get_name (GDataYouTubeState *self) G_GNUC_PURE; +const gchar *gdata_youtube_state_get_reason_code (GDataYouTubeState *self) G_GNUC_PURE; +const gchar *gdata_youtube_state_get_help_uri (GDataYouTubeState *self) G_GNUC_PURE; +const gchar *gdata_youtube_state_get_message (GDataYouTubeState *self) G_GNUC_PURE; + +G_END_DECLS + +#endif /* !GDATA_YOUTUBE_STATE_H */ diff --git a/gdata/services/youtube/gdata-youtube-video.c b/gdata/services/youtube/gdata-youtube-video.c new file mode 100644 index 0000000..f44272d --- /dev/null +++ b/gdata/services/youtube/gdata-youtube-video.c @@ -0,0 +1,2476 @@ +/* -*- Mode: C; indent-tabs-mode: t; c-basic-offset: 8; tab-width: 8 -*- */ +/* + * GData Client + * Copyright (C) Philip Withnall 2008–2010, 2015 + * + * GData Client is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * GData Client is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with GData Client. If not, see . + */ + +/** + * SECTION:gdata-youtube-video + * @short_description: GData YouTube video object + * @stability: Stable + * @include: gdata/services/youtube/gdata-youtube-video.h + * + * #GDataYouTubeVideo is a subclass of #GDataEntry to represent a single video on YouTube, either when uploading or querying. + * + * #GDataYouTubeVideo implements #GDataCommentable, allowing comments on videos + * to be queried and added. + * + * For more details of YouTube’s GData API, see the + * + * online documentation. + * + * + * Getting Basic Video Data + * + * GDataYouTubeVideo *video; + * const gchar *video_id, *title, *player_uri, *description, *video_uri = NULL; + * gint64 updated, published; + * GDataMediaContent *content; + * GList *thumbnails; + * + * video = gdata_youtube_service_query_single_video (service, NULL, "R-9gzmQHoe0", NULL, NULL); + * + * video_id = gdata_entry_get_id (GDATA_ENTRY (video)); /* e.g. "R-9gzmQHoe0" */ + * title = gdata_entry_get_title (GDATA_ENTRY (video)); /* e.g. "Korpiklaani Vodka (official video 2009)" */ + * player_uri = gdata_youtube_video_get_player_uri (video); /* e.g. "http://www.youtube.com/watch?v=ZTUVgYoeN_b" */ + * description = gdata_youtube_video_get_description (video); /* e.g. "Vodka is the first single from the album..." */ + * published = gdata_entry_get_published (GDATA_ENTRY (video)); /* Date and time the video was originally published */ + * updated = gdata_entry_get_updated (GDATA_ENTRY (video)); /* When the video was most recently updated by the author */ + * + * /* Get a list of GDataMediaThumbnails for the video */ + * for (thumbnails = gdata_youtube_video_get_thumbnails (video); thumbnails != NULL; thumbnails = thumbnails->next) + * download_and_do_something_with_thumbnail (gdata_media_thumbnail_get_uri (thumbnail)); + * + * g_object_unref (video); + * + * + */ + +#include +#include +#include +#include +#include + +#include "gdata-youtube-video.h" +#include "gdata-private.h" +#include "gdata-service.h" +#include "gdata-parser.h" +#include "media/gdata-media-category.h" +#include "media/gdata-media-thumbnail.h" +#include "gdata-types.h" +#include "gdata-youtube-enums.h" +#include "gdata-commentable.h" +#include "gdata-youtube-comment.h" +#include "gdata-youtube-service.h" + +static void gdata_youtube_video_dispose (GObject *object); +static void gdata_youtube_video_finalize (GObject *object); +static void gdata_youtube_video_get_property (GObject *object, guint property_id, GValue *value, GParamSpec *pspec); +static void gdata_youtube_video_set_property (GObject *object, guint property_id, const GValue *value, GParamSpec *pspec); +static gboolean parse_json (GDataParsable *parsable, JsonReader *reader, gpointer user_data, GError **error); +static gboolean post_parse_json (GDataParsable *parsable, gpointer user_data, GError **error); +static void get_json (GDataParsable *parsable, JsonBuilder *builder); +static const gchar *get_content_type (void); +static gchar *get_entry_uri (const gchar *id) G_GNUC_WARN_UNUSED_RESULT; +static void gdata_youtube_video_commentable_init (GDataCommentableInterface *iface); +static GDataAuthorizationDomain *get_authorization_domain (GDataCommentable *self) G_GNUC_CONST; +static gchar *get_query_comments_uri (GDataCommentable *self) G_GNUC_MALLOC G_GNUC_WARN_UNUSED_RESULT; +static gchar *get_insert_comment_uri (GDataCommentable *self, GDataComment *comment_) G_GNUC_MALLOC G_GNUC_WARN_UNUSED_RESULT; +static gboolean is_comment_deletable (GDataCommentable *self, GDataComment *comment_); + +struct _GDataYouTubeVideoPrivate { + guint view_count; + guint favorite_count; + gchar *location; + GHashTable/**/ *access_controls; + + /* gd:rating attributes */ + struct { + guint min; + guint max; + guint count; + gdouble average; + } rating; + + gchar **keywords; + gchar *player_uri; + gchar **region_restriction_allowed; + gchar **region_restriction_blocked; + GHashTable *content_ratings; /* owned string → owned string */ + GList *thumbnails; /* GDataMediaThumbnail */ + GDataMediaCategory *category; + guint duration; + gboolean is_private; + gchar *channel_id; /* owned */ + + /* Location. */ + gdouble latitude; + gdouble longitude; + + /* Other properties */ + gchar *rejection_reason; + gchar *processing_status; + gchar *upload_status; + gchar *failure_reason; + GDataYouTubeState *upload_state; /* owned */ + + gint64 recorded; + + /* State for parse_json(). */ + gboolean parsing_in_video_list_response; +}; + +enum { + PROP_VIEW_COUNT = 1, + PROP_FAVORITE_COUNT, + PROP_LOCATION, + PROP_MIN_RATING, + PROP_MAX_RATING, + PROP_RATING_COUNT, + PROP_AVERAGE_RATING, + PROP_KEYWORDS, + PROP_PLAYER_URI, + PROP_CATEGORY, + PROP_CREDIT, + PROP_DESCRIPTION, + PROP_DURATION, + PROP_IS_PRIVATE, + PROP_UPLOADED, + PROP_VIDEO_ID, + PROP_IS_DRAFT, + PROP_STATE, + PROP_RECORDED, + PROP_ASPECT_RATIO, + PROP_LATITUDE, + PROP_LONGITUDE +}; + +G_DEFINE_TYPE_WITH_CODE (GDataYouTubeVideo, gdata_youtube_video, GDATA_TYPE_ENTRY, + G_IMPLEMENT_INTERFACE (GDATA_TYPE_COMMENTABLE, gdata_youtube_video_commentable_init)) + +static void +gdata_youtube_video_class_init (GDataYouTubeVideoClass *klass) +{ + GObjectClass *gobject_class = G_OBJECT_CLASS (klass); + GDataParsableClass *parsable_class = GDATA_PARSABLE_CLASS (klass); + GDataEntryClass *entry_class = GDATA_ENTRY_CLASS (klass); + + g_type_class_add_private (klass, sizeof (GDataYouTubeVideoPrivate)); + + gobject_class->get_property = gdata_youtube_video_get_property; + gobject_class->set_property = gdata_youtube_video_set_property; + gobject_class->dispose = gdata_youtube_video_dispose; + gobject_class->finalize = gdata_youtube_video_finalize; + + parsable_class->parse_json = parse_json; + parsable_class->post_parse_json = post_parse_json; + parsable_class->get_json = get_json; + parsable_class->get_content_type = get_content_type; + + entry_class->get_entry_uri = get_entry_uri; + entry_class->kind_term = "youtube#video"; /* also: youtube#searchResult */ + + /** + * GDataYouTubeVideo:view-count: + * + * The number of times the video has been viewed. + * + * For more information, see the online documentation. + */ + g_object_class_install_property (gobject_class, PROP_VIEW_COUNT, + g_param_spec_uint ("view-count", + "View count", "The number of times the video has been viewed.", + 0, G_MAXUINT, 0, + G_PARAM_READABLE | G_PARAM_STATIC_STRINGS)); + + /** + * GDataYouTubeVideo:favorite-count: + * + * The number of users who have added the video to their favorites. + * + * For more information, see the online documentation. + */ + g_object_class_install_property (gobject_class, PROP_FAVORITE_COUNT, + g_param_spec_uint ("favorite-count", + "Favorite count", "The number of users who have added the video to their favorites.", + 0, G_MAXUINT, 0, + G_PARAM_READABLE | G_PARAM_STATIC_STRINGS)); + + /** + * GDataYouTubeVideo:location: + * + * Descriptive text about the location where the video was taken. + * + * For more information, see the online documentation. + */ + g_object_class_install_property (gobject_class, PROP_LOCATION, + g_param_spec_string ("location", + "Location", "Descriptive text about the location where the video was taken.", + NULL, + G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)); + + /** + * GDataYouTubeVideo:min-rating: + * + * The minimum allowed rating for the video. + * + * For more information, see the online documentation. + */ + g_object_class_install_property (gobject_class, PROP_MIN_RATING, + g_param_spec_uint ("min-rating", + "Minimum rating", "The minimum allowed rating for the video.", + 0, G_MAXUINT, 1, /* defaults to 1 */ + G_PARAM_READABLE | G_PARAM_STATIC_STRINGS)); + + /** + * GDataYouTubeVideo:max-rating: + * + * The maximum allowed rating for the video. + * + * For more information, see the online documentation. + */ + g_object_class_install_property (gobject_class, PROP_MAX_RATING, + g_param_spec_uint ("max-rating", + "Maximum rating", "The maximum allowed rating for the video.", + 0, G_MAXUINT, 5, /* defaults to 5 */ + G_PARAM_READABLE | G_PARAM_STATIC_STRINGS)); + + /** + * GDataYouTubeVideo:rating-count: + * + * The number of times the video has been rated. + * + * For more information, see the online documentation. + */ + g_object_class_install_property (gobject_class, PROP_RATING_COUNT, + g_param_spec_uint ("rating-count", + "Rating count", "The number of times the video has been rated.", + 0, G_MAXUINT, 0, + G_PARAM_READABLE | G_PARAM_STATIC_STRINGS)); + + /** + * GDataYouTubeVideo:average-rating: + * + * The average rating of the video, over all the ratings it's received. + * + * For more information, see the online documentation. + */ + g_object_class_install_property (gobject_class, PROP_AVERAGE_RATING, + g_param_spec_double ("average-rating", + "Average rating", "The average rating of the video.", + 0.0, G_MAXDOUBLE, 0.0, + G_PARAM_READABLE | G_PARAM_STATIC_STRINGS)); + + /** + * GDataYouTubeVideo:keywords: + * + * A %NULL-terminated array of words associated with the video. + * + * For more information, see the online documentation. + */ + g_object_class_install_property (gobject_class, PROP_KEYWORDS, + g_param_spec_boxed ("keywords", + "Keywords", "A NULL-terminated array of words associated with the video.", + G_TYPE_STRV, + G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)); + + /** + * GDataYouTubeVideo:player-uri: + * + * A URI for a browser-based media player for the full-length video (i.e. the video's page on YouTube). + */ + g_object_class_install_property (gobject_class, PROP_PLAYER_URI, + g_param_spec_string ("player-uri", + "Player URI", "A URI for a browser-based media player for the full-length video.", + NULL, + G_PARAM_READABLE | G_PARAM_STATIC_STRINGS)); + + /** + * GDataYouTubeVideo:category: + * + * Specifies a genre or developer tag that describes the video. + * + * For more information, see the online documentation. + */ + g_object_class_install_property (gobject_class, PROP_CATEGORY, + g_param_spec_object ("category", + "Category", "Specifies a genre or developer tag that describes the video.", + GDATA_TYPE_MEDIA_CATEGORY, + G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)); + + G_GNUC_BEGIN_IGNORE_DEPRECATIONS + + /** + * GDataYouTubeVideo:credit: + * + * Identifies the owner of the video. + * + * Deprecated: 0.17.0: This is no longer supported by Google, and + * will always be %NULL. There is no replacement. + */ + g_object_class_install_property (gobject_class, PROP_CREDIT, + g_param_spec_object ("credit", + "Credit", "Identifies the owner of the video.", + GDATA_TYPE_YOUTUBE_CREDIT, + G_PARAM_READABLE | G_PARAM_STATIC_STRINGS | + G_PARAM_DEPRECATED)); + + G_GNUC_END_IGNORE_DEPRECATIONS + + /** + * GDataYouTubeVideo:description: + * + * A summary or description of the video. + * + * For more information, see the online documentation. + */ + g_object_class_install_property (gobject_class, PROP_DESCRIPTION, + g_param_spec_string ("description", + "Description", "A summary or description of the video.", + NULL, + G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)); + + /** + * GDataYouTubeVideo:duration: + * + * The duration of the video in seconds. + * + * For more information, see the online documentation. + */ + g_object_class_install_property (gobject_class, PROP_DURATION, + g_param_spec_uint ("duration", + "Duration", "The duration of the video in seconds.", + 0, G_MAXINT, 0, + G_PARAM_READABLE | G_PARAM_STATIC_STRINGS)); + + /** + * GDataYouTubeVideo:private: + * + * Indicates whether the video is private, meaning that it will not be publicly visible on YouTube's website. + * + * For more information, see the online documentation. + */ + g_object_class_install_property (gobject_class, PROP_IS_PRIVATE, + g_param_spec_boolean ("is-private", + "Private?", "Indicates whether the video is private.", + FALSE, + G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)); + + /** + * GDataYouTubeVideo:uploaded: + * + * Specifies the time the video was originally uploaded to YouTube. + * + * For more information, see the online documentation. + */ + g_object_class_install_property (gobject_class, PROP_UPLOADED, + g_param_spec_int64 ("uploaded", + "Uploaded", "Specifies the time the video was originally uploaded to YouTube.", + -1, G_MAXINT64, -1, + G_PARAM_READABLE | G_PARAM_STATIC_STRINGS)); + + /** + * GDataYouTubeVideo:video-id: + * + * Specifies a unique ID which YouTube uses to identify the video. For example: qz8EfkS4KK0. + * + * For more information, see the online documentation. + * + * Deprecated: 0.17.0: This is now equal to #GDataEntry:id. + */ + g_object_class_install_property (gobject_class, PROP_VIDEO_ID, + g_param_spec_string ("video-id", + "Video ID", "Specifies a unique ID which YouTube uses to identify the video.", + NULL, + G_PARAM_READABLE | G_PARAM_STATIC_STRINGS | + G_PARAM_DEPRECATED)); + + /** + * GDataYouTubeVideo:is-draft: + * + * Indicates whether the video is in draft, or unpublished, status. + * + * Deprecated: 0.17.0: This is now equal to + * #GDataYouTubeVideo:is-private. + */ + g_object_class_install_property (gobject_class, PROP_IS_DRAFT, + g_param_spec_boolean ("is-draft", + "Draft?", "Indicates whether the video is in draft, or unpublished, status.", + FALSE, + G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS | + G_PARAM_DEPRECATED)); + + /** + * GDataYouTubeVideo:state: + * + * Information describing the state of the video. If this is non-%NULL, the video is not playable. + * It points to a #GDataYouTubeState. + * + * For more information, see the online documentation. + */ + g_object_class_install_property (gobject_class, PROP_STATE, + g_param_spec_object ("state", + "State", "Information describing the state of the video.", + GDATA_TYPE_YOUTUBE_STATE, + G_PARAM_READABLE | G_PARAM_STATIC_STRINGS)); + + /** + * GDataYouTubeVideo:recorded: + * + * Specifies the time the video was originally recorded. + * + * For more information, see the online documentation. + * + * Since: 0.3.0 + */ + g_object_class_install_property (gobject_class, PROP_RECORDED, + g_param_spec_int64 ("recorded", + "Recorded", "Specifies the time the video was originally recorded.", + -1, G_MAXINT64, -1, + G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)); + + /** + * GDataYouTubeVideo:aspect-ratio: + * + * The aspect ratio of the video. A %NULL value means the aspect ratio is unknown (it could still be a widescreen video). A value of + * %GDATA_YOUTUBE_ASPECT_RATIO_WIDESCREEN means the video is definitely widescreen. + * + * Since: 0.4.0 + */ + g_object_class_install_property (gobject_class, PROP_ASPECT_RATIO, + g_param_spec_string ("aspect-ratio", + "Aspect Ratio", "The aspect ratio of the video.", + NULL, + G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)); + + /** + * GDataYouTubeVideo:latitude: + * + * The location as a latitude coordinate associated with this video. Valid latitudes range from -90.0 + * to 90.0 inclusive. Set to a value + * outside this range to unset the location. + * + * For more information, see the + * + * online documentation. + * + * Since: 0.8.0 + */ + g_object_class_install_property (gobject_class, PROP_LATITUDE, + g_param_spec_double ("latitude", + "Latitude", "The location as a latitude coordinate associated with this video.", + G_MINDOUBLE, G_MAXDOUBLE, G_MAXDOUBLE, + G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)); + + /** + * GDataYouTubeVideo:longitude: + * + * The location as a longitude coordinate associated with this video. Valid longitudes range from -180.0 + * to 180.0 inclusive. Set to a value + * outside this range to unset the location. + * + * For more information, see the + * + * online documentation. + * + * Since: 0.8.0 + */ + g_object_class_install_property (gobject_class, PROP_LONGITUDE, + g_param_spec_double ("longitude", + "Longitude", "The location as a longitude coordinate associated with this video.", + G_MINDOUBLE, G_MAXDOUBLE, G_MAXDOUBLE, + G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)); +} + +static void +gdata_youtube_video_commentable_init (GDataCommentableInterface *iface) +{ + iface->comment_type = GDATA_TYPE_YOUTUBE_COMMENT; + iface->get_authorization_domain = get_authorization_domain; + iface->get_query_comments_uri = get_query_comments_uri; + iface->get_insert_comment_uri = get_insert_comment_uri; + iface->is_comment_deletable = is_comment_deletable; +} + +static void +gdata_youtube_video_init (GDataYouTubeVideo *self) +{ + self->priv = G_TYPE_INSTANCE_GET_PRIVATE (self, GDATA_TYPE_YOUTUBE_VIDEO, GDataYouTubeVideoPrivate); + self->priv->recorded = -1; + self->priv->access_controls = g_hash_table_new_full (g_str_hash, g_str_equal, (GDestroyNotify) g_free, NULL); + self->priv->latitude = G_MAXDOUBLE; + self->priv->longitude = G_MAXDOUBLE; +} + +static void +gdata_youtube_video_dispose (GObject *object) +{ + GDataYouTubeVideoPrivate *priv = GDATA_YOUTUBE_VIDEO (object)->priv; + + g_clear_object (&priv->category); + g_list_free_full (priv->thumbnails, (GDestroyNotify) g_object_unref); + g_clear_object (&priv->upload_state); + + /* Chain up to the parent class */ + G_OBJECT_CLASS (gdata_youtube_video_parent_class)->dispose (object); +} + +static void +gdata_youtube_video_finalize (GObject *object) +{ + GDataYouTubeVideoPrivate *priv = GDATA_YOUTUBE_VIDEO (object)->priv; + + g_free (priv->location); + g_hash_table_destroy (priv->access_controls); + g_strfreev (priv->keywords); + g_free (priv->channel_id); + g_free (priv->player_uri); + g_strfreev (priv->region_restriction_allowed); + g_strfreev (priv->region_restriction_blocked); + g_clear_pointer (&priv->content_ratings, g_hash_table_unref); + g_free (priv->rejection_reason); + g_free (priv->processing_status); + g_free (priv->upload_status); + g_free (priv->failure_reason); + + /* Chain up to the parent class */ + G_OBJECT_CLASS (gdata_youtube_video_parent_class)->finalize (object); +} + +static void +gdata_youtube_video_get_property (GObject *object, guint property_id, GValue *value, GParamSpec *pspec) +{ + GDataYouTubeVideoPrivate *priv = GDATA_YOUTUBE_VIDEO (object)->priv; + + switch (property_id) { + case PROP_VIEW_COUNT: + g_value_set_uint (value, priv->view_count); + break; + case PROP_FAVORITE_COUNT: + g_value_set_uint (value, priv->favorite_count); + break; + case PROP_LOCATION: + g_value_set_string (value, priv->location); + break; + case PROP_MIN_RATING: + g_value_set_uint (value, priv->rating.min); + break; + case PROP_MAX_RATING: + g_value_set_uint (value, priv->rating.max); + break; + case PROP_RATING_COUNT: + g_value_set_uint (value, priv->rating.count); + break; + case PROP_AVERAGE_RATING: + g_value_set_double (value, priv->rating.average); + break; + case PROP_KEYWORDS: + g_value_set_boxed (value, priv->keywords); + break; + case PROP_PLAYER_URI: + g_value_set_string (value, gdata_youtube_video_get_player_uri (GDATA_YOUTUBE_VIDEO (object))); + break; + case PROP_CATEGORY: + g_value_set_object (value, priv->category); + break; + case PROP_CREDIT: + g_value_set_object (value, NULL); + break; + case PROP_DESCRIPTION: + g_value_set_string (value, gdata_entry_get_summary (GDATA_ENTRY (object))); + break; + case PROP_DURATION: + g_value_set_uint (value, priv->duration); + break; + case PROP_IS_PRIVATE: + g_value_set_boolean (value, priv->is_private); + break; + case PROP_UPLOADED: + g_value_set_int64 (value, gdata_entry_get_published (GDATA_ENTRY (object))); + break; + case PROP_VIDEO_ID: + g_value_set_string (value, gdata_entry_get_id (GDATA_ENTRY (object))); + break; + case PROP_IS_DRAFT: + g_value_set_boolean (value, gdata_youtube_video_is_private (GDATA_YOUTUBE_VIDEO (object))); + break; + case PROP_STATE: + g_value_set_object (value, gdata_youtube_video_get_state (GDATA_YOUTUBE_VIDEO (object))); + break; + case PROP_RECORDED: + g_value_set_int64 (value, priv->recorded); + break; + case PROP_ASPECT_RATIO: + g_value_set_string (value, gdata_youtube_video_get_aspect_ratio (GDATA_YOUTUBE_VIDEO (object))); + break; + case PROP_LATITUDE: + g_value_set_double (value, priv->latitude); + break; + case PROP_LONGITUDE: + g_value_set_double (value, priv->longitude); + break; + default: + /* We don't have any other property... */ + G_OBJECT_WARN_INVALID_PROPERTY_ID (object, property_id, pspec); + break; + } +} + +static void +gdata_youtube_video_set_property (GObject *object, guint property_id, const GValue *value, GParamSpec *pspec) +{ + GDataYouTubeVideo *self = GDATA_YOUTUBE_VIDEO (object); + + switch (property_id) { + case PROP_LOCATION: + gdata_youtube_video_set_location (self, g_value_get_string (value)); + break; + case PROP_KEYWORDS: + gdata_youtube_video_set_keywords (self, g_value_get_boxed (value)); + break; + case PROP_CATEGORY: + gdata_youtube_video_set_category (self, g_value_get_object (value)); + break; + case PROP_DESCRIPTION: + gdata_youtube_video_set_description (self, g_value_get_string (value)); + break; + case PROP_IS_PRIVATE: + gdata_youtube_video_set_is_private (self, g_value_get_boolean (value)); + break; + case PROP_IS_DRAFT: + gdata_youtube_video_set_is_private (self, g_value_get_boolean (value)); + break; + case PROP_RECORDED: + gdata_youtube_video_set_recorded (self, g_value_get_int64 (value)); + break; + case PROP_ASPECT_RATIO: + gdata_youtube_video_set_aspect_ratio (self, g_value_get_string (value)); + break; + case PROP_LATITUDE: + gdata_youtube_video_set_coordinates (self, + g_value_get_double (value), + self->priv->longitude); + break; + case PROP_LONGITUDE: + gdata_youtube_video_set_coordinates (self, + self->priv->latitude, + g_value_get_double (value)); + break; + default: + /* We don't have any other property... */ + G_OBJECT_WARN_INVALID_PROPERTY_ID (object, property_id, pspec); + break; + } +} + +/* https://developers.google.com/youtube/v3/docs/videos#contentDetails.duration + * + * Note that it can also include an ‘hours’ component, as specified in ISO 8601, + * but not in the Google documentation. */ +static gboolean +duration_from_json_member (JsonReader *reader, const gchar *member_name, + GDataParserOptions options, guint *output, + gboolean *success, GError **error) +{ + gchar *duration_str = NULL, *i = NULL, *new_i = NULL; + guint64 seconds; + gboolean child_success = FALSE; + + if (!gdata_parser_string_from_json_member (reader, member_name, options, + &duration_str, + &child_success, error)) { + return FALSE; + } + + *success = child_success; + *output = 0; + + if (!child_success) { + return TRUE; + } + + /* Parse the string. Format: ‘PT(hH)?(mM)?(sS)?’, where ‘h’, ‘m’ and ‘s’ + * are integer numbers of hours, minutes and seconds. Each element may + * not be present. */ + i = duration_str; + if (strncmp (duration_str, "PT", 2) != 0) { + goto error; + } + + i += 2; /* PT */ + + seconds = 0; + + while (*i != '\0') { + guint64 element; + gchar designator; + + element = g_ascii_strtoull (i, &new_i, 10); + if (new_i == i) { + goto error; + } + + i = new_i; + + designator = i[0]; + if (designator == 'H') { + seconds += 60 * 60 * element; + } else if (designator == 'M') { + seconds += 60 * element; + } else if (designator == 'S') { + seconds += element; + } else { + goto error; + } + + i += 1; + } + + *output = seconds; + *success = child_success; + + g_free (duration_str); + + return TRUE; + +error: + gdata_parser_error_not_iso8601_format_json (reader, duration_str, + error); + g_free (duration_str); + + return TRUE; +} + +/* https://developers.google.com/youtube/v3/docs/videos#snippet.thumbnails */ +static gboolean +thumbnails_from_json_member (JsonReader *reader, const gchar *member_name, + GDataParserOptions options, GList **output, + gboolean *success, GError **error) +{ + guint i, len; + GList *thumbnails = NULL; + const GError *child_error = NULL; + + /* Check if there's such element */ + if (g_strcmp0 (json_reader_get_member_name (reader), + member_name) != 0) { + return FALSE; + } + + /* Check if the output string has already been set. The JSON parser + * guarantees this can't happen. */ + g_assert (!(options & P_NO_DUPES) || *output == NULL); + + len = json_reader_count_members (reader); + child_error = json_reader_get_error (reader); + + if (child_error != NULL) { + *success = gdata_parser_error_from_json_error (reader, + child_error, + error); + goto done; + } + + for (i = 0; i < len; i++) { + GDataParsable *thumbnail = NULL; /* GDataMediaThumbnail */ + + json_reader_read_element (reader, i); + thumbnail = _gdata_parsable_new_from_json_node (GDATA_TYPE_MEDIA_THUMBNAIL, + reader, NULL, + error); + json_reader_end_element (reader); + + if (thumbnail == NULL) { + *success = FALSE; + goto done; + } + + thumbnails = g_list_prepend (thumbnails, thumbnail); + } + + /* Success! */ + *output = thumbnails; + thumbnails = NULL; + *success = TRUE; + +done: + g_list_free_full (thumbnails, (GDestroyNotify) g_object_unref); + + return TRUE; +} + +/* https://developers.google.com/youtube/v3/docs/videos#contentDetails.regionRestriction */ +static gboolean +restricted_countries_from_json_member (JsonReader *reader, + const gchar *member_name, + GDataParserOptions options, + gchar ***output_allowed, + gchar ***output_blocked, + gboolean *success, GError **error) +{ + guint i, len; + const GError *child_error = NULL; + + /* Check if there's such element */ + if (g_strcmp0 (json_reader_get_member_name (reader), + member_name) != 0) { + return FALSE; + } + + /* Check if the output string has already been set. The JSON parser guarantees this can't happen. */ + g_assert (!(options & P_NO_DUPES) || + (*output_allowed == NULL && *output_blocked == NULL)); + + len = json_reader_count_members (reader); + child_error = json_reader_get_error (reader); + + if (child_error != NULL) { + *success = gdata_parser_error_from_json_error (reader, + child_error, + error); + return TRUE; + } + + for (i = 0; i < len; i++) { + json_reader_read_element (reader, i); + + if (gdata_parser_strv_from_json_member (reader, "allowed", + P_DEFAULT, + output_allowed, success, + error) || + gdata_parser_strv_from_json_member (reader, "blocked", + P_DEFAULT, + output_blocked, success, + error)) { + /* Nothing to do. */ + } + + json_reader_end_element (reader); + } + + /* Success! */ + *success = TRUE; + + return TRUE; +} + +/* https://developers.google.com/youtube/v3/docs/videos#contentDetails.contentRating */ +static gboolean +content_rating_from_json_member (JsonReader *reader, + const gchar *member_name, + GDataParserOptions options, + GHashTable **output, + gboolean *success, GError **error) +{ + guint i, len; + const GError *child_error = NULL; + + /* Check if there's such element */ + if (g_strcmp0 (json_reader_get_member_name (reader), + member_name) != 0) { + return FALSE; + } + + /* Check if the output string has already been set. The JSON parser + * guarantees this can't happen. */ + g_assert (!(options & P_NO_DUPES) || *output == NULL); + + len = json_reader_count_members (reader); + child_error = json_reader_get_error (reader); + + if (child_error != NULL) { + *success = gdata_parser_error_from_json_error (reader, + child_error, + error); + return TRUE; + } + + *output = g_hash_table_new_full (g_str_hash, g_str_equal, + g_free, g_free); + + for (i = 0; i < len; i++) { + const gchar *scheme, *rating; + + json_reader_read_element (reader, i); + + scheme = json_reader_get_member_name (reader); + rating = json_reader_get_string_value (reader); + + /* Ignore errors. */ + if (rating != NULL) { + g_hash_table_insert (*output, g_strdup (scheme), + g_strdup (rating)); + } + + json_reader_end_element (reader); + } + + /* Success! */ + *success = TRUE; + + return TRUE; +} + +static guint64 +parse_uint64_from_json_string_member (JsonReader *reader, + const gchar *member_name, + GError **error) +{ + const gchar *str_val, *end_ptr; + guint64 out; + const GError *child_error = NULL; + + /* Grab the string. */ + json_reader_read_member (reader, member_name); + + str_val = json_reader_get_string_value (reader); + child_error = json_reader_get_error (reader); + + if (child_error != NULL) { + gdata_parser_error_from_json_error (reader, child_error, error); + out = 0; + goto done; + } + + /* Try and parse it as an integer. */ + out = g_ascii_strtoull (str_val, (gchar **) &end_ptr, 10); + + if (*end_ptr != '\0') { + gdata_parser_error_required_json_content_missing (reader, + error); + out = 0; + goto done; + } + +done: + json_reader_end_member (reader); + + return out; +} + +static gboolean +parse_json (GDataParsable *parsable, JsonReader *reader, gpointer user_data, GError **error) +{ + gboolean success; + GDataYouTubeVideo *self = GDATA_YOUTUBE_VIDEO (parsable); + GDataYouTubeVideoPrivate *priv = self->priv; + + /* HACK: When called with gdata_service_query_single_entry(), the video + * list endpoint returns a 0–1 item list of results as a normal feed. + * (See: https://developers.google.com/youtube/v3/docs/videos/list) + * This differs from the v2 API, which returned just the entry. + * + * So, we need a hack to extract the single entry from the feed without + * being able to invoke the parsing machinery in GDataFeed, because + * gdata_service_query_single_entry() can’t do that. Do that by checking + * the kind, and then ignoring all subsequent members until we reach the + * items member. Recursively parse in there, then break out again. + * This all assumes that we see the kind member before items. */ + if (g_strcmp0 (json_reader_get_member_name (reader), "kind") == 0 && + g_strcmp0 (json_reader_get_string_value (reader), + "youtube#videoListResponse") == 0) { + priv->parsing_in_video_list_response = TRUE; + return TRUE; + } else if (g_strcmp0 (json_reader_get_member_name (reader), "items") == 0 && + priv->parsing_in_video_list_response) { + guint i; + + /* Instead of a 404 when searching for an invalid ID, the server + * returns an empty results list. */ + if (json_reader_count_elements (reader) != 1) { + g_set_error (error, GDATA_SERVICE_ERROR, GDATA_SERVICE_ERROR_NOT_FOUND, + /* Translators: the parameter is an error message returned by the server. */ + _("The requested resource was not found: %s"), + "items"); + return TRUE; + } + + /* Parse the first (and only) array element. */ + json_reader_read_element (reader, 0); + priv->parsing_in_video_list_response = FALSE; + + /* Parse all its properties. */ + for (i = 0; i < (guint) json_reader_count_members (reader); i++) { + g_return_val_if_fail (json_reader_read_element (reader, i), FALSE); + + if (GDATA_PARSABLE_GET_CLASS (self)->parse_json (GDATA_PARSABLE (self), reader, user_data, error) == FALSE) { + json_reader_end_element (reader); + break; + } + + json_reader_end_element (reader); + } + + priv->parsing_in_video_list_response = TRUE; + json_reader_end_element (reader); + + return TRUE; /* handled */ + } else if (priv->parsing_in_video_list_response) { + /* Ignore the member. */ + return TRUE; + } + + /* Actual video property parsing. */ + if (g_strcmp0 (json_reader_get_member_name (reader), "id") == 0) { + const gchar *id = NULL; + + /* If this is a youtube#searchResult, the id will be an object: + * https://developers.google.com/youtube/v3/docs/search#resource + * If it is a youtube#video, the id will be a string: + * https://developers.google.com/youtube/v3/docs/videos#resource + */ + + if (json_reader_is_value (reader)) { + id = json_reader_get_string_value (reader); + } else if (json_reader_is_object (reader)) { + json_reader_read_member (reader, "videoId"); + id = json_reader_get_string_value (reader); + json_reader_end_member (reader); + } + + /* Empty ID? */ + if (id == NULL || *id == '\0') { + return gdata_parser_error_required_json_content_missing (reader, error); + } + + _gdata_entry_set_id (GDATA_ENTRY (parsable), id); + + return TRUE; + } else if (g_strcmp0 (json_reader_get_member_name (reader), + "snippet") == 0) { + guint i; + + /* Check this is an object. */ + if (!json_reader_is_object (reader)) { + return gdata_parser_error_required_json_content_missing (reader, error); + } + + for (i = 0; i < (guint) json_reader_count_members (reader); i++) { + gint64 published_at; + gchar *title = NULL, *description = NULL; + gchar *category_id = NULL; + + json_reader_read_element (reader, i); + + if (gdata_parser_int64_time_from_json_member (reader, "publishedAt", P_DEFAULT, &published_at, &success, error)) { + if (success) { + _gdata_entry_set_published (GDATA_ENTRY (parsable), + published_at); + } + } else if (gdata_parser_string_from_json_member (reader, "title", P_DEFAULT, &title, &success, error)) { + if (success) { + gdata_entry_set_title (GDATA_ENTRY (parsable), + title); + } + + g_free (title); + } else if (gdata_parser_string_from_json_member (reader, "description", P_DEFAULT, &description, &success, error)) { + if (success) { + gdata_entry_set_summary (GDATA_ENTRY (parsable), + description); + } + + g_free (description); + } else if (gdata_parser_strv_from_json_member (reader, "tags", P_DEFAULT, &priv->keywords, &success, error) || + thumbnails_from_json_member (reader, "thumbnails", P_DEFAULT, &priv->thumbnails, &success, error) || + gdata_parser_string_from_json_member (reader, "channelId", P_DEFAULT, &priv->channel_id, &success, error)) { + /* Fall through. */ + } else if (gdata_parser_string_from_json_member (reader, "categoryId", P_DEFAULT, &category_id, &success, error)) { + if (success) { + priv->category = gdata_media_category_new (category_id, + NULL, + NULL); + } + + g_free (category_id); + } + + json_reader_end_element (reader); + + if (!success) { + return FALSE; + } + } + + return TRUE; + } else if (g_strcmp0 (json_reader_get_member_name (reader), + "contentDetails") == 0) { + guint i; + + /* Check this is an object. */ + if (!json_reader_is_object (reader)) { + return gdata_parser_error_required_json_content_missing (reader, error); + } + + for (i = 0; i < (guint) json_reader_count_members (reader); i++) { + json_reader_read_element (reader, i); + + if (duration_from_json_member (reader, "duration", P_DEFAULT, &priv->duration, &success, error) || + restricted_countries_from_json_member (reader, "regionRestriction", P_DEFAULT, &priv->region_restriction_allowed, &priv->region_restriction_blocked, &success, error) || + content_rating_from_json_member (reader, "contentRating", P_DEFAULT, &priv->content_ratings, &success, error)) { + /* Fall through. */ + } + + json_reader_end_element (reader); + + if (!success) { + return FALSE; + } + } + + return TRUE; + } else if (g_strcmp0 (json_reader_get_member_name (reader), + "status") == 0) { + const gchar *privacy_status; + + /* Check this is an object. */ + if (!json_reader_is_object (reader)) { + return gdata_parser_error_required_json_content_missing (reader, error); + } + + json_reader_read_member (reader, "privacyStatus"); + privacy_status = json_reader_get_string_value (reader); + json_reader_end_member (reader); + + if (g_strcmp0 (privacy_status, "private") == 0) { + priv->is_private = TRUE; + } else if (g_strcmp0 (privacy_status, "public") == 0) { + priv->is_private = FALSE; + g_hash_table_insert (priv->access_controls, + g_strdup ("list"), + GINT_TO_POINTER (GDATA_YOUTUBE_PERMISSION_ALLOWED)); + } else if (g_strcmp0 (privacy_status, "unlisted") == 0) { + /* See: ‘list’ on + * https://developers.google.com/youtube/2.0/reference?csw=1#youtube_data_api_tag_yt:accessControl */ + priv->is_private = FALSE; + g_hash_table_insert (priv->access_controls, + g_strdup ("list"), + GINT_TO_POINTER (GDATA_YOUTUBE_PERMISSION_DENIED)); + } + + json_reader_read_member (reader, "embeddable"); + g_hash_table_insert (priv->access_controls, + g_strdup (GDATA_YOUTUBE_ACTION_EMBED), + GINT_TO_POINTER (json_reader_get_boolean_value (reader) ? + GDATA_YOUTUBE_PERMISSION_ALLOWED : + GDATA_YOUTUBE_PERMISSION_DENIED)); + json_reader_end_member (reader); + + json_reader_read_member (reader, "uploadStatus"); + priv->upload_status = g_strdup (json_reader_get_string_value (reader)); + json_reader_end_member (reader); + + json_reader_read_member (reader, "failureReason"); + priv->rejection_reason = g_strdup (json_reader_get_string_value (reader)); + json_reader_end_member (reader); + + json_reader_read_member (reader, "rejectionReason"); + priv->rejection_reason = g_strdup (json_reader_get_string_value (reader)); + json_reader_end_member (reader); + + return TRUE; + } else if (g_strcmp0 (json_reader_get_member_name (reader), + "statistics") == 0) { + gint64 likes, dislikes; + GError *child_error = NULL; + + /* Check this is an object. */ + if (!json_reader_is_object (reader)) { + return gdata_parser_error_required_json_content_missing (reader, error); + } + + /* Views and favourites. For some unknown reason, the feed + * returns them as a string, even though they’re documented as + * being unsigned longs. + * + * Reference: https://developers.google.com/youtube/v3/docs/videos#statistics */ + priv->view_count = parse_uint64_from_json_string_member (reader, "viewCount", &child_error); + if (child_error != NULL) { + g_propagate_error (error, child_error); + return FALSE; + } + + priv->favorite_count = parse_uint64_from_json_string_member (reader, "favoriteCount", &child_error); + if (child_error != NULL) { + g_propagate_error (error, child_error); + return FALSE; + } + + /* The new ratings API (total likes, total dislikes) doesn’t + * really match with the old API (collection of integer ratings + * between 1 and 5). Try and return something appropriate. */ + likes = parse_uint64_from_json_string_member (reader, "likeCount", &child_error); + if (child_error != NULL) { + g_propagate_error (error, child_error); + return FALSE; + } + + dislikes = parse_uint64_from_json_string_member (reader, "dislikeCount", &child_error); + if (child_error != NULL) { + g_propagate_error (error, child_error); + return FALSE; + } + + priv->rating.min = 0; + priv->rating.max = 1; + priv->rating.count = likes + dislikes; + if (likes + dislikes == 0) { + priv->rating.average = 0.0; /* basically undefined */ + } else { + priv->rating.average = (gdouble) likes / (gdouble) (likes + dislikes); + } + + return TRUE; + } else if (g_strcmp0 (json_reader_get_member_name (reader), + "processingDetails") == 0) { + /* Check this is an object. */ + if (!json_reader_is_object (reader)) { + return gdata_parser_error_required_json_content_missing (reader, error); + } + + json_reader_read_member (reader, "processingStatus"); + priv->processing_status = g_strdup (json_reader_get_string_value (reader)); + json_reader_end_member (reader); + + return TRUE; + } else if (g_strcmp0 (json_reader_get_member_name (reader), + "recordingDetails") == 0) { + const gchar *recording_date; + const GError *child_error = NULL; + + /* Check this is an object. */ + if (!json_reader_is_object (reader)) { + return gdata_parser_error_required_json_content_missing (reader, error); + } + + json_reader_read_member (reader, "recordingDate"); + recording_date = json_reader_get_string_value (reader); + json_reader_end_member (reader); + + if (recording_date != NULL && + !gdata_parser_int64_from_date (recording_date, + &priv->recorded)) { + /* Error */ + gdata_parser_error_not_iso8601_format_json (reader, + recording_date, + error); + return FALSE; + } + + json_reader_read_member (reader, "locationDescription"); + priv->location = g_strdup (json_reader_get_string_value (reader)); + json_reader_end_member (reader); + + if (json_reader_read_member (reader, "location")) { + json_reader_read_member (reader, "latitude"); + priv->latitude = json_reader_get_double_value (reader); + json_reader_end_member (reader); + + json_reader_read_member (reader, "longitude"); + priv->longitude = json_reader_get_double_value (reader); + json_reader_end_member (reader); + } + + json_reader_end_member (reader); + + child_error = json_reader_get_error (reader); + if (child_error != NULL) { + return gdata_parser_error_from_json_error (reader, + child_error, + error); + } + + return TRUE; + } else { + return GDATA_PARSABLE_CLASS (gdata_youtube_video_parent_class)->parse_json (parsable, reader, user_data, error); + } + + return TRUE; +} + +static gboolean +post_parse_json (GDataParsable *parsable, gpointer user_data, GError **error) +{ + GDataLink *_link = NULL; /* owned */ + const gchar *id; + gchar *uri = NULL; /* owned */ + + /* Set the self link, which is needed for + * gdata_service_delete_entry(). */ + id = gdata_entry_get_id (GDATA_ENTRY (parsable)); + + if (id == NULL) { + return TRUE; + } + + uri = _gdata_service_build_uri ("https://www.googleapis.com" + "/youtube/v3/videos" + "?id=%s", id); + _link = gdata_link_new (uri, GDATA_LINK_SELF); + gdata_entry_add_link (GDATA_ENTRY (parsable), _link); + g_object_unref (_link); + g_free (uri); + + return TRUE; +} + +static void +get_json (GDataParsable *parsable, JsonBuilder *builder) +{ + GDataEntry *entry = GDATA_ENTRY (parsable); + GDataYouTubeVideoPrivate *priv = GDATA_YOUTUBE_VIDEO (parsable)->priv; + guint i; + gpointer permission_ptr; + + /* Chain up to the parent class */ + GDATA_PARSABLE_CLASS (gdata_youtube_video_parent_class)->get_json (parsable, builder); + + /* Add the video-specific JSON. + * Reference: + * https://developers.google.com/youtube/v3/docs/videos/insert#request_body */ + /* snippet object. */ + json_builder_set_member_name (builder, "snippet"); + json_builder_begin_object (builder); + + if (gdata_entry_get_title (entry) != NULL) { + json_builder_set_member_name (builder, "title"); + json_builder_add_string_value (builder, + gdata_entry_get_title (entry)); + } + + if (gdata_entry_get_summary (entry) != NULL) { + json_builder_set_member_name (builder, "description"); + json_builder_add_string_value (builder, + gdata_entry_get_summary (entry)); + } + + if (priv->keywords != NULL) { + json_builder_set_member_name (builder, "tags"); + json_builder_begin_array (builder); + + for (i = 0; priv->keywords[i] != NULL; i++) { + json_builder_add_string_value (builder, + priv->keywords[i]); + } + + json_builder_end_array (builder); + } + + if (priv->category != NULL) { + json_builder_set_member_name (builder, "categoryId"); + json_builder_add_string_value (builder, + gdata_media_category_get_category (priv->category)); + } + + json_builder_end_object (builder); + + /* status object. */ + json_builder_set_member_name (builder, "status"); + json_builder_begin_object (builder); + + json_builder_set_member_name (builder, "privacyStatus"); + + if (!priv->is_private && + g_hash_table_lookup_extended (priv->access_controls, + "list", NULL, + &permission_ptr)) { + GDataYouTubePermission perm; + + perm = GPOINTER_TO_INT (permission_ptr); + + /* See the ‘list’ documentation on: + * https://developers.google.com/youtube/2.0/reference?csw=1#youtube_data_api_tag_yt:accessControl */ + json_builder_add_string_value (builder, + (perm == GDATA_YOUTUBE_PERMISSION_ALLOWED) ? "public" : "unlisted"); + } else { + json_builder_add_string_value (builder, + priv->is_private ? "private" : "public"); + } + + if (g_hash_table_lookup_extended (priv->access_controls, + GDATA_YOUTUBE_ACTION_EMBED, NULL, + &permission_ptr)) { + GDataYouTubePermission perm; + + perm = GPOINTER_TO_INT (permission_ptr); + + json_builder_set_member_name (builder, "embeddable"); + json_builder_add_boolean_value (builder, + perm == GDATA_YOUTUBE_PERMISSION_ALLOWED); + } + + /* FIXME: add support for: + * publicStatsViewable + * publishAt + * license + */ + + json_builder_end_object (builder); + + /* recordingDetails object. */ + json_builder_set_member_name (builder, "recordingDetails"); + json_builder_begin_object (builder); + + if (priv->location != NULL) { + json_builder_set_member_name (builder, "locationDescription"); + json_builder_add_string_value (builder, priv->location); + } + + if (priv->latitude >= -90.0 && priv->latitude <= 90.0 && + priv->longitude >= -180.0 && priv->longitude <= 180.0) { + json_builder_set_member_name (builder, "location"); + json_builder_begin_object (builder); + + json_builder_set_member_name (builder, "latitude"); + json_builder_add_double_value (builder, priv->latitude); + + json_builder_set_member_name (builder, "longitude"); + json_builder_add_double_value (builder, priv->longitude); + + json_builder_end_object (builder); + } + + if (priv->recorded != -1) { + gchar *recorded = gdata_parser_date_from_int64 (priv->recorded); + json_builder_set_member_name (builder, "recordingDate"); + json_builder_add_string_value (builder, recorded); + g_free (recorded); + } + + json_builder_end_object (builder); +} + +static const gchar * +get_content_type (void) +{ + return "application/json"; +} + +static gchar * +get_entry_uri (const gchar *id) +{ + const gchar *old_prefix = "tag:youtube.com,2008:video:"; + + /* For compatibility with previous video ID formats, strip off the v2 + * ID prefix. */ + if (g_str_has_prefix (id, old_prefix)) { + id += strlen (old_prefix); + } + + /* Build the query URI for a single video. This is a bit of a pain, + * because it actually returns a list containing a single video, but + * there seems no other way to do it. See parsing_in_video_list_response + * in parse_json() for the fallout. + * + * Reference: https://developers.google.com/youtube/v3/docs/videos/list#part */ + return _gdata_service_build_uri ("https://www.googleapis.com/youtube/v3/videos" + "?part=contentDetails,id," + "recordingDetails,snippet," + "status,statistics" + "&id=%s", id); +} + +static GDataAuthorizationDomain * +get_authorization_domain (GDataCommentable *self) +{ + return gdata_youtube_service_get_primary_authorization_domain (); +} + +static gchar * +get_query_comments_uri (GDataCommentable *self) +{ + const gchar *video_id; + + video_id = gdata_entry_get_id (GDATA_ENTRY (self)); + + /* https://developers.google.com/youtube/v3/docs/commentThreads/list */ + return _gdata_service_build_uri ("https://www.googleapis.com" + "/youtube/v3/commentThreads" + "?part=snippet" + "&videoId=%s", video_id); +} + +G_GNUC_INTERNAL void +_gdata_youtube_comment_set_video_id (GDataYouTubeComment *self, + const gchar *video_id); +G_GNUC_INTERNAL void +_gdata_youtube_comment_set_channel_id (GDataYouTubeComment *self, + const gchar *channel_id); + +static gchar * +get_insert_comment_uri (GDataCommentable *self, GDataComment *comment_) +{ + const gchar *video_id, *channel_id; + GDataYouTubeVideoPrivate *priv = GDATA_YOUTUBE_VIDEO (self)->priv; + + video_id = gdata_entry_get_id (GDATA_ENTRY (self)); + channel_id = priv->channel_id; + + /* https://developers.google.com/youtube/v3/docs/commentThreads/insert + * + * We have to set the video ID on the @comment_. */ + _gdata_youtube_comment_set_video_id (GDATA_YOUTUBE_COMMENT (comment_), + video_id); + _gdata_youtube_comment_set_channel_id (GDATA_YOUTUBE_COMMENT (comment_), + channel_id); + + return _gdata_service_build_uri ("https://www.googleapis.com" + "/youtube/v3/commentThreads" + "?part=snippet" + "&shareOnGooglePlus=false"); +} + +static gboolean +is_comment_deletable (GDataCommentable *self, GDataComment *comment_) +{ + /* FIXME: Currently unsupported: + * https://developers.google.com/youtube/v3/migration-guide#to_be_migrated + * https://developers.google.com/youtube/v3/guides/implementation/comments#comments-delete */ + return FALSE; +} + +/** + * gdata_youtube_video_new: + * @id: (allow-none): the video's ID, or %NULL + * + * Creates a new #GDataYouTubeVideo with the given ID and default properties. + * + * Return value: a new #GDataYouTubeVideo; unref with g_object_unref() + */ +GDataYouTubeVideo * +gdata_youtube_video_new (const gchar *id) +{ + return g_object_new (GDATA_TYPE_YOUTUBE_VIDEO, "id", id, NULL); +} + +/** + * gdata_youtube_video_get_view_count: + * @self: a #GDataYouTubeVideo + * + * Gets the #GDataYouTubeVideo:view-count property. + * + * Return value: the number of times the video has been viewed + */ +guint +gdata_youtube_video_get_view_count (GDataYouTubeVideo *self) +{ + g_return_val_if_fail (GDATA_IS_YOUTUBE_VIDEO (self), 0); + return self->priv->view_count; +} + +/** + * gdata_youtube_video_get_favorite_count: + * @self: a #GDataYouTubeVideo + * + * Gets the #GDataYouTubeVideo:favorite-count property. + * + * Return value: the number of users who have added the video to their favorites list + */ +guint +gdata_youtube_video_get_favorite_count (GDataYouTubeVideo *self) +{ + g_return_val_if_fail (GDATA_IS_YOUTUBE_VIDEO (self), 0); + return self->priv->favorite_count; +} + +/** + * gdata_youtube_video_get_location: + * @self: a #GDataYouTubeVideo + * + * Gets the #GDataYouTubeVideo:location property. + * + * Return value: a string describing the video's location, or %NULL + */ +const gchar * +gdata_youtube_video_get_location (GDataYouTubeVideo *self) +{ + g_return_val_if_fail (GDATA_IS_YOUTUBE_VIDEO (self), NULL); + return self->priv->location; +} + +/** + * gdata_youtube_video_set_location: + * @self: a #GDataYouTubeVideo + * @location: (allow-none): a new location, or %NULL + * + * Sets the #GDataYouTubeVideo:location property to the new location string, @location. + * + * Set @location to %NULL to unset the property in the video. + */ +void +gdata_youtube_video_set_location (GDataYouTubeVideo *self, const gchar *location) +{ + g_return_if_fail (GDATA_IS_YOUTUBE_VIDEO (self)); + + g_free (self->priv->location); + self->priv->location = g_strdup (location); + g_object_notify (G_OBJECT (self), "location"); +} + +/** + * gdata_youtube_video_get_access_control: + * @self: a #GDataYouTubeVideo + * @action: the action whose permission should be returned + * + * Gets the permission associated with the given @action on the #GDataYouTubeVideo. If the given @action + * doesn't have a permission set on the video, %GDATA_YOUTUBE_PERMISSION_DENIED is returned. + * + * Return value: the permission associated with @action, or %GDATA_YOUTUBE_PERMISSION_DENIED + * + * Since: 0.7.0 + */ +GDataYouTubePermission +gdata_youtube_video_get_access_control (GDataYouTubeVideo *self, const gchar *action) +{ + gpointer value; + + g_return_val_if_fail (GDATA_IS_YOUTUBE_VIDEO (self), GDATA_YOUTUBE_PERMISSION_DENIED); + g_return_val_if_fail (action != NULL, GDATA_YOUTUBE_PERMISSION_DENIED); + + if (g_hash_table_lookup_extended (self->priv->access_controls, action, NULL, &value) == FALSE) + return GDATA_YOUTUBE_PERMISSION_DENIED; + return GPOINTER_TO_INT (value); +} + +/** + * gdata_youtube_video_set_access_control: + * @self: a #GDataYouTubeVideo + * @action: the action whose permission is being set + * @permission: the permission to give to the action + * + * Sets the permission associated with @action on the #GDataYouTubeVideo, allowing restriction or derestriction of various + * operations on YouTube videos. + * + * Note that only %GDATA_YOUTUBE_ACTION_RATE and %GDATA_YOUTUBE_ACTION_COMMENT actions can have the %GDATA_YOUTUBE_PERMISSION_MODERATED permission. + * + * Since: 0.7.0 + */ +void +gdata_youtube_video_set_access_control (GDataYouTubeVideo *self, const gchar *action, GDataYouTubePermission permission) +{ + g_return_if_fail (GDATA_IS_YOUTUBE_VIDEO (self)); + g_return_if_fail (action != NULL); + + g_hash_table_replace (self->priv->access_controls, g_strdup (action), GINT_TO_POINTER (permission)); +} + +/** + * gdata_youtube_video_get_rating: + * @self: a #GDataYouTubeVideo + * @min: (out caller-allocates) (allow-none): return location for the minimum rating value, or %NULL + * @max: (out caller-allocates) (allow-none): return location for the maximum rating value, or %NULL + * @count: (out caller-allocates) (allow-none): return location for the number of ratings, or %NULL + * @average: (out caller-allocates) (allow-none): return location for the average rating value, or %NULL + * + * Gets various properties of the ratings on the video. + * + * Note that this property may not be retrieved when querying for multiple + * videos at once, but is guaranteed to be retrieved when querying with + * gdata_service_query_single_entry_async(). + */ +void +gdata_youtube_video_get_rating (GDataYouTubeVideo *self, guint *min, guint *max, guint *count, gdouble *average) +{ + g_return_if_fail (GDATA_IS_YOUTUBE_VIDEO (self)); + if (min != NULL) + *min = self->priv->rating.min; + if (max != NULL) + *max = self->priv->rating.max; + if (count != NULL) + *count = self->priv->rating.count; + if (average != NULL) + *average = self->priv->rating.average; +} + +/** + * gdata_youtube_video_get_keywords: + * @self: a #GDataYouTubeVideo + * + * Gets the #GDataYouTubeVideo:keywords property. + * + * Return value: (array zero-terminated=1) (transfer none): a %NULL-terminated array of words associated with the video + */ +const gchar * const * +gdata_youtube_video_get_keywords (GDataYouTubeVideo *self) +{ + g_return_val_if_fail (GDATA_IS_YOUTUBE_VIDEO (self), NULL); + return (const gchar * const *) self->priv->keywords; +} + +/** + * gdata_youtube_video_set_keywords: + * @self: a #GDataYouTubeVideo + * @keywords: (array zero-terminated=1): a new %NULL-terminated array of keywords + * + * Sets the #GDataYouTubeVideo:keywords property to the new keyword list, @keywords. + * + * @keywords must not be %NULL. For more information, see the online documentation. + */ +void +gdata_youtube_video_set_keywords (GDataYouTubeVideo *self, const gchar * const *keywords) +{ + g_return_if_fail (GDATA_IS_YOUTUBE_VIDEO (self)); + g_return_if_fail (keywords != NULL); + + g_strfreev (self->priv->keywords); + self->priv->keywords = g_strdupv ((gchar **) keywords); + g_object_notify (G_OBJECT (self), "keywords"); +} + +/** + * gdata_youtube_video_get_player_uri: + * @self: a #GDataYouTubeVideo + * + * Gets the #GDataYouTubeVideo:player-uri property. + * + * Return value: a URI where the video is playable in a web browser, or %NULL + */ +const gchar * +gdata_youtube_video_get_player_uri (GDataYouTubeVideo *self) +{ + GDataYouTubeVideoPrivate *priv; + + g_return_val_if_fail (GDATA_IS_YOUTUBE_VIDEO (self), NULL); + + priv = self->priv; + + /* Generate and cache the player URI. */ + if (priv->player_uri == NULL) { + priv->player_uri = _gdata_service_build_uri ("https://www.youtube.com/watch?v=%s", + gdata_entry_get_id (GDATA_ENTRY (self))); + } + + return priv->player_uri; +} + +static gboolean +strv_contains (const gchar * const *strv, const gchar *key) +{ + guint i; + + for (i = 0; strv != NULL && strv[i] != NULL; i++) { + if (g_strcmp0 (strv[i], key) == 0) { + return TRUE; + } + } + + return FALSE; +} + +/** + * gdata_youtube_video_is_restricted_in_country: + * @self: a #GDataYouTubeVideo + * @country: an ISO 3166 two-letter country code to check + * + * Checks whether viewing of the video is restricted in @country, either by its content rating, or by the request of the producer. + * The return value from this function is purely informational, and no obligation is assumed. + * + * Return value: %TRUE if the video is restricted in @country, %FALSE otherwise + * + * Since: 0.4.0 + */ +gboolean +gdata_youtube_video_is_restricted_in_country (GDataYouTubeVideo *self, const gchar *country) +{ + GDataYouTubeVideoPrivate *priv; + gboolean allowed_present, allowed_empty; + gboolean in_allowed, in_blocked; + + g_return_val_if_fail (GDATA_IS_YOUTUBE_VIDEO (self), FALSE); + g_return_val_if_fail (country != NULL && *country != '\0', FALSE); + + priv = self->priv; + + allowed_present = (priv->region_restriction_allowed != NULL); + allowed_empty = (allowed_present && + priv->region_restriction_allowed[0] == NULL); + + in_allowed = strv_contains ((const gchar * const *) priv->region_restriction_allowed, country); + in_blocked = strv_contains ((const gchar * const *) priv->region_restriction_blocked, country); + + return ((allowed_present && !in_allowed) || + allowed_empty || + (in_blocked && !in_allowed)); +} + +/* References: + * v2: https://developers.google.com/youtube/2.0/reference#youtube_data_api_tag_media:rating + * v3: https://developers.google.com/youtube/v3/docs/videos#contentDetails.contentRating.mpaaRating + */ +static const gchar * +convert_mpaa_rating (const gchar *v3_rating) +{ + if (g_strcmp0 (v3_rating, "mpaaG") == 0) { + return "g"; + } else if (g_strcmp0 (v3_rating, "mpaaNc17") == 0) { + return "nc-17"; + } else if (g_strcmp0 (v3_rating, "mpaaPg") == 0) { + return "pg"; + } else if (g_strcmp0 (v3_rating, "mpaaPg13") == 0) { + return "pg-13"; + } else if (g_strcmp0 (v3_rating, "mpaaR") == 0) { + return "r"; + } else { + return NULL; + } +} + +/* References: + * v2: https://developers.google.com/youtube/2.0/reference#youtube_data_api_tag_media:rating + * v3: https://developers.google.com/youtube/v3/docs/videos#contentDetails.contentRating.tvpgRating + */ +static const gchar * +convert_tvpg_rating (const gchar *v3_rating) +{ + if (g_strcmp0 (v3_rating, "pg14") == 0) { + return "tv-14"; + } else if (g_strcmp0 (v3_rating, "tvpgG") == 0) { + return "tv-g"; + } else if (g_strcmp0 (v3_rating, "tvpgMa") == 0) { + return "tv-ma"; + } else if (g_strcmp0 (v3_rating, "tvpgPg") == 0) { + return "tv-pg"; + } else if (g_strcmp0 (v3_rating, "tvpgY") == 0) { + return "tv-y"; + } else if (g_strcmp0 (v3_rating, "tvpgY7") == 0) { + return "tv-y7"; + } else if (g_strcmp0 (v3_rating, "tvpgY7Fv") == 0) { + return "tv-y7-fv"; + } else { + return NULL; + } +} + +/** + * gdata_youtube_video_get_media_rating: + * @self: a #GDataYouTubeVideo + * @rating_type: the type of rating to retrieve + * + * Returns the rating of the given type for the video, if one exists. For example, this could be a film rating awarded by the MPAA; or a simple + * rating specifying whether the video contains adult content. + * + * The valid values for @rating_type are: %GDATA_YOUTUBE_RATING_TYPE_MPAA and %GDATA_YOUTUBE_RATING_TYPE_V_CHIP. + * Further values may be added in future; if an unknown rating type is passed to the function, %NULL will be returned. + * + * The possible return values depend on what's passed to @rating_type. Valid values for each rating type are listed in the documentation for the + * rating types. + * + * Return value: the rating of the video for the given @rating_type, or %NULL if the video isn't rated with that type (or the type is unknown) + * + * Since: 0.10.0 + */ +const gchar * +gdata_youtube_video_get_media_rating (GDataYouTubeVideo *self, const gchar *rating_type) +{ + const gchar *rating; + + g_return_val_if_fail (GDATA_IS_YOUTUBE_VIDEO (self), NULL); + g_return_val_if_fail (rating_type != NULL && *rating_type != '\0', NULL); + + /* All ratings are unknown. */ + if (self->priv->content_ratings == NULL) { + return NULL; + } + + /* Compatibility with the old API. */ + if (g_strcmp0 (rating_type, "simple") == 0) { + /* Not supported any more. */ + return NULL; + } else if (g_strcmp0 (rating_type, "mpaa") == 0) { + rating = g_hash_table_lookup (self->priv->content_ratings, + "mpaaRating"); + return convert_mpaa_rating (rating); + } else if (g_strcmp0 (rating_type, "v-chip") == 0) { + rating = g_hash_table_lookup (self->priv->content_ratings, + "tvpgRating"); + return convert_tvpg_rating (rating); + } + + return g_hash_table_lookup (self->priv->content_ratings, rating_type); +} + +/** + * gdata_youtube_video_get_category: + * @self: a #GDataYouTubeVideo + * + * Gets the #GDataYouTubeVideo:category property. + * + * Return value: (transfer none): a #GDataMediaCategory giving the video's single and mandatory category + */ +GDataMediaCategory * +gdata_youtube_video_get_category (GDataYouTubeVideo *self) +{ + g_return_val_if_fail (GDATA_IS_YOUTUBE_VIDEO (self), NULL); + return self->priv->category; +} + +/** + * gdata_youtube_video_set_category: + * @self: a #GDataYouTubeVideo + * @category: a new #GDataMediaCategory + * + * Sets the #GDataYouTubeVideo:category property to the new category, @category, and increments its reference count. + * + * @category must not be %NULL. For more information, see the online documentation. + */ +void +gdata_youtube_video_set_category (GDataYouTubeVideo *self, GDataMediaCategory *category) +{ + g_return_if_fail (GDATA_IS_YOUTUBE_VIDEO (self)); + g_return_if_fail (GDATA_IS_MEDIA_CATEGORY (category)); + + g_object_ref (category); + g_clear_object (&self->priv->category); + self->priv->category = category; + g_object_notify (G_OBJECT (self), "category"); +} + +G_GNUC_BEGIN_IGNORE_DEPRECATIONS + +/** + * gdata_youtube_video_get_credit: + * @self: a #GDataYouTubeVideo + * + * Gets the #GDataYouTubeVideo:credit property. + * + * Return value: (transfer none): a #GDataMediaCredit giving information on whom to credit for the video, or %NULL + * Deprecated: 0.17.0: This is no longer supported by Google, and will + * always return %NULL. There is no replacement. + */ +GDataYouTubeCredit * +gdata_youtube_video_get_credit (GDataYouTubeVideo *self) +{ + g_return_val_if_fail (GDATA_IS_YOUTUBE_VIDEO (self), NULL); + return NULL; +} + +G_GNUC_END_IGNORE_DEPRECATIONS + +/** + * gdata_youtube_video_get_description: + * @self: a #GDataYouTubeVideo + * + * Gets the #GDataYouTubeVideo:description property. + * + * Return value: the video's long text description, or %NULL + */ +const gchar * +gdata_youtube_video_get_description (GDataYouTubeVideo *self) +{ + g_return_val_if_fail (GDATA_IS_YOUTUBE_VIDEO (self), NULL); + return gdata_entry_get_summary (GDATA_ENTRY (self)); +} + +/** + * gdata_youtube_video_set_description: + * @self: a #GDataYouTubeVideo + * @description: (allow-none): the video's new description, or %NULL + * + * Sets the #GDataYouTubeVideo:description property to the new description, @description. + * + * Set @description to %NULL to unset the video's description. + */ +void +gdata_youtube_video_set_description (GDataYouTubeVideo *self, const gchar *description) +{ + g_return_if_fail (GDATA_IS_YOUTUBE_VIDEO (self)); + gdata_entry_set_summary (GDATA_ENTRY (self), description); + g_object_notify (G_OBJECT (self), "description"); +} + +G_GNUC_BEGIN_IGNORE_DEPRECATIONS + +/** + * gdata_youtube_video_look_up_content: + * @self: a #GDataYouTubeVideo + * @type: the MIME type of the content desired + * + * Looks up a #GDataYouTubeContent from the video with the given MIME type. The video's list of contents is + * a list of URIs to various formats of the video itself, such as its SWF URI or RTSP stream. + * + * Return value: (transfer none): a #GDataYouTubeContent matching @type, or %NULL + * Deprecated: 0.17.0: This is no longer supported by Google, and will + * always return %NULL. To view a video, open the URI returned by + * gdata_youtube_video_get_player_uri() in a web browser. + */ +GDataYouTubeContent * +gdata_youtube_video_look_up_content (GDataYouTubeVideo *self, const gchar *type) +{ + g_return_val_if_fail (GDATA_IS_YOUTUBE_VIDEO (self), NULL); + g_return_val_if_fail (type != NULL, NULL); + + /* Not supported in the v3 API. */ + return NULL; +} + +G_GNUC_END_IGNORE_DEPRECATIONS + +/** + * gdata_youtube_video_get_thumbnails: + * @self: a #GDataYouTubeVideo + * + * Gets a list of the thumbnails available for the video. + * + * Return value: (element-type GData.MediaThumbnail) (transfer none): a #GList of #GDataMediaThumbnails, or %NULL + */ +GList * +gdata_youtube_video_get_thumbnails (GDataYouTubeVideo *self) +{ + g_return_val_if_fail (GDATA_IS_YOUTUBE_VIDEO (self), NULL); + return self->priv->thumbnails; +} + +/** + * gdata_youtube_video_get_duration: + * @self: a #GDataYouTubeVideo + * + * Gets the #GDataYouTubeVideo:duration property. + * + * Return value: the video duration in seconds, or 0 if unknown + */ +guint +gdata_youtube_video_get_duration (GDataYouTubeVideo *self) +{ + g_return_val_if_fail (GDATA_IS_YOUTUBE_VIDEO (self), 0); + return self->priv->duration; +} + +/** + * gdata_youtube_video_is_private: + * @self: a #GDataYouTubeVideo + * + * Gets the #GDataYouTubeVideo:is-private property. + * + * Return value: %TRUE if the video is private, %FALSE otherwise + */ +gboolean +gdata_youtube_video_is_private (GDataYouTubeVideo *self) +{ + g_return_val_if_fail (GDATA_IS_YOUTUBE_VIDEO (self), FALSE); + return self->priv->is_private; +} + +/** + * gdata_youtube_video_set_is_private: + * @self: a #GDataYouTubeVideo + * @is_private: whether the video is private + * + * Sets the #GDataYouTubeVideo:is-private property to decide whether the video is publicly viewable. + */ +void +gdata_youtube_video_set_is_private (GDataYouTubeVideo *self, gboolean is_private) +{ + g_return_if_fail (GDATA_IS_YOUTUBE_VIDEO (self)); + self->priv->is_private = is_private; + g_object_notify (G_OBJECT (self), "is-private"); +} + +/** + * gdata_youtube_video_get_uploaded: + * @self: a #GDataYouTubeVideo + * + * Gets the #GDataYouTubeVideo:uploaded property. If the property is unset, -1 will be returned. + * + * Return value: the UNIX timestamp for the time the video was uploaded, or -1 + */ +gint64 +gdata_youtube_video_get_uploaded (GDataYouTubeVideo *self) +{ + g_return_val_if_fail (GDATA_IS_YOUTUBE_VIDEO (self), -1); + return gdata_entry_get_published (GDATA_ENTRY (self)); +} + +/** + * gdata_youtube_video_get_video_id: + * @self: a #GDataYouTubeVideo + * + * Gets the #GDataYouTubeVideo:video-id property. + * + * Return value: the video's unique and permanent ID + * Deprecated: 0.17.0: This is now equal to #GDataEntry:id. + */ +const gchar * +gdata_youtube_video_get_video_id (GDataYouTubeVideo *self) +{ + g_return_val_if_fail (GDATA_IS_YOUTUBE_VIDEO (self), NULL); + return gdata_entry_get_id (GDATA_ENTRY (self)); +} + +/** + * gdata_youtube_video_is_draft: + * @self: a #GDataYouTubeVideo + * + * Gets the #GDataYouTubeVideo:is-draft property. + * + * Return value: %TRUE if the video is a draft, %FALSE otherwise + * Deprecated: 0.17.0: This is now equal to + * gdata_youtube_video_is_private(). + */ +gboolean +gdata_youtube_video_is_draft (GDataYouTubeVideo *self) +{ + g_return_val_if_fail (GDATA_IS_YOUTUBE_VIDEO (self), FALSE); + return gdata_youtube_video_is_private (self); +} + +/** + * gdata_youtube_video_set_is_draft: + * @self: a #GDataYouTubeVideo + * @is_draft: whether the video is a draft + * + * Sets the #GDataYouTubeVideo:is-draft property to decide whether the video is a draft. + * + * Deprecated: 0.17.0: This is now equivalent to + * gdata_youtube_video_set_is_private(). + */ +void +gdata_youtube_video_set_is_draft (GDataYouTubeVideo *self, gboolean is_draft) +{ + g_return_if_fail (GDATA_IS_YOUTUBE_VIDEO (self)); + gdata_youtube_video_set_is_private (self, is_draft); + g_object_notify (G_OBJECT (self), "is-draft"); +} + +/* Convert from v3 to v2 API video upload state. References: + * v2: https://developers.google.com/youtube/2.0/reference?csw=1#youtube_data_api_tag_yt:state + * v3: https://developers.google.com/youtube/v3/docs/videos#processingDetails.processingStatus + * https://developers.google.com/youtube/v3/docs/videos#status.uploadStatus + */ +static const gchar * +convert_state_name (const gchar *v3_processing_status, + const gchar *v3_upload_status) +{ + if (g_strcmp0 (v3_upload_status, "deleted") == 0 || + g_strcmp0 (v3_upload_status, "failed") == 0 || + g_strcmp0 (v3_upload_status, "rejected") == 0) { + return v3_upload_status; + } else if (g_strcmp0 (v3_processing_status, "processing") == 0) { + return v3_processing_status; + } + + return NULL; +} + +/* References: + * v2: https://developers.google.com/youtube/2.0/reference?csw=1#youtube_data_api_tag_yt:state + * v3: https://developers.google.com/youtube/v3/docs/videos#status.failureReason + * https://developers.google.com/youtube/v3/docs/videos#status.rejectionReason + */ +static const gchar * +convert_state_reason_code (const gchar *v2_name, + const gchar *v3_failure_reason, + const gchar *v3_rejection_reason) +{ + if (v2_name == NULL || + g_strcmp0 (v2_name, "processing") == 0 || + g_strcmp0 (v2_name, "deleted") == 0) { + /* Explicitly unset if unknown, processing or deleted. */ + return NULL; + } else if (g_strcmp0 (v2_name, "restricted") == 0) { + /* Unsupported conversion; convert_state_name() can never return + * ‘restricted’ anyway. */ + return NULL; + } else if (g_strcmp0 (v2_name, "rejected") == 0) { + if (g_strcmp0 (v3_rejection_reason, "claim") == 0 || + g_strcmp0 (v3_rejection_reason, "copyright") == 0 || + g_strcmp0 (v3_rejection_reason, "trademark") == 0) { + return "copyright"; + } else if (g_strcmp0 (v3_rejection_reason, "duplicate") == 0) { + return "duplicate"; + } else if (g_strcmp0 (v3_rejection_reason, + "inappropriate") == 0) { + return "inappropriate"; + } else if (g_strcmp0 (v3_rejection_reason, "length") == 0) { + return "tooLong"; + } else if (g_strcmp0 (v3_rejection_reason, "termsOfUse") == 0) { + return "termsOfUse"; + } else if (g_strcmp0 (v3_rejection_reason, + "uploaderAccountClosed") == 0 || + g_strcmp0 (v3_rejection_reason, + "uploaderAccountSuspended") == 0) { + return "duplicate"; + } else { + /* Generic fallback. */ + return "termsOfUse"; + } + } else if (g_strcmp0 (v2_name, "failed") == 0) { + if (g_strcmp0 (v3_failure_reason, "codec") == 0) { + return "unsupportedCodec"; + } else if (g_strcmp0 (v3_failure_reason, "conversion") == 0) { + return "invalidFormat"; + } else if (g_strcmp0 (v3_failure_reason, "emptyFile") == 0) { + return "empty"; + } else if (g_strcmp0 (v3_failure_reason, "tooSmall") == 0) { + return "tooSmall"; + } else { + return "cantProcess"; + } + } + + return NULL; +} + +/** + * gdata_youtube_video_get_state: + * @self: a #GDataYouTubeVideo + * + * Gets the #GDataYouTubeVideo:state property. + * + * For more information, see the online documentation. + * + * Return value: (transfer none): a #GDataYouTubeState showing the state of the video, or %NULL + */ +GDataYouTubeState * +gdata_youtube_video_get_state (GDataYouTubeVideo *self) +{ + GDataYouTubeVideoPrivate *priv; + + g_return_val_if_fail (GDATA_IS_YOUTUBE_VIDEO (self), NULL); + + priv = self->priv; + + /* Lazily create the state object. */ + if (priv->upload_state == NULL) { + const gchar *name, *reason_code; + + name = convert_state_name (priv->processing_status, + priv->upload_status); + reason_code = convert_state_reason_code (name, + priv->failure_reason, + priv->rejection_reason); + + priv->upload_state = g_object_new (GDATA_TYPE_YOUTUBE_STATE, + "name", name, + "reason-code", reason_code, + "help-uri", NULL, + "message", NULL, + NULL); + } + + return priv->upload_state; +} + +/** + * gdata_youtube_video_get_recorded: + * @self: a #GDataYouTubeVideo + * + * Gets the #GDataYouTubeVideo:recorded property. If the property is unset, -1 will be returned. + * + * Return value: the UNIX timestamp for the time the video was recorded, or -1 + * + * Since: 0.3.0 + */ +gint64 +gdata_youtube_video_get_recorded (GDataYouTubeVideo *self) +{ + g_return_val_if_fail (GDATA_IS_YOUTUBE_VIDEO (self), -1); + return self->priv->recorded; +} + +/** + * gdata_youtube_video_set_recorded: + * @self: a #GDataYouTubeVideo + * @recorded: the video's new recorded time, or -1 + * + * Sets the #GDataYouTubeVideo:recorded property to the new recorded time, @recorded. + * + * Set @recorded to -1 to unset the video's recorded time. + * + * Since: 0.3.0 + */ +void +gdata_youtube_video_set_recorded (GDataYouTubeVideo *self, gint64 recorded) +{ + g_return_if_fail (GDATA_IS_YOUTUBE_VIDEO (self)); + g_return_if_fail (recorded >= -1); + + self->priv->recorded = recorded; + g_object_notify (G_OBJECT (self), "recorded"); +} + +/** + * gdata_youtube_video_get_video_id_from_uri: + * @video_uri: a YouTube video player URI + * + * Extracts a video ID from a YouTube video player URI. The video ID is in the same form as returned by + * gdata_youtube_video_get_video_id(), and the @video_uri should be in the same form as returned by + * gdata_youtube_video_get_player_uri(). + * + * The function will validate whether the URI actually points to a hostname containing youtube + * (e.g. youtube.com), and will return %NULL if it doesn't. + * + * For example: + * + * video_id = gdata_youtube_video_get_video_id_from_uri ("http://www.youtube.com/watch?v=BH_vwsyCrTc&feature=featured"); + * g_message ("Video ID: %s", video_id); /* Should print: BH_vwsyCrTc */ + * g_free (video_id); + * + * + * Since: 0.4.0 + * + * Return value: the video ID, or %NULL; free with g_free() + */ +gchar * +gdata_youtube_video_get_video_id_from_uri (const gchar *video_uri) +{ + gchar *video_id = NULL; + SoupURI *uri; + + g_return_val_if_fail (video_uri != NULL && *video_uri != '\0', NULL); + + /* Extract the query string from the URI */ + uri = soup_uri_new (video_uri); + if (uri == NULL) + return NULL; + else if (uri->host == NULL || strstr (uri->host, "youtube") == NULL) { + soup_uri_free (uri); + return NULL; + } + + /* Try the "v" parameter (e.g. format is: http://www.youtube.com/watch?v=ylLzyHk54Z0) */ + if (uri->query != NULL) { + GHashTable *params = soup_form_decode (uri->query); + video_id = g_strdup (g_hash_table_lookup (params, "v")); + g_hash_table_destroy (params); + } + + /* Try the "v" fragment component (e.g. format is: http://www.youtube.com/watch#!v=ylLzyHk54Z0). + * YouTube introduced this new URI format in March 2010: + * http://apiblog.youtube.com/2010/03/upcoming-change-to-youtube-video-page.html */ + if (video_id == NULL && uri->fragment != NULL) { + gchar **components, **i; + + components = g_strsplit (uri->fragment, "!", -1); + for (i = components; *i != NULL; i++) { + if (**i == 'v' && *((*i) + 1) == '=') { + video_id = g_strdup ((*i) + 2); + break; + } + } + g_strfreev (components); + } + + soup_uri_free (uri); + + return video_id; +} + +/** + * gdata_youtube_video_get_aspect_ratio: + * @self: a #GDataYouTubeVideo + * + * Gets the #GDataYouTubeVideo:aspect-ratio property. + * + * Return value: the aspect ratio property, or %NULL + * + * Since: 0.4.0 + */ +const gchar * +gdata_youtube_video_get_aspect_ratio (GDataYouTubeVideo *self) +{ + g_return_val_if_fail (GDATA_IS_YOUTUBE_VIDEO (self), NULL); + + /* Permanently NULL for the moment, but let’s not deprecate the property + * because it looks like it might come in useful in future. */ + return NULL; +} + +/** + * gdata_youtube_video_set_aspect_ratio: + * @self: a #GDataYouTubeVideo + * @aspect_ratio: (allow-none): the aspect ratio property, or %NULL + * + * Sets the #GDataYouTubeVideo:aspect-ratio property to specify the video's aspect ratio. + * If @aspect_ratio is %NULL, the property will be unset. + * + * Since: 0.4.0 + */ +void +gdata_youtube_video_set_aspect_ratio (GDataYouTubeVideo *self, const gchar *aspect_ratio) +{ + g_return_if_fail (GDATA_IS_YOUTUBE_VIDEO (self)); + + /* Ignore it. See note in gdata_youtube_video_get_aspect_ratio(), + * above. */ +} + +/** + * gdata_youtube_video_get_coordinates: + * @self: a #GDataYouTubeVideo + * @latitude: (out caller-allocates) (allow-none): return location for the latitude, or %NULL + * @longitude: (out caller-allocates) (allow-none): return location for the longitude, or %NULL + * + * Gets the #GDataYouTubeVideo:latitude and #GDataYouTubeVideo:longitude properties, setting the out parameters to them. If either latitude or + * longitude is %NULL, that parameter will not be set. If the coordinates are unset, @latitude and @longitude will be set to %G_MAXDOUBLE. + * + * Since: 0.8.0 + */ +void +gdata_youtube_video_get_coordinates (GDataYouTubeVideo *self, gdouble *latitude, gdouble *longitude) +{ + g_return_if_fail (GDATA_IS_YOUTUBE_VIDEO (self)); + + if (latitude != NULL) { + *latitude = self->priv->latitude; + } + if (longitude != NULL) { + *longitude = self->priv->longitude; + } +} + +/** + * gdata_youtube_video_set_coordinates: + * @self: a #GDataYouTubeVideo + * @latitude: the video's new latitude coordinate, or %G_MAXDOUBLE + * @longitude: the video's new longitude coordinate, or %G_MAXDOUBLE + * + * Sets the #GDataYouTubeVideo:latitude and #GDataYouTubeVideo:longitude properties to @latitude and @longitude respectively. + * + * Since: 0.8.0 + */ +void +gdata_youtube_video_set_coordinates (GDataYouTubeVideo *self, gdouble latitude, gdouble longitude) +{ + g_return_if_fail (GDATA_IS_YOUTUBE_VIDEO (self)); + + self->priv->latitude = latitude; + self->priv->longitude = longitude; + + g_object_freeze_notify (G_OBJECT (self)); + g_object_notify (G_OBJECT (self), "latitude"); + g_object_notify (G_OBJECT (self), "longitude"); + g_object_thaw_notify (G_OBJECT (self)); +} diff --git a/gdata/services/youtube/gdata-youtube-video.h b/gdata/services/youtube/gdata-youtube-video.h new file mode 100644 index 0000000..da52633 --- /dev/null +++ b/gdata/services/youtube/gdata-youtube-video.h @@ -0,0 +1,238 @@ +/* -*- Mode: C; indent-tabs-mode: t; c-basic-offset: 8; tab-width: 8 -*- */ +/* + * GData Client + * Copyright (C) Philip Withnall 2008-2009, 2015 + * + * GData Client is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * GData Client is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with GData Client. If not, see . + */ + +#ifndef GDATA_YOUTUBE_VIDEO_H +#define GDATA_YOUTUBE_VIDEO_H + +#include +#include + +#include +#include +#include +#include +#include + +G_BEGIN_DECLS + +/** + * GDATA_YOUTUBE_ASPECT_RATIO_WIDESCREEN: + * + * The aspect ratio for widescreen (16:9) videos. + * + * For more information, see the + * online documentation. + * + * Since: 0.7.0 + */ +#define GDATA_YOUTUBE_ASPECT_RATIO_WIDESCREEN "widescreen" + +/** + * GDATA_YOUTUBE_ACTION_RATE: + * + * An action to rate a video, for use with gdata_youtube_video_set_access_control(). + * + * Since: 0.7.0 + */ +#define GDATA_YOUTUBE_ACTION_RATE "rate" + +/** + * GDATA_YOUTUBE_ACTION_COMMENT: + * + * An action to comment on a video, for use with gdata_youtube_video_set_access_control(). + * + * Since: 0.7.0 + */ +#define GDATA_YOUTUBE_ACTION_COMMENT "comment" + +/** + * GDATA_YOUTUBE_ACTION_COMMENT_VOTE: + * + * An action to rate other users' comments on a video, for use with gdata_youtube_video_set_access_control(). + * + * Since: 0.7.0 + */ +#define GDATA_YOUTUBE_ACTION_COMMENT_VOTE "commentVote" + +/** + * GDATA_YOUTUBE_ACTION_VIDEO_RESPOND: + * + * An action to add a video response to a video, for use with gdata_youtube_video_set_access_control(). + * + * Since: 0.7.0 + */ +#define GDATA_YOUTUBE_ACTION_VIDEO_RESPOND "videoRespond" + +/** + * GDATA_YOUTUBE_ACTION_EMBED: + * + * An action to embed a video on third-party websites, for use with gdata_youtube_video_set_access_control(). + * + * Since: 0.7.0 + */ +#define GDATA_YOUTUBE_ACTION_EMBED "embed" + +/** + * GDATA_YOUTUBE_ACTION_SYNDICATE: + * + * An action allowing YouTube to show the video on mobile phones and televisions, for use with gdata_youtube_video_set_access_control(). + * + * Since: 0.7.0 + */ +#define GDATA_YOUTUBE_ACTION_SYNDICATE "syndicate" + +#ifndef LIBGDATA_DISABLE_DEPRECATED +/** + * GDATA_YOUTUBE_RATING_TYPE_SIMPLE: + * + * A rating type to pass to gdata_youtube_video_get_media_rating() for “simple” ratings. The values which can be returned for such ratings are: + * adult and nonadult. + * + * Since: 0.10.0 + * Deprecated: 0.17.0: No longer supported by Google. Calling + * gdata_youtube_video_get_media_rating() with this rating type will always + * return %NULL. + */ +#define GDATA_YOUTUBE_RATING_TYPE_SIMPLE "simple" +#endif /* !LIBGDATA_DISABLE_DEPRECATED */ + +/** + * GDATA_YOUTUBE_RATING_TYPE_MPAA: + * + * A rating type to pass to gdata_youtube_video_get_media_rating() for ratings by the MPAA. The + * values which can be returned for such ratings are: g, pg, + * pg-13, r and nc-17. + * + * Since: 0.10.0 + */ +#define GDATA_YOUTUBE_RATING_TYPE_MPAA "mpaa" + +/** + * GDATA_YOUTUBE_RATING_TYPE_V_CHIP: + * + * A rating type to pass to gdata_youtube_video_get_media_rating() for ratings following the FCC + * V-Chip system. The values which can be returned for such ratings are: + * tv-y, tv-y7, tv-y7-fv, tv-g, + * tv-pg, tv-14 and tv-ma. + * + * Since: 0.10.0 + */ +#define GDATA_YOUTUBE_RATING_TYPE_V_CHIP "v-chip" + +/** + * GDataYouTubePermission: + * @GDATA_YOUTUBE_PERMISSION_ALLOWED: the action is allowed for everyone + * @GDATA_YOUTUBE_PERMISSION_DENIED: the action is denied for everyone + * @GDATA_YOUTUBE_PERMISSION_MODERATED: the action is moderated by the video owner + * + * Permissions for actions which can be set on a #GDataYouTubeVideo using gdata_youtube_video_set_access_control(). + * + * The only actions which can have the %GDATA_YOUTUBE_PERMISSION_MODERATED permission are + * %GDATA_YOUTUBE_ACTION_RATE and %GDATA_YOUTUBE_ACTION_COMMENT. + * + * Since: 0.7.0 + */ +typedef enum { + GDATA_YOUTUBE_PERMISSION_ALLOWED, + GDATA_YOUTUBE_PERMISSION_DENIED, + GDATA_YOUTUBE_PERMISSION_MODERATED +} GDataYouTubePermission; + +#define GDATA_TYPE_YOUTUBE_VIDEO (gdata_youtube_video_get_type ()) +#define GDATA_YOUTUBE_VIDEO(o) (G_TYPE_CHECK_INSTANCE_CAST ((o), GDATA_TYPE_YOUTUBE_VIDEO, GDataYouTubeVideo)) +#define GDATA_YOUTUBE_VIDEO_CLASS(k) (G_TYPE_CHECK_CLASS_CAST((k), GDATA_TYPE_YOUTUBE_VIDEO, GDataYouTubeVideoClass)) +#define GDATA_IS_YOUTUBE_VIDEO(o) (G_TYPE_CHECK_INSTANCE_TYPE ((o), GDATA_TYPE_YOUTUBE_VIDEO)) +#define GDATA_IS_YOUTUBE_VIDEO_CLASS(k) (G_TYPE_CHECK_CLASS_TYPE ((k), GDATA_TYPE_YOUTUBE_VIDEO)) +#define GDATA_YOUTUBE_VIDEO_GET_CLASS(o) (G_TYPE_INSTANCE_GET_CLASS ((o), GDATA_TYPE_YOUTUBE_VIDEO, GDataYouTubeVideoClass)) + +typedef struct _GDataYouTubeVideoPrivate GDataYouTubeVideoPrivate; + +/** + * GDataYouTubeVideo: + * + * All the fields in the #GDataYouTubeVideo structure are private and should never be accessed directly. + */ +typedef struct { + GDataEntry parent; + GDataYouTubeVideoPrivate *priv; +} GDataYouTubeVideo; + +/** + * GDataYouTubeVideoClass: + * + * All the fields in the #GDataYouTubeVideoClass structure are private and should never be accessed directly. + */ +typedef struct { + /*< private >*/ + GDataEntryClass parent; + + /*< private >*/ + /* Padding for future expansion */ + void (*_g_reserved0) (void); + void (*_g_reserved1) (void); +} GDataYouTubeVideoClass; + +GType gdata_youtube_video_get_type (void) G_GNUC_CONST; + +GDataYouTubeVideo *gdata_youtube_video_new (const gchar *id) G_GNUC_WARN_UNUSED_RESULT G_GNUC_MALLOC; + +guint gdata_youtube_video_get_view_count (GDataYouTubeVideo *self) G_GNUC_PURE; +guint gdata_youtube_video_get_favorite_count (GDataYouTubeVideo *self) G_GNUC_PURE; +const gchar *gdata_youtube_video_get_location (GDataYouTubeVideo *self) G_GNUC_PURE; +void gdata_youtube_video_set_location (GDataYouTubeVideo *self, const gchar *location); +GDataYouTubePermission gdata_youtube_video_get_access_control (GDataYouTubeVideo *self, const gchar *action) G_GNUC_PURE; +void gdata_youtube_video_set_access_control (GDataYouTubeVideo *self, const gchar *action, GDataYouTubePermission permission); +void gdata_youtube_video_get_rating (GDataYouTubeVideo *self, guint *min, guint *max, guint *count, gdouble *average); +const gchar * const *gdata_youtube_video_get_keywords (GDataYouTubeVideo *self) G_GNUC_PURE; +void gdata_youtube_video_set_keywords (GDataYouTubeVideo *self, const gchar * const *keywords); +const gchar *gdata_youtube_video_get_player_uri (GDataYouTubeVideo *self) G_GNUC_PURE; +gboolean gdata_youtube_video_is_restricted_in_country (GDataYouTubeVideo *self, const gchar *country) G_GNUC_PURE; +const gchar *gdata_youtube_video_get_media_rating (GDataYouTubeVideo *self, const gchar *rating_type) G_GNUC_PURE; +GDataMediaCategory *gdata_youtube_video_get_category (GDataYouTubeVideo *self) G_GNUC_PURE; +void gdata_youtube_video_set_category (GDataYouTubeVideo *self, GDataMediaCategory *category); +const gchar *gdata_youtube_video_get_description (GDataYouTubeVideo *self) G_GNUC_PURE; +void gdata_youtube_video_set_description (GDataYouTubeVideo *self, const gchar *description); +GList *gdata_youtube_video_get_thumbnails (GDataYouTubeVideo *self) G_GNUC_PURE; +guint gdata_youtube_video_get_duration (GDataYouTubeVideo *self) G_GNUC_PURE; +gboolean gdata_youtube_video_is_private (GDataYouTubeVideo *self) G_GNUC_PURE; +void gdata_youtube_video_set_is_private (GDataYouTubeVideo *self, gboolean is_private); +gint64 gdata_youtube_video_get_uploaded (GDataYouTubeVideo *self); +GDataYouTubeState *gdata_youtube_video_get_state (GDataYouTubeVideo *self) G_GNUC_PURE; +gint64 gdata_youtube_video_get_recorded (GDataYouTubeVideo *self); +void gdata_youtube_video_set_recorded (GDataYouTubeVideo *self, gint64 recorded); +const gchar *gdata_youtube_video_get_aspect_ratio (GDataYouTubeVideo *self) G_GNUC_PURE; +void gdata_youtube_video_set_aspect_ratio (GDataYouTubeVideo *self, const gchar *aspect_ratio); +void gdata_youtube_video_get_coordinates (GDataYouTubeVideo *self, gdouble *latitude, gdouble *longitude); +void gdata_youtube_video_set_coordinates (GDataYouTubeVideo *self, gdouble latitude, gdouble longitude); + +gchar *gdata_youtube_video_get_video_id_from_uri (const gchar *video_uri) G_GNUC_WARN_UNUSED_RESULT G_GNUC_MALLOC; + +#ifndef LIBGDATA_DISABLE_DEPRECATED +const gchar *gdata_youtube_video_get_video_id (GDataYouTubeVideo *self) G_GNUC_PURE G_GNUC_DEPRECATED_FOR(gdata_entry_get_id); +GDataYouTubeContent *gdata_youtube_video_look_up_content (GDataYouTubeVideo *self, const gchar *type) G_GNUC_PURE G_GNUC_DEPRECATED_FOR(gdata_youtube_video_get_player_uri); + +gboolean gdata_youtube_video_is_draft (GDataYouTubeVideo *self) G_GNUC_PURE G_GNUC_DEPRECATED_FOR(gdata_youtube_video_is_private); +void gdata_youtube_video_set_is_draft (GDataYouTubeVideo *self, gboolean is_draft) G_GNUC_DEPRECATED_FOR(gdata_youtube_video_set_is_private); + +GDataYouTubeCredit *gdata_youtube_video_get_credit (GDataYouTubeVideo *self) G_GNUC_PURE G_GNUC_DEPRECATED; +#endif /* !LIBGDATA_DISABLE_DEPRECATED */ + +G_END_DECLS + +#endif /* !GDATA_YOUTUBE_VIDEO_H */ diff --git a/gdata/services/youtube/meson.build b/gdata/services/youtube/meson.build new file mode 100644 index 0000000..84b2123 --- /dev/null +++ b/gdata/services/youtube/meson.build @@ -0,0 +1,62 @@ +incs += include_directories('.') + +include_subdir = gdata_include_subdir / 'services/youtube' + +headers = files( + 'gdata-youtube-category.h', + 'gdata-youtube-comment.h', + 'gdata-youtube-content.h', + 'gdata-youtube-credit.h', + 'gdata-youtube-feed.h', + 'gdata-youtube-query.h', + 'gdata-youtube-service.h', + 'gdata-youtube-state.h', + 'gdata-youtube-video.h', +) + +install_headers( + headers, + subdir: include_subdir, +) + +gir_headers += headers + +sources += files( + 'gdata-youtube-category.c', + 'gdata-youtube-comment.c', + 'gdata-youtube-content.c', + 'gdata-youtube-credit.c', + 'gdata-youtube-feed.c', + 'gdata-youtube-query.c', + 'gdata-youtube-service.c', + 'gdata-youtube-state.c', + 'gdata-youtube-video.c', +) + +enums = 'gdata-youtube-enums' + +enums_in = gnome.mkenums_simple( + enums + '-in', + sources: headers, +) + +# FIXME: Work around the namespace being incorrectly detected +# by glib-mkenums. This needs to be fixed by changing the +# namespace in libgdata. See !6. +sources += custom_target( + enums + '.c', + input: enums_in[0], + output: enums + '.c', + command: [sed, '-e', 's/-in//', '-e', 's/g_data_you_tube/gdata_youtube/', build_root / '@INPUT@'], + capture: true, +) + +enum_headers += custom_target( + enums + '.h', + input: enums_in[1], + output: enums + '.h', + command: [sed, '-e', 's/g_data_you_tube/gdata_youtube/', '-e', 's/G_TYPE_DATA_YOU_TUBE/GDATA_TYPE_YOUTUBE/', build_root / '@INPUT@'], + capture: true, + install: true, + install_dir: gdata_includedir / include_subdir, +) diff --git a/gdata/symbol.map b/gdata/symbol.map new file mode 100644 index 0000000..f8ab89c --- /dev/null +++ b/gdata/symbol.map @@ -0,0 +1,1147 @@ +{ +global: + gdata_access_handler_get_rules; + gdata_access_handler_get_rules_async; + gdata_access_handler_get_type; + gdata_access_rule_get_edited; + gdata_access_rule_get_key; + gdata_access_rule_get_role; + gdata_access_rule_get_scope; + gdata_access_rule_get_type; + gdata_access_rule_new; + gdata_access_rule_set_role; + gdata_access_rule_set_scope; + gdata_app_categories_get_categories; + gdata_app_categories_get_type; + gdata_app_categories_is_fixed; + gdata_author_get_email_address; + gdata_author_get_name; + gdata_author_get_type; + gdata_author_get_uri; + gdata_author_new; + gdata_author_set_email_address; + gdata_author_set_name; + gdata_author_set_uri; + gdata_authorization_domain_get_scope; + gdata_authorization_domain_get_service_name; + gdata_authorization_domain_get_type; + gdata_authorizer_get_type; + gdata_authorizer_is_authorized_for_domain; + gdata_authorizer_process_request; + gdata_authorizer_refresh_authorization; + gdata_authorizer_refresh_authorization_async; + gdata_authorizer_refresh_authorization_finish; + gdata_batch_operation_add_deletion; + gdata_batch_operation_add_insertion; + gdata_batch_operation_add_query; + gdata_batch_operation_add_update; + gdata_batch_operation_get_authorization_domain; + gdata_batch_operation_get_feed_uri; + gdata_batch_operation_get_service; + gdata_batch_operation_get_type; + gdata_batch_operation_run; + gdata_batch_operation_run_async; + gdata_batch_operation_run_finish; + gdata_batch_operation_type_get_type; + gdata_batchable_create_operation; + gdata_batchable_get_type; + gdata_calendar_access_rule_get_type; + gdata_calendar_access_rule_new; + gdata_calendar_calendar_get_access_level; + gdata_calendar_calendar_get_color; + gdata_calendar_calendar_get_edited; + gdata_calendar_calendar_get_times_cleaned; + gdata_calendar_calendar_get_timezone; + gdata_calendar_calendar_get_type; + gdata_calendar_calendar_is_hidden; + gdata_calendar_calendar_is_selected; + gdata_calendar_calendar_new; + gdata_calendar_calendar_set_color; + gdata_calendar_calendar_set_is_hidden; + gdata_calendar_calendar_set_is_selected; + gdata_calendar_calendar_set_timezone; + gdata_calendar_event_add_person; + gdata_calendar_event_add_place; + gdata_calendar_event_add_time; + gdata_calendar_event_get_anyone_can_add_self; + gdata_calendar_event_get_edited; + gdata_calendar_event_get_guests_can_invite_others; + gdata_calendar_event_get_guests_can_modify; + gdata_calendar_event_get_guests_can_see_guests; + gdata_calendar_event_get_original_event_details; + gdata_calendar_event_get_people; + gdata_calendar_event_get_places; + gdata_calendar_event_get_primary_time; + gdata_calendar_event_get_recurrence; + gdata_calendar_event_get_sequence; + gdata_calendar_event_get_status; + gdata_calendar_event_get_times; + gdata_calendar_event_get_transparency; + gdata_calendar_event_get_type; + gdata_calendar_event_get_uid; + gdata_calendar_event_get_visibility; + gdata_calendar_event_is_exception; + gdata_calendar_event_new; + gdata_calendar_event_set_anyone_can_add_self; + gdata_calendar_event_set_guests_can_invite_others; + gdata_calendar_event_set_guests_can_modify; + gdata_calendar_event_set_guests_can_see_guests; + gdata_calendar_event_set_recurrence; + gdata_calendar_event_set_sequence; + gdata_calendar_event_set_status; + gdata_calendar_event_set_transparency; + gdata_calendar_event_set_uid; + gdata_calendar_event_set_visibility; + gdata_calendar_feed_get_times_cleaned; + gdata_calendar_feed_get_timezone; + gdata_calendar_feed_get_type; + gdata_calendar_query_get_future_events; + gdata_calendar_query_get_max_attendees; + gdata_calendar_query_get_order_by; + gdata_calendar_query_get_recurrence_expansion_end; + gdata_calendar_query_get_recurrence_expansion_start; + gdata_calendar_query_get_single_events; + gdata_calendar_query_get_sort_order; + gdata_calendar_query_get_start_max; + gdata_calendar_query_get_start_min; + gdata_calendar_query_get_timezone; + gdata_calendar_query_get_type; + gdata_calendar_query_new; + gdata_calendar_query_new_with_limits; + gdata_calendar_query_set_future_events; + gdata_calendar_query_set_max_attendees; + gdata_calendar_query_set_order_by; + gdata_calendar_query_set_recurrence_expansion_end; + gdata_calendar_query_set_recurrence_expansion_start; + gdata_calendar_query_set_show_deleted; + gdata_calendar_query_set_single_events; + gdata_calendar_query_set_sort_order; + gdata_calendar_query_set_start_max; + gdata_calendar_query_set_start_min; + gdata_calendar_query_set_timezone; + gdata_calendar_query_show_deleted; + gdata_calendar_service_get_primary_authorization_domain; + gdata_calendar_service_get_type; + gdata_calendar_service_insert_calendar_event; + gdata_calendar_service_insert_calendar_event_async; + gdata_calendar_service_insert_event; + gdata_calendar_service_insert_event_async; + gdata_calendar_service_new; + gdata_calendar_service_query_all_calendars; + gdata_calendar_service_query_all_calendars_async; + gdata_calendar_service_query_events; + gdata_calendar_service_query_events_async; + gdata_calendar_service_query_own_calendars; + gdata_calendar_service_query_own_calendars_async; + gdata_category_get_label; + gdata_category_get_scheme; + gdata_category_get_term; + gdata_category_get_type; + gdata_category_new; + gdata_category_set_label; + gdata_category_set_scheme; + gdata_category_set_term; + gdata_client_login_authorizer_authenticate; + gdata_client_login_authorizer_authenticate_async; + gdata_client_login_authorizer_authenticate_finish; + gdata_client_login_authorizer_error_get_type; + gdata_client_login_authorizer_error_quark; + gdata_client_login_authorizer_get_client_id; + gdata_client_login_authorizer_get_password; + gdata_client_login_authorizer_get_proxy_resolver; + gdata_client_login_authorizer_get_proxy_uri; + gdata_client_login_authorizer_get_timeout; + gdata_client_login_authorizer_get_type; + gdata_client_login_authorizer_get_username; + gdata_client_login_authorizer_new; + gdata_client_login_authorizer_new_for_authorization_domains; + gdata_client_login_authorizer_set_proxy_resolver; + gdata_client_login_authorizer_set_proxy_uri; + gdata_client_login_authorizer_set_timeout; + gdata_color_from_hexadecimal; + gdata_color_get_type; + gdata_color_to_hexadecimal; + gdata_comment_get_type; + gdata_commentable_delete_comment; + gdata_commentable_delete_comment_async; + gdata_commentable_delete_comment_finish; + gdata_commentable_get_type; + gdata_commentable_insert_comment; + gdata_commentable_insert_comment_async; + gdata_commentable_insert_comment_finish; + gdata_commentable_query_comments; + gdata_commentable_query_comments_async; + gdata_commentable_query_comments_finish; + gdata_comparable_compare; + gdata_comparable_get_type; + gdata_contacts_contact_add_calendar; + gdata_contacts_contact_add_email_address; + gdata_contacts_contact_add_event; + gdata_contacts_contact_add_external_id; + gdata_contacts_contact_add_group; + gdata_contacts_contact_add_hobby; + gdata_contacts_contact_add_im_address; + gdata_contacts_contact_add_jot; + gdata_contacts_contact_add_language; + gdata_contacts_contact_add_organization; + gdata_contacts_contact_add_phone_number; + gdata_contacts_contact_add_postal_address; + gdata_contacts_contact_add_relation; + gdata_contacts_contact_add_website; + gdata_contacts_contact_get_billing_information; + gdata_contacts_contact_get_birthday; + gdata_contacts_contact_get_calendars; + gdata_contacts_contact_get_directory_server; + gdata_contacts_contact_get_edited; + gdata_contacts_contact_get_email_addresses; + gdata_contacts_contact_get_events; + gdata_contacts_contact_get_extended_properties; + gdata_contacts_contact_get_extended_property; + gdata_contacts_contact_get_external_ids; + gdata_contacts_contact_get_file_as; + gdata_contacts_contact_get_gender; + gdata_contacts_contact_get_groups; + gdata_contacts_contact_get_hobbies; + gdata_contacts_contact_get_im_addresses; + gdata_contacts_contact_get_initials; + gdata_contacts_contact_get_jots; + gdata_contacts_contact_get_languages; + gdata_contacts_contact_get_maiden_name; + gdata_contacts_contact_get_mileage; + gdata_contacts_contact_get_name; + gdata_contacts_contact_get_nickname; + gdata_contacts_contact_get_occupation; + gdata_contacts_contact_get_organizations; + gdata_contacts_contact_get_phone_numbers; + gdata_contacts_contact_get_photo; + gdata_contacts_contact_get_photo_async; + gdata_contacts_contact_get_photo_etag; + gdata_contacts_contact_get_photo_finish; + gdata_contacts_contact_get_postal_addresses; + gdata_contacts_contact_get_primary_calendar; + gdata_contacts_contact_get_primary_email_address; + gdata_contacts_contact_get_primary_im_address; + gdata_contacts_contact_get_primary_organization; + gdata_contacts_contact_get_primary_phone_number; + gdata_contacts_contact_get_primary_postal_address; + gdata_contacts_contact_get_primary_website; + gdata_contacts_contact_get_priority; + gdata_contacts_contact_get_relations; + gdata_contacts_contact_get_sensitivity; + gdata_contacts_contact_get_short_name; + gdata_contacts_contact_get_subject; + gdata_contacts_contact_get_type; + gdata_contacts_contact_get_user_defined_field; + gdata_contacts_contact_get_user_defined_fields; + gdata_contacts_contact_get_websites; + gdata_contacts_contact_is_deleted; + gdata_contacts_contact_is_group_deleted; + gdata_contacts_contact_new; + gdata_contacts_contact_remove_all_calendars; + gdata_contacts_contact_remove_all_email_addresses; + gdata_contacts_contact_remove_all_events; + gdata_contacts_contact_remove_all_external_ids; + gdata_contacts_contact_remove_all_hobbies; + gdata_contacts_contact_remove_all_im_addresses; + gdata_contacts_contact_remove_all_jots; + gdata_contacts_contact_remove_all_languages; + gdata_contacts_contact_remove_all_organizations; + gdata_contacts_contact_remove_all_phone_numbers; + gdata_contacts_contact_remove_all_postal_addresses; + gdata_contacts_contact_remove_all_relations; + gdata_contacts_contact_remove_all_websites; + gdata_contacts_contact_remove_group; + gdata_contacts_contact_set_billing_information; + gdata_contacts_contact_set_birthday; + gdata_contacts_contact_set_directory_server; + gdata_contacts_contact_set_extended_property; + gdata_contacts_contact_set_file_as; + gdata_contacts_contact_set_gender; + gdata_contacts_contact_set_initials; + gdata_contacts_contact_set_maiden_name; + gdata_contacts_contact_set_mileage; + gdata_contacts_contact_set_name; + gdata_contacts_contact_set_nickname; + gdata_contacts_contact_set_occupation; + gdata_contacts_contact_set_photo; + gdata_contacts_contact_set_photo_async; + gdata_contacts_contact_set_photo_finish; + gdata_contacts_contact_set_priority; + gdata_contacts_contact_set_sensitivity; + gdata_contacts_contact_set_short_name; + gdata_contacts_contact_set_subject; + gdata_contacts_contact_set_user_defined_field; + gdata_contacts_group_get_edited; + gdata_contacts_group_get_extended_properties; + gdata_contacts_group_get_extended_property; + gdata_contacts_group_get_system_group_id; + gdata_contacts_group_get_type; + gdata_contacts_group_is_deleted; + gdata_contacts_group_new; + gdata_contacts_group_set_extended_property; + gdata_contacts_query_get_group; + gdata_contacts_query_get_order_by; + gdata_contacts_query_get_sort_order; + gdata_contacts_query_get_type; + gdata_contacts_query_new; + gdata_contacts_query_new_with_limits; + gdata_contacts_query_set_group; + gdata_contacts_query_set_order_by; + gdata_contacts_query_set_show_deleted; + gdata_contacts_query_set_sort_order; + gdata_contacts_query_show_deleted; + gdata_contacts_service_get_primary_authorization_domain; + gdata_contacts_service_get_type; + gdata_contacts_service_insert_contact; + gdata_contacts_service_insert_contact_async; + gdata_contacts_service_insert_group; + gdata_contacts_service_insert_group_async; + gdata_contacts_service_new; + gdata_contacts_service_query_contacts; + gdata_contacts_service_query_contacts_async; + gdata_contacts_service_query_groups; + gdata_contacts_service_query_groups_async; + gdata_documents_access_rule_get_type; + gdata_documents_access_rule_new; + gdata_documents_document_download; + gdata_documents_document_get_download_uri; + gdata_documents_document_get_thumbnail_uri; + gdata_documents_document_get_type; + gdata_documents_document_new; + gdata_documents_drawing_get_type; + gdata_documents_drawing_new; + gdata_documents_entry_add_documents_property; + gdata_documents_entry_get_document_id; + gdata_documents_entry_get_document_properties; + gdata_documents_entry_get_edited; + gdata_documents_entry_get_file_size; + gdata_documents_entry_get_last_modified_by; + gdata_documents_entry_get_last_viewed; + gdata_documents_entry_get_path; + gdata_documents_entry_get_quota_used; + gdata_documents_entry_get_resource_id; + gdata_documents_entry_get_type; + gdata_documents_entry_is_deleted; + gdata_documents_entry_remove_documents_property; + gdata_documents_entry_set_writers_can_invite; + gdata_documents_entry_writers_can_invite; + gdata_documents_feed_get_type; + gdata_documents_folder_get_type; + gdata_documents_folder_new; + gdata_documents_metadata_get_quota_total; + gdata_documents_metadata_get_quota_used; + gdata_documents_metadata_get_type; + gdata_documents_pdf_get_type; + gdata_documents_pdf_new; + gdata_documents_presentation_get_type; + gdata_documents_presentation_new; + gdata_documents_property_get_etag; + gdata_documents_property_get_key; + gdata_documents_property_get_type; + gdata_documents_property_get_value; + gdata_documents_property_get_visibility; + gdata_documents_property_new; + gdata_documents_property_set_value; + gdata_documents_property_set_visibility; + gdata_documents_query_add_collaborator; + gdata_documents_query_add_reader; + gdata_documents_query_get_collaborator_addresses; + gdata_documents_query_get_exact_title; + gdata_documents_query_get_folder_id; + gdata_documents_query_get_reader_addresses; + gdata_documents_query_get_title; + gdata_documents_query_get_type; + gdata_documents_query_new; + gdata_documents_query_new_with_limits; + gdata_documents_query_set_folder_id; + gdata_documents_query_set_show_deleted; + gdata_documents_query_set_show_folders; + gdata_documents_query_set_title; + gdata_documents_query_show_deleted; + gdata_documents_query_show_folders; + gdata_documents_service_add_entry_to_folder; + gdata_documents_service_add_entry_to_folder_async; + gdata_documents_service_add_entry_to_folder_finish; + gdata_documents_service_copy_document; + gdata_documents_service_copy_document_async; + gdata_documents_service_copy_document_finish; + gdata_documents_service_error_get_type; + gdata_documents_service_error_quark; + gdata_documents_service_finish_upload; + gdata_documents_service_get_metadata; + gdata_documents_service_get_metadata_async; + gdata_documents_service_get_metadata_finish; + gdata_documents_service_get_primary_authorization_domain; + gdata_documents_service_get_spreadsheet_authorization_domain; + gdata_documents_service_get_type; + gdata_documents_service_get_upload_uri; + gdata_documents_service_new; + gdata_documents_service_query_documents; + gdata_documents_service_query_documents_async; + gdata_documents_service_remove_entry_from_folder; + gdata_documents_service_remove_entry_from_folder_async; + gdata_documents_service_remove_entry_from_folder_finish; + gdata_documents_service_update_document; + gdata_documents_service_update_document_resumable; + gdata_documents_service_upload_document; + gdata_documents_service_upload_document_resumable; + gdata_documents_spreadsheet_get_download_uri; + gdata_documents_spreadsheet_get_type; + gdata_documents_spreadsheet_new; + gdata_documents_text_get_type; + gdata_documents_text_new; + gdata_documents_upload_query_build_uri; + gdata_documents_upload_query_get_convert; + gdata_documents_upload_query_get_folder; + gdata_documents_upload_query_get_type; + gdata_documents_upload_query_new; + gdata_documents_upload_query_set_convert; + gdata_documents_upload_query_set_folder; + gdata_download_stream_get_authorization_domain; + gdata_download_stream_get_cancellable; + gdata_download_stream_get_content_length; + gdata_download_stream_get_content_type; + gdata_download_stream_get_download_uri; + gdata_download_stream_get_service; + gdata_download_stream_get_type; + gdata_download_stream_new; + gdata_entry_add_author; + gdata_entry_add_category; + gdata_entry_add_link; + gdata_entry_get_authors; + gdata_entry_get_categories; + gdata_entry_get_content; + gdata_entry_get_content_uri; + gdata_entry_get_etag; + gdata_entry_get_id; + gdata_entry_get_published; + gdata_entry_get_rights; + gdata_entry_get_summary; + gdata_entry_get_title; + gdata_entry_get_type; + gdata_entry_get_updated; + gdata_entry_is_inserted; + gdata_entry_look_up_link; + gdata_entry_look_up_links; + gdata_entry_new; + gdata_entry_remove_link; + gdata_entry_set_content; + gdata_entry_set_content_uri; + gdata_entry_set_rights; + gdata_entry_set_summary; + gdata_entry_set_title; + gdata_feed_get_authors; + gdata_feed_get_categories; + gdata_feed_get_entries; + gdata_feed_get_etag; + gdata_feed_get_generator; + gdata_feed_get_icon; + gdata_feed_get_id; + gdata_feed_get_items_per_page; + gdata_feed_get_links; + gdata_feed_get_logo; + gdata_feed_get_next_page_token; + gdata_feed_get_rights; + gdata_feed_get_start_index; + gdata_feed_get_subtitle; + gdata_feed_get_title; + gdata_feed_get_total_results; + gdata_feed_get_type; + gdata_feed_get_updated; + gdata_feed_look_up_entry; + gdata_feed_look_up_link; + gdata_freebase_query_get_type; + gdata_freebase_query_new; + gdata_freebase_query_new_from_variant; + gdata_freebase_result_dup_variant; + gdata_freebase_result_get_type; + gdata_freebase_result_new; + gdata_freebase_search_filter_type_get_type; + gdata_freebase_search_query_add_filter; + gdata_freebase_search_query_add_location; + gdata_freebase_search_query_close_filter; + gdata_freebase_search_query_get_language; + gdata_freebase_search_query_get_stemmed; + gdata_freebase_search_query_get_type; + gdata_freebase_search_query_new; + gdata_freebase_search_query_open_filter; + gdata_freebase_search_query_set_language; + gdata_freebase_search_query_set_stemmed; + gdata_freebase_search_result_get_item; + gdata_freebase_search_result_get_num_items; + gdata_freebase_search_result_get_total_hits; + gdata_freebase_search_result_get_type; + gdata_freebase_search_result_item_get_id; + gdata_freebase_search_result_item_get_language; + gdata_freebase_search_result_item_get_mid; + gdata_freebase_search_result_item_get_name; + gdata_freebase_search_result_item_get_notable_id; + gdata_freebase_search_result_item_get_notable_name; + gdata_freebase_search_result_item_get_score; + gdata_freebase_search_result_item_get_type; + gdata_freebase_search_result_new; + gdata_freebase_service_get_image; + gdata_freebase_service_get_topic; + gdata_freebase_service_get_topic_async; + gdata_freebase_service_get_type; + gdata_freebase_service_new; + gdata_freebase_service_query; + gdata_freebase_service_query_async; + gdata_freebase_service_search; + gdata_freebase_service_search_async; + gdata_freebase_topic_object_get_id; + gdata_freebase_topic_object_get_property_count; + gdata_freebase_topic_object_get_property_hits; + gdata_freebase_topic_object_get_property_value; + gdata_freebase_topic_object_get_type; + gdata_freebase_topic_object_list_properties; + gdata_freebase_topic_object_ref; + gdata_freebase_topic_object_unref; + gdata_freebase_topic_query_get_filter; + gdata_freebase_topic_query_get_language; + gdata_freebase_topic_query_get_type; + gdata_freebase_topic_query_new; + gdata_freebase_topic_query_set_filter; + gdata_freebase_topic_query_set_language; + gdata_freebase_topic_result_dup_object; + gdata_freebase_topic_result_get_type; + gdata_freebase_topic_result_new; + gdata_freebase_topic_value_copy_value; + gdata_freebase_topic_value_get_creator; + gdata_freebase_topic_value_get_double; + gdata_freebase_topic_value_get_int; + gdata_freebase_topic_value_get_language; + gdata_freebase_topic_value_get_object; + gdata_freebase_topic_value_get_property; + gdata_freebase_topic_value_get_string; + gdata_freebase_topic_value_get_text; + gdata_freebase_topic_value_get_timestamp; + gdata_freebase_topic_value_get_type; + gdata_freebase_topic_value_get_value_type; + gdata_freebase_topic_value_is_image; + gdata_freebase_topic_value_ref; + gdata_freebase_topic_value_unref; + gdata_gcontact_calendar_get_label; + gdata_gcontact_calendar_get_relation_type; + gdata_gcontact_calendar_get_type; + gdata_gcontact_calendar_get_uri; + gdata_gcontact_calendar_is_primary; + gdata_gcontact_calendar_new; + gdata_gcontact_calendar_set_is_primary; + gdata_gcontact_calendar_set_label; + gdata_gcontact_calendar_set_relation_type; + gdata_gcontact_calendar_set_uri; + gdata_gcontact_event_get_date; + gdata_gcontact_event_get_label; + gdata_gcontact_event_get_relation_type; + gdata_gcontact_event_get_type; + gdata_gcontact_event_new; + gdata_gcontact_event_set_date; + gdata_gcontact_event_set_label; + gdata_gcontact_event_set_relation_type; + gdata_gcontact_external_id_get_label; + gdata_gcontact_external_id_get_relation_type; + gdata_gcontact_external_id_get_type; + gdata_gcontact_external_id_get_value; + gdata_gcontact_external_id_new; + gdata_gcontact_external_id_set_label; + gdata_gcontact_external_id_set_relation_type; + gdata_gcontact_external_id_set_value; + gdata_gcontact_jot_get_content; + gdata_gcontact_jot_get_relation_type; + gdata_gcontact_jot_get_type; + gdata_gcontact_jot_new; + gdata_gcontact_jot_set_content; + gdata_gcontact_jot_set_relation_type; + gdata_gcontact_language_get_code; + gdata_gcontact_language_get_label; + gdata_gcontact_language_get_type; + gdata_gcontact_language_new; + gdata_gcontact_language_set_code; + gdata_gcontact_language_set_label; + gdata_gcontact_relation_get_label; + gdata_gcontact_relation_get_name; + gdata_gcontact_relation_get_relation_type; + gdata_gcontact_relation_get_type; + gdata_gcontact_relation_new; + gdata_gcontact_relation_set_label; + gdata_gcontact_relation_set_name; + gdata_gcontact_relation_set_relation_type; + gdata_gcontact_website_get_label; + gdata_gcontact_website_get_relation_type; + gdata_gcontact_website_get_type; + gdata_gcontact_website_get_uri; + gdata_gcontact_website_is_primary; + gdata_gcontact_website_new; + gdata_gcontact_website_set_is_primary; + gdata_gcontact_website_set_label; + gdata_gcontact_website_set_relation_type; + gdata_gcontact_website_set_uri; + gdata_gd_email_address_get_address; + gdata_gd_email_address_get_display_name; + gdata_gd_email_address_get_label; + gdata_gd_email_address_get_relation_type; + gdata_gd_email_address_get_type; + gdata_gd_email_address_is_primary; + gdata_gd_email_address_new; + gdata_gd_email_address_set_address; + gdata_gd_email_address_set_display_name; + gdata_gd_email_address_set_is_primary; + gdata_gd_email_address_set_label; + gdata_gd_email_address_set_relation_type; + gdata_gd_im_address_get_address; + gdata_gd_im_address_get_label; + gdata_gd_im_address_get_protocol; + gdata_gd_im_address_get_relation_type; + gdata_gd_im_address_get_type; + gdata_gd_im_address_is_primary; + gdata_gd_im_address_new; + gdata_gd_im_address_set_address; + gdata_gd_im_address_set_is_primary; + gdata_gd_im_address_set_label; + gdata_gd_im_address_set_protocol; + gdata_gd_im_address_set_relation_type; + gdata_gd_name_get_additional_name; + gdata_gd_name_get_family_name; + gdata_gd_name_get_full_name; + gdata_gd_name_get_given_name; + gdata_gd_name_get_prefix; + gdata_gd_name_get_suffix; + gdata_gd_name_get_type; + gdata_gd_name_new; + gdata_gd_name_set_additional_name; + gdata_gd_name_set_family_name; + gdata_gd_name_set_full_name; + gdata_gd_name_set_given_name; + gdata_gd_name_set_prefix; + gdata_gd_name_set_suffix; + gdata_gd_organization_get_department; + gdata_gd_organization_get_job_description; + gdata_gd_organization_get_label; + gdata_gd_organization_get_location; + gdata_gd_organization_get_name; + gdata_gd_organization_get_relation_type; + gdata_gd_organization_get_symbol; + gdata_gd_organization_get_title; + gdata_gd_organization_get_type; + gdata_gd_organization_is_primary; + gdata_gd_organization_new; + gdata_gd_organization_set_department; + gdata_gd_organization_set_is_primary; + gdata_gd_organization_set_job_description; + gdata_gd_organization_set_label; + gdata_gd_organization_set_location; + gdata_gd_organization_set_name; + gdata_gd_organization_set_relation_type; + gdata_gd_organization_set_symbol; + gdata_gd_organization_set_title; + gdata_gd_phone_number_get_label; + gdata_gd_phone_number_get_number; + gdata_gd_phone_number_get_relation_type; + gdata_gd_phone_number_get_type; + gdata_gd_phone_number_get_uri; + gdata_gd_phone_number_is_primary; + gdata_gd_phone_number_new; + gdata_gd_phone_number_set_is_primary; + gdata_gd_phone_number_set_label; + gdata_gd_phone_number_set_number; + gdata_gd_phone_number_set_relation_type; + gdata_gd_phone_number_set_uri; + gdata_gd_postal_address_get_address; + gdata_gd_postal_address_get_agent; + gdata_gd_postal_address_get_city; + gdata_gd_postal_address_get_country; + gdata_gd_postal_address_get_country_code; + gdata_gd_postal_address_get_house_name; + gdata_gd_postal_address_get_label; + gdata_gd_postal_address_get_mail_class; + gdata_gd_postal_address_get_neighborhood; + gdata_gd_postal_address_get_po_box; + gdata_gd_postal_address_get_postcode; + gdata_gd_postal_address_get_region; + gdata_gd_postal_address_get_relation_type; + gdata_gd_postal_address_get_street; + gdata_gd_postal_address_get_subregion; + gdata_gd_postal_address_get_type; + gdata_gd_postal_address_get_usage; + gdata_gd_postal_address_is_primary; + gdata_gd_postal_address_new; + gdata_gd_postal_address_set_address; + gdata_gd_postal_address_set_agent; + gdata_gd_postal_address_set_city; + gdata_gd_postal_address_set_country; + gdata_gd_postal_address_set_house_name; + gdata_gd_postal_address_set_is_primary; + gdata_gd_postal_address_set_label; + gdata_gd_postal_address_set_mail_class; + gdata_gd_postal_address_set_neighborhood; + gdata_gd_postal_address_set_po_box; + gdata_gd_postal_address_set_postcode; + gdata_gd_postal_address_set_region; + gdata_gd_postal_address_set_relation_type; + gdata_gd_postal_address_set_street; + gdata_gd_postal_address_set_subregion; + gdata_gd_postal_address_set_usage; + gdata_gd_reminder_get_absolute_time; + gdata_gd_reminder_get_method; + gdata_gd_reminder_get_relative_time; + gdata_gd_reminder_get_type; + gdata_gd_reminder_is_absolute_time; + gdata_gd_reminder_new; + gdata_gd_reminder_set_absolute_time; + gdata_gd_reminder_set_method; + gdata_gd_reminder_set_relative_time; + gdata_gd_when_add_reminder; + gdata_gd_when_get_end_time; + gdata_gd_when_get_reminders; + gdata_gd_when_get_start_time; + gdata_gd_when_get_type; + gdata_gd_when_get_value_string; + gdata_gd_when_is_date; + gdata_gd_when_new; + gdata_gd_when_set_end_time; + gdata_gd_when_set_is_date; + gdata_gd_when_set_start_time; + gdata_gd_when_set_value_string; + gdata_gd_where_get_label; + gdata_gd_where_get_relation_type; + gdata_gd_where_get_type; + gdata_gd_where_get_value_string; + gdata_gd_where_new; + gdata_gd_where_set_label; + gdata_gd_where_set_relation_type; + gdata_gd_where_set_value_string; + gdata_gd_who_get_email_address; + gdata_gd_who_get_relation_type; + gdata_gd_who_get_type; + gdata_gd_who_get_value_string; + gdata_gd_who_new; + gdata_gd_who_set_email_address; + gdata_gd_who_set_relation_type; + gdata_gd_who_set_value_string; + gdata_generator_get_name; + gdata_generator_get_type; + gdata_generator_get_uri; + gdata_generator_get_version; + gdata_goa_authorizer_get_goa_object; + gdata_goa_authorizer_get_type; + gdata_goa_authorizer_new; + gdata_link_get_content_type; + gdata_link_get_language; + gdata_link_get_length; + gdata_link_get_relation_type; + gdata_link_get_title; + gdata_link_get_type; + gdata_link_get_uri; + gdata_link_new; + gdata_link_set_content_type; + gdata_link_set_language; + gdata_link_set_length; + gdata_link_set_relation_type; + gdata_link_set_title; + gdata_link_set_uri; + gdata_media_category_get_category; + gdata_media_category_get_label; + gdata_media_category_get_scheme; + gdata_media_category_get_type; + gdata_media_category_new; + gdata_media_category_set_category; + gdata_media_category_set_label; + gdata_media_category_set_scheme; + gdata_media_content_download; + gdata_media_content_get_content_type; + gdata_media_content_get_duration; + gdata_media_content_get_expression; + gdata_media_content_get_filesize; + gdata_media_content_get_height; + gdata_media_content_get_medium; + gdata_media_content_get_type; + gdata_media_content_get_uri; + gdata_media_content_get_width; + gdata_media_content_is_default; + gdata_media_credit_get_credit; + gdata_media_credit_get_role; + gdata_media_credit_get_scheme; + gdata_media_credit_get_type; + gdata_media_expression_get_type; + gdata_media_medium_get_type; + gdata_media_thumbnail_download; + gdata_media_thumbnail_get_height; + gdata_media_thumbnail_get_time; + gdata_media_thumbnail_get_type; + gdata_media_thumbnail_get_uri; + gdata_media_thumbnail_get_width; + gdata_oauth1_authorizer_get_application_name; + gdata_oauth1_authorizer_get_locale; + gdata_oauth1_authorizer_get_proxy_resolver; + gdata_oauth1_authorizer_get_proxy_uri; + gdata_oauth1_authorizer_get_timeout; + gdata_oauth1_authorizer_get_type; + gdata_oauth1_authorizer_new; + gdata_oauth1_authorizer_new_for_authorization_domains; + gdata_oauth1_authorizer_request_authentication_uri; + gdata_oauth1_authorizer_request_authentication_uri_async; + gdata_oauth1_authorizer_request_authentication_uri_finish; + gdata_oauth1_authorizer_request_authorization; + gdata_oauth1_authorizer_request_authorization_async; + gdata_oauth1_authorizer_request_authorization_finish; + gdata_oauth1_authorizer_set_locale; + gdata_oauth1_authorizer_set_proxy_resolver; + gdata_oauth1_authorizer_set_proxy_uri; + gdata_oauth1_authorizer_set_timeout; + gdata_oauth2_authorizer_build_authentication_uri; + gdata_oauth2_authorizer_dup_refresh_token; + gdata_oauth2_authorizer_get_client_id; + gdata_oauth2_authorizer_get_client_secret; + gdata_oauth2_authorizer_get_locale; + gdata_oauth2_authorizer_get_proxy_resolver; + gdata_oauth2_authorizer_get_redirect_uri; + gdata_oauth2_authorizer_get_timeout; + gdata_oauth2_authorizer_get_type; + gdata_oauth2_authorizer_new; + gdata_oauth2_authorizer_new_for_authorization_domains; + gdata_oauth2_authorizer_request_authorization; + gdata_oauth2_authorizer_request_authorization_async; + gdata_oauth2_authorizer_request_authorization_finish; + gdata_oauth2_authorizer_set_locale; + gdata_oauth2_authorizer_set_proxy_resolver; + gdata_oauth2_authorizer_set_refresh_token; + gdata_oauth2_authorizer_set_timeout; + gdata_operation_type_get_type; + gdata_parsable_get_content_type; + gdata_parsable_get_json; + gdata_parsable_get_type; + gdata_parsable_get_xml; + gdata_parsable_new_from_json; + gdata_parsable_new_from_xml; + gdata_parser_error_get_type; + gdata_parser_error_quark; + gdata_picasaweb_album_get_bytes_used; + gdata_picasaweb_album_get_comment_count; + gdata_picasaweb_album_get_contents; + gdata_picasaweb_album_get_coordinates; + gdata_picasaweb_album_get_edited; + gdata_picasaweb_album_get_id; + gdata_picasaweb_album_get_location; + gdata_picasaweb_album_get_nickname; + gdata_picasaweb_album_get_num_photos; + gdata_picasaweb_album_get_num_photos_remaining; + gdata_picasaweb_album_get_tags; + gdata_picasaweb_album_get_thumbnails; + gdata_picasaweb_album_get_timestamp; + gdata_picasaweb_album_get_type; + gdata_picasaweb_album_get_user; + gdata_picasaweb_album_get_visibility; + gdata_picasaweb_album_is_commenting_enabled; + gdata_picasaweb_album_new; + gdata_picasaweb_album_set_coordinates; + gdata_picasaweb_album_set_is_commenting_enabled; + gdata_picasaweb_album_set_location; + gdata_picasaweb_album_set_tags; + gdata_picasaweb_album_set_timestamp; + gdata_picasaweb_album_set_visibility; + gdata_picasaweb_comment_get_type; + gdata_picasaweb_comment_new; + gdata_picasaweb_feed_get_type; + gdata_picasaweb_file_get_album_id; + gdata_picasaweb_file_get_caption; + gdata_picasaweb_file_get_checksum; + gdata_picasaweb_file_get_comment_count; + gdata_picasaweb_file_get_contents; + gdata_picasaweb_file_get_coordinates; + gdata_picasaweb_file_get_credit; + gdata_picasaweb_file_get_distance; + gdata_picasaweb_file_get_edited; + gdata_picasaweb_file_get_exposure; + gdata_picasaweb_file_get_flash; + gdata_picasaweb_file_get_focal_length; + gdata_picasaweb_file_get_fstop; + gdata_picasaweb_file_get_height; + gdata_picasaweb_file_get_id; + gdata_picasaweb_file_get_image_unique_id; + gdata_picasaweb_file_get_iso; + gdata_picasaweb_file_get_make; + gdata_picasaweb_file_get_model; + gdata_picasaweb_file_get_rotation; + gdata_picasaweb_file_get_size; + gdata_picasaweb_file_get_tags; + gdata_picasaweb_file_get_thumbnails; + gdata_picasaweb_file_get_timestamp; + gdata_picasaweb_file_get_type; + gdata_picasaweb_file_get_version; + gdata_picasaweb_file_get_video_status; + gdata_picasaweb_file_get_width; + gdata_picasaweb_file_is_commenting_enabled; + gdata_picasaweb_file_new; + gdata_picasaweb_file_set_album_id; + gdata_picasaweb_file_set_caption; + gdata_picasaweb_file_set_checksum; + gdata_picasaweb_file_set_coordinates; + gdata_picasaweb_file_set_is_commenting_enabled; + gdata_picasaweb_file_set_rotation; + gdata_picasaweb_file_set_tags; + gdata_picasaweb_file_set_timestamp; + gdata_picasaweb_query_get_bounding_box; + gdata_picasaweb_query_get_image_size; + gdata_picasaweb_query_get_location; + gdata_picasaweb_query_get_tag; + gdata_picasaweb_query_get_thumbnail_size; + gdata_picasaweb_query_get_type; + gdata_picasaweb_query_get_visibility; + gdata_picasaweb_query_new; + gdata_picasaweb_query_new_with_limits; + gdata_picasaweb_query_set_bounding_box; + gdata_picasaweb_query_set_image_size; + gdata_picasaweb_query_set_location; + gdata_picasaweb_query_set_tag; + gdata_picasaweb_query_set_thumbnail_size; + gdata_picasaweb_query_set_visibility; + gdata_picasaweb_service_finish_file_upload; + gdata_picasaweb_service_get_primary_authorization_domain; + gdata_picasaweb_service_get_type; + gdata_picasaweb_service_get_user; + gdata_picasaweb_service_get_user_async; + gdata_picasaweb_service_get_user_finish; + gdata_picasaweb_service_insert_album; + gdata_picasaweb_service_insert_album_async; + gdata_picasaweb_service_new; + gdata_picasaweb_service_query_all_albums; + gdata_picasaweb_service_query_all_albums_async; + gdata_picasaweb_service_query_files; + gdata_picasaweb_service_query_files_async; + gdata_picasaweb_service_upload_file; + gdata_picasaweb_user_get_max_photos_per_album; + gdata_picasaweb_user_get_nickname; + gdata_picasaweb_user_get_quota_current; + gdata_picasaweb_user_get_quota_limit; + gdata_picasaweb_user_get_thumbnail_uri; + gdata_picasaweb_user_get_type; + gdata_picasaweb_user_get_user; + gdata_picasaweb_visibility_get_type; + gdata_query_get_author; + gdata_query_get_categories; + gdata_query_get_etag; + gdata_query_get_max_results; + gdata_query_get_published_max; + gdata_query_get_published_min; + gdata_query_get_q; + gdata_query_get_query_uri; + gdata_query_get_start_index; + gdata_query_get_type; + gdata_query_get_updated_max; + gdata_query_get_updated_min; + gdata_query_is_strict; + gdata_query_new; + gdata_query_new_with_limits; + gdata_query_next_page; + gdata_query_previous_page; + gdata_query_set_author; + gdata_query_set_categories; + gdata_query_set_etag; + gdata_query_set_is_strict; + gdata_query_set_max_results; + gdata_query_set_published_max; + gdata_query_set_published_min; + gdata_query_set_q; + gdata_query_set_start_index; + gdata_query_set_updated_max; + gdata_query_set_updated_min; + gdata_service_delete_entry; + gdata_service_delete_entry_async; + gdata_service_delete_entry_finish; + gdata_service_error_get_type; + gdata_service_error_quark; + gdata_service_get_authorization_domains; + gdata_service_get_authorizer; + gdata_service_get_locale; + gdata_service_get_proxy_resolver; + gdata_service_get_proxy_uri; + gdata_service_get_timeout; + gdata_service_get_type; + gdata_service_insert_entry; + gdata_service_insert_entry_async; + gdata_service_insert_entry_finish; + gdata_service_is_authorized; + gdata_service_query; + gdata_service_query_async; + gdata_service_query_finish; + gdata_service_query_single_entry; + gdata_service_query_single_entry_async; + gdata_service_query_single_entry_finish; + gdata_service_set_authorizer; + gdata_service_set_locale; + gdata_service_set_proxy_resolver; + gdata_service_set_proxy_uri; + gdata_service_set_timeout; + gdata_service_update_entry; + gdata_service_update_entry_async; + gdata_service_update_entry_finish; + gdata_tasks_query_get_completed_max; + gdata_tasks_query_get_completed_min; + gdata_tasks_query_get_due_max; + gdata_tasks_query_get_due_min; + gdata_tasks_query_get_show_completed; + gdata_tasks_query_get_show_deleted; + gdata_tasks_query_get_show_hidden; + gdata_tasks_query_get_type; + gdata_tasks_query_new; + gdata_tasks_query_set_completed_max; + gdata_tasks_query_set_completed_min; + gdata_tasks_query_set_due_max; + gdata_tasks_query_set_due_min; + gdata_tasks_query_set_show_completed; + gdata_tasks_query_set_show_deleted; + gdata_tasks_query_set_show_hidden; + gdata_tasks_service_delete_task; + gdata_tasks_service_delete_task_async; + gdata_tasks_service_delete_tasklist; + gdata_tasks_service_delete_tasklist_async; + gdata_tasks_service_get_primary_authorization_domain; + gdata_tasks_service_get_type; + gdata_tasks_service_insert_task; + gdata_tasks_service_insert_task_async; + gdata_tasks_service_insert_tasklist; + gdata_tasks_service_insert_tasklist_async; + gdata_tasks_service_new; + gdata_tasks_service_query_all_tasklists; + gdata_tasks_service_query_all_tasklists_async; + gdata_tasks_service_query_tasks; + gdata_tasks_service_query_tasks_async; + gdata_tasks_service_update_task; + gdata_tasks_service_update_task_async; + gdata_tasks_service_update_tasklist; + gdata_tasks_service_update_tasklist_async; + gdata_tasks_task_get_completed; + gdata_tasks_task_get_due; + gdata_tasks_task_get_notes; + gdata_tasks_task_get_parent; + gdata_tasks_task_get_position; + gdata_tasks_task_get_status; + gdata_tasks_task_get_type; + gdata_tasks_task_is_deleted; + gdata_tasks_task_is_hidden; + gdata_tasks_task_new; + gdata_tasks_task_set_completed; + gdata_tasks_task_set_due; + gdata_tasks_task_set_is_deleted; + gdata_tasks_task_set_notes; + gdata_tasks_task_set_parent; + gdata_tasks_task_set_position; + gdata_tasks_task_set_status; + gdata_tasks_tasklist_get_type; + gdata_tasks_tasklist_new; + gdata_upload_stream_get_authorization_domain; + gdata_upload_stream_get_cancellable; + gdata_upload_stream_get_content_length; + gdata_upload_stream_get_content_type; + gdata_upload_stream_get_entry; + gdata_upload_stream_get_method; + gdata_upload_stream_get_service; + gdata_upload_stream_get_slug; + gdata_upload_stream_get_type; + gdata_upload_stream_get_upload_uri; + gdata_upload_stream_new; + gdata_upload_stream_new_resumable; + gdata_youtube_age_get_type; + gdata_youtube_category_get_type; + gdata_youtube_category_is_assignable; + gdata_youtube_category_is_browsable; + gdata_youtube_category_is_deprecated; + gdata_youtube_comment_get_parent_comment_uri; + gdata_youtube_comment_get_type; + gdata_youtube_comment_new; + gdata_youtube_comment_set_parent_comment_uri; + gdata_youtube_content_get_format; + gdata_youtube_content_get_type; + gdata_youtube_credit_get_entity_type; + gdata_youtube_credit_get_type; + gdata_youtube_feed_get_type; + gdata_youtube_format_get_type; + gdata_youtube_permission_get_type; + gdata_youtube_query_get_age; + gdata_youtube_query_get_format; + gdata_youtube_query_get_language; + gdata_youtube_query_get_license; + gdata_youtube_query_get_location; + gdata_youtube_query_get_order_by; + gdata_youtube_query_get_restriction; + gdata_youtube_query_get_safe_search; + gdata_youtube_query_get_sort_order; + gdata_youtube_query_get_type; + gdata_youtube_query_get_uploader; + gdata_youtube_query_new; + gdata_youtube_query_set_age; + gdata_youtube_query_set_format; + gdata_youtube_query_set_language; + gdata_youtube_query_set_license; + gdata_youtube_query_set_location; + gdata_youtube_query_set_order_by; + gdata_youtube_query_set_restriction; + gdata_youtube_query_set_safe_search; + gdata_youtube_query_set_sort_order; + gdata_youtube_query_set_uploader; + gdata_youtube_safe_search_get_type; + gdata_youtube_service_error_get_type; + gdata_youtube_service_error_quark; + gdata_youtube_service_finish_video_upload; + gdata_youtube_service_get_categories; + gdata_youtube_service_get_categories_async; + gdata_youtube_service_get_categories_finish; + gdata_youtube_service_get_developer_key; + gdata_youtube_service_get_primary_authorization_domain; + gdata_youtube_service_get_type; + gdata_youtube_service_new; + gdata_youtube_service_query_related; + gdata_youtube_service_query_related_async; + gdata_youtube_service_query_standard_feed; + gdata_youtube_service_query_standard_feed_async; + gdata_youtube_service_query_videos; + gdata_youtube_service_query_videos_async; + gdata_youtube_service_upload_video; + gdata_youtube_sort_order_get_type; + gdata_youtube_standard_feed_type_get_type; + gdata_youtube_state_get_help_uri; + gdata_youtube_state_get_message; + gdata_youtube_state_get_name; + gdata_youtube_state_get_reason_code; + gdata_youtube_state_get_type; + gdata_youtube_uploader_get_type; + gdata_youtube_video_get_access_control; + gdata_youtube_video_get_aspect_ratio; + gdata_youtube_video_get_category; + gdata_youtube_video_get_coordinates; + gdata_youtube_video_get_credit; + gdata_youtube_video_get_description; + gdata_youtube_video_get_duration; + gdata_youtube_video_get_favorite_count; + gdata_youtube_video_get_keywords; + gdata_youtube_video_get_location; + gdata_youtube_video_get_media_rating; + gdata_youtube_video_get_player_uri; + gdata_youtube_video_get_rating; + gdata_youtube_video_get_recorded; + gdata_youtube_video_get_state; + gdata_youtube_video_get_thumbnails; + gdata_youtube_video_get_type; + gdata_youtube_video_get_uploaded; + gdata_youtube_video_get_video_id; + gdata_youtube_video_get_video_id_from_uri; + gdata_youtube_video_get_view_count; + gdata_youtube_video_is_draft; + gdata_youtube_video_is_private; + gdata_youtube_video_is_restricted_in_country; + gdata_youtube_video_look_up_content; + gdata_youtube_video_new; + gdata_youtube_video_set_access_control; + gdata_youtube_video_set_aspect_ratio; + gdata_youtube_video_set_category; + gdata_youtube_video_set_coordinates; + gdata_youtube_video_set_description; + gdata_youtube_video_set_is_draft; + gdata_youtube_video_set_is_private; + gdata_youtube_video_set_keywords; + gdata_youtube_video_set_location; + gdata_youtube_video_set_recorded; +local: + *; +}; diff --git a/gdata/tests/authorization.c b/gdata/tests/authorization.c new file mode 100644 index 0000000..61e49e4 --- /dev/null +++ b/gdata/tests/authorization.c @@ -0,0 +1,793 @@ +/* -*- Mode: C; indent-tabs-mode: t; c-basic-offset: 8; tab-width: 8 -*- */ +/* + * GData Client + * Copyright (C) Philip Withnall 2011 + * + * GData Client is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * GData Client is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with GData Client. If not, see . + */ + +#include +#include +#include + +#include "common.h" + +/* Used as common "testing domains" to simplify test code. */ +static GDataAuthorizationDomain *test_domain1 = NULL; +static GDataAuthorizationDomain *test_domain2 = NULL; + +static void +test_authorization_domain_properties (void) +{ + GDataAuthorizationDomain *domain; + gchar *service_name, *scope; + + /* NOTE: It's not expected that client code will normally get hold of GDataAuthorizationDomain instances this way. + * This is just for testing purposes. */ + domain = GDATA_AUTHORIZATION_DOMAIN (g_object_new (GDATA_TYPE_AUTHORIZATION_DOMAIN, + "service-name", "service-name", + "scope", "scope", + NULL)); + + g_assert_cmpstr (gdata_authorization_domain_get_service_name (domain), ==, "service-name"); + g_assert_cmpstr (gdata_authorization_domain_get_scope (domain), ==, "scope"); + + g_object_get (domain, + "service-name", &service_name, + "scope", &scope, + NULL); + + g_assert_cmpstr (service_name, ==, "service-name"); + g_assert_cmpstr (scope, ==, "scope"); + + g_free (service_name); + g_free (scope); +} + +/* Simple implementation of GDataAuthorizer for test purposes */ +#define TYPE_SIMPLE_AUTHORIZER (simple_authorizer_get_type ()) +#define SIMPLE_AUTHORIZER(o) (G_TYPE_CHECK_INSTANCE_CAST ((o), SIMPLE_TYPE_AUTHORIZER, SimpleAuthorizer)) +#define SIMPLE_AUTHORIZER_CLASS(k) (G_TYPE_CHECK_CLASS_CAST((k), SIMPLE_TYPE_AUTHORIZER, SimpleAuthorizerClass)) +#define IS_SIMPLE_AUTHORIZER(o) (G_TYPE_CHECK_INSTANCE_TYPE ((o), SIMPLE_TYPE_AUTHORIZER)) +#define IS_SIMPLE_AUTHORIZER_CLASS(k) (G_TYPE_CHECK_CLASS_TYPE ((k), SIMPLE_TYPE_AUTHORIZER)) +#define SIMPLE_AUTHORIZER_GET_CLASS(o) (G_TYPE_INSTANCE_GET_CLASS ((o), SIMPLE_TYPE_AUTHORIZER, SimpleAuthorizerClass)) + +typedef struct { + GObject parent; +} SimpleAuthorizer; + +typedef struct { + GObjectClass parent; +} SimpleAuthorizerClass; + +static GType simple_authorizer_get_type (void) G_GNUC_CONST; +static void simple_authorizer_authorizer_init (GDataAuthorizerInterface *iface); + +G_DEFINE_TYPE_WITH_CODE (SimpleAuthorizer, simple_authorizer, G_TYPE_OBJECT, + G_IMPLEMENT_INTERFACE (GDATA_TYPE_AUTHORIZER, simple_authorizer_authorizer_init)) + +static void +simple_authorizer_class_init (SimpleAuthorizerClass *klass) +{ + /* Nothing to see here */ +} + +static void +simple_authorizer_init (SimpleAuthorizer *self) +{ + /* Nothing to see here */ +} + +static void +simple_authorizer_process_request (GDataAuthorizer *self, GDataAuthorizationDomain *domain, SoupMessage *message) +{ + SoupURI *test_uri; + + /* Check that the domain and message are as expected */ + g_assert (domain == NULL || GDATA_IS_AUTHORIZATION_DOMAIN (domain)); + if (domain != NULL) { + g_assert_cmpstr (gdata_authorization_domain_get_scope (domain), ==, "scope1"); + } + + g_assert (message != NULL); + g_assert (SOUP_IS_MESSAGE (message)); + test_uri = soup_uri_new ("http://example.com/"); + g_assert (soup_uri_equal (soup_message_get_uri (message), test_uri) == TRUE); + soup_uri_free (test_uri); + + /* Check that this is the first time we've touched the message, and if so, flag the message as touched */ + if (domain != NULL) { + g_assert (soup_message_headers_get_one (message->request_headers, "process_request") == NULL); + soup_message_headers_append (message->request_headers, "process_request", "1"); + } else { + soup_message_headers_append (message->request_headers, "process_request_null", "1"); + } +} + +static gboolean +simple_authorizer_is_authorized_for_domain (GDataAuthorizer *self, GDataAuthorizationDomain *domain) +{ + gboolean is_test_domain1, is_test_domain2; + + /* Check that the domain is as expected */ + g_assert (domain != NULL); + g_assert (GDATA_IS_AUTHORIZATION_DOMAIN (domain)); + + is_test_domain1 = (strcmp (gdata_authorization_domain_get_scope (domain), "scope1") == 0) ? TRUE : FALSE; + is_test_domain2 = (strcmp (gdata_authorization_domain_get_scope (domain), "scope2") == 0) ? TRUE : FALSE; + + g_assert (is_test_domain1 == TRUE || is_test_domain2 == TRUE); + + /* Increment the counter on the domain so we know if this function's been called more than once on each domain */ + g_object_set_data (G_OBJECT (domain), "counter", GUINT_TO_POINTER (GPOINTER_TO_UINT (g_object_get_data (G_OBJECT (domain), "counter")) + 1)); + + /* Only authorise test_domain1 */ + return is_test_domain1; +} + +static void +simple_authorizer_authorizer_init (GDataAuthorizerInterface *iface) +{ + iface->process_request = simple_authorizer_process_request; + iface->is_authorized_for_domain = simple_authorizer_is_authorized_for_domain; +} + +/* Normal implementation of GDataAuthorizer for test purposes */ +#define TYPE_NORMAL_AUTHORIZER (normal_authorizer_get_type ()) +#define NORMAL_AUTHORIZER(o) (G_TYPE_CHECK_INSTANCE_CAST ((o), NORMAL_TYPE_AUTHORIZER, NormalAuthorizer)) +#define NORMAL_AUTHORIZER_CLASS(k) (G_TYPE_CHECK_CLASS_CAST((k), NORMAL_TYPE_AUTHORIZER, NormalAuthorizerClass)) +#define IS_NORMAL_AUTHORIZER(o) (G_TYPE_CHECK_INSTANCE_TYPE ((o), NORMAL_TYPE_AUTHORIZER)) +#define IS_NORMAL_AUTHORIZER_CLASS(k) (G_TYPE_CHECK_CLASS_TYPE ((k), NORMAL_TYPE_AUTHORIZER)) +#define NORMAL_AUTHORIZER_GET_CLASS(o) (G_TYPE_INSTANCE_GET_CLASS ((o), NORMAL_TYPE_AUTHORIZER, NormalAuthorizerClass)) + +typedef struct { + GObject parent; +} NormalAuthorizer; + +typedef struct { + GObjectClass parent; +} NormalAuthorizerClass; + +static GType normal_authorizer_get_type (void) G_GNUC_CONST; +static void normal_authorizer_authorizer_init (GDataAuthorizerInterface *iface); + +G_DEFINE_TYPE_WITH_CODE (NormalAuthorizer, normal_authorizer, G_TYPE_OBJECT, + G_IMPLEMENT_INTERFACE (GDATA_TYPE_AUTHORIZER, normal_authorizer_authorizer_init)) + +static void +normal_authorizer_class_init (NormalAuthorizerClass *klass) +{ + /* Nothing to see here */ +} + +static void +normal_authorizer_init (NormalAuthorizer *self) +{ + /* Nothing to see here */ +} + +static gboolean +normal_authorizer_refresh_authorization (GDataAuthorizer *self, GCancellable *cancellable, GError **error) +{ + /* Check the inputs */ + g_assert (GDATA_IS_AUTHORIZER (self)); + g_assert (cancellable == NULL || G_IS_CANCELLABLE (cancellable)); + g_assert (error == NULL || *error == NULL); + + /* Increment the counter on the authorizer so we know if this function's been called more than once */ + g_object_set_data (G_OBJECT (self), "counter", GUINT_TO_POINTER (GPOINTER_TO_UINT (g_object_get_data (G_OBJECT (self), "counter")) + 1)); + + /* If we're instructed to set an error, do so (with an arbitrary error code) */ + if (g_object_get_data (G_OBJECT (self), "error") != NULL) { + g_set_error_literal (error, GDATA_SERVICE_ERROR, GDATA_SERVICE_ERROR_PROTOCOL_ERROR, "Error message"); + return FALSE; + } + + return TRUE; +} + +static void +normal_authorizer_authorizer_init (GDataAuthorizerInterface *iface) +{ + /* Use the same implementation as SimpleAuthorizer for process_request() and is_authorized_for_domain(). */ + iface->process_request = simple_authorizer_process_request; + iface->is_authorized_for_domain = simple_authorizer_is_authorized_for_domain; + + /* Unlike SimpleAuthorizer, also implement refresh_authorization() (but not the async versions). */ + iface->refresh_authorization = normal_authorizer_refresh_authorization; +} + +/* Complex implementation of GDataAuthorizer for test purposes */ +#define TYPE_COMPLEX_AUTHORIZER (complex_authorizer_get_type ()) +#define COMPLEX_AUTHORIZER(o) (G_TYPE_CHECK_INSTANCE_CAST ((o), COMPLEX_TYPE_AUTHORIZER, ComplexAuthorizer)) +#define COMPLEX_AUTHORIZER_CLASS(k) (G_TYPE_CHECK_CLASS_CAST((k), COMPLEX_TYPE_AUTHORIZER, ComplexAuthorizerClass)) +#define IS_COMPLEX_AUTHORIZER(o) (G_TYPE_CHECK_INSTANCE_TYPE ((o), COMPLEX_TYPE_AUTHORIZER)) +#define IS_COMPLEX_AUTHORIZER_CLASS(k) (G_TYPE_CHECK_CLASS_TYPE ((k), COMPLEX_TYPE_AUTHORIZER)) +#define COMPLEX_AUTHORIZER_GET_CLASS(o) (G_TYPE_INSTANCE_GET_CLASS ((o), COMPLEX_TYPE_AUTHORIZER, ComplexAuthorizerClass)) + +typedef struct { + GObject parent; +} ComplexAuthorizer; + +typedef struct { + GObjectClass parent; +} ComplexAuthorizerClass; + +static GType complex_authorizer_get_type (void) G_GNUC_CONST; +static void complex_authorizer_authorizer_init (GDataAuthorizerInterface *iface); + +G_DEFINE_TYPE_WITH_CODE (ComplexAuthorizer, complex_authorizer, G_TYPE_OBJECT, + G_IMPLEMENT_INTERFACE (GDATA_TYPE_AUTHORIZER, complex_authorizer_authorizer_init)) + +static void +complex_authorizer_class_init (ComplexAuthorizerClass *klass) +{ + /* Nothing to see here */ +} + +static void +complex_authorizer_init (ComplexAuthorizer *self) +{ + /* Nothing to see here */ +} + +static void +complex_authorizer_refresh_authorization_async (GDataAuthorizer *self, GCancellable *cancellable, GAsyncReadyCallback callback, gpointer user_data) +{ + g_autoptr(GTask) task = NULL; + g_autoptr(GError) error = NULL; + + /* Check the inputs */ + g_assert (GDATA_IS_AUTHORIZER (self)); + g_assert (cancellable == NULL || G_IS_CANCELLABLE (cancellable)); + + task = g_task_new (self, cancellable, callback, user_data); + g_task_set_source_tag (task, complex_authorizer_refresh_authorization_async); + + /* Increment the async counter on the authorizer so we know if this function's been called more than once */ + g_object_set_data (G_OBJECT (self), "async-counter", + GUINT_TO_POINTER (GPOINTER_TO_UINT (g_object_get_data (G_OBJECT (self), "async-counter")) + 1)); + + if (g_cancellable_set_error_if_cancelled (cancellable, &error) == TRUE) { + /* Handle cancellation */ + g_task_return_error (task, g_steal_pointer (&error)); + } else if (g_object_get_data (G_OBJECT (self), "error") != NULL) { + /* If we're instructed to set an error, do so (with an arbitrary error code) */ + g_task_return_new_error (task, GDATA_SERVICE_ERROR, GDATA_SERVICE_ERROR_NETWORK_ERROR, "%s", "Error message"); + } else { + g_task_return_boolean (task, TRUE); + } +} + +static gboolean +complex_authorizer_refresh_authorization_finish (GDataAuthorizer *self, GAsyncResult *async_result, GError **error) +{ + /* Check the inputs */ + g_assert (GDATA_IS_AUTHORIZER (self)); + g_assert (G_IS_ASYNC_RESULT (async_result)); + g_assert (error == NULL || *error == NULL); + g_assert (g_task_is_valid (async_result, self)); + g_assert (g_async_result_is_tagged (async_result, complex_authorizer_refresh_authorization_async)); + + /* Assert that the async function's already been called (once) */ + g_assert_cmpuint (GPOINTER_TO_UINT (g_object_get_data (G_OBJECT (self), "async-counter")), ==, 1); + + /* Increment the finish counter on the authorizer so we know if this function's been called more than once */ + g_object_set_data (G_OBJECT (self), "finish-counter", + GUINT_TO_POINTER (GPOINTER_TO_UINT (g_object_get_data (G_OBJECT (self), "finish-counter")) + 1)); + + return g_task_propagate_boolean (G_TASK (async_result), error); +} + +static void +complex_authorizer_authorizer_init (GDataAuthorizerInterface *iface) +{ + /* Use the same implementation as SimpleAuthorizer/NormalAuthorizer for process_request(), is_authorized_for_domain() and + * refresh_authorization(). */ + iface->process_request = simple_authorizer_process_request; + iface->is_authorized_for_domain = simple_authorizer_is_authorized_for_domain; + iface->refresh_authorization = normal_authorizer_refresh_authorization; + + /* Unlike NormalAuthorizer, also implement the async versions of refresh_authorization(). */ + iface->refresh_authorization_async = complex_authorizer_refresh_authorization_async; + iface->refresh_authorization_finish = complex_authorizer_refresh_authorization_finish; +} + +/* Testing data for generic GDataAuthorizer interface tests */ +typedef struct { + GDataAuthorizer *authorizer; +} AuthorizerData; + +static void +set_up_simple_authorizer_data (AuthorizerData *data, gconstpointer user_data) +{ + data->authorizer = GDATA_AUTHORIZER (g_object_new (TYPE_SIMPLE_AUTHORIZER, NULL)); +} + +static void +set_up_normal_authorizer_data (AuthorizerData *data, gconstpointer user_data) +{ + data->authorizer = GDATA_AUTHORIZER (g_object_new (TYPE_NORMAL_AUTHORIZER, NULL)); +} + +static void +set_up_complex_authorizer_data (AuthorizerData *data, gconstpointer user_data) +{ + data->authorizer = GDATA_AUTHORIZER (g_object_new (TYPE_COMPLEX_AUTHORIZER, NULL)); +} + +static void +tear_down_authorizer_data (AuthorizerData *data, gconstpointer user_data) +{ + g_object_unref (data->authorizer); +} + +/* Test that calling gdata_authorizer_process_request() happens correctly */ +static void +test_authorizer_process_request (AuthorizerData *data, gconstpointer user_data) +{ + SoupMessage *message; + + message = soup_message_new (SOUP_METHOD_GET, "http://example.com/"); + + gdata_authorizer_process_request (data->authorizer, test_domain1, message); + g_assert_cmpstr (soup_message_headers_get_one (message->request_headers, "process_request"), ==, "1"); + g_assert (soup_message_headers_get_one (message->request_headers, "process_request_null") == NULL); + + g_object_unref (message); +} + +/* Test that calling gdata_authorizer_process_request() happens correctly for a NULL domain */ +static void +test_authorizer_process_request_null (AuthorizerData *data, gconstpointer user_data) +{ + SoupMessage *message; + + message = soup_message_new (SOUP_METHOD_GET, "http://example.com/"); + + gdata_authorizer_process_request (data->authorizer, NULL, message); + g_assert (soup_message_headers_get_one (message->request_headers, "process_request") == NULL); + g_assert_cmpstr (soup_message_headers_get_one (message->request_headers, "process_request_null"), ==, "1"); + + g_object_unref (message); +} + +/* Test that calling gdata_authorizer_is_authorized_for_domain() happens correctly */ +static void +test_authorizer_is_authorized_for_domain (AuthorizerData *data, gconstpointer user_data) +{ + /* Set some counters on the test domains to check that the interface implementation is only called once per domain */ + g_object_set_data (G_OBJECT (test_domain1), "counter", GUINT_TO_POINTER (0)); + g_object_set_data (G_OBJECT (test_domain2), "counter", GUINT_TO_POINTER (0)); + + g_assert (gdata_authorizer_is_authorized_for_domain (data->authorizer, test_domain1) == TRUE); + g_assert (gdata_authorizer_is_authorized_for_domain (data->authorizer, test_domain2) == FALSE); + + g_assert_cmpuint (GPOINTER_TO_UINT (g_object_get_data (G_OBJECT (test_domain1), "counter")), ==, 1); + g_assert_cmpuint (GPOINTER_TO_UINT (g_object_get_data (G_OBJECT (test_domain2), "counter")), ==, 1); +} + +/* Test that calling gdata_authorizer_is_authorized_for_domain() with a NULL authorizer always returns FALSE */ +static void +test_authorizer_is_authorized_for_domain_null (AuthorizerData *data, gconstpointer user_data) +{ + g_assert (gdata_authorizer_is_authorized_for_domain (NULL, test_domain1) == FALSE); + g_assert (gdata_authorizer_is_authorized_for_domain (NULL, test_domain2) == FALSE); +} + +/* Test that calling refresh_authorization() on an authorizer which implements it returns TRUE without error, and only calls the implementation + * once */ +static void +test_authorizer_refresh_authorization (AuthorizerData *data, gconstpointer user_data) +{ + gboolean success; + GError *error = NULL; + + /* Set a counter on the authoriser to check that the interface implementation is only called once */ + g_object_set_data (G_OBJECT (data->authorizer), "counter", GUINT_TO_POINTER (0)); + + success = gdata_authorizer_refresh_authorization (data->authorizer, NULL, &error); + g_assert_no_error (error); + g_assert (success == TRUE); + g_clear_error (&error); + + g_assert_cmpuint (GPOINTER_TO_UINT (g_object_get_data (G_OBJECT (data->authorizer), "counter")), ==, 1); +} + +/* Test that calling refresh_authorization() on an authorizer which implements it with errors returns FALSE with an error, and only calls the + * implementation once */ +static void +test_authorizer_refresh_authorization_error (AuthorizerData *data, gconstpointer user_data) +{ + gboolean success; + GError *error = NULL; + + /* Set a counter on the authoriser to check that the interface implementation is only called once */ + g_object_set_data (G_OBJECT (data->authorizer), "counter", GUINT_TO_POINTER (0)); + + /* Set a flag on the authoriser to make the NormalAuthorizer implementation return an error for refresh_authorization() */ + g_object_set_data (G_OBJECT (data->authorizer), "error", GUINT_TO_POINTER (TRUE)); + + success = gdata_authorizer_refresh_authorization (data->authorizer, NULL, &error); + g_assert_error (error, GDATA_SERVICE_ERROR, GDATA_SERVICE_ERROR_PROTOCOL_ERROR); + g_assert (success == FALSE); + g_clear_error (&error); + + g_assert_cmpuint (GPOINTER_TO_UINT (g_object_get_data (G_OBJECT (data->authorizer), "counter")), ==, 1); +} + +/* Test that calling refresh_authorization() on an authorizer which doesn't implement it returns FALSE without an error */ +static void +test_authorizer_refresh_authorization_unimplemented (AuthorizerData *data, gconstpointer user_data) +{ + gboolean success; + GError *error = NULL; + + success = gdata_authorizer_refresh_authorization (data->authorizer, NULL, &error); + g_assert_no_error (error); + g_assert (success == FALSE); + g_clear_error (&error); +} + +/* Test that calling refresh_authorization() on an authorizer which doesn't implement it, then cancelling the call returns FALSE without an error + * (not even a cancellation error) */ +static void +test_authorizer_refresh_authorization_cancellation_unimplemented (AuthorizerData *data, gconstpointer user_data) +{ + GCancellable *cancellable; + gboolean success; + GError *error = NULL; + + cancellable = g_cancellable_new (); + g_cancellable_cancel (cancellable); + + success = gdata_authorizer_refresh_authorization (data->authorizer, cancellable, &error); + g_assert_no_error (error); + g_assert (success == FALSE); + g_clear_error (&error); + + g_object_unref (cancellable); +} + +/* Set of standard async callback functions for refresh_authorization_async() which check various combinations of success and error value */ +static void +test_authorizer_refresh_authorization_async_success_no_error_cb (GDataAuthorizer *authorizer, GAsyncResult *async_result, GMainLoop *main_loop) +{ + gboolean success; + GError *error = NULL; + + success = gdata_authorizer_refresh_authorization_finish (authorizer, async_result, &error); + g_assert_no_error (error); + g_assert (success == TRUE); + g_clear_error (&error); + + g_main_loop_quit (main_loop); +} + +static void +test_authorizer_refresh_authorization_async_failure_no_error_cb (GDataAuthorizer *authorizer, GAsyncResult *async_result, GMainLoop *main_loop) +{ + gboolean success; + GError *error = NULL; + + success = gdata_authorizer_refresh_authorization_finish (authorizer, async_result, &error); + g_assert_no_error (error); + g_assert (success == FALSE); + g_clear_error (&error); + + g_main_loop_quit (main_loop); +} + +static void +test_authorizer_refresh_authorization_async_network_error_cb (GDataAuthorizer *authorizer, GAsyncResult *async_result, GMainLoop *main_loop) +{ + gboolean success; + GError *error = NULL; + + success = gdata_authorizer_refresh_authorization_finish (authorizer, async_result, &error); + g_assert_error (error, GDATA_SERVICE_ERROR, GDATA_SERVICE_ERROR_NETWORK_ERROR); + g_assert (success == FALSE); + g_clear_error (&error); + + g_main_loop_quit (main_loop); +} + +static void +test_authorizer_refresh_authorization_async_protocol_error_cb (GDataAuthorizer *authorizer, GAsyncResult *async_result, GMainLoop *main_loop) +{ + gboolean success; + GError *error = NULL; + + success = gdata_authorizer_refresh_authorization_finish (authorizer, async_result, &error); + g_assert_error (error, GDATA_SERVICE_ERROR, GDATA_SERVICE_ERROR_PROTOCOL_ERROR); + g_assert (success == FALSE); + g_clear_error (&error); + + g_main_loop_quit (main_loop); +} + +static void +test_authorizer_refresh_authorization_async_cancelled_error_cb (GDataAuthorizer *authorizer, GAsyncResult *async_result, GMainLoop *main_loop) +{ + gboolean success; + GError *error = NULL; + + success = gdata_authorizer_refresh_authorization_finish (authorizer, async_result, &error); + g_assert_error (error, G_IO_ERROR, G_IO_ERROR_CANCELLED); + g_assert (success == FALSE); + g_clear_error (&error); + + g_main_loop_quit (main_loop); +} + +/* Test that calling refresh_authorization_async() on an authorizer which implements it returns TRUE without an error */ +static void +test_authorizer_refresh_authorization_async (AuthorizerData *data, gconstpointer user_data) +{ + GMainLoop *main_loop; + + /* Set counters on the authoriser to check that the interface implementations are only called once */ + g_object_set_data (G_OBJECT (data->authorizer), "counter", GUINT_TO_POINTER (0)); + g_object_set_data (G_OBJECT (data->authorizer), "async-counter", GUINT_TO_POINTER (0)); + g_object_set_data (G_OBJECT (data->authorizer), "finish-counter", GUINT_TO_POINTER (0)); + + main_loop = g_main_loop_new (NULL, FALSE); + + gdata_authorizer_refresh_authorization_async (data->authorizer, NULL, + (GAsyncReadyCallback) test_authorizer_refresh_authorization_async_success_no_error_cb, + main_loop); + + g_main_loop_run (main_loop); + + g_assert_cmpuint (GPOINTER_TO_UINT (g_object_get_data (G_OBJECT (data->authorizer), "counter")), ==, 0); + g_assert_cmpuint (GPOINTER_TO_UINT (g_object_get_data (G_OBJECT (data->authorizer), "async-counter")), ==, 1); + g_assert_cmpuint (GPOINTER_TO_UINT (g_object_get_data (G_OBJECT (data->authorizer), "finish-counter")), ==, 1); + + g_main_loop_unref (main_loop); +} + +/* Test that calling refresh_authorization_async() on an authorizer which implements it with an error returns FALSE with the appropriate error */ +static void +test_authorizer_refresh_authorization_async_error (AuthorizerData *data, gconstpointer user_data) +{ + GMainLoop *main_loop; + + /* Set counters on the authoriser to check that the interface implementations are only called once */ + g_object_set_data (G_OBJECT (data->authorizer), "counter", GUINT_TO_POINTER (0)); + g_object_set_data (G_OBJECT (data->authorizer), "async-counter", GUINT_TO_POINTER (0)); + g_object_set_data (G_OBJECT (data->authorizer), "finish-counter", GUINT_TO_POINTER (0)); + + /* Set a flag on the authoriser to make the ComplexAuthorizer implementation return an error for refresh_authorization_async() */ + g_object_set_data (G_OBJECT (data->authorizer), "error", GUINT_TO_POINTER (TRUE)); + + main_loop = g_main_loop_new (NULL, FALSE); + + gdata_authorizer_refresh_authorization_async (data->authorizer, NULL, + (GAsyncReadyCallback) test_authorizer_refresh_authorization_async_network_error_cb, main_loop); + + g_main_loop_run (main_loop); + + g_assert_cmpuint (GPOINTER_TO_UINT (g_object_get_data (G_OBJECT (data->authorizer), "counter")), ==, 0); + g_assert_cmpuint (GPOINTER_TO_UINT (g_object_get_data (G_OBJECT (data->authorizer), "async-counter")), ==, 1); + g_assert_cmpuint (GPOINTER_TO_UINT (g_object_get_data (G_OBJECT (data->authorizer), "finish-counter")), ==, 1); + + g_main_loop_unref (main_loop); +} + +/* Test that calling refresh_authorization_async() on an authorizer which implements it, then cancelling the call returns FALSE with a cancellation + * error */ +static void +test_authorizer_refresh_authorization_async_cancellation (AuthorizerData *data, gconstpointer user_data) +{ + GCancellable *cancellable; + GMainLoop *main_loop; + + /* Set counters on the authoriser to check that the interface implementations are only called once */ + g_object_set_data (G_OBJECT (data->authorizer), "counter", GUINT_TO_POINTER (0)); + g_object_set_data (G_OBJECT (data->authorizer), "async-counter", GUINT_TO_POINTER (0)); + g_object_set_data (G_OBJECT (data->authorizer), "finish-counter", GUINT_TO_POINTER (0)); + + main_loop = g_main_loop_new (NULL, FALSE); + + cancellable = g_cancellable_new (); + g_cancellable_cancel (cancellable); + + gdata_authorizer_refresh_authorization_async (data->authorizer, cancellable, + (GAsyncReadyCallback) test_authorizer_refresh_authorization_async_cancelled_error_cb, + main_loop); + + g_main_loop_run (main_loop); + + g_assert_cmpuint (GPOINTER_TO_UINT (g_object_get_data (G_OBJECT (data->authorizer), "counter")), ==, 0); + g_assert_cmpuint (GPOINTER_TO_UINT (g_object_get_data (G_OBJECT (data->authorizer), "async-counter")), ==, 1); + g_assert_cmpuint (GPOINTER_TO_UINT (g_object_get_data (G_OBJECT (data->authorizer), "finish-counter")), ==, 1); + + g_object_unref (cancellable); + g_main_loop_unref (main_loop); +} + +/* Test that calling refresh_authorization_async() on an authorizer which doesn't implement it, but does implement refresh_authorization(), returns + * TRUE without an error */ +static void +test_authorizer_refresh_authorization_async_simulated (AuthorizerData *data, gconstpointer user_data) +{ + GMainLoop *main_loop; + + /* Set a counter on the authoriser to check that the interface implementation is only called once */ + g_object_set_data (G_OBJECT (data->authorizer), "counter", GUINT_TO_POINTER (0)); + + main_loop = g_main_loop_new (NULL, FALSE); + + gdata_authorizer_refresh_authorization_async (data->authorizer, NULL, + (GAsyncReadyCallback) test_authorizer_refresh_authorization_async_success_no_error_cb, + main_loop); + + g_main_loop_run (main_loop); + + g_assert_cmpuint (GPOINTER_TO_UINT (g_object_get_data (G_OBJECT (data->authorizer), "counter")), ==, 1); + + g_main_loop_unref (main_loop); +} + +/* Test that calling refresh_authorization_async() on an authorizer which doesn't implement it, but does implement refresh_authorization() with an + * error, returns FALSE with the appropriate error */ +static void +test_authorizer_refresh_authorization_async_error_simulated (AuthorizerData *data, gconstpointer user_data) +{ + GMainLoop *main_loop; + + /* Set a counter on the authoriser to check that the interface implementation is only called once */ + g_object_set_data (G_OBJECT (data->authorizer), "counter", GUINT_TO_POINTER (0)); + + /* Set a flag on the authoriser to make the NormalAuthorizer implementation return an error for refresh_authorization() */ + g_object_set_data (G_OBJECT (data->authorizer), "error", GUINT_TO_POINTER (TRUE)); + + main_loop = g_main_loop_new (NULL, FALSE); + + gdata_authorizer_refresh_authorization_async (data->authorizer, NULL, + (GAsyncReadyCallback) test_authorizer_refresh_authorization_async_protocol_error_cb, main_loop); + + g_main_loop_run (main_loop); + + g_assert_cmpuint (GPOINTER_TO_UINT (g_object_get_data (G_OBJECT (data->authorizer), "counter")), ==, 1); + + g_main_loop_unref (main_loop); +} + +/* Test that calling refresh_authorization_async() on an authorizer which doesn't implement it, but does implement refresh_authorization(), then + * cancelling the call returns FALSE with a cancellation error */ +static void +test_authorizer_refresh_authorization_async_cancellation_simulated (AuthorizerData *data, gconstpointer user_data) +{ + GCancellable *cancellable; + GMainLoop *main_loop; + + main_loop = g_main_loop_new (NULL, FALSE); + + cancellable = g_cancellable_new (); + g_cancellable_cancel (cancellable); + + /* Note we don't count how many times the implementation of refresh_authorization() is called, since cancellation can legitimately be + * handled by the gdata_authorizer_refresh_authorization_async() code before refresh_authorization() is ever called. */ + gdata_authorizer_refresh_authorization_async (data->authorizer, cancellable, + (GAsyncReadyCallback) test_authorizer_refresh_authorization_async_cancelled_error_cb, + main_loop); + + g_main_loop_run (main_loop); + + g_object_unref (cancellable); + g_main_loop_unref (main_loop); +} + +/* Test that calling refresh_authorization_async() on an authorizer which doesn't implement it returns FALSE without an error */ +static void +test_authorizer_refresh_authorization_async_unimplemented (AuthorizerData *data, gconstpointer user_data) +{ + GMainLoop *main_loop; + + main_loop = g_main_loop_new (NULL, FALSE); + + gdata_authorizer_refresh_authorization_async (data->authorizer, NULL, + (GAsyncReadyCallback) test_authorizer_refresh_authorization_async_failure_no_error_cb, + main_loop); + + g_main_loop_run (main_loop); + + g_main_loop_unref (main_loop); +} + +/* Test that calling refresh_authorization_async() on an authorizer which doesn't implement it, then cancelling the call returns FALSE without an + * error (not even a cancellation error) */ +static void +test_authorizer_refresh_authorization_async_cancellation_unimplemented (AuthorizerData *data, gconstpointer user_data) +{ + GCancellable *cancellable; + GMainLoop *main_loop; + + main_loop = g_main_loop_new (NULL, FALSE); + + cancellable = g_cancellable_new (); + g_cancellable_cancel (cancellable); + + gdata_authorizer_refresh_authorization_async (data->authorizer, cancellable, + (GAsyncReadyCallback) test_authorizer_refresh_authorization_async_failure_no_error_cb, + main_loop); + + g_main_loop_run (main_loop); + + g_object_unref (cancellable); + g_main_loop_unref (main_loop); +} + +int +main (int argc, char *argv[]) +{ + int retval; + + gdata_test_init (argc, argv); + + /* Note: This is not how GDataAuthorizationDomains are meant to be constructed. Client code is not expected to do this. */ + test_domain1 = g_object_new (GDATA_TYPE_AUTHORIZATION_DOMAIN, + "service-name", "service-name1", + "scope", "scope1", + NULL); + test_domain2 = g_object_new (GDATA_TYPE_AUTHORIZATION_DOMAIN, + "service-name", "service-name2", + "scope", "scope2", + NULL); + + /* GDataAuthorizationDomain tests */ + g_test_add_func ("/authorization-domain/properties", test_authorization_domain_properties); + + /* GDataAuthorizer interface tests */ + g_test_add ("/authorizer/process-request", AuthorizerData, NULL, set_up_simple_authorizer_data, test_authorizer_process_request, + tear_down_authorizer_data); + g_test_add ("/authorizer/process-request/null", AuthorizerData, NULL, set_up_simple_authorizer_data, test_authorizer_process_request_null, + tear_down_authorizer_data); + g_test_add ("/authorizer/is-authorized-for-domain", AuthorizerData, NULL, set_up_simple_authorizer_data, + test_authorizer_is_authorized_for_domain, tear_down_authorizer_data); + g_test_add ("/authorizer/is-authorized-for-domain/null", AuthorizerData, NULL, set_up_simple_authorizer_data, + test_authorizer_is_authorized_for_domain_null, tear_down_authorizer_data); + g_test_add ("/authorizer/refresh-authorization", AuthorizerData, NULL, set_up_normal_authorizer_data, + test_authorizer_refresh_authorization, tear_down_authorizer_data); + g_test_add ("/authorizer/refresh-authorization/error", AuthorizerData, NULL, set_up_normal_authorizer_data, + test_authorizer_refresh_authorization_error, tear_down_authorizer_data); + g_test_add ("/authorizer/refresh-authorization/unimplemented", AuthorizerData, NULL, set_up_simple_authorizer_data, + test_authorizer_refresh_authorization_unimplemented, tear_down_authorizer_data); + g_test_add ("/authorizer/refresh-authorization/cancellation/unimplemented", AuthorizerData, NULL, set_up_simple_authorizer_data, + test_authorizer_refresh_authorization_cancellation_unimplemented, tear_down_authorizer_data); + g_test_add ("/authorizer/refresh-authorization/async", AuthorizerData, NULL, set_up_complex_authorizer_data, + test_authorizer_refresh_authorization_async, tear_down_authorizer_data); + g_test_add ("/authorizer/refresh-authorization/async/error", AuthorizerData, NULL, set_up_complex_authorizer_data, + test_authorizer_refresh_authorization_async_error, tear_down_authorizer_data); + g_test_add ("/authorizer/refresh-authorization/async/cancellation", AuthorizerData, NULL, set_up_complex_authorizer_data, + test_authorizer_refresh_authorization_async_cancellation, tear_down_authorizer_data); + g_test_add ("/authorizer/refresh-authorization/async/simulated", AuthorizerData, NULL, set_up_normal_authorizer_data, + test_authorizer_refresh_authorization_async_simulated, tear_down_authorizer_data); + g_test_add ("/authorizer/refresh-authorization/async/error/simulated", AuthorizerData, NULL, set_up_normal_authorizer_data, + test_authorizer_refresh_authorization_async_error_simulated, tear_down_authorizer_data); + g_test_add ("/authorizer/refresh-authorization/async/cancellation/simulated", AuthorizerData, NULL, set_up_normal_authorizer_data, + test_authorizer_refresh_authorization_async_cancellation_simulated, tear_down_authorizer_data); + g_test_add ("/authorizer/refresh-authorization/async/unimplemented", AuthorizerData, NULL, set_up_simple_authorizer_data, + test_authorizer_refresh_authorization_async_unimplemented, tear_down_authorizer_data); + g_test_add ("/authorizer/refresh-authorization/async/cancellation/unimplemented", AuthorizerData, NULL, set_up_simple_authorizer_data, + test_authorizer_refresh_authorization_async_cancellation_unimplemented, tear_down_authorizer_data); + + retval = g_test_run (); + + g_object_unref (test_domain2); + g_object_unref (test_domain1); + + return retval; +} diff --git a/gdata/tests/buffer.c b/gdata/tests/buffer.c new file mode 100644 index 0000000..c4e9d13 --- /dev/null +++ b/gdata/tests/buffer.c @@ -0,0 +1,165 @@ +/* -*- Mode: C; indent-tabs-mode: t; c-basic-offset: 8; tab-width: 8 -*- */ +/* + * GData Client + * Copyright (C) Philip Withnall 2016 + * + * GData Client is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * GData Client is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with GData Client. If not, see . + */ + +#include "config.h" + +#include +#include + +#include "gdata.h" +#include "common.h" + +/* gdata-buffer.h is private, so just include the C file for easy testing. */ +#include "gdata-buffer.c" + + +typedef struct { + gpointer unused; +} Fixture; + + +static void +set_up (Fixture *f, gconstpointer user_data) +{ + /* Abort if we end up blocking. */ + alarm (30); +} + +static void +tear_down (Fixture *f, gconstpointer user_data) +{ + /* Reset the alarm. */ + alarm (0); +} + +static void +test_buffer_construction (Fixture *f, gconstpointer user_data) +{ + GDataBuffer *buffer = NULL; /* owned */ + + buffer = gdata_buffer_new (); + gdata_buffer_free (buffer); +} + +static void +test_buffer_instant_eof (Fixture *f, gconstpointer user_data) +{ + GDataBuffer *buffer = NULL; /* owned */ + gboolean reached_eof = FALSE; + guint8 buf[1]; + + buffer = gdata_buffer_new (); + + g_assert_false (gdata_buffer_push_data (buffer, NULL, 0)); + g_assert_cmpuint (gdata_buffer_pop_data (buffer, buf, sizeof (buf), + &reached_eof, NULL), ==, 0); + g_assert_true (reached_eof); + + gdata_buffer_free (buffer); +} + +static gpointer +test_buffer_thread_eof_func (gpointer user_data) +{ + GDataBuffer *buffer = user_data; + + /* HACK: Wait for a while to be sure that gdata_buffer_pop_data() has + * been already called. */ + g_usleep (G_USEC_PER_SEC / 2); + + g_assert_false (gdata_buffer_push_data (buffer, NULL, 0)); + + return NULL; +} + +/* The test needs to call gdata_buffer_push_data() from another thread only + * once gdata_buffer_pop_data() has reached its blocking loop. */ +static void +test_buffer_thread_eof (Fixture *f, gconstpointer user_data) +{ + GDataBuffer *buffer = NULL; /* owned */ + gboolean reached_eof = FALSE; + guint8 buf[1]; + + g_test_bug ("769727"); + + buffer = gdata_buffer_new (); + + g_thread_new (NULL, test_buffer_thread_eof_func, buffer); + g_assert_cmpuint (gdata_buffer_pop_data (buffer, buf, sizeof (buf), + &reached_eof, NULL), ==, 0); + g_assert_true (reached_eof); + + gdata_buffer_free (buffer); +} + +static void +test_buffer_basic (Fixture *f, gconstpointer user_data) +{ + GDataBuffer *buffer = NULL; /* owned */ + gboolean reached_eof = FALSE; + guint8 buf[100]; + guint8 buf2[100]; + gsize i; + + buffer = gdata_buffer_new (); + + for (i = 0; i < sizeof (buf); i++) + buf[i] = i; + + g_assert_true (gdata_buffer_push_data (buffer, buf, sizeof (buf))); + g_assert_false (gdata_buffer_push_data (buffer, NULL, 0)); + + g_assert_cmpuint (gdata_buffer_pop_data (buffer, buf2, + sizeof (buf2) / 2, + &reached_eof, NULL), ==, + sizeof (buf2) / 2); + g_assert_false (reached_eof); + g_assert_cmpuint (gdata_buffer_pop_data (buffer, + buf2 + sizeof (buf2) / 2, + sizeof (buf2) / 2, + &reached_eof, NULL), ==, + sizeof (buf2) / 2); + g_assert_true (reached_eof); + + for (i = 0; i < sizeof (buf); i++) + g_assert_cmpuint (buf[i], ==, buf2[i]); + + gdata_buffer_free (buffer); +} + +int +main (int argc, char *argv[]) +{ + gdata_test_init (argc, argv); + + /* Only print out headers, since we're sending a lot of data. */ + g_setenv ("LIBGDATA_DEBUG", "2" /* GDATA_LOG_HEADERS */, TRUE); + + g_test_add ("/buffer/construction", Fixture, NULL, + set_up, test_buffer_construction, tear_down); + g_test_add ("/buffer/instant-eof", Fixture, NULL, + set_up, test_buffer_instant_eof, tear_down); + g_test_add ("/buffer/thread-eof", Fixture, NULL, + set_up, test_buffer_thread_eof, tear_down); + g_test_add ("/buffer/basic", Fixture, NULL, + set_up, test_buffer_basic, tear_down); + + return g_test_run (); +} diff --git a/gdata/tests/calendar.c b/gdata/tests/calendar.c new file mode 100644 index 0000000..4d70d1b --- /dev/null +++ b/gdata/tests/calendar.c @@ -0,0 +1,1595 @@ +/* -*- Mode: C; indent-tabs-mode: t; c-basic-offset: 8; tab-width: 8 -*- */ +/* + * GData Client + * Copyright (C) Philip Withnall 2009, 2010, 2014, 2015, 2017 + * + * GData Client is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * GData Client is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with GData Client. If not, see . + */ + +#include +#include +#include + +#include "gdata.h" +#include "common.h" +#include "gdata-dummy-authorizer.h" + +static UhmServer *mock_server = NULL; + +#undef CLIENT_ID /* from common.h */ + +#define CLIENT_ID "352818697630-nqu2cmt5quqd6lr17ouoqmb684u84l1f.apps.googleusercontent.com" +#define CLIENT_SECRET "-fA4pHQJxR3zJ-FyAMPQsikg" +#define REDIRECT_URI "urn:ietf:wg:oauth:2.0:oob" + +typedef struct { + GDataCalendarCalendar *calendar; +} TempCalendarData; + +static void +set_up_temp_calendar (TempCalendarData *data, gconstpointer service) +{ + GDataCalendarCalendar *calendar; + GDataColor colour; + + gdata_test_mock_server_start_trace (mock_server, "setup-temp-calendar"); + + g_assert (gdata_color_from_hexadecimal ("#7A367A", &colour) == TRUE); + + /* Create a single temporary test calendar */ + calendar = gdata_calendar_calendar_new (NULL); + gdata_entry_set_title (GDATA_ENTRY (calendar), "Temp Test Calendar"); + gdata_calendar_calendar_set_color (calendar, &colour); + data->calendar = GDATA_CALENDAR_CALENDAR (gdata_service_insert_entry (GDATA_SERVICE (service), + gdata_calendar_service_get_primary_authorization_domain (), + "https://www.googleapis.com/calendar/v3/calendars", + GDATA_ENTRY (calendar), NULL, NULL)); + g_assert (GDATA_IS_CALENDAR_CALENDAR (data->calendar)); + g_object_unref (calendar); + + uhm_server_end_trace (mock_server); +} + +static void +tear_down_temp_calendar (TempCalendarData *data, gconstpointer service) +{ + gdata_test_mock_server_start_trace (mock_server, "teardown-temp-calendar"); + + /* Delete the calendar */ + g_assert (gdata_service_delete_entry (GDATA_SERVICE (service), gdata_calendar_service_get_primary_authorization_domain (), + GDATA_ENTRY (data->calendar), NULL, NULL) == TRUE); + g_object_unref (data->calendar); + + uhm_server_end_trace (mock_server); +} + +static void +test_authentication (void) +{ + GDataOAuth2Authorizer *authorizer = NULL; /* owned */ + gchar *authentication_uri, *authorisation_code; + + gdata_test_mock_server_start_trace (mock_server, "authentication"); + + authorizer = gdata_oauth2_authorizer_new (CLIENT_ID, CLIENT_SECRET, + REDIRECT_URI, + GDATA_TYPE_CALENDAR_SERVICE); + + /* Get an authentication URI. */ + authentication_uri = gdata_oauth2_authorizer_build_authentication_uri (authorizer, NULL, FALSE); + g_assert (authentication_uri != NULL); + + /* Get the authorisation code off the user. */ + if (uhm_server_get_enable_online (mock_server)) { + authorisation_code = gdata_test_query_user_for_verifier (authentication_uri); + } else { + /* Hard coded, extracted from the trace file. */ + authorisation_code = g_strdup ("4/OEX-S1iMbOA_dOnNgUlSYmGWh3TK.QrR73axcNMkWoiIBeO6P2m_su7cwkQI"); + } + + g_free (authentication_uri); + + if (authorisation_code == NULL) { + /* Skip tests. */ + goto skip_test; + } + + /* Authorise the token */ + g_assert (gdata_oauth2_authorizer_request_authorization (authorizer, authorisation_code, NULL, NULL) == TRUE); + + /* Check all is as it should be */ + g_assert (gdata_authorizer_is_authorized_for_domain (GDATA_AUTHORIZER (authorizer), + gdata_calendar_service_get_primary_authorization_domain ()) == TRUE); + +skip_test: + g_free (authorisation_code); + g_object_unref (authorizer); + + uhm_server_end_trace (mock_server); +} + +typedef struct { + GDataCalendarCalendar *calendar1; + GDataCalendarCalendar *calendar2; +} QueryCalendarsData; + +static void +set_up_query_calendars (QueryCalendarsData *data, gconstpointer service) +{ + GDataCalendarCalendar *calendar; + GDataColor colour; + + gdata_test_mock_server_start_trace (mock_server, "setup-query-calendars"); + + g_assert (gdata_color_from_hexadecimal ("#7A367A", &colour) == TRUE); + + /* Create some new calendars for queries */ + calendar = gdata_calendar_calendar_new (NULL); + gdata_entry_set_title (GDATA_ENTRY (calendar), "Test Calendar 1"); + gdata_calendar_calendar_set_color (calendar, &colour); + data->calendar1 = GDATA_CALENDAR_CALENDAR (gdata_service_insert_entry (GDATA_SERVICE (service), + gdata_calendar_service_get_primary_authorization_domain (), + "https://www.googleapis.com/calendar/v3/calendars", + GDATA_ENTRY (calendar), NULL, NULL)); + g_assert (GDATA_IS_CALENDAR_CALENDAR (data->calendar1)); + g_object_unref (calendar); + + calendar = gdata_calendar_calendar_new (NULL); + gdata_entry_set_title (GDATA_ENTRY (calendar), "Test Calendar 2"); + gdata_calendar_calendar_set_color (calendar, &colour); + data->calendar2 = GDATA_CALENDAR_CALENDAR (gdata_service_insert_entry (GDATA_SERVICE (service), + gdata_calendar_service_get_primary_authorization_domain (), + "https://www.googleapis.com/calendar/v3/calendars", + GDATA_ENTRY (calendar), NULL, NULL)); + g_assert (GDATA_IS_CALENDAR_CALENDAR (data->calendar2)); + g_object_unref (calendar); + + uhm_server_end_trace (mock_server); +} + +static void +tear_down_query_calendars (QueryCalendarsData *data, gconstpointer service) +{ + gdata_test_mock_server_start_trace (mock_server, "teardown-query-calendars"); + + /* Delete the calendars */ + g_assert (gdata_service_delete_entry (GDATA_SERVICE (service), gdata_calendar_service_get_primary_authorization_domain (), + GDATA_ENTRY (data->calendar1), NULL, NULL) == TRUE); + g_object_unref (data->calendar1); + + g_assert (gdata_service_delete_entry (GDATA_SERVICE (service), gdata_calendar_service_get_primary_authorization_domain (), + GDATA_ENTRY (data->calendar2), NULL, NULL) == TRUE); + g_object_unref (data->calendar2); + + uhm_server_end_trace (mock_server); +} + +static void +test_query_all_calendars (QueryCalendarsData *data, gconstpointer service) +{ + GDataFeed *feed; + GError *error = NULL; + + gdata_test_mock_server_start_trace (mock_server, "query-all-calendars"); + + feed = gdata_calendar_service_query_all_calendars (GDATA_CALENDAR_SERVICE (service), NULL, NULL, NULL, NULL, &error); + g_assert_no_error (error); + g_assert (GDATA_IS_CALENDAR_FEED (feed)); + g_clear_error (&error); + + /* TODO: check entries and feed properties */ + + g_object_unref (feed); + + uhm_server_end_trace (mock_server); +} + +GDATA_ASYNC_CLOSURE_FUNCTIONS (query_calendars, QueryCalendarsData); + +GDATA_ASYNC_TEST_FUNCTIONS (query_all_calendars, QueryCalendarsData, +G_STMT_START { + gdata_calendar_service_query_all_calendars_async (GDATA_CALENDAR_SERVICE (service), NULL, cancellable, NULL, + NULL, NULL, async_ready_callback, async_data); +} G_STMT_END, +G_STMT_START { + GDataFeed *feed; + + feed = gdata_service_query_finish (GDATA_SERVICE (obj), async_result, &error); + + if (error == NULL) { + /* TODO: Tests? */ + g_assert (GDATA_IS_CALENDAR_FEED (feed)); + + g_object_unref (feed); + } else { + g_assert (feed == NULL); + } +} G_STMT_END); + +static void +test_query_all_calendars_async_progress_closure (QueryCalendarsData *query_data, gconstpointer service) +{ + GDataAsyncProgressClosure *data = g_slice_new0 (GDataAsyncProgressClosure); + + gdata_test_mock_server_start_trace (mock_server, "query-all-calendars-async-progress-closure"); + + data->main_loop = g_main_loop_new (NULL, TRUE); + + gdata_calendar_service_query_all_calendars_async (GDATA_CALENDAR_SERVICE (service), NULL, NULL, + (GDataQueryProgressCallback) gdata_test_async_progress_callback, + data, (GDestroyNotify) gdata_test_async_progress_closure_free, + (GAsyncReadyCallback) gdata_test_async_progress_finish_callback, data); + + g_main_loop_run (data->main_loop); + g_main_loop_unref (data->main_loop); + + /* Check that both callbacks were called exactly once */ + g_assert_cmpuint (data->progress_destroy_notify_count, ==, 1); + g_assert_cmpuint (data->async_ready_notify_count, ==, 1); + + g_slice_free (GDataAsyncProgressClosure, data); + + uhm_server_end_trace (mock_server); +} + +static void +test_query_own_calendars (QueryCalendarsData *data, gconstpointer service) +{ + GDataFeed *feed; + GError *error = NULL; + + gdata_test_mock_server_start_trace (mock_server, "query-own-calendars"); + + feed = gdata_calendar_service_query_own_calendars (GDATA_CALENDAR_SERVICE (service), NULL, NULL, NULL, NULL, &error); + g_assert_no_error (error); + g_assert (GDATA_IS_CALENDAR_FEED (feed)); + g_clear_error (&error); + + /* TODO: check entries and feed properties */ + + g_object_unref (feed); + + uhm_server_end_trace (mock_server); +} + +GDATA_ASYNC_TEST_FUNCTIONS (query_own_calendars, QueryCalendarsData, +G_STMT_START { + gdata_calendar_service_query_own_calendars_async (GDATA_CALENDAR_SERVICE (service), NULL, cancellable, NULL, + NULL, NULL, async_ready_callback, async_data); +} G_STMT_END, +G_STMT_START { + GDataFeed *feed; + + feed = gdata_service_query_finish (GDATA_SERVICE (obj), async_result, &error); + + if (error == NULL) { + g_assert (GDATA_IS_CALENDAR_FEED (feed)); + /* TODO: Tests? */ + + g_object_unref (feed); + } else { + g_assert (feed == NULL); + } +} G_STMT_END); + +static void +test_query_own_calendars_async_progress_closure (QueryCalendarsData *query_data, gconstpointer service) +{ + GDataAsyncProgressClosure *data = g_slice_new0 (GDataAsyncProgressClosure); + + gdata_test_mock_server_start_trace (mock_server, "query-own-calendars-async-progress-closure"); + + data->main_loop = g_main_loop_new (NULL, TRUE); + + gdata_calendar_service_query_own_calendars_async (GDATA_CALENDAR_SERVICE (service), NULL, NULL, + (GDataQueryProgressCallback) gdata_test_async_progress_callback, + data, (GDestroyNotify) gdata_test_async_progress_closure_free, + (GAsyncReadyCallback) gdata_test_async_progress_finish_callback, data); + + g_main_loop_run (data->main_loop); + g_main_loop_unref (data->main_loop); + + /* Check that both callbacks were called exactly once */ + g_assert_cmpuint (data->progress_destroy_notify_count, ==, 1); + g_assert_cmpuint (data->async_ready_notify_count, ==, 1); + + g_slice_free (GDataAsyncProgressClosure, data); + + uhm_server_end_trace (mock_server); +} + +typedef struct { + TempCalendarData parent; + GDataCalendarEvent *event1; + GDataCalendarEvent *event2; + GDataCalendarEvent *event3; +} QueryEventsData; + +static void +set_up_query_events (QueryEventsData *data, gconstpointer service) +{ + GDataCalendarEvent *event; + GDataGDWhen *when; + GError *error = NULL; + + /* Set up a temporary calendar */ + set_up_temp_calendar ((TempCalendarData*) data, service); + + gdata_test_mock_server_start_trace (mock_server, "setup-query-events"); + + /* Add some test events to it */ + event = gdata_calendar_event_new (NULL); + gdata_entry_set_title (GDATA_ENTRY (event), "Test Event 1"); + + when = gdata_gd_when_new (1419113727, 1419113728, FALSE); + gdata_calendar_event_add_time (event, when); + g_object_unref (when); + + data->event1 = gdata_calendar_service_insert_calendar_event (GDATA_CALENDAR_SERVICE (service), data->parent.calendar, event, NULL, &error); + g_assert_no_error (error); + g_assert (GDATA_IS_CALENDAR_EVENT (data->event1)); + g_object_unref (event); + + event = gdata_calendar_event_new (NULL); + gdata_entry_set_title (GDATA_ENTRY (event), "Test Event 2"); + + when = gdata_gd_when_new (1419113000, 1419114000, FALSE); + gdata_calendar_event_add_time (event, when); + g_object_unref (when); + + data->event2 = gdata_calendar_service_insert_calendar_event (GDATA_CALENDAR_SERVICE (service), data->parent.calendar, event, NULL, &error); + g_assert_no_error (error); + g_assert (GDATA_IS_CALENDAR_EVENT (data->event2)); + g_object_unref (event); + + event = gdata_calendar_event_new (NULL); + gdata_entry_set_title (GDATA_ENTRY (event), "Test Event 3"); + + when = gdata_gd_when_new (1419110000, 1419120000, TRUE); + gdata_calendar_event_add_time (event, when); + g_object_unref (when); + + data->event3 = gdata_calendar_service_insert_calendar_event (GDATA_CALENDAR_SERVICE (service), data->parent.calendar, event, NULL, &error); + g_assert_no_error (error); + g_assert (GDATA_IS_CALENDAR_EVENT (data->event3)); + g_object_unref (event); + + uhm_server_end_trace (mock_server); +} + +static void +tear_down_query_events (QueryEventsData *data, gconstpointer service) +{ + gdata_test_mock_server_start_trace (mock_server, "teardown-query-events"); + + /* Delete the events */ + g_assert (gdata_service_delete_entry (GDATA_SERVICE (service), gdata_calendar_service_get_primary_authorization_domain (), + GDATA_ENTRY (data->event1), NULL, NULL) == TRUE); + g_object_unref (data->event1); + + g_assert (gdata_service_delete_entry (GDATA_SERVICE (service), gdata_calendar_service_get_primary_authorization_domain (), + GDATA_ENTRY (data->event2), NULL, NULL) == TRUE); + g_object_unref (data->event2); + + g_assert (gdata_service_delete_entry (GDATA_SERVICE (service), gdata_calendar_service_get_primary_authorization_domain (), + GDATA_ENTRY (data->event3), NULL, NULL) == TRUE); + g_object_unref (data->event3); + + uhm_server_end_trace (mock_server); + + /* Delete the calendar */ + tear_down_temp_calendar ((TempCalendarData*) data, service); +} + +static void +test_query_events (QueryEventsData *data, gconstpointer service) +{ + GDataFeed *feed; + GError *error = NULL; + + gdata_test_mock_server_start_trace (mock_server, "query-events"); + + /* Get the entry feed */ + feed = gdata_calendar_service_query_events (GDATA_CALENDAR_SERVICE (service), data->parent.calendar, NULL, NULL, NULL, NULL, &error); + g_assert_no_error (error); + g_assert (GDATA_IS_CALENDAR_FEED (feed)); + g_clear_error (&error); + + /* TODO: check entries and feed properties */ + + g_object_unref (feed); + + uhm_server_end_trace (mock_server); +} + +GDATA_ASYNC_CLOSURE_FUNCTIONS (query_events, QueryEventsData); + +GDATA_ASYNC_TEST_FUNCTIONS (query_events, QueryEventsData, +G_STMT_START { + gdata_calendar_service_query_events_async (GDATA_CALENDAR_SERVICE (service), data->parent.calendar, NULL, cancellable, NULL, NULL, NULL, + async_ready_callback, async_data); +} G_STMT_END, +G_STMT_START { + GDataFeed *feed; + + feed = gdata_service_query_finish (GDATA_SERVICE (obj), async_result, &error); + + if (error == NULL) { + g_assert (GDATA_IS_CALENDAR_FEED (feed)); + + g_object_unref (feed); + } else { + g_assert (feed == NULL); + } +} G_STMT_END); + +static void +test_query_events_async_progress_closure (QueryEventsData *query_data, gconstpointer service) +{ + GDataAsyncProgressClosure *data = g_slice_new0 (GDataAsyncProgressClosure); + + gdata_test_mock_server_start_trace (mock_server, "query-events-async-progress-closure"); + + data->main_loop = g_main_loop_new (NULL, TRUE); + + gdata_calendar_service_query_events_async (GDATA_CALENDAR_SERVICE (service), query_data->parent.calendar, NULL, NULL, + (GDataQueryProgressCallback) gdata_test_async_progress_callback, + data, (GDestroyNotify) gdata_test_async_progress_closure_free, + (GAsyncReadyCallback) gdata_test_async_progress_finish_callback, data); + + g_main_loop_run (data->main_loop); + g_main_loop_unref (data->main_loop); + + /* Check that both callbacks were called exactly once */ + g_assert_cmpuint (data->progress_destroy_notify_count, ==, 1); + g_assert_cmpuint (data->async_ready_notify_count, ==, 1); + + g_slice_free (GDataAsyncProgressClosure, data); + + uhm_server_end_trace (mock_server); +} + +typedef struct { + TempCalendarData parent; + GDataCalendarEvent *new_event; +} InsertEventData; + +static void +set_up_insert_event (InsertEventData *data, gconstpointer service) +{ + set_up_temp_calendar ((TempCalendarData*) data, service); + data->new_event = NULL; +} + +static void +tear_down_insert_event (InsertEventData *data, gconstpointer service) +{ + gdata_test_mock_server_start_trace (mock_server, "teardown-insert-event"); + + /* Delete the new event */ + g_assert (gdata_service_delete_entry (GDATA_SERVICE (service), gdata_calendar_service_get_primary_authorization_domain (), + GDATA_ENTRY (data->new_event), NULL, NULL) == TRUE); + g_object_unref (data->new_event); + + uhm_server_end_trace (mock_server); + + /* Delete the calendar too */ + tear_down_temp_calendar ((TempCalendarData*) data, service); +} + +static void +test_event_insert (InsertEventData *data, gconstpointer service) +{ + GDataCalendarEvent *event, *new_event; + GDataGDWhere *where; + GDataGDWho *who; + GDataGDWhen *when; + GTimeVal start_time, end_time; + GError *error = NULL; + + gdata_test_mock_server_start_trace (mock_server, "event-insert"); + + event = gdata_calendar_event_new (NULL); + + gdata_entry_set_title (GDATA_ENTRY (event), "Tennis with Beth"); + gdata_entry_set_content (GDATA_ENTRY (event), "Meet for a quick lesson."); + gdata_calendar_event_set_transparency (event, GDATA_GD_EVENT_TRANSPARENCY_OPAQUE); + gdata_calendar_event_set_status (event, GDATA_GD_EVENT_STATUS_CONFIRMED); + where = gdata_gd_where_new (NULL, "Rolling Lawn Courts", NULL); + gdata_calendar_event_add_place (event, where); + g_object_unref (where); + who = gdata_gd_who_new (GDATA_GD_WHO_EVENT_ORGANIZER, "John Smith‽", "john.smith@example.com"); + gdata_calendar_event_add_person (event, who); + g_object_unref (who); + g_time_val_from_iso8601 ("2009-04-17T15:00:00.000Z", &start_time); + g_time_val_from_iso8601 ("2009-04-17T17:00:00.000Z", &end_time); + when = gdata_gd_when_new (start_time.tv_sec, end_time.tv_sec, FALSE); + gdata_calendar_event_add_time (event, when); + g_object_unref (when); + + /* Insert the event */ + new_event = data->new_event = gdata_calendar_service_insert_calendar_event (GDATA_CALENDAR_SERVICE (service), + data->parent.calendar, event, NULL, &error); + g_assert_no_error (error); + g_assert (GDATA_IS_CALENDAR_EVENT (new_event)); + g_clear_error (&error); + + /* TODO: check entries and feed properties */ + + g_object_unref (event); + + uhm_server_end_trace (mock_server); +} + +GDATA_ASYNC_CLOSURE_FUNCTIONS (insert_event, InsertEventData); + +GDATA_ASYNC_TEST_FUNCTIONS (event_insert, InsertEventData, +G_STMT_START { + GDataCalendarEvent *event; + GDataGDWhere *where; + GDataGDWho *who; + GDataGDWhen *when; + GTimeVal start_time; + GTimeVal end_time; + + event = gdata_calendar_event_new (NULL); + + gdata_entry_set_title (GDATA_ENTRY (event), "Tennis with Beth"); + gdata_entry_set_content (GDATA_ENTRY (event), "Meet for a quick lesson."); + gdata_calendar_event_set_transparency (event, GDATA_GD_EVENT_TRANSPARENCY_OPAQUE); + gdata_calendar_event_set_status (event, GDATA_GD_EVENT_STATUS_CONFIRMED); + where = gdata_gd_where_new (NULL, "Rolling Lawn Courts", NULL); + gdata_calendar_event_add_place (event, where); + g_object_unref (where); + who = gdata_gd_who_new (GDATA_GD_WHO_EVENT_ORGANIZER, "John Smith‽", "john.smith@example.com"); + gdata_calendar_event_add_person (event, who); + g_object_unref (who); + g_time_val_from_iso8601 ("2009-04-17T15:00:00.000Z", &start_time); + g_time_val_from_iso8601 ("2009-04-17T17:00:00.000Z", &end_time); + when = gdata_gd_when_new (start_time.tv_sec, end_time.tv_sec, FALSE); + gdata_calendar_event_add_time (event, when); + g_object_unref (when); + + /* Insert the event */ + gdata_calendar_service_insert_calendar_event_async (GDATA_CALENDAR_SERVICE (service), + data->parent.calendar, event, cancellable, + async_ready_callback, async_data); + + g_object_unref (event); +} G_STMT_END, +G_STMT_START { + GDataEntry *event; + event = gdata_service_insert_entry_finish (GDATA_SERVICE (obj), async_result, &error); + if (error == NULL) { + g_assert (GDATA_IS_CALENDAR_EVENT (event)); + data->new_event = GDATA_CALENDAR_EVENT (event); + g_assert_cmpstr (gdata_entry_get_title (event), ==, "Tennis with Beth"); + } else { + g_assert (event == NULL); + } +} G_STMT_END); + +static void +test_event_json (void) +{ + GDataCalendarEvent *event; + GDataGDWhere *where; + GDataGDWho *who; + GDataGDWhen *when; + GTimeVal start_time, end_time; + + event = gdata_calendar_event_new (NULL); + + gdata_entry_set_title (GDATA_ENTRY (event), "Tennis with Beth"); + gdata_entry_set_content (GDATA_ENTRY (event), "Meet for a quick lesson."); + gdata_calendar_event_set_transparency (event, GDATA_GD_EVENT_TRANSPARENCY_OPAQUE); + gdata_calendar_event_set_status (event, GDATA_GD_EVENT_STATUS_CONFIRMED); + where = gdata_gd_where_new (NULL, "Rolling Lawn Courts", NULL); + gdata_calendar_event_add_place (event, where); + g_object_unref (where); + who = gdata_gd_who_new (GDATA_GD_WHO_EVENT_ORGANIZER, "John Smith‽", "john.smith@example.com"); + gdata_calendar_event_add_person (event, who); + g_object_unref (who); + g_time_val_from_iso8601 ("2009-04-17T15:00:00.000Z", &start_time); + g_time_val_from_iso8601 ("2009-04-17T17:00:00.000Z", &end_time); + when = gdata_gd_when_new (start_time.tv_sec, end_time.tv_sec, FALSE); + gdata_calendar_event_add_time (event, when); + g_object_unref (when); + + /* Check the JSON */ + gdata_test_assert_json (event, "{" + "'summary': 'Tennis with Beth'," + "'description': 'Meet for a quick lesson.'," + "'kind': 'calendar#event'," + "'status': 'confirmed'," + "'transparency': 'opaque'," + "'guestsCanModify': false," + "'guestsCanInviteOthers': false," + "'guestsCanSeeOtherGuests': false," + "'anyoneCanAddSelf': false," + "'start': {" + "'dateTime': '2009-04-17T15:00:00Z'," + "'timeZone': 'UTC'" + "}," + "'end': {" + "'dateTime': '2009-04-17T17:00:00Z'," + "'timeZone': 'UTC'" + "}," + "'attendees': [" + "{" + "'email': 'john.smith@example.com'," + "'displayName': 'John Smith‽'," + "'organizer': true" + "}" + "]," + "'organizer': {" + "'email': 'john.smith@example.com'," + "'displayName': 'John Smith‽'" + "}," + "'location': 'Rolling Lawn Courts'" + "}"); +} + +static void +test_event_json_attendees (void) +{ + GDataCalendarEvent *event; + GList/**/ *l; + guint n_people; + const struct { + const gchar *relation_type; + const gchar *value_string; + const gchar *email_address; + } expected[] = { + { GDATA_GD_WHO_EVENT_ATTENDEE, "Joe Hibbs", "person1@gmail.com" }, + { GDATA_GD_WHO_EVENT_ATTENDEE, "Me McMeeson", "me@gmail.com" }, + { GDATA_GD_WHO_EVENT_ATTENDEE, NULL, "person2@gmail.com" }, + { GDATA_GD_WHO_EVENT_ATTENDEE, "Example Person 3", "person3@gmail.com" }, + { GDATA_GD_WHO_EVENT_ATTENDEE, NULL, "person4@gmail.com" }, + { GDATA_GD_WHO_EVENT_ORGANIZER, "Ruth Pettut", "blah@example.com" }, + }; + GError *error = NULL; + + event = GDATA_CALENDAR_EVENT (gdata_parsable_new_from_json (GDATA_TYPE_CALENDAR_EVENT, "{" + "'kind': 'calendar#event'," + "'id': 'some-id'," + "'created': '2017-02-04T17:53:47.000Z'," + "'summary': 'Duff this'," + "'organizer': {" + "'email': 'blah@example.com'," + "'displayName': 'Ruth Pettut'" + "}," + "'attendees': [" + "{" + "'email': 'person1@gmail.com'," + "'displayName': 'Joe Hibbs'," + "'responseStatus': 'accepted'" + "}," + "{" + "'email': 'me@gmail.com'," + "'displayName': 'Me McMeeson'," + "'self': true," + "'responseStatus': 'needsAction'" + "}," + "{" + "'email': 'person2@gmail.com'," + "'responseStatus': 'needsAction'" + "}," + "{" + "'email': 'person3@gmail.com'," + "'displayName': 'Example Person 3'," + "'responseStatus': 'tentative'," + "'comment': 'Some poor excuse about not coming.'" + "}," + "{" + "'email': 'person4@gmail.com'," + "'responseStatus': 'accepted'" + "}," + "{" + "'email': 'blah@example.com'," + "'displayName': 'Ruth Pettut'," + "'organizer': true," + "'responseStatus': 'accepted'" + "}" + "]" + "}", -1, &error)); + g_assert_no_error (error); + g_assert (GDATA_IS_ENTRY (event)); + g_clear_error (&error); + + /* Check attendee details. */ + for (n_people = 0, l = gdata_calendar_event_get_people (event); + l != NULL; + n_people += 1, l = l->next) { + GDataGDWho *who = GDATA_GD_WHO (l->data); + gsize i; + + g_test_message ("Examining attendee: %s", + gdata_gd_who_get_email_address (who)); + + for (i = 0; i < G_N_ELEMENTS (expected); i++) { + if (g_strcmp0 (gdata_gd_who_get_email_address (who), + expected[i].email_address) == 0) { + g_assert_cmpstr (gdata_gd_who_get_relation_type (who), ==, expected[i].relation_type); + g_assert_cmpstr (gdata_gd_who_get_value_string (who), ==, expected[i].value_string); + break; + } + } + + g_assert_cmpuint (i, <, G_N_ELEMENTS (expected)); + } + + g_assert_cmpuint (n_people, ==, G_N_ELEMENTS (expected)); + + g_object_unref (event); +} + +static void +test_event_json_dates (void) +{ + guint i; + + const struct { + const gchar *json; + gboolean is_date; + gint64 start_time; + gint64 end_time; + const gchar *output_json; /* NULL if equal to @json */ + } test_vectors[] = { + /* Plain date, single day. */ + { "'start': {" + "'date': '2009-04-17'," + "'timeZone': 'UTC'" + "}," + "'end': {" + "'date': '2009-04-18'," + "'timeZone': 'UTC'" + "}", TRUE, 1239926400, 1239926400 + 86400, NULL }, + /* Full date and time. */ + { "'start': {" + "'dateTime': '2009-04-17T15:00:00Z'," + "'timeZone': 'UTC'" + "}," + "'end': {" + "'dateTime': '2009-04-17T16:00:00Z'," + "'timeZone': 'UTC'" + "}", FALSE, 1239926400 + 54000, 1239926400 + 54000 + 3600, NULL }, + /* Start and end time. */ + { "'start': {" + "'date': '2009-04-27'," + "'timeZone': 'UTC'" + "}," + "'end': {" + "'date': '20090506'," + "'timeZone': 'UTC'" + "}", TRUE, 1239926400 + 864000, 1241568000, "'start': {" + "'date': '2009-04-27'," + "'timeZone': 'UTC'" + "}," + "'end': {" + "'date': '2009-05-06'," + "'timeZone': 'UTC'" + "}" }, + }; + + for (i = 0; i < G_N_ELEMENTS (test_vectors); i++) { + gchar *json = NULL, *output_json = NULL; /* owned */ + GDataCalendarEvent *event; + GList *j; + GDataGDWhen *when; + gint64 _time; + GError *error = NULL; + + json = g_strdup_printf ("{" + "'summary': 'Tennis with Beth'," + "'description': 'Meet for a quick lesson.'," + "'kind': 'calendar#event'," + "%s" + "}", test_vectors[i].json); + output_json = g_strdup_printf ("{" + "'summary': 'Tennis with Beth'," + "'description': 'Meet for a quick lesson.'," + "'kind': 'calendar#event'," + "'guestsCanModify': false," + "'guestsCanInviteOthers': false," + "'guestsCanSeeOtherGuests': false," + "'anyoneCanAddSelf': false," + "'attendees': []," + "%s" + "}", (test_vectors[i].output_json != NULL) ? test_vectors[i].output_json : test_vectors[i].json); + + event = GDATA_CALENDAR_EVENT (gdata_parsable_new_from_json (GDATA_TYPE_CALENDAR_EVENT, json, -1, &error)); + g_assert_no_error (error); + g_assert (GDATA_IS_ENTRY (event)); + g_clear_error (&error); + + /* Check the times */ + j = gdata_calendar_event_get_times (event); + g_assert (j != NULL); + + when = GDATA_GD_WHEN (j->data); + g_assert (gdata_gd_when_is_date (when) == test_vectors[i].is_date); + _time = gdata_gd_when_get_start_time (when); + g_assert_cmpint (_time, ==, test_vectors[i].start_time); + _time = gdata_gd_when_get_end_time (when); + g_assert_cmpint (_time, ==, test_vectors[i].end_time); + g_assert (gdata_gd_when_get_value_string (when) == NULL); + g_assert (gdata_gd_when_get_reminders (when) == NULL); + + /* Should be no other times. */ + g_assert (j->next == NULL); + + /* Check the JSON */ + gdata_test_assert_json (event, output_json); + + g_object_unref (event); + g_free (output_json); + g_free (json); + } +} + +static void +test_event_json_organizer (void) +{ + GDataCalendarEvent *event; + GError *error = NULL; + + event = GDATA_CALENDAR_EVENT (gdata_parsable_new_from_json (GDATA_TYPE_CALENDAR_EVENT, "{" + "'kind': 'calendar#event'," + "'id': 'some-id'," + "'created': '2013-12-22T18:00:00.000Z'," + "'summary': 'FOSDEM GNOME Beer Event'," + "'organizer': {" + "'id': 'another-id'," + "'displayName': 'Guillaume Desmottes'" + "}," + "'attendees': [" + "{" + "'id': 'another-id'," + "'displayName': 'Guillaume Desmottes'," + "'organizer': true," + "'responseStatus': 'accepted'" + "}" + "]" + "}", -1, &error)); + g_assert_no_error (error); + g_assert (GDATA_IS_ENTRY (event)); + g_clear_error (&error); + + g_object_unref (event); +} + +static void +test_event_json_recurrence (void) +{ + GDataCalendarEvent *event; + GError *error = NULL; + gchar *id, *uri; + + event = GDATA_CALENDAR_EVENT (gdata_parsable_new_from_json (GDATA_TYPE_CALENDAR_EVENT, "{" + "'id': 'https://www.googleapis.com/calendar/v3/calendars/libgdata.test@googlemail.com/events/g5928e82rrch95b25f8ud0dlsg_20090429T153000Z'," + "'updated': '2009-04-27T17:54:10.000Z'," + "'summary': 'Test daily instance event'," + "'kind': 'calendar#event'," + "'creator': {" + "'displayName': 'GData Test'," + "'email': 'libgdata.test@googlemail.com'" + "}," + "'recurringEventId': 'g5928e82rrch95b25f8ud0dlsg'," + "'originalStartTime': {" + "'dateTime': '2009-04-29T16:30:00.000+01:00'," + "'timeZone': 'UTC'" + "}," + "'guestsCanModify': false," + "'guestsCanInviteOthers': false," + "'guestsCanSeeOtherGuests': false," + "'anyoneCanAddSelf': false," + "'status': 'confirmed'," + "'visibility': 'private'," + "'transparency': 'opaque'," + "'iCalUID': 'g5928e82rrch95b25f8ud0dlsg@google.com'," + "'sequence': '0'," + "'start': {" + "'dateTime': '2009-04-29T17:30:00.000+01:00'," + "'timeZone': 'UTC'" + "}," + "'end': {" + "'dateTime': '2009-04-29T17:30:00.000+01:00'," + "'timeZone': 'UTC'" + "}," + "'reminders': {" + "'overrides': [{" + "'method': 'email'," + "'minutes': 10" + "}, {" + "'method': 'popup'," + "'minutes': 10" + "}]" + "}," + "'attendees': [" + "{" + "'email': 'libgdata.test@googlemail.com'," + "'displayName': 'GData Test'," + "'organizer': true," + "'responseStatus': 'needsAction'" + "}" + "]," + "'organizer': {" + "'email': 'libgdata.test@googlemail.com'," + "'displayName': 'GData Test'" + "}" + "}", -1, &error)); + g_assert_no_error (error); + g_assert (GDATA_IS_ENTRY (event)); + g_clear_error (&error); + + /* Check the original event */ + g_assert (gdata_calendar_event_is_exception (event) == TRUE); + + gdata_calendar_event_get_original_event_details (event, &id, &uri); + g_assert_cmpstr (id, ==, "g5928e82rrch95b25f8ud0dlsg"); + g_assert_cmpstr (uri, ==, "https://www.googleapis.com/calendar/v3/events/g5928e82rrch95b25f8ud0dlsg"); + + g_free (id); + g_free (uri); + g_object_unref (event); +} + +static void +test_calendar_escaping (void) +{ + GDataCalendarCalendar *calendar; + + calendar = gdata_calendar_calendar_new (NULL); + gdata_calendar_calendar_set_timezone (calendar, ""); + + /* Check the outputted JSON is escaped properly */ + gdata_test_assert_json (calendar, "{" + "'kind': 'calendar#calendar'," + "'timeZone': ''," + "'hidden': false," + "'backgroundColor': '#000000'," + "'selected': false" + "}"); + g_object_unref (calendar); +} + +static void +test_event_escaping (void) +{ + GDataCalendarEvent *event; + + event = gdata_calendar_event_new (NULL); + gdata_calendar_event_set_status (event, "\"status\""); + gdata_calendar_event_set_visibility (event, "\"visibility\""); + gdata_calendar_event_set_transparency (event, "\"transparency\""); + gdata_calendar_event_set_uid (event, "\"uid\""); + gdata_calendar_event_set_recurrence (event, "\"recurrence\""); + + /* Check the outputted JSON is escaped properly */ + gdata_test_assert_json (event, "{" + "'kind': 'calendar#event'," + "'status': '\"status\"'," + "'transparency': '\"transparency\"'," + "'visibility': '\"visibility\"'," + "'iCalUID': '\"uid\"'," + "'recurrence': [ '\"recurrence\"' ]," + "'guestsCanModify': false," + "'guestsCanInviteOthers': false," + "'guestsCanSeeOtherGuests': false," + "'anyoneCanAddSelf': false," + "'attendees': []" + "}"); + g_object_unref (event); +} + +/* Test the event parser with the minimal number of properties specified. */ +static void +test_calendar_event_parser_minimal (void) +{ + GDataCalendarEvent *event = NULL; /* owned */ + GDataEntry *entry; /* unowned */ + GError *error = NULL; + + event = GDATA_CALENDAR_EVENT (gdata_parsable_new_from_json (GDATA_TYPE_CALENDAR_EVENT, + "{" + "\"kind\": \"calendar#event\"," + "\"etag\": \"\\\"2838230136828000\\\"\"," + "\"id\": \"hsfgtc50u68vdai81t6634u7lg\"," + "\"status\": \"confirmed\"," + "\"htmlLink\": \"https://www.google.com/calendar/event?eid=aHNmZ3RjNTB1Njh2ZGFpODF0NjYzNHU3bGcgODk5MWkzNjM0YzRzN3Nwa3NrcjNjZjVuanNAZw\"," + "\"created\": \"2014-12-20T22:37:48.000Z\"," + "\"updated\": \"2014-12-20T22:37:48.414Z\"," + "\"summary\": \"Test Event 1\"," + "\"creator\": {" + "\"email\": \"libgdata.test@googlemail.com\"," + "\"displayName\": \"GData Test\"" + "}," + "\"organizer\": {" + "\"email\": \"8991i3634c4s7spkskr3cf5njs@group.calendar.google.com\"," + "\"displayName\": \"Temp Test Calendar\"," + "\"self\": true" + "}," + "\"start\": {" + "\"dateTime\": \"2014-12-20T22:15:27Z\"," + "\"timeZone\": \"UTC\"" + "}," + "\"end\": {" + "\"dateTime\": \"2014-12-20T22:15:28Z\"," + "\"timeZone\": \"UTC\"" + "}," + "\"iCalUID\": \"hsfgtc50u68vdai81t6634u7lg@google.com\"," + "\"sequence\": 0," + "\"guestsCanInviteOthers\": false," + "\"guestsCanSeeOtherGuests\": false," + "\"reminders\": {" + "\"useDefault\": true" + "}" + "}", -1, &error)); + g_assert_no_error (error); + g_assert (GDATA_IS_CALENDAR_EVENT (event)); + gdata_test_compare_kind (GDATA_ENTRY (event), "calendar#event", NULL); + + entry = GDATA_ENTRY (event); + + /* Check the event’s properties. */ + g_assert_cmpstr (gdata_entry_get_id (entry), ==, + "hsfgtc50u68vdai81t6634u7lg"); + g_assert_cmpstr (gdata_entry_get_etag (entry), ==, + "\"2838230136828000\""); + g_assert_cmpstr (gdata_entry_get_title (entry), ==, + "Test Event 1"); + g_assert_cmpint (gdata_entry_get_updated (entry), ==, 1419115068); + + /* TODO: check everything else */ + + g_object_unref (event); +} + +static void +test_access_rule_properties (void) +{ + GDataCalendarAccessRule *rule; + const gchar *scope_type, *scope_value; + + rule = gdata_calendar_access_rule_new (NULL); + + gdata_access_rule_set_role (GDATA_ACCESS_RULE (rule), GDATA_CALENDAR_ACCESS_ROLE_EDITOR); + g_assert_cmpstr (gdata_access_rule_get_role (GDATA_ACCESS_RULE (rule)), ==, GDATA_CALENDAR_ACCESS_ROLE_EDITOR); + + gdata_access_rule_set_scope (GDATA_ACCESS_RULE (rule), GDATA_ACCESS_SCOPE_USER, "darcy@gmail.com"); + gdata_access_rule_get_scope (GDATA_ACCESS_RULE (rule), &scope_type, &scope_value); + g_assert_cmpstr (scope_type, ==, GDATA_ACCESS_SCOPE_USER); + g_assert_cmpstr (scope_value, ==, "darcy@gmail.com"); +} + +static void +test_access_rule_json (void) +{ + GDataCalendarAccessRule *rule; + + rule = gdata_calendar_access_rule_new (NULL); + + gdata_access_rule_set_role (GDATA_ACCESS_RULE (rule), GDATA_CALENDAR_ACCESS_ROLE_EDITOR); + gdata_access_rule_set_scope (GDATA_ACCESS_RULE (rule), GDATA_ACCESS_SCOPE_USER, "darcy@gmail.com"); + + /* Check the JSON */ + gdata_test_assert_json (rule, "{" + "'kind': 'calendar#aclRule'," + "'role': 'writer'," + "'scope': {" + "'type': 'user'," + "'value': 'darcy@gmail.com'" + "}" + "}"); +} + +static void +test_query_uri (void) +{ + gint64 _time; + GTimeVal time_val; + gchar *query_uri; + GDataCalendarQuery *query = gdata_calendar_query_new ("q"); + + /* Set to false or it will override our startMin below. */ + gdata_calendar_query_set_future_events (query, FALSE); + g_assert (gdata_calendar_query_get_future_events (query) == FALSE); + + gdata_calendar_query_set_order_by (query, "starttime"); + g_assert_cmpstr (gdata_calendar_query_get_order_by (query), ==, "starttime"); + +G_GNUC_BEGIN_IGNORE_DEPRECATIONS + g_time_val_from_iso8601 ("2009-04-17T15:00:00.000Z", &time_val); + gdata_calendar_query_set_recurrence_expansion_start (query, time_val.tv_sec); + _time = gdata_calendar_query_get_recurrence_expansion_start (query); + g_assert_cmpint (_time, ==, time_val.tv_sec); + + g_time_val_from_iso8601 ("2010-04-17T15:00:00.000Z", &time_val); + gdata_calendar_query_set_recurrence_expansion_end (query, time_val.tv_sec); + _time = gdata_calendar_query_get_recurrence_expansion_end (query); + g_assert_cmpint (_time, ==, time_val.tv_sec); +G_GNUC_END_IGNORE_DEPRECATIONS + + gdata_calendar_query_set_single_events (query, TRUE); + g_assert (gdata_calendar_query_get_single_events (query) == TRUE); + +G_GNUC_BEGIN_IGNORE_DEPRECATIONS + gdata_calendar_query_set_sort_order (query, "descending"); + g_assert_cmpstr (gdata_calendar_query_get_sort_order (query), ==, "descending"); +G_GNUC_END_IGNORE_DEPRECATIONS + + g_time_val_from_iso8601 ("2009-04-17T15:00:00.000Z", &time_val); + gdata_calendar_query_set_start_min (query, time_val.tv_sec); + _time = gdata_calendar_query_get_start_min (query); + g_assert_cmpint (_time, ==, time_val.tv_sec); + + g_time_val_from_iso8601 ("2010-04-17T15:00:00.000Z", &time_val); + gdata_calendar_query_set_start_max (query, time_val.tv_sec); + _time = gdata_calendar_query_get_start_max (query); + g_assert_cmpint (_time, ==, time_val.tv_sec); + + gdata_calendar_query_set_timezone (query, "America/Los Angeles"); + g_assert_cmpstr (gdata_calendar_query_get_timezone (query), ==, "America/Los_Angeles"); + + gdata_calendar_query_set_max_attendees (query, 15); + g_assert_cmpuint (gdata_calendar_query_get_max_attendees (query), ==, 15); + + gdata_calendar_query_set_show_deleted (query, TRUE); + g_assert (gdata_calendar_query_show_deleted (query) == TRUE); + + /* Check the built query URI with a normal feed URI */ + query_uri = gdata_query_get_query_uri (GDATA_QUERY (query), "http://example.com"); + g_assert_cmpstr (query_uri, ==, "http://example.com?q=q&orderBy=startTime&singleEvents=true" + "&timeMin=2009-04-17T15:00:00Z&timeMax=2010-04-17T15:00:00Z&timeZone=America%2FLos_Angeles&maxAttendees=15" + "&showDeleted=true"); + g_free (query_uri); + + /* …with a feed URI with a trailing slash */ + query_uri = gdata_query_get_query_uri (GDATA_QUERY (query), "http://example.com/"); + g_assert_cmpstr (query_uri, ==, "http://example.com/?q=q&orderBy=startTime&singleEvents=true" + "&timeMin=2009-04-17T15:00:00Z&timeMax=2010-04-17T15:00:00Z&timeZone=America%2FLos_Angeles&maxAttendees=15" + "&showDeleted=true"); + g_free (query_uri); + + /* …with a feed URI with pre-existing arguments */ + query_uri = gdata_query_get_query_uri (GDATA_QUERY (query), "http://example.com/bar/?test=test&this=that"); + g_assert_cmpstr (query_uri, ==, "http://example.com/bar/?test=test&this=that&q=q&orderBy=startTime" + "&singleEvents=true&timeMin=2009-04-17T15:00:00Z&timeMax=2010-04-17T15:00:00Z" + "&timeZone=America%2FLos_Angeles&maxAttendees=15&showDeleted=true"); + g_free (query_uri); + + g_object_unref (query); +} + +static void +test_query_etag (void) +{ + GDataCalendarQuery *query = gdata_calendar_query_new (NULL); + + /* Test that setting any property will unset the ETag */ + g_test_bug ("613529"); + +#define CHECK_ETAG(C) \ + gdata_query_set_etag (GDATA_QUERY (query), "foobar"); \ + (C); \ + g_assert (gdata_query_get_etag (GDATA_QUERY (query)) == NULL); + + CHECK_ETAG (gdata_calendar_query_set_future_events (query, FALSE)) + CHECK_ETAG (gdata_calendar_query_set_order_by (query, "shizzle")) +G_GNUC_BEGIN_IGNORE_DEPRECATIONS + CHECK_ETAG (gdata_calendar_query_set_recurrence_expansion_start (query, -1)) + CHECK_ETAG (gdata_calendar_query_set_recurrence_expansion_end (query, -1)) +G_GNUC_END_IGNORE_DEPRECATIONS + CHECK_ETAG (gdata_calendar_query_set_single_events (query, FALSE)) +G_GNUC_BEGIN_IGNORE_DEPRECATIONS + CHECK_ETAG (gdata_calendar_query_set_sort_order (query, "shizzle")) +G_GNUC_END_IGNORE_DEPRECATIONS + CHECK_ETAG (gdata_calendar_query_set_start_min (query, -1)) + CHECK_ETAG (gdata_calendar_query_set_start_max (query, -1)) + CHECK_ETAG (gdata_calendar_query_set_timezone (query, "about now")) + CHECK_ETAG (gdata_calendar_query_set_max_attendees (query, 10)) + CHECK_ETAG (gdata_calendar_query_set_show_deleted (query, TRUE)) + +#undef CHECK_ETAG + + g_object_unref (query); +} + +typedef struct { + TempCalendarData parent; + GDataCalendarAccessRule *rule; +} TempCalendarAclsData; + +static void +calendar_access_rule_set_self_link (GDataCalendarCalendar *parent_calendar, + GDataCalendarAccessRule *rule) +{ + GDataLink *_link = NULL; /* owned */ + const gchar *calendar_id, *id; + gchar *uri = NULL; /* owned */ + + /* FIXME: Horrendous hack to set the self link, which is needed for + * gdata_service_delete_entry(). Unfortunately, it needs the + * ACL ID _and_ the calendar ID. + * + * Do _not_ copy this code. It needs to be fixed architecturally in + * libgdata. */ + calendar_id = gdata_entry_get_id (GDATA_ENTRY (parent_calendar)); + id = gdata_entry_get_id (GDATA_ENTRY (rule)); + uri = g_strconcat ("https://www.googleapis.com" + "/calendar/v3/calendars/", + calendar_id, "/acl/", id, NULL); + _link = gdata_link_new (uri, GDATA_LINK_SELF); + gdata_entry_add_link (GDATA_ENTRY (rule), _link); + g_object_unref (_link); + g_free (uri); +} + +static void +set_up_temp_calendar_acls (TempCalendarAclsData *data, gconstpointer service) +{ + GDataCalendarAccessRule *rule; + GDataLink *_link; + GError *error = NULL; + + /* Set up a calendar */ + set_up_temp_calendar ((TempCalendarData*) data, service); + + gdata_test_mock_server_start_trace (mock_server, "setup-temp-calendar-acls"); + + /* Add an access rule to the calendar */ + rule = gdata_calendar_access_rule_new (NULL); + + gdata_access_rule_set_role (GDATA_ACCESS_RULE (rule), GDATA_CALENDAR_ACCESS_ROLE_EDITOR); + gdata_access_rule_set_scope (GDATA_ACCESS_RULE (rule), GDATA_ACCESS_SCOPE_USER, "darcy@gmail.com"); + + /* Insert the rule */ + _link = gdata_entry_look_up_link (GDATA_ENTRY (data->parent.calendar), GDATA_LINK_ACCESS_CONTROL_LIST); + g_assert (_link != NULL); + + data->rule = GDATA_CALENDAR_ACCESS_RULE (gdata_service_insert_entry (GDATA_SERVICE (service), + gdata_calendar_service_get_primary_authorization_domain (), + gdata_link_get_uri (_link), GDATA_ENTRY (rule), NULL, + &error)); + g_assert_no_error (error); + g_assert (GDATA_IS_CALENDAR_ACCESS_RULE (data->rule)); + + calendar_access_rule_set_self_link (data->parent.calendar, data->rule); + + g_object_unref (rule); + + uhm_server_end_trace (mock_server); +} + +static void +set_up_temp_calendar_acls_no_insertion (TempCalendarAclsData *data, gconstpointer service) +{ + set_up_temp_calendar ((TempCalendarData*) data, service); + data->rule = NULL; +} + +static void +tear_down_temp_calendar_acls (TempCalendarAclsData *data, gconstpointer service) +{ + /* Delete the access rule if it still exists */ + if (data->rule != NULL) { + gdata_test_mock_server_start_trace (mock_server, "teardown-temp-calendar-acls"); + + g_assert (gdata_service_delete_entry (GDATA_SERVICE (service), gdata_calendar_service_get_primary_authorization_domain (), + GDATA_ENTRY (data->rule), NULL, NULL) == TRUE); + g_object_unref (data->rule); + + uhm_server_end_trace (mock_server); + } + + /* Delete the calendar */ + tear_down_temp_calendar ((TempCalendarData*) data, service); +} + +static void +test_access_rule_get (TempCalendarAclsData *data, gconstpointer service) +{ + GDataFeed *feed; + GError *error = NULL; + + gdata_test_mock_server_start_trace (mock_server, "access-rule-get"); + + /* Get the rules */ + feed = gdata_access_handler_get_rules (GDATA_ACCESS_HANDLER (data->parent.calendar), GDATA_SERVICE (service), NULL, NULL, NULL, &error); + g_assert_no_error (error); + g_assert (GDATA_IS_FEED (feed)); + g_clear_error (&error); + + /* TODO: check rules and feed properties */ + + g_object_unref (feed); + + uhm_server_end_trace (mock_server); +} + +static void +test_access_rule_insert (TempCalendarAclsData *data, gconstpointer service) +{ + GDataCalendarAccessRule *rule, *new_rule; + const gchar *scope_type, *scope_value; + GDataCategory *category; + GDataLink *_link; + GList *categories; + gint64 edited; + GError *error = NULL; + + gdata_test_mock_server_start_trace (mock_server, "access-rule-insert"); + + rule = gdata_calendar_access_rule_new (NULL); + + gdata_access_rule_set_role (GDATA_ACCESS_RULE (rule), GDATA_CALENDAR_ACCESS_ROLE_EDITOR); + gdata_access_rule_set_scope (GDATA_ACCESS_RULE (rule), GDATA_ACCESS_SCOPE_USER, "darcy@gmail.com"); + + /* Insert the rule */ + _link = gdata_entry_look_up_link (GDATA_ENTRY (data->parent.calendar), GDATA_LINK_ACCESS_CONTROL_LIST); + g_assert (_link != NULL); + + new_rule = data->rule = GDATA_CALENDAR_ACCESS_RULE (gdata_service_insert_entry (GDATA_SERVICE (service), + gdata_calendar_service_get_primary_authorization_domain (), + gdata_link_get_uri (_link), GDATA_ENTRY (rule), NULL, &error)); + g_assert_no_error (error); + g_assert (GDATA_IS_ACCESS_RULE (new_rule)); + g_clear_error (&error); + + calendar_access_rule_set_self_link (data->parent.calendar, data->rule); + + /* Check the properties of the returned rule */ + g_assert_cmpstr (gdata_access_rule_get_role (GDATA_ACCESS_RULE (new_rule)), ==, GDATA_CALENDAR_ACCESS_ROLE_EDITOR); + gdata_access_rule_get_scope (GDATA_ACCESS_RULE (new_rule), &scope_type, &scope_value); + g_assert_cmpstr (scope_type, ==, GDATA_ACCESS_SCOPE_USER); + g_assert_cmpstr (scope_value, ==, "darcy@gmail.com"); + edited = gdata_access_rule_get_edited (GDATA_ACCESS_RULE (new_rule)); + g_assert_cmpuint (edited, >, 0); + + /* Check it only has the one category and that it's correct */ + categories = gdata_entry_get_categories (GDATA_ENTRY (new_rule)); + g_assert (categories != NULL); + g_assert_cmpuint (g_list_length (categories), ==, 1); + category = categories->data; + g_assert_cmpstr (gdata_category_get_term (category), ==, "calendar#aclRule"); + g_assert_cmpstr (gdata_category_get_scheme (category), ==, "http://schemas.google.com/g/2005#kind"); + g_assert (gdata_category_get_label (category) == NULL); + + /* TODO: Check more properties? */ + + g_object_unref (rule); + + uhm_server_end_trace (mock_server); +} + +static void +test_access_rule_update (TempCalendarAclsData *data, gconstpointer service) +{ + GDataCalendarAccessRule *new_rule; + const gchar *scope_type, *scope_value; + gint64 edited; + GError *error = NULL; + + gdata_test_mock_server_start_trace (mock_server, "access-rule-update"); + + /* Update the rule */ + gdata_access_rule_set_role (GDATA_ACCESS_RULE (data->rule), GDATA_CALENDAR_ACCESS_ROLE_READ); + + /* Send the update to the server */ + new_rule = GDATA_CALENDAR_ACCESS_RULE (gdata_service_update_entry (GDATA_SERVICE (service), gdata_calendar_service_get_primary_authorization_domain (), + GDATA_ENTRY (data->rule), NULL, &error)); + g_assert_no_error (error); + g_assert (GDATA_IS_ACCESS_RULE (new_rule)); + g_clear_error (&error); + + calendar_access_rule_set_self_link (data->parent.calendar, new_rule); + + /* Check the properties of the returned rule */ + g_assert_cmpstr (gdata_access_rule_get_role (GDATA_ACCESS_RULE (new_rule)), ==, GDATA_CALENDAR_ACCESS_ROLE_READ); + gdata_access_rule_get_scope (GDATA_ACCESS_RULE (new_rule), &scope_type, &scope_value); + g_assert_cmpstr (scope_type, ==, GDATA_ACCESS_SCOPE_USER); + g_assert_cmpstr (scope_value, ==, "darcy@gmail.com"); + edited = gdata_access_rule_get_edited (GDATA_ACCESS_RULE (new_rule)); + g_assert_cmpuint (edited, >, 0); + + g_object_unref (new_rule); + + uhm_server_end_trace (mock_server); +} + +static void +test_access_rule_delete (TempCalendarAclsData *data, gconstpointer service) +{ + gboolean success; + GError *error = NULL; + + gdata_test_mock_server_start_trace (mock_server, "access-rule-delete"); + + /* Delete the rule */ + success = gdata_service_delete_entry (GDATA_SERVICE (service), gdata_calendar_service_get_primary_authorization_domain (), + GDATA_ENTRY (data->rule), NULL, &error); + g_assert_no_error (error); + g_assert (success == TRUE); + g_clear_error (&error); + + g_object_unref (data->rule); + data->rule = NULL; + + uhm_server_end_trace (mock_server); +} + +static void +mock_server_notify_resolver_cb (GObject *object, GParamSpec *pspec, gpointer user_data) +{ + UhmServer *server; + UhmResolver *resolver; + + server = UHM_SERVER (object); + + /* Set up the expected domain names here. This should technically be split up between + * the different unit test suites, but that's too much effort. */ + resolver = uhm_server_get_resolver (server); + + if (resolver != NULL) { + const gchar *ip_address = uhm_server_get_address (server); + + uhm_resolver_add_A (resolver, "www.google.com", ip_address); + uhm_resolver_add_A (resolver, "www.googleapis.com", ip_address); + uhm_resolver_add_A (resolver, + "accounts.google.com", ip_address); + } +} + +/* Set up a global GDataAuthorizer to be used for all the tests. Unfortunately, + * the Google Calendar API is limited to OAuth1 and OAuth2 authorisation, so + * this requires user interaction when online. + * + * If not online, use a dummy authoriser. */ +static GDataAuthorizer * +create_global_authorizer (void) +{ + GDataOAuth2Authorizer *authorizer = NULL; /* owned */ + gchar *authentication_uri, *authorisation_code; + GError *error = NULL; + + /* If not online, just return a dummy authoriser. */ + if (!uhm_server_get_enable_online (mock_server)) { + return GDATA_AUTHORIZER (gdata_dummy_authorizer_new (GDATA_TYPE_CALENDAR_SERVICE)); + } + + /* Otherwise, go through the interactive OAuth dance. */ + gdata_test_mock_server_start_trace (mock_server, "global-authentication"); + authorizer = gdata_oauth2_authorizer_new (CLIENT_ID, CLIENT_SECRET, + REDIRECT_URI, + GDATA_TYPE_CALENDAR_SERVICE); + + /* Get an authentication URI */ + authentication_uri = gdata_oauth2_authorizer_build_authentication_uri (authorizer, NULL, FALSE); + g_assert (authentication_uri != NULL); + + /* Get the authorisation code off the user. */ + authorisation_code = gdata_test_query_user_for_verifier (authentication_uri); + + g_free (authentication_uri); + + if (authorisation_code == NULL) { + /* Skip tests. */ + g_object_unref (authorizer); + authorizer = NULL; + goto skip_test; + } + + /* Authorise the token */ + g_assert (gdata_oauth2_authorizer_request_authorization (authorizer, authorisation_code, NULL, &error)); + g_assert_no_error (error); + +skip_test: + g_free (authorisation_code); + + uhm_server_end_trace (mock_server); + + return GDATA_AUTHORIZER (authorizer); +} + +int +main (int argc, char *argv[]) +{ + gint retval; + GDataAuthorizer *authorizer = NULL; + GDataService *service = NULL; + GFile *trace_directory; + gchar *path = NULL; + + gdata_test_init (argc, argv); + + mock_server = gdata_test_get_mock_server (); + g_signal_connect (G_OBJECT (mock_server), "notify::resolver", (GCallback) mock_server_notify_resolver_cb, NULL); + path = g_test_build_filename (G_TEST_DIST, "traces/calendar", NULL); + trace_directory = g_file_new_for_path (path); + g_free (path); + uhm_server_set_trace_directory (mock_server, trace_directory); + g_object_unref (trace_directory); + + authorizer = create_global_authorizer (); + + service = GDATA_SERVICE (gdata_calendar_service_new (authorizer)); + + g_test_add_func ("/calendar/authentication", test_authentication); + + g_test_add ("/calendar/query/all_calendars", QueryCalendarsData, service, set_up_query_calendars, test_query_all_calendars, + tear_down_query_calendars); + g_test_add ("/calendar/query/all_calendars/async", GDataAsyncTestData, service, set_up_query_calendars_async, + test_query_all_calendars_async, tear_down_query_calendars_async); + g_test_add ("/calendar/query/all_calendars/async/progress_closure", QueryCalendarsData, service, set_up_query_calendars, + test_query_all_calendars_async_progress_closure, tear_down_query_calendars); + g_test_add ("/calendar/query/all_calendars/async/cancellation", GDataAsyncTestData, service, set_up_query_calendars_async, + test_query_all_calendars_async_cancellation, tear_down_query_calendars_async); + + g_test_add ("/calendar/query/own_calendars", QueryCalendarsData, service, set_up_query_calendars, test_query_own_calendars, + tear_down_query_calendars); + g_test_add ("/calendar/query/own_calendars/async", GDataAsyncTestData, service, set_up_query_calendars_async, + test_query_own_calendars_async, tear_down_query_calendars_async); + g_test_add ("/calendar/query/own_calendars/async/progress_closure", QueryCalendarsData, service, set_up_query_calendars, + test_query_own_calendars_async_progress_closure, tear_down_query_calendars); + g_test_add ("/calendar/query/own_calendars/async/cancellation", GDataAsyncTestData, service, set_up_query_calendars_async, + test_query_own_calendars_async_cancellation, tear_down_query_calendars_async); + + g_test_add ("/calendar/query/events", QueryEventsData, service, set_up_query_events, test_query_events, tear_down_query_events); + g_test_add ("/calendar/query/events/async", GDataAsyncTestData, service, set_up_query_events_async, test_query_events_async, + tear_down_query_events_async); + g_test_add ("/calendar/query/events/async/progress_closure", QueryEventsData, service, set_up_query_events, + test_query_events_async_progress_closure, tear_down_query_events); + g_test_add ("/calendar/query/events/async/cancellation", GDataAsyncTestData, service, set_up_query_events_async, + test_query_events_async_cancellation, tear_down_query_events_async); + + g_test_add ("/calendar/event/insert", InsertEventData, service, set_up_insert_event, test_event_insert, tear_down_insert_event); + g_test_add ("/calendar/event/insert/async", GDataAsyncTestData, service, set_up_insert_event_async, test_event_insert_async, + tear_down_insert_event_async); + g_test_add ("/calendar/event/insert/async/cancellation", GDataAsyncTestData, service, set_up_insert_event_async, + test_event_insert_async_cancellation, tear_down_insert_event_async); + + g_test_add ("/calendar/access-rule/get", TempCalendarAclsData, service, set_up_temp_calendar_acls, test_access_rule_get, + tear_down_temp_calendar_acls); + g_test_add ("/calendar/access-rule/insert", TempCalendarAclsData, service, set_up_temp_calendar_acls_no_insertion, + test_access_rule_insert, tear_down_temp_calendar_acls); + g_test_add ("/calendar/access-rule/update", TempCalendarAclsData, service, set_up_temp_calendar_acls, test_access_rule_update, + tear_down_temp_calendar_acls); + g_test_add ("/calendar/access-rule/delete", TempCalendarAclsData, service, set_up_temp_calendar_acls, test_access_rule_delete, + tear_down_temp_calendar_acls); + + g_test_add_func ("/calendar/event/json", test_event_json); + g_test_add_func ("/calendar/event/json/attendees", test_event_json_attendees); + g_test_add_func ("/calendar/event/json/dates", test_event_json_dates); + g_test_add_func ("/calendar/event/json/organizer", test_event_json_organizer); + g_test_add_func ("/calendar/event/json/recurrence", test_event_json_recurrence); + g_test_add_func ("/calendar/event/escaping", test_event_escaping); + g_test_add_func ("/calendar/event/parser/minimal", + test_calendar_event_parser_minimal); + + g_test_add_func ("/calendar/calendar/escaping", test_calendar_escaping); + + g_test_add_func ("/calendar/access-rule/properties", test_access_rule_properties); + g_test_add_func ("/calendar/access-rule/json", test_access_rule_json); + + g_test_add_func ("/calendar/query/uri", test_query_uri); + g_test_add_func ("/calendar/query/etag", test_query_etag); + + retval = g_test_run (); + + if (service != NULL) + g_object_unref (service); + + return retval; +} diff --git a/gdata/tests/cert.pem b/gdata/tests/cert.pem new file mode 100644 index 0000000..2dfc433 --- /dev/null +++ b/gdata/tests/cert.pem @@ -0,0 +1,23 @@ +-----BEGIN CERTIFICATE----- +MIID6TCCAtGgAwIBAgIJAI9hYGsc661fMA0GCSqGSIb3DQEBBQUAMIGKMQswCQYD +VQQGEwJHQjEVMBMGA1UEBwwMRGVmYXVsdCBDaXR5MREwDwYDVQQKDAhsaWJnZGF0 +YTEOMAwGA1UECwwFVGVzdHMxFzAVBgNVBAMMDmxpYmdkYXRhIHRlc3RzMSgwJgYJ +KoZIhvcNAQkBFhlsaWJnZGF0YS1tYWludEBnbm9tZS5idWdzMB4XDTEzMDcwNjE3 +NDQxNFoXDTEzMDgwNTE3NDQxNFowgYoxCzAJBgNVBAYTAkdCMRUwEwYDVQQHDAxE +ZWZhdWx0IENpdHkxETAPBgNVBAoMCGxpYmdkYXRhMQ4wDAYDVQQLDAVUZXN0czEX +MBUGA1UEAwwObGliZ2RhdGEgdGVzdHMxKDAmBgkqhkiG9w0BCQEWGWxpYmdkYXRh +LW1haW50QGdub21lLmJ1Z3MwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIB +AQDCbpdfrtWTz+ZpNaVZuxaeAAY+f/xZz4wEH1gaNBNb3u9CPEWofW+fLNB6izkn +f9qhx2K8PrM9LKHDJS4uUU9dkfQHQsrCSffRWqQTeOOnpYHjS21iDYdOt4e//f/J +erAEIyWMQAP5eqMt4hp5wrfhSh2ul9lcHz2Lv5u6H+I8ygoUaMyH15WIlEzxOsn4 +i+lXSkdmso2n1FYbiMyyMYButnnmv+EcPvOdw88PB8Y6PnCN2Ye0fo9HvcJhHEdg +GM4SKsejA/L+T8fX0FYCXrsLPYU0Ntm15ZV8nNsxCoZFGmdTs/prL8ztXaI1tYdi +lI1RKVTOVxD2DKdrCs5bnxYhAgMBAAGjUDBOMB0GA1UdDgQWBBQwhz/4hEriPnF5 +F3TDY9TQLzxlnDAfBgNVHSMEGDAWgBQwhz/4hEriPnF5F3TDY9TQLzxlnDAMBgNV +HRMEBTADAQH/MA0GCSqGSIb3DQEBBQUAA4IBAQAIVnySe76zjb5UHromPibgT9eL +n8oZ76aGj6+VMLucpaK8K7U7y2ONAO+BB+wUyLaq48EYb6DmpFKThAxTajYd1f/7 +14bJIew8papMEooiJHyOVfZPLOePjCldV5+hPfwsfJ3NSDL8dc+IB2PQmgp32nom +9uvQMOdD56hHSIP5zFZwNiWH75piWyUNs/+cbHKgnyVGWaoVd7z3E5dNelOMopbo +qvWk2MM3nHpiQqMZyliTkq5uD2Q8WiXBD4rPUeEU55NaPslB8xKwldmrAlcwYvIg +2SDhAsTPLcCgjNuHlr/v4VC29YsF37oYCGfmWvLwGFGufsxcxXkrVhhNr2WB +-----END CERTIFICATE----- diff --git a/gdata/tests/common.c b/gdata/tests/common.c new file mode 100644 index 0000000..2109004 --- /dev/null +++ b/gdata/tests/common.c @@ -0,0 +1,1050 @@ +/* -*- Mode: C; indent-tabs-mode: t; c-basic-offset: 8; tab-width: 8 -*- */ +/* + * GData Client + * Copyright (C) Philip Withnall 2010 + * + * GData Client is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * GData Client is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with GData Client. If not, see . + */ + +#include +#include +#include +#include +#include +#include +#include + +#include "common.h" + +/* %TRUE if interactive tests should be skipped because we're running automatically (for example) */ +static gboolean no_interactive = TRUE; + +/* declaration of debug handler */ +static void gdata_test_debug_handler (const gchar *log_domain, GLogLevelFlags log_level, const gchar *message, gpointer user_data); + +/* Directory to output network trace files to, if trace output is enabled. (NULL otherwise.) */ +static GFile *trace_dir = NULL; + +/* TRUE if tests should be run online and a trace file written for each; FALSE if tests should run offline against existing trace files. */ +static gboolean write_traces = FALSE; + +/* TRUE if tests should be run online and the server's responses compared to the existing trace file for each; FALSE if tests should run offline without comparison. */ +static gboolean compare_traces = FALSE; + +/* Global mock server instance used by all tests. */ +static UhmServer *mock_server = NULL; + +void +gdata_test_init (int argc, char **argv) +{ + GTlsCertificate *cert; + GError *child_error = NULL; + gchar *cert_path = NULL, *key_path = NULL; + gint i; + + setlocale (LC_ALL, ""); + + /* Parse the custom options */ + for (i = 1; i < argc; i++) { + if (strcmp ("--no-interactive", argv[i]) == 0 || strcmp ("-ni", argv[i]) == 0) { + no_interactive = TRUE; + argv[i] = (char*) ""; + } else if (strcmp ("--interactive", argv[i]) == 0 || strcmp ("-i", argv[i]) == 0) { + no_interactive = FALSE; + argv[i] = (char*) ""; + } else if (strcmp ("--trace-dir", argv[i]) == 0 || strcmp ("-t", argv[i]) == 0) { + if (i >= argc - 1) { + fprintf (stderr, "Error: Missing directory for --trace-dir option.\n"); + exit (1); + } + + trace_dir = g_file_new_for_path (argv[i + 1]); + + argv[i] = (char*) ""; + argv[i + 1] = (char*) ""; + i++; + } else if (strcmp ("--write-traces", argv[i]) == 0 || strcmp ("-w", argv[i]) == 0) { + write_traces = TRUE; + argv[i] = (char*) ""; + } else if (strcmp ("--compare-traces", argv[i]) == 0 || strcmp ("-c", argv[i]) == 0) { + compare_traces = TRUE; + argv[i] = (char*) ""; + } else if (strcmp ("-?", argv[i]) == 0 || strcmp ("--help", argv[i]) == 0 || strcmp ("-h" , argv[i]) == 0) { + /* We have to override --help in order to document --no-interactive and the trace flags. */ + printf ("Usage:\n" + " %s [OPTION...]\n\n" + "Help Options:\n" + " -?, --help Show help options\n" + "Test Options:\n" + " -l List test cases available in a test executable\n" + " -seed=RANDOMSEED Provide a random seed to reproduce test\n" + " runs using random numbers\n" + " --verbose Run tests verbosely\n" + " -q, --quiet Run tests quietly\n" + " -p TESTPATH Execute all tests matching TESTPATH\n" + " -m {perf|slow|thorough|quick} Execute tests according modes\n" + " --debug-log Debug test logging output\n" + " -ni, --no-interactive Only execute tests which don't require user interaction\n" + " -i, --interactive Execute tests including those requiring user interaction\n" + " -t, --trace-dir [directory] Read/Write trace files in the specified directory\n" + " -w, --write-traces Work online and write trace files to --trace-dir\n" + " -c, --compare-traces Work online and compare with existing trace files in --trace-dir\n", + argv[0]); + exit (0); + } + } + + /* --[write|compare]-traces are mutually exclusive. */ + if (write_traces == TRUE && compare_traces == TRUE) { + fprintf (stderr, "Error: --write-traces and --compare-traces are mutually exclusive.\n"); + exit (1); + } + + g_test_init (&argc, &argv, NULL); + g_test_bug_base ("http://bugzilla.gnome.org/show_bug.cgi?id="); + + /* Set handler of debug information */ + g_log_set_handler (G_LOG_DOMAIN, G_LOG_LEVEL_DEBUG, (GLogFunc) gdata_test_debug_handler, NULL); + + /* Enable full debugging. These options are seriously unsafe, but we don't care for test cases. */ + g_setenv ("LIBGDATA_DEBUG", "4" /* GDATA_LOG_FULL_UNREDACTED */, FALSE); + g_setenv ("G_MESSAGES_DEBUG", "libgdata", FALSE); + g_setenv ("LIBGDATA_LAX_SSL_CERTIFICATES", "1", FALSE); + + mock_server = uhm_server_new (); + uhm_server_set_enable_logging (mock_server, write_traces); + uhm_server_set_enable_online (mock_server, write_traces || compare_traces); + + /* Build the certificate. */ + cert_path = g_test_build_filename (G_TEST_DIST, "cert.pem", NULL); + key_path = g_test_build_filename (G_TEST_DIST, "key.pem", NULL); + + cert = g_tls_certificate_new_from_files (cert_path, key_path, &child_error); + g_assert_no_error (child_error); + + g_free (key_path); + g_free (cert_path); + + /* Set it as the property. */ + uhm_server_set_tls_certificate (mock_server, cert); + g_object_unref (cert); +} + +/* + * gdata_test_get_mock_server: + * + * Returns the singleton #UhmServer instance used throughout the test suite. + * + * Return value: (transfer none): the mock server + * + * Since: 0.13.4 + */ +UhmServer * +gdata_test_get_mock_server (void) +{ + return mock_server; +} + +/* + * gdata_test_interactive: + * + * Returns whether tests which require interactivity should be run. + * + * Return value: %TRUE if interactive tests should be run, %FALSE otherwise + * + * Since: 0.9.0 + */ +gboolean +gdata_test_interactive (void) +{ + return (no_interactive == FALSE) ? TRUE : FALSE; +} + +typedef struct { + GDataBatchOperation *operation; + guint op_id; + GDataBatchOperationType operation_type; + GDataEntry *entry; + GDataEntry **returned_entry; + gchar *id; + GType entry_type; + GError **error; +} BatchOperationData; + +static void +batch_operation_data_free (BatchOperationData *data) +{ + if (data->operation != NULL) + g_object_unref (data->operation); + if (data->entry != NULL) + g_object_unref (data->entry); + g_free (data->id); + + /* We don't free data->error, as it's owned by the calling code */ + + g_slice_free (BatchOperationData, data); +} + +static void +test_batch_operation_query_cb (guint operation_id, GDataBatchOperationType operation_type, GDataEntry *entry, GError *error, gpointer user_data) +{ + BatchOperationData *data = user_data; + + /* Mark the callback as having been run */ + g_object_set_data (G_OBJECT (data->operation), "test::called-callbacks", + GUINT_TO_POINTER (GPOINTER_TO_UINT (g_object_get_data (G_OBJECT (data->operation), "test::called-callbacks")) + 1)); + + /* Check that the @operation_type and @operation_id matches those stored in @data */ + g_assert_cmpuint (operation_id, ==, data->op_id); + g_assert_cmpuint (operation_type, ==, data->operation_type); + + /* If data->error is set, we're expecting the operation to fail; otherwise, we're expecting it to succeed */ + if (data->error != NULL) { + g_assert (error != NULL); + *(data->error) = g_error_copy (error); + g_assert (entry == NULL); + + if (data->returned_entry != NULL) + *(data->returned_entry) = NULL; + } else { + g_assert_no_error (error); + g_assert (entry != NULL); + g_assert (entry != data->entry); /* check that the pointers aren't the same */ + g_assert (gdata_entry_is_inserted (entry) == TRUE); + + /* Check the ID and type of the returned entry */ + /* TODO: We can't check this, because the Contacts service is stupid with IDs + * g_assert_cmpstr (gdata_entry_get_id (entry), ==, data->id); */ + g_assert (G_TYPE_CHECK_INSTANCE_TYPE (entry, data->entry_type)); + + /* Check the entries match */ + if (data->entry != NULL) { + g_assert_cmpstr (gdata_entry_get_title (entry), ==, gdata_entry_get_title (data->entry)); + g_assert_cmpstr (gdata_entry_get_summary (entry), ==, gdata_entry_get_summary (data->entry)); + g_assert_cmpstr (gdata_entry_get_content (entry), ==, gdata_entry_get_content (data->entry)); + g_assert_cmpstr (gdata_entry_get_content_uri (entry), ==, gdata_entry_get_content_uri (data->entry)); + g_assert_cmpstr (gdata_entry_get_rights (entry), ==, gdata_entry_get_rights (data->entry)); + } + + /* Copy the returned entry for the calling test code to prod later */ + if (data->returned_entry != NULL) + *(data->returned_entry) = g_object_ref (entry); + } + + /* Free the data */ + batch_operation_data_free (data); +} + +guint +gdata_test_batch_operation_query (GDataBatchOperation *operation, const gchar *id, GType entry_type, GDataEntry *entry, GDataEntry **returned_entry, + GError **error) +{ + guint op_id; + BatchOperationData *data; + + data = g_slice_new (BatchOperationData); + data->operation = g_object_ref (operation); + data->op_id = 0; + data->operation_type = GDATA_BATCH_OPERATION_QUERY; + data->entry = g_object_ref (entry); + data->returned_entry = returned_entry; + data->id = g_strdup (id); + data->entry_type = entry_type; + data->error = error; + + op_id = gdata_batch_operation_add_query (operation, id, entry_type, test_batch_operation_query_cb, data); + + data->op_id = op_id; + + /* We expect a callback to be called when the operation is run */ + g_object_set_data (G_OBJECT (operation), "test::expected-callbacks", + GUINT_TO_POINTER (GPOINTER_TO_UINT (g_object_get_data (G_OBJECT (operation), "test::expected-callbacks")) + 1)); + + return op_id; +} + +static void +test_batch_operation_insertion_update_cb (guint operation_id, GDataBatchOperationType operation_type, GDataEntry *entry, GError *error, + gpointer user_data) +{ + BatchOperationData *data = user_data; + + /* Mark the callback as having been run */ + g_object_set_data (G_OBJECT (data->operation), "test::called-callbacks", + GUINT_TO_POINTER (GPOINTER_TO_UINT (g_object_get_data (G_OBJECT (data->operation), "test::called-callbacks")) + 1)); + + /* Check that the @operation_type and @operation_id matches those stored in @data */ + g_assert_cmpuint (operation_id, ==, data->op_id); + g_assert_cmpuint (operation_type, ==, data->operation_type); + + /* If data->error is set, we're expecting the operation to fail; otherwise, we're expecting it to succeed */ + if (data->error != NULL) { + g_assert (error != NULL); + *(data->error) = g_error_copy (error); + g_assert (entry == NULL); + + if (data->returned_entry != NULL) + *(data->returned_entry) = NULL; + } else { + g_assert_no_error (error); + g_assert (entry != NULL); + g_assert (entry != data->entry); /* check that the pointers aren't the same */ + g_assert (gdata_entry_is_inserted (entry) == TRUE); + + /* Check the entries match */ + g_assert_cmpstr (gdata_entry_get_title (entry), ==, gdata_entry_get_title (data->entry)); + g_assert_cmpstr (gdata_entry_get_summary (entry), ==, gdata_entry_get_summary (data->entry)); + g_assert_cmpstr (gdata_entry_get_content (entry), ==, gdata_entry_get_content (data->entry)); + g_assert_cmpstr (gdata_entry_get_rights (entry), ==, gdata_entry_get_rights (data->entry)); + + /* Only test for differences in content URI if we had one to begin with, since the inserted entry could feasibly generate and return + * new content. */ + if (gdata_entry_get_content_uri (data->entry) != NULL) + g_assert_cmpstr (gdata_entry_get_content_uri (entry), ==, gdata_entry_get_content_uri (data->entry)); + + /* Copy the inserted entry for the calling test code to prod later */ + if (data->returned_entry != NULL) + *(data->returned_entry) = g_object_ref (entry); + } + + /* Free the data */ + batch_operation_data_free (data); +} + +guint +gdata_test_batch_operation_insertion (GDataBatchOperation *operation, GDataEntry *entry, GDataEntry **inserted_entry, GError **error) +{ + guint op_id; + BatchOperationData *data; + + data = g_slice_new (BatchOperationData); + data->operation = g_object_ref (operation); + data->op_id = 0; + data->operation_type = GDATA_BATCH_OPERATION_INSERTION; + data->entry = g_object_ref (entry); + data->returned_entry = inserted_entry; + data->id = NULL; + data->entry_type = G_TYPE_INVALID; + data->error = error; + + op_id = gdata_batch_operation_add_insertion (operation, entry, test_batch_operation_insertion_update_cb, data); + + data->op_id = op_id; + + /* We expect a callback to be called when the operation is run */ + g_object_set_data (G_OBJECT (operation), "test::expected-callbacks", + GUINT_TO_POINTER (GPOINTER_TO_UINT (g_object_get_data (G_OBJECT (operation), "test::expected-callbacks")) + 1)); + + return op_id; +} + +guint +gdata_test_batch_operation_update (GDataBatchOperation *operation, GDataEntry *entry, GDataEntry **updated_entry, GError **error) +{ + guint op_id; + BatchOperationData *data; + + data = g_slice_new (BatchOperationData); + data->operation = g_object_ref (operation); + data->op_id = 0; + data->operation_type = GDATA_BATCH_OPERATION_UPDATE; + data->entry = g_object_ref (entry); + data->returned_entry = updated_entry; + data->id = NULL; + data->entry_type = G_TYPE_INVALID; + data->error = error; + + op_id = gdata_batch_operation_add_update (operation, entry, test_batch_operation_insertion_update_cb, data); + + data->op_id = op_id; + + /* We expect a callback to be called when the operation is run */ + g_object_set_data (G_OBJECT (operation), "test::expected-callbacks", + GUINT_TO_POINTER (GPOINTER_TO_UINT (g_object_get_data (G_OBJECT (operation), "test::expected-callbacks")) + 1)); + + return op_id; +} + +static void +test_batch_operation_deletion_cb (guint operation_id, GDataBatchOperationType operation_type, GDataEntry *entry, GError *error, gpointer user_data) +{ + BatchOperationData *data = user_data; + + /* Mark the callback as having been run */ + g_object_set_data (G_OBJECT (data->operation), "test::called-callbacks", + GUINT_TO_POINTER (GPOINTER_TO_UINT (g_object_get_data (G_OBJECT (data->operation), "test::called-callbacks")) + 1)); + + /* Check that the @operation_type and @operation_id matches those stored in @data */ + g_assert_cmpuint (operation_id, ==, data->op_id); + g_assert_cmpuint (operation_type, ==, data->operation_type); + g_assert (entry == NULL); + + /* If data->error is set, we're expecting the operation to fail; otherwise, we're expecting it to succeed */ + if (data->error != NULL) { + g_assert (error != NULL); + *(data->error) = g_error_copy (error); + } else { + g_assert_no_error (error); + } + + /* Free the data */ + batch_operation_data_free (data); +} + +guint +gdata_test_batch_operation_deletion (GDataBatchOperation *operation, GDataEntry *entry, GError **error) +{ + guint op_id; + BatchOperationData *data; + + data = g_slice_new (BatchOperationData); + data->operation = g_object_ref (operation); + data->op_id = 0; + data->operation_type = GDATA_BATCH_OPERATION_DELETION; + data->entry = g_object_ref (entry); + data->returned_entry = NULL; + data->id = NULL; + data->entry_type = G_TYPE_INVALID; + data->error = error; + + op_id = gdata_batch_operation_add_deletion (operation, entry, test_batch_operation_deletion_cb, data); + + data->op_id = op_id; + + /* We expect a callback to be called when the operation is run */ + g_object_set_data (G_OBJECT (operation), "test::expected-callbacks", + GUINT_TO_POINTER (GPOINTER_TO_UINT (g_object_get_data (G_OBJECT (operation), "test::expected-callbacks")) + 1)); + + return op_id; +} + +gboolean +gdata_test_batch_operation_run (GDataBatchOperation *operation, GCancellable *cancellable, GError **error) +{ + gboolean success = gdata_batch_operation_run (operation, cancellable, error); + + /* Assert that callbacks were called exactly once for each operation in the batch operation */ + g_assert_cmpuint (GPOINTER_TO_UINT (g_object_get_data (G_OBJECT (operation), "test::expected-callbacks")), ==, + GPOINTER_TO_UINT (g_object_get_data (G_OBJECT (operation), "test::called-callbacks"))); + + return success; +} + +gboolean +gdata_test_batch_operation_run_finish (GDataBatchOperation *operation, GAsyncResult *async_result, GError **error) +{ + gboolean success = gdata_batch_operation_run_finish (operation, async_result, error); + + /* Assert that callbacks were called exactly once for each operation in the batch operation */ + g_assert_cmpuint (GPOINTER_TO_UINT (g_object_get_data (G_OBJECT (operation), "test::expected-callbacks")), ==, + GPOINTER_TO_UINT (g_object_get_data (G_OBJECT (operation), "test::called-callbacks"))); + + return success; +} + +static gboolean +compare_xml_namespaces (xmlNs *ns1, xmlNs *ns2) +{ + if (ns1 == ns2) + return TRUE; + + /* Compare various simple properties */ + if (ns1->type != ns2->type || + xmlStrcmp (ns1->href, ns2->href) != 0 || + xmlStrcmp (ns1->prefix, ns2->prefix) != 0 || + ns1->context != ns2->context) { + return FALSE; + } + + return TRUE; +} + +static gboolean compare_xml_nodes (xmlNode *node1, xmlNode *node2); + +static gboolean +compare_xml_node_lists (xmlNode *list1, xmlNode *list2) +{ + GHashTable *table; + xmlNode *child; + + /* Compare their child elements. We iterate through the first linked list and, for each child node, iterate through the second linked list + * comparing it against each node there. We keep a hashed set of nodes in the second linked list which have already been visited and compared + * successfully, both for speed and to guarantee that one element in the second linked list doesn't match more than one in the first linked + * list. We take this approach because we can't modify the second linked list in place to remove matched nodes. + * Finally, we iterate through the second node list and check that all its elements are in the hash table (i.e. they've all been visited + * exactly once). + * This approach is O(n^2) in the number of nodes in the linked lists, but since we should be dealing with fairly narrow XML trees this should + * be OK. */ + table = g_hash_table_new (g_direct_hash, g_direct_equal); + + for (child = list1; child != NULL; child = child->next) { + xmlNode *other_child; + gboolean matched = FALSE; + + for (other_child = list2; other_child != NULL; other_child = other_child->next) { + if (g_hash_table_lookup (table, other_child) != NULL) + continue; + + if (compare_xml_nodes (child, other_child) == TRUE) { + g_hash_table_insert (table, other_child, other_child); + matched = TRUE; + break; + } + } + + if (matched == FALSE) { + g_hash_table_destroy (table); + return FALSE; + } + } + + for (child = list2; child != NULL; child = child->next) { + if (g_hash_table_lookup (table, child) == NULL) { + g_hash_table_destroy (table); + return FALSE; + } + } + + g_hash_table_destroy (table); + + return TRUE; +} + +static gboolean +compare_xml_nodes (xmlNode *node1, xmlNode *node2) +{ + GHashTable *table; + xmlAttr *attr1, *attr2; + xmlNs *ns; + + if (node1 == node2) + return TRUE; + + /* Compare various simple properties */ + if (node1->type != node2->type || + xmlStrcmp (node1->name, node2->name) != 0 || + compare_xml_namespaces (node1->ns, node2->ns) == FALSE || + xmlStrcmp (node1->content, node2->content) != 0) { + return FALSE; + } + + /* Compare their attributes. This is done in document order, which isn't strictly correct, since XML specifically does not apply an ordering + * over attributes. However, it suffices for our needs. */ + for (attr1 = node1->properties, attr2 = node2->properties; attr1 != NULL && attr2 != NULL; attr1 = attr1->next, attr2 = attr2->next) { + /* Compare various simple properties */ + if (attr1->type != attr2->type || + xmlStrcmp (attr1->name, attr2->name) != 0 || + compare_xml_namespaces (attr1->ns, attr2->ns) == FALSE || + attr1->atype != attr2->atype) { + return FALSE; + } + + /* Compare their child nodes (values represented as text and entity nodes) */ + if (compare_xml_node_lists (attr1->children, attr2->children) == FALSE) + return FALSE; + } + + /* Stragglers? */ + if (attr1 != NULL || attr2 != NULL) + return FALSE; + + /* Compare their namespace definitions regardless of order. Do this by inserting all the definitions from node1 into a hash table, then running + * through the definitions in node2 and ensuring they exist in the hash table, removing each one from the table as we go. Check there aren't + * any left in the hash table afterwards. */ + table = g_hash_table_new (g_str_hash, g_str_equal); + + for (ns = node1->nsDef; ns != NULL; ns = ns->next) { + /* Prefixes should be unique, but I trust libxml about as far as I can throw it. */ + if (g_hash_table_lookup (table, ns->prefix ? ns->prefix : (gpointer) "") != NULL) { + g_hash_table_destroy (table); + return FALSE; + } + + g_hash_table_insert (table, ns->prefix ? (gpointer) ns->prefix : (gpointer) "", ns); + } + + for (ns = node2->nsDef; ns != NULL; ns = ns->next) { + xmlNs *original_ns = g_hash_table_lookup (table, ns->prefix ? ns->prefix : (gpointer) ""); + + if (original_ns == NULL || + compare_xml_namespaces (original_ns, ns) == FALSE) { + g_hash_table_destroy (table); + return FALSE; + } + + g_hash_table_remove (table, ns->prefix ? ns->prefix : (gpointer) ""); + } + + if (g_hash_table_size (table) != 0) { + g_hash_table_destroy (table); + return FALSE; + } + + g_hash_table_destroy (table); + + /* Compare their child nodes */ + if (compare_xml_node_lists (node1->children, node2->children) == FALSE) + return FALSE; + + /* Success! */ + return TRUE; +} + +gboolean +gdata_test_compare_xml_strings (const gchar *parsable_xml, const gchar *expected_xml, gboolean print_error) +{ + gboolean success; + xmlDoc *parsable_doc, *expected_doc; + + /* Parse both the XML strings */ + parsable_doc = xmlReadMemory (parsable_xml, strlen (parsable_xml), "/dev/null", NULL, 0); + expected_doc = xmlReadMemory (expected_xml, strlen (expected_xml), "/dev/null", NULL, 0); + + g_assert (parsable_doc != NULL && expected_doc != NULL); + + /* Recursively compare the two XML trees */ + success = compare_xml_nodes (xmlDocGetRootElement (parsable_doc), xmlDocGetRootElement (expected_doc)); + if (success == FALSE && print_error == TRUE) { + /* The comparison has failed, so print out the two XML strings for ease of debugging */ + g_message ("\n\nParsable: %s\n\nExpected: %s\n\n", parsable_xml, expected_xml); + } + + xmlFreeDoc (expected_doc); + xmlFreeDoc (parsable_doc); + + return success; +} + +gboolean +gdata_test_compare_xml (GDataParsable *parsable, const gchar *expected_xml, gboolean print_error) +{ + gboolean success; + gchar *parsable_xml; + + /* Get an XML string for the GDataParsable */ + parsable_xml = gdata_parsable_get_xml (parsable); + success = gdata_test_compare_xml_strings (parsable_xml, expected_xml, print_error); + g_free (parsable_xml); + + return success; +} + +static gboolean +compare_json_nodes (JsonNode *node1, JsonNode *node2) +{ + if (node1 == node2) + return TRUE; + + if (JSON_NODE_TYPE (node1) != JSON_NODE_TYPE (node2)) + return FALSE; + + switch (JSON_NODE_TYPE (node1)) { + case JSON_NODE_OBJECT: { + JsonObject *object1, *object2; + guint size1, size2; + GList *members, *i; + + object1 = json_node_get_object (node1); + object2 = json_node_get_object (node2); + + size1 = json_object_get_size (object1); + size2 = json_object_get_size (object2); + + if (size1 != size2) + return FALSE; + + /* Iterate over the first object, checking that every member is also present in the second object. */ + members = json_object_get_members (object1); + + for (i = members; i != NULL; i = i->next) { + JsonNode *child_node1, *child_node2; + + child_node1 = json_object_get_member (object1, i->data); + child_node2 = json_object_get_member (object2, i->data); + + g_assert (child_node1 != NULL); + if (child_node2 == NULL) { + g_list_free (members); + return FALSE; + } + + if (compare_json_nodes (child_node1, child_node2) == FALSE) { + g_list_free (members); + return FALSE; + } + } + + g_list_free (members); + + return TRUE; + } + case JSON_NODE_ARRAY: { + JsonArray *array1, *array2; + guint length1, length2, i; + + array1 = json_node_get_array (node1); + array2 = json_node_get_array (node2); + + length1 = json_array_get_length (array1); + length2 = json_array_get_length (array2); + + if (length1 != length2) + return FALSE; + + /* Iterate over both arrays, checking the elements at each index are identical. */ + for (i = 0; i < length1; i++) { + JsonNode *child_node1, *child_node2; + + child_node1 = json_array_get_element (array1, i); + child_node2 = json_array_get_element (array2, i); + + if (compare_json_nodes (child_node1, child_node2) == FALSE) + return FALSE; + } + + return TRUE; + } + case JSON_NODE_VALUE: { + GType type1, type2; + + type1 = json_node_get_value_type (node1); + type2 = json_node_get_value_type (node2); + + if (type1 != type2) + return FALSE; + + switch (type1) { + case G_TYPE_BOOLEAN: + return (json_node_get_boolean (node1) == json_node_get_boolean (node2)) ? TRUE : FALSE; + case G_TYPE_DOUBLE: + /* Note: This doesn't need an epsilon-based comparison because we only want to return + * true if the string representation of the two values is equal — and if it is, their + * parsed values should be binary identical too. */ + return (json_node_get_double (node1) == json_node_get_double (node2)) ? TRUE : FALSE; + case G_TYPE_INT64: + return (json_node_get_int (node1) == json_node_get_int (node2)) ? TRUE : FALSE; + case G_TYPE_STRING: + return (g_strcmp0 (json_node_get_string (node1), json_node_get_string (node2)) == 0) ? TRUE : FALSE; + default: + /* JSON doesn't support any other types. */ + g_assert_not_reached (); + } + + return TRUE; + } + case JSON_NODE_NULL: + return TRUE; + default: + g_assert_not_reached (); + } +} + +gboolean +gdata_test_compare_json_strings (const gchar *parsable_json, const gchar *expected_json, gboolean print_error) +{ + gboolean success; + JsonParser *parsable_parser, *expected_parser; + GError *child_error = NULL; + + /* Parse both strings. */ + parsable_parser = json_parser_new (); + expected_parser = json_parser_new (); + + json_parser_load_from_data (parsable_parser, parsable_json, -1, &child_error); + if (child_error != NULL) { + if (print_error == TRUE) { + g_message ("\n\nParsable: %s\n\nNot valid JSON: %s", parsable_json, child_error->message); + } + + g_error_free (child_error); + return FALSE; + } + + json_parser_load_from_data (expected_parser, expected_json, -1, &child_error); + g_assert_no_error (child_error); /* this really should never fail; or the test has encoded bad JSON */ + + /* Recursively compare the two JSON nodes. */ + success = compare_json_nodes (json_parser_get_root (parsable_parser), json_parser_get_root (expected_parser)); + if (success == FALSE && print_error == TRUE) { + /* The comparison has failed, so print out the two JSON strings for ease of debugging */ + g_message ("\n\nParsable: %s\n\nExpected: %s\n\n", parsable_json, expected_json); + } + + g_object_unref (expected_parser); + g_object_unref (parsable_parser); + + return success; +} + +gboolean +gdata_test_compare_json (GDataParsable *parsable, const gchar *expected_json, gboolean print_error) +{ + gboolean success; + gchar *parsable_json; + + /* Get a JSON string for the GDataParsable. */ + parsable_json = gdata_parsable_get_json (parsable); + success = gdata_test_compare_json_strings (parsable_json, expected_json, print_error); + g_free (parsable_json); + + return success; +} + +gboolean +gdata_test_compare_kind (GDataEntry *entry, const gchar *expected_term, const gchar *expected_label) +{ + GList *list; + + /* Check the entry's kind category is present and correct */ + for (list = gdata_entry_get_categories (entry); list != NULL; list = list->next) { + GDataCategory *category = GDATA_CATEGORY (list->data); + + if (g_strcmp0 (gdata_category_get_scheme (category), "http://schemas.google.com/g/2005#kind") == 0) { + /* Found the kind category; check its term and label. */ + return (g_strcmp0 (gdata_category_get_term (category), expected_term) == 0) && + (g_strcmp0 (gdata_category_get_label (category), expected_label) == 0); + } + } + + /* No kind! */ + return FALSE; +} + +/* Common code for tests of async query functions that have progress callbacks */ + +void +gdata_test_async_progress_callback (GDataEntry *entry, guint entry_key, guint entry_count, GDataAsyncProgressClosure *data) +{ + /* No-op */ +} + +void +gdata_test_async_progress_closure_free (GDataAsyncProgressClosure *data) +{ + /* Check that this callback is called first */ + g_assert_cmpuint (data->async_ready_notify_count, ==, 0); + data->progress_destroy_notify_count++; +} + +void +gdata_test_async_progress_finish_callback (GObject *service, GAsyncResult *res, GDataAsyncProgressClosure *data) +{ + /* Check that this callback is called second */ + g_assert_cmpuint (data->progress_destroy_notify_count, ==, 1); + data->async_ready_notify_count++; + + g_main_loop_quit (data->main_loop); +} + +gboolean +gdata_async_test_cancellation_cb (GDataAsyncTestData *async_data) +{ + g_cancellable_cancel (async_data->cancellable); + async_data->cancellation_timeout_id = 0; + return FALSE; +} + +void +gdata_set_up_async_test_data (GDataAsyncTestData *async_data, gconstpointer test_data) +{ + async_data->main_loop = g_main_loop_new (NULL, FALSE); + async_data->cancellable = g_cancellable_new (); + async_data->cancellation_timeout = 0; + async_data->cancellation_successful = FALSE; + + async_data->test_data = test_data; +} + +void +gdata_tear_down_async_test_data (GDataAsyncTestData *async_data, gconstpointer test_data) +{ + g_assert (async_data->test_data == test_data); /* sanity check */ + + g_object_unref (async_data->cancellable); + g_main_loop_unref (async_data->main_loop); +} + +/* Output a log message. Note the output is prefixed with ‘# ’ so that it + * doesn’t interfere with TAP output. */ +static void +output_commented_lines (const gchar *message) +{ + const gchar *i, *next_newline; + + for (i = message; i != NULL && *i != '\0'; i = next_newline) { + gchar *line; + + next_newline = strchr (i, '\n'); + if (next_newline != NULL) { + line = g_strndup (i, next_newline - i); + next_newline++; + } else { + line = g_strdup (i); + } + + printf ("# %s\n", line); + + g_free (line); + } +} + +static void +output_log_message (const gchar *message) +{ + if (strlen (message) > 2 && message[2] == '<') { + /* As debug string starts with direction indicator and space, t.i. "< ", */ + /* we need access string starting from third character and see if it's */ + /* looks like xml - t.i. it starts with '<' */ + xmlChar *xml_buff; + int buffer_size; + xmlDocPtr xml_doc; + /* we need to cut to the beginning of XML string */ + message = message + 2; + /* create xml document and dump it to string buffer */ + xml_doc = xmlParseDoc ((const xmlChar*) message); + xmlDocDumpFormatMemory (xml_doc, &xml_buff, &buffer_size, 1); + /* print out structured xml - if it's not xml, it will get error in output */ + output_commented_lines ((gchar*) xml_buff); + /* free xml structs */ + xmlFree (xml_buff); + xmlFreeDoc (xml_doc); + } else { + output_commented_lines ((gchar*) message); + } +} + +static void +gdata_test_debug_handler (const gchar *log_domain, GLogLevelFlags log_level, const gchar *message, gpointer user_data) +{ + output_log_message (message); + + /* Log to the trace file. */ + if ((*message == '<' || *message == '>' || *message == ' ') && *(message + 1) == ' ') { + uhm_server_received_message_chunk (mock_server, message, strlen (message), NULL); + } +} + +/** + * gdata_test_set_https_port: + * @server: a #UhmServer + * + * Sets the HTTPS port used for all future libgdata requests to that used by the given mock @server, + * effectively redirecting all client requests to the mock server. + * + * Since: 0.13.4 + */ +void +gdata_test_set_https_port (UhmServer *server) +{ + gchar *port_string = g_strdup_printf ("%u", uhm_server_get_port (server)); + g_setenv ("LIBGDATA_HTTPS_PORT", port_string, TRUE); + g_free (port_string); +} + +/** + * gdata_test_mock_server_start_trace: + * @server: a #UhmServer + * @trace_filename: filename of the trace to load + * + * Wrapper around uhm_server_start_trace() which additionally sets the LIBGDATA_HTTPS_PORT + * environment variable to redirect all libgdata requests to the mock server. + * + * Since: 0.13.4 + */ +void +gdata_test_mock_server_start_trace (UhmServer *server, const gchar *trace_filename) +{ + GError *child_error = NULL; + + uhm_server_start_trace (server, trace_filename, &child_error); + g_assert_no_error (child_error); + gdata_test_set_https_port (server); +} + +/** + * gdata_test_mock_server_handle_message_error: + * @server: a #UhmServer + * @message: the message whose response should be filled + * @client: the currently connected client + * @user_data: user data provided when connecting the signal + * + * Handler for #UhmServer::handle-message which sets the HTTP response for @message to the HTTP error status + * specified in a #GDataTestRequestErrorData structure passed to @user_data. + * + * Since: 0.13.4 + */ +gboolean +gdata_test_mock_server_handle_message_error (UhmServer *server, SoupMessage *message, SoupClientContext *client, gpointer user_data) +{ + const GDataTestRequestErrorData *data = user_data; + + soup_message_set_status_full (message, data->status_code, data->reason_phrase); + soup_message_body_append (message->response_body, SOUP_MEMORY_STATIC, data->message_body, strlen (data->message_body)); + + return TRUE; +} + +/** + * gdata_test_mock_server_handle_message_timeout: + * @server: a #UhmServer + * @message: the message whose response should be filled + * @client: the currently connected client + * @user_data: user data provided when connecting the signal + * + * Handler for #UhmServer::handle-message which waits for 2 seconds before returning a %SOUP_STATUS_REQUEST_TIMEOUT status + * and appropriate error message body. If used in conjunction with a 1 second timeout in the client code under test, this can + * simulate network error conditions and timeouts, in order to test the error handling code for such conditions. + * + * Since: 0.13.4 + */ +gboolean +gdata_test_mock_server_handle_message_timeout (UhmServer *server, SoupMessage *message, SoupClientContext *client, gpointer user_data) +{ + /* Sleep for longer than the timeout set on the client. */ + g_usleep (2 * G_USEC_PER_SEC); + + soup_message_set_status_full (message, SOUP_STATUS_REQUEST_TIMEOUT, "Request Timeout"); + soup_message_body_append (message->response_body, SOUP_MEMORY_STATIC, "Request timed out.", strlen ("Request timed out.")); + + return TRUE; +} + +/** + * gdata_test_query_user_for_verifier: + * @authentication_uri: authentication URI to present + * + * Given an authentication URI, prompt the user to go to that URI, grant access + * to the test application and enter the resulting verifier. This is to be used + * with interactive OAuth authorisation requests. + * + * Returns: (transfer full): verifier from the web page + */ +gchar * +gdata_test_query_user_for_verifier (const gchar *authentication_uri) +{ + char verifier[100]; + + /* Wait for the user to retrieve and enter the verifier */ + g_print ("Please navigate to the following URI and grant access: %s\n", authentication_uri); + g_print ("Enter verifier (EOF to skip test): "); + if (scanf ("%100s", verifier) != 1) { + /* Skip the test */ + g_test_message ("Skipping test on user request."); + return NULL; + } + + g_test_message ("Proceeding with user-provided verifier “%s”.", verifier); + + return g_strdup (verifier); +} diff --git a/gdata/tests/common.h b/gdata/tests/common.h new file mode 100644 index 0000000..92ff753 --- /dev/null +++ b/gdata/tests/common.h @@ -0,0 +1,344 @@ +/* -*- Mode: C; indent-tabs-mode: t; c-basic-offset: 8; tab-width: 8 -*- */ +/* + * GData Client + * Copyright (C) Philip Withnall 2009 + * + * GData Client is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * GData Client is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with GData Client. If not, see . + */ + +#include +#include + +#include + +#ifndef GDATA_TEST_COMMON_H +#define GDATA_TEST_COMMON_H + +G_BEGIN_DECLS + +#define CLIENT_ID "ytapi-GNOME-libgdata-444fubtt-0" +#define DOCUMENTS_USERNAME "libgdata.documents@gmail.com" + +/* These two must match */ +#define USERNAME_NO_DOMAIN "libgdata.test" +#define USERNAME USERNAME_NO_DOMAIN "@gmail.com" + +/* This must not match the above two */ +#define INCORRECT_USERNAME "libgdata.test.invalid@gmail.com" + +/* These two must not match (obviously) */ +#define PASSWORD "gdata-gdata" +#define INCORRECT_PASSWORD "bad-password" + +/* The amount of fuzziness (in seconds) used in comparisons between times which should (theoretically) be equal. + * Due to the weak consistency used in Google's servers, it's hard to guarantee that timestamps which should be equal, + * actually are. */ +#define TIME_FUZZINESS 5 + +void gdata_test_init (int argc, char **argv); + +UhmServer *gdata_test_get_mock_server (void) G_GNUC_WARN_UNUSED_RESULT; + +gboolean gdata_test_interactive (void); + +guint gdata_test_batch_operation_query (GDataBatchOperation *operation, const gchar *id, GType entry_type, + GDataEntry *entry, GDataEntry **returned_entry, GError **error); +guint gdata_test_batch_operation_insertion (GDataBatchOperation *operation, GDataEntry *entry, GDataEntry **inserted_entry, GError **error); +guint gdata_test_batch_operation_update (GDataBatchOperation *operation, GDataEntry *entry, GDataEntry **updated_entry, GError **error); +guint gdata_test_batch_operation_deletion (GDataBatchOperation *operation, GDataEntry *entry, GError **error); + +gboolean gdata_test_batch_operation_run (GDataBatchOperation *operation, GCancellable *cancellable, GError **error); +gboolean gdata_test_batch_operation_run_finish (GDataBatchOperation *operation, GAsyncResult *async_result, GError **error); + +gboolean gdata_test_compare_xml_strings (const gchar *parsable_xml, const gchar *expected_xml, gboolean print_error); +gboolean gdata_test_compare_xml (GDataParsable *parsable, const gchar *expected_xml, gboolean print_error); + +gboolean gdata_test_compare_json_strings (const gchar *parsable_json, const gchar *expected_json, gboolean print_error); +gboolean gdata_test_compare_json (GDataParsable *parsable, const gchar *expected_json, gboolean print_error); + +gboolean gdata_test_compare_kind (GDataEntry *entry, const gchar *expected_term, const gchar *expected_label); + +/* Convenience macros. */ +#define gdata_test_assert_xml(Parsable, XML) \ + G_STMT_START { \ + gboolean _test_success = gdata_test_compare_xml (GDATA_PARSABLE (Parsable), XML, TRUE); \ + g_assert (_test_success == TRUE); \ + } G_STMT_END + +#define gdata_test_assert_json(Parsable, JSON) \ + G_STMT_START { \ + gboolean _test_success = gdata_test_compare_json (GDATA_PARSABLE (Parsable), JSON, TRUE); \ + g_assert (_test_success == TRUE); \ + } G_STMT_END + +/* Common code for tests of async query functions that have progress callbacks */ +typedef struct { + guint progress_destroy_notify_count; + guint async_ready_notify_count; + GMainLoop *main_loop; +} GDataAsyncProgressClosure; +void gdata_test_async_progress_callback (GDataEntry *entry, guint entry_key, guint entry_count, GDataAsyncProgressClosure *data); +void gdata_test_async_progress_closure_free (GDataAsyncProgressClosure *data); +void gdata_test_async_progress_finish_callback (GObject *service, GAsyncResult *res, GDataAsyncProgressClosure *data); + +typedef struct { + /*< private >*/ + GMainLoop *main_loop; + GCancellable *cancellable; + guint cancellation_timeout; /* timeout period in ms */ + guint cancellation_timeout_id; /* ID of the callback source */ + gboolean cancellation_successful; + + gconstpointer test_data; +} GDataAsyncTestData; + +/** + * GDATA_ASYNC_CLOSURE_FUNCTIONS: + * @CLOSURE_NAME: the name of the closure + * @TestStructType: the type of the synchronous closure structure + * + * Defines set up and tear down functions for a version of @TestStructType which is wrapped by #GDataAsyncTestData (i.e. allocated and pointed to by + * the #GDataAsyncTestData.test_data pointer). These functions will be named set_up_CLOSURE_NAME_async + * and tear_down_CLOSURE_NAME_async. + * + * Since: 0.10.0 + */ +#define GDATA_ASYNC_CLOSURE_FUNCTIONS(CLOSURE_NAME, TestStructType) \ +static void \ +set_up_##CLOSURE_NAME##_async (GDataAsyncTestData *async_data, gconstpointer service) \ +{ \ + TestStructType *test_data = g_slice_new (TestStructType); \ + set_up_##CLOSURE_NAME (test_data, service); \ + gdata_set_up_async_test_data (async_data, test_data); \ +} \ + \ +static void \ +tear_down_##CLOSURE_NAME##_async (GDataAsyncTestData *async_data, gconstpointer service) \ +{ \ + tear_down_##CLOSURE_NAME ((TestStructType*) async_data->test_data, service); \ + g_slice_free (TestStructType, (TestStructType*) async_data->test_data); \ + gdata_tear_down_async_test_data (async_data, async_data->test_data); \ +} + +/** + * GDATA_ASYNC_STARTING_TIMEOUT: + * + * The initial timeout for cancellation tests, which will be the first timeout used after testing cancelling the operation before it's started. + * The value is in milliseconds. + * + * Since: 0.10.0 + */ +#define GDATA_ASYNC_STARTING_TIMEOUT 20 /* ms */ + +/** + * GDATA_ASYNC_TIMEOUT_MULTIPLIER: + * + * The factor by which the asynchronous cancellation timeout will be multiplied between iterations of the cancellation test. + * + * Since: 0.10.0 + */ +#define GDATA_ASYNC_TIMEOUT_MULTIPLIER 3 + +/** + * GDATA_ASYNC_MAXIMUM_TIMEOUT: + * + * The maximum timeout value for cancellation tests before they fail. i.e. If an operation takes longer than this period of time, the asynchronous + * operation test will fail. + * The value is in milliseconds. + * + * Since: 0.10.0 + */ +#define GDATA_ASYNC_MAXIMUM_TIMEOUT 43740 /* ms */ + +/** + * GDATA_ASYNC_TEST_FUNCTIONS: + * @TEST_NAME: the name of the test, excluding the “test_” prefix and the “_async” suffix + * @TestStructType: type of the closure structure to use, or void + * @TEST_BEGIN_CODE: code to execute to begin the test and start the asynchronous call + * @TEST_END_CODE: code to execute once the asynchronous call has completed, which will check the return values and any changed state + * + * Defines test and callback functions to test normal asynchronous operation and the cancellation behaviour of the given asynchronous function call. + * + * The asynchronous function call should be started in @TEST_BEGIN_CODE, using cancellable as its #GCancellable parameter, + * async_ready_callback as its #GAsyncReadyCallback parameter and async_data as its user_data + * parameter. There is no need for the code to create its own main loop: that's taken care of by the wrapper code. + * + * The code in @TEST_END_CODE will be inserted into the callback function for both the normal asynchronous test and the cancellation test, so should + * finish the asynchronous function call, using obj as the object on which the asynchronous function call was made, + * async_result as its #GAsyncResult parameter and error as its #GError parameter. The code should then check + * error: if it's %NULL, the code should assert success conditions; if it's non-%NULL, the code should assert failure conditions. + * The wrapper code will ensure that the error is a %G_IO_ERROR_CANCELLED at the appropriate times. + * + * The following functions will be defined, and should be added to the test suite using the #GAsyncTestData closure structure: + * test_TEST_NAME_async and + * test_TEST_NAME_async_cancellation. + * + * These functions assume the existence of a mock_server variable which points to the current #UhmServer instance. They + * will automatically use traces TEST_NAME-async and + * TEST_NAME-async-cancellation. + * + * Since: 0.10.0 + */ +#define GDATA_ASYNC_TEST_FUNCTIONS(TEST_NAME, TestStructType, TEST_BEGIN_CODE, TEST_END_CODE) \ +static void \ +test_##TEST_NAME##_async_cb (GObject *obj, GAsyncResult *async_result, GDataAsyncTestData *async_data) \ +{ \ + TestStructType *data = (TestStructType*) async_data->test_data; \ + GError *error = NULL; \ + \ + (void) data; /* hide potential unused variable warning */ \ + \ + { \ + TEST_END_CODE; \ + \ + if (g_error_matches (error, G_IO_ERROR, G_IO_ERROR_CANCELLED) == TRUE) { \ + g_assert (g_cancellable_is_cancelled (async_data->cancellable) == TRUE); \ + async_data->cancellation_successful = TRUE; \ + } else if (error == NULL) { \ + g_assert (g_cancellable_is_cancelled (async_data->cancellable) == FALSE || async_data->cancellation_timeout > 0); \ + async_data->cancellation_successful = FALSE; \ + } else { \ + /* Unexpected error: explode. */ \ + g_assert_no_error (error); \ + async_data->cancellation_successful = FALSE; \ + } \ + } \ + \ + g_clear_error (&error); \ + \ + g_main_loop_quit (async_data->main_loop); \ +} \ +\ +static void \ +test_##TEST_NAME##_async (GDataAsyncTestData *async_data, gconstpointer service) \ +{ \ + GAsyncReadyCallback async_ready_callback = (GAsyncReadyCallback) test_##TEST_NAME##_async_cb; \ + TestStructType *data = (TestStructType*) async_data->test_data; \ + GCancellable *cancellable = NULL; /* don't expose the cancellable, so the test proceeds as normal */ \ + \ + (void) data; /* hide potential unused variable warning */ \ + \ + /* Just run the test without doing any cancellation, and assert that it succeeds. */ \ + async_data->cancellation_timeout = 0; \ + \ + g_test_message ("Running normal operation test…"); \ + \ + gdata_test_mock_server_start_trace (mock_server, G_STRINGIFY (TEST_NAME) "-async"); \ + \ + { \ + TEST_BEGIN_CODE; \ + } \ + \ + g_main_loop_run (async_data->main_loop); \ + \ + uhm_server_end_trace (mock_server); \ +} \ + \ +static void \ +test_##TEST_NAME##_async_cancellation (GDataAsyncTestData *async_data, gconstpointer service) \ +{ \ + async_data->cancellation_timeout = 0; \ + \ + /* Starting with a short timeout, repeatedly run the async. operation, cancelling it after the timeout and increasing the timeout until + * the operation succeeds for the first time. We then finish the test. This guarantees that if, for example, the test creates an entry on + * the server, it only ever creates one; because the test only ever succeeds once. (Of course, this assumes that the server does not change + * state if we cancel the operation, which is a fairly optimistic assumption. Sigh.) */ \ + do { \ + GCancellable *cancellable = async_data->cancellable; \ + GAsyncReadyCallback async_ready_callback = (GAsyncReadyCallback) test_##TEST_NAME##_async_cb; \ + TestStructType *data = (TestStructType*) async_data->test_data; \ + \ + gdata_test_mock_server_start_trace (mock_server, G_STRINGIFY (TEST_NAME) "-async-cancellation"); \ + \ + (void) data; /* hide potential unused variable warning */ \ + \ + /* Ensure the timeout remains sane. */ \ + g_assert_cmpuint (async_data->cancellation_timeout, <=, GDATA_ASYNC_MAXIMUM_TIMEOUT); \ + \ + /* Schedule the cancellation after the timeout. */ \ + if (async_data->cancellation_timeout == 0) { \ + /* For the first test, cancel the cancellable before the test code is run */ \ + gdata_async_test_cancellation_cb (async_data); \ + } else { \ + async_data->cancellation_timeout_id = g_timeout_add (async_data->cancellation_timeout, \ + (GSourceFunc) gdata_async_test_cancellation_cb, async_data); \ + } \ + \ + /* Mark the cancellation as unsuccessful and hope we get proven wrong. */ \ + async_data->cancellation_successful = FALSE; \ + \ + g_test_message ("Running cancellation test with timeout of %u ms…", async_data->cancellation_timeout); \ + \ + { \ + TEST_BEGIN_CODE; \ + } \ + \ + g_main_loop_run (async_data->main_loop); \ + \ + /* Reset the cancellable for the next iteration and increase the timeout geometrically. */ \ + g_cancellable_reset (cancellable); \ + \ + if (async_data->cancellation_timeout == 0) { \ + async_data->cancellation_timeout = GDATA_ASYNC_STARTING_TIMEOUT; /* ms */ \ + } else { \ + async_data->cancellation_timeout *= GDATA_ASYNC_TIMEOUT_MULTIPLIER; \ + } \ + \ + uhm_server_end_trace (mock_server); \ + } while (async_data->cancellation_successful == TRUE); \ + \ + /* Clean up the last timeout callback */ \ + if (async_data->cancellation_timeout_id != 0) { \ + g_source_remove (async_data->cancellation_timeout_id); \ + } \ +} + +gboolean gdata_async_test_cancellation_cb (GDataAsyncTestData *async_data); +void gdata_set_up_async_test_data (GDataAsyncTestData *async_data, gconstpointer test_data); +void gdata_tear_down_async_test_data (GDataAsyncTestData *async_data, gconstpointer test_data); + +/** + * GDataTestRequestErrorData: + * @status_code: HTTP response status code + * @reason_phrase: HTTP response status phrase + * @message_body: HTTP response message body + * @error_domain_func: constant function returning the #GQuark for the expected error domain + * @error_code: expected error code + * + * A mapping between a HTTP response emitted by a #UhmServer and the error expected to be thrown by the HTTP client. + * This is designed for testing error handling in the client code, typically by running a single request through an array + * of these such mappings and testing the client code throws the correct error in each case. + * + * Since: 0.13.4 + */ +typedef struct { + /* HTTP response. */ + guint status_code; + const gchar *reason_phrase; + const gchar *message_body; + /* Expected GData error. */ + GQuark (*error_domain_func) (void); /* typically gdata_service_error_quark */ + gint error_code; +} GDataTestRequestErrorData; + +void gdata_test_set_https_port (UhmServer *server); +void gdata_test_mock_server_start_trace (UhmServer *server, const gchar *trace_filename); +gboolean gdata_test_mock_server_handle_message_error (UhmServer *server, SoupMessage *message, SoupClientContext *client, gpointer user_data); +gboolean gdata_test_mock_server_handle_message_timeout (UhmServer *server, SoupMessage *message, SoupClientContext *client, gpointer user_data); + +gchar *gdata_test_query_user_for_verifier (const gchar *authentication_uri) G_GNUC_WARN_UNUSED_RESULT G_GNUC_MALLOC; + +G_END_DECLS + +#endif /* !GDATA_TEST_COMMON_H */ diff --git a/gdata/tests/contacts.c b/gdata/tests/contacts.c new file mode 100644 index 0000000..e4f72de --- /dev/null +++ b/gdata/tests/contacts.c @@ -0,0 +1,2703 @@ +/* -*- Mode: C; indent-tabs-mode: t; c-basic-offset: 8; tab-width: 8 -*- */ +/* + * GData Client + * Copyright (C) Philip Withnall 2009, 2010, 2011, 2014 + * + * GData Client is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * GData Client is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with GData Client. If not, see . + */ + +#include +#include +#include + +#include "gdata.h" +#include "common.h" +#include "gdata-dummy-authorizer.h" + +static UhmServer *mock_server = NULL; + +#undef CLIENT_ID /* from common.h */ + +#define CLIENT_ID "352818697630-nqu2cmt5quqd6lr17ouoqmb684u84l1f.apps.googleusercontent.com" +#define CLIENT_SECRET "-fA4pHQJxR3zJ-FyAMPQsikg" +#define REDIRECT_URI "urn:ietf:wg:oauth:2.0:oob" + +typedef struct { + GDataContactsContact *contact; +} TempContactData; + +static void +set_up_temp_contact (TempContactData *data, gconstpointer service) +{ + GDataContactsContact *contact; + + gdata_test_mock_server_start_trace (mock_server, "setup-temp-contact"); + + /* Create a new temporary contact to use for a single test */ + contact = gdata_contacts_contact_new (NULL); + gdata_contacts_contact_set_nickname (contact, "Test Contact Esq."); + + /* Insert the contact */ + data->contact = gdata_contacts_service_insert_contact (GDATA_CONTACTS_SERVICE (service), contact, NULL, NULL); + g_assert (GDATA_IS_CONTACTS_CONTACT (data->contact)); + gdata_test_compare_kind (GDATA_ENTRY (data->contact), "http://schemas.google.com/contact/2008#contact", NULL); + + g_object_unref (contact); + + uhm_server_end_trace (mock_server); + + /* HACK. Wait for the server to propagate distributed changes. */ + if (uhm_server_get_enable_online (mock_server) == TRUE) { + sleep (10); + } +} + +static void +tear_down_temp_contact (TempContactData *data, gconstpointer service) +{ + GDataEntry *updated_contact; + + gdata_test_mock_server_start_trace (mock_server, "teardown-temp-contact"); + + /* Re-query for the contact to get any updated ETags */ + updated_contact = gdata_service_query_single_entry (GDATA_SERVICE (service), gdata_contacts_service_get_primary_authorization_domain (), + gdata_entry_get_id (GDATA_ENTRY (data->contact)), NULL, GDATA_TYPE_CONTACTS_CONTACT, + NULL, NULL); + g_assert (GDATA_IS_CONTACTS_CONTACT (updated_contact)); + + g_object_unref (data->contact); + + /* Delete the new/updated contact */ + g_assert (gdata_service_delete_entry (GDATA_SERVICE (service), gdata_contacts_service_get_primary_authorization_domain (), + updated_contact, NULL, NULL) == TRUE); + + g_object_unref (updated_contact); + + uhm_server_end_trace (mock_server); +} + +GDATA_ASYNC_CLOSURE_FUNCTIONS (temp_contact, TempContactData); + +static void +test_authentication (void) +{ + GDataOAuth2Authorizer *authorizer = NULL; /* owned */ + gchar *authentication_uri, *authorisation_code; + + gdata_test_mock_server_start_trace (mock_server, "authentication"); + + authorizer = gdata_oauth2_authorizer_new (CLIENT_ID, CLIENT_SECRET, + REDIRECT_URI, + GDATA_TYPE_CONTACTS_SERVICE); + + /* Get an authentication URI. */ + authentication_uri = gdata_oauth2_authorizer_build_authentication_uri (authorizer, NULL, FALSE); + g_assert (authentication_uri != NULL); + + /* Get the authorisation code off the user. */ + if (uhm_server_get_enable_online (mock_server)) { + authorisation_code = gdata_test_query_user_for_verifier (authentication_uri); + } else { + /* Hard coded, extracted from the trace file. */ + authorisation_code = g_strdup ("4/OEX-S1iMbOA_dOnNgUlSYmGWh3TK.QrR73axcNMkWoiIBeO6P2m_su7cwkQI"); + } + + g_free (authentication_uri); + + if (authorisation_code == NULL) { + /* Skip tests. */ + goto skip_test; + } + + /* Authorise the token */ + g_assert (gdata_oauth2_authorizer_request_authorization (authorizer, authorisation_code, NULL, NULL) == TRUE); + + /* Check all is as it should be */ + g_assert (gdata_authorizer_is_authorized_for_domain (GDATA_AUTHORIZER (authorizer), + gdata_contacts_service_get_primary_authorization_domain ()) == TRUE); + +skip_test: + g_free (authorisation_code); + g_object_unref (authorizer); + + uhm_server_end_trace (mock_server); +} + +typedef struct { + GDataContactsContact *contact1; + GDataContactsContact *contact2; + GDataContactsContact *contact3; +} QueryAllContactsData; + +static void +set_up_query_all_contacts (QueryAllContactsData *data, gconstpointer service) +{ + GDataContactsContact *contact; + + gdata_test_mock_server_start_trace (mock_server, "setup-query-all-contacts"); + + /* Create new temporary contacts to use for the query all contacts tests */ + contact = gdata_contacts_contact_new (NULL); + gdata_contacts_contact_set_nickname (contact, "Test Contact 1"); + data->contact1 = gdata_contacts_service_insert_contact (GDATA_CONTACTS_SERVICE (service), contact, NULL, NULL); + g_object_unref (contact); + + contact = gdata_contacts_contact_new (NULL); + gdata_contacts_contact_set_nickname (contact, "Test Contact 2"); + data->contact2 = gdata_contacts_service_insert_contact (GDATA_CONTACTS_SERVICE (service), contact, NULL, NULL); + g_object_unref (contact); + + contact = gdata_contacts_contact_new (NULL); + gdata_contacts_contact_set_nickname (contact, "Test Contact 3"); + data->contact3 = gdata_contacts_service_insert_contact (GDATA_CONTACTS_SERVICE (service), contact, NULL, NULL); + g_object_unref (contact); + + uhm_server_end_trace (mock_server); + + /* It takes a few seconds for the contacts to reliably propagate around Google's servers. Distributed systems are so fun. Not. + * Thankfully, we don't have to wait when running against the mock server. */ + if (uhm_server_get_enable_online (mock_server) == TRUE) { + g_usleep (G_USEC_PER_SEC * 5); + } +} + +static void +tear_down_query_all_contacts (QueryAllContactsData *data, gconstpointer service) +{ + gdata_test_mock_server_start_trace (mock_server, "teardown-query-all-contacts"); + + /* Delete the new contacts */ + g_assert (gdata_service_delete_entry (GDATA_SERVICE (service), gdata_contacts_service_get_primary_authorization_domain (), + GDATA_ENTRY (data->contact1), NULL, NULL) == TRUE); + g_object_unref (data->contact1); + + g_assert (gdata_service_delete_entry (GDATA_SERVICE (service), gdata_contacts_service_get_primary_authorization_domain (), + GDATA_ENTRY (data->contact2), NULL, NULL) == TRUE); + g_object_unref (data->contact2); + + g_assert (gdata_service_delete_entry (GDATA_SERVICE (service), gdata_contacts_service_get_primary_authorization_domain (), + GDATA_ENTRY (data->contact3), NULL, NULL) == TRUE); + g_object_unref (data->contact3); + + uhm_server_end_trace (mock_server); +} + +static void +test_query_all_contacts (QueryAllContactsData *data, gconstpointer service) +{ + GDataFeed *feed; + GError *error = NULL; + + gdata_test_mock_server_start_trace (mock_server, "query-all-contacts"); + + feed = gdata_contacts_service_query_contacts (GDATA_CONTACTS_SERVICE (service), NULL, NULL, NULL, NULL, &error); + g_assert_no_error (error); + g_assert (GDATA_IS_FEED (feed)); + g_clear_error (&error); + + /* TODO: check entries, kinds and feed properties */ + + g_object_unref (feed); + + uhm_server_end_trace (mock_server); +} + +GDATA_ASYNC_CLOSURE_FUNCTIONS (query_all_contacts, QueryAllContactsData); + +GDATA_ASYNC_TEST_FUNCTIONS (query_all_contacts, QueryAllContactsData, +G_STMT_START { + gdata_contacts_service_query_contacts_async (GDATA_CONTACTS_SERVICE (service), NULL, cancellable, NULL, + NULL, NULL, async_ready_callback, async_data); +} G_STMT_END, +G_STMT_START { + GDataFeed *feed; + + feed = gdata_service_query_finish (GDATA_SERVICE (obj), async_result, &error); + + if (error == NULL) { + g_assert (GDATA_IS_FEED (feed)); + /* TODO: Tests? */ + + g_object_unref (feed); + } else { + g_assert (feed == NULL); + } +} G_STMT_END); + +static void +test_query_all_contacts_async_progress_closure (QueryAllContactsData *query_data, gconstpointer service) +{ + GDataAsyncProgressClosure *data = g_slice_new0 (GDataAsyncProgressClosure); + + gdata_test_mock_server_start_trace (mock_server, "query-all-contacts-async-progress-closure"); + + data->main_loop = g_main_loop_new (NULL, TRUE); + + gdata_contacts_service_query_contacts_async (GDATA_CONTACTS_SERVICE (service), NULL, NULL, + (GDataQueryProgressCallback) gdata_test_async_progress_callback, + data, (GDestroyNotify) gdata_test_async_progress_closure_free, + (GAsyncReadyCallback) gdata_test_async_progress_finish_callback, data); + g_main_loop_run (data->main_loop); + g_main_loop_unref (data->main_loop); + + /* Check that both callbacks were called exactly once */ + g_assert_cmpuint (data->progress_destroy_notify_count, ==, 1); + g_assert_cmpuint (data->async_ready_notify_count, ==, 1); + + g_slice_free (GDataAsyncProgressClosure, data); + + uhm_server_end_trace (mock_server); +} + +typedef struct { + GDataContactsContact *new_contact; +} InsertData; + +static void +set_up_insert (InsertData *data, gconstpointer service) +{ + data->new_contact = NULL; +} + +static void +tear_down_insert (InsertData *data, gconstpointer service) +{ + gdata_test_mock_server_start_trace (mock_server, "teardown-insert"); + + /* Delete the new contact */ + g_assert (gdata_service_delete_entry (GDATA_SERVICE (service), gdata_contacts_service_get_primary_authorization_domain (), + GDATA_ENTRY (data->new_contact), NULL, NULL) == TRUE); + + g_object_unref (data->new_contact); + + uhm_server_end_trace (mock_server); +} + +static void +test_contact_insert (InsertData *data, gconstpointer service) +{ + GDataContactsContact *contact, *new_contact; + GDataGDName *name, *name2; + GDataGDEmailAddress *email_address1, *email_address2; + GDataGDPhoneNumber *phone_number1, *phone_number2; + GDataGDIMAddress *im_address; + GDataGDOrganization *org; + GDataGDPostalAddress *postal_address; + GDataGContactJot *jot; + GDataGContactRelation *relation; + GDataGContactWebsite *website; + GDataGContactEvent *event; + GDataGContactCalendar *calendar; + GDataGContactExternalID *external_id; + GDataGContactLanguage *language; + GList *list; + GDate date; + GHashTable *properties; + GTimeVal current_time; + gint64 edited, creation_time; + GError *error = NULL; + + gdata_test_mock_server_start_trace (mock_server, "contact-insert"); + + contact = gdata_contacts_contact_new (NULL); + g_get_current_time (¤t_time); + + /* Check the kind is present and correct */ + g_assert (GDATA_IS_CONTACTS_CONTACT (contact)); + gdata_test_compare_kind (GDATA_ENTRY (contact), "http://schemas.google.com/contact/2008#contact", NULL); + + /* Set and check the name (to check if the title of the entry is updated) */ + gdata_entry_set_title (GDATA_ENTRY (contact), "Elizabeth Bennet"); + name = gdata_contacts_contact_get_name (contact); + gdata_gd_name_set_full_name (name, "Lizzie Bennet"); + + name2 = gdata_gd_name_new ("John", "Smith"); + gdata_gd_name_set_full_name (name2, "John Smith"); + gdata_contacts_contact_set_name (contact, name2); + g_object_unref (name2); + + gdata_contacts_contact_set_nickname (contact, "Big J"); + gdata_contacts_contact_set_file_as (contact, "J, Big"); + g_date_set_dmy (&date, 1, 1, 1900); + gdata_contacts_contact_set_birthday (contact, &date, FALSE); + gdata_entry_set_content (GDATA_ENTRY (contact), "Notes"); + gdata_contacts_contact_set_billing_information (contact, "Big J Enterprises, Ltd."); + gdata_contacts_contact_set_directory_server (contact, "This is a server"); + gdata_contacts_contact_set_gender (contact, GDATA_CONTACTS_GENDER_MALE); + gdata_contacts_contact_set_initials (contact, "A. B. C."); + gdata_contacts_contact_set_maiden_name (contact, "Smith"); + gdata_contacts_contact_set_mileage (contact, "12km"); + gdata_contacts_contact_set_occupation (contact, "Professional bum"); + gdata_contacts_contact_set_priority (contact, GDATA_CONTACTS_PRIORITY_HIGH); + gdata_contacts_contact_set_sensitivity (contact, GDATA_CONTACTS_SENSITIVITY_PERSONAL); + gdata_contacts_contact_set_short_name (contact, "Jon"); + gdata_contacts_contact_set_subject (contact, "Charity work"); + + email_address1 = gdata_gd_email_address_new ("liz@gmail.com", GDATA_GD_EMAIL_ADDRESS_WORK, NULL, FALSE); + gdata_contacts_contact_add_email_address (contact, email_address1); + g_object_unref (email_address1); + + email_address2 = gdata_gd_email_address_new ("liz@example.org", GDATA_GD_EMAIL_ADDRESS_HOME, NULL, FALSE); + gdata_contacts_contact_add_email_address (contact, email_address2); + g_object_unref (email_address2); + + phone_number1 = gdata_gd_phone_number_new ("(206)555-1212", GDATA_GD_PHONE_NUMBER_WORK, NULL, NULL, TRUE); + gdata_contacts_contact_add_phone_number (contact, phone_number1); + g_object_unref (phone_number1); + + phone_number2 = gdata_gd_phone_number_new ("(206)555-1213", GDATA_GD_PHONE_NUMBER_HOME, NULL, NULL, FALSE); + gdata_contacts_contact_add_phone_number (contact, phone_number2); + g_object_unref (phone_number2); + + im_address = gdata_gd_im_address_new ("liz@gmail.com", GDATA_GD_IM_PROTOCOL_GOOGLE_TALK, GDATA_GD_IM_ADDRESS_HOME, NULL, FALSE); + gdata_contacts_contact_add_im_address (contact, im_address); + g_object_unref (im_address); + + postal_address = gdata_gd_postal_address_new (GDATA_GD_POSTAL_ADDRESS_WORK, NULL, TRUE); + gdata_gd_postal_address_set_street (postal_address, "1600 Amphitheatre Pkwy Mountain View"); + gdata_contacts_contact_add_postal_address (contact, postal_address); + g_object_unref (postal_address); + + org = gdata_gd_organization_new ("OrgCorp", "President", GDATA_GD_ORGANIZATION_WORK, NULL, FALSE); + gdata_contacts_contact_add_organization (contact, org); + g_object_unref (org); + + jot = gdata_gcontact_jot_new ("This is a jot.", GDATA_GCONTACT_JOT_OTHER); + gdata_contacts_contact_add_jot (contact, jot); + g_object_unref (jot); + + relation = gdata_gcontact_relation_new ("Brian Haddock", GDATA_GCONTACT_RELATION_FRIEND, NULL); + gdata_contacts_contact_add_relation (contact, relation); + g_object_unref (relation); + + website = gdata_gcontact_website_new ("http://example.com/", GDATA_GCONTACT_WEBSITE_PROFILE, NULL, TRUE); + gdata_contacts_contact_add_website (contact, website); + g_object_unref (website); + + event = gdata_gcontact_event_new (&date, GDATA_GCONTACT_EVENT_ANNIVERSARY, NULL); + gdata_contacts_contact_add_event (contact, event); + g_object_unref (event); + + calendar = gdata_gcontact_calendar_new ("http://calendar.example.com/", GDATA_GCONTACT_CALENDAR_HOME, NULL, TRUE); + gdata_contacts_contact_add_calendar (contact, calendar); + g_object_unref (calendar); + + external_id = gdata_gcontact_external_id_new ("Number Six", GDATA_GCONTACT_EXTERNAL_ID_ORGANIZATION, NULL); + gdata_contacts_contact_add_external_id (contact, external_id); + g_object_unref (external_id); + + gdata_contacts_contact_add_hobby (contact, "Rowing"); + + language = gdata_gcontact_language_new ("en-GB", NULL); + gdata_contacts_contact_add_language (contact, language); + g_object_unref (language); + + /* Add some extended properties */ + g_assert (gdata_contacts_contact_set_extended_property (contact, "TITLE", NULL) == TRUE); + g_assert (gdata_contacts_contact_set_extended_property (contact, "ROLE", "") == TRUE); + g_assert (gdata_contacts_contact_set_extended_property (contact, "CALURI", "http://example.com/") == TRUE); + + /* Add some user-defined fields */ + gdata_contacts_contact_set_user_defined_field (contact, "Favourite colour", "Blue"); + gdata_contacts_contact_set_user_defined_field (contact, "Owes me", "£10"); + gdata_contacts_contact_set_user_defined_field (contact, "My notes", ""); + gdata_contacts_contact_set_user_defined_field (contact, "", "Foo"); /* bgo#648058 */ + + /* Insert the contact */ + new_contact = data->new_contact = gdata_contacts_service_insert_contact (GDATA_CONTACTS_SERVICE (service), contact, NULL, &error); + g_assert_no_error (error); + g_assert (GDATA_IS_CONTACTS_CONTACT (new_contact)); + gdata_test_compare_kind (GDATA_ENTRY (new_contact), "http://schemas.google.com/contact/2008#contact", NULL); + g_clear_error (&error); + + /* Check its edited date. Yes, we have to allow the edited time to possibly precede the creation time because Google's + * servers can allow this to happen. Somehow. + * This check isn't run when testing against a mock server because the dates in the trace file may be waaaay out of date. */ + edited = gdata_contacts_contact_get_edited (contact); + if (uhm_server_get_enable_online (mock_server) == TRUE) { + creation_time = gdata_contacts_contact_get_edited (new_contact); + g_assert_cmpint (creation_time + TIME_FUZZINESS, >=, edited); + g_assert_cmpint (creation_time - TIME_FUZZINESS, <=, edited); + } + + /* Various properties */ + g_assert_cmpstr (gdata_contacts_contact_get_nickname (new_contact), ==, "Big J"); + g_assert_cmpstr (gdata_contacts_contact_get_file_as (new_contact), ==, "J, Big"); + g_assert (gdata_contacts_contact_get_birthday (new_contact, &date) == FALSE); + g_assert (g_date_valid (&date) == TRUE); + g_assert_cmpuint (g_date_get_month (&date), ==, 1); + g_assert_cmpuint (g_date_get_day (&date), ==, 1); + g_assert_cmpstr (gdata_contacts_contact_get_billing_information (new_contact), ==, "Big J Enterprises, Ltd."); + g_assert_cmpstr (gdata_contacts_contact_get_directory_server (new_contact), ==, "This is a server"); + g_assert_cmpstr (gdata_contacts_contact_get_gender (new_contact), ==, GDATA_CONTACTS_GENDER_MALE); + g_assert_cmpstr (gdata_contacts_contact_get_initials (new_contact), ==, "A. B. C."); + g_assert_cmpstr (gdata_contacts_contact_get_maiden_name (new_contact), ==, "Smith"); + g_assert_cmpstr (gdata_contacts_contact_get_mileage (new_contact), ==, "12km"); + g_assert_cmpstr (gdata_contacts_contact_get_occupation (new_contact), ==, "Professional bum"); + /* FIXME: https://code.google.com/a/google.com/p/apps-api-issues/issues/detail?id=3662 + * g_assert_cmpstr (gdata_contacts_contact_get_priority (new_contact), ==, GDATA_CONTACTS_PRIORITY_HIGH); + * g_assert_cmpstr (gdata_contacts_contact_get_sensitivity (new_contact), ==, GDATA_CONTACTS_SENSITIVITY_PERSONAL); */ + g_assert_cmpstr (gdata_contacts_contact_get_short_name (new_contact), ==, "Jon"); + g_assert_cmpstr (gdata_contacts_contact_get_subject (new_contact), ==, "Charity work"); + + /* E-mail addresses */ + list = gdata_contacts_contact_get_email_addresses (new_contact); + g_assert_cmpuint (g_list_length (list), ==, 2); + g_assert (GDATA_IS_GD_EMAIL_ADDRESS (list->data)); + + g_assert (gdata_contacts_contact_get_primary_email_address (new_contact) == NULL); + + /* IM addresses */ + list = gdata_contacts_contact_get_im_addresses (new_contact); + g_assert_cmpuint (g_list_length (list), ==, 1); + g_assert (GDATA_IS_GD_IM_ADDRESS (list->data)); + + g_assert (gdata_contacts_contact_get_primary_im_address (new_contact) == NULL); + + /* Phone numbers */ + list = gdata_contacts_contact_get_phone_numbers (new_contact); + g_assert_cmpuint (g_list_length (list), ==, 2); + g_assert (GDATA_IS_GD_PHONE_NUMBER (list->data)); + + g_assert (GDATA_IS_GD_PHONE_NUMBER (gdata_contacts_contact_get_primary_phone_number (new_contact))); + + /* Postal addresses */ + list = gdata_contacts_contact_get_postal_addresses (new_contact); + g_assert_cmpuint (g_list_length (list), ==, 1); + g_assert (GDATA_IS_GD_POSTAL_ADDRESS (list->data)); + + g_assert (GDATA_IS_GD_POSTAL_ADDRESS (gdata_contacts_contact_get_primary_postal_address (new_contact))); + + /* Organizations */ + list = gdata_contacts_contact_get_organizations (new_contact); + g_assert_cmpuint (g_list_length (list), ==, 1); + g_assert (GDATA_IS_GD_ORGANIZATION (list->data)); + + g_assert (gdata_contacts_contact_get_primary_organization (new_contact) == NULL); + + /* Jots */ + list = gdata_contacts_contact_get_jots (new_contact); + g_assert_cmpuint (g_list_length (list), ==, 1); + g_assert (GDATA_IS_GCONTACT_JOT (list->data)); + + /* Relations */ + list = gdata_contacts_contact_get_relations (new_contact); + g_assert_cmpuint (g_list_length (list), ==, 1); + g_assert (GDATA_IS_GCONTACT_RELATION (list->data)); + + /* Websites */ + list = gdata_contacts_contact_get_websites (new_contact); + g_assert_cmpuint (g_list_length (list), ==, 1); + g_assert (GDATA_IS_GCONTACT_WEBSITE (list->data)); + + g_assert (GDATA_IS_GCONTACT_WEBSITE (gdata_contacts_contact_get_primary_website (new_contact))); + + /* Events */ + list = gdata_contacts_contact_get_events (new_contact); + g_assert_cmpuint (g_list_length (list), ==, 1); + g_assert (GDATA_IS_GCONTACT_EVENT (list->data)); + + /* Calendars */ + list = gdata_contacts_contact_get_calendars (new_contact); + g_assert_cmpuint (g_list_length (list), ==, 1); + g_assert (GDATA_IS_GCONTACT_CALENDAR (list->data)); + + g_assert (GDATA_IS_GCONTACT_CALENDAR (gdata_contacts_contact_get_primary_calendar (new_contact))); + + /* External IDs */ + list = gdata_contacts_contact_get_external_ids (new_contact); + g_assert_cmpuint (g_list_length (list), ==, 1); + g_assert (GDATA_IS_GCONTACT_EXTERNAL_ID (list->data)); + + /* Languages */ + list = gdata_contacts_contact_get_languages (new_contact); + g_assert_cmpuint (g_list_length (list), ==, 1); + g_assert (GDATA_IS_GCONTACT_LANGUAGE (list->data)); + + /* Hobbies */ + list = gdata_contacts_contact_get_hobbies (new_contact); + g_assert_cmpuint (g_list_length (list), ==, 1); + g_assert_cmpstr (list->data, ==, "Rowing"); + + /* Extended properties */ + g_assert_cmpstr (gdata_contacts_contact_get_extended_property (new_contact, "CALURI"), ==, "http://example.com/"); + g_assert (gdata_contacts_contact_get_extended_property (new_contact, "non-existent") == NULL); + + properties = gdata_contacts_contact_get_extended_properties (new_contact); + g_assert (properties != NULL); + g_assert_cmpuint (g_hash_table_size (properties), ==, 1); + + /* User-defined fields */ + g_assert_cmpstr (gdata_contacts_contact_get_user_defined_field (new_contact, "Favourite colour"), ==, "Blue"); + g_assert_cmpstr (gdata_contacts_contact_get_user_defined_field (new_contact, "Owes me"), ==, "£10"); + g_assert_cmpstr (gdata_contacts_contact_get_user_defined_field (new_contact, "My notes"), ==, ""); + g_assert_cmpstr (gdata_contacts_contact_get_user_defined_field (new_contact, ""), ==, "Foo"); + + properties = gdata_contacts_contact_get_user_defined_fields (new_contact); + g_assert (properties != NULL); + g_assert_cmpuint (g_hash_table_size (properties), ==, 4); + + /* Groups */ + list = gdata_contacts_contact_get_groups (new_contact); + g_assert (list == NULL); + + /* Deleted? */ + g_assert (gdata_contacts_contact_is_deleted (new_contact) == FALSE); + + /* TODO: check entries and feed properties */ + + g_object_unref (contact); + + uhm_server_end_trace (mock_server); +} + +static void +test_contact_update (TempContactData *data, gconstpointer service) +{ + GDataContactsContact *new_contact; + GError *error = NULL; + + gdata_test_mock_server_start_trace (mock_server, "contact-update"); + + /* Update the contact's name and add an extended property */ + gdata_entry_set_title (GDATA_ENTRY (data->contact), "John Wilson"); + g_assert (gdata_contacts_contact_set_extended_property (data->contact, "contact-test", "value")); + + /* Update the contact */ + new_contact = GDATA_CONTACTS_CONTACT (gdata_service_update_entry (GDATA_SERVICE (service), + gdata_contacts_service_get_primary_authorization_domain (), + GDATA_ENTRY (data->contact), NULL, &error)); + g_assert_no_error (error); + g_assert (GDATA_IS_CONTACTS_CONTACT (new_contact)); + gdata_test_compare_kind (GDATA_ENTRY (new_contact), "http://schemas.google.com/contact/2008#contact", NULL); + g_clear_error (&error); + + /* Check a few properties */ + g_assert_cmpstr (gdata_entry_get_title (GDATA_ENTRY (new_contact)), ==, "John Wilson"); + g_assert_cmpstr (gdata_contacts_contact_get_extended_property (new_contact, "contact-test"), ==, "value"); + g_assert (gdata_contacts_contact_is_deleted (new_contact) == FALSE); + + g_object_unref (new_contact); + + uhm_server_end_trace (mock_server); +} + +typedef struct { + GDataContactsGroup *group1; + GDataContactsGroup *group2; + GDataContactsGroup *group3; +} QueryAllGroupsData; + +static void +set_up_query_all_groups (QueryAllGroupsData *data, gconstpointer service) +{ + GDataContactsGroup *group; + + gdata_test_mock_server_start_trace (mock_server, "setup-query-all-groups"); + + group = gdata_contacts_group_new (NULL); + gdata_entry_set_title (GDATA_ENTRY (group), "Test Group 1"); + data->group1 = gdata_contacts_service_insert_group (GDATA_CONTACTS_SERVICE (service), group, NULL, NULL); + g_assert (GDATA_IS_CONTACTS_GROUP (data->group1)); + g_object_unref (group); + + group = gdata_contacts_group_new (NULL); + gdata_entry_set_title (GDATA_ENTRY (group), "Test Group 2"); + data->group2 = gdata_contacts_service_insert_group (GDATA_CONTACTS_SERVICE (service), group, NULL, NULL); + g_assert (GDATA_IS_CONTACTS_GROUP (data->group2)); + g_object_unref (group); + + group = gdata_contacts_group_new (NULL); + gdata_entry_set_title (GDATA_ENTRY (group), "Test Group 3"); + data->group3 = gdata_contacts_service_insert_group (GDATA_CONTACTS_SERVICE (service), group, NULL, NULL); + g_assert (GDATA_IS_CONTACTS_GROUP (data->group3)); + g_object_unref (group); + + uhm_server_end_trace (mock_server); + + /* HACK! Guess what? Distributed system inconsistency strikes again! */ + if (uhm_server_get_enable_online (mock_server) == TRUE) { + sleep (10); + } +} + +static void +tear_down_query_all_groups (QueryAllGroupsData *data, gconstpointer service) +{ + gdata_test_mock_server_start_trace (mock_server, "teardown-query-all-groups"); + + g_assert (gdata_service_delete_entry (GDATA_SERVICE (service), gdata_contacts_service_get_primary_authorization_domain (), + GDATA_ENTRY (data->group1), NULL, NULL) == TRUE); + g_object_unref (data->group1); + + g_assert (gdata_service_delete_entry (GDATA_SERVICE (service), gdata_contacts_service_get_primary_authorization_domain (), + GDATA_ENTRY (data->group2), NULL, NULL) == TRUE); + g_object_unref (data->group2); + + g_assert (gdata_service_delete_entry (GDATA_SERVICE (service), gdata_contacts_service_get_primary_authorization_domain (), + GDATA_ENTRY (data->group3), NULL, NULL) == TRUE); + g_object_unref (data->group3); + + uhm_server_end_trace (mock_server); +} + +static void +test_query_all_groups (QueryAllGroupsData *data, gconstpointer service) +{ + GDataFeed *feed; + GError *error = NULL; + + gdata_test_mock_server_start_trace (mock_server, "query-all-groups"); + + feed = gdata_contacts_service_query_groups (GDATA_CONTACTS_SERVICE (service), NULL, NULL, NULL, NULL, &error); + g_assert_no_error (error); + g_assert (GDATA_IS_FEED (feed)); + g_clear_error (&error); + + /* TODO: check entries, kinds and feed properties */ + + g_object_unref (feed); + + uhm_server_end_trace (mock_server); +} + +GDATA_ASYNC_CLOSURE_FUNCTIONS (query_all_groups, QueryAllGroupsData); + +GDATA_ASYNC_TEST_FUNCTIONS (query_all_groups, QueryAllGroupsData, +G_STMT_START { + gdata_contacts_service_query_groups_async (GDATA_CONTACTS_SERVICE (service), NULL, cancellable, NULL, NULL, NULL, + async_ready_callback, async_data); +} G_STMT_END, +G_STMT_START { + GDataFeed *feed; + + feed = gdata_service_query_finish (GDATA_SERVICE (obj), async_result, &error); + + if (error == NULL) { + g_assert (GDATA_IS_FEED (feed)); + /* TODO: Tests? */ + + g_object_unref (feed); + } else { + g_assert (feed == NULL); + } +} G_STMT_END); + +static void +test_query_all_groups_async_progress_closure (QueryAllGroupsData *query_data, gconstpointer service) +{ + GDataAsyncProgressClosure *data = g_slice_new0 (GDataAsyncProgressClosure); + + gdata_test_mock_server_start_trace (mock_server, "query-all-groups-async-progress-closure"); + + data->main_loop = g_main_loop_new (NULL, TRUE); + + gdata_contacts_service_query_groups_async (GDATA_CONTACTS_SERVICE (service), NULL, NULL, + (GDataQueryProgressCallback) gdata_test_async_progress_callback, + data, (GDestroyNotify) gdata_test_async_progress_closure_free, + (GAsyncReadyCallback) gdata_test_async_progress_finish_callback, data); + + g_main_loop_run (data->main_loop); + g_main_loop_unref (data->main_loop); + + /* Check that both callbacks were called exactly once */ + g_assert_cmpuint (data->progress_destroy_notify_count, ==, 1); + g_assert_cmpuint (data->async_ready_notify_count, ==, 1); + + g_slice_free (GDataAsyncProgressClosure, data); + + uhm_server_end_trace (mock_server); +} + +typedef struct { + GDataContactsGroup *new_group; +} InsertGroupData; + +static void +set_up_insert_group (InsertGroupData *data, gconstpointer service) +{ + data->new_group = NULL; +} + +static void +tear_down_insert_group (InsertGroupData *data, gconstpointer service) +{ + /* HACK! Distributed systems suck. */ + if (uhm_server_get_enable_online (mock_server) == TRUE) { + sleep (10); + } + + gdata_test_mock_server_start_trace (mock_server, "teardown-insert-group"); + + /* Delete the group, just to be tidy */ + g_assert (gdata_service_delete_entry (GDATA_SERVICE (service), gdata_contacts_service_get_primary_authorization_domain (), + GDATA_ENTRY (data->new_group), NULL, NULL) == TRUE); + g_object_unref (data->new_group); + + uhm_server_end_trace (mock_server); +} + +static void +test_group_insert (InsertGroupData *data, gconstpointer service) +{ + GDataContactsGroup *group, *new_group; + GTimeVal time_val; + GHashTable *properties; + GError *error = NULL; + + gdata_test_mock_server_start_trace (mock_server, "group-insert"); + + g_get_current_time (&time_val); + + group = gdata_contacts_group_new (NULL); + + /* Check the kind is present and correct */ + g_assert (GDATA_IS_CONTACTS_GROUP (group)); + gdata_test_compare_kind (GDATA_ENTRY (group), "http://schemas.google.com/contact/2008#group", NULL); + + /* Set various properties */ + gdata_entry_set_title (GDATA_ENTRY (group), "New Group!"); + g_assert (gdata_contacts_group_set_extended_property (group, "foobar", "barfoo") == TRUE); + + /* Insert the group */ + new_group = data->new_group = gdata_contacts_service_insert_group (GDATA_CONTACTS_SERVICE (service), group, NULL, &error); + g_assert_no_error (error); + g_assert (GDATA_IS_CONTACTS_GROUP (new_group)); + gdata_test_compare_kind (GDATA_ENTRY (new_group), "http://schemas.google.com/contact/2008#group", NULL); + g_clear_error (&error); + + /* Check the properties. Time-based properties can't be checked when running against a mock server, since + * the trace files may be quite old. */ + if (uhm_server_get_enable_online (mock_server) == TRUE) { + g_assert_cmpint (gdata_contacts_group_get_edited (new_group), >=, time_val.tv_sec); + } + g_assert (gdata_contacts_group_is_deleted (new_group) == FALSE); + g_assert (gdata_contacts_group_get_system_group_id (new_group) == NULL); + + properties = gdata_contacts_group_get_extended_properties (new_group); + g_assert (properties != NULL); + g_assert_cmpint (g_hash_table_size (properties), ==, 1); + g_assert_cmpstr (gdata_contacts_group_get_extended_property (new_group, "foobar"), ==, "barfoo"); + + g_object_unref (group); + + uhm_server_end_trace (mock_server); +} + +GDATA_ASYNC_CLOSURE_FUNCTIONS (insert_group, InsertGroupData); + +GDATA_ASYNC_TEST_FUNCTIONS (group_insert, InsertGroupData, +G_STMT_START { + GDataContactsGroup *group; + + group = gdata_contacts_group_new (NULL); + + /* Check the kind is present and correct */ + g_assert (GDATA_IS_CONTACTS_GROUP (group)); + gdata_test_compare_kind (GDATA_ENTRY (group), "http://schemas.google.com/contact/2008#group", NULL); + + /* Set various properties */ + gdata_entry_set_title (GDATA_ENTRY (group), "New Group!"); + g_assert (gdata_contacts_group_set_extended_property (group, "foobar", "barfoo") == TRUE); + + gdata_contacts_service_insert_group_async (GDATA_CONTACTS_SERVICE (service), group, cancellable, async_ready_callback, async_data); + + g_object_unref (group); +} G_STMT_END, +G_STMT_START { + GDataEntry *entry; + + entry = gdata_service_insert_entry_finish (GDATA_SERVICE (obj), async_result, &error); + + if (error == NULL) { + g_assert (GDATA_IS_CONTACTS_GROUP (entry)); + /* TODO: Tests? */ + + data->new_group = GDATA_CONTACTS_GROUP (entry); + } else { + g_assert (entry == NULL); + } +} G_STMT_END); + +static void +test_contact_properties (void) +{ + GDataContactsContact *contact; + GDataGDName *name, *name2; + GDataGDEmailAddress *email_address1, *email_address2; + GDataGDPhoneNumber *phone_number1, *phone_number2; + GDataGDIMAddress *im_address; + GDataGDOrganization *org; + GDataGDPostalAddress *postal_address; + GDataGContactJot *jot; + GDataGContactRelation *relation; + GDataGContactWebsite *website; + GDataGContactEvent *event; + GDataGContactCalendar *calendar; + GDataGContactExternalID *external_id; + GDataGContactLanguage *language; + gchar *nickname, *file_as, *billing_information, *directory_server, *gender, *initials, *maiden_name, *mileage, *occupation; + gchar *priority, *sensitivity, *short_name, *subject, *photo_etag; + GDate date, *date2; + GTimeVal current_time; + gint64 edited; + gboolean deleted, birthday_has_year; + + contact = gdata_contacts_contact_new (NULL); + g_get_current_time (¤t_time); + + /* Check the kind is present and correct */ + g_assert (GDATA_IS_CONTACTS_CONTACT (contact)); + gdata_test_compare_kind (GDATA_ENTRY (contact), "http://schemas.google.com/contact/2008#contact", NULL); + + /* Set and check the name (to check if the title of the entry is updated) */ + gdata_entry_set_title (GDATA_ENTRY (contact), "Elizabeth Bennet"); + name = gdata_contacts_contact_get_name (contact); + g_assert_cmpstr (gdata_gd_name_get_full_name (name), ==, "Elizabeth Bennet"); + gdata_gd_name_set_full_name (name, "Lizzie Bennet"); + g_assert_cmpstr (gdata_entry_get_title (GDATA_ENTRY (contact)), ==, "Lizzie Bennet"); + + name2 = gdata_gd_name_new ("John", "Smith"); + gdata_gd_name_set_full_name (name2, "John Smith"); + gdata_contacts_contact_set_name (contact, name2); + g_object_unref (name2); + g_assert_cmpstr (gdata_entry_get_title (GDATA_ENTRY (contact)), ==, "John Smith"); + + gdata_contacts_contact_set_nickname (contact, "Big J"); + gdata_contacts_contact_set_file_as (contact, "J, Big"); + g_date_set_dmy (&date, 1, 1, 1900); + gdata_contacts_contact_set_birthday (contact, &date, FALSE); + gdata_entry_set_content (GDATA_ENTRY (contact), "Notes"); + gdata_contacts_contact_set_billing_information (contact, "Big J Enterprises, Ltd."); + gdata_contacts_contact_set_directory_server (contact, "This is a server"); + gdata_contacts_contact_set_gender (contact, GDATA_CONTACTS_GENDER_MALE); + gdata_contacts_contact_set_initials (contact, "A. B. C."); + gdata_contacts_contact_set_maiden_name (contact, "Smith"); + gdata_contacts_contact_set_mileage (contact, "12km"); + gdata_contacts_contact_set_occupation (contact, "Professional bum"); + gdata_contacts_contact_set_priority (contact, GDATA_CONTACTS_PRIORITY_HIGH); + gdata_contacts_contact_set_sensitivity (contact, GDATA_CONTACTS_SENSITIVITY_PERSONAL); + gdata_contacts_contact_set_short_name (contact, "Jon"); + gdata_contacts_contact_set_subject (contact, "Charity work"); + + email_address1 = gdata_gd_email_address_new ("liz@gmail.com", GDATA_GD_EMAIL_ADDRESS_WORK, NULL, FALSE); + gdata_contacts_contact_add_email_address (contact, email_address1); + g_object_unref (email_address1); + + email_address2 = gdata_gd_email_address_new ("liz@example.org", GDATA_GD_EMAIL_ADDRESS_HOME, NULL, FALSE); + gdata_contacts_contact_add_email_address (contact, email_address2); + g_object_unref (email_address2); + + phone_number1 = gdata_gd_phone_number_new ("(206)555-1212", GDATA_GD_PHONE_NUMBER_WORK, NULL, NULL, TRUE); + gdata_contacts_contact_add_phone_number (contact, phone_number1); + g_object_unref (phone_number1); + + phone_number2 = gdata_gd_phone_number_new ("(206)555-1213", GDATA_GD_PHONE_NUMBER_HOME, NULL, NULL, FALSE); + gdata_contacts_contact_add_phone_number (contact, phone_number2); + g_object_unref (phone_number2); + + im_address = gdata_gd_im_address_new ("liz@gmail.com", GDATA_GD_IM_PROTOCOL_GOOGLE_TALK, GDATA_GD_IM_ADDRESS_HOME, NULL, FALSE); + gdata_contacts_contact_add_im_address (contact, im_address); + g_object_unref (im_address); + + postal_address = gdata_gd_postal_address_new (GDATA_GD_POSTAL_ADDRESS_WORK, NULL, TRUE); + gdata_gd_postal_address_set_street (postal_address, "1600 Amphitheatre Pkwy Mountain View"); + gdata_contacts_contact_add_postal_address (contact, postal_address); + g_object_unref (postal_address); + + org = gdata_gd_organization_new ("OrgCorp", "President", GDATA_GD_ORGANIZATION_WORK, NULL, FALSE); + gdata_contacts_contact_add_organization (contact, org); + g_object_unref (org); + + jot = gdata_gcontact_jot_new ("This is a jot.", GDATA_GCONTACT_JOT_OTHER); + gdata_contacts_contact_add_jot (contact, jot); + g_object_unref (jot); + + relation = gdata_gcontact_relation_new ("Brian Haddock", GDATA_GCONTACT_RELATION_FRIEND, NULL); + gdata_contacts_contact_add_relation (contact, relation); + g_object_unref (relation); + + website = gdata_gcontact_website_new ("http://example.com/", GDATA_GCONTACT_WEBSITE_PROFILE, NULL, TRUE); + gdata_contacts_contact_add_website (contact, website); + g_object_unref (website); + + event = gdata_gcontact_event_new (&date, GDATA_GCONTACT_EVENT_ANNIVERSARY, NULL); + gdata_contacts_contact_add_event (contact, event); + g_object_unref (event); + + calendar = gdata_gcontact_calendar_new ("http://calendar.example.com/", GDATA_GCONTACT_CALENDAR_HOME, NULL, TRUE); + gdata_contacts_contact_add_calendar (contact, calendar); + g_object_unref (calendar); + + external_id = gdata_gcontact_external_id_new ("Number Six", GDATA_GCONTACT_EXTERNAL_ID_ORGANIZATION, NULL); + gdata_contacts_contact_add_external_id (contact, external_id); + g_object_unref (external_id); + + gdata_contacts_contact_add_hobby (contact, "Rowing"); + + language = gdata_gcontact_language_new ("en-GB", NULL); + gdata_contacts_contact_add_language (contact, language); + g_object_unref (language); + + /* Add some extended properties */ + g_assert (gdata_contacts_contact_set_extended_property (contact, "TITLE", NULL) == TRUE); + g_assert (gdata_contacts_contact_set_extended_property (contact, "ROLE", "") == TRUE); + g_assert (gdata_contacts_contact_set_extended_property (contact, "CALURI", "http://example.com/") == TRUE); + + /* Add some user-defined fields */ + gdata_contacts_contact_set_user_defined_field (contact, "Favourite colour", "Blue"); + gdata_contacts_contact_set_user_defined_field (contact, "Owes me", "£10"); + gdata_contacts_contact_set_user_defined_field (contact, "My notes", ""); + gdata_contacts_contact_set_user_defined_field (contact, "", "Foo"); /* bgo#648058 */ + + /* Check the properties of the object */ + g_object_get (G_OBJECT (contact), + "edited", &edited, + "deleted", &deleted, + "photo-etag", &photo_etag, + "name", &name, + "nickname", &nickname, + "file-as", &file_as, + "birthday", &date2, + "birthday-has-year", &birthday_has_year, + "billing-information", &billing_information, + "directory-server", &directory_server, + "gender", &gender, + "initials", &initials, + "maiden-name", &maiden_name, + "mileage", &mileage, + "occupation", &occupation, + "priority", &priority, + "sensitivity", &sensitivity, + "short-name", &short_name, + "subject", &subject, + NULL); + + g_assert_cmpint (edited, ==, current_time.tv_sec); + g_assert (deleted == FALSE); + g_assert (photo_etag == NULL); + g_assert (name2 == name); + g_assert_cmpstr (nickname, ==, "Big J"); + g_assert_cmpstr (file_as, ==, "J, Big"); + g_assert (g_date_valid (date2) == TRUE); + g_assert_cmpuint (g_date_get_month (date2), ==, 1); + g_assert_cmpuint (g_date_get_day (date2), ==, 1); + g_assert (birthday_has_year == FALSE); + g_assert_cmpstr (billing_information, ==, "Big J Enterprises, Ltd."); + g_assert_cmpstr (directory_server, ==, "This is a server"); + g_assert_cmpstr (gender, ==, GDATA_CONTACTS_GENDER_MALE); + g_assert_cmpstr (initials, ==, "A. B. C."); + g_assert_cmpstr (maiden_name, ==, "Smith"); + g_assert_cmpstr (mileage, ==, "12km"); + g_assert_cmpstr (occupation, ==, "Professional bum"); + g_assert_cmpstr (priority, ==, GDATA_CONTACTS_PRIORITY_HIGH); + g_assert_cmpstr (sensitivity, ==, GDATA_CONTACTS_SENSITIVITY_PERSONAL); + g_assert_cmpstr (short_name, ==, "Jon"); + g_assert_cmpstr (subject, ==, "Charity work"); + + g_object_unref (name2); + g_free (date2); + g_free (nickname); + g_free (file_as); + g_free (billing_information); + g_free (directory_server); + g_free (gender); + g_free (initials); + g_free (maiden_name); + g_free (mileage); + g_free (occupation); + g_free (priority); + g_free (sensitivity); + g_free (short_name); + g_free (subject); + g_free (photo_etag); + + /* Check the XML */ + gdata_test_assert_xml (contact, + "" + "" + "John Smith" + "Notes" + "" + "" + "John" + "Smith" + "John Smith" + "" + "" + "" + "" + "(206)555-1212" + "(206)555-1213" + "" + "1600 Amphitheatre Pkwy Mountain View" + "" + "" + "OrgCorp" + "President" + "" + "This is a jot." + "Brian Haddock" + "" + "" + "" + "" + "" + "http://example.com/" + "" + "" + "" + "" /* bgo#648058 */ + "Rowing" + "Big J" + "J, Big" + "" + "Big J Enterprises, Ltd." + "This is a server" + "" + "A. B. C." + "Smith" + "12km" + "Professional bum" + "" + "" + "Jon" + "Charity work" + ""); + + /* Try removing some things from the contact and ensure it works */ + gdata_contacts_contact_remove_all_email_addresses (contact); + g_assert (gdata_contacts_contact_get_email_addresses (contact) == NULL); + g_assert (gdata_contacts_contact_get_primary_email_address (contact) == NULL); + + gdata_contacts_contact_remove_all_im_addresses (contact); + g_assert (gdata_contacts_contact_get_im_addresses (contact) == NULL); + g_assert (gdata_contacts_contact_get_primary_im_address (contact) == NULL); + + gdata_contacts_contact_remove_all_phone_numbers (contact); + g_assert (gdata_contacts_contact_get_phone_numbers (contact) == NULL); + g_assert (gdata_contacts_contact_get_primary_phone_number (contact) == NULL); + + gdata_contacts_contact_remove_all_postal_addresses (contact); + g_assert (gdata_contacts_contact_get_postal_addresses (contact) == NULL); + g_assert (gdata_contacts_contact_get_primary_postal_address (contact) == NULL); + + gdata_contacts_contact_remove_all_organizations (contact); + g_assert (gdata_contacts_contact_get_organizations (contact) == NULL); + g_assert (gdata_contacts_contact_get_primary_organization (contact) == NULL); + + gdata_contacts_contact_remove_all_jots (contact); + g_assert (gdata_contacts_contact_get_jots (contact) == NULL); + + gdata_contacts_contact_remove_all_relations (contact); + g_assert (gdata_contacts_contact_get_relations (contact) == NULL); + + gdata_contacts_contact_remove_all_websites (contact); + g_assert (gdata_contacts_contact_get_websites (contact) == NULL); + g_assert (gdata_contacts_contact_get_primary_website (contact) == NULL); + + gdata_contacts_contact_remove_all_events (contact); + g_assert (gdata_contacts_contact_get_events (contact) == NULL); + + gdata_contacts_contact_remove_all_calendars (contact); + g_assert (gdata_contacts_contact_get_calendars (contact) == NULL); + g_assert (gdata_contacts_contact_get_primary_calendar (contact) == NULL); + + gdata_contacts_contact_remove_all_external_ids (contact); + g_assert (gdata_contacts_contact_get_external_ids (contact) == NULL); + + gdata_contacts_contact_remove_all_languages (contact); + g_assert (gdata_contacts_contact_get_languages (contact) == NULL); + + gdata_contacts_contact_remove_all_hobbies (contact); + g_assert (gdata_contacts_contact_get_hobbies (contact) == NULL); +} + +static void +test_contact_escaping (void) +{ + GDataContactsContact *contact; + + contact = gdata_contacts_contact_new (NULL); + gdata_contacts_contact_set_nickname (contact, "Nickname & stuff"); + gdata_contacts_contact_set_file_as (contact, "Stuff, & Nickname"); + gdata_contacts_contact_set_billing_information (contact, "Billing information & stuff"); + gdata_contacts_contact_set_directory_server (contact, "http://foo.com?foo&bar"); + gdata_contacts_contact_set_gender (contact, "Misc. & other"); + gdata_contacts_contact_set_initials (contact, ""); + gdata_contacts_contact_set_maiden_name (contact, "Maiden & name"); + gdata_contacts_contact_set_mileage (contact, "Over the hills & far away"); + gdata_contacts_contact_set_occupation (contact, "Occupation & stuff"); + gdata_contacts_contact_set_priority (contact, "http://foo.com?foo&priority=bar"); + gdata_contacts_contact_set_sensitivity (contact, "http://foo.com?foo&sensitivity=bar"); + gdata_contacts_contact_set_short_name (contact, "Short name & stuff"); + gdata_contacts_contact_set_subject (contact, "Subject & stuff"); + gdata_contacts_contact_add_hobby (contact, "Escaping &s"); + gdata_contacts_contact_set_extended_property (contact, "extended & prop", "Value should be a pre-escaped XML blob."); + gdata_contacts_contact_set_user_defined_field (contact, "User defined field & stuff", "Value & stuff"); + gdata_contacts_contact_add_group (contact, "http://foo.com?foo&bar"); + + /* Check the outputted XML is escaped properly */ + gdata_test_assert_xml (contact, + "" + "" + "" + "" + "" + "" + "Value should be a pre-escaped XML blob." + "" + "" + "" + "Escaping &s" + "Nickname & stuff" + "Stuff, & Nickname" + "Billing information & stuff" + "http://foo.com?foo&bar" + "" + "<AB>" + "Maiden & name" + "Over the hills & far away" + "Occupation & stuff" + "" + "" + "Short name & stuff" + "Subject & stuff" + ""); + g_object_unref (contact); +} + +static void +test_group_escaping (void) +{ + GDataContactsGroup *group; + + group = gdata_contacts_group_new (NULL); + gdata_contacts_group_set_extended_property (group, "extended & prop", "Value should be a pre-escaped XML blob."); + + /* Check the outputted XML is escaped properly */ + gdata_test_assert_xml (group, + "" + "" + "" + "" + "" + "Value should be a pre-escaped XML blob." + "" + ""); + g_object_unref (group); +} + +static void +test_query_uri (void) +{ + gchar *query_uri; + GDataContactsQuery *query = gdata_contacts_query_new ("q"); + + gdata_contacts_query_set_order_by (query, "lastmodified"); + g_assert_cmpstr (gdata_contacts_query_get_order_by (query), ==, "lastmodified"); + + gdata_contacts_query_set_show_deleted (query, FALSE); + g_assert (gdata_contacts_query_show_deleted (query) == FALSE); + + /* Test it with both values of show-deleted */ + query_uri = gdata_query_get_query_uri (GDATA_QUERY (query), "http://example.com"); + g_assert_cmpstr (query_uri, ==, "http://example.com?q=q&orderby=lastmodified&showdeleted=false"); + g_free (query_uri); + + gdata_contacts_query_set_show_deleted (query, TRUE); + g_assert (gdata_contacts_query_show_deleted (query) == TRUE); + + gdata_contacts_query_set_sort_order (query, "descending"); + g_assert_cmpstr (gdata_contacts_query_get_sort_order (query), ==, "descending"); + + gdata_contacts_query_set_group (query, "http://www.google.com/feeds/contacts/groups/jo@gmail.com/base/1234a"); + g_assert_cmpstr (gdata_contacts_query_get_group (query), ==, "http://www.google.com/feeds/contacts/groups/jo@gmail.com/base/1234a"); + + /* Check the built query URI with a normal feed URI */ + query_uri = gdata_query_get_query_uri (GDATA_QUERY (query), "http://example.com"); + g_assert_cmpstr (query_uri, ==, "http://example.com?q=q&orderby=lastmodified&showdeleted=true&sortorder=descending" + "&group=http%3A%2F%2Fwww.google.com%2Ffeeds%2Fcontacts%2Fgroups%2Fjo%40gmail.com%2Fbase%2F1234a"); + g_free (query_uri); + + /* …with a feed URI with a trailing slash */ + query_uri = gdata_query_get_query_uri (GDATA_QUERY (query), "http://example.com/"); + g_assert_cmpstr (query_uri, ==, "http://example.com/?q=q&orderby=lastmodified&showdeleted=true&sortorder=descending" + "&group=http%3A%2F%2Fwww.google.com%2Ffeeds%2Fcontacts%2Fgroups%2Fjo%40gmail.com%2Fbase%2F1234a"); + g_free (query_uri); + + /* …with a feed URI with pre-existing arguments */ + query_uri = gdata_query_get_query_uri (GDATA_QUERY (query), "http://example.com/bar/?test=test&this=that"); + g_assert_cmpstr (query_uri, ==, "http://example.com/bar/?test=test&this=that&q=q&orderby=lastmodified&showdeleted=true&sortorder=descending" + "&group=http%3A%2F%2Fwww.google.com%2Ffeeds%2Fcontacts%2Fgroups%2Fjo%40gmail.com%2Fbase%2F1234a"); + g_free (query_uri); + + g_object_unref (query); +} + +static void +test_query_etag (void) +{ + GDataContactsQuery *query = gdata_contacts_query_new (NULL); + + /* Test that setting any property will unset the ETag */ + g_test_bug ("613529"); + +#define CHECK_ETAG(C) \ + gdata_query_set_etag (GDATA_QUERY (query), "foobar"); \ + (C); \ + g_assert (gdata_query_get_etag (GDATA_QUERY (query)) == NULL); + + CHECK_ETAG (gdata_contacts_query_set_order_by (query, "foobar")) + CHECK_ETAG (gdata_contacts_query_set_show_deleted (query, FALSE)) + CHECK_ETAG (gdata_contacts_query_set_sort_order (query, "shizzle")) + CHECK_ETAG (gdata_contacts_query_set_group (query, "support group")) + +#undef CHECK_ETAG + + g_object_unref (query); +} + +static void +test_query_properties (void) +{ + gchar *order_by, *sort_order, *group; + gboolean show_deleted; + guint start_index, max_results; + GDataContactsQuery *query = gdata_contacts_query_new_with_limits ("q", 1, 10); + + /* Set the properties */ + g_object_set (G_OBJECT (query), + "order-by", "lastmodified", + "show-deleted", TRUE, + "sort-order", "descending", + "group", "http://www.google.com/feeds/contacts/groups/jo@gmail.com/base/1234a", + NULL); + + /* Check the query's properties */ + g_object_get (G_OBJECT (query), + "order-by", &order_by, + "show-deleted", &show_deleted, + "sort-order", &sort_order, + "group", &group, + "start-index", &start_index, + "max-results", &max_results, + NULL); + + g_assert_cmpstr (order_by, ==, "lastmodified"); + g_assert (show_deleted == TRUE); + g_assert_cmpstr (sort_order, ==, "descending"); + g_assert_cmpstr (group, ==, "http://www.google.com/feeds/contacts/groups/jo@gmail.com/base/1234a"); + g_assert_cmpuint (start_index, ==, 1); + g_assert_cmpuint (max_results, ==, 10); + + g_free (order_by); + g_free (sort_order); + g_free (group); + + g_object_unref (query); +} + +static void +test_contact_parser_minimal (void) +{ + GDataContactsContact *contact; + GDate birthday; + GError *error = NULL; + + g_test_bug ("580330"); + + contact = GDATA_CONTACTS_CONTACT (gdata_parsable_new_from_xml (GDATA_TYPE_CONTACTS_CONTACT, + "" + "http://www.google.com/m8/feeds/contacts/libgdata.test@googlemail.com/base/1b46cdd20bfbee3b" + "2009-04-25T15:21:53.688Z" + "2009-04-25T15:21:53.688Z" + "" + "" /* Here's where it all went wrong */ + "" + "" + "" + "" + "", -1, &error)); + g_assert_no_error (error); + g_assert (GDATA_IS_CONTACTS_CONTACT (contact)); + gdata_test_compare_kind (GDATA_ENTRY (contact), "http://schemas.google.com/contact/2008#contact", NULL); + g_clear_error (&error); + + /* Check the contact's properties */ + g_assert (gdata_entry_get_title (GDATA_ENTRY (contact)) != NULL); + g_assert (*gdata_entry_get_title (GDATA_ENTRY (contact)) == '\0'); + + /* TODO: Check the other properties */ + + g_assert (gdata_contacts_contact_get_nickname (contact) == NULL); + g_assert (gdata_contacts_contact_get_file_as (contact) == NULL); + g_assert (gdata_contacts_contact_get_birthday (contact, &birthday) == FALSE); + g_assert (g_date_valid (&birthday) == FALSE); + g_assert (gdata_contacts_contact_get_billing_information (contact) == NULL); + g_assert (gdata_contacts_contact_get_directory_server (contact) == NULL); + g_assert (gdata_contacts_contact_get_gender (contact) == NULL); + g_assert (gdata_contacts_contact_get_initials (contact) == NULL); + g_assert (gdata_contacts_contact_get_maiden_name (contact) == NULL); + g_assert (gdata_contacts_contact_get_mileage (contact) == NULL); + g_assert (gdata_contacts_contact_get_occupation (contact) == NULL); + g_assert (gdata_contacts_contact_get_priority (contact) == NULL); + g_assert (gdata_contacts_contact_get_sensitivity (contact) == NULL); + g_assert (gdata_contacts_contact_get_short_name (contact) == NULL); + g_assert (gdata_contacts_contact_get_subject (contact) == NULL); + g_assert (gdata_contacts_contact_get_jots (contact) == NULL); + g_assert (gdata_contacts_contact_get_relations (contact) == NULL); + g_assert (gdata_contacts_contact_get_websites (contact) == NULL); + g_assert (gdata_contacts_contact_get_primary_website (contact) == NULL); + g_assert (gdata_contacts_contact_get_events (contact) == NULL); + g_assert (gdata_contacts_contact_get_calendars (contact) == NULL); + g_assert (gdata_contacts_contact_get_primary_calendar (contact) == NULL); + g_assert (gdata_contacts_contact_get_external_ids (contact) == NULL); + g_assert (gdata_contacts_contact_get_languages (contact) == NULL); + g_assert (gdata_contacts_contact_get_hobbies (contact) == NULL); + + g_object_unref (contact); +} + +static void +test_contact_parser_normal (void) +{ + GDataContactsContact *contact; + GDate date; + GList *list; + GError *error = NULL; + + contact = GDATA_CONTACTS_CONTACT (gdata_parsable_new_from_xml (GDATA_TYPE_CONTACTS_CONTACT, + "" + "http://www.google.com/m8/feeds/contacts/libgdata.test@googlemail.com/base/1b46cdd20bfbee3b" + "2009-04-25T15:21:53.688Z" + "2009-04-25T15:21:53.688Z" + "" + "" /* Here's where it all went wrong */ + "" + "" + "" + "" + "" /* https://bugzilla.gnome.org/show_bug.cgi?id=734863 */ + "" + "" + "" + "" + "" + "Agent Smith" + "Smith, Agent" + "" + "Foo & Bar Inc." + "Directory & server" + "" + "X. Y. Z." + "Foo" + "15km" + "Occupied" + "" + "" + "Smith" + "Film buddy" + "Moved house on 2010-02-14 to the North Pole." + "Owes me ten pounds." + "" /* Empty on purpose */ + "Darth Vader" + "Rob Halford" + "" + "" + "" + "" /* empty on purpose; see bgo#790671 */ + "" + "" + "" + "" + "" + "" + "" + "" + "" + "Programming" + "Heavy metal" + "Heavy metal" /* Test that duplicates get merged */ + "", -1, &error)); + g_assert_no_error (error); + g_assert (GDATA_IS_CONTACTS_CONTACT (contact)); + gdata_test_compare_kind (GDATA_ENTRY (contact), "http://schemas.google.com/contact/2008#contact", NULL); + g_clear_error (&error); + + /* TODO: Check the other properties */ + + g_assert_cmpstr (gdata_contacts_contact_get_nickname (contact), ==, "Agent Smith"); + g_assert_cmpstr (gdata_contacts_contact_get_file_as (contact), ==, "Smith, Agent"); + g_assert_cmpstr (gdata_contacts_contact_get_billing_information (contact), ==, "Foo & Bar Inc."); + g_assert_cmpstr (gdata_contacts_contact_get_directory_server (contact), ==, "Directory & server"); + g_assert_cmpstr (gdata_contacts_contact_get_gender (contact), ==, GDATA_CONTACTS_GENDER_FEMALE); + g_assert_cmpstr (gdata_contacts_contact_get_initials (contact), ==, "X. Y. Z."); + g_assert_cmpstr (gdata_contacts_contact_get_maiden_name (contact), ==, "Foo"); + g_assert_cmpstr (gdata_contacts_contact_get_mileage (contact), ==, "15km"); + g_assert_cmpstr (gdata_contacts_contact_get_occupation (contact), ==, "Occupied"); + g_assert_cmpstr (gdata_contacts_contact_get_priority (contact), ==, GDATA_CONTACTS_PRIORITY_LOW); + g_assert_cmpstr (gdata_contacts_contact_get_sensitivity (contact), ==, GDATA_CONTACTS_SENSITIVITY_CONFIDENTIAL); + g_assert_cmpstr (gdata_contacts_contact_get_short_name (contact), ==, "Smith"); + g_assert_cmpstr (gdata_contacts_contact_get_subject (contact), ==, "Film buddy"); + + /* Birthday */ + g_assert (gdata_contacts_contact_get_birthday (contact, &date) == TRUE); + g_assert (g_date_valid (&date) == TRUE); + g_assert_cmpuint (g_date_get_year (&date), ==, 2010); + g_assert_cmpuint (g_date_get_month (&date), ==, 12); + g_assert_cmpuint (g_date_get_day (&date), ==, 3); + + /* Jots */ + list = gdata_contacts_contact_get_jots (contact); + g_assert_cmpuint (g_list_length (list), ==, 3); + + g_assert (GDATA_IS_GCONTACT_JOT (list->data)); + g_assert_cmpstr (gdata_gcontact_jot_get_content (GDATA_GCONTACT_JOT (list->data)), ==, "Moved house on 2010-02-14 to the North Pole."); + g_assert_cmpstr (gdata_gcontact_jot_get_relation_type (GDATA_GCONTACT_JOT (list->data)), ==, GDATA_GCONTACT_JOT_HOME); + + list = list->next; + g_assert (GDATA_IS_GCONTACT_JOT (list->data)); + g_assert_cmpstr (gdata_gcontact_jot_get_content (GDATA_GCONTACT_JOT (list->data)), ==, "Owes me ten pounds."); + g_assert_cmpstr (gdata_gcontact_jot_get_relation_type (GDATA_GCONTACT_JOT (list->data)), ==, GDATA_GCONTACT_JOT_USER); + + list = list->next; + g_assert (GDATA_IS_GCONTACT_JOT (list->data)); + g_assert (gdata_gcontact_jot_get_content (GDATA_GCONTACT_JOT (list->data)) == NULL); + g_assert_cmpstr (gdata_gcontact_jot_get_relation_type (GDATA_GCONTACT_JOT (list->data)), ==, GDATA_GCONTACT_JOT_OTHER); + + /* Relations */ + list = gdata_contacts_contact_get_relations (contact); + g_assert_cmpuint (g_list_length (list), ==, 2); + + g_assert (GDATA_IS_GCONTACT_RELATION (list->data)); + g_assert_cmpstr (gdata_gcontact_relation_get_name (GDATA_GCONTACT_RELATION (list->data)), ==, "Darth Vader"); + g_assert_cmpstr (gdata_gcontact_relation_get_relation_type (GDATA_GCONTACT_RELATION (list->data)), ==, GDATA_GCONTACT_RELATION_FATHER); + g_assert (gdata_gcontact_relation_get_label (GDATA_GCONTACT_RELATION (list->data)) == NULL); + + list = list->next; + g_assert (GDATA_IS_GCONTACT_RELATION (list->data)); + g_assert_cmpstr (gdata_gcontact_relation_get_name (GDATA_GCONTACT_RELATION (list->data)), ==, "Rob Halford"); + g_assert (gdata_gcontact_relation_get_relation_type (GDATA_GCONTACT_RELATION (list->data)) == NULL); + g_assert_cmpstr (gdata_gcontact_relation_get_label (GDATA_GCONTACT_RELATION (list->data)), ==, "Favourite singer"); + + /* Websites */ + list = gdata_contacts_contact_get_websites (contact); + g_assert_cmpuint (g_list_length (list), ==, 3); + /* Note the empty website should *not* be present. See bgo#790671. */ + + g_assert (GDATA_IS_GCONTACT_WEBSITE (list->data)); + g_assert_cmpstr (gdata_gcontact_website_get_uri (GDATA_GCONTACT_WEBSITE (list->data)), ==, "http://example.com"); + g_assert_cmpstr (gdata_gcontact_website_get_relation_type (GDATA_GCONTACT_WEBSITE (list->data)), ==, GDATA_GCONTACT_WEBSITE_HOME_PAGE); + g_assert_cmpstr (gdata_gcontact_website_get_label (GDATA_GCONTACT_WEBSITE (list->data)), ==, "Home tab #1"); + g_assert (gdata_gcontact_website_is_primary (GDATA_GCONTACT_WEBSITE (list->data)) == TRUE); + + g_assert (gdata_contacts_contact_get_primary_website (contact) == list->data); + + list = list->next; + g_assert (GDATA_IS_GCONTACT_WEBSITE (list->data)); + g_assert_cmpstr (gdata_gcontact_website_get_uri (GDATA_GCONTACT_WEBSITE (list->data)), ==, "http://example.com"); + g_assert_cmpstr (gdata_gcontact_website_get_relation_type (GDATA_GCONTACT_WEBSITE (list->data)), ==, GDATA_GCONTACT_WEBSITE_WORK); + g_assert (gdata_gcontact_website_get_label (GDATA_GCONTACT_WEBSITE (list->data)) == NULL); + g_assert (gdata_gcontact_website_is_primary (GDATA_GCONTACT_WEBSITE (list->data)) == FALSE); + + list = list->next; + g_assert (GDATA_IS_GCONTACT_WEBSITE (list->data)); + g_assert_cmpstr (gdata_gcontact_website_get_uri (GDATA_GCONTACT_WEBSITE (list->data)), ==, "http://bar.com"); + g_assert_cmpstr (gdata_gcontact_website_get_relation_type (GDATA_GCONTACT_WEBSITE (list->data)), ==, GDATA_GCONTACT_WEBSITE_PROFILE); + g_assert (gdata_gcontact_website_get_label (GDATA_GCONTACT_WEBSITE (list->data)) == NULL); + g_assert (gdata_gcontact_website_is_primary (GDATA_GCONTACT_WEBSITE (list->data)) == FALSE); + + /* Events */ + list = gdata_contacts_contact_get_events (contact); + g_assert_cmpuint (g_list_length (list), ==, 2); + + g_assert (GDATA_IS_GCONTACT_EVENT (list->data)); + gdata_gcontact_event_get_date (GDATA_GCONTACT_EVENT (list->data), &date); + g_assert (g_date_valid (&date) == TRUE); + g_assert_cmpuint (g_date_get_year (&date), ==, 2010); + g_assert_cmpuint (g_date_get_month (&date), ==, 3); + g_assert_cmpuint (g_date_get_day (&date), ==, 4); + g_assert_cmpstr (gdata_gcontact_event_get_relation_type (GDATA_GCONTACT_EVENT (list->data)), ==, GDATA_GCONTACT_EVENT_ANNIVERSARY); + g_assert (gdata_gcontact_event_get_label (GDATA_GCONTACT_EVENT (list->data)) == NULL); + + list = list->next; + g_assert (GDATA_IS_GCONTACT_EVENT (list->data)); + gdata_gcontact_event_get_date (GDATA_GCONTACT_EVENT (list->data), &date); + g_assert (g_date_valid (&date) == TRUE); + g_assert_cmpuint (g_date_get_year (&date), ==, 1900); + g_assert_cmpuint (g_date_get_month (&date), ==, 1); + g_assert_cmpuint (g_date_get_day (&date), ==, 1); + g_assert (gdata_gcontact_event_get_relation_type (GDATA_GCONTACT_EVENT (list->data)) == NULL); + g_assert_cmpstr (gdata_gcontact_event_get_label (GDATA_GCONTACT_EVENT (list->data)), ==, "Foobar"); + + /* Calendars */ + list = gdata_contacts_contact_get_calendars (contact); + g_assert_cmpuint (g_list_length (list), ==, 3); + + g_assert (GDATA_IS_GCONTACT_CALENDAR (list->data)); + g_assert_cmpstr (gdata_gcontact_calendar_get_uri (GDATA_GCONTACT_CALENDAR (list->data)), ==, "http://example.com/"); + g_assert_cmpstr (gdata_gcontact_calendar_get_relation_type (GDATA_GCONTACT_CALENDAR (list->data)), ==, GDATA_GCONTACT_CALENDAR_FREE_BUSY); + g_assert (gdata_gcontact_calendar_get_label (GDATA_GCONTACT_CALENDAR (list->data)) == NULL); + g_assert (gdata_gcontact_calendar_is_primary (GDATA_GCONTACT_CALENDAR (list->data)) == TRUE); + + g_assert (gdata_contacts_contact_get_primary_calendar (contact) == list->data); + + list = list->next; + g_assert (GDATA_IS_GCONTACT_CALENDAR (list->data)); + g_assert_cmpstr (gdata_gcontact_calendar_get_uri (GDATA_GCONTACT_CALENDAR (list->data)), ==, "http://example.com/"); + g_assert (gdata_gcontact_calendar_get_relation_type (GDATA_GCONTACT_CALENDAR (list->data)) == NULL); + g_assert_cmpstr (gdata_gcontact_calendar_get_label (GDATA_GCONTACT_CALENDAR (list->data)), ==, "Gig list"); + g_assert (gdata_gcontact_calendar_is_primary (GDATA_GCONTACT_CALENDAR (list->data)) == FALSE); + + list = list->next; + g_assert (GDATA_IS_GCONTACT_CALENDAR (list->data)); + g_assert_cmpstr (gdata_gcontact_calendar_get_uri (GDATA_GCONTACT_CALENDAR (list->data)), ==, "http://foo.com/calendar"); + g_assert_cmpstr (gdata_gcontact_calendar_get_relation_type (GDATA_GCONTACT_CALENDAR (list->data)), ==, GDATA_GCONTACT_CALENDAR_HOME); + g_assert (gdata_gcontact_calendar_get_label (GDATA_GCONTACT_CALENDAR (list->data)) == NULL); + g_assert (gdata_gcontact_calendar_is_primary (GDATA_GCONTACT_CALENDAR (list->data)) == FALSE); + + /* External IDs */ + list = gdata_contacts_contact_get_external_ids (contact); + g_assert_cmpuint (g_list_length (list), ==, 2); + + g_assert (GDATA_IS_GCONTACT_EXTERNAL_ID (list->data)); + g_assert (GDATA_IS_GCONTACT_EXTERNAL_ID (list->next->data)); + + /* Languages */ + list = gdata_contacts_contact_get_languages (contact); + g_assert_cmpuint (g_list_length (list), ==, 2); + + g_assert (GDATA_IS_GCONTACT_LANGUAGE (list->data)); + g_assert (GDATA_IS_GCONTACT_LANGUAGE (list->next->data)); + + /* Hobbies */ + list = gdata_contacts_contact_get_hobbies (contact); + g_assert_cmpuint (g_list_length (list), ==, 2); + + g_assert_cmpstr (list->data, ==, "Programming"); + g_assert_cmpstr (list->next->data, ==, "Heavy metal"); + + g_object_unref (contact); +} + +static void +test_contact_parser_error_handling (void) +{ + GDataContactsContact *contact; + GError *error = NULL; + +#define TEST_XML_ERROR_HANDLING(x) \ + contact = GDATA_CONTACTS_CONTACT (gdata_parsable_new_from_xml (GDATA_TYPE_CONTACTS_CONTACT,\ + ""\ + x\ + "", -1, &error));\ + g_assert_error (error, GDATA_SERVICE_ERROR, GDATA_SERVICE_ERROR_PROTOCOL_ERROR);\ + g_assert (contact == NULL);\ + g_clear_error (&error) + + /* app:edited */ + TEST_XML_ERROR_HANDLING ("this shouldn't parse"); + + /* gd:name */ + TEST_XML_ERROR_HANDLING ("SpartacusSpartacus"); + + /* gd:email */ + TEST_XML_ERROR_HANDLING ("neither should this"); + + /* gd:im */ + TEST_XML_ERROR_HANDLING ("nor this"); + + /* gd:phoneNumber */ + TEST_XML_ERROR_HANDLING (""); + + /* gd:structuredPostalAddress */ + TEST_XML_ERROR_HANDLING (""); + + /* gd:organization */ + TEST_XML_ERROR_HANDLING (""); + + /* gd:extendedProperty */ + TEST_XML_ERROR_HANDLING (""); + + /* gContact:userDefinedField */ + TEST_XML_ERROR_HANDLING (""); /* no key or value */ + TEST_XML_ERROR_HANDLING (""); /* no value */ + TEST_XML_ERROR_HANDLING (""); /* no key */ + + /* gContact:groupMembershipInfo */ + TEST_XML_ERROR_HANDLING (""); + TEST_XML_ERROR_HANDLING (""); + + /* gContact:nickname */ + TEST_XML_ERROR_HANDLING (""); /* missing content */ + TEST_XML_ERROR_HANDLING ("Nickname 1Duplicate!"); /* duplicate */ + + /* gContact:fileAs */ + TEST_XML_ERROR_HANDLING (""); /* missing content */ + TEST_XML_ERROR_HANDLING ("File As 1Duplicate!"); /* duplicate */ + + /* gContact:birthday */ + TEST_XML_ERROR_HANDLING (""); /* missing "when" attribute */ + TEST_XML_ERROR_HANDLING (""); /* invalid date */ + TEST_XML_ERROR_HANDLING (""); /* duplicate */ + + /* gContact:billingInformation */ + TEST_XML_ERROR_HANDLING (""); /* missing content */ + TEST_XML_ERROR_HANDLING ("foo" + "Dupe!"); /* duplicate */ + + /* gContact:directoryServer */ + TEST_XML_ERROR_HANDLING (""); /* missing content */ + TEST_XML_ERROR_HANDLING ("foo" + "Dupe!"); /* duplicate */ + + /* gContact:gender */ + TEST_XML_ERROR_HANDLING (""); /* missing content */ + TEST_XML_ERROR_HANDLING (""); /* duplicate */ + + /* gContact:initials */ + TEST_XML_ERROR_HANDLING (""); /* missing content */ + TEST_XML_ERROR_HANDLING ("AB"); /* duplicate */ + + /* gContact:maidenName */ + TEST_XML_ERROR_HANDLING (""); /* missing content */ + TEST_XML_ERROR_HANDLING ("AB"); /* duplicate */ + + /* gContact:mileage */ + TEST_XML_ERROR_HANDLING (""); /* missing content */ + TEST_XML_ERROR_HANDLING ("12 mi12 mi"); /* duplicate */ + + /* gContact:occupation */ + TEST_XML_ERROR_HANDLING (""); /* missing content */ + TEST_XML_ERROR_HANDLING ("FooBar"); /* duplicate */ + + /* gContact:priority */ + TEST_XML_ERROR_HANDLING (""); /* missing rel param */ + TEST_XML_ERROR_HANDLING (""); /* empty rel param */ + TEST_XML_ERROR_HANDLING (""); /* duplicate */ + + /* gContact:sensitivity */ + TEST_XML_ERROR_HANDLING (""); /* missing rel param */ + TEST_XML_ERROR_HANDLING (""); /* empty rel param */ + TEST_XML_ERROR_HANDLING (""); /* duplicate */ + + /* gContact:shortName */ + TEST_XML_ERROR_HANDLING (""); /* missing content */ + TEST_XML_ERROR_HANDLING ("FooBar"); /* duplicate */ + + /* gContact:subject */ + TEST_XML_ERROR_HANDLING (""); /* missing content */ + TEST_XML_ERROR_HANDLING ("FooBar"); /* duplicate */ + + /* gContact:jot */ + TEST_XML_ERROR_HANDLING (""); + + /* gContact:relation */ + TEST_XML_ERROR_HANDLING (""); + + /* gContact:website errors are ignored (see bgo#790671) */ + + /* gContact:event */ + TEST_XML_ERROR_HANDLING (""); + + /* gContact:calendar */ + TEST_XML_ERROR_HANDLING (""); + + /* gContact:externalId */ + TEST_XML_ERROR_HANDLING (""); + + /* gContact:language */ + TEST_XML_ERROR_HANDLING (""); + + /* gContact:hobby */ + TEST_XML_ERROR_HANDLING (""); + +#undef TEST_XML_ERROR_HANDLING +} + +static void +test_group_properties (void) +{ + GDataContactsGroup *group; + GTimeVal time_val; + GHashTable *properties; + gint64 edited; + gboolean deleted; + gchar *system_group_id; + + group = gdata_contacts_group_new (NULL); + + /* Check the kind is present and correct */ + g_assert (GDATA_IS_CONTACTS_GROUP (group)); + gdata_test_compare_kind (GDATA_ENTRY (group), "http://schemas.google.com/contact/2008#group", NULL); + + /* Set various properties */ + gdata_entry_set_title (GDATA_ENTRY (group), "New Group!"); + g_assert (gdata_contacts_group_set_extended_property (group, "foobar", "barfoo") == TRUE); + + /* Check various properties */ + g_get_current_time (&time_val); + g_assert_cmpint (gdata_contacts_group_get_edited (group), ==, time_val.tv_sec); + g_assert (gdata_contacts_group_is_deleted (group) == FALSE); + g_assert (gdata_contacts_group_get_system_group_id (group) == NULL); + + properties = gdata_contacts_group_get_extended_properties (group); + g_assert (properties != NULL); + g_assert_cmpint (g_hash_table_size (properties), ==, 1); + g_assert_cmpstr (gdata_contacts_group_get_extended_property (group, "foobar"), ==, "barfoo"); + + /* Check the properties a different way */ + g_object_get (G_OBJECT (group), + "edited", &edited, + "deleted", &deleted, + "system-group-id", &system_group_id, + NULL); + + g_assert_cmpint (edited, ==, time_val.tv_sec); + g_assert (deleted == FALSE); + g_assert (system_group_id == NULL); + + g_free (system_group_id); + + /* Check the XML */ + gdata_test_assert_xml (group, + "" + "" + "New Group!" + "New Group!" + "" + "barfoo" + ""); + + g_object_unref (group); +} + +static void +test_group_parser_normal (void) +{ + GDataContactsGroup *group; + GHashTable *properties; + GError *error = NULL; + + group = GDATA_CONTACTS_GROUP (gdata_parsable_new_from_xml (GDATA_TYPE_CONTACTS_GROUP, + "" + "" + "http://www.google.com/feeds/groups/jo%40gmail.com/base/1234" + "2005-01-18T21:00:00Z" + "2006-01-01T00:00:00Z" + "2006-01-01T00:00:00Z" + "Salsa class members" + "" + "" + "" + "Some text." + "" + "Foobar." + "" + "" + "", -1, &error)); + g_assert_no_error (error); + g_assert (GDATA_IS_CONTACTS_GROUP (group)); + gdata_test_compare_kind (GDATA_ENTRY (group), "http://schemas.google.com/contact/2008#group", NULL); + g_clear_error (&error); + + g_assert_cmpint (gdata_contacts_group_get_edited (group), ==, 1136073600); + g_assert (gdata_contacts_group_is_deleted (group) == TRUE); + g_assert (gdata_contacts_group_get_system_group_id (group) == NULL); + + g_assert_cmpstr (gdata_contacts_group_get_extended_property (group, "more info"), ==, "Some text."); + g_assert_cmpstr (gdata_contacts_group_get_extended_property (group, "extra info"), ==, "Foobar."); + + properties = gdata_contacts_group_get_extended_properties (group); + g_assert_cmpint (g_hash_table_size (properties), ==, 2); + + g_object_unref (group); +} + +static void +test_group_parser_system (void) +{ + GDataContactsGroup *group; + GError *error = NULL; + + group = GDATA_CONTACTS_GROUP (gdata_parsable_new_from_xml (GDATA_TYPE_CONTACTS_GROUP, + "" + "" + "http://www.google.com/feeds/groups/jo%40gmail.com/base/1234" + "2005-01-18T21:00:00Z" + "2006-01-01T00:00:00Z" + "2006-01-01T00:00:00Z" + "Salsa class members" + "" + "" + "" + "" + "", -1, &error)); + g_assert_no_error (error); + g_assert (GDATA_IS_CONTACTS_GROUP (group)); + gdata_test_compare_kind (GDATA_ENTRY (group), "http://schemas.google.com/contact/2008#group", NULL); + g_clear_error (&error); + + g_assert_cmpint (gdata_contacts_group_get_edited (group), ==, 1136073600); + g_assert (gdata_contacts_group_is_deleted (group) == FALSE); + g_assert_cmpstr (gdata_contacts_group_get_system_group_id (group), ==, GDATA_CONTACTS_GROUP_CONTACTS); + + g_object_unref (group); +} + +static void +test_group_parser_error_handling (void) +{ + GDataContactsGroup *group; + GError *error = NULL; + +#define TEST_XML_ERROR_HANDLING(x) \ + group = GDATA_CONTACTS_GROUP (gdata_parsable_new_from_xml (GDATA_TYPE_CONTACTS_GROUP,\ + ""\ + x\ + "", -1, &error));\ + g_assert_error (error, GDATA_SERVICE_ERROR, GDATA_SERVICE_ERROR_PROTOCOL_ERROR);\ + g_assert (group == NULL);\ + g_clear_error (&error) + + /* app:edited */ + TEST_XML_ERROR_HANDLING ("this shouldn't parse"); + + /* gd:deleted */ + TEST_XML_ERROR_HANDLING (""); + + /* gd:extendedProperty */ + TEST_XML_ERROR_HANDLING (""); + + /* gContact:systemGroup */ + TEST_XML_ERROR_HANDLING (""); + TEST_XML_ERROR_HANDLING (""); + +#undef TEST_XML_ERROR_HANDLING +} + +static void +test_photo_has_photo (gconstpointer service) +{ + GDataContactsContact *contact; + gsize length = 0; + gchar *content_type = NULL; + GError *error = NULL; + + contact = GDATA_CONTACTS_CONTACT (gdata_parsable_new_from_xml (GDATA_TYPE_CONTACTS_CONTACT, + "" + "http://www.google.com/m8/feeds/contacts/libgdata.test@googlemail.com/base/1b46cdd20bfbee3b" + "2009-04-25T15:21:53.688Z" + "" + "" /* Here's where it all went wrong */ + "" + "", -1, &error)); + g_assert_no_error (error); + g_assert (GDATA_IS_CONTACTS_CONTACT (contact)); + gdata_test_compare_kind (GDATA_ENTRY (contact), "http://schemas.google.com/contact/2008#contact", NULL); + g_clear_error (&error); + + /* Check for no photo */ + g_assert (gdata_contacts_contact_get_photo_etag (contact) == NULL); + g_assert (gdata_contacts_contact_get_photo (contact, GDATA_CONTACTS_SERVICE (service), &length, &content_type, NULL, &error) == NULL); + g_assert_cmpint (length, ==, 0); + g_assert (content_type == NULL); + g_assert_no_error (error); + + g_clear_error (&error); + g_free (content_type); + g_object_unref (contact); + + /* Try again with a photo */ + contact = GDATA_CONTACTS_CONTACT (gdata_parsable_new_from_xml (GDATA_TYPE_CONTACTS_CONTACT, + "" + "http://www.google.com/m8/feeds/contacts/libgdata.test@googlemail.com/base/1b46cdd20bfbee3b" + "2009-04-25T15:21:53.688Z" + "" + "" /* Here's where it all went wrong */ + "" + "", -1, &error)); + g_assert_no_error (error); + g_assert (GDATA_IS_CONTACTS_CONTACT (contact)); + gdata_test_compare_kind (GDATA_ENTRY (contact), "http://schemas.google.com/contact/2008#contact", NULL); + g_clear_error (&error); + + g_assert (gdata_contacts_contact_get_photo_etag (contact) != NULL); + g_object_unref (contact); +} + +static void +test_photo_add (TempContactData *data, gconstpointer service) +{ + guint8 *photo_data; + gsize length; + gboolean retval; + gchar *path = NULL; + GError *error = NULL; + + gdata_test_mock_server_start_trace (mock_server, "photo-add"); + + /* Get the photo */ + path = g_test_build_filename (G_TEST_DIST, "photo.jpg", NULL); + g_assert (g_file_get_contents (path, (gchar**) &photo_data, &length, NULL) == TRUE); + g_free (path); + + /* Add it to the contact */ + retval = gdata_contacts_contact_set_photo (data->contact, GDATA_CONTACTS_SERVICE (service), photo_data, length, "image/jpeg", NULL, &error); + g_assert_no_error (error); + g_assert (retval == TRUE); + + g_clear_error (&error); + g_free (photo_data); + + uhm_server_end_trace (mock_server); +} + +GDATA_ASYNC_TEST_FUNCTIONS (photo_add, TempContactData, +G_STMT_START { + guint8 *photo_data; + gsize length; + gchar *path = NULL; + + /* Get the photo */ + path = g_test_build_filename (G_TEST_DIST, "photo.jpg", NULL); + g_assert (g_file_get_contents (path, (gchar**) &photo_data, &length, NULL) == TRUE); + g_free (path); + + /* Add it to the contact asynchronously */ + gdata_contacts_contact_set_photo_async (data->contact, GDATA_CONTACTS_SERVICE (service), photo_data, length, "image/jpeg", cancellable, + async_ready_callback, async_data); + + g_free (photo_data); +} G_STMT_END, +G_STMT_START { + GDataContactsContact *contact = GDATA_CONTACTS_CONTACT (obj); + gboolean success; + + success = gdata_contacts_contact_set_photo_finish (contact, async_result, &error); + + if (error == NULL) { + g_assert (success == TRUE); + g_assert (gdata_contacts_contact_get_photo_etag (contact) != NULL); + } else { + g_assert (success == FALSE); + /*g_assert (gdata_contacts_contact_get_photo_etag (contact) == NULL);*/ + + /* Bail out on a conflict error, since it means the addition went through + * (but not fast enough for libgdata to return success rather than cancellation). */ + if (g_error_matches (error, GDATA_SERVICE_ERROR, GDATA_SERVICE_ERROR_CONFLICT) == TRUE) { + g_clear_error (&error); + async_data->cancellation_successful = FALSE; + } + } +} G_STMT_END); + +static void +add_photo_to_contact (GDataContactsService *service, GDataContactsContact **contact) +{ + guint8 *photo_data; + gsize length; + GDataEntry *updated_contact; + gchar *path = NULL; + + /* Get the photo and add it to the contact */ + path = g_test_build_filename (G_TEST_DIST, "photo.jpg", NULL); + g_assert (g_file_get_contents (path, (gchar**) &photo_data, &length, NULL) == TRUE); + g_assert (gdata_contacts_contact_set_photo (*contact, service, photo_data, length, "image/jpeg", NULL, NULL) == TRUE); + + g_free (path); + g_free (photo_data); + + /* HACK: It fairly consistently seems to take the Google servers about 4 seconds to process uploaded photos. Before this + * time, a query for the photo will return an error. So let's wait for 10. + * Helps: bgo#679072 */ + if (uhm_server_get_enable_online (mock_server) == TRUE) { + sleep (10); + } + + /* Re-query for the contact to get any updated ETags. */ + updated_contact = gdata_service_query_single_entry (GDATA_SERVICE (service), gdata_contacts_service_get_primary_authorization_domain (), + gdata_entry_get_id (GDATA_ENTRY (*contact)), NULL, GDATA_TYPE_CONTACTS_CONTACT, + NULL, NULL); + g_assert (GDATA_IS_CONTACTS_CONTACT (updated_contact)); + + g_object_unref (*contact); + *contact = GDATA_CONTACTS_CONTACT (updated_contact); +} + +typedef TempContactData TempContactWithPhotoData; + +static void +set_up_temp_contact_with_photo (TempContactWithPhotoData *data, gconstpointer service) +{ + set_up_temp_contact ((TempContactData*) data, service); + + gdata_test_mock_server_start_trace (mock_server, "setup-temp-contact-with-photo"); + add_photo_to_contact (GDATA_CONTACTS_SERVICE (service), &data->contact); + uhm_server_end_trace (mock_server); +} + +static void +tear_down_temp_contact_with_photo (TempContactWithPhotoData *data, gconstpointer service) +{ + tear_down_temp_contact ((TempContactData*) data, service); +} + +GDATA_ASYNC_CLOSURE_FUNCTIONS (temp_contact_with_photo, TempContactWithPhotoData); + +static void +test_photo_get (TempContactData *data, gconstpointer service) +{ + guint8 *photo_data; + gchar *content_type = NULL; + gsize length = 0; + GError *error = NULL; + + gdata_test_mock_server_start_trace (mock_server, "photo-get"); + + g_assert (gdata_contacts_contact_get_photo_etag (data->contact) != NULL); + + /* Get the photo from the network */ + photo_data = gdata_contacts_contact_get_photo (data->contact, GDATA_CONTACTS_SERVICE (service), &length, &content_type, NULL, &error); + g_assert_no_error (error); + g_assert (photo_data != NULL); + g_assert (length != 0); + g_assert_cmpstr (content_type, ==, "image/jpeg"); + + g_assert (gdata_contacts_contact_get_photo_etag (data->contact) != NULL); + + g_free (content_type); + g_free (photo_data); + g_clear_error (&error); + + uhm_server_end_trace (mock_server); +} + +GDATA_ASYNC_TEST_FUNCTIONS (photo_get, TempContactData, +G_STMT_START { + g_assert (gdata_contacts_contact_get_photo_etag (data->contact) != NULL); + + /* Get the photo from the network asynchronously */ + gdata_contacts_contact_get_photo_async (data->contact, GDATA_CONTACTS_SERVICE (service), cancellable, async_ready_callback, async_data); +} G_STMT_END, +G_STMT_START { + GDataContactsContact *contact = GDATA_CONTACTS_CONTACT (obj); + guint8 *photo_data; + gsize length; + gchar *content_type; + + /* Finish getting the photo */ + photo_data = gdata_contacts_contact_get_photo_finish (contact, async_result, &length, &content_type, &error); + + if (error == NULL) { + g_assert (photo_data != NULL); + g_assert (length != 0); + g_assert_cmpstr (content_type, ==, "image/jpeg"); + + g_assert (gdata_contacts_contact_get_photo_etag (contact) != NULL); + } else { + g_assert (photo_data == NULL); + g_assert (length == 0); + g_assert (content_type == NULL); + } + + g_free (content_type); + g_free (photo_data); +} G_STMT_END); + +static void +test_photo_delete (TempContactData *data, gconstpointer service) +{ + GError *error = NULL; + + gdata_test_mock_server_start_trace (mock_server, "photo-delete"); + + g_assert (gdata_contacts_contact_get_photo_etag (data->contact) != NULL); + + /* Remove the contact's photo */ + g_assert (gdata_contacts_contact_set_photo (data->contact, GDATA_CONTACTS_SERVICE (service), NULL, 0, NULL, NULL, &error) == TRUE); + g_assert_no_error (error); + + g_assert (gdata_contacts_contact_get_photo_etag (data->contact) == NULL); + + g_clear_error (&error); + + uhm_server_end_trace (mock_server); +} + +static void +test_photo_delete_async_cancellation (GDataAsyncTestData *data, + gconstpointer service) __attribute__((unused)); + +GDATA_ASYNC_TEST_FUNCTIONS (photo_delete, TempContactData, +G_STMT_START { + g_assert (gdata_contacts_contact_get_photo_etag (data->contact) != NULL); + + /* Delete it from the contact asynchronously */ + gdata_contacts_contact_set_photo_async (data->contact, GDATA_CONTACTS_SERVICE (service), NULL, 0, NULL, cancellable, + async_ready_callback, async_data); +} G_STMT_END, +G_STMT_START { + GDataContactsContact *contact = GDATA_CONTACTS_CONTACT (obj); + gboolean success; + + success = gdata_contacts_contact_set_photo_finish (contact, async_result, &error); + + if (error == NULL) { + g_assert (success == TRUE); + g_assert (gdata_contacts_contact_get_photo_etag (contact) == NULL); + } else { + g_assert (success == FALSE); + g_assert (gdata_contacts_contact_get_photo_etag (contact) != NULL); + } +} G_STMT_END); + +static void +test_batch (gconstpointer service) +{ + GDataBatchOperation *operation; + GDataService *service2; + GDataContactsContact *contact, *contact2, *contact3; + GDataEntry *inserted_entry, *inserted_entry2, *inserted_entry3; + gchar *feed_uri; + guint op_id, op_id2, op_id3; + GError *error = NULL, *entry_error = NULL; + + gdata_test_mock_server_start_trace (mock_server, "batch"); + + /* Here we hardcode the feed URI, but it should really be extracted from a contacts feed, as the GDATA_LINK_BATCH link */ + operation = gdata_batchable_create_operation (GDATA_BATCHABLE (service), gdata_contacts_service_get_primary_authorization_domain (), + "https://www.google.com/m8/feeds/contacts/default/full/batch"); + + /* Check the properties of the operation */ + g_assert (gdata_batch_operation_get_service (operation) == service); + g_assert_cmpstr (gdata_batch_operation_get_feed_uri (operation), ==, "https://www.google.com/m8/feeds/contacts/default/full/batch"); + + g_object_get (operation, + "service", &service2, + "feed-uri", &feed_uri, + NULL); + + g_assert (service2 == service); + g_assert_cmpstr (feed_uri, ==, "https://www.google.com/m8/feeds/contacts/default/full/batch"); + + g_object_unref (service2); + g_free (feed_uri); + + /* Run a singleton batch operation to insert a new entry */ + contact = gdata_contacts_contact_new (NULL); + gdata_entry_set_title (GDATA_ENTRY (contact), "Fooish Bar"); + + gdata_test_batch_operation_insertion (operation, GDATA_ENTRY (contact), &inserted_entry, NULL); + g_assert (gdata_test_batch_operation_run (operation, NULL, &error) == TRUE); + g_assert_no_error (error); + + g_clear_error (&error); + g_object_unref (operation); + g_object_unref (contact); + + /* Run another batch operation to insert another entry and query the previous one */ + contact2 = gdata_contacts_contact_new (NULL); + gdata_entry_set_title (GDATA_ENTRY (contact2), "Brian"); + + operation = gdata_batchable_create_operation (GDATA_BATCHABLE (service), gdata_contacts_service_get_primary_authorization_domain (), + "https://www.google.com/m8/feeds/contacts/default/full/batch"); + op_id = gdata_test_batch_operation_insertion (operation, GDATA_ENTRY (contact2), &inserted_entry2, NULL); + op_id2 = gdata_test_batch_operation_query (operation, gdata_entry_get_id (inserted_entry), GDATA_TYPE_CONTACTS_CONTACT, inserted_entry, NULL, + NULL); + g_assert_cmpuint (op_id, !=, op_id2); + + g_assert (gdata_test_batch_operation_run (operation, NULL, &error) == TRUE); + g_assert_no_error (error); + + g_clear_error (&error); + g_object_unref (operation); + g_object_unref (contact2); + + /* Run another batch operation to delete the first entry and a fictitious one to test error handling, and update the second entry */ + gdata_entry_set_title (inserted_entry2, "Toby"); + contact3 = gdata_contacts_contact_new ("foobar"); + + operation = gdata_batchable_create_operation (GDATA_BATCHABLE (service), gdata_contacts_service_get_primary_authorization_domain (), + "https://www.google.com/m8/feeds/contacts/default/full/batch"); + op_id = gdata_test_batch_operation_deletion (operation, inserted_entry, NULL); + op_id2 = gdata_test_batch_operation_deletion (operation, GDATA_ENTRY (contact3), &entry_error); + op_id3 = gdata_test_batch_operation_update (operation, inserted_entry2, &inserted_entry3, NULL); + g_assert_cmpuint (op_id, !=, op_id2); + g_assert_cmpuint (op_id, !=, op_id3); + g_assert_cmpuint (op_id2, !=, op_id3); + + g_assert (gdata_test_batch_operation_run (operation, NULL, &error) == TRUE); + g_assert_no_error (error); + + g_assert_error (entry_error, GDATA_SERVICE_ERROR, GDATA_SERVICE_ERROR_PROTOCOL_ERROR); + + g_clear_error (&error); + g_clear_error (&entry_error); + g_object_unref (operation); + g_object_unref (inserted_entry); + g_object_unref (contact3); + + /* Run another batch operation to update the second entry with the wrong ETag (i.e. pass the old version of the entry to the batch operation + * to test error handling */ +#if 0 + operation = gdata_batchable_create_operation (GDATA_BATCHABLE (service), gdata_contacts_service_get_primary_authorization_domain (), + "https://www.google.com/m8/feeds/contacts/default/full/batch"); + gdata_test_batch_operation_update (operation, inserted_entry2, NULL, &entry_error); + g_assert (gdata_test_batch_operation_run (operation, NULL, &error) == TRUE); + g_assert_no_error (error); + + g_assert_error (entry_error, GDATA_SERVICE_ERROR, GDATA_SERVICE_ERROR_CONFLICT); +#endif + g_clear_error (&error); + g_clear_error (&entry_error); +/* g_object_unref (operation);*/ + g_object_unref (inserted_entry2); + + /* Run a final batch operation to delete the second entry */ +/* operation = gdata_batchable_create_operation (GDATA_BATCHABLE (service), gdata_contacts_service_get_primary_authorization_domain (), + "https://www.google.com/m8/feeds/contacts/default/full/batch"); + gdata_test_batch_operation_deletion (operation, inserted_entry3, NULL); + g_assert (gdata_test_batch_operation_run (operation, NULL, &error) == TRUE); + g_assert_no_error (error); +*/ + g_clear_error (&error); + /*g_object_unref (operation);*/ + g_object_unref (inserted_entry3); + + uhm_server_end_trace (mock_server); +} + +typedef struct { + GDataContactsContact *new_contact; +} BatchAsyncData; + +static void +setup_batch_async (BatchAsyncData *data, gconstpointer service) +{ + GDataContactsContact *contact; + GError *error = NULL; + + gdata_test_mock_server_start_trace (mock_server, "setup-batch-async"); + + /* Insert a new contact which we can query asyncly */ + contact = gdata_contacts_contact_new (NULL); + gdata_entry_set_title (GDATA_ENTRY (contact), "Fooish Bar"); + + data->new_contact = gdata_contacts_service_insert_contact (GDATA_CONTACTS_SERVICE (service), contact, NULL, &error); + g_assert_no_error (error); + g_assert (GDATA_IS_CONTACTS_CONTACT (data->new_contact)); + g_clear_error (&error); + + g_object_unref (contact); + + uhm_server_end_trace (mock_server); +} + +static void +test_batch_async_cb (GDataBatchOperation *operation, GAsyncResult *async_result, GMainLoop *main_loop) +{ + GError *error = NULL; + + /* Clear all pending events (such as callbacks for the operations) */ + while (g_main_context_iteration (NULL, FALSE) == TRUE); + + g_assert (gdata_test_batch_operation_run_finish (operation, async_result, &error) == TRUE); + g_assert_no_error (error); + g_clear_error (&error); + + g_main_loop_quit (main_loop); +} + +static void +test_batch_async (BatchAsyncData *data, gconstpointer service) +{ + GDataBatchOperation *operation; + GMainLoop *main_loop; + + gdata_test_mock_server_start_trace (mock_server, "batch-async"); + + /* Run an async query operation on the contact */ + operation = gdata_batchable_create_operation (GDATA_BATCHABLE (service), gdata_contacts_service_get_primary_authorization_domain (), + "https://www.google.com/m8/feeds/contacts/default/full/batch"); + gdata_test_batch_operation_query (operation, gdata_entry_get_id (GDATA_ENTRY (data->new_contact)), GDATA_TYPE_CONTACTS_CONTACT, + GDATA_ENTRY (data->new_contact), NULL, NULL); + + main_loop = g_main_loop_new (NULL, TRUE); + + gdata_batch_operation_run_async (operation, NULL, (GAsyncReadyCallback) test_batch_async_cb, main_loop); + g_main_loop_run (main_loop); + + g_main_loop_unref (main_loop); + g_object_unref (operation); + + uhm_server_end_trace (mock_server); +} + +static void +test_batch_async_cancellation_cb (GDataBatchOperation *operation, GAsyncResult *async_result, GMainLoop *main_loop) +{ + GError *error = NULL; + + /* Clear all pending events (such as callbacks for the operations) */ + while (g_main_context_iteration (NULL, FALSE) == TRUE); + + g_assert (gdata_test_batch_operation_run_finish (operation, async_result, &error) == FALSE); + g_assert_error (error, G_IO_ERROR, G_IO_ERROR_CANCELLED); + g_clear_error (&error); + + g_main_loop_quit (main_loop); +} + +static void +test_batch_async_cancellation (BatchAsyncData *data, gconstpointer service) +{ + GDataBatchOperation *operation; + GMainLoop *main_loop; + GCancellable *cancellable; + GError *error = NULL; + + gdata_test_mock_server_start_trace (mock_server, "batch-async-cancellation"); + + /* Run an async query operation on the contact */ + operation = gdata_batchable_create_operation (GDATA_BATCHABLE (service), gdata_contacts_service_get_primary_authorization_domain (), + "https://www.google.com/m8/feeds/contacts/default/full/batch"); + gdata_test_batch_operation_query (operation, gdata_entry_get_id (GDATA_ENTRY (data->new_contact)), GDATA_TYPE_CONTACTS_CONTACT, + GDATA_ENTRY (data->new_contact), NULL, &error); + + main_loop = g_main_loop_new (NULL, TRUE); + cancellable = g_cancellable_new (); + + gdata_batch_operation_run_async (operation, cancellable, (GAsyncReadyCallback) test_batch_async_cancellation_cb, main_loop); + g_cancellable_cancel (cancellable); /* this should cancel the operation before it even starts, as we haven't run the main loop yet */ + + g_main_loop_run (main_loop); + + g_assert_error (error, G_IO_ERROR, G_IO_ERROR_CANCELLED); + g_clear_error (&error); + + g_main_loop_unref (main_loop); + g_object_unref (cancellable); + g_object_unref (operation); + + uhm_server_end_trace (mock_server); +} + +static void +teardown_batch_async (BatchAsyncData *data, gconstpointer service) +{ + GError *error = NULL; + + gdata_test_mock_server_start_trace (mock_server, "teardown-batch-async"); + + /* Delete the contact */ + g_assert (gdata_service_delete_entry (GDATA_SERVICE (service), gdata_contacts_service_get_primary_authorization_domain (), + GDATA_ENTRY (data->new_contact), NULL, &error) == TRUE); + g_assert_no_error (error); + g_clear_error (&error); + + g_object_unref (data->new_contact); + + uhm_server_end_trace (mock_server); +} + +static void +test_group_membership (void) +{ + GDataContactsContact *contact; + GList *groups; + + /* Create a new contact with no groups */ + contact = gdata_contacts_contact_new (NULL); + g_assert (GDATA_IS_CONTACTS_CONTACT (contact)); + g_assert (gdata_contacts_contact_get_groups (contact) == NULL); + g_assert (gdata_contacts_contact_is_group_deleted (contact, "http://notagroup.com/") == FALSE); + + /* Add a group */ + gdata_contacts_contact_add_group (contact, "http://foo.com/group1"); + g_assert (gdata_contacts_contact_is_group_deleted (contact, "http://foo.com/group1") == FALSE); + + groups = gdata_contacts_contact_get_groups (contact); + g_assert_cmpint (g_list_length (groups), ==, 1); + g_assert_cmpstr (groups->data, ==, "http://foo.com/group1"); + + /* Add another group */ + gdata_contacts_contact_add_group (contact, "http://foo.com/group2"); + g_assert (gdata_contacts_contact_is_group_deleted (contact, "http://foo.com/group1") == FALSE); + g_assert (gdata_contacts_contact_is_group_deleted (contact, "http://foo.com/group2") == FALSE); + + groups = gdata_contacts_contact_get_groups (contact); + g_assert_cmpint (g_list_length (groups), ==, 2); + if (strcmp (groups->data, "http://foo.com/group1") == 0) + g_assert_cmpstr (groups->next->data, ==, "http://foo.com/group2"); + else if (strcmp (groups->data, "http://foo.com/group2") == 0) + g_assert_cmpstr (groups->next->data, ==, "http://foo.com/group1"); + else + g_assert_not_reached (); + + /* Remove the first group */ + gdata_contacts_contact_remove_group (contact, "http://foo.com/group1"); + g_assert (gdata_contacts_contact_is_group_deleted (contact, "http://foo.com/group1") == FALSE); /* hasn't been propagated to the server */ + + groups = gdata_contacts_contact_get_groups (contact); + g_assert_cmpint (g_list_length (groups), ==, 1); + g_assert_cmpstr (groups->data, ==, "http://foo.com/group2"); + + g_object_unref (contact); +} + +static void +test_contact_id (void) +{ + GDataContactsContact *contact; + GError *error = NULL; + + /* Check that IDs are changed to the full projection when creating a new contact… */ + contact = gdata_contacts_contact_new ("http://www.google.com/m8/feeds/contacts/libgdata.test@googlemail.com/base/1b46cdd20bfbee3b"); + g_assert_cmpstr (gdata_entry_get_id (GDATA_ENTRY (contact)), ==, + "http://www.google.com/m8/feeds/contacts/libgdata.test@googlemail.com/full/1b46cdd20bfbee3b"); + g_object_unref (contact); + + /* …and when creating one from XML. */ + contact = GDATA_CONTACTS_CONTACT (gdata_parsable_new_from_xml (GDATA_TYPE_CONTACTS_CONTACT, + "" + "http://www.google.com/m8/feeds/contacts/libgdata.test@googlemail.com/base/1b46cdd20bfbee3b" + "2009-04-25T15:21:53.688Z" + "" + "Foobar" + "", -1, &error)); + g_assert_no_error (error); + g_assert (GDATA_IS_CONTACTS_CONTACT (contact)); + g_clear_error (&error); + + g_assert_cmpstr (gdata_entry_get_id (GDATA_ENTRY (contact)), ==, + "http://www.google.com/m8/feeds/contacts/libgdata.test@googlemail.com/full/1b46cdd20bfbee3b"); + + g_object_unref (contact); +} + +static void +mock_server_notify_resolver_cb (GObject *object, GParamSpec *pspec, gpointer user_data) +{ + UhmServer *server; + UhmResolver *resolver; + + server = UHM_SERVER (object); + + /* Set up the expected domain names here. This should technically be split up between + * the different unit test suites, but that's too much effort. */ + resolver = uhm_server_get_resolver (server); + + if (resolver != NULL) { + const gchar *ip_address = uhm_server_get_address (server); + + uhm_resolver_add_A (resolver, "www.google.com", ip_address); + uhm_resolver_add_A (resolver, + "accounts.google.com", ip_address); + } +} + +/* Set up a global GDataAuthorizer to be used for all the tests. Unfortunately, + * the Google Contacts API is effectively limited to OAuth1 and OAuth2 + * authorisation, so this requires user interaction when online. + * + * If not online, use a dummy authoriser. */ +static GDataAuthorizer * +create_global_authorizer (void) +{ + GDataOAuth2Authorizer *authorizer = NULL; /* owned */ + gchar *authentication_uri, *authorisation_code; + GError *error = NULL; + + /* If not online, just return a dummy authoriser. */ + if (!uhm_server_get_enable_online (mock_server)) { + return GDATA_AUTHORIZER (gdata_dummy_authorizer_new (GDATA_TYPE_CONTACTS_SERVICE)); + } + + /* Otherwise, go through the interactive OAuth dance. */ + gdata_test_mock_server_start_trace (mock_server, "global-authentication"); + authorizer = gdata_oauth2_authorizer_new (CLIENT_ID, CLIENT_SECRET, + REDIRECT_URI, + GDATA_TYPE_CONTACTS_SERVICE); + + /* Get an authentication URI */ + authentication_uri = gdata_oauth2_authorizer_build_authentication_uri (authorizer, NULL, FALSE); + g_assert (authentication_uri != NULL); + + /* Get the authorisation code off the user. */ + authorisation_code = gdata_test_query_user_for_verifier (authentication_uri); + + g_free (authentication_uri); + + if (authorisation_code == NULL) { + /* Skip tests. */ + g_object_unref (authorizer); + authorizer = NULL; + goto skip_test; + } + + /* Authorise the token */ + g_assert (gdata_oauth2_authorizer_request_authorization (authorizer, authorisation_code, NULL, &error)); + g_assert_no_error (error); + +skip_test: + g_free (authorisation_code); + + uhm_server_end_trace (mock_server); + + return GDATA_AUTHORIZER (authorizer); +} + +int +main (int argc, char *argv[]) +{ + gint retval; + GDataAuthorizer *authorizer = NULL; /* owned */ + GDataService *service = NULL; /* owned */ + GFile *trace_directory = NULL; /* owned */ + gchar *path = NULL; /* owned */ + + gdata_test_init (argc, argv); + + mock_server = gdata_test_get_mock_server (); + g_signal_connect (G_OBJECT (mock_server), "notify::resolver", + (GCallback) mock_server_notify_resolver_cb, NULL); + path = g_test_build_filename (G_TEST_DIST, "traces/contacts", NULL); + trace_directory = g_file_new_for_path (path); + g_free (path); + uhm_server_set_trace_directory (mock_server, trace_directory); + g_object_unref (trace_directory); + + authorizer = create_global_authorizer (); + service = GDATA_SERVICE (gdata_contacts_service_new (authorizer)); + + g_test_add_func ("/contacts/authentication", test_authentication); + + g_test_add ("/contacts/contact/insert", InsertData, service, set_up_insert, test_contact_insert, tear_down_insert); + g_test_add ("/contacts/contact/update", TempContactData, service, set_up_temp_contact, test_contact_update, tear_down_temp_contact); + + g_test_add ("/contacts/query/all_contacts", QueryAllContactsData, service, set_up_query_all_contacts, test_query_all_contacts, + tear_down_query_all_contacts); + g_test_add ("/contacts/query/all_contacts/async", GDataAsyncTestData, service, set_up_query_all_contacts_async, + test_query_all_contacts_async, tear_down_query_all_contacts_async); + g_test_add ("/contacts/query/all_contacts/async/progress_closure", QueryAllContactsData, service, + set_up_query_all_contacts, test_query_all_contacts_async_progress_closure, tear_down_query_all_contacts); + g_test_add ("/contacts/query/all_contacts/cancellation", GDataAsyncTestData, service, set_up_query_all_contacts_async, + test_query_all_contacts_async_cancellation, tear_down_query_all_contacts_async); + + g_test_add_data_func ("/contacts/photo/has_photo", service, test_photo_has_photo); + g_test_add ("/contacts/photo/add", TempContactData, service, set_up_temp_contact, test_photo_add, tear_down_temp_contact); + g_test_add ("/contacts/photo/add/async", GDataAsyncTestData, service, set_up_temp_contact_async, test_photo_add_async, + tear_down_temp_contact_async); + g_test_add ("/contacts/photo/add/async/cancellation", GDataAsyncTestData, service, set_up_temp_contact_async, + test_photo_add_async_cancellation, tear_down_temp_contact_async); + g_test_add ("/contacts/photo/get", TempContactData, service, set_up_temp_contact_with_photo, test_photo_get, tear_down_temp_contact); + g_test_add ("/contacts/photo/get/async", GDataAsyncTestData, service, set_up_temp_contact_with_photo_async, test_photo_get_async, + tear_down_temp_contact_with_photo_async); + g_test_add ("/contacts/photo/get/async/cancellation", GDataAsyncTestData, service, set_up_temp_contact_with_photo_async, + test_photo_get_async_cancellation, tear_down_temp_contact_with_photo_async); + + g_test_add ("/contacts/photo/delete", TempContactData, service, set_up_temp_contact_with_photo, test_photo_delete, + tear_down_temp_contact); + g_test_add ("/contacts/photo/delete/async", GDataAsyncTestData, service, set_up_temp_contact_with_photo_async, + test_photo_delete_async, tear_down_temp_contact_with_photo_async); +/* + Too broken to continue running at the moment. + g_test_add ("/contacts/photo/delete/async/cancellation", GDataAsyncTestData, service, set_up_temp_contact_with_photo_async, + test_photo_delete_async_cancellation, tear_down_temp_contact_with_photo_async); +*/ + + g_test_add_data_func ("/contacts/batch", service, test_batch); + g_test_add ("/contacts/batch/async", BatchAsyncData, service, setup_batch_async, test_batch_async, teardown_batch_async); + g_test_add ("/contacts/batch/async/cancellation", BatchAsyncData, service, setup_batch_async, test_batch_async_cancellation, + teardown_batch_async); + + g_test_add ("/contacts/group/query", QueryAllGroupsData, service, set_up_query_all_groups, test_query_all_groups, + tear_down_query_all_groups); + g_test_add ("/contacts/group/query/async", GDataAsyncTestData, service, set_up_query_all_groups_async, + test_query_all_groups_async, tear_down_query_all_groups_async); + g_test_add ("/contacts/group/query/async/progress_closure", QueryAllGroupsData, service, set_up_query_all_groups, + test_query_all_groups_async_progress_closure, tear_down_query_all_groups); + g_test_add ("/contacts/group/query/async/cancellation", GDataAsyncTestData, service, set_up_query_all_groups_async, + test_query_all_groups_async_cancellation, tear_down_query_all_groups_async); + + g_test_add ("/contacts/group/insert", InsertGroupData, service, set_up_insert_group, test_group_insert, tear_down_insert_group); + g_test_add ("/contacts/group/insert/async", GDataAsyncTestData, service, set_up_insert_group_async, test_group_insert_async, + tear_down_insert_group_async); + g_test_add ("/contacts/group/insert/async/cancellation", GDataAsyncTestData, service, set_up_insert_group_async, + test_group_insert_async_cancellation, tear_down_insert_group_async); + + g_test_add_func ("/contacts/contact/properties", test_contact_properties); + g_test_add_func ("/contacts/contact/escaping", test_contact_escaping); + g_test_add_func ("/contacts/contact/parser/minimal", test_contact_parser_minimal); + g_test_add_func ("/contacts/contact/parser/normal", test_contact_parser_normal); + g_test_add_func ("/contacts/contact/parser/error_handling", test_contact_parser_error_handling); + g_test_add_func ("/contacts/contact/id", test_contact_id); + + g_test_add_func ("/contacts/query/uri", test_query_uri); + g_test_add_func ("/contacts/query/etag", test_query_etag); + g_test_add_func ("/contacts/query/properties", test_query_properties); + + g_test_add_func ("/contacts/group/properties", test_group_properties); + g_test_add_func ("/contacts/group/escaping", test_group_escaping); + g_test_add_func ("/contacts/group/parser/normal", test_group_parser_normal); + g_test_add_func ("/contacts/group/parser/system", test_group_parser_system); + g_test_add_func ("/contacts/group/parser/error_handling", test_group_parser_error_handling); + g_test_add_func ("/contacts/group/membership", test_group_membership); + + retval = g_test_run (); + + g_clear_object (&service); + g_clear_object (&authorizer); + + return retval; +} diff --git a/gdata/tests/documents.c b/gdata/tests/documents.c new file mode 100644 index 0000000..868ae09 --- /dev/null +++ b/gdata/tests/documents.c @@ -0,0 +1,2284 @@ +/* -*- Mode: C; indent-tabs-mode: t; c-basic-offset: 8; tab-width: 8 -*- */ +/* + * GData Client + * Copyright (C) Thibault Saunier 2009 + * Copyright (C) Philip Withnall 2010 + * Copyright (C) Red Hat, Inc. 2015, 2016 + * + * GData Client is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * GData Client is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with GData Client. If not, see . + */ + +#include +#include +#include + +/* For the thumbnail size tests in test_download_thumbnail() */ +#ifdef HAVE_GDK_PIXBUF +#include +#endif + +#include "gdata.h" +#include "common.h" +#include "gdata-dummy-authorizer.h" + +static UhmServer *mock_server = NULL; + +#undef CLIENT_ID /* from common.h */ + +#define CLIENT_ID "352818697630-nqu2cmt5quqd6lr17ouoqmb684u84l1f.apps.googleusercontent.com" +#define CLIENT_SECRET "-fA4pHQJxR3zJ-FyAMPQsikg" +#define REDIRECT_URI "urn:ietf:wg:oauth:2.0:oob" + +static void +add_folder_link_to_entry (GDataDocumentsEntry *entry, GDataDocumentsFolder *folder) +{ + GDataLink *_link; + const gchar *id; + gchar *uri; + + /* HACK: Build the GDataLink:uri from the ID by adding the prefix. */ + id = gdata_entry_get_id (GDATA_ENTRY (folder)); + uri = g_strconcat ("https://www.googleapis.com/drive/v2/files/", id, NULL); + _link = gdata_link_new (uri, GDATA_LINK_PARENT); + gdata_entry_add_link (GDATA_ENTRY (entry), _link); + g_object_unref (_link); + g_free (uri); +} + +static gboolean +check_document_is_in_folder (GDataDocumentsDocument *document, GDataDocumentsFolder *folder) +{ + GList *links; + gboolean found_folder_category = FALSE; + GDataLink *folder_self_link; + + folder_self_link = gdata_entry_look_up_link (GDATA_ENTRY (folder), GDATA_LINK_SELF); + g_assert (folder_self_link != NULL); + + for (links = gdata_entry_look_up_links (GDATA_ENTRY (document), GDATA_LINK_PARENT); + links != NULL; links = links->next) { + GDataLink *_link = GDATA_LINK (links->data); + + if (strcmp (gdata_link_get_uri (_link), gdata_link_get_uri (folder_self_link)) == 0) { + g_assert (found_folder_category == FALSE); + found_folder_category = TRUE; + } + } + + return found_folder_category; +} + +static gboolean +check_document_is_in_root_folder (GDataDocumentsDocument *document) +{ + GList *links; + gboolean is_in_root_folder; + + links = gdata_entry_look_up_links (GDATA_ENTRY (document), GDATA_LINK_PARENT); + is_in_root_folder = (links == NULL) ? TRUE : FALSE; + g_list_free (links); + + return is_in_root_folder; +} + +static void +delete_entry (GDataDocumentsEntry *entry, GDataService *service) +{ + GDataEntry *new_entry; + + /* Re-query for the entry because its ETag may have changed over the course of the tests (or because the Documents servers like to + * arbitrarily change ETag values). */ + new_entry = gdata_service_query_single_entry (service, gdata_documents_service_get_primary_authorization_domain (), + gdata_entry_get_id (GDATA_ENTRY (entry)), NULL, G_OBJECT_TYPE (entry), NULL, NULL); + g_assert (GDATA_IS_DOCUMENTS_ENTRY (new_entry)); + + /* Delete the entry. Don't bother asserting that it succeeds, because it will often fail because Google keep giving us the wrong ETag above. */ + gdata_service_delete_entry (service, gdata_documents_service_get_primary_authorization_domain (), new_entry, NULL, NULL); + g_object_unref (new_entry); +} + +static GDataDocumentsFolder * +create_folder (GDataDocumentsService *service, const gchar *title) +{ + GDataDocumentsFolder *folder, *new_folder; + GDataDocumentsFolder *root; + + root = GDATA_DOCUMENTS_FOLDER (gdata_service_query_single_entry (GDATA_SERVICE (service), + gdata_documents_service_get_primary_authorization_domain (), + "root", + NULL, + GDATA_TYPE_DOCUMENTS_FOLDER, + NULL, + NULL)); + + folder = gdata_documents_folder_new (NULL); + gdata_entry_set_title (GDATA_ENTRY (folder), title); + + /* Insert the folder */ + new_folder = GDATA_DOCUMENTS_FOLDER (gdata_documents_service_add_entry_to_folder (GDATA_DOCUMENTS_SERVICE (service), + GDATA_DOCUMENTS_ENTRY (folder), + root, + NULL, + NULL)); + g_assert (GDATA_IS_DOCUMENTS_FOLDER (new_folder)); + g_object_unref (folder); + g_object_unref (root); + + return new_folder; +} + +static void +test_authentication (void) +{ + GDataOAuth2Authorizer *authorizer = NULL; /* owned */ + gchar *authentication_uri, *authorisation_code; + + gdata_test_mock_server_start_trace (mock_server, "authentication"); + + authorizer = gdata_oauth2_authorizer_new (CLIENT_ID, CLIENT_SECRET, REDIRECT_URI, GDATA_TYPE_DOCUMENTS_SERVICE); + + /* Get an authentication URI. */ + authentication_uri = gdata_oauth2_authorizer_build_authentication_uri (authorizer, NULL, FALSE); + g_assert (authentication_uri != NULL); + + /* Get the authorisation code off the user. */ + if (uhm_server_get_enable_online (mock_server)) { + authorisation_code = gdata_test_query_user_for_verifier (authentication_uri); + } else { + /* Hard coded, extracted from the trace file. */ + authorisation_code = g_strdup ("FIXME: to be updated from the trace file"); + } + + g_free (authentication_uri); + + if (authorisation_code == NULL) { + /* Skip tests. */ + goto skip_test; + } + + /* Authorise the token */ + g_assert (gdata_oauth2_authorizer_request_authorization (authorizer, authorisation_code, NULL, NULL) == TRUE); + + /* Check all is as it should be */ + g_assert (gdata_authorizer_is_authorized_for_domain (GDATA_AUTHORIZER (authorizer), + gdata_documents_service_get_primary_authorization_domain ()) == TRUE); + g_assert (gdata_authorizer_is_authorized_for_domain (GDATA_AUTHORIZER (authorizer), + gdata_documents_service_get_spreadsheet_authorization_domain ()) == TRUE); + +skip_test: + g_free (authorisation_code); + g_object_unref (authorizer); + + uhm_server_end_trace (mock_server); +} + +typedef struct { + GDataDocumentsFolder *folder; +} TempFolderData; + +static void +set_up_temp_folder (TempFolderData *data, gconstpointer service) +{ + GDataDocumentsFolder *folder; + GDataDocumentsFolder *root; + + gdata_test_mock_server_start_trace (mock_server, "setup-temp-folder"); + + root = GDATA_DOCUMENTS_FOLDER (gdata_service_query_single_entry (GDATA_SERVICE (service), + gdata_documents_service_get_primary_authorization_domain (), + "root", + NULL, + GDATA_TYPE_DOCUMENTS_FOLDER, + NULL, + NULL)); + + /* Create a folder */ + folder = gdata_documents_folder_new (NULL); + gdata_entry_set_title (GDATA_ENTRY (folder), "Temporary Folder"); + + /* Insert the folder */ + data->folder = GDATA_DOCUMENTS_FOLDER (gdata_documents_service_add_entry_to_folder (GDATA_DOCUMENTS_SERVICE (service), + GDATA_DOCUMENTS_ENTRY (folder), + root, + NULL, + NULL)); + g_assert (GDATA_IS_DOCUMENTS_FOLDER (data->folder)); + g_object_unref (folder); + g_object_unref (root); + + uhm_server_end_trace (mock_server); +} + +static void +tear_down_temp_folder (TempFolderData *data, gconstpointer service) +{ + gdata_test_mock_server_start_trace (mock_server, "teardown-temp-folder"); + + if (data->folder != NULL) { + delete_entry (GDATA_DOCUMENTS_ENTRY (data->folder), GDATA_SERVICE (service)); + g_object_unref (data->folder); + } + + uhm_server_end_trace (mock_server); +} + +typedef struct { + GDataDocumentsDocument *document; +} TempDocumentData; + +static GDataDocumentsDocument * +_set_up_temp_document (GDataDocumentsEntry *entry, GDataService *service, GFile *document_file) +{ + GDataDocumentsDocument *document, *new_document; + GFileInfo *file_info; + GFileInputStream *file_stream; + GDataUploadStream *upload_stream; + GError *error = NULL; + + /* Query for information on the file. */ + file_info = g_file_query_info (document_file, + G_FILE_ATTRIBUTE_STANDARD_DISPLAY_NAME "," G_FILE_ATTRIBUTE_STANDARD_CONTENT_TYPE, + G_FILE_QUERY_INFO_NONE, NULL, &error); + g_assert_no_error (error); + + /* Prepare the upload stream */ + upload_stream = gdata_documents_service_upload_document (GDATA_DOCUMENTS_SERVICE (service), + GDATA_DOCUMENTS_DOCUMENT (entry), + g_file_info_get_display_name (file_info), + g_file_info_get_content_type (file_info), + NULL, NULL, &error); + g_assert_no_error (error); + g_assert (GDATA_IS_UPLOAD_STREAM (upload_stream)); + + g_object_unref (file_info); + + /* Open the file */ + file_stream = g_file_read (document_file, NULL, &error); + g_assert_no_error (error); + + /* Upload the document */ + g_output_stream_splice (G_OUTPUT_STREAM (upload_stream), G_INPUT_STREAM (file_stream), + G_OUTPUT_STREAM_SPLICE_CLOSE_SOURCE | G_OUTPUT_STREAM_SPLICE_CLOSE_TARGET, NULL, &error); + g_assert_no_error (error); + + /* Finish the upload */ + document = gdata_documents_service_finish_upload (GDATA_DOCUMENTS_SERVICE (service), upload_stream, &error); + g_assert_no_error (error); + + g_object_unref (upload_stream); + + /* HACK: Query for the new document, as Google's servers appear to modify it behind our back when creating the document: + * http://code.google.com/a/google.com/p/apps-api-issues/issues/detail?id=2337. We have to wait a few seconds before trying this to allow the + * various Google servers to catch up with each other. Thankfully, we don't have to wait when running against the mock server. */ + if (uhm_server_get_enable_online (mock_server) == TRUE) { + g_usleep (5 * G_USEC_PER_SEC); + } + + new_document = GDATA_DOCUMENTS_DOCUMENT (gdata_service_query_single_entry (service, + gdata_documents_service_get_primary_authorization_domain (), + gdata_entry_get_id (GDATA_ENTRY (document)), NULL, + G_OBJECT_TYPE (document), NULL, NULL)); + g_assert (GDATA_IS_DOCUMENTS_DOCUMENT (new_document)); + + g_object_unref (document); + + return new_document; +} + +static void +set_up_temp_document_spreadsheet (TempDocumentData *data, gconstpointer service) +{ + GDataDocumentsSpreadsheet *document; + gchar *document_file_path; + GFile *document_file; + + gdata_test_mock_server_start_trace (mock_server, "setup-temp-document-spreadsheet"); + + /* Create a document */ + document = gdata_documents_spreadsheet_new (NULL); + gdata_entry_set_title (GDATA_ENTRY (document), "Temporary Document (Spreadsheet)"); + + document_file_path = g_test_build_filename (G_TEST_DIST, "test.ods", NULL); + document_file = g_file_new_for_path (document_file_path); + g_free (document_file_path); + + data->document = _set_up_temp_document (GDATA_DOCUMENTS_ENTRY (document), GDATA_SERVICE (service), document_file); + + g_object_unref (document_file); + g_object_unref (document); + + uhm_server_end_trace (mock_server); +} + +static void +tear_down_temp_document (TempDocumentData *data, gconstpointer service) +{ + gdata_test_mock_server_start_trace (mock_server, "teardown-temp-document"); + + if (data->document != NULL) { + delete_entry (GDATA_DOCUMENTS_ENTRY (data->document), GDATA_SERVICE (service)); + g_object_unref (data->document); + } + + uhm_server_end_trace (mock_server); +} + +static void +test_delete_folder (TempFolderData *data, gconstpointer service) +{ + gboolean success; + GDataEntry *updated_folder; + GError *error = NULL; + + gdata_test_mock_server_start_trace (mock_server, "delete-folder"); + + g_assert (gdata_documents_entry_is_deleted (GDATA_DOCUMENTS_ENTRY (data->folder)) == FALSE); + + /* Delete the folder */ + success = gdata_service_delete_entry (GDATA_SERVICE (service), gdata_documents_service_get_primary_authorization_domain (), + GDATA_ENTRY (data->folder), NULL, &error); + g_assert_no_error (error); + g_assert (success == TRUE); + g_clear_error (&error); + + /* Re-query for the folder to ensure it's been deleted */ + updated_folder = gdata_service_query_single_entry (GDATA_SERVICE (service), gdata_documents_service_get_primary_authorization_domain (), + gdata_entry_get_id (GDATA_ENTRY (data->folder)), NULL, + GDATA_TYPE_DOCUMENTS_FOLDER, NULL, &error); + g_assert_error (error, GDATA_SERVICE_ERROR, GDATA_SERVICE_ERROR_NOT_FOUND); + g_assert (updated_folder == NULL); + g_clear_error (&error); + + g_object_unref (data->folder); + data->folder = NULL; + + uhm_server_end_trace (mock_server); +} + +static void +test_delete_document (TempDocumentData *data, gconstpointer service) +{ + gboolean success; + GDataEntry *updated_document; + GError *error = NULL; + + gdata_test_mock_server_start_trace (mock_server, "delete-document"); + + g_assert (gdata_documents_entry_is_deleted (GDATA_DOCUMENTS_ENTRY (data->document)) == FALSE); + + /* Delete the document */ + success = gdata_service_delete_entry (GDATA_SERVICE (service), gdata_documents_service_get_primary_authorization_domain (), + GDATA_ENTRY (data->document), NULL, &error); + g_assert_no_error (error); + g_assert (success == TRUE); + g_clear_error (&error); + + /* Re-query for the document to ensure it's been deleted */ + updated_document = gdata_service_query_single_entry (GDATA_SERVICE (service), gdata_documents_service_get_primary_authorization_domain (), + gdata_entry_get_id (GDATA_ENTRY (data->document)), NULL, + G_OBJECT_TYPE (data->document), NULL, &error); + g_assert_error (error, GDATA_SERVICE_ERROR, GDATA_SERVICE_ERROR_NOT_FOUND); + g_assert (updated_document == NULL); + g_clear_error (&error); + + g_object_unref (data->document); + data->document = NULL; + + uhm_server_end_trace (mock_server); +} + +typedef struct { + TempFolderData parent; + GDataDocumentsSpreadsheet *spreadsheet_document; + GDataDocumentsPresentation *presentation_document; + GDataDocumentsText *text_document; + GDataDocumentsDocument *arbitrary_document; +} TempDocumentsData; + +static void +set_up_temp_documents (TempDocumentsData *data, gconstpointer service) +{ + GDataDocumentsEntry *document; + gchar *document_file_path; + GFile *document_file; + + /* Create a temporary folder */ + set_up_temp_folder ((TempFolderData*) data, service); + + gdata_test_mock_server_start_trace (mock_server, "setup-temp-documents"); + + /* Create some temporary documents of different types */ + document = GDATA_DOCUMENTS_ENTRY (gdata_documents_spreadsheet_new (NULL)); + gdata_entry_set_title (GDATA_ENTRY (document), "Temporary Spreadsheet"); + data->spreadsheet_document = GDATA_DOCUMENTS_SPREADSHEET ( + gdata_documents_service_add_entry_to_folder (GDATA_DOCUMENTS_SERVICE (service), document, ((TempFolderData*) data)->folder, + NULL, NULL) + ); + g_assert (GDATA_IS_DOCUMENTS_SPREADSHEET (data->spreadsheet_document)); + g_object_unref (document); + + document = GDATA_DOCUMENTS_ENTRY (gdata_documents_presentation_new (NULL)); + gdata_entry_set_title (GDATA_ENTRY (document), "Temporary Presentation"); + data->presentation_document = GDATA_DOCUMENTS_PRESENTATION ( + gdata_documents_service_add_entry_to_folder (GDATA_DOCUMENTS_SERVICE (service), document, ((TempFolderData*) data)->folder, + NULL, NULL) + ); + g_assert (GDATA_IS_DOCUMENTS_PRESENTATION (data->presentation_document)); + g_object_unref (document); + + document = GDATA_DOCUMENTS_ENTRY (gdata_documents_text_new (NULL)); + gdata_entry_set_title (GDATA_ENTRY (document), "Temporary Text Document"); + data->text_document = GDATA_DOCUMENTS_TEXT ( + gdata_documents_service_add_entry_to_folder (GDATA_DOCUMENTS_SERVICE (service), document, ((TempFolderData*) data)->folder, + NULL, NULL) + ); + g_assert (GDATA_IS_DOCUMENTS_TEXT (data->text_document)); + g_object_unref (document); + + document_file_path = g_test_build_filename (G_TEST_DIST, "test.odt", NULL); + document_file = g_file_new_for_path (document_file_path); + g_free (document_file_path); + + document = GDATA_DOCUMENTS_ENTRY (gdata_documents_document_new (NULL)); + gdata_entry_set_title (GDATA_ENTRY (document), "Temporary Arbitrary Document"); + data->arbitrary_document = _set_up_temp_document (document, GDATA_SERVICE (service), document_file); + g_assert (GDATA_IS_DOCUMENTS_DOCUMENT (data->arbitrary_document)); + g_object_unref (document); + + g_object_unref (document_file); + + uhm_server_end_trace (mock_server); +} + +static void +tear_down_temp_documents (TempDocumentsData *data, gconstpointer service) +{ + gdata_test_mock_server_start_trace (mock_server, "teardown-temp-documents"); + + /* Delete the documents */ + delete_entry (GDATA_DOCUMENTS_ENTRY (data->spreadsheet_document), GDATA_SERVICE (service)); + g_object_unref (data->spreadsheet_document); + + delete_entry (GDATA_DOCUMENTS_ENTRY (data->presentation_document), GDATA_SERVICE (service)); + g_object_unref (data->presentation_document); + + delete_entry (GDATA_DOCUMENTS_ENTRY (data->text_document), GDATA_SERVICE (service)); + g_object_unref (data->text_document); + + delete_entry (GDATA_DOCUMENTS_ENTRY (data->arbitrary_document), GDATA_SERVICE (service)); + g_object_unref (data->arbitrary_document); + + uhm_server_end_trace (mock_server); + + /* Delete the folder */ + tear_down_temp_folder ((TempFolderData*) data, service); +} + +static void +test_query_all_documents_with_folder (TempDocumentsData *data, gconstpointer service) +{ + GDataDocumentsFeed *feed; + GDataDocumentsQuery *query; + GError *error = NULL; + + gdata_test_mock_server_start_trace (mock_server, "query-all-documents-with-folder"); + + query = gdata_documents_query_new (NULL); + gdata_documents_query_set_show_folders (query, TRUE); + + feed = gdata_documents_service_query_documents (GDATA_DOCUMENTS_SERVICE (service), query, NULL, NULL, NULL, &error); + g_assert_no_error (error); + g_assert (GDATA_IS_FEED (feed)); + + /* TODO: Test the feed */ + + g_clear_error (&error); + g_object_unref (feed); + g_object_unref (query); + + uhm_server_end_trace (mock_server); +} + +static void +test_query_all_documents (TempDocumentsData *data, gconstpointer service) +{ + GDataDocumentsFeed *feed; + GError *error = NULL; + + gdata_test_mock_server_start_trace (mock_server, "query-all-documents"); + + feed = gdata_documents_service_query_documents (GDATA_DOCUMENTS_SERVICE (service), NULL, NULL, NULL, NULL, &error); + g_assert_no_error (error); + g_assert (GDATA_IS_FEED (feed)); + g_clear_error (&error); + + /* TODO: check entries and feed properties */ + + g_object_unref (feed); + + uhm_server_end_trace (mock_server); +} + +GDATA_ASYNC_CLOSURE_FUNCTIONS (temp_documents, TempDocumentsData); + +GDATA_ASYNC_TEST_FUNCTIONS (query_all_documents, TempDocumentsData, +G_STMT_START { + gdata_documents_service_query_documents_async (GDATA_DOCUMENTS_SERVICE (service), NULL, cancellable, NULL, NULL, + NULL, async_ready_callback, async_data); +} G_STMT_END, +G_STMT_START { + GDataDocumentsFeed *feed; + + feed = GDATA_DOCUMENTS_FEED (gdata_service_query_finish (GDATA_SERVICE (obj), async_result, &error)); + + if (error == NULL) { + g_assert (GDATA_IS_FEED (feed)); + /* TODO: Tests? */ + + g_object_unref (feed); + } else { + g_assert (feed == NULL); + } +} G_STMT_END); + +static void +test_query_all_documents_async_progress_closure (TempDocumentsData *documents_data, gconstpointer service) +{ + GDataAsyncProgressClosure *data = g_slice_new0 (GDataAsyncProgressClosure); + + gdata_test_mock_server_start_trace (mock_server, "query-all-documents-async-progress-closure"); + + data->main_loop = g_main_loop_new (NULL, TRUE); + + gdata_documents_service_query_documents_async (GDATA_DOCUMENTS_SERVICE (service), NULL, NULL, + (GDataQueryProgressCallback) gdata_test_async_progress_callback, + data, (GDestroyNotify) gdata_test_async_progress_closure_free, + (GAsyncReadyCallback) gdata_test_async_progress_finish_callback, data); + + g_main_loop_run (data->main_loop); + g_main_loop_unref (data->main_loop); + + /* Check that both callbacks were called exactly once */ + g_assert_cmpuint (data->progress_destroy_notify_count, ==, 1); + g_assert_cmpuint (data->async_ready_notify_count, ==, 1); + + g_slice_free (GDataAsyncProgressClosure, data); + + uhm_server_end_trace (mock_server); +} + +typedef enum { + UPLOAD_METADATA_ONLY, + UPLOAD_CONTENT_ONLY, + UPLOAD_CONTENT_AND_METADATA, +} PayloadType; +#define UPLOAD_PAYLOAD_TYPE_MAX UPLOAD_CONTENT_AND_METADATA + +const gchar *payload_type_names[] = { + "metadata-only", + "content-only", + "content-and-metadata", +}; + +typedef enum { + UPLOAD_IN_FOLDER, + UPLOAD_ROOT_FOLDER, +} FolderType; +#define UPLOAD_FOLDER_TYPE_MAX UPLOAD_ROOT_FOLDER + +const gchar *folder_type_names[] = { + "in-folder", + "root-folder", +}; + +typedef enum { + UPLOAD_RESUMABLE, + UPLOAD_NON_RESUMABLE, +} ResumableType; +#define UPLOAD_RESUMABLE_TYPE_MAX UPLOAD_NON_RESUMABLE + +const gchar *resumable_type_names[] = { + "resumable", + "non-resumable", +}; + +typedef enum { + UPLOAD_ODT_CONVERT, + UPLOAD_ODT_NO_CONVERT, + UPLOAD_BIN_NO_CONVERT, +} DocumentType; +#define UPLOAD_DOCUMENT_TYPE_MAX UPLOAD_BIN_NO_CONVERT + +const gchar *document_type_names[] = { + "odt-convert", + "odt-no-convert", + "bin-no-convert", +}; + +typedef struct { + PayloadType payload_type; + FolderType folder_type; + ResumableType resumable_type; + DocumentType document_type; + gchar *test_name; + + GDataDocumentsService *service; +} UploadDocumentTestParams; + +typedef struct { + GDataDocumentsFolder *folder; + GDataDocumentsDocument *new_document; +} UploadDocumentData; + +static void +set_up_upload_document (UploadDocumentData *data, gconstpointer _test_params) +{ + const UploadDocumentTestParams *test_params = _test_params; + gchar *trace_name; + + /* The trace name needs to take the test parameters into account. */ + trace_name = g_strdup_printf ("setup-upload-document_%s-%s-%s-%s", + payload_type_names[test_params->payload_type], + folder_type_names[test_params->folder_type], + resumable_type_names[test_params->resumable_type], + document_type_names[test_params->document_type]); + gdata_test_mock_server_start_trace (mock_server, trace_name); + g_free (trace_name); + + data->new_document = NULL; + + switch (test_params->folder_type) { + case UPLOAD_IN_FOLDER: + data->folder = create_folder (test_params->service, "Temporary Folder for Uploading Documents"); + break; + case UPLOAD_ROOT_FOLDER: + data->folder = NULL; + break; + default: + g_assert_not_reached (); + } + + uhm_server_end_trace (mock_server); +} + +static void +tear_down_upload_document (UploadDocumentData *data, gconstpointer _test_params) +{ + const UploadDocumentTestParams *test_params = _test_params; + gchar *trace_name; + + /* The trace name needs to take the test parameters into account. */ + trace_name = g_strdup_printf ("teardown-upload-document_%s-%s-%s-%s", + payload_type_names[test_params->payload_type], + folder_type_names[test_params->folder_type], + resumable_type_names[test_params->resumable_type], + document_type_names[test_params->document_type]); + gdata_test_mock_server_start_trace (mock_server, trace_name); + g_free (trace_name); + + /* Delete the new file */ + if (data->new_document != NULL) { + /* HACK: Query for the new document, as Google's servers appear to modify it behind our back if we don't upload both metadata and data + * when creating the document: http://code.google.com/a/google.com/p/apps-api-issues/issues/detail?id=2337. We have to wait a few + * seconds before trying this to allow the various Google servers to catch up with each other. */ + if (uhm_server_get_enable_online (mock_server) == TRUE) { + g_usleep (5 * G_USEC_PER_SEC); + } + + delete_entry (GDATA_DOCUMENTS_ENTRY (data->new_document), GDATA_SERVICE (test_params->service)); + g_object_unref (data->new_document); + } + + /* Delete the folder */ + if (data->folder != NULL) { + delete_entry (GDATA_DOCUMENTS_ENTRY (data->folder), GDATA_SERVICE (test_params->service)); + g_object_unref (data->folder); + } + + uhm_server_end_trace (mock_server); +} + +static void +test_upload (UploadDocumentData *data, gconstpointer _test_params) +{ + const UploadDocumentTestParams *test_params = _test_params; + + GDataDocumentsDocument *document = NULL; + const gchar *document_filename = NULL, *document_title = NULL; + gchar *trace_name; + GFile *document_file = NULL; + GFileInfo *file_info = NULL; + GDataDocumentsUploadQuery *upload_query = NULL; + GDataLink *edit_media_link; + GError *error = NULL; + + /* The trace name needs to take the test parameters into account. */ + trace_name = g_strdup_printf ("upload_%s-%s-%s-%s", + payload_type_names[test_params->payload_type], + folder_type_names[test_params->folder_type], + resumable_type_names[test_params->resumable_type], + document_type_names[test_params->document_type]); + gdata_test_mock_server_start_trace (mock_server, trace_name); + g_free (trace_name); + + upload_query = gdata_documents_upload_query_new (); + + /* File to upload. (Ignored if we're doing a metadata-only upload.) Also set the conversion type (ignored for non-resumable uploads). */ + switch (test_params->document_type) { + case UPLOAD_ODT_CONVERT: + /* ODT file. */ + document_filename = "test.odt"; + document_title = "test"; + gdata_documents_upload_query_set_convert (upload_query, TRUE); + break; + case UPLOAD_ODT_NO_CONVERT: + /* ODT file. */ + document_filename = "test.odt"; + document_title = "test"; + gdata_documents_upload_query_set_convert (upload_query, FALSE); + break; + case UPLOAD_BIN_NO_CONVERT: + /* Arbitrary binary file. */ + document_filename = "sample.ogg"; + document_title = "sample"; + gdata_documents_upload_query_set_convert (upload_query, FALSE); + break; + default: + g_assert_not_reached (); + } + + /* Upload content? */ + switch (test_params->payload_type) { + case UPLOAD_METADATA_ONLY: + document_filename = NULL; + document_title = NULL; + document_file = NULL; + file_info = NULL; + break; + case UPLOAD_CONTENT_ONLY: + case UPLOAD_CONTENT_AND_METADATA: { + gchar *document_file_path = g_test_build_filename (G_TEST_DIST, document_filename, NULL); + document_file = g_file_new_for_path (document_file_path); + g_free (document_file_path); + + file_info = g_file_query_info (document_file, + G_FILE_ATTRIBUTE_STANDARD_DISPLAY_NAME "," G_FILE_ATTRIBUTE_STANDARD_CONTENT_TYPE "," + G_FILE_ATTRIBUTE_STANDARD_SIZE, G_FILE_QUERY_INFO_NONE, NULL, &error); + g_assert_no_error (error); + + break; + } + default: + g_assert_not_reached (); + } + + /* Upload metadata? */ + switch (test_params->payload_type) { + case UPLOAD_CONTENT_ONLY: + document = NULL; + break; + case UPLOAD_METADATA_ONLY: + case UPLOAD_CONTENT_AND_METADATA: { + gchar *title; + + switch (test_params->document_type) { + case UPLOAD_ODT_CONVERT: + document = GDATA_DOCUMENTS_DOCUMENT (gdata_documents_text_new (NULL)); + break; + case UPLOAD_ODT_NO_CONVERT: + case UPLOAD_BIN_NO_CONVERT: + document = GDATA_DOCUMENTS_DOCUMENT (gdata_documents_document_new (NULL)); + break; + default: + g_assert_not_reached (); + } + + /* Build a title including the test details. */ + title = g_strdup_printf ("Test Upload file (%s)", test_params->test_name); + gdata_entry_set_title (GDATA_ENTRY (document), title); + g_free (title); + + break; + } + default: + g_assert_not_reached (); + } + + if (test_params->payload_type == UPLOAD_METADATA_ONLY) { + data->new_document = GDATA_DOCUMENTS_DOCUMENT (gdata_documents_service_add_entry_to_folder (test_params->service, + GDATA_DOCUMENTS_ENTRY (document), + data->folder, NULL, &error)); + g_assert_no_error (error); + } else { + GDataUploadStream *upload_stream; + GFileInputStream *file_stream; + + /* Prepare the upload stream */ + switch (test_params->resumable_type) { + case UPLOAD_NON_RESUMABLE: + upload_stream = gdata_documents_service_upload_document (test_params->service, document, + g_file_info_get_display_name (file_info), + g_file_info_get_content_type (file_info), data->folder, + NULL, &error); + break; + case UPLOAD_RESUMABLE: + gdata_documents_upload_query_set_folder (upload_query, data->folder); + + upload_stream = gdata_documents_service_upload_document_resumable (test_params->service, document, + g_file_info_get_display_name (file_info), + g_file_info_get_content_type (file_info), + g_file_info_get_size (file_info), upload_query, + NULL, &error); + + break; + default: + g_assert_not_reached (); + } + + g_assert_no_error (error); + g_assert (GDATA_IS_UPLOAD_STREAM (upload_stream)); + + g_object_unref (file_info); + + /* Open the file */ + file_stream = g_file_read (document_file, NULL, &error); + g_assert_no_error (error); + + /* Upload the document */ + g_output_stream_splice (G_OUTPUT_STREAM (upload_stream), G_INPUT_STREAM (file_stream), + G_OUTPUT_STREAM_SPLICE_CLOSE_SOURCE | G_OUTPUT_STREAM_SPLICE_CLOSE_TARGET, NULL, &error); + g_assert_no_error (error); + + /* Finish the upload */ + data->new_document = gdata_documents_service_finish_upload (test_params->service, upload_stream, &error); + g_assert_no_error (error); + + g_object_unref (upload_stream); + g_object_unref (file_stream); + } + + g_assert (GDATA_IS_DOCUMENTS_DOCUMENT (data->new_document)); /* note that this isn't entirely specific */ + + /* Verify the uploaded document is the same as the original */ + switch (test_params->payload_type) { + case UPLOAD_METADATA_ONLY: + case UPLOAD_CONTENT_AND_METADATA: + g_assert_cmpstr (gdata_entry_get_title (GDATA_ENTRY (data->new_document)), ==, gdata_entry_get_title (GDATA_ENTRY (document))); + break; + case UPLOAD_CONTENT_ONLY: + /* HACK: The title returned by the server varies depending on how we uploaded the document. */ + if (test_params->resumable_type == UPLOAD_NON_RESUMABLE) { + g_assert_cmpstr (gdata_entry_get_title (GDATA_ENTRY (data->new_document)), ==, document_title); + } else { + g_assert_cmpstr (gdata_entry_get_title (GDATA_ENTRY (data->new_document)), ==, "Untitled"); + } + + break; + default: + g_assert_not_reached (); + } + + /* Check it's been correctly converted/not converted and is of the right document type. */ + edit_media_link = gdata_entry_look_up_link (GDATA_ENTRY (data->new_document), GDATA_LINK_EDIT_MEDIA); + + switch (test_params->document_type) { + case UPLOAD_ODT_CONVERT: + g_assert (GDATA_IS_DOCUMENTS_TEXT (data->new_document)); + g_assert (g_str_has_prefix (gdata_documents_entry_get_resource_id (GDATA_DOCUMENTS_ENTRY (data->new_document)), "document:")); + g_assert_cmpstr (gdata_link_get_content_type (edit_media_link), ==, "text/html"); + break; + case UPLOAD_ODT_NO_CONVERT: + g_assert (GDATA_IS_DOCUMENTS_DOCUMENT (data->new_document)); + g_assert (g_str_has_prefix (gdata_documents_entry_get_resource_id (GDATA_DOCUMENTS_ENTRY (data->new_document)), "file:")); + g_assert_cmpstr (gdata_link_get_content_type (edit_media_link), ==, "application/vnd.oasis.opendocument.text"); + break; + case UPLOAD_BIN_NO_CONVERT: + g_assert (GDATA_IS_DOCUMENTS_DOCUMENT (data->new_document)); + g_assert (g_str_has_prefix (gdata_documents_entry_get_resource_id (GDATA_DOCUMENTS_ENTRY (data->new_document)), "file:")); + g_assert_cmpstr (gdata_link_get_content_type (edit_media_link), ==, "video/x-theora+ogg"); + break; + default: + g_assert_not_reached (); + } + + /* Check it's in the right folder. */ + switch (test_params->folder_type) { + case UPLOAD_IN_FOLDER: + /* HACK: When uploading content-only to a folder using the folder's resumable-create-media link, Google decides that it's + * not useful to list the folder in the returned entry XML for the new document (i.e. the server pretends the document's + * not in the folder you've just uploaded it to). Joy. */ + g_assert (test_params->payload_type == UPLOAD_CONTENT_ONLY || + check_document_is_in_folder (data->new_document, data->folder) == TRUE); + break; + case UPLOAD_ROOT_FOLDER: + /* Check root folder. */ + g_assert (check_document_is_in_root_folder (data->new_document) == TRUE); + break; + default: + g_assert_not_reached (); + } + + g_clear_error (&error); + g_clear_object (&upload_query); + g_clear_object (&document_file); + g_clear_object (&document); + + uhm_server_end_trace (mock_server); +} + +typedef struct { + PayloadType payload_type; + ResumableType resumable_type; + gchar *test_name; + + GDataDocumentsService *service; +} UpdateDocumentTestParams; + +typedef struct { + GDataDocumentsDocument *document; +} UpdateDocumentData; + +static void +set_up_update_document (UpdateDocumentData *data, gconstpointer _test_params) +{ + const UpdateDocumentTestParams *test_params = _test_params; + GDataDocumentsText *document; + gchar *title, *document_file_path, *trace_name; + GFile *document_file; + + /* The trace name needs to take the test parameters into account. */ + trace_name = g_strdup_printf ("setup-update-document_%s-%s", + payload_type_names[test_params->payload_type], + resumable_type_names[test_params->resumable_type]); + gdata_test_mock_server_start_trace (mock_server, trace_name); + g_free (trace_name); + + /* Create a document */ + document = gdata_documents_text_new (NULL); + title = g_strdup_printf ("Test Update file (%s)", test_params->test_name); + gdata_entry_set_title (GDATA_ENTRY (document), title); + g_free (title); + + document_file_path = g_test_build_filename (G_TEST_DIST, "test.odt", NULL); + document_file = g_file_new_for_path (document_file_path); + g_free (document_file_path); + + data->document = _set_up_temp_document (GDATA_DOCUMENTS_ENTRY (document), GDATA_SERVICE (test_params->service), document_file); + + g_object_unref (document_file); + g_object_unref (document); + + uhm_server_end_trace (mock_server); +} + +static void +tear_down_update_document (UpdateDocumentData *data, gconstpointer _test_params) +{ + const UpdateDocumentTestParams *test_params = _test_params; + gchar *trace_name; + + /* The trace name needs to take the test parameters into account. */ + trace_name = g_strdup_printf ("teardown-update-document_%s-%s", + payload_type_names[test_params->payload_type], + resumable_type_names[test_params->resumable_type]); + gdata_test_mock_server_start_trace (mock_server, trace_name); + g_free (trace_name); + + /* Delete the new file */ + if (data->document != NULL) { + /* HACK: Query for the new document, as Google's servers appear to modify it behind our back if we don't update both metadata and data + * when creating the document: http://code.google.com/a/google.com/p/apps-api-issues/issues/detail?id=2337. We have to wait a few + * seconds before trying this to allow the various Google servers to catch up with each other. */ + if (uhm_server_get_enable_online (mock_server) == TRUE) { + g_usleep (5 * G_USEC_PER_SEC); + } + + delete_entry (GDATA_DOCUMENTS_ENTRY (data->document), GDATA_SERVICE (test_params->service)); + g_object_unref (data->document); + } + + uhm_server_end_trace (mock_server); +} + +static void +test_update (UpdateDocumentData *data, gconstpointer _test_params) +{ + const UpdateDocumentTestParams *test_params = _test_params; + + GDataDocumentsDocument *updated_document; + gchar *original_title, *trace_name; + GError *error = NULL; + + /* The trace name needs to take the test parameters into account. */ + trace_name = g_strdup_printf ("update_%s-%s", + payload_type_names[test_params->payload_type], + resumable_type_names[test_params->resumable_type]); + gdata_test_mock_server_start_trace (mock_server, trace_name); + g_free (trace_name); + + switch (test_params->payload_type) { + case UPLOAD_METADATA_ONLY: + case UPLOAD_CONTENT_AND_METADATA: { + gchar *new_title; + + /* Change the title of the document */ + original_title = g_strdup (gdata_entry_get_title (GDATA_ENTRY (data->document))); + new_title = g_strdup_printf ("Updated Test Update file (%s)", test_params->test_name); + gdata_entry_set_title (GDATA_ENTRY (data->document), new_title); + g_free (new_title); + + break; + } + case UPLOAD_CONTENT_ONLY: + original_title = NULL; + break; + default: + g_assert_not_reached (); + } + + if (test_params->payload_type == UPLOAD_METADATA_ONLY) { + /* Update the document */ + updated_document = GDATA_DOCUMENTS_DOCUMENT (gdata_service_update_entry (GDATA_SERVICE (test_params->service), + gdata_documents_service_get_primary_authorization_domain (), + GDATA_ENTRY (data->document), NULL, &error)); + g_assert_no_error (error); + } else { + GDataUploadStream *upload_stream; + GFileInputStream *file_stream; + GFile *updated_document_file; + GFileInfo *file_info; + gchar *path = NULL; + + /* Prepare the updated file */ + path = g_test_build_filename (G_TEST_DIST, "test_updated.odt", NULL); + updated_document_file = g_file_new_for_path (path); + g_free (path); + + file_info = g_file_query_info (updated_document_file, G_FILE_ATTRIBUTE_STANDARD_DISPLAY_NAME "," + G_FILE_ATTRIBUTE_STANDARD_CONTENT_TYPE "," G_FILE_ATTRIBUTE_STANDARD_SIZE, G_FILE_QUERY_INFO_NONE, + NULL, &error); + g_assert_no_error (error); + + /* Prepare the upload stream */ + switch (test_params->resumable_type) { + case UPLOAD_NON_RESUMABLE: + upload_stream = gdata_documents_service_update_document (test_params->service, data->document, + g_file_info_get_display_name (file_info), + g_file_info_get_content_type (file_info), + NULL, &error); + break; + case UPLOAD_RESUMABLE: + upload_stream = gdata_documents_service_update_document_resumable (test_params->service, data->document, + g_file_info_get_display_name (file_info), + g_file_info_get_content_type (file_info), + g_file_info_get_size (file_info), NULL, &error); + break; + default: + g_assert_not_reached (); + } + + g_assert_no_error (error); + g_assert (GDATA_IS_UPLOAD_STREAM (upload_stream)); + + g_object_unref (file_info); + + /* Open the file */ + file_stream = g_file_read (updated_document_file, NULL, &error); + g_assert_no_error (error); + + g_object_unref (updated_document_file); + + /* Upload the updated document */ + g_output_stream_splice (G_OUTPUT_STREAM (upload_stream), G_INPUT_STREAM (file_stream), + G_OUTPUT_STREAM_SPLICE_CLOSE_SOURCE | G_OUTPUT_STREAM_SPLICE_CLOSE_TARGET, NULL, &error); + g_assert_no_error (error); + + /* Finish the upload */ + updated_document = gdata_documents_service_finish_upload (test_params->service, upload_stream, &error); + g_assert_no_error (error); + + g_object_unref (upload_stream); + g_object_unref (file_stream); + } + + g_assert (GDATA_IS_DOCUMENTS_TEXT (updated_document)); + + /* Check for success */ + switch (test_params->payload_type) { + case UPLOAD_METADATA_ONLY: + case UPLOAD_CONTENT_AND_METADATA: + g_assert_cmpstr (gdata_entry_get_title (GDATA_ENTRY (updated_document)), !=, original_title); + /* Fall through */ + case UPLOAD_CONTENT_ONLY: + g_assert_cmpstr (gdata_entry_get_title (GDATA_ENTRY (updated_document)), ==, + gdata_entry_get_title (GDATA_ENTRY (data->document))); + break; + default: + g_assert_not_reached (); + } + + g_free (original_title); + g_object_unref (updated_document); + + uhm_server_end_trace (mock_server); +} + +typedef struct { + TempDocumentData parent; + GDataDocumentsDocument *new_document; +} TempCopyDocumentData; + +static void +set_up_copy_document (TempCopyDocumentData *data, gconstpointer service) +{ + /* Create a temporary document. */ + set_up_temp_document_spreadsheet ((TempDocumentData*) data, service); + + data->new_document = NULL; +} + +static void +tear_down_copy_document (TempCopyDocumentData *data, gconstpointer service) +{ + gdata_test_mock_server_start_trace (mock_server, "teardown-copy-document"); + + /* Delete the copied document */ + delete_entry (GDATA_DOCUMENTS_ENTRY (data->new_document), GDATA_SERVICE (service)); + g_object_unref (data->new_document); + + uhm_server_end_trace (mock_server); + + /* Delete the folder */ + tear_down_temp_document ((TempDocumentData*) data, service); +} + +static void +test_copy_document (TempCopyDocumentData *data, gconstpointer service) +{ + GError *error = NULL; + + gdata_test_mock_server_start_trace (mock_server, "copy-document"); + + /* Copy the document */ + data->new_document = gdata_documents_service_copy_document (GDATA_DOCUMENTS_SERVICE (service), data->parent.document, NULL, &error); + g_assert_no_error (error); + g_assert (GDATA_IS_DOCUMENTS_SPREADSHEET (data->new_document)); + + /* Check their IDs are different but that their other properties (e.g. title) are the same. */ + g_assert_cmpstr (gdata_entry_get_id (GDATA_ENTRY (data->parent.document)), !=, gdata_entry_get_id (GDATA_ENTRY (data->new_document))); + g_assert_cmpstr (gdata_entry_get_title (GDATA_ENTRY (data->parent.document)), ==, gdata_entry_get_title (GDATA_ENTRY (data->new_document))); + + uhm_server_end_trace (mock_server); +} + +typedef struct { + GDataDocumentsFolder *folder; + GDataDocumentsDocument *document; +} FoldersData; + +static void +set_up_folders (FoldersData *data, GDataDocumentsService *service, gboolean initially_in_folder) +{ + GDataDocumentsFolder *folder; + GDataDocumentsFolder *root; + GDataDocumentsDocument *document, *new_document; + GDataUploadStream *upload_stream; + GFileInputStream *file_stream; + GFile *document_file; + GFileInfo *file_info; + gchar *path = NULL; + GError *error = NULL; + + root = GDATA_DOCUMENTS_FOLDER (gdata_service_query_single_entry (GDATA_SERVICE (service), + gdata_documents_service_get_primary_authorization_domain (), + "root", + NULL, + GDATA_TYPE_DOCUMENTS_FOLDER, + NULL, + NULL)); + /* Create a new folder for the tests */ + folder = gdata_documents_folder_new (NULL); + gdata_entry_set_title (GDATA_ENTRY (folder), "add_file_folder_move_folder"); + + /* Insert the folder */ + data->folder = GDATA_DOCUMENTS_FOLDER (gdata_documents_service_add_entry_to_folder (GDATA_DOCUMENTS_SERVICE (service), + GDATA_DOCUMENTS_ENTRY (folder), + root, + NULL, + &error)); + g_assert_no_error (error); + g_assert (GDATA_IS_DOCUMENTS_FOLDER (data->folder)); + + g_object_unref (folder); + + /* Create a new file for the tests */ + path = g_test_build_filename (G_TEST_DIST, "test.odt", NULL); + document_file = g_file_new_for_path (path); + g_free (path); + + document = GDATA_DOCUMENTS_DOCUMENT (gdata_documents_text_new (NULL)); + gdata_entry_set_title (GDATA_ENTRY (document), "add_file_folder_move_text"); + if (initially_in_folder) + add_folder_link_to_entry (GDATA_DOCUMENTS_ENTRY (document), root); + + g_object_unref (root); + + file_info = g_file_query_info (document_file, G_FILE_ATTRIBUTE_STANDARD_DISPLAY_NAME "," G_FILE_ATTRIBUTE_STANDARD_CONTENT_TYPE, + G_FILE_QUERY_INFO_NONE, NULL, &error); + g_assert_no_error (error); + + /* Prepare the upload stream */ + upload_stream = gdata_documents_service_upload_document (service, document, g_file_info_get_display_name (file_info), + g_file_info_get_content_type (file_info), + (initially_in_folder == TRUE) ? data->folder : NULL, NULL, &error); + g_assert_no_error (error); + g_assert (GDATA_IS_UPLOAD_STREAM (upload_stream)); + + g_object_unref (file_info); + g_object_unref (document); + + /* Open the file */ + file_stream = g_file_read (document_file, NULL, &error); + g_assert_no_error (error); + + g_object_unref (document_file); + + /* Upload the document */ + g_output_stream_splice (G_OUTPUT_STREAM (upload_stream), G_INPUT_STREAM (file_stream), + G_OUTPUT_STREAM_SPLICE_CLOSE_SOURCE | G_OUTPUT_STREAM_SPLICE_CLOSE_TARGET, NULL, &error); + g_assert_no_error (error); + + /* Finish the upload */ + new_document = gdata_documents_service_finish_upload (service, upload_stream, &error); + g_assert_no_error (error); + g_assert (GDATA_IS_DOCUMENTS_TEXT (new_document)); + + g_object_unref (upload_stream); + g_object_unref (file_stream); + + /* HACK: Query for the new document, as Google's servers appear to modify it behind our back when creating the document: + * http://code.google.com/a/google.com/p/apps-api-issues/issues/detail?id=2337. We have to wait a few seconds before trying this to allow the + * various Google servers to catch up with each other. */ + if (uhm_server_get_enable_online (mock_server) == TRUE) { + g_usleep (5 * G_USEC_PER_SEC); + } + + data->document = GDATA_DOCUMENTS_DOCUMENT (gdata_service_query_single_entry (GDATA_SERVICE (service), + gdata_documents_service_get_primary_authorization_domain (), + gdata_entry_get_id (GDATA_ENTRY (new_document)), NULL, + G_OBJECT_TYPE (new_document), NULL, NULL)); + g_assert (GDATA_IS_DOCUMENTS_TEXT (data->document)); +} + +static void +set_up_folders_add_to_folder (FoldersData *data, gconstpointer service) +{ + gdata_test_mock_server_start_trace (mock_server, "setup-folders-add-to-folder"); + set_up_folders (data, GDATA_DOCUMENTS_SERVICE (service), FALSE); + uhm_server_end_trace (mock_server); +} + +static void +tear_down_folders_add_to_folder (FoldersData *data, gconstpointer service) +{ + gdata_test_mock_server_start_trace (mock_server, "teardown-folders-add-to-folder"); + + delete_entry (GDATA_DOCUMENTS_ENTRY (data->document), GDATA_SERVICE (service)); + g_object_unref (data->document); + + delete_entry (GDATA_DOCUMENTS_ENTRY (data->folder), GDATA_SERVICE (service)); + g_object_unref (data->folder); + + uhm_server_end_trace (mock_server); +} + +static void +test_folders_add_to_folder (FoldersData *data, gconstpointer service) +{ + GDataDocumentsDocument *new_document; + GError *error = NULL; + + gdata_test_mock_server_start_trace (mock_server, "folders-add-to-folder"); + + /* Add the document to the folder */ + new_document = GDATA_DOCUMENTS_DOCUMENT (gdata_documents_service_add_entry_to_folder (GDATA_DOCUMENTS_SERVICE (service), + GDATA_DOCUMENTS_ENTRY (data->document), + data->folder, NULL, &error)); + g_assert_no_error (error); + g_assert (GDATA_IS_DOCUMENTS_TEXT (new_document)); + + /* Check it's still the same document */ + g_assert_cmpstr (gdata_entry_get_title (GDATA_ENTRY (new_document)), ==, gdata_entry_get_title (GDATA_ENTRY (data->document))); + g_assert (check_document_is_in_folder (new_document, data->folder) == TRUE); + + g_object_unref (new_document); + + uhm_server_end_trace (mock_server); +} + +GDATA_ASYNC_CLOSURE_FUNCTIONS (folders_add_to_folder, FoldersData); + +GDATA_ASYNC_TEST_FUNCTIONS (folders_add_to_folder, FoldersData, +G_STMT_START { + /* Add the document to the folder asynchronously */ + gdata_documents_service_add_entry_to_folder_async (GDATA_DOCUMENTS_SERVICE (service), GDATA_DOCUMENTS_ENTRY (data->document), + data->folder, cancellable, async_ready_callback, async_data); +} G_STMT_END, +G_STMT_START { + GDataDocumentsEntry *entry; + + entry = gdata_documents_service_add_entry_to_folder_finish (GDATA_DOCUMENTS_SERVICE (obj), async_result, &error); + + if (error == NULL) { + g_assert (GDATA_IS_DOCUMENTS_ENTRY (entry)); + + /* Check it's still the same document */ + g_assert_cmpstr (gdata_entry_get_title (GDATA_ENTRY (entry)), ==, gdata_entry_get_title (GDATA_ENTRY (data->document))); + g_assert (check_document_is_in_folder (GDATA_DOCUMENTS_DOCUMENT (entry), data->folder) == TRUE); + + g_object_unref (entry); + } else { + g_assert (entry == NULL); + } +} G_STMT_END); + +static void +set_up_folders_remove_from_folder (FoldersData *data, gconstpointer service) +{ + gdata_test_mock_server_start_trace (mock_server, "setup-folders-remove-from-folder"); + set_up_folders (data, GDATA_DOCUMENTS_SERVICE (service), TRUE); + uhm_server_end_trace (mock_server); +} + +static void +tear_down_folders_remove_from_folder (FoldersData *data, gconstpointer service) +{ + tear_down_folders_add_to_folder (data, service); +} + +static void +test_folders_remove_from_folder (FoldersData *data, gconstpointer service) +{ + GDataDocumentsDocument *new_document; + GError *error = NULL; + + gdata_test_mock_server_start_trace (mock_server, "folders-remove-from-folder"); + + /* Remove the document from the folder */ + new_document = GDATA_DOCUMENTS_DOCUMENT (gdata_documents_service_remove_entry_from_folder (GDATA_DOCUMENTS_SERVICE (service), + GDATA_DOCUMENTS_ENTRY (data->document), + data->folder, NULL, &error)); + g_assert_no_error (error); + g_assert (GDATA_IS_DOCUMENTS_TEXT (new_document)); + + /* Check it's still the same document */ + g_assert_cmpstr (gdata_entry_get_title (GDATA_ENTRY (new_document)), ==, gdata_entry_get_title (GDATA_ENTRY (data->document))); + g_assert (check_document_is_in_folder (new_document, data->folder) == FALSE); + + g_object_unref (new_document); + + uhm_server_end_trace (mock_server); +} + +GDATA_ASYNC_CLOSURE_FUNCTIONS (folders_remove_from_folder, FoldersData); + +GDATA_ASYNC_TEST_FUNCTIONS (folders_remove_from_folder, FoldersData, +G_STMT_START { + /* Remove the document from the folder asynchronously */ + gdata_documents_service_remove_entry_from_folder_async (GDATA_DOCUMENTS_SERVICE (service), GDATA_DOCUMENTS_ENTRY (data->document), + data->folder, cancellable, async_ready_callback, async_data); +} G_STMT_END, +G_STMT_START { + GDataDocumentsEntry *entry; + GDataEntry *new_entry; + + entry = gdata_documents_service_remove_entry_from_folder_finish (GDATA_DOCUMENTS_SERVICE (obj), async_result, &error); + + if (error == NULL) { + g_assert (GDATA_IS_DOCUMENTS_ENTRY (entry)); + + /* Check it's still the same document */ + g_assert_cmpstr (gdata_entry_get_title (GDATA_ENTRY (entry)), ==, gdata_entry_get_title (GDATA_ENTRY (data->document))); + g_assert (check_document_is_in_folder (GDATA_DOCUMENTS_DOCUMENT (entry), data->folder) == FALSE); + + g_object_unref (entry); + } else { + g_assert (entry == NULL); + } + + /* Since this code is called for the cancellation tests, we don't know exactly how many requests will be made + * before cancellation kicks in; so the epilogue request (below) needs to be in a separate trace file. */ + uhm_server_end_trace (mock_server); + gdata_test_mock_server_start_trace (mock_server, "folders_remove_from_folder-async-epilogue"); + + /* With the longer cancellation timeouts, the server can somehow modify the document without getting around to completely + * deleting it; hence its ETag changes, but it isn't marked as deleted. Joy of joys. Re-query for the document after every + * attempt to ensure we've always got the latest ETag value. */ + new_entry = gdata_service_query_single_entry (GDATA_SERVICE (obj), gdata_documents_service_get_primary_authorization_domain (), + gdata_entry_get_id (GDATA_ENTRY (data->document)), NULL, + G_OBJECT_TYPE (data->document), NULL, NULL); + g_assert (GDATA_IS_DOCUMENTS_ENTRY (new_entry)); + + g_object_unref (data->document); + data->document = GDATA_DOCUMENTS_DOCUMENT (new_entry); +} G_STMT_END); + +static void +_test_download_document (GDataDocumentsDocument *document, GDataService *service) +{ + GDataDownloadStream *download_stream; + GFileOutputStream *output_stream; + GFile *destination_file; + GFileInfo *file_info; + const gchar *destination_file_extension; + gchar *destination_file_name, *destination_file_path; + GError *error = NULL; + + if (GDATA_IS_DOCUMENTS_PRESENTATION (document)) { + /* Presentation */ + destination_file_extension = "odp"; + download_stream = gdata_documents_document_download (document, GDATA_DOCUMENTS_SERVICE (service), + GDATA_DOCUMENTS_PRESENTATION_PPT, NULL, &error); + } else if (GDATA_IS_DOCUMENTS_SPREADSHEET (document)) { + /* Spreadsheet */ + destination_file_extension = "ods"; + download_stream = gdata_documents_document_download (document, GDATA_DOCUMENTS_SERVICE (service), + GDATA_DOCUMENTS_SPREADSHEET_ODS, NULL, &error); + } else if (GDATA_IS_DOCUMENTS_TEXT (document)) { + /* Text document */ + destination_file_extension = "odt"; + download_stream = gdata_documents_document_download (document, GDATA_DOCUMENTS_SERVICE (service), + GDATA_DOCUMENTS_TEXT_ODT, NULL, &error); + } else { + /* Error! */ + g_assert_not_reached (); + } + + g_assert_no_error (error); + g_clear_error (&error); + + /* Find a destination file */ + destination_file_name = g_strdup_printf ("%s.%s", gdata_documents_entry_get_resource_id (GDATA_DOCUMENTS_ENTRY (document)), + destination_file_extension); + destination_file_path = g_build_filename (g_get_tmp_dir (), destination_file_name, NULL); + g_free (destination_file_name); + + destination_file = g_file_new_for_path (destination_file_path); + g_free (destination_file_path); + + /* Download the file */ + output_stream = g_file_replace (destination_file, NULL, FALSE, G_FILE_CREATE_REPLACE_DESTINATION, NULL, &error); + g_assert_no_error (error); + g_clear_error (&error); + + g_output_stream_splice (G_OUTPUT_STREAM (output_stream), G_INPUT_STREAM (download_stream), + G_OUTPUT_STREAM_SPLICE_CLOSE_SOURCE | G_OUTPUT_STREAM_SPLICE_CLOSE_TARGET, NULL, &error); + g_assert_no_error (error); + g_clear_error (&error); + + g_object_unref (output_stream); + g_object_unref (download_stream); + + /* Check the file size. + * Checking the content types turns out to be quite involved, and not worth doing, as it depends on the local user's content type DB. */ + file_info = g_file_query_info (destination_file, G_FILE_ATTRIBUTE_STANDARD_SIZE, G_FILE_QUERY_INFO_NONE, NULL, &error); + g_assert_no_error (error); + g_clear_error (&error); + + g_assert_cmpint (g_file_info_get_size (file_info), >, 0); + + g_object_unref (file_info); + + /* Delete the file (shouldn't cause the test to fail if this fails) */ + g_file_delete (destination_file, NULL, NULL); + g_object_unref (destination_file); +} + +static void +test_download_document (TempDocumentsData *data, gconstpointer service) +{ + gdata_test_mock_server_start_trace (mock_server, "download-document"); + + _test_download_document (GDATA_DOCUMENTS_DOCUMENT (data->spreadsheet_document), GDATA_SERVICE (service)); + _test_download_document (GDATA_DOCUMENTS_DOCUMENT (data->presentation_document), GDATA_SERVICE (service)); + _test_download_document (GDATA_DOCUMENTS_DOCUMENT (data->text_document), GDATA_SERVICE (service)); + _test_download_document (GDATA_DOCUMENTS_DOCUMENT (data->arbitrary_document), GDATA_SERVICE (service)); + + uhm_server_end_trace (mock_server); +} + +static void +test_download_thumbnail (TempDocumentData *data, gconstpointer service) +{ + const gchar *thumbnail_uri; + GDataDownloadStream *download_stream; + gchar *destination_file_name, *destination_file_path; + GFile *destination_file; + GFileOutputStream *file_stream; + gssize transfer_size; + GError *error = NULL; + + thumbnail_uri = gdata_documents_document_get_thumbnail_uri (data->document); + + /* Google takes many minutes to generate thumbnails for uploaded documents, so with our current testing strategy of creating fresh documents + * for each test, this particular test is fairly useless. */ + if (thumbnail_uri == NULL) { + g_test_message ("Skipping thumbnail download test because document ‘%s’ doesn’t have a thumbnail.", + gdata_documents_entry_get_resource_id (GDATA_DOCUMENTS_ENTRY (data->document))); + return; + } + + gdata_test_mock_server_start_trace (mock_server, "download-thumbnail"); + + /* Download the thumbnail to a file for testing (in case we weren't compiled with GdkPixbuf support) */ + download_stream = GDATA_DOWNLOAD_STREAM (gdata_download_stream_new (GDATA_SERVICE (service), NULL, thumbnail_uri, NULL)); + g_assert (GDATA_IS_DOWNLOAD_STREAM (download_stream)); + + /* Prepare a file to write the data to */ + destination_file_name = g_strdup_printf ("%s_thumbnail.jpg", gdata_documents_entry_get_resource_id (GDATA_DOCUMENTS_ENTRY (data->document))); + destination_file_path = g_build_filename (g_get_tmp_dir (), destination_file_name, NULL); + g_free (destination_file_name); + destination_file = g_file_new_for_path (destination_file_path); + g_free (destination_file_path); + + /* Download the file */ + file_stream = g_file_replace (destination_file, NULL, FALSE, G_FILE_CREATE_REPLACE_DESTINATION, NULL, &error); + g_assert_no_error (error); + g_assert (G_IS_FILE_OUTPUT_STREAM (file_stream)); + + transfer_size = g_output_stream_splice (G_OUTPUT_STREAM (file_stream), G_INPUT_STREAM (download_stream), + G_OUTPUT_STREAM_SPLICE_CLOSE_SOURCE | G_OUTPUT_STREAM_SPLICE_CLOSE_TARGET, NULL, &error); + g_assert_no_error (error); + g_assert_cmpint (transfer_size, >, 0); + + g_object_unref (file_stream); + g_object_unref (download_stream); + + /* Delete the file (shouldn't cause the test to fail if this fails) */ + g_file_delete (destination_file, NULL, NULL); + g_object_unref (destination_file); + +#ifdef HAVE_GDK_PIXBUF + /* Test downloading all thumbnails directly into GdkPixbufs, and check that they're all the correct size */ + { + GdkPixbuf *pixbuf; + + /* Prepare a new download stream */ + download_stream = GDATA_DOWNLOAD_STREAM (gdata_download_stream_new (GDATA_SERVICE (service), NULL, thumbnail_uri, NULL)); + g_assert (GDATA_IS_DOWNLOAD_STREAM (download_stream)); + + /* Download into a new GdkPixbuf */ + pixbuf = gdk_pixbuf_new_from_stream (G_INPUT_STREAM (download_stream), NULL, &error); + g_assert_no_error (error); + g_assert (GDK_IS_PIXBUF (pixbuf)); + + g_object_unref (download_stream); + + /* Check the dimensions are as expected. */ + g_assert_cmpint (gdk_pixbuf_get_width (pixbuf), ==, 10); + g_assert_cmpint (gdk_pixbuf_get_height (pixbuf), ==, 10); + + g_object_unref (pixbuf); + } +#endif /* HAVE_GDK_PIXBUF */ + + uhm_server_end_trace (mock_server); +} + +static void +test_access_rule_insert (TempDocumentData *data, gconstpointer service) +{ + GDataDocumentsAccessRule *access_rule, *new_access_rule; + GDataLink *_link; + GError *error = NULL; + + gdata_test_mock_server_start_trace (mock_server, "access-rule-insert"); + + /* New access rule */ + access_rule = gdata_documents_access_rule_new (NULL); + gdata_access_rule_set_role (GDATA_ACCESS_RULE (access_rule), GDATA_DOCUMENTS_ACCESS_ROLE_WRITER); + gdata_access_rule_set_scope (GDATA_ACCESS_RULE (access_rule), GDATA_ACCESS_SCOPE_USER, "libgdata.test@gmail.com"); + + /* Set access rules */ + _link = gdata_entry_look_up_link (GDATA_ENTRY (data->document), GDATA_LINK_ACCESS_CONTROL_LIST); + g_assert (_link != NULL); + + new_access_rule = GDATA_DOCUMENTS_ACCESS_RULE (gdata_service_insert_entry (GDATA_SERVICE (service), + gdata_documents_service_get_primary_authorization_domain (), + gdata_link_get_uri (_link), + GDATA_ENTRY (access_rule), NULL, &error)); + g_assert_no_error (error); + g_assert (GDATA_IS_DOCUMENTS_ACCESS_RULE (new_access_rule)); + g_clear_error (&error); + + /* TODO: Check if everything is as it should be */ + + g_object_unref (access_rule); + g_object_unref (new_access_rule); + + uhm_server_end_trace (mock_server); +} + +static void +test_folder_parser_normal (void) +{ + GDataDocumentsFolder *folder; + gchar *path; + GDataAuthor *author; + GError *error = NULL; + + folder = GDATA_DOCUMENTS_FOLDER (gdata_parsable_new_from_xml (GDATA_TYPE_DOCUMENTS_FOLDER, + "" + "" + "https://docs.google.com/feeds/id/folder%3A0BzY2jgHHwMwYalFhbjhVT3dyams" + "2012-04-14T09:12:19.418Z" + "2012-04-14T09:12:19.418Z" + "2012-04-14T09:12:20.055Z" + "" + "Temporary Folder" + "" + "" + "" + "" + "" + "" + "" + "" + "libgdata.documents" + "libgdata.documents@gmail.com" + "" + "folder:0BzY2jgHHwMwYalFhbjhVT3dyams" + "" + "libgdata.documents" + "libgdata.documents@gmail.com" + "" + "0" + "" + "" + "", -1, &error)); + g_assert_no_error (error); + g_assert (GDATA_IS_DOCUMENTS_FOLDER (folder)); + gdata_test_compare_kind (GDATA_ENTRY (folder), "http://schemas.google.com/docs/2007#folder", NULL); + + /* Check IDs. */ + g_assert_cmpstr (gdata_documents_entry_get_resource_id (GDATA_DOCUMENTS_ENTRY (folder)), ==, "folder:0BzY2jgHHwMwYalFhbjhVT3dyams"); + + path = gdata_documents_entry_get_path (GDATA_DOCUMENTS_ENTRY (folder)); + g_assert_cmpstr (path, ==, "/0BzY2jgHHwMwYalFhbjhVT3dyams"); + g_free (path); + + /* Check dates. */ + G_GNUC_BEGIN_IGNORE_DEPRECATIONS + g_assert_cmpuint (gdata_documents_entry_get_edited (GDATA_DOCUMENTS_ENTRY (folder)), ==, 1334394740); + G_GNUC_END_IGNORE_DEPRECATIONS + g_assert_cmpuint (gdata_documents_entry_get_last_viewed (GDATA_DOCUMENTS_ENTRY (folder)), ==, -1); + + author = gdata_documents_entry_get_last_modified_by (GDATA_DOCUMENTS_ENTRY (folder)); + + g_assert_cmpstr (gdata_author_get_name (author), ==, "libgdata.documents"); + g_assert_cmpstr (gdata_author_get_uri (author), ==, NULL); + g_assert_cmpstr (gdata_author_get_email_address (author), ==, "libgdata.documents@gmail.com"); + + /* Check permissions/quotas. */ + g_assert (gdata_documents_entry_writers_can_invite (GDATA_DOCUMENTS_ENTRY (folder)) == FALSE); + g_assert_cmpuint (gdata_documents_entry_get_quota_used (GDATA_DOCUMENTS_ENTRY (folder)), ==, 0); + + /* Check miscellany. */ + g_assert (gdata_documents_entry_is_deleted (GDATA_DOCUMENTS_ENTRY (folder)) == FALSE); + + g_object_unref (folder); +} + +static void +test_query_etag (void) +{ + GDataDocumentsQuery *query = gdata_documents_query_new (NULL); + + /* Test that setting any property will unset the ETag */ + g_test_bug ("613529"); + +#define CHECK_ETAG(C) \ + gdata_query_set_etag (GDATA_QUERY (query), "foobar"); \ + (C); \ + g_assert (gdata_query_get_etag (GDATA_QUERY (query)) == NULL); + + CHECK_ETAG (gdata_documents_query_set_show_deleted (query, FALSE)) + CHECK_ETAG (gdata_documents_query_set_show_folders (query, TRUE)) + CHECK_ETAG (gdata_documents_query_set_folder_id (query, "this-is-an-id")) + CHECK_ETAG (gdata_documents_query_set_title (query, "Title", FALSE)) + CHECK_ETAG (gdata_documents_query_add_reader (query, "foo@example.com")) + CHECK_ETAG (gdata_documents_query_add_collaborator (query, "foo@example.com")) + +#undef CHECK_ETAG + + g_object_unref (query); +} + +/* Test getting and setting the GDataDocumentsUploadQuery:convert property */ +static void +test_upload_query_properties_convert (void) +{ + gboolean convert; + GDataDocumentsUploadQuery *query; + + /* Verifying the normal state of the property in a newly-constructed instance of GDataDocumentsUploadQuery */ + query = gdata_documents_upload_query_new (); + g_assert (gdata_documents_upload_query_get_convert (query) == TRUE); + + g_object_get (query, "convert", &convert, NULL); + g_assert (convert == TRUE); + + /* Setting the property. */ + gdata_documents_upload_query_set_convert (query, FALSE); + g_assert (gdata_documents_upload_query_get_convert (query) == FALSE); + + /* Setting it another way. */ + g_object_set (query, "convert", TRUE, NULL); + g_assert (gdata_documents_upload_query_get_convert (query) == TRUE); + + g_object_unref (query); +} + +/* Here we hardcode the feed URI, but it should really be extracted from a document feed, as the GDATA_LINK_BATCH link */ +#define BATCH_URI "https://docs.google.com/feeds/default/private/full/batch" + +static void +test_batch (gconstpointer service) +{ + GDataBatchOperation *operation; + GDataService *service2; + GDataDocumentsText *doc, *doc2, *doc3; + GDataEntry *inserted_entry, *inserted_entry_updated, *inserted_entry2, *inserted_entry2_updated, *inserted_entry3; + gchar *feed_uri; + guint op_id, op_id2, op_id3; + GError *error = NULL, *entry_error = NULL; + + gdata_test_mock_server_start_trace (mock_server, "batch"); + + operation = gdata_batchable_create_operation (GDATA_BATCHABLE (service), gdata_documents_service_get_primary_authorization_domain (), + BATCH_URI); + + /* Check the properties of the operation */ + g_assert (gdata_batch_operation_get_service (operation) == service); + g_assert_cmpstr (gdata_batch_operation_get_feed_uri (operation), ==, BATCH_URI); + + g_object_get (operation, + "service", &service2, + "feed-uri", &feed_uri, + NULL); + + g_assert (service2 == service); + g_assert_cmpstr (feed_uri, ==, BATCH_URI); + + g_object_unref (service2); + g_free (feed_uri); + + /* Run a singleton batch operation to insert a new entry */ + doc = gdata_documents_text_new (NULL); + gdata_entry_set_title (GDATA_ENTRY (doc), "My First Document"); + + gdata_test_batch_operation_insertion (operation, GDATA_ENTRY (doc), &inserted_entry, NULL); + g_assert (gdata_test_batch_operation_run (operation, NULL, &error) == TRUE); + g_assert_no_error (error); + + g_clear_error (&error); + g_object_unref (operation); + g_object_unref (doc); + + /* Run another batch operation to insert another entry and query the previous one */ + doc2 = gdata_documents_text_new (NULL); + gdata_entry_set_title (GDATA_ENTRY (doc2), "I'm a poet and I didn't know it"); + + operation = gdata_batchable_create_operation (GDATA_BATCHABLE (service), gdata_documents_service_get_primary_authorization_domain (), + BATCH_URI); + op_id = gdata_test_batch_operation_insertion (operation, GDATA_ENTRY (doc2), &inserted_entry2, NULL); + op_id2 = gdata_test_batch_operation_query (operation, gdata_entry_get_id (inserted_entry), GDATA_TYPE_DOCUMENTS_TEXT, inserted_entry, NULL, + NULL); + g_assert_cmpuint (op_id, !=, op_id2); + + g_assert (gdata_test_batch_operation_run (operation, NULL, &error) == TRUE); + g_assert_no_error (error); + + g_clear_error (&error); + g_object_unref (operation); + g_object_unref (doc2); + + /* Run another batch operation to query one of the entries we just created, since it seems that the ETags for documents change for no + * apparent reason when you're not looking. */ + operation = gdata_batchable_create_operation (GDATA_BATCHABLE (service), gdata_documents_service_get_primary_authorization_domain (), + BATCH_URI); + gdata_test_batch_operation_query (operation, gdata_entry_get_id (inserted_entry), GDATA_TYPE_DOCUMENTS_TEXT, inserted_entry, + &inserted_entry_updated, NULL); + + g_assert (gdata_test_batch_operation_run (operation, NULL, &error) == TRUE); + g_assert_no_error (error); + + g_clear_error (&error); + g_object_unref (operation); + g_object_unref (inserted_entry); + + /* Run another batch operation to query the other entry we just created. It would be sensible to batch this query together with the previous + * one, seeing as we're testing _batch_ functionality. Funnily enough, the combination of two idempotent operations changes the ETags and + * makes the whole effort worthless. */ + operation = gdata_batchable_create_operation (GDATA_BATCHABLE (service), gdata_documents_service_get_primary_authorization_domain (), + BATCH_URI); + gdata_test_batch_operation_query (operation, gdata_entry_get_id (inserted_entry2), GDATA_TYPE_DOCUMENTS_TEXT, inserted_entry2, + &inserted_entry2_updated, NULL); + + g_assert (gdata_test_batch_operation_run (operation, NULL, &error) == TRUE); + g_assert_no_error (error); + + g_clear_error (&error); + g_object_unref (operation); + + /* Run another batch operation to delete the first entry and a fictitious one to test error handling, and update the second entry */ + gdata_entry_set_title (inserted_entry2_updated, "War & Peace"); + doc3 = gdata_documents_text_new ("foobar"); + + operation = gdata_batchable_create_operation (GDATA_BATCHABLE (service), gdata_documents_service_get_primary_authorization_domain (), + BATCH_URI); + op_id = gdata_test_batch_operation_deletion (operation, inserted_entry_updated, NULL); + op_id2 = gdata_test_batch_operation_deletion (operation, GDATA_ENTRY (doc3), &entry_error); + op_id3 = gdata_test_batch_operation_update (operation, inserted_entry2_updated, &inserted_entry3, NULL); + g_assert_cmpuint (op_id, !=, op_id2); + g_assert_cmpuint (op_id, !=, op_id3); + g_assert_cmpuint (op_id2, !=, op_id3); + + g_assert (gdata_test_batch_operation_run (operation, NULL, &error) == TRUE); + g_assert_no_error (error); + + g_assert_error (entry_error, GDATA_SERVICE_ERROR, GDATA_SERVICE_ERROR_PROTOCOL_ERROR); + + g_clear_error (&error); + g_clear_error (&entry_error); + g_object_unref (operation); + g_object_unref (inserted_entry_updated); + g_object_unref (inserted_entry2_updated); + g_object_unref (doc3); + + /* Run another batch operation to update the second entry with the wrong ETag (i.e. pass the old version of the entry to the batch operation + * to test error handling */ + operation = gdata_batchable_create_operation (GDATA_BATCHABLE (service), gdata_documents_service_get_primary_authorization_domain (), + BATCH_URI); + gdata_test_batch_operation_update (operation, inserted_entry2, NULL, &entry_error); + g_assert (gdata_test_batch_operation_run (operation, NULL, &error) == TRUE); + g_assert_no_error (error); + + g_assert_error (entry_error, GDATA_SERVICE_ERROR, GDATA_SERVICE_ERROR_CONFLICT); + + g_clear_error (&error); + g_clear_error (&entry_error); + g_object_unref (operation); + g_object_unref (inserted_entry2); + + /* Run a final batch operation to delete the second entry */ + operation = gdata_batchable_create_operation (GDATA_BATCHABLE (service), gdata_documents_service_get_primary_authorization_domain (), + BATCH_URI); + gdata_test_batch_operation_deletion (operation, inserted_entry3, NULL); + g_assert (gdata_test_batch_operation_run (operation, NULL, &error) == TRUE); + g_assert_no_error (error); + + g_clear_error (&error); + g_object_unref (operation); + g_object_unref (inserted_entry3); + + uhm_server_end_trace (mock_server); +} + +typedef struct { + GDataDocumentsEntry *new_doc; +} BatchAsyncData; + +static void +set_up_batch_async (BatchAsyncData *data, gconstpointer service) +{ + GDataDocumentsText *doc; + gchar *upload_uri; + GError *error = NULL; + + gdata_test_mock_server_start_trace (mock_server, "setup-batch-async"); + + /* Insert a new document which we can query asyncly */ + doc = gdata_documents_text_new (NULL); + gdata_entry_set_title (GDATA_ENTRY (doc), "A View from the Bridge"); + + upload_uri = gdata_documents_service_get_upload_uri (NULL); + data->new_doc = GDATA_DOCUMENTS_ENTRY (gdata_service_insert_entry (GDATA_SERVICE (service), + gdata_documents_service_get_primary_authorization_domain (), + upload_uri, GDATA_ENTRY (doc), NULL, &error)); + g_free (upload_uri); + + g_assert_no_error (error); + g_assert (GDATA_IS_DOCUMENTS_TEXT (data->new_doc)); + g_clear_error (&error); + + g_object_unref (doc); + + uhm_server_end_trace (mock_server); +} + +static void +test_batch_async_cb (GDataBatchOperation *operation, GAsyncResult *async_result, GMainLoop *main_loop) +{ + GError *error = NULL; + + /* Clear all pending events (such as callbacks for the operations) */ + while (g_main_context_iteration (NULL, FALSE) == TRUE); + + g_assert (gdata_test_batch_operation_run_finish (operation, async_result, &error) == TRUE); + g_assert_no_error (error); + g_clear_error (&error); + + g_main_loop_quit (main_loop); +} + +static void +test_batch_async (BatchAsyncData *data, gconstpointer service) +{ + GDataBatchOperation *operation; + GMainLoop *main_loop; + + gdata_test_mock_server_start_trace (mock_server, "batch-async"); + + /* Run an async query operation on the document */ + operation = gdata_batchable_create_operation (GDATA_BATCHABLE (service), gdata_documents_service_get_primary_authorization_domain (), + BATCH_URI); + gdata_test_batch_operation_query (operation, gdata_entry_get_id (GDATA_ENTRY (data->new_doc)), GDATA_TYPE_DOCUMENTS_TEXT, + GDATA_ENTRY (data->new_doc), NULL, NULL); + + main_loop = g_main_loop_new (NULL, TRUE); + + gdata_batch_operation_run_async (operation, NULL, (GAsyncReadyCallback) test_batch_async_cb, main_loop); + g_main_loop_run (main_loop); + + g_main_loop_unref (main_loop); + g_object_unref (operation); + + uhm_server_end_trace (mock_server); +} + +static void +test_batch_async_cancellation_cb (GDataBatchOperation *operation, GAsyncResult *async_result, GMainLoop *main_loop) +{ + GError *error = NULL; + + /* Clear all pending events (such as callbacks for the operations) */ + while (g_main_context_iteration (NULL, FALSE) == TRUE); + + g_assert (gdata_test_batch_operation_run_finish (operation, async_result, &error) == FALSE); + g_assert_error (error, G_IO_ERROR, G_IO_ERROR_CANCELLED); + g_clear_error (&error); + + g_main_loop_quit (main_loop); +} + +static void +test_batch_async_cancellation (BatchAsyncData *data, gconstpointer service) +{ + GDataBatchOperation *operation; + GMainLoop *main_loop; + GCancellable *cancellable; + GError *error = NULL; + + gdata_test_mock_server_start_trace (mock_server, "batch-async-cancellation"); + + /* Run an async query operation on the document */ + operation = gdata_batchable_create_operation (GDATA_BATCHABLE (service), gdata_documents_service_get_primary_authorization_domain (), + BATCH_URI); + gdata_test_batch_operation_query (operation, gdata_entry_get_id (GDATA_ENTRY (data->new_doc)), GDATA_TYPE_DOCUMENTS_TEXT, + GDATA_ENTRY (data->new_doc), NULL, &error); + + main_loop = g_main_loop_new (NULL, TRUE); + cancellable = g_cancellable_new (); + + gdata_batch_operation_run_async (operation, cancellable, (GAsyncReadyCallback) test_batch_async_cancellation_cb, main_loop); + g_cancellable_cancel (cancellable); /* this should cancel the operation before it even starts, as we haven't run the main loop yet */ + + g_main_loop_run (main_loop); + + g_assert_error (error, G_IO_ERROR, G_IO_ERROR_CANCELLED); + g_clear_error (&error); + + g_main_loop_unref (main_loop); + g_object_unref (cancellable); + g_object_unref (operation); + + uhm_server_end_trace (mock_server); +} + +static void +tear_down_batch_async (BatchAsyncData *data, gconstpointer service) +{ + gdata_test_mock_server_start_trace (mock_server, "teardown-batch-async"); + + delete_entry (GDATA_DOCUMENTS_ENTRY (data->new_doc), GDATA_SERVICE (service)); + g_object_unref (data->new_doc); + + uhm_server_end_trace (mock_server); +} + +static void +mock_server_notify_resolver_cb (GObject *object, GParamSpec *pspec, gpointer user_data) +{ + UhmServer *server; + UhmResolver *resolver; + + server = UHM_SERVER (object); + + /* Set up the expected domain names here. This should technically be split up between + * the different unit test suites, but that's too much effort. */ + resolver = uhm_server_get_resolver (server); + + if (resolver != NULL) { + const gchar *ip_address = uhm_server_get_address (server); + + uhm_resolver_add_A (resolver, "www.google.com", ip_address); + uhm_resolver_add_A (resolver, "docs.google.com", ip_address); + uhm_resolver_add_A (resolver, "lh3.googleusercontent.com", ip_address); + uhm_resolver_add_A (resolver, "lh5.googleusercontent.com", ip_address); + uhm_resolver_add_A (resolver, "lh6.googleusercontent.com", ip_address); + } +} + +/* Set up a global GDataAuthorizer to be used for all the tests. Unfortunately, + * the Google Drive API is effectively limited to OAuth2 authorisation, + * so this requires user interaction when online. + * + * If not online, use a dummy authoriser. */ +static GDataAuthorizer * +create_global_authorizer (void) +{ + GDataOAuth2Authorizer *authorizer = NULL; /* owned */ + gchar *authentication_uri, *authorisation_code; + GError *error = NULL; + + /* If not online, just return a dummy authoriser. */ + if (!uhm_server_get_enable_online (mock_server)) { + return GDATA_AUTHORIZER (gdata_dummy_authorizer_new (GDATA_TYPE_DOCUMENTS_SERVICE)); + } + + /* Otherwise, go through the interactive OAuth dance. */ + gdata_test_mock_server_start_trace (mock_server, "global-authentication"); + authorizer = gdata_oauth2_authorizer_new (CLIENT_ID, CLIENT_SECRET, REDIRECT_URI, GDATA_TYPE_DOCUMENTS_SERVICE); + + /* Get an authentication URI */ + authentication_uri = gdata_oauth2_authorizer_build_authentication_uri (authorizer, NULL, FALSE); + g_assert (authentication_uri != NULL); + + /* Get the authorisation code off the user. */ + authorisation_code = gdata_test_query_user_for_verifier (authentication_uri); + + g_free (authentication_uri); + + if (authorisation_code == NULL) { + /* Skip tests. */ + g_object_unref (authorizer); + authorizer = NULL; + goto skip_test; + } + + /* Authorise the token */ + g_assert (gdata_oauth2_authorizer_request_authorization (authorizer, authorisation_code, NULL, &error)); + g_assert_no_error (error); + +skip_test: + g_free (authorisation_code); + + uhm_server_end_trace (mock_server); + + return GDATA_AUTHORIZER (authorizer); +} + +int +main (int argc, char *argv[]) +{ + gint retval; + GDataAuthorizer *authorizer = NULL; + GDataService *service = NULL; + GFile *trace_directory; + gchar *path = NULL; + + gdata_test_init (argc, argv); + + mock_server = gdata_test_get_mock_server (); + g_signal_connect (G_OBJECT (mock_server), "notify::resolver", (GCallback) mock_server_notify_resolver_cb, NULL); + path = g_test_build_filename (G_TEST_DIST, "traces/documents", NULL); + trace_directory = g_file_new_for_path (path); + g_free (path); + uhm_server_set_trace_directory (mock_server, trace_directory); + g_object_unref (trace_directory); + + authorizer = create_global_authorizer (); + service = GDATA_SERVICE (gdata_documents_service_new (authorizer)); + + g_test_add_func ("/documents/authentication", test_authentication); + + g_test_add ("/documents/delete/document", TempDocumentData, service, set_up_temp_document_spreadsheet, test_delete_document, + tear_down_temp_document); + g_test_add ("/documents/delete/folder", TempFolderData, service, set_up_temp_folder, test_delete_folder, tear_down_temp_folder); + + /* Test all possible combinations of conditions for resumable uploads. */ + { + PayloadType i; + FolderType j; + ResumableType k; + DocumentType l; + + for (i = 0; i < UPLOAD_PAYLOAD_TYPE_MAX + 1; i++) { + for (j = 0; j < UPLOAD_FOLDER_TYPE_MAX + 1; j++) { + for (k = 0; k < UPLOAD_RESUMABLE_TYPE_MAX + 1; k++) { + for (l = 0; l < UPLOAD_DOCUMENT_TYPE_MAX + 1; l++) { + UploadDocumentTestParams *test_params; + gchar *test_name; + + /* FIXME: Resumable uploads are not implemented. */ + if (k == UPLOAD_RESUMABLE) { + continue; + } + + /* FIXME: Conversion during uploads is not implemented. */ + if (l == UPLOAD_ODT_CONVERT) { + continue; + } + + /* Resumable metadata-only uploads don't make sense. */ + if (i == UPLOAD_METADATA_ONLY && k == UPLOAD_RESUMABLE) { + continue; + } + /* Non-resumable non-conversion uploads don't make sense. */ + if (k == UPLOAD_NON_RESUMABLE && l != UPLOAD_ODT_CONVERT) { + continue; + } + + test_name = g_strdup_printf ("/documents/upload/%s/%s/%s/%s", + payload_type_names[i], folder_type_names[j], + resumable_type_names[k], document_type_names[l]); + + /* Allocate a new struct. We leak this. */ + test_params = g_slice_new0 (UploadDocumentTestParams); + test_params->payload_type = i; + test_params->folder_type = j; + test_params->resumable_type = k; + test_params->document_type = l; + test_params->test_name = g_strdup (test_name); + test_params->service = GDATA_DOCUMENTS_SERVICE (service); + + g_test_add (test_name, UploadDocumentData, test_params, set_up_upload_document, test_upload, + tear_down_upload_document); + + g_free (test_name); + } + } + } + } + } + + g_test_add ("/documents/download/document", TempDocumentsData, service, set_up_temp_documents, test_download_document, + tear_down_temp_documents); + g_test_add ("/documents/download/thumbnail", TempDocumentData, service, set_up_temp_document_spreadsheet, test_download_thumbnail, + tear_down_temp_document); + + /* Test all possible combinations of conditions for resumable updates. */ + { + PayloadType i; + ResumableType j; + + for (i = 0; i < UPLOAD_PAYLOAD_TYPE_MAX + 1; i++) { + for (j = 0; j < UPLOAD_RESUMABLE_TYPE_MAX + 1; j++) { + UpdateDocumentTestParams *test_params; + gchar *test_name; + + /* Resumable metadata-only updates don't make sense. */ + if (i == UPLOAD_METADATA_ONLY && j == UPLOAD_RESUMABLE) { + continue; + } + + /* FIXME: Resumable uploads are not implemented. */ + if (j == UPLOAD_RESUMABLE) { + continue; + } + + test_name = g_strdup_printf ("/documents/update/%s/%s", payload_type_names[i], resumable_type_names[j]); + + /* Allocate a new struct. We leak this. */ + test_params = g_slice_new0 (UpdateDocumentTestParams); + test_params->payload_type = i; + test_params->resumable_type = j; + test_params->test_name = g_strdup (test_name); + test_params->service = GDATA_DOCUMENTS_SERVICE (service); + + g_test_add (test_name, UpdateDocumentData, test_params, set_up_update_document, test_update, + tear_down_update_document); + + g_free (test_name); + } + } + } + + g_test_add ("/documents/access-rule/insert", TempDocumentData, service, set_up_temp_document_spreadsheet, test_access_rule_insert, + tear_down_temp_document); + + g_test_add ("/documents/query/all_documents", TempDocumentsData, service, set_up_temp_documents, test_query_all_documents, + tear_down_temp_documents); + g_test_add ("/documents/query/all_documents/with_folder", TempDocumentsData, service, set_up_temp_documents, + test_query_all_documents_with_folder, tear_down_temp_documents); + g_test_add ("/documents/query/all_documents/async", GDataAsyncTestData, service, set_up_temp_documents_async, + test_query_all_documents_async, tear_down_temp_documents_async); + g_test_add ("/documents/query/all_documents/async/progress_closure", TempDocumentsData, service, set_up_temp_documents, + test_query_all_documents_async_progress_closure, tear_down_temp_documents); + g_test_add ("/documents/query/all_documents/async/cancellation", GDataAsyncTestData, service, set_up_temp_documents_async, + test_query_all_documents_async_cancellation, tear_down_temp_documents_async); + + g_test_add ("/documents/copy", TempCopyDocumentData, service, set_up_copy_document, test_copy_document, tear_down_copy_document); + /*g_test_add ("/documents/copy/async", GDataAsyncTestData, service, set_up_folders_add_to_folder_async, + test_folders_add_to_folder_async, tear_down_folders_add_to_folder_async); + g_test_add ("/documents/copy/async/cancellation", GDataAsyncTestData, service, set_up_folders_add_to_folder_async, + test_folders_add_to_folder_async_cancellation, tear_down_folders_add_to_folder_async);*/ + + g_test_add ("/documents/folders/add_to_folder", FoldersData, service, set_up_folders_add_to_folder, + test_folders_add_to_folder, tear_down_folders_add_to_folder); + g_test_add ("/documents/folders/add_to_folder/async", GDataAsyncTestData, service, set_up_folders_add_to_folder_async, + test_folders_add_to_folder_async, tear_down_folders_add_to_folder_async); + g_test_add ("/documents/folders/add_to_folder/async/cancellation", GDataAsyncTestData, service, set_up_folders_add_to_folder_async, + test_folders_add_to_folder_async_cancellation, tear_down_folders_add_to_folder_async); + + g_test_add ("/documents/folders/remove_from_folder", FoldersData, service, set_up_folders_remove_from_folder, + test_folders_remove_from_folder, tear_down_folders_remove_from_folder); + g_test_add ("/documents/folders/remove_from_folder/async", GDataAsyncTestData, service, set_up_folders_remove_from_folder_async, + test_folders_remove_from_folder_async, tear_down_folders_remove_from_folder_async); + g_test_add ("/documents/folders/remove_from_folder/async/cancellation", GDataAsyncTestData, service, + set_up_folders_remove_from_folder_async, test_folders_remove_from_folder_async_cancellation, + tear_down_folders_remove_from_folder_async); + + g_test_add_data_func ("/documents/batch", service, test_batch); + g_test_add ("/documents/batch/async", BatchAsyncData, service, set_up_batch_async, test_batch_async, tear_down_batch_async); + g_test_add ("/documents/batch/async/cancellation", BatchAsyncData, service, set_up_batch_async, test_batch_async_cancellation, + tear_down_batch_async); + + g_test_add_func ("/documents/folder/parser/normal", test_folder_parser_normal); + g_test_add_func ("/documents/query/etag", test_query_etag); + g_test_add_func ("/documents/upload-query/properties/convert", test_upload_query_properties_convert); + + retval = g_test_run (); + + if (service != NULL) + g_object_unref (service); + + g_clear_object (&authorizer); + + return retval; +} diff --git a/gdata/tests/gdata-dummy-authorizer.c b/gdata/tests/gdata-dummy-authorizer.c new file mode 100644 index 0000000..b9b246e --- /dev/null +++ b/gdata/tests/gdata-dummy-authorizer.c @@ -0,0 +1,222 @@ +/* -*- Mode: C; indent-tabs-mode: t; c-basic-offset: 8; tab-width: 8 -*- */ +/* + * GData Client + * Copyright (C) Philip Withnall 2014 + * + * GData Client is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * GData Client is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with GData Client. If not, see . + */ + +/* + * SECTION:gdata-dummy-authorizer + * @short_description: GData dummy authorization interface + * @stability: Stable + * @include: tests/gdata-dummy-authorizer.h + * + * #GDataDummyAuthorizer is a dummy #GDataAuthorizer implementation intended for + * use in prototyping and testing code. It should not be used in production + * code. + * + * It adds a constant ‘Authorization’ header to all requests it processes whose + * domain is in the set of domains the authorizer was initialised with. All + * requests for other domains have no header added, and are considered + * non-authorized. + * + * Since: 0.16.0 + */ + +#include +#include +#include +#include + +#include "gdata-dummy-authorizer.h" +#include "gdata-private.h" + +static void authorizer_init (GDataAuthorizerInterface *iface); +static void finalize (GObject *object); + +static void process_request (GDataAuthorizer *self, + GDataAuthorizationDomain *domain, + SoupMessage *message); +static gboolean is_authorized_for_domain (GDataAuthorizer *self, + GDataAuthorizationDomain *domain); + +struct _GDataDummyAuthorizerPrivate { + GMutex mutex; /* mutex for authorization_domains */ + + /* Mapping from GDataAuthorizationDomain to itself; a set of domains + * which are authorised. */ + GHashTable *authorization_domains; +}; + +G_DEFINE_TYPE_WITH_CODE (GDataDummyAuthorizer, gdata_dummy_authorizer, + G_TYPE_OBJECT, + G_IMPLEMENT_INTERFACE (GDATA_TYPE_AUTHORIZER, + authorizer_init)) + +static void +gdata_dummy_authorizer_class_init (GDataDummyAuthorizerClass *klass) +{ + GObjectClass *gobject_class = G_OBJECT_CLASS (klass); + + g_type_class_add_private (klass, sizeof (GDataDummyAuthorizerPrivate)); + + gobject_class->finalize = finalize; +} + +static void +authorizer_init (GDataAuthorizerInterface *iface) +{ + iface->process_request = process_request; + iface->is_authorized_for_domain = is_authorized_for_domain; +} + +static void +gdata_dummy_authorizer_init (GDataDummyAuthorizer *self) +{ + self->priv = G_TYPE_INSTANCE_GET_PRIVATE (self, + GDATA_TYPE_DUMMY_AUTHORIZER, + GDataDummyAuthorizerPrivate); + + /* Set up the authorizer's mutex */ + g_mutex_init (&(self->priv->mutex)); + self->priv->authorization_domains = g_hash_table_new_full (g_direct_hash, + g_direct_equal, + g_object_unref, + NULL); +} + +static void +finalize (GObject *object) +{ + GDataDummyAuthorizerPrivate *priv = GDATA_DUMMY_AUTHORIZER (object)->priv; + + g_hash_table_destroy (priv->authorization_domains); + g_mutex_clear (&(priv->mutex)); + + /* Chain up to the parent class */ + G_OBJECT_CLASS (gdata_dummy_authorizer_parent_class)->finalize (object); +} + +static void +process_request (GDataAuthorizer *self, GDataAuthorizationDomain *domain, + SoupMessage *message) +{ + GDataDummyAuthorizerPrivate *priv = GDATA_DUMMY_AUTHORIZER (self)->priv; + + /* Set the authorisation header */ + g_mutex_lock (&(priv->mutex)); + + if (g_hash_table_lookup (priv->authorization_domains, domain) != NULL) { + soup_message_headers_replace (message->request_headers, + "Authorization", "dummy"); + } + + g_mutex_unlock (&(priv->mutex)); +} + +static gboolean +is_authorized_for_domain (GDataAuthorizer *self, + GDataAuthorizationDomain *domain) +{ + GDataDummyAuthorizerPrivate *priv = GDATA_DUMMY_AUTHORIZER (self)->priv; + gpointer result; + + g_mutex_lock (&(priv->mutex)); + result = g_hash_table_lookup (priv->authorization_domains, domain); + g_mutex_unlock (&(priv->mutex)); + + /* Sanity check */ + g_assert (result == NULL || result == domain); + + return (result != NULL); +} + +/* + * gdata_dummy_authorizer_new: + * @service_type: the #GType of a #GDataService subclass which the + * #GDataDummyAuthorizer will be used with + * + * Creates a new #GDataDummyAuthorizer. + * + * The #GDataAuthorizationDomains for the given @service_type (i.e. as + * returned by gdata_service_get_authorization_domains()) will be authorized, + * and all others will not. + * + * Return value: (transfer full): a new #GDataDummyAuthorizer; unref with + * g_object_unref() + * + * Since: 0.16.0 + */ +GDataDummyAuthorizer * +gdata_dummy_authorizer_new (GType service_type) +{ + GList/**/ *domains; /* owned */ + GDataDummyAuthorizer *retval = NULL; /* owned */ + + g_return_val_if_fail (g_type_is_a (service_type, GDATA_TYPE_SERVICE), + NULL); + + domains = gdata_service_get_authorization_domains (service_type); + retval = gdata_dummy_authorizer_new_for_authorization_domains (domains); + g_list_free (domains); + + return retval; +} + +/* + * gdata_dummy_authorizer_new_for_authorization_domains: + * @authorization_domains: (element-type GDataAuthorizationDomain) (transfer none): + * a non-empty list of #GDataAuthorizationDomains to be authorized + * against by the #GDataDummyAuthorizer + * + * Creates a new #GDataDummyAuthorizer. This function is intended to be used + * only when the default authorization domain list for a single #GDataService, + * as used by gdata_dummy_authorizer_new(), isn't suitable. For example, this + * could be because the #GDataDummyAuthorizer will be used with multiple + * #GDataService subclasses, or because the client requires a specific set of + * authorization domains. + * + * Return value: (transfer full): a new #GDataDummyAuthorizer; unref with + * g_object_unref() + * + * Since: 0.16.0 + */ +GDataDummyAuthorizer * +gdata_dummy_authorizer_new_for_authorization_domains (GList *authorization_domains) +{ + GList *i; + GDataDummyAuthorizer *authorizer; + + g_return_val_if_fail (authorization_domains != NULL, NULL); + + authorizer = GDATA_DUMMY_AUTHORIZER (g_object_new (GDATA_TYPE_DUMMY_AUTHORIZER, + NULL)); + + /* Register all the domains with the authorizer */ + for (i = authorization_domains; i != NULL; i = i->next) { + GDataAuthorizationDomain *domain; + + g_return_val_if_fail (GDATA_IS_AUTHORIZATION_DOMAIN (i->data), + NULL); + + /* We don't have to lock the authoriser's mutex here as no other + * code has seen the authoriser yet */ + domain = GDATA_AUTHORIZATION_DOMAIN (i->data); + g_hash_table_insert (authorizer->priv->authorization_domains, + g_object_ref (domain), domain); + } + + return authorizer; +} diff --git a/gdata/tests/gdata-dummy-authorizer.h b/gdata/tests/gdata-dummy-authorizer.h new file mode 100644 index 0000000..a739a0e --- /dev/null +++ b/gdata/tests/gdata-dummy-authorizer.h @@ -0,0 +1,77 @@ +/* -*- Mode: C; indent-tabs-mode: t; c-basic-offset: 8; tab-width: 8 -*- */ +/* + * GData Client + * Copyright (C) Philip Withnall 2014 + * + * GData Client is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * GData Client is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with GData Client. If not, see . + */ + +#ifndef GDATA_DUMMY_AUTHORIZER_H +#define GDATA_DUMMY_AUTHORIZER_H + +#include +#include + +#include "gdata-authorizer.h" + +G_BEGIN_DECLS + +#define GDATA_TYPE_DUMMY_AUTHORIZER (gdata_dummy_authorizer_get_type ()) +#define GDATA_DUMMY_AUTHORIZER(o) (G_TYPE_CHECK_INSTANCE_CAST ((o), GDATA_TYPE_DUMMY_AUTHORIZER, GDataDummyAuthorizer)) +#define GDATA_DUMMY_AUTHORIZER_CLASS(k) (G_TYPE_CHECK_CLASS_CAST((k), GDATA_TYPE_DUMMY_AUTHORIZER, GDataDummyAuthorizerClass)) +#define GDATA_IS_DUMMY_AUTHORIZER(o) (G_TYPE_CHECK_INSTANCE_TYPE ((o), GDATA_TYPE_DUMMY_AUTHORIZER)) +#define GDATA_IS_DUMMY_AUTHORIZER_CLASS(k) (G_TYPE_CHECK_CLASS_TYPE ((k), GDATA_TYPE_DUMMY_AUTHORIZER)) +#define GDATA_DUMMY_AUTHORIZER_GET_CLASS(o) (G_TYPE_INSTANCE_GET_CLASS ((o), GDATA_TYPE_DUMMY_AUTHORIZER, GDataDummyAuthorizerClass)) + +typedef struct _GDataDummyAuthorizerPrivate GDataDummyAuthorizerPrivate; + +/** + * GDataDummyAuthorizer: + * + * All the fields in the #GDataDummyAuthorizer structure are private and should never be accessed directly. + * + * Since: 0.16.0 + */ +typedef struct { + /*< private >*/ + GObject parent; + GDataDummyAuthorizerPrivate *priv; +} GDataDummyAuthorizer; + +/** + * GDataDummyAuthorizerClass: + * + * All the fields in the #GDataDummyAuthorizerClass structure are private and should never be accessed directly. + * + * Since: 0.16.0 + */ +typedef struct { + /*< private >*/ + GObjectClass parent; + + /*< private >*/ + /* Padding for future expansion */ + void (*_g_reserved0) (void); + void (*_g_reserved1) (void); +} GDataDummyAuthorizerClass; + +GType gdata_dummy_authorizer_get_type (void) G_GNUC_CONST; +G_DEFINE_AUTOPTR_CLEANUP_FUNC (GDataDummyAuthorizer, g_object_unref) + +GDataDummyAuthorizer *gdata_dummy_authorizer_new (GType service_type) G_GNUC_WARN_UNUSED_RESULT G_GNUC_MALLOC; +GDataDummyAuthorizer *gdata_dummy_authorizer_new_for_authorization_domains (GList *authorization_domains) G_GNUC_WARN_UNUSED_RESULT G_GNUC_MALLOC; + +G_END_DECLS + +#endif /* !GDATA_DUMMY_AUTHORIZER_H */ diff --git a/gdata/tests/general.c b/gdata/tests/general.c new file mode 100644 index 0000000..30604ba --- /dev/null +++ b/gdata/tests/general.c @@ -0,0 +1,5005 @@ +/* -*- Mode: C; indent-tabs-mode: t; c-basic-offset: 8; tab-width: 8 -*- */ +/* + * GData Client + * Copyright (C) Philip Withnall 2008–2010 + * + * GData Client is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * GData Client is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with GData Client. If not, see . + */ + +#include +#include + +#include "gdata.h" +#include "common.h" + +static void +test_documents_property_parse_json (void) +{ + GDataDocumentsProperty *property; + GError *error = NULL; + + /* Create an entry from JSON with unhandled nodes. */ + property = GDATA_DOCUMENTS_PROPERTY (gdata_parsable_new_from_json (GDATA_TYPE_DOCUMENTS_PROPERTY, + "{" + "\"key\":\"foobar\"," + "\"etag\":\"some-etag\"," + "\"value\":\"some foobar value\"," + "\"visibility\":\"PUBLIC\"," + "\"unhandled-boolean\":false," + "\"unhandled-string\":\"this-is-a-string---sometimes\"," + "\"unhandled-int\":15," + "\"unhandled-double\":42.42," + "\"unhandled-object\":{" + "\"a\":true," + "\"b\":true" + "}," + "\"unhandled-array\":[" + "1," + "2," + "3" + "]," + "\"unhandled-null\":null" + "}", -1, &error)); + g_assert_no_error (error); + g_assert (GDATA_IS_DOCUMENTS_PROPERTY (property)); + + /* Now check the outputted JSON from the property still has the unhandled nodes. */ + gdata_test_assert_json (property, + "{" + "\"key\":\"foobar\"," + "\"etag\":\"some-etag\"," + "\"value\":\"some foobar value\"," + "\"visibility\":\"PUBLIC\"," + "\"unhandled-boolean\":false," + "\"unhandled-string\":\"this-is-a-string---sometimes\"," + "\"unhandled-int\":15," + "\"unhandled-double\":42.42," + "\"unhandled-object\":{" + "\"a\":true," + "\"b\":true" + "}," + "\"unhandled-array\":[" + "1," + "2," + "3" + "]," + "\"unhandled-null\":null" + "}"); + g_object_unref (property); +} + +static void +test_documents_property_get_json (void) +{ + GDataDocumentsProperty *property1, *property2; + gchar *json; + GError *error = NULL; + + property1 = gdata_documents_property_new ("Testing key & \"escaping\""); + + /* Set the properties more conventionally */ + gdata_documents_property_set_value (property1, "Testing value & \"escaping\""); + gdata_documents_property_set_visibility (property1, GDATA_DOCUMENTS_PROPERTY_VISIBILITY_PRIVATE); + + /* Check the generated JSON's OK */ + gdata_test_assert_json (property1, + "{" + "\"key\":\"Testing key & \\\"escaping\\\"\"," + "\"value\":\"Testing value & \\\"escaping\\\"\"," + "\"visibility\":\"PRIVATE\"" + "}"); + + /* Check again by re-parsing the JSON to a GDataEntry. */ + json = gdata_parsable_get_json (GDATA_PARSABLE (property1)); + property2 = GDATA_DOCUMENTS_PROPERTY (gdata_parsable_new_from_json (GDATA_TYPE_DOCUMENTS_PROPERTY, json, -1, &error)); + g_assert_no_error (error); + g_assert (GDATA_IS_DOCUMENTS_PROPERTY (property2)); + g_clear_error (&error); + g_free (json); + + g_assert_cmpstr (gdata_documents_property_get_key (property1), ==, gdata_documents_property_get_key (property2)); + g_assert_cmpstr (gdata_documents_property_get_etag (property1), ==, gdata_documents_property_get_etag (property2)); + g_assert_cmpstr (gdata_documents_property_get_value (property1), ==, gdata_documents_property_get_value (property2)); + g_assert_cmpstr (gdata_documents_property_get_visibility (property1), ==, gdata_documents_property_get_visibility (property2)); + + g_object_unref (property1); + g_object_unref (property2); +} + +static void +test_xml_comparison (void) +{ + GDataAccessRule *rule; + + /* Since we've written the XML comparison function used across all the test suites, it's necessary to test that it actually works before we + * blindly assert that its results are correct. */ + rule = gdata_access_rule_new ("an-id"); + gdata_access_rule_set_role (rule, GDATA_ACCESS_ROLE_NONE); + gdata_access_rule_set_scope (rule, GDATA_ACCESS_SCOPE_USER, "foo@example.com"); + + /* Check a valid comparison */ + gdata_test_assert_xml (rule, + "" + "" + "none" + "an-id" + "" + "" + "" + ""); + + /* Check a valid comparison with namespaces swapped */ + gdata_test_assert_xml (rule, + "" + "" + "none" + "an-id" + "" + "" + "" + ""); + + /* Check a valid comparison with elements swapped */ + gdata_test_assert_xml (rule, + "" + "" + "an-id" + "none" + "" + "" + "" + ""); + + /* Missing namespace (still valid XML, just not what's expected) */ + g_assert (gdata_test_compare_xml (GDATA_PARSABLE (rule), + "" + "" + "none" + "an-id" + "" + "" + "" + "", FALSE) == FALSE); + + /* Extra namespace */ + g_assert (gdata_test_compare_xml (GDATA_PARSABLE (rule), + "" + "" + "none" + "an-id" + "" + "" + "" + "", FALSE) == FALSE); + + /* Missing element */ + g_assert (gdata_test_compare_xml (GDATA_PARSABLE (rule), + "" + "" + "an-id" + "" + "" + "" + "", FALSE) == FALSE); + + /* Extra element */ + g_assert (gdata_test_compare_xml (GDATA_PARSABLE (rule), + "" + "" + "none" + "bar" + "an-id" + "" + "" + "" + "", FALSE) == FALSE); + + /* Incorrect namespace on element */ + g_assert (gdata_test_compare_xml (GDATA_PARSABLE (rule), + "" + "" + "none" + "an-id" + "" + "" + "" + "", FALSE) == FALSE); + + /* Mis-valued content */ + g_assert (gdata_test_compare_xml (GDATA_PARSABLE (rule), + "" + "" + "none" + "an-other-id" + "" + "" + "" + "", FALSE) == FALSE); + + /* Missing attribute */ + g_assert (gdata_test_compare_xml (GDATA_PARSABLE (rule), + "" + "" + "none" + "an-id" + "" + "" + "" + "", FALSE) == FALSE); + + /* Extra attribute */ + g_assert (gdata_test_compare_xml (GDATA_PARSABLE (rule), + "" + "" + "none" + "an-id" + "" + "" + "" + "", FALSE) == FALSE); + + /* Mis-valued attribute */ + g_assert (gdata_test_compare_xml (GDATA_PARSABLE (rule), + "" + "" + "none" + "an-id" + "" + "" + "" + "", FALSE) == FALSE); + + g_object_unref (rule); +} + +static void +test_entry_get_xml (void) +{ + gint64 updated, published, updated2, published2, updated3, published3; + GDataEntry *entry, *entry2; + GDataCategory *category; + GDataLink *_link; /* stupid unistd.h */ + GDataAuthor *author; + gchar *xml, *title, *summary, *id, *etag, *content, *content_uri, *rights; + gboolean is_inserted; + GList *list; + GError *error = NULL; + + entry = gdata_entry_new (NULL); + + /* Test setting properties directly */ + g_object_set (G_OBJECT (entry), + "title", "First testing title & escaping", + "summary", "Test summary & escaping.", + "content", "Test & escaping.", + "rights", "Philip Withnall ", + NULL); + + g_assert_cmpstr (gdata_entry_get_title (entry), ==, "First testing title & escaping"); + g_assert_cmpstr (gdata_entry_get_summary (entry), ==, "Test summary & escaping."); + g_assert_cmpstr (gdata_entry_get_content (entry), ==, "Test & escaping."); + g_assert (gdata_entry_get_content_uri (entry) == NULL); + g_assert_cmpstr (gdata_entry_get_rights (entry), ==, "Philip Withnall "); + + /* Set the properties more conventionally */ + gdata_entry_set_title (entry, "Testing title & escaping"); + gdata_entry_set_summary (entry, NULL); + gdata_entry_set_content (entry, "This is some sample content testing, amongst other things, & odd characters‽"); + gdata_entry_set_rights (entry, NULL); + + /* Content URI */ + g_object_set (G_OBJECT (entry), "content-uri", "http://foo.com/", NULL); + + g_assert (gdata_entry_get_content (entry) == NULL); + g_assert_cmpstr (gdata_entry_get_content_uri (entry), ==, "http://foo.com/"); + + gdata_entry_set_content_uri (entry, "http://bar.com/"); + + /* Check the generated XML's OK */ + gdata_test_assert_xml (entry, + "" + "" + "Testing title & escaping" + "" + ""); + + /* Reset the content */ + gdata_entry_set_content (entry, "This is some sample content testing, amongst other things, & odd characters‽"); + + /* Categories */ + category = gdata_category_new ("test", NULL, NULL); + gdata_entry_add_category (entry, category); + g_object_unref (category); + category = gdata_category_new ("example", NULL, "Example stuff"); + gdata_entry_add_category (entry, category); + g_object_unref (category); + category = gdata_category_new ("Film", "http://gdata.youtube.com/schemas/2007/categories.cat", "Film & Animation"); + gdata_entry_add_category (entry, category); + g_object_unref (category); + + /* Links */ + _link = gdata_link_new ("http://test.com/", GDATA_LINK_SELF); + gdata_link_set_content_type (_link, "application/atom+xml"); + gdata_entry_add_link (entry, _link); + g_object_unref (_link); + _link = gdata_link_new ("http://example.com/", NULL); + gdata_entry_add_link (entry, _link); + g_object_unref (_link); + _link = gdata_link_new ("http://test.mn/", GDATA_LINK_RELATED); + gdata_link_set_content_type (_link, "text/html"); + gdata_link_set_language (_link, "mn"); + gdata_link_set_title (_link, "A treatise on Mongolian test websites & other stuff."); + gdata_link_set_length (_link, 5010); + gdata_entry_add_link (entry, _link); + g_object_unref (_link); + _link = gdata_link_new ("http://example.com/", "http://foobar.link"); + gdata_entry_add_link (entry, _link); + g_object_unref (_link); + _link = gdata_link_new ("http://example2.com/", "http://foobar.link"); + gdata_entry_add_link (entry, _link); + g_object_unref (_link); + + /* Authors */ + author = gdata_author_new ("Joe Bloggs", "http://example.com/", "joe@example.com"); + gdata_entry_add_author (entry, author); + g_object_unref (author); + author = gdata_author_new ("John Smith", NULL, "smith.john@example.com"); + gdata_entry_add_author (entry, author); + g_object_unref (author); + author = gdata_author_new ("F. Barr؟", NULL, NULL); + gdata_entry_add_author (entry, author); + g_object_unref (author); + + /* Check the generated XML's OK */ + gdata_test_assert_xml (entry, + "" + "" + "Testing title & escaping" + "This is some sample content testing, amongst other things, <markup> & odd characters\342\200\275" + "" + "" + "" + "" + "" + "" + "" + "" + "F. Barr\330\237" + "John Smithsmith.john@example.com" + "Joe Bloggshttp://example.com/joe@example.com" + ""); + + /* Check again by re-parsing the XML to a GDataEntry */ + xml = gdata_parsable_get_xml (GDATA_PARSABLE (entry)); + entry2 = GDATA_ENTRY (gdata_parsable_new_from_xml (GDATA_TYPE_ENTRY, xml, -1, &error)); + g_assert_no_error (error); + g_assert (GDATA_IS_ENTRY (entry2)); + g_clear_error (&error); + g_free (xml); + + g_assert_cmpstr (gdata_entry_get_title (entry), ==, gdata_entry_get_title (entry2)); + g_assert_cmpstr (gdata_entry_get_id (entry), ==, gdata_entry_get_id (entry2)); /* should both be NULL */ + g_assert_cmpstr (gdata_entry_get_content (entry), ==, gdata_entry_get_content (entry2)); + g_assert_cmpstr (gdata_entry_get_content_uri (entry), ==, gdata_entry_get_content_uri (entry2)); /* should both be NULL */ + + updated = gdata_entry_get_updated (entry); + updated2 = gdata_entry_get_updated (entry2); + g_assert_cmpuint (updated, ==, updated2); + + published = gdata_entry_get_published (entry); + published2 = gdata_entry_get_published (entry2); + g_assert_cmpuint (published, ==, published2); + + /* Check links */ + _link = gdata_entry_look_up_link (entry, GDATA_LINK_SELF); + g_assert (_link != NULL); + g_assert_cmpstr (gdata_link_get_uri (_link), ==, "http://test.com/"); + g_assert_cmpstr (gdata_link_get_relation_type (_link), ==, GDATA_LINK_SELF); + g_assert_cmpstr (gdata_link_get_content_type (_link), ==, "application/atom+xml"); + + _link = gdata_entry_look_up_link (entry, "http://link.not.exist"); + g_assert (_link == NULL); + + list = gdata_entry_look_up_links (entry, "http://foobar.link"); + g_assert (list != NULL); + g_assert_cmpint (g_list_length (list), ==, 2); + + _link = GDATA_LINK (list->data); + g_assert (_link != NULL); + g_assert_cmpstr (gdata_link_get_uri (_link), ==, "http://example2.com/"); + g_assert_cmpstr (gdata_link_get_relation_type (_link), ==, "http://foobar.link"); + + _link = GDATA_LINK (list->next->data); + g_assert (_link != NULL); + g_assert_cmpstr (gdata_link_get_uri (_link), ==, "http://example.com/"); + g_assert_cmpstr (gdata_link_get_relation_type (_link), ==, "http://foobar.link"); + + g_list_free (list); + + /* Check authors */ + list = gdata_entry_get_authors (entry); + g_assert_cmpuint (g_list_length (list), ==, 3); + + author = GDATA_AUTHOR (list->data); + g_assert (author != NULL); + g_assert_cmpstr (gdata_author_get_name (author), ==, "F. Barr؟"); + g_assert (gdata_author_get_uri (author) == NULL); + g_assert (gdata_author_get_email_address (author) == NULL); + + author = GDATA_AUTHOR (list->next->data); + g_assert (author != NULL); + g_assert_cmpstr (gdata_author_get_name (author), ==, "John Smith"); + g_assert (gdata_author_get_uri (author) == NULL); + g_assert_cmpstr (gdata_author_get_email_address (author), ==, "smith.john@example.com"); + + author = GDATA_AUTHOR (list->next->next->data); + g_assert (author != NULL); + g_assert_cmpstr (gdata_author_get_name (author), ==, "Joe Bloggs"); + g_assert_cmpstr (gdata_author_get_uri (author), ==, "http://example.com/"); + g_assert_cmpstr (gdata_author_get_email_address (author), ==, "joe@example.com"); + + /* Check categories */ + list = gdata_entry_get_categories (entry); + g_assert (list != NULL); + g_assert_cmpint (g_list_length (list), ==, 3); + + category = GDATA_CATEGORY (list->data); + g_assert (category != NULL); + g_assert_cmpstr (gdata_category_get_term (category), ==, "Film"); + g_assert_cmpstr (gdata_category_get_scheme (category), ==, "http://gdata.youtube.com/schemas/2007/categories.cat"); + g_assert_cmpstr (gdata_category_get_label (category), ==, "Film & Animation"); + + category = GDATA_CATEGORY (list->next->data); + g_assert (category != NULL); + g_assert_cmpstr (gdata_category_get_term (category), ==, "example"); + g_assert (gdata_category_get_scheme (category) == NULL); + g_assert_cmpstr (gdata_category_get_label (category), ==, "Example stuff"); + + category = GDATA_CATEGORY (list->next->next->data); + g_assert (category != NULL); + g_assert_cmpstr (gdata_category_get_term (category), ==, "test"); + g_assert (gdata_category_get_scheme (category) == NULL); + g_assert (gdata_category_get_label (category) == NULL); + + /* TODO: Check authors */ + + /* Check properties a different way */ + g_object_get (G_OBJECT (entry2), + "title", &title, + "summary", &summary, + "id", &id, + "etag", &etag, + "updated", &updated3, + "published", &published3, + "content", &content, + "content-uri", &content_uri, + "is-inserted", &is_inserted, + "rights", &rights, + NULL); + + g_assert_cmpstr (title, ==, gdata_entry_get_title (entry)); + g_assert_cmpstr (summary, ==, gdata_entry_get_summary (entry)); + g_assert_cmpstr (id, ==, gdata_entry_get_id (entry)); + g_assert_cmpstr (etag, ==, gdata_entry_get_etag (entry)); + g_assert_cmpint (updated3, ==, updated); + g_assert_cmpint (published3, ==, published); + g_assert_cmpstr (content, ==, gdata_entry_get_content (entry)); + g_assert_cmpstr (content_uri, ==, gdata_entry_get_content_uri (entry)); + g_assert (is_inserted == FALSE); + g_assert_cmpstr (rights, ==, gdata_entry_get_rights (entry)); + + g_free (title); + g_free (summary); + g_free (id); + g_free (etag); + g_free (content); + g_free (content_uri); + g_free (rights); + + /* Set the content URI and check that */ + gdata_entry_set_content_uri (entry, "http://baz.net/"); + + g_object_get (G_OBJECT (entry), + "content", &content, + "content-uri", &content_uri, + NULL); + + g_assert_cmpstr (content, ==, gdata_entry_get_content (entry)); + g_assert_cmpstr (content_uri, ==, gdata_entry_get_content_uri (entry)); + + g_free (content); + g_free (content_uri); + + g_object_unref (entry); + g_object_unref (entry2); +} + +static void +test_entry_get_json (void) +{ + gint64 updated, published, updated2, published2; + GDataEntry *entry, *entry2; + gchar *json; + GError *error = NULL; + + entry = gdata_entry_new (NULL); + + /* Set the properties more conventionally */ + gdata_entry_set_title (entry, "Testing title & \"escaping\""); + gdata_entry_set_summary (entry, NULL); + gdata_entry_set_content (entry, NULL); + gdata_entry_set_rights (entry, NULL); + + /* Check the generated JSON's OK */ + gdata_test_assert_json (entry, + "{" + "\"title\":\"Testing title & \\\"escaping\\\"\"" + "}"); + + /* Check again by re-parsing the JSON to a GDataEntry. */ + json = gdata_parsable_get_json (GDATA_PARSABLE (entry)); + entry2 = GDATA_ENTRY (gdata_parsable_new_from_json (GDATA_TYPE_ENTRY, json, -1, &error)); + g_assert_no_error (error); + g_assert (GDATA_IS_ENTRY (entry2)); + g_clear_error (&error); + g_free (json); + + g_assert_cmpstr (gdata_entry_get_title (entry), ==, gdata_entry_get_title (entry2)); + g_assert_cmpstr (gdata_entry_get_id (entry), ==, gdata_entry_get_id (entry2)); /* should both be NULL */ + g_assert_cmpstr (gdata_entry_get_content (entry), ==, gdata_entry_get_content (entry2)); + g_assert_cmpstr (gdata_entry_get_content_uri (entry), ==, gdata_entry_get_content_uri (entry2)); /* should both be NULL */ + + updated = gdata_entry_get_updated (entry); + updated2 = gdata_entry_get_updated (entry2); + g_assert_cmpuint (updated, ==, updated2); + + published = gdata_entry_get_published (entry); + published2 = gdata_entry_get_published (entry2); + g_assert_cmpuint (published, ==, published2); + + g_object_unref (entry); + g_object_unref (entry2); +} + +static void +test_entry_parse_xml (void) +{ + GDataEntry *entry; + GError *error = NULL; + + /* Create an entry from XML with unhandled elements */ + entry = GDATA_ENTRY (gdata_parsable_new_from_xml (GDATA_TYPE_ENTRY, + "" + "Testing unhandled XML" + "2009-01-25T14:07:37Z" + "2009-01-23T14:06:37Z" + "Here we test unhandled XML elements." + "Test!" + "" + "How about some characters‽" + "", -1, &error)); + g_assert_no_error (error); + g_assert (GDATA_IS_ENTRY (entry)); + g_clear_error (&error); + + /* Now check the outputted XML from the entry still has the unhandled elements */ + gdata_test_assert_xml (entry, + "" + "" + "Testing unhandled XML" + "2009-01-25T14:07:37Z" + "2009-01-23T14:06:37Z" + "Here we test unhandled XML elements." + "Test!" + "" + "How about some characters‽" + ""); + g_object_unref (entry); +} + +static void +test_entry_parse_xml_kind_category (void) +{ + GDataEntry *entry; + GError *error = NULL; + + g_test_bug ("707477"); + + /* Create an entry from XML with a ‘kind’ category with extra attributes. */ + entry = GDATA_ENTRY (gdata_parsable_new_from_xml (GDATA_TYPE_ENTRY, + "" + "Testing kind categories" + "2009-01-25T14:07:37Z" + "2009-01-23T14:06:37Z" + "Here we test kind categories." + "" + "" + "", -1, &error)); + g_assert_no_error (error); + g_assert (GDATA_IS_ENTRY (entry)); + g_clear_error (&error); + + /* Now check the outputted XML from the entry still has the extra attributes */ + gdata_test_assert_xml (entry, + "" + "" + "Testing kind categories" + "2009-01-25T14:07:37Z" + "2009-01-23T14:06:37Z" + "Here we test kind categories." + "" + "" + ""); + g_object_unref (entry); +} + +static void +test_entry_parse_json (void) +{ + GDataEntry *entry; + GError *error = NULL; + + /* Create an entry from JSON with unhandled nodes. */ + entry = GDATA_ENTRY (gdata_parsable_new_from_json (GDATA_TYPE_ENTRY, + "{" + "\"title\":\"A title\"," + "\"updated\":\"2009-01-25T14:07:37Z\"," + "\"selfLink\":\"http://example.com/\"," + "\"etag\":\"some-etag\"," + "\"id\":\"some-id\"," + "\"kind\":\"kind#kind\"," + "\"unhandled-boolean\":false," + "\"unhandled-string\":\"this-is-a-string---sometimes\"," + "\"unhandled-int\":15," + "\"unhandled-double\":42.42," + "\"unhandled-object\":{" + "\"a\":true," + "\"b\":true" + "}," + "\"unhandled-array\":[" + "1," + "2," + "3" + "]," + "\"unhandled-null\":null" + "}", -1, &error)); + g_assert_no_error (error); + g_assert (GDATA_IS_ENTRY (entry)); + + /* Now check the outputted JSON from the entry still has the unhandled nodes. */ + gdata_test_assert_json (entry, + "{" + "\"title\":\"A title\"," + "\"id\":\"some-id\"," + "\"updated\":\"2009-01-25T14:07:37Z\"," + "\"etag\":\"some-etag\"," + "\"selfLink\":\"http://example.com/\"," + "\"kind\":\"kind#kind\"," + "\"unhandled-boolean\":false," + "\"unhandled-string\":\"this-is-a-string---sometimes\"," + "\"unhandled-int\":15," + "\"unhandled-double\":42.42," + "\"unhandled-object\":{" + "\"a\":true," + "\"b\":true" + "}," + "\"unhandled-array\":[" + "1," + "2," + "3" + "]," + "\"unhandled-null\":null" + "}"); + g_object_unref (entry); + + /* Test parsing of empty titles. */ + entry = GDATA_ENTRY (gdata_parsable_new_from_json (GDATA_TYPE_ENTRY, + "{" + "\"title\":\"\"" + "}", -1, &error)); + g_assert_no_error (error); + g_assert (GDATA_IS_ENTRY (entry)); + g_object_unref (entry); +} + +static void +test_entry_error_handling_xml (void) +{ + GDataEntry *entry; + GError *error = NULL; + +#define TEST_XML_ERROR_HANDLING(x) entry = GDATA_ENTRY (gdata_parsable_new_from_xml (GDATA_TYPE_ENTRY,\ + ""\ + x\ + "", -1, &error));\ + g_assert_error (error, GDATA_SERVICE_ERROR, GDATA_SERVICE_ERROR_PROTOCOL_ERROR);\ + g_assert (entry == NULL);\ + g_clear_error (&error) + + /* updated */ + TEST_XML_ERROR_HANDLING ("not a date"); /* invalid date */ + + /* published */ + TEST_XML_ERROR_HANDLING ("also not a date"); /* invalid date */ + + /* category */ + TEST_XML_ERROR_HANDLING (""); /* invalid category */ + + /* link */ + TEST_XML_ERROR_HANDLING (""); /* invalid link */ + + /* author */ + TEST_XML_ERROR_HANDLING (""); /* invalid author */ + +#undef TEST_XML_ERROR_HANDLING +} + +static void +test_entry_error_handling_json (void) +{ + GDataEntry *entry; + GError *error = NULL; + +#define TEST_JSON_ERROR_HANDLING(x) \ + entry = GDATA_ENTRY (gdata_parsable_new_from_json (GDATA_TYPE_ENTRY,x, -1, &error));\ + g_assert_error (error, GDATA_SERVICE_ERROR, GDATA_SERVICE_ERROR_PROTOCOL_ERROR);\ + g_assert (entry == NULL);\ + g_clear_error (&error) +#define TEST_JSON_ERROR_HANDLING_PARSER(x) \ + entry = GDATA_ENTRY (gdata_parsable_new_from_json (GDATA_TYPE_ENTRY,x, -1, &error));\ + g_assert_error (error, GDATA_PARSER_ERROR, GDATA_PARSER_ERROR_PARSING_STRING);\ + g_assert (entry == NULL);\ + g_clear_error (&error) + + /* General structure. */ + TEST_JSON_ERROR_HANDLING_PARSER ("[true,false,true]"); /* root node is not an object */ + TEST_JSON_ERROR_HANDLING_PARSER ("false"); /* root node is not an object */ + TEST_JSON_ERROR_HANDLING_PARSER ("invalid json"); /* totally invalid JSON */ + + /* id */ + TEST_JSON_ERROR_HANDLING ("{\"id\":\"\"}"); /* empty */ + TEST_JSON_ERROR_HANDLING ("{\"id\":null}"); /* invalid type */ + + /* updated */ + TEST_JSON_ERROR_HANDLING ("{\"updated\":\"not correct\"}"); /* incorrect format */ + TEST_JSON_ERROR_HANDLING ("{\"updated\":false}"); /* invalid type */ + TEST_JSON_ERROR_HANDLING ("{\"updated\":\"\"}"); /* empty */ + + /* title */ + TEST_JSON_ERROR_HANDLING ("{\"title\":false}"); /* invalid type */ + + /* etag */ + TEST_JSON_ERROR_HANDLING ("{\"etag\":\"\"}"); /* empty */ + TEST_JSON_ERROR_HANDLING ("{\"etag\":false}"); /* invalid type */ + + /* selfLink */ + TEST_JSON_ERROR_HANDLING ("{\"selfLink\":\"\"}"); /* empty */ + TEST_JSON_ERROR_HANDLING ("{\"selfLink\":false}"); /* invalid type */ + + /* kind */ + TEST_JSON_ERROR_HANDLING ("{\"kind\":\"\"}"); /* empty */ + TEST_JSON_ERROR_HANDLING ("{\"kind\":false}"); /* invalid type */ + +#undef TEST_JSON_ERROR_HANDLING_PARSER +#undef TEST_JSON_ERROR_HANDLING +} + +static void +test_entry_escaping (void) +{ + GDataEntry *entry; + GError *error = NULL; + + /* Since we can't construct a GDataEntry directly, we need to parse it from XML */ + entry = GDATA_ENTRY (gdata_parsable_new_from_xml (GDATA_TYPE_ENTRY, + "" + "" + "Escaped content & stuff" + "http://foo.com/?foo&bar" + "2010-12-10T17:21:24Z" + "2010-12-10T17:21:24Z" + "Summary & stuff" + "Free & open source" + "Content & things." + "", -1, &error)); + g_assert_no_error (error); + g_assert (GDATA_IS_ENTRY (entry)); + + /* Check the outputted XML is escaped properly */ + gdata_test_assert_xml (entry, + "" + "" + "Escaped content & stuff" + "http://foo.com/?foo&bar" + "2010-12-10T17:21:24Z" + "2010-12-10T17:21:24Z" + "Summary & stuff" + "Free & open source" + "Content & things." + ""); + g_object_unref (entry); + + /* Repeat with content given by a URI */ + entry = GDATA_ENTRY (gdata_parsable_new_from_xml (GDATA_TYPE_ENTRY, + "" + "" + "Escaped content & stuff" + "" + "", -1, &error)); + g_assert_no_error (error); + g_assert (GDATA_IS_ENTRY (entry)); + + /* Check the outputted XML is escaped properly */ + gdata_test_assert_xml (entry, + "" + "" + "Escaped content & stuff" + "" + ""); + g_object_unref (entry); +} + +static void +test_entry_links_remove (void) +{ + GDataEntry *entry; + GDataLink *link_, *link2_; + GError *error = NULL; + + /* Since we can't construct a GDataEntry directly, we need to parse it from XML. */ + entry = GDATA_ENTRY (gdata_parsable_new_from_xml (GDATA_TYPE_ENTRY, + "" + "" + "Escaped content & stuff" + "http://foo.com/?foo&bar" + "2010-12-10T17:21:24Z" + "2010-12-10T17:21:24Z" + "Summary & stuff" + "Free & open source" + "Content & things." + "", -1, &error)); + g_assert_no_error (error); + g_assert (GDATA_IS_ENTRY (entry)); + + link_ = gdata_link_new ("http://example.com/", GDATA_LINK_RELATED); + + /* Add a link. */ + gdata_entry_add_link (entry, link_); + g_assert (gdata_entry_look_up_link (entry, GDATA_LINK_RELATED) == link_); + + /* Remove the link. */ + g_assert (gdata_entry_remove_link (entry, link_) == TRUE); + g_assert (gdata_entry_look_up_link (entry, GDATA_LINK_RELATED) == NULL); + + /* Attempt to remove a non-existent link. */ + link2_ = gdata_link_new ("http://foobar.com/", GDATA_LINK_SELF); + g_assert (gdata_entry_remove_link (entry, link2_) == FALSE); + + g_object_unref (link2_); + g_object_unref (link_); + g_object_unref (entry); +} + +static void +test_feed_parse_xml (void) +{ + GDataFeed *feed; + GDataEntry *entry; + GDataLink *_link; /* stupid unistd.h */ + GList *list; + gchar *title, *subtitle, *id, *etag, *logo, *icon, *rights; + gint64 updated, updated2; + GDataGenerator *generator; + guint items_per_page, start_index, total_results; + GError *error = NULL; + + feed = GDATA_FEED (gdata_parsable_new_from_xml (GDATA_TYPE_FEED, + "" + "http://example.com/id" + "2009-02-25T14:07:37.880860Z" + "Test feed" + "Test subtitle" + "http://example.com/logo.png" + "http://example.com/icon.png" + "" + "" + "" + "" + "" + "public" + "" + "Joe Smith" + "j.smith@example.com" + "" + "Example Generator" + "2" + "1" + "50" + "" + "entry1" + "Testing unhandled XML" + "2009-01-25T14:07:37.880860Z" + "2009-01-23T14:06:37.880860Z" + "Here we test unhandled XML elements." + "" + "" + "entry2" + "Testing unhandled XML 2" + "2009-02-25T14:07:37.880860Z" + "2009-02-23T14:06:37.880860Z" + "Here we test unhandled XML elements again." + "" + "Test unhandled elements!" + "", -1, &error)); + g_assert_no_error (error); + g_assert (GDATA_IS_FEED (feed)); + g_clear_error (&error); + + /* Check the feed's properties */ + g_object_get (G_OBJECT (feed), + "title", &title, + "subtitle", &subtitle, + "id", &id, + "etag", &etag, + "updated", &updated, + "logo", &logo, + "icon", &icon, + "generator", &generator, + "rights", &rights, + "items-per-page", &items_per_page, + "start-index", &start_index, + "total-results", &total_results, + NULL); + + g_assert_cmpstr (title, ==, "Test feed"); + g_assert_cmpstr (subtitle, ==, "Test subtitle"); + g_assert_cmpstr (id, ==, "http://example.com/id"); + g_assert_cmpstr (etag, ==, "W/\"D08FQn8-eil7ImA9WxZbFEw.\""); + + g_assert_cmpint (updated, ==, 1235570857); + + g_assert_cmpstr (logo, ==, "http://example.com/logo.png"); + g_assert_cmpstr (icon, ==, "http://example.com/icon.png"); + g_assert_cmpstr (rights, ==, "public"); + + g_assert (GDATA_IS_GENERATOR (generator)); + g_assert_cmpstr (gdata_generator_get_name (generator), ==, "Example Generator"); + g_assert_cmpstr (gdata_generator_get_uri (generator), ==, "http://example.com/"); + g_assert_cmpstr (gdata_generator_get_version (generator), ==, "0.6"); + + g_assert_cmpuint (items_per_page, ==, 50); + g_assert_cmpuint (start_index, ==, 1); + g_assert_cmpuint (total_results, ==, 2); + + g_free (title); + g_free (subtitle); + g_free (id); + g_free (etag); + g_free (logo); + g_free (icon); + g_free (rights); + g_object_unref (generator); + + /* Check the entries */ + entry = gdata_feed_look_up_entry (feed, "entry1"); + g_assert (GDATA_IS_ENTRY (entry)); + + entry = gdata_feed_look_up_entry (feed, "this doesn't exist"); + g_assert (entry == NULL); + + entry = gdata_feed_look_up_entry (feed, "entry2"); + g_assert (GDATA_IS_ENTRY (entry)); + + /* Check the categories */ + list = gdata_feed_get_categories (feed); + g_assert (list != NULL); + g_assert_cmpint (g_list_length (list), ==, 1); + g_assert (GDATA_IS_CATEGORY (list->data)); + + /* Check the links */ + list = gdata_feed_get_links (feed); + g_assert (list != NULL); + g_assert_cmpint (g_list_length (list), ==, 4); + g_assert (GDATA_IS_LINK (list->data)); + g_assert (GDATA_IS_LINK (list->next->data)); + g_assert (GDATA_IS_LINK (list->next->next->data)); + g_assert (GDATA_IS_LINK (list->next->next->next->data)); + + _link = gdata_feed_look_up_link (feed, GDATA_LINK_ALTERNATE); + g_assert (GDATA_IS_LINK (_link)); + + _link = gdata_feed_look_up_link (feed, "this doesn't exist"); + g_assert (_link == NULL); + + _link = gdata_feed_look_up_link (feed, "http://schemas.google.com/g/2005#feed"); + g_assert (GDATA_IS_LINK (_link)); + + _link = gdata_feed_look_up_link (feed, "http://schemas.google.com/g/2005#post"); + g_assert (GDATA_IS_LINK (_link)); + + _link = gdata_feed_look_up_link (feed, GDATA_LINK_SELF); + g_assert (GDATA_IS_LINK (_link)); + + /* Check the authors */ + list = gdata_feed_get_authors (feed); + g_assert (list != NULL); + g_assert_cmpint (g_list_length (list), ==, 1); + g_assert (GDATA_IS_AUTHOR (list->data)); + + /* Check the other properties again, the more normal way this time */ + g_assert_cmpstr (gdata_feed_get_title (feed), ==, "Test feed"); + g_assert_cmpstr (gdata_feed_get_subtitle (feed), ==, "Test subtitle"); + g_assert_cmpstr (gdata_feed_get_id (feed), ==, "http://example.com/id"); + g_assert_cmpstr (gdata_feed_get_etag (feed), ==, "W/\"D08FQn8-eil7ImA9WxZbFEw.\""); + + updated2 = gdata_feed_get_updated (feed); + g_assert_cmpint (updated2, ==, 1235570857); + + g_assert_cmpstr (gdata_feed_get_logo (feed), ==, "http://example.com/logo.png"); + g_assert_cmpstr (gdata_feed_get_icon (feed), ==, "http://example.com/icon.png"); + g_assert_cmpstr (gdata_feed_get_rights (feed), ==, "public"); + + generator = gdata_feed_get_generator (feed); + g_assert (GDATA_IS_GENERATOR (generator)); + g_assert_cmpstr (gdata_generator_get_name (generator), ==, "Example Generator"); + g_assert_cmpstr (gdata_generator_get_uri (generator), ==, "http://example.com/"); + g_assert_cmpstr (gdata_generator_get_version (generator), ==, "0.6"); + + g_assert_cmpuint (gdata_feed_get_items_per_page (feed), ==, 50); + g_assert_cmpuint (gdata_feed_get_start_index (feed), ==, 1); + g_assert_cmpuint (gdata_feed_get_total_results (feed), ==, 2); + + g_object_unref (feed); +} + +static void +test_feed_error_handling (void) +{ + GDataFeed *feed; + GError *error = NULL; + +#define TEST_XML_ERROR_HANDLING(x) feed = GDATA_FEED (gdata_parsable_new_from_xml (GDATA_TYPE_FEED, \ + ""\ + x\ + "", -1, &error));\ + g_assert_error (error, GDATA_SERVICE_ERROR, GDATA_SERVICE_ERROR_PROTOCOL_ERROR);\ + g_assert (feed == NULL);\ + g_clear_error (&error) + + /* entry */ + TEST_XML_ERROR_HANDLING ("this isn't a date"); /* invalid entry */ + + /* title */ + TEST_XML_ERROR_HANDLING ("First titleSecond title"); /* duplicate title */ +#if 0 + /* FIXME: Removed due to the YouTube comments feed not being a valid Atom feed. + * See: https://code.google.com/p/gdata-issues/issues/detail?id=2908 + * and: https://bugzilla.gnome.org/show_bug.cgi?id=679072 */ + TEST_XML_ERROR_HANDLING ("ID2009-01-25T14:07:37.880860Z"); /* missing title */ +#endif + + /* subtitle */ + TEST_XML_ERROR_HANDLING ("First subtitleSecond subtitle"); /* duplicate subtitle */ + + /* id */ + TEST_XML_ERROR_HANDLING ("First IDSecond ID"); /* duplicate ID */ + TEST_XML_ERROR_HANDLING ("Title2009-01-25T14:07:37.880860Z"); /* missing ID */ + + /* updated */ + TEST_XML_ERROR_HANDLING ("2009-01-25T14:07:37.880860Z" + "2009-01-25T14:07:37.880860Z"); /* duplicate updated */ + TEST_XML_ERROR_HANDLING ("not a date"); /* invalid date */ + TEST_XML_ERROR_HANDLING ("TitleID"); /* missing updated */ + + /* category */ + TEST_XML_ERROR_HANDLING (""); /* invalid category */ + + /* logo */ + TEST_XML_ERROR_HANDLING ("First logoSecond logo"); /* duplicate logo */ + + /* icon */ + TEST_XML_ERROR_HANDLING ("First iconSecond icon"); /* duplicate icon */ + + /* link */ + TEST_XML_ERROR_HANDLING (""); /* invalid link */ + + /* author */ + TEST_XML_ERROR_HANDLING (""); /* invalid author */ + + /* generator */ + TEST_XML_ERROR_HANDLING ("First generatorSecond generator"); /* duplicate generator */ + TEST_XML_ERROR_HANDLING (""); /* invalid generator */ + + /* openSearch:totalResults */ + TEST_XML_ERROR_HANDLING ("5" + "3"); /* duplicate totalResults */ + TEST_XML_ERROR_HANDLING (""); /* missing content */ + TEST_XML_ERROR_HANDLING ("this isn't a number!"); /* invalid number */ + + /* openSearch:startIndex */ + TEST_XML_ERROR_HANDLING ("5" + "3"); /* duplicate startIndex */ + TEST_XML_ERROR_HANDLING (""); /* missing content */ + TEST_XML_ERROR_HANDLING ("this isn't a number!"); /* invalid number */ + + /* openSearch:itemsPerPage */ + TEST_XML_ERROR_HANDLING ("5" + "3"); /* duplicate itemsPerPage */ + TEST_XML_ERROR_HANDLING (""); /* missing content */ + TEST_XML_ERROR_HANDLING ("this isn't a number!"); /* invalid number */ + +#undef TEST_XML_ERROR_HANDLING +} + +static void +test_feed_escaping (void) +{ + GDataFeed *feed; + GError *error = NULL; + + /* Since we can't construct a GDataEntry directly, we need to parse it from XML */ + feed = GDATA_FEED (gdata_parsable_new_from_xml (GDATA_TYPE_FEED, + "" + "" + "http://foo.com?foo&bar" + "2010-12-10T17:49:15Z" + "Test feed & stuff." + "", -1, &error)); + g_assert_no_error (error); + g_assert (GDATA_IS_FEED (feed)); + + /* Check the outputted XML is escaped properly */ + gdata_test_assert_xml (feed, + "" + "" + "Test feed & stuff." + "http://foo.com?foo&bar" + "2010-12-10T17:49:15Z" + ""); + g_object_unref (feed); +} + +static void +test_query_categories (void) +{ + GDataQuery *query; + gchar *query_uri; + + query = gdata_query_new ("foobar"); + + /* AND */ + gdata_query_set_categories (query, "Fritz/Laurie"); + query_uri = gdata_query_get_query_uri (query, "http://example.com"); + g_assert_cmpstr (query_uri, ==, "http://example.com/-/Fritz/Laurie?q=foobar"); + g_free (query_uri); + + /* OR */ + gdata_query_set_categories (query, "Fritz|Laurie"); + query_uri = gdata_query_get_query_uri (query, "http://example.com"); + g_assert_cmpstr (query_uri, ==, "http://example.com/-/Fritz%7CLaurie?q=foobar"); + g_free (query_uri); + + /* Combination */ + gdata_query_set_categories (query, "A|-{urn:google.com}B/-C"); + query_uri = gdata_query_get_query_uri (query, "http://example.com/gdata_test"); + g_assert_cmpstr (query_uri, ==, "http://example.com/gdata_test/-/A%7C-%7Burn%3Agoogle.com%7DB/-C?q=foobar"); + g_free (query_uri); + + /* Same combination without q param */ + gdata_query_set_q (query, NULL); + query_uri = gdata_query_get_query_uri (query, "http://example.com"); + g_assert_cmpstr (query_uri, ==, "http://example.com/-/A%7C-%7Burn%3Agoogle.com%7DB/-C"); + g_free (query_uri); + + g_object_unref (query); +} + +static void +test_query_dates (void) +{ + GDataQuery *query; + gchar *query_uri; + + query = gdata_query_new ("baz"); + + /* updated-min */ + gdata_query_set_updated_min (query, 1373280114); /* 2013-07-08T10:41:54Z */ + query_uri = gdata_query_get_query_uri (query, "http://example.com"); + g_assert_cmpstr (query_uri, ==, "http://example.com?q=baz&updated-min=2013-07-08T10:41:54Z"); + g_free (query_uri); + gdata_query_set_updated_min (query, -1); + + /* updated-max */ + gdata_query_set_updated_max (query, 1373280114); /* 2013-07-08T10:41:54Z */ + query_uri = gdata_query_get_query_uri (query, "http://example.com"); + g_assert_cmpstr (query_uri, ==, "http://example.com?q=baz&updated-max=2013-07-08T10:41:54Z"); + g_free (query_uri); + gdata_query_set_updated_max (query, -1); + + /* published-min */ + gdata_query_set_published_min (query, 1373280114); /* 2013-07-08T10:41:54Z */ + query_uri = gdata_query_get_query_uri (query, "http://example.com"); + g_assert_cmpstr (query_uri, ==, "http://example.com?q=baz&published-min=2013-07-08T10:41:54Z"); + g_free (query_uri); + gdata_query_set_published_min (query, -1); + + /* published-max */ + gdata_query_set_published_max (query, 1373280114); /* 2013-07-08T10:41:54Z */ + query_uri = gdata_query_get_query_uri (query, "http://example.com"); + g_assert_cmpstr (query_uri, ==, "http://example.com?q=baz&published-max=2013-07-08T10:41:54Z"); + g_free (query_uri); + gdata_query_set_published_max (query, -1); + + g_object_unref (query); +} + +static void +test_query_strict (void) +{ + GDataQuery *query; + gchar *query_uri; + + query = gdata_query_new ("bar"); + + gdata_query_set_is_strict (query, TRUE); + query_uri = gdata_query_get_query_uri (query, "http://example.com"); + g_assert_cmpstr (query_uri, ==, "http://example.com?q=bar&strict=true"); + g_free (query_uri); + + gdata_query_set_is_strict (query, FALSE); + query_uri = gdata_query_get_query_uri (query, "http://example.com"); + g_assert_cmpstr (query_uri, ==, "http://example.com?q=bar"); + g_free (query_uri); + + g_object_unref (query); +} + +static void +test_query_pagination (void) +{ + GDataQuery *query; + gchar *query_uri; + + query = gdata_query_new ("test"); + gdata_query_set_max_results (query, 15); + gdata_query_set_etag (query, "etag"); /* this should be cleared by pagination */ + + query_uri = gdata_query_get_query_uri (query, "http://example.com/"); + g_assert_cmpstr (query_uri, ==, "http://example.com/?q=test&max-results=15"); + g_free (query_uri); + + /* Try the next and previous pages. */ + gdata_query_next_page (query); + g_assert (gdata_query_get_etag (query) == NULL); + + query_uri = gdata_query_get_query_uri (query, "http://example.com/"); + g_assert_cmpstr (query_uri, ==, "http://example.com/?q=test&start-index=16&max-results=15"); + g_free (query_uri); + + gdata_query_set_etag (query, "etag"); + g_assert (gdata_query_previous_page (query) == TRUE); + g_assert (gdata_query_get_etag (query) == NULL); + + query_uri = gdata_query_get_query_uri (query, "http://example.com/"); + g_assert_cmpstr (query_uri, ==, "http://example.com/?q=test&max-results=15"); + g_free (query_uri); + + /* Try another previous page. This should fail, and the ETag should be untouched. */ + gdata_query_set_etag (query, "etag"); + g_assert (gdata_query_previous_page (query) == FALSE); + g_assert_cmpstr (gdata_query_get_etag (query), ==, "etag"); + + g_object_unref (query); + + /* Try the alternate constructor. */ + query = gdata_query_new_with_limits ("test", 40, 10); + + query_uri = gdata_query_get_query_uri (query, "http://example.com/"); + g_assert_cmpstr (query_uri, ==, "http://example.com/?q=test&start-index=40&max-results=10"); + g_free (query_uri); + + /* Try the next and previous pages again. */ + gdata_query_next_page (query); + + query_uri = gdata_query_get_query_uri (query, "http://example.com/"); + g_assert_cmpstr (query_uri, ==, "http://example.com/?q=test&start-index=50&max-results=10"); + g_free (query_uri); + + g_assert (gdata_query_previous_page (query) == TRUE); + + query_uri = gdata_query_get_query_uri (query, "http://example.com/"); + g_assert_cmpstr (query_uri, ==, "http://example.com/?q=test&start-index=40&max-results=10"); + g_free (query_uri); + + g_assert (gdata_query_previous_page (query) == TRUE); + + query_uri = gdata_query_get_query_uri (query, "http://example.com/"); + g_assert_cmpstr (query_uri, ==, "http://example.com/?q=test&start-index=30&max-results=10"); + g_free (query_uri); + + g_object_unref (query); +} + +static void +notify_cb (GObject *obj, GParamSpec *pspec, gpointer user_data) +{ + gboolean *notification_received = user_data; + g_assert (*notification_received == FALSE); + *notification_received = TRUE; +} + +static void +test_query_properties (void) +{ + GDataQuery *query; + gboolean notification_received = FALSE; + gulong handler_id; + + query = gdata_query_new ("default"); + +#define CHECK_PROPERTY(cmptype, name_hyphens, name_underscores, default_val, new_val, new_val2, val_type, free_val) \ + { \ + val_type val; \ + \ + handler_id = g_signal_connect (query, "notify::" name_hyphens, (GCallback) notify_cb, ¬ification_received); \ + \ + g_assert_##cmptype (gdata_query_get_##name_underscores (query), ==, default_val); \ + g_object_get (query, name_hyphens, &val, NULL); \ + g_assert_##cmptype (val, ==, default_val); \ + if (free_val == TRUE) { \ + g_free ((gpointer) ((guintptr) val)); \ + } \ + \ + notification_received = FALSE; \ + gdata_query_set_##name_underscores (query, new_val); \ + g_assert (notification_received == TRUE); \ + \ + g_assert_##cmptype (gdata_query_get_##name_underscores (query), ==, new_val); \ + \ + notification_received = FALSE; \ + g_object_set (query, name_hyphens, (val_type) new_val2, NULL); \ + g_assert (notification_received == TRUE); \ + \ + g_assert_##cmptype (gdata_query_get_##name_underscores (query), ==, new_val2); \ + \ + g_signal_handler_disconnect (query, handler_id); \ + } +#define CHECK_PROPERTY_STR(name_hyphens, name_underscores, default_val) \ + CHECK_PROPERTY (cmpstr, name_hyphens, name_underscores, default_val, "new", "new2", gchar*, TRUE) +#define CHECK_PROPERTY_INT64(name_hyphens, name_underscores, default_val) \ + CHECK_PROPERTY (cmpint, name_hyphens, name_underscores, default_val, 123, 5134132, gint64, FALSE) +#define CHECK_PROPERTY_UINT(name_hyphens, name_underscores, default_val) \ + CHECK_PROPERTY (cmpuint, name_hyphens, name_underscores, default_val, 535, 123, guint, FALSE) +#define CHECK_PROPERTY_BOOLEAN(name_hyphens, name_underscores, default_val) \ + CHECK_PROPERTY (cmpuint, name_hyphens, name_underscores, default_val, TRUE, FALSE, gboolean, FALSE) + + CHECK_PROPERTY_STR ("q", q, "default"); + CHECK_PROPERTY_STR ("categories", categories, NULL); + CHECK_PROPERTY_STR ("author", author, NULL); + CHECK_PROPERTY_INT64 ("updated-min", updated_min, -1); + CHECK_PROPERTY_INT64 ("updated-max", updated_max, -1); + CHECK_PROPERTY_INT64 ("published-min", published_min, -1); + CHECK_PROPERTY_INT64 ("published-max", published_max, -1); + CHECK_PROPERTY_UINT ("start-index", start_index, 0); +#define gdata_query_get_is_strict gdata_query_is_strict + CHECK_PROPERTY_BOOLEAN ("is-strict", is_strict, FALSE); +#undef gdata_query_get_is_strict + CHECK_PROPERTY_UINT ("max-results", max_results, 0); + CHECK_PROPERTY_STR ("etag", etag, NULL); + +#undef CHECK_PROPERTY_BOOLEAN +#undef CHECK_PROPERTY_UINT +#undef CHECK_PROPERTY_INT64 +#undef CHECK_PROPERTY_STR +#undef CHECK_PROPERTY + + g_object_unref (query); +} + +static void +test_query_unicode (void) +{ + GDataQuery *query; + gchar *query_uri; + + g_test_bug ("602497"); + + /* Simple query */ + query = gdata_query_new ("fööbar‽"); + query_uri = gdata_query_get_query_uri (query, "http://example.com"); + g_assert_cmpstr (query_uri, ==, "http://example.com?q=f%C3%B6%C3%B6bar%E2%80%BD"); + g_free (query_uri); + + /* Categories */ + gdata_query_set_categories (query, "Ümlauts|¿Questions‽"); + query_uri = gdata_query_get_query_uri (query, "http://example.com"); + g_assert_cmpstr (query_uri, ==, "http://example.com/-/%C3%9Cmlauts%7C%C2%BFQuestions%E2%80%BD?q=f%C3%B6%C3%B6bar%E2%80%BD"); + g_free (query_uri); + + /* Author */ + gdata_query_set_author (query, "Lørd Brïan Bleßêd"); + query_uri = gdata_query_get_query_uri (query, "http://example.com"); + g_assert_cmpstr (query_uri, ==, "http://example.com/-/%C3%9Cmlauts%7C%C2%BFQuestions%E2%80%BD?q=f%C3%B6%C3%B6bar%E2%80%BD&author=L%C3%B8rd%20Br%C3%AFan%20Ble%C3%9F%C3%AAd"); + g_free (query_uri); + + g_object_unref (query); +} + +static void +test_query_etag (void) +{ + GDataQuery *query = gdata_query_new (NULL); + + /* Test that setting any property will unset the ETag */ + g_test_bug ("613529"); + + /* Also check that setting the ETag doesn't unset the ETag! */ + gdata_query_set_etag (query, "foobar"); + g_assert_cmpstr (gdata_query_get_etag (query), ==, "foobar"); + +#define CHECK_ETAG(C) \ + gdata_query_set_etag (query, "foobar"); \ + C; \ + g_assert (gdata_query_get_etag (query) == NULL); + + CHECK_ETAG (gdata_query_set_q (query, "q")) + CHECK_ETAG (gdata_query_set_categories (query, "shizzle,foobar")) + CHECK_ETAG (gdata_query_set_author (query, "John Smith")) + CHECK_ETAG (gdata_query_set_updated_min (query, -1)) + CHECK_ETAG (gdata_query_set_updated_max (query, -1)) + CHECK_ETAG (gdata_query_set_published_min (query, -1)) + CHECK_ETAG (gdata_query_set_published_max (query, -1)) + CHECK_ETAG (gdata_query_set_start_index (query, 5)) + CHECK_ETAG (gdata_query_set_is_strict (query, TRUE)) + CHECK_ETAG (gdata_query_set_max_results (query, 1000)) + CHECK_ETAG (gdata_query_next_page (query)) + CHECK_ETAG (g_assert (gdata_query_previous_page (query))) + +#undef CHECK_ETAG + + g_object_unref (query); +} + +static void +test_service_network_error (void) +{ + GDataService *service; +#if 0 + SoupURI *proxy_uri; +#endif + GError *error = NULL; + + /* Skip this test unless explicitly asked for, so that we don’t do network accesses on build machines by default. */ + if (!g_test_slow ()) { + g_test_skip ("Test requires network access"); + return; + } + + /* This is a little hacky, but it should work */ + service = g_object_new (GDATA_TYPE_SERVICE, NULL); + + /* Try a query which should always fail due to errors resolving the hostname */ + g_assert (gdata_service_query (service, NULL, "https://thisshouldnotexist.invalid", NULL, GDATA_TYPE_ENTRY, + NULL, NULL, NULL, &error) == NULL); + g_assert_error (error, GDATA_SERVICE_ERROR, GDATA_SERVICE_ERROR_NETWORK_ERROR); + g_clear_error (&error); + + /* TODO: We have to disable this test, as libsoup 2.30.2 < x <= 2.32.0 doesn't return SOUP_STATUS_CANT_RESOLVE_PROXY properly any more. + * Filed as bgo#632354. */ +#if 0 + /* Try one with a bad proxy set */ + proxy_uri = soup_uri_new ("https://thisshouldalsonotexist.invalid/proxy"); + gdata_service_set_proxy_uri (service, proxy_uri); + soup_uri_free (proxy_uri); + + g_assert (gdata_service_query (service, "https://google.com", NULL, GDATA_TYPE_ENTRY, NULL, NULL, NULL, &error) == NULL); + g_assert_error (error, GDATA_SERVICE_ERROR, GDATA_SERVICE_ERROR_PROXY_ERROR); + g_clear_error (&error); +#endif + + g_object_unref (service); +} + +static void +test_service_locale (void) +{ + GDataService *service; + gchar *locale; + + /* This is a little hacky, but it should work */ + service = g_object_new (GDATA_TYPE_SERVICE, NULL); + + /* Just test setting and getting the locale */ + g_assert (gdata_service_get_locale (service) == NULL); + gdata_service_set_locale (service, "en_GB"); + g_assert_cmpstr (gdata_service_get_locale (service), ==, "en_GB"); + + g_object_get (service, "locale", &locale, NULL); + g_assert_cmpstr (locale, ==, "en_GB"); + g_free (locale); + + g_object_unref (service); +} + +static void +test_access_rule_get_xml (void) +{ + GDataAccessRule *rule, *rule2; + const gchar *content_type; + gchar *xml, *role, *scope_type3, *scope_value3, *key; + gint64 edited, edited2; + const gchar *scope_type, *scope_value, *scope_type2, *scope_value2; + GError *error = NULL; + + rule = gdata_access_rule_new ("an-id"); + + /* Test setting properties directly */ + g_object_set (G_OBJECT (rule), + "role", "A role", + "scope-type", "A scope type", + "scope-value", "A scope value", + NULL); + + g_assert_cmpstr (gdata_access_rule_get_role (rule), ==, "A role"); + gdata_access_rule_get_scope (rule, &scope_type, &scope_value); + g_assert_cmpstr (scope_type, ==, "A scope type"); + g_assert_cmpstr (scope_value, ==, "A scope value"); + edited = gdata_access_rule_get_edited (rule); + g_assert_cmpuint (edited, >, 0); /* current time */ + g_assert_cmpstr (gdata_access_rule_get_key (rule), ==, NULL); + + /* Set the properties more conventionally */ + gdata_access_rule_set_role (rule, GDATA_ACCESS_ROLE_NONE); + gdata_access_rule_set_scope (rule, GDATA_ACCESS_SCOPE_USER, "foo@example.com"); + + content_type = gdata_parsable_get_content_type (GDATA_PARSABLE (rule)); + g_assert_cmpstr (content_type, ==, "application/atom+xml"); + + /* Check the generated XML's OK */ + gdata_test_assert_xml (rule, + "" + "" + "none" + "an-id" + "" + "" + "" + ""); + + /* Check again by re-parsing the XML to a GDataAccessRule */ + xml = gdata_parsable_get_xml (GDATA_PARSABLE (rule)); + rule2 = GDATA_ACCESS_RULE (gdata_parsable_new_from_xml (GDATA_TYPE_ACCESS_RULE, xml, -1, &error)); + g_assert_no_error (error); + g_assert (GDATA_IS_ACCESS_RULE (rule2)); + g_clear_error (&error); + g_free (xml); + + content_type = gdata_parsable_get_content_type (GDATA_PARSABLE (rule2)); + g_assert_cmpstr (content_type, ==, "application/atom+xml"); + + g_assert_cmpstr (gdata_access_rule_get_role (rule), ==, gdata_access_rule_get_role (rule2)); + gdata_access_rule_get_scope (rule, &scope_type, &scope_value); + gdata_access_rule_get_scope (rule2, &scope_type2, &scope_value2); + g_assert_cmpstr (scope_type, ==, scope_type2); + g_assert_cmpstr (scope_value, ==, scope_value2); + edited = gdata_access_rule_get_edited (rule2); + g_assert_cmpuint (edited, ==, -1); /* unspecified in XML */ + g_assert_cmpstr (gdata_access_rule_get_key (rule), ==, gdata_access_rule_get_key (rule2)); + + /* Check properties a different way */ + g_object_get (G_OBJECT (rule2), + "role", &role, + "scope-type", &scope_type3, + "scope-value", &scope_value3, + "edited", &edited2, + "key", &key, + NULL); + + g_assert_cmpstr (role, ==, gdata_access_rule_get_role (rule)); + g_assert_cmpstr (scope_type, ==, scope_type3); + g_assert_cmpstr (scope_value, ==, scope_value3); + g_assert_cmpuint (edited2, ==, -1); + g_assert_cmpstr (key, ==, NULL); + + g_free (role); + g_free (scope_type3); + g_free (scope_value3); + + /* Test that the GDataAccessRule:role and GDataEntry:title properties are linked */ + gdata_entry_set_title (GDATA_ENTRY (rule), "Another role"); + g_assert_cmpstr (gdata_access_rule_get_role (rule), ==, "Another role"); + gdata_access_rule_set_role (rule, GDATA_ACCESS_ROLE_NONE); + g_assert_cmpstr (gdata_entry_get_title (GDATA_ENTRY (rule)), ==, "none"); + + g_object_unref (rule); + g_object_unref (rule2); + + /* Check that a rule with scope type 'default' doesn't have a value. + * See: https://developers.google.com/google-apps/calendar/v2/reference#gacl_reference */ + rule = gdata_access_rule_new ("another-id"); + gdata_access_rule_set_role (rule, GDATA_ACCESS_ROLE_NONE); + gdata_access_rule_set_scope (rule, GDATA_ACCESS_SCOPE_DEFAULT, NULL); + + content_type = gdata_parsable_get_content_type (GDATA_PARSABLE (rule)); + g_assert_cmpstr (content_type, ==, "application/atom+xml"); + + /* Check the generated XML's OK */ + gdata_test_assert_xml (rule, + "" + "" + "none" + "another-id" + "" + "" + "" + ""); + + /* Check by re-parsing the XML to a GDataAccessRule */ + xml = gdata_parsable_get_xml (GDATA_PARSABLE (rule)); + rule2 = GDATA_ACCESS_RULE (gdata_parsable_new_from_xml (GDATA_TYPE_ACCESS_RULE, xml, -1, &error)); + g_assert_no_error (error); + g_assert (GDATA_IS_ACCESS_RULE (rule2)); + g_clear_error (&error); + g_free (xml); + + content_type = gdata_parsable_get_content_type (GDATA_PARSABLE (rule2)); + g_assert_cmpstr (content_type, ==, "application/atom+xml"); + + g_assert_cmpstr (gdata_access_rule_get_role (rule), ==, gdata_access_rule_get_role (rule2)); + gdata_access_rule_get_scope (rule, &scope_type, &scope_value); + gdata_access_rule_get_scope (rule2, &scope_type2, &scope_value2); + g_assert_cmpstr (scope_type, ==, scope_type2); + g_assert_cmpstr (scope_value, ==, scope_value2); + edited = gdata_access_rule_get_edited (rule2); + g_assert_cmpuint (edited, ==, -1); /* unspecified in XML */ + + g_object_unref (rule); + g_object_unref (rule2); +} + +static void +test_access_rule_get_xml_with_key (void) +{ + GDataAccessRule *rule; + gint64 edited; + const gchar *content_type, *scope_type, *scope_value; + GError *error = NULL; + + rule = GDATA_ACCESS_RULE (gdata_parsable_new_from_xml (GDATA_TYPE_ACCESS_RULE, + "" + "" + "none" + "an-id" + "" + "" + "" + "", -1, &error)); + g_assert_no_error (error); + g_assert (GDATA_IS_ACCESS_RULE (rule)); + + /* Check the properties. */ + g_assert_cmpstr (gdata_access_rule_get_role (rule), ==, "none"); + gdata_access_rule_get_scope (rule, &scope_type, &scope_value); + g_assert_cmpstr (scope_type, ==, "user"); + g_assert_cmpstr (scope_value, ==, "foo@example.com"); + edited = gdata_access_rule_get_edited (rule); + g_assert_cmpuint (edited, >, 0); /* current time */ + g_assert_cmpstr (gdata_access_rule_get_key (rule), ==, "asdasd"); + + content_type = gdata_parsable_get_content_type (GDATA_PARSABLE (rule)); + g_assert_cmpstr (content_type, ==, "application/atom+xml"); + + /* Check the outputted XML is the same. */ + gdata_test_assert_xml (rule, + "" + "" + "none" + "an-id" + "" + "" + "" + ""); + + g_object_unref (rule); +} + +static void +test_access_rule_error_handling (void) +{ + GDataAccessRule *rule; + GError *error = NULL; + +#define TEST_XML_ERROR_HANDLING(x) rule = GDATA_ACCESS_RULE (gdata_parsable_new_from_xml (GDATA_TYPE_ACCESS_RULE,\ + ""\ + x\ + "", -1, &error));\ + g_assert_error (error, GDATA_SERVICE_ERROR, GDATA_SERVICE_ERROR_PROTOCOL_ERROR);\ + g_assert (rule == NULL);\ + g_clear_error (&error) + + /* role */ + TEST_XML_ERROR_HANDLING (""); /* missing value */ + + /* scope */ + TEST_XML_ERROR_HANDLING (""); /* missing type */ + TEST_XML_ERROR_HANDLING (""); /* missing value */ + TEST_XML_ERROR_HANDLING (""); /* missing value */ + + /* edited */ + TEST_XML_ERROR_HANDLING (""); /* missing date */ + TEST_XML_ERROR_HANDLING ("not a date"); /* bad date */ + + /* withKey */ + TEST_XML_ERROR_HANDLING (""); /* missing key */ + TEST_XML_ERROR_HANDLING (""); /* missing role */ + TEST_XML_ERROR_HANDLING (""); /* missing role */ + +#undef TEST_XML_ERROR_HANDLING +} + +static void +test_access_rule_escaping (void) +{ + GDataAccessRule *rule; + + rule = gdata_access_rule_new (NULL); + gdata_access_rule_set_role (rule, ""); + gdata_access_rule_set_scope (rule, "", ""); + + /* Check the outputted XML is escaped properly */ + gdata_test_assert_xml (rule, + "" + "" + "<role>" + "" + "" + "" + ""); + g_object_unref (rule); +} + +static void +test_comparable (void) +{ + GDataComparable *category = GDATA_COMPARABLE (gdata_category_new ("term", "http://scheme", "label")); + + /* Test the NULL comparisons */ + g_assert_cmpint (gdata_comparable_compare (category, NULL), ==, 1); + g_assert_cmpint (gdata_comparable_compare (NULL, category), ==, -1); + g_assert_cmpint (gdata_comparable_compare (NULL, NULL), ==, 0); + g_assert_cmpint (gdata_comparable_compare (category, category), ==, 0); + + g_object_unref (category); +} + +static void +test_color_parsing (void) +{ + GDataColor color; + + /* With hash */ + g_assert (gdata_color_from_hexadecimal ("#F99Ff0", &color) == TRUE); + g_assert_cmpuint (color.red, ==, 249); + g_assert_cmpuint (color.green, ==, 159); + g_assert_cmpuint (color.blue, ==, 240); + + /* Without hash */ + g_assert (gdata_color_from_hexadecimal ("F99Ff0", &color) == TRUE); + g_assert_cmpuint (color.red, ==, 249); + g_assert_cmpuint (color.green, ==, 159); + g_assert_cmpuint (color.blue, ==, 240); + + /* Invalid, but correct length */ + g_assert (gdata_color_from_hexadecimal ("foobar", &color) == FALSE); + + /* Wildly invalid */ + g_assert (gdata_color_from_hexadecimal ("this is not a real colour!", &color) == FALSE); +} + +static void +test_color_output (void) +{ + GDataColor color; + gchar *color_string; + + /* General test */ + g_assert (gdata_color_from_hexadecimal ("#F99Ff0", &color) == TRUE); + color_string = gdata_color_to_hexadecimal (&color); + g_assert_cmpstr (color_string, ==, "#f99ff0"); + g_free (color_string); + + /* Boundary tests */ + g_assert (gdata_color_from_hexadecimal ("#ffffff", &color) == TRUE); + color_string = gdata_color_to_hexadecimal (&color); + g_assert_cmpstr (color_string, ==, "#ffffff"); + g_free (color_string); + + g_assert (gdata_color_from_hexadecimal ("#000000", &color) == TRUE); + color_string = gdata_color_to_hexadecimal (&color); + g_assert_cmpstr (color_string, ==, "#000000"); + g_free (color_string); +} + +/*static void +test_media_thumbnail_parse_time (const gchar *locale) +{ + g_test_bug ("584737"); + + g_test_message ("Testing gdata_media_thumbnail_parse_time in the \"%s\" locale...", locale); + g_assert_cmpstr (setlocale (LC_ALL, locale), ==, locale); + + g_assert_cmpint (gdata_media_thumbnail_parse_time ("00:01:42.500"), ==, 102500); + g_assert_cmpint (gdata_media_thumbnail_parse_time ("00:02:45"), ==, 165000); + g_assert_cmpint (gdata_media_thumbnail_parse_time ("12:00:15.000"), ==, 43215000); + g_assert_cmpint (gdata_media_thumbnail_parse_time ("00:00:00"), ==, 0); + g_assert_cmpint (gdata_media_thumbnail_parse_time ("foobar"), ==, -1); + + setlocale (LC_ALL, ""); +}*/ + +static void +test_atom_author (void) +{ + GDataAuthor *author, *author2; + const gchar *content_type; + gchar *name, *uri, *email_address; + GError *error = NULL; + + author = GDATA_AUTHOR (gdata_parsable_new_from_xml (GDATA_TYPE_AUTHOR, + "" + "John Smöth" + "http://example.com/" + "john@example.com" + "", -1, &error)); + g_assert_no_error (error); + g_assert (GDATA_IS_AUTHOR (author)); + g_clear_error (&error); + + /* Check the properties */ + g_assert_cmpstr (gdata_author_get_name (author), ==, "John Smöth"); + g_assert_cmpstr (gdata_author_get_uri (author), ==, "http://example.com/"); + g_assert_cmpstr (gdata_author_get_email_address (author), ==, "john@example.com"); + + /* Compare it against another identical author */ + author2 = gdata_author_new ("John Smöth", "http://example.com/", "john@example.com"); + g_assert_cmpint (gdata_comparable_compare (GDATA_COMPARABLE (author), GDATA_COMPARABLE (author2)), ==, 0); + g_object_unref (author2); + + /* …and a different author */ + author2 = gdata_author_new ("Brian Blessed", NULL, NULL); + g_assert_cmpint (gdata_comparable_compare (GDATA_COMPARABLE (author), GDATA_COMPARABLE (author2)), !=, 0); + g_object_unref (author2); + + content_type = gdata_parsable_get_content_type (GDATA_PARSABLE (author)); + g_assert_cmpstr (content_type, ==, "application/atom+xml"); + + /* Check the outputted XML is the same */ + gdata_test_assert_xml (author, + "" + "" + "John Smöth" + "http://example.com/" + "john@example.com" + ""); + + /* Check the properties */ + g_object_get (G_OBJECT (author), + "name", &name, + "uri", &uri, + "email-address", &email_address, + NULL); + + g_assert_cmpstr (name, ==, "John Smöth"); + g_assert_cmpstr (uri, ==, "http://example.com/"); + g_assert_cmpstr (email_address, ==, "john@example.com"); + + g_free (name); + g_free (uri); + g_free (email_address); + g_object_unref (author); + + /* Now parse an author with little information available */ + author = GDATA_AUTHOR (gdata_parsable_new_from_xml (GDATA_TYPE_AUTHOR, + "" + "James Johnson" + "", -1, &error)); + g_assert_no_error (error); + g_assert (GDATA_IS_AUTHOR (author)); + g_clear_error (&error); + + content_type = gdata_parsable_get_content_type (GDATA_PARSABLE (author)); + g_assert_cmpstr (content_type, ==, "application/atom+xml"); + + /* Check the properties */ + g_assert_cmpstr (gdata_author_get_name (author), ==, "James Johnson"); + g_assert (gdata_author_get_uri (author) == NULL); + g_assert (gdata_author_get_email_address (author) == NULL); + + g_object_unref (author); +} + +static void +test_atom_author_error_handling (void) +{ + GDataAuthor *author; + GError *error = NULL; + +#define TEST_XML_ERROR_HANDLING(x) author = GDATA_AUTHOR (gdata_parsable_new_from_xml (GDATA_TYPE_AUTHOR,\ + ""\ + x\ + "", -1, &error));\ + g_assert_error (error, GDATA_SERVICE_ERROR, GDATA_SERVICE_ERROR_PROTOCOL_ERROR);\ + g_assert (author == NULL);\ + g_clear_error (&error) + + /* name */ + TEST_XML_ERROR_HANDLING ("John SmöthNot John Smöth"); /* duplicated name */ + TEST_XML_ERROR_HANDLING (""); /* empty name */ + TEST_XML_ERROR_HANDLING ("http://example.com/john@example.com"); /* missing name */ + + /* uri */ + TEST_XML_ERROR_HANDLING ("http://example.com/http://another-example.com/"); /* duplicated URI */ + + /* email */ + TEST_XML_ERROR_HANDLING ("john@example.comjohn@another-example.com"); /* duplicated e-mail address */ + +#undef TEST_XML_ERROR_HANDLING +} + +static void +test_atom_author_escaping (void) +{ + GDataAuthor *author; + + author = gdata_author_new ("First & Last Name", "http://foo.com?foo&bar", "John Smith "); + + /* Check the outputted XML is escaped properly */ + gdata_test_assert_xml (author, + "" + "" + "First & Last Name" + "http://foo.com?foo&bar" + "John Smith <john.smith@gmail.com>" + ""); + g_object_unref (author); +} + +static void +test_atom_category (void) +{ + GDataCategory *category, *category2; + const gchar *content_type; + gchar *term, *scheme, *label; + GError *error = NULL; + + category = GDATA_CATEGORY (gdata_parsable_new_from_xml (GDATA_TYPE_CATEGORY, + "", -1, &error)); + g_assert_no_error (error); + g_assert (GDATA_IS_CATEGORY (category)); + g_clear_error (&error); + + /* Check the properties */ + g_assert_cmpstr (gdata_category_get_term (category), ==, "jokes"); + g_assert_cmpstr (gdata_category_get_scheme (category), ==, "http://foobar.com#categories"); + g_assert_cmpstr (gdata_category_get_label (category), ==, "Jokes & Trivia"); + + /* Compare it against another identical category */ + category2 = gdata_category_new ("jokes", "http://foobar.com#categories", "Jokes & Trivia"); + g_assert_cmpint (gdata_comparable_compare (GDATA_COMPARABLE (category), GDATA_COMPARABLE (category2)), ==, 0); + g_object_unref (category2); + + /* …and a different category */ + category2 = gdata_category_new ("sports", "http://foobar.com#categories", NULL); + g_assert_cmpint (gdata_comparable_compare (GDATA_COMPARABLE (category), GDATA_COMPARABLE (category2)), !=, 0); + g_object_unref (category2); + + content_type = gdata_parsable_get_content_type (GDATA_PARSABLE (category)); + g_assert_cmpstr (content_type, ==, "application/atom+xml"); + + /* Check the outputted XML is the same */ + gdata_test_assert_xml (category, + "" + ""); + + /* Check the properties */ + g_object_get (G_OBJECT (category), + "term", &term, + "scheme", &scheme, + "label", &label, + NULL); + + g_assert_cmpstr (term, ==, "jokes"); + g_assert_cmpstr (scheme, ==, "http://foobar.com#categories"); + g_assert_cmpstr (label, ==, "Jokes & Trivia"); + + g_free (term); + g_free (scheme); + g_free (label); + g_object_unref (category); + + /* Now parse a category with less information available */ + category = GDATA_CATEGORY (gdata_parsable_new_from_xml (GDATA_TYPE_CATEGORY, + "", -1, &error)); + g_assert_no_error (error); + g_assert (GDATA_IS_CATEGORY (category)); + g_clear_error (&error); + + content_type = gdata_parsable_get_content_type (GDATA_PARSABLE (category)); + g_assert_cmpstr (content_type, ==, "application/atom+xml"); + + /* Check the properties */ + g_assert_cmpstr (gdata_category_get_term (category), ==, "sports"); + g_assert (gdata_category_get_scheme (category) == NULL); + g_assert (gdata_category_get_label (category) == NULL); + g_object_unref (category); + + /* Try a category with custom content */ + category = GDATA_CATEGORY (gdata_parsable_new_from_xml (GDATA_TYPE_CATEGORY, + "" + "" + "" + "", -1, &error)); + g_assert_no_error (error); + g_assert (GDATA_IS_CATEGORY (category)); + g_clear_error (&error); + + content_type = gdata_parsable_get_content_type (GDATA_PARSABLE (category)); + g_assert_cmpstr (content_type, ==, "application/atom+xml"); + + /* Check the outputted XML contains the unknown XML */ + gdata_test_assert_xml (category, + "" + "" + "" + "" + ""); + g_object_unref (category); +} + +static void +test_atom_category_error_handling (void) +{ + GDataCategory *category; + GError *error = NULL; + + /* Missing term */ + category = GDATA_CATEGORY (gdata_parsable_new_from_xml (GDATA_TYPE_CATEGORY, "", -1, &error)); + g_assert_error (error, GDATA_SERVICE_ERROR, GDATA_SERVICE_ERROR_PROTOCOL_ERROR); + g_assert (category == NULL); + g_clear_error (&error); +} + +static void +test_atom_category_escaping (void) +{ + GDataCategory *category; + + category = gdata_category_new ("", "http://foo.com?foo&bar", "Label & Stuff"); + + /* Check the outputted XML is escaped properly */ + gdata_test_assert_xml (category, + "" + ""); + g_object_unref (category); +} + +static void +test_atom_generator (void) +{ + GDataGenerator *generator, *generator2; + const gchar *content_type; + gchar *name, *uri, *version; + GError *error = NULL; + + generator = GDATA_GENERATOR (gdata_parsable_new_from_xml (GDATA_TYPE_GENERATOR, + "Bach & Son's Generator", -1, &error)); + g_assert_no_error (error); + g_assert (GDATA_IS_GENERATOR (generator)); + g_clear_error (&error); + + content_type = gdata_parsable_get_content_type (GDATA_PARSABLE (generator)); + g_assert_cmpstr (content_type, ==, "application/atom+xml"); + + /* Compare it against another identical generator */ + generator2 = GDATA_GENERATOR (gdata_parsable_new_from_xml (GDATA_TYPE_GENERATOR, + "Bach & Son's Generator", -1, NULL)); + g_assert_cmpint (gdata_comparable_compare (GDATA_COMPARABLE (generator), GDATA_COMPARABLE (generator2)), ==, 0); + g_object_unref (generator2); + + /* …and a different generator */ + generator2 = GDATA_GENERATOR (gdata_parsable_new_from_xml (GDATA_TYPE_GENERATOR, + "Different generator", -1, &error)); + g_assert_no_error (error); + g_assert (GDATA_IS_GENERATOR (generator)); + g_assert_cmpint (gdata_comparable_compare (GDATA_COMPARABLE (generator), GDATA_COMPARABLE (generator2)), !=, 0); + g_object_unref (generator2); + + /* Check the properties */ + g_assert_cmpstr (gdata_generator_get_name (generator), ==, "Bach & Son's Generator"); + g_assert_cmpstr (gdata_generator_get_uri (generator), ==, "http://example.com/"); + g_assert_cmpstr (gdata_generator_get_version (generator), ==, "15"); + + /* Check them a different way too */ + g_object_get (G_OBJECT (generator), + "name", &name, + "uri", &uri, + "version", &version, + NULL); + + g_assert_cmpstr (name, ==, "Bach & Son's Generator"); + g_assert_cmpstr (uri, ==, "http://example.com/"); + g_assert_cmpstr (version, ==, "15"); + + g_free (name); + g_free (uri); + g_free (version); + g_object_unref (generator); + + /* Now parse a generator with less information available */ + generator = GDATA_GENERATOR (gdata_parsable_new_from_xml (GDATA_TYPE_GENERATOR, + "", -1, &error)); + g_assert_no_error (error); + g_assert (GDATA_IS_GENERATOR (generator)); + g_clear_error (&error); + + content_type = gdata_parsable_get_content_type (GDATA_PARSABLE (generator)); + g_assert_cmpstr (content_type, ==, "application/atom+xml"); + + /* Check the properties */ + g_assert (gdata_generator_get_name (generator) == NULL); + g_assert (gdata_generator_get_uri (generator) == NULL); + g_assert (gdata_generator_get_version (generator) == NULL); + g_object_unref (generator); +} + +static void +test_atom_generator_error_handling (void) +{ + GDataGenerator *generator; + GError *error = NULL; + + /* Empty URI */ + generator = GDATA_GENERATOR (gdata_parsable_new_from_xml (GDATA_TYPE_GENERATOR, "", -1, &error)); + g_assert_error (error, GDATA_SERVICE_ERROR, GDATA_SERVICE_ERROR_PROTOCOL_ERROR); + g_assert (generator == NULL); + g_clear_error (&error); +} + +static void +test_atom_link (void) +{ + GDataLink *link1, *link2; + gchar *uri, *relation_type, *content_type, *language, *title; + gint length; + GError *error = NULL; + + link1 = GDATA_LINK (gdata_parsable_new_from_xml (GDATA_TYPE_LINK, + "", -1, &error)); + g_assert_no_error (error); + g_assert (GDATA_IS_LINK (link1)); + g_clear_error (&error); + + /* Check the properties */ + g_assert_cmpstr (gdata_link_get_uri (link1), ==, "http://example.com/"); + g_assert_cmpstr (gdata_link_get_relation_type (link1), ==, "http://test.com#link-type"); + g_assert_cmpstr (gdata_link_get_content_type (link1), ==, "text/plain"); + g_assert_cmpstr (gdata_link_get_language (link1), ==, "de"); + g_assert_cmpstr (gdata_link_get_title (link1), ==, "All About Angle Brackets: <, >"); + g_assert_cmpint (gdata_link_get_length (link1), ==, 2000); + + /* Compare it against another identical link */ + link2 = gdata_link_new ("http://example.com/", "http://test.com#link-type"); + g_assert_cmpint (gdata_comparable_compare (GDATA_COMPARABLE (link1), GDATA_COMPARABLE (link2)), ==, 0); + gdata_link_set_content_type (link2, "text/plain"); + gdata_link_set_language (link2, "de"); + gdata_link_set_title (link2, "All About Angle Brackets: <, >"); + gdata_link_set_length (link2, 2000); + g_assert_cmpint (gdata_comparable_compare (GDATA_COMPARABLE (link1), GDATA_COMPARABLE (link2)), ==, 0); + + /* Try with a dissimilar link */ + gdata_link_set_uri (link2, "http://gnome.org/"); + g_assert_cmpint (gdata_comparable_compare (GDATA_COMPARABLE (link1), GDATA_COMPARABLE (link2)), !=, 0); + g_object_unref (link2); + + g_assert_cmpstr (gdata_parsable_get_content_type (GDATA_PARSABLE (link1)), ==, "application/atom+xml"); + + /* Check the outputted XML is the same */ + gdata_test_assert_xml (link1, + "" + ""); + + /* Set some of the properties */ + g_object_set (G_OBJECT (link1), + "uri", "http://another-example.com/", + "relation-type", "http://test.com#link-type2", + "content-type", "text/html", + "language", "sv", + "title", "This & That About ", + "length", -1, + NULL); + + /* Check the properties */ + g_object_get (G_OBJECT (link1), + "uri", &uri, + "relation-type", &relation_type, + "content-type", &content_type, + "language", &language, + "title", &title, + "length", &length, + NULL); + + g_assert_cmpstr (uri, ==, "http://another-example.com/"); + g_assert_cmpstr (relation_type, ==, "http://test.com#link-type2"); + g_assert_cmpstr (content_type, ==, "text/html"); + g_assert_cmpstr (language, ==, "sv"); + g_assert_cmpstr (title, ==, "This & That About "); + g_assert_cmpint (length, ==, -1); + + g_free (uri); + g_free (relation_type); + g_free (content_type); + g_free (language); + g_free (title); + g_object_unref (link1); + + /* Now parse a link with less information available */ + link1 = GDATA_LINK (gdata_parsable_new_from_xml (GDATA_TYPE_LINK, + "Test Content", -1, &error)); + g_assert_no_error (error); + g_assert (GDATA_IS_LINK (link1)); + g_clear_error (&error); + + /* Check the properties */ + g_assert_cmpstr (gdata_link_get_uri (link1), ==, "http://shizzle.com"); + g_assert_cmpstr (gdata_link_get_relation_type (link1), ==, "http://www.iana.org/assignments/relation/alternate"); + g_assert (gdata_link_get_content_type (link1) == NULL); + g_assert (gdata_link_get_language (link1) == NULL); + g_assert (gdata_link_get_title (link1) == NULL); + g_assert (gdata_link_get_length (link1) == -1); + + g_assert_cmpstr (gdata_parsable_get_content_type (GDATA_PARSABLE (link1)), ==, "application/atom+xml"); + + /* Check the outputted XML contains the unknown XML */ + gdata_test_assert_xml (link1, + "" + "" + "Test Content"); + g_object_unref (link1); +} + +static void +test_atom_link_error_handling (void) +{ + GDataLink *_link; /* stupid unistd.h */ + GError *error = NULL; + +#define TEST_XML_ERROR_HANDLING(x) _link = GDATA_LINK (gdata_parsable_new_from_xml (GDATA_TYPE_LINK,\ + "", -1, &error));\ + g_assert_error (error, GDATA_SERVICE_ERROR, GDATA_SERVICE_ERROR_PROTOCOL_ERROR);\ + g_assert (_link == NULL);\ + g_clear_error (&error) + + /* href */ + TEST_XML_ERROR_HANDLING (""); /* missing href */ + TEST_XML_ERROR_HANDLING ("href=''"); /* empty href */ + + /* rel */ + TEST_XML_ERROR_HANDLING ("href='http://example.com/' rel=''"); /* empty rel */ + + /* type */ + TEST_XML_ERROR_HANDLING ("href='http://example.com/' type=''"); /* empty type */ + + /* hreflang */ + TEST_XML_ERROR_HANDLING ("href='http://example.com/' hreflang=''"); /* empty hreflang */ + +#undef TEST_XML_ERROR_HANDLING +} + +static void +test_atom_link_escaping (void) +{ + GDataLink *_link; + + _link = gdata_link_new ("http://foo.com?foo&bar", "http://foo.com?foo&relation=bar"); + gdata_link_set_content_type (_link, ""); + gdata_link_set_language (_link, ""); + gdata_link_set_title (_link, "Title & stuff"); + + + /* Check the outputted XML is escaped properly */ + gdata_test_assert_xml (_link, + "" + ""); + g_object_unref (_link); +} + +static void +test_app_categories (void) +{ + GDataAPPCategories *categories; + GList *_categories; + gboolean fixed; + const gchar *content_type; + GError *error = NULL; + + categories = GDATA_APP_CATEGORIES (gdata_parsable_new_from_json (GDATA_TYPE_APP_CATEGORIES, + "{" + "'kind': 'youtube#videoCategoryListResponse'," + "'etag': '\"tbWC5XrSXxe1WOAx6MK9z4hHSU8/1v2mrzYSYG6onNLt2qTj13hkQZk\"'," + "'items': [" + "{" + "'kind': 'youtube#videoCategory'," + "'etag': '\"tbWC5XrSXxe1WOAx6MK9z4hHSU8/Xy1mB4_yLrHy_BmKmPBggty2mZQ\"'," + "'id': '1'," + "'snippet': {" + "'channelId': 'UCBR8-60-B28hp2BmDPdntcQ'," + "'title': 'Film & Animation'," + "'assignable': true" + "}" + "}," + "{" + "'kind': 'youtube#videoCategory'," + "'etag': '\"tbWC5XrSXxe1WOAx6MK9z4hHSU8/UZ1oLIIz2dxIhO45ZTFR3a3NyTA\"'," + "'id': '2'," + "'snippet': {" + "'channelId': 'UCBR8-60-B28hp2BmDPdntcQ'," + "'title': 'Autos & Vehicles'," + "'assignable': true" + "}" + "}" + "]" + "}", -1, &error)); + g_assert_no_error (error); + g_assert (GDATA_IS_APP_CATEGORIES (categories)); + g_clear_error (&error); + + content_type = gdata_parsable_get_content_type (GDATA_PARSABLE (categories)); + g_assert_cmpstr (content_type, ==, "application/json"); + + /* Check the properties */ + g_assert (gdata_app_categories_is_fixed (categories) == FALSE); + + /* Check them a different way too */ + g_object_get (G_OBJECT (categories), "is-fixed", &fixed, NULL); + g_assert (fixed == FALSE); + + /* Check the categories and scheme inheritance */ + _categories = gdata_app_categories_get_categories (categories); + g_assert_cmpint (g_list_length (_categories), ==, 2); + + g_assert (GDATA_IS_CATEGORY (_categories->data)); + g_assert_cmpstr (gdata_category_get_scheme (GDATA_CATEGORY (_categories->data)), ==, NULL); + g_assert_cmpstr (gdata_category_get_label (GDATA_CATEGORY (_categories->data)), ==, "Film & Animation"); + + g_assert (GDATA_IS_CATEGORY (_categories->next->data)); + g_assert_cmpstr (gdata_category_get_scheme (GDATA_CATEGORY (_categories->next->data)), ==, NULL); + g_assert_cmpstr (gdata_category_get_label (GDATA_CATEGORY (_categories->next->data)), ==, "Autos & Vehicles"); + + g_object_unref (categories); + + /* Now parse one with less information available */ + categories = GDATA_APP_CATEGORIES (gdata_parsable_new_from_json (GDATA_TYPE_APP_CATEGORIES, + "{" + "'kind': 'youtube#videoCategoryListResponse'," + "'items': []" + "}", -1, &error)); + g_assert_no_error (error); + g_assert (GDATA_IS_APP_CATEGORIES (categories)); + g_clear_error (&error); + + content_type = gdata_parsable_get_content_type (GDATA_PARSABLE (categories)); + g_assert_cmpstr (content_type, ==, "application/json"); + + /* Check the properties */ + g_assert (gdata_app_categories_is_fixed (categories) == FALSE); + g_object_unref (categories); +} + +static void +test_gd_email_address (void) +{ + GDataGDEmailAddress *email, *email2; + GError *error = NULL; + const gchar *content_type; + + email = GDATA_GD_EMAIL_ADDRESS (gdata_parsable_new_from_xml (GDATA_TYPE_GD_EMAIL_ADDRESS, + "", -1, &error)); + g_assert_no_error (error); + g_assert (GDATA_IS_GD_EMAIL_ADDRESS (email)); + g_clear_error (&error); + + /* Check the properties */ + g_assert_cmpstr (gdata_gd_email_address_get_address (email), ==, "fubar@gmail.com"); + g_assert_cmpstr (gdata_gd_email_address_get_relation_type (email), ==, GDATA_GD_EMAIL_ADDRESS_HOME); + g_assert_cmpstr (gdata_gd_email_address_get_label (email), ==, "Personal & Private"); + g_assert_cmpstr (gdata_gd_email_address_get_display_name (email), ==, ""); + g_assert (gdata_gd_email_address_is_primary (email) == TRUE); + + /* Compare it against another identical address */ + email2 = gdata_gd_email_address_new ("fubar@gmail.com", GDATA_GD_EMAIL_ADDRESS_HOME, "Personal & Private", TRUE); + gdata_gd_email_address_set_display_name (email2, ""); + g_assert_cmpint (gdata_comparable_compare (GDATA_COMPARABLE (email), GDATA_COMPARABLE (email2)), ==, 0); + + /* …and a different one */ + gdata_gd_email_address_set_address (email2, "test@example.com"); + g_assert_cmpint (gdata_comparable_compare (GDATA_COMPARABLE (email), GDATA_COMPARABLE (email2)), !=, 0); + g_object_unref (email2); + + content_type = gdata_parsable_get_content_type (GDATA_PARSABLE (email)); + g_assert_cmpstr (content_type, ==, "application/atom+xml"); + + /* Check the outputted XML is the same */ + gdata_test_assert_xml (email, + "" + ""); + g_object_unref (email); + + /* Now parse an address with less information available */ + email = GDATA_GD_EMAIL_ADDRESS (gdata_parsable_new_from_xml (GDATA_TYPE_GD_EMAIL_ADDRESS, + "", -1, &error)); + g_assert_no_error (error); + g_assert (GDATA_IS_GD_EMAIL_ADDRESS (email)); + g_clear_error (&error); + + /* Check the properties */ + g_assert_cmpstr (gdata_gd_email_address_get_address (email), ==, "test@example.com"); + g_assert (gdata_gd_email_address_get_relation_type (email) == NULL); + g_assert (gdata_gd_email_address_get_label (email) == NULL); + g_assert (gdata_gd_email_address_get_display_name (email) == NULL); + g_assert (gdata_gd_email_address_is_primary (email) == FALSE); + + content_type = gdata_parsable_get_content_type (GDATA_PARSABLE (email)); + g_assert_cmpstr (content_type, ==, "application/atom+xml"); + + /* Check the outputted XML contains the unknown XML */ + gdata_test_assert_xml (email, + "" + ""); + g_object_unref (email); +} + +static void +test_gd_email_address_escaping (void) +{ + GDataGDEmailAddress *email; + + g_test_bug ("630350"); + + email = gdata_gd_email_address_new ("Fubar ", GDATA_GD_EMAIL_ADDRESS_HOME "?foo&bar", "Personal & Private", TRUE); + gdata_gd_email_address_set_display_name (email, ""); + + /* Check the outputted XML is escaped properly */ + gdata_test_assert_xml (email, + "" + ""); + g_object_unref (email); +} + +static void +test_gd_email_address_comparison (void) +{ + GDataGDEmailAddress *email1, *email2; + + /* Should only compare equal if addresses are equal. */ + email1 = gdata_gd_email_address_new ("foo@example.com", NULL, NULL, TRUE); + email2 = gdata_gd_email_address_new ("foo@example.com", NULL, "label", FALSE); + g_assert_cmpint (gdata_comparable_compare (GDATA_COMPARABLE (email1), GDATA_COMPARABLE (email2)), ==, 0); + + gdata_gd_email_address_set_address (email1, "bar@example.com"); + g_assert_cmpint (gdata_comparable_compare (GDATA_COMPARABLE (email1), GDATA_COMPARABLE (email2)), !=, 0); + + g_object_unref (email2); + g_object_unref (email1); +} + +static void +test_gd_im_address (void) +{ + GDataGDIMAddress *im, *im2; + GError *error = NULL; + const gchar *content_type; + + im = GDATA_GD_IM_ADDRESS (gdata_parsable_new_from_xml (GDATA_TYPE_GD_IM_ADDRESS, + "", -1, &error)); + g_assert_no_error (error); + g_assert (GDATA_IS_GD_IM_ADDRESS (im)); + g_clear_error (&error); + + /* Check the properties */ + g_assert_cmpstr (gdata_gd_im_address_get_address (im), ==, "foo@bar.msn.com"); + g_assert_cmpstr (gdata_gd_im_address_get_protocol (im), ==, GDATA_GD_IM_PROTOCOL_LIVE_MESSENGER); + g_assert_cmpstr (gdata_gd_im_address_get_relation_type (im), ==, GDATA_GD_IM_ADDRESS_HOME); + g_assert (gdata_gd_im_address_get_label (im) == NULL); + g_assert (gdata_gd_im_address_is_primary (im) == TRUE); + + /* Compare it against another identical address */ + im2 = gdata_gd_im_address_new ("foo@bar.msn.com", GDATA_GD_IM_PROTOCOL_LIVE_MESSENGER, GDATA_GD_IM_ADDRESS_HOME, NULL, TRUE); + g_assert_cmpint (gdata_comparable_compare (GDATA_COMPARABLE (im), GDATA_COMPARABLE (im2)), ==, 0); + + /* …and a different one */ + gdata_gd_im_address_set_protocol (im2, GDATA_GD_IM_PROTOCOL_GOOGLE_TALK); + g_assert_cmpint (gdata_comparable_compare (GDATA_COMPARABLE (im), GDATA_COMPARABLE (im2)), !=, 0); + g_object_unref (im2); + + content_type = gdata_parsable_get_content_type (GDATA_PARSABLE (im)); + g_assert_cmpstr (content_type, ==, "application/atom+xml"); + + /* Check the outputted XML is the same */ + gdata_test_assert_xml (im, + "" + ""); + g_object_unref (im); + + /* Now parse an address with less information available */ + im = GDATA_GD_IM_ADDRESS (gdata_parsable_new_from_xml (GDATA_TYPE_GD_IM_ADDRESS, + "", -1, &error)); + g_assert_no_error (error); + g_assert (GDATA_IS_GD_IM_ADDRESS (im)); + g_clear_error (&error); + + /* Check the properties */ + g_assert_cmpstr (gdata_gd_im_address_get_address (im), ==, "foo@baz.example.com"); + g_assert (gdata_gd_im_address_get_protocol (im) == NULL); + g_assert (gdata_gd_im_address_get_relation_type (im) == NULL); + g_assert_cmpstr (gdata_gd_im_address_get_label (im), ==, "Other & Miscellaneous"); + g_assert (gdata_gd_im_address_is_primary (im) == FALSE); + + content_type = gdata_parsable_get_content_type (GDATA_PARSABLE (im)); + g_assert_cmpstr (content_type, ==, "application/atom+xml"); + + /* Check the outputted XML contains the unknown XML */ + gdata_test_assert_xml (im, + "" + ""); + g_object_unref (im); +} + +static void +test_gd_im_address_escaping (void) +{ + GDataGDIMAddress *im; + + im = gdata_gd_im_address_new ("Fubar ", GDATA_GD_IM_PROTOCOL_GOOGLE_TALK "?foo&bar", GDATA_GD_IM_ADDRESS_HOME "?foo&bar", + "Personal & Private", TRUE); + + /* Check the outputted XML is escaped properly */ + gdata_test_assert_xml (im, + "" + ""); + g_object_unref (im); +} + +static void +test_gd_im_address_comparison (void) +{ + GDataGDIMAddress *im_address1, *im_address2; + + /* Should only compare equal if address and protocol are both equal. */ + im_address1 = gdata_gd_im_address_new ("foo@example.com", GDATA_GD_IM_PROTOCOL_LIVE_MESSENGER, NULL, NULL, TRUE); + im_address2 = gdata_gd_im_address_new ("foo@example.com", GDATA_GD_IM_PROTOCOL_LIVE_MESSENGER, NULL, "label", FALSE); + g_assert_cmpint (gdata_comparable_compare (GDATA_COMPARABLE (im_address1), GDATA_COMPARABLE (im_address2)), ==, 0); + + /* Different addresses, same protocol. */ + gdata_gd_im_address_set_address (im_address1, "bar@example.com"); + g_assert_cmpint (gdata_comparable_compare (GDATA_COMPARABLE (im_address1), GDATA_COMPARABLE (im_address2)), !=, 0); + + /* Same address, different protocols. */ + gdata_gd_im_address_set_address (im_address1, "foo@example.com"); + gdata_gd_im_address_set_protocol (im_address1, GDATA_GD_IM_PROTOCOL_JABBER); + g_assert_cmpint (gdata_comparable_compare (GDATA_COMPARABLE (im_address1), GDATA_COMPARABLE (im_address2)), !=, 0); + + g_object_unref (im_address2); + g_object_unref (im_address1); +} + +static void +test_gd_name (void) +{ + GDataGDName *name, *name2; + GError *error = NULL; + const gchar *content_type; + + name = GDATA_GD_NAME (gdata_parsable_new_from_xml (GDATA_TYPE_GD_NAME, + "" + "Brian" + "Charles" + "Blessed" + "Mr" + "ABC" + "Mr Brian Charles Blessed, ABC" + "", -1, &error)); + g_assert_no_error (error); + g_assert (GDATA_IS_GD_NAME (name)); + g_clear_error (&error); + + /* Check the properties */ + g_assert_cmpstr (gdata_gd_name_get_given_name (name), ==, "Brian"); + g_assert_cmpstr (gdata_gd_name_get_additional_name (name), ==, "Charles"); + g_assert_cmpstr (gdata_gd_name_get_family_name (name), ==, "Blessed"); + g_assert_cmpstr (gdata_gd_name_get_prefix (name), ==, "Mr"); + g_assert_cmpstr (gdata_gd_name_get_suffix (name), ==, "ABC"); + g_assert_cmpstr (gdata_gd_name_get_full_name (name), ==, "Mr Brian Charles Blessed, ABC"); + + /* Compare it against another identical name */ + name2 = gdata_gd_name_new ("Brian", "Blessed"); + gdata_gd_name_set_additional_name (name2, "Charles"); + gdata_gd_name_set_prefix (name2, "Mr"); + gdata_gd_name_set_suffix (name2, "ABC"); + g_assert_cmpint (gdata_comparable_compare (GDATA_COMPARABLE (name), GDATA_COMPARABLE (name2)), ==, 0); + + /* …and a different one */ + gdata_gd_name_set_prefix (name2, "Mrs"); + g_assert_cmpint (gdata_comparable_compare (GDATA_COMPARABLE (name), GDATA_COMPARABLE (name2)), !=, 0); + g_object_unref (name2); + + content_type = gdata_parsable_get_content_type (GDATA_PARSABLE (name)); + g_assert_cmpstr (content_type, ==, "application/atom+xml"); + + /* Check the outputted XML is the same */ + gdata_test_assert_xml (name, + "" + "" + "Brian" + "Charles" + "Blessed" + "Mr" + "ABC" + "Mr Brian Charles Blessed, ABC" + ""); + g_object_unref (name); + + /* Now parse an address with less information available */ + name = GDATA_GD_NAME (gdata_parsable_new_from_xml (GDATA_TYPE_GD_NAME, + "Bob", -1, &error)); + g_assert_no_error (error); + g_assert (GDATA_IS_GD_NAME (name)); + g_clear_error (&error); + + /* Check the properties */ + g_assert_cmpstr (gdata_gd_name_get_given_name (name), ==, "Bob"); + g_assert (gdata_gd_name_get_additional_name (name) == NULL); + g_assert (gdata_gd_name_get_family_name (name) == NULL); + g_assert (gdata_gd_name_get_prefix (name) == NULL); + g_assert (gdata_gd_name_get_suffix (name) == NULL); + g_assert (gdata_gd_name_get_full_name (name) == NULL); + + content_type = gdata_parsable_get_content_type (GDATA_PARSABLE (name)); + g_assert_cmpstr (content_type, ==, "application/atom+xml"); + + /* Check the outputted XML is still correct */ + gdata_test_assert_xml (name, + "" + "" + "Bob" + ""); + g_object_unref (name); +} + +static void +test_gd_name_empty_strings (void) +{ + GDataGDName *name; + GError *error = NULL; + + g_test_bug ("662290"); + + /* Test that empty full names get treated as NULL correctly. */ + name = GDATA_GD_NAME (gdata_parsable_new_from_xml (GDATA_TYPE_GD_NAME, + "" + "" + "", -1, &error)); + g_assert_no_error (error); + g_assert (GDATA_IS_GD_NAME (name)); + g_clear_error (&error); + + /* Check the properties */ + g_assert_cmpstr (gdata_gd_name_get_given_name (name), ==, NULL); + g_assert_cmpstr (gdata_gd_name_get_additional_name (name), ==, NULL); + g_assert_cmpstr (gdata_gd_name_get_family_name (name), ==, NULL); + g_assert_cmpstr (gdata_gd_name_get_prefix (name), ==, NULL); + g_assert_cmpstr (gdata_gd_name_get_suffix (name), ==, NULL); + g_assert_cmpstr (gdata_gd_name_get_full_name (name), ==, NULL); + + g_object_unref (name); + + /* Build a name with an empty string full name and check the serialisation */ + name = gdata_gd_name_new ("Georgey", "Porgey"); + gdata_gd_name_set_full_name (name, ""); + + g_assert_cmpstr (gdata_gd_name_get_full_name (name), ==, NULL); + + /* Check the outputted XML is the same */ + gdata_test_assert_xml (name, + "" + "" + "Georgey" + "Porgey" + ""); + + g_object_unref (name); +} + +static void +test_gd_name_comparison (void) +{ + GDataGDName *name1, *name2; + + /* Names are only equal if the given, additional and family names are all equal, and the prefixes are equal too. */ + name1 = gdata_gd_name_new ("Given", "Family"); + gdata_gd_name_set_additional_name (name1, "Additional"); + gdata_gd_name_set_prefix (name1, "Mrs"); + name2 = gdata_gd_name_new ("Given", "Family"); + gdata_gd_name_set_additional_name (name2, "Additional"); + gdata_gd_name_set_prefix (name2, "Mrs"); + + g_assert_cmpint (gdata_comparable_compare (GDATA_COMPARABLE (name1), GDATA_COMPARABLE (name2)), ==, 0); + + /* Different given names. */ + gdata_gd_name_set_given_name (name1, "Different"); + g_assert_cmpint (gdata_comparable_compare (GDATA_COMPARABLE (name1), GDATA_COMPARABLE (name2)), !=, 0); + + /* Different additional names. */ + gdata_gd_name_set_given_name (name1, "Given"); + gdata_gd_name_set_additional_name (name1, "Different"); + g_assert_cmpint (gdata_comparable_compare (GDATA_COMPARABLE (name1), GDATA_COMPARABLE (name2)), !=, 0); + + /* Different family names. */ + gdata_gd_name_set_additional_name (name1, "Additional"); + gdata_gd_name_set_family_name (name1, "Different"); + g_assert_cmpint (gdata_comparable_compare (GDATA_COMPARABLE (name1), GDATA_COMPARABLE (name2)), !=, 0); + + /* Different prefixes. */ + gdata_gd_name_set_family_name (name1, "Family"); + gdata_gd_name_set_prefix (name1, "Mr"); + g_assert_cmpint (gdata_comparable_compare (GDATA_COMPARABLE (name1), GDATA_COMPARABLE (name2)), !=, 0); + + g_object_unref (name2); + g_object_unref (name1); +} + +static void +test_gd_organization (void) +{ + GDataGDOrganization *org, *org2; + GDataGDWhere *location; + GError *error = NULL; + const gchar *content_type; + + org = GDATA_GD_ORGANIZATION (gdata_parsable_new_from_xml (GDATA_TYPE_GD_ORGANIZATION, + "" + "Google, Inc." + "<Angle Bracketeer>" + "Finance" + "Doing stuff." + "FOO" + "" + "", -1, &error)); + g_assert_no_error (error); + g_assert (GDATA_IS_GD_ORGANIZATION (org)); + g_clear_error (&error); + + /* Check the properties */ + g_assert_cmpstr (gdata_gd_organization_get_name (org), ==, "Google, Inc."); + g_assert_cmpstr (gdata_gd_organization_get_title (org), ==, ""); + g_assert_cmpstr (gdata_gd_organization_get_relation_type (org), ==, GDATA_GD_ORGANIZATION_WORK); + g_assert_cmpstr (gdata_gd_organization_get_label (org), ==, "Work & Occupation"); + g_assert_cmpstr (gdata_gd_organization_get_department (org), ==, "Finance"); + g_assert_cmpstr (gdata_gd_organization_get_job_description (org), ==, "Doing stuff."); + g_assert_cmpstr (gdata_gd_organization_get_symbol (org), ==, "FOO"); + location = gdata_gd_organization_get_location (org); + g_assert (GDATA_IS_GD_WHERE (location)); + g_assert (gdata_gd_organization_is_primary (org) == TRUE); + + /* Compare it against another identical organization */ + org2 = gdata_gd_organization_new ("Google, Inc.", "", GDATA_GD_ORGANIZATION_WORK, "Work & Occupation", TRUE); + gdata_gd_organization_set_department (org2, "Finance"); + gdata_gd_organization_set_location (org2, location); + g_assert_cmpint (gdata_comparable_compare (GDATA_COMPARABLE (org), GDATA_COMPARABLE (org2)), ==, 0); + + /* …and a different one */ + gdata_gd_organization_set_title (org2, "Demoted!"); + g_assert_cmpint (gdata_comparable_compare (GDATA_COMPARABLE (org), GDATA_COMPARABLE (org2)), !=, 0); + g_object_unref (org2); + + content_type = gdata_parsable_get_content_type (GDATA_PARSABLE (org)); + g_assert_cmpstr (content_type, ==, "application/atom+xml"); + + /* Check the outputted XML is the same */ + gdata_test_assert_xml (org, + "" + "" + "Google, Inc." + "<Angle Bracketeer>" + "Finance" + "Doing stuff." + "FOO" + "" + ""); + g_object_unref (org); + + /* Now parse an organization with less information available */ + org = GDATA_GD_ORGANIZATION (gdata_parsable_new_from_xml (GDATA_TYPE_GD_ORGANIZATION, + "", -1, &error)); + g_assert_no_error (error); + g_assert (GDATA_IS_GD_ORGANIZATION (org)); + g_clear_error (&error); + + /* Check the properties */ + g_assert (gdata_gd_organization_get_name (org) == NULL); + g_assert (gdata_gd_organization_get_title (org) == NULL); + g_assert (gdata_gd_organization_get_relation_type (org) == NULL); + g_assert (gdata_gd_organization_get_label (org) == NULL); + g_assert (gdata_gd_organization_is_primary (org) == FALSE); + g_assert (gdata_gd_organization_get_department (org) == NULL); + g_assert (gdata_gd_organization_get_job_description (org) == NULL); + g_assert (gdata_gd_organization_get_symbol (org) == NULL); + g_assert (gdata_gd_organization_get_location (org) == NULL); + + content_type = gdata_parsable_get_content_type (GDATA_PARSABLE (org)); + g_assert_cmpstr (content_type, ==, "application/atom+xml"); + + /* Check the outputted XML contains the unknown XML */ + gdata_test_assert_xml (org, + "" + ""); + g_object_unref (org); +} + +static void +test_gd_organization_escaping (void) +{ + GDataGDOrganization *org; + + org = gdata_gd_organization_new ("Steptoe & Son", "Title & Stuff", GDATA_GD_ORGANIZATION_WORK "?foo&bar", "Personal & Private", TRUE); + gdata_gd_organization_set_department (org, "Department & Stuff"); + gdata_gd_organization_set_job_description (org, "Escaping ."); + gdata_gd_organization_set_symbol (org, "<&>"); + + /* Check the outputted XML is escaped properly */ + gdata_test_assert_xml (org, + "" + "" + "Steptoe & Son" + "Title & Stuff" + "Department & Stuff" + "Escaping <brackets>." + "<&>" + ""); + g_object_unref (org); +} + +static void +test_gd_organization_comparison (void) +{ + GDataGDOrganization *org1, *org2; + + /* Organisation positions are equal if the name, title and department are all equal. */ + org1 = gdata_gd_organization_new ("Name", "Title", NULL, NULL, TRUE); + gdata_gd_organization_set_department (org1, "Department"); + org2 = gdata_gd_organization_new ("Name", "Title", NULL, "label", FALSE); + gdata_gd_organization_set_department (org2, "Department"); + + g_assert_cmpint (gdata_comparable_compare (GDATA_COMPARABLE (org1), GDATA_COMPARABLE (org2)), ==, 0); + + /* Different name. */ + gdata_gd_organization_set_name (org1, "Different"); + g_assert_cmpint (gdata_comparable_compare (GDATA_COMPARABLE (org1), GDATA_COMPARABLE (org2)), !=, 0); + + /* Different title. */ + gdata_gd_organization_set_name (org1, "Name"); + gdata_gd_organization_set_title (org1, "Different"); + g_assert_cmpint (gdata_comparable_compare (GDATA_COMPARABLE (org1), GDATA_COMPARABLE (org2)), !=, 0); + + /* Different department. */ + gdata_gd_organization_set_title (org1, "Title"); + gdata_gd_organization_set_department (org1, "Different"); + g_assert_cmpint (gdata_comparable_compare (GDATA_COMPARABLE (org1), GDATA_COMPARABLE (org2)), !=, 0); + + g_object_unref (org2); + g_object_unref (org1); +} + +static void +test_gd_phone_number (void) +{ + GDataGDPhoneNumber *phone, *phone2; + GError *error = NULL; + const gchar *content_type; + + phone = GDATA_GD_PHONE_NUMBER (gdata_parsable_new_from_xml (GDATA_TYPE_GD_PHONE_NUMBER, + "+1 206 555 1212", -1, &error)); + g_assert_no_error (error); + g_assert (GDATA_IS_GD_PHONE_NUMBER (phone)); + g_clear_error (&error); + + /* Check the properties */ + g_assert_cmpstr (gdata_gd_phone_number_get_number (phone), ==, "+1 206 555 1212"); + g_assert_cmpstr (gdata_gd_phone_number_get_uri (phone), ==, "tel:+12065551212"); + g_assert_cmpstr (gdata_gd_phone_number_get_relation_type (phone), ==, GDATA_GD_PHONE_NUMBER_MOBILE); + g_assert_cmpstr (gdata_gd_phone_number_get_label (phone), ==, "Personal & business calls only"); + g_assert (gdata_gd_phone_number_is_primary (phone) == FALSE); + + /* Compare it against another identical number */ + phone2 = gdata_gd_phone_number_new ("+1 206 555 1212", GDATA_GD_PHONE_NUMBER_MOBILE, "Personal & business calls only", + "tel:+12065551212", FALSE); + g_assert_cmpint (gdata_comparable_compare (GDATA_COMPARABLE (phone), GDATA_COMPARABLE (phone2)), ==, 0); + + /* …and a different one */ + gdata_gd_phone_number_set_number (phone2, "+1 206 555 1212 666"); + gdata_gd_phone_number_set_uri (phone2, NULL); + g_assert_cmpint (gdata_comparable_compare (GDATA_COMPARABLE (phone), GDATA_COMPARABLE (phone2)), !=, 0); + g_object_unref (phone2); + + content_type = gdata_parsable_get_content_type (GDATA_PARSABLE (phone)); + g_assert_cmpstr (content_type, ==, "application/atom+xml"); + + /* Check the outputted XML is the same */ + gdata_test_assert_xml (phone, + "" + "+1 206 555 1212"); + + /* Check we trim whitespace properly, and respect Unicode characters */ + gdata_gd_phone_number_set_number (phone, " 0123456 (789) ëxt 300 "); + g_assert_cmpstr (gdata_gd_phone_number_get_number (phone), ==, "0123456 (789) ëxt 300"); + g_object_unref (phone); + + /* Now parse a phone number with less information available, but some extraneous whitespace */ + phone = GDATA_GD_PHONE_NUMBER (gdata_parsable_new_from_xml (GDATA_TYPE_GD_PHONE_NUMBER, + " (425) 555-8080 ext. 72585 \n ", -1, &error)); + g_assert_no_error (error); + g_assert (GDATA_IS_GD_PHONE_NUMBER (phone)); + g_clear_error (&error); + + /* Check the properties */ + g_assert_cmpstr (gdata_gd_phone_number_get_number (phone), ==, "(425) 555-8080 ext. 72585"); + g_assert (gdata_gd_phone_number_get_uri (phone) == NULL); + g_assert (gdata_gd_phone_number_get_relation_type (phone) == NULL); + g_assert (gdata_gd_phone_number_get_label (phone) == NULL); + g_assert (gdata_gd_phone_number_is_primary (phone) == FALSE); + + content_type = gdata_parsable_get_content_type (GDATA_PARSABLE (phone)); + g_assert_cmpstr (content_type, ==, "application/atom+xml"); + + /* Check the outputted XML contains the unknown XML */ + gdata_test_assert_xml (phone, + "" + "(425) 555-8080 ext. 72585"); + g_object_unref (phone); +} + +static void +test_gd_phone_number_escaping (void) +{ + GDataGDPhoneNumber *phone; + + phone = gdata_gd_phone_number_new ("0123456789 <54>", GDATA_GD_PHONE_NUMBER_WORK_MOBILE "?foo&bar", "Personal & Private", + "tel:+012345678954?foo&bar", TRUE); + + /* Check the outputted XML is escaped properly */ + gdata_test_assert_xml (phone, + "" + "0123456789 <54>"); + g_object_unref (phone); +} + +static void +test_gd_phone_number_comparison (void) +{ + GDataGDPhoneNumber *phone1, *phone2; + + /* Phone numbers are equal if the number or the URI matches (NULL URIs cannot match). */ + phone1 = gdata_gd_phone_number_new ("123", NULL, NULL, "phone://123", TRUE); + phone2 = gdata_gd_phone_number_new ("123", NULL, "label", "phone://123", FALSE); + g_assert_cmpint (gdata_comparable_compare (GDATA_COMPARABLE (phone1), GDATA_COMPARABLE (phone2)), ==, 0); + + /* Same numbers, different URIs. */ + gdata_gd_phone_number_set_uri (phone1, "phone://+44123"); + g_assert_cmpint (gdata_comparable_compare (GDATA_COMPARABLE (phone1), GDATA_COMPARABLE (phone2)), ==, 0); + + /* Different numbers, same URIs. */ + gdata_gd_phone_number_set_uri (phone1, "phone://123"); + gdata_gd_phone_number_set_number (phone1, "+44123"); + g_assert_cmpint (gdata_comparable_compare (GDATA_COMPARABLE (phone1), GDATA_COMPARABLE (phone2)), ==, 0); + + /* Different numbers and URIs. */ + gdata_gd_phone_number_set_number (phone1, "456"); + gdata_gd_phone_number_set_uri (phone1, "phone://456"); + g_assert_cmpint (gdata_comparable_compare (GDATA_COMPARABLE (phone1), GDATA_COMPARABLE (phone2)), !=, 0); + + /* Different numbers, NULL URIs. */ + gdata_gd_phone_number_set_uri (phone1, NULL); + gdata_gd_phone_number_set_uri (phone2, NULL); + g_assert_cmpint (gdata_comparable_compare (GDATA_COMPARABLE (phone1), GDATA_COMPARABLE (phone2)), !=, 0); + + /* Same numbers, NULL URIs. */ + gdata_gd_phone_number_set_number (phone1, "123"); + g_assert_cmpint (gdata_comparable_compare (GDATA_COMPARABLE (phone1), GDATA_COMPARABLE (phone2)), ==, 0); + + g_object_unref (phone2); + g_object_unref (phone1); +} + +static void +test_gd_postal_address (void) +{ + GDataGDPostalAddress *postal, *postal2; + GError *error = NULL; + const gchar *content_type; + + postal = GDATA_GD_POSTAL_ADDRESS (gdata_parsable_new_from_xml (GDATA_TYPE_GD_POSTAL_ADDRESS, + "" + "500 West 45th Street" + "New York" + "NY 10036" + "United States" + "", -1, &error)); + g_assert_no_error (error); + g_assert (GDATA_IS_GD_POSTAL_ADDRESS (postal)); + g_clear_error (&error); + + /* Check the properties */ + g_assert_cmpstr (gdata_gd_postal_address_get_street (postal), ==, "500 West 45th Street"); + g_assert_cmpstr (gdata_gd_postal_address_get_city (postal), ==, "New York"); + g_assert_cmpstr (gdata_gd_postal_address_get_postcode (postal), ==, "NY 10036"); + g_assert_cmpstr (gdata_gd_postal_address_get_relation_type (postal), ==, GDATA_GD_POSTAL_ADDRESS_HOME); + g_assert_cmpstr (gdata_gd_postal_address_get_label (postal), ==, "Home & Safe House"); + g_assert_cmpstr (gdata_gd_postal_address_get_country (postal), ==, "United States"); + g_assert_cmpstr (gdata_gd_postal_address_get_country_code (postal), ==, "US"); + g_assert (gdata_gd_postal_address_is_primary (postal) == TRUE); + + /* Compare it against another identical address */ + postal2 = gdata_gd_postal_address_new (GDATA_GD_POSTAL_ADDRESS_HOME, "Home & Safe House", TRUE); + gdata_gd_postal_address_set_street (postal2, "500 West 45th Street"); + gdata_gd_postal_address_set_city (postal2, "New York"); + gdata_gd_postal_address_set_postcode (postal2, "NY 10036"); + gdata_gd_postal_address_set_country (postal2, "United States", "US"); + g_assert_cmpint (gdata_comparable_compare (GDATA_COMPARABLE (postal), GDATA_COMPARABLE (postal2)), ==, 0); + + /* …and a different one */ + gdata_gd_postal_address_set_city (postal2, "Atlas Mountains"); + g_assert_cmpint (gdata_comparable_compare (GDATA_COMPARABLE (postal), GDATA_COMPARABLE (postal2)), !=, 0); + g_object_unref (postal2); + + content_type = gdata_parsable_get_content_type (GDATA_PARSABLE (postal)); + g_assert_cmpstr (content_type, ==, "application/atom+xml"); + + /* Check the outputted XML is the same */ + gdata_test_assert_xml (postal, + "" + "" + "500 West 45th Street" + "New York" + "NY 10036" + "United States" + ""); + + /* Check we trim whitespace properly, and respect Unicode characters */ + gdata_gd_postal_address_set_address (postal, " Schöne Grüße Straße\nGermany "); + g_assert_cmpstr (gdata_gd_postal_address_get_address (postal), ==, "Schöne Grüße Straße\nGermany"); + g_object_unref (postal); + + /* Now parse an address with less information available */ + postal = GDATA_GD_POSTAL_ADDRESS (gdata_parsable_new_from_xml (GDATA_TYPE_GD_POSTAL_ADDRESS, + "f", + -1, &error)); + g_assert_no_error (error); + g_assert (GDATA_IS_GD_POSTAL_ADDRESS (postal)); + g_clear_error (&error); + + /* Check the properties */ + g_assert_cmpstr (gdata_gd_postal_address_get_street (postal), ==, "f"); + g_assert (gdata_gd_postal_address_get_relation_type (postal) == NULL); + g_assert (gdata_gd_postal_address_get_label (postal) == NULL); + g_assert (gdata_gd_postal_address_is_primary (postal) == FALSE); + + content_type = gdata_parsable_get_content_type (GDATA_PARSABLE (postal)); + g_assert_cmpstr (content_type, ==, "application/atom+xml"); + + /* Check the outputted XML contains the unknown XML */ + gdata_test_assert_xml (postal, + "" + "" + "f"); + g_object_unref (postal); +} + +static void +test_gd_postal_address_escaping (void) +{ + GDataGDPostalAddress *address; + + address = gdata_gd_postal_address_new (GDATA_GD_POSTAL_ADDRESS_WORK "?foo&bar", "Personal & Private", TRUE); + gdata_gd_postal_address_set_address (address, "
"); + gdata_gd_postal_address_set_mail_class (address, GDATA_GD_MAIL_CLASS_BOTH "?foo&bar"); + gdata_gd_postal_address_set_usage (address, GDATA_GD_ADDRESS_USAGE_GENERAL "?foo&bar"); + gdata_gd_postal_address_set_agent (address, ""); + gdata_gd_postal_address_set_house_name (address, "House & House"); + gdata_gd_postal_address_set_street (address, "Church & Main Street"); + gdata_gd_postal_address_set_po_box (address, "<515>"); + gdata_gd_postal_address_set_neighborhood (address, ""); + gdata_gd_postal_address_set_city (address, "City <17>"); + gdata_gd_postal_address_set_subregion (address, "Subregion <5>"); + gdata_gd_postal_address_set_region (address, ""); + gdata_gd_postal_address_set_postcode (address, "Postcode & stuff"); + gdata_gd_postal_address_set_country (address, "", ""); + + /* Check the outputted XML is escaped properly */ + gdata_test_assert_xml (address, + "" + "" + "<agent>" + "House & House" + "Church & Main Street" + "<515>" + "<neighbourhood>" + "City <17>" + "Subregion <5>" + "<region>" + "Postcode & stuff" + "<foo>" + "<address>" + ""); + g_object_unref (address); +} + +static void +test_gd_postal_address_comparison (void) +{ + GDataGDPostalAddress *address1, *address2; + + /* Postal addresses compare equal if the street, city, PO box and postcode are all equal. */ + address1 = gdata_gd_postal_address_new (NULL, NULL, TRUE); + gdata_gd_postal_address_set_street (address1, "Street"); + gdata_gd_postal_address_set_city (address1, "City"); + gdata_gd_postal_address_set_po_box (address1, "PO box"); + gdata_gd_postal_address_set_postcode (address1, "Postcode"); + address2 = gdata_gd_postal_address_new (NULL, "label", FALSE); + gdata_gd_postal_address_set_street (address2, "Street"); + gdata_gd_postal_address_set_city (address2, "City"); + gdata_gd_postal_address_set_po_box (address2, "PO box"); + gdata_gd_postal_address_set_postcode (address2, "Postcode"); + + g_assert_cmpint (gdata_comparable_compare (GDATA_COMPARABLE (address1), GDATA_COMPARABLE (address2)), ==, 0); + + /* Different streets. */ + gdata_gd_postal_address_set_street (address1, "Different"); + g_assert_cmpint (gdata_comparable_compare (GDATA_COMPARABLE (address1), GDATA_COMPARABLE (address2)), !=, 0); + + /* Different cities. */ + gdata_gd_postal_address_set_street (address1, "Street"); + gdata_gd_postal_address_set_city (address1, "Different"); + g_assert_cmpint (gdata_comparable_compare (GDATA_COMPARABLE (address1), GDATA_COMPARABLE (address2)), !=, 0); + + /* Different PO box. */ + gdata_gd_postal_address_set_city (address1, "City"); + gdata_gd_postal_address_set_po_box (address1, "Different"); + g_assert_cmpint (gdata_comparable_compare (GDATA_COMPARABLE (address1), GDATA_COMPARABLE (address2)), !=, 0); + + /* Different postcode. */ + gdata_gd_postal_address_set_po_box (address1, "PO box"); + gdata_gd_postal_address_set_postcode (address1, "Different"); + g_assert_cmpint (gdata_comparable_compare (GDATA_COMPARABLE (address1), GDATA_COMPARABLE (address2)), !=, 0); + + g_object_unref (address2); + g_object_unref (address1); +} + +static void +test_gd_reminder (void) +{ + GDataGDReminder *reminder, *reminder2; + gint64 _time; + GError *error = NULL; + const gchar *content_type; + + reminder = GDATA_GD_REMINDER (gdata_parsable_new_from_xml (GDATA_TYPE_GD_REMINDER, + "", -1, &error)); + g_assert_no_error (error); + g_assert (GDATA_IS_GD_REMINDER (reminder)); + g_clear_error (&error); + + /* Check the properties */ + g_assert (gdata_gd_reminder_get_method (reminder) == NULL); + g_assert (gdata_gd_reminder_is_absolute_time (reminder) == FALSE); + g_assert_cmpint (gdata_gd_reminder_get_relative_time (reminder), ==, 15 * 24 * 60); + + content_type = gdata_parsable_get_content_type (GDATA_PARSABLE (reminder)); + g_assert_cmpstr (content_type, ==, "application/atom+xml"); + + /* Check the outputted XML */ + gdata_test_assert_xml (reminder, + "" + ""); + g_object_unref (reminder); + + /* Try again with a different property */ + reminder = GDATA_GD_REMINDER (gdata_parsable_new_from_xml (GDATA_TYPE_GD_REMINDER, + "", -1, &error)); + g_assert_no_error (error); + g_assert (GDATA_IS_GD_REMINDER (reminder)); + g_clear_error (&error); + + /* Check the properties */ + g_assert (gdata_gd_reminder_get_method (reminder) == NULL); + g_assert (gdata_gd_reminder_is_absolute_time (reminder) == FALSE); + g_assert_cmpint (gdata_gd_reminder_get_relative_time (reminder), ==, 15 * 60); + + /* Compare to another reminder */ + reminder2 = gdata_gd_reminder_new (NULL, -1, 15 * 60); + g_assert_cmpint (gdata_comparable_compare (GDATA_COMPARABLE (reminder), GDATA_COMPARABLE (reminder2)), ==, 0); + g_object_unref (reminder2); + g_object_unref (reminder); + + /* …and another */ + reminder = GDATA_GD_REMINDER (gdata_parsable_new_from_xml (GDATA_TYPE_GD_REMINDER, + "", -1, &error)); + g_assert_no_error (error); + g_assert (GDATA_IS_GD_REMINDER (reminder)); + g_clear_error (&error); + + /* Check the properties */ + g_assert (gdata_gd_reminder_get_method (reminder) == NULL); + g_assert (gdata_gd_reminder_is_absolute_time (reminder) == FALSE); + g_assert_cmpint (gdata_gd_reminder_get_relative_time (reminder), ==, 15); + g_object_unref (reminder); + + /* Try again with an absolute time and a method */ + reminder = GDATA_GD_REMINDER (gdata_parsable_new_from_xml (GDATA_TYPE_GD_REMINDER, + "", -1, &error)); + g_assert_no_error (error); + g_assert (GDATA_IS_GD_REMINDER (reminder)); + g_clear_error (&error); + + /* Check the properties */ + g_assert_cmpstr (gdata_gd_reminder_get_method (reminder), ==, GDATA_GD_REMINDER_ALERT); + g_assert (gdata_gd_reminder_is_absolute_time (reminder) == TRUE); + _time = gdata_gd_reminder_get_absolute_time (reminder); + g_assert_cmpint (_time, ==, 1118105700); + + /* Compare to another reminder */ + reminder2 = gdata_gd_reminder_new (GDATA_GD_REMINDER_ALERT, _time, -1); + g_assert_cmpint (gdata_comparable_compare (GDATA_COMPARABLE (reminder), GDATA_COMPARABLE (reminder2)), ==, 0); + g_object_unref (reminder2); + + content_type = gdata_parsable_get_content_type (GDATA_PARSABLE (reminder)); + g_assert_cmpstr (content_type, ==, "application/atom+xml"); + + /* Check the outputted XML */ + gdata_test_assert_xml (reminder, + "" + ""); + g_object_unref (reminder); +} + +static void +test_gd_reminder_escaping (void) +{ + GDataGDReminder *reminder; + + reminder = gdata_gd_reminder_new (GDATA_GD_REMINDER_ALERT "?foo&bar", -1, 15); + + /* Check the outputted XML is escaped properly */ + gdata_test_assert_xml (reminder, + "" + ""); + g_object_unref (reminder); +} + +static void +test_gd_reminder_comparison (void) +{ + GDataGDReminder *reminder1, *reminder2; + +#define ASSERT_COMPARISON(op) \ + g_assert_cmpint (gdata_comparable_compare (GDATA_COMPARABLE (reminder1), GDATA_COMPARABLE (reminder2)), op, 0) + + /* Check for equality. */ + reminder1 = gdata_gd_reminder_new (GDATA_GD_REMINDER_ALERT, -1, 15); + reminder2 = gdata_gd_reminder_new (GDATA_GD_REMINDER_ALERT, -1, 15); + ASSERT_COMPARISON(==); + + /* Different methods, same time type, same time. */ + gdata_gd_reminder_set_method (reminder1, GDATA_GD_REMINDER_SMS); + ASSERT_COMPARISON(>); + + /* Same method, different time type, same time. */ + gdata_gd_reminder_set_method (reminder1, GDATA_GD_REMINDER_ALERT); + gdata_gd_reminder_set_relative_time (reminder1, -1); + gdata_gd_reminder_set_absolute_time (reminder1, 5); + ASSERT_COMPARISON(>); + + /* Same method, same time type, different time. */ + gdata_gd_reminder_set_absolute_time (reminder1, -1); + gdata_gd_reminder_set_relative_time (reminder1, 20); + ASSERT_COMPARISON(>); + + g_object_unref (reminder2); + g_object_unref (reminder1); + +#undef ASSERT_COMPARISON +} + +static void +test_gd_when (void) +{ + GDataGDWhen *when, *when2; + GDataGDReminder *reminder; + GList *reminders; + gint64 _time, _time2; + GError *error = NULL; + const gchar *content_type; + + when = GDATA_GD_WHEN (gdata_parsable_new_from_xml (GDATA_TYPE_GD_WHEN, + "", + -1, &error)); + g_assert_no_error (error); + g_assert (GDATA_IS_GD_WHEN (when)); + g_clear_error (&error); + + /* Check the properties */ + _time = gdata_gd_when_get_start_time (when); + g_assert_cmpint (_time, ==, 1118106000); + _time2 = gdata_gd_when_get_end_time (when); + g_assert_cmpint (_time2, ==, 1118109600); + g_assert (gdata_gd_when_is_date (when) == FALSE); + g_assert (gdata_gd_when_get_value_string (when) == NULL); + g_assert (gdata_gd_when_get_reminders (when) == NULL); + + /* Compare it against another identical time */ + when2 = gdata_gd_when_new (_time, _time2, FALSE); + g_assert_cmpint (gdata_comparable_compare (GDATA_COMPARABLE (when), GDATA_COMPARABLE (when2)), ==, 0); + + /* …and a different one */ + _time2 = 100; + gdata_gd_when_set_end_time (when2, _time2); + g_assert_cmpint (gdata_comparable_compare (GDATA_COMPARABLE (when), GDATA_COMPARABLE (when2)), !=, 0); + g_object_unref (when2); + + content_type = gdata_parsable_get_content_type (GDATA_PARSABLE (when)); + g_assert_cmpstr (content_type, ==, "application/atom+xml"); + + /* Check the outputted XML is the same */ + gdata_test_assert_xml (when, + "" + ""); + g_object_unref (when); + + /* Now parse a time with different information */ + when = GDATA_GD_WHEN (gdata_parsable_new_from_xml (GDATA_TYPE_GD_WHEN, + "" + "" + "" + "", -1, &error)); + g_assert_no_error (error); + g_assert (GDATA_IS_GD_WHEN (when)); + g_clear_error (&error); + + /* Check the properties */ + _time = gdata_gd_when_get_start_time (when); + g_assert_cmpint (_time, ==, 1118016000); + _time2 = gdata_gd_when_get_end_time (when); + g_assert_cmpint (_time2, ==, 1118188800); + g_assert (gdata_gd_when_is_date (when) == TRUE); + g_assert_cmpstr (gdata_gd_when_get_value_string (when), ==, "This weekend"); + + reminders = gdata_gd_when_get_reminders (when); + g_assert (reminders != NULL); + g_assert (GDATA_IS_GD_REMINDER (reminders->data)); + g_assert (reminders->next == NULL); + g_assert (gdata_gd_reminder_is_absolute_time (GDATA_GD_REMINDER (reminders->data)) == FALSE); + g_assert_cmpint (gdata_gd_reminder_get_relative_time (GDATA_GD_REMINDER (reminders->data)), ==, 15); + + /* Add another reminder */ + reminder = gdata_gd_reminder_new (GDATA_GD_REMINDER_ALERT, _time, -1); + gdata_gd_when_add_reminder (when, reminder); + g_object_unref (reminder); + + content_type = gdata_parsable_get_content_type (GDATA_PARSABLE (when)); + g_assert_cmpstr (content_type, ==, "application/atom+xml"); + + /* Check the outputted XML is correct */ + gdata_test_assert_xml (when, + "" + "" + "" + "" + "" + ""); + g_object_unref (when); +} + +static void +test_gd_when_escaping (void) +{ + GDataGDWhen *when; + GTimeVal start_time; + + g_time_val_from_iso8601 ("2005-06-07T01:00:00Z", &start_time); + when = gdata_gd_when_new (start_time.tv_sec, -1, FALSE); + gdata_gd_when_set_value_string (when, "Value string & stuff!"); + + /* Check the outputted XML is escaped properly */ + gdata_test_assert_xml (when, + "" + ""); + g_object_unref (when); +} + +static void +test_gd_when_comparison (void) +{ + GDataGDWhen *when1, *when2; + + /* Whens are non-equal if one is a date and the other isn't, if their start times differ, or if their end times differ. */ + when1 = gdata_gd_when_new (0, 1000, FALSE); + when2 = gdata_gd_when_new (0, 1000, FALSE); + + g_assert_cmpint (gdata_comparable_compare (GDATA_COMPARABLE (when1), GDATA_COMPARABLE (when2)), ==, 0); + + /* Different date/time type. */ + gdata_gd_when_set_is_date (when1, TRUE); + g_assert_cmpint (gdata_comparable_compare (GDATA_COMPARABLE (when1), GDATA_COMPARABLE (when2)), !=, 0); + + /* Different start time. */ + gdata_gd_when_set_is_date (when1, FALSE); + gdata_gd_when_set_start_time (when1, 500); + g_assert_cmpint (gdata_comparable_compare (GDATA_COMPARABLE (when1), GDATA_COMPARABLE (when2)), !=, 0); + + /* Different end time. */ + gdata_gd_when_set_start_time (when1, 0); + gdata_gd_when_set_end_time (when1, 15000); + g_assert_cmpint (gdata_comparable_compare (GDATA_COMPARABLE (when1), GDATA_COMPARABLE (when2)), !=, 0); + + g_object_unref (when2); + g_object_unref (when1); +} + +static void +test_gd_where (void) +{ + GDataGDWhere *where, *where2; + GError *error = NULL; + const gchar *content_type; + + where = GDATA_GD_WHERE (gdata_parsable_new_from_xml (GDATA_TYPE_GD_WHERE, + "", -1, &error)); + g_assert_no_error (error); + g_assert (GDATA_IS_GD_WHERE (where)); + g_clear_error (&error); + + /* Check the properties */ + g_assert_cmpstr (gdata_gd_where_get_relation_type (where), ==, GDATA_GD_WHERE_EVENT_ALTERNATE); + g_assert_cmpstr (gdata_gd_where_get_value_string (where), ==, "Metropolis"); + g_assert_cmpstr (gdata_gd_where_get_label (where), ==, "New York Location "); + + /* Compare it against another identical place */ + where2 = gdata_gd_where_new (GDATA_GD_WHERE_EVENT_ALTERNATE, "Metropolis", "New York Location "); + g_assert_cmpint (gdata_comparable_compare (GDATA_COMPARABLE (where), GDATA_COMPARABLE (where2)), ==, 0); + + /* …and a different one */ + gdata_gd_where_set_label (where2, "Atlas Mountains"); + g_assert_cmpint (gdata_comparable_compare (GDATA_COMPARABLE (where), GDATA_COMPARABLE (where2)), !=, 0); + g_object_unref (where2); + + content_type = gdata_parsable_get_content_type (GDATA_PARSABLE (where)); + g_assert_cmpstr (content_type, ==, "application/atom+xml"); + + /* Check the outputted XML is the same */ + gdata_test_assert_xml (where, + "" + ""); + g_object_unref (where); + + /* Now parse a place with less information available */ + where = GDATA_GD_WHERE (gdata_parsable_new_from_xml (GDATA_TYPE_GD_WHERE, + "", -1, &error)); + g_assert_no_error (error); + g_assert (GDATA_IS_GD_WHERE (where)); + g_clear_error (&error); + + /* Check the properties */ + g_assert_cmpstr (gdata_gd_where_get_value_string (where), ==, "Google Cafeteria "); + g_assert (gdata_gd_where_get_relation_type (where) == NULL); + g_assert (gdata_gd_where_get_label (where) == NULL); + + content_type = gdata_parsable_get_content_type (GDATA_PARSABLE (where)); + g_assert_cmpstr (content_type, ==, "application/atom+xml"); + + /* Check the outputted XML contains the unknown XML */ + gdata_test_assert_xml (where, + "" + ""); + g_object_unref (where); +} + +static void +test_gd_where_escaping (void) +{ + GDataGDWhere *where; + + where = gdata_gd_where_new (GDATA_GD_WHERE_EVENT "?foo&bar", "Value string & stuff!", "