summaryrefslogtreecommitdiffstats
path: root/src/components/AppNavigation/GroupNavigationItem.vue
blob: 4ced354334f42f930512ed30c8c0c266ce15b44f (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
<!--
  - @copyright Copyright (c) 2018 John Molakvoæ <skjnldsv@protonmail.com>
  -
  - @author John Molakvoæ <skjnldsv@protonmail.com>
  -
  - @license GNU AGPL version 3 or any later version
  -
  - This program is free software: you can redistribute it and/or modify
  - it under the terms of the GNU Affero General Public License as
  - published by the Free Software Foundation, either version 3 of the
  - License, or (at your option) any later version.
  -
  - This program 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 Affero General Public License for more details.
  -
  - You should have received a copy of the GNU Affero General Public License
  - along with this program. If not, see <http://www.gnu.org/licenses/>.
  -
  -->
<template>
	<div class="group-drop-area"
		data-testid="group-drop-area"
		@drop="onDrop($event, group)"
		@dragenter.prevent
		@dragover="onDragOver($event)"
		@dragleave="onDragLeave($event)">
		<AppNavigationItem :key="group.key"
			:to="group.router"
			:name="group.name">
			<template #icon>
				<IconContact :size="20" />
			</template>
			<template #actions>
				<ActionButton :close-after-click="true"
					@click="addContactsToGroup(group)">
					<template #icon>
						<IconAdd :size="20" />
					</template>
					{{ t('contacts', 'Add contacts') }}
				</ActionButton>
				<ActionButton :close-after-click="true"
					@click="downloadGroup(group)">
					<template #icon>
						<IconDownload :size="20" />
					</template>
					{{ t('contacts', 'Export') }}
				</ActionButton>
				<ActionButton @click="emailGroup(group)">
					<template #icon>
						<IconEmail :size="20" />
					</template>
					{{ t('contacts', 'Send email') }}
				</ActionButton>
				<ActionButton @click="emailGroup(group, 'bcc')">
					<template #icon>
						<IconEmail :size="20" />
					</template>
					{{ t('contacts', 'Send email as BCC') }}
				</ActionButton>
			</template>

			<template #counter>
				<NcCounterBubble v-if="group.contacts.length > 0">
					{{ group.contacts.length }}
				</NcCounterBubble>
			</template>
		</AppNavigationItem>
	</div>
</template>

<script>
import { emit } from '@nextcloud/event-bus'
import download from 'downloadjs'
import moment from 'moment'

import {
	NcActionButton as ActionButton,
	NcCounterBubble,
	NcAppNavigationItem as AppNavigationItem,
} from '@nextcloud/vue'
import IconContact from 'vue-material-design-icons/AccountMultiple.vue'
import IconAdd from 'vue-material-design-icons/Plus.vue'
import IconDownload from 'vue-material-design-icons/Download.vue'
import IconEmail from 'vue-material-design-icons/Email.vue'
import { showError } from '@nextcloud/dialogs'

export default {
	name: 'GroupNavigationItem',

	components: {
		ActionButton,
		NcCounterBubble,
		AppNavigationItem,
		IconContact,
		IconAdd,
		IconDownload,
		IconEmail,
	},

	props: {
		group: {
			type: Object,
			required: true,
		},
	},

	computed: {
		contacts() {
			return this.$store.getters.getContacts
		},
	},

	methods: {
		/**
		 * @param groups
		 * @param groupId
		 */
		isInGroup(groups, groupId) {
			return groups.includes(groupId)
		},
		/**
		 * Drop contact on group handler.
		 *
		 * @param {object} event drop event
		 * @param {object} group to add to dropped contact
		 * @return {Promise<void>}
		 */
		async onDrop(event, group) {
			try {
				const contactFromDropData = JSON.parse(event.dataTransfer.getData('item'))
				const contactFromStore = this.$store.getters.getContact(`${contactFromDropData.uid}~${contactFromDropData.addressbookId}`)
				if (contactFromStore && !this.isInGroup(contactFromStore.groups, group.id)) {
					const contact = this.$store.getters.getContact(`${contactFromDropData.uid}~${contactFromDropData.addressbookId}`)
					await this.$store.dispatch('updateContactGroups', {
						groupNames: [...contactFromStore.groups, group.id],
						contact,
					})
					const localContact = Object.assign(
						Object.create(Object.getPrototypeOf(contact)),
						contact,
					)
					localContact.groups = [...contactFromStore.groups, group.id]
					await this.$store.dispatch('updateContact', localContact)
				}
			} catch (e) {
				console.error(e)
				showError('Tried to drop an invalid contact!')
			} finally {
				event.target.closest('.group-drop-area').removeAttribute('drop-active')
			}
		},
		// Add marker for drop area
		onDragOver(event) {
			event.preventDefault()
			event.target.closest('.group-drop-area').setAttribute('drop-active', true)
		},
		// Remove marker from drop area
		onDragLeave(event) {
			event.target.closest('.group-drop-area').removeAttribute('drop-active')
		},
		// Trigger the entity picker view
		addContactsToGroup() {
			emit('contacts:group:append', this.group.name)
		},

		/**
		 * Download group of contacts
		 *
		 * @param {object} group of contacts to be downloaded
		 */
		downloadGroup(group) {
			// get grouped contacts
			let groupedContacts = {}
			group.contacts.forEach(key => {
				const id = this.contacts[key].addressbook.id
				groupedContacts = Object.assign({
					[id]: {
						addressbook: this.contacts[key].addressbook,
						contacts: [],
					},
				}, groupedContacts)
				groupedContacts[id].contacts.push(this.contacts[key].url)
			})

			// create vcard promise with the requested contacts
			const vcardPromise = Promise.all(
				Object.keys(groupedContacts).map(key =>
					groupedContacts[key].addressbook.dav.addressbookMultigetExport(groupedContacts[key].contacts)))
				.then(response => ({
					groupName: group.name,
					data: response.map(data => data.body).join(''),
				}))

			// download vcard
			this.downloadVcardPromise(vcardPromise)
		},

		/**
		 * Download vcard promise as vcard file
		 *
		 * @param {Promise} vcardPromise the full vcf file promise
		 */
		async downloadVcardPromise(vcardPromise) {
			vcardPromise.then(response => {
				const filename = moment().format('YYYY-MM-DD_HH-mm') + '_' + response.groupName + '.vcf'
				download(response.data, filename, 'text/vcard')
			})
		},

		/**
		 * Open mailto: for contacts in a group
		 *
		 * @param {object} group of contacts to be emailed
		 * @param {string} mode
		 */
		emailGroup(group, mode = 'to') {
			const emails = []
			group.contacts.filter(key => this.contacts[key].email !== null).forEach(key => {
				// The email property could contain "John Doe <john.doe@example.com>", but vcard spec only
				// allows addr-spec, not name-addr, so to stay compliant, replace everything outside of <>
				const email = this.contacts[key].email.replace(/(.*<)([^>]*)(>)/g, '$2').trim()
				const name = this.contacts[key].fullName.replace(/[,<>]/g, '').trim()
				if (email === '') {
					return
				}
				if (name === null || name === '') {
					emails.push(email)
					return
				}
				emails.push(`${name} <${email}>`)
			})
			// We could just do mailto:${emails}, but if we want to use name-addr, not addr-spec, then we
			// have to explicitly set the "to:" or "bcc:" header.
			window.location.href = `mailto:?${mode}=${emails.map(encodeURIComponent).join(',')}`
		},

	},
}
</script>

<style lang="scss" scoped>
.group-drop-area[drop-active=true] {
	background-color: var(--color-primary-light);
}
</style>