Append ls -v output to status items.
[paraslash.git] / aft.c
1 /*
2 * Copyright (C) 2007 Andre Noll <maan@systemlinux.org>
3 *
4 * Licensed under the GPL v2. For licencing details see COPYING.
5 */
6
7 /** \file aft.c Audio file table functions. */
8
9 #include <dirent.h> /* readdir() */
10 #include "para.h"
11 #include "error.h"
12 #include "string.h"
13 #include <sys/mman.h>
14 #include <fnmatch.h>
15 #include "afh.h"
16 #include "afs.h"
17 #include "net.h"
18 #include "vss.h"
19 #include "fd.h"
20 #include "ipc.h"
21
22 static struct osl_table *audio_file_table;
23
24 /** The different sorting methods of the ls command. */
25 enum ls_sorting_method {
26 /** -sp (default) */
27 LS_SORT_BY_PATH,
28 /** -ss */
29 LS_SORT_BY_SCORE,
30 /** -sl */
31 LS_SORT_BY_LAST_PLAYED,
32 /** -sn */
33 LS_SORT_BY_NUM_PLAYED,
34 /** -sf */
35 LS_SORT_BY_FREQUENCY,
36 /** -sc */
37 LS_SORT_BY_CHANNELS,
38 /** -si */
39 LS_SORT_BY_IMAGE_ID,
40 /** -sy */
41 LS_SORT_BY_LYRICS_ID,
42 /** -sb */
43 LS_SORT_BY_BITRATE,
44 /** -sd */
45 LS_SORT_BY_DURATION,
46 /** -sa */
47 LS_SORT_BY_AUDIO_FORMAT,
48 /** -sh */
49 LS_SORT_BY_HASH,
50 };
51
52 /** The different listing modes of the ls command. */
53 enum ls_listing_mode {
54 /** Default listing mode. */
55 LS_MODE_SHORT,
56 /** -l or -ll */
57 LS_MODE_LONG,
58 /** -lv */
59 LS_MODE_VERBOSE,
60 /** -lm */
61 LS_MODE_MBOX
62 };
63
64 /** The flags accepted by the ls command. */
65 enum ls_flags {
66 /** -p */
67 LS_FLAG_FULL_PATH = 1,
68 /** -a */
69 LS_FLAG_ADMISSIBLE_ONLY = 2,
70 /** -r */
71 LS_FLAG_REVERSE = 4,
72 };
73
74 /**
75 * The size of the individual output fields of the ls command.
76 *
77 * These depend on the actual content being listed. If, for instance only files
78 * with duration less than an hour are being listed, then the duration with is
79 * made smaller because then the duration is listed as mm:ss rather than
80 * hh:mm:ss.
81 */
82 struct ls_widths {
83 /** size of the score field. */
84 unsigned short score_width;
85 /** size of the image id field. */
86 unsigned short image_id_width;
87 /** size of the lyrics id field. */
88 unsigned short lyrics_id_width;
89 /** size of the bitrate field. */
90 unsigned short bitrate_width;
91 /** size of the frequency field. */
92 unsigned short frequency_width;
93 /** size of the duration field. */
94 unsigned short duration_width;
95 /** size of the num played field. */
96 unsigned short num_played_width;
97 };
98
99 /** Data passed from the ls command handler to its callback function. */
100 struct ls_options {
101 /** The given command line flags. */
102 unsigned flags;
103 /** The sorting method given at the command line. */
104 enum ls_sorting_method sorting;
105 /** The given listing mode (short, long, verbose, mbox). */
106 enum ls_listing_mode mode;
107 /** The arguments passed to the ls command. */
108 char **patterns;
109 /** Number of non-option arguments. */
110 int num_patterns;
111 /** Used for long listing mode to align the output fields. */
112 struct ls_widths widths;
113 /** Size of the \a data array. */
114 uint32_t array_size;
115 /** Number of used entries in the data array. */
116 uint32_t num_matching_paths;
117 /** Array of matching entries. */
118 struct ls_data *data;
119 /** Used to sort the array. */
120 struct ls_data **data_ptr;
121 };
122
123 /**
124 * Describes the layout of the mmapped-afs info struct.
125 *
126 * \sa struct afs_info.
127 */
128 enum afsi_offsets {
129 /** Where .last_played is stored. */
130 AFSI_LAST_PLAYED_OFFSET = 0,
131 /** Storage position of the attributes bitmap. */
132 AFSI_ATTRIBUTES_OFFSET = 8,
133 /** Storage position of the .num_played field. */
134 AFSI_NUM_PLAYED_OFFSET = 16,
135 /** Storage position of the .image_id field. */
136 AFSI_IMAGE_ID_OFFSET = 20,
137 /** Storage position of the .lyrics_id field. */
138 AFSI_LYRICS_ID_OFFSET = 24,
139 /** Storage position of the .audio_format_id field. */
140 AFSI_AUDIO_FORMAT_ID_OFFSET = 28,
141 /** 3 bytes reserved space for future usage. */
142 AFSI_AUDIO_FORMAT_UNUSED_OFFSET = 29,
143 /** On-disk storage space needed. */
144 AFSI_SIZE = 32
145 };
146
147 /**
148 * Convert a struct afs_info to an osl object.
149 *
150 * \param afsi Pointer to the audio file info to be converted.
151 * \param obj Result pointer.
152 *
153 * \sa load_afsi().
154 */
155 void save_afsi(struct afs_info *afsi, struct osl_object *obj)
156 {
157 char *buf = obj->data;
158
159 write_u64(buf + AFSI_LAST_PLAYED_OFFSET, afsi->last_played);
160 write_u64(buf + AFSI_ATTRIBUTES_OFFSET, afsi->attributes);
161 write_u32(buf + AFSI_NUM_PLAYED_OFFSET, afsi->num_played);
162 write_u32(buf + AFSI_IMAGE_ID_OFFSET, afsi->image_id);
163 write_u32(buf + AFSI_LYRICS_ID_OFFSET, afsi->lyrics_id);
164 write_u8(buf + AFSI_AUDIO_FORMAT_ID_OFFSET,
165 afsi->audio_format_id);
166 memset(buf + AFSI_AUDIO_FORMAT_UNUSED_OFFSET, 0, 3);
167 }
168
169 /**
170 * Get the audio file selector info struct stored in an osl object.
171 *
172 * \param afsi Points to the audio_file info structure to be filled in.
173 * \param obj The osl object holding the data.
174 *
175 * \return Positive on success, negative on errors. Possible errors: \p E_BAD_AFS.
176 *
177 * \sa save_afsi().
178 */
179 int load_afsi(struct afs_info *afsi, struct osl_object *obj)
180 {
181 char *buf = obj->data;
182 if (obj->size < AFSI_SIZE)
183 return -E_BAD_AFSI;
184 afsi->last_played = read_u64(buf + AFSI_LAST_PLAYED_OFFSET);
185 afsi->attributes = read_u64(buf + AFSI_ATTRIBUTES_OFFSET);
186 afsi->num_played = read_u32(buf + AFSI_NUM_PLAYED_OFFSET);
187 afsi->image_id = read_u32(buf + AFSI_IMAGE_ID_OFFSET);
188 afsi->lyrics_id = read_u32(buf + AFSI_LYRICS_ID_OFFSET);
189 afsi->audio_format_id = read_u8(buf +
190 AFSI_AUDIO_FORMAT_ID_OFFSET);
191 return 1;
192 }
193
194 /** The columns of the audio file table. */
195 enum audio_file_table_columns {
196 /** The hash on the content of the audio file. */
197 AFTCOL_HASH,
198 /** The full path in the filesystem. */
199 AFTCOL_PATH,
200 /** The audio file selector info. */
201 AFTCOL_AFSI,
202 /** The audio format handler info. */
203 AFTCOL_AFHI,
204 /** The chunk table info and the chunk table of the audio file. */
205 AFTCOL_CHUNKS,
206 /** The number of columns of this table. */
207 NUM_AFT_COLUMNS
208 };
209
210 static struct osl_column_description aft_cols[] = {
211 [AFTCOL_HASH] = {
212 .storage_type = OSL_MAPPED_STORAGE,
213 .storage_flags = OSL_RBTREE | OSL_FIXED_SIZE | OSL_UNIQUE,
214 .name = "hash",
215 .compare_function = osl_hash_compare,
216 .data_size = HASH_SIZE
217 },
218 [AFTCOL_PATH] = {
219 .storage_type = OSL_MAPPED_STORAGE,
220 .storage_flags = OSL_RBTREE | OSL_UNIQUE,
221 .name = "path",
222 .compare_function = string_compare,
223 },
224 [AFTCOL_AFSI] = {
225 .storage_type = OSL_MAPPED_STORAGE,
226 .storage_flags = OSL_FIXED_SIZE,
227 .name = "afs_info",
228 .data_size = AFSI_SIZE
229 },
230 [AFTCOL_AFHI] = {
231 .storage_type = OSL_MAPPED_STORAGE,
232 .name = "afh_info",
233 },
234 [AFTCOL_CHUNKS] = {
235 .storage_type = OSL_DISK_STORAGE,
236 .name = "chunks",
237 }
238 };
239
240 static struct osl_table_description audio_file_table_desc = {
241 .name = "audio_files",
242 .num_columns = NUM_AFT_COLUMNS,
243 .flags = OSL_LARGE_TABLE,
244 .column_descriptions = aft_cols
245 };
246
247 /* We don't want * dot or dot-dot anywhere. */
248 static int verify_dotfile(const char *rest)
249 {
250 /*
251 * The first character was '.', but that has already been discarded, we
252 * now test the rest.
253 */
254 switch (*rest) {
255 case '\0': case '/': /* /foo/. and /foo/./bar are not ok */
256 return -1;
257 case '.': /* path start with /foo/.. */
258 if (rest[1] == '\0' || rest[1] == '/')
259 return -1; /* /foo/.. or /foo/../bar are not ok */
260 /* /foo/..bar is ok */
261 }
262 return 1;
263 }
264
265 /*
266 * We fundamentally don't like some paths: We don't want double slashes or
267 * slashes at the end that can make pathnames ambiguous.
268 */
269 static int verify_path(const char *orig_path, char **resolved_path)
270 {
271 char c;
272 size_t len;
273 char *path;
274
275 if (*orig_path != '/') /* we only accept absolute paths */
276 return -E_BAD_PATH;
277 len = strlen(orig_path);
278 *resolved_path = para_strdup(orig_path);
279 path = *resolved_path;
280 while (len > 1 && path[--len] == '/')
281 path[len] = '\0'; /* remove slash at the end */
282 c = *path++;
283 while (c) {
284 if (c == '/') {
285 c = *path++;
286 switch (c) {
287 case '/': /* double slash */
288 goto bad_path;
289 case '.':
290 if (verify_dotfile(path) < 0)
291 goto bad_path;
292 default:
293 continue;
294 }
295 }
296 c = *path++;
297 }
298 return 1;
299 bad_path:
300 free(*resolved_path);
301 return -E_BAD_PATH;
302 }
303
304 /** The on-disk layout of a afhi struct. */
305 enum afhi_offsets {
306 /** Where the number of seconds is stored. */
307 AFHI_SECONDS_TOTAL_OFFSET = 0,
308 /** Position of the bitrate. */
309 AFHI_BITRATE_OFFSET = 4,
310 /** Position of the frequency. */
311 AFHI_FREQUENCY_OFFSET = 8,
312 /** Location of the audio file header. */
313 AFHI_HEADER_OFFSET_OFFSET = 12,
314 /* Length of the audio file header. Zero means: No header. */
315 AFHI_HEADER_LEN_OFFSET = 16,
316 /** Number of channels is stored here. */
317 AFHI_CHANNELS_OFFSET = 20,
318 /** EOF timeout in ms. */
319 AFHI_EOF_OFFSET = 21,
320 /** The tag info position. */
321 AFHI_INFO_STRING_OFFSET = 23,
322 /** Minimal on-disk size of a valid afhi struct. */
323 MIN_AFHI_SIZE = 24
324 };
325
326 static unsigned sizeof_afhi_buf(const struct afh_info *afhi)
327 {
328 if (!afhi)
329 return 0;
330 return strlen(afhi->info_string) + MIN_AFHI_SIZE;
331 }
332
333 static void save_afhi(struct afh_info *afhi, char *buf)
334 {
335 if (!afhi)
336 return;
337 write_u32(buf + AFHI_SECONDS_TOTAL_OFFSET,
338 afhi->seconds_total);
339 write_u32(buf + AFHI_BITRATE_OFFSET, afhi->bitrate);
340 write_u32(buf + AFHI_FREQUENCY_OFFSET, afhi->frequency);
341 write_u32(buf + AFHI_HEADER_OFFSET_OFFSET, afhi->header_offset);
342 write_u32(buf + AFHI_HEADER_LEN_OFFSET, afhi->header_len);
343 write_u8(buf + AFHI_CHANNELS_OFFSET, afhi->channels);
344 write_u16(buf + AFHI_EOF_OFFSET, tv2ms(&afhi->eof_tv));
345 strcpy(buf + AFHI_INFO_STRING_OFFSET, afhi->info_string); /* OK */
346 PARA_DEBUG_LOG("last byte written: %p\n", buf + AFHI_INFO_STRING_OFFSET + strlen(afhi->info_string));
347 }
348
349 static void load_afhi(const char *buf, struct afh_info *afhi)
350 {
351 afhi->seconds_total = read_u32(buf + AFHI_SECONDS_TOTAL_OFFSET);
352 afhi->bitrate = read_u32(buf + AFHI_BITRATE_OFFSET);
353 afhi->frequency = read_u32(buf + AFHI_FREQUENCY_OFFSET);
354 afhi->channels = read_u8(buf + AFHI_CHANNELS_OFFSET);
355 afhi->header_offset = read_u32(buf + AFHI_HEADER_OFFSET_OFFSET);
356 afhi->header_len = read_u32(buf + AFHI_HEADER_LEN_OFFSET);
357 ms2tv(read_u16(buf + AFHI_EOF_OFFSET), &afhi->eof_tv);
358 strcpy(afhi->info_string, buf + AFHI_INFO_STRING_OFFSET);
359 }
360
361 //#define SIZEOF_CHUNK_TABLE(afhi) (((afhi)->chunks_total + 1) * sizeof(uint32_t))
362
363 static unsigned sizeof_chunk_info_buf(struct afh_info *afhi)
364 {
365 if (!afhi)
366 return 0;
367 return 4 * (afhi->chunks_total + 1) + 20;
368
369 }
370
371 /** The offsets of the data contained in the AFTCOL_CHUNKS column. */
372 enum chunk_info_offsets{
373 /** The total number of chunks (4 bytes). */
374 CHUNKS_TOTAL_OFFSET = 0,
375 /** The length of the audio file header (4 bytes). */
376 HEADER_LEN_OFFSET = 4,
377 /** The start of the audio file header (4 bytes). */
378 HEADER_OFFSET_OFFSET = 8,
379 /** The seconds part of the chunk time (4 bytes). */
380 CHUNK_TV_TV_SEC_OFFSET = 12,
381 /** The microseconds part of the chunk time (4 bytes). */
382 CHUNK_TV_TV_USEC = 16,
383 /** Chunk table entries start here. */
384 CHUNK_TABLE_OFFSET = 20,
385 };
386
387 static void save_chunk_table(struct afh_info *afhi, char *buf)
388 {
389 int i;
390
391 PARA_DEBUG_LOG("%lu chunks\n", afhi->chunks_total);
392 for (i = 0; i <= afhi->chunks_total; i++)
393 write_u32(buf + 4 * i, afhi->chunk_table[i]);
394 }
395
396 static void load_chunk_table(struct afh_info *afhi, char *buf)
397 {
398 int i;
399 for (i = 0; i <= afhi->chunks_total; i++)
400 afhi->chunk_table[i] = read_u32(buf + 4 * i);
401 }
402
403 /* TODO: audio format handlers could just produce this */
404 static void save_chunk_info(struct afh_info *afhi, char *buf)
405 {
406 if (!afhi)
407 return;
408 write_u32(buf + CHUNKS_TOTAL_OFFSET, afhi->chunks_total);
409 write_u32(buf + HEADER_LEN_OFFSET, afhi->header_len);
410 write_u32(buf + HEADER_OFFSET_OFFSET, afhi->header_offset);
411 write_u32(buf + CHUNK_TV_TV_SEC_OFFSET, afhi->chunk_tv.tv_sec);
412 write_u32(buf + CHUNK_TV_TV_USEC, afhi->chunk_tv.tv_usec);
413 save_chunk_table(afhi, buf + CHUNK_TABLE_OFFSET);
414 }
415
416 static int load_chunk_info(struct osl_object *obj, struct afh_info *afhi)
417 {
418 char *buf = obj->data;
419
420 if (obj->size < CHUNK_TABLE_OFFSET)
421 return -E_BAD_DATA_SIZE;
422
423 afhi->chunks_total = read_u32(buf + CHUNKS_TOTAL_OFFSET);
424 afhi->header_len = read_u32(buf + HEADER_LEN_OFFSET);
425 afhi->header_offset = read_u32(buf + HEADER_OFFSET_OFFSET);
426 afhi->chunk_tv.tv_sec = read_u32(buf + CHUNK_TV_TV_SEC_OFFSET);
427 afhi->chunk_tv.tv_usec = read_u32(buf + CHUNK_TV_TV_USEC);
428
429 if ((afhi->chunks_total + 1) * 4 + CHUNK_TABLE_OFFSET > obj->size)
430 return -E_BAD_DATA_SIZE;
431 afhi->chunk_table = para_malloc((afhi->chunks_total + 1) * 4);
432 load_chunk_table(afhi, buf + CHUNK_TABLE_OFFSET);
433 return 1;
434 }
435
436 /**
437 * Get the row of the audio file table corresponding to the given path.
438 *
439 * \param path The full path of the audio file.
440 * \param row Result pointer.
441 *
442 * \return The return value of the underlying call to osl_get_row().
443 */
444 int aft_get_row_of_path(const char *path, struct osl_row **row)
445 {
446 struct osl_object obj = {.data = (char *)path, .size = strlen(path) + 1};
447
448 return osl_get_row(audio_file_table, AFTCOL_PATH, &obj, row);
449 }
450
451 /**
452 * Get the row of the audio file table corresponding to the given hash value.
453 *
454 * \param hash The hash value of the desired audio file.
455 * \param row resul pointer.
456 *
457 * \return The return value of the underlying call to osl_get_row().
458 */
459 int aft_get_row_of_hash(HASH_TYPE *hash, struct osl_row **row)
460 {
461 const struct osl_object obj = {.data = hash, .size = HASH_SIZE};
462 return osl_get_row(audio_file_table, AFTCOL_HASH, &obj, row);
463 }
464
465 /**
466 * Get the osl object holding the audio file selector info of a row.
467 *
468 * \param row Pointer to a row in the audio file table.
469 * \param obj Result pointer.
470 *
471 * \return The return value of the underlying call to osl_get_object().
472 */
473 int get_afsi_object_of_row(const struct osl_row *row, struct osl_object *obj)
474 {
475 return osl_get_object(audio_file_table, row, AFTCOL_AFSI, obj);
476 }
477
478 /**
479 * Get the osl object holding the audio file selector info, given a path.
480 *
481 *
482 * \param path The full path of the audio file.
483 * \param obj Result pointer.
484 *
485 * \return Positive on success, negative on errors.
486 */
487 int get_afsi_object_of_path(const char *path, struct osl_object *obj)
488 {
489 struct osl_row *row;
490 int ret = aft_get_row_of_path(path, &row);
491 if (ret < 0)
492 return ret;
493 return get_afsi_object_of_row(row, obj);
494 }
495
496 /**
497 * Get the audio file selector info, given a row of the audio file table.
498 *
499 * \param row Pointer to a row in the audio file table.
500 * \param afsi Result pointer.
501 *
502 * \return Positive on success, negative on errors.
503 */
504 int get_afsi_of_row(const struct osl_row *row, struct afs_info *afsi)
505 {
506 struct osl_object obj;
507 int ret = get_afsi_object_of_row(row, &obj);
508 if (ret < 0)
509 return ret;
510 return load_afsi(afsi, &obj);
511 }
512
513 /**
514 * Get the audio file selector info, given the path of an audio table.
515 *
516 * \param path The full path of the audio file.
517 * \param afsi Result pointer.
518 *
519 * \return Positive on success, negative on errors.
520 */
521 int get_afsi_of_path(const char *path, struct afs_info *afsi)
522 {
523 struct osl_object obj;
524 int ret = get_afsi_object_of_path(path, &obj);
525 if (ret < 0)
526 return ret;
527 return load_afsi(afsi, &obj);
528 }
529
530 /**
531 * Get the path of an audio file, given a row of the audio file table.
532 *
533 * \param row Pointer to a row in the audio file table.
534 * \param path Result pointer.
535 *
536 * The result is a pointer to mmapped data. The caller must not attempt
537 * to free it.
538 *
539 * \return Standard.
540 */
541 int get_audio_file_path_of_row(const struct osl_row *row, char **path)
542 {
543 struct osl_object path_obj;
544 int ret = osl_get_object(audio_file_table, row, AFTCOL_PATH,
545 &path_obj);
546 if (ret < 0)
547 return ret;
548 *path = path_obj.data;
549 return 1;
550 }
551
552 /**
553 * Get the object containing the hash value of an audio file, given a row.
554 *
555 * \param row Pointer to a row of the audio file table.
556 * \param obj Result pointer.
557 *
558 * \return The return value of the underlying call to osl_get_object().
559 *
560 * \sa get_hash_of_row().
561 */
562 static int get_hash_object_of_aft_row(const struct osl_row *row, struct osl_object *obj)
563 {
564 return osl_get_object(audio_file_table, row, AFTCOL_HASH, obj);
565 }
566
567 /**
568 * Get the hash value of an audio file, given a row of the audio file table.
569 *
570 * \param row Pointer to a row of the audio file table.
571 * \param hash Result pointer.
572 *
573 * \a hash points to mapped data and must not be freed by the caller.
574 *
575 * \return The return value of the underlying call to
576 * get_hash_object_of_aft_row().
577 */
578 static int get_hash_of_row(const struct osl_row *row, HASH_TYPE **hash)
579 {
580 struct osl_object obj;
581 int ret = get_hash_object_of_aft_row(row, &obj);
582
583 if (ret < 0)
584 return ret;
585 *hash = obj.data;
586 return 1;
587 }
588
589 /**
590 * Get the audio format handler info, given a row of the audio file table.
591 *
592 * \param row Pointer to a row of the audio file table.
593 * \param afhi Result pointer.
594 *
595 * \return The return value of the underlying call to osl_get_object().
596 *
597 * \sa get_chunk_table_of_row().
598 */
599 int get_afhi_of_row(const struct osl_row *row, struct afh_info *afhi)
600 {
601 struct osl_object obj;
602 int ret = osl_get_object(audio_file_table, row, AFTCOL_AFHI,
603 &obj);
604 if (ret < 0)
605 return ret;
606 load_afhi(obj.data, afhi);
607 return 1;
608 }
609
610 /* returns shmid on success */
611 static int save_afd(struct audio_file_data *afd)
612 {
613 size_t size = sizeof(*afd)
614 + 4 * (afd->afhi.chunks_total + 1);
615
616 PARA_DEBUG_LOG("size: %zu\n", size);
617 int shmid, ret = shm_new(size);
618 void *shm_afd;
619 char *buf;
620
621 if (ret < 0)
622 return ret;
623 shmid = ret;
624 ret = shm_attach(shmid, ATTACH_RW, &shm_afd);
625 if (ret < 0)
626 goto err;
627 *(struct audio_file_data *)shm_afd = *afd;
628 buf = shm_afd;
629 buf += sizeof(*afd);
630 save_chunk_table(&afd->afhi, buf);
631 shm_detach(shm_afd);
632 return shmid;
633 err:
634 shm_destroy(shmid);
635 return ret;
636 }
637
638 int load_afd(int shmid, struct audio_file_data *afd)
639 {
640 void *shm_afd;
641 char *buf;
642 int ret;
643
644 ret = shm_attach(shmid, ATTACH_RO, &shm_afd);
645 if (ret < 0)
646 return ret;
647 *afd = *(struct audio_file_data *)shm_afd;
648 buf = shm_afd;
649 buf += sizeof(*afd);
650 afd->afhi.chunk_table = para_malloc((afd->afhi.chunks_total + 1) * 4);
651 load_chunk_table(&afd->afhi, buf);
652 shm_detach(shm_afd);
653 return 1;
654 }
655
656 /**
657 * Mmap the given audio file and update statistics.
658 *
659 * \param aft_row Determines the audio file to be opened and updated.
660 * \param afd Result pointer.
661 *
662 * On success, the numplayed field of the audio file selector info is increased
663 * and the lastplayed time is set to the current time. Finally, the score of
664 * the audio file is updated.
665 *
666 * \return Positive on success, negative on errors.
667 */
668 int open_and_update_audio_file(struct osl_row *aft_row, struct audio_file_data *afd)
669 {
670 HASH_TYPE *aft_hash, file_hash[HASH_SIZE];
671 struct osl_object afsi_obj;
672 struct afs_info new_afsi;
673 int ret = get_hash_of_row(aft_row, &aft_hash);
674 struct afsi_change_event_data aced;
675 struct osl_object map, chunk_table_obj;
676 char *tmp, *path;
677
678 if (ret < 0)
679 return ret;
680 ret = get_audio_file_path_of_row(aft_row, &path);
681 if (ret < 0)
682 return ret;
683 strncpy(afd->path, path, sizeof(afd->path) - 1);
684 afd->path[sizeof(afd->path) - 1] = '\0';
685 ret = get_afsi_object_of_row(aft_row, &afsi_obj);
686 if (ret < 0)
687 return ret;
688 ret = load_afsi(&afd->afsi, &afsi_obj);
689 if (ret < 0)
690 return ret;
691 ret = get_afhi_of_row(aft_row, &afd->afhi);
692 if (ret < 0)
693 return ret;
694 ret = osl_open_disk_object(audio_file_table, aft_row,
695 AFTCOL_CHUNKS, &chunk_table_obj);
696 if (ret < 0)
697 return ret;
698 ret = mmap_full_file(path, O_RDONLY, &map.data,
699 &map.size, &afd->fd);
700 if (ret < 0)
701 goto err;
702 hash_function(map.data, map.size, file_hash);
703 ret = hash_compare(file_hash, aft_hash);
704 para_munmap(map.data, map.size);
705 if (ret) {
706 ret = -E_HASH_MISMATCH;
707 goto err;
708 }
709 new_afsi = afd->afsi;
710 new_afsi.num_played++;
711 new_afsi.last_played = time(NULL);
712 save_afsi(&new_afsi, &afsi_obj); /* in-place update */
713
714 ret = load_chunk_info(&chunk_table_obj, &afd->afhi);
715 if (ret < 0)
716 goto err;
717 ret = get_attribute_text(&afd->afsi.attributes, " ", &tmp);
718 if (ret < 0)
719 goto err;
720 assert(tmp);
721 strncpy(afd->attributes_string, tmp, sizeof(afd->attributes_string));
722 afd->attributes_string[sizeof(afd->attributes_string) - 1] = '\0';
723 free(tmp);
724
725 {
726 struct ls_data d = {
727 .afhi = afd->afhi,
728 .afsi = afd->afsi,
729 .path = path,
730 .score = afd->score,
731 .hash = file_hash
732 };
733 struct para_buffer pb = {.buf = NULL};
734 ret = make_status_items(&d, &pb);
735 if (ret < 0)
736 goto err;
737 strncpy(afd->afs_status_info, pb.buf, AFS_STATUS_INFO_SIZE);
738 afd->afs_status_info[AFS_STATUS_INFO_SIZE] = '\0';
739 free(pb.buf);
740 }
741 aced.aft_row = aft_row;
742 aced.old_afsi = &afd->afsi;
743 afs_event(AFSI_CHANGE, NULL, &aced);
744 ret = save_afd(afd);
745 if (ret < 0)
746 goto err;
747 free(afd->afhi.chunk_table);
748 err:
749 osl_close_disk_object(&chunk_table_obj);
750 return ret;
751 }
752
753 static int get_local_time(uint64_t *seconds, char *buf, size_t size,
754 time_t current_time, enum ls_listing_mode lm)
755 {
756 struct tm t;
757
758 if (!localtime_r((time_t *)seconds, &t))
759 return -E_LOCALTIME;
760 if (lm == LS_MODE_MBOX) {
761 if (!strftime(buf, size, "%c", &t))
762 return -E_STRFTIME;
763 return 1;
764 }
765 if (*seconds + 6 * 30 * 24 * 3600 > current_time) {
766 if (!strftime(buf, size, "%b %e %k:%M", &t))
767 return -E_STRFTIME;
768 return 1;
769 }
770 if (!strftime(buf, size, "%b %e %Y", &t))
771 return -E_STRFTIME;
772 return 1;
773 }
774
775 /** Compute the number of (decimal) digits of a number. */
776 #define GET_NUM_DIGITS(x, num) { \
777 typeof((x)) _tmp = PARA_ABS(x); \
778 *num = 1; \
779 if ((x)) \
780 while ((_tmp) > 9) { \
781 (_tmp) /= 10; \
782 (*num)++; \
783 } \
784 }
785
786 static short unsigned get_duration_width(int seconds)
787 {
788 short unsigned width;
789 unsigned hours = seconds / 3600, mins = (seconds % 3600) / 60;
790
791 if (!hours) /* less than one hour => m:ss or mm:ss => 4 or 5 digits */
792 return 4 + (mins > 9);
793 /* more than one hour => h:mm:ss, hh:mm:ss, hhh:mm:ss, ... */
794 GET_NUM_DIGITS(hours, &width);
795 return width + 6;
796 }
797
798 static void get_duration_buf(int seconds, char *buf, short unsigned max_width)
799 {
800 unsigned hours = seconds / 3600, mins = (seconds % 3600) / 60;
801
802 if (!hours) /* m:ss or mm:ss */
803 sprintf(buf, "%*u:%02u", max_width - 3, mins, seconds % 60);
804 else /* more than one hour => h:mm:ss, hh:mm:ss, hhh:mm:ss, ... */
805 sprintf(buf, "%*u:%02u:%02u", max_width - 6, hours, mins,
806 seconds % 60);
807 }
808
809 static char *make_attribute_lines(const char *att_bitmap, struct afs_info *afsi)
810 {
811 char *att_text, *att_lines;
812
813 get_attribute_text(&afsi->attributes, " ", &att_text);
814 if (!att_text)
815 return para_strdup(att_bitmap);
816 att_lines = make_message("%s\nattributes_txt: %s",
817 att_bitmap, att_text);
818 free(att_text);
819 return att_lines;
820 }
821
822 static char *make_lyrics_line(struct afs_info *afsi)
823 {
824 char *lyrics_name;
825
826 lyr_get_name_by_id(afsi->lyrics_id, &lyrics_name);
827 if (!lyrics_name)
828 return make_message("%u", afsi->lyrics_id);
829 return make_message("%u (%s)", afsi->lyrics_id, lyrics_name);
830 }
831
832 static char *make_image_line(struct afs_info *afsi)
833 {
834 char *image_name;
835 img_get_name_by_id(afsi->image_id, &image_name);
836 if (!image_name)
837 return make_message("%u", afsi->image_id);
838 return make_message("%u (%s)", afsi->image_id, image_name);
839 }
840
841 static int print_list_item(struct ls_data *d, struct ls_options *opts,
842 struct para_buffer *b, time_t current_time)
843 {
844 int ret;
845 char att_buf[65];
846 char last_played_time[30];
847 char duration_buf[30]; /* nobody has an audio file long enough to overflow this */
848 char score_buf[30] = "";
849 struct afs_info *afsi = &d->afsi;
850 struct afh_info *afhi = &d->afhi;
851 struct ls_widths *w = &opts->widths;
852 int have_score = opts->flags & LS_FLAG_ADMISSIBLE_ONLY;
853 char asc_hash[2 * HASH_SIZE + 1];
854 char *att_lines, *lyrics_line, *image_line;
855
856 if (opts->mode == LS_MODE_SHORT) {
857 para_printf(b, "%s\n", d->path);
858 return 1;
859 }
860 get_attribute_bitmap(&afsi->attributes, att_buf);
861 ret = get_local_time(&afsi->last_played, last_played_time,
862 sizeof(last_played_time), current_time, opts->mode);
863 if (ret < 0)
864 return ret;
865 get_duration_buf(afhi->seconds_total, duration_buf, w->duration_width);
866 if (have_score) {
867 if (opts->mode == LS_MODE_LONG)
868 sprintf(score_buf, "%*li ", w->score_width, d->score);
869 else
870 sprintf(score_buf, "%li ", d->score);
871 }
872
873 if (opts->mode == LS_MODE_LONG) {
874 para_printf(b,
875 "%s" /* score */
876 "%s " /* attributes */
877 "%*d " /* image_id */
878 "%*d " /* lyrics_id */
879 "%*d " /* bitrate */
880 "%s " /* audio format */
881 "%*d " /* frequency */
882 "%d " /* channels */
883 "%s " /* duration */
884 "%*d " /* num_played */
885 "%s " /* last_played */
886 "%s\n", /* path */
887 score_buf,
888 att_buf,
889 w->image_id_width, afsi->image_id,
890 w->lyrics_id_width, afsi->lyrics_id,
891 w->bitrate_width, afhi->bitrate,
892 audio_format_name(afsi->audio_format_id),
893 w->frequency_width, afhi->frequency,
894 afhi->channels,
895 duration_buf,
896 w->num_played_width, afsi->num_played,
897 last_played_time,
898 d->path
899 );
900 return 1;
901 }
902 hash_to_asc(d->hash, asc_hash);
903 att_lines = make_attribute_lines(att_buf, afsi);
904 lyrics_line = make_lyrics_line(afsi);
905 image_line = make_image_line(afsi);
906 if (opts->mode == LS_MODE_VERBOSE) {
907 para_printf(b,
908 "%s: %s\n" /* path */
909 "%s%s%s" /* score */
910 "attributes: %s\n"
911 "hash: %s\n"
912 "image_id: %s\n"
913 "lyrics_id: %s\n"
914 "bitrate: %dkbit/s\n"
915 "format: %s\n"
916 "frequency: %dHz\n"
917 "channels: %d\n"
918 "duration: %s\n"
919 "num_played: %d\n"
920 "last_played: %s\n"
921 "tag info: %s\n",
922 (opts->flags & LS_FLAG_FULL_PATH)?
923 "path" : "file", d->path,
924 have_score? "score: " : "", score_buf,
925 have_score? "\n" : "",
926 att_lines,
927 asc_hash,
928 image_line,
929 lyrics_line,
930 afhi->bitrate,
931 audio_format_name(afsi->audio_format_id),
932 afhi->frequency,
933 afhi->channels,
934 duration_buf,
935 afsi->num_played,
936 last_played_time,
937 afhi->info_string
938 );
939 } else { /* mbox mode */
940 struct osl_object lyrics_def;
941 lyr_get_def_by_id(afsi->lyrics_id, &lyrics_def);
942 para_printf(b,
943 "From foo@localhost %s\n"
944 "Received: from\nTo: bar\nFrom: a\n"
945 "Subject: %s\n\n" /* path */
946 "%s%s%s" /* score */
947 "%s\n" /* attributes */
948 "hash: %s\n"
949 "image_id: %s\n"
950 "lyrics_id: %s\n"
951 "bitrate: %dkbit/s\n"
952 "format: %s\n"
953 "frequency: %dHz\n"
954 "channels: %d\n"
955 "duration: %s\n"
956 "num_played: %d\n"
957 "tag info: %s\n"
958 "%s%s\n",
959 last_played_time,
960 d->path,
961 have_score? "score: " : "", score_buf,
962 have_score? "\n" : "",
963 att_lines,
964 asc_hash,
965 image_line,
966 lyrics_line,
967 afhi->bitrate,
968 audio_format_name(afsi->audio_format_id),
969 afhi->frequency,
970 afhi->channels,
971 duration_buf,
972 afsi->num_played,
973 afhi->info_string,
974 lyrics_def.data? "Lyrics:\n~~~~~~~\n" : "",
975 lyrics_def.data? (char *)lyrics_def.data : ""
976 );
977 if (lyrics_def.data)
978 osl_close_disk_object(lyrics_def.data);
979 }
980 free(att_lines);
981 free(lyrics_line);
982 free(image_line);
983 return 1;
984 }
985
986 int make_status_items(struct ls_data *d, struct para_buffer *pb)
987 {
988 struct ls_options opts = {
989 .flags = LS_FLAG_FULL_PATH | LS_FLAG_ADMISSIBLE_ONLY,
990 .mode = LS_MODE_VERBOSE,
991 };
992 time_t current_time;
993
994 time(&current_time);
995 return print_list_item(d, &opts, pb, current_time);
996 }
997
998
999 static int ls_audio_format_compare(const void *a, const void *b)
1000 {
1001 struct ls_data *d1 = *(struct ls_data **)a, *d2 = *(struct ls_data **)b;
1002 return NUM_COMPARE(d1->afsi.audio_format_id, d2->afsi.audio_format_id);
1003 }
1004
1005 static int ls_duration_compare(const void *a, const void *b)
1006 {
1007 struct ls_data *d1 = *(struct ls_data **)a, *d2 = *(struct ls_data **)b;
1008 return NUM_COMPARE(d1->afhi.seconds_total, d2->afhi.seconds_total);
1009 }
1010
1011 static int ls_bitrate_compare(const void *a, const void *b)
1012 {
1013 struct ls_data *d1 = *(struct ls_data **)a, *d2 = *(struct ls_data **)b;
1014 return NUM_COMPARE(d1->afhi.bitrate, d2->afhi.bitrate);
1015 }
1016
1017 static int ls_lyrics_id_compare(const void *a, const void *b)
1018 {
1019 struct ls_data *d1 = *(struct ls_data **)a, *d2 = *(struct ls_data **)b;
1020 return NUM_COMPARE(d1->afsi.lyrics_id, d2->afsi.lyrics_id);
1021 }
1022
1023 static int ls_image_id_compare(const void *a, const void *b)
1024 {
1025 struct ls_data *d1 = *(struct ls_data **)a, *d2 = *(struct ls_data **)b;
1026 return NUM_COMPARE(d1->afsi.image_id, d2->afsi.image_id);
1027 }
1028
1029 static int ls_channels_compare(const void *a, const void *b)
1030 {
1031 struct ls_data *d1 = *(struct ls_data **)a, *d2 = *(struct ls_data **)b;
1032 return NUM_COMPARE(d1->afhi.channels, d2->afhi.channels);
1033 }
1034
1035 static int ls_frequency_compare(const void *a, const void *b)
1036 {
1037 struct ls_data *d1 = *(struct ls_data **)a, *d2 = *(struct ls_data **)b;
1038 return NUM_COMPARE(d1->afhi.frequency, d2->afhi.frequency);
1039 }
1040
1041 static int ls_num_played_compare(const void *a, const void *b)
1042 {
1043 struct ls_data *d1 = *(struct ls_data **)a, *d2 = *(struct ls_data **)b;
1044 return NUM_COMPARE(d1->afsi.num_played, d2->afsi.num_played);
1045 }
1046
1047 static int ls_last_played_compare(const void *a, const void *b)
1048 {
1049 struct ls_data *d1 = *(struct ls_data **)a, *d2 = *(struct ls_data **)b;
1050 return NUM_COMPARE(d1->afsi.last_played, d2->afsi.last_played);
1051 }
1052
1053 static int ls_score_compare(const void *a, const void *b)
1054 {
1055 struct ls_data *d1 = *(struct ls_data **)a, *d2 = *(struct ls_data **)b;
1056 return NUM_COMPARE(d1->score, d2->score);
1057 }
1058
1059 static int ls_path_compare(const void *a, const void *b)
1060 {
1061 struct ls_data *d1 = *(struct ls_data **)a, *d2 = *(struct ls_data **)b;
1062 return strcmp(d1->path, d2->path);
1063 }
1064
1065 static int sort_matching_paths(struct ls_options *options)
1066 {
1067 size_t nmemb = options->num_matching_paths;
1068 size_t size = sizeof(*options->data_ptr);
1069 int (*compar)(const void *, const void *);
1070 int i;
1071
1072 options->data_ptr = para_malloc(nmemb * sizeof(*options->data_ptr));
1073 for (i = 0; i < nmemb; i++)
1074 options->data_ptr[i] = options->data + i;
1075
1076 /* In these cases the array is already sorted */
1077 if (options->sorting == LS_SORT_BY_PATH
1078 && !(options->flags & LS_FLAG_ADMISSIBLE_ONLY)
1079 && (options->flags & LS_FLAG_FULL_PATH))
1080 return 1;
1081 if (options->sorting == LS_SORT_BY_SCORE &&
1082 options->flags & LS_FLAG_ADMISSIBLE_ONLY)
1083 return 1;
1084
1085 switch (options->sorting) {
1086 case LS_SORT_BY_PATH:
1087 compar = ls_path_compare; break;
1088 case LS_SORT_BY_SCORE:
1089 compar = ls_score_compare; break;
1090 case LS_SORT_BY_LAST_PLAYED:
1091 compar = ls_last_played_compare; break;
1092 case LS_SORT_BY_NUM_PLAYED:
1093 compar = ls_num_played_compare; break;
1094 case LS_SORT_BY_FREQUENCY:
1095 compar = ls_frequency_compare; break;
1096 case LS_SORT_BY_CHANNELS:
1097 compar = ls_channels_compare; break;
1098 case LS_SORT_BY_IMAGE_ID:
1099 compar = ls_image_id_compare; break;
1100 case LS_SORT_BY_LYRICS_ID:
1101 compar = ls_lyrics_id_compare; break;
1102 case LS_SORT_BY_BITRATE:
1103 compar = ls_bitrate_compare; break;
1104 case LS_SORT_BY_DURATION:
1105 compar = ls_duration_compare; break;
1106 case LS_SORT_BY_AUDIO_FORMAT:
1107 compar = ls_audio_format_compare; break;
1108 default:
1109 return -E_BAD_SORT;
1110 }
1111 qsort(options->data_ptr, nmemb, size, compar);
1112 return 1;
1113 }
1114
1115 /* row is either an aft_row or a row of the score table */
1116 /* TODO: Only compute widths if we need them */
1117 static int prepare_ls_row(struct osl_row *row, void *ls_opts)
1118 {
1119 int ret, i;
1120 struct ls_options *options = ls_opts;
1121 struct ls_data *d;
1122 struct ls_widths *w;
1123 unsigned short num_digits;
1124 unsigned tmp;
1125 struct osl_row *aft_row;
1126 long score;
1127 char *path;
1128
1129 if (options->flags & LS_FLAG_ADMISSIBLE_ONLY) {
1130 ret = get_score_and_aft_row(row, &score, &aft_row);
1131 if (ret < 0)
1132 return ret;
1133 } else
1134 aft_row = row;
1135 ret = get_audio_file_path_of_row(aft_row, &path);
1136 if (ret < 0)
1137 return ret;
1138 if (!(options->flags & LS_FLAG_FULL_PATH)) {
1139 char *p = strrchr(path, '/');
1140 if (p)
1141 path = p + 1;
1142 }
1143 if (options->num_patterns) {
1144 for (i = 0; i < options->num_patterns; i++) {
1145 ret = fnmatch(options->patterns[i], path, 0);
1146 if (!ret)
1147 break;
1148 if (ret == FNM_NOMATCH)
1149 continue;
1150 return -E_FNMATCH;
1151 }
1152 if (i >= options->num_patterns) /* no match */
1153 return 1;
1154 }
1155 tmp = options->num_matching_paths++;
1156 if (options->num_matching_paths > options->array_size) {
1157 options->array_size++;
1158 options->array_size *= 2;
1159 options->data = para_realloc(options->data, options->array_size
1160 * sizeof(*options->data));
1161 }
1162 d = options->data + tmp;
1163 ret = get_afsi_of_row(aft_row, &d->afsi);
1164 if (ret < 0)
1165 return ret;
1166 ret = get_afhi_of_row(aft_row, &d->afhi);
1167 if (ret < 0)
1168 return ret;
1169 d->path = path;
1170 ret = get_hash_of_row(aft_row, &d->hash);
1171 if (ret < 0)
1172 return ret;
1173 w = &options->widths;
1174 GET_NUM_DIGITS(d->afsi.image_id, &num_digits);
1175 w->image_id_width = PARA_MAX(w->image_id_width, num_digits);
1176 GET_NUM_DIGITS(d->afsi.lyrics_id, &num_digits);
1177 w->lyrics_id_width = PARA_MAX(w->lyrics_id_width, num_digits);
1178 GET_NUM_DIGITS(d->afhi.bitrate, &num_digits);
1179 w->bitrate_width = PARA_MAX(w->bitrate_width, num_digits);
1180 GET_NUM_DIGITS(d->afhi.frequency, &num_digits);
1181 w->frequency_width = PARA_MAX(w->frequency_width, num_digits);
1182 GET_NUM_DIGITS(d->afsi.num_played, &num_digits);
1183 w->num_played_width = PARA_MAX(w->num_played_width, num_digits);
1184 /* get the number of chars to print this amount of time */
1185 tmp = get_duration_width(d->afhi.seconds_total);
1186 w->duration_width = PARA_MAX(w->duration_width, tmp);
1187 if (options->flags & LS_FLAG_ADMISSIBLE_ONLY) {
1188 GET_NUM_DIGITS(score, &num_digits);
1189 num_digits++; /* add one for the sign (space or "-") */
1190 w->score_width = PARA_MAX(w->score_width, num_digits);
1191 d->score = score;
1192 }
1193 return 1;
1194 }
1195
1196 static int com_ls_callback(const struct osl_object *query,
1197 struct osl_object *ls_output)
1198 {
1199 struct ls_options *opts = query->data;
1200 char *p, *pattern_start = (char *)query->data + sizeof(*opts);
1201 struct para_buffer b = {.buf = NULL, .size = 0};
1202 int i = 0, ret;
1203 time_t current_time;
1204
1205
1206 if (opts->num_patterns) {
1207 opts->patterns = para_malloc(opts->num_patterns * sizeof(char *));
1208 for (i = 0, p = pattern_start; i < opts->num_patterns; i++) {
1209 opts->patterns[i] = p;
1210 p += strlen(p) + 1;
1211 }
1212 } else
1213 opts->patterns = NULL;
1214 if (opts->flags & LS_FLAG_ADMISSIBLE_ONLY)
1215 ret = admissible_file_loop(opts, prepare_ls_row);
1216 else
1217 ret = osl_rbtree_loop(audio_file_table, AFTCOL_PATH, opts,
1218 prepare_ls_row);
1219 if (ret < 0)
1220 goto out;
1221 ret = opts->num_patterns? -E_NO_MATCH : 0;
1222 if (!opts->num_matching_paths)
1223 goto out;
1224 ret = sort_matching_paths(opts);
1225 if (ret < 0)
1226 goto out;
1227 time(&current_time);
1228 if (opts->flags & LS_FLAG_REVERSE)
1229 for (i = opts->num_matching_paths - 1; i >= 0; i--) {
1230 ret = print_list_item(opts->data_ptr[i], opts, &b, current_time);
1231 if (ret < 0)
1232 break;
1233 }
1234 else
1235 for (i = 0; i < opts->num_matching_paths; i++) {
1236 ret = print_list_item(opts->data_ptr[i], opts, &b, current_time);
1237 if (ret < 0)
1238 break;
1239 }
1240 ret = 1;
1241 out:
1242 ls_output->data = b.buf;
1243 ls_output->size = b.size;
1244 free(opts->data);
1245 free(opts->data_ptr);
1246 free(opts->patterns);
1247 return ret;
1248 }
1249
1250 /*
1251 * TODO: flags -h (sort by hash)
1252 */
1253 int com_ls(int fd, int argc, char * const * const argv)
1254 {
1255 int i, ret;
1256 unsigned flags = 0;
1257 enum ls_sorting_method sort = LS_SORT_BY_PATH;
1258 enum ls_listing_mode mode = LS_MODE_SHORT;
1259 struct ls_options opts = {.patterns = NULL};
1260 struct osl_object query = {.data = &opts, .size = sizeof(opts)},
1261 ls_output;
1262
1263 for (i = 1; i < argc; i++) {
1264 const char *arg = argv[i];
1265 if (arg[0] != '-')
1266 break;
1267 if (!strcmp(arg, "--")) {
1268 i++;
1269 break;
1270 }
1271 if (!strncmp(arg, "-l", 2)) {
1272 if (!*(arg + 2)) {
1273 mode = LS_MODE_LONG;
1274 continue;
1275 }
1276 if (*(arg + 3))
1277 return -E_AFT_SYNTAX;
1278 switch(*(arg + 2)) {
1279 case 's':
1280 mode = LS_MODE_SHORT;
1281 continue;
1282 case 'l':
1283 mode = LS_MODE_LONG;
1284 continue;
1285 case 'v':
1286 mode = LS_MODE_VERBOSE;
1287 continue;
1288 case 'm':
1289 mode = LS_MODE_MBOX;
1290 continue;
1291 default:
1292 return -E_AFT_SYNTAX;
1293 }
1294 }
1295 if (!strcmp(arg, "-p")) {
1296 flags |= LS_FLAG_FULL_PATH;
1297 continue;
1298 }
1299 if (!strcmp(arg, "-a")) {
1300 flags |= LS_FLAG_ADMISSIBLE_ONLY;
1301 continue;
1302 }
1303 if (!strcmp(arg, "-r")) {
1304 flags |= LS_FLAG_REVERSE;
1305 continue;
1306 }
1307 if (!strncmp(arg, "-s", 2)) {
1308 if (!*(arg + 2) || *(arg + 3))
1309 return -E_AFT_SYNTAX;
1310 switch(*(arg + 2)) {
1311 case 'p':
1312 sort = LS_SORT_BY_PATH;
1313 continue;
1314 case 's': /* -ss implies -a */
1315 sort = LS_SORT_BY_SCORE;
1316 flags |= LS_FLAG_ADMISSIBLE_ONLY;
1317 continue;
1318 case 'l':
1319 sort = LS_SORT_BY_LAST_PLAYED;
1320 continue;
1321 case 'n':
1322 sort = LS_SORT_BY_NUM_PLAYED;
1323 continue;
1324 case 'f':
1325 sort = LS_SORT_BY_FREQUENCY;
1326 continue;
1327 case 'c':
1328 sort = LS_SORT_BY_CHANNELS;
1329 continue;
1330 case 'i':
1331 sort = LS_SORT_BY_IMAGE_ID;
1332 continue;
1333 case 'y':
1334 sort = LS_SORT_BY_LYRICS_ID;
1335 continue;
1336 case 'b':
1337 sort = LS_SORT_BY_BITRATE;
1338 continue;
1339 case 'd':
1340 sort = LS_SORT_BY_DURATION;
1341 continue;
1342 case 'a':
1343 sort = LS_SORT_BY_AUDIO_FORMAT;
1344 continue;
1345 default:
1346 return -E_AFT_SYNTAX;
1347 }
1348 }
1349 return -E_AFT_SYNTAX;
1350 }
1351 opts.flags = flags;
1352 opts.sorting = sort;
1353 opts.mode = mode;
1354 opts.num_patterns = argc - i;
1355 ret = send_option_arg_callback_request(&query, opts.num_patterns,
1356 argv + i, com_ls_callback, &ls_output);
1357 if (ret > 0) {
1358 ret = send_buffer(fd, (char *)ls_output.data);
1359 free(ls_output.data);
1360 }
1361 return ret;
1362 }
1363
1364 /**
1365 * Call the given function for each file in the audio file table.
1366 *
1367 * \param private_data An arbitrary data pointer, passed to \a func.
1368 * \param func The custom function to be called.
1369 *
1370 * \return The return value of the underlying call to osl_rbtree_loop().
1371 */
1372 int audio_file_loop(void *private_data, osl_rbtree_loop_func *func)
1373 {
1374 return osl_rbtree_loop(audio_file_table, AFTCOL_HASH, private_data,
1375 func);
1376 }
1377
1378 static struct osl_row *find_hash_sister(HASH_TYPE *hash)
1379 {
1380 const struct osl_object obj = {.data = hash, .size = HASH_SIZE};
1381 struct osl_row *row;
1382
1383 osl_get_row(audio_file_table, AFTCOL_HASH, &obj, &row);
1384 return row;
1385 }
1386
1387 enum aft_row_offsets {
1388 AFTROW_AFHI_OFFSET_POS = 0,
1389 AFTROW_CHUNKS_OFFSET_POS = 2,
1390 AFTROW_AUDIO_FORMAT_OFFSET = 4,
1391 AFTROW_FLAGS_OFFSET = 5,
1392 AFTROW_HASH_OFFSET = 9,
1393 AFTROW_PATH_OFFSET = (AFTROW_HASH_OFFSET + HASH_SIZE),
1394 };
1395
1396 /* never save the afsi, as the server knows it too. Note that afhi might be NULL.
1397 * In this case, afhi won't be stored in the buffer */
1398 static void save_audio_file_info(HASH_TYPE *hash, const char *path,
1399 struct afh_info *afhi, uint32_t flags,
1400 uint8_t audio_format_num, struct osl_object *obj)
1401 {
1402 size_t path_len = strlen(path) + 1;
1403 size_t afhi_size = sizeof_afhi_buf(afhi);
1404 size_t size = AFTROW_PATH_OFFSET + path_len + afhi_size
1405 + sizeof_chunk_info_buf(afhi);
1406 char *buf = para_malloc(size);
1407 uint16_t pos;
1408
1409 write_u8(buf + AFTROW_AUDIO_FORMAT_OFFSET, audio_format_num);
1410 write_u32(buf + AFTROW_FLAGS_OFFSET, flags);
1411
1412 memcpy(buf + AFTROW_HASH_OFFSET, hash, HASH_SIZE);
1413 strcpy(buf + AFTROW_PATH_OFFSET, path);
1414
1415 pos = AFTROW_PATH_OFFSET + path_len;
1416 PARA_DEBUG_LOG("size: %zu, afhi starts at %d\n", size, pos);
1417 PARA_DEBUG_LOG("last afhi byte: %p, pos %zu\n", buf + pos + afhi_size - 1,
1418 pos + afhi_size - 1);
1419 write_u16(buf + AFTROW_AFHI_OFFSET_POS, pos);
1420 save_afhi(afhi, buf + pos);
1421
1422 pos += afhi_size;
1423 PARA_DEBUG_LOG("size: %zu, chunks start at %d\n", size, pos);
1424 write_u16(buf + AFTROW_CHUNKS_OFFSET_POS, pos);
1425 save_chunk_info(afhi, buf + pos);
1426 PARA_DEBUG_LOG("last byte in buf: %p\n", buf + size - 1);
1427 obj->data = buf;
1428 obj->size = size;
1429 }
1430
1431 /*
1432 input:
1433 ~~~~~~
1434 HS: hash sister
1435 PB: path brother
1436 F: force flag given
1437
1438 output:
1439 ~~~~~~~
1440 AFHI: whether afhi and chunk table are computed and sent
1441 ACTION: table modifications to be performed
1442
1443 +---+----+-----+------+---------------------------------------------------+
1444 | HS | PB | F | AFHI | ACTION
1445 +---+----+-----+------+---------------------------------------------------+
1446 | Y | Y | Y | Y | if HS != PB: remove PB. HS: force afhi update,
1447 | | update path, keep afsi
1448 +---+----+-----+------+---------------------------------------------------+
1449 | Y | Y | N | N | if HS == PB: do not send callback request at all.
1450 | | otherwise: remove PB, HS: update path, keep afhi,
1451 | | afsi.
1452 +---+----+-----+------+---------------------------------------------------+
1453 | Y | N | Y | Y | (rename) force afhi update of HS, update path of
1454 | | HS, keep afsi
1455 +---+----+-----+------+---------------------------------------------------+
1456 | Y | N | N | N | (file rename) update path of HS, keep afsi, afhi
1457 +---+----+-----+------+---------------------------------------------------+
1458 | N | Y | Y | Y | (file change) update afhi, hash, of PB, keep afsi
1459 | | (force has no effect)
1460 +---+----+-----+------+---------------------------------------------------+
1461 | N | Y | N | Y | (file change) update afhi, hash of PB, keep afsi
1462 +---+----+-----+------+---------------------------------------------------+
1463 | N | N | Y | Y | (new file) create new entry (force has no effect)
1464 +---+----+-----+------+---------------------------------------------------+
1465 | N | N | N | Y | (new file) create new entry
1466 +---+----+-----+------+---------------------------------------------------+
1467
1468 afhi <=> force or no HS
1469
1470 */
1471
1472 /** Flags passed to the add command. */
1473 enum com_add_flags {
1474 /** Skip paths that exist already. */
1475 ADD_FLAG_LAZY = 1,
1476 /** Force adding. */
1477 ADD_FLAG_FORCE = 2,
1478 /** Print what is being done. */
1479 ADD_FLAG_VERBOSE = 4,
1480 /** Try to add files with unknown suffixes. */
1481 ADD_FLAG_ALL = 8,
1482 };
1483
1484 static int com_add_callback(const struct osl_object *query,
1485 struct osl_object *result)
1486 {
1487 char *buf = query->data, *path;
1488 struct osl_row *pb, *aft_row;
1489 struct osl_row *hs;
1490 struct osl_object objs[NUM_AFT_COLUMNS];
1491 HASH_TYPE *hash;
1492 char asc[2 * HASH_SIZE + 1];
1493 int ret;
1494 char afsi_buf[AFSI_SIZE];
1495 uint32_t flags = read_u32(buf + AFTROW_FLAGS_OFFSET);
1496 struct afs_info default_afsi = {.last_played = 0};
1497 struct para_buffer msg = {.buf = NULL};
1498
1499 hash = (HASH_TYPE *)buf + AFTROW_HASH_OFFSET;
1500 hash_to_asc(hash, asc);;
1501 objs[AFTCOL_HASH].data = buf + AFTROW_HASH_OFFSET;
1502 objs[AFTCOL_HASH].size = HASH_SIZE;
1503
1504 path = buf + AFTROW_PATH_OFFSET;
1505 objs[AFTCOL_PATH].data = path;
1506 objs[AFTCOL_PATH].size = strlen(path) + 1;
1507
1508 PARA_INFO_LOG("request to add %s\n", path);
1509 hs = find_hash_sister(hash);
1510 ret = aft_get_row_of_path(path, &pb);
1511 if (ret < 0 && ret != -E_RB_KEY_NOT_FOUND)
1512 return ret;
1513 if (hs && pb && hs == pb && !(flags & ADD_FLAG_FORCE)) {
1514 if (flags & ADD_FLAG_VERBOSE)
1515 para_printf(&msg, "ignoring duplicate\n");
1516 ret = 1;
1517 goto out;
1518 }
1519 if (hs && hs != pb) {
1520 struct osl_object obj;
1521 if (pb) { /* hs trumps pb, remove pb */
1522 if (flags & ADD_FLAG_VERBOSE)
1523 para_printf(&msg, "removing path brother\n");
1524 ret = osl_del_row(audio_file_table, pb);
1525 if (ret < 0)
1526 goto out;
1527 pb = NULL;
1528 }
1529 /* file rename, update hs' path */
1530 if (flags & ADD_FLAG_VERBOSE) {
1531 ret = osl_get_object(audio_file_table, hs,
1532 AFTCOL_PATH, &obj);
1533 if (ret < 0)
1534 goto out;
1535 para_printf(&msg, "renamed from %s\n", (char *)obj.data);
1536 }
1537 ret = osl_update_object(audio_file_table, hs, AFTCOL_PATH,
1538 &objs[AFTCOL_PATH]);
1539 if (ret < 0)
1540 goto out;
1541 afs_event(AUDIO_FILE_RENAME, &msg, hs);
1542 if (!(flags & ADD_FLAG_FORCE))
1543 goto out;
1544 }
1545 /* no hs or force mode, child must have sent afhi */
1546 uint16_t afhi_offset = read_u16(buf + AFTROW_AFHI_OFFSET_POS);
1547 uint16_t chunks_offset = read_u16(buf + AFTROW_CHUNKS_OFFSET_POS);
1548
1549 objs[AFTCOL_AFHI].data = buf + afhi_offset;
1550 objs[AFTCOL_AFHI].size = chunks_offset - afhi_offset;
1551 ret = -E_NO_AFHI;
1552 if (!objs[AFTCOL_AFHI].size) /* "impossible" */
1553 goto out;
1554 objs[AFTCOL_CHUNKS].data = buf + chunks_offset;
1555 objs[AFTCOL_CHUNKS].size = query->size - chunks_offset;
1556 if (pb && !hs) { /* update pb's hash */
1557 char old_asc[2 * HASH_SIZE + 1];
1558 HASH_TYPE *old_hash;
1559 ret = get_hash_of_row(pb, &old_hash);
1560 if (ret < 0)
1561 goto out;
1562 hash_to_asc(old_hash, old_asc);
1563 if (flags & ADD_FLAG_VERBOSE)
1564 para_printf(&msg, "file change: %s -> %s\n",
1565 old_asc, asc);
1566 ret = osl_update_object(audio_file_table, pb, AFTCOL_HASH,
1567 &objs[AFTCOL_HASH]);
1568 if (ret < 0)
1569 goto out;
1570 }
1571 if (hs || pb) { /* (hs != NULL and pb != NULL) implies hs == pb */
1572 struct osl_row *row = pb? pb : hs;
1573 /* update afhi and chunk_table */
1574 if (flags & ADD_FLAG_VERBOSE)
1575 para_printf(&msg, "updating afhi and chunk table\n");
1576 ret = osl_update_object(audio_file_table, row, AFTCOL_AFHI,
1577 &objs[AFTCOL_AFHI]);
1578 if (ret < 0)
1579 goto out;
1580 ret = osl_update_object(audio_file_table, row, AFTCOL_CHUNKS,
1581 &objs[AFTCOL_CHUNKS]);
1582 if (ret < 0)
1583 goto out;
1584 afs_event(AFHI_CHANGE, &msg, row);
1585 goto out;
1586 }
1587 /* new entry, use default afsi */
1588 if (flags & ADD_FLAG_VERBOSE)
1589 para_printf(&msg, "new file\n");
1590 default_afsi.last_played = time(NULL) - 365 * 24 * 60 * 60;
1591 default_afsi.audio_format_id = read_u8(buf + AFTROW_AUDIO_FORMAT_OFFSET);
1592
1593 objs[AFTCOL_AFSI].data = &afsi_buf;
1594 objs[AFTCOL_AFSI].size = AFSI_SIZE;
1595 save_afsi(&default_afsi, &objs[AFTCOL_AFSI]);
1596 ret = osl_add_and_get_row(audio_file_table, objs, &aft_row);
1597 out:
1598 if (ret < 0)
1599 para_printf(&msg, "%s\n", PARA_STRERROR(-ret));
1600 if (!msg.buf)
1601 return 0;
1602 result->data = msg.buf;
1603 result->size = msg.size;
1604 afs_event(AUDIO_FILE_ADD, &msg, aft_row);
1605 return 1;
1606 }
1607
1608 /** Used by com_add(). */
1609 struct private_add_data {
1610 /** The socket file descriptor. */
1611 int fd;
1612 /** The given add flags. */
1613 uint32_t flags;
1614 };
1615
1616 static int path_brother_callback(const struct osl_object *query,
1617 struct osl_object *result)
1618 {
1619 char *path = query->data;
1620 struct osl_row *path_brother;
1621 int ret = aft_get_row_of_path(path, &path_brother);
1622 if (ret < 0)
1623 return ret;
1624 result->data = para_malloc(sizeof(path_brother));
1625 result->size = sizeof(path_brother);
1626 *(struct osl_row **)(result->data) = path_brother;
1627 return 1;
1628 }
1629
1630 static int hash_sister_callback(const struct osl_object *query,
1631 struct osl_object *result)
1632 {
1633 HASH_TYPE *hash = query->data;
1634 struct osl_row *hash_sister;
1635
1636 hash_sister = find_hash_sister(hash);
1637 if (!hash_sister)
1638 return -E_RB_KEY_NOT_FOUND;
1639 result->data = para_malloc(sizeof(hash_sister));
1640 result->size = sizeof(hash_sister);
1641 *(struct osl_row **)(result->data) = hash_sister;
1642 return 1;
1643 }
1644
1645 static int add_one_audio_file(const char *path, const void *private_data)
1646 {
1647 int ret, ret2;
1648 uint8_t format_num = -1;
1649 const struct private_add_data *pad = private_data;
1650 struct afh_info afhi, *afhi_ptr = NULL;
1651 struct osl_row *pb = NULL, *hs = NULL; /* path brother/hash sister */
1652 struct osl_object map, obj = {.data = NULL}, query, result = {.data = NULL};
1653 HASH_TYPE hash[HASH_SIZE];
1654
1655 afhi.header_offset = 0;
1656 afhi.header_len = 0;
1657 ret = guess_audio_format(path);
1658 if (ret < 0 && !(pad->flags & ADD_FLAG_ALL))
1659 goto out_free;
1660 query.data = (char *)path;
1661 query.size = strlen(path) + 1;
1662 ret = send_callback_request(path_brother_callback, &query, &result);
1663 if (ret < 0 && ret != -E_RB_KEY_NOT_FOUND)
1664 goto out_free;
1665 if (ret >= 0) {
1666 pb = *(struct osl_row **)result.data;
1667 free(result.data);
1668 }
1669 ret = 1;
1670 if (pb && (pad->flags & ADD_FLAG_LAZY)) { /* lazy is really cheap */
1671 if (pad->flags & ADD_FLAG_VERBOSE)
1672 ret = send_va_buffer(pad->fd, "lazy-ignore: %s\n", path);
1673 goto out_free;
1674 }
1675 /* We still want to add this file. Compute its hash. */
1676 ret = mmap_full_file(path, O_RDONLY, &map.data, &map.size, NULL);
1677 if (ret < 0)
1678 goto out_free;
1679 hash_function(map.data, map.size, hash);
1680
1681 /* Check whether database contains file with the same hash. */
1682 query.data = hash;
1683 query.size = HASH_SIZE;
1684 ret = send_callback_request(hash_sister_callback, &query, &result);
1685 if (ret < 0 && ret != -E_RB_KEY_NOT_FOUND)
1686 goto out_free;
1687 if (ret >= 0) {
1688 hs = *(struct osl_row **)result.data;
1689 free(result.data);
1690 }
1691 /* Return success if we already know this file. */
1692 ret = 1;
1693 if (pb && hs && hs == pb && (!(pad->flags & ADD_FLAG_FORCE))) {
1694 if (pad->flags & ADD_FLAG_VERBOSE)
1695 ret = send_va_buffer(pad->fd,
1696 "%s exists, not forcing update\n", path);
1697 goto out_unmap;
1698 }
1699 /*
1700 * we won't recalculate the audio format info and the chunk table if
1701 * there is a hash sister unless in FORCE mode.
1702 */
1703 if (!hs || (pad->flags & ADD_FLAG_FORCE)) {
1704 ret = compute_afhi(path, map.data, map.size, &afhi);
1705 if (ret < 0)
1706 goto out_unmap;
1707 format_num = ret;
1708 afhi_ptr = &afhi;
1709 }
1710 if (pad->flags & ADD_FLAG_VERBOSE) {
1711 ret = send_va_buffer(pad->fd, "adding %s\n", path);
1712 if (ret < 0)
1713 goto out_unmap;
1714 }
1715 munmap(map.data, map.size);
1716 save_audio_file_info(hash, path, afhi_ptr, pad->flags, format_num, &obj);
1717 /* Ask afs to consider this entry for adding. */
1718 ret = send_callback_request(com_add_callback, &obj, &result);
1719 if (ret > 0) {
1720 ret2 = send_va_buffer(pad->fd, "%s", (char *)result.data);
1721 free(result.data);
1722 if (ret >= 0 && ret2 < 0)
1723 ret = ret2;
1724 }
1725 goto out_free;
1726
1727 out_unmap:
1728 munmap(map.data, map.size);
1729 out_free:
1730 if (ret < 0 && ret != -E_SEND)
1731 send_va_buffer(pad->fd, "failed to add %s (%s)\n", path,
1732 PARA_STRERROR(-ret));
1733 free(obj.data);
1734 if (afhi_ptr)
1735 free(afhi_ptr->chunk_table);
1736 /* it's not an error if not all files could be added */
1737 return ret == -E_SEND? ret : 1;
1738 }
1739
1740 int com_add(int fd, int argc, char * const * const argv)
1741 {
1742 int i, ret;
1743 struct private_add_data pad = {.fd = fd, .flags = 0};
1744 struct stat statbuf;
1745
1746 for (i = 1; i < argc; i++) {
1747 const char *arg = argv[i];
1748 if (arg[0] != '-')
1749 break;
1750 if (!strcmp(arg, "--")) {
1751 i++;
1752 break;
1753 }
1754 if (!strcmp(arg, "-a")) {
1755 pad.flags |= ADD_FLAG_ALL;
1756 continue;
1757 }
1758 if (!strcmp(arg, "-l")) {
1759 pad.flags |= ADD_FLAG_LAZY;
1760 continue;
1761 }
1762 if (!strcmp(arg, "-f")) {
1763 pad.flags |= ADD_FLAG_FORCE;
1764 continue;
1765 }
1766 if (!strcmp(arg, "-v")) {
1767 pad.flags |= ADD_FLAG_VERBOSE;
1768 continue;
1769 }
1770 }
1771 if (argc <= i)
1772 return -E_AFT_SYNTAX;
1773 for (; i < argc; i++) {
1774 char *path;
1775 ret = verify_path(argv[i], &path);
1776 if (ret < 0) {
1777 ret = send_va_buffer(fd, "%s: %s\n", argv[i], PARA_STRERROR(-ret));
1778 if (ret < 0)
1779 return ret;
1780 continue;
1781 }
1782 ret = stat(path, &statbuf);
1783 if (ret < 0) {
1784 ret = send_va_buffer(fd, "failed to stat %s (%s)\n", path,
1785 strerror(errno));
1786 free(path);
1787 if (ret < 0)
1788 return ret;
1789 continue;
1790 }
1791 if (S_ISDIR(statbuf.st_mode))
1792 ret = for_each_file_in_dir(path, add_one_audio_file,
1793 &pad);
1794 else
1795 ret = add_one_audio_file(path, &pad);
1796 if (ret < 0) {
1797 send_va_buffer(fd, "%s: %s\n", path, PARA_STRERROR(-ret));
1798 free(path);
1799 return ret;
1800 }
1801 free(path);
1802 }
1803 return 1;
1804
1805 }
1806
1807 /**
1808 * Flags used by the touch command.
1809 *
1810 * \sa com_touch().
1811 */
1812 enum touch_flags {
1813 /** Whether the \p FNM_PATHNAME flag should be passed to fnmatch(). */
1814 TOUCH_FLAG_FNM_PATHNAME = 1,
1815 /** Activates verbose mode. */
1816 TOUCH_FLAG_VERBOSE = 2
1817 };
1818
1819 /** Options used by com_touch(). */
1820 struct com_touch_options {
1821 /** New num_played value. */
1822 int32_t num_played;
1823 /** New last played count. */
1824 int64_t last_played;
1825 /** new lyrics id. */
1826 int32_t lyrics_id;
1827 /** new image id. */
1828 int32_t image_id;
1829 /** command line flags (see \ref touch_flags). */
1830 unsigned flags;
1831 };
1832
1833 /** Data passed to the action handler of com_touch(). */
1834 struct touch_action_data {
1835 /** Command line options (see \ref com_touch_options). */
1836 struct com_touch_options *cto;
1837 /** Message buffer. */
1838 struct para_buffer pb;
1839 };
1840
1841 static int touch_audio_file(__a_unused struct osl_table *table,
1842 struct osl_row *row, const char *name, void *data)
1843 {
1844 struct touch_action_data *tad = data;
1845 struct osl_object obj;
1846 struct afs_info old_afsi, new_afsi;
1847 int ret, no_options = tad->cto->num_played < 0 && tad->cto->last_played < 0 &&
1848 tad->cto->lyrics_id < 0 && tad->cto->image_id < 0;
1849 struct afsi_change_event_data aced;
1850
1851 ret = get_afsi_object_of_row(row, &obj);
1852 if (ret < 0) {
1853 para_printf(&tad->pb, "%s: %s\n", name, PARA_STRERROR(-ret));
1854 return 1;
1855 }
1856 ret = load_afsi(&old_afsi, &obj);
1857 if (ret < 0) {
1858 para_printf(&tad->pb, "%s: %s\n", name, PARA_STRERROR(-ret));
1859 return 1;
1860 }
1861 new_afsi = old_afsi;
1862 if (no_options) {
1863 new_afsi.num_played++;
1864 new_afsi.last_played = time(NULL);
1865 if (tad->cto->flags & TOUCH_FLAG_VERBOSE)
1866 para_printf(&tad->pb, "%s: num_played = %u, "
1867 "last_played = now()\n", name,
1868 new_afsi.num_played);
1869 } else {
1870 if (tad->cto->flags & TOUCH_FLAG_VERBOSE)
1871 para_printf(&tad->pb, "touching %s\n", name);
1872 if (tad->cto->lyrics_id >= 0)
1873 new_afsi.lyrics_id = tad->cto->lyrics_id;
1874 if (tad->cto->image_id >= 0)
1875 new_afsi.image_id = tad->cto->image_id;
1876 if (tad->cto->num_played >= 0)
1877 new_afsi.num_played = tad->cto->num_played;
1878 if (tad->cto->last_played >= 0)
1879 new_afsi.last_played = tad->cto->last_played;
1880 }
1881 save_afsi(&new_afsi, &obj); /* in-place update */
1882 aced.aft_row = row;
1883 aced.old_afsi = &old_afsi;
1884 afs_event(AFSI_CHANGE, &tad->pb, &aced);
1885 return 1;
1886 }
1887
1888 static int com_touch_callback(const struct osl_object *query,
1889 struct osl_object *result)
1890 {
1891 struct touch_action_data tad = {.cto = query->data};
1892 int ret;
1893 struct pattern_match_data pmd = {
1894 .table = audio_file_table,
1895 .loop_col_num = AFTCOL_HASH,
1896 .match_col_num = AFTCOL_PATH,
1897 .patterns = {.data = (char *)query->data + sizeof(*tad.cto),
1898 .size = query->size - sizeof(*tad.cto)},
1899 .data = &tad,
1900 .action = touch_audio_file
1901 };
1902 if (tad.cto->flags & TOUCH_FLAG_FNM_PATHNAME)
1903 pmd.fnmatch_flags |= FNM_PATHNAME;
1904 ret = for_each_matching_row(&pmd);
1905 if (ret < 0)
1906 para_printf(&tad.pb, "%s\n", PARA_STRERROR(-ret));
1907 if (tad.pb.buf) {
1908 result->data = tad.pb.buf;
1909 result->size = tad.pb.size;
1910 return 1;
1911 }
1912 return ret < 0? ret : 0;
1913 }
1914
1915 int com_touch(int fd, int argc, char * const * const argv)
1916 {
1917 struct com_touch_options cto = {
1918 .num_played = -1,
1919 .last_played = -1,
1920 .lyrics_id = -1,
1921 .image_id = -1
1922 };
1923 struct osl_object query = {.data = &cto, .size = sizeof(cto)},
1924 result;
1925 int i, ret;
1926
1927
1928 for (i = 1; i < argc; i++) {
1929 const char *arg = argv[i];
1930 if (arg[0] != '-')
1931 break;
1932 if (!strcmp(arg, "--")) {
1933 i++;
1934 break;
1935 }
1936 if (!strncmp(arg, "-n", 2)) {
1937 ret = para_atoi32(arg + 2, &cto.num_played);
1938 if (ret < 0)
1939 return ret;
1940 continue;
1941 }
1942 if (!strncmp(arg, "-l", 2)) {
1943 ret = para_atoi64(arg + 2, &cto.last_played);
1944 if (ret < 0)
1945 return ret;
1946 continue;
1947 }
1948 if (!strncmp(arg, "-y", 2)) {
1949 ret = para_atoi32(arg + 2, &cto.lyrics_id);
1950 if (ret < 0)
1951 return ret;
1952 continue;
1953 }
1954 if (!strncmp(arg, "-i", 2)) {
1955 ret = para_atoi32(arg + 2, &cto.image_id);
1956 if (ret < 0)
1957 return ret;
1958 continue;
1959 }
1960 if (!strcmp(arg, "-p")) {
1961 cto.flags |= TOUCH_FLAG_FNM_PATHNAME;
1962 continue;
1963 }
1964 if (!strcmp(arg, "-v")) {
1965 cto.flags |= TOUCH_FLAG_VERBOSE;
1966 continue;
1967 }
1968 break; /* non-option starting with dash */
1969 }
1970 if (i >= argc)
1971 return -E_AFT_SYNTAX;
1972 ret = send_option_arg_callback_request(&query, argc - i,
1973 argv + i, com_touch_callback, &result);
1974 if (ret > 0) {
1975 send_buffer(fd, (char *)result.data);
1976 free(result.data);
1977 } else if (ret < 0)
1978 send_va_buffer(fd, "%s\n", PARA_STRERROR(-ret));
1979 return ret;
1980 }
1981
1982 /** Flags for com_rm(). */
1983 enum rm_flags {
1984 /** -v */
1985 RM_FLAG_VERBOSE = 1,
1986 /** -f */
1987 RM_FLAG_FORCE = 2,
1988 /** -p */
1989 RM_FLAG_FNM_PATHNAME = 4
1990 };
1991
1992 /** Data passed to the action handler of com_rm(). */
1993 struct com_rm_action_data {
1994 /** Command line flags ((see \ref rm_flags). */
1995 uint32_t flags;
1996 /** Message buffer. */
1997 struct para_buffer pb;
1998 /** Number of audio files removed. */
1999 unsigned num_removed;
2000 };
2001
2002 static int remove_audio_file(__a_unused struct osl_table *table,
2003 struct osl_row *row, const char *name, void *data)
2004 {
2005 struct com_rm_action_data *crd = data;
2006 int ret;
2007
2008 if (crd->flags & RM_FLAG_VERBOSE)
2009 para_printf(&crd->pb, "removing %s\n", name);
2010 afs_event(AUDIO_FILE_REMOVE, &crd->pb, row);
2011 ret = osl_del_row(audio_file_table, row);
2012 if (ret < 0)
2013 para_printf(&crd->pb, "%s: %s\n", name, PARA_STRERROR(-ret));
2014 else
2015 crd->num_removed++;
2016 return 1;
2017 }
2018
2019 static int com_rm_callback(const struct osl_object *query,
2020 __a_unused struct osl_object *result)
2021 {
2022 struct com_rm_action_data crd = {.flags = *(uint32_t *)query->data};
2023 int ret;
2024 struct pattern_match_data pmd = {
2025 .table = audio_file_table,
2026 .loop_col_num = AFTCOL_HASH,
2027 .match_col_num = AFTCOL_PATH,
2028 .patterns = {.data = (char *)query->data + sizeof(uint32_t),
2029 .size = query->size - sizeof(uint32_t)},
2030 .data = &crd,
2031 .action = remove_audio_file
2032 };
2033 if (crd.flags & RM_FLAG_FNM_PATHNAME)
2034 pmd.fnmatch_flags |= FNM_PATHNAME;
2035 ret = for_each_matching_row(&pmd);
2036 if (ret < 0)
2037 para_printf(&crd.pb, "%s\n", PARA_STRERROR(-ret));
2038 if (!crd.num_removed && !(crd.flags & RM_FLAG_FORCE))
2039 para_printf(&crd.pb, "no matches -- nothing removed\n");
2040 else {
2041 if (crd.flags & RM_FLAG_VERBOSE)
2042 para_printf(&crd.pb, "removed %u files\n", crd.num_removed);
2043 }
2044 if (crd.pb.buf) {
2045 result->data = crd.pb.buf;
2046 result->size = crd.pb.size;
2047 return 1;
2048 }
2049 return ret < 0? ret : 0;
2050 }
2051
2052 /* TODO options: -r (recursive) */
2053 int com_rm(int fd, int argc, char * const * const argv)
2054 {
2055 uint32_t flags = 0;
2056 struct osl_object query = {.data = &flags, .size = sizeof(flags)},
2057 result;
2058 int i, ret;
2059
2060 for (i = 1; i < argc; i++) {
2061 const char *arg = argv[i];
2062 if (arg[0] != '-')
2063 break;
2064 if (!strcmp(arg, "--")) {
2065 i++;
2066 break;
2067 }
2068 if (!strcmp(arg, "-f")) {
2069 flags |= RM_FLAG_FORCE;
2070 continue;
2071 }
2072 if (!strcmp(arg, "-p")) {
2073 flags |= RM_FLAG_FNM_PATHNAME;
2074 continue;
2075 }
2076 if (!strcmp(arg, "-v")) {
2077 flags |= RM_FLAG_VERBOSE;
2078 continue;
2079 }
2080 break;
2081 }
2082 if (i >= argc)
2083 return -E_AFT_SYNTAX;
2084 ret = send_option_arg_callback_request(&query, argc - i, argv + i,
2085 com_rm_callback, &result);
2086 if (ret > 0) {
2087 send_buffer(fd, (char *)result.data);
2088 free(result.data);
2089 } else if (ret < 0)
2090 send_va_buffer(fd, "%s\n", PARA_STRERROR(-ret));
2091 return ret;
2092 }
2093
2094 /**
2095 * Flags used by the cpsi command.
2096 *
2097 * \sa com_cpsi().
2098 */
2099 enum cpsi_flags {
2100 /** Whether the lyrics id should be copied. */
2101 CPSI_FLAG_COPY_LYRICS_ID = 1,
2102 /** Whether the image id should be copied. */
2103 CPSI_FLAG_COPY_IMAGE_ID = 2,
2104 /** Whether the lastplayed time should be copied. */
2105 CPSI_FLAG_COPY_LASTPLAYED = 4,
2106 /** Whether the numplayed count should be copied. */
2107 CPSI_FLAG_COPY_NUMPLAYED = 8,
2108 /** Whether the attributes should be copied. */
2109 CPSI_FLAG_COPY_ATTRIBUTES = 16,
2110 /** Activates verbose mode. */
2111 CPSI_FLAG_VERBOSE = 32,
2112 };
2113
2114 /** Data passed to the action handler of com_cpsi(). */
2115 struct cpsi_action_data {
2116 /** command line flags (see \ref cpsi_flags). */
2117 unsigned flags;
2118 /** Number of audio files changed. */
2119 unsigned num_copied;
2120 /** Message buffer. */
2121 struct para_buffer pb;
2122 /** Values are copied from here. */
2123 struct afs_info source_afsi;
2124 };
2125
2126 static int copy_selector_info(__a_unused struct osl_table *table,
2127 struct osl_row *row, const char *name, void *data)
2128 {
2129 struct cpsi_action_data *cad = data;
2130 struct osl_object target_afsi_obj;
2131 int ret;
2132 struct afs_info old_afsi, target_afsi;
2133 struct afsi_change_event_data aced;
2134
2135 ret = get_afsi_object_of_row(row, &target_afsi_obj);
2136 if (ret < 0)
2137 return ret;
2138 load_afsi(&target_afsi, &target_afsi_obj);
2139 old_afsi = target_afsi;
2140 if (cad->flags & CPSI_FLAG_COPY_LYRICS_ID)
2141 target_afsi.lyrics_id = cad->source_afsi.lyrics_id;
2142 if (cad->flags & CPSI_FLAG_COPY_IMAGE_ID)
2143 target_afsi.image_id = cad->source_afsi.image_id;
2144 if (cad->flags & CPSI_FLAG_COPY_LASTPLAYED)
2145 target_afsi.last_played = cad->source_afsi.last_played;
2146 if (cad->flags & CPSI_FLAG_COPY_NUMPLAYED)
2147 target_afsi.num_played = cad->source_afsi.num_played;
2148 if (cad->flags & CPSI_FLAG_COPY_ATTRIBUTES)
2149 target_afsi.attributes = cad->source_afsi.attributes;
2150 save_afsi(&target_afsi, &target_afsi_obj); /* in-place update */
2151 cad->num_copied++;
2152 if (cad->flags & CPSI_FLAG_VERBOSE)
2153 para_printf(&cad->pb, "copied afsi to %s\n", name);
2154 aced.aft_row = row;
2155 aced.old_afsi = &old_afsi;
2156 afs_event(AFSI_CHANGE, &cad->pb, &aced);
2157 return 1;
2158 }
2159
2160 static int com_cpsi_callback(const struct osl_object *query,
2161 struct osl_object *result)
2162 {
2163 struct cpsi_action_data cad = {.flags = *(unsigned *)query->data};
2164 int ret;
2165 char *source_path = (char *)query->data + sizeof(cad.flags);
2166
2167 ret = get_afsi_of_path(source_path, &cad.source_afsi);
2168 if (ret < 0)
2169 goto out;
2170 struct pattern_match_data pmd = {
2171 .table = audio_file_table,
2172 .loop_col_num = AFTCOL_HASH,
2173 .match_col_num = AFTCOL_PATH,
2174 .patterns = {.data = source_path + strlen(source_path) + 1,
2175 .size = query->size - sizeof(cad.flags)
2176 - strlen(source_path) - 1},
2177 .data = &cad,
2178 .action = copy_selector_info
2179 };
2180 ret = for_each_matching_row(&pmd);
2181 out:
2182 if (ret < 0)
2183 para_printf(&cad.pb, "%s\n", PARA_STRERROR(-ret));
2184 if (cad.flags & CPSI_FLAG_VERBOSE) {
2185 if (cad.num_copied)
2186 para_printf(&cad.pb, "copied requested afsi from %s "
2187 "to %u files\n",
2188 source_path, cad.num_copied);
2189 else
2190 para_printf(&cad.pb, "nothing copied\n");
2191 }
2192 if (cad.pb.buf) {
2193 result->data = cad.pb.buf;
2194 result->size = cad.pb.size;
2195 return 1;
2196 }
2197 return ret < 0? ret : 0;
2198 }
2199
2200 int com_cpsi(int fd, int argc, char * const * const argv)
2201 {
2202 unsigned flags = 0;
2203 int i, ret;
2204 struct osl_object options = {.data = &flags, .size = sizeof(flags)},
2205 result;
2206
2207 for (i = 1; i < argc; i++) {
2208 const char *arg = argv[i];
2209 if (arg[0] != '-')
2210 break;
2211 if (!strcmp(arg, "--")) {
2212 i++;
2213 break;
2214 }
2215 if (!strcmp(arg, "-y")) {
2216 flags |= CPSI_FLAG_COPY_LYRICS_ID;
2217 continue;
2218 }
2219 if (!strcmp(arg, "-i")) {
2220 flags |= CPSI_FLAG_COPY_IMAGE_ID;
2221 continue;
2222 }
2223 if (!strcmp(arg, "-l")) {
2224 flags |= CPSI_FLAG_COPY_LASTPLAYED;
2225 continue;
2226 }
2227 if (!strcmp(arg, "-n")) {
2228 flags |= CPSI_FLAG_COPY_NUMPLAYED;
2229 continue;
2230 }
2231 if (!strcmp(arg, "-a")) {
2232 flags |= CPSI_FLAG_COPY_ATTRIBUTES;
2233 continue;
2234 }
2235 if (!strcmp(arg, "-v")) {
2236 flags |= CPSI_FLAG_VERBOSE;
2237 continue;
2238 }
2239 break;
2240 }
2241 if (i + 1 >= argc) /* need at least souce file and pattern */
2242 return -E_AFT_SYNTAX;
2243 if (!(flags & ~CPSI_FLAG_VERBOSE)) /* no copy flags given */
2244 flags = ~(unsigned)CPSI_FLAG_VERBOSE | flags;
2245 ret = send_option_arg_callback_request(&options, argc - i, argv + i,
2246 com_cpsi_callback, &result);
2247 if (ret > 0) {
2248 send_buffer(fd, (char *)result.data);
2249 free(result.data);
2250 } else
2251 send_va_buffer(fd, "%s\n", PARA_STRERROR(-ret));
2252 return ret;
2253 }
2254
2255 /* TODO: optionally fix problems by removing offending rows */
2256 static int check_audio_file(struct osl_row *row, void *data)
2257 {
2258 char *path;
2259 struct para_buffer *pb = data;
2260 struct stat statbuf;
2261 int ret = get_audio_file_path_of_row(row, &path);
2262 struct afs_info afsi;
2263 char *blob_name;
2264
2265 if (ret < 0) {
2266 para_printf(pb, "%s\n", PARA_STRERROR(-ret));
2267 return 1;
2268 }
2269 if (stat(path, &statbuf) < 0)
2270 para_printf(pb, "%s: stat error (%s)\n", path, strerror(errno));
2271 else {
2272 if (!S_ISREG(statbuf.st_mode))
2273 para_printf(pb, "%s: not a regular file\n", path);
2274 }
2275 ret = get_afsi_of_row(row, &afsi);
2276 if (ret < 0) {
2277 para_printf(pb, "%s: %s\n", path, PARA_STRERROR(-ret));
2278 return 1;
2279 }
2280 ret = lyr_get_name_by_id(afsi.lyrics_id, &blob_name);
2281 if (ret < 0)
2282 para_printf(pb, "%s lyrics id %u: %s\n", path, afsi.lyrics_id,
2283 PARA_STRERROR(-ret));
2284 ret = img_get_name_by_id(afsi.image_id, &blob_name);
2285 if (ret < 0)
2286 para_printf(pb, "%s image id %u: %s\n", path, afsi.image_id,
2287 PARA_STRERROR(-ret));
2288 return 1;
2289 }
2290
2291 /**
2292 * Check the audio file table for inconsistencies.
2293 *
2294 * \param query Unused.
2295 * \param result Contains message string upon return.
2296 *
2297 * This function always succeeds.
2298 *
2299 * \sa com_check().
2300 */
2301 int aft_check_callback(__a_unused const struct osl_object *query, struct osl_object *result)
2302 {
2303 struct para_buffer pb = {.buf = NULL};
2304
2305 para_printf(&pb, "checking audio file table...\n");
2306 audio_file_loop(&pb, check_audio_file);
2307 result->data = pb.buf;
2308 result->size = pb.size;
2309 return 1;
2310
2311 }
2312
2313 /**
2314 * Close the audio file table.
2315 *
2316 * \param flags Usual flags that are passed to osl_close_table().
2317 *
2318 * \sa osl_close_table().
2319 */
2320 static void aft_close(void)
2321 {
2322 osl_close_table(audio_file_table, OSL_MARK_CLEAN);
2323 audio_file_table = NULL;
2324 }
2325
2326 /**
2327 * Open the audio file table.
2328 *
2329 * \param dir The database directory.
2330 *
2331 * \return Standard.
2332 *
2333 * \sa osl_open_table().
2334 */
2335 static int aft_open(const char *dir)
2336 {
2337 int ret;
2338
2339 audio_file_table_desc.dir = dir;
2340 ret = osl_open_table(&audio_file_table_desc, &audio_file_table);
2341 if (ret >= 0) {
2342 unsigned num;
2343 osl_get_num_rows(audio_file_table, &num);
2344 PARA_INFO_LOG("audio file table contains %d files\n", num);
2345 return ret;
2346 }
2347 PARA_INFO_LOG("failed to open audio file table\n");
2348 audio_file_table = NULL;
2349 if (ret >= 0 || is_errno(-ret, ENOENT))
2350 return 1;
2351 return ret;
2352 }
2353
2354 static int aft_create(const char *dir)
2355 {
2356 audio_file_table_desc.dir = dir;
2357 return osl_create_table(&audio_file_table_desc);
2358 }
2359
2360 static int clear_attribute(struct osl_row *row, void *data)
2361 {
2362 struct rmatt_event_data *red = data;
2363 struct afs_info afsi;
2364 struct osl_object obj;
2365 int ret = get_afsi_object_of_row(row, &obj);
2366 uint64_t mask = ~(1ULL << red->bitnum);
2367
2368 if (ret < 0)
2369 return ret;
2370 ret = load_afsi(&afsi, &obj);
2371 if (ret < 0)
2372 return ret;
2373 afsi.attributes &= mask;
2374 save_afsi(&afsi, &obj);
2375 return 1;
2376 }
2377
2378 static int aft_event_handler(enum afs_events event, struct para_buffer *pb,
2379 void *data)
2380 {
2381 switch(event) {
2382 case ATTRIBUTE_REMOVE: {
2383 const struct rmatt_event_data *red = data;
2384 para_printf(pb, "clearing attribute %s (bit %u) from all "
2385 "entries in the audio file table\n", red->name,
2386 red->bitnum);
2387 return audio_file_loop(data, clear_attribute);
2388 }
2389 default:
2390 return 1;
2391 }
2392 }
2393
2394 void aft_init(struct afs_table *t)
2395 {
2396 t->name = audio_file_table_desc.name;
2397 t->open = aft_open;
2398 t->close = aft_close;
2399 t->create = aft_create;
2400 t->event_handler = aft_event_handler;
2401 }